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
c7d8f386f5659dffd8399f6e427a1e0fad098043
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Structure.lean
2686fcd659b29b634ab79bf2da2831eb09cb2500
[ "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
9,145
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura Helper functions for retrieving structure information. -/ import Lean.Environment import Lean.ProjFns namespace Lean structure StructureFieldInfo where fieldName : Name projFn : Name /-- It is `some parentStructName` if it is a subobject, and `parentStructName` is the name of the parent structure -/ subobject? : Option Name binderInfo : BinderInfo autoParam? : Option Expr := none deriving Inhabited, Repr def StructureFieldInfo.lt (i₁ i₂ : StructureFieldInfo) : Bool := Name.quickLt i₁.fieldName i₂.fieldName structure StructureInfo where structName : Name fieldNames : Array Name := #[] -- sorted by field position in the structure fieldInfo : Array StructureFieldInfo := #[] -- sorted by `fieldName` deriving Inhabited def StructureInfo.lt (i₁ i₂ : StructureInfo) : Bool := Name.quickLt i₁.structName i₂.structName def StructureInfo.getProjFn? (info : StructureInfo) (i : Nat) : Option Name := if h : i < info.fieldNames.size then let fieldName := info.fieldNames.get ⟨i, h⟩ info.fieldInfo.binSearch { fieldName := fieldName, projFn := default, subobject? := none, binderInfo := default } StructureFieldInfo.lt |>.map (·.projFn) else none /-- Auxiliary state for structures defined in the current module. -/ private structure StructureState where map : Std.PersistentHashMap Name StructureInfo := {} deriving Inhabited builtin_initialize structureExt : SimplePersistentEnvExtension StructureInfo StructureState ← registerSimplePersistentEnvExtension { name := `structExt addImportedFn := fun _ => {} addEntryFn := fun s e => { s with map := s.map.insert e.structName e } toArrayFn := fun es => es.toArray.qsort StructureInfo.lt } structure StructureDescr where structName : Name fields : Array StructureFieldInfo -- Should use the order the field appear in the constructor. deriving Inhabited def registerStructure (env : Environment) (e : StructureDescr) : Environment := structureExt.addEntry env { structName := e.structName fieldNames := e.fields.map fun e => e.fieldName fieldInfo := e.fields.qsort StructureFieldInfo.lt } def getStructureInfo? (env : Environment) (structName : Name) : Option StructureInfo := match env.getModuleIdxFor? structName with | some modIdx => structureExt.getModuleEntries env modIdx |>.binSearch { structName } StructureInfo.lt | none => structureExt.getState env |>.map.find? structName def getStructureCtor (env : Environment) (constName : Name) : ConstructorVal := match env.find? constName with | some (.inductInfo { isRec := false, ctors := [ctorName], .. }) => match env.find? ctorName with | some (ConstantInfo.ctorInfo val) => val | _ => panic! "ill-formed environment" | _ => panic! "structure expected" /-- Get direct field names for the given structure. -/ def getStructureFields (env : Environment) (structName : Name) : Array Name := if let some info := getStructureInfo? env structName then info.fieldNames else panic! "structure expected" def getFieldInfo? (env : Environment) (structName : Name) (fieldName : Name) : Option StructureFieldInfo := if let some info := getStructureInfo? env structName then info.fieldInfo.binSearch { fieldName := fieldName, projFn := default, subobject? := none, binderInfo := default } StructureFieldInfo.lt else none /-- If `fieldName` represents the relation to a parent structure `S`, return `S` -/ def isSubobjectField? (env : Environment) (structName : Name) (fieldName : Name) : Option Name := if let some fieldInfo := getFieldInfo? env structName fieldName then fieldInfo.subobject? else none /-- Return immediate parent structures -/ def getParentStructures (env : Environment) (structName : Name) : Array Name := let fieldNames := getStructureFields env structName; fieldNames.foldl (init := #[]) fun acc fieldName => match isSubobjectField? env structName fieldName with | some parentStructName => acc.push parentStructName | none => acc /-- Return all parent structures -/ partial def getAllParentStructures (env : Environment) (structName : Name) : Array Name := visit structName |>.run #[] |>.2 where visit (structName : Name) : StateT (Array Name) Id Unit := do for p in getParentStructures env structName do modify fun s => s.push p visit p /-- `findField? env S fname`. If `fname` is defined in a parent `S'` of `S`, return `S'` -/ partial def findField? (env : Environment) (structName : Name) (fieldName : Name) : Option Name := if (getStructureFields env structName).contains fieldName then some structName else getParentStructures env structName |>.findSome? fun parentStructName => findField? env parentStructName fieldName private partial def getStructureFieldsFlattenedAux (env : Environment) (structName : Name) (fullNames : Array Name) (includeSubobjectFields : Bool) : Array Name := (getStructureFields env structName).foldl (init := fullNames) fun fullNames fieldName => match isSubobjectField? env structName fieldName with | some parentStructName => let fullNames := if includeSubobjectFields then fullNames.push fieldName else fullNames getStructureFieldsFlattenedAux env parentStructName fullNames includeSubobjectFields | none => fullNames.push fieldName /-- Return field names for the given structure, including "flattened" fields from parent structures. To omit `toParent` projections, set `includeSubobjectFields := false`. For example, given `Bar` such that ```lean structure Foo where a : Nat structure Bar extends Foo where b : Nat ``` return `#[toFoo,a,b]` or `#[a,b]` with subobject fields omitted. -/ def getStructureFieldsFlattened (env : Environment) (structName : Name) (includeSubobjectFields := true) : Array Name := getStructureFieldsFlattenedAux env structName #[] includeSubobjectFields /-- Return true if `constName` is the name of an inductive datatype created using the `structure` or `class` commands. We perform the check by testing whether auxiliary projection functions have been created. -/ def isStructure (env : Environment) (constName : Name) : Bool := getStructureInfo? env constName |>.isSome def getProjFnForField? (env : Environment) (structName : Name) (fieldName : Name) : Option Name := if let some fieldInfo := getFieldInfo? env structName fieldName then some fieldInfo.projFn else none def getProjFnInfoForField? (env : Environment) (structName : Name) (fieldName : Name) : Option (Name × ProjectionFunctionInfo) := if let some projFn := getProjFnForField? env structName fieldName then (projFn, ·) <$> env.getProjectionFnInfo? projFn else none def mkDefaultFnOfProjFn (projFn : Name) : Name := projFn ++ `_default def getDefaultFnForField? (env : Environment) (structName : Name) (fieldName : Name) : Option Name := if let some projName := getProjFnForField? env structName fieldName then let defFn := mkDefaultFnOfProjFn projName if env.contains defFn then defFn else none else -- Check if we have a default function for a default values overridden by substructure. let defFn := mkDefaultFnOfProjFn (structName ++ fieldName) if env.contains defFn then defFn else none partial def getPathToBaseStructureAux (env : Environment) (baseStructName : Name) (structName : Name) (path : List Name) : Option (List Name) := if baseStructName == structName then some path.reverse else let fieldNames := getStructureFields env structName; fieldNames.findSome? fun fieldName => match isSubobjectField? env structName fieldName with | none => none | some parentStructName => match getProjFnForField? env structName fieldName with | none => none | some projFn => getPathToBaseStructureAux env baseStructName parentStructName (projFn :: path) /-- If `baseStructName` is an ancestor structure for `structName`, then return a sequence of projection functions to go from `structName` to `baseStructName`. -/ def getPathToBaseStructure? (env : Environment) (baseStructName : Name) (structName : Name) : Option (List Name) := getPathToBaseStructureAux env baseStructName structName [] /-- Return true iff `constName` is the a non-recursive inductive datatype that has only one constructor. -/ def isStructureLike (env : Environment) (constName : Name) : Bool := match env.find? constName with | some (.inductInfo { isRec := false, ctors := [_], numIndices := 0, .. }) => true | _ => false /-- Return number of fields for a structure-like type -/ def getStructureLikeNumFields (env : Environment) (constName : Name) : Nat := match env.find? constName with | some (.inductInfo { isRec := false, ctors := [ctor], numIndices := 0, .. }) => match env.find? ctor with | some (.ctorInfo { numFields := n, .. }) => n | _ => 0 | _ => 0 end Lean
6ce81e6c470496bfbbc40130a62bb39f2e38cd6b
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/preadditive/hom_orthogonal.lean
7da288e5423d0a5fe21f6cbfd60b266cb5789cac
[ "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
7,375
lean
/- Copyright (c) 2022 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.linear.basic import category_theory.preadditive.biproducts import linear_algebra.matrix.invariant_basis_number /-! # Hom orthogonal families. A family of objects in a category with zero morphisms is "hom orthogonal" if the only morphism between distinct objects is the zero morphism. We show that in any category with zero morphisms and finite biproducts, a morphism between biproducts drawn from a hom orthogonal family `s : ι → C` can be decomposed into a block diagonal matrix with entries in the endomorphism rings of the `s i`. When the category is preadditive, this decomposition is an additive equivalence, and intertwines composition and matrix multiplication. When the category is `R`-linear, the decomposition is an `R`-linear equivalence. If every object in the hom orthogonal family has an endomorphism ring with invariant basis number (e.g. if each object in the family is simple, so its endomorphism ring is a division ring, or otherwise if each endomorphism ring is commutative), then decompositions of an object as a biproduct of the family have uniquely defined multiplicities. We state this as: ``` lemma hom_orthogonal.equiv_of_iso (o : hom_orthogonal s) {f : α → ι} {g : β → ι} (i : ⨁ (λ a, s (f a)) ≅ ⨁ (λ b, s (g b))) : ∃ e : α ≃ β, ∀ a, g (e a) = f a ``` This is preliminary to defining semisimple categories. -/ open_locale classical matrix open category_theory.limits universes v u namespace category_theory variables {C : Type u} [category.{v} C] /-- A family of objects is "hom orthogonal" if there is at most one morphism between distinct objects. (In a category with zero morphisms, that must be the zero morphism.) -/ def hom_orthogonal {ι : Type*} (s : ι → C) : Prop := ∀ i j, i ≠ j → subsingleton (s i ⟶ s j) namespace hom_orthogonal variables {ι : Type*} {s : ι → C} lemma eq_zero [has_zero_morphisms C] (o : hom_orthogonal s) {i j : ι} (w : i ≠ j) (f : s i ⟶ s j) : f = 0 := by { haveI := o i j w, apply subsingleton.elim, } section variables [has_zero_morphisms C] [has_finite_biproducts C] /-- Morphisms between two direct sums over a hom orthogonal family `s : ι → C` are equivalent to block diagonal matrices, with blocks indexed by `ι`, and matrix entries in `i`-th block living in the endomorphisms of `s i`. -/ @[simps] noncomputable def matrix_decomposition (o : hom_orthogonal s) {α β : Type} [fintype α] [fintype β] {f : α → ι} {g : β → ι} : (⨁ (λ a, s (f a)) ⟶ ⨁ (λ b, s (g b))) ≃ Π (i : ι), matrix (g ⁻¹' {i}) (f ⁻¹' {i}) (End (s i)) := { to_fun := λ z i j k, eq_to_hom (by { rcases k with ⟨k, ⟨⟩⟩, simp, }) ≫ biproduct.components z k j ≫ eq_to_hom (by { rcases j with ⟨j, ⟨⟩⟩, simp, }), inv_fun := λ z, biproduct.matrix (λ j k, if h : f j = g k then z (f j) ⟨k, by simp [h]⟩ ⟨j, by simp⟩ ≫ eq_to_hom (by simp [h]) else 0), left_inv := λ z, begin ext j k, simp only [category.assoc, biproduct.lift_π, biproduct.ι_matrix], split_ifs, { simp, refl, }, { symmetry, apply o.eq_zero h, }, end, right_inv := λ z, begin ext i ⟨j, w⟩ ⟨k, ⟨⟩⟩, simp only [set.mem_preimage, set.mem_singleton_iff], simp [w.symm], refl, end, } end section variables [preadditive C] [has_finite_biproducts C] /-- `hom_orthogonal.matrix_decomposition` as an additive equivalence. -/ @[simps] noncomputable def matrix_decomposition_add_equiv (o : hom_orthogonal s) {α β : Type} [fintype α] [fintype β] {f : α → ι} {g : β → ι} : (⨁ (λ a, s (f a)) ⟶ ⨁ (λ b, s (g b))) ≃+ Π (i : ι), matrix (g ⁻¹' {i}) (f ⁻¹' {i}) (End (s i)) := { map_add' := λ w z, by { ext, dsimp [biproduct.components], simp, }, ..o.matrix_decomposition, }. @[simp] lemma matrix_decomposition_id (o : hom_orthogonal s) {α : Type} [fintype α] {f : α → ι} (i : ι) : o.matrix_decomposition (𝟙 (⨁ (λ a, s (f a)))) i = 1 := begin ext ⟨b, ⟨⟩⟩ ⟨a⟩, simp only [set.mem_preimage, set.mem_singleton_iff] at j_property, simp only [category.comp_id, category.id_comp, category.assoc, End.one_def, eq_to_hom_refl, matrix.one_apply, hom_orthogonal.matrix_decomposition_apply, biproduct.components], split_ifs with h, { cases h, simp, }, { convert comp_zero, simpa using biproduct.ι_π_ne _ (ne.symm h), }, end lemma matrix_decomposition_comp (o : hom_orthogonal s) {α β γ : Type} [fintype α] [fintype β] [fintype γ] {f : α → ι} {g : β → ι} {h : γ → ι} (z : (⨁ (λ a, s (f a)) ⟶ ⨁ (λ b, s (g b)))) (w : (⨁ (λ b, s (g b)) ⟶ ⨁ (λ c, s (h c)))) (i : ι) : o.matrix_decomposition (z ≫ w) i = o.matrix_decomposition w i ⬝ o.matrix_decomposition z i := begin ext ⟨c, ⟨⟩⟩ ⟨a⟩, simp only [set.mem_preimage, set.mem_singleton_iff] at j_property, simp only [matrix.mul_apply, limits.biproduct.components, hom_orthogonal.matrix_decomposition_apply, category.comp_id, category.id_comp, category.assoc, End.mul_def, eq_to_hom_refl, eq_to_hom_trans_assoc, finset.sum_congr], conv_lhs { rw [←category.id_comp w, ←biproduct.total], }, simp only [preadditive.sum_comp, preadditive.comp_sum], apply finset.sum_congr_set, { intros, simp, refl, }, { intros b nm, simp only [set.mem_preimage, set.mem_singleton_iff] at nm, simp only [category.assoc], convert comp_zero, convert comp_zero, convert comp_zero, convert comp_zero, apply o.eq_zero nm, }, end section variables {R : Type*} [semiring R] [linear R C] /-- `hom_orthogonal.matrix_decomposition` as an `R`-linear equivalence. -/ @[simps] noncomputable def matrix_decomposition_linear_equiv (o : hom_orthogonal s) {α β : Type} [fintype α] [fintype β] {f : α → ι} {g : β → ι} : (⨁ (λ a, s (f a)) ⟶ ⨁ (λ b, s (g b))) ≃ₗ[R] Π (i : ι), matrix (g ⁻¹' {i}) (f ⁻¹' {i}) (End (s i)) := { map_smul' := λ w z, by { ext, dsimp [biproduct.components], simp, }, ..o.matrix_decomposition_add_equiv, } end /-! The hypothesis that `End (s i)` has invariant basis number is automatically satisfied if `s i` is simple (as then `End (s i)` is a division ring). -/ variables [∀ i, invariant_basis_number (End (s i))] /-- Given a hom orthogonal family `s : ι → C` for which each `End (s i)` is a ring with invariant basis number (e.g. if each `s i` is simple), if two direct sums over `s` are isomorphic, then they have the same multiplicities. -/ lemma equiv_of_iso (o : hom_orthogonal s) {α β : Type} [fintype α] [fintype β] {f : α → ι} {g : β → ι} (i : ⨁ (λ a, s (f a)) ≅ ⨁ (λ b, s (g b))) : ∃ e : α ≃ β, ∀ a, g (e a) = f a := begin refine ⟨equiv.of_preimage_equiv _, λ a, equiv.of_preimage_equiv_map _ _⟩, intro c, apply nonempty.some, apply cardinal.eq.1, simp only [cardinal.mk_fintype, nat.cast_inj], exact matrix.square_of_invertible (o.matrix_decomposition i.inv c) (o.matrix_decomposition i.hom c) (by { rw ←o.matrix_decomposition_comp, simp, }) (by { rw ←o.matrix_decomposition_comp, simp, }) end end end hom_orthogonal end category_theory
37157fcd5a6f57b5a146811a64d75c49e6d0931e
4f065978c49388d188224610d9984673079f7d91
/partition.lean
5d3883f754dde8212d55dd125b77594daa243693
[]
no_license
kckennylau/Lean
b323103f52706304907adcfaee6f5cb8095d4a33
907d0a4d2bd8f23785abd6142ad53d308c54fdcb
refs/heads/master
1,624,623,720,653
1,563,901,820,000
1,563,901,820,000
109,506,702
3
1
null
null
null
null
UTF-8
Lean
false
false
4,337
lean
import data.set.basic universe u structure equivalence_relation (α : Type u) := (f : α → α → Prop) (reflexive : ∀ x, f x x) (symmetric : ∀ x y, f x y → f y x) (transitive : ∀ x y z, f x y → f y z → f x z) structure partition (α : Type u) := (A : set (set α)) (prop : ∀ x, ∃! t, x ∈ t ∧ t ∈ A) (non_empty : ∀ X, X ∈ A → ∃ y, y ∈ X) open equivalence_relation open partition variables {α : Type u} def equivalence_relation.stage_1 (f : α → α → Prop) : α → set α := λ x y, f x y def equivalence_relation.stage_2 (f : α → α → Prop) : set (set α) := set.image (equivalence_relation.stage_1 f) set.univ variable α instance equivalence_relation.to_partition : has_coe (equivalence_relation α) (partition α) := begin constructor, intro h, fapply partition.mk, exact equivalence_relation.stage_2 h.f, intro x, existsi equivalence_relation.stage_1 h.f x, split, split, exact h.reflexive x, existsi x, split, constructor, refl, intros X hy, cases hy with h1 h2, cases h2 with y h2, cases h2 with h2 h3, rw ←h3 at *, apply set.ext, intro z, split, intro h4, apply h.transitive x y z, apply h.symmetric, exact h1, exact h4, intro h4, apply h.transitive y x z, exact h1, exact h4, intros X h1, unfold equivalence_relation.stage_2 at h1, cases h1 with x h1, existsi x, rw ←h1.2, exact h.reflexive x end variable {α} def partition.stage_1 (A : set (set α)) : α → α → Prop := λ x y, ∃ t, t ∈ A ∧ x ∈ t ∧ y ∈ t variable α instance partition.to_equivalence_relation : has_coe (partition α) (equivalence_relation α) := begin constructor, intro h, fapply equivalence_relation.mk, exact partition.stage_1 h.A, intro x, cases h.prop x with X h1, cases h1 with h1 h2, existsi X, exact ⟨h1.2, h1.1, h1.1⟩, intros x y h1, cases h1 with X h1, existsi X, exact ⟨h1.1, h1.2.2, h1.2.1⟩, intros x y z hxy hyz, cases hxy with X hxy, cases hyz with Y hyz, cases h.prop y with Z h1, have h2 := h1.2 X ⟨hxy.2.2, hxy.1⟩, have h3 := h1.2 Y ⟨hyz.2.1, hyz.1⟩, existsi X, rw h2 at *, rw h3 at *, exact ⟨hxy.1, hxy.2.1, hyz.2.2⟩ end theorem equivalence_relation.to_partition.to_equivalence_relation (h : equivalence_relation α) : has_coe.coe (equivalence_relation α) (has_coe.coe (partition α) h) = h:= begin unfold has_coe.coe, cases h, congr, unfold partition.stage_1, apply funext, intro x, apply funext, intro y, unfold equivalence_relation.stage_2, unfold equivalence_relation.stage_1, apply iff_iff_eq.1, split, intro h, cases h with X h, cases h with h1 h2, cases h2 with h2 h3, unfold set.image at h1, cases h1 with z h1, dsimp at h1, apply h_transitive x z y, apply h_symmetric, rw h1.2, exact h2, rw h1.2, exact h3, intro h, existsi h_f x, split, existsi x, split, constructor, refl, split, exact h_reflexive x, exact h end theorem partition.to_equivalence_relation.to_partition (h : partition α) : has_coe.coe (partition α) (has_coe.coe (equivalence_relation α) h) = h:= begin unfold has_coe.coe, cases h, congr, unfold equivalence_relation.stage_2, unfold equivalence_relation.stage_1, unfold partition.stage_1, unfold set.image, apply set.ext, intro X, split, intro h, cases h with x h, dsimp at h, cases h with h1 h, clear h1, have h1 := h_prop x, cases h1 with Y h1, cases h1 with h1 h2, cases h1 with h1 h3, have h4 : X = Y, apply set.ext, intro z, split, intro hz, rw ←h at hz, cases hz with Z hz, specialize h2 Z ⟨hz.2.1, hz.1⟩, rw ←h2, exact hz.2.2, intro hz, rw ←h, existsi Y, exact ⟨h3,h1,hz⟩, rwa h4, intro h, dsimp, cases h_non_empty X h with x hx, existsi x, split, constructor, apply set.ext, intro z, split, intro hz, cases hz with Y h1, cases h1 with h1 h2, cases h_prop x with Z hz, have h3 := hz.2 X ⟨hx,h⟩, have h4 := hz.2 Y ⟨h2.1,h1⟩, rw h3, rw ←h4, exact h2.2, intro hz, existsi X, exact ⟨h,hx,hz⟩ end
5fb4a1be3d61f89edd823e1099e8ca5920945c79
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/order/module.lean
be66690ff16950bbd9a6ac2c0d92a03ba2b04ee4
[ "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
8,857
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, Yaël Dillies -/ import algebra.order.smul /-! # Ordered module > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we provide lemmas about `ordered_smul` that hold once a module structure is present. ## References * https://en.wikipedia.org/wiki/Ordered_module ## Tags ordered module, ordered scalar, ordered smul, ordered action, ordered vector space -/ open_locale pointwise variables {k M N : Type*} instance [semiring k] [ordered_add_comm_monoid M] [module k M] : module k Mᵒᵈ := { add_smul := λ r s x, order_dual.rec (add_smul _ _) x, zero_smul := λ m, order_dual.rec (zero_smul _) m } section semiring variables [ordered_semiring k] [ordered_add_comm_group M] [module k M] [ordered_smul k M] {a b : M} {c : k} /- can be generalized from `module k M` to `distrib_mul_action_with_zero k M` once it exists. where `distrib_mul_action_with_zero k M`is the conjunction of `distrib_mul_action k M` and `smul_with_zero k M`.-/ lemma smul_neg_iff_of_pos (hc : 0 < c) : c • a < 0 ↔ a < 0 := begin rw [←neg_neg a, smul_neg, neg_neg_iff_pos, neg_neg_iff_pos], exact smul_pos_iff_of_pos hc, end end semiring section ring variables [ordered_ring k] [ordered_add_comm_group M] [module k M] [ordered_smul k M] {a b : M} {c : k} lemma smul_lt_smul_of_neg (h : a < b) (hc : c < 0) : c • b < c • a := begin rw [←neg_neg c, neg_smul, neg_smul (-c), neg_lt_neg_iff], exact smul_lt_smul_of_pos h (neg_pos_of_neg hc), end lemma smul_le_smul_of_nonpos (h : a ≤ b) (hc : c ≤ 0) : c • b ≤ c • a := begin rw [←neg_neg c, neg_smul, neg_smul (-c), neg_le_neg_iff], exact smul_le_smul_of_nonneg h (neg_nonneg_of_nonpos hc), end lemma eq_of_smul_eq_smul_of_neg_of_le (hab : c • a = c • b) (hc : c < 0) (h : a ≤ b) : a = b := begin rw [←neg_neg c, neg_smul, neg_smul (-c), neg_inj] at hab, exact eq_of_smul_eq_smul_of_pos_of_le hab (neg_pos_of_neg hc) h, end lemma lt_of_smul_lt_smul_of_nonpos (h : c • a < c • b) (hc : c ≤ 0) : b < a := begin rw [←neg_neg c, neg_smul, neg_smul (-c), neg_lt_neg_iff] at h, exact lt_of_smul_lt_smul_of_nonneg h (neg_nonneg_of_nonpos hc), end lemma smul_lt_smul_iff_of_neg (hc : c < 0) : c • a < c • b ↔ b < a := begin rw [←neg_neg c, neg_smul, neg_smul (-c), neg_lt_neg_iff], exact smul_lt_smul_iff_of_pos (neg_pos_of_neg hc), end lemma smul_neg_iff_of_neg (hc : c < 0) : c • a < 0 ↔ 0 < a := begin rw [←neg_neg c, neg_smul, neg_neg_iff_pos], exact smul_pos_iff_of_pos (neg_pos_of_neg hc), end lemma smul_pos_iff_of_neg (hc : c < 0) : 0 < c • a ↔ a < 0 := begin rw [←neg_neg c, neg_smul, neg_pos], exact smul_neg_iff_of_pos (neg_pos_of_neg hc), end lemma smul_nonpos_of_nonpos_of_nonneg (hc : c ≤ 0) (ha : 0 ≤ a) : c • a ≤ 0 := calc c • a ≤ c • 0 : smul_le_smul_of_nonpos ha hc ... = 0 : smul_zero c lemma smul_nonneg_of_nonpos_of_nonpos (hc : c ≤ 0) (ha : a ≤ 0) : 0 ≤ c • a := @smul_nonpos_of_nonpos_of_nonneg k Mᵒᵈ _ _ _ _ _ _ hc ha alias smul_pos_iff_of_neg ↔ _ smul_pos_of_neg_of_neg alias smul_neg_iff_of_pos ↔ _ smul_neg_of_pos_of_neg alias smul_neg_iff_of_neg ↔ _ smul_neg_of_neg_of_pos lemma antitone_smul_left (hc : c ≤ 0) : antitone (has_smul.smul c : M → M) := λ a b h, smul_le_smul_of_nonpos h hc lemma strict_anti_smul_left (hc : c < 0) : strict_anti (has_smul.smul c : M → M) := λ a b h, smul_lt_smul_of_neg h hc /-- Binary **rearrangement inequality**. -/ lemma smul_add_smul_le_smul_add_smul [contravariant_class M M (+) (≤)] {a b : k} {c d : M} (hab : a ≤ b) (hcd : c ≤ d) : a • d + b • c ≤ a • c + b • d := begin obtain ⟨b, rfl⟩ := exists_add_of_le hab, obtain ⟨d, rfl⟩ := exists_add_of_le hcd, rw [smul_add, add_right_comm, smul_add, ←add_assoc, add_smul _ _ d], rw le_add_iff_nonneg_right at hab hcd, exact add_le_add_left (le_add_of_nonneg_right $ smul_nonneg hab hcd) _, end /-- Binary **rearrangement inequality**. -/ lemma smul_add_smul_le_smul_add_smul' [contravariant_class M M (+) (≤)] {a b : k} {c d : M} (hba : b ≤ a) (hdc : d ≤ c) : a • d + b • c ≤ a • c + b • d := by { rw [add_comm (a • d), add_comm (a • c)], exact smul_add_smul_le_smul_add_smul hba hdc } /-- Binary strict **rearrangement inequality**. -/ lemma smul_add_smul_lt_smul_add_smul [covariant_class M M (+) (<)] [contravariant_class M M (+) (<)] {a b : k} {c d : M} (hab : a < b) (hcd : c < d) : a • d + b • c < a • c + b • d := begin obtain ⟨b, rfl⟩ := exists_add_of_le hab.le, obtain ⟨d, rfl⟩ := exists_add_of_le hcd.le, rw [smul_add, add_right_comm, smul_add, ←add_assoc, add_smul _ _ d], rw lt_add_iff_pos_right at hab hcd, exact add_lt_add_left (lt_add_of_pos_right _ $ smul_pos hab hcd) _, end /-- Binary strict **rearrangement inequality**. -/ lemma smul_add_smul_lt_smul_add_smul' [covariant_class M M (+) (<)] [contravariant_class M M (+) (<)] {a b : k} {c d : M} (hba : b < a) (hdc : d < c) : a • d + b • c < a • c + b • d := by { rw [add_comm (a • d), add_comm (a • c)], exact smul_add_smul_lt_smul_add_smul hba hdc } end ring section field variables [linear_ordered_field k] [ordered_add_comm_group M] [module k M] [ordered_smul k M] {a b : M} {c : k} lemma smul_le_smul_iff_of_neg (hc : c < 0) : c • a ≤ c • b ↔ b ≤ a := begin rw [←neg_neg c, neg_smul, neg_smul (-c), neg_le_neg_iff], exact smul_le_smul_iff_of_pos (neg_pos_of_neg hc), end lemma inv_smul_le_iff_of_neg (h : c < 0) : c⁻¹ • a ≤ b ↔ c • b ≤ a := by { rw [←smul_le_smul_iff_of_neg h, smul_inv_smul₀ h.ne], apply_instance } lemma inv_smul_lt_iff_of_neg (h : c < 0) : c⁻¹ • a < b ↔ c • b < a := by { rw [←smul_lt_smul_iff_of_neg h, smul_inv_smul₀ h.ne], apply_instance } lemma smul_inv_le_iff_of_neg (h : c < 0) : a ≤ c⁻¹ • b ↔ b ≤ c • a := by { rw [←smul_le_smul_iff_of_neg h, smul_inv_smul₀ h.ne], apply_instance } lemma smul_inv_lt_iff_of_neg (h : c < 0) : a < c⁻¹ • b ↔ b < c • a := by { rw [←smul_lt_smul_iff_of_neg h, smul_inv_smul₀ h.ne], apply_instance } variables (M) /-- Left scalar multiplication as an order isomorphism. -/ @[simps] def order_iso.smul_left_dual {c : k} (hc : c < 0) : M ≃o Mᵒᵈ := { to_fun := λ b, order_dual.to_dual (c • b), inv_fun := λ b, c⁻¹ • (order_dual.of_dual b), left_inv := inv_smul_smul₀ hc.ne, right_inv := smul_inv_smul₀ hc.ne, map_rel_iff' := λ b₁ b₂, smul_le_smul_iff_of_neg hc } end field /-! ### Upper/lower bounds -/ section ordered_ring variables [ordered_ring k] [ordered_add_comm_group M] [module k M] [ordered_smul k M] {s : set M} {c : k} lemma smul_lower_bounds_subset_upper_bounds_smul (hc : c ≤ 0) : c • lower_bounds s ⊆ upper_bounds (c • s) := (antitone_smul_left hc).image_lower_bounds_subset_upper_bounds_image lemma smul_upper_bounds_subset_lower_bounds_smul (hc : c ≤ 0) : c • upper_bounds s ⊆ lower_bounds (c • s) := (antitone_smul_left hc).image_upper_bounds_subset_lower_bounds_image lemma bdd_below.smul_of_nonpos (hc : c ≤ 0) (hs : bdd_below s) : bdd_above (c • s) := (antitone_smul_left hc).map_bdd_below hs lemma bdd_above.smul_of_nonpos (hc : c ≤ 0) (hs : bdd_above s) : bdd_below (c • s) := (antitone_smul_left hc).map_bdd_above hs end ordered_ring section linear_ordered_ring variables [linear_ordered_ring k] [linear_ordered_add_comm_group M] [module k M] [ordered_smul k M] {a : k} lemma smul_max_of_nonpos (ha : a ≤ 0) (b₁ b₂ : M) : a • max b₁ b₂ = min (a • b₁) (a • b₂) := (antitone_smul_left ha : antitone (_ : M → M)).map_max lemma smul_min_of_nonpos (ha : a ≤ 0) (b₁ b₂ : M) : a • min b₁ b₂ = max (a • b₁) (a • b₂) := (antitone_smul_left ha : antitone (_ : M → M)).map_min end linear_ordered_ring section linear_ordered_field variables [linear_ordered_field k] [ordered_add_comm_group M] [module k M] [ordered_smul k M] {s : set M} {c : k} @[simp] lemma lower_bounds_smul_of_neg (hc : c < 0) : lower_bounds (c • s) = c • upper_bounds s := (order_iso.smul_left_dual M hc).upper_bounds_image @[simp] lemma upper_bounds_smul_of_neg (hc : c < 0) : upper_bounds (c • s) = c • lower_bounds s := (order_iso.smul_left_dual M hc).lower_bounds_image @[simp] lemma bdd_below_smul_iff_of_neg (hc : c < 0) : bdd_below (c • s) ↔ bdd_above s := (order_iso.smul_left_dual M hc).bdd_above_image @[simp] lemma bdd_above_smul_iff_of_neg (hc : c < 0) : bdd_above (c • s) ↔ bdd_below s := (order_iso.smul_left_dual M hc).bdd_below_image end linear_ordered_field
d9afb9d5821fc408883d12257aee69981146cc40
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/category_theory/category/basic.lean
1de3fae786fda1b26340e9495801eca4318c03cc
[ "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
10,531
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Scott Morrison, Johannes Hölzl, Reid Barton -/ import combinatorics.quiver.basic import tactic.basic /-! # Categories Defines a category, as a type class parametrised by the type of objects. ## Notations Introduces notations * `X ⟶ Y` for the morphism spaces, * `f ≫ g` for composition in the 'arrows' convention. Users may like to add `f ⊚ g` for composition in the standard convention, using ```lean local notation f ` ⊚ `:80 g:80 := category.comp g f -- type as \oo ``` -/ /-- The typeclass `category C` describes morphisms associated to objects of type `C : Type u`. The universe levels of the objects and morphisms are independent, and will often need to be specified explicitly, as `category.{v} C`. Typically any concrete example will either be a `small_category`, where `v = u`, which can be introduced as ``` universes u variables {C : Type u} [small_category C] ``` or a `large_category`, where `u = v+1`, which can be introduced as ``` universes u variables {C : Type (u+1)} [large_category C] ``` In order for the library to handle these cases uniformly, we generally work with the unconstrained `category.{v u}`, for which objects live in `Type u` and morphisms live in `Type v`. Because the universe parameter `u` for the objects can be inferred from `C` when we write `category C`, while the universe parameter `v` for the morphisms can not be automatically inferred, through the category theory library we introduce universe parameters with morphism levels listed first, as in ``` universes v u ``` or ``` universes v₁ v₂ u₁ u₂ ``` when multiple independent universes are needed. This has the effect that we can simply write `category.{v} C` (that is, only specifying a single parameter) while `u` will be inferred. Often, however, it's not even necessary to include the `.{v}`. (Although it was in earlier versions of Lean.) If it is omitted a "free" universe will be used. -/ library_note "category_theory universes" universes v u namespace category_theory /-- A preliminary structure on the way to defining a category, containing the data, but none of the axioms. -/ class category_struct (obj : Type u) extends quiver.{v+1} obj : Type (max u (v+1)) := (id : Π X : obj, hom X X) (comp : Π {X Y Z : obj}, (X ⟶ Y) → (Y ⟶ Z) → (X ⟶ Z)) notation `𝟙` := category_struct.id -- type as \b1 infixr ` ≫ `:80 := category_struct.comp -- type as \gg /-- The typeclass `category C` describes morphisms associated to objects of type `C`. The universe levels of the objects and morphisms are unconstrained, and will often need to be specified explicitly, as `category.{v} C`. (See also `large_category` and `small_category`.) See https://stacks.math.columbia.edu/tag/0014. -/ class category (obj : Type u) extends category_struct.{v} obj : Type (max u (v+1)) := (id_comp' : ∀ {X Y : obj} (f : hom X Y), 𝟙 X ≫ f = f . obviously) (comp_id' : ∀ {X Y : obj} (f : hom X Y), f ≫ 𝟙 Y = f . obviously) (assoc' : ∀ {W X Y Z : obj} (f : hom W X) (g : hom X Y) (h : hom Y Z), (f ≫ g) ≫ h = f ≫ (g ≫ h) . obviously) -- `restate_axiom` is a command that creates a lemma from a structure field, -- discarding any auto_param wrappers from the type. -- (It removes a backtick from the name, if it finds one, and otherwise adds "_lemma".) restate_axiom category.id_comp' restate_axiom category.comp_id' restate_axiom category.assoc' attribute [simp] category.id_comp category.comp_id category.assoc attribute [trans] category_struct.comp /-- A `large_category` has objects in one universe level higher than the universe level of the morphisms. It is useful for examples such as the category of types, or the category of groups, etc. -/ abbreviation large_category (C : Type (u+1)) : Type (u+1) := category.{u} C /-- A `small_category` has objects and morphisms in the same universe level. -/ abbreviation small_category (C : Type u) : Type (u+1) := category.{u} C section variables {C : Type u} [category.{v} C] {X Y Z : C} initialize_simps_projections category (to_category_struct_to_quiver_hom → hom, to_category_struct_comp → comp, to_category_struct_id → id, -to_category_struct) /-- postcompose an equation between morphisms by another morphism -/ lemma eq_whisker {f g : X ⟶ Y} (w : f = g) (h : Y ⟶ Z) : f ≫ h = g ≫ h := by rw w /-- precompose an equation between morphisms by another morphism -/ lemma whisker_eq (f : X ⟶ Y) {g h : Y ⟶ Z} (w : g = h) : f ≫ g = f ≫ h := by rw w infixr ` =≫ `:80 := eq_whisker infixr ` ≫= `:80 := whisker_eq lemma eq_of_comp_left_eq {f g : X ⟶ Y} (w : ∀ {Z : C} (h : Y ⟶ Z), f ≫ h = g ≫ h) : f = g := by { convert w (𝟙 Y), tidy } lemma eq_of_comp_right_eq {f g : Y ⟶ Z} (w : ∀ {X : C} (h : X ⟶ Y), h ≫ f = h ≫ g) : f = g := by { convert w (𝟙 Y), tidy } lemma eq_of_comp_left_eq' (f g : X ⟶ Y) (w : (λ {Z : C} (h : Y ⟶ Z), f ≫ h) = (λ {Z : C} (h : Y ⟶ Z), g ≫ h)) : f = g := eq_of_comp_left_eq (λ Z h, by convert congr_fun (congr_fun w Z) h) lemma eq_of_comp_right_eq' (f g : Y ⟶ Z) (w : (λ {X : C} (h : X ⟶ Y), h ≫ f) = (λ {X : C} (h : X ⟶ Y), h ≫ g)) : f = g := eq_of_comp_right_eq (λ X h, by convert congr_fun (congr_fun w X) h) lemma id_of_comp_left_id (f : X ⟶ X) (w : ∀ {Y : C} (g : X ⟶ Y), f ≫ g = g) : f = 𝟙 X := by { convert w (𝟙 X), tidy } lemma id_of_comp_right_id (f : X ⟶ X) (w : ∀ {Y : C} (g : Y ⟶ X), g ≫ f = g) : f = 𝟙 X := by { convert w (𝟙 X), tidy } lemma comp_dite {P : Prop} [decidable P] {X Y Z : C} (f : X ⟶ Y) (g : P → (Y ⟶ Z)) (g' : ¬P → (Y ⟶ Z)) : (f ≫ if h : P then g h else g' h) = (if h : P then f ≫ g h else f ≫ g' h) := by { split_ifs; refl } lemma dite_comp {P : Prop} [decidable P] {X Y Z : C} (f : P → (X ⟶ Y)) (f' : ¬P → (X ⟶ Y)) (g : Y ⟶ Z) : (if h : P then f h else f' h) ≫ g = (if h : P then f h ≫ g else f' h ≫ g) := by { split_ifs; refl } /-- A morphism `f` is an epimorphism if it can be "cancelled" when precomposed: `f ≫ g = f ≫ h` implies `g = h`. See https://stacks.math.columbia.edu/tag/003B. -/ class epi (f : X ⟶ Y) : Prop := (left_cancellation : Π {Z : C} (g h : Y ⟶ Z) (w : f ≫ g = f ≫ h), g = h) /-- A morphism `f` is a monomorphism if it can be "cancelled" when postcomposed: `g ≫ f = h ≫ f` implies `g = h`. See https://stacks.math.columbia.edu/tag/003B. -/ class mono (f : X ⟶ Y) : Prop := (right_cancellation : Π {Z : C} (g h : Z ⟶ X) (w : g ≫ f = h ≫ f), g = h) instance (X : C) : epi (𝟙 X) := ⟨λ Z g h w, by simpa using w⟩ instance (X : C) : mono (𝟙 X) := ⟨λ Z g h w, by simpa using w⟩ lemma cancel_epi (f : X ⟶ Y) [epi f] {g h : Y ⟶ Z} : (f ≫ g = f ≫ h) ↔ g = h := ⟨ λ p, epi.left_cancellation g h p, begin intro a, subst a end ⟩ lemma cancel_mono (f : X ⟶ Y) [mono f] {g h : Z ⟶ X} : (g ≫ f = h ≫ f) ↔ g = h := ⟨ λ p, mono.right_cancellation g h p, begin intro a, subst a end ⟩ lemma cancel_epi_id (f : X ⟶ Y) [epi f] {h : Y ⟶ Y} : (f ≫ h = f) ↔ h = 𝟙 Y := by { convert cancel_epi f, simp, } lemma cancel_mono_id (f : X ⟶ Y) [mono f] {g : X ⟶ X} : (g ≫ f = f) ↔ g = 𝟙 X := by { convert cancel_mono f, simp, } lemma epi_comp {X Y Z : C} (f : X ⟶ Y) [epi f] (g : Y ⟶ Z) [epi g] : epi (f ≫ g) := begin split, intros Z a b w, apply (cancel_epi g).1, apply (cancel_epi f).1, simpa using w, end lemma mono_comp {X Y Z : C} (f : X ⟶ Y) [mono f] (g : Y ⟶ Z) [mono g] : mono (f ≫ g) := begin split, intros Z a b w, apply (cancel_mono f).1, apply (cancel_mono g).1, simpa using w, end lemma mono_of_mono {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [mono (f ≫ g)] : mono f := begin split, intros Z a b w, replace w := congr_arg (λ k, k ≫ g) w, dsimp at w, rw [category.assoc, category.assoc] at w, exact (cancel_mono _).1 w, end lemma mono_of_mono_fac {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} {h : X ⟶ Z} [mono h] (w : f ≫ g = h) : mono f := by { substI h, exact mono_of_mono f g, } lemma epi_of_epi {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [epi (f ≫ g)] : epi g := begin split, intros Z a b w, replace w := congr_arg (λ k, f ≫ k) w, dsimp at w, rw [←category.assoc, ←category.assoc] at w, exact (cancel_epi _).1 w, end lemma epi_of_epi_fac {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} {h : X ⟶ Z} [epi h] (w : f ≫ g = h) : epi g := by substI h; exact epi_of_epi f g end section variable (C : Type u) variable [category.{v} C] universe u' instance ulift_category : category.{v} (ulift.{u'} C) := { hom := λ X Y, (X.down ⟶ Y.down), id := λ X, 𝟙 X.down, comp := λ _ _ _ f g, f ≫ g } -- We verify that this previous instance can lift small categories to large categories. example (D : Type u) [small_category D] : large_category (ulift.{u+1} D) := by apply_instance end end category_theory /-- Many proofs in the category theory library use the `dsimp, simp` pattern, which typically isn't necessary elsewhere. One would usually hope that the same effect could be achieved simply with `simp`. The essential issue is that composition of morphisms involves dependent types. When you have a chain of morphisms being composed, say `f : X ⟶ Y` and `g : Y ⟶ Z`, then `simp` can operate succesfully on the morphisms (e.g. if `f` is the identity it can strip that off). However if we have an equality of objects, say `Y = Y'`, then `simp` can't operate because it would break the typing of the composition operations. We rarely have interesting equalities of objects (because that would be "evil" --- anything interesting should be expressed as an isomorphism and tracked explicitly), except of course that we have plenty of definitional equalities of objects. `dsimp` can apply these safely, even inside a composition. After `dsimp` has cleared up the object level, `simp` can resume work on the morphism level --- but without the `dsimp` step, because `simp` looks at expressions syntactically, the relevant lemmas might not fire. There's no bound on how many times you potentially could have to switch back and forth, if the `simp` introduced new objects we again need to `dsimp`. In practice this does occur, but only rarely, because `simp` tends to shorten chains of compositions (i.e. not introduce new objects at all). -/ library_note "dsimp, simp"
1dbb089a7b59736ce7bc179f3bf8748072e8aacf
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/category_theory/natural_isomorphism.lean
55d1b7c2f3c93c55b26838c63468c905ac69eb0b
[ "Apache-2.0" ]
permissive
SAAluthwela/mathlib
62044349d72dd63983a8500214736aa7779634d3
83a4b8b990907291421de54a78988c024dc8a552
refs/heads/master
1,679,433,873,417
1,615,998,031,000
1,615,998,031,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,344
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baumann, Stephen Morgan, Scott Morrison, Floris van Doorn -/ import category_theory.functor_category import category_theory.isomorphism /-! # Natural isomorphisms For the most part, natural isomorphisms are just another sort of isomorphism. We provide some special support for extracting components: * if `α : F ≅ G`, then `a.app X : F.obj X ≅ G.obj X`, and building natural isomorphisms from components: * ``` nat_iso.of_components (app : ∀ X : C, F.obj X ≅ G.obj X) (naturality : ∀ {X Y : C} (f : X ⟶ Y), F.map f ≫ (app Y).hom = (app X).hom ≫ G.map f) : F ≅ G ``` only needing to check naturality in one direction. ## Implementation Note that `nat_iso` is a namespace without a corresponding definition; we put some declarations that are specifically about natural isomorphisms in the `iso` namespace so that they are available using dot notation. -/ open category_theory -- declare the `v`'s first; see `category_theory.category` for an explanation universes v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄ namespace category_theory open nat_trans variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] {E : Type u₃} [category.{v₃} E] namespace iso /-- The application of a natural isomorphism to an object. We put this definition in a different namespace, so that we can use `α.app` -/ @[simps] def app {F G : C ⥤ D} (α : F ≅ G) (X : C) : F.obj X ≅ G.obj X := { hom := α.hom.app X, inv := α.inv.app X, hom_inv_id' := begin rw [← comp_app, iso.hom_inv_id], refl end, inv_hom_id' := begin rw [← comp_app, iso.inv_hom_id], refl end } @[simp, reassoc] lemma hom_inv_id_app {F G : C ⥤ D} (α : F ≅ G) (X : C) : α.hom.app X ≫ α.inv.app X = 𝟙 (F.obj X) := congr_fun (congr_arg nat_trans.app α.hom_inv_id) X @[simp, reassoc] lemma inv_hom_id_app {F G : C ⥤ D} (α : F ≅ G) (X : C) : α.inv.app X ≫ α.hom.app X = 𝟙 (G.obj X) := congr_fun (congr_arg nat_trans.app α.inv_hom_id) X end iso namespace nat_iso open category_theory.category category_theory.functor @[simp] lemma trans_app {F G H : C ⥤ D} (α : F ≅ G) (β : G ≅ H) (X : C) : (α ≪≫ β).app X = α.app X ≪≫ β.app X := rfl lemma app_hom {F G : C ⥤ D} (α : F ≅ G) (X : C) : (α.app X).hom = α.hom.app X := rfl lemma app_inv {F G : C ⥤ D} (α : F ≅ G) (X : C) : (α.app X).inv = α.inv.app X := rfl variables {F G : C ⥤ D} instance hom_app_is_iso (α : F ≅ G) (X : C) : is_iso (α.hom.app X) := ⟨α.inv.app X, ⟨by rw [←comp_app, iso.hom_inv_id, ←id_app], by rw [←comp_app, iso.inv_hom_id, ←id_app]⟩⟩ instance inv_app_is_iso (α : F ≅ G) (X : C) : is_iso (α.inv.app X) := ⟨α.hom.app X, ⟨by rw [←comp_app, iso.inv_hom_id, ←id_app], by rw [←comp_app, iso.hom_inv_id, ←id_app]⟩⟩ section /-! Unfortunately we need a separate set of cancellation lemmas for components of natural isomorphisms, because the `simp` normal form is `α.hom.app X`, rather than `α.app.hom X`. (With the later, the morphism would be visibly part of an isomorphism, so general lemmas about isomorphisms would apply.) In the future, we should consider a redesign that changes this simp norm form, but for now it breaks too many proofs. -/ variables (α : F ≅ G) @[simp] lemma cancel_nat_iso_hom_left {X : C} {Z : D} (g g' : G.obj X ⟶ Z) : α.hom.app X ≫ g = α.hom.app X ≫ g' ↔ g = g' := by simp only [cancel_epi] @[simp] lemma cancel_nat_iso_inv_left {X : C} {Z : D} (g g' : F.obj X ⟶ Z) : α.inv.app X ≫ g = α.inv.app X ≫ g' ↔ g = g' := by simp only [cancel_epi] @[simp] lemma cancel_nat_iso_hom_right {X : D} {Y : C} (f f' : X ⟶ F.obj Y) : f ≫ α.hom.app Y = f' ≫ α.hom.app Y ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_nat_iso_inv_right {X : D} {Y : C} (f f' : X ⟶ G.obj Y) : f ≫ α.inv.app Y = f' ≫ α.inv.app Y ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_nat_iso_hom_right_assoc {W X X' : D} {Y : C} (f : W ⟶ X) (g : X ⟶ F.obj Y) (f' : W ⟶ X') (g' : X' ⟶ F.obj Y) : f ≫ g ≫ α.hom.app Y = f' ≫ g' ≫ α.hom.app Y ↔ f ≫ g = f' ≫ g' := by simp only [←category.assoc, cancel_mono] @[simp] lemma cancel_nat_iso_inv_right_assoc {W X X' : D} {Y : C} (f : W ⟶ X) (g : X ⟶ G.obj Y) (f' : W ⟶ X') (g' : X' ⟶ G.obj Y) : f ≫ g ≫ α.inv.app Y = f' ≫ g' ≫ α.inv.app Y ↔ f ≫ g = f' ≫ g' := by simp only [←category.assoc, cancel_mono] end variables {X Y : C} lemma naturality_1 (α : F ≅ G) (f : X ⟶ Y) : (α.inv.app X) ≫ (F.map f) ≫ (α.hom.app Y) = G.map f := by rw [naturality, ←category.assoc, ←nat_trans.comp_app, α.inv_hom_id, id_app, category.id_comp] lemma naturality_2 (α : F ≅ G) (f : X ⟶ Y) : (α.hom.app X) ≫ (G.map f) ≫ (α.inv.app Y) = F.map f := by rw [naturality, ←category.assoc, ←nat_trans.comp_app, α.hom_inv_id, id_app, category.id_comp] /-- The components of a natural isomorphism are isomorphisms. -/ instance is_iso_app_of_is_iso (α : F ⟶ G) [is_iso α] (X) : is_iso (α.app X) := ⟨(inv α).app X, ⟨congr_fun (congr_arg nat_trans.app (is_iso.hom_inv_id α)) X, congr_fun (congr_arg nat_trans.app (is_iso.inv_hom_id α)) X⟩⟩ @[simp] lemma is_iso_inv_app (α : F ⟶ G) [is_iso α] (X) : (inv α).app X = inv (α.app X) := by { ext, rw ←nat_trans.comp_app, simp, } /-- Construct a natural isomorphism between functors by giving object level isomorphisms, and checking naturality only in the forward direction. -/ def of_components (app : ∀ X : C, F.obj X ≅ G.obj X) (naturality : ∀ {X Y : C} (f : X ⟶ Y), F.map f ≫ (app Y).hom = (app X).hom ≫ G.map f) : F ≅ G := { hom := { app := λ X, (app X).hom }, inv := { app := λ X, (app X).inv, naturality' := λ X Y f, begin have h := congr_arg (λ f, (app X).inv ≫ (f ≫ (app Y).inv)) (naturality f).symm, simp only [iso.inv_hom_id_assoc, iso.hom_inv_id, assoc, comp_id, cancel_mono] at h, exact h end }, } @[simp] lemma of_components.app (app' : ∀ X : C, F.obj X ≅ G.obj X) (naturality) (X) : (of_components app' naturality).app X = app' X := by tidy @[simp] lemma of_components.hom_app (app : ∀ X : C, F.obj X ≅ G.obj X) (naturality) (X) : (of_components app naturality).hom.app X = (app X).hom := rfl @[simp] lemma of_components.inv_app (app : ∀ X : C, F.obj X ≅ G.obj X) (naturality) (X) : (of_components app naturality).inv.app X = (app X).inv := by simp [of_components] /-- A natural transformation is an isomorphism if all its components are isomorphisms. -/ -- Making this an instance would cause a typeclass inference loop with `is_iso_app_of_is_iso`. lemma is_iso_of_is_iso_app (α : F ⟶ G) [∀ X : C, is_iso (α.app X)] : is_iso α := is_iso.of_iso (of_components (λ X, as_iso (α.app X)) (by tidy)) /-- Horizontal composition of natural isomorphisms. -/ def hcomp {F G : C ⥤ D} {H I : D ⥤ E} (α : F ≅ G) (β : H ≅ I) : F ⋙ H ≅ G ⋙ I := begin refine ⟨α.hom ◫ β.hom, α.inv ◫ β.inv, _, _⟩, { ext, rw [←nat_trans.exchange], simp, refl }, ext, rw [←nat_trans.exchange], simp, refl end end nat_iso end category_theory
e2ab7230771926fb4753153639d1166470b811b3
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/probability/martingale/borel_cantelli.lean
d5093ba542c9860fba10ff0a902d90f71558a83b
[ "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
18,732
lean
/- Copyright (c) 2022 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import probability.martingale.convergence import probability.martingale.optional_stopping import probability.martingale.centering /-! # Generalized Borel-Cantelli lemma This file proves Lévy's generalized Borel-Cantelli lemma which is a generalization of the Borel-Cantelli lemmas. With this generalization, one can easily deduce the Borel-Cantelli lemmas by choosing appropriate filtrations. This file also contains the one sided martingale bound which is required to prove the generalized Borel-Cantelli. ## Main results - `measure_theory.submartingale.bdd_above_iff_exists_tendsto`: the one sided martingale bound: given a submartingale `f` with uniformly bounded differences, the set for which `f` converges is almost everywhere equal to the set for which it is bounded. - `measure_theory.ae_mem_limsup_at_top_iff`: Lévy's generalized Borel-Cantelli: given a filtration `ℱ` and a sequence of sets `s` such that `s n ∈ ℱ n` for all `n`, `limsup at_top s` is almost everywhere equal to the set for which `∑ ℙ[s (n + 1)∣ℱ n] = ∞`. -/ open filter open_locale nnreal ennreal measure_theory probability_theory big_operators topological_space namespace measure_theory variables {Ω : Type*} {m0 : measurable_space Ω} {μ : measure Ω} {ℱ : filtration ℕ m0} {f : ℕ → Ω → ℝ} {ω : Ω} /-! ### One sided martingale bound -/ -- TODO: `least_ge` should be defined taking values in `with_top ℕ` once the `stopped_process` -- refactor is complete /-- `least_ge f r n` is the stopping time corresponding to the first time `f ≥ r`. -/ noncomputable def least_ge (f : ℕ → Ω → ℝ) (r : ℝ) (n : ℕ) := hitting f (set.Ici r) 0 n lemma adapted.is_stopping_time_least_ge (r : ℝ) (n : ℕ) (hf : adapted ℱ f) : is_stopping_time ℱ (least_ge f r n) := hitting_is_stopping_time hf measurable_set_Ici lemma least_ge_le {i : ℕ} {r : ℝ} (ω : Ω) : least_ge f r i ω ≤ i := hitting_le ω -- The following four lemmas shows `least_ge` behaves like a stopped process. Ideally we should -- define `least_ge` as a stopping time and take its stopped process. However, we can't do that -- with our current definition since a stopping time takes only finite indicies. An upcomming -- refactor should hopefully make it possible to have stopping times taking infinity as a value lemma least_ge_mono {n m : ℕ} (hnm : n ≤ m) (r : ℝ) (ω : Ω) : least_ge f r n ω ≤ least_ge f r m ω := hitting_mono hnm lemma least_ge_eq_min (π : Ω → ℕ) (r : ℝ) (ω : Ω) {n : ℕ} (hπn : ∀ ω, π ω ≤ n) : least_ge f r (π ω) ω = min (π ω) (least_ge f r n ω) := begin classical, refine le_antisymm (le_min (least_ge_le _) (least_ge_mono (hπn ω) r ω)) _, by_cases hle : π ω ≤ least_ge f r n ω, { rw [min_eq_left hle, least_ge], by_cases h : ∃ j ∈ set.Icc 0 (π ω), f j ω ∈ set.Ici r, { refine hle.trans (eq.le _), rw [least_ge, ← hitting_eq_hitting_of_exists (hπn ω) h] }, { simp only [hitting, if_neg h] } }, { rw [min_eq_right (not_le.1 hle).le, least_ge, least_ge, ← hitting_eq_hitting_of_exists (hπn ω) _], rw [not_le, least_ge, hitting_lt_iff _ (hπn ω)] at hle, exact let ⟨j, hj₁, hj₂⟩ := hle in ⟨j, ⟨hj₁.1, hj₁.2.le⟩, hj₂⟩ } end lemma stopped_value_stopped_value_least_ge (f : ℕ → Ω → ℝ) (π : Ω → ℕ) (r : ℝ) {n : ℕ} (hπn : ∀ ω, π ω ≤ n) : stopped_value (λ i, stopped_value f (least_ge f r i)) π = stopped_value (stopped_process f (least_ge f r n)) π := by { ext1 ω, simp_rw [stopped_process, stopped_value], rw least_ge_eq_min _ _ _ hπn, } lemma submartingale.stopped_value_least_ge [is_finite_measure μ] (hf : submartingale f ℱ μ) (r : ℝ) : submartingale (λ i, stopped_value f (least_ge f r i)) ℱ μ := begin rw submartingale_iff_expected_stopped_value_mono, { intros σ π hσ hπ hσ_le_π hπ_bdd, obtain ⟨n, hπ_le_n⟩ := hπ_bdd, simp_rw stopped_value_stopped_value_least_ge f σ r (λ i, (hσ_le_π i).trans (hπ_le_n i)), simp_rw stopped_value_stopped_value_least_ge f π r hπ_le_n, refine hf.expected_stopped_value_mono _ _ _ (λ ω, (min_le_left _ _).trans (hπ_le_n ω)), { exact hσ.min (hf.adapted.is_stopping_time_least_ge _ _), }, { exact hπ.min (hf.adapted.is_stopping_time_least_ge _ _), }, { exact λ ω, min_le_min (hσ_le_π ω) le_rfl, }, }, { exact λ i, strongly_measurable_stopped_value_of_le hf.adapted.prog_measurable_of_discrete (hf.adapted.is_stopping_time_least_ge _ _) least_ge_le, }, { exact λ i, integrable_stopped_value _ ((hf.adapted.is_stopping_time_least_ge _ _)) (hf.integrable) least_ge_le, }, end variables {r : ℝ} {R : ℝ≥0} lemma norm_stopped_value_least_ge_le (hr : 0 ≤ r) (hf0 : f 0 = 0) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) (i : ℕ) : ∀ᵐ ω ∂μ, stopped_value f (least_ge f r i) ω ≤ r + R := begin filter_upwards [hbdd] with ω hbddω, change f (least_ge f r i ω) ω ≤ r + R, by_cases heq : least_ge f r i ω = 0, { rw [heq, hf0, pi.zero_apply], exact add_nonneg hr R.coe_nonneg }, { obtain ⟨k, hk⟩ := nat.exists_eq_succ_of_ne_zero heq, rw [hk, add_comm, ← sub_le_iff_le_add], have := not_mem_of_lt_hitting (hk.symm ▸ k.lt_succ_self : k < least_ge f r i ω) (zero_le _), simp only [set.mem_union, set.mem_Iic, set.mem_Ici, not_or_distrib, not_le] at this, exact (sub_lt_sub_left this _).le.trans ((le_abs_self _).trans (hbddω _)) } end lemma submartingale.stopped_value_least_ge_snorm_le [is_finite_measure μ] (hf : submartingale f ℱ μ) (hr : 0 ≤ r) (hf0 : f 0 = 0) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) (i : ℕ) : snorm (stopped_value f (least_ge f r i)) 1 μ ≤ 2 * μ set.univ * ennreal.of_real (r + R) := begin refine snorm_one_le_of_le' ((hf.stopped_value_least_ge r).integrable _) _ (norm_stopped_value_least_ge_le hr hf0 hbdd i), rw ← integral_univ, refine le_trans _ ((hf.stopped_value_least_ge r).set_integral_le (zero_le _) measurable_set.univ), simp_rw [stopped_value, least_ge, hitting_of_le le_rfl, hf0, integral_zero'] end lemma submartingale.stopped_value_least_ge_snorm_le' [is_finite_measure μ] (hf : submartingale f ℱ μ) (hr : 0 ≤ r) (hf0 : f 0 = 0) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) (i : ℕ) : snorm (stopped_value f (least_ge f r i)) 1 μ ≤ ennreal.to_nnreal (2 * μ set.univ * ennreal.of_real (r + R)) := begin refine (hf.stopped_value_least_ge_snorm_le hr hf0 hbdd i).trans _, simp [ennreal.coe_to_nnreal (measure_ne_top μ _), ennreal.coe_to_nnreal], end /-- This lemma is superceded by `submartingale.bdd_above_iff_exists_tendsto`. -/ lemma submartingale.exists_tendsto_of_abs_bdd_above_aux [is_finite_measure μ] (hf : submartingale f ℱ μ) (hf0 : f 0 = 0) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) : ∀ᵐ ω ∂μ, bdd_above (set.range $ λ n, f n ω) → ∃ c, tendsto (λ n, f n ω) at_top (𝓝 c) := begin have ht : ∀ᵐ ω ∂μ, ∀ i : ℕ, ∃ c, tendsto (λ n, stopped_value f (least_ge f i n) ω) at_top (𝓝 c), { rw ae_all_iff, exact λ i, submartingale.exists_ae_tendsto_of_bdd (hf.stopped_value_least_ge i) (hf.stopped_value_least_ge_snorm_le' i.cast_nonneg hf0 hbdd) }, filter_upwards [ht] with ω hω hωb, rw bdd_above at hωb, obtain ⟨i, hi⟩ := exists_nat_gt hωb.some, have hib : ∀ n, f n ω < i, { intro n, exact lt_of_le_of_lt ((mem_upper_bounds.1 hωb.some_mem) _ ⟨n, rfl⟩) hi }, have heq : ∀ n, stopped_value f (least_ge f i n) ω = f n ω, { intro n, rw [least_ge, hitting, stopped_value], simp only, rw if_neg, simp only [set.mem_Icc, set.mem_union, set.mem_Ici], push_neg, exact λ j _, hib j }, simp only [← heq, hω i], end lemma submartingale.bdd_above_iff_exists_tendsto_aux [is_finite_measure μ] (hf : submartingale f ℱ μ) (hf0 : f 0 = 0) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) : ∀ᵐ ω ∂μ, bdd_above (set.range $ λ n, f n ω) ↔ ∃ c, tendsto (λ n, f n ω) at_top (𝓝 c) := by filter_upwards [hf.exists_tendsto_of_abs_bdd_above_aux hf0 hbdd] with ω hω using ⟨hω, λ ⟨c, hc⟩, hc.bdd_above_range⟩ /-- One sided martingale bound: If `f` is a submartingale which has uniformly bounded differences, then for almost every `ω`, `f n ω` is bounded above (in `n`) if and only if it converges. -/ lemma submartingale.bdd_above_iff_exists_tendsto [is_finite_measure μ] (hf : submartingale f ℱ μ) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) : ∀ᵐ ω ∂μ, bdd_above (set.range $ λ n, f n ω) ↔ ∃ c, tendsto (λ n, f n ω) at_top (𝓝 c) := begin set g : ℕ → Ω → ℝ := λ n ω, f n ω - f 0 ω with hgdef, have hg : submartingale g ℱ μ := hf.sub_martingale (martingale_const_fun _ _ (hf.adapted 0) (hf.integrable 0)), have hg0 : g 0 = 0, { ext ω, simp only [hgdef, sub_self, pi.zero_apply] }, have hgbdd : ∀ᵐ ω ∂μ, ∀ (i : ℕ), |g (i + 1) ω - g i ω| ≤ ↑R, { simpa only [sub_sub_sub_cancel_right] }, filter_upwards [hg.bdd_above_iff_exists_tendsto_aux hg0 hgbdd] with ω hω, convert hω using 1; rw eq_iff_iff, { simp only [hgdef], refine ⟨λ h, _, λ h, _⟩; obtain ⟨b, hb⟩ := h; refine ⟨b + |f 0 ω|, λ y hy, _⟩; obtain ⟨n, rfl⟩ := hy, { simp_rw [sub_eq_add_neg], exact add_le_add (hb ⟨n, rfl⟩) (neg_le_abs_self _) }, { exact sub_le_iff_le_add.1 (le_trans (sub_le_sub_left (le_abs_self _) _) (hb ⟨n, rfl⟩)) } }, { simp only [hgdef], refine ⟨λ h, _, λ h, _⟩; obtain ⟨c, hc⟩ := h, { exact ⟨c - f 0 ω, hc.sub_const _⟩ }, { refine ⟨c + f 0 ω, _⟩, have := hc.add_const (f 0 ω), simpa only [sub_add_cancel] } } end /-! ### Lévy's generalization of the Borel-Cantelli lemma Lévy's generalization of the Borel-Cantelli lemma states that: given a natural number indexed filtration $(\mathcal{F}_n)$, and a sequence of sets $(s_n)$ such that for all $n$, $s_n \in \mathcal{F}_n$, $limsup_n s_n$ is almost everywhere equal to the set for which $\sum_n \mathbb{P}[s_n \mid \mathcal{F}_n] = \infty$. The proof strategy follows by constructing a martingale satisfying the one sided martingale bound. In particular, we define $$ f_n := \sum_{k < n} \mathbf{1}_{s_{n + 1}} - \mathbb{P}[s_{n + 1} \mid \mathcal{F}_n]. $$ Then, as a martingale is both a sub and a super-martingale, the set for which it is unbounded from above must agree with the set for which it is unbounded from below almost everywhere. Thus, it can only converge to $\pm \infty$ with probability 0. Thus, by considering $$ \limsup_n s_n = \{\sum_n \mathbf{1}_{s_n} = \infty\} $$ almost everywhere, the result follows. -/ lemma martingale.bdd_above_range_iff_bdd_below_range [is_finite_measure μ] (hf : martingale f ℱ μ) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) : ∀ᵐ ω ∂μ, bdd_above (set.range (λ n, f n ω)) ↔ bdd_below (set.range (λ n, f n ω)) := begin have hbdd' : ∀ᵐ ω ∂μ, ∀ i, |(-f) (i + 1) ω - (-f) i ω| ≤ R, { filter_upwards [hbdd] with ω hω i, erw [← abs_neg, neg_sub, sub_neg_eq_add, neg_add_eq_sub], exact hω i }, have hup := hf.submartingale.bdd_above_iff_exists_tendsto hbdd, have hdown := hf.neg.submartingale.bdd_above_iff_exists_tendsto hbdd', filter_upwards [hup, hdown] with ω hω₁ hω₂, have : (∃ c, tendsto (λ n, f n ω) at_top (𝓝 c)) ↔ ∃ c, tendsto (λ n, (-f) n ω) at_top (𝓝 c), { split; rintro ⟨c, hc⟩, { exact ⟨-c, hc.neg⟩ }, { refine ⟨-c, _⟩, convert hc.neg, simp only [neg_neg, pi.neg_apply] } }, rw [hω₁, this, ← hω₂], split; rintro ⟨c, hc⟩; refine ⟨-c, λ ω hω, _⟩, { rw mem_upper_bounds at hc, refine neg_le.2 (hc _ _), simpa only [pi.neg_apply, set.mem_range, neg_inj] }, { rw mem_lower_bounds at hc, simp_rw [set.mem_range, pi.neg_apply, neg_eq_iff_neg_eq, eq_comm] at hω, refine le_neg.1 (hc _ _), simpa only [set.mem_range] } end lemma martingale.ae_not_tendsto_at_top_at_top [is_finite_measure μ] (hf : martingale f ℱ μ) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) : ∀ᵐ ω ∂μ, ¬ tendsto (λ n, f n ω) at_top at_top := by filter_upwards [hf.bdd_above_range_iff_bdd_below_range hbdd] with ω hω htop using unbounded_of_tendsto_at_top htop (hω.2 $ bdd_below_range_of_tendsto_at_top_at_top htop) lemma martingale.ae_not_tendsto_at_top_at_bot [is_finite_measure μ] (hf : martingale f ℱ μ) (hbdd : ∀ᵐ ω ∂μ, ∀ i, |f (i + 1) ω - f i ω| ≤ R) : ∀ᵐ ω ∂μ, ¬ tendsto (λ n, f n ω) at_top at_bot := by filter_upwards [hf.bdd_above_range_iff_bdd_below_range hbdd] with ω hω htop using unbounded_of_tendsto_at_bot htop (hω.1 $ bdd_above_range_of_tendsto_at_top_at_bot htop) namespace borel_cantelli /-- Auxiliary definition required to prove Lévy's generalization of the Borel-Cantelli lemmas for which we will take the martingale part. -/ noncomputable def process (s : ℕ → set Ω) (n : ℕ) : Ω → ℝ := ∑ k in finset.range n, (s (k + 1)).indicator 1 variables {s : ℕ → set Ω} lemma process_zero : process s 0 = 0 := by rw [process, finset.range_zero, finset.sum_empty] lemma adapted_process (hs : ∀ n, measurable_set[ℱ n] (s n)) : adapted ℱ (process s) := λ n, finset.strongly_measurable_sum' _ $ λ k hk, strongly_measurable_one.indicator $ ℱ.mono (finset.mem_range.1 hk) _ $ hs _ lemma martingale_part_process_ae_eq (ℱ : filtration ℕ m0) (μ : measure Ω) (s : ℕ → set Ω) (n : ℕ) : martingale_part (process s) ℱ μ n = ∑ k in finset.range n, ((s (k + 1)).indicator 1 - μ[(s (k + 1)).indicator 1 | ℱ k]) := begin simp only [martingale_part_eq_sum, process_zero, zero_add], refine finset.sum_congr rfl (λ k hk, _), simp only [process, finset.sum_range_succ_sub_sum], end lemma predictable_part_process_ae_eq (ℱ : filtration ℕ m0) (μ : measure Ω) (s : ℕ → set Ω) (n : ℕ) : predictable_part (process s) ℱ μ n = ∑ k in finset.range n, μ[(s (k + 1)).indicator (1 : Ω → ℝ) | ℱ k] := begin have := martingale_part_process_ae_eq ℱ μ s n, simp_rw [martingale_part, process, finset.sum_sub_distrib] at this, exact sub_right_injective this, end lemma process_difference_le (s : ℕ → set Ω) (ω : Ω) (n : ℕ) : |process s (n + 1) ω - process s n ω| ≤ (1 : ℝ≥0) := begin rw [nonneg.coe_one, process, process, finset.sum_apply, finset.sum_apply, finset.sum_range_succ_sub_sum, ← real.norm_eq_abs, norm_indicator_eq_indicator_norm], refine set.indicator_le' (λ _ _, _) (λ _ _, zero_le_one) _, rw [pi.one_apply, norm_one] end lemma integrable_process (μ : measure Ω) [is_finite_measure μ] (hs : ∀ n, measurable_set[ℱ n] (s n)) (n : ℕ) : integrable (process s n) μ := integrable_finset_sum' _ $ λ k hk, integrable_on.integrable_indicator (integrable_const 1) $ ℱ.le _ _ $ hs _ end borel_cantelli open borel_cantelli /-- An a.e. monotone adapted process `f` with uniformly bounded differences converges to `+∞` if and only if its predictable part also converges to `+∞`. -/ lemma tendsto_sum_indicator_at_top_iff [is_finite_measure μ] (hfmono : ∀ᵐ ω ∂μ, ∀ n, f n ω ≤ f (n + 1) ω) (hf : adapted ℱ f) (hint : ∀ n, integrable (f n) μ) (hbdd : ∀ᵐ ω ∂μ, ∀ n, |f (n + 1) ω - f n ω| ≤ R) : ∀ᵐ ω ∂μ, tendsto (λ n, f n ω) at_top at_top ↔ tendsto (λ n, predictable_part f ℱ μ n ω) at_top at_top := begin have h₁ := (martingale_martingale_part hf hint).ae_not_tendsto_at_top_at_top (martingale_part_bdd_difference ℱ hbdd), have h₂ := (martingale_martingale_part hf hint).ae_not_tendsto_at_top_at_bot (martingale_part_bdd_difference ℱ hbdd), have h₃ : ∀ᵐ ω ∂μ, ∀ n, 0 ≤ μ[f (n + 1) - f n | ℱ n] ω, { refine ae_all_iff.2 (λ n, condexp_nonneg _), filter_upwards [ae_all_iff.1 hfmono n] with ω hω using sub_nonneg.2 hω }, filter_upwards [h₁, h₂, h₃, hfmono] with ω hω₁ hω₂ hω₃ hω₄, split; intro ht, { refine tendsto_at_top_at_top_of_monotone' _ _, { intros n m hnm, simp only [predictable_part, finset.sum_apply], refine finset.sum_mono_set_of_nonneg hω₃ (finset.range_mono hnm) }, rintro ⟨b, hbdd⟩, rw ← tendsto_neg_at_bot_iff at ht, simp only [martingale_part, sub_eq_add_neg] at hω₁, exact hω₁ (tendsto_at_top_add_right_of_le _ (-b) (tendsto_neg_at_bot_iff.1 ht) $ λ n, neg_le_neg (hbdd ⟨n, rfl⟩)) }, { refine tendsto_at_top_at_top_of_monotone' (monotone_nat_of_le_succ hω₄) _, rintro ⟨b, hbdd⟩, exact hω₂ (tendsto_at_bot_add_left_of_ge _ b (λ n, hbdd ⟨n, rfl⟩) $ tendsto_neg_at_bot_iff.2 ht) }, end open borel_cantelli lemma tendsto_sum_indicator_at_top_iff' [is_finite_measure μ] {s : ℕ → set Ω} (hs : ∀ n, measurable_set[ℱ n] (s n)) : ∀ᵐ ω ∂μ, tendsto (λ n, ∑ k in finset.range n, (s (k + 1)).indicator (1 : Ω → ℝ) ω) at_top at_top ↔ tendsto (λ n, ∑ k in finset.range n, μ[(s (k + 1)).indicator (1 : Ω → ℝ) | ℱ k] ω) at_top at_top := begin have := tendsto_sum_indicator_at_top_iff (eventually_of_forall $ λ ω n, _) (adapted_process hs) (integrable_process μ hs) (eventually_of_forall $ process_difference_le s), swap, { rw [process, process, ← sub_nonneg, finset.sum_apply, finset.sum_apply, finset.sum_range_succ_sub_sum], exact set.indicator_nonneg (λ _ _, zero_le_one) _ }, simp_rw [process, predictable_part_process_ae_eq] at this, simpa using this, end /-- **Lévy's generalization of the Borel-Cantelli lemma**: given a sequence of sets `s` and a filtration `ℱ` such that for all `n`, `s n` is `ℱ n`-measurable, `at_top.limsup s` is almost everywhere equal to the set for which `∑ k, ℙ(s (k + 1) | ℱ k) = ∞`. -/ theorem ae_mem_limsup_at_top_iff (μ : measure Ω) [is_finite_measure μ] {s : ℕ → set Ω} (hs : ∀ n, measurable_set[ℱ n] (s n)) : ∀ᵐ ω ∂μ, ω ∈ limsup s at_top ↔ tendsto (λ n, ∑ k in finset.range n, μ[(s (k + 1)).indicator (1 : Ω → ℝ) | ℱ k] ω) at_top at_top := (limsup_eq_tendsto_sum_indicator_at_top ℝ s).symm ▸ tendsto_sum_indicator_at_top_iff' hs end measure_theory
cf3b7fdffb8e97eacd708b5bca25b071588d565d
0d7f5899c0475f9e105a439896d9377f80c0d7c3
/src/fron_ralg.lean
7535508188f59d80ee06672022b373433acf9910
[]
no_license
adamtopaz/UnivAlg
127038f320e68cdf3efcd0c084c9af02fdb8da3d
2458d47a6e4fd0525e3a25b07cb7dd518ac173ef
refs/heads/master
1,670,320,985,286
1,597,350,882,000
1,597,350,882,000
280,585,500
4
0
null
1,597,350,883,000
1,595,048,527,000
Lean
UTF-8
Lean
false
false
3,612
lean
import .lang import .forget import .free_ralg import .ualg namespace lang_hom variables {L0 : lang} {L1 : lang} (ι : L0 →# L1) variables (A : Type*) [has_app L0 A] -- goal is to construct the free has_app L1 -- compatible with the has_app L0 namespace fron -- ι.fron A open lang include ι inductive rel : (L1.free A) → (L1.free A) → Prop | of {n} (as : ftuple A n) (t : L0 n) : rel (applyo (ι t) (as.map (free.univ L1 A))) (free.univ L1 A (applyo t as)) | refl (a) : rel a a | symm (a b) : rel a b → rel b a | trans (a b c) : rel a b → rel b c → rel a c | compat {n} {t : L1 n} {as bs : ftuple (L1.free A) n} : (∀ i, rel (as i) (bs i)) → rel (applyo t as) (applyo t bs) def setoid : setoid (L1.free A) := ⟨rel ι A, rel.refl, rel.symm, rel.trans⟩ end fron def fron := quotient (fron.setoid ι A) namespace fron instance : has_app L1 (ι.fron A) := { app := λ n t, by letI := fron.setoid ι A; exact ftuple.quotient_lift (λ as, ⟦applyo t as⟧) (λ as bs hyp, quotient.sound $ rel.compat hyp) } instance : compat ι (ι.fron A) := ι.forget_along (ι.fron A) def quot : L1.free A →$[L1] (ι.fron A) := { to_fn := by letI := fron.setoid ι A; exact λ a, ⟦a⟧, applyo_map' := begin intros n t as, dsimp only [], letI := fron.setoid ι A, change ftuple.quotient_lift _ _ _ = _, rw ftuple.quotient_lift_beta, end } def univ : A →$[L0] (ι.fron A) := { to_fn := by letI := fron.setoid ι A; exact λ a, ⟦lang.free.univ L1 A a⟧, applyo_map' := begin intros n t as, letI := fron.setoid ι A, dsimp only [], change applyo t ((as.map (lang.free.univ L1 A)).map (quot ι A)) = _, simp_rw compat.compat, rw ralg_hom.applyo_map, apply quotient.sound, apply rel.of, end } variable {A} def lift {B : Type*} [has_app L1 B] [compat ι B] (f : A →$[L0] B) : ι.fron A →$[L1] B := { to_fn := by letI := fron.setoid ι A; exact quotient.lift (lang.free.lift L1 f) begin intros a b h, induction h, { change _ = f _, rw ←ralg_hom.applyo_map, rw [←ftuple.map_map,lang.free.univ_comp_lift], rw ←ralg_hom.applyo_map, rw compat.compat }, repeat {cc}, { dsimp only [] at h_ih, simp_rw ←ralg_hom.applyo_map, apply congr_arg, ext, apply h_ih}, end, applyo_map' := begin intros n t as, letI := fron.setoid ι A, dsimp only [], change _ = quotient.lift _ _ _, rcases ftuple.exists_rep as quotient.exists_rep with ⟨as,rfl⟩, change _ = quotient.lift _ _ (applyo _ (as.map (quot ι A))), simp_rw ralg_hom.applyo_map, erw quotient.lift_beta, simp_rw ←ralg_hom.applyo_map, apply congr_arg, ext, simp only [ftuple.map_eval,quotient.lift_beta], end } theorem univ_comp_lift {B : Type*} [has_app L1 B] [compat ι B] (f : A →$[L0] B) : (univ ι A).comp ((lift ι f).drop ι) = f := by {ext, refl} open lang theorem lift_unique {B : Type*} [has_app L1 B] [compat ι B] (f : A →$[L0] B) (g : ι.fron A →$[L1] B) : (univ ι A).comp (g.drop ι) = f → g = lift ι f := begin intro hyp, ext, letI := fron.setoid ι A, have : ∃ y : L1.free A, (quot ι A) y = x, by apply quotient.exists_rep, rcases this with ⟨y,rfl⟩, change _ = free.lift _ _ y, induction y with _ n t as ind, { change _ = f y, rw ←hyp, refl }, { change _ = (free.lift L1 f) (applyo t as), change g ( (quot ι A) (applyo t as)) = _, simp_rw ←ralg_hom.applyo_map, apply congr_arg, ext, apply ind } end end fron end lang_hom
4d8c7d9354651b5e903726d60631e40ef6f1b580
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/src/Lean/Meta/GeneralizeTelescope.lean
edb1e6f39a5e2b8056f9f07f47349bbb9a944390
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,864
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.KAbstract namespace Lean.Meta namespace GeneralizeTelescope structure Entry where expr : Expr type : Expr modified : Bool partial def updateTypes (e eNew : Expr) (entries : Array Entry) (i : Nat) : MetaM (Array Entry) := if h : i < entries.size then let entry := entries.get ⟨i, h⟩ match entry with | ⟨_, type, _⟩ => do let typeAbst ← kabstract type e if typeAbst.hasLooseBVars then do let typeNew := typeAbst.instantiate1 eNew let entries := entries.set ⟨i, h⟩ { entry with type := typeNew, modified := true } updateTypes e eNew entries (i+1) else updateTypes e eNew entries (i+1) else pure entries partial def generalizeTelescopeAux {α} (k : Array Expr → MetaM α) (entries : Array Entry) (i : Nat) (fvars : Array Expr) : MetaM α := do if h : i < entries.size then let replace (baseUserName : Name) (e : Expr) (type : Expr) : MetaM α := do let userName ← mkFreshUserName baseUserName withLocalDeclD userName type fun x => do let entries ← updateTypes e x entries (i+1) generalizeTelescopeAux k entries (i+1) (fvars.push x) match entries.get ⟨i, h⟩ with | ⟨e@(Expr.fvar fvarId _), type, false⟩ => let localDecl ← getLocalDecl fvarId match localDecl with | LocalDecl.cdecl .. => generalizeTelescopeAux k entries (i+1) (fvars.push e) | LocalDecl.ldecl .. => replace localDecl.userName e type | ⟨e, type, modified⟩ => if modified then unless (← isTypeCorrect type) do throwError! "failed to create telescope generalizing {entries.map Entry.expr}" replace `x e type else k fvars end GeneralizeTelescope open GeneralizeTelescope /-- Given expressions `es := #[e_1, e_2, ..., e_n]`, execute `k` with the free variables `(x_1 : A_1) (x_2 : A_2 [x_1]) ... (x_n : A_n [x_1, ... x_{n-1}])`. Moreover, - type of `e_1` is definitionally equal to `A_1`, - type of `e_2` is definitionally equal to `A_2[e_1]`. - ... - type of `e_n` is definitionally equal to `A_n[e_1, ..., e_{n-1}]`. This method tries to avoid the creation of new free variables. For example, if `e_i` is a free variable `x_i` and it is not a let-declaration variable, and its type does not depend on previous `e_j`s, the method will just use `x_i`. The telescope `x_1 ... x_n` can be used to create lambda and forall abstractions. Moreover, for any type correct lambda abstraction `f` constructed using `mkForall #[x_1, ..., x_n] ...`, The application `f e_1 ... e_n` is also type correct. The `kabstract` method is used to "locate" and abstract forward dependencies. That is, an occurrence of `e_i` in the of `e_j` for `j > i`. The method checks whether the abstract types `A_i` are type correct. Here is an example where `generalizeTelescope` fails to create the telescope `x_1 ... x_n`. Assume the local context contains `(n : Nat := 10) (xs : Vec Nat n) (ys : Vec Nat 10) (h : xs = ys)`. Then, assume we invoke `generalizeTelescope` with `es := #[10, xs, ys, h]` A type error is detected when processing `h`'s type. At this point, the method had successfully produced ``` (x_1 : Nat) (xs : Vec Nat n) (x_2 : Vec Nat x_1) ``` and the type for the new variable abstracting `h` is `xs = x_2` which is not type correct. -/ def generalizeTelescope {α} (es : Array Expr) (k : Array Expr → MetaM α) : MetaM α := do let es ← es.mapM fun e => do let type ← inferType e let type ← instantiateMVars type pure { expr := e, type := type, modified := false : Entry } generalizeTelescopeAux k es 0 #[] end Lean.Meta
e7dd518b1df7f948ec92ea33730e80cca16fc994
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/big_operators/option.lean
560824c0e2b79bf9437db10955edac6e9f4a78e5
[ "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
1,246
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 algebra.big_operators.basic import data.finset.option /-! # Lemmas about products and sums over finite sets in `option α` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove formulas for products and sums over `finset.insert_none s` and `finset.erase_none s`. -/ open_locale big_operators open function namespace finset variables {α M : Type*} [comm_monoid M] @[simp, to_additive] lemma prod_insert_none (f : option α → M) (s : finset α) : ∏ x in s.insert_none, f x = f none * ∏ x in s, f (some x) := by simp [insert_none] @[to_additive] lemma prod_erase_none (f : α → M) (s : finset (option α)) : ∏ x in s.erase_none, f x = ∏ x in s, option.elim 1 f x := by classical; calc ∏ x in s.erase_none, f x = ∏ x in s.erase_none.map embedding.some, option.elim 1 f x : (prod_map s.erase_none embedding.some $ option.elim 1 f).symm ... = ∏ x in s.erase none, option.elim 1 f x : by rw map_some_erase_none ... = ∏ x in s, option.elim 1 f x : prod_erase _ rfl end finset
7ea7b8531bc9974030ad7aed5757e0822e9225d5
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/analysis/calculus/iterated_deriv.lean
2622251ee83085087bcc059c51431cc4dc54e62a
[ "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
14,716
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.calculus.deriv import analysis.calculus.times_cont_diff /-! # One-dimensional iterated derivatives We define the `n`-th derivative of a function `f : 𝕜 → F` as a function `iterated_deriv n f : 𝕜 → F`, as well as a version on domains `iterated_deriv_within n f s : 𝕜 → F`, and prove their basic properties. ## Main definitions and results Let `𝕜` be a nondiscrete normed field, and `F` a normed vector space over `𝕜`. Let `f : 𝕜 → F`. * `iterated_deriv n f` is the `n`-th derivative of `f`, seen as a function from `𝕜` to `F`. It is defined as the `n`-th Fréchet derivative (which is a multilinear map) applied to the vector `(1, ..., 1)`, to take advantage of all the existing framework, but we show that it coincides with the naive iterative definition. * `iterated_deriv_eq_iterate` states that the `n`-th derivative of `f` is obtained by starting from `f` and differentiating it `n` times. * `iterated_deriv_within n f s` is the `n`-th derivative of `f` within the domain `s`. It only behaves well when `s` has the unique derivative property. * `iterated_deriv_within_eq_iterate` states that the `n`-th derivative of `f` in the domain `s` is obtained by starting from `f` and differentiating it `n` times within `s`. This only holds when `s` has the unique derivative property. ## Implementation details The results are deduced from the corresponding results for the more general (multilinear) iterated Fréchet derivative. For this, we write `iterated_deriv n f` as the composition of `iterated_fderiv 𝕜 n f` and a continuous linear equiv. As continuous linear equivs respect differentiability and commute with differentiation, this makes it possible to prove readily that the derivative of the `n`-th derivative is the `n+1`-th derivative in `iterated_deriv_within_succ`, by translating the corresponding result `iterated_fderiv_within_succ_apply_left` for the iterated Fréchet derivative. -/ noncomputable theory open_locale classical topological_space big_operators open filter asymptotics set variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] /-- The `n`-th iterated derivative of a function from `𝕜` to `F`, as a function from `𝕜` to `F`. -/ def iterated_deriv (n : ℕ) (f : 𝕜 → F) (x : 𝕜) : F := (iterated_fderiv 𝕜 n f x : ((fin n) → 𝕜) → F) (λ(i : fin n), 1) /-- The `n`-th iterated derivative of a function from `𝕜` to `F` within a set `s`, as a function from `𝕜` to `F`. -/ def iterated_deriv_within (n : ℕ) (f : 𝕜 → F) (s : set 𝕜) (x : 𝕜) : F := (iterated_fderiv_within 𝕜 n f s x : ((fin n) → 𝕜) → F) (λ(i : fin n), 1) variables {n : ℕ} {f : 𝕜 → F} {s : set 𝕜} {x : 𝕜} lemma iterated_deriv_within_univ : iterated_deriv_within n f univ = iterated_deriv n f := by { ext x, rw [iterated_deriv_within, iterated_deriv, iterated_fderiv_within_univ] } /-! ### Properties of the iterated derivative within a set -/ lemma iterated_deriv_within_eq_iterated_fderiv_within : iterated_deriv_within n f s x = (iterated_fderiv_within 𝕜 n f s x : ((fin n) → 𝕜) → F) (λ(i : fin n), 1) := rfl /-- Write the iterated derivative as the composition of a continuous linear equiv and the iterated Fréchet derivative -/ lemma iterated_deriv_within_eq_equiv_comp : iterated_deriv_within n f s = (continuous_multilinear_map.pi_field_equiv 𝕜 (fin n) F).symm ∘ (iterated_fderiv_within 𝕜 n f s) := by { ext x, refl } /-- Write the iterated Fréchet derivative as the composition of a continuous linear equiv and the iterated derivative. -/ lemma iterated_fderiv_within_eq_equiv_comp : iterated_fderiv_within 𝕜 n f s = (continuous_multilinear_map.pi_field_equiv 𝕜 (fin n) F) ∘ (iterated_deriv_within n f s) := begin rw [iterated_deriv_within_eq_equiv_comp, ← function.comp.assoc, continuous_linear_equiv.self_comp_symm], refl end /-- The `n`-th Fréchet derivative applied to a vector `(m 0, ..., m (n-1))` is the derivative multiplied by the product of the `m i`s. -/ lemma iterated_fderiv_within_apply_eq_iterated_deriv_within_mul_prod {m : (fin n) → 𝕜} : (iterated_fderiv_within 𝕜 n f s x : ((fin n) → 𝕜) → F) m = (∏ i, m i) • iterated_deriv_within n f s x := begin rw [iterated_deriv_within_eq_iterated_fderiv_within, ← continuous_multilinear_map.map_smul_univ], simp end @[simp] lemma iterated_deriv_within_zero : iterated_deriv_within 0 f s = f := by { ext x, simp [iterated_deriv_within] } @[simp] lemma iterated_deriv_within_one (hs : unique_diff_on 𝕜 s) {x : 𝕜} (hx : x ∈ s): iterated_deriv_within 1 f s x = deriv_within f s x := by { simp [iterated_deriv_within, iterated_fderiv_within_one_apply hs hx], refl } /-- If the first `n` derivatives within a set of a function are continuous, and its first `n-1` derivatives are differentiable, then the function is `C^n`. This is not an equivalence in general, but this is an equivalence when the set has unique derivatives, see `times_cont_diff_on_iff_continuous_on_differentiable_on_deriv`. -/ lemma times_cont_diff_on_of_continuous_on_differentiable_on_deriv {n : with_top ℕ} (Hcont : ∀ (m : ℕ), (m : with_top ℕ) ≤ n → continuous_on (λ x, iterated_deriv_within m f s x) s) (Hdiff : ∀ (m : ℕ), (m : with_top ℕ) < n → differentiable_on 𝕜 (λ x, iterated_deriv_within m f s x) s) : times_cont_diff_on 𝕜 n f s := begin apply times_cont_diff_on_of_continuous_on_differentiable_on, { simpa [iterated_fderiv_within_eq_equiv_comp, continuous_linear_equiv.comp_continuous_on_iff] }, { simpa [iterated_fderiv_within_eq_equiv_comp, continuous_linear_equiv.comp_differentiable_on_iff] } end /-- To check that a function is `n` times continuously differentiable, it suffices to check that its first `n` derivatives are differentiable. This is slightly too strong as the condition we require on the `n`-th derivative is differentiability instead of continuity, but it has the advantage of avoiding the discussion of continuity in the proof (and for `n = ∞` this is optimal). -/ lemma times_cont_diff_on_of_differentiable_on_deriv {n : with_top ℕ} (h : ∀(m : ℕ), (m : with_top ℕ) ≤ n → differentiable_on 𝕜 (iterated_deriv_within m f s) s) : times_cont_diff_on 𝕜 n f s := begin apply times_cont_diff_on_of_differentiable_on, simpa [iterated_fderiv_within_eq_equiv_comp, continuous_linear_equiv.comp_differentiable_on_iff, -coe_fn_coe_base], end /-- On a set with unique derivatives, a `C^n` function has derivatives up to `n` which are continuous. -/ lemma times_cont_diff_on.continuous_on_iterated_deriv_within {n : with_top ℕ} {m : ℕ} (h : times_cont_diff_on 𝕜 n f s) (hmn : (m : with_top ℕ) ≤ n) (hs : unique_diff_on 𝕜 s) : continuous_on (iterated_deriv_within m f s) s := begin simp [iterated_deriv_within_eq_equiv_comp, continuous_linear_equiv.comp_continuous_on_iff, -coe_fn_coe_base], exact h.continuous_on_iterated_fderiv_within hmn hs end /-- On a set with unique derivatives, a `C^n` function has derivatives less than `n` which are differentiable. -/ lemma times_cont_diff_on.differentiable_on_iterated_deriv_within {n : with_top ℕ} {m : ℕ} (h : times_cont_diff_on 𝕜 n f s) (hmn : (m : with_top ℕ) < n) (hs : unique_diff_on 𝕜 s) : differentiable_on 𝕜 (iterated_deriv_within m f s) s := begin simp [iterated_deriv_within_eq_equiv_comp, continuous_linear_equiv.comp_differentiable_on_iff, -coe_fn_coe_base], exact h.differentiable_on_iterated_fderiv_within hmn hs end /-- The property of being `C^n`, initially defined in terms of the Fréchet derivative, can be reformulated in terms of the one-dimensional derivative on sets with unique derivatives. -/ lemma times_cont_diff_on_iff_continuous_on_differentiable_on_deriv {n : with_top ℕ} (hs : unique_diff_on 𝕜 s) : times_cont_diff_on 𝕜 n f s ↔ (∀m:ℕ, (m : with_top ℕ) ≤ n → continuous_on (iterated_deriv_within m f s) s) ∧ (∀m:ℕ, (m : with_top ℕ) < n → differentiable_on 𝕜 (iterated_deriv_within m f s) s) := by simp only [times_cont_diff_on_iff_continuous_on_differentiable_on hs, iterated_fderiv_within_eq_equiv_comp, continuous_linear_equiv.comp_continuous_on_iff, continuous_linear_equiv.comp_differentiable_on_iff] /-- The `n+1`-th iterated derivative within a set with unique derivatives can be obtained by differentiating the `n`-th iterated derivative. -/ lemma iterated_deriv_within_succ {x : 𝕜} (hxs : unique_diff_within_at 𝕜 s x) : iterated_deriv_within (n + 1) f s x = deriv_within (iterated_deriv_within n f s) s x := begin rw [iterated_deriv_within_eq_iterated_fderiv_within, iterated_fderiv_within_succ_apply_left, iterated_fderiv_within_eq_equiv_comp, continuous_linear_equiv.comp_fderiv_within _ hxs, deriv_within], change ((continuous_multilinear_map.mk_pi_field 𝕜 (fin n) ((fderiv_within 𝕜 (iterated_deriv_within n f s) s x : 𝕜 → F) 1)) : (fin n → 𝕜 ) → F) (λ (i : fin n), 1) = (fderiv_within 𝕜 (iterated_deriv_within n f s) s x : 𝕜 → F) 1, simp end /-- The `n`-th iterated derivative within a set with unique derivatives can be obtained by iterating `n` times the differentiation operation. -/ lemma iterated_deriv_within_eq_iterate {x : 𝕜} (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) : iterated_deriv_within n f s x = ((λ (g : 𝕜 → F), deriv_within g s)^[n]) f x := begin induction n with n IH generalizing x, { simp }, { rw [iterated_deriv_within_succ (hs x hx), function.iterate_succ'], exact deriv_within_congr (hs x hx) (λ y hy, IH hy) (IH hx) } end /-- The `n+1`-th iterated derivative within a set with unique derivatives can be obtained by taking the `n`-th derivative of the derivative. -/ lemma iterated_deriv_within_succ' {x : 𝕜} (hxs : unique_diff_on 𝕜 s) (hx : x ∈ s) : iterated_deriv_within (n + 1) f s x = (iterated_deriv_within n (deriv_within f s) s) x := by { rw [iterated_deriv_within_eq_iterate hxs hx, iterated_deriv_within_eq_iterate hxs hx], refl } /-! ### Properties of the iterated derivative on the whole space -/ lemma iterated_deriv_eq_iterated_fderiv : iterated_deriv n f x = (iterated_fderiv 𝕜 n f x : ((fin n) → 𝕜) → F) (λ(i : fin n), 1) := rfl /-- Write the iterated derivative as the composition of a continuous linear equiv and the iterated Fréchet derivative -/ lemma iterated_deriv_eq_equiv_comp : iterated_deriv n f = (continuous_multilinear_map.pi_field_equiv 𝕜 (fin n) F).symm ∘ (iterated_fderiv 𝕜 n f) := by { ext x, refl } /-- Write the iterated Fréchet derivative as the composition of a continuous linear equiv and the iterated derivative. -/ lemma iterated_fderiv_eq_equiv_comp : iterated_fderiv 𝕜 n f = (continuous_multilinear_map.pi_field_equiv 𝕜 (fin n) F) ∘ (iterated_deriv n f) := begin rw [iterated_deriv_eq_equiv_comp, ← function.comp.assoc, continuous_linear_equiv.self_comp_symm], refl end /-- The `n`-th Fréchet derivative applied to a vector `(m 0, ..., m (n-1))` is the derivative multiplied by the product of the `m i`s. -/ lemma iterated_fderiv_apply_eq_iterated_deriv_mul_prod {m : (fin n) → 𝕜} : (iterated_fderiv 𝕜 n f x : ((fin n) → 𝕜) → F) m = (∏ i, m i) • iterated_deriv n f x := by { rw [iterated_deriv_eq_iterated_fderiv, ← continuous_multilinear_map.map_smul_univ], simp } @[simp] lemma iterated_deriv_zero : iterated_deriv 0 f = f := by { ext x, simp [iterated_deriv] } @[simp] lemma iterated_deriv_one : iterated_deriv 1 f = deriv f := by { ext x, simp [iterated_deriv], refl } /-- The property of being `C^n`, initially defined in terms of the Fréchet derivative, can be reformulated in terms of the one-dimensional derivative. -/ lemma times_cont_diff_iff_iterated_deriv {n : with_top ℕ} : times_cont_diff 𝕜 n f ↔ (∀m:ℕ, (m : with_top ℕ) ≤ n → continuous (iterated_deriv m f)) ∧ (∀m:ℕ, (m : with_top ℕ) < n → differentiable 𝕜 (iterated_deriv m f)) := by simp only [times_cont_diff_iff_continuous_differentiable, iterated_fderiv_eq_equiv_comp, continuous_linear_equiv.comp_continuous_iff, continuous_linear_equiv.comp_differentiable_iff] /-- To check that a function is `n` times continuously differentiable, it suffices to check that its first `n` derivatives are differentiable. This is slightly too strong as the condition we require on the `n`-th derivative is differentiability instead of continuity, but it has the advantage of avoiding the discussion of continuity in the proof (and for `n = ∞` this is optimal). -/ lemma times_cont_diff_of_differentiable_iterated_deriv {n : with_top ℕ} (h : ∀(m : ℕ), (m : with_top ℕ) ≤ n → differentiable 𝕜 (iterated_deriv m f)) : times_cont_diff 𝕜 n f := times_cont_diff_iff_iterated_deriv.2 ⟨λ m hm, (h m hm).continuous, λ m hm, (h m (le_of_lt hm))⟩ lemma times_cont_diff.continuous_iterated_deriv {n : with_top ℕ} (m : ℕ) (h : times_cont_diff 𝕜 n f) (hmn : (m : with_top ℕ) ≤ n) : continuous (iterated_deriv m f) := (times_cont_diff_iff_iterated_deriv.1 h).1 m hmn lemma times_cont_diff.differentiable_iterated_deriv {n : with_top ℕ} (m : ℕ) (h : times_cont_diff 𝕜 n f) (hmn : (m : with_top ℕ) < n) : differentiable 𝕜 (iterated_deriv m f) := (times_cont_diff_iff_iterated_deriv.1 h).2 m hmn /-- The `n+1`-th iterated derivative can be obtained by differentiating the `n`-th iterated derivative. -/ lemma iterated_deriv_succ : iterated_deriv (n + 1) f = deriv (iterated_deriv n f) := begin ext x, rw [← iterated_deriv_within_univ, ← iterated_deriv_within_univ, ← deriv_within_univ], exact iterated_deriv_within_succ unique_diff_within_at_univ, end /-- The `n`-th iterated derivative can be obtained by iterating `n` times the differentiation operation. -/ lemma iterated_deriv_eq_iterate : iterated_deriv n f = (deriv^[n]) f := begin ext x, rw [← iterated_deriv_within_univ], convert iterated_deriv_within_eq_iterate unique_diff_on_univ (mem_univ x), simp [deriv_within_univ] end /-- The `n+1`-th iterated derivative can be obtained by taking the `n`-th derivative of the derivative. -/ lemma iterated_deriv_succ' : iterated_deriv (n + 1) f = iterated_deriv n (deriv f) := by { rw [iterated_deriv_eq_iterate, iterated_deriv_eq_iterate], refl }
b662e9d7d44276f835e33dd23156193778db4fc5
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/data/pnat/basic.lean
5d961fcfef54e47ca80d0aa38b30ff94b13c3898
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
18,795
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro, Neil Strickland -/ import data.nat.prime /-- `ℕ+` is the type of positive natural numbers. It is defined as a subtype, and the VM representation of `ℕ+` is the same as `ℕ` because the proof is not stored. -/ def pnat := {n : ℕ // 0 < n} notation `ℕ+` := pnat instance coe_pnat_nat : has_coe ℕ+ ℕ := ⟨subtype.val⟩ instance : has_repr ℕ+ := ⟨λ n, repr n.1⟩ /-- Predecessor of a `ℕ+`, as a `ℕ`. -/ def pnat.nat_pred (i : ℕ+) : ℕ := i - 1 namespace nat /-- Convert a natural number to a positive natural number. The positivity assumption is inferred by `dec_trivial`. -/ def to_pnat (n : ℕ) (h : 0 < n . tactic.exact_dec_trivial) : ℕ+ := ⟨n, h⟩ /-- Write a successor as an element of `ℕ+`. -/ def succ_pnat (n : ℕ) : ℕ+ := ⟨succ n, succ_pos n⟩ @[simp] theorem succ_pnat_coe (n : ℕ) : (succ_pnat n : ℕ) = succ n := rfl theorem succ_pnat_inj {n m : ℕ} : succ_pnat n = succ_pnat m → n = m := λ h, by { let h' := congr_arg (coe : ℕ+ → ℕ) h, exact nat.succ.inj h' } /-- Convert a natural number to a pnat. `n+1` is mapped to itself, and `0` becomes `1`. -/ def to_pnat' (n : ℕ) : ℕ+ := succ_pnat (pred n) @[simp] theorem to_pnat'_coe : ∀ (n : ℕ), ((to_pnat' n) : ℕ) = ite (0 < n) n 1 | 0 := rfl | (m + 1) := by {rw [if_pos (succ_pos m)], refl} namespace primes instance coe_pnat : has_coe nat.primes ℕ+ := ⟨λ p, ⟨(p : ℕ), p.property.pos⟩⟩ theorem coe_pnat_nat (p : nat.primes) : ((p : ℕ+) : ℕ) = p := rfl theorem coe_pnat_inj (p q : nat.primes) : (p : ℕ+) = (q : ℕ+) → p = q := λ h, begin replace h : ((p : ℕ+) : ℕ) = ((q : ℕ+) : ℕ) := congr_arg subtype.val h, rw [coe_pnat_nat, coe_pnat_nat] at h, exact subtype.eq h, end end primes end nat namespace pnat open nat /-- We now define a long list of structures on ℕ+ induced by similar structures on ℕ. Most of these behave in a completely obvious way, but there are a few things to be said about subtraction, division and powers. -/ instance : decidable_eq ℕ+ := λ (a b : ℕ+), by apply_instance instance : decidable_linear_order ℕ+ := subtype.decidable_linear_order _ @[simp] lemma mk_le_mk (n k : ℕ) (hn : 0 < n) (hk : 0 < k) : (⟨n, hn⟩ : ℕ+) ≤ ⟨k, hk⟩ ↔ n ≤ k := iff.rfl @[simp] lemma mk_lt_mk (n k : ℕ) (hn : 0 < n) (hk : 0 < k) : (⟨n, hn⟩ : ℕ+) < ⟨k, hk⟩ ↔ n < k := iff.rfl @[simp, norm_cast] lemma coe_le_coe (n k : ℕ+) : (n:ℕ) ≤ k ↔ n ≤ k := iff.rfl @[simp, norm_cast] lemma coe_lt_coe (n k : ℕ+) : (n:ℕ) < k ↔ n < k := iff.rfl @[simp] theorem pos (n : ℕ+) : 0 < (n : ℕ) := n.2 theorem eq {m n : ℕ+} : (m : ℕ) = n → m = n := subtype.eq @[simp] lemma coe_inj {m n : ℕ+} : (m : ℕ) = n ↔ m = n := set_coe.ext_iff @[simp] theorem mk_coe (n h) : ((⟨n, h⟩ : ℕ+) : ℕ) = n := rfl instance : add_comm_semigroup ℕ+ := { add := λ a b, ⟨(a + b : ℕ), add_pos a.pos b.pos⟩, add_comm := λ a b, subtype.eq (add_comm a b), add_assoc := λ a b c, subtype.eq (add_assoc a b c) } @[simp] theorem add_coe (m n : ℕ+) : ((m + n : ℕ+) : ℕ) = m + n := rfl instance coe_add_hom : is_add_hom (coe : ℕ+ → ℕ) := ⟨add_coe⟩ instance : add_left_cancel_semigroup ℕ+ := { add_left_cancel := λ a b c h, by { replace h := congr_arg (coe : ℕ+ → ℕ) h, rw [add_coe, add_coe] at h, exact eq ((add_right_inj (a : ℕ)).mp h)}, .. (pnat.add_comm_semigroup) } instance : add_right_cancel_semigroup ℕ+ := { add_right_cancel := λ a b c h, by { replace h := congr_arg (coe : ℕ+ → ℕ) h, rw [add_coe, add_coe] at h, exact eq ((add_left_inj (b : ℕ)).mp h)}, .. (pnat.add_comm_semigroup) } @[simp] theorem ne_zero (n : ℕ+) : (n : ℕ) ≠ 0 := ne_of_gt n.2 theorem to_pnat'_coe {n : ℕ} : 0 < n → (n.to_pnat' : ℕ) = n := succ_pred_eq_of_pos @[simp] theorem coe_to_pnat' (n : ℕ+) : (n : ℕ).to_pnat' = n := eq (to_pnat'_coe n.pos) instance : comm_monoid ℕ+ := { mul := λ m n, ⟨m.1 * n.1, mul_pos m.2 n.2⟩, mul_assoc := λ a b c, subtype.eq (mul_assoc _ _ _), one := succ_pnat 0, one_mul := λ a, subtype.eq (one_mul _), mul_one := λ a, subtype.eq (mul_one _), mul_comm := λ a b, subtype.eq (mul_comm _ _) } theorem lt_add_one_iff : ∀ {a b : ℕ+}, a < b + 1 ↔ a ≤ b := λ a b, nat.lt_add_one_iff theorem add_one_le_iff : ∀ {a b : ℕ+}, a + 1 ≤ b ↔ a < b := λ a b, nat.add_one_le_iff @[simp] lemma one_le (n : ℕ+) : (1 : ℕ+) ≤ n := n.2 instance : order_bot ℕ+ := { bot := 1, bot_le := λ a, a.property, ..(by apply_instance : partial_order ℕ+) } @[simp] lemma bot_eq_zero : (⊥ : ℕ+) = 1 := rfl instance : inhabited ℕ+ := ⟨1⟩ -- Some lemmas that rewrite `pnat.mk n h`, for `n` an explicit numeral, into explicit numerals. @[simp] lemma mk_one {h} : (⟨1, h⟩ : ℕ+) = (1 : ℕ+) := rfl @[simp] lemma mk_bit0 (n) {h} : (⟨bit0 n, h⟩ : ℕ+) = (bit0 ⟨n, pos_of_bit0_pos h⟩ : ℕ+) := rfl @[simp] lemma mk_bit1 (n) {h} {k} : (⟨bit1 n, h⟩ : ℕ+) = (bit1 ⟨n, k⟩ : ℕ+) := rfl -- Some lemmas that rewrite inequalities between explicit numerals in `pnat` -- into the corresponding inequalities in `nat`. -- TODO: perhaps this should not be attempted by `simp`, -- and instead we should expect `norm_num` to take care of these directly? -- TODO: these lemmas are perhaps incomplete: -- * 1 is not represented as a bit0 or bit1 -- * strict inequalities? @[simp] lemma bit0_le_bit0 (n m : ℕ+) : (bit0 n) ≤ (bit0 m) ↔ (bit0 (n : ℕ)) ≤ (bit0 (m : ℕ)) := iff.rfl @[simp] lemma bit0_le_bit1 (n m : ℕ+) : (bit0 n) ≤ (bit1 m) ↔ (bit0 (n : ℕ)) ≤ (bit1 (m : ℕ)) := iff.rfl @[simp] lemma bit1_le_bit0 (n m : ℕ+) : (bit1 n) ≤ (bit0 m) ↔ (bit1 (n : ℕ)) ≤ (bit0 (m : ℕ)) := iff.rfl @[simp] lemma bit1_le_bit1 (n m : ℕ+) : (bit1 n) ≤ (bit1 m) ↔ (bit1 (n : ℕ)) ≤ (bit1 (m : ℕ)) := iff.rfl @[simp] theorem one_coe : ((1 : ℕ+) : ℕ) = 1 := rfl @[simp] theorem mul_coe (m n : ℕ+) : ((m * n : ℕ+) : ℕ) = m * n := rfl instance coe_mul_hom : is_monoid_hom (coe : ℕ+ → ℕ) := {map_one := one_coe, map_mul := mul_coe} @[simp] lemma coe_eq_one_iff {m : ℕ+} : (m : ℕ) = 1 ↔ m = 1 := by { split; intro h; try { apply pnat.eq}; rw h; simp } @[simp] lemma coe_bit0 (a : ℕ+) : ((bit0 a : ℕ+) : ℕ) = bit0 (a : ℕ) := rfl @[simp] lemma coe_bit1 (a : ℕ+) : ((bit1 a : ℕ+) : ℕ) = bit1 (a : ℕ) := rfl @[simp] theorem pow_coe (m : ℕ+) (n : ℕ) : ((m ^ n : ℕ+) : ℕ) = (m : ℕ) ^ n := by induction n with n ih; [refl, rw [pow_succ', pow_succ, mul_coe, mul_comm, ih]] instance : left_cancel_semigroup ℕ+ := { mul_left_cancel := λ a b c h, by { replace h := congr_arg (coe : ℕ+ → ℕ) h, exact eq ((nat.mul_right_inj a.pos).mp h)}, .. (pnat.comm_monoid) } instance : right_cancel_semigroup ℕ+ := { mul_right_cancel := λ a b c h, by { replace h := congr_arg (coe : ℕ+ → ℕ) h, exact eq ((nat.mul_left_inj b.pos).mp h)}, .. (pnat.comm_monoid) } instance : ordered_cancel_comm_monoid ℕ+ := { mul_le_mul_left := by { intros, apply nat.mul_le_mul_left, assumption }, le_of_mul_le_mul_left := by { intros a b c h, apply nat.le_of_mul_le_mul_left h a.property, }, .. (pnat.left_cancel_semigroup), .. (pnat.right_cancel_semigroup), .. (pnat.decidable_linear_order), .. (pnat.comm_monoid)} instance : distrib ℕ+ := { left_distrib := λ a b c, eq (mul_add a b c), right_distrib := λ a b c, eq (add_mul a b c), ..(pnat.add_comm_semigroup), ..(pnat.comm_monoid) } /-- Subtraction a - b is defined in the obvious way when a > b, and by a - b = 1 if a ≤ b. -/ instance : has_sub ℕ+ := ⟨λ a b, to_pnat' (a - b : ℕ)⟩ theorem sub_coe (a b : ℕ+) : ((a - b : ℕ+) : ℕ) = ite (b < a) (a - b : ℕ) 1 := begin change ((to_pnat' ((a : ℕ) - (b : ℕ)) : ℕ)) = ite ((a : ℕ) > (b : ℕ)) ((a : ℕ) - (b : ℕ)) 1, split_ifs with h, { exact to_pnat'_coe (nat.sub_pos_of_lt h) }, { rw [nat.sub_eq_zero_iff_le.mpr (le_of_not_gt h)], refl } end theorem add_sub_of_lt {a b : ℕ+} : a < b → a + (b - a) = b := λ h, eq $ by { rw [add_coe, sub_coe, if_pos h], exact nat.add_sub_of_le (le_of_lt h) } /-- We define m % k and m / k in the same way as for nat except that when m = n * k we take m % k = k and m / k = n - 1. This ensures that m % k is always positive and m = (m % k) + k * (m / k) in all cases. Later we define a function div_exact which gives the usual m / k in the case where k divides m. -/ def mod_div_aux : ℕ+ → ℕ → ℕ → ℕ+ × ℕ | k 0 q := ⟨k, q.pred⟩ | k (r + 1) q := ⟨⟨r + 1, nat.succ_pos r⟩, q⟩ lemma mod_div_aux_spec : ∀ (k : ℕ+) (r q : ℕ) (h : ¬ (r = 0 ∧ q = 0)), (((mod_div_aux k r q).1 : ℕ) + k * (mod_div_aux k r q).2 = (r + k * q)) | k 0 0 h := (h ⟨rfl, rfl⟩).elim | k 0 (q + 1) h := by { change (k : ℕ) + (k : ℕ) * (q + 1).pred = 0 + (k : ℕ) * (q + 1), rw [nat.pred_succ, nat.mul_succ, zero_add, add_comm]} | k (r + 1) q h := rfl def mod_div (m k : ℕ+) : ℕ+ × ℕ := mod_div_aux k ((m : ℕ) % (k : ℕ)) ((m : ℕ) / (k : ℕ)) def mod (m k : ℕ+) : ℕ+ := (mod_div m k).1 def div (m k : ℕ+) : ℕ := (mod_div m k).2 theorem mod_add_div (m k : ℕ+) : (m : ℕ) = (mod m k) + k * (div m k) := begin let h₀ := nat.mod_add_div (m : ℕ) (k : ℕ), have : ¬ ((m : ℕ) % (k : ℕ) = 0 ∧ (m : ℕ) / (k : ℕ) = 0), by { rintro ⟨hr, hq⟩, rw [hr, hq, mul_zero, zero_add] at h₀, exact (m.ne_zero h₀.symm).elim }, have := mod_div_aux_spec k ((m : ℕ) % (k : ℕ)) ((m : ℕ) / (k : ℕ)) this, exact (this.trans h₀).symm, end theorem mod_coe (m k : ℕ+) : ((mod m k) : ℕ) = ite ((m : ℕ) % (k : ℕ) = 0) (k : ℕ) ((m : ℕ) % (k : ℕ)) := begin dsimp [mod, mod_div], cases (m : ℕ) % (k : ℕ), { rw [if_pos rfl], refl }, { rw [if_neg n.succ_ne_zero], refl } end theorem div_coe (m k : ℕ+) : ((div m k) : ℕ) = ite ((m : ℕ) % (k : ℕ) = 0) ((m : ℕ) / (k : ℕ)).pred ((m : ℕ) / (k : ℕ)) := begin dsimp [div, mod_div], cases (m : ℕ) % (k : ℕ), { rw [if_pos rfl], refl }, { rw [if_neg n.succ_ne_zero], refl } end theorem mod_le (m k : ℕ+) : mod m k ≤ m ∧ mod m k ≤ k := begin change ((mod m k) : ℕ) ≤ (m : ℕ) ∧ ((mod m k) : ℕ) ≤ (k : ℕ), rw [mod_coe], split_ifs, { have hm : (m : ℕ) > 0 := m.pos, rw [← nat.mod_add_div (m : ℕ) (k : ℕ), h, zero_add] at hm ⊢, by_cases h' : ((m : ℕ) / (k : ℕ)) = 0, { rw [h', mul_zero] at hm, exact (lt_irrefl _ hm).elim}, { let h' := nat.mul_le_mul_left (k : ℕ) (nat.succ_le_of_lt (nat.pos_of_ne_zero h')), rw [mul_one] at h', exact ⟨h', le_refl (k : ℕ)⟩ } }, { exact ⟨nat.mod_le (m : ℕ) (k : ℕ), le_of_lt (nat.mod_lt (m : ℕ) k.pos)⟩ } end theorem dvd_iff {k m : ℕ+} : k ∣ m ↔ (k : ℕ) ∣ (m : ℕ) := begin split; intro h, rcases h with ⟨_, rfl⟩, apply dvd_mul_right, rcases h with ⟨a, h⟩, cases a, { contrapose h, apply ne_zero, }, use a.succ, apply nat.succ_pos, rw [← coe_inj, h, mul_coe, mk_coe], end theorem dvd_iff' {k m : ℕ+} : k ∣ m ↔ mod m k = k := begin rw dvd_iff, rw [nat.dvd_iff_mod_eq_zero], split, { intro h, apply eq, rw [mod_coe, if_pos h] }, { intro h, by_cases h' : (m : ℕ) % (k : ℕ) = 0, { exact h'}, { replace h : ((mod m k) : ℕ) = (k : ℕ) := congr_arg _ h, rw [mod_coe, if_neg h'] at h, exact (ne_of_lt (nat.mod_lt (m : ℕ) k.pos) h).elim } } end lemma le_of_dvd {m n : ℕ+} : m ∣ n → m ≤ n := by { rw dvd_iff', intro h, rw ← h, apply (mod_le n m).left } def div_exact {m k : ℕ+} (h : k ∣ m) : ℕ+ := ⟨(div m k).succ, nat.succ_pos _⟩ theorem mul_div_exact {m k : ℕ+} (h : k ∣ m) : k * (div_exact h) = m := begin apply eq, rw [mul_coe], change (k : ℕ) * (div m k).succ = m, rw [mod_add_div m k, dvd_iff'.mp h, nat.mul_succ, add_comm], end theorem dvd_antisymm {m n : ℕ+} : m ∣ n → n ∣ m → m = n := λ hmn hnm, le_antisymm (le_of_dvd hmn) (le_of_dvd hnm) theorem dvd_one_iff (n : ℕ+) : n ∣ 1 ↔ n = 1 := ⟨λ h, dvd_antisymm h (one_dvd n), λ h, h.symm ▸ (dvd_refl 1)⟩ def gcd (n m : ℕ+) : ℕ+ := ⟨nat.gcd (n : ℕ) (m : ℕ), nat.gcd_pos_of_pos_left (m : ℕ) n.pos⟩ def lcm (n m : ℕ+) : ℕ+ := ⟨nat.lcm (n : ℕ) (m : ℕ), by { let h := mul_pos n.pos m.pos, rw [← gcd_mul_lcm (n : ℕ) (m : ℕ), mul_comm] at h, exact pos_of_dvd_of_pos (dvd.intro (nat.gcd (n : ℕ) (m : ℕ)) rfl) h }⟩ @[simp] theorem gcd_coe (n m : ℕ+) : ((gcd n m) : ℕ) = nat.gcd n m := rfl @[simp] theorem lcm_coe (n m : ℕ+) : ((lcm n m) : ℕ) = nat.lcm n m := rfl theorem gcd_dvd_left (n m : ℕ+) : (gcd n m) ∣ n := dvd_iff.2 (nat.gcd_dvd_left (n : ℕ) (m : ℕ)) theorem gcd_dvd_right (n m : ℕ+) : (gcd n m) ∣ m := dvd_iff.2 (nat.gcd_dvd_right (n : ℕ) (m : ℕ)) theorem dvd_gcd {m n k : ℕ+} (hm : k ∣ m) (hn : k ∣ n) : k ∣ gcd m n := dvd_iff.2 (@nat.dvd_gcd (m : ℕ) (n : ℕ) (k : ℕ) (dvd_iff.1 hm) (dvd_iff.1 hn)) theorem dvd_lcm_left (n m : ℕ+) : n ∣ lcm n m := dvd_iff.2 (nat.dvd_lcm_left (n : ℕ) (m : ℕ)) theorem dvd_lcm_right (n m : ℕ+) : m ∣ lcm n m := dvd_iff.2 (nat.dvd_lcm_right (n : ℕ) (m : ℕ)) theorem lcm_dvd {m n k : ℕ+} (hm : m ∣ k) (hn : n ∣ k) : lcm m n ∣ k := dvd_iff.2 (@nat.lcm_dvd (m : ℕ) (n : ℕ) (k : ℕ) (dvd_iff.1 hm) (dvd_iff.1 hn)) theorem gcd_mul_lcm (n m : ℕ+) : (gcd n m) * (lcm n m) = n * m := subtype.eq (nat.gcd_mul_lcm (n : ℕ) (m : ℕ)) lemma eq_one_of_lt_two {n : ℕ+} : n < 2 → n = 1 := begin intro h, apply le_antisymm, swap, apply pnat.one_le, change n < 1 + 1 at h, rw pnat.lt_add_one_iff at h, apply h end section prime /-! ### Prime numbers -/ def prime (p : ℕ+) : Prop := (p : ℕ).prime lemma prime.one_lt {p : ℕ+} : p.prime → 1 < p := nat.prime.one_lt lemma prime_two : (2 : ℕ+).prime := nat.prime_two lemma dvd_prime {p m : ℕ+} (pp : p.prime) : (m ∣ p ↔ m = 1 ∨ m = p) := by { rw pnat.dvd_iff, rw nat.dvd_prime pp, simp } lemma prime.ne_one {p : ℕ+} : p.prime → p ≠ 1 := by { intro pp, intro contra, apply nat.prime.ne_one pp, rw pnat.coe_eq_one_iff, apply contra } @[simp] lemma not_prime_one : ¬ (1: ℕ+).prime := nat.not_prime_one lemma prime.not_dvd_one {p : ℕ+} : p.prime → ¬ p ∣ 1 := λ pp : p.prime, by {rw dvd_iff, apply nat.prime.not_dvd_one pp} lemma exists_prime_and_dvd {n : ℕ+} : 2 ≤ n → (∃ (p : ℕ+), p.prime ∧ p ∣ n) := begin intro h, cases nat.exists_prime_and_dvd h with p hp, existsi (⟨p, nat.prime.pos hp.left⟩ : ℕ+), rw dvd_iff, apply hp end end prime section coprime /-! ### Coprime numbers and gcd -/ /-- Two pnats are coprime if their gcd is 1. -/ def coprime (m n : ℕ+) : Prop := m.gcd n = 1 @[simp] lemma coprime_coe {m n : ℕ+} : nat.coprime ↑m ↑n ↔ m.coprime n := by { unfold coprime, unfold nat.coprime, rw ← coe_inj, simp } lemma coprime.mul {k m n : ℕ+} : m.coprime k → n.coprime k → (m * n).coprime k := by { repeat {rw ← coprime_coe}, rw mul_coe, apply nat.coprime.mul } lemma coprime.mul_right {k m n : ℕ+} : k.coprime m → k.coprime n → k.coprime (m * n) := by { repeat {rw ← coprime_coe}, rw mul_coe, apply nat.coprime.mul_right } lemma gcd_comm {m n : ℕ+} : m.gcd n = n.gcd m := by { apply eq, simp only [gcd_coe], apply nat.gcd_comm } lemma gcd_eq_left_iff_dvd {m n : ℕ+} : m ∣ n ↔ m.gcd n = m := by { rw dvd_iff, rw nat.gcd_eq_left_iff_dvd, rw ← coe_inj, simp } lemma gcd_eq_right_iff_dvd {m n : ℕ+} : m ∣ n ↔ n.gcd m = m := by { rw gcd_comm, apply gcd_eq_left_iff_dvd, } lemma coprime.gcd_mul_left_cancel (m : ℕ+) {n k : ℕ+} : k.coprime n → (k * m).gcd n = m.gcd n := begin intro h, apply eq, simp only [gcd_coe, mul_coe], apply nat.coprime.gcd_mul_left_cancel, simpa end lemma coprime.gcd_mul_right_cancel (m : ℕ+) {n k : ℕ+} : k.coprime n → (m * k).gcd n = m.gcd n := begin rw mul_comm, apply coprime.gcd_mul_left_cancel, end lemma coprime.gcd_mul_left_cancel_right (m : ℕ+) {n k : ℕ+} : k.coprime m → m.gcd (k * n) = m.gcd n := begin intro h, iterate 2 {rw gcd_comm, symmetry}, apply coprime.gcd_mul_left_cancel _ h, end lemma coprime.gcd_mul_right_cancel_right (m : ℕ+) {n k : ℕ+} : k.coprime m → m.gcd (n * k) = m.gcd n := begin rw mul_comm, apply coprime.gcd_mul_left_cancel_right, end @[simp] lemma one_gcd {n : ℕ+} : gcd 1 n = 1 := by { rw ← gcd_eq_left_iff_dvd, apply one_dvd } @[simp] lemma gcd_one {n : ℕ+} : gcd n 1 = 1 := by { rw gcd_comm, apply one_gcd } @[symm] lemma coprime.symm {m n : ℕ+} : m.coprime n → n.coprime m := by { unfold coprime, rw gcd_comm, simp } @[simp] lemma one_coprime {n : ℕ+} : (1 : ℕ+).coprime n := one_gcd @[simp] lemma coprime_one {n : ℕ+} : n.coprime 1 := coprime.symm one_coprime lemma coprime.coprime_dvd_left {m k n : ℕ+} : m ∣ k → k.coprime n → m.coprime n := by { rw dvd_iff, repeat {rw ← coprime_coe}, apply nat.coprime.coprime_dvd_left } lemma coprime.factor_eq_gcd_left {a b m n : ℕ+} (cop : m.coprime n) (am : a ∣ m) (bn : b ∣ n): a = (a * b).gcd m := begin rw gcd_eq_left_iff_dvd at am, conv_lhs {rw ← am}, symmetry, apply coprime.gcd_mul_right_cancel a, apply coprime.coprime_dvd_left bn cop.symm, end lemma coprime.factor_eq_gcd_right {a b m n : ℕ+} (cop : m.coprime n) (am : a ∣ m) (bn : b ∣ n): a = (b * a).gcd m := begin rw mul_comm, apply coprime.factor_eq_gcd_left cop am bn, end lemma coprime.factor_eq_gcd_left_right {a b m n : ℕ+} (cop : m.coprime n) (am : a ∣ m) (bn : b ∣ n): a = m.gcd (a * b) := begin rw gcd_comm, apply coprime.factor_eq_gcd_left cop am bn, end lemma coprime.factor_eq_gcd_right_right {a b m n : ℕ+} (cop : m.coprime n) (am : a ∣ m) (bn : b ∣ n): a = m.gcd (b * a) := begin rw gcd_comm, apply coprime.factor_eq_gcd_right cop am bn, end lemma coprime.gcd_mul (k : ℕ+) {m n : ℕ+} (h: m.coprime n) : k.gcd (m * n) = k.gcd m * k.gcd n := begin rw ← coprime_coe at h, apply eq, simp only [gcd_coe, mul_coe], apply nat.coprime.gcd_mul k h end lemma gcd_eq_left {m n : ℕ+} : m ∣ n → m.gcd n = m := by { rw dvd_iff, intro h, apply eq, simp only [gcd_coe], apply nat.gcd_eq_left h } lemma coprime.pow {m n : ℕ+} (k l : ℕ) (h : m.coprime n) : (m ^ k).coprime (n ^ l) := begin rw ← coprime_coe at *, simp only [pow_coe], apply nat.coprime.pow, apply h end end coprime end pnat
d06f8be076d7a4d6c2706706b5b62b82e980515b
1b8f093752ba748c5ca0083afef2959aaa7dace5
/src/category_theory/examples/rings/universal.lean
a156792758e77dc7ea0e4d3b23278b11c53fc029
[]
no_license
khoek/lean-category-theory
7ec4cda9cc64a5a4ffeb84712ac7d020dbbba386
63dcb598e9270a3e8b56d1769eb4f825a177cd95
refs/heads/master
1,585,251,725,759
1,539,344,445,000
1,539,344,445,000
145,281,070
0
0
null
1,534,662,376,000
1,534,662,376,000
null
UTF-8
Lean
false
false
3,227
lean
import ring_theory.ideals import linear_algebra.quotient_module import category_theory.examples.rings import category_theory.limits import category_theory.filtered universes v namespace category_theory.examples open category_theory open category_theory.limits variables {α : Type v} instance : has_products.{v+1 v} CommRing := sorry def coequalizer_ideal {R S : CommRing} (f g : R ⟶ S) : set S.1 := span (set.range (λ x : R, f x - g x)) instance {R S : CommRing} (f g : R ⟶ S) : is_ideal (coequalizer_ideal f g) := sorry local attribute [instance] classical.prop_decidable instance : has_coequalizers.{v+1 v} CommRing := { coequalizer := λ R S f g, { X := { α := quotient_ring.quotient (coequalizer_ideal f g) }, π := ⟨ quotient_ring.mk, by apply_instance ⟩, w := sorry /- almost there: -/ /- begin ext, dsimp, apply quotient.sound, fsplit, exact finsupp.single 1 (f.map x - g.map x), obviously, sorry, sorry end -/ }, is_coequalizer := λ R S f g, { desc := λ s, { val := sorry, property := sorry, }, fac := sorry, uniq := sorry } } instance : has_colimits.{v+1 v} CommRing := sorry section variables {J : Type v} [𝒥 : small_category J] [filtered.{v v} J] include 𝒥 def matching (F : J ⥤ CommRing) (a b : Σ j : J, (F j).1) : Prop := ∃ (j : J) (f_a : a.1 ⟶ j) (f_b : b.1 ⟶ j), (F.map f_a) a.2 = (F.map f_b) b.2 def filtered_colimit (F : J ⥤ CommRing) := @quot (Σ j : J, (F j).1) (matching F) local attribute [elab_with_expected_type] quot.lift def filtered_colimit.zero (F : J ⥤ CommRing) : filtered_colimit F := quot.mk _ ⟨ filtered.default.{v v} J, 0 ⟩ -- TODO do this in two steps. def filtered_colimit.add (F : J ⥤ CommRing) (x y : filtered_colimit F) : filtered_colimit F := quot.lift (λ p : Σ j, (F j).1, quot.lift (λ q : Σ j, (F j).1, quot.mk _ (begin have s := filtered.obj_bound.{v v} p.1 q.1, exact ⟨ s.X, ((F.map s.ι₁) p.2) + ((F.map s.ι₂) q.2) ⟩ end : Σ j, (F j).1)) (λ q q' (r : matching F q q'), @quot.sound _ (matching F) _ _ begin dunfold matching, dsimp, dsimp [matching] at r, rcases r with ⟨j, f_a, f_b, e⟩, /- this is messy, but doable -/ sorry end)) (λ p p' (r : matching F p p'), funext $ λ q, begin dsimp, /- no idea -/ sorry end) x y def filtered_colimit_is_comm_ring (F : J ⥤ CommRing) : comm_ring (filtered_colimit F) := { add := filtered_colimit.add F, neg := sorry, mul := sorry, zero := filtered_colimit.zero F, one := sorry, add_comm := sorry, add_assoc := sorry, zero_add := sorry, add_zero := sorry, add_left_neg := sorry, mul_comm := sorry, mul_assoc := sorry, one_mul := sorry, mul_one := sorry, left_distrib := sorry, right_distrib := sorry } end instance : has_filtered_colimits.{v+1 v} CommRing := { colimit := λ J 𝒥 f F, begin resetI, exact { X := { α := filtered_colimit F, str := filtered_colimit_is_comm_ring F }, ι := λ j, { val := λ x, begin sorry end, property := sorry }, w := sorry, } end, is_colimit := sorry } end category_theory.examples
2ef5b6015232a42dde744dbda783eda05048c244
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/run/univ_problem.lean
d846183a29aa3aeac82c98d7f4886add9dbf0379
[ "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
3,076
lean
import logic data.nat.basic data.prod data.unit open nat prod inductive vector (A : Type) : nat → Type := vnil {} : vector A zero, vcons : Π {n : nat}, A → vector A n → vector A (succ n) namespace vector print definition no_confusion infixr `::` := vcons section universe variables l₁ l₂ variable {A : Type.{l₁}} variable {C : Π (n : nat), vector A n → Type.{l₂+1}} definition brec_on {n : nat} (v : vector A n) (H : Π (n : nat) (v : vector A n), @below A C n v → C n v) : C n v := have general : C n v × @below A C n v, from rec_on v (pair (H zero vnil unit.star) unit.star) (λ (n₁ : nat) (a₁ : A) (v₁ : vector A n₁) (r₁ : C n₁ v₁ × @below A C n₁ v₁), have b : @below A C _ (vcons a₁ v₁), from r₁, have c : C (succ n₁) (vcons a₁ v₁), from H (succ n₁) (vcons a₁ v₁) b, pair c b), pr₁ general end print "=====================" definition append {A : Type} {n m : nat} (w : vector A m) (v : vector A n) : vector A (n + m) := brec_on w (λ (n : nat) (w : vector A n), cases_on w (λ (B : below vnil), v) (λ (n₁ : nat) (a₁ : A) (v₁ : vector A n₁) (B : below (vcons a₁ v₁)), vcons a₁ (pr₁ B))) exit check brec_on definition bw := @below definition sum {n : nat} (v : vector nat n) : nat := brec_on v (λ (n : nat) (v : vector nat n), cases_on v (λ (B : bw vnil), zero) (λ (n₁ : nat) (a : nat) (v₁ : vector nat n₁) (B : bw (vcons a v₁)), a + pr₁ B)) example : sum (10 :: 20 :: vnil) = 30 := rfl definition addk {n : nat} (v : vector nat n) (k : nat) : vector nat n := brec_on v (λ (n : nat) (v : vector nat n), cases_on v (λ (B : bw vnil), vnil) (λ (n₁ : nat) (a₁ : nat) (v₁ : vector nat n₁) (B : bw (vcons a₁ v₁)), vcons (a₁+k) (pr₁ B))) example : addk (1 :: 2 :: vnil) 3 = 4 :: 5 :: vnil := rfl example : append (1 :: 2 :: vnil) (3 :: vnil) = 1 :: 2 :: 3 :: vnil := rfl definition head {A : Type} {n : nat} (v : vector A (succ n)) : A := cases_on v (λ H : succ n = 0, nat.no_confusion H) (λn' h t (H : succ n = succ n'), h) rfl definition tail {A : Type} {n : nat} (v : vector A (succ n)) : vector A n := @cases_on A (λn' v, succ n = n' → vector A (pred n')) (succ n) v (λ H : succ n = 0, nat.no_confusion H) (λ (n' : nat) (h : A) (t : vector A n') (H : succ n = succ n'), t) rfl definition add {n : nat} (w v : vector nat n) : vector nat n := @brec_on nat (λ (n : nat) (v : vector nat n), vector nat n → vector nat n) n w (λ (n : nat) (w : vector nat n), cases_on w (λ (B : bw vnil) (w : vector nat zero), vnil) (λ (n₁ : nat) (a₁ : nat) (v₁ : vector nat n₁) (B : bw (vcons a₁ v₁)) (v : vector nat (succ n₁)), vcons (a₁ + head v) (pr₁ B (tail v)))) v example : add (1 :: 2 :: vnil) (3 :: 5 :: vnil) = 4 :: 7 :: vnil := rfl end vector
759e6e505731522d2c20b0652db5751a97f08bdf
b7f22e51856f4989b970961f794f1c435f9b8f78
/hott/types/arrow_2.hlean
f35fbbb28e492022ecb520048df4686b1a2940bb
[ "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
7,029
hlean
/- Copyright (c) 2015 Ulrik Buchholtz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ulrik Buchholtz -/ import ..function open eq is_equiv function namespace arrow structure arrow := (dom : Type) (cod : Type) (arrow : dom → cod) abbreviation dom [unfold 2] := @arrow.dom abbreviation cod [unfold 2] := @arrow.cod definition arrow_of_fn {A B : Type} (f : A → B) : arrow := arrow.mk A B f structure morphism (A B : Type) := (mor : A → B) definition morphism_of_arrow [coercion] (f : arrow) : morphism (dom f) (cod f) := morphism.mk (arrow.arrow f) attribute morphism.mor [coercion] structure arrow_hom (f g : arrow) := (on_dom : dom f → dom g) (on_cod : cod f → cod g) (commute : Π(x : dom f), g (on_dom x) = on_cod (f x)) abbreviation on_dom [unfold 2] := @arrow_hom.on_dom abbreviation on_cod [unfold 2] := @arrow_hom.on_cod abbreviation commute [unfold 2] := @arrow_hom.commute variables {f g : arrow} definition on_fiber [reducible] (r : arrow_hom f g) (y : cod f) : fiber f y → fiber g (on_cod r y) := fiber.rec (λx p, fiber.mk (on_dom r x) (commute r x ⬝ ap (on_cod r) p)) structure is_retraction [class] (r : arrow_hom f g) : Type := (sect : arrow_hom g f) (right_inverse_dom : Π(a : dom g), on_dom r (on_dom sect a) = a) (right_inverse_cod : Π(b : cod g), on_cod r (on_cod sect b) = b) (cohere : Π(a : dom g), commute r (on_dom sect a) ⬝ ap (on_cod r) (commute sect a) = ap g (right_inverse_dom a) ⬝ (right_inverse_cod (g a))⁻¹) definition retraction_on_fiber [reducible] (r : arrow_hom f g) [H : is_retraction r] (b : cod g) : fiber f (on_cod (is_retraction.sect r) b) → fiber g b := fiber.rec (λx q, fiber.mk (on_dom r x) (commute r x ⬝ ap (on_cod r) q ⬝ is_retraction.right_inverse_cod r b)) definition retraction_on_fiber_right_inverse' (r : arrow_hom f g) [H : is_retraction r] (a : dom g) (b : cod g) (p : g a = b) : retraction_on_fiber r b (on_fiber (is_retraction.sect r) b (fiber.mk a p)) = fiber.mk a p := begin induction p, unfold on_fiber, unfold retraction_on_fiber, apply @fiber.fiber_eq _ _ g (g a) (fiber.mk (on_dom r (on_dom (is_retraction.sect r) a)) (commute r (on_dom (is_retraction.sect r) a) ⬝ ap (on_cod r) (commute (is_retraction.sect r) a) ⬝ is_retraction.right_inverse_cod r (g a))) (fiber.mk a (refl (g a))) (is_retraction.right_inverse_dom r a), -- everything but this field should be inferred rewrite [is_retraction.cohere r a], apply inv_con_cancel_right end definition retraction_on_fiber_right_inverse (r : arrow_hom f g) [H : is_retraction r] : Π(b : cod g), Π(z : fiber g b), retraction_on_fiber r b (on_fiber (is_retraction.sect r) b z) = z := λb, fiber.rec (λa p, retraction_on_fiber_right_inverse' r a b p) -- Lemma 4.7.3 definition retraction_on_fiber_is_retraction [instance] (r : arrow_hom f g) [H : is_retraction r] (b : cod g) : _root_.is_retraction (retraction_on_fiber r b) := _root_.is_retraction.mk (on_fiber (is_retraction.sect r) b) (retraction_on_fiber_right_inverse r b) -- Theorem 4.7.4 definition retract_of_equivalence_is_equivalence (r : arrow_hom f g) [H : is_retraction r] [K : is_equiv f] : is_equiv g := begin apply @is_equiv_of_is_contr_fun _ _ g, intro b, apply is_contr_retract (retraction_on_fiber r b), exact is_contr_fun_of_is_equiv f (on_cod (is_retraction.sect r) b) end end arrow namespace arrow variables {A B : Type} {f g : A → B} (p : f ~ g) definition arrow_hom_of_homotopy : arrow_hom (arrow_of_fn f) (arrow_of_fn g) := arrow_hom.mk id id (λx, (p x)⁻¹) definition is_retraction_arrow_hom_of_homotopy [instance] : is_retraction (arrow_hom_of_homotopy p) := is_retraction.mk (arrow_hom_of_homotopy (λx, (p x)⁻¹)) (λa, idp) (λb, idp) (λa, con_eq_of_eq_inv_con (ap_id _)) end arrow namespace arrow /- equivalences in the arrow category; could be packaged into structures. cannot be moved to types.pi because of the dependence on types.equiv. -/ variables {A A' B B' : Type} (f : A → B) (f' : A' → B') (α : A → A') (β : B → B') [Hf : is_equiv f] [Hf' : is_equiv f'] include Hf Hf' open function definition inv_commute_of_commute (p : f' ∘ α ~ β ∘ f) : f'⁻¹ ∘ β ~ α ∘ f⁻¹ := begin apply inv_homotopy_of_homotopy_post f' (α ∘ f⁻¹) β, apply homotopy.symm, apply inv_homotopy_of_homotopy_pre f (f' ∘ α) β, apply p end definition inv_commute_of_commute_top (p : f' ∘ α ~ β ∘ f) (a : A) : inv_commute_of_commute f f' α β p (f a) = (ap f'⁻¹ (p a))⁻¹ ⬝ left_inv f' (α a) ⬝ ap α (left_inv f a)⁻¹ := begin unfold inv_commute_of_commute, unfold inv_homotopy_of_homotopy_post, unfold inv_homotopy_of_homotopy_pre, rewrite [adj f a,-(ap_compose β f)], rewrite [eq_of_square (natural_square_tr p (left_inv f a))], rewrite [ap_inv f'⁻¹,ap_con f'⁻¹,con_inv,con.assoc,con.assoc], apply whisker_left (ap f'⁻¹ (p a))⁻¹, apply eq_of_square, rewrite [ap_inv α,-(ap_compose f'⁻¹ (f' ∘ α))], apply hinverse, rewrite [ap_compose (f'⁻¹ ∘ f') α], refine vconcat_eq _ (ap_id (ap α (left_inv f a))), apply natural_square (left_inv f') (ap α (left_inv f a)) end definition ap_bot_inv_commute_of_commute (p : f' ∘ α ~ β ∘ f) (b : B) : ap f' (inv_commute_of_commute f f' α β p b) = right_inv f' (β b) ⬝ ap β (right_inv f b)⁻¹ ⬝ (p (f⁻¹ b))⁻¹ := begin unfold inv_commute_of_commute, unfold inv_homotopy_of_homotopy_post, unfold inv_homotopy_of_homotopy_pre, rewrite [ap_con,-(ap_compose f' f'⁻¹),-(adj f' (α (f⁻¹ b)))], rewrite [con.assoc (right_inv f' (β b)) (ap β (right_inv f b)⁻¹) (p (f⁻¹ b))⁻¹], apply eq_of_square, refine vconcat_eq _ (whisker_right (ap_inv β (right_inv f b)) (p (f⁻¹ b))⁻¹)⁻¹, refine vconcat_eq _ (con_inv (p (f⁻¹ b)) (ap β (right_inv f b))), refine vconcat_eq _ (ap_id (p (f⁻¹ b) ⬝ ap β (right_inv f b))⁻¹), apply natural_square (right_inv f') (p (f⁻¹ b) ⬝ ap β (right_inv f b))⁻¹ end definition is_equiv_inv_commute_of_commute : is_equiv (inv_commute_of_commute f f' α β) := begin unfold inv_commute_of_commute, apply @is_equiv_compose _ _ _ (inv_homotopy_of_homotopy_post f' (α ∘ f⁻¹) β) (homotopy.symm ∘ (inv_homotopy_of_homotopy_pre f (f' ∘ α) β)), { apply @is_equiv_compose _ _ _ homotopy.symm (inv_homotopy_of_homotopy_pre f (f' ∘ α) β), { apply inv_homotopy_of_homotopy_pre.is_equiv }, { apply pi.is_equiv_homotopy_symm } }, { apply inv_homotopy_of_homotopy_post.is_equiv } end end arrow
4227a6ec87a1070c4658f3503353410a6d4eb8e7
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/stage0/src/Lean/Elab/PreDefinition/Main.lean
8c87db13215a3118667287ec952f873e5174b6b5
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,709
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.PreDefinition.Basic import Lean.Elab.PreDefinition.Structural import Lean.Elab.PreDefinition.WF namespace Lean namespace Elab open Meta open Term private def addAndCompilePartial (preDefs : Array PreDefinition) : TermElabM Unit := do preDefs.forM fun preDef => forallTelescopeReducing preDef.type fun xs type => do inh ← liftM $ mkInhabitantFor preDef.declName xs type; addNonRec { preDef with kind := DefKind.«opaque», value := inh }; addAndCompileUnsafeRec preDefs private def isNonRecursive (preDef : PreDefinition) : Bool := Option.isNone $ preDef.value.find? fun c => match c with | Expr.const declName _ _ => preDef.declName == declName | _ => false private def partitionPreDefs (preDefs : Array PreDefinition) : Array (Array PreDefinition) := let getPreDef := fun declName => (preDefs.find? fun preDef => preDef.declName == declName).get!; let vertices := preDefs.toList.map fun preDef => preDef.declName; let successorsOf := fun declName => (getPreDef declName).value.foldConsts [] fun declName successors => if preDefs.any fun preDef => preDef.declName == declName then declName :: successors else successors; let sccs := SCC.scc vertices successorsOf; sccs.toArray.map fun scc => scc.toArray.map getPreDef private def collectMVarsAtPreDef (preDef : PreDefinition) : StateRefT CollectMVars.State MetaM Unit := do collectMVars preDef.value; collectMVars preDef.type private def getMVarsAtPreDef (preDef : PreDefinition) : MetaM (Array MVarId) := do (_, s) ← (collectMVarsAtPreDef preDef).run {}; pure s.result private def ensureNoUnassignedMVarsAtPreDef (preDef : PreDefinition) : TermElabM Unit := do pendingMVarIds ← liftMetaM $ getMVarsAtPreDef preDef; foundError ← logUnassignedUsingErrorContext pendingMVarIds; when foundError throwAbort def addPreDefinitions (preDefs : Array PreDefinition) : TermElabM Unit := do preDefs.forM fun preDef => trace `Elab.definition.body fun _ => preDef.declName ++ " : " ++ preDef.type ++ " :=" ++ Format.line ++ preDef.value; preDefs.forM ensureNoUnassignedMVarsAtPreDef; (partitionPreDefs preDefs).forM fun preDefs => do if preDefs.size == 1 && isNonRecursive (preDefs.get! 0) then addAndCompileNonRec (preDefs.get! 0) else if preDefs.any fun preDef => preDef.modifiers.isUnsafe then addAndCompileUnsafe preDefs else if preDefs.any fun preDef => preDef.modifiers.isPartial then addAndCompilePartial preDefs else unlessM (structuralRecursion preDefs) do WFRecursion preDefs end Elab end Lean
aa2beea61e75cd5339bb745cab8e504b5d6c10d3
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/data/complex/basic.lean
88c0e6dc56d50db4b63dceb3d2b2df8ea826fafb
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
30,825
lean
/- Copyright (c) 2017 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Mario Carneiro -/ import data.real.sqrt /-! # The complex numbers The complex numbers are modelled as ℝ^2 in the obvious way and it is shown that they form a field of characteristic zero. The result that the complex numbers are algebraically closed, see `field_theory.algebraic_closure`. -/ open_locale big_operators open set function /-! ### Definition and basic arithmmetic -/ /-- Complex numbers consist of two `real`s: a real part `re` and an imaginary part `im`. -/ structure complex : Type := (re : ℝ) (im : ℝ) notation `ℂ` := complex namespace complex open_locale complex_conjugate noncomputable instance : decidable_eq ℂ := classical.dec_eq _ /-- The equivalence between the complex numbers and `ℝ × ℝ`. -/ @[simps apply] def equiv_real_prod : ℂ ≃ (ℝ × ℝ) := { to_fun := λ z, ⟨z.re, z.im⟩, inv_fun := λ p, ⟨p.1, p.2⟩, left_inv := λ ⟨x, y⟩, rfl, right_inv := λ ⟨x, y⟩, rfl } @[simp] theorem eta : ∀ z : ℂ, complex.mk z.re z.im = z | ⟨a, b⟩ := rfl @[ext] theorem ext : ∀ {z w : ℂ}, z.re = w.re → z.im = w.im → z = w | ⟨zr, zi⟩ ⟨_, _⟩ rfl rfl := rfl theorem ext_iff {z w : ℂ} : z = w ↔ z.re = w.re ∧ z.im = w.im := ⟨λ H, by simp [H], and.rec ext⟩ theorem re_surjective : surjective re := λ x, ⟨⟨x, 0⟩, rfl⟩ theorem im_surjective : surjective im := λ y, ⟨⟨0, y⟩, rfl⟩ @[simp] theorem range_re : range re = univ := re_surjective.range_eq @[simp] theorem range_im : range im = univ := im_surjective.range_eq instance : has_coe ℝ ℂ := ⟨λ r, ⟨r, 0⟩⟩ @[simp, norm_cast] lemma of_real_re (r : ℝ) : (r : ℂ).re = r := rfl @[simp, norm_cast] lemma of_real_im (r : ℝ) : (r : ℂ).im = 0 := rfl lemma of_real_def (r : ℝ) : (r : ℂ) = ⟨r, 0⟩ := rfl @[simp, norm_cast] theorem of_real_inj {z w : ℝ} : (z : ℂ) = w ↔ z = w := ⟨congr_arg re, congr_arg _⟩ theorem of_real_injective : function.injective (coe : ℝ → ℂ) := λ z w, congr_arg re instance : can_lift ℂ ℝ := { cond := λ z, z.im = 0, coe := coe, prf := λ z hz, ⟨z.re, ext rfl hz.symm⟩ } /-- The product of a set on the real axis and a set on the imaginary axis of the complex plane, denoted by `s ×ℂ t`. -/ def _root_.set.re_prod_im (s t : set ℝ) : set ℂ := re ⁻¹' s ∩ im ⁻¹' t infix ` ×ℂ `:72 := set.re_prod_im lemma mem_re_prod_im {z : ℂ} {s t : set ℝ} : z ∈ s ×ℂ t ↔ z.re ∈ s ∧ z.im ∈ t := iff.rfl instance : has_zero ℂ := ⟨(0 : ℝ)⟩ instance : inhabited ℂ := ⟨0⟩ @[simp] lemma zero_re : (0 : ℂ).re = 0 := rfl @[simp] lemma zero_im : (0 : ℂ).im = 0 := rfl @[simp, norm_cast] lemma of_real_zero : ((0 : ℝ) : ℂ) = 0 := rfl @[simp] theorem of_real_eq_zero {z : ℝ} : (z : ℂ) = 0 ↔ z = 0 := of_real_inj theorem of_real_ne_zero {z : ℝ} : (z : ℂ) ≠ 0 ↔ z ≠ 0 := not_congr of_real_eq_zero instance : has_one ℂ := ⟨(1 : ℝ)⟩ @[simp] lemma one_re : (1 : ℂ).re = 1 := rfl @[simp] lemma one_im : (1 : ℂ).im = 0 := rfl @[simp, norm_cast] lemma of_real_one : ((1 : ℝ) : ℂ) = 1 := rfl @[simp] theorem of_real_eq_one {z : ℝ} : (z : ℂ) = 1 ↔ z = 1 := of_real_inj theorem of_real_ne_one {z : ℝ} : (z : ℂ) ≠ 1 ↔ z ≠ 1 := not_congr of_real_eq_one instance : has_add ℂ := ⟨λ z w, ⟨z.re + w.re, z.im + w.im⟩⟩ @[simp] lemma add_re (z w : ℂ) : (z + w).re = z.re + w.re := rfl @[simp] lemma add_im (z w : ℂ) : (z + w).im = z.im + w.im := rfl @[simp] lemma bit0_re (z : ℂ) : (bit0 z).re = bit0 z.re := rfl @[simp] lemma bit1_re (z : ℂ) : (bit1 z).re = bit1 z.re := rfl @[simp] lemma bit0_im (z : ℂ) : (bit0 z).im = bit0 z.im := eq.refl _ @[simp] lemma bit1_im (z : ℂ) : (bit1 z).im = bit0 z.im := add_zero _ @[simp, norm_cast] lemma of_real_add (r s : ℝ) : ((r + s : ℝ) : ℂ) = r + s := ext_iff.2 $ by simp @[simp, norm_cast] lemma of_real_bit0 (r : ℝ) : ((bit0 r : ℝ) : ℂ) = bit0 r := ext_iff.2 $ by simp [bit0] @[simp, norm_cast] lemma of_real_bit1 (r : ℝ) : ((bit1 r : ℝ) : ℂ) = bit1 r := ext_iff.2 $ by simp [bit1] instance : has_neg ℂ := ⟨λ z, ⟨-z.re, -z.im⟩⟩ @[simp] lemma neg_re (z : ℂ) : (-z).re = -z.re := rfl @[simp] lemma neg_im (z : ℂ) : (-z).im = -z.im := rfl @[simp, norm_cast] lemma of_real_neg (r : ℝ) : ((-r : ℝ) : ℂ) = -r := ext_iff.2 $ by simp instance : has_sub ℂ := ⟨λ z w, ⟨z.re - w.re, z.im - w.im⟩⟩ instance : has_mul ℂ := ⟨λ z w, ⟨z.re * w.re - z.im * w.im, z.re * w.im + z.im * w.re⟩⟩ @[simp] lemma mul_re (z w : ℂ) : (z * w).re = z.re * w.re - z.im * w.im := rfl @[simp] lemma mul_im (z w : ℂ) : (z * w).im = z.re * w.im + z.im * w.re := rfl @[simp, norm_cast] lemma of_real_mul (r s : ℝ) : ((r * s : ℝ) : ℂ) = r * s := ext_iff.2 $ by simp lemma of_real_mul_re (r : ℝ) (z : ℂ) : (↑r * z).re = r * z.re := by simp lemma of_real_mul_im (r : ℝ) (z : ℂ) : (↑r * z).im = r * z.im := by simp lemma of_real_mul' (r : ℝ) (z : ℂ) : (↑r * z) = ⟨r * z.re, r * z.im⟩ := ext (of_real_mul_re _ _) (of_real_mul_im _ _) /-! ### The imaginary unit, `I` -/ /-- The imaginary unit. -/ def I : ℂ := ⟨0, 1⟩ @[simp] lemma I_re : I.re = 0 := rfl @[simp] lemma I_im : I.im = 1 := rfl @[simp] lemma I_mul_I : I * I = -1 := ext_iff.2 $ by simp lemma I_mul (z : ℂ) : I * z = ⟨-z.im, z.re⟩ := ext_iff.2 $ by simp lemma I_ne_zero : (I : ℂ) ≠ 0 := mt (congr_arg im) zero_ne_one.symm lemma mk_eq_add_mul_I (a b : ℝ) : complex.mk a b = a + b * I := ext_iff.2 $ by simp @[simp] lemma re_add_im (z : ℂ) : (z.re : ℂ) + z.im * I = z := ext_iff.2 $ by simp lemma mul_I_re (z : ℂ) : (z * I).re = -z.im := by simp lemma mul_I_im (z : ℂ) : (z * I).im = z.re := by simp lemma I_mul_re (z : ℂ) : (I * z).re = -z.im := by simp lemma I_mul_im (z : ℂ) : (I * z).im = z.re := by simp @[simp] lemma equiv_real_prod_symm_apply (p : ℝ × ℝ) : equiv_real_prod.symm p = p.1 + p.2 * I := by { ext; simp [equiv_real_prod] } /-! ### Commutative ring instance and lemmas -/ /- We use a nonstandard formula for the `ℕ` and `ℤ` actions to make sure there is no diamond from the other actions they inherit through the `ℝ`-action on `ℂ` and action transitivity defined in `data.complex.module.lean`. -/ instance : add_comm_group ℂ := by refine_struct { zero := (0 : ℂ), add := (+), neg := has_neg.neg, sub := has_sub.sub, nsmul := λ n z, ⟨n • z.re - 0 * z.im, n • z.im + 0 * z.re⟩, zsmul := λ n z, ⟨n • z.re - 0 * z.im, n • z.im + 0 * z.re⟩ }; intros; try { refl }; apply ext_iff.2; split; simp; {ring1 <|> ring_nf} instance : add_group_with_one ℂ := { nat_cast := λ n, ⟨n, 0⟩, nat_cast_zero := by ext; simp [nat.cast], nat_cast_succ := λ _, by ext; simp [nat.cast], int_cast := λ n, ⟨n, 0⟩, int_cast_of_nat := λ _, by ext; simp [λ n, show @coe ℕ ℂ ⟨_⟩ n = ⟨n, 0⟩, from rfl], int_cast_neg_succ_of_nat := λ _, by ext; simp [λ n, show @coe ℕ ℂ ⟨_⟩ n = ⟨n, 0⟩, from rfl], one := 1, .. complex.add_comm_group } instance : comm_ring ℂ := by refine_struct { zero := (0 : ℂ), add := (+), one := 1, mul := (*), npow := @npow_rec _ ⟨(1 : ℂ)⟩ ⟨(*)⟩, .. complex.add_group_with_one }; intros; try { refl }; apply ext_iff.2; split; simp; {ring1 <|> ring_nf} /-- This shortcut instance ensures we do not find `ring` via the noncomputable `complex.field` instance. -/ instance : ring ℂ := by apply_instance /-- This shortcut instance ensures we do not find `comm_semiring` via the noncomputable `complex.field` instance. -/ instance : comm_semiring ℂ := infer_instance /-- The "real part" map, considered as an additive group homomorphism. -/ def re_add_group_hom : ℂ →+ ℝ := { to_fun := re, map_zero' := zero_re, map_add' := add_re } @[simp] lemma coe_re_add_group_hom : (re_add_group_hom : ℂ → ℝ) = re := rfl /-- The "imaginary part" map, considered as an additive group homomorphism. -/ def im_add_group_hom : ℂ →+ ℝ := { to_fun := im, map_zero' := zero_im, map_add' := add_im } @[simp] lemma coe_im_add_group_hom : (im_add_group_hom : ℂ → ℝ) = im := rfl @[simp] lemma I_pow_bit0 (n : ℕ) : I ^ (bit0 n) = (-1) ^ n := by rw [pow_bit0', I_mul_I] @[simp] lemma I_pow_bit1 (n : ℕ) : I ^ (bit1 n) = (-1) ^ n * I := by rw [pow_bit1', I_mul_I] /-! ### Complex conjugation -/ /-- This defines the complex conjugate as the `star` operation of the `star_ring ℂ`. It is recommended to use the ring endomorphism version `star_ring_end`, available under the notation `conj` in the locale `complex_conjugate`. -/ instance : star_ring ℂ := { star := λ z, ⟨z.re, -z.im⟩, star_involutive := λ x, by simp only [eta, neg_neg], star_mul := λ a b, by ext; simp [add_comm]; ring, star_add := λ a b, by ext; simp [add_comm] } @[simp] lemma conj_re (z : ℂ) : (conj z).re = z.re := rfl @[simp] lemma conj_im (z : ℂ) : (conj z).im = -z.im := rfl lemma conj_of_real (r : ℝ) : conj (r : ℂ) = r := ext_iff.2 $ by simp [conj] @[simp] lemma conj_I : conj I = -I := ext_iff.2 $ by simp lemma conj_bit0 (z : ℂ) : conj (bit0 z) = bit0 (conj z) := ext_iff.2 $ by simp [bit0] lemma conj_bit1 (z : ℂ) : conj (bit1 z) = bit1 (conj z) := ext_iff.2 $ by simp [bit0] @[simp] lemma conj_neg_I : conj (-I) = I := ext_iff.2 $ by simp lemma eq_conj_iff_real {z : ℂ} : conj z = z ↔ ∃ r : ℝ, z = r := ⟨λ h, ⟨z.re, ext rfl $ eq_zero_of_neg_eq (congr_arg im h)⟩, λ ⟨h, e⟩, by rw [e, conj_of_real]⟩ lemma eq_conj_iff_re {z : ℂ} : conj z = z ↔ (z.re : ℂ) = z := eq_conj_iff_real.trans ⟨by rintro ⟨r, rfl⟩; simp, λ h, ⟨_, h.symm⟩⟩ lemma eq_conj_iff_im {z : ℂ} : conj z = z ↔ z.im = 0 := ⟨λ h, add_self_eq_zero.mp (neg_eq_iff_add_eq_zero.mp (congr_arg im h)), λ h, ext rfl (neg_eq_iff_add_eq_zero.mpr (add_self_eq_zero.mpr h))⟩ -- `simp_nf` complains about this being provable by `is_R_or_C.star_def` even -- though it's not imported by this file. @[simp, nolint simp_nf] lemma star_def : (has_star.star : ℂ → ℂ) = conj := rfl /-! ### Norm squared -/ /-- The norm squared function. -/ @[pp_nodot] def norm_sq : ℂ →*₀ ℝ := { to_fun := λ z, z.re * z.re + z.im * z.im, map_zero' := by simp, map_one' := by simp, map_mul' := λ z w, by { dsimp, ring } } lemma norm_sq_apply (z : ℂ) : norm_sq z = z.re * z.re + z.im * z.im := rfl @[simp] lemma norm_sq_of_real (r : ℝ) : norm_sq r = r * r := by simp [norm_sq] @[simp] lemma norm_sq_mk (x y : ℝ) : norm_sq ⟨x, y⟩ = x * x + y * y := rfl lemma norm_sq_add_mul_I (x y : ℝ) : norm_sq (x + y * I) = x ^ 2 + y ^ 2 := by rw [← mk_eq_add_mul_I, norm_sq_mk, sq, sq] lemma norm_sq_eq_conj_mul_self {z : ℂ} : (norm_sq z : ℂ) = conj z * z := by { ext; simp [norm_sq, mul_comm], } @[simp] lemma norm_sq_zero : norm_sq 0 = 0 := norm_sq.map_zero @[simp] lemma norm_sq_one : norm_sq 1 = 1 := norm_sq.map_one @[simp] lemma norm_sq_I : norm_sq I = 1 := by simp [norm_sq] lemma norm_sq_nonneg (z : ℂ) : 0 ≤ norm_sq z := add_nonneg (mul_self_nonneg _) (mul_self_nonneg _) @[simp] lemma range_norm_sq : range norm_sq = Ici 0 := subset.antisymm (range_subset_iff.2 norm_sq_nonneg) $ λ x hx, ⟨real.sqrt x, by rw [norm_sq_of_real, real.mul_self_sqrt hx]⟩ lemma norm_sq_eq_zero {z : ℂ} : norm_sq z = 0 ↔ z = 0 := ⟨λ h, ext (eq_zero_of_mul_self_add_mul_self_eq_zero h) (eq_zero_of_mul_self_add_mul_self_eq_zero $ (add_comm _ _).trans h), λ h, h.symm ▸ norm_sq_zero⟩ @[simp] lemma norm_sq_pos {z : ℂ} : 0 < norm_sq z ↔ z ≠ 0 := (norm_sq_nonneg z).lt_iff_ne.trans $ not_congr (eq_comm.trans norm_sq_eq_zero) @[simp] lemma norm_sq_neg (z : ℂ) : norm_sq (-z) = norm_sq z := by simp [norm_sq] @[simp] lemma norm_sq_conj (z : ℂ) : norm_sq (conj z) = norm_sq z := by simp [norm_sq] lemma norm_sq_mul (z w : ℂ) : norm_sq (z * w) = norm_sq z * norm_sq w := norm_sq.map_mul z w lemma norm_sq_add (z w : ℂ) : norm_sq (z + w) = norm_sq z + norm_sq w + 2 * (z * conj w).re := by dsimp [norm_sq]; ring lemma re_sq_le_norm_sq (z : ℂ) : z.re * z.re ≤ norm_sq z := le_add_of_nonneg_right (mul_self_nonneg _) lemma im_sq_le_norm_sq (z : ℂ) : z.im * z.im ≤ norm_sq z := le_add_of_nonneg_left (mul_self_nonneg _) theorem mul_conj (z : ℂ) : z * conj z = norm_sq z := ext_iff.2 $ by simp [norm_sq, mul_comm, sub_eq_neg_add, add_comm] theorem add_conj (z : ℂ) : z + conj z = (2 * z.re : ℝ) := ext_iff.2 $ by simp [two_mul] /-- The coercion `ℝ → ℂ` as a `ring_hom`. -/ def of_real : ℝ →+* ℂ := ⟨coe, of_real_one, of_real_mul, of_real_zero, of_real_add⟩ @[simp] lemma of_real_eq_coe (r : ℝ) : of_real r = r := rfl @[simp] lemma I_sq : I ^ 2 = -1 := by rw [sq, I_mul_I] @[simp] lemma sub_re (z w : ℂ) : (z - w).re = z.re - w.re := rfl @[simp] lemma sub_im (z w : ℂ) : (z - w).im = z.im - w.im := rfl @[simp, norm_cast] lemma of_real_sub (r s : ℝ) : ((r - s : ℝ) : ℂ) = r - s := ext_iff.2 $ by simp @[simp, norm_cast] lemma of_real_pow (r : ℝ) (n : ℕ) : ((r ^ n : ℝ) : ℂ) = r ^ n := by induction n; simp [*, of_real_mul, pow_succ] theorem sub_conj (z : ℂ) : z - conj z = (2 * z.im : ℝ) * I := ext_iff.2 $ by simp [two_mul, sub_eq_add_neg] lemma norm_sq_sub (z w : ℂ) : norm_sq (z - w) = norm_sq z + norm_sq w - 2 * (z * conj w).re := by { rw [sub_eq_add_neg, norm_sq_add], simp only [ring_hom.map_neg, mul_neg, neg_re, tactic.ring.add_neg_eq_sub, norm_sq_neg] } /-! ### Inversion -/ noncomputable instance : has_inv ℂ := ⟨λ z, conj z * ((norm_sq z)⁻¹:ℝ)⟩ theorem inv_def (z : ℂ) : z⁻¹ = conj z * ((norm_sq z)⁻¹:ℝ) := rfl @[simp] lemma inv_re (z : ℂ) : (z⁻¹).re = z.re / norm_sq z := by simp [inv_def, division_def] @[simp] lemma inv_im (z : ℂ) : (z⁻¹).im = -z.im / norm_sq z := by simp [inv_def, division_def] @[simp, norm_cast] lemma of_real_inv (r : ℝ) : ((r⁻¹ : ℝ) : ℂ) = r⁻¹ := ext_iff.2 $ by simp protected lemma inv_zero : (0⁻¹ : ℂ) = 0 := by rw [← of_real_zero, ← of_real_inv, inv_zero] protected theorem mul_inv_cancel {z : ℂ} (h : z ≠ 0) : z * z⁻¹ = 1 := by rw [inv_def, ← mul_assoc, mul_conj, ← of_real_mul, mul_inv_cancel (mt norm_sq_eq_zero.1 h), of_real_one] /-! ### Field instance and lemmas -/ noncomputable instance : field ℂ := { inv := has_inv.inv, exists_pair_ne := ⟨0, 1, mt (congr_arg re) zero_ne_one⟩, mul_inv_cancel := @complex.mul_inv_cancel, inv_zero := complex.inv_zero, ..complex.comm_ring } @[simp] lemma I_zpow_bit0 (n : ℤ) : I ^ (bit0 n) = (-1) ^ n := by rw [zpow_bit0', I_mul_I] @[simp] lemma I_zpow_bit1 (n : ℤ) : I ^ (bit1 n) = (-1) ^ n * I := by rw [zpow_bit1', I_mul_I] lemma div_re (z w : ℂ) : (z / w).re = z.re * w.re / norm_sq w + z.im * w.im / norm_sq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg] lemma div_im (z w : ℂ) : (z / w).im = z.im * w.re / norm_sq w - z.re * w.im / norm_sq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg, add_comm] lemma conj_inv (x : ℂ) : conj (x⁻¹) = (conj x)⁻¹ := star_inv' _ @[simp, norm_cast] lemma of_real_div (r s : ℝ) : ((r / s : ℝ) : ℂ) = r / s := map_div₀ of_real r s @[simp, norm_cast] lemma of_real_zpow (r : ℝ) (n : ℤ) : ((r ^ n : ℝ) : ℂ) = (r : ℂ) ^ n := map_zpow₀ of_real r n @[simp] lemma div_I (z : ℂ) : z / I = -(z * I) := (div_eq_iff_mul_eq I_ne_zero).2 $ by simp [mul_assoc] @[simp] lemma inv_I : I⁻¹ = -I := by simp [inv_eq_one_div] @[simp] lemma norm_sq_inv (z : ℂ) : norm_sq z⁻¹ = (norm_sq z)⁻¹ := map_inv₀ norm_sq z @[simp] lemma norm_sq_div (z w : ℂ) : norm_sq (z / w) = norm_sq z / norm_sq w := map_div₀ norm_sq z w /-! ### Cast lemmas -/ @[simp, norm_cast] theorem of_real_nat_cast (n : ℕ) : ((n : ℝ) : ℂ) = n := map_nat_cast of_real n @[simp, norm_cast] lemma nat_cast_re (n : ℕ) : (n : ℂ).re = n := by rw [← of_real_nat_cast, of_real_re] @[simp, norm_cast] lemma nat_cast_im (n : ℕ) : (n : ℂ).im = 0 := by rw [← of_real_nat_cast, of_real_im] @[simp, norm_cast] theorem of_real_int_cast (n : ℤ) : ((n : ℝ) : ℂ) = n := of_real.map_int_cast n @[simp, norm_cast] lemma int_cast_re (n : ℤ) : (n : ℂ).re = n := by rw [← of_real_int_cast, of_real_re] @[simp, norm_cast] lemma int_cast_im (n : ℤ) : (n : ℂ).im = 0 := by rw [← of_real_int_cast, of_real_im] @[simp, norm_cast] theorem of_real_rat_cast (n : ℚ) : ((n : ℝ) : ℂ) = n := map_rat_cast of_real n @[simp, norm_cast] lemma rat_cast_re (q : ℚ) : (q : ℂ).re = q := by rw [← of_real_rat_cast, of_real_re] @[simp, norm_cast] lemma rat_cast_im (q : ℚ) : (q : ℂ).im = 0 := by rw [← of_real_rat_cast, of_real_im] /-! ### Characteristic zero -/ instance char_zero_complex : char_zero ℂ := char_zero_of_inj_zero $ λ n h, by rwa [← of_real_nat_cast, of_real_eq_zero, nat.cast_eq_zero] at h /-- A complex number `z` plus its conjugate `conj z` is `2` times its real part. -/ theorem re_eq_add_conj (z : ℂ) : (z.re : ℂ) = (z + conj z) / 2 := by simp only [add_conj, of_real_mul, of_real_one, of_real_bit0, mul_div_cancel_left (z.re:ℂ) two_ne_zero'] /-- A complex number `z` minus its conjugate `conj z` is `2i` times its imaginary part. -/ theorem im_eq_sub_conj (z : ℂ) : (z.im : ℂ) = (z - conj(z))/(2 * I) := by simp only [sub_conj, of_real_mul, of_real_one, of_real_bit0, mul_right_comm, mul_div_cancel_left _ (mul_ne_zero two_ne_zero' I_ne_zero : 2 * I ≠ 0)] /-! ### Absolute value -/ /-- The complex absolute value function, defined as the square root of the norm squared. -/ @[pp_nodot] noncomputable def abs (z : ℂ) : ℝ := (norm_sq z).sqrt local notation `abs'` := has_abs.abs @[simp, norm_cast] lemma abs_of_real (r : ℝ) : abs r = |r| := by simp [abs, norm_sq_of_real, real.sqrt_mul_self_eq_abs] lemma abs_of_nonneg {r : ℝ} (h : 0 ≤ r) : abs r = r := (abs_of_real _).trans (abs_of_nonneg h) lemma abs_of_nat (n : ℕ) : complex.abs n = n := calc complex.abs n = complex.abs (n:ℝ) : by rw [of_real_nat_cast] ... = _ : abs_of_nonneg (nat.cast_nonneg n) lemma mul_self_abs (z : ℂ) : abs z * abs z = norm_sq z := real.mul_self_sqrt (norm_sq_nonneg _) lemma sq_abs (z : ℂ) : abs z ^ 2 = norm_sq z := real.sq_sqrt (norm_sq_nonneg _) @[simp] lemma sq_abs_sub_sq_re (z : ℂ) : abs z ^ 2 - z.re ^ 2 = z.im ^ 2 := by rw [sq_abs, norm_sq_apply, ← sq, ← sq, add_sub_cancel'] @[simp] lemma sq_abs_sub_sq_im (z : ℂ) : abs z ^ 2 - z.im ^ 2 = z.re ^ 2 := by rw [← sq_abs_sub_sq_re, sub_sub_cancel] @[simp] lemma abs_zero : abs 0 = 0 := by simp [abs] @[simp] lemma abs_one : abs 1 = 1 := by simp [abs] @[simp] lemma abs_I : abs I = 1 := by simp [abs] @[simp] lemma abs_two : abs 2 = 2 := calc abs 2 = abs (2 : ℝ) : by rw [of_real_bit0, of_real_one] ... = (2 : ℝ) : abs_of_nonneg (by norm_num) lemma abs_nonneg (z : ℂ) : 0 ≤ abs z := real.sqrt_nonneg _ @[simp] lemma range_abs : range abs = Ici 0 := subset.antisymm (range_subset_iff.2 abs_nonneg) $ λ x hx, ⟨x, abs_of_nonneg hx⟩ @[simp] lemma abs_eq_zero {z : ℂ} : abs z = 0 ↔ z = 0 := (real.sqrt_eq_zero $ norm_sq_nonneg _).trans norm_sq_eq_zero lemma abs_ne_zero {z : ℂ} : abs z ≠ 0 ↔ z ≠ 0 := not_congr abs_eq_zero @[simp] lemma abs_conj (z : ℂ) : abs (conj z) = abs z := by simp [abs] @[simp] lemma abs_mul (z w : ℂ) : abs (z * w) = abs z * abs w := by rw [abs, norm_sq_mul, real.sqrt_mul (norm_sq_nonneg _)]; refl /-- `complex.abs` as a `monoid_with_zero_hom`. -/ @[simps] noncomputable def abs_hom : ℂ →*₀ ℝ := { to_fun := abs, map_zero' := abs_zero, map_one' := abs_one, map_mul' := abs_mul } @[simp] lemma abs_prod {ι : Type*} (s : finset ι) (f : ι → ℂ) : abs (s.prod f) = s.prod (λ i, abs (f i)) := map_prod abs_hom _ _ @[simp] lemma abs_pow (z : ℂ) (n : ℕ) : abs (z ^ n) = abs z ^ n := map_pow abs_hom z n @[simp] lemma abs_zpow (z : ℂ) (n : ℤ) : abs (z ^ n) = abs z ^ n := map_zpow₀ abs_hom z n lemma abs_re_le_abs (z : ℂ) : |z.re| ≤ abs z := by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg z.re) (abs_nonneg _), abs_mul_abs_self, mul_self_abs]; apply re_sq_le_norm_sq lemma abs_im_le_abs (z : ℂ) : |z.im| ≤ abs z := by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg z.im) (abs_nonneg _), abs_mul_abs_self, mul_self_abs]; apply im_sq_le_norm_sq lemma re_le_abs (z : ℂ) : z.re ≤ abs z := (abs_le.1 (abs_re_le_abs _)).2 lemma im_le_abs (z : ℂ) : z.im ≤ abs z := (abs_le.1 (abs_im_le_abs _)).2 @[simp] lemma abs_re_lt_abs {z : ℂ} : |z.re| < abs z ↔ z.im ≠ 0 := by rw [abs, real.lt_sqrt (_root_.abs_nonneg _), norm_sq_apply, _root_.sq_abs, ← sq, lt_add_iff_pos_right, mul_self_pos] @[simp] lemma abs_im_lt_abs {z : ℂ} : |z.im| < abs z ↔ z.re ≠ 0 := by simpa using @abs_re_lt_abs (z * I) /-- The **triangle inequality** for complex numbers. -/ lemma abs_add (z w : ℂ) : abs (z + w) ≤ abs z + abs w := (mul_self_le_mul_self_iff (abs_nonneg _) (add_nonneg (abs_nonneg _) (abs_nonneg _))).2 $ begin rw [mul_self_abs, add_mul_self_eq, mul_self_abs, mul_self_abs, add_right_comm, norm_sq_add, add_le_add_iff_left, mul_assoc, mul_le_mul_left (@zero_lt_two ℝ _ _)], simpa [-mul_re] using re_le_abs (z * conj w) end instance : is_absolute_value abs := { abv_nonneg := abs_nonneg, abv_eq_zero := λ _, abs_eq_zero, abv_add := abs_add, abv_mul := abs_mul } open is_absolute_value @[simp] lemma abs_abs (z : ℂ) : |(abs z)| = abs z := _root_.abs_of_nonneg (abs_nonneg _) @[simp] lemma abs_pos {z : ℂ} : 0 < abs z ↔ z ≠ 0 := abv_pos abs @[simp] lemma abs_neg : ∀ z, abs (-z) = abs z := abv_neg abs lemma abs_sub_comm : ∀ z w, abs (z - w) = abs (w - z) := abv_sub abs lemma abs_sub_le : ∀ a b c, abs (a - c) ≤ abs (a - b) + abs (b - c) := abv_sub_le abs @[simp] theorem abs_inv : ∀ z, abs z⁻¹ = (abs z)⁻¹ := abv_inv abs @[simp] theorem abs_div : ∀ z w, abs (z / w) = abs z / abs w := abv_div abs lemma abs_abs_sub_le_abs_sub : ∀ z w, |abs z - abs w| ≤ abs (z - w) := abs_abv_sub_le_abv_sub abs lemma abs_le_abs_re_add_abs_im (z : ℂ) : abs z ≤ |z.re| + |z.im| := by simpa [re_add_im] using abs_add z.re (z.im * I) lemma abs_le_sqrt_two_mul_max (z : ℂ) : abs z ≤ real.sqrt 2 * max (|z.re|) (|z.im|) := begin cases z with x y, simp only [abs, norm_sq_mk, ← sq], wlog hle : |x| ≤ |y| := le_total (|x|) (|y|) using [x y, y x] tactic.skip, { calc real.sqrt (x ^ 2 + y ^ 2) ≤ real.sqrt (y ^ 2 + y ^ 2) : real.sqrt_le_sqrt (add_le_add_right (sq_le_sq.2 hle) _) ... = real.sqrt 2 * max (|x|) (|y|) : by rw [max_eq_right hle, ← two_mul, real.sqrt_mul two_pos.le, real.sqrt_sq_eq_abs] }, { rwa [add_comm, max_comm] } end lemma abs_re_div_abs_le_one (z : ℂ) : |z.re / z.abs| ≤ 1 := if hz : z = 0 then by simp [hz, zero_le_one] else by { simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, abs_re_le_abs] } lemma abs_im_div_abs_le_one (z : ℂ) : |z.im / z.abs| ≤ 1 := if hz : z = 0 then by simp [hz, zero_le_one] else by { simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, abs_im_le_abs] } @[simp, norm_cast] lemma abs_cast_nat (n : ℕ) : abs (n : ℂ) = n := by rw [← of_real_nat_cast, abs_of_nonneg (nat.cast_nonneg n)] @[simp, norm_cast] lemma int_cast_abs (n : ℤ) : ↑|n| = abs n := by rw [← of_real_int_cast, abs_of_real, int.cast_abs] lemma norm_sq_eq_abs (x : ℂ) : norm_sq x = abs x ^ 2 := by rw [abs, sq, real.mul_self_sqrt (norm_sq_nonneg _)] /-- We put a partial order on ℂ so that `z ≤ w` exactly if `w - z` is real and nonnegative. Complex numbers with different imaginary parts are incomparable. -/ protected def partial_order : partial_order ℂ := { le := λ z w, z.re ≤ w.re ∧ z.im = w.im, lt := λ z w, z.re < w.re ∧ z.im = w.im, lt_iff_le_not_le := λ z w, by { dsimp, rw lt_iff_le_not_le, tauto }, le_refl := λ x, ⟨le_rfl, rfl⟩, le_trans := λ x y z h₁ h₂, ⟨h₁.1.trans h₂.1, h₁.2.trans h₂.2⟩, le_antisymm := λ z w h₁ h₂, ext (h₁.1.antisymm h₂.1) h₁.2 } section complex_order localized "attribute [instance] complex.partial_order" in complex_order lemma le_def {z w : ℂ} : z ≤ w ↔ z.re ≤ w.re ∧ z.im = w.im := iff.rfl lemma lt_def {z w : ℂ} : z < w ↔ z.re < w.re ∧ z.im = w.im := iff.rfl @[simp, norm_cast] lemma real_le_real {x y : ℝ} : (x : ℂ) ≤ (y : ℂ) ↔ x ≤ y := by simp [le_def] @[simp, norm_cast] lemma real_lt_real {x y : ℝ} : (x : ℂ) < (y : ℂ) ↔ x < y := by simp [lt_def] @[simp, norm_cast] lemma zero_le_real {x : ℝ} : (0 : ℂ) ≤ (x : ℂ) ↔ 0 ≤ x := real_le_real @[simp, norm_cast] lemma zero_lt_real {x : ℝ} : (0 : ℂ) < (x : ℂ) ↔ 0 < x := real_lt_real lemma not_le_iff {z w : ℂ} : ¬(z ≤ w) ↔ w.re < z.re ∨ z.im ≠ w.im := by rw [le_def, not_and_distrib, not_le] lemma not_lt_iff {z w : ℂ} : ¬(z < w) ↔ w.re ≤ z.re ∨ z.im ≠ w.im := by rw [lt_def, not_and_distrib, not_lt] lemma not_le_zero_iff {z : ℂ} : ¬z ≤ 0 ↔ 0 < z.re ∨ z.im ≠ 0 := not_le_iff lemma not_lt_zero_iff {z : ℂ} : ¬z < 0 ↔ 0 ≤ z.re ∨ z.im ≠ 0 := not_lt_iff /-- With `z ≤ w` iff `w - z` is real and nonnegative, `ℂ` is an ordered ring. -/ protected def ordered_comm_ring : ordered_comm_ring ℂ := { zero_le_one := ⟨zero_le_one, rfl⟩, add_le_add_left := λ w z h y, ⟨add_le_add_left h.1 _, congr_arg2 (+) rfl h.2⟩, mul_pos := λ z w hz hw, by simp [lt_def, mul_re, mul_im, ← hz.2, ← hw.2, mul_pos hz.1 hw.1], .. complex.partial_order, .. complex.comm_ring } localized "attribute [instance] complex.ordered_comm_ring" in complex_order /-- With `z ≤ w` iff `w - z` is real and nonnegative, `ℂ` is a star ordered ring. (That is, a star ring in which the nonnegative elements are those of the form `star z * z`.) -/ protected def star_ordered_ring : star_ordered_ring ℂ := { nonneg_iff := λ r, by { refine ⟨λ hr, ⟨real.sqrt r.re, _⟩, λ h, _⟩, { have h₁ : 0 ≤ r.re := by { rw [le_def] at hr, exact hr.1 }, have h₂ : r.im = 0 := by { rw [le_def] at hr, exact hr.2.symm }, ext, { simp only [of_real_im, star_def, of_real_re, sub_zero, conj_re, mul_re, mul_zero, ←real.sqrt_mul h₁ r.re, real.sqrt_mul_self h₁] }, { simp only [h₂, add_zero, of_real_im, star_def, zero_mul, conj_im, mul_im, mul_zero, neg_zero] } }, { obtain ⟨s, rfl⟩ := h, simp only [←norm_sq_eq_conj_mul_self, norm_sq_nonneg, zero_le_real, star_def] } }, ..complex.ordered_comm_ring } localized "attribute [instance] complex.star_ordered_ring" in complex_order end complex_order /-! ### Cauchy sequences -/ theorem is_cau_seq_re (f : cau_seq ℂ abs) : is_cau_seq abs' (λ n, (f n).re) := λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij, lt_of_le_of_lt (by simpa using abs_re_le_abs (f j - f i)) (H _ ij) theorem is_cau_seq_im (f : cau_seq ℂ abs) : is_cau_seq abs' (λ n, (f n).im) := λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij, lt_of_le_of_lt (by simpa using abs_im_le_abs (f j - f i)) (H _ ij) /-- The real part of a complex Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cau_seq_re (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_re f⟩ /-- The imaginary part of a complex Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cau_seq_im (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_im f⟩ lemma is_cau_seq_abs {f : ℕ → ℂ} (hf : is_cau_seq abs f) : is_cau_seq abs' (abs ∘ f) := λ ε ε0, let ⟨i, hi⟩ := hf ε ε0 in ⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩ /-- The limit of a Cauchy sequence of complex numbers. -/ noncomputable def lim_aux (f : cau_seq ℂ abs) : ℂ := ⟨cau_seq.lim (cau_seq_re f), cau_seq.lim (cau_seq_im f)⟩ theorem equiv_lim_aux (f : cau_seq ℂ abs) : f ≈ cau_seq.const abs (lim_aux f) := λ ε ε0, (exists_forall_ge_and (cau_seq.equiv_lim ⟨_, is_cau_seq_re f⟩ _ (half_pos ε0)) (cau_seq.equiv_lim ⟨_, is_cau_seq_im f⟩ _ (half_pos ε0))).imp $ λ i H j ij, begin cases H _ ij with H₁ H₂, apply lt_of_le_of_lt (abs_le_abs_re_add_abs_im _), dsimp [lim_aux] at *, have := add_lt_add H₁ H₂, rwa add_halves at this, end instance : cau_seq.is_complete ℂ abs := ⟨λ f, ⟨lim_aux f, equiv_lim_aux f⟩⟩ open cau_seq lemma lim_eq_lim_im_add_lim_re (f : cau_seq ℂ abs) : lim f = ↑(lim (cau_seq_re f)) + ↑(lim (cau_seq_im f)) * I := lim_eq_of_equiv_const $ calc f ≈ _ : equiv_lim_aux f ... = cau_seq.const abs (↑(lim (cau_seq_re f)) + ↑(lim (cau_seq_im f)) * I) : cau_seq.ext (λ _, complex.ext (by simp [lim_aux, cau_seq_re]) (by simp [lim_aux, cau_seq_im])) lemma lim_re (f : cau_seq ℂ abs) : lim (cau_seq_re f) = (lim f).re := by rw [lim_eq_lim_im_add_lim_re]; simp lemma lim_im (f : cau_seq ℂ abs) : lim (cau_seq_im f) = (lim f).im := by rw [lim_eq_lim_im_add_lim_re]; simp lemma is_cau_seq_conj (f : cau_seq ℂ abs) : is_cau_seq abs (λ n, conj (f n)) := λ ε ε0, let ⟨i, hi⟩ := f.2 ε ε0 in ⟨i, λ j hj, by rw [← ring_hom.map_sub, abs_conj]; exact hi j hj⟩ /-- The complex conjugate of a complex Cauchy sequence, as a complex Cauchy sequence. -/ noncomputable def cau_seq_conj (f : cau_seq ℂ abs) : cau_seq ℂ abs := ⟨_, is_cau_seq_conj f⟩ lemma lim_conj (f : cau_seq ℂ abs) : lim (cau_seq_conj f) = conj (lim f) := complex.ext (by simp [cau_seq_conj, (lim_re _).symm, cau_seq_re]) (by simp [cau_seq_conj, (lim_im _).symm, cau_seq_im, (lim_neg _).symm]; refl) /-- The absolute value of a complex Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cau_seq_abs (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_abs f.2⟩ lemma lim_abs (f : cau_seq ℂ abs) : lim (cau_seq_abs f) = abs (lim f) := lim_eq_of_equiv_const (λ ε ε0, let ⟨i, hi⟩ := equiv_lim f ε ε0 in ⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩) variables {α : Type*} (s : finset α) @[simp, norm_cast] lemma of_real_prod (f : α → ℝ) : ((∏ i in s, f i : ℝ) : ℂ) = ∏ i in s, (f i : ℂ) := ring_hom.map_prod of_real _ _ @[simp, norm_cast] lemma of_real_sum (f : α → ℝ) : ((∑ i in s, f i : ℝ) : ℂ) = ∑ i in s, (f i : ℂ) := ring_hom.map_sum of_real _ _ @[simp] lemma re_sum (f : α → ℂ) : (∑ i in s, f i).re = ∑ i in s, (f i).re := re_add_group_hom.map_sum f s @[simp] lemma im_sum (f : α → ℂ) : (∑ i in s, f i).im = ∑ i in s, (f i).im := im_add_group_hom.map_sum f s end complex
e69e3ecaa2c0456e3f974dc0bd2989cb8ebba7d7
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/limits/shapes/split_coequalizer.lean
1ea6d4372a4bbe64d0e79305b389d153b3719271
[ "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
5,648
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.shapes.equalizers /-! # Split coequalizers We define what it means for a triple of morphisms `f g : X ⟶ Y`, `π : Y ⟶ Z` to be a split coequalizer: there is a section `s` of `π` and a section `t` of `g`, which additionally satisfy `t ≫ f = π ≫ s`. In addition, we show that every split coequalizer is a coequalizer (`category_theory.is_split_coequalizer.is_coequalizer`) and absolute (`category_theory.is_split_coequalizer.map`) A pair `f g : X ⟶ Y` has a split coequalizer if there is a `Z` and `π : Y ⟶ Z` making `f,g,π` a split coequalizer. A pair `f g : X ⟶ Y` has a `G`-split coequalizer if `G f, G g` has a split coequalizer. These definitions and constructions are useful in particular for the monadicity theorems. ## TODO Dualise to split equalizers. -/ namespace category_theory universes v v₂ u u₂ variables {C : Type u} [category.{v} C] variables {D : Type u₂} [category.{v₂} D] variables (G : C ⥤ D) variables {X Y : C} (f g : X ⟶ Y) /-- A split coequalizer diagram consists of morphisms f π X ⇉ Y → Z g satisfying `f ≫ π = g ≫ π` together with morphisms t s X ← Y ← Z satisfying `s ≫ π = 𝟙 Z`, `t ≫ g = 𝟙 Y` and `t ≫ f = π ≫ s`. The name "coequalizer" is appropriate, since any split coequalizer is a coequalizer, see `category_theory.is_split_coequalizer.is_coequalizer`. Split coequalizers are also absolute, since a functor preserves all the structure above. -/ structure is_split_coequalizer {Z : C} (π : Y ⟶ Z) := (right_section : Z ⟶ Y) (left_section : Y ⟶ X) (condition : f ≫ π = g ≫ π) (right_section_π : right_section ≫ π = 𝟙 Z) (left_section_bottom : left_section ≫ g = 𝟙 Y) (left_section_top : left_section ≫ f = π ≫ right_section) instance {X : C} : inhabited (is_split_coequalizer (𝟙 X) (𝟙 X) (𝟙 X)) := ⟨⟨𝟙 _, 𝟙 _, rfl, category.id_comp _, category.id_comp _, rfl⟩⟩ open is_split_coequalizer attribute [reassoc] condition attribute [simp, reassoc] right_section_π left_section_bottom left_section_top variables {f g} /-- Split coequalizers are absolute: they are preserved by any functor. -/ @[simps] def is_split_coequalizer.map {Z : C} {π : Y ⟶ Z} (q : is_split_coequalizer f g π) (F : C ⥤ D) : is_split_coequalizer (F.map f) (F.map g) (F.map π) := { right_section := F.map q.right_section, left_section := F.map q.left_section, condition := by rw [←F.map_comp, q.condition, F.map_comp], right_section_π := by rw [←F.map_comp, q.right_section_π, F.map_id], left_section_bottom := by rw [←F.map_comp, q.left_section_bottom, F.map_id], left_section_top := by rw [←F.map_comp, q.left_section_top, F.map_comp] } section open limits /-- A split coequalizer clearly induces a cofork. -/ @[simps X] def is_split_coequalizer.as_cofork {Z : C} {h : Y ⟶ Z} (t : is_split_coequalizer f g h) : cofork f g := cofork.of_π h t.condition @[simp] lemma is_split_coequalizer.as_cofork_π {Z : C} {h : Y ⟶ Z} (t : is_split_coequalizer f g h) : t.as_cofork.π = h := rfl /-- The cofork induced by a split coequalizer is a coequalizer, justifying the name. In some cases it is more convenient to show a given cofork is a coequalizer by showing it is split. -/ def is_split_coequalizer.is_coequalizer {Z : C} {h : Y ⟶ Z} (t : is_split_coequalizer f g h) : is_colimit t.as_cofork := cofork.is_colimit.mk' _ $ λ s, ⟨t.right_section ≫ s.π, by { dsimp, rw [← t.left_section_top_assoc, s.condition, t.left_section_bottom_assoc] }, λ m hm, by { simp [←hm] }⟩ end variables (f g) /-- The pair `f,g` is a split pair if there is a `h : Y ⟶ Z` so that `f, g, h` forms a split coequalizer in `C`. -/ class has_split_coequalizer : Prop := (splittable [] : ∃ {Z : C} (h : Y ⟶ Z), nonempty (is_split_coequalizer f g h)) /-- The pair `f,g` is a `G`-split pair if there is a `h : G Y ⟶ Z` so that `G f, G g, h` forms a split coequalizer in `D`. -/ abbreviation functor.is_split_pair : Prop := has_split_coequalizer (G.map f) (G.map g) /-- Get the coequalizer object from the typeclass `is_split_pair`. -/ noncomputable def has_split_coequalizer.coequalizer_of_split [has_split_coequalizer f g] : C := (has_split_coequalizer.splittable f g).some /-- Get the coequalizer morphism from the typeclass `is_split_pair`. -/ noncomputable def has_split_coequalizer.coequalizer_π [has_split_coequalizer f g] : Y ⟶ has_split_coequalizer.coequalizer_of_split f g := (has_split_coequalizer.splittable f g).some_spec.some /-- The coequalizer morphism `coequalizer_ι` gives a split coequalizer on `f,g`. -/ noncomputable def has_split_coequalizer.is_split_coequalizer [has_split_coequalizer f g] : is_split_coequalizer f g (has_split_coequalizer.coequalizer_π f g) := classical.choice (has_split_coequalizer.splittable f g).some_spec.some_spec /-- If `f, g` is split, then `G f, G g` is split. -/ instance map_is_split_pair [has_split_coequalizer f g] : has_split_coequalizer (G.map f) (G.map g) := { splittable := ⟨_, _, ⟨is_split_coequalizer.map (has_split_coequalizer.is_split_coequalizer f g) _⟩⟩ } namespace limits /-- If a pair has a split coequalizer, it has a coequalizer. -/ @[priority 1] instance has_coequalizer_of_has_split_coequalizer [has_split_coequalizer f g] : has_coequalizer f g := has_colimit.mk ⟨_, (has_split_coequalizer.is_split_coequalizer f g).is_coequalizer⟩ end limits end category_theory
d7a9ea0b91496743099dadfbfe4d0417c5aa2542
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/group_theory/sylow.lean
a8daa7014ea6bc954b93402eca28ac0857679619
[ "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
13,257
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import group_theory.group_action import group_theory.quotient_group import group_theory.order_of_element import data.zmod.basic import data.fintype.card import data.list.rotate /-! # Sylow theorems The Sylow theorems are the following results for every finite group `G` and every prime number `p`. * There exists a Sylow `p`-subgroup of `G`. * All Sylow `p`-subgroups of `G` are conjugate to each other. * Let `nₚ` be the number of Sylow `p`-subgroups of `G`, then `nₚ` divides the index of the Sylow `p`-subgroup, `nₚ ≡ 1 [MOD p]`, and `nₚ` is equal to the index of the normalizer of the Sylow `p`-subgroup in `G`. In this file, currently only the first of these results is proven. ## Main statements * `exists_prime_order_of_dvd_card`: For every prime `p` dividing the order of `G` there exists an element of order `p` in `G`. This is known as Cauchy`s theorem. * `exists_subgroup_card_pow_prime`: A generalisation of the first of the Sylow theorems: For every prime power `pⁿ` dividing `G`, there exists a subgroup of `G` of order `pⁿ`. ## TODO * Prove the second and third of the Sylow theorems. * Sylow theorems for infinite groups -/ open equiv fintype finset mul_action function open equiv.perm subgroup list quotient_group open_locale big_operators universes u v w variables {G : Type u} {α : Type v} {β : Type w} [group G] local attribute [instance, priority 10] subtype.fintype set_fintype classical.prop_decidable namespace mul_action variables [mul_action G α] lemma mem_fixed_points_iff_card_orbit_eq_one {a : α} [fintype (orbit G a)] : a ∈ fixed_points G α ↔ card (orbit G a) = 1 := begin rw [fintype.card_eq_one_iff, mem_fixed_points], split, { exact λ h, ⟨⟨a, mem_orbit_self _⟩, λ ⟨b, ⟨x, hx⟩⟩, subtype.eq $ by simp [h x, hx.symm]⟩ }, { assume h x, rcases h with ⟨⟨z, hz⟩, hz₁⟩, exact calc x • a = z : subtype.mk.inj (hz₁ ⟨x • a, mem_orbit _ _⟩) ... = a : (subtype.mk.inj (hz₁ ⟨a, mem_orbit_self _⟩)).symm } end lemma card_modeq_card_fixed_points [fintype α] [fintype G] [fintype (fixed_points G α)] (p : ℕ) {n : ℕ} [hp : fact p.prime] (h : card G = p ^ n) : card α ≡ card (fixed_points G α) [MOD p] := calc card α = card (Σ y : quotient (orbit_rel G α), {x // quotient.mk' x = y}) : card_congr (sigma_preimage_equiv (@quotient.mk' _ (orbit_rel G α))).symm ... = ∑ a : quotient (orbit_rel G α), card {x // quotient.mk' x = a} : card_sigma _ ... ≡ ∑ a : fixed_points G α, 1 [MOD p] : begin rw [← zmod.eq_iff_modeq_nat p, sum_nat_cast, sum_nat_cast], refine eq.symm (sum_bij_ne_zero (λ a _ _, quotient.mk' a.1) (λ _ _ _, mem_univ _) (λ a₁ a₂ _ _ _ _ h, subtype.eq ((mem_fixed_points' α).1 a₂.2 a₁.1 (quotient.exact' h))) (λ b, _) (λ a ha _, by rw [← mem_fixed_points_iff_card_orbit_eq_one.1 a.2]; simp only [quotient.eq']; congr)), { refine quotient.induction_on' b (λ b _ hb, _), have : card (orbit G b) ∣ p ^ n, { rw [← h, fintype.card_congr (orbit_equiv_quotient_stabilizer G b)], exact card_quotient_dvd_card _ }, rcases (nat.dvd_prime_pow hp.1).1 this with ⟨k, _, hk⟩, have hb' :¬ p ^ 1 ∣ p ^ k, { rw [pow_one, ← hk, ← nat.modeq.modeq_zero_iff, ← zmod.eq_iff_modeq_nat, nat.cast_zero, ← ne.def], exact eq.mpr (by simp only [quotient.eq']; congr) hb }, have : k = 0 := nat.le_zero_iff.1 (nat.le_of_lt_succ (lt_of_not_ge (mt (pow_dvd_pow p) hb'))), refine ⟨⟨b, mem_fixed_points_iff_card_orbit_eq_one.2 $ by rw [hk, this, pow_zero]⟩, mem_univ _, _, rfl⟩, rw [nat.cast_one], exact one_ne_zero } end ... = _ : by simp; refl end mul_action lemma quotient_group.card_preimage_mk [fintype G] (s : subgroup G) (t : set (quotient s)) : fintype.card (quotient_group.mk ⁻¹' t) = fintype.card s * fintype.card t := by rw [← fintype.card_prod, fintype.card_congr (preimage_mk_equiv_subgroup_times_set _ _)] namespace sylow /-- Given a vector `v` of length `n`, make a vector of length `n+1` whose product is `1`, by consing the the inverse of the product of `v`. -/ def mk_vector_prod_eq_one (n : ℕ) (v : vector G n) : vector G (n+1) := v.to_list.prod⁻¹ ::ᵥ v lemma mk_vector_prod_eq_one_injective (n : ℕ) : injective (@mk_vector_prod_eq_one G _ n) := λ ⟨v, _⟩ ⟨w, _⟩ h, subtype.eq (show v = w, by injection h with h; injection h) /-- The type of vectors with terms from `G`, length `n`, and product equal to `1:G`. -/ def vectors_prod_eq_one (G : Type*) [group G] (n : ℕ) : set (vector G n) := {v | v.to_list.prod = 1} lemma mem_vectors_prod_eq_one {n : ℕ} (v : vector G n) : v ∈ vectors_prod_eq_one G n ↔ v.to_list.prod = 1 := iff.rfl lemma mem_vectors_prod_eq_one_iff {n : ℕ} (v : vector G (n + 1)) : v ∈ vectors_prod_eq_one G (n + 1) ↔ v ∈ set.range (@mk_vector_prod_eq_one G _ n) := ⟨λ (h : v.to_list.prod = 1), ⟨v.tail, begin unfold mk_vector_prod_eq_one, conv {to_rhs, rw ← vector.cons_head_tail v}, suffices : (v.tail.to_list.prod)⁻¹ = v.head, { rw this }, rw [← mul_left_inj v.tail.to_list.prod, inv_mul_self, ← list.prod_cons, ← vector.to_list_cons, vector.cons_head_tail, h] end⟩, λ ⟨w, hw⟩, by rw [mem_vectors_prod_eq_one, ← hw, mk_vector_prod_eq_one, vector.to_list_cons, list.prod_cons, inv_mul_self]⟩ /-- The rotation action of `zmod n` (viewed as multiplicative group) on `vectors_prod_eq_one G n`, where `G` is a multiplicative group. -/ def rotate_vectors_prod_eq_one (G : Type*) [group G] (n : ℕ) (m : multiplicative (zmod n)) (v : vectors_prod_eq_one G n) : vectors_prod_eq_one G n := ⟨⟨v.1.to_list.rotate m.val, by simp⟩, prod_rotate_eq_one_of_prod_eq_one v.2 _⟩ instance rotate_vectors_prod_eq_one.mul_action (n : ℕ) [fact (0 < n)] : mul_action (multiplicative (zmod n)) (vectors_prod_eq_one G n) := { smul := (rotate_vectors_prod_eq_one G n), one_smul := begin intro v, apply subtype.eq, apply vector.eq _ _, show rotate _ (0 : zmod n).val = _, rw zmod.val_zero, exact rotate_zero v.1.to_list end, mul_smul := λ a b ⟨⟨v, hv₁⟩, hv₂⟩, subtype.eq $ vector.eq _ _ $ show v.rotate ((a + b : zmod n).val) = list.rotate (list.rotate v (b.val)) (a.val), by rw [zmod.val_add, rotate_rotate, ← rotate_mod _ (b.val + a.val), add_comm, hv₁] } lemma one_mem_vectors_prod_eq_one (n : ℕ) : vector.repeat (1 : G) n ∈ vectors_prod_eq_one G n := by simp [vector.repeat, vectors_prod_eq_one] lemma one_mem_fixed_points_rotate (n : ℕ) [fact (0 < n)] : (⟨vector.repeat (1 : G) n, one_mem_vectors_prod_eq_one n⟩ : vectors_prod_eq_one G n) ∈ fixed_points (multiplicative (zmod n)) (vectors_prod_eq_one G n) := λ m, subtype.eq $ vector.eq _ _ $ rotate_eq_self_iff_eq_repeat.2 ⟨(1 : G), show list.repeat (1 : G) n = list.repeat 1 (list.repeat (1 : G) n).length, by simp⟩ _ /-- Cauchy's theorem -/ lemma exists_prime_order_of_dvd_card [fintype G] (p : ℕ) [hp : fact p.prime] (hdvd : p ∣ card G) : ∃ x : G, order_of x = p := let n : ℕ+ := ⟨p - 1, nat.sub_pos_of_lt hp.1.one_lt⟩ in have hn : p = n + 1 := nat.succ_sub hp.1.pos, have hcard : card (vectors_prod_eq_one G (n + 1)) = card G ^ (n : ℕ), by rw [set.ext mem_vectors_prod_eq_one_iff, set.card_range_of_injective (mk_vector_prod_eq_one_injective _), card_vector], have hzmod : fintype.card (multiplicative (zmod p)) = p ^ 1, by { rw pow_one p, exact zmod.card p }, have hmodeq : _ = _ := @mul_action.card_modeq_card_fixed_points (multiplicative (zmod p)) (vectors_prod_eq_one G p) _ _ _ _ _ _ 1 hp hzmod, have hdvdcard : p ∣ fintype.card (vectors_prod_eq_one G (n + 1)) := calc p ∣ card G ^ 1 : by rwa pow_one ... ∣ card G ^ (n : ℕ) : pow_dvd_pow _ n.2 ... = card (vectors_prod_eq_one G (n + 1)) : hcard.symm, have hdvdcard₂ : p ∣ card (fixed_points (multiplicative (zmod p)) (vectors_prod_eq_one G p)), by { rw nat.dvd_iff_mod_eq_zero at hdvdcard ⊢, rwa [← hn, hmodeq] at hdvdcard }, have hcard_pos : 0 < card (fixed_points (multiplicative (zmod p)) (vectors_prod_eq_one G p)) := fintype.card_pos_iff.2 ⟨⟨⟨vector.repeat 1 p, one_mem_vectors_prod_eq_one _⟩, one_mem_fixed_points_rotate _⟩⟩, have hlt : 1 < card (fixed_points (multiplicative (zmod p)) (vectors_prod_eq_one G p)) := calc (1 : ℕ) < p : hp.1.one_lt ... ≤ _ : nat.le_of_dvd hcard_pos hdvdcard₂, let ⟨⟨⟨⟨x, hx₁⟩, hx₂⟩, hx₃⟩, hx₄⟩ := fintype.exists_ne_of_one_lt_card hlt ⟨_, one_mem_fixed_points_rotate p⟩ in have hx : x ≠ list.repeat (1 : G) p, from λ h, by simpa [h, vector.repeat] using hx₄, have ∃ a, x = list.repeat a x.length := by exactI rotate_eq_self_iff_eq_repeat.1 (λ n, have list.rotate x (n : zmod p).val = x := subtype.mk.inj (subtype.mk.inj (hx₃ (n : zmod p))), by rwa [zmod.val_nat_cast, ← hx₁, rotate_mod] at this), let ⟨a, ha⟩ := this in ⟨a, have hx1 : x.prod = 1 := hx₂, have ha1: a ≠ 1, from λ h, hx (ha.symm ▸ h ▸ hx₁ ▸ rfl), have a ^ p = 1, by rwa [ha, list.prod_repeat, hx₁] at hx1, (hp.1.2 _ (order_of_dvd_of_pow_eq_one this)).resolve_left (λ h, ha1 (order_of_eq_one_iff.1 h))⟩ open subgroup submonoid is_group_hom mul_action lemma mem_fixed_points_mul_left_cosets_iff_mem_normalizer {H : subgroup G} [fintype ((H : set G) : Type u)] {x : G} : (x : quotient H) ∈ fixed_points H (quotient H) ↔ x ∈ normalizer H := ⟨λ hx, have ha : ∀ {y : quotient H}, y ∈ orbit H (x : quotient H) → y = x, from λ _, ((mem_fixed_points' _).1 hx _), (inv_mem_iff _).1 (@mem_normalizer_fintype _ _ _ _inst_2 _ (λ n (hn : n ∈ H), have (n⁻¹ * x)⁻¹ * x ∈ H := quotient_group.eq.1 (ha (mem_orbit _ ⟨n⁻¹, H.inv_mem hn⟩)), show _ ∈ H, by {rw [mul_inv_rev, inv_inv] at this, convert this, rw inv_inv} )), λ (hx : ∀ (n : G), n ∈ H ↔ x * n * x⁻¹ ∈ H), (mem_fixed_points' _).2 $ λ y, quotient.induction_on' y $ λ y hy, quotient_group.eq.2 (let ⟨⟨b, hb₁⟩, hb₂⟩ := hy in have hb₂ : (b * x)⁻¹ * y ∈ H := quotient_group.eq.1 hb₂, (inv_mem_iff H).1 $ (hx _).2 $ (mul_mem_cancel_left H (H.inv_mem hb₁)).1 $ by rw hx at hb₂; simpa [mul_inv_rev, mul_assoc] using hb₂)⟩ def fixed_points_mul_left_cosets_equiv_quotient (H : subgroup G) [fintype (H : set G)] : fixed_points H (quotient H) ≃ quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H) := @subtype_quotient_equiv_quotient_subtype G (normalizer H : set G) (id _) (id _) (fixed_points _ _) (λ a, (@mem_fixed_points_mul_left_cosets_iff_mem_normalizer _ _ _ _inst_2 _).symm) (by intros; refl) /-- The first of the Sylow theorems. -/ theorem exists_subgroup_card_pow_prime [fintype G] (p : ℕ) : ∀ {n : ℕ} [hp : fact p.prime] (hdvd : p ^ n ∣ card G), ∃ H : subgroup G, fintype.card H = p ^ n | 0 := λ _ _, ⟨(⊥ : subgroup G), by convert card_bot⟩ | (n+1) := λ hp hdvd, let ⟨H, hH2⟩ := @exists_subgroup_card_pow_prime _ hp (dvd.trans (pow_dvd_pow _ (nat.le_succ _)) hdvd) in let ⟨s, hs⟩ := exists_eq_mul_left_of_dvd hdvd in have hcard : card (quotient H) = s * p := (nat.mul_left_inj (show card H > 0, from fintype.card_pos_iff.2 ⟨⟨1, H.one_mem⟩⟩)).1 (by rwa [← card_eq_card_quotient_mul_card_subgroup H, hH2, hs, pow_succ', mul_assoc, mul_comm p]), have hm : s * p % p = card (quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H)) % p := card_congr (fixed_points_mul_left_cosets_equiv_quotient H) ▸ hcard ▸ @card_modeq_card_fixed_points _ _ _ _ _ _ _ p _ hp hH2, have hm' : p ∣ card (quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H)) := nat.dvd_of_mod_eq_zero (by rwa [nat.mod_eq_zero_of_dvd (dvd_mul_left _ _), eq_comm] at hm), let ⟨x, hx⟩ := @exists_prime_order_of_dvd_card _ (quotient_group.quotient.group _) _ _ hp hm' in have hequiv : H ≃ (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H) := ⟨λ a, ⟨⟨a.1, le_normalizer a.2⟩, a.2⟩, λ a, ⟨a.1.1, a.2⟩, λ ⟨_, _⟩, rfl, λ ⟨⟨_, _⟩, _⟩, rfl⟩, -- begin proof of ∃ H : subgroup G, fintype.card H = p ^ n ⟨subgroup.map ((normalizer H).subtype) (subgroup.comap (quotient_group.mk' (comap H.normalizer.subtype H)) (gpowers x)), begin show card ↥(map H.normalizer.subtype (comap (mk' (comap H.normalizer.subtype H)) (subgroup.gpowers x))) = p ^ (n + 1), suffices : card ↥(subtype.val '' ((subgroup.comap (mk' (comap H.normalizer.subtype H)) (gpowers x)) : set (↥(H.normalizer)))) = p^(n+1), { convert this using 2 }, rw [set.card_image_of_injective (subgroup.comap (mk' (comap H.normalizer.subtype H)) (gpowers x) : set (H.normalizer)) subtype.val_injective, pow_succ', ← hH2, fintype.card_congr hequiv, ← hx, order_eq_card_gpowers, ← fintype.card_prod], exact @fintype.card_congr _ _ (id _) (id _) (preimage_mk_equiv_subgroup_times_set _ _) end⟩ end sylow
b4812c50a9391b52343d3db8d4ca6e3bfdd11ba9
4034f8da6f54c838133a7ab6a8c0c61086c9c949
/src/gluing.lean
395fadd03ea521c3b17876849179935cd931d587
[]
no_license
mguaypaq/lean-topology
f9e6c69e2b85cca1377ee89d75c65bd384225170
57b15b3862d441095e254e65009856fa922758cc
refs/heads/main
1,691,451,271,943
1,631,647,691,000
1,631,647,691,000
398,682,545
0
0
null
null
null
null
UTF-8
Lean
false
false
9,626
lean
import tactic import .topology noncomputable theory section cover -- cover of a set structure cover (I X : Type) := (part : I → set X) (hx : ∀ (x : X), ∃ (i : I), x ∈ part i) -- coercion so we can write "U i" when (U : cover I X) and (i : I) instance cover_to_parts (I X : Type) : has_coe_to_fun (cover I X) := {F := λ _, I → set X, coe := λ U, U.part} lemma cover_set_eq {I X : Type} (U : cover I X) (A : set X) : A = ⋃₀ {A' | ∃ j, A' = (U j) ∩ A} := begin ext a, split; intro ha, obtain ⟨i, hi⟩ := U.hx a, use (U i) ∩ A, exact ⟨⟨i, rfl⟩, hi, ha⟩, obtain ⟨A', ⟨j, hj⟩, hA''⟩ := ha, rw hj at hA'', exact hA''.2, end example {X Y : Type} (f : X → Y) (U : set Y) : set.preimage f U → U := λ x, ⟨f x.val, x.prop⟩ example {X Y : Type} (f : X → Y) : X → f '' set.univ := λ x, ⟨f x, ⟨x, trivial, rfl⟩⟩ -- consistent functions on each part of the cover structure gluing_data (I X Y : Type) := (U : cover I X) (f : Π (i : I), U i → Y) (hglue : ∀ (i j : I) (x : X) (hxi : x ∈ U i) (hxj : x ∈ U j), (f i) ⟨x, hxi⟩ = (f j) ⟨x, hxj⟩) -- what it means for f : X → Y to be compatible with gluing data def compatible {I X Y : Type} (gl : gluing_data I X Y) (f : X → Y) := ∀ (i : I) (x : X) (hxi : x ∈ gl.U i), f x = gl.f i ⟨x, hxi⟩ lemma compatible_iff_restrict_eq {I X Y : Type} (gl : gluing_data I X Y) {f : X → Y} : compatible gl f ↔ ∀ (i : I), subtype.restrict f _ = gl.f i := begin split; intros hf i, specialize hf i, ext ⟨x, hx⟩, rw subtype.restrict_apply, exact hf x hx, intros x hx, rw ← hf, rw subtype.restrict_apply, end -- existence of compatible function -- (uses choice, even though the result is unique) def mk_function {I X Y : Type} (gl : gluing_data I X Y) : X → Y := λ x, let ⟨i, hxi⟩ := classical.subtype_of_exists (gl.U.hx x) in gl.f i ⟨x, hxi⟩ lemma mk_compatible {I X Y} (gl : @gluing_data I X Y) : compatible gl (mk_function gl) := begin intros i x hxi, let j := classical.subtype_of_exists (gl.U.hx x), exact gl.hglue j.val i x j.prop hxi, end lemma compatible_unique {I X Y : Type} (gl : @gluing_data I X Y) (f g : X → Y) : compatible gl f → compatible gl g → f = g := begin intros hf hg, ext, obtain ⟨i, hxi⟩ := gl.U.hx x, specialize hf i x hxi, specialize hg i x hxi, rwa [hf, hg], end section refine @[reducible] def pullback_cover {I X Y : Type} (f : X → Y) (U : cover I Y) : cover I X := ⟨ λ i, f ⁻¹' (U i), λ x, U.hx (f x)⟩ infix `⁻¹c`:110 := pullback_cover lemma pullback_cover.comp {I X Y Z : Type} (f : X → Y) (g : Y → Z) (U : cover I Z) : (g ∘ f) ⁻¹c U = f ⁻¹c (g ⁻¹c U) := by split variables (I J X Y : Type) (CI : cover I X) (CJ : cover J X) (gl : gluing_data I X Y) def refine : cover (I × J) X := ⟨λ ij, (CI.part ij.1) ∩ (CJ.part ij.2), λ x, let ⟨i, hxi⟩ := CI.hx x in let ⟨j, hxj⟩ := CJ.hx x in ⟨⟨i, j⟩, ⟨hxi, hxj⟩⟩⟩ /- Note: this is asymmetric: f is defined on Uᵢ ∩ Vⱼ as the restriction of f from Uᵢ, not Vⱼ. -/ def gl_refine : gluing_data (I × J) X Y := ⟨ -- U, f, hglue refine I J X gl.U CJ, -- U λ ⟨i, j⟩ ⟨x, hxij⟩, gl.f i ⟨x, hxij.left⟩, λ ⟨i₁, j₁⟩ ⟨i₂, j₂⟩ x ⟨hxi₁, hxj₁⟩ ⟨hxi₂, hxj₂⟩, gl.hglue i₁ i₂ x hxi₁ hxi₂, ⟩ lemma compat_of_refine_of_compat (f : X → Y) : compatible gl f → compatible (gl_refine _ _ _ _ CJ gl) f := begin rintros hf ⟨i, j⟩ x ⟨hxi, hxj⟩, exact hf i x hxi, end end refine end cover section open_cover open topology --(@pullback J E' B π' V) structure open_cover (I X : Type) [topology X] extends (cover I X) := (hopen : ∀ (i : I), part i ∈ opens X) instance (I X : Type) [topology X] : has_coe (open_cover I X) (cover I X) := ⟨λ U, ⟨U.part, U.hx⟩⟩ structure cts_gluing_data (I X Y : Type) [topology X] [topology Y] := (U : open_cover I X) (f : Π (i : I), (U i) → Y) (hglue : ∀ (i j : I) (x : X) (hxi : x ∈ U i) (hxj : x ∈ U j), (f i) ⟨x, hxi⟩ = (f j) ⟨x, hxj⟩) (hf : Π (i : I), cts (f i)) instance (I X Y : Type) [topology X] [topology Y] : has_coe (cts_gluing_data I X Y) (gluing_data I X Y) := ⟨λ gl, ⟨gl.U, gl.f, gl.hglue⟩⟩ variables {I X : Type} [topology X] lemma subset_open_iff_open_cover (U : open_cover I X) (A : set X) : A ∈ opens X ↔ ∀ (i : I), (U i) ∩ A ∈ opens X := begin split, intros hA i, apply inter₂ _ _ (U.hopen i) hA, intro hA, rw cover_set_eq U.to_cover A, apply union, rintros A' ⟨i, hi⟩, rw hi, exact hA i, end def open_cover.refine {J : Type} (CI : open_cover I X) (CJ : open_cover J X) : open_cover (I × J) X := { part := (refine I J X CI CJ).part, hx := (refine I J X CI CJ).hx, hopen := λ ⟨i, j⟩, inter₂ _ _ (CI.hopen i) (CJ.hopen j), } /- ⟨λ ⟨i, j⟩, (CI i) ∩ (CJ j), λ x, let ⟨i, hxi⟩ := CI.to_cover.hx x.1 in let ⟨j, hxj⟩ := CJ.to_cover.hx x.2 in ⟨⟨i, j⟩, ⟨hxi, hxj⟩⟩⟩ -/ variables {Y : Type} [topology Y] (U : open_cover I X) (gl : cts_gluing_data I X Y) (f g : X → Y) @[reducible] def pullback_open_cover (hf : cts f) (U : open_cover I Y) : open_cover I X := ⟨ pullback_cover f ↑U, λ i, hf _ (U.hopen i)⟩ lemma cts_iff_cts_on_cover (f : X → Y) : cts f ↔ Π (i : I), @cts _ _ (subspace_topology (U i)) _ (subtype.restrict f (U i)) := begin split, intros hf i, apply pullback_cts_along_inverse_image, exact hf, intro hfi, -- check continuity pointwise, then on a piece of the cover rw cts_iff_ptwise_cts, intro x, obtain ⟨i, hxi⟩ := U.hx x, specialize hfi i, rw cts_iff_ptwise_cts at hfi, specialize hfi ⟨x, hxi⟩, rwa cts_at_pt_of_open f (U i) (U.hopen i) x hxi, end -- function compatible with cts gluing data is cts -- (mostly equivalent to cts_iff_cts_on_cover) lemma cts_of_cts_compat : compatible (gl : gluing_data I X Y) f → cts f := begin intro hf, rw cts_iff_cts_on_cover gl.U, rw compatible_iff_restrict_eq at hf, intro i, specialize hf i, convert gl.hf i, end -- the glued function is continuous! 🎉 lemma mk_function_cts : cts (mk_function (gl : gluing_data I X Y)) := cts_of_cts_compat gl (mk_function (gl : gluing_data I X Y)) (mk_compatible ↑gl) end open_cover -- an attempt at doing covers using maps rather than subsets section b_cover structure b_cover (I X : Type) := (part : I → Type) (map : Π {i : I}, (part i) → X) (hx : ∀ (x : X), ∃ i (u : part i), map u = x) instance b_cover_to_parts (I X : Type) : has_coe_to_fun (b_cover I X) := {F := λ _, I → Type, coe := λ U, U.part} def to_fun {I X : Type} (U : b_cover I X) (i : I) : U i → X := λ x, U.map x structure b_cover₂ (I X : Type) extends (b_cover I X) := (part₂ : I → I → Type) (map₂l : Π {i j : I}, (part₂ i j) → part i) (map₂r : Π {i j : I}, (part₂ i j) → part j) (compat₂ : Π {i j : I} (u_ij : part₂ i j), map (map₂l u_ij) = map (map₂r u_ij)) (hx₂ : ∀ {i j : I} {u_i : part i} {u_j : part j}, map u_i = map u_j ↔ ∃ u_ij, map₂l u_ij = u_i ∧ map₂r u_ij = u_j) -- consistent functions on each part of the cover structure b_gluing_data (I X Y : Type) extends (b_cover₂ I X) := (f : Π {i : I}, part i → Y) (hglue : ∀ {i j : I} (u : part₂ i j), f (map₂l u) = f (map₂r u)) -- what it means for f : X → Y to be compatible with gluing data def b_compatible {I X Y : Type} (gl : b_gluing_data I X Y) (f : X → Y) := ∀ {i : I} (u : gl.part i), f (gl.map u) = gl.f u -- existence of compatible function -- (uses choice, even though the result is unique) def b_mk_function {I X Y : Type} (gl : b_gluing_data I X Y) : X → Y := λ x, let hi := classical.some_spec (gl.hx x) in let u := classical.some hi in gl.f u lemma b_mk_compatible {I X Y} (gl : b_gluing_data I X Y) : b_compatible gl (b_mk_function gl) := begin intros i v, let hi := classical.some_spec (gl.hx (gl.map v)), let u := classical.some hi, let hu := classical.some_spec hi, rw gl.hx₂ at hu, change gl.f u = gl.f v, obtain ⟨uij, hl, hr⟩ := hu, change gl.map₂l uij = u at hl, have key := gl.hglue uij, rwa [hl, hr] at key, end lemma b_compatible_unique {I X Y : Type} (gl : b_gluing_data I X Y) (f g : X → Y) : b_compatible gl f → b_compatible gl g → f = g := begin intros hf hg, ext, obtain ⟨i, ⟨u, hu⟩⟩ := gl.hx x, specialize hf u, specialize hg u, rw hu at *, rwa [hf, hg], end section b_refine variables (I J X Y : Type) (CI : b_cover I X) (CJ : b_cover J X) (gl : b_gluing_data I X Y) def b_refine : b_cover (I × J) X := ⟨λ ⟨i, j⟩, {uv : CI i × CJ j // CI.map uv.fst = CJ.map uv.snd}, λ ⟨i, j⟩ ⟨uv, h⟩, CI.map uv.fst, begin intro x, obtain ⟨i, ⟨u, hu⟩⟩ := CI.hx x, obtain ⟨j, ⟨v, hv⟩⟩ := CJ.hx x, use ⟨i, j⟩, use ⟨u, v⟩, rwa [hu, hv], end⟩ /- Note: this is asymmetric: f is defined on Uᵢ ∩ Vⱼ as the restriction of f from Uᵢ, not Vⱼ. -/ def b_gl_refine : b_gluing_data (I × J) X Y := sorry /- ⟨ -- U, f, hglue b_refine I J X CI CJ, -- U λ ⟨i, j⟩ ⟨x, hxij⟩, gl.f i ⟨x, hxij.left⟩, λ ⟨i₁, j₁⟩ ⟨i₂, j₂⟩ x ⟨hxi₁, hxj₁⟩ ⟨hxi₂, hxj₂⟩, gl.hglue i₁ i₂ x hxi₁ hxi₂, ⟩ -/ end b_refine end b_cover
cf80c4086604dc370bef78bda5276eab4733408d
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/limits/shapes/products_auto.lean
8e2e0ed15721d36cb1f5c2e4ab2ec00df2fb63c5
[]
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,819
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.limits.limits import Mathlib.category_theory.discrete_category import Mathlib.PostPort universes v u u_1 u₂ namespace Mathlib namespace category_theory.limits -- We don't need an analogue of `pair` (for binary products), `parallel_pair` (for equalizers), -- or `(co)span`, since we already have `discrete.functor`. /-- A fan over `f : β → C` consists of a collection of maps from an object `P` to every `f b`. -/ /-- A cofan over `f : β → C` consists of a collection of maps from every `f b` to an object `P`. -/ def fan {β : Type v} {C : Type u} [category C] (f : β → C) := cone (discrete.functor f) def cofan {β : Type v} {C : Type u} [category C] (f : β → C) := cocone (discrete.functor f) /-- A fan over `f : β → C` consists of a collection of maps from an object `P` to every `f b`. -/ @[simp] theorem fan.mk_X {β : Type v} {C : Type u} [category C] {f : β → C} (P : C) (p : (b : β) → P ⟶ f b) : cone.X (fan.mk P p) = P := Eq.refl (cone.X (fan.mk P p)) /-- A cofan over `f : β → C` consists of a collection of maps from every `f b` to an object `P`. -/ @[simp] theorem cofan.mk_X {β : Type v} {C : Type u} [category C] {f : β → C} (P : C) (p : (b : β) → f b ⟶ P) : cocone.X (cofan.mk P p) = P := Eq.refl (cocone.X (cofan.mk P p)) /-- An abbreviation for `has_limit (discrete.functor f)`. -/ def has_product {β : Type v} {C : Type u} [category C] (f : β → C) := has_limit (discrete.functor f) /-- An abbreviation for `has_colimit (discrete.functor f)`. -/ def has_coproduct {β : Type v} {C : Type u} [category C] (f : β → C) := has_colimit (discrete.functor f) /-- An abbreviation for `has_limits_of_shape (discrete f)`. -/ /-- An abbreviation for `has_colimits_of_shape (discrete f)`. -/ def has_products_of_shape (β : Type v) (C : Type u_1) [category C] := has_limits_of_shape (discrete β) def has_coproducts_of_shape (β : Type v) (C : Type u_1) [category C] := has_colimits_of_shape (discrete β) /-- `pi_obj f` computes the product of a family of elements `f`. (It is defined as an abbreviation for `limit (discrete.functor f)`, so for most facts about `pi_obj f`, you will just use general facts about limits.) -/ /-- `sigma_obj f` computes the coproduct of a family of elements `f`. (It is defined as an abbreviation def pi_obj {β : Type v} {C : Type u} [category C] (f : β → C) [has_product f] : C := limit (discrete.functor f) for `colimit (discrete.functor f)`, so for most facts about `sigma_obj f`, you will just use general facts about colimits.) -/ def sigma_obj {β : Type v} {C : Type u} [category C] (f : β → C) [has_coproduct f] : C := colimit (discrete.functor f) prefix:20 "∏ " => Mathlib.category_theory.limits.pi_obj prefix:20 "∐ " => Mathlib.category_theory.limits.sigma_obj /-- The `b`-th projection from the pi object over `f` has the form `∏ f ⟶ f b`. -/ def pi.π {β : Type v} {C : Type u} [category C] (f : β → C) [has_product f] (b : β) : ∏ f ⟶ f b := limit.π (discrete.functor f) b /-- The `b`-th inclusion into the sigma object over `f` has the form `f b ⟶ ∐ f`. -/ def sigma.ι {β : Type v} {C : Type u} [category C] (f : β → C) [has_coproduct f] (b : β) : f b ⟶ ∐ f := colimit.ι (discrete.functor f) b /-- The fan constructed of the projections from the product is limiting. -/ def product_is_product {β : Type v} {C : Type u} [category C] (f : β → C) [has_product f] : is_limit (fan.mk (∏ f) (pi.π f)) := is_limit.of_iso_limit (limit.is_limit (discrete.functor f)) (cones.ext (iso.refl (cone.X (limit.cone (discrete.functor fun (b : β) => f b)))) sorry) /-- A collection of morphisms `P ⟶ f b` induces a morphism `P ⟶ ∏ f`. -/ def pi.lift {β : Type v} {C : Type u} [category C] {f : β → C} [has_product f] {P : C} (p : (b : β) → P ⟶ f b) : P ⟶ ∏ f := limit.lift (discrete.functor fun (b : β) => f b) (fan.mk P p) /-- A collection of morphisms `f b ⟶ P` induces a morphism `∐ f ⟶ P`. -/ def sigma.desc {β : Type v} {C : Type u} [category C] {f : β → C} [has_coproduct f] {P : C} (p : (b : β) → f b ⟶ P) : ∐ f ⟶ P := colimit.desc (discrete.functor fun (b : β) => f b) (cofan.mk P p) /-- Construct a morphism between categorical products (indexed by the same type) from a family of morphisms between the factors. -/ def pi.map {β : Type v} {C : Type u} [category C] {f : β → C} {g : β → C} [has_product f] [has_product g] (p : (b : β) → f b ⟶ g b) : ∏ f ⟶ ∏ g := lim_map (discrete.nat_trans p) /-- Construct an isomorphism between categorical products (indexed by the same type) from a family of isomorphisms between the factors. -/ def pi.map_iso {β : Type v} {C : Type u} [category C] {f : β → C} {g : β → C} [has_products_of_shape β C] (p : (b : β) → f b ≅ g b) : ∏ f ≅ ∏ g := functor.map_iso lim (discrete.nat_iso p) /-- Construct a morphism between categorical coproducts (indexed by the same type) from a family of morphisms between the factors. -/ def sigma.map {β : Type v} {C : Type u} [category C] {f : β → C} {g : β → C} [has_coproduct f] [has_coproduct g] (p : (b : β) → f b ⟶ g b) : ∐ f ⟶ ∐ g := colim_map (discrete.nat_trans p) /-- Construct an isomorphism between categorical coproducts (indexed by the same type) from a family of isomorphisms between the factors. -/ def sigma.map_iso {β : Type v} {C : Type u} [category C] {f : β → C} {g : β → C} [has_coproducts_of_shape β C] (p : (b : β) → f b ≅ g b) : ∐ f ≅ ∐ g := functor.map_iso colim (discrete.nat_iso p) -- TODO: show this is an iso iff G preserves the product of f. /-- The comparison morphism for the product of `f`. -/ def pi_comparison {β : Type v} {C : Type u} [category C] {D : Type u₂} [category D] (G : C ⥤ D) (f : β → C) [has_product f] [has_product fun (b : β) => functor.obj G (f b)] : functor.obj G (∏ f) ⟶ ∏ fun (b : β) => functor.obj G (f b) := pi.lift fun (b : β) => functor.map G (pi.π f b) @[simp] theorem pi_comparison_comp_π_assoc {β : Type v} {C : Type u} [category C] {D : Type u₂} [category D] (G : C ⥤ D) (f : β → C) [has_product f] [has_product fun (b : β) => functor.obj G (f b)] (b : β) {X' : D} (f' : functor.obj G (f b) ⟶ X') : pi_comparison G f ≫ pi.π (fun (b : β) => functor.obj G (f b)) b ≫ f' = functor.map G (pi.π f b) ≫ f' := sorry @[simp] theorem map_lift_pi_comparison_assoc {β : Type v} {C : Type u} [category C] {D : Type u₂} [category D] (G : C ⥤ D) (f : β → C) [has_product f] [has_product fun (b : β) => functor.obj G (f b)] (P : C) (g : (j : β) → P ⟶ f j) {X' : D} (f' : (∏ fun (b : β) => functor.obj G (f b)) ⟶ X') : functor.map G (pi.lift g) ≫ pi_comparison G f ≫ f' = (pi.lift fun (j : β) => functor.map G (g j)) ≫ f' := sorry -- TODO: show this is an iso iff G preserves the coproduct of f. /-- The comparison morphism for the coproduct of `f`. -/ def sigma_comparison {β : Type v} {C : Type u} [category C] {D : Type u₂} [category D] (G : C ⥤ D) (f : β → C) [has_coproduct f] [has_coproduct fun (b : β) => functor.obj G (f b)] : (∐ fun (b : β) => functor.obj G (f b)) ⟶ functor.obj G (∐ f) := sigma.desc fun (b : β) => functor.map G (sigma.ι f b) @[simp] theorem ι_comp_sigma_comparison_assoc {β : Type v} {C : Type u} [category C] {D : Type u₂} [category D] (G : C ⥤ D) (f : β → C) [has_coproduct f] [has_coproduct fun (b : β) => functor.obj G (f b)] (b : β) {X' : D} (f' : functor.obj G (∐ f) ⟶ X') : sigma.ι (fun (b : β) => functor.obj G (f b)) b ≫ sigma_comparison G f ≫ f' = functor.map G (sigma.ι f b) ≫ f' := sorry @[simp] theorem sigma_comparison_map_desc {β : Type v} {C : Type u} [category C] {D : Type u₂} [category D] (G : C ⥤ D) (f : β → C) [has_coproduct f] [has_coproduct fun (b : β) => functor.obj G (f b)] (P : C) (g : (j : β) → f j ⟶ P) : sigma_comparison G f ≫ functor.map G (sigma.desc g) = sigma.desc fun (j : β) => functor.map G (g j) := sorry /-- An abbreviation for `Π J, has_limits_of_shape (discrete J) C` -/ /-- An abbreviation for `Π J, has_colimits_of_shape (discrete J) C` -/ def has_products (C : Type u) [category C] := ∀ (J : Type v), has_limits_of_shape (discrete J) C def has_coproducts (C : Type u) [category C] := ∀ (J : Type v), has_colimits_of_shape (discrete J) C end Mathlib
a79f7883b7d9d7ef4dfb011b1e1a637d77481947
aa2345b30d710f7e75f13157a35845ee6d48c017
/algebra/euclidean_domain.lean
a0027a6145b296fdb0b331ce496ba52b6c0fead9
[ "Apache-2.0" ]
permissive
CohenCyril/mathlib
5241b20a3fd0ac0133e48e618a5fb7761ca7dcbe
a12d5a192f5923016752f638d19fc1a51610f163
refs/heads/master
1,586,031,957,957
1,541,432,824,000
1,541,432,824,000
156,246,337
0
0
Apache-2.0
1,541,434,514,000
1,541,434,513,000
null
UTF-8
Lean
false
false
8,783
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 class euclidean_domain (α : Type u) extends integral_domain α := (quotient : α → α → α) (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) namespace euclidean_domain variable {α : Type u} variables [euclidean_domain α] local infix ` ≺ `:50 := euclidean_domain.r instance : has_div α := ⟨quotient⟩ 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 zero_div {a : α} (a0 : a ≠ 0) : 0 / a = 0 := 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 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] @[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 α⟩]} 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 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 @[simp] 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 end gcd instance : euclidean_domain ℤ := { quotient := (/), 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 _) } end euclidean_domain
bcb1bb376239aab5818f403e6f0488589c6ea20b
9028d228ac200bbefe3a711342514dd4e4458bff
/src/ring_theory/noetherian.lean
484e285edf1bfd1d27a0a339ddad218931a20546
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
23,373
lean
/- Copyright (c) 2018 Mario Carneiro and Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kevin Buzzard -/ import ring_theory.ideal.operations import linear_algebra.linear_independent import order.order_iso_nat /-! # Noetherian rings and modules The following are equivalent for a module M over a ring R: 1. Every increasing chain of submodule M₁ ⊆ M₂ ⊆ M₃ ⊆ ⋯ eventually stabilises. 2. Every submodule is finitely generated. A module satisfying these equivalent conditions is said to be a *Noetherian* R-module. A ring is a *Noetherian ring* if it is Noetherian as a module over itself. ## Main definitions Let `R` be a ring and let `M` and `P` be `R`-modules. Let `N` be an `R`-submodule of `M`. * `fg N : Prop` is the assertion that `N` is finitely generated as an `R`-module. * `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module. It is a class, implemented as the predicate that all `R`-submodules of `M` are finitely generated. ## Main statements * `exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul` is Nakayama's lemma, in the following form: if N is a finitely generated submodule of an ambient R-module M and I is an ideal of R such that N ⊆ IN, then there exists r ∈ 1 + I such that rN = 0. * `is_noetherian_iff_well_founded` is the theorem that an R-module M is Noetherian iff `>` is well-founded on `submodule R M`. Note that the Hilbert basis theorem, that if a commutative ring R is Noetherian then so is R[X], is proved in `ring_theory.polynomial`. ## References * [M. F. Atiyah and I. G. Macdonald, *Introduction to commutative algebra*][atiyah-macdonald] ## Tags Noetherian, noetherian, Noetherian ring, Noetherian module, noetherian ring, noetherian module -/ open set open_locale big_operators namespace submodule variables {R : Type*} {M : Type*} [semiring R] [add_comm_monoid M] [semimodule R M] /-- A submodule of `M` is finitely generated if it is the span of a finite subset of `M`. -/ def fg (N : submodule R M) : Prop := ∃ S : finset M, submodule.span R ↑S = N theorem fg_def {N : submodule R M} : N.fg ↔ ∃ S : set M, finite S ∧ span R S = N := ⟨λ ⟨t, h⟩, ⟨_, finset.finite_to_set t, h⟩, begin rintro ⟨t', h, rfl⟩, rcases finite.exists_finset_coe h with ⟨t, rfl⟩, exact ⟨t, rfl⟩ end⟩ /-- Nakayama's Lemma. Atiyah-Macdonald 2.5, Eisenbud 4.7, Matsumura 2.2, Stacks 00DV -/ theorem exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul {R : Type*} [comm_ring R] {M : Type*} [add_comm_group M] [module R M] (I : ideal R) (N : submodule R M) (hn : N.fg) (hin : N ≤ I • N) : ∃ r : R, r - 1 ∈ I ∧ ∀ n ∈ N, r • n = (0 : M) := begin rw fg_def at hn, rcases hn with ⟨s, hfs, hs⟩, have : ∃ r : R, r - 1 ∈ I ∧ N ≤ (I • span R s).comap (linear_map.lsmul R M r) ∧ s ⊆ N, { refine ⟨1, _, _, _⟩, { rw sub_self, exact I.zero_mem }, { rw [hs], intros n hn, rw [mem_comap], change (1:R) • n ∈ I • N, rw one_smul, exact hin hn }, { rw [← span_le, hs], exact le_refl N } }, clear hin hs, revert this, refine set.finite.dinduction_on hfs (λ H, _) (λ i s his hfs ih H, _), { rcases H with ⟨r, hr1, hrn, hs⟩, refine ⟨r, hr1, λ n hn, _⟩, specialize hrn hn, rwa [mem_comap, span_empty, smul_bot, mem_bot] at hrn }, apply ih, rcases H with ⟨r, hr1, hrn, hs⟩, rw [← set.singleton_union, span_union, smul_sup] at hrn, rw [set.insert_subset] at hs, have : ∃ c : R, c - 1 ∈ I ∧ c • i ∈ I • span R s, { specialize hrn hs.1, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • i at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨c, hci, rfl⟩, use r-c, split, { rw [sub_right_comm], exact I.sub_mem hr1 hci }, { rw [sub_smul, ← hyz, add_sub_cancel'], exact hz } }, rcases this with ⟨c, hc1, hci⟩, refine ⟨c * r, _, _, hs.2⟩, { rw [← ideal.quotient.eq, ring_hom.map_one] at hr1 hc1 ⊢, rw [ring_hom.map_mul, hc1, hr1, mul_one] }, { intros n hn, specialize hrn hn, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • n at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨d, hdi, rfl⟩, change _ • _ ∈ I • span R s, rw [mul_smul, ← hyz, smul_add, smul_smul, mul_comm, mul_smul], exact add_mem _ (smul_mem _ _ hci) (smul_mem _ _ hz) } end theorem fg_bot : (⊥ : submodule R M).fg := ⟨∅, by rw [finset.coe_empty, span_empty]⟩ theorem fg_sup {N₁ N₂ : submodule R M} (hN₁ : N₁.fg) (hN₂ : N₂.fg) : (N₁ ⊔ N₂).fg := let ⟨t₁, ht₁⟩ := fg_def.1 hN₁, ⟨t₂, ht₂⟩ := fg_def.1 hN₂ in fg_def.2 ⟨t₁ ∪ t₂, ht₁.1.union ht₂.1, by rw [span_union, ht₁.2, ht₂.2]⟩ variables {P : Type*} [add_comm_monoid P] [semimodule R P] variables {f : M →ₗ[R] P} theorem fg_map {N : submodule R M} (hs : N.fg) : (N.map f).fg := let ⟨t, ht⟩ := fg_def.1 hs in fg_def.2 ⟨f '' t, ht.1.image _, by rw [span_image, ht.2]⟩ lemma fg_of_fg_map {R M P : Type*} [ring R] [add_comm_group M] [module R M] [add_comm_group P] [module R P] (f : M →ₗ[R] P) (hf : f.ker = ⊥) {N : submodule R M} (hfn : (N.map f).fg) : N.fg := let ⟨t, ht⟩ := hfn in ⟨t.preimage f $ λ x _ y _ h, linear_map.ker_eq_bot.1 hf h, linear_map.map_injective hf $ by { rw [map_span, finset.coe_preimage, set.image_preimage_eq_inter_range, set.inter_eq_self_of_subset_left, ht], rw [← linear_map.range_coe, ← span_le, ht, ← map_top], exact map_mono le_top }⟩ lemma fg_top {R M : Type*} [ring R] [add_comm_group M] [module R M] (N : submodule R M) : (⊤ : submodule R N).fg ↔ N.fg := ⟨λ h, N.range_subtype ▸ map_top N.subtype ▸ fg_map h, λ h, fg_of_fg_map N.subtype N.ker_subtype $ by rwa [map_top, range_subtype]⟩ lemma fg_of_linear_equiv (e : M ≃ₗ[R] P) (h : (⊤ : submodule R P).fg) : (⊤ : submodule R M).fg := e.symm.range ▸ map_top (e.symm : P →ₗ[R] M) ▸ fg_map h theorem fg_prod {sb : submodule R M} {sc : submodule R P} (hsb : sb.fg) (hsc : sc.fg) : (sb.prod sc).fg := let ⟨tb, htb⟩ := fg_def.1 hsb, ⟨tc, htc⟩ := fg_def.1 hsc in fg_def.2 ⟨linear_map.inl R M P '' tb ∪ linear_map.inr R M P '' tc, (htb.1.image _).union (htc.1.image _), by rw [linear_map.span_inl_union_inr, htb.2, htc.2]⟩ /-- If 0 → M' → M → M'' → 0 is exact and M' and M'' are finitely generated then so is M. -/ theorem fg_of_fg_map_of_fg_inf_ker {R M P : Type*} [ring R] [add_comm_group M] [module R M] [add_comm_group P] [module R P] (f : M →ₗ[R] P) {s : submodule R M} (hs1 : (s.map f).fg) (hs2 : (s ⊓ f.ker).fg) : s.fg := begin haveI := classical.dec_eq R, haveI := classical.dec_eq M, haveI := classical.dec_eq P, cases hs1 with t1 ht1, cases hs2 with t2 ht2, have : ∀ y ∈ t1, ∃ x ∈ s, f x = y, { intros y hy, have : y ∈ map f s, { rw ← ht1, exact subset_span hy }, rcases mem_map.1 this with ⟨x, hx1, hx2⟩, exact ⟨x, hx1, hx2⟩ }, have : ∃ g : P → M, ∀ y ∈ t1, g y ∈ s ∧ f (g y) = y, { choose g hg1 hg2, existsi λ y, if H : y ∈ t1 then g y H else 0, intros y H, split, { simp only [dif_pos H], apply hg1 }, { simp only [dif_pos H], apply hg2 } }, cases this with g hg, clear this, existsi t1.image g ∪ t2, rw [finset.coe_union, span_union, finset.coe_image], apply le_antisymm, { refine sup_le (span_le.2 $ image_subset_iff.2 _) (span_le.2 _), { intros y hy, exact (hg y hy).1 }, { intros x hx, have := subset_span hx, rw ht2 at this, exact this.1 } }, intros x hx, have : f x ∈ map f s, { rw mem_map, exact ⟨x, hx, rfl⟩ }, rw [← ht1,← set.image_id ↑t1, finsupp.mem_span_iff_total] at this, rcases this with ⟨l, hl1, hl2⟩, refine mem_sup.2 ⟨(finsupp.total M M R id).to_fun ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, x - finsupp.total M M R id ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, add_sub_cancel'_right _ _⟩, { rw [← set.image_id (g '' ↑t1), finsupp.mem_span_iff_total], refine ⟨_, _, rfl⟩, haveI : inhabited P := ⟨0⟩, rw [← finsupp.lmap_domain_supported _ _ g, mem_map], refine ⟨l, hl1, _⟩, refl, }, rw [ht2, mem_inf], split, { apply s.sub_mem hx, rw [finsupp.total_apply, finsupp.lmap_domain_apply, finsupp.sum_map_domain_index], refine s.sum_mem _, { intros y hy, exact s.smul_mem _ (hg y (hl1 hy)).1 }, { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } }, { rw [linear_map.mem_ker, f.map_sub, ← hl2], rw [finsupp.total_apply, finsupp.total_apply, finsupp.lmap_domain_apply], rw [finsupp.sum_map_domain_index, finsupp.sum, finsupp.sum, f.map_sum], rw sub_eq_zero, refine finset.sum_congr rfl (λ y hy, _), unfold id, rw [f.map_smul, (hg y (hl1 hy)).2], { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } } end end submodule /-- `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module, implemented as the predicate that all `R`-submodules of `M` are finitely generated. -/ class is_noetherian (R M) [semiring R] [add_comm_monoid M] [semimodule R M] : Prop := (noetherian : ∀ (s : submodule R M), s.fg) section variables {R : Type*} {M : Type*} {P : Type*} variables [ring R] [add_comm_group M] [add_comm_group P] variables [module R M] [module R P] open is_noetherian include R theorem is_noetherian_submodule {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, s ≤ N → s.fg := ⟨λ ⟨hn⟩, λ s hs, have s ≤ N.subtype.range, from (N.range_subtype).symm ▸ hs, linear_map.map_comap_eq_self this ▸ submodule.fg_map (hn _), λ h, ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker N.subtype (h _ $ submodule.map_subtype_le _ _) $ by rw [submodule.ker_subtype, inf_bot_eq]; exact submodule.fg_bot⟩⟩ theorem is_noetherian_submodule_left {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (N ⊓ s).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_left, λ H s hs, (inf_of_le_right hs) ▸ H _⟩ theorem is_noetherian_submodule_right {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (s ⊓ N).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_right, λ H s hs, (inf_of_le_left hs) ▸ H _⟩ instance is_noetherian_submodule' [is_noetherian R M] (N : submodule R M) : is_noetherian R N := is_noetherian_submodule.2 $ λ _ _, is_noetherian.noetherian _ variable (M) theorem is_noetherian_of_surjective (f : M →ₗ[R] P) (hf : f.range = ⊤) [is_noetherian R M] : is_noetherian R P := ⟨λ s, have (s.comap f).map f = s, from linear_map.map_comap_eq_self $ hf.symm ▸ le_top, this ▸ submodule.fg_map $ noetherian _⟩ variable {M} theorem is_noetherian_of_linear_equiv (f : M ≃ₗ[R] P) [is_noetherian R M] : is_noetherian R P := is_noetherian_of_surjective _ f.to_linear_map f.range lemma is_noetherian_of_injective [is_noetherian R P] (f : M →ₗ[R] P) (hf : f.ker = ⊥) : is_noetherian R M := is_noetherian_of_linear_equiv (linear_equiv.of_injective f hf).symm lemma fg_of_injective [is_noetherian R P] {N : submodule R M} (f : M →ₗ[R] P) (hf : f.ker = ⊥) : N.fg := @@is_noetherian.noetherian _ _ _ (is_noetherian_of_injective f hf) N instance is_noetherian_prod [is_noetherian R M] [is_noetherian R P] : is_noetherian R (M × P) := ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker (linear_map.snd R M P) (noetherian _) $ have s ⊓ linear_map.ker (linear_map.snd R M P) ≤ linear_map.range (linear_map.inl R M P), from λ x ⟨hx1, hx2⟩, ⟨x.1, trivial, prod.ext rfl $ eq.symm $ linear_map.mem_ker.1 hx2⟩, linear_map.map_comap_eq_self this ▸ submodule.fg_map (noetherian _)⟩ instance is_noetherian_pi {R ι : Type*} {M : ι → Type*} [ring R] [Π i, add_comm_group (M i)] [Π i, module R (M i)] [fintype ι] [∀ i, is_noetherian R (M i)] : is_noetherian R (Π i, M i) := begin haveI := classical.dec_eq ι, suffices : ∀ s : finset ι, is_noetherian R (Π i : (↑s : set ι), M i), { letI := this finset.univ, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ ⟨_, _, _, _, _, _⟩ (this finset.univ), { exact λ f i, f ⟨i, finset.mem_univ _⟩ }, { intros, ext, refl }, { intros, ext, refl }, { exact λ f i, f i.1 }, { intro, ext ⟨⟩, refl }, { intro, ext i, refl } }, intro s, induction s using finset.induction with a s has ih, { split, intro s, convert submodule.fg_bot, apply eq_bot_iff.2, intros x hx, refine (submodule.mem_bot R).2 _, ext i, cases i.2 }, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ ⟨_, _, _, _, _, _⟩ (@is_noetherian_prod _ (M a) _ _ _ _ _ _ _ ih), { exact λ f i, or.by_cases (finset.mem_insert.1 i.2) (λ h : i.1 = a, show M i.1, from (eq.rec_on h.symm f.1)) (λ h : i.1 ∈ s, show M i.1, from f.2 ⟨i.1, h⟩) }, { intros f g, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = _ + _, simp only [dif_pos], refl }, { change _ = _ + _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { intros c f, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = c • _, simp only [dif_pos], refl }, { change _ = c • _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { exact λ f, (f ⟨a, finset.mem_insert_self _ _⟩, λ i, f ⟨i.1, finset.mem_insert_of_mem i.2⟩) }, { intro f, apply prod.ext, { simp only [or.by_cases, dif_pos] }, { ext ⟨i, his⟩, have : ¬i = a, { rintro rfl, exact has his }, dsimp only [or.by_cases], change i ∈ s at his, rw [dif_neg this, dif_pos his] } }, { intro f, ext ⟨i, hi⟩, rcases finset.mem_insert.1 hi with rfl | h, { simp only [or.by_cases, dif_pos], refl }, { have : ¬i = a, { rintro rfl, exact has h }, simp only [or.by_cases, dif_neg this, dif_pos h], refl } } end end open is_noetherian submodule function theorem is_noetherian_iff_well_founded {R M} [ring R] [add_comm_group M] [module R M] : is_noetherian R M ↔ well_founded ((>) : submodule R M → submodule R M → Prop) := ⟨λ h, begin apply rel_embedding.well_founded_iff_no_descending_seq.2, swap, { apply is_strict_order.swap }, rintro ⟨⟨N, hN⟩⟩, let Q := ⨆ n, N n, resetI, rcases submodule.fg_def.1 (noetherian Q) with ⟨t, h₁, h₂⟩, have hN' : ∀ {a b}, a ≤ b → N a ≤ N b := λ a b, (strict_mono.le_iff_le (λ _ _, hN.1)).2, have : t ⊆ ⋃ i, (N i : set M), { rw [← submodule.coe_supr_of_directed N _], { show t ⊆ Q, rw ← h₂, apply submodule.subset_span }, { exact λ i j, ⟨max i j, hN' (le_max_left _ _), hN' (le_max_right _ _)⟩ } }, simp [subset_def] at this, choose f hf using show ∀ x : t, ∃ (i : ℕ), x.1 ∈ N i, { simpa }, cases h₁ with h₁, let A := finset.sup (@finset.univ t h₁) f, have : Q ≤ N A, { rw ← h₂, apply submodule.span_le.2, exact λ x h, hN' (finset.le_sup (@finset.mem_univ t h₁ _)) (hf ⟨x, h⟩) }, exact not_le_of_lt (hN.1 (nat.lt_succ_self A)) (le_trans (le_supr _ _) this) end, begin assume h, split, assume N, suffices : ∀ P ≤ N, ∃ s, finite s ∧ P ⊔ submodule.span R s = N, { rcases this ⊥ bot_le with ⟨s, hs, e⟩, exact submodule.fg_def.2 ⟨s, hs, by simpa using e⟩ }, refine λ P, h.induction P _, intros P IH PN, letI := classical.dec, by_cases h : ∀ x, x ∈ N → x ∈ P, { cases le_antisymm PN h, exact ⟨∅, by simp⟩ }, { simp [not_forall] at h, rcases h with ⟨x, h, h₂⟩, have : ¬P ⊔ submodule.span R {x} ≤ P, { intro hn, apply h₂, have := le_trans le_sup_right hn, exact submodule.span_le.1 this (mem_singleton x) }, rcases IH (P ⊔ submodule.span R {x}) ⟨@le_sup_left _ _ P _, this⟩ (sup_le PN (submodule.span_le.2 (by simpa))) with ⟨s, hs, hs₂⟩, refine ⟨insert x s, hs.insert x, _⟩, rw [← hs₂, sup_assoc, ← submodule.span_union], simp } end⟩ lemma well_founded_submodule_gt (R M) [ring R] [add_comm_group M] [module R M] : ∀ [is_noetherian R M], well_founded ((>) : submodule R M → submodule R M → Prop) := is_noetherian_iff_well_founded.mp lemma finite_of_linear_independent {R M} [comm_ring R] [nontrivial R] [add_comm_group M] [module R M] [is_noetherian R M] {s : set M} (hs : linear_independent R (coe : s → M)) : s.finite := begin refine classical.by_contradiction (λ hf, rel_embedding.well_founded_iff_no_descending_seq.1 (well_founded_submodule_gt R M) ⟨_⟩), have f : ℕ ↪ s, from @infinite.nat_embedding s ⟨λ f, hf ⟨f⟩⟩, have : ∀ n, (coe ∘ f) '' {m | m ≤ n} ⊆ s, { rintros n x ⟨y, hy₁, hy₂⟩, subst hy₂, exact (f y).2 }, have : ∀ a b : ℕ, a ≤ b ↔ span R ((coe ∘ f) '' {m | m ≤ a}) ≤ span R ((coe ∘ f) '' {m | m ≤ b}), { assume a b, rw [span_le_span_iff hs (this a) (this b), set.image_subset_image_iff (subtype.coe_injective.comp f.injective), set.subset_def], exact ⟨λ hab x (hxa : x ≤ a), le_trans hxa hab, λ hx, hx a (le_refl a)⟩ }, exact ⟨⟨λ n, span R ((coe ∘ f) '' {m | m ≤ n}), λ x y, by simp [le_antisymm_iff, (this _ _).symm] {contextual := tt}⟩, by dsimp [gt]; simp only [lt_iff_le_not_le, (this _ _).symm]; tauto⟩ end /-- A module is Noetherian iff every nonempty set of submodules has a maximal submodule among them. -/ theorem set_has_maximal_iff_noetherian {R M} [ring R] [add_comm_group M] [module R M] : (∀ a : set $ submodule R M, a.nonempty → ∃ M' ∈ a, ∀ I ∈ a, M' ≤ I → I = M') ↔ is_noetherian R M := by rw [is_noetherian_iff_well_founded, well_founded.well_founded_iff_has_max'] /-- A ring is Noetherian if it is Noetherian as a module over itself, i.e. all its ideals are finitely generated. -/ @[class] def is_noetherian_ring (R) [ring R] : Prop := is_noetherian R R instance is_noetherian_ring.to_is_noetherian {R : Type*} [ring R] : ∀ [is_noetherian_ring R], is_noetherian R R := id @[priority 80] -- see Note [lower instance priority] instance ring.is_noetherian_of_fintype (R M) [fintype M] [ring R] [add_comm_group M] [module R M] : is_noetherian R M := by letI := classical.dec; exact ⟨assume s, ⟨to_finset s, by rw [set.coe_to_finset, submodule.span_eq]⟩⟩ theorem ring.is_noetherian_of_zero_eq_one {R} [ring R] (h01 : (0 : R) = 1) : is_noetherian_ring R := by haveI := subsingleton_of_zero_eq_one h01; haveI := fintype.of_subsingleton (0:R); exact ring.is_noetherian_of_fintype _ _ theorem is_noetherian_of_submodule_of_noetherian (R M) [ring R] [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N := begin rw is_noetherian_iff_well_founded at h ⊢, exact order_embedding.well_founded (submodule.map_subtype.order_embedding N).dual h, end theorem is_noetherian_of_quotient_of_noetherian (R) [ring R] (M) [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N.quotient := begin rw is_noetherian_iff_well_founded at h ⊢, exact order_embedding.well_founded (submodule.comap_mkq.order_embedding N).dual h, end theorem is_noetherian_of_fg_of_noetherian {R M} [ring R] [add_comm_group M] [module R M] (N : submodule R M) [is_noetherian_ring R] (hN : N.fg) : is_noetherian R N := let ⟨s, hs⟩ := hN in begin haveI := classical.dec_eq M, haveI := classical.dec_eq R, letI : is_noetherian R R := by apply_instance, have : ∀ x ∈ s, x ∈ N, from λ x hx, hs ▸ submodule.subset_span hx, refine @@is_noetherian_of_surjective ((↑s : set M) → R) _ _ _ (pi.semimodule _ _ _) _ _ _ is_noetherian_pi, { fapply linear_map.mk, { exact λ f, ⟨∑ i in s.attach, f i • i.1, N.sum_mem (λ c _, N.smul_mem _ $ this _ c.2)⟩ }, { intros f g, apply subtype.eq, change ∑ i in s.attach, (f i + g i) • _ = _, simp only [add_smul, finset.sum_add_distrib], refl }, { intros c f, apply subtype.eq, change ∑ i in s.attach, (c • f i) • _ = _, simp only [smul_eq_mul, mul_smul], exact finset.smul_sum.symm } }, rw linear_map.range_eq_top, rintro ⟨n, hn⟩, change n ∈ N at hn, rw [← hs, ← set.image_id ↑s, finsupp.mem_span_iff_total] at hn, rcases hn with ⟨l, hl1, hl2⟩, refine ⟨λ x, l x, subtype.ext _⟩, change ∑ i in s.attach, l i • (i : M) = n, rw [@finset.sum_attach M M s _ (λ i, l i • i), ← hl2, finsupp.total_apply, finsupp.sum, eq_comm], refine finset.sum_subset hl1 (λ x _ hx, _), rw [finsupp.not_mem_support_iff.1 hx, zero_smul] end lemma is_noetherian_of_fg_of_noetherian' {R M} [ring R] [add_comm_group M] [module R M] [is_noetherian_ring R] (h : (⊤ : submodule R M).fg) : is_noetherian R M := have is_noetherian R (⊤ : submodule R M), from is_noetherian_of_fg_of_noetherian _ h, by exactI is_noetherian_of_linear_equiv (linear_equiv.of_top (⊤ : submodule R M) rfl) /-- In a module over a noetherian ring, the submodule generated by finitely many vectors is noetherian. -/ theorem is_noetherian_span_of_finite (R) {M} [ring R] [add_comm_group M] [module R M] [is_noetherian_ring R] {A : set M} (hA : finite A) : is_noetherian R (submodule.span R A) := is_noetherian_of_fg_of_noetherian _ (submodule.fg_def.mpr ⟨A, hA, rfl⟩) theorem is_noetherian_ring_of_surjective (R) [comm_ring R] (S) [comm_ring S] (f : R →+* S) (hf : function.surjective f) [H : is_noetherian_ring R] : is_noetherian_ring S := begin rw [is_noetherian_ring, is_noetherian_iff_well_founded] at H ⊢, exact order_embedding.well_founded (ideal.order_embedding_of_surjective f hf).dual H, end instance is_noetherian_ring_set_range {R} [comm_ring R] {S} [comm_ring S] (f : R →+* S) [is_noetherian_ring R] : is_noetherian_ring (set.range f) := is_noetherian_ring_of_surjective R (set.range f) (f.cod_restrict (set.range f) set.mem_range_self) set.surjective_onto_range instance is_noetherian_ring_range {R} [comm_ring R] {S} [comm_ring S] (f : R →+* S) [is_noetherian_ring R] : is_noetherian_ring f.range := is_noetherian_ring_of_surjective R f.range (f.cod_restrict' f.range f.mem_range_self) f.surjective_onto_range theorem is_noetherian_ring_of_ring_equiv (R) [comm_ring R] {S} [comm_ring S] (f : R ≃+* S) [is_noetherian_ring R] : is_noetherian_ring S := is_noetherian_ring_of_surjective R S f.to_ring_hom f.to_equiv.surjective namespace submodule variables {R : Type*} {A : Type*} [comm_ring R] [ring A] [algebra R A] variables (M N : submodule R A) theorem fg_mul (hm : M.fg) (hn : N.fg) : (M * N).fg := let ⟨m, hfm, hm⟩ := fg_def.1 hm, ⟨n, hfn, hn⟩ := fg_def.1 hn in fg_def.2 ⟨m * n, hfm.mul hfn, span_mul_span R m n ▸ hm ▸ hn ▸ rfl⟩ lemma fg_pow (h : M.fg) (n : ℕ) : (M ^ n).fg := nat.rec_on n (⟨{1}, by simp [one_eq_span]⟩) (λ n ih, by simpa [pow_succ] using fg_mul _ _ h ih) end submodule
be6df4da34cda914d8af46a0727c7c3f0ede6c4d
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/set_theory/cardinal_ordinal_auto.lean
b0198e833e58315f905660670b0a22c1ba050151
[]
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
18,808
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.set_theory.ordinal_arithmetic import Mathlib.tactic.omega.default import Mathlib.PostPort universes u_1 u v w u_2 namespace Mathlib /-! # Cardinals and ordinals Relationships between cardinals and ordinals, properties of cardinals that are proved using ordinals. ## Main definitions and results * The `aleph'` function gives the cardinals listed by their ordinal index, and is the inverse of `aleph_idx`. `aleph' n = n`, `aleph' ω = ω`, `aleph' (ω + 1) = ℵ₁`, etc. It is an order isomorphism between ordinals and cardinals. * The `aleph` function gives the infinite cardinals listed by their ordinal index. `aleph 0 = ω`, `aleph 1 = succ ω` is the first uncountable cardinal, and so on. * `mul_eq_max` and `add_eq_max` state that the product (resp. sum) of two infinite cardinals is just their maximum. Several variations around this fact are also given. * `mk_list_eq_mk` : when `α` is infinite, `α` and `list α` have the same cardinality. * simp lemmas for inequalities between `bit0 a` and `bit1 b` are registered, making simp able to prove inequalities about numeral cardinals. -/ namespace cardinal theorem ord_is_limit {c : cardinal} (co : omega ≤ c) : ordinal.is_limit (ord c) := sorry /-- The `aleph'` index function, which gives the ordinal index of a cardinal. (The `aleph'` part is because unlike `aleph` this counts also the finite stages. So `aleph_idx n = n`, `aleph_idx ω = ω`, `aleph_idx ℵ₁ = ω + 1` and so on.) In this definition, we register additionally that this function is an initial segment, i.e., it is order preserving and its range is an initial segment of the ordinals. For the basic function version, see `aleph_idx`. For an upgraded version stating that the range is everything, see `aleph_idx.rel_iso`. -/ def aleph_idx.initial_seg : initial_seg Less Less := rel_embedding.collapse (order_embedding.lt_embedding ord.order_embedding) /-- The `aleph'` index function, which gives the ordinal index of a cardinal. (The `aleph'` part is because unlike `aleph` this counts also the finite stages. So `aleph_idx n = n`, `aleph_idx ω = ω`, `aleph_idx ℵ₁ = ω + 1` and so on.) For an upgraded version stating that the range is everything, see `aleph_idx.rel_iso`. -/ def aleph_idx : cardinal → ordinal := ⇑sorry @[simp] theorem aleph_idx.initial_seg_coe : ⇑aleph_idx.initial_seg = aleph_idx := rfl @[simp] theorem aleph_idx_lt {a : cardinal} {b : cardinal} : aleph_idx a < aleph_idx b ↔ a < b := rel_embedding.map_rel_iff (initial_seg.to_rel_embedding aleph_idx.initial_seg) @[simp] theorem aleph_idx_le {a : cardinal} {b : cardinal} : aleph_idx a ≤ aleph_idx b ↔ a ≤ b := sorry theorem aleph_idx.init {a : cardinal} {b : ordinal} : b < aleph_idx a → ∃ (c : cardinal), aleph_idx c = b := initial_seg.init aleph_idx.initial_seg a b /-- The `aleph'` index function, which gives the ordinal index of a cardinal. (The `aleph'` part is because unlike `aleph` this counts also the finite stages. So `aleph_idx n = n`, `aleph_idx ω = ω`, `aleph_idx ℵ₁ = ω + 1` and so on.) In this version, we register additionally that this function is an order isomorphism between cardinals and ordinals. For the basic function version, see `aleph_idx`. -/ def aleph_idx.rel_iso : Less ≃r Less := rel_iso.of_surjective ↑aleph_idx.initial_seg sorry @[simp] theorem aleph_idx.rel_iso_coe : ⇑aleph_idx.rel_iso = aleph_idx := rfl @[simp] theorem type_cardinal : ordinal.type Less = ordinal.univ := eq.mpr (id (Eq._oldrec (Eq.refl (ordinal.type Less = ordinal.univ)) ordinal.univ_id)) (quotient.sound (Nonempty.intro aleph_idx.rel_iso)) @[simp] theorem mk_cardinal : mk cardinal = univ := sorry /-- The `aleph'` function gives the cardinals listed by their ordinal index, and is the inverse of `aleph_idx`. `aleph' n = n`, `aleph' ω = ω`, `aleph' (ω + 1) = ℵ₁`, etc. In this version, we register additionally that this function is an order isomorphism between ordinals and cardinals. For the basic function version, see `aleph'`. -/ def aleph'.rel_iso : Less ≃r Less := rel_iso.symm aleph_idx.rel_iso /-- The `aleph'` function gives the cardinals listed by their ordinal index, and is the inverse of `aleph_idx`. `aleph' n = n`, `aleph' ω = ω`, `aleph' (ω + 1) = ℵ₁`, etc. -/ def aleph' : ordinal → cardinal := ⇑sorry @[simp] theorem aleph'.rel_iso_coe : ⇑aleph'.rel_iso = aleph' := rfl @[simp] theorem aleph'_lt {o₁ : ordinal} {o₂ : ordinal} : aleph' o₁ < aleph' o₂ ↔ o₁ < o₂ := rel_iso.map_rel_iff aleph'.rel_iso @[simp] theorem aleph'_le {o₁ : ordinal} {o₂ : ordinal} : aleph' o₁ ≤ aleph' o₂ ↔ o₁ ≤ o₂ := iff.mpr le_iff_le_iff_lt_iff_lt aleph'_lt @[simp] theorem aleph'_aleph_idx (c : cardinal) : aleph' (aleph_idx c) = c := equiv.symm_apply_apply (rel_iso.to_equiv aleph_idx.rel_iso) c @[simp] theorem aleph_idx_aleph' (o : ordinal) : aleph_idx (aleph' o) = o := equiv.apply_symm_apply (rel_iso.to_equiv aleph_idx.rel_iso) o @[simp] theorem aleph'_zero : aleph' 0 = 0 := sorry @[simp] theorem aleph'_succ {o : ordinal} : aleph' (ordinal.succ o) = succ (aleph' o) := sorry @[simp] theorem aleph'_nat (n : ℕ) : aleph' ↑n = ↑n := sorry theorem aleph'_le_of_limit {o : ordinal} (l : ordinal.is_limit o) {c : cardinal} : aleph' o ≤ c ↔ ∀ (o' : ordinal), o' < o → aleph' o' ≤ c := sorry @[simp] theorem aleph'_omega : aleph' ordinal.omega = omega := sorry /-- `aleph'` and `aleph_idx` form an equivalence between `ordinal` and `cardinal` -/ @[simp] def aleph'_equiv : ordinal ≃ cardinal := equiv.mk aleph' aleph_idx aleph_idx_aleph' aleph'_aleph_idx /-- The `aleph` function gives the infinite cardinals listed by their ordinal index. `aleph 0 = ω`, `aleph 1 = succ ω` is the first uncountable cardinal, and so on. -/ def aleph (o : ordinal) : cardinal := aleph' (ordinal.omega + o) @[simp] theorem aleph_lt {o₁ : ordinal} {o₂ : ordinal} : aleph o₁ < aleph o₂ ↔ o₁ < o₂ := iff.trans aleph'_lt (ordinal.add_lt_add_iff_left ordinal.omega) @[simp] theorem aleph_le {o₁ : ordinal} {o₂ : ordinal} : aleph o₁ ≤ aleph o₂ ↔ o₁ ≤ o₂ := iff.mpr le_iff_le_iff_lt_iff_lt aleph_lt @[simp] theorem aleph_succ {o : ordinal} : aleph (ordinal.succ o) = succ (aleph o) := sorry @[simp] theorem aleph_zero : aleph 0 = omega := sorry theorem omega_le_aleph' {o : ordinal} : omega ≤ aleph' o ↔ ordinal.omega ≤ o := eq.mpr (id (Eq._oldrec (Eq.refl (omega ≤ aleph' o ↔ ordinal.omega ≤ o)) (Eq.symm aleph'_omega))) (eq.mpr (id (Eq._oldrec (Eq.refl (aleph' ordinal.omega ≤ aleph' o ↔ ordinal.omega ≤ o)) (propext aleph'_le))) (iff.refl (ordinal.omega ≤ o))) theorem omega_le_aleph (o : ordinal) : omega ≤ aleph o := eq.mpr (id (Eq._oldrec (Eq.refl (omega ≤ aleph o)) (aleph.equations._eqn_1 o))) (eq.mpr (id (Eq._oldrec (Eq.refl (omega ≤ aleph' (ordinal.omega + o))) (propext omega_le_aleph'))) (ordinal.le_add_right ordinal.omega o)) theorem ord_aleph_is_limit (o : ordinal) : ordinal.is_limit (ord (aleph o)) := ord_is_limit (omega_le_aleph o) theorem exists_aleph {c : cardinal} : omega ≤ c ↔ ∃ (o : ordinal), c = aleph o := sorry theorem aleph'_is_normal : ordinal.is_normal (ord ∘ aleph') := sorry theorem aleph_is_normal : ordinal.is_normal (ord ∘ aleph) := ordinal.is_normal.trans aleph'_is_normal (ordinal.add_is_normal ordinal.omega) /-! ### Properties of `mul` -/ /-- If `α` is an infinite type, then `α × α` and `α` have the same cardinality. -/ theorem mul_eq_self {c : cardinal} (h : omega ≤ c) : c * c = c := sorry /-- If `α` and `β` are infinite types, then the cardinality of `α × β` is the maximum of the cardinalities of `α` and `β`. -/ theorem mul_eq_max {a : cardinal} {b : cardinal} (ha : omega ≤ a) (hb : omega ≤ b) : a * b = max a b := sorry theorem mul_lt_of_lt {a : cardinal} {b : cardinal} {c : cardinal} (hc : omega ≤ c) (h1 : a < c) (h2 : b < c) : a * b < c := sorry theorem mul_le_max_of_omega_le_left {a : cardinal} {b : cardinal} (h : omega ≤ a) : a * b ≤ max a b := sorry theorem mul_eq_max_of_omega_le_left {a : cardinal} {b : cardinal} (h : omega ≤ a) (h' : b ≠ 0) : a * b = max a b := sorry theorem mul_eq_left {a : cardinal} {b : cardinal} (ha : omega ≤ a) (hb : b ≤ a) (hb' : b ≠ 0) : a * b = a := eq.mpr (id (Eq._oldrec (Eq.refl (a * b = a)) (mul_eq_max_of_omega_le_left ha hb'))) (eq.mpr (id (Eq._oldrec (Eq.refl (max a b = a)) (max_eq_left hb))) (Eq.refl a)) theorem mul_eq_right {a : cardinal} {b : cardinal} (hb : omega ≤ b) (ha : a ≤ b) (ha' : a ≠ 0) : a * b = b := eq.mpr (id (Eq._oldrec (Eq.refl (a * b = b)) (mul_comm a b))) (eq.mpr (id (Eq._oldrec (Eq.refl (b * a = b)) (mul_eq_left hb ha ha'))) (Eq.refl b)) theorem le_mul_left {a : cardinal} {b : cardinal} (h : b ≠ 0) : a ≤ b * a := sorry theorem le_mul_right {a : cardinal} {b : cardinal} (h : b ≠ 0) : a ≤ a * b := eq.mpr (id (Eq._oldrec (Eq.refl (a ≤ a * b)) (mul_comm a b))) (le_mul_left h) theorem mul_eq_left_iff {a : cardinal} {b : cardinal} : a * b = a ↔ max omega b ≤ a ∧ b ≠ 0 ∨ b = 1 ∨ a = 0 := sorry /-! ### Properties of `add` -/ /-- If `α` is an infinite type, then `α ⊕ α` and `α` have the same cardinality. -/ theorem add_eq_self {c : cardinal} (h : omega ≤ c) : c + c = c := sorry /-- If `α` is an infinite type, then the cardinality of `α ⊕ β` is the maximum of the cardinalities of `α` and `β`. -/ theorem add_eq_max {a : cardinal} {b : cardinal} (ha : omega ≤ a) : a + b = max a b := le_antisymm (add_eq_self (le_trans ha (le_max_left a b)) ▸ add_le_add (le_max_left a b) (le_max_right a b)) (max_le (self_le_add_right a b) (self_le_add_left b a)) theorem add_lt_of_lt {a : cardinal} {b : cardinal} {c : cardinal} (hc : omega ≤ c) (h1 : a < c) (h2 : b < c) : a + b < c := sorry theorem eq_of_add_eq_of_omega_le {a : cardinal} {b : cardinal} {c : cardinal} (h : a + b = c) (ha : a < c) (hc : omega ≤ c) : b = c := sorry theorem add_eq_left {a : cardinal} {b : cardinal} (ha : omega ≤ a) (hb : b ≤ a) : a + b = a := eq.mpr (id (Eq._oldrec (Eq.refl (a + b = a)) (add_eq_max ha))) (eq.mpr (id (Eq._oldrec (Eq.refl (max a b = a)) (max_eq_left hb))) (Eq.refl a)) theorem add_eq_right {a : cardinal} {b : cardinal} (hb : omega ≤ b) (ha : a ≤ b) : a + b = b := eq.mpr (id (Eq._oldrec (Eq.refl (a + b = b)) (add_comm a b))) (eq.mpr (id (Eq._oldrec (Eq.refl (b + a = b)) (add_eq_left hb ha))) (Eq.refl b)) theorem add_eq_left_iff {a : cardinal} {b : cardinal} : a + b = a ↔ max omega b ≤ a ∨ b = 0 := sorry theorem add_eq_right_iff {a : cardinal} {b : cardinal} : a + b = b ↔ max omega a ≤ b ∨ a = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (a + b = b ↔ max omega a ≤ b ∨ a = 0)) (add_comm a b))) (eq.mpr (id (Eq._oldrec (Eq.refl (b + a = b ↔ max omega a ≤ b ∨ a = 0)) (propext add_eq_left_iff))) (iff.refl (max omega a ≤ b ∨ a = 0))) theorem add_one_eq {a : cardinal} (ha : omega ≤ a) : a + 1 = a := (fun (this : 1 ≤ a) => add_eq_left ha this) (le_trans (le_of_lt one_lt_omega) ha) protected theorem eq_of_add_eq_add_left {a : cardinal} {b : cardinal} {c : cardinal} (h : a + b = a + c) (ha : a < omega) : b = c := sorry protected theorem eq_of_add_eq_add_right {a : cardinal} {b : cardinal} {c : cardinal} (h : a + b = c + b) (hb : b < omega) : a = c := sorry /-! ### Properties about power -/ theorem pow_le {κ : cardinal} {μ : cardinal} (H1 : omega ≤ κ) (H2 : μ < omega) : κ ^ μ ≤ κ := sorry theorem power_self_eq {c : cardinal} (h : omega ≤ c) : c ^ c = bit0 1 ^ c := sorry theorem power_nat_le {c : cardinal} {n : ℕ} (h : omega ≤ c) : c ^ ↑n ≤ c := pow_le h (nat_lt_omega n) theorem powerlt_omega {c : cardinal} (h : omega ≤ c) : c ^< omega = c := sorry theorem powerlt_omega_le (c : cardinal) : c ^< omega ≤ max c omega := sorry /-! ### Computing cardinality of various types -/ theorem mk_list_eq_mk {α : Type u} (H1 : omega ≤ mk α) : mk (List α) = mk α := sorry theorem mk_finset_eq_mk {α : Type u} (h : omega ≤ mk α) : mk (finset α) = mk α := Eq.symm (le_antisymm (mk_le_of_injective fun (x y : α) => iff.mp finset.singleton_inj) (trans_rel_left LessEq (mk_le_of_surjective list.to_finset_surjective) (mk_list_eq_mk h))) theorem mk_bounded_set_le_of_omega_le (α : Type u) (c : cardinal) (hα : omega ≤ mk α) : mk (Subtype fun (t : set α) => mk ↥t ≤ c) ≤ mk α ^ c := sorry theorem mk_bounded_set_le (α : Type u) (c : cardinal) : mk (Subtype fun (t : set α) => mk ↥t ≤ c) ≤ max (mk α) omega ^ c := sorry theorem mk_bounded_subset_le {α : Type u} (s : set α) (c : cardinal) : mk (Subtype fun (t : set α) => t ⊆ s ∧ mk ↥t ≤ c) ≤ max (mk ↥s) omega ^ c := sorry /-! ### Properties of `compl` -/ theorem mk_compl_of_omega_le {α : Type u_1} (s : set α) (h : omega ≤ mk α) (h2 : mk ↥s < mk α) : mk ↥(sᶜ) = mk α := eq_of_add_eq_of_omega_le (mk_sum_compl s) h2 h theorem mk_compl_finset_of_omega_le {α : Type u_1} (s : finset α) (h : omega ≤ mk α) : mk ↥(↑sᶜ) = mk α := mk_compl_of_omega_le (↑s) h (lt_of_lt_of_le (finset_card_lt_omega s) h) theorem mk_compl_eq_mk_compl_infinite {α : Type u_1} {s : set α} {t : set α} (h : omega ≤ mk α) (hs : mk ↥s < mk α) (ht : mk ↥t < mk α) : mk ↥(sᶜ) = mk ↥(tᶜ) := eq.mpr (id (Eq._oldrec (Eq.refl (mk ↥(sᶜ) = mk ↥(tᶜ))) (mk_compl_of_omega_le s h hs))) (eq.mpr (id (Eq._oldrec (Eq.refl (mk α = mk ↥(tᶜ))) (mk_compl_of_omega_le t h ht))) (Eq.refl (mk α))) theorem mk_compl_eq_mk_compl_finite_lift {α : Type u} {β : Type v} {s : set α} {t : set β} (hα : mk α < omega) (h1 : lift (mk α) = lift (mk β)) (h2 : lift (mk ↥s) = lift (mk ↥t)) : lift (mk ↥(sᶜ)) = lift (mk ↥(tᶜ)) := sorry theorem mk_compl_eq_mk_compl_finite {α : Type u} {β : Type u} {s : set α} {t : set β} (hα : mk α < omega) (h1 : mk α = mk β) (h : mk ↥s = mk ↥t) : mk ↥(sᶜ) = mk ↥(tᶜ) := sorry theorem mk_compl_eq_mk_compl_finite_same {α : Type u_1} {s : set α} {t : set α} (hα : mk α < omega) (h : mk ↥s = mk ↥t) : mk ↥(sᶜ) = mk ↥(tᶜ) := mk_compl_eq_mk_compl_finite hα rfl h /-! ### Extending an injection to an equiv -/ theorem extend_function {α : Type u_1} {β : Type u_2} {s : set α} (f : ↥s ↪ β) (h : Nonempty (↥(sᶜ) ≃ ↥(set.range ⇑fᶜ))) : ∃ (g : α ≃ β), ∀ (x : ↥s), coe_fn g ↑x = coe_fn f x := sorry theorem extend_function_finite {α : Type u_1} {β : Type u_2} {s : set α} (f : ↥s ↪ β) (hs : mk α < omega) (h : Nonempty (α ≃ β)) : ∃ (g : α ≃ β), ∀ (x : ↥s), coe_fn g ↑x = coe_fn f x := sorry theorem extend_function_of_lt {α : Type u_1} {β : Type u_2} {s : set α} (f : ↥s ↪ β) (hs : mk ↥s < mk α) (h : Nonempty (α ≃ β)) : ∃ (g : α ≃ β), ∀ (x : ↥s), coe_fn g ↑x = coe_fn f x := sorry /-! This section proves inequalities for `bit0` and `bit1`, enabling `simp` to solve inequalities for numeral cardinals. The complexity of the resulting algorithm is not good, as in some cases `simp` reduces an inequality to a disjunction of two situations, depending on whether a cardinal is finite or infinite. Since the evaluation of the branches is not lazy, this is bad. It is good enough for practical situations, though. For specific numbers, these inequalities could also be deduced from the corresponding inequalities of natural numbers using `norm_cast`: ``` example : (37 : cardinal) < 42 := by { norm_cast, norm_num } ``` -/ @[simp] theorem bit0_ne_zero (a : cardinal) : ¬bit0 a = 0 ↔ ¬a = 0 := sorry @[simp] theorem bit1_ne_zero (a : cardinal) : ¬bit1 a = 0 := sorry @[simp] theorem zero_lt_bit0 (a : cardinal) : 0 < bit0 a ↔ 0 < a := sorry @[simp] theorem zero_lt_bit1 (a : cardinal) : 0 < bit1 a := lt_of_lt_of_le zero_lt_one (self_le_add_left 1 (bit0 a)) @[simp] theorem one_le_bit0 (a : cardinal) : 1 ≤ bit0 a ↔ 0 < a := { mp := fun (h : 1 ≤ bit0 a) => iff.mp (zero_lt_bit0 a) (lt_of_lt_of_le zero_lt_one h), mpr := fun (h : 0 < a) => le_trans (iff.mpr one_le_iff_pos h) (self_le_add_left a a) } @[simp] theorem one_le_bit1 (a : cardinal) : 1 ≤ bit1 a := self_le_add_left 1 (bit0 a) theorem bit0_eq_self {c : cardinal} (h : omega ≤ c) : bit0 c = c := add_eq_self h @[simp] theorem bit0_lt_omega {c : cardinal} : bit0 c < omega ↔ c < omega := sorry @[simp] theorem omega_le_bit0 {c : cardinal} : omega ≤ bit0 c ↔ omega ≤ c := sorry @[simp] theorem bit1_eq_self_iff {c : cardinal} : bit1 c = c ↔ omega ≤ c := sorry @[simp] theorem bit1_lt_omega {c : cardinal} : bit1 c < omega ↔ c < omega := sorry @[simp] theorem omega_le_bit1 {c : cardinal} : omega ≤ bit1 c ↔ omega ≤ c := sorry @[simp] theorem bit0_le_bit0 {a : cardinal} {b : cardinal} : bit0 a ≤ bit0 b ↔ a ≤ b := sorry @[simp] theorem bit0_le_bit1 {a : cardinal} {b : cardinal} : bit0 a ≤ bit1 b ↔ a ≤ b := sorry @[simp] theorem bit1_le_bit1 {a : cardinal} {b : cardinal} : bit1 a ≤ bit1 b ↔ a ≤ b := { mp := fun (h : bit1 a ≤ bit1 b) => iff.mp bit0_le_bit1 (le_trans (self_le_add_right (bit0 a) 1) h), mpr := fun (h : a ≤ b) => le_trans (add_le_add_right (add_le_add_left h a) 1) (add_le_add_right (add_le_add_right h b) 1) } @[simp] theorem bit1_le_bit0 {a : cardinal} {b : cardinal} : bit1 a ≤ bit0 b ↔ a < b ∨ a ≤ b ∧ omega ≤ a := sorry @[simp] theorem bit0_lt_bit0 {a : cardinal} {b : cardinal} : bit0 a < bit0 b ↔ a < b := sorry @[simp] theorem bit1_lt_bit0 {a : cardinal} {b : cardinal} : bit1 a < bit0 b ↔ a < b := sorry @[simp] theorem bit1_lt_bit1 {a : cardinal} {b : cardinal} : bit1 a < bit1 b ↔ a < b := sorry @[simp] theorem bit0_lt_bit1 {a : cardinal} {b : cardinal} : bit0 a < bit1 b ↔ a < b ∨ a ≤ b ∧ a < omega := sorry -- This strategy works generally to prove inequalities between numerals in `cardinality`. theorem one_lt_two : 1 < bit0 1 := sorry @[simp] theorem one_lt_bit0 {a : cardinal} : 1 < bit0 a ↔ 0 < a := sorry @[simp] theorem one_lt_bit1 (a : cardinal) : 1 < bit1 a ↔ 0 < a := sorry @[simp] theorem one_le_one : 1 ≤ 1 := le_refl 1 end Mathlib
7282c6c2f93e8f4e323e6d816be401b12c0f8e49
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/measure_theory/pi.lean
90ba72e5ebf67dfa85b35c8e3d1c24d40f9c495b
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,306
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 -/ import measure_theory.prod /-! # Product measures In this file we define and prove properties about finite products of measures (and at some point, countable products of measures). ## Main definition * `measure_theory.measure.pi`: The product of finitely many σ-finite measures. Given `μ : Π i : ι, measure (α i)` for `[fintype ι]` it has type `measure (Π i : ι, α i)`. ## Implementation Notes We define `measure_theory.outer_measure.pi`, the product of finitely many outer measures, as the maximal outer measure `n` with the property that `n (pi univ s) ≤ ∏ i, m i (s i)`, where `pi univ s` is the product of the sets `{ s i | i : ι }`. We then show that this induces a product of measures, called `measure_theory.measure.pi`. For a collection of σ-finite measures `μ` and a collection of measurable sets `s` we show that `measure.pi μ (pi univ s) = ∏ i, m i (s i)`. To do this, we follow the following steps: * We know that there is some ordering on `ι`, given by an element of `[encodable ι]`. * Using this, we have an equivalence `measurable_equiv.pi_measurable_equiv_tprod` between `Π ι, α i` and an iterated product of `α i`, called `list.tprod α l` for some list `l`. * On this iterated product we can easily define a product measure `measure_theory.measure.tprod` by iterating `measure_theory.measure.prod` * Using the previous two steps we construct `measure_theory.measure.pi'` on `Π ι, α i` for encodable `ι`. * We know that `measure_theory.measure.pi'` sends products of sets to products of measures, and since `measure_theory.measure.pi` is the maximal such measure (or at least, it comes from an outer measure which is the maximal such outer measure), we get the same rule for `measure_theory.measure.pi`. ## Tags finitary product measure -/ noncomputable theory open function set measure_theory.outer_measure filter open_locale classical big_operators topological_space ennreal namespace measure_theory variables {ι : Type*} [fintype ι] {α : ι → Type*} {m : Π i, outer_measure (α i)} /-- An upper bound for the measure in a finite product space. It is defined to by taking the image of the set under all projections, and taking the product of the measures of these images. For measurable boxes it is equal to the correct measure. -/ @[simp] def pi_premeasure (m : Π i, outer_measure (α i)) (s : set (Π i, α i)) : ℝ≥0∞ := ∏ i, m i (eval i '' s) lemma pi_premeasure_pi {s : Π i, set (α i)} (hs : (pi univ s).nonempty) : pi_premeasure m (pi univ s) = ∏ i, m i (s i) := by simp [hs] lemma pi_premeasure_pi' [nonempty ι] {s : Π i, set (α i)} : pi_premeasure m (pi univ s) = ∏ i, m i (s i) := begin cases (pi univ s).eq_empty_or_nonempty with h h, { rcases univ_pi_eq_empty_iff.mp h with ⟨i, hi⟩, have : ∃ i, m i (s i) = 0 := ⟨i, by simp [hi]⟩, simpa [h, finset.card_univ, zero_pow (fintype.card_pos_iff.mpr _inst_2), @eq_comm _ (0 : ℝ≥0∞), finset.prod_eq_zero_iff] }, { simp [h] } end lemma pi_premeasure_pi_mono {s t : set (Π i, α i)} (h : s ⊆ t) : pi_premeasure m s ≤ pi_premeasure m t := finset.prod_le_prod' (λ i _, (m i).mono' (image_subset _ h)) lemma pi_premeasure_pi_eval [nonempty ι] {s : set (Π i, α i)} : pi_premeasure m (pi univ (λ i, eval i '' s)) = pi_premeasure m s := by simp [pi_premeasure_pi'] namespace outer_measure /-- `outer_measure.pi m` is the finite product of the outer measures `{m i | i : ι}`. It is defined to be the maximal outer measure `n` with the property that `n (pi univ s) ≤ ∏ i, m i (s i)`, where `pi univ s` is the product of the sets `{ s i | i : ι }`. -/ protected def pi (m : Π i, outer_measure (α i)) : outer_measure (Π i, α i) := bounded_by (pi_premeasure m) lemma pi_pi_le (m : Π i, outer_measure (α i)) (s : Π i, set (α i)) : outer_measure.pi m (pi univ s) ≤ ∏ i, m i (s i) := by { cases (pi univ s).eq_empty_or_nonempty with h h, simp [h], exact (bounded_by_le _).trans_eq (pi_premeasure_pi h) } lemma le_pi {m : Π i, outer_measure (α i)} {n : outer_measure (Π i, α i)} : n ≤ outer_measure.pi m ↔ ∀ (s : Π i, set (α i)), (pi univ s).nonempty → n (pi univ s) ≤ ∏ i, m i (s i) := begin rw [outer_measure.pi, le_bounded_by'], split, { intros h s hs, refine (h _ hs).trans_eq (pi_premeasure_pi hs) }, { intros h s hs, refine le_trans (n.mono $ subset_pi_eval_image univ s) (h _ _), simp [univ_pi_nonempty_iff, hs] } end end outer_measure namespace measure variables [Π i, measurable_space (α i)] (μ : Π i, measure (α i)) section tprod open list variables {δ : Type*} {π : δ → Type*} [∀ x, measurable_space (π x)] /-- A product of measures in `tprod α l`. -/ -- for some reason the equation compiler doesn't like this definition protected def tprod (l : list δ) (μ : Π i, measure (π i)) : measure (tprod π l) := by { induction l with i l ih, exact dirac punit.star, exact (μ i).prod ih } @[simp] lemma tprod_nil (μ : Π i, measure (π i)) : measure.tprod [] μ = dirac punit.star := rfl @[simp] lemma tprod_cons (i : δ) (l : list δ) (μ : Π i, measure (π i)) : measure.tprod (i :: l) μ = (μ i).prod (measure.tprod l μ) := rfl instance sigma_finite_tprod (l : list δ) (μ : Π i, measure (π i)) [∀ i, sigma_finite (μ i)] : sigma_finite (measure.tprod l μ) := begin induction l with i l ih, { rw [tprod_nil], apply_instance }, { rw [tprod_cons], resetI, apply_instance } end lemma tprod_tprod (l : list δ) (μ : Π i, measure (π i)) [∀ i, sigma_finite (μ i)] {s : Π i, set (π i)} (hs : ∀ i, measurable_set (s i)) : measure.tprod l μ (set.tprod l s) = (l.map (λ i, (μ i) (s i))).prod := begin induction l with i l ih, { simp }, simp_rw [tprod_cons, set.tprod, prod_prod (hs i) (measurable_set.tprod l hs), map_cons, prod_cons, ih] end lemma tprod_tprod_le (l : list δ) (μ : Π i, measure (π i)) [∀ i, sigma_finite (μ i)] (s : Π i, set (π i)) : measure.tprod l μ (set.tprod l s) ≤ (l.map (λ i, (μ i) (s i))).prod := begin induction l with i l ih, { simp [le_refl] }, simp_rw [tprod_cons, set.tprod, map_cons, prod_cons], refine (prod_prod_le _ _).trans _, exact ennreal.mul_left_mono ih end end tprod section encodable open list measurable_equiv variables [encodable ι] /-- The product measure on an encodable finite type, defined by mapping `measure.tprod` along the equivalence `measurable_equiv.pi_measurable_equiv_tprod`. The definition `measure_theory.measure.pi` should be used instead of this one. -/ def pi' : measure (Π i, α i) := measure.map (tprod.elim' encodable.mem_sorted_univ) (measure.tprod (encodable.sorted_univ ι) μ) lemma pi'_pi [∀ i, sigma_finite (μ i)] {s : Π i, set (α i)} (hs : ∀ i, measurable_set (s i)) : pi' μ (pi univ s) = ∏ i, μ i (s i) := begin have hl := λ i : ι, encodable.mem_sorted_univ i, have hnd := @encodable.sorted_univ_nodup ι _ _, rw [pi', map_apply (measurable_tprod_elim' hl) (measurable_set.pi_fintype (λ i _, hs i)), elim_preimage_pi hnd, tprod_tprod _ μ hs, ← list.prod_to_finset _ hnd], congr' with i, simp [hl] end lemma pi'_pi_le [∀ i, sigma_finite (μ i)] {s : Π i, set (α i)} : pi' μ (pi univ s) ≤ ∏ i, μ i (s i) := begin have hl := λ i : ι, encodable.mem_sorted_univ i, have hnd := @encodable.sorted_univ_nodup ι _ _, apply ((pi_measurable_equiv_tprod hnd hl).symm.map_apply (pi univ s)).trans_le, dsimp only [pi_measurable_equiv_tprod, tprod.pi_equiv_tprod, coe_symm_mk, equiv.coe_fn_symm_mk], rw [elim_preimage_pi hnd], refine (tprod_tprod_le _ _ _).trans_eq _, rw [← list.prod_to_finset _ hnd], congr' with i, simp [hl] end end encodable lemma pi_caratheodory : measurable_space.pi ≤ (outer_measure.pi (λ i, (μ i).to_outer_measure)).caratheodory := begin refine supr_le _, intros i s hs, rw [measurable_space.comap] at hs, rcases hs with ⟨s, hs, rfl⟩, apply bounded_by_caratheodory, intro t, simp_rw [pi_premeasure], refine finset.prod_add_prod_le' (finset.mem_univ i) _ _ _, { simp [image_inter_preimage, image_diff_preimage, (μ i).caratheodory hs, le_refl] }, { rintro j - hj, apply mono', apply image_subset, apply inter_subset_left }, { rintro j - hj, apply mono', apply image_subset, apply diff_subset } end /-- `measure.pi μ` is the finite product of the measures `{μ i | i : ι}`. It is defined to be measure corresponding to `measure_theory.outer_measure.pi`. -/ @[irreducible] protected def pi : measure (Π i, α i) := to_measure (outer_measure.pi (λ i, (μ i).to_outer_measure)) (pi_caratheodory μ) variables [∀ i, sigma_finite (μ i)] lemma pi_pi (s : Π i, set (α i)) (hs : ∀ i, measurable_set (s i)) : measure.pi μ (pi univ s) = ∏ i, μ i (s i) := begin refine le_antisymm _ _, { rw [measure.pi, to_measure_apply _ _ (measurable_set.pi_fintype (λ i _, hs i))], apply outer_measure.pi_pi_le }, { haveI : encodable ι := encodable.fintype.encodable ι, rw [← pi'_pi μ hs], simp_rw [← pi'_pi μ hs, measure.pi, to_measure_apply _ _ (measurable_set.pi_fintype (λ i _, hs i)), ← to_outer_measure_apply], suffices : (pi' μ).to_outer_measure ≤ outer_measure.pi (λ i, (μ i).to_outer_measure), { exact this _ }, clear hs s, rw [outer_measure.le_pi], intros s hs, simp_rw [to_outer_measure_apply], exact pi'_pi_le μ } end lemma pi_eval_preimage_null {i : ι} {s : set (α i)} (hs : μ i s = 0) : measure.pi μ (eval i ⁻¹' s) = 0 := begin /- WLOG, `s` is measurable -/ rcases exists_measurable_superset_of_null hs with ⟨t, hst, htm, hμt⟩, suffices : measure.pi μ (eval i ⁻¹' t) = 0, from measure_mono_null (preimage_mono hst) this, clear_dependent s, /- Now rewrite it as `set.pi`, and apply `pi_pi` -/ rw [← univ_pi_update_univ, pi_pi], { apply finset.prod_eq_zero (finset.mem_univ i), simp [hμt] }, { intro j, rcases em (j = i) with rfl | hj; simp * } end lemma pi_hyperplane (i : ι) [has_no_atoms (μ i)] (x : α i) : measure.pi μ {f : Π i, α i | f i = x} = 0 := show measure.pi μ (eval i ⁻¹' {x}) = 0, from pi_eval_preimage_null _ (measure_singleton x) lemma ae_eval_ne (i : ι) [has_no_atoms (μ i)] (x : α i) : ∀ᵐ y : Π i, α i ∂measure.pi μ, y i ≠ x := compl_mem_ae_iff.2 (pi_hyperplane μ i x) variable {μ} lemma tendsto_eval_ae_ae {i : ι} : tendsto (eval i) (measure.pi μ).ae (μ i).ae := λ s hs, pi_eval_preimage_null μ hs -- TODO: should we introduce `filter.pi` and prove some basic facts about it? -- The same combinator appears here and in `nhds_pi` lemma ae_pi_le_infi_comap : (measure.pi μ).ae ≤ ⨅ i, filter.comap (eval i) (μ i).ae := le_infi $ λ i, tendsto_eval_ae_ae.le_comap lemma ae_eq_pi {β : ι → Type*} {f f' : Π i, α i → β i} (h : ∀ i, f i =ᵐ[μ i] f' i) : (λ (x : Π i, α i) i, f i (x i)) =ᵐ[measure.pi μ] (λ x i, f' i (x i)) := (eventually_all.2 (λ i, tendsto_eval_ae_ae.eventually (h i))).mono $ λ x hx, funext hx lemma ae_le_pi {β : ι → Type*} [Π i, preorder (β i)] {f f' : Π i, α i → β i} (h : ∀ i, f i ≤ᵐ[μ i] f' i) : (λ (x : Π i, α i) i, f i (x i)) ≤ᵐ[measure.pi μ] (λ x i, f' i (x i)) := (eventually_all.2 (λ i, tendsto_eval_ae_ae.eventually (h i))).mono $ λ x hx, hx lemma ae_le_set_pi {I : set ι} {s t : Π i, set (α i)} (h : ∀ i ∈ I, s i ≤ᵐ[μ i] t i) : (set.pi I s) ≤ᵐ[measure.pi μ] (set.pi I t) := ((eventually_all_finite (finite.of_fintype I)).2 (λ i hi, tendsto_eval_ae_ae.eventually (h i hi))).mono $ λ x hst hx i hi, hst i hi $ hx i hi lemma ae_eq_set_pi {I : set ι} {s t : Π i, set (α i)} (h : ∀ i ∈ I, s i =ᵐ[μ i] t i) : (set.pi I s) =ᵐ[measure.pi μ] (set.pi I t) := (ae_le_set_pi (λ i hi, (h i hi).le)).antisymm (ae_le_set_pi (λ i hi, (h i hi).symm.le)) section intervals variables {μ} [Π i, partial_order (α i)] [∀ i, has_no_atoms (μ i)] lemma pi_Iio_ae_eq_pi_Iic {s : set ι} {f : Π i, α i} : pi s (λ i, Iio (f i)) =ᵐ[measure.pi μ] pi s (λ i, Iic (f i)) := ae_eq_set_pi $ λ i hi, Iio_ae_eq_Iic lemma pi_Ioi_ae_eq_pi_Ici {s : set ι} {f : Π i, α i} : pi s (λ i, Ioi (f i)) =ᵐ[measure.pi μ] pi s (λ i, Ici (f i)) := ae_eq_set_pi $ λ i hi, Ioi_ae_eq_Ici lemma univ_pi_Iio_ae_eq_Iic {f : Π i, α i} : pi univ (λ i, Iio (f i)) =ᵐ[measure.pi μ] Iic f := by { rw ← pi_univ_Iic, exact pi_Iio_ae_eq_pi_Iic } lemma univ_pi_Ioi_ae_eq_Ici {f : Π i, α i} : pi univ (λ i, Ioi (f i)) =ᵐ[measure.pi μ] Ici f := by { rw ← pi_univ_Ici, exact pi_Ioi_ae_eq_pi_Ici } lemma pi_Ioo_ae_eq_pi_Icc {s : set ι} {f g : Π i, α i} : pi s (λ i, Ioo (f i) (g i)) =ᵐ[measure.pi μ] pi s (λ i, Icc (f i) (g i)) := ae_eq_set_pi $ λ i hi, Ioo_ae_eq_Icc lemma univ_pi_Ioo_ae_eq_Icc {f g : Π i, α i} : pi univ (λ i, Ioo (f i) (g i)) =ᵐ[measure.pi μ] Icc f g := by { rw ← pi_univ_Icc, exact pi_Ioo_ae_eq_pi_Icc } lemma pi_Ioc_ae_eq_pi_Icc {s : set ι} {f g : Π i, α i} : pi s (λ i, Ioc (f i) (g i)) =ᵐ[measure.pi μ] pi s (λ i, Icc (f i) (g i)) := ae_eq_set_pi $ λ i hi, Ioc_ae_eq_Icc lemma univ_pi_Ioc_ae_eq_Icc {f g : Π i, α i} : pi univ (λ i, Ioc (f i) (g i)) =ᵐ[measure.pi μ] Icc f g := by { rw ← pi_univ_Icc, exact pi_Ioc_ae_eq_pi_Icc } lemma pi_Ico_ae_eq_pi_Icc {s : set ι} {f g : Π i, α i} : pi s (λ i, Ico (f i) (g i)) =ᵐ[measure.pi μ] pi s (λ i, Icc (f i) (g i)) := ae_eq_set_pi $ λ i hi, Ico_ae_eq_Icc lemma univ_pi_Ico_ae_eq_Icc {f g : Π i, α i} : pi univ (λ i, Ico (f i) (g i)) =ᵐ[measure.pi μ] Icc f g := by { rw ← pi_univ_Icc, exact pi_Ico_ae_eq_pi_Icc } end intervals /-- If one of the measures `μ i` has no atoms, them `measure.pi µ` has no atoms. The instance below assumes that all `μ i` have no atoms. -/ lemma pi_has_no_atoms (i : ι) [has_no_atoms (μ i)] : has_no_atoms (measure.pi μ) := ⟨λ x, flip measure_mono_null (pi_hyperplane μ i (x i)) (singleton_subset_iff.2 rfl)⟩ instance [h : nonempty ι] [∀ i, has_no_atoms (μ i)] : has_no_atoms (measure.pi μ) := h.elim $ λ i, pi_has_no_atoms i instance [Π i, topological_space (α i)] [∀ i, opens_measurable_space (α i)] [∀ i, locally_finite_measure (μ i)] : locally_finite_measure (measure.pi μ) := begin refine ⟨λ x, _⟩, choose s hxs ho hμ using λ i, (μ i).exists_is_open_measure_lt_top (x i), refine ⟨pi univ s, set_pi_mem_nhds finite_univ (λ i hi, mem_nhds_sets (ho i) (hxs i)), _⟩, rw [pi_pi], exacts [ennreal.prod_lt_top (λ i _, hμ i), λ i, (ho i).measurable_set] end end measure instance measure_space.pi [Π i, measure_space (α i)] : measure_space (Π i, α i) := ⟨measure.pi (λ i, volume)⟩ lemma volume_pi [Π i, measure_space (α i)] : (volume : measure (Π i, α i)) = measure.pi (λ i, volume) := rfl lemma volume_pi_pi [Π i, measure_space (α i)] [∀ i, sigma_finite (volume : measure (α i))] (s : Π i, set (α i)) (hs : ∀ i, measurable_set (s i)) : volume (pi univ s) = ∏ i, volume (s i) := measure.pi_pi (λ i, volume) s hs end measure_theory
4ca759e732522e6168cc54963e7e924abb141a58
92b50235facfbc08dfe7f334827d47281471333b
/library/data/nat/power.lean
324b79eae1a5a3fc43c235566f604f5ddfa2ed7e
[ "Apache-2.0" ]
permissive
htzh/lean
24f6ed7510ab637379ec31af406d12584d31792c
d70c79f4e30aafecdfc4a60b5d3512199200ab6e
refs/heads/master
1,607,677,731,270
1,437,089,952,000
1,437,089,952,000
37,078,816
0
0
null
1,433,780,956,000
1,433,780,955,000
null
UTF-8
Lean
false
false
4,593
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad The power function on the natural numbers. -/ import data.nat.basic data.nat.order data.nat.div data.nat.gcd algebra.ring_power namespace nat section migrate_algebra open [classes] algebra local attribute nat.comm_semiring [instance] local attribute nat.linear_ordered_semiring [instance] definition pow (a : ℕ) (n : ℕ) : ℕ := algebra.pow a n infix ^ := pow theorem pow_le_pow_of_le {x y : ℕ} (i : ℕ) (H : x ≤ y) : x^i ≤ y^i := algebra.pow_le_pow_of_le i !zero_le H migrate from algebra with nat replacing dvd → dvd, has_le.ge → ge, has_lt.gt → gt, pow → pow hiding add_pos_of_pos_of_nonneg, add_pos_of_nonneg_of_pos, add_eq_zero_iff_eq_zero_and_eq_zero_of_nonneg_of_nonneg, le_add_of_nonneg_of_le, le_add_of_le_of_nonneg, lt_add_of_nonneg_of_lt, lt_add_of_lt_of_nonneg, lt_of_mul_lt_mul_left, lt_of_mul_lt_mul_right, pos_of_mul_pos_left, pos_of_mul_pos_right, pow_nonneg_of_nonneg end migrate_algebra -- generalize to semirings? theorem le_pow_self {x : ℕ} (H : x > 1) : ∀ i, i ≤ x^i | 0 := !zero_le | (succ j) := have xpos : x > 0, from lt.trans zero_lt_one H, have xjge1 : x^j ≥ 1, from succ_le_of_lt (pow_pos_of_pos _ xpos), have xge2 : x ≥ 2, from succ_le_of_lt H, calc succ j = j + 1 : rfl ... ≤ x^j + 1 : add_le_add_right (le_pow_self j) ... ≤ x^j + x^j : add_le_add_left xjge1 ... = x^j * (1 + 1) : by rewrite [mul.left_distrib, *mul_one] ... = x^j * 2 : rfl ... ≤ x^j * x : mul_le_mul_left _ xge2 ... = x^(succ j) : rfl -- TODO: eventually this will be subsumed under the algebraic theorems theorem mul_self_eq_pow_2 (a : nat) : a * a = pow a 2 := show a * a = pow a (succ (succ zero)), from by rewrite [*pow_succ, *pow_zero, one_mul] theorem pow_cancel_left : ∀ {a b c : nat}, a > 1 → pow a b = pow a c → b = c | a 0 0 h₁ h₂ := rfl | a (succ b) 0 h₁ h₂ := assert aeq1 : a = 1, by rewrite [pow_succ' at h₂, pow_zero at h₂]; exact (eq_one_of_mul_eq_one_right h₂), assert h₁ : 1 < 1, by rewrite [aeq1 at h₁]; exact h₁, absurd h₁ !lt.irrefl | a 0 (succ c) h₁ h₂ := assert aeq1 : a = 1, by rewrite [pow_succ' at h₂, pow_zero at h₂]; exact (eq_one_of_mul_eq_one_right (eq.symm h₂)), assert h₁ : 1 < 1, by rewrite [aeq1 at h₁]; exact h₁, absurd h₁ !lt.irrefl | a (succ b) (succ c) h₁ h₂ := assert ane0 : a ≠ 0, from assume aeq0, by rewrite [aeq0 at h₁]; exact (absurd h₁ dec_trivial), assert beqc : pow a b = pow a c, by rewrite [*pow_succ' at h₂]; exact (eq_of_mul_eq_mul_left (pos_of_ne_zero ane0) h₂), by rewrite [pow_cancel_left h₁ beqc] theorem pow_div_cancel : ∀ {a b : nat}, a ≠ 0 → pow a (succ b) div a = pow a b | a 0 h := by rewrite [pow_succ', pow_zero, mul_one, div_self (pos_of_ne_zero h)] | a (succ b) h := by rewrite [pow_succ', mul_div_cancel_left _ (pos_of_ne_zero h)] lemma dvd_pow : ∀ (i : nat) {n : nat}, n > 0 → i ∣ i^n | i 0 h := absurd h !lt.irrefl | i (succ n) h := by rewrite [pow_succ]; apply dvd_mul_left lemma dvd_pow_of_dvd_of_pos : ∀ {i j n : nat}, i ∣ j → n > 0 → i ∣ j^n | i j 0 h₁ h₂ := absurd h₂ !lt.irrefl | i j (succ n) h₁ h₂ := by rewrite [pow_succ]; apply dvd_mul_of_dvd_right h₁ lemma pow_mod_eq_zero (i : nat) {n : nat} (h : n > 0) : (i^n) mod i = 0 := iff.mp !dvd_iff_mod_eq_zero (dvd_pow i h) lemma pow_dvd_of_pow_succ_dvd {p i n : nat} : p^(succ i) ∣ n → p^i ∣ n := assume Psuccdvd, assert Pdvdsucc : p^i ∣ p^(succ i), from by rewrite [pow_succ]; apply dvd_of_eq_mul; apply rfl, dvd.trans Pdvdsucc Psuccdvd lemma dvd_of_pow_succ_dvd_mul_pow {p i n : nat} (Ppos : p > 0) : p^(succ i) ∣ (n * p^i) → p ∣ n := by rewrite [pow_succ']; apply dvd_of_mul_dvd_mul_right; apply pow_pos_of_pos _ Ppos lemma coprime_pow_right {a b} : ∀ n, coprime b a → coprime b (a^n) | 0 h := !comprime_one_right | (succ n) h := begin rewrite [pow_succ], apply coprime_mul_right, exact coprime_pow_right n h, exact h end lemma coprime_pow_left {a b} : ∀ n, coprime b a → coprime (b^n) a := λ n h, coprime_swap (coprime_pow_right n (coprime_swap h)) end nat
f676743b9a42670f3820f7fc6b194fef744d81f8
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/logic/unnamed_1555.lean
8d7b4cb03a3891463d7774b466866405e7817f41
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
436
lean
import data.real.basic -- BEGIN example {x y : ℝ} (h : x ≤ y ∧ x ≠ y) : ¬ y ≤ x := begin cases h with h₀ h₁, contrapose! h₁, exact le_antisymm h₀ h₁ end example {x y : ℝ} : x ≤ y ∧ x ≠ y → ¬ y ≤ x := begin rintros ⟨h₀, h₁⟩ h', exact h₁ (le_antisymm h₀ h') end example {x y : ℝ} : x ≤ y ∧ x ≠ y → ¬ y ≤ x := λ ⟨h₀, h₁⟩ h', h₁ (le_antisymm h₀ h') -- END
870bb10225d380f1970b68d563784e9a169f245e
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/quot.lean
5a254b5175f037df93fff95786f504c1844d7126
[]
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
23,946
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 -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.logic.relator import Mathlib.PostPort universes u_1 u_2 u_3 u_4 u namespace Mathlib /-! # Quotient types This module extends the core library's treatment of quotient types (`init.data.quot`). ## Tags quotient -/ namespace setoid theorem ext {α : Sort u_1} {s : setoid α} {t : setoid α} : (∀ (a b : α), r a b ↔ r a b) → s = t := sorry end setoid namespace quot protected instance inhabited {α : Sort u_1} {ra : α → α → Prop} [Inhabited α] : Inhabited (Quot ra) := { default := Quot.mk ra Inhabited.default } /-- Recursion on two `quotient` arguments `a` and `b`, result type depends on `⟦a⟧` and `⟦b⟧`. -/ protected def hrec_on₂ {α : Sort u_1} {β : Sort u_2} {ra : α → α → Prop} {rb : β → β → Prop} {φ : Quot ra → Quot rb → Sort u_3} (qa : Quot ra) (qb : Quot rb) (f : (a : α) → (b : β) → φ (Quot.mk ra a) (Quot.mk rb b)) (ca : ∀ {b : β} {a₁ a₂ : α}, ra a₁ a₂ → f a₁ b == f a₂ b) (cb : ∀ {a : α} {b₁ b₂ : β}, rb b₁ b₂ → f a b₁ == f a b₂) : φ qa qb := quot.hrec_on qa (fun (a : α) => quot.hrec_on qb (f a) sorry) sorry /-- Map a function `f : α → β` such that `ra x y` implies `rb (f x) (f y)` to a map `quot ra → quot rb`. -/ protected def map {α : Sort u_1} {β : Sort u_2} {ra : α → α → Prop} {rb : β → β → Prop} (f : α → β) (h : relator.lift_fun ra rb f f) : Quot ra → Quot rb := Quot.lift (fun (x : α) => Quot.mk rb (f x)) sorry /-- If `ra` is a subrelation of `ra'`, then we have a natural map `quot ra → quot ra'`. -/ protected def map_right {α : Sort u_1} {ra : α → α → Prop} {ra' : α → α → Prop} (h : ∀ (a₁ a₂ : α), ra a₁ a₂ → ra' a₁ a₂) : Quot ra → Quot ra' := quot.map id h /-- weaken the relation of a quotient -/ def factor {α : Type u_1} (r : α → α → Prop) (s : α → α → Prop) (h : ∀ (x y : α), r x y → s x y) : Quot r → Quot s := Quot.lift (Quot.mk s) sorry theorem factor_mk_eq {α : Type u_1} (r : α → α → Prop) (s : α → α → Prop) (h : ∀ (x y : α), r x y → s x y) : factor r s h ∘ Quot.mk r = Quot.mk s := rfl /-- Descends a function `f : α → β → γ` to quotients of `α` and `β`. -/ protected def lift₂ {α : Sort u_1} {β : Sort u_2} {γ : Sort u_4} {r : α → α → Prop} {s : β → β → Prop} (f : α → β → γ) (hr : ∀ (a : α) (b₁ b₂ : β), s b₁ b₂ → f a b₁ = f a b₂) (hs : ∀ (a₁ a₂ : α) (b : β), r a₁ a₂ → f a₁ b = f a₂ b) (q₁ : Quot r) (q₂ : Quot s) : γ := Quot.lift (fun (a : α) => Quot.lift (f a) (hr a)) sorry q₁ q₂ @[simp] theorem lift₂_mk {α : Sort u_1} {β : Sort u_2} {γ : Sort u_4} {r : α → α → Prop} {s : β → β → Prop} (a : α) (b : β) (f : α → β → γ) (hr : ∀ (a : α) (b₁ b₂ : β), s b₁ b₂ → f a b₁ = f a b₂) (hs : ∀ (a₁ a₂ : α) (b : β), r a₁ a₂ → f a₁ b = f a₂ b) : quot.lift₂ f hr hs (Quot.mk r a) (Quot.mk s b) = f a b := rfl /-- Descends a function `f : α → β → γ` to quotients of `α` and `β` and applies it. -/ protected def lift_on₂ {α : Sort u_1} {β : Sort u_2} {γ : Sort u_4} {r : α → α → Prop} {s : β → β → Prop} (p : Quot r) (q : Quot s) (f : α → β → γ) (hr : ∀ (a : α) (b₁ b₂ : β), s b₁ b₂ → f a b₁ = f a b₂) (hs : ∀ (a₁ a₂ : α) (b : β), r a₁ a₂ → f a₁ b = f a₂ b) : γ := quot.lift₂ f hr hs p q @[simp] theorem lift_on₂_mk {α : Sort u_1} {β : Sort u_2} {γ : Sort u_4} {r : α → α → Prop} {s : β → β → Prop} (a : α) (b : β) (f : α → β → γ) (hr : ∀ (a : α) (b₁ b₂ : β), s b₁ b₂ → f a b₁ = f a b₂) (hs : ∀ (a₁ a₂ : α) (b : β), r a₁ a₂ → f a₁ b = f a₂ b) : quot.lift_on₂ (Quot.mk r a) (Quot.mk s b) f hr hs = f a b := rfl /-- Descends a function `f : α → β → γ` to quotients of `α` and `β` wih values in a quotient of `γ`. -/ protected def map₂ {α : Sort u_1} {β : Sort u_2} {γ : Sort u_4} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} (f : α → β → γ) (hr : ∀ (a : α) (b₁ b₂ : β), s b₁ b₂ → t (f a b₁) (f a b₂)) (hs : ∀ (a₁ a₂ : α) (b : β), r a₁ a₂ → t (f a₁ b) (f a₂ b)) (q₁ : Quot r) (q₂ : Quot s) : Quot t := quot.lift₂ (fun (a : α) (b : β) => Quot.mk t (f a b)) sorry sorry q₁ q₂ @[simp] theorem map₂_mk {α : Sort u_1} {β : Sort u_2} {γ : Sort u_4} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} (f : α → β → γ) (hr : ∀ (a : α) (b₁ b₂ : β), s b₁ b₂ → t (f a b₁) (f a b₂)) (hs : ∀ (a₁ a₂ : α) (b : β), r a₁ a₂ → t (f a₁ b) (f a₂ b)) (a : α) (b : β) : quot.map₂ f hr hs (Quot.mk r a) (Quot.mk s b) = Quot.mk t (f a b) := rfl protected theorem induction_on₂ {α : Sort u_1} {β : Sort u_2} {r : α → α → Prop} {s : β → β → Prop} {δ : Quot r → Quot s → Prop} (q₁ : Quot r) (q₂ : Quot s) (h : ∀ (a : α) (b : β), δ (Quot.mk r a) (Quot.mk s b)) : δ q₁ q₂ := Quot.ind (fun (a₁ : α) => Quot.ind (fun (a₂ : β) => h a₁ a₂) q₂) q₁ protected theorem induction_on₃ {α : Sort u_1} {β : Sort u_2} {γ : Sort u_4} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} {δ : Quot r → Quot s → Quot t → Prop} (q₁ : Quot r) (q₂ : Quot s) (q₃ : Quot t) (h : ∀ (a : α) (b : β) (c : γ), δ (Quot.mk r a) (Quot.mk s b) (Quot.mk t c)) : δ q₁ q₂ q₃ := Quot.ind (fun (a₁ : α) => Quot.ind (fun (a₂ : β) => Quot.ind (fun (a₃ : γ) => h a₁ a₂ a₃) q₃) q₂) q₁ end quot namespace quotient protected instance inhabited {α : Sort u_1} [sa : setoid α] [Inhabited α] : Inhabited (quotient sa) := { default := quotient.mk Inhabited.default } /-- Induction on two `quotient` arguments `a` and `b`, result type depends on `⟦a⟧` and `⟦b⟧`. -/ protected def hrec_on₂ {α : Sort u_1} {β : Sort u_2} [sa : setoid α] [sb : setoid β] {φ : quotient sa → quotient sb → Sort u_3} (qa : quotient sa) (qb : quotient sb) (f : (a : α) → (b : β) → φ (quotient.mk a) (quotient.mk b)) (c : ∀ (a₁ : α) (b₁ : β) (a₂ : α) (b₂ : β), a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ == f a₂ b₂) : φ qa qb := quot.hrec_on₂ qa qb f sorry sorry /-- Map a function `f : α → β` that sends equivalent elements to equivalent elements to a function `quotient sa → quotient sb`. Useful to define unary operations on quotients. -/ protected def map {α : Sort u_1} {β : Sort u_2} [sa : setoid α] [sb : setoid β] (f : α → β) (h : relator.lift_fun has_equiv.equiv has_equiv.equiv f f) : quotient sa → quotient sb := quot.map f h @[simp] theorem map_mk {α : Sort u_1} {β : Sort u_2} [sa : setoid α] [sb : setoid β] (f : α → β) (h : relator.lift_fun has_equiv.equiv has_equiv.equiv f f) (x : α) : quotient.map f h (quotient.mk x) = quotient.mk (f x) := rfl /-- Map a function `f : α → β → γ` that sends equivalent elements to equivalent elements to a function `f : quotient sa → quotient sb → quotient sc`. Useful to define binary operations on quotients. -/ protected def map₂ {α : Sort u_1} {β : Sort u_2} [sa : setoid α] [sb : setoid β] {γ : Sort u_4} [sc : setoid γ] (f : α → β → γ) (h : relator.lift_fun has_equiv.equiv (has_equiv.equiv ⇒ has_equiv.equiv) f f) : quotient sa → quotient sb → quotient sc := quotient.lift₂ (fun (x : α) (y : β) => quotient.mk (f x y)) sorry end quotient theorem quot.eq {α : Type u_1} {r : α → α → Prop} {x : α} {y : α} : Quot.mk r x = Quot.mk r y ↔ eqv_gen r x y := { mp := quot.exact r, mpr := quot.eqv_gen_sound } @[simp] theorem quotient.eq {α : Sort u_1} [r : setoid α] {x : α} {y : α} : quotient.mk x = quotient.mk y ↔ x ≈ y := { mp := quotient.exact, mpr := quotient.sound } theorem forall_quotient_iff {α : Type u_1} [r : setoid α] {p : quotient r → Prop} : (∀ (a : quotient r), p a) ↔ ∀ (a : α), p (quotient.mk a) := { mp := fun (h : ∀ (a : quotient r), p a) (x : α) => h (quotient.mk x), mpr := fun (h : ∀ (a : α), p (quotient.mk a)) (a : quotient r) => quotient.induction_on a h } @[simp] theorem quotient.lift_beta {α : Sort u_1} {β : Sort u_2} [s : setoid α] (f : α → β) (h : ∀ (a b : α), a ≈ b → f a = f b) (x : α) : quotient.lift f h (quotient.mk x) = f x := rfl @[simp] theorem quotient.lift_on_beta {α : Sort u_1} {β : Sort u_2} [s : setoid α] (f : α → β) (h : ∀ (a b : α), a ≈ b → f a = f b) (x : α) : quotient.lift_on (quotient.mk x) f h = f x := rfl @[simp] theorem quotient.lift_on_beta₂ {α : Sort u_1} {β : Sort u_2} [setoid α] (f : α → α → β) (h : ∀ (a₁ a₂ b₁ b₂ : α), a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂) (x : α) (y : α) : quotient.lift_on₂ (quotient.mk x) (quotient.mk y) f h = f x y := rfl /-- `quot.mk r` is a surjective function. -/ theorem surjective_quot_mk {α : Sort u_1} (r : α → α → Prop) : function.surjective (Quot.mk r) := quot.exists_rep /-- `quotient.mk` is a surjective function. -/ theorem surjective_quotient_mk (α : Sort u_1) [s : setoid α] : function.surjective quotient.mk := quot.exists_rep /-- Choose an element of the equivalence class using the axiom of choice. Sound but noncomputable. -/ def quot.out {α : Sort u_1} {r : α → α → Prop} (q : Quot r) : α := classical.some (quot.exists_rep q) /-- Unwrap the VM representation of a quotient to obtain an element of the equivalence class. Computable but unsound. -/ @[simp] theorem quot.out_eq {α : Sort u_1} {r : α → α → Prop} (q : Quot r) : Quot.mk r (quot.out q) = q := classical.some_spec (quot.exists_rep q) /-- Choose an element of the equivalence class using the axiom of choice. Sound but noncomputable. -/ def quotient.out {α : Sort u_1} [s : setoid α] : quotient s → α := quot.out @[simp] theorem quotient.out_eq {α : Sort u_1} [s : setoid α] (q : quotient s) : quotient.mk (quotient.out q) = q := quot.out_eq q theorem quotient.mk_out {α : Sort u_1} [s : setoid α] (a : α) : quotient.out (quotient.mk a) ≈ a := quotient.exact (quotient.out_eq (quotient.mk a)) protected instance pi_setoid {ι : Sort u_1} {α : ι → Sort u_2} [(i : ι) → setoid (α i)] : setoid ((i : ι) → α i) := setoid.mk (fun (a b : (i : ι) → α i) => ∀ (i : ι), a i ≈ b i) sorry /-- Given a function `f : Π i, quotient (S i)`, returns the class of functions `Π i, α i` sending each `i` to an element of the class `f i`. -/ def quotient.choice {ι : Type u_1} {α : ι → Type u_2} [S : (i : ι) → setoid (α i)] (f : (i : ι) → quotient (S i)) : quotient Mathlib.pi_setoid := quotient.mk fun (i : ι) => quotient.out (f i) theorem quotient.choice_eq {ι : Type u_1} {α : ι → Type u_2} [(i : ι) → setoid (α i)] (f : (i : ι) → α i) : (quotient.choice fun (i : ι) => quotient.mk (f i)) = quotient.mk f := quotient.sound fun (i : ι) => quotient.mk_out (f i) theorem nonempty_quotient_iff {α : Sort u_1} (s : setoid α) : Nonempty (quotient s) ↔ Nonempty α := sorry /-- `trunc α` is the quotient of `α` by the always-true relation. This is related to the propositional truncation in HoTT, and is similar in effect to `nonempty α`, but unlike `nonempty α`, `trunc α` is data, so the VM representation is the same as `α`, and so this can be used to maintain computability. -/ def trunc (α : Sort u) := Quot fun (_x _x : α) => True theorem true_equivalence {α : Sort u_1} : equivalence fun (_x _x : α) => True := { left := fun (_x : α) => trivial, right := { left := fun (_x _x : α) (_x : True) => trivial, right := fun (_x _x _x : α) (_x _x : True) => trivial } } namespace trunc /-- Constructor for `trunc α` -/ def mk {α : Sort u_1} (a : α) : trunc α := Quot.mk (fun (_x _x : α) => True) a protected instance inhabited {α : Sort u_1} [Inhabited α] : Inhabited (trunc α) := { default := mk Inhabited.default } /-- Any constant function lifts to a function out of the truncation -/ def lift {α : Sort u_1} {β : Sort u_2} (f : α → β) (c : ∀ (a b : α), f a = f b) : trunc α → β := Quot.lift f sorry theorem ind {α : Sort u_1} {β : trunc α → Prop} : (∀ (a : α), β (mk a)) → ∀ (q : trunc α), β q := Quot.ind protected theorem lift_beta {α : Sort u_1} {β : Sort u_2} (f : α → β) (c : ∀ (a b : α), f a = f b) (a : α) : lift f c (mk a) = f a := rfl /-- Lift a constant function on `q : trunc α`. -/ protected def lift_on {α : Sort u_1} {β : Sort u_2} (q : trunc α) (f : α → β) (c : ∀ (a b : α), f a = f b) : β := lift f c q protected theorem induction_on {α : Sort u_1} {β : trunc α → Prop} (q : trunc α) (h : ∀ (a : α), β (mk a)) : β q := ind h q theorem exists_rep {α : Sort u_1} (q : trunc α) : ∃ (a : α), mk a = q := quot.exists_rep q protected theorem induction_on₂ {α : Sort u_1} {β : Sort u_2} {C : trunc α → trunc β → Prop} (q₁ : trunc α) (q₂ : trunc β) (h : ∀ (a : α) (b : β), C (mk a) (mk b)) : C q₁ q₂ := trunc.induction_on q₁ fun (a₁ : α) => trunc.induction_on q₂ (h a₁) protected theorem eq {α : Sort u_1} (a : trunc α) (b : trunc α) : a = b := trunc.induction_on₂ a b fun (x y : α) => quot.sound trivial protected instance subsingleton {α : Sort u_1} : subsingleton (trunc α) := subsingleton.intro trunc.eq /-- The `bind` operator for the `trunc` monad. -/ def bind {α : Sort u_1} {β : Sort u_2} (q : trunc α) (f : α → trunc β) : trunc β := trunc.lift_on q f sorry /-- A function `f : α → β` defines a function `map f : trunc α → trunc β`. -/ def map {α : Sort u_1} {β : Sort u_2} (f : α → β) (q : trunc α) : trunc β := bind q (mk ∘ f) protected instance monad : Monad trunc := sorry protected instance is_lawful_monad : is_lawful_monad trunc := is_lawful_monad.mk (fun (α β : Type u_1) (q : α) (f : α → trunc β) => rfl) fun (α β γ : Type u_1) (x : trunc α) (f : α → trunc β) (g : β → trunc γ) => trunc.eq (x >>= f >>= g) (x >>= fun (x : α) => f x >>= g) /-- Recursion/induction principle for `trunc`. -/ protected def rec {α : Sort u_1} {C : trunc α → Sort u_3} (f : (a : α) → C (mk a)) (h : ∀ (a b : α), Eq._oldrec (f a) (rec._proof_1 a b) = f b) (q : trunc α) : C q := quot.rec f sorry q /-- A version of `trunc.rec` taking `q : trunc α` as the first argument. -/ protected def rec_on {α : Sort u_1} {C : trunc α → Sort u_3} (q : trunc α) (f : (a : α) → C (mk a)) (h : ∀ (a b : α), Eq._oldrec (f a) (rec_on._proof_1 a b) = f b) : C q := trunc.rec f h q /-- A version of `trunc.rec_on` assuming the codomain is a `subsingleton`. -/ protected def rec_on_subsingleton {α : Sort u_1} {C : trunc α → Sort u_3} [∀ (a : α), subsingleton (C (mk a))] (q : trunc α) (f : (a : α) → C (mk a)) : C q := trunc.rec f sorry q /-- Noncomputably extract a representative of `trunc α` (using the axiom of choice). -/ def out {α : Sort u_1} : trunc α → α := quot.out @[simp] theorem out_eq {α : Sort u_1} (q : trunc α) : mk (out q) = q := trunc.eq (mk (out q)) q end trunc theorem nonempty_of_trunc {α : Sort u_1} (q : trunc α) : Nonempty α := (fun (_a : ∃ (a : α), trunc.mk a = q) => Exists.dcases_on _a fun (w : α) (h : trunc.mk w = q) => idRhs (Nonempty α) (Nonempty.intro w)) (trunc.exists_rep q) namespace quotient /- Versions of quotient definitions and lemmas ending in `'` use unification instead of typeclass inference for inferring the `setoid` argument. This is useful when there are several different quotient relations on a type, for example quotient groups, rings and modules -/ /-- A version of `quotient.mk` taking `{s : setoid α}` as an implicit argument instead of an instance argument. -/ protected def mk' {α : Sort u_1} {s₁ : setoid α} (a : α) : quotient s₁ := Quot.mk setoid.r a /-- `quotient.mk'` is a surjective function. -/ theorem surjective_quotient_mk' {α : Sort u_1} {s₁ : setoid α} : function.surjective quotient.mk' := quot.exists_rep /-- A version of `quotient.lift_on` taking `{s : setoid α}` as an implicit argument instead of an instance argument. -/ protected def lift_on' {α : Sort u_1} {φ : Sort u_4} {s₁ : setoid α} (q : quotient s₁) (f : α → φ) (h : ∀ (a b : α), setoid.r a b → f a = f b) : φ := quotient.lift_on q f h @[simp] protected theorem lift_on'_beta {α : Sort u_1} {φ : Sort u_4} {s₁ : setoid α} (f : α → φ) (h : ∀ (a b : α), setoid.r a b → f a = f b) (x : α) : quotient.lift_on' (quotient.mk' x) f h = f x := rfl /-- A version of `quotient.lift_on₂` taking `{s₁ : setoid α} {s₂ : setoid β}` as implicit arguments instead of instance arguments. -/ protected def lift_on₂' {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {s₁ : setoid α} {s₂ : setoid β} (q₁ : quotient s₁) (q₂ : quotient s₂) (f : α → β → γ) (h : ∀ (a₁ : α) (a₂ : β) (b₁ : α) (b₂ : β), setoid.r a₁ b₁ → setoid.r a₂ b₂ → f a₁ a₂ = f b₁ b₂) : γ := quotient.lift_on₂ q₁ q₂ f h @[simp] protected theorem lift_on₂'_beta {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {s₁ : setoid α} {s₂ : setoid β} (f : α → β → γ) (h : ∀ (a₁ : α) (a₂ : β) (b₁ : α) (b₂ : β), setoid.r a₁ b₁ → setoid.r a₂ b₂ → f a₁ a₂ = f b₁ b₂) (a : α) (b : β) : quotient.lift_on₂' (quotient.mk' a) (quotient.mk' b) f h = f a b := rfl /-- A version of `quotient.ind` taking `{s : setoid α}` as an implicit argument instead of an instance argument. -/ protected theorem ind' {α : Sort u_1} {s₁ : setoid α} {p : quotient s₁ → Prop} (h : ∀ (a : α), p (quotient.mk' a)) (q : quotient s₁) : p q := quotient.ind h q /-- A version of `quotient.ind₂` taking `{s₁ : setoid α} {s₂ : setoid β}` as implicit arguments instead of instance arguments. -/ protected theorem ind₂' {α : Sort u_1} {β : Sort u_2} {s₁ : setoid α} {s₂ : setoid β} {p : quotient s₁ → quotient s₂ → Prop} (h : ∀ (a₁ : α) (a₂ : β), p (quotient.mk' a₁) (quotient.mk' a₂)) (q₁ : quotient s₁) (q₂ : quotient s₂) : p q₁ q₂ := quotient.ind₂ h q₁ q₂ /-- A version of `quotient.induction_on` taking `{s : setoid α}` as an implicit argument instead of an instance argument. -/ protected theorem induction_on' {α : Sort u_1} {s₁ : setoid α} {p : quotient s₁ → Prop} (q : quotient s₁) (h : ∀ (a : α), p (quotient.mk' a)) : p q := quotient.induction_on q h /-- A version of `quotient.induction_on₂` taking `{s₁ : setoid α} {s₂ : setoid β}` as implicit arguments instead of instance arguments. -/ protected theorem induction_on₂' {α : Sort u_1} {β : Sort u_2} {s₁ : setoid α} {s₂ : setoid β} {p : quotient s₁ → quotient s₂ → Prop} (q₁ : quotient s₁) (q₂ : quotient s₂) (h : ∀ (a₁ : α) (a₂ : β), p (quotient.mk' a₁) (quotient.mk' a₂)) : p q₁ q₂ := quotient.induction_on₂ q₁ q₂ h /-- A version of `quotient.induction_on₃` taking `{s₁ : setoid α} {s₂ : setoid β} {s₃ : setoid γ}` as implicit arguments instead of instance arguments. -/ protected theorem induction_on₃' {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {s₁ : setoid α} {s₂ : setoid β} {s₃ : setoid γ} {p : quotient s₁ → quotient s₂ → quotient s₃ → Prop} (q₁ : quotient s₁) (q₂ : quotient s₂) (q₃ : quotient s₃) (h : ∀ (a₁ : α) (a₂ : β) (a₃ : γ), p (quotient.mk' a₁) (quotient.mk' a₂) (quotient.mk' a₃)) : p q₁ q₂ q₃ := quotient.induction_on₃ q₁ q₂ q₃ h /-- Recursion on a `quotient` argument `a`, result type depends on `⟦a⟧`. -/ protected def hrec_on' {α : Sort u_1} {s₁ : setoid α} {φ : quotient s₁ → Sort u_2} (qa : quotient s₁) (f : (a : α) → φ (quotient.mk' a)) (c : ∀ (a₁ a₂ : α), a₁ ≈ a₂ → f a₁ == f a₂) : φ qa := quot.hrec_on qa f c @[simp] theorem hrec_on'_mk' {α : Sort u_1} {s₁ : setoid α} {φ : quotient s₁ → Sort u_2} (f : (a : α) → φ (quotient.mk' a)) (c : ∀ (a₁ a₂ : α), a₁ ≈ a₂ → f a₁ == f a₂) (x : α) : quotient.hrec_on' (quotient.mk' x) f c = f x := rfl /-- Recursion on two `quotient` arguments `a` and `b`, result type depends on `⟦a⟧` and `⟦b⟧`. -/ protected def hrec_on₂' {α : Sort u_1} {β : Sort u_2} {s₁ : setoid α} {s₂ : setoid β} {φ : quotient s₁ → quotient s₂ → Sort u_3} (qa : quotient s₁) (qb : quotient s₂) (f : (a : α) → (b : β) → φ (quotient.mk' a) (quotient.mk' b)) (c : ∀ (a₁ : α) (b₁ : β) (a₂ : α) (b₂ : β), a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ == f a₂ b₂) : φ qa qb := quotient.hrec_on₂ qa qb f c @[simp] theorem hrec_on₂'_mk' {α : Sort u_1} {β : Sort u_2} {s₁ : setoid α} {s₂ : setoid β} {φ : quotient s₁ → quotient s₂ → Sort u_3} (f : (a : α) → (b : β) → φ (quotient.mk' a) (quotient.mk' b)) (c : ∀ (a₁ : α) (b₁ : β) (a₂ : α) (b₂ : β), a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ == f a₂ b₂) (x : α) (qb : quotient s₂) : quotient.hrec_on₂' (quotient.mk' x) qb f c = quotient.hrec_on' qb (f x) fun (b₁ b₂ : β) => c x b₁ x b₂ (setoid.refl x) := rfl /-- Map a function `f : α → β` that sends equivalent elements to equivalent elements to a function `quotient sa → quotient sb`. Useful to define unary operations on quotients. -/ protected def map' {α : Sort u_1} {β : Sort u_2} {s₁ : setoid α} {s₂ : setoid β} (f : α → β) (h : relator.lift_fun has_equiv.equiv has_equiv.equiv f f) : quotient s₁ → quotient s₂ := quot.map f h @[simp] theorem map'_mk' {α : Sort u_1} {β : Sort u_2} {s₁ : setoid α} {s₂ : setoid β} (f : α → β) (h : relator.lift_fun has_equiv.equiv has_equiv.equiv f f) (x : α) : quotient.map' f h (quotient.mk' x) = quotient.mk' (f x) := rfl /-- A version of `quotient.map₂` using curly braces and unification. -/ protected def map₂' {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {s₁ : setoid α} {s₂ : setoid β} {s₃ : setoid γ} (f : α → β → γ) (h : relator.lift_fun has_equiv.equiv (has_equiv.equiv ⇒ has_equiv.equiv) f f) : quotient s₁ → quotient s₂ → quotient s₃ := quotient.map₂ f h @[simp] theorem map₂'_mk' {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {s₁ : setoid α} {s₂ : setoid β} {s₃ : setoid γ} (f : α → β → γ) (h : relator.lift_fun has_equiv.equiv (has_equiv.equiv ⇒ has_equiv.equiv) f f) (x : α) : quotient.map₂' f h (quotient.mk' x) = quotient.map' (f x) (h (setoid.refl x)) := rfl theorem exact' {α : Sort u_1} {s₁ : setoid α} {a : α} {b : α} : quotient.mk' a = quotient.mk' b → setoid.r a b := exact theorem sound' {α : Sort u_1} {s₁ : setoid α} {a : α} {b : α} : setoid.r a b → quotient.mk' a = quotient.mk' b := sound @[simp] protected theorem eq' {α : Sort u_1} {s₁ : setoid α} {a : α} {b : α} : quotient.mk' a = quotient.mk' b ↔ setoid.r a b := eq /-- A version of `quotient.out` taking `{s₁ : setoid α}` as an implicit argument instead of an instance argument. -/ def out' {α : Sort u_1} {s₁ : setoid α} (a : quotient s₁) : α := out a @[simp] theorem out_eq' {α : Sort u_1} {s₁ : setoid α} (q : quotient s₁) : quotient.mk' (out' q) = q := out_eq q theorem mk_out' {α : Sort u_1} {s₁ : setoid α} (a : α) : setoid.r (out' (quotient.mk' a)) a := exact (out_eq (quotient.mk' a))
1312fb192aab0835c904575d8efc8e96af3cf535
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/data/set/function.lean
e55a8340dbc61f80a5c17ef5c3446490c96e5aaa
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
12,260
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Andrew Zipperer, Haitao Zhang, Minchao Wu Functions over sets. -/ import data.set.basic logic.function open function namespace set universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} /- maps to -/ /-- `maps_to f a b` means that the image of `a` is contained in `b`. -/ @[reducible] def maps_to (f : α → β) (a : set α) (b : set β) : Prop := a ⊆ f ⁻¹' b theorem maps_to' (f : α → β) (a : set α) (b : set β) : maps_to f a b ↔ f '' a ⊆ b := image_subset_iff.symm theorem maps_to_of_eq_on {f1 f2 : α → β} {a : set α} {b : set β} (h₁ : eq_on f1 f2 a) (h₂ : maps_to f1 a b) : maps_to f2 a b := λ x h, by rw [mem_preimage, ← h₁ _ h]; exact h₂ h theorem maps_to_comp {g : β → γ} {f : α → β} {a : set α} {b : set β} {c : set γ} (h₁ : maps_to g b c) (h₂ : maps_to f a b) : maps_to (g ∘ f) a c := λ x h, h₁ (h₂ h) theorem maps_to_univ (f : α → β) (a) : maps_to f a univ := λ x h, trivial theorem maps_to_image (f : α → β) (a : set α) : maps_to f a (f '' a) := by rw maps_to' theorem maps_to_range (f : α → β) (a : set α) : maps_to f a (range f) := by rw [← image_univ, maps_to']; exact image_subset _ (subset_univ _) theorem image_subset_of_maps_to_of_subset {f : α → β} {a c : set α} {b : set β} (h₁ : maps_to f a b) (h₂ : c ⊆ a) : f '' c ⊆ b := λ y hy, let ⟨x, hx, heq⟩ := hy in by rw [←heq]; apply h₁; apply h₂; assumption theorem image_subset_of_maps_to {f : α → β} {a : set α} {b : set β} (h : maps_to f a b) : f '' a ⊆ b := image_subset_of_maps_to_of_subset h (subset.refl _) /- injectivity -/ /-- `f` is injective on `a` if the restriction of `f` to `a` is injective. -/ @[reducible] def inj_on (f : α → β) (a : set α) : Prop := ∀⦃x1 x2 : α⦄, x1 ∈ a → x2 ∈ a → f x1 = f x2 → x1 = x2 theorem inj_on_empty (f : α → β) : inj_on f ∅ := λ _ _ h₁ _ _, false.elim h₁ theorem inj_on_of_eq_on {f1 f2 : α → β} {a : set α} (h₁ : eq_on f1 f2 a) (h₂ : inj_on f1 a) : inj_on f2 a := λ _ _ h₁' h₂' heq, by apply h₂ h₁' h₂'; rw [h₁, heq, ←h₁]; repeat {assumption} theorem inj_on_of_inj_on_of_subset {f : α → β} {a b : set α} (h₁ : inj_on f b) (h₂ : a ⊆ b) : inj_on f a := λ _ _ h₁' h₂' heq, h₁ (h₂ h₁') (h₂ h₂') heq lemma injective_iff_inj_on_univ {f : α → β} : injective f ↔ inj_on f univ := iff.intro (λ h _ _ _ _ heq, h heq) (λ h _ _ heq, h trivial trivial heq) lemma inj_on_of_injective {α β : Type*} {f : α → β} (s : set α) (h : injective f) : inj_on f s := inj_on_of_inj_on_of_subset (injective_iff_inj_on_univ.1 h) (subset_univ s) theorem inj_on_comp {g : β → γ} {f : α → β} {a : set α} {b : set β} (h₁ : maps_to f a b) (h₂ : inj_on g b) (h₃: inj_on f a) : inj_on (g ∘ f) a := λ _ _ h₁' h₂' heq, by apply h₃ h₁' h₂'; apply h₂; repeat {apply h₁, assumption}; assumption lemma inj_on_comp_of_injective_left {g : β → γ} {f : α → β} {a : set α} (hg : injective g) (hf : inj_on f a) : inj_on (g ∘ f) a := inj_on_comp (maps_to_univ _ _) (injective_iff_inj_on_univ.mp hg) hf lemma inj_on_iff_injective {f : α → β} {s : set α} : inj_on f s ↔ injective (λ x:s, f x.1) := ⟨λ H a b h, subtype.eq $ H a.2 b.2 h, λ H a b as bs h, congr_arg subtype.val $ @H ⟨a, as⟩ ⟨b, bs⟩ h⟩ lemma inv_fun_on_image [inhabited α] {β : Type v} {s t : set α} {f : α → β} (h : inj_on f s) (ht : t ⊆ s) : (inv_fun_on f s) '' (f '' t) = t := begin have A : ∀z, z ∈ t → ((inv_fun_on f s) ∘ f) z = z := λz hz, inv_fun_on_eq' h (ht hz), rw ← image_comp, ext, simp [A] {contextual := tt} end lemma inj_on_preimage {f : α → β} {B : set (set β)} (hB : B ⊆ powerset (range f)) : inj_on (preimage f) B := begin intros s t hs ht hst, rw [←image_preimage_eq_of_subset (hB hs), ←image_preimage_eq_of_subset (hB ht), hst] end lemma subset_image_iff {s : set α} {t : set β} (f : α → β) : t ⊆ f '' s ↔ ∃u⊆s, t = f '' u ∧ inj_on f u := begin split, { assume h, choose g hg using h, refine ⟨ {a | ∃ b (h : b ∈ t), g h = a }, _, set.ext $ assume b, ⟨_, _⟩, _⟩, { rintros a ⟨b, hb, rfl⟩, exact (hg hb).1 }, { rintros hb, exact ⟨g hb, ⟨b, hb, rfl⟩, (hg hb).2⟩ }, { rintros ⟨c, ⟨b, hb, rfl⟩, rfl⟩, rwa (hg hb).2 }, { rintros a₁ a₂ ⟨b₁, h₁, rfl⟩ ⟨b₂, h₂, rfl⟩ eq, rw [(hg h₁).2, (hg h₂).2] at eq, subst eq } }, { rintros ⟨u, hu, rfl, _⟩, exact image_subset _ hu } end lemma subset_range_iff {s : set β} (f : α → β) : s ⊆ set.range f ↔ ∃u, s = f '' u ∧ inj_on f u := by rw [← image_univ, subset_image_iff]; simp /- surjectivity -/ /-- `f` is surjective from `a` to `b` if `b` is contained in the image of `a`. -/ @[reducible] def surj_on (f : α → β) (a : set α) (b : set β) : Prop := b ⊆ f '' a theorem surj_on_of_eq_on {f1 f2 : α → β} {a : set α} {b : set β} (h₁ : eq_on f1 f2 a) (h₂ : surj_on f1 a b) : surj_on f2 a b := λ _ h, let ⟨x, hx⟩ := h₂ h in ⟨x, hx.left, by rw [←h₁ _ hx.left]; exact hx.right⟩ theorem surj_on_comp {g : β → γ} {f : α → β} {a : set α} {b : set β} {c : set γ} (h₁ : surj_on g b c) (h₂ : surj_on f a b) : surj_on (g ∘ f) a c := λ z h, let ⟨y, hy⟩ := h₁ h, ⟨x, hx⟩ := h₂ hy.left in ⟨x, hx.left, calc g (f x) = g y : by rw [hx.right] ... = z : hy.right⟩ lemma surjective_iff_surj_on_univ {f : α → β} : surjective f ↔ surj_on f univ univ := by simp [surjective, surj_on, subset_def] lemma surj_on_iff_surjective {f : α → β} {s : set α} : surj_on f s univ ↔ surjective (λ x:s, f x.1) := ⟨λ H b, let ⟨a, as, e⟩ := @H b trivial in ⟨⟨a, as⟩, e⟩, λ H b _, let ⟨⟨a, as⟩, e⟩ := H b in ⟨a, as, e⟩⟩ lemma image_eq_of_maps_to_of_surj_on {f : α → β} {a : set α} {b : set β} (h₁ : maps_to f a b) (h₂ : surj_on f a b) : f '' a = b := eq_of_subset_of_subset (image_subset_of_maps_to h₁) h₂ /- bijectivity -/ /-- `f` is bijective from `a` to `b` if `f` is injective on `a` and `f '' a = b`. -/ @[reducible] def bij_on (f : α → β) (a : set α) (b : set β) : Prop := maps_to f a b ∧ inj_on f a ∧ surj_on f a b lemma maps_to_of_bij_on {f : α → β} {a : set α} {b : set β} (h : bij_on f a b) : maps_to f a b := h.left lemma inj_on_of_bij_on {f : α → β} {a : set α} {b : set β} (h : bij_on f a b) : inj_on f a := h.right.left lemma surj_on_of_bij_on {f : α → β} {a : set α} {b : set β} (h : bij_on f a b) : surj_on f a b := h.right.right lemma bij_on.mk {f : α → β} {a : set α} {b : set β} (h₁ : maps_to f a b) (h₂ : inj_on f a) (h₃ : surj_on f a b) : bij_on f a b := ⟨h₁, h₂, h₃⟩ theorem bij_on_of_eq_on {f1 f2 : α → β} {a : set α} {b : set β} (h₁ : eq_on f1 f2 a) (h₂ : bij_on f1 a b) : bij_on f2 a b := let ⟨map, inj, surj⟩ := h₂ in ⟨maps_to_of_eq_on h₁ map, inj_on_of_eq_on h₁ inj, surj_on_of_eq_on h₁ surj⟩ lemma image_eq_of_bij_on {f : α → β} {a : set α} {b : set β} (h : bij_on f a b) : f '' a = b := image_eq_of_maps_to_of_surj_on h.left h.right.right theorem bij_on_comp {g : β → γ} {f : α → β} {a : set α} {b : set β} {c : set γ} (h₁ : bij_on g b c) (h₂: bij_on f a b) : bij_on (g ∘ f) a c := let ⟨gmap, ginj, gsurj⟩ := h₁, ⟨fmap, finj, fsurj⟩ := h₂ in ⟨maps_to_comp gmap fmap, inj_on_comp fmap ginj finj, surj_on_comp gsurj fsurj⟩ lemma bijective_iff_bij_on_univ {f : α → β} : bijective f ↔ bij_on f univ univ := iff.intro (λ h, let ⟨inj, surj⟩ := h in ⟨maps_to_univ f _, iff.mp injective_iff_inj_on_univ inj, iff.mp surjective_iff_surj_on_univ surj⟩) (λ h, let ⟨map, inj, surj⟩ := h in ⟨iff.mpr injective_iff_inj_on_univ inj, iff.mpr surjective_iff_surj_on_univ surj⟩) /- left inverse -/ /-- `g` is a left inverse to `f` on `a` means that `g (f x) = x` for all `x ∈ a`. -/ @[reducible] def left_inv_on (g : β → α) (f : α → β) (a : set α) : Prop := ∀ x ∈ a, g (f x) = x theorem left_inv_on_of_eq_on_left {g1 g2 : β → α} {f : α → β} {a : set α} {b : set β} (h₁ : maps_to f a b) (h₂ : eq_on g1 g2 b) (h₃ : left_inv_on g1 f a) : left_inv_on g2 f a := λ x h, calc g2 (f x) = g1 (f x) : eq.symm $ h₂ _ (h₁ h) ... = x : h₃ _ h theorem left_inv_on_of_eq_on_right {g : β → α} {f1 f2 : α → β} {a : set α} (h₁ : eq_on f1 f2 a) (h₂ : left_inv_on g f1 a) : left_inv_on g f2 a := λ x h, calc g (f2 x) = g (f1 x) : congr_arg g (h₁ _ h).symm ... = x : h₂ _ h theorem inj_on_of_left_inv_on {g : β → α} {f : α → β} {a : set α} (h : left_inv_on g f a) : inj_on f a := λ x₁ x₂ h₁ h₂ heq, calc x₁ = g (f x₁) : eq.symm $ h _ h₁ ... = g (f x₂) : congr_arg g heq ... = x₂ : h _ h₂ theorem left_inv_on_comp {f' : β → α} {g' : γ → β} {g : β → γ} {f : α → β} {a : set α} {b : set β} (h₁ : maps_to f a b) (h₂ : left_inv_on f' f a) (h₃ : left_inv_on g' g b) : left_inv_on (f' ∘ g') (g ∘ f) a := λ x h, calc (f' ∘ g') ((g ∘ f) x) = f' (f x) : congr_arg f' (h₃ _ (h₁ h)) ... = x : h₂ _ h /- right inverse -/ /-- `g` is a right inverse to `f` on `b` if `f (g x) = x` for all `x ∈ b`. -/ @[reducible] def right_inv_on (g : β → α) (f : α → β) (b : set β) : Prop := left_inv_on f g b theorem right_inv_on_of_eq_on_left {g1 g2 : β → α} {f : α → β} {a : set α} {b : set β} (h₁ : eq_on g1 g2 b) (h₂ : right_inv_on g1 f b) : right_inv_on g2 f b := left_inv_on_of_eq_on_right h₁ h₂ theorem right_inv_on_of_eq_on_right {g : β → α} {f1 f2 : α → β} {a : set α} {b : set β} (h₁ : maps_to g b a) (h₂ : eq_on f1 f2 a) (h₃ : right_inv_on g f1 b) : right_inv_on g f2 b := left_inv_on_of_eq_on_left h₁ h₂ h₃ theorem surj_on_of_right_inv_on {g : β → α} {f : α → β} {a : set α} {b : set β} (h₁ : maps_to g b a) (h₂ : right_inv_on g f b) : surj_on f a b := λ y h, ⟨g y, h₁ h, h₂ _ h⟩ theorem right_inv_on_comp {f' : β → α} {g' : γ → β} {g : β → γ} {f : α → β} {c : set γ} {b : set β} (g'cb : maps_to g' c b) (h₁ : right_inv_on f' f b) (h₂ : right_inv_on g' g c) : right_inv_on (f' ∘ g') (g ∘ f) c := left_inv_on_comp g'cb h₂ h₁ theorem right_inv_on_of_inj_on_of_left_inv_on {f : α → β} {g : β → α} {a : set α} {b : set β} (h₁ : maps_to f a b) (h₂ : maps_to g b a) (h₃ : inj_on f a) (h₄ : left_inv_on f g b) : right_inv_on f g a := λ x h, h₃ (h₂ $ h₁ h) h (h₄ _ (h₁ h)) theorem eq_on_of_left_inv_of_right_inv {g₁ g₂ : β → α} {f : α → β} {a : set α} {b : set β} (h₁ : maps_to g₂ b a) (h₂ : left_inv_on g₁ f a) (h₃ : right_inv_on g₂ f b) : eq_on g₁ g₂ b := λ y h, calc g₁ y = (g₁ ∘ f ∘ g₂) y : congr_arg g₁ (h₃ _ h).symm ... = g₂ y : h₂ _ (h₁ h) theorem left_inv_on_of_surj_on_right_inv_on {f : α → β} {g : β → α} {a : set α} {b : set β} (h₁ : surj_on f a b) (h₂ : right_inv_on f g a) : left_inv_on f g b := λ y h, let ⟨x, hx, heq⟩ := h₁ h in calc (f ∘ g) y = (f ∘ g ∘ f) x : congr_arg (f ∘ g) heq.symm ... = f x : congr_arg f (h₂ _ hx) ... = y : heq /- inverses -/ /-- `g` is an inverse to `f` viewed as a map from `a` to `b` -/ @[reducible] def inv_on (g : β → α) (f : α → β) (a : set α) (b : set β) : Prop := left_inv_on g f a ∧ right_inv_on g f b theorem bij_on_of_inv_on {g : β → α} {f : α → β} {a : set α} {b : set β} (h₁ : maps_to f a b) (h₂ : maps_to g b a) (h₃ : inv_on g f a b) : bij_on f a b := ⟨h₁, inj_on_of_left_inv_on h₃.left, surj_on_of_right_inv_on h₂ h₃.right⟩ end set
bd7e28cd2959a0ad6932f873d962f8a0be0e6819
4fa161becb8ce7378a709f5992a594764699e268
/src/algebra/field.lean
512be06769c43cb317c5001873f662681be3d4b2
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
11,278
lean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis, Leonardo de Moura, Johannes Hölzl, Mario Carneiro -/ import algebra.ring import algebra.group_with_zero open set set_option default_priority 100 -- see Note [default priority] set_option old_structure_cmd true universe u variables {α : Type u} @[protect_proj, ancestor ring has_inv] class division_ring (α : Type u) extends ring α, has_inv α := (mul_inv_cancel : ∀ {a : α}, a ≠ 0 → a * a⁻¹ = 1) (inv_mul_cancel : ∀ {a : α}, a ≠ 0 → a⁻¹ * a = 1) (inv_zero : (0 : α)⁻¹ = 0) (zero_ne_one : (0 : α) ≠ 1) section division_ring variables [division_ring α] {a b : α} instance division_ring.to_nonzero : nonzero α := ⟨division_ring.zero_ne_one⟩ instance division_ring_has_div : has_div α := ⟨λ a b, a * b⁻¹⟩ /-- Every division ring is a `group_with_zero`. -/ @[priority 100] -- see Note [lower instance priority] instance division_ring.to_group_with_zero : group_with_zero α := { .. ‹division_ring α›, .. (infer_instance : semiring α) } @[simp] lemma one_div_eq_inv (a : α) : 1 / a = a⁻¹ := one_mul a⁻¹ @[field_simps] lemma inv_eq_one_div (a : α) : a⁻¹ = 1 / a := by simp local attribute [simp] division_def mul_comm mul_assoc mul_left_comm mul_inv_cancel inv_mul_cancel @[field_simps] lemma mul_div_assoc' (a b c : α) : a * (b / c) = (a * b) / c := by simp [mul_div_assoc] local attribute [simp] one_inv_eq -- note: integral domain has a "mul_ne_zero". a commutative division ring is an integral -- domain, but let's not define that class for now. lemma division_ring.mul_ne_zero (ha : a ≠ 0) (hb : b ≠ 0) : a * b ≠ 0 := assume : a * b = 0, have a * 1 = 0, by rw [← mul_one_div_cancel hb, ← mul_assoc, this, zero_mul], have a = 0, by rwa mul_one at this, absurd this ha lemma mul_ne_zero_comm (h : a * b ≠ 0) : b * a ≠ 0 := have h₁ : a ≠ 0, from ne_zero_of_mul_ne_zero_right h, have h₂ : b ≠ 0, from ne_zero_of_mul_ne_zero_left h, division_ring.mul_ne_zero h₂ h₁ lemma eq_one_div_of_mul_eq_one (h : a * b = 1) : b = 1 / a := have a ≠ 0, from assume : a = 0, have 0 = (1:α), by rwa [this, zero_mul] at h, absurd this zero_ne_one, have b = (1 / a) * a * b, by rw [one_div_mul_cancel this, one_mul], show b = 1 / a, by rwa [mul_assoc, h, mul_one] at this lemma eq_one_div_of_mul_eq_one_left (h : b * a = 1) : b = 1 / a := have a ≠ 0, from assume : a = 0, have 0 = (1:α), by rwa [this, mul_zero] at h, absurd this zero_ne_one, by rw [← h, mul_div_assoc, div_self this, mul_one] lemma division_ring.one_div_mul_one_div : (1 / a) * (1 / b) = 1 / (b * a) := match classical.em (a = 0), classical.em (b = 0) with | or.inr ha, or.inr hb := have (b * a) * ((1 / a) * (1 / b)) = 1, by rw [mul_assoc, ← mul_assoc a, mul_one_div_cancel ha, one_mul, mul_one_div_cancel hb], eq_one_div_of_mul_eq_one this | or.inl ha, _ := by simp [ha] | _ , or.inl hb := by simp [hb] end lemma one_div_neg_one_eq_neg_one : (1:α) / (-1) = -1 := have (-1) * (-1) = (1:α), by rw [neg_mul_neg, one_mul], eq.symm (eq_one_div_of_mul_eq_one this) lemma one_div_neg_eq_neg_one_div (a : α) : 1 / (- a) = - (1 / a) := calc 1 / (- a) = 1 / ((-1) * a) : by rw neg_eq_neg_one_mul ... = (1 / a) * (1 / (- 1)) : by rw division_ring.one_div_mul_one_div ... = (1 / a) * (-1) : by rw one_div_neg_one_eq_neg_one ... = - (1 / a) : by rw [mul_neg_eq_neg_mul_symm, mul_one] lemma div_neg_eq_neg_div (a b : α) : b / (- a) = - (b / a) := calc b / (- a) = b * (1 / (- a)) : by rw [← inv_eq_one_div, division_def] ... = b * -(1 / a) : by rw one_div_neg_eq_neg_one_div ... = -(b * (1 / a)) : by rw neg_mul_eq_mul_neg ... = - (b * a⁻¹) : by rw inv_eq_one_div lemma neg_div (a b : α) : (-b) / a = - (b / a) := by rw [neg_eq_neg_one_mul, mul_div_assoc, ← neg_eq_neg_one_mul] @[field_simps] lemma neg_div' {α : Type*} [division_ring α] (a b : α) : - (b / a) = (-b) / a := by simp [neg_div] lemma neg_div_neg_eq (a b : α) : (-a) / (-b) = a / b := by rw [div_neg_eq_neg_div, neg_div, neg_neg] lemma one_div_one_div (a : α) : 1 / (1 / a) = a := match classical.em (a = 0) with | or.inl h := by simp [h] | or.inr h := eq.symm (eq_one_div_of_mul_eq_one_left (mul_one_div_cancel h)) end lemma eq_of_one_div_eq_one_div (h : 1 / a = 1 / b) : a = b := by rw [← one_div_one_div a, h,one_div_one_div] lemma mul_inv' (a b : α) : (b * a)⁻¹ = a⁻¹ * b⁻¹ := eq.symm $ calc a⁻¹ * b⁻¹ = (1 / a) * (1 / b) : by simp ... = (1 / (b * a)) : division_ring.one_div_mul_one_div ... = (b * a)⁻¹ : by simp lemma one_div_div (a b : α) : 1 / (a / b) = b / a := by rw [one_div_eq_inv, division_def, mul_inv', inv_inv', division_def] @[field_simps] lemma div_add_div_same (a b c : α) : a / c + b / c = (a + b) / c := eq.symm $ right_distrib a b (c⁻¹) lemma div_sub_div_same (a b c : α) : (a / c) - (b / c) = (a - b) / c := by rw [sub_eq_add_neg, ← neg_div, div_add_div_same, sub_eq_add_neg] lemma neg_inv : - a⁻¹ = (- a)⁻¹ := by rw [inv_eq_one_div, inv_eq_one_div, div_neg_eq_neg_div] lemma add_div (a b c : α) : (a + b) / c = a / c + b / c := (div_add_div_same _ _ _).symm lemma sub_div (a b c : α) : (a - b) / c = a / c - b / c := (div_sub_div_same _ _ _).symm lemma division_ring.inv_inj : a⁻¹ = b⁻¹ ↔ a = b := inv_inj'' _ _ lemma division_ring.inv_eq_iff : a⁻¹ = b ↔ b⁻¹ = a := inv_eq_iff lemma div_neg (a : α) : a / -b = -(a / b) := by rw [← div_neg_eq_neg_div] lemma inv_neg : (-a)⁻¹ = -(a⁻¹) := by rw neg_inv lemma one_div_mul_add_mul_one_div_eq_one_div_add_one_div (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (a + b) * (1 / b) = 1 / a + 1 / b := by rw [(left_distrib (1 / a)), (one_div_mul_cancel ha), right_distrib, one_mul, mul_assoc, (mul_one_div_cancel hb), mul_one, add_comm] lemma one_div_mul_sub_mul_one_div_eq_one_div_add_one_div (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (b - a) * (1 / b) = 1 / a - 1 / b := by rw [(mul_sub_left_distrib (1 / a)), (one_div_mul_cancel ha), mul_sub_right_distrib, one_mul, mul_assoc, (mul_one_div_cancel hb), mul_one] lemma div_eq_one_iff_eq (a : α) {b : α} (hb : b ≠ 0) : a / b = 1 ↔ a = b := iff.intro (assume : a / b = 1, calc a = a / b * b : by simp [hb] ... = 1 * b : by rw this ... = b : by simp) (assume : a = b, by simp [this, hb]) lemma eq_of_div_eq_one (a : α) {b : α} (Hb : b ≠ 0) : a / b = 1 → a = b := iff.mp $ div_eq_one_iff_eq a Hb lemma eq_div_iff_mul_eq (a b : α) {c : α} (hc : c ≠ 0) : a = b / c ↔ a * c = b := iff.intro (assume : a = b / c, by rw [this, (div_mul_cancel _ hc)]) (assume : a * c = b, by rw [← this, mul_div_cancel _ hc]) lemma eq_div_of_mul_eq (a b : α) {c : α} (hc : c ≠ 0) : a * c = b → a = b / c := iff.mpr $ eq_div_iff_mul_eq a b hc lemma mul_eq_of_eq_div (a b: α) {c : α} (hc : c ≠ 0) : a = b / c → a * c = b := iff.mp $ eq_div_iff_mul_eq a b hc lemma add_div_eq_mul_add_div (a b : α) {c : α} (hc : c ≠ 0) : a + b / c = (a * c + b) / c := have (a + b / c) * c = a * c + b, by rw [right_distrib, (div_mul_cancel _ hc)], (iff.mpr (eq_div_iff_mul_eq _ _ hc)) this lemma mul_mul_div (a : α) {c : α} (hc : c ≠ 0) : a = a * c * (1 / c) := by simp [hc] instance division_ring.to_domain : domain α := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, classical.by_contradiction $ λ hn, division_ring.mul_ne_zero (mt or.inl hn) (mt or.inr hn) h ..‹division_ring α›, ..(by apply_instance : semiring α) } end division_ring @[protect_proj, ancestor division_ring comm_ring] class field (α : Type u) extends comm_ring α, has_inv α := (mul_inv_cancel : ∀ {a : α}, a ≠ 0 → a * a⁻¹ = 1) (inv_zero : (0 : α)⁻¹ = 0) (zero_ne_one : (0 : α) ≠ 1) section field variable [field α] instance field.to_division_ring : division_ring α := { inv_mul_cancel := λ _ h, by rw [mul_comm, field.mul_inv_cancel h] ..show field α, by apply_instance } /-- Every field is a `comm_group_with_zero`. -/ instance field.to_comm_group_with_zero : comm_group_with_zero α := { .. (_ : group_with_zero α), .. ‹field α› } lemma one_div_add_one_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : 1 / a + 1 / b = (a + b) / (a * b) := by rw [add_comm, ← div_mul_left ha, ← div_mul_right _ hb, division_def, division_def, division_def, ← right_distrib, mul_comm a] local attribute [simp] mul_assoc mul_comm mul_left_comm lemma div_add_div (a : α) {b : α} (c : α) {d : α} (hb : b ≠ 0) (hd : d ≠ 0) : (a / b) + (c / d) = ((a * d) + (b * c)) / (b * d) := by rw [← mul_div_mul_right _ b hd, ← mul_div_mul_left c d hb, div_add_div_same] @[field_simps] lemma div_sub_div (a : α) {b : α} (c : α) {d : α} (hb : b ≠ 0) (hd : d ≠ 0) : (a / b) - (c / d) = ((a * d) - (b * c)) / (b * d) := begin simp [sub_eq_add_neg], rw [neg_eq_neg_one_mul, ← mul_div_assoc, div_add_div _ _ hb hd, ← mul_assoc, mul_comm b, mul_assoc, ← neg_eq_neg_one_mul] end lemma inv_add_inv {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ + b⁻¹ = (a + b) / (a * b) := by rw [inv_eq_one_div, inv_eq_one_div, one_div_add_one_div ha hb] lemma inv_sub_inv {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ - b⁻¹ = (b - a) / (a * b) := by rw [inv_eq_one_div, inv_eq_one_div, div_sub_div _ _ ha hb, one_mul, mul_one] @[field_simps] lemma add_div' (a b c : α) (hc : c ≠ 0) : b + a / c = (b * c + a) / c := by simpa using div_add_div b a one_ne_zero hc @[field_simps] lemma sub_div' (a b c : α) (hc : c ≠ 0) : b - a / c = (b * c - a) / c := by simpa using div_sub_div b a one_ne_zero hc @[field_simps] lemma div_add' (a b c : α) (hc : c ≠ 0) : a / c + b = (a + b * c) / c := by rwa [add_comm, add_div', add_comm] @[field_simps] lemma div_sub' (a b c : α) (hc : c ≠ 0) : a / c - b = (a - c * b) / c := by simpa using div_sub_div a b hc one_ne_zero @[priority 100] -- see Note [lower instance priority] instance field.to_integral_domain : integral_domain α := { ..‹field α›, ..division_ring.to_domain } end field namespace ring_hom section variables {β : Type*} [division_ring α] [division_ring β] (f : α →+* β) {x y : α} lemma map_ne_zero : f x ≠ 0 ↔ x ≠ 0 := ⟨mt $ λ h, h.symm ▸ f.map_zero, λ x0 h, one_ne_zero $ by rw [← f.map_one, ← mul_inv_cancel x0, f.map_mul, h, zero_mul]⟩ lemma map_eq_zero : f x = 0 ↔ x = 0 := by haveI := classical.dec; exact not_iff_not.1 f.map_ne_zero lemma map_inv : f x⁻¹ = (f x)⁻¹ := begin classical, by_cases h : x = 0, by simp [h], apply (domain.mul_right_inj (f.map_ne_zero.2 h)).1, rw [mul_inv_cancel (f.map_ne_zero.2 h), ← f.map_mul, mul_inv_cancel h, f.map_one] end lemma map_div : f (x / y) = f x / f y := (f.map_mul _ _).trans $ congr_arg _ $ f.map_inv lemma injective : function.injective f := f.injective_iff.2 (λ a ha, classical.by_contradiction $ λ ha0, by simpa [ha, f.map_mul, f.map_one, zero_ne_one] using congr_arg f (mul_inv_cancel ha0)) end end ring_hom
af5485d8d41b9fa9c82e16c3d84470d49ccfe60a
ce4db867008cc96ee6ea6a34d39c2fa7c6ccb536
/src/Par.lean
88b4e0713c11e0f2d36fec11448bda3fd172479a
[]
no_license
PatrickMassot/lean-bavard
ab0ceedd6bab43dc0444903a80b911c5fbfb23c3
92a1a8c7ff322e4f575ec709b8c5348990d64f18
refs/heads/master
1,679,565,084,665
1,616,158,570,000
1,616,158,570,000
348,144,867
1
1
null
null
null
null
UTF-8
Lean
false
false
5,636
lean
import tactic import .tokens .commun namespace tactic setup_tactic_parser @[derive has_reflect] meta inductive Par_args -- Par fait (appliqué à args) on obtient news (tel que news') | obtenir (fait : pexpr) (args : list pexpr) (news : list maybe_typed_ident) : Par_args -- Par fait (appliqué à args) on obtient news (tel que news') | choisir (fait : pexpr) (args : list pexpr) (news : list maybe_typed_ident) : Par_args -- Par fait (appliqué à args) il suffit de montrer que buts | appliquer (fait : pexpr) (args : list pexpr) (buts : list pexpr) : Par_args open Par_args /-- Parse une liste de conséquences, peut-être vide. -/ meta def on_obtient_parser : lean.parser (list maybe_typed_ident) := do { news ← tk "obtient" *> maybe_typed_ident_parser*, news' ← (tk "tel" *> tk "que" *> maybe_typed_ident_parser*) <|> pure [], pure (news ++ news') } /-- Parse une liste de conséquences pour `choose`. -/ meta def on_choisit_parser : lean.parser (list maybe_typed_ident) := do { news ← tk "choisit" *> maybe_typed_ident_parser*, news' ← (tk "tel" *> tk "que" *> maybe_typed_ident_parser*) <|> pure [], pure (news ++ news') } /-- Parse un ou plusieurs nouveaux buts. -/ meta def buts_parser : lean.parser (list pexpr) := tk "il" *> tk "suffit" *> tk "de" *> tk "montrer" *> tk "que" *> pexpr_list_or_texpr /-- Parser principal pour la tactique Par. -/ meta def Par_parser : lean.parser Par_args := with_desc "... (appliqué à ...) on obtient ... (tel que ...) / Par ... (appliqué à ...) il suffit de montrer que ..." $ do e ← texpr, args ← applique_a_parser, do { _ ← tk "on", (Par_args.obtenir e args <$> on_obtient_parser) <|> (Par_args.choisir e args <$> on_choisit_parser) } <|> (Par_args.appliquer e args <$> buts_parser) meta def verifie_type : maybe_typed_ident → tactic unit | (n, some t) := do n_type ← get_local n >>= infer_type, to_expr t >>= unify n_type | (n, none) := skip /-- Récupère de l'information d'une hypothèse ou d'un lemme ou bien réduit le but à un ou plusieurs nouveaux buts en appliquant une hypothèse ou un lemme. -/ @[interactive] meta def Par : parse Par_parser → tactic unit | (Par_args.obtenir fait args news) := focus1 (do news.mmap' (λ p : maybe_typed_ident, verifie_nom p.1), efait ← to_expr fait, applied ← mk_mapp_pexpr efait args, if news.length = 1 then do { -- Cas où il n'y a rien à déstructurer nom ← match news with | ((nom, some new) :: t) := do enew ← to_expr new, infer_type applied >>= unify enew, pure nom | ((nom, none) :: t) := pure nom | _ := fail "Il faut indiquer un nom pour l'information obtenue." -- ne devrait pas arriver end, hyp ← note nom none applied, nettoyage, news.mmap' verifie_type } else do tactic.rcases none (to_pexpr $ applied) $ rcases_patt.tuple $ news.map rcases_patt_of_maybe_typed_ident, nettoyage ) | (Par_args.choisir fait args news) := focus1 (do efait ← to_expr fait, applied ← mk_mapp_pexpr efait args, choose tt applied (news.map prod.fst), nettoyage, news.mmap' verifie_type) | (Par_args.appliquer fait args buts) := focus1 (do efait ← to_expr fait, ebuts ← buts.mmap to_expr, mk_mapp_pexpr efait args >>= apply, vrai_buts ← get_goals, let paires := list.zip vrai_buts buts, focus' (paires.map (λ p : expr × pexpr, do `(force_type %%p _) ← i_to_expr_no_subgoals ``(force_type %%p.2 %%p.1), skip)) <|> fail "Ce n'est pas ce qu'il faut démontrer") end tactic example (P Q : (ℕ → ℕ) → Prop) (h : true ∧ ∃ u : ℕ → ℕ, P u ∧ Q u) : true := begin Par h on obtient (a : true) (u : ℕ → ℕ) (b : P u) (c : Q u), trivial end example (n : ℕ) (h : ∃ k, n = 2*k) : ∃ l, n+1 = 2*l + 1 := begin Par h on obtient k hk, use k, rw hk end example (n : ℕ) (h : ∃ k, n = 2*k) : ∃ l, n+1 = 2*l + 1 := begin Par h on obtient k tel que hk : n = 2*k, use k, rw hk end example (n : ℕ) (h : ∃ k, n = 2*k) : ∃ l, n+1 = 2*l + 1 := begin success_if_fail { Par h on obtient k tel que (hk : 0 = 1), }, Par h on obtient k tel que (hk : n = 2*k), use k, rw hk end example (f g : ℕ → ℕ) (hf : ∀ y, ∃ x, f x = y) (hg : ∀ y, ∃ x, g x = y) : ∀ y, ∃ x, (g ∘ f) x = y := begin intro y, success_if_fail { Par hg appliqué à y on obtient x tel que (hx : g x = x) }, Par hg appliqué à y on obtient x tel que (hx : g x = y), Par hf appliqué à x on obtient z hz, use z, change g (f z) = y, rw [hz, hx], end example (P Q : Prop) (h : P ∧ Q) : Q := begin Par h on obtient (hP : P) (hQ : Q), exact hQ, end noncomputable example (f : ℕ → ℕ) (h : ∀ y, ∃ x, f x = y) : ℕ → ℕ := begin Par h on choisit g tel que (H : ∀ (y : ℕ), f (g y) = y), exact g, end example (P Q : Prop) (h : P → Q) (h' : P) : Q := begin Par h il suffit de montrer que P, exact h', end example (P Q R : Prop) (h : P → R → Q) (hP : P) (hR : R) : Q := begin Par h il suffit de montrer que [P, R], exact hP, exact hR end example (P Q : Prop) (h : ∀ n : ℕ, P → Q) (h' : P) : Q := begin success_if_fail { Par h appliqué à [0, 1] il suffit de montrer que P }, Par h appliqué à 0 il suffit de montrer que P, exact h', end example (Q : Prop) (h : ∀ n : ℤ, n > 0 → Q) : Q := begin Par h il suffit de montrer que (1 > 0), norm_num, end
6a7c22ce8c90cef10df86118d9ff49770cdb29af
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/ring_theory/power_series/basic.lean
7a5cae7345c2d87cbc9851edfe8f1a35231c5ce7
[]
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
52,579
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Kenny Lau -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.mv_polynomial.default import Mathlib.ring_theory.ideal.operations import Mathlib.ring_theory.multiplicity import Mathlib.ring_theory.algebra_tower import Mathlib.tactic.linarith.default import Mathlib.PostPort universes u_1 u_2 u_3 u_4 namespace Mathlib /-! # Formal power series This file defines (multivariate) formal power series and develops the basic properties of these objects. A formal power series is to a polynomial like an infinite sum is to a finite sum. We provide the natural inclusion from polynomials to formal power series. ## Generalities The file starts with setting up the (semi)ring structure on multivariate power series. `trunc n φ` truncates a formal power series to the polynomial that has the same coefficients as `φ`, for all `m ≤ n`, and `0` otherwise. If the constant coefficient of a formal power series is invertible, then this formal power series is invertible. Formal power series over a local ring form a local ring. ## Formal power series in one variable We prove that if the ring of coefficients is an integral domain, then formal power series in one variable form an integral domain. The `order` of a formal power series `φ` is the multiplicity of the variable `X` in `φ`. If the coefficients form an integral domain, then `order` is a valuation (`order_mul`, `le_order_add`). ## Implementation notes In this file we define multivariate formal power series with variables indexed by `σ` and coefficients in `R` as `mv_power_series σ R := (σ →₀ ℕ) → R`. Unfortunately there is not yet enough API to show that they are the completion of the ring of multivariate polynomials. However, we provide most of the infrastructure that is needed to do this. Once I-adic completion (topological or algebraic) is available it should not be hard to fill in the details. Formal power series in one variable are defined as `power_series R := mv_power_series unit R`. This allows us to port a lot of proofs and properties from the multivariate case to the single variable case. However, it means that formal power series are indexed by `unit →₀ ℕ`, which is of course canonically isomorphic to `ℕ`. We then build some glue to treat formal power series as if they are indexed by `ℕ`. Occasionally this leads to proofs that are uglier than expected. -/ /-- Multivariate formal power series, where `σ` is the index set of the variables and `R` is the coefficient ring.-/ def mv_power_series (σ : Type u_1) (R : Type u_2) := (σ →₀ ℕ) → R namespace mv_power_series protected instance inhabited {σ : Type u_1} {R : Type u_2} [Inhabited R] : Inhabited (mv_power_series σ R) := { default := fun (_x : σ →₀ ℕ) => Inhabited.default } protected instance has_zero {σ : Type u_1} {R : Type u_2} [HasZero R] : HasZero (mv_power_series σ R) := pi.has_zero protected instance add_monoid {σ : Type u_1} {R : Type u_2} [add_monoid R] : add_monoid (mv_power_series σ R) := pi.add_monoid protected instance add_group {σ : Type u_1} {R : Type u_2} [add_group R] : add_group (mv_power_series σ R) := pi.add_group protected instance add_comm_monoid {σ : Type u_1} {R : Type u_2} [add_comm_monoid R] : add_comm_monoid (mv_power_series σ R) := pi.add_comm_monoid protected instance add_comm_group {σ : Type u_1} {R : Type u_2} [add_comm_group R] : add_comm_group (mv_power_series σ R) := pi.add_comm_group protected instance nontrivial {σ : Type u_1} {R : Type u_2} [nontrivial R] : nontrivial (mv_power_series σ R) := function.nontrivial protected instance semimodule {σ : Type u_1} {R : Type u_2} {A : Type u_3} [semiring R] [add_comm_monoid A] [semimodule R A] : semimodule R (mv_power_series σ A) := pi.semimodule (σ →₀ ℕ) (fun (ᾰ : σ →₀ ℕ) => A) R protected instance is_scalar_tower {σ : Type u_1} {R : Type u_2} {A : Type u_3} {S : Type u_4} [semiring R] [semiring S] [add_comm_monoid A] [semimodule R A] [semimodule S A] [has_scalar R S] [is_scalar_tower R S A] : is_scalar_tower R S (mv_power_series σ A) := pi.is_scalar_tower /-- The `n`th monomial with coefficient `a` as multivariate formal power series.-/ def monomial {σ : Type u_1} (R : Type u_2) [semiring R] (n : σ →₀ ℕ) : linear_map R R (mv_power_series σ R) := linear_map.std_basis R (fun (n : σ →₀ ℕ) => R) n /-- The `n`th coefficient of a multivariate formal power series.-/ def coeff {σ : Type u_1} (R : Type u_2) [semiring R] (n : σ →₀ ℕ) : linear_map R (mv_power_series σ R) R := linear_map.proj n /-- Two multivariate formal power series are equal if all their coefficients are equal.-/ theorem ext {σ : Type u_1} {R : Type u_2} [semiring R] {φ : mv_power_series σ R} {ψ : mv_power_series σ R} (h : ∀ (n : σ →₀ ℕ), coe_fn (coeff R n) φ = coe_fn (coeff R n) ψ) : φ = ψ := funext h /-- Two multivariate formal power series are equal if and only if all their coefficients are equal.-/ theorem ext_iff {σ : Type u_1} {R : Type u_2} [semiring R] {φ : mv_power_series σ R} {ψ : mv_power_series σ R} : φ = ψ ↔ ∀ (n : σ →₀ ℕ), coe_fn (coeff R n) φ = coe_fn (coeff R n) ψ := function.funext_iff theorem coeff_monomial {σ : Type u_1} {R : Type u_2} [semiring R] (m : σ →₀ ℕ) (n : σ →₀ ℕ) (a : R) : coe_fn (coeff R m) (coe_fn (monomial R n) a) = ite (m = n) a 0 := sorry @[simp] theorem coeff_monomial_same {σ : Type u_1} {R : Type u_2} [semiring R] (n : σ →₀ ℕ) (a : R) : coe_fn (coeff R n) (coe_fn (monomial R n) a) = a := linear_map.std_basis_same R (fun (n : σ →₀ ℕ) => R) n a theorem coeff_monomial_ne {σ : Type u_1} {R : Type u_2} [semiring R] {m : σ →₀ ℕ} {n : σ →₀ ℕ} (h : m ≠ n) (a : R) : coe_fn (coeff R m) (coe_fn (monomial R n) a) = 0 := linear_map.std_basis_ne R (fun (n : σ →₀ ℕ) => R) n m h a theorem eq_of_coeff_monomial_ne_zero {σ : Type u_1} {R : Type u_2} [semiring R] {m : σ →₀ ℕ} {n : σ →₀ ℕ} {a : R} (h : coe_fn (coeff R m) (coe_fn (monomial R n) a) ≠ 0) : m = n := by_contra fun (h' : ¬m = n) => h (coeff_monomial_ne h' a) @[simp] theorem coeff_comp_monomial {σ : Type u_1} {R : Type u_2} [semiring R] (n : σ →₀ ℕ) : linear_map.comp (coeff R n) (monomial R n) = linear_map.id := linear_map.ext (coeff_monomial_same n) @[simp] theorem coeff_zero {σ : Type u_1} {R : Type u_2} [semiring R] (n : σ →₀ ℕ) : coe_fn (coeff R n) 0 = 0 := rfl protected instance has_one {σ : Type u_1} {R : Type u_2} [semiring R] : HasOne (mv_power_series σ R) := { one := coe_fn (monomial R 0) 1 } theorem coeff_one {σ : Type u_1} {R : Type u_2} [semiring R] (n : σ →₀ ℕ) : coe_fn (coeff R n) 1 = ite (n = 0) 1 0 := coeff_monomial n 0 1 theorem coeff_zero_one {σ : Type u_1} {R : Type u_2} [semiring R] : coe_fn (coeff R 0) 1 = 1 := coeff_monomial_same 0 1 theorem monomial_zero_one {σ : Type u_1} {R : Type u_2} [semiring R] : coe_fn (monomial R 0) 1 = 1 := rfl protected instance has_mul {σ : Type u_1} {R : Type u_2} [semiring R] : Mul (mv_power_series σ R) := { mul := fun (φ ψ : mv_power_series σ R) (n : σ →₀ ℕ) => finset.sum (finsupp.support (finsupp.antidiagonal n)) fun (p : (σ →₀ ℕ) × (σ →₀ ℕ)) => coe_fn (coeff R (prod.fst p)) φ * coe_fn (coeff R (prod.snd p)) ψ } theorem coeff_mul {σ : Type u_1} {R : Type u_2} [semiring R] (n : σ →₀ ℕ) (φ : mv_power_series σ R) (ψ : mv_power_series σ R) : coe_fn (coeff R n) (φ * ψ) = finset.sum (finsupp.support (finsupp.antidiagonal n)) fun (p : (σ →₀ ℕ) × (σ →₀ ℕ)) => coe_fn (coeff R (prod.fst p)) φ * coe_fn (coeff R (prod.snd p)) ψ := rfl protected theorem zero_mul {σ : Type u_1} {R : Type u_2} [semiring R] (φ : mv_power_series σ R) : 0 * φ = 0 := sorry protected theorem mul_zero {σ : Type u_1} {R : Type u_2} [semiring R] (φ : mv_power_series σ R) : φ * 0 = 0 := sorry theorem coeff_monomial_mul {σ : Type u_1} {R : Type u_2} [semiring R] (m : σ →₀ ℕ) (n : σ →₀ ℕ) (φ : mv_power_series σ R) (a : R) : coe_fn (coeff R m) (coe_fn (monomial R n) a * φ) = ite (n ≤ m) (a * coe_fn (coeff R (m - n)) φ) 0 := sorry theorem coeff_mul_monomial {σ : Type u_1} {R : Type u_2} [semiring R] (m : σ →₀ ℕ) (n : σ →₀ ℕ) (φ : mv_power_series σ R) (a : R) : coe_fn (coeff R m) (φ * coe_fn (monomial R n) a) = ite (n ≤ m) (coe_fn (coeff R (m - n)) φ * a) 0 := sorry theorem coeff_add_monomial_mul {σ : Type u_1} {R : Type u_2} [semiring R] (m : σ →₀ ℕ) (n : σ →₀ ℕ) (φ : mv_power_series σ R) (a : R) : coe_fn (coeff R (m + n)) (coe_fn (monomial R m) a * φ) = a * coe_fn (coeff R n) φ := sorry theorem coeff_add_mul_monomial {σ : Type u_1} {R : Type u_2} [semiring R] (m : σ →₀ ℕ) (n : σ →₀ ℕ) (φ : mv_power_series σ R) (a : R) : coe_fn (coeff R (m + n)) (φ * coe_fn (monomial R n) a) = coe_fn (coeff R m) φ * a := sorry protected theorem one_mul {σ : Type u_1} {R : Type u_2} [semiring R] (φ : mv_power_series σ R) : 1 * φ = φ := sorry protected theorem mul_one {σ : Type u_1} {R : Type u_2} [semiring R] (φ : mv_power_series σ R) : φ * 1 = φ := sorry protected theorem mul_add {σ : Type u_1} {R : Type u_2} [semiring R] (φ₁ : mv_power_series σ R) (φ₂ : mv_power_series σ R) (φ₃ : mv_power_series σ R) : φ₁ * (φ₂ + φ₃) = φ₁ * φ₂ + φ₁ * φ₃ := sorry protected theorem add_mul {σ : Type u_1} {R : Type u_2} [semiring R] (φ₁ : mv_power_series σ R) (φ₂ : mv_power_series σ R) (φ₃ : mv_power_series σ R) : (φ₁ + φ₂) * φ₃ = φ₁ * φ₃ + φ₂ * φ₃ := sorry protected theorem mul_assoc {σ : Type u_1} {R : Type u_2} [semiring R] (φ₁ : mv_power_series σ R) (φ₂ : mv_power_series σ R) (φ₃ : mv_power_series σ R) : φ₁ * φ₂ * φ₃ = φ₁ * (φ₂ * φ₃) := sorry protected instance semiring {σ : Type u_1} {R : Type u_2} [semiring R] : semiring (mv_power_series σ R) := semiring.mk add_comm_monoid.add sorry add_comm_monoid.zero sorry sorry sorry Mul.mul mv_power_series.mul_assoc 1 mv_power_series.one_mul mv_power_series.mul_one mv_power_series.zero_mul mv_power_series.mul_zero mv_power_series.mul_add mv_power_series.add_mul protected instance comm_semiring {σ : Type u_1} {R : Type u_2} [comm_semiring R] : comm_semiring (mv_power_series σ R) := comm_semiring.mk semiring.add sorry semiring.zero sorry sorry sorry semiring.mul sorry semiring.one sorry sorry sorry sorry sorry sorry sorry protected instance ring {σ : Type u_1} {R : Type u_2} [ring R] : ring (mv_power_series σ R) := ring.mk semiring.add sorry semiring.zero sorry sorry add_comm_group.neg add_comm_group.sub sorry sorry semiring.mul sorry semiring.one sorry sorry sorry sorry protected instance comm_ring {σ : Type u_1} {R : Type u_2} [comm_ring R] : comm_ring (mv_power_series σ R) := comm_ring.mk comm_semiring.add sorry comm_semiring.zero sorry sorry add_comm_group.neg add_comm_group.sub sorry sorry comm_semiring.mul sorry comm_semiring.one sorry sorry sorry sorry sorry theorem monomial_mul_monomial {σ : Type u_1} {R : Type u_2} [semiring R] (m : σ →₀ ℕ) (n : σ →₀ ℕ) (a : R) (b : R) : coe_fn (monomial R m) a * coe_fn (monomial R n) b = coe_fn (monomial R (m + n)) (a * b) := sorry /-- The constant multivariate formal power series.-/ def C (σ : Type u_1) (R : Type u_2) [semiring R] : R →+* mv_power_series σ R := ring_hom.mk (linear_map.to_fun (monomial R 0)) sorry sorry sorry sorry @[simp] theorem monomial_zero_eq_C {σ : Type u_1} {R : Type u_2} [semiring R] : ⇑(monomial R 0) = ⇑(C σ R) := rfl theorem monomial_zero_eq_C_apply {σ : Type u_1} {R : Type u_2} [semiring R] (a : R) : coe_fn (monomial R 0) a = coe_fn (C σ R) a := rfl theorem coeff_C {σ : Type u_1} {R : Type u_2} [semiring R] (n : σ →₀ ℕ) (a : R) : coe_fn (coeff R n) (coe_fn (C σ R) a) = ite (n = 0) a 0 := coeff_monomial n 0 a theorem coeff_zero_C {σ : Type u_1} {R : Type u_2} [semiring R] (a : R) : coe_fn (coeff R 0) (coe_fn (C σ R) a) = a := coeff_monomial_same 0 a /-- The variables of the multivariate formal power series ring.-/ def X {σ : Type u_1} {R : Type u_2} [semiring R] (s : σ) : mv_power_series σ R := coe_fn (monomial R (finsupp.single s 1)) 1 theorem coeff_X {σ : Type u_1} {R : Type u_2} [semiring R] (n : σ →₀ ℕ) (s : σ) : coe_fn (coeff R n) (X s) = ite (n = finsupp.single s 1) 1 0 := coeff_monomial n (finsupp.single s 1) 1 theorem coeff_index_single_X {σ : Type u_1} {R : Type u_2} [semiring R] (s : σ) (t : σ) : coe_fn (coeff R (finsupp.single t 1)) (X s) = ite (t = s) 1 0 := sorry @[simp] theorem coeff_index_single_self_X {σ : Type u_1} {R : Type u_2} [semiring R] (s : σ) : coe_fn (coeff R (finsupp.single s 1)) (X s) = 1 := coeff_monomial_same (finsupp.single s 1) 1 theorem coeff_zero_X {σ : Type u_1} {R : Type u_2} [semiring R] (s : σ) : coe_fn (coeff R 0) (X s) = 0 := sorry theorem X_def {σ : Type u_1} {R : Type u_2} [semiring R] (s : σ) : X s = coe_fn (monomial R (finsupp.single s 1)) 1 := rfl theorem X_pow_eq {σ : Type u_1} {R : Type u_2} [semiring R] (s : σ) (n : ℕ) : X s ^ n = coe_fn (monomial R (finsupp.single s n)) 1 := sorry theorem coeff_X_pow {σ : Type u_1} {R : Type u_2} [semiring R] (m : σ →₀ ℕ) (s : σ) (n : ℕ) : coe_fn (coeff R m) (X s ^ n) = ite (m = finsupp.single s n) 1 0 := sorry @[simp] theorem coeff_mul_C {σ : Type u_1} {R : Type u_2} [semiring R] (n : σ →₀ ℕ) (φ : mv_power_series σ R) (a : R) : coe_fn (coeff R n) (φ * coe_fn (C σ R) a) = coe_fn (coeff R n) φ * a := sorry @[simp] theorem coeff_C_mul {σ : Type u_1} {R : Type u_2} [semiring R] (n : σ →₀ ℕ) (φ : mv_power_series σ R) (a : R) : coe_fn (coeff R n) (coe_fn (C σ R) a * φ) = a * coe_fn (coeff R n) φ := sorry theorem coeff_zero_mul_X {σ : Type u_1} {R : Type u_2} [semiring R] (φ : mv_power_series σ R) (s : σ) : coe_fn (coeff R 0) (φ * X s) = 0 := sorry /-- The constant coefficient of a formal power series.-/ def constant_coeff (σ : Type u_1) (R : Type u_2) [semiring R] : mv_power_series σ R →+* R := ring_hom.mk (⇑(coeff R 0)) coeff_zero_one sorry sorry sorry @[simp] theorem coeff_zero_eq_constant_coeff {σ : Type u_1} {R : Type u_2} [semiring R] : ⇑(coeff R 0) = ⇑(constant_coeff σ R) := rfl theorem coeff_zero_eq_constant_coeff_apply {σ : Type u_1} {R : Type u_2} [semiring R] (φ : mv_power_series σ R) : coe_fn (coeff R 0) φ = coe_fn (constant_coeff σ R) φ := rfl @[simp] theorem constant_coeff_C {σ : Type u_1} {R : Type u_2} [semiring R] (a : R) : coe_fn (constant_coeff σ R) (coe_fn (C σ R) a) = a := rfl @[simp] theorem constant_coeff_comp_C {σ : Type u_1} {R : Type u_2} [semiring R] : ring_hom.comp (constant_coeff σ R) (C σ R) = ring_hom.id R := rfl @[simp] theorem constant_coeff_zero {σ : Type u_1} {R : Type u_2} [semiring R] : coe_fn (constant_coeff σ R) 0 = 0 := rfl @[simp] theorem constant_coeff_one {σ : Type u_1} {R : Type u_2} [semiring R] : coe_fn (constant_coeff σ R) 1 = 1 := rfl @[simp] theorem constant_coeff_X {σ : Type u_1} {R : Type u_2} [semiring R] (s : σ) : coe_fn (constant_coeff σ R) (X s) = 0 := coeff_zero_X s /-- If a multivariate formal power series is invertible, then so is its constant coefficient.-/ theorem is_unit_constant_coeff {σ : Type u_1} {R : Type u_2} [semiring R] (φ : mv_power_series σ R) (h : is_unit φ) : is_unit (coe_fn (constant_coeff σ R) φ) := is_unit.map' (⇑(constant_coeff σ R)) h @[simp] theorem coeff_smul {σ : Type u_1} {R : Type u_2} [semiring R] (f : mv_power_series σ R) (n : σ →₀ ℕ) (a : R) : coe_fn (coeff R n) (a • f) = a * coe_fn (coeff R n) f := rfl theorem X_inj {σ : Type u_1} {R : Type u_2} [semiring R] [nontrivial R] {s : σ} {t : σ} : X s = X t ↔ s = t := sorry /-- The map between multivariate formal power series induced by a map on the coefficients.-/ def map (σ : Type u_1) {R : Type u_2} {S : Type u_3} [semiring R] [semiring S] (f : R →+* S) : mv_power_series σ R →+* mv_power_series σ S := ring_hom.mk (fun (φ : mv_power_series σ R) (n : σ →₀ ℕ) => coe_fn f (coe_fn (coeff R n) φ)) sorry sorry sorry sorry @[simp] theorem map_id {σ : Type u_1} {R : Type u_2} [semiring R] : map σ (ring_hom.id R) = ring_hom.id (mv_power_series σ R) := rfl theorem map_comp {σ : Type u_1} {R : Type u_2} {S : Type u_3} {T : Type u_4} [semiring R] [semiring S] [semiring T] (f : R →+* S) (g : S →+* T) : map σ (ring_hom.comp g f) = ring_hom.comp (map σ g) (map σ f) := rfl @[simp] theorem coeff_map {σ : Type u_1} {R : Type u_2} {S : Type u_3} [semiring R] [semiring S] (f : R →+* S) (n : σ →₀ ℕ) (φ : mv_power_series σ R) : coe_fn (coeff S n) (coe_fn (map σ f) φ) = coe_fn f (coe_fn (coeff R n) φ) := rfl @[simp] theorem constant_coeff_map {σ : Type u_1} {R : Type u_2} {S : Type u_3} [semiring R] [semiring S] (f : R →+* S) (φ : mv_power_series σ R) : coe_fn (constant_coeff σ S) (coe_fn (map σ f) φ) = coe_fn f (coe_fn (constant_coeff σ R) φ) := rfl @[simp] theorem map_monomial {σ : Type u_1} {R : Type u_2} {S : Type u_3} [semiring R] [semiring S] (f : R →+* S) (n : σ →₀ ℕ) (a : R) : coe_fn (map σ f) (coe_fn (monomial R n) a) = coe_fn (monomial S n) (coe_fn f a) := sorry @[simp] theorem map_C {σ : Type u_1} {R : Type u_2} {S : Type u_3} [semiring R] [semiring S] (f : R →+* S) (a : R) : coe_fn (map σ f) (coe_fn (C σ R) a) = coe_fn (C σ S) (coe_fn f a) := map_monomial f 0 a @[simp] theorem map_X {σ : Type u_1} {R : Type u_2} {S : Type u_3} [semiring R] [semiring S] (f : R →+* S) (s : σ) : coe_fn (map σ f) (X s) = X s := sorry protected instance algebra {σ : Type u_1} {R : Type u_2} {A : Type u_3} [comm_semiring R] [semiring A] [algebra R A] : algebra R (mv_power_series σ A) := algebra.mk (ring_hom.comp (map σ (algebra_map R A)) (C σ R)) sorry sorry /-- Auxiliary definition for the truncation function. -/ def trunc_fun {σ : Type u_1} {R : Type u_2} [comm_semiring R] (n : σ →₀ ℕ) (φ : mv_power_series σ R) : mv_polynomial σ R := finsupp.mk (finset.filter (fun (m : σ →₀ ℕ) => coe_fn (coeff R m) φ ≠ 0) (finset.image prod.fst (finsupp.support (finsupp.antidiagonal n)))) (fun (m : σ →₀ ℕ) => ite (m ≤ n) (coe_fn (coeff R m) φ) 0) sorry /-- The `n`th truncation of a multivariate formal power series to a multivariate polynomial -/ def trunc {σ : Type u_1} (R : Type u_2) [comm_semiring R] (n : σ →₀ ℕ) : mv_power_series σ R →+ mv_polynomial σ R := add_monoid_hom.mk (trunc_fun n) sorry sorry theorem coeff_trunc {σ : Type u_1} {R : Type u_2} [comm_semiring R] (n : σ →₀ ℕ) (m : σ →₀ ℕ) (φ : mv_power_series σ R) : mv_polynomial.coeff m (coe_fn (trunc R n) φ) = ite (m ≤ n) (coe_fn (coeff R m) φ) 0 := rfl @[simp] theorem trunc_one {σ : Type u_1} {R : Type u_2} [comm_semiring R] (n : σ →₀ ℕ) : coe_fn (trunc R n) 1 = 1 := sorry @[simp] theorem trunc_C {σ : Type u_1} {R : Type u_2} [comm_semiring R] (n : σ →₀ ℕ) (a : R) : coe_fn (trunc R n) (coe_fn (C σ R) a) = coe_fn mv_polynomial.C a := sorry theorem X_pow_dvd_iff {σ : Type u_1} {R : Type u_2} [comm_semiring R] {s : σ} {n : ℕ} {φ : mv_power_series σ R} : X s ^ n ∣ φ ↔ ∀ (m : σ →₀ ℕ), coe_fn m s < n → coe_fn (coeff R m) φ = 0 := sorry theorem X_dvd_iff {σ : Type u_1} {R : Type u_2} [comm_semiring R] {s : σ} {φ : mv_power_series σ R} : X s ∣ φ ↔ ∀ (m : σ →₀ ℕ), coe_fn m s = 0 → coe_fn (coeff R m) φ = 0 := sorry /- The inverse of a multivariate formal power series is defined by well-founded recursion on the coeffients of the inverse. -/ /-- Auxiliary definition that unifies the totalised inverse formal power series `(_)⁻¹` and the inverse formal power series that depends on an inverse of the constant coefficient `inv_of_unit`.-/ protected def inv.aux {σ : Type u_1} {R : Type u_2} [ring R] (a : R) (φ : mv_power_series σ R) : mv_power_series σ R := sorry theorem coeff_inv_aux {σ : Type u_1} {R : Type u_2} [ring R] (n : σ →₀ ℕ) (a : R) (φ : mv_power_series σ R) : coe_fn (coeff R n) (inv.aux a φ) = ite (n = 0) a (-a * finset.sum (finsupp.support (finsupp.antidiagonal n)) fun (x : (σ →₀ ℕ) × (σ →₀ ℕ)) => ite (prod.snd x < n) (coe_fn (coeff R (prod.fst x)) φ * coe_fn (coeff R (prod.snd x)) (inv.aux a φ)) 0) := sorry /-- A multivariate formal power series is invertible if the constant coefficient is invertible.-/ def inv_of_unit {σ : Type u_1} {R : Type u_2} [ring R] (φ : mv_power_series σ R) (u : units R) : mv_power_series σ R := inv.aux (↑(u⁻¹)) φ theorem coeff_inv_of_unit {σ : Type u_1} {R : Type u_2} [ring R] (n : σ →₀ ℕ) (φ : mv_power_series σ R) (u : units R) : coe_fn (coeff R n) (inv_of_unit φ u) = ite (n = 0) (↑(u⁻¹)) (-↑(u⁻¹) * finset.sum (finsupp.support (finsupp.antidiagonal n)) fun (x : (σ →₀ ℕ) × (σ →₀ ℕ)) => ite (prod.snd x < n) (coe_fn (coeff R (prod.fst x)) φ * coe_fn (coeff R (prod.snd x)) (inv_of_unit φ u)) 0) := coeff_inv_aux n (↑(u⁻¹)) φ @[simp] theorem constant_coeff_inv_of_unit {σ : Type u_1} {R : Type u_2} [ring R] (φ : mv_power_series σ R) (u : units R) : coe_fn (constant_coeff σ R) (inv_of_unit φ u) = ↑(u⁻¹) := sorry theorem mul_inv_of_unit {σ : Type u_1} {R : Type u_2} [ring R] (φ : mv_power_series σ R) (u : units R) (h : coe_fn (constant_coeff σ R) φ = ↑u) : φ * inv_of_unit φ u = 1 := sorry /-- Multivariate formal power series over a local ring form a local ring. -/ protected instance is_local_ring {σ : Type u_1} {R : Type u_2} [comm_ring R] [local_ring R] : local_ring (mv_power_series σ R) := sorry -- TODO(jmc): once adic topology lands, show that this is complete -- Thanks to the linter for informing us that this instance does -- not actually need R and S to be local rings! /-- The map `A[[X]] → B[[X]]` induced by a local ring hom `A → B` is local -/ protected instance map.is_local_ring_hom {σ : Type u_1} {R : Type u_2} {S : Type u_3} [comm_ring R] [comm_ring S] (f : R →+* S) [is_local_ring_hom f] : is_local_ring_hom (map σ f) := is_local_ring_hom.mk fun (φ : mv_power_series σ R) (ᾰ : is_unit (coe_fn (map σ f) φ)) => Exists.dcases_on ᾰ fun (ψ : units (mv_power_series σ S)) (h : ↑ψ = coe_fn (map σ f) φ) => Exists.dcases_on (is_unit_of_map_unit f (coe_fn (constant_coeff σ R) φ) (eq.mp (Eq._oldrec (Eq.refl (is_unit (coe_fn (constant_coeff σ S) ↑ψ))) (eq.mp (Eq._oldrec (Eq.refl (coe_fn (constant_coeff σ S) ↑ψ = coe_fn (constant_coeff σ S) (coe_fn (map σ f) φ))) (constant_coeff_map f φ)) (congr_arg (⇑(constant_coeff σ S)) h))) (is_unit_constant_coeff (↑ψ) (is_unit_unit ψ)))) fun (c : units R) (hc : ↑c = coe_fn (constant_coeff σ R) φ) => is_unit_of_mul_eq_one φ (inv_of_unit φ c) (mul_inv_of_unit φ c (Eq.symm hc)) protected instance local_ring {σ : Type u_1} {R : Type u_2} [comm_ring R] [local_ring R] : local_ring (mv_power_series σ R) := local_ring.mk local_ring.is_local /-- The inverse `1/f` of a multivariable power series `f` over a field -/ protected def inv {σ : Type u_1} {k : Type u_3} [field k] (φ : mv_power_series σ k) : mv_power_series σ k := sorry protected instance has_inv {σ : Type u_1} {k : Type u_3} [field k] : has_inv (mv_power_series σ k) := has_inv.mk mv_power_series.inv theorem coeff_inv {σ : Type u_1} {k : Type u_3} [field k] (n : σ →₀ ℕ) (φ : mv_power_series σ k) : coe_fn (coeff k n) (φ⁻¹) = ite (n = 0) (coe_fn (constant_coeff σ k) φ⁻¹) (-(coe_fn (constant_coeff σ k) φ⁻¹) * finset.sum (finsupp.support (finsupp.antidiagonal n)) fun (x : (σ →₀ ℕ) × (σ →₀ ℕ)) => ite (prod.snd x < n) (coe_fn (coeff k (prod.fst x)) φ * coe_fn (coeff k (prod.snd x)) (φ⁻¹)) 0) := coeff_inv_aux n (coe_fn (constant_coeff σ k) φ⁻¹) φ @[simp] theorem constant_coeff_inv {σ : Type u_1} {k : Type u_3} [field k] (φ : mv_power_series σ k) : coe_fn (constant_coeff σ k) (φ⁻¹) = (coe_fn (constant_coeff σ k) φ⁻¹) := sorry theorem inv_eq_zero {σ : Type u_1} {k : Type u_3} [field k] {φ : mv_power_series σ k} : φ⁻¹ = 0 ↔ coe_fn (constant_coeff σ k) φ = 0 := sorry @[simp] theorem inv_of_unit_eq {σ : Type u_1} {k : Type u_3} [field k] (φ : mv_power_series σ k) (h : coe_fn (constant_coeff σ k) φ ≠ 0) : inv_of_unit φ (units.mk0 (coe_fn (constant_coeff σ k) φ) h) = (φ⁻¹) := rfl @[simp] theorem inv_of_unit_eq' {σ : Type u_1} {k : Type u_3} [field k] (φ : mv_power_series σ k) (u : units k) (h : coe_fn (constant_coeff σ k) φ = ↑u) : inv_of_unit φ u = (φ⁻¹) := sorry @[simp] protected theorem mul_inv {σ : Type u_1} {k : Type u_3} [field k] (φ : mv_power_series σ k) (h : coe_fn (constant_coeff σ k) φ ≠ 0) : φ * (φ⁻¹) = 1 := sorry @[simp] protected theorem inv_mul {σ : Type u_1} {k : Type u_3} [field k] (φ : mv_power_series σ k) (h : coe_fn (constant_coeff σ k) φ ≠ 0) : φ⁻¹ * φ = 1 := eq.mpr (id (Eq._oldrec (Eq.refl (φ⁻¹ * φ = 1)) (mul_comm (φ⁻¹) φ))) (eq.mpr (id (Eq._oldrec (Eq.refl (φ * (φ⁻¹) = 1)) (mv_power_series.mul_inv φ h))) (Eq.refl 1)) protected theorem eq_mul_inv_iff_mul_eq {σ : Type u_1} {k : Type u_3} [field k] {φ₁ : mv_power_series σ k} {φ₂ : mv_power_series σ k} {φ₃ : mv_power_series σ k} (h : coe_fn (constant_coeff σ k) φ₃ ≠ 0) : φ₁ = φ₂ * (φ₃⁻¹) ↔ φ₁ * φ₃ = φ₂ := sorry protected theorem eq_inv_iff_mul_eq_one {σ : Type u_1} {k : Type u_3} [field k] {φ : mv_power_series σ k} {ψ : mv_power_series σ k} (h : coe_fn (constant_coeff σ k) ψ ≠ 0) : φ = (ψ⁻¹) ↔ φ * ψ = 1 := eq.mpr (id (Eq._oldrec (Eq.refl (φ = (ψ⁻¹) ↔ φ * ψ = 1)) (Eq.symm (propext (mv_power_series.eq_mul_inv_iff_mul_eq h))))) (eq.mpr (id (Eq._oldrec (Eq.refl (φ = (ψ⁻¹) ↔ φ = 1 * (ψ⁻¹))) (one_mul (ψ⁻¹)))) (iff.refl (φ = (ψ⁻¹)))) protected theorem inv_eq_iff_mul_eq_one {σ : Type u_1} {k : Type u_3} [field k] {φ : mv_power_series σ k} {ψ : mv_power_series σ k} (h : coe_fn (constant_coeff σ k) ψ ≠ 0) : ψ⁻¹ = φ ↔ φ * ψ = 1 := eq.mpr (id (Eq._oldrec (Eq.refl (ψ⁻¹ = φ ↔ φ * ψ = 1)) (propext eq_comm))) (eq.mpr (id (Eq._oldrec (Eq.refl (φ = (ψ⁻¹) ↔ φ * ψ = 1)) (propext (mv_power_series.eq_inv_iff_mul_eq_one h)))) (iff.refl (φ * ψ = 1))) end mv_power_series namespace mv_polynomial /-- The natural inclusion from multivariate polynomials into multivariate formal power series.-/ protected instance coe_to_mv_power_series {σ : Type u_1} {R : Type u_2} [comm_semiring R] : has_coe (mv_polynomial σ R) (mv_power_series σ R) := has_coe.mk fun (φ : mv_polynomial σ R) (n : σ →₀ ℕ) => coeff n φ @[simp] theorem coeff_coe {σ : Type u_1} {R : Type u_2} [comm_semiring R] (φ : mv_polynomial σ R) (n : σ →₀ ℕ) : coe_fn (mv_power_series.coeff R n) ↑φ = coeff n φ := rfl @[simp] theorem coe_monomial {σ : Type u_1} {R : Type u_2} [comm_semiring R] (n : σ →₀ ℕ) (a : R) : ↑(monomial n a) = coe_fn (mv_power_series.monomial R n) a := sorry @[simp] theorem coe_zero {σ : Type u_1} {R : Type u_2} [comm_semiring R] : ↑0 = 0 := rfl @[simp] theorem coe_one {σ : Type u_1} {R : Type u_2} [comm_semiring R] : ↑1 = 1 := coe_monomial 0 1 @[simp] theorem coe_add {σ : Type u_1} {R : Type u_2} [comm_semiring R] (φ : mv_polynomial σ R) (ψ : mv_polynomial σ R) : ↑(φ + ψ) = ↑φ + ↑ψ := rfl @[simp] theorem coe_mul {σ : Type u_1} {R : Type u_2} [comm_semiring R] (φ : mv_polynomial σ R) (ψ : mv_polynomial σ R) : ↑(φ * ψ) = ↑φ * ↑ψ := sorry @[simp] theorem coe_C {σ : Type u_1} {R : Type u_2} [comm_semiring R] (a : R) : ↑(coe_fn C a) = coe_fn (mv_power_series.C σ R) a := coe_monomial 0 a @[simp] theorem coe_X {σ : Type u_1} {R : Type u_2} [comm_semiring R] (s : σ) : ↑(X s) = mv_power_series.X s := coe_monomial (finsupp.single s 1) 1 /-- The coercion from multivariable polynomials to multivariable power series as a ring homomorphism. -/ -- TODO as an algebra homomorphism? def coe_to_mv_power_series.ring_hom {σ : Type u_1} {R : Type u_2} [comm_semiring R] : mv_polynomial σ R →+* mv_power_series σ R := ring_hom.mk coe coe_one coe_mul coe_zero coe_add end mv_polynomial /-- Formal power series over the coefficient ring `R`.-/ def power_series (R : Type u_1) := mv_power_series Unit R namespace power_series protected instance inhabited {R : Type u_1} [Inhabited R] : Inhabited (power_series R) := mv_power_series.inhabited protected instance add_monoid {R : Type u_1} [add_monoid R] : add_monoid (power_series R) := mv_power_series.add_monoid protected instance add_group {R : Type u_1} [add_group R] : add_group (power_series R) := mv_power_series.add_group protected instance add_comm_monoid {R : Type u_1} [add_comm_monoid R] : add_comm_monoid (power_series R) := mv_power_series.add_comm_monoid protected instance add_comm_group {R : Type u_1} [add_comm_group R] : add_comm_group (power_series R) := mv_power_series.add_comm_group protected instance semiring {R : Type u_1} [semiring R] : semiring (power_series R) := mv_power_series.semiring protected instance comm_semiring {R : Type u_1} [comm_semiring R] : comm_semiring (power_series R) := mv_power_series.comm_semiring protected instance ring {R : Type u_1} [ring R] : ring (power_series R) := mv_power_series.ring protected instance comm_ring {R : Type u_1} [comm_ring R] : comm_ring (power_series R) := mv_power_series.comm_ring protected instance nontrivial {R : Type u_1} [nontrivial R] : nontrivial (power_series R) := mv_power_series.nontrivial protected instance semimodule {R : Type u_1} {A : Type u_2} [semiring R] [add_comm_monoid A] [semimodule R A] : semimodule R (power_series A) := mv_power_series.semimodule protected instance is_scalar_tower {R : Type u_1} {A : Type u_2} {S : Type u_3} [semiring R] [semiring S] [add_comm_monoid A] [semimodule R A] [semimodule S A] [has_scalar R S] [is_scalar_tower R S A] : is_scalar_tower R S (power_series A) := pi.is_scalar_tower protected instance algebra {R : Type u_1} [comm_ring R] : algebra R (power_series R) := mv_power_series.algebra /-- The `n`th coefficient of a formal power series.-/ def coeff (R : Type u_1) [semiring R] (n : ℕ) : linear_map R (power_series R) R := mv_power_series.coeff R (finsupp.single Unit.unit n) /-- The `n`th monomial with coefficient `a` as formal power series.-/ def monomial (R : Type u_1) [semiring R] (n : ℕ) : linear_map R R (power_series R) := mv_power_series.monomial R (finsupp.single Unit.unit n) theorem coeff_def {R : Type u_1} [semiring R] {s : Unit →₀ ℕ} {n : ℕ} (h : coe_fn s Unit.unit = n) : coeff R n = mv_power_series.coeff R s := sorry /-- Two formal power series are equal if all their coefficients are equal.-/ theorem ext {R : Type u_1} [semiring R] {φ : power_series R} {ψ : power_series R} (h : ∀ (n : ℕ), coe_fn (coeff R n) φ = coe_fn (coeff R n) ψ) : φ = ψ := sorry /-- Two formal power series are equal if all their coefficients are equal.-/ theorem ext_iff {R : Type u_1} [semiring R] {φ : power_series R} {ψ : power_series R} : φ = ψ ↔ ∀ (n : ℕ), coe_fn (coeff R n) φ = coe_fn (coeff R n) ψ := { mp := fun (h : φ = ψ) (n : ℕ) => congr_arg (⇑(coeff R n)) h, mpr := ext } /-- Constructor for formal power series.-/ def mk {R : Type u_1} (f : ℕ → R) : power_series R := fun (s : Unit →₀ ℕ) => f (coe_fn s Unit.unit) @[simp] theorem coeff_mk {R : Type u_1} [semiring R] (n : ℕ) (f : ℕ → R) : coe_fn (coeff R n) (mk f) = f n := congr_arg f finsupp.single_eq_same theorem coeff_monomial {R : Type u_1} [semiring R] (m : ℕ) (n : ℕ) (a : R) : coe_fn (coeff R m) (coe_fn (monomial R n) a) = ite (m = n) a 0 := sorry theorem monomial_eq_mk {R : Type u_1} [semiring R] (n : ℕ) (a : R) : coe_fn (monomial R n) a = mk fun (m : ℕ) => ite (m = n) a 0 := sorry @[simp] theorem coeff_monomial_same {R : Type u_1} [semiring R] (n : ℕ) (a : R) : coe_fn (coeff R n) (coe_fn (monomial R n) a) = a := mv_power_series.coeff_monomial_same (finsupp.single Unit.unit n) a @[simp] theorem coeff_comp_monomial {R : Type u_1} [semiring R] (n : ℕ) : linear_map.comp (coeff R n) (monomial R n) = linear_map.id := linear_map.ext (coeff_monomial_same n) /--The constant coefficient of a formal power series. -/ def constant_coeff (R : Type u_1) [semiring R] : power_series R →+* R := mv_power_series.constant_coeff Unit R /-- The constant formal power series.-/ def C (R : Type u_1) [semiring R] : R →+* power_series R := mv_power_series.C Unit R /-- The variable of the formal power series ring.-/ def X {R : Type u_1} [semiring R] : power_series R := mv_power_series.X Unit.unit @[simp] theorem coeff_zero_eq_constant_coeff {R : Type u_1} [semiring R] : ⇑(coeff R 0) = ⇑(constant_coeff R) := sorry theorem coeff_zero_eq_constant_coeff_apply {R : Type u_1} [semiring R] (φ : power_series R) : coe_fn (coeff R 0) φ = coe_fn (constant_coeff R) φ := eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn (coeff R 0) φ = coe_fn (constant_coeff R) φ)) coeff_zero_eq_constant_coeff)) (Eq.refl (coe_fn (constant_coeff R) φ)) @[simp] theorem monomial_zero_eq_C {R : Type u_1} [semiring R] : ⇑(monomial R 0) = ⇑(C R) := sorry theorem monomial_zero_eq_C_apply {R : Type u_1} [semiring R] (a : R) : coe_fn (monomial R 0) a = coe_fn (C R) a := sorry theorem coeff_C {R : Type u_1} [semiring R] (n : ℕ) (a : R) : coe_fn (coeff R n) (coe_fn (C R) a) = ite (n = 0) a 0 := sorry theorem coeff_zero_C {R : Type u_1} [semiring R] (a : R) : coe_fn (coeff R 0) (coe_fn (C R) a) = a := eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn (coeff R 0) (coe_fn (C R) a) = a)) (Eq.symm (monomial_zero_eq_C_apply a)))) (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn (coeff R 0) (coe_fn (monomial R 0) a) = a)) (coeff_monomial_same 0 a))) (Eq.refl a)) theorem X_eq {R : Type u_1} [semiring R] : X = coe_fn (monomial R 1) 1 := rfl theorem coeff_X {R : Type u_1} [semiring R] (n : ℕ) : coe_fn (coeff R n) X = ite (n = 1) 1 0 := sorry theorem coeff_zero_X {R : Type u_1} [semiring R] : coe_fn (coeff R 0) X = 0 := sorry @[simp] theorem coeff_one_X {R : Type u_1} [semiring R] : coe_fn (coeff R 1) X = 1 := eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn (coeff R 1) X = 1)) (coeff_X 1))) (eq.mpr (id (Eq._oldrec (Eq.refl (ite (1 = 1) 1 0 = 1)) (if_pos rfl))) (Eq.refl 1)) theorem X_pow_eq {R : Type u_1} [semiring R] (n : ℕ) : X ^ n = coe_fn (monomial R n) 1 := mv_power_series.X_pow_eq Unit.unit n theorem coeff_X_pow {R : Type u_1} [semiring R] (m : ℕ) (n : ℕ) : coe_fn (coeff R m) (X ^ n) = ite (m = n) 1 0 := sorry @[simp] theorem coeff_X_pow_self {R : Type u_1} [semiring R] (n : ℕ) : coe_fn (coeff R n) (X ^ n) = 1 := eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn (coeff R n) (X ^ n) = 1)) (coeff_X_pow n n))) (eq.mpr (id (Eq._oldrec (Eq.refl (ite (n = n) 1 0 = 1)) (if_pos rfl))) (Eq.refl 1)) @[simp] theorem coeff_one {R : Type u_1} [semiring R] (n : ℕ) : coe_fn (coeff R n) 1 = ite (n = 0) 1 0 := sorry theorem coeff_zero_one {R : Type u_1} [semiring R] : coe_fn (coeff R 0) 1 = 1 := coeff_zero_C 1 theorem coeff_mul {R : Type u_1} [semiring R] (n : ℕ) (φ : power_series R) (ψ : power_series R) : coe_fn (coeff R n) (φ * ψ) = finset.sum (finset.nat.antidiagonal n) fun (p : ℕ × ℕ) => coe_fn (coeff R (prod.fst p)) φ * coe_fn (coeff R (prod.snd p)) ψ := sorry @[simp] theorem coeff_mul_C {R : Type u_1} [semiring R] (n : ℕ) (φ : power_series R) (a : R) : coe_fn (coeff R n) (φ * coe_fn (C R) a) = coe_fn (coeff R n) φ * a := mv_power_series.coeff_mul_C (finsupp.single Unit.unit n) φ a @[simp] theorem coeff_C_mul {R : Type u_1} [semiring R] (n : ℕ) (φ : power_series R) (a : R) : coe_fn (coeff R n) (coe_fn (C R) a * φ) = a * coe_fn (coeff R n) φ := mv_power_series.coeff_C_mul (finsupp.single Unit.unit n) φ a @[simp] theorem coeff_smul {R : Type u_1} [semiring R] (n : ℕ) (φ : power_series R) (a : R) : coe_fn (coeff R n) (a • φ) = a * coe_fn (coeff R n) φ := rfl @[simp] theorem coeff_succ_mul_X {R : Type u_1} [semiring R] (n : ℕ) (φ : power_series R) : coe_fn (coeff R (n + 1)) (φ * X) = coe_fn (coeff R n) φ := sorry @[simp] theorem constant_coeff_C {R : Type u_1} [semiring R] (a : R) : coe_fn (constant_coeff R) (coe_fn (C R) a) = a := rfl @[simp] theorem constant_coeff_comp_C {R : Type u_1} [semiring R] : ring_hom.comp (constant_coeff R) (C R) = ring_hom.id R := rfl @[simp] theorem constant_coeff_zero {R : Type u_1} [semiring R] : coe_fn (constant_coeff R) 0 = 0 := rfl @[simp] theorem constant_coeff_one {R : Type u_1} [semiring R] : coe_fn (constant_coeff R) 1 = 1 := rfl @[simp] theorem constant_coeff_X {R : Type u_1} [semiring R] : coe_fn (constant_coeff R) X = 0 := mv_power_series.coeff_zero_X Unit.unit theorem coeff_zero_mul_X {R : Type u_1} [semiring R] (φ : power_series R) : coe_fn (coeff R 0) (φ * X) = 0 := sorry /-- If a formal power series is invertible, then so is its constant coefficient.-/ theorem is_unit_constant_coeff {R : Type u_1} [semiring R] (φ : power_series R) (h : is_unit φ) : is_unit (coe_fn (constant_coeff R) φ) := mv_power_series.is_unit_constant_coeff φ h /-- The map between formal power series induced by a map on the coefficients.-/ def map {R : Type u_1} [semiring R] {S : Type u_2} [semiring S] (f : R →+* S) : power_series R →+* power_series S := mv_power_series.map Unit f @[simp] theorem map_id {R : Type u_1} [semiring R] : ⇑(map (ring_hom.id R)) = id := rfl theorem map_comp {R : Type u_1} [semiring R] {S : Type u_2} {T : Type u_3} [semiring S] [semiring T] (f : R →+* S) (g : S →+* T) : map (ring_hom.comp g f) = ring_hom.comp (map g) (map f) := rfl @[simp] theorem coeff_map {R : Type u_1} [semiring R] {S : Type u_2} [semiring S] (f : R →+* S) (n : ℕ) (φ : power_series R) : coe_fn (coeff S n) (coe_fn (map f) φ) = coe_fn f (coe_fn (coeff R n) φ) := rfl theorem X_pow_dvd_iff {R : Type u_1} [comm_semiring R] {n : ℕ} {φ : power_series R} : X ^ n ∣ φ ↔ ∀ (m : ℕ), m < n → coe_fn (coeff R m) φ = 0 := sorry theorem X_dvd_iff {R : Type u_1} [comm_semiring R] {φ : power_series R} : X ∣ φ ↔ coe_fn (constant_coeff R) φ = 0 := sorry /-- The `n`th truncation of a formal power series to a polynomial -/ def trunc {R : Type u_1} [comm_semiring R] (n : ℕ) (φ : power_series R) : polynomial R := finsupp.mk (finset.filter (fun (m : ℕ) => coe_fn (coeff R m) φ ≠ 0) (finset.image prod.fst (finset.nat.antidiagonal n))) (fun (m : ℕ) => ite (m ≤ n) (coe_fn (coeff R m) φ) 0) sorry theorem coeff_trunc {R : Type u_1} [comm_semiring R] (m : ℕ) (n : ℕ) (φ : power_series R) : polynomial.coeff (trunc n φ) m = ite (m ≤ n) (coe_fn (coeff R m) φ) 0 := rfl @[simp] theorem trunc_zero {R : Type u_1} [comm_semiring R] (n : ℕ) : trunc n 0 = 0 := sorry @[simp] theorem trunc_one {R : Type u_1} [comm_semiring R] (n : ℕ) : trunc n 1 = 1 := sorry @[simp] theorem trunc_C {R : Type u_1} [comm_semiring R] (n : ℕ) (a : R) : trunc n (coe_fn (C R) a) = coe_fn polynomial.C a := sorry @[simp] theorem trunc_add {R : Type u_1} [comm_semiring R] (n : ℕ) (φ : power_series R) (ψ : power_series R) : trunc n (φ + ψ) = trunc n φ + trunc n ψ := sorry /-- Auxiliary function used for computing inverse of a power series -/ protected def inv.aux {R : Type u_1} [ring R] : R → power_series R → power_series R := mv_power_series.inv.aux theorem coeff_inv_aux {R : Type u_1} [ring R] (n : ℕ) (a : R) (φ : power_series R) : coe_fn (coeff R n) (inv.aux a φ) = ite (n = 0) a (-a * finset.sum (finset.nat.antidiagonal n) fun (x : ℕ × ℕ) => ite (prod.snd x < n) (coe_fn (coeff R (prod.fst x)) φ * coe_fn (coeff R (prod.snd x)) (inv.aux a φ)) 0) := sorry /-- A formal power series is invertible if the constant coefficient is invertible.-/ def inv_of_unit {R : Type u_1} [ring R] (φ : power_series R) (u : units R) : power_series R := mv_power_series.inv_of_unit φ u theorem coeff_inv_of_unit {R : Type u_1} [ring R] (n : ℕ) (φ : power_series R) (u : units R) : coe_fn (coeff R n) (inv_of_unit φ u) = ite (n = 0) (↑(u⁻¹)) (-↑(u⁻¹) * finset.sum (finset.nat.antidiagonal n) fun (x : ℕ × ℕ) => ite (prod.snd x < n) (coe_fn (coeff R (prod.fst x)) φ * coe_fn (coeff R (prod.snd x)) (inv_of_unit φ u)) 0) := coeff_inv_aux n (↑(u⁻¹)) φ @[simp] theorem constant_coeff_inv_of_unit {R : Type u_1} [ring R] (φ : power_series R) (u : units R) : coe_fn (constant_coeff R) (inv_of_unit φ u) = ↑(u⁻¹) := sorry theorem mul_inv_of_unit {R : Type u_1} [ring R] (φ : power_series R) (u : units R) (h : coe_fn (constant_coeff R) φ = ↑u) : φ * inv_of_unit φ u = 1 := mv_power_series.mul_inv_of_unit φ u h theorem eq_zero_or_eq_zero_of_mul_eq_zero {R : Type u_1} [integral_domain R] (φ : power_series R) (ψ : power_series R) (h : φ * ψ = 0) : φ = 0 ∨ ψ = 0 := sorry protected instance integral_domain {R : Type u_1} [integral_domain R] : integral_domain (power_series R) := integral_domain.mk comm_ring.add sorry comm_ring.zero sorry sorry comm_ring.neg comm_ring.sub sorry sorry comm_ring.mul sorry comm_ring.one sorry sorry sorry sorry sorry sorry eq_zero_or_eq_zero_of_mul_eq_zero /-- The ideal spanned by the variable in the power series ring over an integral domain is a prime ideal.-/ theorem span_X_is_prime {R : Type u_1} [integral_domain R] : ideal.is_prime (ideal.span (singleton X)) := sorry /-- The variable of the power series ring over an integral domain is prime.-/ theorem X_prime {R : Type u_1} [integral_domain R] : prime X := sorry protected instance map.is_local_ring_hom {R : Type u_1} {S : Type u_2} [comm_ring R] [comm_ring S] (f : R →+* S) [is_local_ring_hom f] : is_local_ring_hom (map f) := mv_power_series.map.is_local_ring_hom f protected instance local_ring {R : Type u_1} [comm_ring R] [local_ring R] : local_ring (power_series R) := mv_power_series.local_ring /-- The inverse 1/f of a power series f defined over a field -/ protected def inv {k : Type u_2} [field k] : power_series k → power_series k := mv_power_series.inv protected instance has_inv {k : Type u_2} [field k] : has_inv (power_series k) := has_inv.mk power_series.inv theorem inv_eq_inv_aux {k : Type u_2} [field k] (φ : power_series k) : φ⁻¹ = inv.aux (coe_fn (constant_coeff k) φ⁻¹) φ := rfl theorem coeff_inv {k : Type u_2} [field k] (n : ℕ) (φ : power_series k) : coe_fn (coeff k n) (φ⁻¹) = ite (n = 0) (coe_fn (constant_coeff k) φ⁻¹) (-(coe_fn (constant_coeff k) φ⁻¹) * finset.sum (finset.nat.antidiagonal n) fun (x : ℕ × ℕ) => ite (prod.snd x < n) (coe_fn (coeff k (prod.fst x)) φ * coe_fn (coeff k (prod.snd x)) (φ⁻¹)) 0) := sorry @[simp] theorem constant_coeff_inv {k : Type u_2} [field k] (φ : power_series k) : coe_fn (constant_coeff k) (φ⁻¹) = (coe_fn (constant_coeff k) φ⁻¹) := mv_power_series.constant_coeff_inv φ theorem inv_eq_zero {k : Type u_2} [field k] {φ : power_series k} : φ⁻¹ = 0 ↔ coe_fn (constant_coeff k) φ = 0 := mv_power_series.inv_eq_zero @[simp] theorem inv_of_unit_eq {k : Type u_2} [field k] (φ : power_series k) (h : coe_fn (constant_coeff k) φ ≠ 0) : inv_of_unit φ (units.mk0 (coe_fn (constant_coeff k) φ) h) = (φ⁻¹) := mv_power_series.inv_of_unit_eq φ h @[simp] theorem inv_of_unit_eq' {k : Type u_2} [field k] (φ : power_series k) (u : units k) (h : coe_fn (constant_coeff k) φ = ↑u) : inv_of_unit φ u = (φ⁻¹) := mv_power_series.inv_of_unit_eq' φ u h @[simp] protected theorem mul_inv {k : Type u_2} [field k] (φ : power_series k) (h : coe_fn (constant_coeff k) φ ≠ 0) : φ * (φ⁻¹) = 1 := mv_power_series.mul_inv φ h @[simp] protected theorem inv_mul {k : Type u_2} [field k] (φ : power_series k) (h : coe_fn (constant_coeff k) φ ≠ 0) : φ⁻¹ * φ = 1 := mv_power_series.inv_mul φ h theorem eq_mul_inv_iff_mul_eq {k : Type u_2} [field k] {φ₁ : power_series k} {φ₂ : power_series k} {φ₃ : power_series k} (h : coe_fn (constant_coeff k) φ₃ ≠ 0) : φ₁ = φ₂ * (φ₃⁻¹) ↔ φ₁ * φ₃ = φ₂ := mv_power_series.eq_mul_inv_iff_mul_eq h theorem eq_inv_iff_mul_eq_one {k : Type u_2} [field k] {φ : power_series k} {ψ : power_series k} (h : coe_fn (constant_coeff k) ψ ≠ 0) : φ = (ψ⁻¹) ↔ φ * ψ = 1 := mv_power_series.eq_inv_iff_mul_eq_one h theorem inv_eq_iff_mul_eq_one {k : Type u_2} [field k] {φ : power_series k} {ψ : power_series k} (h : coe_fn (constant_coeff k) ψ ≠ 0) : ψ⁻¹ = φ ↔ φ * ψ = 1 := mv_power_series.inv_eq_iff_mul_eq_one h end power_series namespace power_series /-- The order of a formal power series `φ` is the greatest `n : enat` such that `X^n` divides `φ`. The order is `⊤` if and only if `φ = 0`. -/ def order {R : Type u_1} [comm_semiring R] (φ : power_series R) : enat := multiplicity X φ theorem order_finite_of_coeff_ne_zero {R : Type u_1} [comm_semiring R] (φ : power_series R) (h : ∃ (n : ℕ), coe_fn (coeff R n) φ ≠ 0) : roption.dom (order φ) := sorry /-- If the order of a formal power series is finite, then the coefficient indexed by the order is nonzero.-/ theorem coeff_order {R : Type u_1} [comm_semiring R] (φ : power_series R) (h : roption.dom (order φ)) : coe_fn (coeff R (roption.get (order φ) h)) φ ≠ 0 := sorry /-- If the `n`th coefficient of a formal power series is nonzero, then the order of the power series is less than or equal to `n`.-/ theorem order_le {R : Type u_1} [comm_semiring R] (φ : power_series R) (n : ℕ) (h : coe_fn (coeff R n) φ ≠ 0) : order φ ≤ ↑n := sorry /-- The `n`th coefficient of a formal power series is `0` if `n` is strictly smaller than the order of the power series.-/ theorem coeff_of_lt_order {R : Type u_1} [comm_semiring R] (φ : power_series R) (n : ℕ) (h : ↑n < order φ) : coe_fn (coeff R n) φ = 0 := sorry /-- The order of the `0` power series is infinite.-/ @[simp] theorem order_zero {R : Type u_1} [comm_semiring R] : order 0 = ⊤ := multiplicity.zero X /-- The `0` power series is the unique power series with infinite order.-/ @[simp] theorem order_eq_top {R : Type u_1} [comm_semiring R] {φ : power_series R} : order φ = ⊤ ↔ φ = 0 := sorry /-- The order of a formal power series is at least `n` if the `i`th coefficient is `0` for all `i < n`.-/ theorem nat_le_order {R : Type u_1} [comm_semiring R] (φ : power_series R) (n : ℕ) (h : ∀ (i : ℕ), i < n → coe_fn (coeff R i) φ = 0) : ↑n ≤ order φ := sorry /-- The order of a formal power series is at least `n` if the `i`th coefficient is `0` for all `i < n`.-/ theorem le_order {R : Type u_1} [comm_semiring R] (φ : power_series R) (n : enat) (h : ∀ (i : ℕ), ↑i < n → coe_fn (coeff R i) φ = 0) : n ≤ order φ := sorry /-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero, and the `i`th coefficient is `0` for all `i < n`.-/ theorem order_eq_nat {R : Type u_1} [comm_semiring R] {φ : power_series R} {n : ℕ} : order φ = ↑n ↔ coe_fn (coeff R n) φ ≠ 0 ∧ ∀ (i : ℕ), i < n → coe_fn (coeff R i) φ = 0 := sorry /-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero, and the `i`th coefficient is `0` for all `i < n`.-/ theorem order_eq {R : Type u_1} [comm_semiring R] {φ : power_series R} {n : enat} : order φ = n ↔ (∀ (i : ℕ), ↑i = n → coe_fn (coeff R i) φ ≠ 0) ∧ ∀ (i : ℕ), ↑i < n → coe_fn (coeff R i) φ = 0 := sorry /-- The order of the sum of two formal power series is at least the minimum of their orders.-/ theorem le_order_add {R : Type u_1} [comm_semiring R] (φ : power_series R) (ψ : power_series R) : min (order φ) (order ψ) ≤ order (φ + ψ) := multiplicity.min_le_multiplicity_add /-- The order of the sum of two formal power series is the minimum of their orders if their orders differ.-/ theorem order_add_of_order_eq {R : Type u_1} [comm_semiring R] (φ : power_series R) (ψ : power_series R) (h : order φ ≠ order ψ) : order (φ + ψ) = order φ ⊓ order ψ := sorry /-- The order of the product of two formal power series is at least the sum of their orders.-/ theorem order_mul_ge {R : Type u_1} [comm_semiring R] (φ : power_series R) (ψ : power_series R) : order φ + order ψ ≤ order (φ * ψ) := sorry /-- The order of the monomial `a*X^n` is infinite if `a = 0` and `n` otherwise.-/ theorem order_monomial {R : Type u_1} [comm_semiring R] (n : ℕ) (a : R) : order (coe_fn (monomial R n) a) = ite (a = 0) ⊤ ↑n := sorry /-- The order of the monomial `a*X^n` is `n` if `a ≠ 0`.-/ theorem order_monomial_of_ne_zero {R : Type u_1} [comm_semiring R] (n : ℕ) (a : R) (h : a ≠ 0) : order (coe_fn (monomial R n) a) = ↑n := eq.mpr (id (Eq._oldrec (Eq.refl (order (coe_fn (monomial R n) a) = ↑n)) (order_monomial n a))) (eq.mpr (id (Eq._oldrec (Eq.refl (ite (a = 0) ⊤ ↑n = ↑n)) (if_neg h))) (Eq.refl ↑n)) /-- The order of the formal power series `1` is `0`.-/ @[simp] theorem order_one {R : Type u_1} [comm_semiring R] [nontrivial R] : order 1 = 0 := sorry /-- The order of the formal power series `X` is `1`.-/ @[simp] theorem order_X {R : Type u_1} [comm_semiring R] [nontrivial R] : order X = 1 := order_monomial_of_ne_zero 1 1 one_ne_zero /-- The order of the formal power series `X^n` is `n`.-/ @[simp] theorem order_X_pow {R : Type u_1} [comm_semiring R] [nontrivial R] (n : ℕ) : order (X ^ n) = ↑n := eq.mpr (id (Eq._oldrec (Eq.refl (order (X ^ n) = ↑n)) (X_pow_eq n))) (eq.mpr (id (Eq._oldrec (Eq.refl (order (coe_fn (monomial R n) 1) = ↑n)) (order_monomial_of_ne_zero n 1 one_ne_zero))) (Eq.refl ↑n)) /-- The order of the product of two formal power series over an integral domain is the sum of their orders.-/ theorem order_mul {R : Type u_1} [integral_domain R] (φ : power_series R) (ψ : power_series R) : order (φ * ψ) = order φ + order ψ := multiplicity.mul X_prime end power_series namespace polynomial /-- The natural inclusion from polynomials into formal power series.-/ protected instance coe_to_power_series {R : Type u_2} [comm_semiring R] : has_coe (polynomial R) (power_series R) := has_coe.mk fun (φ : polynomial R) => power_series.mk fun (n : ℕ) => coeff φ n @[simp] theorem coeff_coe {R : Type u_2} [comm_semiring R] (φ : polynomial R) (n : ℕ) : coe_fn (power_series.coeff R n) ↑φ = coeff φ n := congr_arg (coeff φ) finsupp.single_eq_same @[simp] theorem coe_monomial {R : Type u_2} [comm_semiring R] (n : ℕ) (a : R) : ↑(coe_fn (monomial n) a) = coe_fn (power_series.monomial R n) a := sorry @[simp] theorem coe_zero {R : Type u_2} [comm_semiring R] : ↑0 = 0 := rfl @[simp] theorem coe_one {R : Type u_2} [comm_semiring R] : ↑1 = 1 := sorry @[simp] theorem coe_add {R : Type u_2} [comm_semiring R] (φ : polynomial R) (ψ : polynomial R) : ↑(φ + ψ) = ↑φ + ↑ψ := rfl @[simp] theorem coe_mul {R : Type u_2} [comm_semiring R] (φ : polynomial R) (ψ : polynomial R) : ↑(φ * ψ) = ↑φ * ↑ψ := sorry @[simp] theorem coe_C {R : Type u_2} [comm_semiring R] (a : R) : ↑(coe_fn C a) = coe_fn (power_series.C R) a := sorry @[simp] theorem coe_X {R : Type u_2} [comm_semiring R] : ↑X = power_series.X := coe_monomial 1 1 /-- The coercion from polynomials to power series as a ring homomorphism. -/ -- TODO as an algebra homomorphism? def coe_to_power_series.ring_hom {R : Type u_2} [comm_semiring R] : polynomial R →+* power_series R := ring_hom.mk coe coe_one coe_mul coe_zero coe_add
1e170f2980ba056d265d3f9d1b27438f7fb6e3c7
d0f9af2b0ace5ce352570d61b09019c8ef4a3b96
/exam_2/predicate_logic/introduction.lean
f7657b8a56de87dfeaa443c08776c3cff2e9658a
[]
no_license
jngo13/Discrete-Mathematics
8671540ef2da7c75915d32332dd20c02f001474e
bf674a866e61f60e6e6d128df85fa73819091787
refs/heads/master
1,675,615,657,924
1,609,142,011,000
1,609,142,011,000
267,190,341
0
0
null
null
null
null
UTF-8
Lean
false
false
6,913
lean
/- Predicate logic: (1) Vastly extends concept of domain: can be pretty much anything - domain no longer just boolean, but can involve objects of any type - e.g., natural numbers, persons, programs, program states, locations - variables can now range over objects of any type (e.g., n : ℕ) - can also refer to *relations*, e.g., =, is_even, is_mother_of, likes - you've been using predicate logic in limited ways all along in Lean (2) Language of propositions is extended, in syntax and semantics - variables can range over objects of arbitrary types - inherits all logical connectives from propositional logic - adds ability to use functions to indirectly refer to objects - adds universal (∀) and existential (∃) quantifiers - adds predicates to represent properties of and relations among objects - (predicates are propositions with parameters; give values to get a proposition) - question of validity is greatly complicated, no longer a fixed domain Examples: - ∀ (n : ℕ), n = 0 ∨ n ≠ 0 - english: every natural number n is either 0 or not 0 - ∀ (n : ℕ), (∃ (m : ℕ), n - m = 0) - english: every natural number n, there exists a natural number m that makes the difference equal to 0 - ∀ (p1 : Person), ∀ (p2 : Person), likes p1 p2 -- likes is a relation - english: for every person p1 and p2, p1 likes p2 (everyone is liked by someone) - ∀ (p1 : Person), ∃ (p2 : Person), likes p2 p1 - english: for every person p1, there exists a person p2 that likes p1 - ∃ (p1 : Person), ∀ (p2 : Person), likes p2 p1 - ∃ (p1 : Person), ∀ (p2 : Person), likes p2 p1 - ∃ (p1 : Person), ∀ (p2 : Person), ¬ likes p2 p1 - ∀ (o : Object), madeOfUranium o → relativelyHeavy o -- properties - english: for all objects madeOfUranium o, it (o) is relativelyHeavy - ∃ (a b c : ℕ), a^2 + b^2 = c^2 -- the pythagorean predicate - ∃ (a b c : ℕ), a>0 ∧ b>0 ∧ c>0 ∧ a^2 + b^2 = c^2 -- the pythagorean predicate - ∃ (a b c : ℕ), pythagorean a b c -- pythagorean is a relation - ¬ exist (a b c n: ℕ), a>0 ∧ b>0 ∧ c>0 ∧ n>2 ∧ a^n+b^n=c^n -- Fermat's last theorem (3) Introduces the concept of *proof* as arbiter of truth - a proposition is deemed true iff there's a *proof* of it - this is the fundamental idea underlying all of mathematics - fundamental question: what then constitutes a correct proof? - answer: a formal argument from accepted truths (axioms) using accepted rules of reasoning (most of which we've already seen!) to deduce the conclusion that a given proposition must be true. Example: Conjecture: Assume P and Q are propositions. Prove P ∧ Q → Q ∧ P. The following quasi-formal proof (written in natural language but rigorously following formal logical rules of reasoning) uses predicate logic versions of the rules of and elimination and and introduction to prove the "conjecture". Reminders: - P ∧ Q → P (left and elimination) - P ∧ Q → Q (right and elimination) - X → Y → X ∧ Y (and introduction) Strategy: To prove the implication, P ∧ Q → Q ∧ P, we have to show that *if we assume* that P ∧ Q is true, which is to say that we have a proof of it, pq, then from this assumption and by using only valid rules of logical reasoning, we can deduce (a better word is "construct") a proof of Q ∧ P. Proof: Assume that we have a proof, pq, of P ∧ Q. Apply the left and elimination rule to pq to deduce a proof, p, of P. Next apply the right and elimination rule to pq to deduce a proof, q, of Q. Finally, apply the and introduction rule to q and p, in that order, to construct a proof of Q ∧ P. QED. This shows that from the *assumption* (or *condition*) that there is a proof of P ∧ Q one can derive a proof of Q ∧ P. Thus is P ∧ Q is true, then Q ∧ P *must* also be true. Exercise: Prove that if P is true then so is P ∨ Q. That is, prove P → P ∨ Q. or_intro_left. Exercise: Prove that P ∧ Q → P ∨ Q. - and_elim_left and and_elim_right Exercise: Produce a different but equally good quasi-formal proof of this proposition. Exercise: Prove P ∨ Q → Q ∨ P. (4) As to deciding whether a putative proof itself is correct, that is a major problem! In traditional mathematical practice, deciding whether a proof is correct is a *social* process. The community of mathematicians reviews purported proofs of major novel claims and tries to determine whether the proof depends only on accepted premises and from there correctly applies the rules of logical reasoning to deduce a proof of the proposition to be proved. This is in general a difficult, costly, and also unreliable process, though it remains for the most part the way that mathematics works in practice. Consider the famous and controversial putative proof by Mochizuki of the so-called ABC conjecture. Here's the statement of the ABC conjecture. For every positive real number ε, there exist only finitely many triples (a, b, c) of coprime positive integers, with a + b = c, such that c > rad(abc)^(1 + ε). It was just announced that his nearly impenetrable 600-page putative proof of this profoundly important conjecture will be published, even though there is very significant concern that the proof contains a fundamental flaw in reasoning. You can read about it in Nature: https://www.nature.com/articles/d41586-020-00998-2 (you don't have to understand the maths to read this article). (5) To address this concern, there is an emerging effort among some mathematicians to formally and automatically *verify* the correctness of proofs in mathematical logic. Lean is an example of an automated logic in which this goal is being pursued. Coq is another example. Such systems are based on a rich logic called "type theory", or constructive, or intuitionistic logic. That's what you are using in Lean. Such logics are so expressive that we can "implement" many other logics within them. We have already seen how we can "embed" propositional logic, including validity checkers and satisfiability solvers, in Lean. Going forward we will learn to reason very precisely in predicate logic by seeing how it is embedded in Lean. The goal here is not to teach Lean, but to make the processes of reasoning in predicate logic precise, and to give you a sense for how such reasoning can be checked automatically by a proof checker, such as Lean or Coq. You are responsible for being able to write quasi-formal proofs of basic propositions in mathematics and in other domains. The way to learn to do this in this class is to learn the entire set of rules of reasoning and how to apply them in Lean. One can then easily write quasi-formal proofs, skipping over obviously correct details to make for more readable proofs. Of course Mochizuki's tale highlights the risks of skipping over potentially critical details! -/ -- sTuCK!
6b028514c3dacd1787aaf052f18beea9fe6a1aa5
137c667471a40116a7afd7261f030b30180468c2
/src/data/int/basic.lean
242f5d30aa28264559a0e45080a8c10d899e32b4
[ "Apache-2.0" ]
permissive
bragadeesh153/mathlib
46bf814cfb1eecb34b5d1549b9117dc60f657792
b577bb2cd1f96eb47031878256856020b76f73cd
refs/heads/master
1,687,435,188,334
1,626,384,207,000
1,626,384,207,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
57,674
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad The integers, with addition, multiplication, and subtraction. -/ import data.nat.pow import algebra.order_functions open nat namespace int instance : inhabited ℤ := ⟨int.zero⟩ instance : nontrivial ℤ := ⟨⟨0, 1, int.zero_ne_one⟩⟩ instance : comm_ring int := { add := int.add, add_assoc := int.add_assoc, zero := int.zero, zero_add := int.zero_add, add_zero := int.add_zero, neg := int.neg, add_left_neg := int.add_left_neg, add_comm := int.add_comm, mul := int.mul, mul_assoc := int.mul_assoc, one := int.one, one_mul := int.one_mul, mul_one := int.mul_one, sub := int.sub, left_distrib := int.distrib_left, right_distrib := int.distrib_right, mul_comm := int.mul_comm, gsmul := (*), gsmul_zero' := int.zero_mul, gsmul_succ' := λ n x, by rw [succ_eq_one_add, of_nat_add, int.distrib_right, of_nat_one, int.one_mul], gsmul_neg' := λ n x, neg_mul_eq_neg_mul_symm (n.succ : ℤ) x } /-! ### Extra instances to short-circuit type class resolution -/ -- instance : has_sub int := by apply_instance -- This is in core instance : add_comm_monoid int := by apply_instance instance : add_monoid int := by apply_instance instance : monoid int := by apply_instance instance : comm_monoid int := by apply_instance instance : comm_semigroup int := by apply_instance instance : semigroup int := by apply_instance instance : add_comm_semigroup int := by apply_instance instance : add_semigroup int := by apply_instance instance : comm_semiring int := by apply_instance instance : semiring int := by apply_instance instance : ring int := by apply_instance instance : distrib int := by apply_instance instance : linear_ordered_comm_ring int := { add_le_add_left := @int.add_le_add_left, mul_pos := @int.mul_pos, zero_le_one := le_of_lt int.zero_lt_one, .. int.comm_ring, .. int.linear_order, .. int.nontrivial } instance : linear_ordered_add_comm_group int := by apply_instance @[simp] lemma add_neg_one (i : ℤ) : i + -1 = i - 1 := rfl theorem abs_eq_nat_abs : ∀ a : ℤ, abs a = nat_abs a | (n : ℕ) := abs_of_nonneg $ coe_zero_le _ | -[1+ n] := abs_of_nonpos $ le_of_lt $ neg_succ_lt_zero _ theorem nat_abs_abs (a : ℤ) : nat_abs (abs a) = nat_abs a := by rw [abs_eq_nat_abs]; refl theorem sign_mul_abs (a : ℤ) : sign a * abs a = a := by rw [abs_eq_nat_abs, sign_mul_nat_abs] @[simp] lemma default_eq_zero : default ℤ = 0 := rfl meta instance : has_to_format ℤ := ⟨λ z, to_string z⟩ meta instance : has_reflect ℤ := by tactic.mk_has_reflect_instance attribute [simp] int.coe_nat_add int.coe_nat_mul int.coe_nat_zero int.coe_nat_one int.coe_nat_succ attribute [simp] int.of_nat_eq_coe int.bodd @[simp] theorem add_def {a b : ℤ} : int.add a b = a + b := rfl @[simp] theorem mul_def {a b : ℤ} : int.mul a b = a * b := rfl @[simp] lemma neg_succ_not_nonneg (n : ℕ) : 0 ≤ -[1+ n] ↔ false := by { simp only [not_le, iff_false], exact int.neg_succ_lt_zero n, } @[simp] lemma neg_succ_not_pos (n : ℕ) : 0 < -[1+ n] ↔ false := by simp only [not_lt, iff_false] @[simp] lemma neg_succ_sub_one (n : ℕ) : -[1+ n] - 1 = -[1+ (n+1)] := rfl @[simp] theorem coe_nat_mul_neg_succ (m n : ℕ) : (m : ℤ) * -[1+ n] = -(m * succ n) := rfl @[simp] theorem neg_succ_mul_coe_nat (m n : ℕ) : -[1+ m] * n = -(succ m * n) := rfl @[simp] theorem neg_succ_mul_neg_succ (m n : ℕ) : -[1+ m] * -[1+ n] = succ m * succ n := rfl @[simp, norm_cast] theorem coe_nat_le {m n : ℕ} : (↑m : ℤ) ≤ ↑n ↔ m ≤ n := coe_nat_le_coe_nat_iff m n @[simp, norm_cast] theorem coe_nat_lt {m n : ℕ} : (↑m : ℤ) < ↑n ↔ m < n := coe_nat_lt_coe_nat_iff m n @[simp, norm_cast] theorem coe_nat_inj' {m n : ℕ} : (↑m : ℤ) = ↑n ↔ m = n := int.coe_nat_eq_coe_nat_iff m n @[simp] theorem coe_nat_pos {n : ℕ} : (0 : ℤ) < n ↔ 0 < n := by rw [← int.coe_nat_zero, coe_nat_lt] @[simp] theorem coe_nat_eq_zero {n : ℕ} : (n : ℤ) = 0 ↔ n = 0 := by rw [← int.coe_nat_zero, coe_nat_inj'] theorem coe_nat_ne_zero {n : ℕ} : (n : ℤ) ≠ 0 ↔ n ≠ 0 := not_congr coe_nat_eq_zero @[simp] lemma coe_nat_nonneg (n : ℕ) : 0 ≤ (n : ℤ) := coe_nat_le.2 (nat.zero_le _) lemma coe_nat_ne_zero_iff_pos {n : ℕ} : (n : ℤ) ≠ 0 ↔ 0 < n := ⟨λ h, nat.pos_of_ne_zero (coe_nat_ne_zero.1 h), λ h, (ne_of_lt (coe_nat_lt.2 h)).symm⟩ lemma coe_nat_succ_pos (n : ℕ) : 0 < (n.succ : ℤ) := int.coe_nat_pos.2 (succ_pos n) @[simp, norm_cast] theorem coe_nat_abs (n : ℕ) : abs (n : ℤ) = n := abs_of_nonneg (coe_nat_nonneg n) /-! ### succ and pred -/ /-- Immediate successor of an integer: `succ n = n + 1` -/ def succ (a : ℤ) := a + 1 /-- Immediate predecessor of an integer: `pred n = n - 1` -/ def pred (a : ℤ) := a - 1 theorem nat_succ_eq_int_succ (n : ℕ) : (nat.succ n : ℤ) = int.succ n := rfl theorem pred_succ (a : ℤ) : pred (succ a) = a := add_sub_cancel _ _ theorem succ_pred (a : ℤ) : succ (pred a) = a := sub_add_cancel _ _ theorem neg_succ (a : ℤ) : -succ a = pred (-a) := neg_add _ _ theorem succ_neg_succ (a : ℤ) : succ (-succ a) = -a := by rw [neg_succ, succ_pred] theorem neg_pred (a : ℤ) : -pred a = succ (-a) := by rw [eq_neg_of_eq_neg (neg_succ (-a)).symm, neg_neg] theorem pred_neg_pred (a : ℤ) : pred (-pred a) = -a := by rw [neg_pred, pred_succ] theorem pred_nat_succ (n : ℕ) : pred (nat.succ n) = n := pred_succ n theorem neg_nat_succ (n : ℕ) : -(nat.succ n : ℤ) = pred (-n) := neg_succ n theorem succ_neg_nat_succ (n : ℕ) : succ (-nat.succ n) = -n := succ_neg_succ n theorem lt_succ_self (a : ℤ) : a < succ a := lt_add_of_pos_right _ zero_lt_one theorem pred_self_lt (a : ℤ) : pred a < a := sub_lt_self _ zero_lt_one theorem add_one_le_iff {a b : ℤ} : a + 1 ≤ b ↔ a < b := iff.rfl theorem lt_add_one_iff {a b : ℤ} : a < b + 1 ↔ a ≤ b := add_le_add_iff_right _ @[simp] lemma succ_coe_nat_pos (n : ℕ) : 0 < (n : ℤ) + 1 := lt_add_one_iff.mpr (by simp) @[norm_cast] lemma coe_pred_of_pos {n : ℕ} (h : 0 < n) : ((n - 1 : ℕ) : ℤ) = (n : ℤ) - 1 := by { cases n, cases h, simp, } lemma le_add_one {a b : ℤ} (h : a ≤ b) : a ≤ b + 1 := le_of_lt (int.lt_add_one_iff.mpr h) theorem sub_one_lt_iff {a b : ℤ} : a - 1 < b ↔ a ≤ b := sub_lt_iff_lt_add.trans lt_add_one_iff theorem le_sub_one_iff {a b : ℤ} : a ≤ b - 1 ↔ a < b := le_sub_iff_add_le @[simp] lemma eq_zero_iff_abs_lt_one {a : ℤ} : abs a < 1 ↔ a = 0 := ⟨λ a0, let ⟨hn, hp⟩ := abs_lt.mp a0 in (le_of_lt_add_one (by exact hp)).antisymm hn, λ a0, (abs_eq_zero.mpr a0).le.trans_lt zero_lt_one⟩ @[elab_as_eliminator] protected lemma induction_on {p : ℤ → Prop} (i : ℤ) (hz : p 0) (hp : ∀ i : ℕ, p i → p (i + 1)) (hn : ∀ i : ℕ, p (-i) → p (-i - 1)) : p i := begin induction i, { induction i, { exact hz }, { exact hp _ i_ih } }, { have : ∀ n:ℕ, p (- n), { intro n, induction n, { simp [hz] }, { convert hn _ n_ih using 1, simp [sub_eq_neg_add] } }, exact this (i + 1) } end /-- Inductively define a function on `ℤ` by defining it at `b`, for the `succ` of a number greater than `b`, and the `pred` of a number less than `b`. -/ protected def induction_on' {C : ℤ → Sort*} (z : ℤ) (b : ℤ) : C b → (∀ k, b ≤ k → C k → C (k + 1)) → (∀ k ≤ b, C k → C (k - 1)) → C z := λ H0 Hs Hp, begin rw ←sub_add_cancel z b, induction (z - b) with n n, { induction n with n ih, { rwa [of_nat_zero, zero_add] }, rw [of_nat_succ, add_assoc, add_comm 1 b, ←add_assoc], exact Hs _ (le_add_of_nonneg_left (of_nat_nonneg _)) ih }, { induction n with n ih, { rw [neg_succ_of_nat_eq, ←of_nat_eq_coe, of_nat_zero, zero_add, neg_add_eq_sub], exact Hp _ (le_refl _) H0 }, { rw [neg_succ_of_nat_coe', nat.succ_eq_add_one, ←neg_succ_of_nat_coe, sub_add_eq_add_sub], exact Hp _ (le_of_lt (add_lt_of_neg_of_le (neg_succ_lt_zero _) (le_refl _))) ih } } end /-! ### nat abs -/ attribute [simp] nat_abs nat_abs_of_nat nat_abs_zero nat_abs_one theorem nat_abs_add_le (a b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b := begin have : ∀ (a b : ℕ), nat_abs (sub_nat_nat a (nat.succ b)) ≤ nat.succ (a + b), { refine (λ a b : ℕ, sub_nat_nat_elim a b.succ (λ m n i, n = b.succ → nat_abs i ≤ (m + b).succ) _ _ rfl); intros i n e, { subst e, rw [add_comm _ i, add_assoc], exact nat.le_add_right i (b.succ + b).succ }, { apply succ_le_succ, rw [← succ.inj e, ← add_assoc, add_comm], apply nat.le_add_right } }, cases a; cases b with b b; simp [nat_abs, nat.succ_add]; try {refl}; [skip, rw add_comm a b]; apply this end lemma nat_abs_sub_le (a b : ℤ) : nat_abs (a - b) ≤ nat_abs a + nat_abs b := by { rw [sub_eq_add_neg, ← int.nat_abs_neg b], apply nat_abs_add_le } theorem nat_abs_neg_of_nat (n : ℕ) : nat_abs (neg_of_nat n) = n := by cases n; refl theorem nat_abs_mul (a b : ℤ) : nat_abs (a * b) = (nat_abs a) * (nat_abs b) := by cases a; cases b; simp only [← int.mul_def, int.mul, nat_abs_neg_of_nat, eq_self_iff_true, int.nat_abs] lemma nat_abs_mul_nat_abs_eq {a b : ℤ} {c : ℕ} (h : a * b = (c : ℤ)) : a.nat_abs * b.nat_abs = c := by rw [← nat_abs_mul, h, nat_abs_of_nat] @[simp] lemma nat_abs_mul_self' (a : ℤ) : (nat_abs a * nat_abs a : ℤ) = a * a := by rw [← int.coe_nat_mul, nat_abs_mul_self] theorem neg_succ_of_nat_eq' (m : ℕ) : -[1+ m] = -m - 1 := by simp [neg_succ_of_nat_eq, sub_eq_neg_add] lemma nat_abs_ne_zero_of_ne_zero {z : ℤ} (hz : z ≠ 0) : z.nat_abs ≠ 0 := λ h, hz $ int.eq_zero_of_nat_abs_eq_zero h @[simp] lemma nat_abs_eq_zero {a : ℤ} : a.nat_abs = 0 ↔ a = 0 := ⟨int.eq_zero_of_nat_abs_eq_zero, λ h, h.symm ▸ rfl⟩ lemma nat_abs_ne_zero {a : ℤ} : a.nat_abs ≠ 0 ↔ a ≠ 0 := not_congr int.nat_abs_eq_zero lemma nat_abs_lt_nat_abs_of_nonneg_of_lt {a b : ℤ} (w₁ : 0 ≤ a) (w₂ : a < b) : a.nat_abs < b.nat_abs := begin lift b to ℕ using le_trans w₁ (le_of_lt w₂), lift a to ℕ using w₁, simpa using w₂, end lemma nat_abs_eq_nat_abs_iff {a b : ℤ} : a.nat_abs = b.nat_abs ↔ a = b ∨ a = -b := begin split; intro h, { cases int.nat_abs_eq a with h₁ h₁; cases int.nat_abs_eq b with h₂ h₂; rw [h₁, h₂]; simp [h], }, { cases h; rw h, rw int.nat_abs_neg, }, end lemma nat_abs_eq_iff {a : ℤ} {n : ℕ} : a.nat_abs = n ↔ a = n ∨ a = -n := by rw [←int.nat_abs_eq_nat_abs_iff, int.nat_abs_of_nat] lemma nat_abs_eq_iff_mul_self_eq {a b : ℤ} : a.nat_abs = b.nat_abs ↔ a * a = b * b := begin rw [← abs_eq_iff_mul_self_eq, abs_eq_nat_abs, abs_eq_nat_abs], exact int.coe_nat_inj'.symm end lemma nat_abs_lt_iff_mul_self_lt {a b : ℤ} : a.nat_abs < b.nat_abs ↔ a * a < b * b := begin rw [← abs_lt_iff_mul_self_lt, abs_eq_nat_abs, abs_eq_nat_abs], exact int.coe_nat_lt.symm end lemma nat_abs_le_iff_mul_self_le {a b : ℤ} : a.nat_abs ≤ b.nat_abs ↔ a * a ≤ b * b := begin rw [← abs_le_iff_mul_self_le, abs_eq_nat_abs, abs_eq_nat_abs], exact int.coe_nat_le.symm end lemma nat_abs_eq_iff_sq_eq {a b : ℤ} : a.nat_abs = b.nat_abs ↔ a ^ 2 = b ^ 2 := by { rw [sq, sq], exact nat_abs_eq_iff_mul_self_eq } lemma nat_abs_lt_iff_sq_lt {a b : ℤ} : a.nat_abs < b.nat_abs ↔ a ^ 2 < b ^ 2 := by { rw [sq, sq], exact nat_abs_lt_iff_mul_self_lt } lemma nat_abs_le_iff_sq_le {a b : ℤ} : a.nat_abs ≤ b.nat_abs ↔ a ^ 2 ≤ b ^ 2 := by { rw [sq, sq], exact nat_abs_le_iff_mul_self_le } /-! ### `/` -/ @[simp] theorem of_nat_div (m n : ℕ) : of_nat (m / n) = (of_nat m) / (of_nat n) := rfl @[simp, norm_cast] theorem coe_nat_div (m n : ℕ) : ((m / n : ℕ) : ℤ) = m / n := rfl theorem neg_succ_of_nat_div (m : ℕ) {b : ℤ} (H : 0 < b) : -[1+m] / b = -(m / b + 1) := match b, eq_succ_of_zero_lt H with ._, ⟨n, rfl⟩ := rfl end -- Will be generalized to Euclidean domains. local attribute [simp] protected theorem zero_div : ∀ (b : ℤ), 0 / b = 0 | 0 := show of_nat _ = _, by simp | (n+1:ℕ) := show of_nat _ = _, by simp | -[1+ n] := show -of_nat _ = _, by simp local attribute [simp] -- Will be generalized to Euclidean domains. protected theorem div_zero : ∀ (a : ℤ), a / 0 = 0 | 0 := show of_nat _ = _, by simp | (n+1:ℕ) := show of_nat _ = _, by simp | -[1+ n] := rfl @[simp] protected theorem div_neg : ∀ (a b : ℤ), a / -b = -(a / b) | (m : ℕ) 0 := show of_nat (m / 0) = -(m / 0 : ℕ), by rw nat.div_zero; refl | (m : ℕ) (n+1:ℕ) := rfl | 0 -[1+ n] := by simp | (m+1:ℕ) -[1+ n] := (neg_neg _).symm | -[1+ m] 0 := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl theorem div_of_neg_of_pos {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b = -((-a - 1) / b + 1) := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := by change (- -[1+ m] : ℤ) with (m+1 : ℤ); rw add_sub_cancel; refl end protected theorem div_nonneg {a b : ℤ} (Ha : 0 ≤ a) (Hb : 0 ≤ b) : 0 ≤ a / b := match a, b, eq_coe_of_zero_le Ha, eq_coe_of_zero_le Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := coe_zero_le _ end protected theorem div_nonpos {a b : ℤ} (Ha : 0 ≤ a) (Hb : b ≤ 0) : a / b ≤ 0 := nonpos_of_neg_nonneg $ by rw [← int.div_neg]; exact int.div_nonneg Ha (neg_nonneg_of_nonpos Hb) theorem div_neg' {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b < 0 := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := neg_succ_lt_zero _ end @[simp] protected theorem div_one : ∀ (a : ℤ), a / 1 = a | 0 := show of_nat _ = _, by simp | (n+1:ℕ) := congr_arg of_nat (nat.div_one _) | -[1+ n] := congr_arg neg_succ_of_nat (nat.div_one _) theorem div_eq_zero_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a / b = 0 := match a, b, eq_coe_of_zero_le H1, eq_succ_of_zero_lt (lt_of_le_of_lt H1 H2), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.div_eq_of_lt $ lt_of_coe_nat_lt_coe_nat H2 end theorem div_eq_zero_of_lt_abs {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < abs b) : a / b = 0 := match b, abs b, abs_eq_nat_abs b, H2 with | (n : ℕ), ._, rfl, H2 := div_eq_zero_of_lt H1 H2 | -[1+ n], ._, rfl, H2 := neg_injective $ by rw [← int.div_neg]; exact div_eq_zero_of_lt H1 H2 end protected theorem add_mul_div_right (a b : ℤ) {c : ℤ} (H : c ≠ 0) : (a + b * c) / c = a / c + b := have ∀ {k n : ℕ} {a : ℤ}, (a + n * k.succ) / k.succ = a / k.succ + n, from λ k n a, match a with | (m : ℕ) := congr_arg of_nat $ nat.add_mul_div_right _ _ k.succ_pos | -[1+ m] := show ((n * k.succ:ℕ) - m.succ : ℤ) / k.succ = n - (m / k.succ + 1 : ℕ), begin cases lt_or_ge m (n*k.succ) with h h, { rw [← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.div_lt_iff_lt_mul _ _ k.succ_pos).2 h)], apply congr_arg of_nat, rw [mul_comm, nat.mul_sub_div], rwa mul_comm }, { change (↑(n * nat.succ k) - (m + 1) : ℤ) / ↑(nat.succ k) = ↑n - ((m / nat.succ k : ℕ) + 1), rw [← sub_sub, ← sub_sub, ← neg_sub (m:ℤ), ← neg_sub _ (n:ℤ), ← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.le_div_iff_mul_le _ _ k.succ_pos).2 h), ← neg_succ_of_nat_coe', ← neg_succ_of_nat_coe'], { apply congr_arg neg_succ_of_nat, rw [mul_comm, nat.sub_mul_div], rwa mul_comm } } end end, have ∀ {a b c : ℤ}, 0 < c → (a + b * c) / c = a / c + b, from λ a b c H, match c, eq_succ_of_zero_lt H, b with | ._, ⟨k, rfl⟩, (n : ℕ) := this | ._, ⟨k, rfl⟩, -[1+ n] := show (a - n.succ * k.succ) / k.succ = (a / k.succ) - n.succ, from eq_sub_of_add_eq $ by rw [← this, sub_add_cancel] end, match lt_trichotomy c 0 with | or.inl hlt := neg_inj.1 $ by rw [← int.div_neg, neg_add, ← int.div_neg, ← neg_mul_neg]; apply this (neg_pos_of_neg hlt) | or.inr (or.inl heq) := absurd heq H | or.inr (or.inr hgt) := this hgt end protected theorem add_mul_div_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b ≠ 0) : (a + b * c) / b = a / b + c := by rw [mul_comm, int.add_mul_div_right _ _ H] protected theorem add_div_of_dvd_right {a b c : ℤ} (H : c ∣ b) : (a + b) / c = a / c + b / c := begin by_cases h1 : c = 0, { simp [h1] }, cases H with k hk, rw hk, change c ≠ 0 at h1, rw [mul_comm c k, int.add_mul_div_right _ _ h1, ←zero_add (k * c), int.add_mul_div_right _ _ h1, int.zero_div, zero_add] end protected theorem add_div_of_dvd_left {a b c : ℤ} (H : c ∣ a) : (a + b) / c = a / c + b / c := by rw [add_comm, int.add_div_of_dvd_right H, add_comm] @[simp] protected theorem mul_div_cancel (a : ℤ) {b : ℤ} (H : b ≠ 0) : a * b / b = a := by have := int.add_mul_div_right 0 a H; rwa [zero_add, int.zero_div, zero_add] at this @[simp] protected theorem mul_div_cancel_left {a : ℤ} (b : ℤ) (H : a ≠ 0) : a * b / a = b := by rw [mul_comm, int.mul_div_cancel _ H] @[simp] protected theorem div_self {a : ℤ} (H : a ≠ 0) : a / a = 1 := by have := int.mul_div_cancel 1 H; rwa one_mul at this /-! ### mod -/ theorem of_nat_mod (m n : nat) : (m % n : ℤ) = of_nat (m % n) := rfl @[simp, norm_cast] theorem coe_nat_mod (m n : ℕ) : (↑(m % n) : ℤ) = ↑m % ↑n := rfl theorem neg_succ_of_nat_mod (m : ℕ) {b : ℤ} (bpos : 0 < b) : -[1+m] % b = b - 1 - m % b := by rw [sub_sub, add_comm]; exact match b, eq_succ_of_zero_lt bpos with ._, ⟨n, rfl⟩ := rfl end @[simp] theorem mod_neg : ∀ (a b : ℤ), a % -b = a % b | (m : ℕ) n := @congr_arg ℕ ℤ _ _ (λ i, ↑(m % i)) (nat_abs_neg _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λ i, sub_nat_nat i (nat.succ (m % i))) (nat_abs_neg _) @[simp] theorem mod_abs (a b : ℤ) : a % (abs b) = a % b := abs_by_cases (λ i, a % i = a % b) rfl (mod_neg _ _) local attribute [simp] -- Will be generalized to Euclidean domains. theorem zero_mod (b : ℤ) : 0 % b = 0 := rfl local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_zero : ∀ (a : ℤ), a % 0 = a | (m : ℕ) := congr_arg of_nat $ nat.mod_zero _ | -[1+ m] := congr_arg neg_succ_of_nat $ nat.mod_zero _ local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_one : ∀ (a : ℤ), a % 1 = 0 | (m : ℕ) := congr_arg of_nat $ nat.mod_one _ | -[1+ m] := show (1 - (m % 1).succ : ℤ) = 0, by rw nat.mod_one; refl theorem mod_eq_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a % b = a := match a, b, eq_coe_of_zero_le H1, eq_coe_of_zero_le (le_trans H1 (le_of_lt H2)), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.mod_eq_of_lt (lt_of_coe_nat_lt_coe_nat H2) end theorem mod_nonneg : ∀ (a : ℤ) {b : ℤ}, b ≠ 0 → 0 ≤ a % b | (m : ℕ) n H := coe_zero_le _ | -[1+ m] n H := sub_nonneg_of_le $ coe_nat_le_coe_nat_of_le $ nat.mod_lt _ (nat_abs_pos_of_ne_zero H) theorem mod_lt_of_pos (a : ℤ) {b : ℤ} (H : 0 < b) : a % b < b := match a, b, eq_succ_of_zero_lt H with | (m : ℕ), ._, ⟨n, rfl⟩ := coe_nat_lt_coe_nat_of_lt (nat.mod_lt _ (nat.succ_pos _)) | -[1+ m], ._, ⟨n, rfl⟩ := sub_lt_self _ (coe_nat_lt_coe_nat_of_lt $ nat.succ_pos _) end theorem mod_lt (a : ℤ) {b : ℤ} (H : b ≠ 0) : a % b < abs b := by rw [← mod_abs]; exact mod_lt_of_pos _ (abs_pos.2 H) theorem mod_add_div_aux (m n : ℕ) : (n - (m % n + 1) - (n * (m / n) + n) : ℤ) = -[1+ m] := begin rw [← sub_sub, neg_succ_of_nat_coe, sub_sub (n:ℤ)], apply eq_neg_of_eq_neg, rw [neg_sub, sub_sub_self, add_right_comm], exact @congr_arg ℕ ℤ _ _ (λi, (i + 1 : ℤ)) (nat.mod_add_div _ _).symm end theorem mod_add_div : ∀ (a b : ℤ), a % b + b * (a / b) = a | (m : ℕ) 0 := congr_arg of_nat (nat.mod_add_div _ _) | (m : ℕ) (n+1:ℕ) := congr_arg of_nat (nat.mod_add_div _ _) | 0 -[1+ n] := by simp | (m+1:ℕ) -[1+ n] := show (_ + -(n+1) * -((m + 1) / (n + 1) : ℕ) : ℤ) = _, by rw [neg_mul_neg]; exact congr_arg of_nat (nat.mod_add_div _ _) | -[1+ m] 0 := by rw [mod_zero, int.div_zero]; refl | -[1+ m] (n+1:ℕ) := mod_add_div_aux m n.succ | -[1+ m] -[1+ n] := mod_add_div_aux m n.succ theorem div_add_mod (a b : ℤ) : b * (a / b) + a % b = a := (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 _ _ } theorem mod_def (a b : ℤ) : a % b = a - b * (a / b) := eq_sub_of_add_eq (mod_add_div _ _) @[simp] theorem add_mul_mod_self {a b c : ℤ} : (a + b * c) % c = a % c := if cz : c = 0 then by rw [cz, mul_zero, add_zero] else by rw [mod_def, mod_def, int.add_mul_div_right _ _ cz, mul_add, mul_comm, add_sub_add_right_eq_sub] @[simp] theorem add_mul_mod_self_left (a b c : ℤ) : (a + b * c) % b = a % b := by rw [mul_comm, add_mul_mod_self] @[simp] theorem add_mod_self {a b : ℤ} : (a + b) % b = a % b := by have := add_mul_mod_self_left a b 1; rwa mul_one at this @[simp] theorem add_mod_self_left {a b : ℤ} : (a + b) % a = b % a := by rw [add_comm, add_mod_self] @[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] theorem mod_add_cancel_right {m n k : ℤ} (i) : (m + i) % n = (k + i) % n ↔ m % n = k % n := ⟨λ H, by have := add_mod_eq_add_mod_right (-i) H; rwa [add_neg_cancel_right, add_neg_cancel_right] at this, add_mod_eq_add_mod_right _⟩ theorem mod_add_cancel_left {m n k i : ℤ} : (i + m) % n = (i + k) % n ↔ m % n = k % n := by rw [add_comm, add_comm i, mod_add_cancel_right] theorem mod_sub_cancel_right {m n k : ℤ} (i) : (m - i) % n = (k - i) % n ↔ m % n = k % n := mod_add_cancel_right _ theorem mod_eq_mod_iff_mod_sub_eq_zero {m n k : ℤ} : m % n = k % n ↔ (m - k) % n = 0 := (mod_sub_cancel_right k).symm.trans $ by simp @[simp] theorem mul_mod_left (a b : ℤ) : (a * b) % b = 0 := by rw [← zero_add (a * b), add_mul_mod_self, zero_mod] @[simp] theorem mul_mod_right (a b : ℤ) : (a * b) % a = 0 := by rw [mul_comm, mul_mod_left] 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] } end @[simp] lemma neg_mod_two (i : ℤ) : (-i) % 2 = i % 2 := begin apply int.mod_eq_mod_iff_mod_sub_eq_zero.mpr, convert int.mul_mod_right 2 (-i), simp only [two_mul, sub_eq_add_neg] end local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_self {a : ℤ} : a % a = 0 := by have := mul_mod_left 1 a; rwa one_mul at this @[simp] theorem mod_mod_of_dvd (n : ℤ) {m k : ℤ} (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 b : ℤ) : a % b % b = a % b := by conv {to_rhs, rw [← mod_add_div a b, add_mul_mod_self_left]} lemma sub_mod (a b n : ℤ) : (a - b) % n = ((a % n) - (b % n)) % n := begin apply (mod_add_cancel_right b).mp, rw [sub_add_cancel, ← add_mod_mod, sub_add_cancel, mod_mod] end /-! ### properties of `/` and `%` -/ @[simp] theorem mul_div_mul_of_pos {a : ℤ} (b c : ℤ) (H : 0 < a) : a * b / (a * c) = b / c := suffices ∀ (m k : ℕ) (b : ℤ), (m.succ * b / (m.succ * k) : ℤ) = b / k, from match a, eq_succ_of_zero_lt H, c, eq_coe_or_neg c with | ._, ⟨m, rfl⟩, ._, ⟨k, or.inl rfl⟩ := this _ _ _ | ._, ⟨m, rfl⟩, ._, ⟨k, or.inr rfl⟩ := by rw [← neg_mul_eq_mul_neg, int.div_neg, int.div_neg]; apply congr_arg has_neg.neg; apply this end, λ m k b, match b, k with | (n : ℕ), k := congr_arg of_nat (nat.mul_div_mul _ _ m.succ_pos) | -[1+ n], 0 := by rw [int.coe_nat_zero, mul_zero, int.div_zero, int.div_zero] | -[1+ n], k+1 := congr_arg neg_succ_of_nat $ show (m.succ * n + m) / (m.succ * k.succ) = n / k.succ, begin apply nat.div_eq_of_lt_le, { refine le_trans _ (nat.le_add_right _ _), rw [← nat.mul_div_mul _ _ m.succ_pos], apply nat.div_mul_le_self }, { change m.succ * n.succ ≤ _, rw [mul_left_comm], apply nat.mul_le_mul_left, apply (nat.div_lt_iff_lt_mul _ _ k.succ_pos).1, apply nat.lt_succ_self } end end @[simp] theorem mul_div_mul_of_pos_left (a : ℤ) {b : ℤ} (H : 0 < b) (c : ℤ) : a * b / (c * b) = a / c := by rw [mul_comm, mul_comm c, mul_div_mul_of_pos _ _ H] @[simp] theorem mul_mod_mul_of_pos {a : ℤ} (H : 0 < a) (b c : ℤ) : a * b % (a * c) = a * (b % c) := by rw [mod_def, mod_def, mul_div_mul_of_pos _ _ H, mul_sub_left_distrib, mul_assoc] theorem lt_div_add_one_mul_self (a : ℤ) {b : ℤ} (H : 0 < b) : a < (a / b + 1) * b := by { rw [add_mul, one_mul, mul_comm, ← sub_lt_iff_lt_add', ← mod_def], exact mod_lt_of_pos _ H } theorem abs_div_le_abs : ∀ (a b : ℤ), abs (a / b) ≤ abs a := suffices ∀ (a : ℤ) (n : ℕ), abs (a / n) ≤ abs a, from λ a b, match b, eq_coe_or_neg b with | ._, ⟨n, or.inl rfl⟩ := this _ _ | ._, ⟨n, or.inr rfl⟩ := by rw [int.div_neg, abs_neg]; apply this end, λ a n, by rw [abs_eq_nat_abs, abs_eq_nat_abs]; exact coe_nat_le_coe_nat_of_le (match a, n with | (m : ℕ), n := nat.div_le_self _ _ | -[1+ m], 0 := nat.zero_le _ | -[1+ m], n+1 := nat.succ_le_succ (nat.div_le_self _ _) end) theorem div_le_self {a : ℤ} (b : ℤ) (Ha : 0 ≤ a) : a / b ≤ a := by have := le_trans (le_abs_self _) (abs_div_le_abs a b); rwa [abs_of_nonneg Ha] at this theorem mul_div_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : b * (a / b) = a := by have := mod_add_div a b; rwa [H, zero_add] at this theorem div_mul_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : a / b * b = a := by rw [mul_comm, mul_div_cancel_of_mod_eq_zero H] lemma mod_two_eq_zero_or_one (n : ℤ) : n % 2 = 0 ∨ n % 2 = 1 := have h : n % 2 < 2 := abs_of_nonneg (show 0 ≤ (2 : ℤ), from dec_trivial) ▸ int.mod_lt _ dec_trivial, have h₁ : 0 ≤ n % 2 := int.mod_nonneg _ dec_trivial, match (n % 2), h, h₁ with | (0 : ℕ) := λ _ _, or.inl rfl | (1 : ℕ) := λ _ _, or.inr rfl | (k + 2 : ℕ) := λ h _, absurd h dec_trivial | -[1+ a] := λ _ h₁, absurd h₁ dec_trivial end /-! ### dvd -/ @[norm_cast] theorem coe_nat_dvd {m n : ℕ} : (↑m : ℤ) ∣ ↑n ↔ m ∣ n := ⟨λ ⟨a, ae⟩, m.eq_zero_or_pos.elim (λm0, by simp [m0] at ae; simp [ae, m0]) (λm0l, by { cases eq_coe_of_zero_le (@nonneg_of_mul_nonneg_left ℤ _ m a (by simp [ae.symm]) (by simpa using m0l)) with k e, subst a, exact ⟨k, int.coe_nat_inj ae⟩ }), λ ⟨k, e⟩, dvd.intro k $ by rw [e, int.coe_nat_mul]⟩ theorem coe_nat_dvd_left {n : ℕ} {z : ℤ} : (↑n : ℤ) ∣ z ↔ n ∣ z.nat_abs := by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd] theorem coe_nat_dvd_right {n : ℕ} {z : ℤ} : z ∣ (↑n : ℤ) ↔ z.nat_abs ∣ n := by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd] theorem dvd_antisymm {a b : ℤ} (H1 : 0 ≤ a) (H2 : 0 ≤ b) : a ∣ b → b ∣ a → a = b := begin rw [← abs_of_nonneg H1, ← abs_of_nonneg H2, abs_eq_nat_abs, abs_eq_nat_abs], rw [coe_nat_dvd, coe_nat_dvd, coe_nat_inj'], apply nat.dvd_antisymm end theorem dvd_of_mod_eq_zero {a b : ℤ} (H : b % a = 0) : a ∣ b := ⟨b / a, (mul_div_cancel_of_mod_eq_zero H).symm⟩ theorem mod_eq_zero_of_dvd : ∀ {a b : ℤ}, a ∣ b → b % a = 0 | a ._ ⟨c, rfl⟩ := mul_mod_right _ _ theorem dvd_iff_mod_eq_zero (a b : ℤ) : a ∣ b ↔ b % a = 0 := ⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩ /-- If `a % b = c` then `b` divides `a - c`. -/ lemma dvd_sub_of_mod_eq {a b c : ℤ} (h : a % b = c) : b ∣ a - c := begin have hx : a % b % b = c % b, { rw h }, rw [mod_mod, ←mod_sub_cancel_right c, sub_self, zero_mod] at hx, exact dvd_of_mod_eq_zero hx end theorem nat_abs_dvd {a b : ℤ} : (a.nat_abs : ℤ) ∣ b ↔ a ∣ b := (nat_abs_eq a).elim (λ e, by rw ← e) (λ e, by rw [← neg_dvd_iff_dvd, ← e]) theorem dvd_nat_abs {a b : ℤ} : a ∣ b.nat_abs ↔ a ∣ b := (nat_abs_eq b).elim (λ e, by rw ← e) (λ e, by rw [← dvd_neg_iff_dvd, ← e]) instance decidable_dvd : @decidable_rel ℤ (∣) := assume a n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm protected theorem div_mul_cancel {a b : ℤ} (H : b ∣ a) : a / b * b = a := div_mul_cancel_of_mod_eq_zero (mod_eq_zero_of_dvd H) protected theorem mul_div_cancel' {a b : ℤ} (H : a ∣ b) : a * (b / a) = b := by rw [mul_comm, int.div_mul_cancel H] protected theorem mul_div_assoc (a : ℤ) : ∀ {b c : ℤ}, c ∣ b → (a * b) / c = a * (b / c) | ._ c ⟨d, rfl⟩ := if cz : c = 0 then by simp [cz] else by rw [mul_left_comm, int.mul_div_cancel_left _ cz, int.mul_div_cancel_left _ cz] protected theorem mul_div_assoc' (b : ℤ) {a c : ℤ} (h : c ∣ a) : a * b / c = a / c * b := by rw [mul_comm, int.mul_div_assoc _ h, mul_comm] theorem div_dvd_div : ∀ {a b c : ℤ} (H1 : a ∣ b) (H2 : b ∣ c), b / a ∣ c / a | a ._ ._ ⟨b, rfl⟩ ⟨c, rfl⟩ := if az : a = 0 then by simp [az] else by rw [int.mul_div_cancel_left _ az, mul_assoc, int.mul_div_cancel_left _ az]; apply dvd_mul_right protected theorem eq_mul_of_div_eq_right {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := by rw [← H2, int.mul_div_cancel' H1] protected theorem div_eq_of_eq_mul_right {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = b * c) : a / b = c := by rw [H2, int.mul_div_cancel_left _ H1] protected theorem eq_div_of_mul_eq_right {a b c : ℤ} (H1 : a ≠ 0) (H2 : a * b = c) : b = c / a := eq.symm $ int.div_eq_of_eq_mul_right H1 H2.symm protected theorem div_eq_iff_eq_mul_right {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = b * c := ⟨int.eq_mul_of_div_eq_right H', int.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 int.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, int.eq_mul_of_div_eq_right H1 H2] protected theorem div_eq_of_eq_mul_left {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = c * b) : a / b = c := int.div_eq_of_eq_mul_right H1 (by rw [mul_comm, H2]) protected lemma eq_zero_of_div_eq_zero {d n : ℤ} (h : d ∣ n) (H : n / d = 0) : n = 0 := by rw [← int.mul_div_cancel' h, H, mul_zero] theorem neg_div_of_dvd : ∀ {a b : ℤ} (H : b ∣ a), -a / b = -(a / b) | ._ b ⟨c, rfl⟩ := if bz : b = 0 then by simp [bz] else by rw [neg_mul_eq_mul_neg, int.mul_div_cancel_left _ bz, int.mul_div_cancel_left _ bz] lemma sub_div_of_dvd (a : ℤ) {b c : ℤ} (hcb : c ∣ b) : (a - b) / c = a / c - b / c := begin rw [sub_eq_add_neg, sub_eq_add_neg, int.add_div_of_dvd_right ((dvd_neg c b).mpr hcb)], congr, exact neg_div_of_dvd hcb, end lemma sub_div_of_dvd_sub {a b c : ℤ} (hcab : c ∣ (a - b)) : (a - b) / c = a / c - b / c := by rw [eq_sub_iff_add_eq, ← int.add_div_of_dvd_left hcab, sub_add_cancel] theorem div_sign : ∀ a b, a / sign b = a * sign b | a (n+1:ℕ) := by unfold sign; simp | a 0 := by simp [sign] | a -[1+ n] := by simp [sign] @[simp] theorem sign_mul : ∀ a b, sign (a * b) = sign a * sign b | a 0 := by simp | 0 b := by simp | (m+1:ℕ) (n+1:ℕ) := rfl | (m+1:ℕ) -[1+ n] := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl protected theorem sign_eq_div_abs (a : ℤ) : sign a = a / (abs a) := if az : a = 0 then by simp [az] else (int.div_eq_of_eq_mul_left (mt abs_eq_zero.1 az) (sign_mul_abs _).symm).symm theorem mul_sign : ∀ (i : ℤ), i * sign i = nat_abs i | (n+1:ℕ) := mul_one _ | 0 := mul_zero _ | -[1+ n] := mul_neg_one _ @[simp] theorem sign_pow_bit1 (k : ℕ) : ∀ n : ℤ, n.sign ^ (bit1 k) = n.sign | (n+1:ℕ) := one_pow (bit1 k) | 0 := zero_pow (nat.zero_lt_bit1 k) | -[1+ n] := (neg_pow_bit1 1 k).trans (congr_arg (λ x, -x) (one_pow (bit1 k))) theorem le_of_dvd {a b : ℤ} (bpos : 0 < b) (H : a ∣ b) : a ≤ b := match a, b, eq_succ_of_zero_lt bpos, H with | (m : ℕ), ._, ⟨n, rfl⟩, H := coe_nat_le_coe_nat_of_le $ nat.le_of_dvd n.succ_pos $ coe_nat_dvd.1 H | -[1+ m], ._, ⟨n, rfl⟩, _ := le_trans (le_of_lt $ neg_succ_lt_zero _) (coe_zero_le _) end theorem eq_one_of_dvd_one {a : ℤ} (H : 0 ≤ a) (H' : a ∣ 1) : a = 1 := match a, eq_coe_of_zero_le H, H' with | ._, ⟨n, rfl⟩, H' := congr_arg coe $ nat.eq_one_of_dvd_one $ coe_nat_dvd.1 H' end theorem eq_one_of_mul_eq_one_right {a b : ℤ} (H : 0 ≤ a) (H' : a * b = 1) : a = 1 := eq_one_of_dvd_one H ⟨b, H'.symm⟩ theorem eq_one_of_mul_eq_one_left {a b : ℤ} (H : 0 ≤ b) (H' : a * b = 1) : b = 1 := eq_one_of_mul_eq_one_right H (by rw [mul_comm, H']) lemma of_nat_dvd_of_dvd_nat_abs {a : ℕ} : ∀ {z : ℤ} (haz : a ∣ z.nat_abs), ↑a ∣ z | (int.of_nat _) haz := int.coe_nat_dvd.2 haz | -[1+k] haz := begin change ↑a ∣ -(k+1 : ℤ), apply dvd_neg_of_dvd, apply int.coe_nat_dvd.2, exact haz end lemma dvd_nat_abs_of_of_nat_dvd {a : ℕ} : ∀ {z : ℤ} (haz : ↑a ∣ z), a ∣ z.nat_abs | (int.of_nat _) haz := int.coe_nat_dvd.1 (int.dvd_nat_abs.2 haz) | -[1+k] haz := have haz' : (↑a:ℤ) ∣ (↑(k+1):ℤ), from dvd_of_dvd_neg haz, int.coe_nat_dvd.1 haz' lemma pow_dvd_of_le_of_pow_dvd {p m n : ℕ} {k : ℤ} (hmn : m ≤ n) (hdiv : ↑(p ^ n) ∣ k) : ↑(p ^ m) ∣ k := begin induction k, { apply int.coe_nat_dvd.2, apply pow_dvd_of_le_of_pow_dvd hmn, apply int.coe_nat_dvd.1 hdiv }, change -[1+k] with -(↑(k+1) : ℤ), apply dvd_neg_of_dvd, apply int.coe_nat_dvd.2, apply pow_dvd_of_le_of_pow_dvd hmn, apply int.coe_nat_dvd.1, apply dvd_of_dvd_neg, exact hdiv, end lemma dvd_of_pow_dvd {p k : ℕ} {m : ℤ} (hk : 1 ≤ k) (hpk : ↑(p^k) ∣ m) : ↑p ∣ m := by rw ←pow_one p; exact pow_dvd_of_le_of_pow_dvd hk hpk /-- If `n > 0` then `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_add_one_iff, ← not_lt] at h2k, exact h2k h1k }, { intro h, rw [dvd_iff_mod_eq_zero, ← ne.def] at h, have := (mod_nonneg m hn.ne.symm).lt_of_ne h.symm, simp only [← mod_add_div m n] {single_pass := tt}, refine ⟨m / n, lt_add_of_pos_left _ this, _⟩, rw [add_comm _ (1 : ℤ), left_distrib, mul_one], exact add_lt_add_right (mod_lt_of_pos _ hn) _ } end /-! ### `/` and ordering -/ protected theorem div_mul_le (a : ℤ) {b : ℤ} (H : b ≠ 0) : a / b * b ≤ a := le_of_sub_nonneg $ by rw [mul_comm, ← mod_def]; apply mod_nonneg _ H protected theorem div_le_of_le_mul {a b c : ℤ} (H : 0 < c) (H' : a ≤ b * c) : a / c ≤ b := le_of_mul_le_mul_right (le_trans (int.div_mul_le _ (ne_of_gt H)) H') H protected theorem mul_lt_of_lt_div {a b c : ℤ} (H : 0 < c) (H3 : a < b / c) : a * c < b := lt_of_not_ge $ mt (int.div_le_of_le_mul H) (not_le_of_gt H3) protected theorem mul_le_of_le_div {a b c : ℤ} (H1 : 0 < c) (H2 : a ≤ b / c) : a * c ≤ b := le_trans (decidable.mul_le_mul_of_nonneg_right H2 (le_of_lt H1)) (int.div_mul_le _ (ne_of_gt H1)) protected theorem le_div_of_mul_le {a b c : ℤ} (H1 : 0 < c) (H2 : a * c ≤ b) : a ≤ b / c := le_of_lt_add_one $ lt_of_mul_lt_mul_right (lt_of_le_of_lt H2 (lt_div_add_one_mul_self _ H1)) (le_of_lt H1) protected theorem le_div_iff_mul_le {a b c : ℤ} (H : 0 < c) : a ≤ b / c ↔ a * c ≤ b := ⟨int.mul_le_of_le_div H, int.le_div_of_mul_le H⟩ protected theorem div_le_div {a b c : ℤ} (H : 0 < c) (H' : a ≤ b) : a / c ≤ b / c := int.le_div_of_mul_le H (le_trans (int.div_mul_le _ (ne_of_gt H)) H') protected theorem div_lt_of_lt_mul {a b c : ℤ} (H : 0 < c) (H' : a < b * c) : a / c < b := lt_of_not_ge $ mt (int.mul_le_of_le_div H) (not_le_of_gt H') protected theorem lt_mul_of_div_lt {a b c : ℤ} (H1 : 0 < c) (H2 : a / c < b) : a < b * c := lt_of_not_ge $ mt (int.le_div_of_mul_le H1) (not_le_of_gt H2) protected theorem div_lt_iff_lt_mul {a b c : ℤ} (H : 0 < c) : a / c < b ↔ a < b * c := ⟨int.lt_mul_of_div_lt H, int.div_lt_of_lt_mul H⟩ protected theorem le_mul_of_div_le {a b c : ℤ} (H1 : 0 ≤ b) (H2 : b ∣ a) (H3 : a / b ≤ c) : a ≤ c * b := by rw [← int.div_mul_cancel H2]; exact decidable.mul_le_mul_of_nonneg_right H3 H1 protected theorem lt_div_of_mul_lt {a b c : ℤ} (H1 : 0 ≤ b) (H2 : b ∣ c) (H3 : a * b < c) : a < c / b := lt_of_not_ge $ mt (int.le_mul_of_div_le H1 H2) (not_le_of_gt H3) protected theorem lt_div_iff_mul_lt {a b : ℤ} (c : ℤ) (H : 0 < c) (H' : c ∣ b) : a < b / c ↔ a * c < b := ⟨int.mul_lt_of_lt_div H, int.lt_div_of_mul_lt (le_of_lt H) H'⟩ theorem div_pos_of_pos_of_dvd {a b : ℤ} (H1 : 0 < a) (H2 : 0 ≤ b) (H3 : b ∣ a) : 0 < a / b := int.lt_div_of_mul_lt H2 H3 (by rwa zero_mul) theorem div_eq_div_of_mul_eq_mul {a b c d : ℤ} (H2 : d ∣ c) (H3 : b ≠ 0) (H4 : d ≠ 0) (H5 : a * d = b * c) : a / b = c / d := int.div_eq_of_eq_mul_right H3 $ by rw [← int.mul_div_assoc _ H2]; exact (int.div_eq_of_eq_mul_left H4 H5.symm).symm theorem eq_mul_div_of_mul_eq_mul_of_dvd_left {a b c d : ℤ} (hb : b ≠ 0) (hbc : b ∣ c) (h : b * a = c * d) : a = c / b * d := begin cases hbc with k hk, subst hk, rw [int.mul_div_cancel_left _ hb], rw mul_assoc at h, apply mul_left_cancel' hb h end /-- If an integer with larger absolute value divides an integer, it is zero. -/ lemma eq_zero_of_dvd_of_nat_abs_lt_nat_abs {a b : ℤ} (w : a ∣ b) (h : nat_abs b < nat_abs a) : b = 0 := begin rw [←nat_abs_dvd, ←dvd_nat_abs, coe_nat_dvd] at w, rw ←nat_abs_eq_zero, exact eq_zero_of_dvd_of_lt w h end lemma eq_zero_of_dvd_of_nonneg_of_lt {a b : ℤ} (w₁ : 0 ≤ a) (w₂ : a < b) (h : b ∣ a) : a = 0 := eq_zero_of_dvd_of_nat_abs_lt_nat_abs h (nat_abs_lt_nat_abs_of_nonneg_of_lt w₁ w₂) /-- If two integers are congruent to a sufficiently large modulus, they are equal. -/ lemma eq_of_mod_eq_of_nat_abs_sub_lt_nat_abs {a b c : ℤ} (h1 : a % b = c) (h2 : nat_abs (a - c) < nat_abs b) : a = c := eq_of_sub_eq_zero (eq_zero_of_dvd_of_nat_abs_lt_nat_abs (dvd_sub_of_mod_eq h1) h2) theorem of_nat_add_neg_succ_of_nat_of_lt {m n : ℕ} (h : m < n.succ) : of_nat m + -[1+n] = -[1+ n - m] := begin change sub_nat_nat _ _ = _, have h' : n.succ - m = (n - m).succ, apply succ_sub, apply le_of_lt_succ h, simp [*, sub_nat_nat] end theorem of_nat_add_neg_succ_of_nat_of_ge {m n : ℕ} (h : n.succ ≤ m) : of_nat m + -[1+n] = of_nat (m - n.succ) := begin change sub_nat_nat _ _ = _, have h' : n.succ - m = 0, apply sub_eq_zero_of_le h, simp [*, sub_nat_nat] end @[simp] theorem neg_add_neg (m n : ℕ) : -[1+m] + -[1+n] = -[1+nat.succ(m+n)] := rfl /-! ### to_nat -/ theorem to_nat_eq_max : ∀ (a : ℤ), (to_nat a : ℤ) = max a 0 | (n : ℕ) := (max_eq_left (coe_zero_le n)).symm | -[1+ n] := (max_eq_right (le_of_lt (neg_succ_lt_zero n))).symm @[simp] lemma to_nat_zero : (0 : ℤ).to_nat = 0 := rfl @[simp] lemma to_nat_one : (1 : ℤ).to_nat = 1 := rfl @[simp] theorem to_nat_of_nonneg {a : ℤ} (h : 0 ≤ a) : (to_nat a : ℤ) = a := by rw [to_nat_eq_max, max_eq_left h] @[simp] lemma to_nat_sub_of_le {a b : ℤ} (h : b ≤ a) : (to_nat (a - b) : ℤ) = a - b := int.to_nat_of_nonneg (sub_nonneg_of_le h) @[simp] theorem to_nat_coe_nat (n : ℕ) : to_nat ↑n = n := rfl @[simp] lemma to_nat_coe_nat_add_one {n : ℕ} : ((n : ℤ) + 1).to_nat = n + 1 := rfl theorem le_to_nat (a : ℤ) : a ≤ to_nat a := by rw [to_nat_eq_max]; apply le_max_left @[simp] theorem to_nat_le {a : ℤ} {n : ℕ} : to_nat a ≤ n ↔ a ≤ n := by rw [(coe_nat_le_coe_nat_iff _ _).symm, to_nat_eq_max, max_le_iff]; exact and_iff_left (coe_zero_le _) @[simp] theorem lt_to_nat {n : ℕ} {a : ℤ} : n < to_nat a ↔ (n : ℤ) < a := le_iff_le_iff_lt_iff_lt.1 to_nat_le theorem to_nat_le_to_nat {a b : ℤ} (h : a ≤ b) : to_nat a ≤ to_nat b := by rw to_nat_le; exact le_trans h (le_to_nat b) theorem to_nat_lt_to_nat {a b : ℤ} (hb : 0 < b) : to_nat a < to_nat b ↔ a < b := ⟨λ h, begin cases a, exact lt_to_nat.1 h, exact lt_trans (neg_succ_of_nat_lt_zero a) hb, end, λ h, begin rw lt_to_nat, cases a, exact h, exact hb end⟩ theorem lt_of_to_nat_lt {a b : ℤ} (h : to_nat a < to_nat b) : a < b := (to_nat_lt_to_nat $ lt_to_nat.1 $ lt_of_le_of_lt (nat.zero_le _) h).1 h lemma to_nat_add {a b : ℤ} (ha : 0 ≤ a) (hb : 0 ≤ b) : (a + b).to_nat = a.to_nat + b.to_nat := begin lift a to ℕ using ha, lift b to ℕ using hb, norm_cast, end lemma to_nat_add_nat {a : ℤ} (ha : 0 ≤ a) (n : ℕ) : (a + n).to_nat = a.to_nat + n := begin lift a to ℕ using ha, norm_cast, end @[simp] lemma pred_to_nat : ∀ (i : ℤ), (i - 1).to_nat = i.to_nat - 1 | (0:ℕ) := rfl | (n+1:ℕ) := by simp | -[1+ n] := rfl @[simp] lemma to_nat_pred_coe_of_pos {i : ℤ} (h : 0 < i) : ((i.to_nat - 1 : ℕ) : ℤ) = i - 1 := by simp [h, le_of_lt h] with push_cast @[simp] lemma to_nat_sub_to_nat_neg : ∀ (n : ℤ), ↑n.to_nat - ↑((-n).to_nat) = n | (0 : ℕ) := rfl | (n+1 : ℕ) := show ↑(n+1) - (0:ℤ) = n+1, from sub_zero _ | -[1+ n] := show 0 - (n+1 : ℤ) = _, from zero_sub _ @[simp] lemma to_nat_add_to_nat_neg_eq_nat_abs : ∀ (n : ℤ), (n.to_nat) + ((-n).to_nat) = n.nat_abs | (0 : ℕ) := rfl | (n+1 : ℕ) := show (n+1) + 0 = n+1, from add_zero _ | -[1+ n] := show 0 + (n+1) = n+1, from zero_add _ /-- If `n : ℕ`, then `int.to_nat' n = some n`, if `n : ℤ` is negative, then `int.to_nat' n = none`. -/ def to_nat' : ℤ → option ℕ | (n : ℕ) := some n | -[1+ n] := none theorem mem_to_nat' : ∀ (a : ℤ) (n : ℕ), n ∈ to_nat' a ↔ a = n | (m : ℕ) n := option.some_inj.trans coe_nat_inj'.symm | -[1+ m] n := by split; intro h; cases h lemma to_nat_of_nonpos : ∀ {z : ℤ}, z ≤ 0 → z.to_nat = 0 | (0 : ℕ) := λ _, rfl | (n + 1 : ℕ) := λ h, (h.not_lt (by { exact_mod_cast nat.succ_pos n })).elim | (-[1+ n]) := λ _, rfl /-! ### units -/ @[simp] theorem units_nat_abs (u : units ℤ) : nat_abs u = 1 := units.ext_iff.1 $ nat.units_eq_one ⟨nat_abs u, nat_abs ↑u⁻¹, by rw [← nat_abs_mul, units.mul_inv]; refl, by rw [← nat_abs_mul, units.inv_mul]; refl⟩ theorem units_eq_one_or (u : units ℤ) : u = 1 ∨ u = -1 := by simpa only [units.ext_iff, units_nat_abs] using nat_abs_eq u lemma is_unit_eq_one_or {a : ℤ} : is_unit a → a = 1 ∨ a = -1 | ⟨x, hx⟩ := hx ▸ (units_eq_one_or _).imp (congr_arg coe) (congr_arg coe) lemma is_unit_iff {a : ℤ} : is_unit a ↔ a = 1 ∨ a = -1 := begin refine ⟨λ h, is_unit_eq_one_or h, λ h, _⟩, rcases h with rfl | rfl, { exact is_unit_one }, { exact is_unit_one.neg } end theorem is_unit_iff_nat_abs_eq {n : ℤ} : is_unit n ↔ n.nat_abs = 1 := by simp [nat_abs_eq_iff, is_unit_iff] lemma units_inv_eq_self (u : units ℤ) : u⁻¹ = u := (units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl) @[simp] lemma units_mul_self (u : units ℤ) : u * u = 1 := (units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl) -- `units.coe_mul` is a "wrong turn" for the simplifier, this undoes it and simplifies further @[simp] lemma units_coe_mul_self (u : units ℤ) : (u * u : ℤ) = 1 := by rw [←units.coe_mul, units_mul_self, units.coe_one] @[simp] lemma neg_one_pow_ne_zero {n : ℕ} : (-1 : ℤ)^n ≠ 0 := pow_ne_zero _ (abs_pos.mp trivial) /-! ### bitwise ops -/ @[simp] lemma bodd_zero : bodd 0 = ff := rfl @[simp] lemma bodd_one : bodd 1 = tt := rfl lemma bodd_two : bodd 2 = ff := rfl @[simp, norm_cast] lemma bodd_coe (n : ℕ) : int.bodd n = nat.bodd n := rfl @[simp] lemma bodd_sub_nat_nat (m n : ℕ) : bodd (sub_nat_nat m n) = bxor m.bodd n.bodd := by apply sub_nat_nat_elim m n (λ m n i, bodd i = bxor m.bodd n.bodd); intros; simp; cases i.bodd; simp @[simp] lemma bodd_neg_of_nat (n : ℕ) : bodd (neg_of_nat n) = n.bodd := by cases n; simp; refl @[simp] lemma bodd_neg (n : ℤ) : bodd (-n) = bodd n := by cases n; simp [has_neg.neg, int.coe_nat_eq, int.neg, bodd, -of_nat_eq_coe] @[simp] lemma bodd_add (m n : ℤ) : bodd (m + n) = bxor (bodd m) (bodd n) := by cases m with m m; cases n with n n; unfold has_add.add; simp [int.add, -of_nat_eq_coe, bool.bxor_comm] @[simp] lemma bodd_mul (m n : ℤ) : bodd (m * n) = bodd m && bodd n := by cases m with m m; cases n with n n; simp [← int.mul_def, int.mul, -of_nat_eq_coe, bool.bxor_comm] theorem bodd_add_div2 : ∀ n, cond (bodd n) 1 0 + 2 * div2 n = n | (n : ℕ) := by rw [show (cond (bodd n) 1 0 : ℤ) = (cond (bodd n) 1 0 : ℕ), by cases bodd n; refl]; exact congr_arg of_nat n.bodd_add_div2 | -[1+ n] := begin refine eq.trans _ (congr_arg neg_succ_of_nat n.bodd_add_div2), dsimp [bodd], cases nat.bodd n; dsimp [cond, bnot, div2, int.mul], { change -[1+ 2 * nat.div2 n] = _, rw zero_add }, { rw [zero_add, add_comm], refl } end theorem div2_val : ∀ n, div2 n = n / 2 | (n : ℕ) := congr_arg of_nat n.div2_val | -[1+ n] := congr_arg neg_succ_of_nat n.div2_val lemma bit0_val (n : ℤ) : bit0 n = 2 * n := (two_mul _).symm lemma bit1_val (n : ℤ) : bit1 n = 2 * n + 1 := congr_arg (+(1:ℤ)) (bit0_val _) lemma bit_val (b n) : bit b n = 2 * n + cond b 1 0 := by { cases b, apply (bit0_val n).trans (add_zero _).symm, apply bit1_val } lemma bit_decomp (n : ℤ) : bit (bodd n) (div2 n) = n := (bit_val _ _).trans $ (add_comm _ _).trans $ bodd_add_div2 _ /-- Defines a function from `ℤ` conditionally, if it is defined for odd and even integers separately using `bit`. -/ def {u} bit_cases_on {C : ℤ → Sort u} (n) (h : ∀ b n, C (bit b n)) : C n := by rw [← bit_decomp n]; apply h @[simp] lemma bit_zero : bit ff 0 = 0 := rfl @[simp] lemma bit_coe_nat (b) (n : ℕ) : bit b n = nat.bit b n := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bit_neg_succ (b) (n : ℕ) : bit b -[1+ n] = -[1+ nat.bit (bnot b) n] := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bodd_bit (b n) : bodd (bit b n) = b := by rw bit_val; simp; cases b; cases bodd 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_bit (b n) : div2 (bit b n) = n := begin rw [bit_val, div2_val, add_comm, int.add_mul_div_left, (_ : (_/2:ℤ) = 0), zero_add], cases b, { simp }, { show of_nat _ = _, rw nat.div_eq_zero; simp }, { cc } end lemma bit0_ne_bit1 (m n : ℤ) : bit0 m ≠ bit1 n := mt (congr_arg bodd) $ by simp lemma bit1_ne_bit0 (m n : ℤ) : bit1 m ≠ bit0 n := (bit0_ne_bit1 _ _).symm lemma bit1_ne_zero (m : ℤ) : bit1 m ≠ 0 := by simpa only [bit0_zero] using bit1_ne_bit0 m 0 @[simp] lemma test_bit_zero (b) : ∀ n, test_bit (bit b n) 0 = b | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_zero | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_zero]; clear test_bit_zero; cases b; refl @[simp] lemma test_bit_succ (m b) : ∀ n, test_bit (bit b n) (nat.succ m) = test_bit n m | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_succ | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_succ] private meta def bitwise_tac : tactic unit := `[ funext m, funext n, cases m with m m; cases n with n n; try {refl}, all_goals { apply congr_arg of_nat <|> apply congr_arg neg_succ_of_nat, try {dsimp [nat.land, nat.ldiff, nat.lor]}, try {rw [ show nat.bitwise (λ a b, a && bnot b) n m = nat.bitwise (λ a b, b && bnot a) m n, from congr_fun (congr_fun (@nat.bitwise_swap (λ a b, b && bnot a) rfl) n) m]}, apply congr_arg (λ f, nat.bitwise f m n), funext a, funext b, cases a; cases b; refl }, all_goals {unfold nat.land nat.ldiff nat.lor} ] theorem bitwise_or : bitwise bor = lor := by bitwise_tac theorem bitwise_and : bitwise band = land := by bitwise_tac theorem bitwise_diff : bitwise (λ a b, a && bnot b) = ldiff := by bitwise_tac theorem bitwise_xor : bitwise bxor = lxor := by bitwise_tac @[simp] lemma bitwise_bit (f : bool → bool → bool) (a m b n) : bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) := begin cases m with m m; cases n with n n; repeat { rw [← int.coe_nat_eq] <|> rw bit_coe_nat <|> rw bit_neg_succ }; unfold bitwise nat_bitwise bnot; [ induction h : f ff ff, induction h : f ff tt, induction h : f tt ff, induction h : f tt tt ], all_goals { unfold cond, rw nat.bitwise_bit, repeat { rw bit_coe_nat <|> rw bit_neg_succ <|> rw bnot_bnot } }, all_goals { unfold bnot {fail_if_unchanged := ff}; rw h; refl } end @[simp] lemma lor_bit (a m b n) : lor (bit a m) (bit b n) = bit (a || b) (lor m n) := by rw [← bitwise_or, bitwise_bit] @[simp] lemma land_bit (a m b n) : land (bit a m) (bit b n) = bit (a && b) (land m n) := by rw [← bitwise_and, bitwise_bit] @[simp] lemma ldiff_bit (a m b n) : ldiff (bit a m) (bit b n) = bit (a && bnot b) (ldiff m n) := by rw [← bitwise_diff, bitwise_bit] @[simp] lemma lxor_bit (a m b n) : lxor (bit a m) (bit b n) = bit (bxor a b) (lxor m n) := by rw [← bitwise_xor, bitwise_bit] @[simp] lemma lnot_bit (b) : ∀ n, lnot (bit b n) = bit (bnot b) (lnot n) | (n : ℕ) := by simp [lnot] | -[1+ n] := by simp [lnot] @[simp] lemma test_bit_bitwise (f : bool → bool → bool) (m n k) : test_bit (bitwise f m n) k = f (test_bit m k) (test_bit n k) := begin induction k with k IH generalizing m n; apply bit_cases_on m; intros a m'; apply bit_cases_on n; intros b n'; rw bitwise_bit, { simp [test_bit_zero] }, { simp [test_bit_succ, IH] } end @[simp] lemma test_bit_lor (m n k) : test_bit (lor m n) k = test_bit m k || test_bit n k := by rw [← bitwise_or, test_bit_bitwise] @[simp] lemma test_bit_land (m n k) : test_bit (land m n) k = test_bit m k && test_bit n k := by rw [← bitwise_and, test_bit_bitwise] @[simp] lemma test_bit_ldiff (m n k) : test_bit (ldiff m n) k = test_bit m k && bnot (test_bit n k) := by rw [← bitwise_diff, test_bit_bitwise] @[simp] lemma test_bit_lxor (m n k) : test_bit (lxor m n) k = bxor (test_bit m k) (test_bit n k) := by rw [← bitwise_xor, test_bit_bitwise] @[simp] lemma test_bit_lnot : ∀ n k, test_bit (lnot n) k = bnot (test_bit n k) | (n : ℕ) k := by simp [lnot, test_bit] | -[1+ n] k := by simp [lnot, test_bit] lemma shiftl_add : ∀ (m : ℤ) (n : ℕ) (k : ℤ), shiftl m (n + k) = shiftl (shiftl m n) k | (m : ℕ) n (k:ℕ) := congr_arg of_nat (nat.shiftl_add _ _ _) | -[1+ m] n (k:ℕ) := congr_arg neg_succ_of_nat (nat.shiftl'_add _ _ _ _) | (m : ℕ) n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl ↑m i = nat.shiftr (nat.shiftl m n) k) (λ i n, congr_arg coe $ by rw [← nat.shiftl_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg coe $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl_sub, nat.sub_self]; refl) | -[1+ m] n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl -[1+ m] i = -[1+ nat.shiftr (nat.shiftl' tt m n) k]) (λ i n, congr_arg neg_succ_of_nat $ by rw [← nat.shiftl'_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg neg_succ_of_nat $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl'_sub, nat.sub_self]; refl) lemma shiftl_sub (m : ℤ) (n : ℕ) (k : ℤ) : shiftl m (n - k) = shiftr (shiftl m n) k := shiftl_add _ _ _ @[simp] lemma shiftl_neg (m n : ℤ) : shiftl m (-n) = shiftr m n := rfl @[simp] lemma shiftr_neg (m n : ℤ) : shiftr m (-n) = shiftl m n := by rw [← shiftl_neg, neg_neg] @[simp] lemma shiftl_coe_nat (m n : ℕ) : shiftl m n = nat.shiftl m n := rfl @[simp] lemma shiftr_coe_nat (m n : ℕ) : shiftr m n = nat.shiftr m n := by cases n; refl @[simp] lemma shiftl_neg_succ (m n : ℕ) : shiftl -[1+ m] n = -[1+ nat.shiftl' tt m n] := rfl @[simp] lemma shiftr_neg_succ (m n : ℕ) : shiftr -[1+ m] n = -[1+ nat.shiftr m n] := by cases n; refl lemma shiftr_add : ∀ (m : ℤ) (n k : ℕ), shiftr m (n + k) = shiftr (shiftr m n) k | (m : ℕ) n k := by rw [shiftr_coe_nat, shiftr_coe_nat, ← int.coe_nat_add, shiftr_coe_nat, nat.shiftr_add] | -[1+ m] n k := by rw [shiftr_neg_succ, shiftr_neg_succ, ← int.coe_nat_add, shiftr_neg_succ, nat.shiftr_add] lemma shiftl_eq_mul_pow : ∀ (m : ℤ) (n : ℕ), shiftl m n = m * ↑(2 ^ n) | (m : ℕ) n := congr_arg coe (nat.shiftl_eq_mul_pow _ _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λi, -i) (nat.shiftl'_tt_eq_mul_pow _ _) lemma shiftr_eq_div_pow : ∀ (m : ℤ) (n : ℕ), shiftr m n = m / ↑(2 ^ n) | (m : ℕ) n := by rw shiftr_coe_nat; exact congr_arg coe (nat.shiftr_eq_div_pow _ _) | -[1+ m] n := begin rw [shiftr_neg_succ, neg_succ_of_nat_div, nat.shiftr_eq_div_pow], refl, exact coe_nat_lt_coe_nat_of_lt (pow_pos dec_trivial _) end lemma one_shiftl (n : ℕ) : shiftl 1 n = (2 ^ n : ℕ) := congr_arg coe (nat.one_shiftl _) @[simp] lemma zero_shiftl : ∀ n : ℤ, shiftl 0 n = 0 | (n : ℕ) := congr_arg coe (nat.zero_shiftl _) | -[1+ n] := congr_arg coe (nat.zero_shiftr _) @[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 := zero_shiftl _ /-! ### Least upper bound property for integers -/ /-- A computable version of `exists_least_of_bdd`: given a decidable predicate on the integers, with an explicit lower bound and a proof that it is somewhere true, return the least value for which the predicate is true. -/ def least_of_bdd {P : ℤ → Prop} [decidable_pred P] (b : ℤ) (Hb : ∀ z : ℤ, P z → b ≤ z) (Hinh : ∃ z : ℤ, P z) : {lb : ℤ // P lb ∧ (∀ z : ℤ, P z → lb ≤ z)} := have EX : ∃ n : ℕ, P (b + n), from let ⟨elt, Helt⟩ := Hinh in match elt, le.dest (Hb _ Helt), Helt with | ._, ⟨n, rfl⟩, Hn := ⟨n, Hn⟩ end, ⟨b + (nat.find EX : ℤ), nat.find_spec EX, λ z h, match z, le.dest (Hb _ h), h with | ._, ⟨n, rfl⟩, h := add_le_add_left (int.coe_nat_le.2 $ nat.find_min' _ h) _ end⟩ theorem exists_least_of_bdd {P : ℤ → Prop} (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → b ≤ z) (Hinh : ∃ z : ℤ, P z) : ∃ lb : ℤ, P lb ∧ (∀ z : ℤ, P z → lb ≤ z) := by classical; exact let ⟨b, Hb⟩ := Hbdd, ⟨lb, H⟩ := least_of_bdd b Hb Hinh in ⟨lb, H⟩ lemma coe_least_of_bdd_eq {P : ℤ → Prop} [decidable_pred P] {b b' : ℤ} (Hb : ∀ z : ℤ, P z → b ≤ z) (Hb' : ∀ z : ℤ, P z → b' ≤ z) (Hinh : ∃ z : ℤ, P z) : (least_of_bdd b Hb Hinh : ℤ) = least_of_bdd b' Hb' Hinh := begin rcases least_of_bdd b Hb Hinh with ⟨n, hn, h2n⟩, rcases least_of_bdd b' Hb' Hinh with ⟨n', hn', h2n'⟩, exact le_antisymm (h2n _ hn') (h2n' _ hn), end /-- A computable version of `exists_greatest_of_bdd`: given a decidable predicate on the integers, with an explicit upper bound and a proof that it is somewhere true, return the greatest value for which the predicate is true. -/ def greatest_of_bdd {P : ℤ → Prop} [decidable_pred P] (b : ℤ) (Hb : ∀ z : ℤ, P z → z ≤ b) (Hinh : ∃ z : ℤ, P z) : {ub : ℤ // P ub ∧ (∀ z : ℤ, P z → z ≤ ub)} := have Hbdd' : ∀ (z : ℤ), P (-z) → -b ≤ z, from λ z h, neg_le.1 (Hb _ h), have Hinh' : ∃ z : ℤ, P (-z), from let ⟨elt, Helt⟩ := Hinh in ⟨-elt, by rw [neg_neg]; exact Helt⟩, let ⟨lb, Plb, al⟩ := least_of_bdd (-b) Hbdd' Hinh' in ⟨-lb, Plb, λ z h, le_neg.1 $ al _ $ by rwa neg_neg⟩ theorem exists_greatest_of_bdd {P : ℤ → Prop} (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → z ≤ b) (Hinh : ∃ z : ℤ, P z) : ∃ ub : ℤ, P ub ∧ (∀ z : ℤ, P z → z ≤ ub) := by classical; exact let ⟨b, Hb⟩ := Hbdd, ⟨lb, H⟩ := greatest_of_bdd b Hb Hinh in ⟨lb, H⟩ lemma coe_greatest_of_bdd_eq {P : ℤ → Prop} [decidable_pred P] {b b' : ℤ} (Hb : ∀ z : ℤ, P z → z ≤ b) (Hb' : ∀ z : ℤ, P z → z ≤ b') (Hinh : ∃ z : ℤ, P z) : (greatest_of_bdd b Hb Hinh : ℤ) = greatest_of_bdd b' Hb' Hinh := begin rcases greatest_of_bdd b Hb Hinh with ⟨n, hn, h2n⟩, rcases greatest_of_bdd b' Hb' Hinh with ⟨n', hn', h2n'⟩, exact le_antisymm (h2n' _ hn) (h2n _ hn'), end end int attribute [irreducible] int.nonneg
fc90e4ca5b530218b77a6c4cdff7fe5851036bb0
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/probability/variance.lean
bf41ae83ad847999d6dbce010a0dad13c4db4202
[ "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
17,405
lean
/- Copyright (c) 2022 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Kexing Ying -/ import probability.notation import probability.integration import measure_theory.function.l2_space /-! # Variance of random variables > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We define the variance of a real-valued random variable as `Var[X] = 𝔼[(X - 𝔼[X])^2]` (in the `probability_theory` locale). ## Main definitions * `probability_theory.evariance`: the variance of a real-valued random variable as a extended non-negative real. * `probability_theory.variance`: the variance of a real-valued random variable as a real number. ## Main results * `probability_theory.variance_le_expectation_sq`: the inequality `Var[X] ≤ 𝔼[X^2]`. * `probability_theory.meas_ge_le_variance_div_sq`: Chebyshev's inequality, i.e., `ℙ {ω | c ≤ |X ω - 𝔼[X]|} ≤ ennreal.of_real (Var[X] / c ^ 2)`. * `probability_theory.meas_ge_le_evariance_div_sq`: Chebyshev's inequality formulated with `evariance` without requiring the random variables to be L². * `probability_theory.indep_fun.variance_add`: the variance of the sum of two independent random variables is the sum of the variances. * `probability_theory.indep_fun.variance_sum`: the variance of a finite sum of pairwise independent random variables is the sum of the variances. -/ open measure_theory filter finset noncomputable theory open_locale big_operators measure_theory probability_theory ennreal nnreal namespace probability_theory /-- The `ℝ≥0∞`-valued variance of a real-valued random variable defined as the Lebesgue integral of `(X - 𝔼[X])^2`. -/ def evariance {Ω : Type*} {m : measurable_space Ω} (X : Ω → ℝ) (μ : measure Ω) : ℝ≥0∞ := ∫⁻ ω, ‖X ω - μ[X]‖₊^2 ∂μ /-- The `ℝ`-valued variance of a real-valued random variable defined by applying `ennreal.to_real` to `evariance`. -/ def variance {Ω : Type*} {m : measurable_space Ω} (X : Ω → ℝ) (μ : measure Ω) : ℝ := (evariance X μ).to_real variables {Ω : Type*} {m : measurable_space Ω} {X : Ω → ℝ} {μ : measure Ω} lemma _root_.measure_theory.mem_ℒp.evariance_lt_top [is_finite_measure μ] (hX : mem_ℒp X 2 μ) : evariance X μ < ∞ := begin have := ennreal.pow_lt_top (hX.sub $ mem_ℒp_const $ μ[X]).2 2, rw [snorm_eq_lintegral_rpow_nnnorm two_ne_zero ennreal.two_ne_top, ← ennreal.rpow_two] at this, simp only [pi.sub_apply, ennreal.to_real_bit0, ennreal.one_to_real, one_div] at this, rw [← ennreal.rpow_mul, inv_mul_cancel (two_ne_zero : (2 : ℝ) ≠ 0), ennreal.rpow_one] at this, simp_rw ennreal.rpow_two at this, exact this, end lemma evariance_eq_top [is_finite_measure μ] (hXm : ae_strongly_measurable X μ) (hX : ¬ mem_ℒp X 2 μ) : evariance X μ = ∞ := begin by_contra h, rw [← ne.def, ← lt_top_iff_ne_top] at h, have : mem_ℒp (λ ω, X ω - μ[X]) 2 μ, { refine ⟨hXm.sub ae_strongly_measurable_const, _⟩, rw snorm_eq_lintegral_rpow_nnnorm two_ne_zero ennreal.two_ne_top, simp only [ennreal.to_real_bit0, ennreal.one_to_real, ennreal.rpow_two, ne.def], exact ennreal.rpow_lt_top_of_nonneg (by simp) h.ne }, refine hX _, convert this.add (mem_ℒp_const $ μ[X]), ext ω, rw [pi.add_apply, sub_add_cancel], end lemma evariance_lt_top_iff_mem_ℒp [is_finite_measure μ] (hX : ae_strongly_measurable X μ) : evariance X μ < ∞ ↔ mem_ℒp X 2 μ := begin refine ⟨_, measure_theory.mem_ℒp.evariance_lt_top⟩, contrapose, rw [not_lt, top_le_iff], exact evariance_eq_top hX end lemma _root_.measure_theory.mem_ℒp.of_real_variance_eq [is_finite_measure μ] (hX : mem_ℒp X 2 μ) : ennreal.of_real (variance X μ) = evariance X μ := by { rw [variance, ennreal.of_real_to_real], exact hX.evariance_lt_top.ne, } include m lemma evariance_eq_lintegral_of_real (X : Ω → ℝ) (μ : measure Ω) : evariance X μ = ∫⁻ ω, ennreal.of_real ((X ω - μ[X])^2) ∂μ := begin rw evariance, congr, ext1 ω, rw [pow_two, ← ennreal.coe_mul, ← nnnorm_mul, ← pow_two], congr, exact (real.to_nnreal_eq_nnnorm_of_nonneg $ sq_nonneg _).symm, end lemma _root_.measure_theory.mem_ℒp.variance_eq_of_integral_eq_zero (hX : mem_ℒp X 2 μ) (hXint : μ[X] = 0) : variance X μ = μ[X^2] := begin rw [variance, evariance_eq_lintegral_of_real, ← of_real_integral_eq_lintegral_of_real, ennreal.to_real_of_real]; simp_rw [hXint, sub_zero], { refl }, { exact integral_nonneg (λ ω, pow_two_nonneg _) }, { convert hX.integrable_norm_rpow two_ne_zero ennreal.two_ne_top, ext ω, simp only [pi.sub_apply, real.norm_eq_abs, ennreal.to_real_bit0, ennreal.one_to_real, real.rpow_two, pow_bit0_abs] }, { exact ae_of_all _ (λ ω, pow_two_nonneg _) } end lemma _root_.measure_theory.mem_ℒp.variance_eq [is_finite_measure μ] (hX : mem_ℒp X 2 μ) : variance X μ = μ[(X - (λ ω, μ[X]))^2] := begin rw [variance, evariance_eq_lintegral_of_real, ← of_real_integral_eq_lintegral_of_real, ennreal.to_real_of_real], { refl }, { exact integral_nonneg (λ ω, pow_two_nonneg _) }, { convert (hX.sub $ mem_ℒp_const (μ[X])).integrable_norm_rpow two_ne_zero ennreal.two_ne_top, ext ω, simp only [pi.sub_apply, real.norm_eq_abs, ennreal.to_real_bit0, ennreal.one_to_real, real.rpow_two, pow_bit0_abs] }, { exact ae_of_all _ (λ ω, pow_two_nonneg _) } end @[simp] lemma evariance_zero : evariance 0 μ = 0 := by simp [evariance] lemma evariance_eq_zero_iff (hX : ae_measurable X μ) : evariance X μ = 0 ↔ X =ᵐ[μ] λ ω, μ[X] := begin rw [evariance, lintegral_eq_zero_iff'], split; intro hX; filter_upwards [hX] with ω hω, { simp only [pi.zero_apply, pow_eq_zero_iff, nat.succ_pos', ennreal.coe_eq_zero, nnnorm_eq_zero, sub_eq_zero] at hω, exact hω }, { rw hω, simp }, { measurability } end lemma evariance_mul (c : ℝ) (X : Ω → ℝ) (μ : measure Ω) : evariance (λ ω, c * X ω) μ = ennreal.of_real (c^2) * evariance X μ := begin rw [evariance, evariance, ← lintegral_const_mul' _ _ ennreal.of_real_lt_top.ne], congr, ext1 ω, rw [ennreal.of_real, ← ennreal.coe_pow, ← ennreal.coe_pow, ← ennreal.coe_mul], congr, rw [← sq_abs, ← real.rpow_two, real.to_nnreal_rpow_of_nonneg (abs_nonneg _), nnreal.rpow_two, ← mul_pow, real.to_nnreal_mul_nnnorm _ (abs_nonneg _)], conv_rhs { rw [← nnnorm_norm, norm_mul, norm_abs_eq_norm, ← norm_mul, nnnorm_norm, mul_sub] }, congr, rw mul_comm, simp_rw [← smul_eq_mul, ← integral_smul_const, smul_eq_mul, mul_comm], end localized "notation (name := probability_theory.evariance) `eVar[` X `]` := probability_theory.evariance X measure_theory.measure_space.volume" in probability_theory @[simp] lemma variance_zero (μ : measure Ω) : variance 0 μ = 0 := by simp only [variance, evariance_zero, ennreal.zero_to_real] lemma variance_nonneg (X : Ω → ℝ) (μ : measure Ω) : 0 ≤ variance X μ := ennreal.to_real_nonneg lemma variance_mul (c : ℝ) (X : Ω → ℝ) (μ : measure Ω) : variance (λ ω, c * X ω) μ = c^2 * variance X μ := begin rw [variance, evariance_mul, ennreal.to_real_mul, ennreal.to_real_of_real (sq_nonneg _)], refl, end lemma variance_smul (c : ℝ) (X : Ω → ℝ) (μ : measure Ω) : variance (c • X) μ = c^2 * variance X μ := variance_mul c X μ lemma variance_smul' {A : Type*} [comm_semiring A] [algebra A ℝ] (c : A) (X : Ω → ℝ) (μ : measure Ω) : variance (c • X) μ = c^2 • variance X μ := begin convert variance_smul (algebra_map A ℝ c) X μ, { ext1 x, simp only [algebra_map_smul], }, { simp only [algebra.smul_def, map_pow], } end localized "notation (name := probability_theory.variance) `Var[` X `]` := probability_theory.variance X measure_theory.measure_space.volume" in probability_theory omit m variables [measure_space Ω] lemma variance_def' [is_probability_measure (ℙ : measure Ω)] {X : Ω → ℝ} (hX : mem_ℒp X 2) : Var[X] = 𝔼[X^2] - 𝔼[X]^2 := begin rw [hX.variance_eq, sub_sq', integral_sub', integral_add'], rotate, { exact hX.integrable_sq }, { convert integrable_const (𝔼[X] ^ 2), apply_instance }, { apply hX.integrable_sq.add, convert integrable_const (𝔼[X] ^ 2), apply_instance }, { exact ((hX.integrable one_le_two).const_mul 2).mul_const' _ }, simp only [integral_mul_right, pi.pow_apply, pi.mul_apply, pi.bit0_apply, pi.one_apply, integral_const (integral ℙ X ^ 2), integral_mul_left (2 : ℝ), one_mul, variance, pi.pow_apply, measure_univ, ennreal.one_to_real, algebra.id.smul_eq_mul], ring, end lemma variance_le_expectation_sq [is_probability_measure (ℙ : measure Ω)] {X : Ω → ℝ} (hm : ae_strongly_measurable X ℙ) : Var[X] ≤ 𝔼[X^2] := begin by_cases hX : mem_ℒp X 2, { rw variance_def' hX, simp only [sq_nonneg, sub_le_self_iff] }, rw [variance, evariance_eq_lintegral_of_real, ← integral_eq_lintegral_of_nonneg_ae], by_cases hint : integrable X, swap, { simp only [integral_undef hint, pi.pow_apply, pi.sub_apply, sub_zero] }, { rw integral_undef, { exact integral_nonneg (λ a, sq_nonneg _) }, { intro h, have A : mem_ℒp (X - λ (ω : Ω), 𝔼[X]) 2 ℙ := (mem_ℒp_two_iff_integrable_sq (hint.ae_strongly_measurable.sub ae_strongly_measurable_const)).2 h, have B : mem_ℒp (λ (ω : Ω), 𝔼[X]) 2 ℙ := mem_ℒp_const _, apply hX, convert A.add B, simp } }, { exact ae_of_all _ (λ x, sq_nonneg _) }, { exact (ae_measurable.pow_const (hm.ae_measurable.sub_const _) _).ae_strongly_measurable }, end lemma evariance_def' [is_probability_measure (ℙ : measure Ω)] {X : Ω → ℝ} (hX : ae_strongly_measurable X ℙ) : eVar[X] = (∫⁻ ω, ‖X ω‖₊^2) - ennreal.of_real (𝔼[X]^2) := begin by_cases hℒ : mem_ℒp X 2, { rw [← hℒ.of_real_variance_eq, variance_def' hℒ, ennreal.of_real_sub _ (sq_nonneg _)], congr, simp_rw ← ennreal.coe_pow, rw lintegral_coe_eq_integral, { congr' 2 with ω, simp only [pi.pow_apply, nnreal.coe_pow, coe_nnnorm, real.norm_eq_abs, pow_bit0_abs] }, { exact hℒ.abs.integrable_sq } }, { symmetry, rw [evariance_eq_top hX hℒ, ennreal.sub_eq_top_iff], refine ⟨_, ennreal.of_real_ne_top⟩, rw [mem_ℒp, not_and] at hℒ, specialize hℒ hX, simp only [snorm_eq_lintegral_rpow_nnnorm two_ne_zero ennreal.two_ne_top, not_lt, top_le_iff, ennreal.to_real_bit0, ennreal.one_to_real, ennreal.rpow_two, one_div, ennreal.rpow_eq_top_iff, inv_lt_zero, inv_pos, zero_lt_bit0, zero_lt_one, and_true, or_iff_not_imp_left, not_and_distrib] at hℒ, exact hℒ (λ _, zero_le_two) } end /-- *Chebyshev's inequality* for `ℝ≥0∞`-valued variance. -/ theorem meas_ge_le_evariance_div_sq {X : Ω → ℝ} (hX : ae_strongly_measurable X ℙ) {c : ℝ≥0} (hc : c ≠ 0) : ℙ {ω | ↑c ≤ |X ω - 𝔼[X]|} ≤ eVar[X] / c ^ 2 := begin have A : (c : ℝ≥0∞) ≠ 0, { rwa [ne.def, ennreal.coe_eq_zero] }, have B : ae_strongly_measurable (λ (ω : Ω), 𝔼[X]) ℙ := ae_strongly_measurable_const, convert meas_ge_le_mul_pow_snorm ℙ two_ne_zero ennreal.two_ne_top (hX.sub B) A, { ext ω, simp only [pi.sub_apply, ennreal.coe_le_coe, ← real.norm_eq_abs, ← coe_nnnorm, nnreal.coe_le_coe, ennreal.of_real_coe_nnreal] }, { rw snorm_eq_lintegral_rpow_nnnorm two_ne_zero ennreal.two_ne_top, simp only [ennreal.to_real_bit0, ennreal.one_to_real, pi.sub_apply, one_div], rw [div_eq_mul_inv, ennreal.inv_pow, mul_comm, ennreal.rpow_two], congr, simp_rw [← ennreal.rpow_mul, inv_mul_cancel (two_ne_zero : (2 : ℝ) ≠ 0), ennreal.rpow_two, ennreal.rpow_one, evariance] } end /-- *Chebyshev's inequality* : one can control the deviation probability of a real random variable from its expectation in terms of the variance. -/ theorem meas_ge_le_variance_div_sq [is_finite_measure (ℙ : measure Ω)] {X : Ω → ℝ} (hX : mem_ℒp X 2) {c : ℝ} (hc : 0 < c) : ℙ {ω | c ≤ |X ω - 𝔼[X]|} ≤ ennreal.of_real (Var[X] / c ^ 2) := begin rw [ennreal.of_real_div_of_pos (sq_pos_of_ne_zero _ hc.ne.symm), hX.of_real_variance_eq], convert @meas_ge_le_evariance_div_sq _ _ _ hX.1 (c.to_nnreal) (by simp [hc]), { simp only [real.coe_to_nnreal', max_le_iff, abs_nonneg, and_true] }, { rw ennreal.of_real_pow hc.le, refl } end /-- The variance of the sum of two independent random variables is the sum of the variances. -/ theorem indep_fun.variance_add [is_probability_measure (ℙ : measure Ω)] {X Y : Ω → ℝ} (hX : mem_ℒp X 2) (hY : mem_ℒp Y 2) (h : indep_fun X Y) : Var[X + Y] = Var[X] + Var[Y] := calc Var[X + Y] = 𝔼[λ a, (X a)^2 + (Y a)^2 + 2 * X a * Y a] - 𝔼[X+Y]^2 : by simp [variance_def' (hX.add hY), add_sq'] ... = (𝔼[X^2] + 𝔼[Y^2] + 2 * 𝔼[X * Y]) - (𝔼[X] + 𝔼[Y])^2 : begin simp only [pi.add_apply, pi.pow_apply, pi.mul_apply, mul_assoc], rw [integral_add, integral_add, integral_add, integral_mul_left], { exact hX.integrable one_le_two }, { exact hY.integrable one_le_two }, { exact hX.integrable_sq }, { exact hY.integrable_sq }, { exact hX.integrable_sq.add hY.integrable_sq }, { apply integrable.const_mul, exact h.integrable_mul (hX.integrable one_le_two) (hY.integrable one_le_two) } end ... = (𝔼[X^2] + 𝔼[Y^2] + 2 * (𝔼[X] * 𝔼[Y])) - (𝔼[X] + 𝔼[Y])^2 : begin congr, exact h.integral_mul_of_integrable (hX.integrable one_le_two) (hY.integrable one_le_two), end ... = Var[X] + Var[Y] : by { simp only [variance_def', hX, hY, pi.pow_apply], ring } /-- The variance of a finite sum of pairwise independent random variables is the sum of the variances. -/ theorem indep_fun.variance_sum [is_probability_measure (ℙ : measure Ω)] {ι : Type*} {X : ι → Ω → ℝ} {s : finset ι} (hs : ∀ i ∈ s, mem_ℒp (X i) 2) (h : set.pairwise ↑s (λ i j, indep_fun (X i) (X j))) : Var[∑ i in s, X i] = ∑ i in s, Var[X i] := begin classical, induction s using finset.induction_on with k s ks IH, { simp only [finset.sum_empty, variance_zero] }, rw [variance_def' (mem_ℒp_finset_sum' _ hs), sum_insert ks, sum_insert ks], simp only [add_sq'], calc 𝔼[X k ^ 2 + (∑ i in s, X i) ^ 2 + 2 * X k * ∑ i in s, X i] - 𝔼[X k + ∑ i in s, X i] ^ 2 = (𝔼[X k ^ 2] + 𝔼[(∑ i in s, X i) ^ 2] + 𝔼[2 * X k * ∑ i in s, X i]) - (𝔼[X k] + 𝔼[∑ i in s, X i]) ^ 2 : begin rw [integral_add', integral_add', integral_add'], { exact mem_ℒp.integrable one_le_two (hs _ (mem_insert_self _ _)) }, { apply integrable_finset_sum' _ (λ i hi, _), exact mem_ℒp.integrable one_le_two (hs _ (mem_insert_of_mem hi)) }, { exact mem_ℒp.integrable_sq (hs _ (mem_insert_self _ _)) }, { apply mem_ℒp.integrable_sq, exact mem_ℒp_finset_sum' _ (λ i hi, (hs _ (mem_insert_of_mem hi))) }, { apply integrable.add, { exact mem_ℒp.integrable_sq (hs _ (mem_insert_self _ _)) }, { apply mem_ℒp.integrable_sq, exact mem_ℒp_finset_sum' _ (λ i hi, (hs _ (mem_insert_of_mem hi))) } }, { rw mul_assoc, apply integrable.const_mul _ (2:ℝ), simp only [mul_sum, sum_apply, pi.mul_apply], apply integrable_finset_sum _ (λ i hi, _), apply indep_fun.integrable_mul _ (mem_ℒp.integrable one_le_two (hs _ (mem_insert_self _ _))) (mem_ℒp.integrable one_le_two (hs _ (mem_insert_of_mem hi))), apply h (mem_insert_self _ _) (mem_insert_of_mem hi), exact (λ hki, ks (hki.symm ▸ hi)) } end ... = Var[X k] + Var[∑ i in s, X i] + (𝔼[2 * X k * ∑ i in s, X i] - 2 * 𝔼[X k] * 𝔼[∑ i in s, X i]) : begin rw [variance_def' (hs _ (mem_insert_self _ _)), variance_def' (mem_ℒp_finset_sum' _ (λ i hi, (hs _ (mem_insert_of_mem hi))))], ring, end ... = Var[X k] + Var[∑ i in s, X i] : begin simp only [mul_assoc, integral_mul_left, pi.mul_apply, pi.bit0_apply, pi.one_apply, sum_apply, add_right_eq_self, mul_sum], rw integral_finset_sum s (λ i hi, _), swap, { apply integrable.const_mul _ (2:ℝ), apply indep_fun.integrable_mul _ (mem_ℒp.integrable one_le_two (hs _ (mem_insert_self _ _))) (mem_ℒp.integrable one_le_two (hs _ (mem_insert_of_mem hi))), apply h (mem_insert_self _ _) (mem_insert_of_mem hi), exact (λ hki, ks (hki.symm ▸ hi)) }, rw [integral_finset_sum s (λ i hi, (mem_ℒp.integrable one_le_two (hs _ (mem_insert_of_mem hi)))), mul_sum, mul_sum, ← sum_sub_distrib], apply finset.sum_eq_zero (λ i hi, _), rw [integral_mul_left, indep_fun.integral_mul', sub_self], { apply h (mem_insert_self _ _) (mem_insert_of_mem hi), exact (λ hki, ks (hki.symm ▸ hi)) }, { exact mem_ℒp.ae_strongly_measurable (hs _ (mem_insert_self _ _)) }, { exact mem_ℒp.ae_strongly_measurable (hs _ (mem_insert_of_mem hi)) } end ... = Var[X k] + ∑ i in s, Var[X i] : by rw IH (λ i hi, hs i (mem_insert_of_mem hi)) (h.mono (by simp only [coe_insert, set.subset_insert])) end end probability_theory
266315d811eb85e627a9f738415f616c7f236ede
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/topology/algebra/group_with_zero.lean
6ade1929d75e2cf64c4014cd797df17b0a7b6e30
[ "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
11,406
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import topology.algebra.monoid import algebra.group.pi import algebra.group_with_zero.power import topology.homeomorph /-! # Topological group with zero In this file we define `has_continuous_inv'` to be a mixin typeclass a type with `has_inv` and `has_zero` (e.g., a `group_with_zero`) such that `λ x, x⁻¹` is continuous at all nonzero points. Any normed (semi)field has this property. Currently the only example of `has_continuous_inv'` in `mathlib` which is not a normed field is the type `nnnreal` (a.k.a. `ℝ≥0`) of nonnegative real numbers. Then we prove lemmas about continuity of `x ↦ x⁻¹` and `f / g` providing dot-style `*.inv'` and `*.div` operations on `filter.tendsto`, `continuous_at`, `continuous_within_at`, `continuous_on`, and `continuous`. As a special case, we provide `*.div_const` operations that require only `group_with_zero` and `has_continuous_mul` instances. All lemmas about `(⁻¹)` use `inv'` in their names because lemmas without `'` are used for `topological_group`s. We also use `'` in the typeclass name `has_continuous_inv'` for the sake of consistency of notation. On a `group_with_zero` with continuous multiplication, we also define left and right multiplication as homeomorphisms. -/ open_locale topological_space filter open filter function /-! ### A group with zero with continuous multiplication If `G₀` is a group with zero with continuous `(*)`, then `(/y)` is continuous for any `y`. In this section we prove lemmas that immediately follow from this fact providing `*.div_const` dot-style operations on `filter.tendsto`, `continuous_at`, `continuous_within_at`, `continuous_on`, and `continuous`. -/ variables {α β G₀ : Type*} section div_const variables [group_with_zero G₀] [topological_space G₀] [has_continuous_mul G₀] {f : α → G₀} {s : set α} {l : filter α} lemma filter.tendsto.div_const {x y : G₀} (hf : tendsto f l (𝓝 x)) : tendsto (λa, f a / y) l (𝓝 (x / y)) := by simpa only [div_eq_mul_inv] using hf.mul tendsto_const_nhds variables [topological_space α] lemma continuous_at.div_const {a : α} (hf : continuous_at f a) {y : G₀} : continuous_at (λ x, f x / y) a := by simpa only [div_eq_mul_inv] using hf.mul continuous_at_const lemma continuous_within_at.div_const {a} (hf : continuous_within_at f s a) {y : G₀} : continuous_within_at (λ x, f x / y) s a := hf.div_const lemma continuous_on.div_const (hf : continuous_on f s) {y : G₀} : continuous_on (λ x, f x / y) s := by simpa only [div_eq_mul_inv] using hf.mul continuous_on_const @[continuity] lemma continuous.div_const (hf : continuous f) {y : G₀} : continuous (λ x, f x / y) := by simpa only [div_eq_mul_inv] using hf.mul continuous_const end div_const /-- A type with `0` and `has_inv` such that `λ x, x⁻¹` is continuous at all nonzero points. Any normed (semi)field has this property. -/ class has_continuous_inv₀ (G₀ : Type*) [has_zero G₀] [has_inv G₀] [topological_space G₀] := (continuous_at_inv₀ : ∀ ⦃x : G₀⦄, x ≠ 0 → continuous_at has_inv.inv x) export has_continuous_inv₀ (continuous_at_inv₀) section inv₀ variables [has_zero G₀] [has_inv G₀] [topological_space G₀] [has_continuous_inv₀ G₀] {l : filter α} {f : α → G₀} {s : set α} {a : α} /-! ### Continuity of `λ x, x⁻¹` at a non-zero point We define `topological_group_with_zero` to be a `group_with_zero` such that the operation `x ↦ x⁻¹` is continuous at all nonzero points. In this section we prove dot-style `*.inv'` lemmas for `filter.tendsto`, `continuous_at`, `continuous_within_at`, `continuous_on`, and `continuous`. -/ lemma tendsto_inv₀ {x : G₀} (hx : x ≠ 0) : tendsto has_inv.inv (𝓝 x) (𝓝 x⁻¹) := continuous_at_inv₀ hx lemma continuous_on_inv₀ : continuous_on (has_inv.inv : G₀ → G₀) {0}ᶜ := λ x hx, (continuous_at_inv₀ hx).continuous_within_at /-- If a function converges to a nonzero value, its inverse converges to the inverse of this value. We use the name `tendsto.inv₀` as `tendsto.inv` is already used in multiplicative topological groups. -/ lemma filter.tendsto.inv₀ {a : G₀} (hf : tendsto f l (𝓝 a)) (ha : a ≠ 0) : tendsto (λ x, (f x)⁻¹) l (𝓝 a⁻¹) := (tendsto_inv₀ ha).comp hf variables [topological_space α] lemma continuous_within_at.inv₀ (hf : continuous_within_at f s a) (ha : f a ≠ 0) : continuous_within_at (λ x, (f x)⁻¹) s a := hf.inv₀ ha lemma continuous_at.inv₀ (hf : continuous_at f a) (ha : f a ≠ 0) : continuous_at (λ x, (f x)⁻¹) a := hf.inv₀ ha @[continuity] lemma continuous.inv₀ (hf : continuous f) (h0 : ∀ x, f x ≠ 0) : continuous (λ x, (f x)⁻¹) := continuous_iff_continuous_at.2 $ λ x, (hf.tendsto x).inv₀ (h0 x) lemma continuous_on.inv₀ (hf : continuous_on f s) (h0 : ∀ x ∈ s, f x ≠ 0) : continuous_on (λ x, (f x)⁻¹) s := λ x hx, (hf x hx).inv₀ (h0 x hx) end inv₀ /-! ### Continuity of division If `G₀` is a `group_with_zero` with `x ↦ x⁻¹` continuous at all nonzero points and `(*)`, then division `(/)` is continuous at any point where the denominator is continuous. -/ section div variables [group_with_zero G₀] [topological_space G₀] [has_continuous_inv₀ G₀] [has_continuous_mul G₀] {f g : α → G₀} lemma filter.tendsto.div {l : filter α} {a b : G₀} (hf : tendsto f l (𝓝 a)) (hg : tendsto g l (𝓝 b)) (hy : b ≠ 0) : tendsto (f / g) l (𝓝 (a / b)) := by simpa only [div_eq_mul_inv] using hf.mul (hg.inv₀ hy) variables [topological_space α] [topological_space β] {s : set α} {a : α} lemma continuous_within_at.div (hf : continuous_within_at f s a) (hg : continuous_within_at g s a) (h₀ : g a ≠ 0) : continuous_within_at (f / g) s a := hf.div hg h₀ lemma continuous_on.div (hf : continuous_on f s) (hg : continuous_on g s) (h₀ : ∀ x ∈ s, g x ≠ 0) : continuous_on (f / g) s := λ x hx, (hf x hx).div (hg x hx) (h₀ x hx) /-- Continuity at a point of the result of dividing two functions continuous at that point, where the denominator is nonzero. -/ lemma continuous_at.div (hf : continuous_at f a) (hg : continuous_at g a) (h₀ : g a ≠ 0) : continuous_at (f / g) a := hf.div hg h₀ @[continuity] lemma continuous.div (hf : continuous f) (hg : continuous g) (h₀ : ∀ x, g x ≠ 0) : continuous (f / g) := by simpa only [div_eq_mul_inv] using hf.mul (hg.inv₀ h₀) lemma continuous_on_div : continuous_on (λ p : G₀ × G₀, p.1 / p.2) {p | p.2 ≠ 0} := continuous_on_fst.div continuous_on_snd $ λ _, id /-- The function `f x / g x` is discontinuous when `g x = 0`. However, under appropriate conditions, `h x (f x / g x)` is still continuous. The condition is that if `g a = 0` then `h x y` must tend to `h a 0` when `x` tends to `a`, with no information about `y`. This is represented by the `⊤` filter. Note: `filter.tendsto_prod_top_iff` characterizes this convergence in uniform spaces. See also `filter.prod_top` and `filter.mem_prod_top`. -/ lemma continuous_at.comp_div_cases {f g : α → G₀} (h : α → G₀ → β) (hf : continuous_at f a) (hg : continuous_at g a) (hh : g a ≠ 0 → continuous_at ↿h (a, f a / g a)) (h2h : g a = 0 → tendsto ↿h (𝓝 a ×ᶠ ⊤) (𝓝 (h a 0))) : continuous_at (λ x, h x (f x / g x)) a := begin show continuous_at (↿h ∘ (λ x, (x, f x / g x))) a, by_cases hga : g a = 0, { rw [continuous_at], simp_rw [comp_app, hga, div_zero], exact (h2h hga).comp (continuous_at_id.prod_mk tendsto_top) }, { exact continuous_at.comp (hh hga) (continuous_at_id.prod (hf.div hg hga)) } end /-- `h x (f x / g x)` is continuous under certain conditions, even if the denominator is sometimes `0`. See docstring of `continuous_at.comp_div_cases`. -/ lemma continuous.comp_div_cases {f g : α → G₀} (h : α → G₀ → β) (hf : continuous f) (hg : continuous g) (hh : ∀ a, g a ≠ 0 → continuous_at ↿h (a, f a / g a)) (h2h : ∀ a, g a = 0 → tendsto ↿h (𝓝 a ×ᶠ ⊤) (𝓝 (h a 0))) : continuous (λ x, h x (f x / g x)) := continuous_iff_continuous_at.mpr $ λ a, hf.continuous_at.comp_div_cases _ hg.continuous_at (hh a) (h2h a) end div /-! ### Left and right multiplication as homeomorphisms -/ namespace homeomorph variables [topological_space α] [group_with_zero α] [has_continuous_mul α] /-- Left multiplication by a nonzero element in a `group_with_zero` with continuous multiplication is a homeomorphism of the underlying type. -/ protected def mul_left₀ (c : α) (hc : c ≠ 0) : α ≃ₜ α := { continuous_to_fun := continuous_mul_left _, continuous_inv_fun := continuous_mul_left _, .. equiv.mul_left₀ c hc } /-- Right multiplication by a nonzero element in a `group_with_zero` with continuous multiplication is a homeomorphism of the underlying type. -/ protected def mul_right₀ (c : α) (hc : c ≠ 0) : α ≃ₜ α := { continuous_to_fun := continuous_mul_right _, continuous_inv_fun := continuous_mul_right _, .. equiv.mul_right₀ c hc } @[simp] lemma coe_mul_left₀ (c : α) (hc : c ≠ 0) : ⇑(homeomorph.mul_left₀ c hc) = (*) c := rfl @[simp] lemma mul_left₀_symm_apply (c : α) (hc : c ≠ 0) : ((homeomorph.mul_left₀ c hc).symm : α → α) = (*) c⁻¹ := rfl @[simp] lemma coe_mul_right₀ (c : α) (hc : c ≠ 0) : ⇑(homeomorph.mul_right₀ c hc) = λ x, x * c := rfl @[simp] lemma mul_right₀_symm_apply (c : α) (hc : c ≠ 0) : ((homeomorph.mul_right₀ c hc).symm : α → α) = λ x, x * c⁻¹ := rfl end homeomorph section zpow variables [group_with_zero G₀] [topological_space G₀] [has_continuous_inv₀ G₀] [has_continuous_mul G₀] lemma continuous_at_zpow (x : G₀) (m : ℤ) (h : x ≠ 0 ∨ 0 ≤ m) : continuous_at (λ x, x ^ m) x := begin cases m, { simpa only [zpow_of_nat] using continuous_at_pow x m }, { simp only [zpow_neg_succ_of_nat], have hx : x ≠ 0, from h.resolve_right (int.neg_succ_of_nat_lt_zero m).not_le, exact (continuous_at_pow x (m + 1)).inv₀ (pow_ne_zero _ hx) } end lemma continuous_on_zpow (m : ℤ) : continuous_on (λ x : G₀, x ^ m) {0}ᶜ := λ x hx, (continuous_at_zpow _ _ (or.inl hx)).continuous_within_at lemma filter.tendsto.zpow {f : α → G₀} {l : filter α} {a : G₀} (hf : tendsto f l (𝓝 a)) (m : ℤ) (h : a ≠ 0 ∨ 0 ≤ m) : tendsto (λ x, (f x) ^ m) l (𝓝 (a ^ m)) := (continuous_at_zpow _ m h).tendsto.comp hf variables {X : Type*} [topological_space X] {a : X} {s : set X} {f : X → G₀} lemma continuous_at.zpow (hf : continuous_at f a) (m : ℤ) (h : f a ≠ 0 ∨ 0 ≤ m) : continuous_at (λ x, (f x) ^ m) a := hf.zpow m h lemma continuous_within_at.zpow (hf : continuous_within_at f s a) (m : ℤ) (h : f a ≠ 0 ∨ 0 ≤ m) : continuous_within_at (λ x, f x ^ m) s a := hf.zpow m h lemma continuous_on.zpow (hf : continuous_on f s) (m : ℤ) (h : ∀ a ∈ s, f a ≠ 0 ∨ 0 ≤ m) : continuous_on (λ x, f x ^ m) s := λ a ha, (hf a ha).zpow m (h a ha) @[continuity] lemma continuous.zpow (hf : continuous f) (m : ℤ) (h0 : ∀ a, f a ≠ 0 ∨ 0 ≤ m) : continuous (λ x, (f x) ^ m) := continuous_iff_continuous_at.2 $ λ x, (hf.tendsto x).zpow m (h0 x) end zpow
16485c5bdf3b2a4f64d46b0a7b6a840de90e26c0
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/ParserCompiler/Attribute.lean
13fdf32dc9184d063963929d027b8a591c241d14
[ "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
2,031
lean
/- Copyright (c) 2020 Sebastian Ullrich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Attributes import Lean.Compiler.InitAttr import Lean.ToExpr namespace Lean namespace ParserCompiler structure CombinatorAttribute where impl : AttributeImpl ext : SimplePersistentEnvExtension (Name × Name) (NameMap Name) deriving Inhabited -- TODO(Sebastian): We'll probably want priority support here at some point def registerCombinatorAttribute (name : Name) (descr : String) (ref : Name := by exact decl_name%) : IO CombinatorAttribute := do let ext : SimplePersistentEnvExtension (Name × Name) (NameMap Name) ← registerSimplePersistentEnvExtension { name := ref, addImportedFn := mkStateFromImportedEntries (fun s p => s.insert p.1 p.2) {}, addEntryFn := fun (s : NameMap Name) (p : Name × Name) => s.insert p.1 p.2, } let attrImpl : AttributeImpl := { ref := ref, name := name, descr := descr, add := fun decl stx _ => do let env ← getEnv let parserDeclName ← Elab.resolveGlobalConstNoOverloadWithInfo (← Attribute.Builtin.getIdent stx) setEnv <| ext.addEntry env (parserDeclName, decl) } registerBuiltinAttribute attrImpl pure { impl := attrImpl, ext := ext } namespace CombinatorAttribute def getDeclFor? (attr : CombinatorAttribute) (env : Environment) (parserDecl : Name) : Option Name := (attr.ext.getState env).find? parserDecl def setDeclFor (attr : CombinatorAttribute) (env : Environment) (parserDecl : Name) (decl : Name) : Environment := attr.ext.addEntry env (parserDecl, decl) unsafe def runDeclFor {α} (attr : CombinatorAttribute) (parserDecl : Name) : CoreM α := do match attr.getDeclFor? (← getEnv) parserDecl with | some d => evalConst α d | _ => throwError "no declaration of attribute [{attr.impl.name}] found for '{parserDecl}'" end CombinatorAttribute end ParserCompiler end Lean
4a295a1a97abba8b814bd9e5a91829b242355fd2
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/real/pi/bounds.lean
2a6c704d82b90282dd6095e3e71fff239d60887c
[ "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
7,898
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Mario Carneiro -/ import analysis.special_functions.trigonometric.bounds /-! # Pi > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains lemmas which establish bounds on `real.pi`. Notably, these include `pi_gt_sqrt_two_add_series` and `pi_lt_sqrt_two_add_series`, which bound `π` using series; numerical bounds on `π` such as `pi_gt_314`and `pi_lt_315` (more precise versions are given, too). See also `data.real.pi.leibniz` and `data.real.pi.wallis` for infinite formulas for `π`. -/ open_locale real namespace real lemma pi_gt_sqrt_two_add_series (n : ℕ) : 2 ^ (n+1) * sqrt (2 - sqrt_two_add_series 0 n) < π := begin have : sqrt (2 - sqrt_two_add_series 0 n) / 2 * 2 ^ (n+2) < π, { rw [← lt_div_iff, ←sin_pi_over_two_pow_succ], apply sin_lt, apply div_pos pi_pos, all_goals { apply pow_pos, norm_num } }, apply lt_of_le_of_lt (le_of_eq _) this, rw [pow_succ _ (n+1), ←mul_assoc, div_mul_cancel, mul_comm], norm_num end lemma pi_lt_sqrt_two_add_series (n : ℕ) : π < 2 ^ (n+1) * sqrt (2 - sqrt_two_add_series 0 n) + 1 / 4 ^ n := begin have : π < (sqrt (2 - sqrt_two_add_series 0 n) / 2 + 1 / (2 ^ n) ^ 3 / 4) * 2 ^ (n+2), { rw [← div_lt_iff, ← sin_pi_over_two_pow_succ], refine lt_of_lt_of_le (lt_add_of_sub_right_lt (sin_gt_sub_cube _ _)) _, { apply div_pos pi_pos, apply pow_pos, norm_num }, { rw div_le_iff', { refine le_trans pi_le_four _, simp only [show ((4 : ℝ) = 2 ^ 2), by norm_num, mul_one], apply pow_le_pow, norm_num, apply le_add_of_nonneg_left, apply nat.zero_le }, { apply pow_pos, norm_num } }, apply add_le_add_left, rw div_le_div_right, rw [le_div_iff, ←mul_pow], refine le_trans _ (le_of_eq (one_pow 3)), apply pow_le_pow_of_le_left, { apply le_of_lt, apply mul_pos, apply div_pos pi_pos, apply pow_pos, norm_num, apply pow_pos, norm_num }, rw ← le_div_iff, refine le_trans ((div_le_div_right _).mpr pi_le_four) _, apply pow_pos, norm_num, rw [pow_succ, pow_succ, ←mul_assoc, ←div_div], convert le_rfl, all_goals { repeat {apply pow_pos}, norm_num }}, apply lt_of_lt_of_le this (le_of_eq _), rw [add_mul], congr' 1, { rw [pow_succ _ (n+1), ←mul_assoc, div_mul_cancel, mul_comm], norm_num }, rw [pow_succ, ←pow_mul, mul_comm n 2, pow_mul, show (2 : ℝ) ^ 2 = 4, by norm_num, pow_succ, pow_succ, ←mul_assoc (2 : ℝ), show (2 : ℝ) * 2 = 4, by norm_num, ←mul_assoc, div_mul_cancel, mul_comm ((2 : ℝ) ^ n), ←div_div, div_mul_cancel], apply pow_ne_zero, norm_num, norm_num end /-- From an upper bound on `sqrt_two_add_series 0 n = 2 cos (π / 2 ^ (n+1))` of the form `sqrt_two_add_series 0 n ≤ 2 - (a / 2 ^ (n + 1)) ^ 2)`, one can deduce the lower bound `a < π` thanks to basic trigonometric inequalities as expressed in `pi_gt_sqrt_two_add_series`. -/ theorem pi_lower_bound_start (n : ℕ) {a} (h : sqrt_two_add_series ((0:ℕ) / (1:ℕ)) n ≤ 2 - (a / 2 ^ (n + 1)) ^ 2) : a < π := begin refine lt_of_le_of_lt _ (pi_gt_sqrt_two_add_series n), rw [mul_comm], refine (div_le_iff (pow_pos (by norm_num) _ : (0 : ℝ) < _)).mp (le_sqrt_of_sq_le _), rwa [le_sub_comm, show (0:ℝ) = (0:ℕ)/(1:ℕ), by rw [nat.cast_zero, zero_div]], end lemma sqrt_two_add_series_step_up (c d : ℕ) {a b n : ℕ} {z : ℝ} (hz : sqrt_two_add_series (c/d) n ≤ z) (hb : 0 < b) (hd : 0 < d) (h : (2 * b + a) * d ^ 2 ≤ c ^ 2 * b) : sqrt_two_add_series (a/b) (n+1) ≤ z := begin refine le_trans _ hz, rw sqrt_two_add_series_succ, apply sqrt_two_add_series_monotone_left, have hb' : 0 < (b:ℝ) := nat.cast_pos.2 hb, have hd' : 0 < (d:ℝ) := nat.cast_pos.2 hd, rw [sqrt_le_left (div_nonneg c.cast_nonneg d.cast_nonneg), div_pow, add_div_eq_mul_add_div _ _ (ne_of_gt hb'), div_le_div_iff hb' (pow_pos hd' _)], exact_mod_cast h end /-- Create a proof of `a < π` for a fixed rational number `a`, given a witness, which is a sequence of rational numbers `sqrt 2 < r 1 < r 2 < ... < r n < 2` satisfying the property that `sqrt (2 + r i) ≤ r(i+1)`, where `r 0 = 0` and `sqrt (2 - r n) ≥ a/2^(n+1)`. -/ meta def pi_lower_bound (l : list ℚ) : tactic unit := do let n := l.length, tactic.apply `(@pi_lower_bound_start %%(reflect n)), l.mmap' (λ r, do let a := r.num.to_nat, let b := r.denom, (() <$ tactic.apply `(@sqrt_two_add_series_step_up %%(reflect a) %%(reflect b))); [tactic.skip, `[norm_num1], `[norm_num1], `[norm_num1]]), `[simp only [sqrt_two_add_series, nat.cast_bit0, nat.cast_bit1, nat.cast_one, nat.cast_zero]], `[norm_num1] /-- From a lower bound on `sqrt_two_add_series 0 n = 2 cos (π / 2 ^ (n+1))` of the form `2 - ((a - 1 / 4 ^ n) / 2 ^ (n + 1)) ^ 2 ≤ sqrt_two_add_series 0 n`, one can deduce the upper bound `π < a` thanks to basic trigonometric formulas as expressed in `pi_lt_sqrt_two_add_series`. -/ theorem pi_upper_bound_start (n : ℕ) {a} (h : 2 - ((a - 1 / 4 ^ n) / 2 ^ (n + 1)) ^ 2 ≤ sqrt_two_add_series ((0:ℕ) / (1:ℕ)) n) (h₂ : 1 / 4 ^ n ≤ a) : π < a := begin refine lt_of_lt_of_le (pi_lt_sqrt_two_add_series n) _, rw [← le_sub_iff_add_le, ← le_div_iff', sqrt_le_left, sub_le_comm], { rwa [nat.cast_zero, zero_div] at h }, { exact div_nonneg (sub_nonneg.2 h₂) (pow_nonneg (le_of_lt zero_lt_two) _) }, { exact pow_pos zero_lt_two _ } end lemma sqrt_two_add_series_step_down (a b : ℕ) {c d n : ℕ} {z : ℝ} (hz : z ≤ sqrt_two_add_series (a/b) n) (hb : 0 < b) (hd : 0 < d) (h : a ^ 2 * d ≤ (2 * d + c) * b ^ 2) : z ≤ sqrt_two_add_series (c/d) (n+1) := begin apply le_trans hz, rw sqrt_two_add_series_succ, apply sqrt_two_add_series_monotone_left, apply le_sqrt_of_sq_le, have hb' : 0 < (b:ℝ) := nat.cast_pos.2 hb, have hd' : 0 < (d:ℝ) := nat.cast_pos.2 hd, rw [div_pow, add_div_eq_mul_add_div _ _ (ne_of_gt hd'), div_le_div_iff (pow_pos hb' _) hd'], exact_mod_cast h end /-- Create a proof of `π < a` for a fixed rational number `a`, given a witness, which is a sequence of rational numbers `sqrt 2 < r 1 < r 2 < ... < r n < 2` satisfying the property that `sqrt (2 + r i) ≥ r(i+1)`, where `r 0 = 0` and `sqrt (2 - r n) ≥ (a - 1/4^n) / 2^(n+1)`. -/ meta def pi_upper_bound (l : list ℚ) : tactic unit := do let n := l.length, (() <$ tactic.apply `(@pi_upper_bound_start %%(reflect n))); [pure (), `[norm_num1]], l.mmap' (λ r, do let a := r.num.to_nat, let b := r.denom, (() <$ tactic.apply `(@sqrt_two_add_series_step_down %%(reflect a) %%(reflect b))); [pure (), `[norm_num1], `[norm_num1], `[norm_num1]]), `[simp only [sqrt_two_add_series, nat.cast_bit0, nat.cast_bit1, nat.cast_one, nat.cast_zero]], `[norm_num] lemma pi_gt_three : 3 < π := by pi_lower_bound [23/16] lemma pi_gt_314 : 3.14 < π := by pi_lower_bound [99/70, 874/473, 1940/989, 1447/727] lemma pi_lt_315 : π < 3.15 := by pi_upper_bound [140/99, 279/151, 51/26, 412/207] lemma pi_gt_31415 : 3.1415 < π := by pi_lower_bound [ 11482/8119, 5401/2923, 2348/1197, 11367/5711, 25705/12868, 23235/11621] lemma pi_lt_31416 : π < 3.1416 := by pi_upper_bound [ 4756/3363, 101211/54775, 505534/257719, 83289/41846, 411278/205887, 438142/219137, 451504/225769, 265603/132804, 849938/424971] lemma pi_gt_3141592 : 3.141592 < π := by pi_lower_bound [ 11482/8119, 7792/4217, 54055/27557, 949247/476920, 3310126/1657059, 2635492/1318143, 1580265/790192, 1221775/610899, 3612247/1806132, 849943/424972] lemma pi_lt_3141593 : π < 3.141593 := by pi_upper_bound [ 27720/19601, 56935/30813, 49359/25163, 258754/130003, 113599/56868, 1101994/551163, 8671537/4336095, 3877807/1938940, 52483813/26242030, 56946167/28473117, 23798415/11899211] end real
d8fd2c643f50f408cc12e679b428a5bfc9370dde
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Elab/BuiltinCommand.lean
cba007eef0ec1837803af3f584fcef7e783c899c
[ "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
18,538
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.Elab.DeclarationRange import Lean.DocString import Lean.Util.CollectLevelParams import Lean.Elab.Eval import Lean.Elab.Command import Lean.Elab.Open namespace Lean.Elab.Command @[builtinCommandElab moduleDoc] def elabModuleDoc : CommandElab := fun stx => do match stx[1] with | Syntax.atom _ val => let doc := val.extract 0 (val.endPos - ⟨2⟩) let range ← Elab.getDeclarationRange stx modifyEnv fun env => addMainModuleDoc env ⟨doc, range⟩ | _ => throwErrorAt stx "unexpected module doc string{indentD stx[1]}" private def addScope (isNewNamespace : Bool) (isNoncomputable : Bool) (header : String) (newNamespace : Name) : CommandElabM Unit := do modify fun s => { s with env := s.env.registerNamespace newNamespace, scopes := { s.scopes.head! with header := header, currNamespace := newNamespace, isNoncomputable := s.scopes.head!.isNoncomputable || isNoncomputable } :: s.scopes } pushScope if isNewNamespace then activateScoped newNamespace private def addScopes (isNewNamespace : Bool) (isNoncomputable : Bool) : Name → CommandElabM Unit | .anonymous => pure () | .str p header => do addScopes isNewNamespace isNoncomputable p let currNamespace ← getCurrNamespace addScope isNewNamespace isNoncomputable header (if isNewNamespace then Name.mkStr currNamespace header else currNamespace) | _ => throwError "invalid scope" private def addNamespace (header : Name) : CommandElabM Unit := addScopes (isNewNamespace := true) (isNoncomputable := false) header def withNamespace {α} (ns : Name) (elabFn : CommandElabM α) : CommandElabM α := do addNamespace ns let a ← elabFn modify fun s => { s with scopes := s.scopes.drop ns.getNumParts } pure a private def popScopes (numScopes : Nat) : CommandElabM Unit := for _ in [0:numScopes] do popScope private def checkAnonymousScope : List Scope → Bool | { header := "", .. } :: _ => true | _ => false private def checkEndHeader : Name → List Scope → Bool | .anonymous, _ => true | .str p s, { header := h, .. } :: scopes => h == s && checkEndHeader p scopes | _, _ => false @[builtinCommandElab «namespace»] def elabNamespace : CommandElab := fun stx => match stx with | `(namespace $n) => addNamespace n.getId | _ => throwUnsupportedSyntax @[builtinCommandElab «section»] def elabSection : CommandElab := fun stx => do match stx with | `(section $header:ident) => addScopes (isNewNamespace := false) (isNoncomputable := false) header.getId | `(section) => addScope (isNewNamespace := false) (isNoncomputable := false) "" (← getCurrNamespace) | _ => throwUnsupportedSyntax @[builtinCommandElab noncomputableSection] def elabNonComputableSection : CommandElab := fun stx => do match stx with | `(noncomputable section $header:ident) => addScopes (isNewNamespace := false) (isNoncomputable := true) header.getId | `(noncomputable section) => addScope (isNewNamespace := false) (isNoncomputable := true) "" (← getCurrNamespace) | _ => throwUnsupportedSyntax @[builtinCommandElab «end»] def elabEnd : CommandElab := fun stx => do let header? := (stx.getArg 1).getOptionalIdent?; let endSize := match header? with | none => 1 | some n => n.getNumParts let scopes ← getScopes if endSize < scopes.length then modify fun s => { s with scopes := s.scopes.drop endSize } popScopes endSize else -- we keep "root" scope let n := (← get).scopes.length - 1 modify fun s => { s with scopes := s.scopes.drop n } popScopes n throwError "invalid 'end', insufficient scopes" match header? with | none => unless checkAnonymousScope scopes do throwError "invalid 'end', name is missing" | some header => unless checkEndHeader header scopes do addCompletionInfo <| CompletionInfo.endSection stx (scopes.map fun scope => scope.header) throwError "invalid 'end', name mismatch" private partial def elabChoiceAux (cmds : Array Syntax) (i : Nat) : CommandElabM Unit := if h : i < cmds.size then let cmd := cmds.get ⟨i, h⟩; catchInternalId unsupportedSyntaxExceptionId (elabCommand cmd) (fun _ => elabChoiceAux cmds (i+1)) else throwUnsupportedSyntax @[builtinCommandElab choice] def elabChoice : CommandElab := fun stx => elabChoiceAux stx.getArgs 0 @[builtinCommandElab «universe»] def elabUniverse : CommandElab := fun n => do n[1].forArgsM addUnivLevel @[builtinCommandElab «init_quot»] def elabInitQuot : CommandElab := fun _ => do match (← getEnv).addDecl Declaration.quotDecl with | Except.ok env => setEnv env | Except.error ex => throwError (ex.toMessageData (← getOptions)) @[builtinCommandElab «export»] def elabExport : CommandElab := fun stx => do -- `stx` is of the form (Command.export "export" <namespace> "(" (null <ids>*) ")") let id := stx[1].getId let nss ← resolveNamespace id let currNamespace ← getCurrNamespace if nss == [currNamespace] then throwError "invalid 'export', self export" let ids := stx[3].getArgs let mut aliases := #[] for idStx in ids do let id := idStx.getId let declName ← resolveNameUsingNamespaces nss idStx aliases := aliases.push (currNamespace ++ id, declName) modify fun s => { s with env := aliases.foldl (init := s.env) fun env p => addAlias env p.1 p.2 } @[builtinCommandElab «open»] def elabOpen : CommandElab := fun n => do let openDecls ← elabOpenDecl n[1] modifyScope fun scope => { scope with openDecls := openDecls } private def typelessBinder? : Syntax → Option (Array (TSyntax [`ident, `Lean.Parser.Term.hole]) × Bool) | `(bracketedBinder|($ids*)) => some <| (ids, true) | `(bracketedBinder|{$ids*}) => some <| (ids, false) | _ => none /-- If `id` is an identifier, return true if `ids` contains `id`. -/ private def containsId (ids : Array (TSyntax [`ident, ``Parser.Term.hole])) (id : TSyntax [`ident, ``Parser.Term.hole]) : Bool := id.raw.isIdent && ids.any fun id' => id'.raw.getId == id.raw.getId /-- Auxiliary method for processing binder annotation update commands: `variable (α)` and `variable {α}`. The argument `binder` is the binder of the `variable` command. The method retuns an array containing the "residue", that is, variables that do not correspond to updates. Recall that a `bracketedBinder` can be of the form `(x y)`. ``` variable {α β : Type} variable (α γ) ``` The second `variable` command updates the binder annotation for `α`, and returns "residue" `γ`. -/ private def replaceBinderAnnotation (binder : TSyntax ``Parser.Term.bracketedBinder) : CommandElabM (Array (TSyntax ``Parser.Term.bracketedBinder)) := do let some (binderIds, explicit) := typelessBinder? binder | return #[binder] let varDecls := (← getScope).varDecls let mut varDeclsNew := #[] let mut binderIds := binderIds let mut binderIdsIniSize := binderIds.size let mut modifiedVarDecls := false for varDecl in varDecls do let (ids, ty?, explicit') ← match varDecl with | `(bracketedBinder|($ids* $[: $ty?]? $(annot?)?)) => if annot?.isSome then for binderId in binderIds do if containsId ids binderId then throwErrorAt binderId "cannot update binder annotation of variables with default values/tactics" pure (ids, ty?, true) | `(bracketedBinder|{$ids* $[: $ty?]?}) => pure (ids, ty?, false) | `(bracketedBinder|[$id : $_]) => for binderId in binderIds do if binderId.raw.isIdent && binderId.raw.getId == id.getId then throwErrorAt binderId "cannot change the binder annotation of the previously declared local instance `{id.getId}`" varDeclsNew := varDeclsNew.push varDecl; continue | _ => varDeclsNew := varDeclsNew.push varDecl; continue if explicit == explicit' then -- no update, ensure we don't have redundant annotations. for binderId in binderIds do if containsId ids binderId then throwErrorAt binderId "redundant binder annotation update" varDeclsNew := varDeclsNew.push varDecl else if binderIds.all fun binderId => !containsId ids binderId then -- `binderIds` and `ids` are disjoint varDeclsNew := varDeclsNew.push varDecl else let mkBinder (id : TSyntax [`ident, ``Parser.Term.hole]) (explicit : Bool) : CommandElabM (TSyntax ``Parser.Term.bracketedBinder) := if explicit then `(bracketedBinder| ($id $[: $ty?]?)) else `(bracketedBinder| {$id $[: $ty?]?}) for id in ids do if let some idx := binderIds.findIdx? fun binderId => binderId.raw.isIdent && binderId.raw.getId == id.raw.getId then binderIds := binderIds.eraseIdx idx modifiedVarDecls := true varDeclsNew := varDeclsNew.push (← mkBinder id explicit) else varDeclsNew := varDeclsNew.push (← mkBinder id explicit') if modifiedVarDecls then modifyScope fun scope => { scope with varDecls := varDeclsNew } if binderIds.size != binderIdsIniSize then binderIds.mapM fun binderId => if explicit then `(bracketedBinder| ($binderId)) else `(bracketedBinder| {$binderId}) else return #[binder] @[builtinCommandElab «variable»] def elabVariable : CommandElab | `(variable $binders*) => do -- Try to elaborate `binders` for sanity checking runTermElabM fun _ => Term.withAutoBoundImplicit <| Term.elabBinders binders fun _ => pure () for binder in binders do let binders ← replaceBinderAnnotation binder -- Remark: if we want to produce error messages when variables shadow existing ones, here is the place to do it. for binder in binders do let varUIds ← getBracketedBinderIds binder |>.mapM (withFreshMacroScope ∘ MonadQuotation.addMacroScope) modifyScope fun scope => { scope with varDecls := scope.varDecls.push binder, varUIds := scope.varUIds ++ varUIds } | _ => throwUnsupportedSyntax open Meta def elabCheckCore (ignoreStuckTC : Bool) : CommandElab | `(#check%$tk $term) => withoutModifyingEnv <| runTermElabM fun _ => Term.withDeclName `_check do let e ← Term.elabTerm term none Term.synthesizeSyntheticMVarsNoPostponing (ignoreStuckTC := ignoreStuckTC) let (e, _) ← Term.levelMVarToParam (← instantiateMVars e) let type ← inferType e unless e.isSyntheticSorry do logInfoAt tk m!"{e} : {type}" | _ => throwUnsupportedSyntax @[builtinCommandElab Lean.Parser.Command.check] def elabCheck : CommandElab := elabCheckCore (ignoreStuckTC := true) @[builtinCommandElab Lean.Parser.Command.reduce] def elabReduce : CommandElab | `(#reduce%$tk $term) => withoutModifyingEnv <| runTermElabM fun _ => Term.withDeclName `_reduce do let e ← Term.elabTerm term none Term.synthesizeSyntheticMVarsNoPostponing let (e, _) ← Term.levelMVarToParam (← instantiateMVars e) -- TODO: add options or notation for setting the following parameters withTheReader Core.Context (fun ctx => { ctx with options := ctx.options.setBool `smartUnfolding false }) do let e ← withTransparency (mode := TransparencyMode.all) <| reduce e (skipProofs := false) (skipTypes := false) logInfoAt tk e | _ => throwUnsupportedSyntax def hasNoErrorMessages : CommandElabM Bool := do return !(← get).messages.hasErrors def failIfSucceeds (x : CommandElabM Unit) : CommandElabM Unit := do let resetMessages : CommandElabM MessageLog := do let s ← get let messages := s.messages; modify fun s => { s with messages := {} }; pure messages let restoreMessages (prevMessages : MessageLog) : CommandElabM Unit := do modify fun s => { s with messages := prevMessages ++ s.messages.errorsToWarnings } let prevMessages ← resetMessages let succeeded ← try x hasNoErrorMessages catch | ex@(Exception.error _ _) => do logException ex; pure false | Exception.internal id _ => do logError (← id.getName); pure false finally restoreMessages prevMessages if succeeded then throwError "unexpected success" @[builtinCommandElab «check_failure»] def elabCheckFailure : CommandElab | `(#check_failure $term) => do failIfSucceeds <| elabCheckCore (ignoreStuckTC := false) (← `(#check $term)) | _ => throwUnsupportedSyntax private def mkEvalInstCore (evalClassName : Name) (e : Expr) : MetaM Expr := do let α ← inferType e let u ← getDecLevel α let inst := mkApp (Lean.mkConst evalClassName [u]) α try synthInstance inst catch _ => -- Put `α` in WHNF and try again try let α ← whnf α synthInstance (mkApp (Lean.mkConst evalClassName [u]) α) catch _ => -- Fully reduce `α` and try again try let α ← reduce (skipTypes := false) α synthInstance (mkApp (Lean.mkConst evalClassName [u]) α) catch _ => throwError "expression{indentExpr e}\nhas type{indentExpr α}\nbut instance{indentExpr inst}\nfailed to be synthesized, this instance instructs Lean on how to display the resulting value, recall that any type implementing the `Repr` class also implements the `{evalClassName}` class" private def mkRunMetaEval (e : Expr) : MetaM Expr := withLocalDeclD `env (mkConst ``Lean.Environment) fun env => withLocalDeclD `opts (mkConst ``Lean.Options) fun opts => do let α ← inferType e let u ← getDecLevel α let instVal ← mkEvalInstCore ``Lean.MetaEval e let e := mkAppN (mkConst ``Lean.runMetaEval [u]) #[α, instVal, env, opts, e] instantiateMVars (← mkLambdaFVars #[env, opts] e) private def mkRunEval (e : Expr) : MetaM Expr := do let α ← inferType e let u ← getDecLevel α let instVal ← mkEvalInstCore ``Lean.Eval e instantiateMVars (mkAppN (mkConst ``Lean.runEval [u]) #[α, instVal, mkSimpleThunk e]) unsafe def elabEvalUnsafe : CommandElab | `(#eval%$tk $term) => do let declName := `_eval let addAndCompile (value : Expr) : TermElabM Unit := do let (value, _) ← Term.levelMVarToParam (← instantiateMVars value) let type ← inferType value let us := collectLevelParams {} value |>.params let value ← instantiateMVars value let decl := Declaration.defnDecl { name := declName levelParams := us.toList type := type value := value hints := ReducibilityHints.opaque safety := DefinitionSafety.unsafe } Term.ensureNoUnassignedMVars decl addAndCompile decl -- Elaborate `term` let elabEvalTerm : TermElabM Expr := do let e ← Term.elabTerm term none Term.synthesizeSyntheticMVarsNoPostponing if (← Term.logUnassignedUsingErrorInfos (← getMVars e)) then throwAbortTerm if (← isProp e) then mkDecide e else return e -- Evaluate using term using `MetaEval` class. let elabMetaEval : CommandElabM Unit := do -- act? is `some act` if elaborated `term` has type `CommandElabM α` let act? ← runTermElabM fun _ => Term.withDeclName declName do let e ← elabEvalTerm let eType ← instantiateMVars (← inferType e) if eType.isAppOfArity ``CommandElabM 1 then let mut stx ← Term.exprToSyntax e unless (← isDefEq eType.appArg! (mkConst ``Unit)) do stx ← `($stx >>= fun v => IO.println (repr v)) let act ← Lean.Elab.Term.evalTerm (CommandElabM Unit) (mkApp (mkConst ``CommandElabM) (mkConst ``Unit)) stx pure <| some act else let e ← mkRunMetaEval e let env ← getEnv let opts ← getOptions let act ← try addAndCompile e; evalConst (Environment → Options → IO (String × Except IO.Error Environment)) declName finally setEnv env let (out, res) ← act env opts -- we execute `act` using the environment logInfoAt tk out match res with | Except.error e => throwError e.toString | Except.ok env => do setEnv env; pure none let some act := act? | return () act -- Evaluate using term using `Eval` class. let elabEval : CommandElabM Unit := runTermElabM fun _ => Term.withDeclName declName do -- fall back to non-meta eval if MetaEval hasn't been defined yet -- modify e to `runEval e` let e ← mkRunEval (← elabEvalTerm) let env ← getEnv let act ← try addAndCompile e; evalConst (IO (String × Except IO.Error Unit)) declName finally setEnv env let (out, res) ← liftM (m := IO) act logInfoAt tk out match res with | Except.error e => throwError e.toString | Except.ok _ => pure () if (← getEnv).contains ``Lean.MetaEval then do elabMetaEval else elabEval | _ => throwUnsupportedSyntax @[builtinCommandElab «eval», implementedBy elabEvalUnsafe] opaque elabEval : CommandElab @[builtinCommandElab «synth»] def elabSynth : CommandElab := fun stx => do let term := stx[1] withoutModifyingEnv <| runTermElabM fun _ => Term.withDeclName `_synth_cmd do let inst ← Term.elabTerm term none Term.synthesizeSyntheticMVarsNoPostponing let inst ← instantiateMVars inst let val ← synthInstance inst logInfo val pure () @[builtinCommandElab «set_option»] def elabSetOption : CommandElab := fun stx => do let options ← Elab.elabSetOption stx[1] stx[2] modify fun s => { s with maxRecDepth := maxRecDepth.get options } modifyScope fun scope => { scope with opts := options } @[builtinMacro Lean.Parser.Command.«in»] def expandInCmd : Macro | `($cmd₁ in $cmd₂) => `(section $cmd₁:command $cmd₂ end) | _ => Macro.throwUnsupported @[builtinCommandElab Parser.Command.addDocString] def elabAddDeclDoc : CommandElab := fun stx => do match stx with | `($doc:docComment add_decl_doc $id) => let declName ← resolveGlobalConstNoOverloadWithInfo id addDocString declName (← getDocStringText doc) | _ => throwUnsupportedSyntax end Lean.Elab.Command
d57dc7769c4445132ee221bd55fa760b0eb5df21
9ad8d18fbe5f120c22b5e035bc240f711d2cbd7e
/src/undergraduate/MAS114/Semester 1/Q20.lean
8e259e1f1f21c8e1c616dc372d4217e988904501
[]
no_license
agusakov/lean_lib
c0e9cc29fc7d2518004e224376adeb5e69b5cc1a
f88d162da2f990b87c4d34f5f46bbca2bbc5948e
refs/heads/master
1,642,141,461,087
1,557,395,798,000
1,557,395,798,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
949
lean
import tactic.norm_num namespace MAS114 namespace exercises_1 namespace Q20 lemma L1 : nat.gcd 896 1200 = 16 := begin have e0 : 1200 % 896 = 304 := by norm_num, have e1 : 896 % 304 = 288 := by norm_num, have e2 : 304 % 288 = 16 := by norm_num, have e3 : 288 % 16 = 0 := by norm_num, exact calc nat.gcd 896 1200 = nat.gcd 304 896 : by rw[nat.gcd_rec,e0] ... = nat.gcd 288 304 : by rw[nat.gcd_rec,e1] ... = nat.gcd 16 288 : by rw[nat.gcd_rec,e2] ... = nat.gcd 0 16 : by rw[nat.gcd_rec,e3] ... = 16 : rfl end lemma L2 : nat.gcd 123456789 987654321 = 9 := begin have e0 : 987654321 % 123456789 = 9 := by norm_num, have e1 : 123456789 % 9 = 0 := by norm_num, exact calc nat.gcd 123456789 987654321 = nat.gcd 9 123456789 : by rw[nat.gcd_rec,e0] ... = nat.gcd 0 9 : by rw[nat.gcd_rec,e1] ... = 9 : rfl end end Q20 end exercises_1 end MAS114
e7e73611f7c49cc705a473631528e59a45caaf7b
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/pfilter.lean
33fa6d787f53a9cef7a073c1ca6526f95d18a3aa
[ "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
5,128
lean
/- Copyright (c) 2020 Mathieu Guay-Paquet. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mathieu Guay-Paquet -/ import order.ideal /-! # Order filters ## Main definitions Throughout this file, `P` is at least a preorder, but some sections require more structure, such as a bottom element, a top element, or a join-semilattice structure. - `order.pfilter P`: The type of nonempty, downward directed, upward closed subsets of `P`. This is dual to `order.ideal`, so it simply wraps `order.ideal Pᵒᵈ`. - `order.is_pfilter P`: a predicate for when a `set P` is a filter. Note the relation between `order/filter` and `order/pfilter`: for any type `α`, `filter α` represents the same mathematical object as `pfilter (set α)`. ## References - <https://en.wikipedia.org/wiki/Filter_(mathematics)> ## Tags pfilter, filter, ideal, dual -/ namespace order variables {P : Type*} /-- A filter on a preorder `P` is a subset of `P` that is - nonempty - downward directed - upward closed. -/ structure pfilter (P) [preorder P] := (dual : ideal Pᵒᵈ) /-- A predicate for when a subset of `P` is a filter. -/ def is_pfilter [preorder P] (F : set P) : Prop := @is_ideal Pᵒᵈ _ F lemma is_pfilter.of_def [preorder P] {F : set P} (nonempty : F.nonempty) (directed : directed_on (≥) F) (mem_of_le : ∀ {x y : P}, x ≤ y → x ∈ F → y ∈ F) : is_pfilter F := ⟨λ _ _ _ _, mem_of_le ‹_› ‹_›, nonempty, directed⟩ /-- Create an element of type `order.pfilter` from a set satisfying the predicate `order.is_pfilter`. -/ def is_pfilter.to_pfilter [preorder P] {F : set P} (h : is_pfilter F) : pfilter P := ⟨h.to_ideal⟩ namespace pfilter section preorder variables [preorder P] {x y : P} (F s t : pfilter P) instance [inhabited P] : inhabited (pfilter P) := ⟨⟨default⟩⟩ /-- A filter on `P` is a subset of `P`. -/ instance : has_coe (pfilter P) (set P) := ⟨λ F, F.dual.carrier⟩ /-- For the notation `x ∈ F`. -/ instance : has_mem P (pfilter P) := ⟨λ x F, x ∈ (F : set P)⟩ @[simp] lemma mem_coe : x ∈ (F : set P) ↔ x ∈ F := iff_of_eq rfl lemma is_pfilter : is_pfilter (F : set P) := F.dual.is_ideal lemma nonempty : (F : set P).nonempty := F.dual.nonempty lemma directed : directed_on (≥) (F : set P) := F.dual.directed lemma mem_of_le {F : pfilter P} : x ≤ y → x ∈ F → y ∈ F := λ h, F.dual.lower h /-- Two filters are equal when their underlying sets are equal. -/ @[ext] lemma ext (h : (s : set P) = t) : s = t := by { cases s, cases t, exact congr_arg _ (ideal.ext h) } /-- The partial ordering by subset inclusion, inherited from `set P`. -/ instance : partial_order (pfilter P) := partial_order.lift coe ext @[trans] lemma mem_of_mem_of_le {F G : pfilter P} : x ∈ F → F ≤ G → x ∈ G := ideal.mem_of_mem_of_le /-- The smallest filter containing a given element. -/ def principal (p : P) : pfilter P := ⟨ideal.principal p⟩ @[simp] lemma mem_def (x : P) (I : ideal Pᵒᵈ) : x ∈ (⟨I⟩ : pfilter P) ↔ order_dual.to_dual x ∈ I := iff.rfl @[simp] lemma principal_le_iff {F : pfilter P} : principal x ≤ F ↔ x ∈ F := ideal.principal_le_iff @[simp] lemma mem_principal : x ∈ principal y ↔ y ≤ x := ideal.mem_principal -- defeq abuse lemma antitone_principal : antitone (principal : P → pfilter P) := by delta antitone; simp lemma principal_le_principal_iff {p q : P} : principal q ≤ principal p ↔ p ≤ q := by simp end preorder section order_top variables [preorder P] [order_top P] {F : pfilter P} /-- A specific witness of `pfilter.nonempty` when `P` has a top element. -/ @[simp] lemma top_mem : ⊤ ∈ F := ideal.bot_mem _ /-- There is a bottom filter when `P` has a top element. -/ instance : order_bot (pfilter P) := { bot := ⟨⊥⟩, bot_le := λ F, (bot_le : ⊥ ≤ F.dual) } end order_top /-- There is a top filter when `P` has a bottom element. -/ instance {P} [preorder P] [order_bot P] : order_top (pfilter P) := { top := ⟨⊤⟩, le_top := λ F, (le_top : F.dual ≤ ⊤) } section semilattice_inf variables [semilattice_inf P] {x y : P} {F : pfilter P} /-- A specific witness of `pfilter.directed` when `P` has meets. -/ lemma inf_mem (hx : x ∈ F) (hy : y ∈ F) : x ⊓ y ∈ F := ideal.sup_mem hx hy @[simp] lemma inf_mem_iff : x ⊓ y ∈ F ↔ x ∈ F ∧ y ∈ F := ideal.sup_mem_iff end semilattice_inf section complete_semilattice_Inf variables [complete_semilattice_Inf P] {F : pfilter P} lemma Inf_gc : galois_connection (λ x, order_dual.to_dual (principal x)) (λ F, Inf (order_dual.of_dual F : pfilter P)) := λ x F, by { simp, refl } /-- If a poset `P` admits arbitrary `Inf`s, then `principal` and `Inf` form a Galois coinsertion. -/ def Inf_gi : galois_coinsertion (λ x, order_dual.to_dual (principal x)) (λ F, Inf (order_dual.of_dual F : pfilter P)) := { choice := λ F _, Inf (id F : pfilter P), gc := Inf_gc, u_l_le := λ s, Inf_le $ mem_principal.2 $ le_refl s, choice_eq := λ _ _, rfl } end complete_semilattice_Inf end pfilter end order
cc432f12884c33743f17fa00ca20d49524f9cea5
271e26e338b0c14544a889c31c30b39c989f2e0f
/tests/bench/rbmap.lean
737ad997bf97cc6dec1c93ccd8d34e23d489bc2b
[ "Apache-2.0" ]
permissive
dgorokho/lean4
805f99b0b60c545b64ac34ab8237a8504f89d7d4
e949a052bad59b1c7b54a82d24d516a656487d8a
refs/heads/master
1,607,061,363,851
1,578,006,086,000
1,578,006,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,891
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Coe import Init.Data.Option.Basic import Init.Data.List.BasicAux import Init.System.IO universes u v w w' inductive color | Red | Black inductive Tree | Leaf {} : Tree | Node (color : color) (lchild : Tree) (key : Nat) (val : Bool) (rchild : Tree) : Tree variables {σ : Type w} open color Nat Tree def fold (f : Nat → Bool → σ → σ) : Tree → σ → σ | Leaf, b => b | Node _ l k v r, b => fold r (f k v (fold l b)) @[inline] def balance1 : Nat → Bool → Tree → Tree → Tree | kv, vv, t, Node _ (Node Red l kx vx r₁) ky vy r₂ => Node Red (Node Black l kx vx r₁) ky vy (Node Black r₂ kv vv t) | kv, vv, t, Node _ l₁ ky vy (Node Red l₂ kx vx r) => Node Red (Node Black l₁ ky vy l₂) kx vx (Node Black r kv vv t) | kv, vv, t, Node _ l ky vy r => Node Black (Node Red l ky vy r) kv vv t | _, _, _, _ => Leaf @[inline] def balance2 : Tree → Nat → Bool → Tree → Tree | t, kv, vv, Node _ (Node Red l kx₁ vx₁ r₁) ky vy r₂ => Node Red (Node Black t kv vv l) kx₁ vx₁ (Node Black r₁ ky vy r₂) | t, kv, vv, Node _ l₁ ky vy (Node Red l₂ kx₂ vx₂ r₂) => Node Red (Node Black t kv vv l₁) ky vy (Node Black l₂ kx₂ vx₂ r₂) | t, kv, vv, Node _ l ky vy r => Node Black t kv vv (Node Red l ky vy r) | _, _, _, _ => Leaf def isRed : Tree → Bool | Node Red _ _ _ _ => true | _ => false def ins : Tree → Nat → Bool → Tree | Leaf, kx, vx => Node Red Leaf kx vx Leaf | Node Red a ky vy b, kx, vx => (if kx < ky then Node Red (ins a kx vx) ky vy b else if kx = ky then Node Red a kx vx b else Node Red a ky vy (ins b kx vx)) | Node Black a ky vy b, kx, vx => if kx < ky then (if isRed a then balance1 ky vy b (ins a kx vx) else Node Black (ins a kx vx) ky vy b) else if kx = ky then Node Black a kx vx b else if isRed b then balance2 a ky vy (ins b kx vx) else Node Black a ky vy (ins b kx vx) def setBlack : Tree → Tree | Node _ l k v r => Node Black l k v r | e => e def insert (t : Tree) (k : Nat) (v : Bool) : Tree := if isRed t then setBlack (ins t k v) else ins t k v def mkMapAux : Nat → Tree → Tree | 0, m => m | n+1, m => mkMapAux n (insert m n (n % 10 = 0)) def mkMap (n : Nat) := mkMapAux n Leaf def main (xs : List String) : IO UInt32 := let m := mkMap xs.head!.toNat; let v := fold (fun (k : Nat) (v : Bool) (r : Nat) => if v then r + 1 else r) m 0; IO.println (toString v) *> pure 0
a7cb0bc2e14c884a4705521a768437925990f857
0dc59d2b959c9b11a672f655b104d7d7d3e37660
/other_peoples_work/miller_logic_and_set.lean
dd5a9868f0cf6217ebb62bcd47e206fdfcbbb31f
[]
no_license
kbuzzard/lean4-filters
5aa17d95079ceb906622543209064151fa645e71
29f90055b7a2341c86d924954463c439bd128fb7
refs/heads/master
1,679,762,259,673
1,616,701,300,000
1,616,701,300,000
350,784,493
5
1
null
1,625,691,081,000
1,616,517,435,000
Lean
UTF-8
Lean
false
false
1,845
lean
section Logic theorem andSymm : p ∧ q → q ∧ p := λ (And.intro x y) => And.intro y x theorem andComm : p ∧ q ↔ q ∧ p := Iff.intro andSymm andSymm theorem orSymm : p ∨ q → q ∨ p | Or.inl x => Or.inr x | Or.inr x => Or.inl x theorem orComm : p ∨ q ↔ q ∨ p := Iff.intro orSymm orSymm end Logic def Set (α : Type u) : Type u := α → Prop @[reducible] def Set.mk (p : α → Prop) : Set α := p class HasMem (α : outParam $ Type u) (β : Type v) where mem : α → β → Prop infix:50 " ∈ " => HasMem.mem instance : HasMem α (Set α) where mem x s := s x syntax "{ " ident (" : " term)? " | " term " }" : term macro_rules | `({ $x : $type | $p }) => `(Set.mk (λ ($x:ident : $type) => $p)) | `({ $x | $p }) => `(Set.mk (λ ($x:ident : _) => $p)) abbrev setOf (b : β) [HasMem α β] : Set α := {x | x ∈ b} namespace Set theorem ext {s t : Set α} (h : (x : α) → x ∈ s ↔ x ∈ t) : s = t := by funext x exact propext (h x) def univ {α : Type u} : Set α := λ _ => True def subset (s t : Set α) : Prop := ∀ {x}, x ∈ s → x ∈ t def inter (s t : Set α) : Set α := {x | x ∈ s ∧ x ∈ t} def union (s t : Set α) : Set α := {x | x ∈ s ∨ x ∈ t} infixl:70 " ∩ " => inter infixl:65 " ∪ " => union infix:50 " ⊆ " => subset @[simp] theorem memUniv (a : α) : a ∈ univ := trivial @[simp] theorem memInter (x : α) (s t : Set α) : x ∈ s ∩ t ↔ x ∈ s ∧ x ∈ t := Iff.rfl @[simp] theorem memUnion (x : α) (s t : Set α) : x ∈ s ∪ t ↔ x ∈ s ∨ x ∈ t := Iff.rfl theorem interComm (s t : Set α) : s ∩ t = t ∩ s := by apply ext simp intro rw andComm exact Iff.rfl theorem unionComm (s t : Set α) : s ∪ t = t ∪ s := by apply ext simp intro rw orComm exact Iff.rfl end Set
f3517d72a5c38c1d9767ab4bdd4bfd7dd010d7be
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Meta/ExprDefEq.lean
f23c964efc287790615ce882e4e5b036fe9c26bd
[ "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
77,493
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Offset import Lean.Meta.UnificationHint import Lean.Util.OccursCheck namespace Lean.Meta /-- Return true if `b` is of the form `mk a.1 ... a.n`, and `a` is not a constructor application. If `a` and `b` are constructor applications, the method returns `false` to force `isDefEq` to use `isDefEqArgs`. For example, suppose we are trying to solve the constraint ``` Fin.mk ?n ?h =?= Fin.mk n h ``` If this method is applied, the constraints are reduced to ``` n =?= (Fin.mk ?n ?h).1 h =?= (Fin.mk ?n ?h).2 ``` The first constraint produces the assignment `?n := n`. Then, the second constraint is solved using proof irrelevance without assigning `?h`. TODO: investigate better solutions for the proof irrelevance issue. The problem above can happen is other scenarios. That is, proof irrelevance may prevent us from performing desired mvar assignments. -/ private def isDefEqEtaStruct (a b : Expr) : MetaM Bool := do matchConstCtor b.getAppFn (fun _ => return false) fun ctorVal us => do if (← useEtaStruct ctorVal.induct) then matchConstCtor a.getAppFn (fun _ => go ctorVal us) fun _ _ => return false else return false where go ctorVal us := do if ctorVal.numParams + ctorVal.numFields != b.getAppNumArgs then trace[Meta.isDefEq.eta.struct] "failed, insufficient number of arguments at{indentExpr b}" return false else if !isStructureLike (← getEnv) ctorVal.induct then trace[Meta.isDefEq.eta.struct] "failed, type is not a structure{indentExpr b}" return false else if (← isDefEq (← inferType a) (← inferType b)) then checkpointDefEq do let args := b.getAppArgs let params := args[:ctorVal.numParams].toArray for i in [ctorVal.numParams : args.size] do let j := i - ctorVal.numParams let proj ← mkProjFn ctorVal us params j a trace[Meta.isDefEq.eta.struct] "{a} =?= {b} @ [{j}], {proj} =?= {args[i]!}" unless (← isDefEq proj args[i]!) do trace[Meta.isDefEq.eta.struct] "failed, unexpect arg #{i}, projection{indentExpr proj}\nis not defeq to{indentExpr args[i]!}" return false return true else return false /-- Try to solve `a := (fun x => t) =?= b` by eta-expanding `b`. Remark: eta-reduction is not a good alternative even in a system without universe cumulativity like Lean. Example: ``` (fun x : A => f ?m) =?= f ``` The left-hand side of the constraint above it not eta-reduced because `?m` is a metavariable. -/ private def isDefEqEta (a b : Expr) : MetaM Bool := do if a.isLambda && !b.isLambda then let bType ← inferType b let bType ← whnfD bType match bType with | Expr.forallE n d _ c => let b' := mkLambda n c d (mkApp b (mkBVar 0)) checkpointDefEq <| Meta.isExprDefEqAux a b' | _ => pure false else return false /-- Support for `Lean.reduceBool` and `Lean.reduceNat` -/ def isDefEqNative (s t : Expr) : MetaM LBool := do let isDefEq (s t) : MetaM LBool := toLBoolM <| Meta.isExprDefEqAux s t let s? ← reduceNative? s let t? ← reduceNative? t match s?, t? with | some s, some t => isDefEq s t | some s, none => isDefEq s t | none, some t => isDefEq s t | none, none => pure LBool.undef /-- Support for reducing Nat basic operations. -/ def isDefEqNat (s t : Expr) : MetaM LBool := do let isDefEq (s t) : MetaM LBool := toLBoolM <| Meta.isExprDefEqAux s t if s.hasFVar || s.hasMVar || t.hasFVar || t.hasMVar then pure LBool.undef else let s? ← reduceNat? s let t? ← reduceNat? t match s?, t? with | some s, some t => isDefEq s t | some s, none => isDefEq s t | none, some t => isDefEq s t | none, none => pure LBool.undef /-- Support for constraints of the form `("..." =?= String.mk cs)` -/ def isDefEqStringLit (s t : Expr) : MetaM LBool := do let isDefEq (s t) : MetaM LBool := toLBoolM <| Meta.isExprDefEqAux s t if s.isStringLit && t.isAppOf ``String.mk then isDefEq s.toCtorIfLit t else if s.isAppOf `String.mk && t.isStringLit then isDefEq s t.toCtorIfLit else pure LBool.undef /-- Return `true` if `e` is of the form `fun (x_1 ... x_n) => ?m x_1 ... x_n)`, and `?m` is unassigned. Remark: `n` may be 0. -/ def isEtaUnassignedMVar (e : Expr) : MetaM Bool := do match e.etaExpanded? with | some (Expr.mvar mvarId) => if (← mvarId.isReadOnlyOrSyntheticOpaque) then pure false else if (← mvarId.isAssigned) then pure false else pure true | _ => pure false private def trySynthPending (e : Expr) : MetaM Bool := do let mvarId? ← getStuckMVar? e match mvarId? with | some mvarId => Meta.synthPending mvarId | none => pure false /-- Result type for `isDefEqArgsFirstPass`. -/ inductive DefEqArgsFirstPassResult where /-- Failed to establish that explicit arguments are def-eq. Remark: higher output parameters, and parameters that depend on them are postponed. -/ | failed /-- Succeeded. The array `postponedImplicit` contains the position of the implicit arguments for which def-eq has been postponed. `postponedHO` contains the higher order output parameters, and parameters that depend on them. They should be processed after the implict ones. `postponedHO` is used to handle applications involving functions that contain higher order output parameters. Example: ```lean getElem : {cont : Type u_1} → {idx : Type u_2} → {elem : Type u_3} → {dom : cont → idx → Prop} → [self : GetElem cont idx elem dom] → (xs : cont) → (i : idx) → (h : dom xs i) → elem ``` The argumengs `dom` and `h` must be processed after all implicit arguments otherwise higher-order unification problems are generated. See issue #1299, when trying to solve ``` getElem ?a ?i ?h =?= getElem a i (Fin.val_lt_of_le i ...) ``` we have to solve the constraint ``` ?dom a i.val =?= LT.lt i.val (Array.size a) ``` by solving after the instance has been synthesized, we reduce this constraint to a simple check. -/ | ok (postponedImplicit : Array Nat) (postponedHO : Array Nat) /-- First pass for `isDefEqArgs`. We unify explicit arguments, *and* easy cases Here, we say a case is easy if it is of the form ?m =?= t or t =?= ?m where `?m` is unassigned. These easy cases are not just an optimization. When `?m` is a function, by assigning it to t, we make sure a unification constraint (in the explicit part) ``` ?m t =?= f s ``` is not higher-order. We also handle the eta-expanded cases: ``` fun x₁ ... xₙ => ?m x₁ ... xₙ =?= t t =?= fun x₁ ... xₙ => ?m x₁ ... xₙ ``` This is important because type inference often produces eta-expanded terms, and without this extra case, we could introduce counter intuitive behavior. Pre: `paramInfo.size <= args₁.size = args₂.size` See `DefEqArgsFirstPassResult` for additional information. -/ private def isDefEqArgsFirstPass (paramInfo : Array ParamInfo) (args₁ args₂ : Array Expr) : MetaM DefEqArgsFirstPassResult := do let mut postponedImplicit := #[] let mut postponedHO := #[] for i in [:paramInfo.size] do let info := paramInfo[i]! let a₁ := args₁[i]! let a₂ := args₂[i]! if info.dependsOnHigherOrderOutParam || info.higherOrderOutParam then trace[Meta.isDefEq] "found messy {a₁} =?= {a₂}" postponedHO := postponedHO.push i else if info.isExplicit then unless (← Meta.isExprDefEqAux a₁ a₂) do return .failed else if (← isEtaUnassignedMVar a₁ <||> isEtaUnassignedMVar a₂) then unless (← Meta.isExprDefEqAux a₁ a₂) do return .failed else postponedImplicit := postponedImplicit.push i return .ok postponedImplicit postponedHO private partial def isDefEqArgs (f : Expr) (args₁ args₂ : Array Expr) : MetaM Bool := do unless args₁.size == args₂.size do return false let finfo ← getFunInfoNArgs f args₁.size let .ok postponedImplicit postponedHO ← isDefEqArgsFirstPass finfo.paramInfo args₁ args₂ | pure false -- finfo.paramInfo.size may be smaller than args₁.size for i in [finfo.paramInfo.size:args₁.size] do unless (← Meta.isExprDefEqAux args₁[i]! args₂[i]!) do return false for i in postponedImplicit do /- Second pass: unify implicit arguments. In the second pass, we make sure we are unfolding at least non reducible definitions (default setting). -/ let a₁ := args₁[i]! let a₂ := args₂[i]! let info := finfo.paramInfo[i]! if info.isInstImplicit then discard <| trySynthPending a₁ discard <| trySynthPending a₂ unless (← withAtLeastTransparency TransparencyMode.default <| Meta.isExprDefEqAux a₁ a₂) do return false for i in postponedHO do let a₁ := args₁[i]! let a₂ := args₂[i]! let info := finfo.paramInfo[i]! if info.isInstImplicit then unless (← withAtLeastTransparency TransparencyMode.default <| Meta.isExprDefEqAux a₁ a₂) do return false else unless (← Meta.isExprDefEqAux a₁ a₂) do return false return true /-- Check whether the types of the free variables at `fvars` are definitionally equal to the types at `ds₂`. Pre: `fvars.size == ds₂.size` This method also updates the set of local instances, and invokes the continuation `k` with the updated set. We can't use `withNewLocalInstances` because the `isDeq fvarType d₂` may use local instances. -/ @[specialize] partial def isDefEqBindingDomain (fvars : Array Expr) (ds₂ : Array Expr) (k : MetaM Bool) : MetaM Bool := let rec loop (i : Nat) := do if h : i < fvars.size then do let fvar := fvars.get ⟨i, h⟩ let fvarDecl ← getFVarLocalDecl fvar let fvarType := fvarDecl.type let d₂ := ds₂[i]! if (← Meta.isExprDefEqAux fvarType d₂) then match (← isClass? fvarType) with | some className => withNewLocalInstance className fvar <| loop (i+1) | none => loop (i+1) else pure false else k loop 0 /-- Auxiliary function for `isDefEqBinding` for handling binders `forall/fun`. It accumulates the new free variables in `fvars`, and declare them at `lctx`. We use the domain types of `e₁` to create the new free variables. We store the domain types of `e₂` at `ds₂`. -/ private partial def isDefEqBindingAux (lctx : LocalContext) (fvars : Array Expr) (e₁ e₂ : Expr) (ds₂ : Array Expr) : MetaM Bool := let process (n : Name) (d₁ d₂ b₁ b₂ : Expr) : MetaM Bool := do let d₁ := d₁.instantiateRev fvars let d₂ := d₂.instantiateRev fvars let fvarId ← mkFreshFVarId let lctx := lctx.mkLocalDecl fvarId n d₁ let fvars := fvars.push (mkFVar fvarId) isDefEqBindingAux lctx fvars b₁ b₂ (ds₂.push d₂) match e₁, e₂ with | Expr.forallE n d₁ b₁ _, Expr.forallE _ d₂ b₂ _ => process n d₁ d₂ b₁ b₂ | Expr.lam n d₁ b₁ _, Expr.lam _ d₂ b₂ _ => process n d₁ d₂ b₁ b₂ | _, _ => withReader (fun ctx => { ctx with lctx := lctx }) do isDefEqBindingDomain fvars ds₂ do Meta.isExprDefEqAux (e₁.instantiateRev fvars) (e₂.instantiateRev fvars) @[inline] private def isDefEqBinding (a b : Expr) : MetaM Bool := do let lctx ← getLCtx isDefEqBindingAux lctx #[] a b #[] private def checkTypesAndAssign (mvar : Expr) (v : Expr) : MetaM Bool := withTraceNode `Meta.isDefEq.assign.checkTypes (return m!"{exceptBoolEmoji ·} ({mvar} : {← inferType mvar}) := ({v} : {← inferType v})") do if !mvar.isMVar then trace[Meta.isDefEq.assign.checkTypes] "metavariable expected" return false else -- must check whether types are definitionally equal or not, before assigning and returning true let mvarType ← inferType mvar let vType ← inferType v if (← withTransparency TransparencyMode.default <| Meta.isExprDefEqAux mvarType vType) then mvar.mvarId!.assign v pure true else pure false /-- Auxiliary method for solving constraints of the form `?m xs := v`. It creates a lambda using `mkLambdaFVars ys v`, where `ys` is a superset of `xs`. `ys` is often equal to `xs`. It is a bigger when there are let-declaration dependencies in `xs`. For example, suppose we have `xs` of the form `#[a, c]` where ``` a : Nat b : Nat := f a c : b = a ``` In this scenario, the type of `?m` is `(x1 : Nat) -> (x2 : f x1 = x1) -> C[x1, x2]`, and type of `v` is `C[a, c]`. Note that, `?m a c` is type correct since `f a = a` is definitionally equal to the type of `c : b = a`, and the type of `?m a c` is equal to the type of `v`. Note that `fun xs => v` is the term `fun (x1 : Nat) (x2 : b = x1) => v` which has type `(x1 : Nat) -> (x2 : b = x1) -> C[x1, x2]` which is not definitionally equal to the type of `?m`, and may not even be type correct. The issue here is that we are not capturing the `let`-declarations. This method collects let-declarations `y` occurring between `xs[0]` and `xs.back` s.t. some `x` in `xs` depends on `y`. `ys` is the `xs` with these extra let-declarations included. In the example above, `ys` is `#[a, b, c]`, and `mkLambdaFVars ys v` produces `fun a => let b := f a; fun (c : b = a) => v` which has a type definitionally equal to the type of `?m`. Recall that the method `checkAssignment` ensures `v` does not contain offending `let`-declarations. This method assumes that for any `xs[i]` and `xs[j]` where `i < j`, we have that `index of xs[i]` < `index of xs[j]`. where the index is the position in the local context. -/ private partial def mkLambdaFVarsWithLetDeps (xs : Array Expr) (v : Expr) : MetaM (Option Expr) := do if not (← hasLetDeclsInBetween) then mkLambdaFVars xs v else let ys ← addLetDeps mkLambdaFVars ys v where /-- Return true if there are let-declarions between `xs[0]` and `xs[xs.size-1]`. We use it a quick-check to avoid the more expensive collection procedure. -/ hasLetDeclsInBetween : MetaM Bool := do let check (lctx : LocalContext) : Bool := Id.run do let start := lctx.getFVar! xs[0]! |>.index let stop := lctx.getFVar! xs.back |>.index for i in [start+1:stop] do match lctx.getAt? i with | some localDecl => if localDecl.isLet then return true | _ => pure () return false if xs.size <= 1 then return false else return check (← getLCtx) /-- Traverse `e` and stores in the state `NameHashSet` any let-declaration with index greater than `(← read)`. The context `Nat` is the position of `xs[0]` in the local context. -/ collectLetDeclsFrom (e : Expr) : ReaderT Nat (StateRefT FVarIdHashSet MetaM) Unit := do let rec visit (e : Expr) : MonadCacheT Expr Unit (ReaderT Nat (StateRefT FVarIdHashSet MetaM)) Unit := checkCache e fun _ => do match e with | Expr.forallE _ d b _ => visit d; visit b | Expr.lam _ d b _ => visit d; visit b | Expr.letE _ t v b _ => visit t; visit v; visit b | Expr.app f a => visit f; visit a | Expr.mdata _ b => visit b | Expr.proj _ _ b => visit b | Expr.fvar fvarId => let localDecl ← fvarId.getDecl if localDecl.isLet && localDecl.index > (← read) then modify fun s => s.insert localDecl.fvarId | _ => pure () visit (← instantiateMVars e) |>.run /-- Auxiliary definition for traversing all declarations between `xs[0]` ... `xs.back` backwards. The `Nat` argument is the current position in the local context being visited, and it is less than or equal to the position of `xs.back` in the local context. The `Nat` context `(← read)` is the position of `xs[0]` in the local context. -/ collectLetDepsAux : Nat → ReaderT Nat (StateRefT FVarIdHashSet MetaM) Unit | 0 => return () | i+1 => do if i+1 == (← read) then return () else match (← getLCtx).getAt? (i+1) with | none => collectLetDepsAux i | some localDecl => if (← get).contains localDecl.fvarId then collectLetDeclsFrom localDecl.type match localDecl.value? with | some val => collectLetDeclsFrom val | _ => pure () collectLetDepsAux i /-- Computes the set `ys`. It is a set of `FVarId`s, -/ collectLetDeps : MetaM FVarIdHashSet := do let lctx ← getLCtx let start := lctx.getFVar! xs[0]! |>.index let stop := lctx.getFVar! xs.back |>.index let s := xs.foldl (init := {}) fun s x => s.insert x.fvarId! let (_, s) ← collectLetDepsAux stop |>.run start |>.run s return s /-- Computes the array `ys` containing let-decls between `xs[0]` and `xs.back` that some `x` in `xs` depends on. -/ addLetDeps : MetaM (Array Expr) := do let lctx ← getLCtx let s ← collectLetDeps /- Convert `s` into the array `ys` -/ let start := lctx.getFVar! xs[0]! |>.index let stop := lctx.getFVar! xs.back |>.index let mut ys := #[] for i in [start:stop+1] do match lctx.getAt? i with | none => pure () | some localDecl => if s.contains localDecl.fvarId then ys := ys.push localDecl.toExpr return ys /-! Each metavariable is declared in a particular local context. We use the notation `C |- ?m : t` to denote a metavariable `?m` that was declared at the local context `C` with type `t` (see `MetavarDecl`). We also use `?m@C` as a shorthand for `C |- ?m : t` where `t` is the type of `?m`. The following method process the unification constraint ?m@C a₁ ... aₙ =?= t We say the unification constraint is a pattern IFF 1) `a₁ ... aₙ` are pairwise distinct free variables that are ​*not*​ let-variables. 2) `a₁ ... aₙ` are not in `C` 3) `t` only contains free variables in `C` and/or `{a₁, ..., aₙ}` 4) For every metavariable `?m'@C'` occurring in `t`, `C'` is a subprefix of `C` 5) `?m` does not occur in `t` Claim: we don't have to check free variable declarations. That is, if `t` contains a reference to `x : A := v`, we don't need to check `v`. Reason: The reference to `x` is a free variable, and it must be in `C` (by 1 and 3). If `x` is in `C`, then any metavariable occurring in `v` must have been defined in a strict subprefix of `C`. So, condition 4 and 5 are satisfied. If the conditions above have been satisfied, then the solution for the unification constrain is ?m := fun a₁ ... aₙ => t Now, we consider some workarounds/approximations. A1) Suppose `t` contains a reference to `x : A := v` and `x` is not in `C` (failed condition 3) (precise) solution: unfold `x` in `t`. A2) Suppose some `aᵢ` is in `C` (failed condition 2) (approximated) solution (when `config.quasiPatternApprox` is set to true) : ignore condition and also use ?m := fun a₁ ... aₙ => t Here is an example where this approximation fails: Given `C` containing `a : nat`, consider the following two constraints ?m@C a =?= a ?m@C b =?= a If we use the approximation in the first constraint, we get ?m := fun x => x when we apply this solution to the second one we get a failure. IMPORTANT: When applying this approximation we need to make sure the abstracted term `fun a₁ ... aₙ => t` is type correct. The check can only be skipped in the pattern case described above. Consider the following example. Given the local context (α : Type) (a : α) we try to solve ?m α =?= @id α a If we use the approximation above we obtain: ?m := (fun α' => @id α' a) which is a type incorrect term. `a` has type `α` but it is expected to have type `α'`. The problem occurs because the right hand side contains a free variable `a` that depends on the free variable `α` being abstracted. Note that this dependency cannot occur in patterns. We can address this by type checking the term after abstraction. This is not a significant performance bottleneck because this case doesn't happen very often in practice (262 times when compiling stdlib on Jan 2018). The second example is trickier, but it also occurs less frequently (8 times when compiling stdlib on Jan 2018, and all occurrences were at Init/Control when we define monads and auxiliary combinators for them). We considered three options for the addressing the issue on the second example: A3) `a₁ ... aₙ` are not pairwise distinct (failed condition 1). In Lean3, we would try to approximate this case using an approach similar to A2. However, this approximation complicates the code, and is never used in the Lean3 stdlib and mathlib. A4) `t` contains a metavariable `?m'@C'` where `C'` is not a subprefix of `C`. If `?m'` is assigned, we substitute. If not, we create an auxiliary metavariable with a smaller scope. Actually, we let `elimMVarDeps` at `MetavarContext.lean` to perform this step. A5) If some `aᵢ` is not a free variable, then we use first-order unification (if `config.foApprox` is set to true) ?m a_1 ... a_i a_{i+1} ... a_{i+k} =?= f b_1 ... b_k reduces to ?M a_1 ... a_i =?= f a_{i+1} =?= b_1 ... a_{i+k} =?= b_k A6) If (m =?= v) is of the form ?m a_1 ... a_n =?= ?m b_1 ... b_k then we use first-order unification (if `config.foApprox` is set to true) A7) When `foApprox`, we may use another approximation (`constApprox`) for solving constraints of the form ``` ?m s₁ ... sₙ =?= t ``` where `s₁ ... sₙ` are arbitrary terms. We solve them by assigning the constant function to `?m`. ``` ?m := fun _ ... _ => t ``` In general, this approximation may produce bad solutions, and may prevent coercions from being tried. For example, consider the term `pure (x > 0)` with inferred type `?m Prop` and expected type `IO Bool`. In this situation, the elaborator generates the unification constraint ``` ?m Prop =?= IO Bool ``` It is not a higher-order pattern, nor first-order approximation is applicable. However, constant approximation produces the bogus solution `?m := fun _ => IO Bool`, and prevents the system from using the coercion from the decidable proposition `x > 0` to `Bool`. On the other hand, the constant approximation is desirable for elaborating the term ``` let f (x : _) := pure "hello"; f () ``` with expected type `IO String`. In this example, the following unification contraint is generated. ``` ?m () String =?= IO String ``` It is not a higher-order pattern, first-order approximation reduces it to ``` ?m () =?= IO ``` which fails to be solved. However, constant approximation solves it by assigning ``` ?m := fun _ => IO ``` Note that `f`s type is `(x : ?α) -> ?m x String`. The metavariable `?m` may depend on `x`. If `constApprox` is set to true, we use constant approximation. Otherwise, we use a heuristic to decide whether we should apply it or not. The heuristic is based on observing where the constraints above come from. In the first example, the constraint `?m Prop =?= IO Bool` come from polymorphic method where `?m` is expected to be a **function** of type `Type -> Type`. In the second example, the first argument of `?m` is used to model a **potential** dependency on `x`. By using constant approximation here, we are just saying the type of `f` does **not** depend on `x`. We claim this is a reasonable approximation in practice. Moreover, it is expected by any functional programmer used to non-dependently type languages (e.g., Haskell). We distinguish the two cases above by using the field `numScopeArgs` at `MetavarDecl`. This fiels tracks how many metavariable arguments are representing dependencies. -/ def mkAuxMVar (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (numScopeArgs : Nat := 0) : MetaM Expr := do mkFreshExprMVarAt lctx localInsts type MetavarKind.natural Name.anonymous numScopeArgs namespace CheckAssignment builtin_initialize checkAssignmentExceptionId : InternalExceptionId ← registerInternalExceptionId `checkAssignment builtin_initialize outOfScopeExceptionId : InternalExceptionId ← registerInternalExceptionId `outOfScope structure State where cache : ExprStructMap Expr := {} structure Context where mvarId : MVarId mvarDecl : MetavarDecl fvars : Array Expr hasCtxLocals : Bool rhs : Expr abbrev CheckAssignmentM := ReaderT Context $ StateRefT State MetaM def throwCheckAssignmentFailure : CheckAssignmentM α := throw <| Exception.internal checkAssignmentExceptionId def throwOutOfScopeFVar : CheckAssignmentM α := throw <| Exception.internal outOfScopeExceptionId private def findCached? (e : Expr) : CheckAssignmentM (Option Expr) := do return (← get).cache.find? e private def cache (e r : Expr) : CheckAssignmentM Unit := do modify fun s => { s with cache := s.cache.insert e r } instance : MonadCache Expr Expr CheckAssignmentM where findCached? := findCached? cache := cache @[inline] private def visit (f : Expr → CheckAssignmentM Expr) (e : Expr) : CheckAssignmentM Expr := if !e.hasExprMVar && !e.hasFVar then pure e else checkCache e (fun _ => f e) private def addAssignmentInfo (msg : MessageData) : CheckAssignmentM MessageData := do let ctx ← read return m!"{msg} @ {mkMVar ctx.mvarId} {ctx.fvars} := {ctx.rhs}" @[inline] def run (x : CheckAssignmentM Expr) (mvarId : MVarId) (fvars : Array Expr) (hasCtxLocals : Bool) (v : Expr) : MetaM (Option Expr) := do let mvarDecl ← mvarId.getDecl let ctx := { mvarId := mvarId, mvarDecl := mvarDecl, fvars := fvars, hasCtxLocals := hasCtxLocals, rhs := v : Context } let x : CheckAssignmentM (Option Expr) := catchInternalIds [outOfScopeExceptionId, checkAssignmentExceptionId] (do let e ← x; return some e) (fun _ => pure none) x.run ctx |>.run' {} mutual partial def checkFVar (fvar : Expr) : CheckAssignmentM Expr := do let ctxMeta ← readThe Meta.Context let ctx ← read if ctx.mvarDecl.lctx.containsFVar fvar then pure fvar else let lctx := ctxMeta.lctx match lctx.findFVar? fvar with | some (.ldecl (value := v) ..) => visit check v | _ => if ctx.fvars.contains fvar then pure fvar else traceM `Meta.isDefEq.assign.outOfScopeFVar do addAssignmentInfo fvar throwOutOfScopeFVar partial def checkMVar (mvar : Expr) : CheckAssignmentM Expr := do let mvarId := mvar.mvarId! let ctx ← read if mvarId == ctx.mvarId then traceM `Meta.isDefEq.assign.occursCheck <| addAssignmentInfo "occurs check failed" throwCheckAssignmentFailure else match (← getExprMVarAssignment? mvarId) with | some v => check v | none => match (← mvarId.findDecl?) with | none => throwUnknownMVar mvarId | some mvarDecl => if ctx.hasCtxLocals then throwCheckAssignmentFailure -- It is not a pattern, then we fail and fall back to FO unification else if mvarDecl.lctx.isSubPrefixOf ctx.mvarDecl.lctx ctx.fvars then /- The local context of `mvar` - free variables being abstracted is a subprefix of the metavariable being assigned. We "substract" variables being abstracted because we use `elimMVarDeps` -/ pure mvar else if mvarDecl.depth != (← getMCtx).depth || mvarDecl.kind.isSyntheticOpaque then traceM `Meta.isDefEq.assign.readOnlyMVarWithBiggerLCtx <| addAssignmentInfo (mkMVar mvarId) throwCheckAssignmentFailure else let ctxMeta ← readThe Meta.Context if ctxMeta.config.ctxApprox && ctx.mvarDecl.lctx.isSubPrefixOf mvarDecl.lctx then /- Create an auxiliary metavariable with a smaller context and "checked" type. Note that `mvarType` may be different from `mvarDecl.type`. Example: `mvarType` contains a metavariable that we also need to reduce the context. We remove from `ctx.mvarDecl.lctx` any variable that is not in `mvarDecl.lctx` or in `ctx.fvars`. We don't need to remove the ones in `ctx.fvars` because `elimMVarDeps` will take care of them. First, we collect `toErase` the variables that need to be erased. Notat that if a variable is `ctx.fvars`, but it depends on variable at `toErase`, we must also erase it. -/ let toErase ← mvarDecl.lctx.foldlM (init := #[]) fun toErase localDecl => do if ctx.mvarDecl.lctx.contains localDecl.fvarId then return toErase else if ctx.fvars.any fun fvar => fvar.fvarId! == localDecl.fvarId then if (← findLocalDeclDependsOn localDecl fun fvarId => toErase.contains fvarId) then -- localDecl depends on a variable that will be erased. So, we must add it to `toErase` too return toErase.push localDecl.fvarId else return toErase else return toErase.push localDecl.fvarId let lctx := toErase.foldl (init := mvarDecl.lctx) fun lctx toEraseFVar => lctx.erase toEraseFVar /- Compute new set of local instances. -/ let localInsts := mvarDecl.localInstances.filter fun localInst => toErase.contains localInst.fvar.fvarId! let mvarType ← check mvarDecl.type let newMVar ← mkAuxMVar lctx localInsts mvarType mvarDecl.numScopeArgs mvarId.assign newMVar pure newMVar else traceM `Meta.isDefEq.assign.readOnlyMVarWithBiggerLCtx <| addAssignmentInfo (mkMVar mvarId) throwCheckAssignmentFailure /-- Auxiliary function used to "fix" subterms of the form `?m x_1 ... x_n` where `x_i`s are free variables, and one of them is out-of-scope. See `Expr.app` case at `check`. If `ctxApprox` is true, then we solve this case by creating a fresh metavariable ?n with the correct scope, an assigning `?m := fun _ ... _ => ?n` -/ partial def assignToConstFun (mvar : Expr) (numArgs : Nat) (newMVar : Expr) : MetaM Bool := do let mvarType ← inferType mvar forallBoundedTelescope mvarType numArgs fun xs _ => do if xs.size != numArgs then pure false else let some v ← mkLambdaFVarsWithLetDeps xs newMVar | return false match (← checkAssignmentAux mvar.mvarId! #[] false v) with | some v => checkTypesAndAssign mvar v | none => return false -- See checkAssignment partial def checkAssignmentAux (mvarId : MVarId) (fvars : Array Expr) (hasCtxLocals : Bool) (v : Expr) : MetaM (Option Expr) := do run (check v) mvarId fvars hasCtxLocals v partial def checkApp (e : Expr) : CheckAssignmentM Expr := e.withApp fun f args => do let ctxMeta ← readThe Meta.Context if f.isMVar && ctxMeta.config.ctxApprox && args.all Expr.isFVar then let f ← visit checkMVar f catchInternalId outOfScopeExceptionId (do let args ← args.mapM (visit check) return mkAppN f args) (fun ex => do if !f.isMVar then throw ex else if (← f.mvarId!.isDelayedAssigned) then throw ex else let eType ← inferType e let mvarType ← check eType /- Create an auxiliary metavariable with a smaller context and "checked" type, assign `?f := fun _ => ?newMVar` Note that `mvarType` may be different from `eType`. -/ let ctx ← read let newMVar ← mkAuxMVar ctx.mvarDecl.lctx ctx.mvarDecl.localInstances mvarType if (← assignToConstFun f args.size newMVar) then pure newMVar else throw ex) else let f ← visit check f let args ← args.mapM (visit check) return mkAppN f args partial def check (e : Expr) : CheckAssignmentM Expr := do match e with | Expr.mdata _ b => return e.updateMData! (← visit check b) | Expr.proj _ _ s => return e.updateProj! (← visit check s) | Expr.lam _ d b _ => return e.updateLambdaE! (← visit check d) (← visit check b) | Expr.forallE _ d b _ => return e.updateForallE! (← visit check d) (← visit check b) | Expr.letE _ t v b _ => return e.updateLet! (← visit check t) (← visit check v) (← visit check b) | Expr.bvar .. => return e | Expr.sort .. => return e | Expr.const .. => return e | Expr.lit .. => return e | Expr.fvar .. => visit checkFVar e | Expr.mvar .. => visit checkMVar e | Expr.app .. => checkApp e -- TODO: investigate whether the following feature is too expensive or not /- catchInternalIds [checkAssignmentExceptionId, outOfScopeExceptionId] (checkApp e) fun ex => do let e' ← whnfR e if e != e' then check e' else throw ex -/ end end CheckAssignment namespace CheckAssignmentQuick partial def check (hasCtxLocals : Bool) (mctx : MetavarContext) (lctx : LocalContext) (mvarDecl : MetavarDecl) (mvarId : MVarId) (fvars : Array Expr) (e : Expr) : Bool := let rec visit (e : Expr) : Bool := if !e.hasExprMVar && !e.hasFVar then true else match e with | Expr.mdata _ b => visit b | Expr.proj _ _ s => visit s | Expr.app f a => visit f && visit a | Expr.lam _ d b _ => visit d && visit b | Expr.forallE _ d b _ => visit d && visit b | Expr.letE _ t v b _ => visit t && visit v && visit b | Expr.bvar .. => true | Expr.sort .. => true | Expr.const .. => true | Expr.lit .. => true | Expr.fvar fvarId .. => if mvarDecl.lctx.contains fvarId then true else match lctx.find? fvarId with | some (LocalDecl.ldecl ..) => false -- need expensive CheckAssignment.check | _ => if fvars.any fun x => x.fvarId! == fvarId then true else false -- We could throw an exception here, but we would have to use ExceptM. So, we let CheckAssignment.check do it | Expr.mvar mvarId' => match mctx.getExprAssignmentCore? mvarId' with | some _ => false -- use CheckAssignment.check to instantiate | none => if mvarId' == mvarId then false -- occurs check failed, use CheckAssignment.check to throw exception else match mctx.findDecl? mvarId' with | none => false | some mvarDecl' => if hasCtxLocals then false -- use CheckAssignment.check else if mvarDecl'.lctx.isSubPrefixOf mvarDecl.lctx fvars then true else false -- use CheckAssignment.check visit e end CheckAssignmentQuick /-- Auxiliary function for handling constraints of the form `?m a₁ ... aₙ =?= v`. It will check whether we can perform the assignment ``` ?m := fun fvars => v ``` The result is `none` if the assignment can't be performed. The result is `some newV` where `newV` is a possibly updated `v`. This method may need to unfold let-declarations. -/ def checkAssignment (mvarId : MVarId) (fvars : Array Expr) (v : Expr) : MetaM (Option Expr) := do /- Check whether `mvarId` occurs in the type of `fvars` or not. If it does, return `none` to prevent us from creating the cyclic assignment `?m := fun fvars => v` -/ for fvar in fvars do unless (← occursCheck mvarId (← inferType fvar)) do return none if !v.hasExprMVar && !v.hasFVar then pure (some v) else let mvarDecl ← mvarId.getDecl let hasCtxLocals := fvars.any fun fvar => mvarDecl.lctx.containsFVar fvar let ctx ← read let mctx ← getMCtx if CheckAssignmentQuick.check hasCtxLocals mctx ctx.lctx mvarDecl mvarId fvars v then pure (some v) else let v ← instantiateMVars v CheckAssignment.checkAssignmentAux mvarId fvars hasCtxLocals v private def processAssignmentFOApproxAux (mvar : Expr) (args : Array Expr) (v : Expr) : MetaM Bool := match v with | .mdata _ e => processAssignmentFOApproxAux mvar args e | Expr.app f a => if args.isEmpty then pure false else Meta.isExprDefEqAux args.back a <&&> Meta.isExprDefEqAux (mkAppRange mvar 0 (args.size - 1) args) f | _ => pure false /-- Auxiliary method for applying first-order unification. It is an approximation. Remark: this method is trying to solve the unification constraint: ?m a₁ ... aₙ =?= v It is uses processAssignmentFOApproxAux, if it fails, it tries to unfold `v`. We have added support for unfolding here because we want to be able to solve unification problems such as ?m Unit =?= ITactic where `ITactic` is defined as def ITactic := Tactic Unit -/ private partial def processAssignmentFOApprox (mvar : Expr) (args : Array Expr) (v : Expr) : MetaM Bool := let rec loop (v : Expr) := do let cfg ← getConfig if !cfg.foApprox then pure false else trace[Meta.isDefEq.foApprox] "{mvar} {args} := {v}" let v := v.headBeta if (← checkpointDefEq <| processAssignmentFOApproxAux mvar args v) then pure true else match (← unfoldDefinition? v) with | none => pure false | some v => loop v loop v private partial def simpAssignmentArgAux (e : Expr) : MetaM Expr := do match e with | .mdata _ e => simpAssignmentArgAux e | .fvar fvarId => let some value ← fvarId.getValue? | return e simpAssignmentArgAux value | _ => return e /-- Auxiliary procedure for processing `?m a₁ ... aₙ =?= v`. We apply it to each `aᵢ`. It instantiates assigned metavariables if `aᵢ` is of the form `f[?n] b₁ ... bₘ`, and then removes metadata, and zeta-expand let-decls. -/ private def simpAssignmentArg (arg : Expr) : MetaM Expr := do let arg ← if arg.getAppFn.hasExprMVar then instantiateMVars arg else pure arg simpAssignmentArgAux arg /-- Assign `mvar := fun a_1 ... a_{numArgs} => v`. We use it at `processConstApprox` and `isDefEqMVarSelf` -/ private def assignConst (mvar : Expr) (numArgs : Nat) (v : Expr) : MetaM Bool := do let mvarDecl ← mvar.mvarId!.getDecl forallBoundedTelescope mvarDecl.type numArgs fun xs _ => do if xs.size != numArgs then pure false else let some v ← mkLambdaFVarsWithLetDeps xs v | pure false match (← checkAssignment mvar.mvarId! #[] v) with | none => pure false | some v => trace[Meta.isDefEq.constApprox] "{mvar} := {v}" checkTypesAndAssign mvar v /-- Auxiliary procedure for solving `?m args =?= v` when `args[:patternVarPrefix]` contains only pairwise distinct free variables. Let `args[:patternVarPrefix] = #[a₁, ..., aₙ]`, and `args[patternVarPrefix:] = #[b₁, ..., bᵢ]`, this procedure first reduces the constraint to ``` ?m a₁ ... aₙ =?= fun x₁ ... xᵢ => v ``` where the left-hand-side is a constant function. Then, it tries to find the longest prefix `#[a₁, ..., aⱼ]` of `#[a₁, ..., aₙ]` such that the following assignment is valid. ``` ?m := fun y₁ ... y‌ⱼ => (fun y_{j+1} ... yₙ x₁ ... xᵢ => v)[a₁/y₁, .., aⱼ/yⱼ] ``` That is, after the longest prefix is found, we solve the contraint as the lhs was a pattern. See the definition of "pattern" above. -/ private partial def processConstApprox (mvar : Expr) (args : Array Expr) (patternVarPrefix : Nat) (v : Expr) : MetaM Bool := do trace[Meta.isDefEq.constApprox] "{mvar} {args} := {v}" let rec defaultCase : MetaM Bool := assignConst mvar args.size v let cfg ← getConfig let mvarId := mvar.mvarId! let mvarDecl ← mvarId.getDecl let numArgs := args.size if mvarDecl.numScopeArgs != numArgs && !cfg.constApprox then return false else if patternVarPrefix == 0 then defaultCase else let argsPrefix : Array Expr := args[:patternVarPrefix] let type ← instantiateForall mvarDecl.type argsPrefix let suffixSize := numArgs - argsPrefix.size forallBoundedTelescope type suffixSize fun xs _ => do if xs.size != suffixSize then defaultCase else let some v ← mkLambdaFVarsWithLetDeps xs v | defaultCase let rec go (argsPrefix : Array Expr) (v : Expr) : MetaM Bool := do trace[Meta.isDefEq] "processConstApprox.go {mvar} {argsPrefix} := {v}" let rec cont : MetaM Bool := do if argsPrefix.isEmpty then defaultCase else let some v ← mkLambdaFVarsWithLetDeps #[argsPrefix.back] v | defaultCase go argsPrefix.pop v match (← checkAssignment mvarId argsPrefix v) with | none => cont | some vNew => let some vNew ← mkLambdaFVarsWithLetDeps argsPrefix vNew | cont if argsPrefix.any (fun arg => mvarDecl.lctx.containsFVar arg) then /- We need to type check `vNew` because abstraction using `mkLambdaFVars` may have produced a type incorrect term. See discussion at A2 -/ (isTypeCorrect vNew <&&> checkTypesAndAssign mvar vNew) <||> cont else checkTypesAndAssign mvar vNew <||> cont go argsPrefix v /-- Tries to solve `?m a₁ ... aₙ =?= v` by assigning `?m`. It assumes `?m` is unassigned. -/ private partial def processAssignment (mvarApp : Expr) (v : Expr) : MetaM Bool := withTraceNode `Meta.isDefEq.assign (return m!"{exceptBoolEmoji ·} {mvarApp} := {v}") do let mvar := mvarApp.getAppFn let mvarDecl ← mvar.mvarId!.getDecl let rec process (i : Nat) (args : Array Expr) (v : Expr) := do let cfg ← getConfig let useFOApprox (args : Array Expr) : MetaM Bool := processAssignmentFOApprox mvar args v <||> processConstApprox mvar args i v if h : i < args.size then let arg := args.get ⟨i, h⟩ let arg ← simpAssignmentArg arg let args := args.set ⟨i, h⟩ arg match arg with | Expr.fvar fvarId => if args[0:i].any fun prevArg => prevArg == arg then useFOApprox args else if mvarDecl.lctx.contains fvarId && !cfg.quasiPatternApprox then useFOApprox args else process (i+1) args v | _ => useFOApprox args else let v ← instantiateMVars v -- enforce A4 if v.getAppFn == mvar then -- using A6 useFOApprox args else let mvarId := mvar.mvarId! match (← checkAssignment mvarId args v) with | none => useFOApprox args | some v => do trace[Meta.isDefEq.assign.beforeMkLambda] "{mvar} {args} := {v}" let some v ← mkLambdaFVarsWithLetDeps args v | return false if args.any (fun arg => mvarDecl.lctx.containsFVar arg) then /- We need to type check `v` because abstraction using `mkLambdaFVars` may have produced a type incorrect term. See discussion at A2 -/ if (← isTypeCorrect v) then checkTypesAndAssign mvar v else trace[Meta.isDefEq.assign.typeError] "{mvar} := {v}" useFOApprox args else checkTypesAndAssign mvar v process 0 mvarApp.getAppArgs v /-- Similar to processAssignment, but if it fails, compute v's whnf and try again. This helps to solve constraints such as `?m =?= { α := ?m, ... }.α` Note this is not perfect solution since we still fail occurs check for constraints such as ```lean ?m =?= List { α := ?m, β := Nat }.β ``` -/ private def processAssignment' (mvarApp : Expr) (v : Expr) : MetaM Bool := do if (← processAssignment mvarApp v) then return true else let vNew ← whnf v if vNew != v then if mvarApp == vNew then return true else processAssignment mvarApp vNew else return false private def isDeltaCandidate? (t : Expr) : MetaM (Option ConstantInfo) := do match t.getAppFn with | Expr.const c _ => match (← getConst? c) with | r@(some info) => if info.hasValue then return r else return none | _ => return none | _ => pure none /-- Auxiliary method for isDefEqDelta -/ private def isListLevelDefEq (us vs : List Level) : MetaM LBool := toLBoolM <| isListLevelDefEqAux us vs /-- Auxiliary method for isDefEqDelta -/ private def isDefEqLeft (fn : Name) (t s : Expr) : MetaM LBool := do trace[Meta.isDefEq.delta.unfoldLeft] fn toLBoolM <| Meta.isExprDefEqAux t s /-- Auxiliary method for isDefEqDelta -/ private def isDefEqRight (fn : Name) (t s : Expr) : MetaM LBool := do trace[Meta.isDefEq.delta.unfoldRight] fn toLBoolM <| Meta.isExprDefEqAux t s /-- Auxiliary method for isDefEqDelta -/ private def isDefEqLeftRight (fn : Name) (t s : Expr) : MetaM LBool := do trace[Meta.isDefEq.delta.unfoldLeftRight] fn toLBoolM <| Meta.isExprDefEqAux t s /-- Try to solve `f a₁ ... aₙ =?= f b₁ ... bₙ` by solving `a₁ =?= b₁, ..., aₙ =?= bₙ`. Auxiliary method for isDefEqDelta -/ private def tryHeuristic (t s : Expr) : MetaM Bool := do let mut t := t let mut s := s let tFn := t.getAppFn let sFn := s.getAppFn let info ← getConstInfo tFn.constName! /- We only use the heuristic when `f` is a regular definition or an auxiliary `match` application. That is, it is not marked an abbreviation (e.g., a user-facing projection) or as opaque (e.g., proof). We check whether terms contain metavariables to make sure we can solve constraints such as `S.proj ?x =?= S.proj t` without performing delta-reduction. That is, we are assuming the heuristic implemented by this method is seldom effective when `t` and `s` do not have metavariables, are not structurally equal, and `f` is an abbreviation. On the other hand, by unfolding `f`, we often produce smaller terms. Recall that auxiliary `match` definitions are marked as abbreviations, but we must use the heuristic on them since they will not be unfolded when smartUnfolding is turned on. The abbreviation annotation in this case is used to help the kernel type checker. -/ unless info.hints.isRegular || isMatcherCore (← getEnv) tFn.constName! do unless t.hasExprMVar || s.hasExprMVar do return false withTraceNode `Meta.isDefEq.delta (return m!"{exceptBoolEmoji ·} {t} =?= {s}") do /- We process arguments before universe levels to reduce a source of brittleness in the TC procedure. In the TC procedure, we can solve problems containing metavariables. If the TC procedure tries to assign one of these metavariables, it interrupts the search using a "stuck" exception. The elaborator catches it, and "interprets" it as "we should try again later". Now suppose we have a TC problem, and there are two "local" candidate instances we can try: "bad" and "good". The "bad" candidate is stuck because of a universe metavariable in the TC problem. If we try "bad" first, the TC procedure is interrupted. Moreover, if we have ignored the exception, "bad" would fail anyway trying to assign two different free variables `α =?= β`. Example: `Preorder.{?u} α =?= Preorder.{?v} β`, where `?u` and `?v` are universe metavariables that were not created by the TC procedure. The key issue here is that we have an `isDefEq t s` invocation that is interrupted by the "stuck" exception, but it would have failed anyway if we had continued processing it. By solving the arguments first, we make the example above fail without throwing the "stuck" exception. TODO: instead of throwing an exception as soon as we get stuck, we should just set a flag. Then the entry-point for `isDefEq` checks the flag before returning `true`. -/ checkpointDefEq do isDefEqArgs tFn t.getAppArgs s.getAppArgs <&&> isListLevelDefEqAux tFn.constLevels! sFn.constLevels! /-- Auxiliary method for isDefEqDelta -/ private abbrev unfold (e : Expr) (failK : MetaM α) (successK : Expr → MetaM α) : MetaM α := do match (← unfoldDefinition? e) with | some e => successK e | none => failK /-- Auxiliary method for isDefEqDelta -/ private def unfoldBothDefEq (fn : Name) (t s : Expr) : MetaM LBool := do match t, s with | Expr.const _ ls₁, Expr.const _ ls₂ => isListLevelDefEq ls₁ ls₂ | Expr.app _ _, Expr.app _ _ => if (← tryHeuristic t s) then pure LBool.true else unfold t (unfold s (pure LBool.undef) (fun s => isDefEqRight fn t s)) (fun t => unfold s (isDefEqLeft fn t s) (fun s => isDefEqLeftRight fn t s)) | _, _ => pure LBool.false private def sameHeadSymbol (t s : Expr) : Bool := match t.getAppFn, s.getAppFn with | Expr.const c₁ _, Expr.const c₂ _ => c₁ == c₂ | _, _ => false /-- - If headSymbol (unfold t) == headSymbol s, then unfold t - If headSymbol (unfold s) == headSymbol t, then unfold s - Otherwise unfold t and s if possible. Auxiliary method for isDefEqDelta -/ private def unfoldComparingHeadsDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := unfold t (unfold s (pure LBool.undef) -- `t` and `s` failed to be unfolded (fun s => isDefEqRight sInfo.name t s)) (fun tNew => if sameHeadSymbol tNew s then isDefEqLeft tInfo.name tNew s else unfold s (isDefEqLeft tInfo.name tNew s) (fun sNew => if sameHeadSymbol t sNew then isDefEqRight sInfo.name t sNew else isDefEqLeftRight tInfo.name tNew sNew)) /-- If `t` and `s` do not contain metavariables, then use kernel definitional equality heuristics. Otherwise, use `unfoldComparingHeadsDefEq`. Auxiliary method for isDefEqDelta -/ private def unfoldDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := if !t.hasExprMVar && !s.hasExprMVar then /- If `t` and `s` do not contain metavariables, we simulate strategy used in the kernel. -/ if tInfo.hints.lt sInfo.hints then unfold t (unfoldComparingHeadsDefEq tInfo sInfo t s) fun t => isDefEqLeft tInfo.name t s else if sInfo.hints.lt tInfo.hints then unfold s (unfoldComparingHeadsDefEq tInfo sInfo t s) fun s => isDefEqRight sInfo.name t s else unfoldComparingHeadsDefEq tInfo sInfo t s else unfoldComparingHeadsDefEq tInfo sInfo t s /-- When `TransparencyMode` is set to `default` or `all`. If `t` is reducible and `s` is not ==> `isDefEqLeft (unfold t) s` If `s` is reducible and `t` is not ==> `isDefEqRight t (unfold s)` Otherwise, use `unfoldDefEq` Auxiliary method for isDefEqDelta -/ private def unfoldReducibeDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := do if (← shouldReduceReducibleOnly) then unfoldDefEq tInfo sInfo t s else let tReducible ← isReducible tInfo.name let sReducible ← isReducible sInfo.name if tReducible && !sReducible then unfold t (unfoldDefEq tInfo sInfo t s) fun t => isDefEqLeft tInfo.name t s else if !tReducible && sReducible then unfold s (unfoldDefEq tInfo sInfo t s) fun s => isDefEqRight sInfo.name t s else unfoldDefEq tInfo sInfo t s /-- This is an auxiliary method for isDefEqDelta. If `t` is a (non-class) projection function application and `s` is not ==> `isDefEqRight t (unfold s)` If `s` is a (non-class) projection function application and `t` is not ==> `isDefEqRight (unfold t) s` Otherwise, use `unfoldReducibeDefEq` One motivation for the heuristic above is unification problems such as ``` id (?m.1) =?= (a, b).1 ``` We want to reduce the lhs instead of the rhs, and eventually assign `?m := (a, b)`. Another motivation for the heuristic above is unification problems such as ``` List.length (a :: as) =?= HAdd.hAdd (List.length as) 1 ``` However, for class projections, we also unpack them and check whether the result function is the one on the other side. This is relevant for unification problems such as ``` Foo.pow x 256 =?= Pow.pow x 256 ``` where the the `Pow` instance is wrapping `Foo.pow` See issue #1419 for the complete example. -/ private partial def unfoldNonProjFnDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := do let tProjInfo? ← getProjectionFnInfo? tInfo.name let sProjInfo? ← getProjectionFnInfo? sInfo.name if let some tNew ← packedInstanceOf? tProjInfo? t sInfo.name then isDefEqLeft tInfo.name tNew s else if let some sNew ← packedInstanceOf? sProjInfo? s tInfo.name then isDefEqRight sInfo.name t sNew else match tProjInfo?, sProjInfo? with | some _, none => unfold s (unfoldDefEq tInfo sInfo t s) fun s => isDefEqRight sInfo.name t s | none, some _ => unfold t (unfoldDefEq tInfo sInfo t s) fun t => isDefEqLeft tInfo.name t s | _, _ => unfoldReducibeDefEq tInfo sInfo t s where packedInstanceOf? (projInfo? : Option ProjectionFunctionInfo) (e : Expr) (declName : Name) : MetaM (Option Expr) := do let some { fromClass := true, .. } := projInfo? | return none -- It is not a class projection let some e ← unfoldDefinition? e | return none let e ← whnfCore e if e.isAppOf declName then return some e let .const name _ := e.getAppFn | return none -- Keep going if new `e` is also a class projection packedInstanceOf? (← getProjectionFnInfo? name) e declName /-- isDefEq by lazy delta reduction. This method implements many different heuristics: 1- If only `t` can be unfolded => then unfold `t` and continue 2- If only `s` can be unfolded => then unfold `s` and continue 3- If `t` and `s` can be unfolded and they have the same head symbol, then a) First try to solve unification by unifying arguments. b) If it fails, unfold both and continue. Implemented by `unfoldBothDefEq` 4- If `t` is a projection function application and `s` is not => then unfold `s` and continue. 5- If `s` is a projection function application and `t` is not => then unfold `t` and continue. Remark: 4&5 are implemented by `unfoldNonProjFnDefEq` 6- If `t` is reducible and `s` is not => then unfold `t` and continue. 7- If `s` is reducible and `t` is not => then unfold `s` and continue Remark: 6&7 are implemented by `unfoldReducibeDefEq` 8- If `t` and `s` do not contain metavariables, then use heuristic used in the Kernel. Implemented by `unfoldDefEq` 9- If `headSymbol (unfold t) == headSymbol s`, then unfold t and continue. 10- If `headSymbol (unfold s) == headSymbol t`, then unfold s 11- Otherwise, unfold `t` and `s` and continue. Remark: 9&10&11 are implemented by `unfoldComparingHeadsDefEq` -/ private def isDefEqDelta (t s : Expr) : MetaM LBool := do let tInfo? ← isDeltaCandidate? t let sInfo? ← isDeltaCandidate? s match tInfo?, sInfo? with | none, none => pure LBool.undef | some tInfo, none => unfold t (pure LBool.undef) fun t => isDefEqLeft tInfo.name t s | none, some sInfo => unfold s (pure LBool.undef) fun s => isDefEqRight sInfo.name t s | some tInfo, some sInfo => if tInfo.name == sInfo.name then unfoldBothDefEq tInfo.name t s else unfoldNonProjFnDefEq tInfo sInfo t s private def isAssigned : Expr → MetaM Bool | Expr.mvar mvarId => mvarId.isAssigned | _ => pure false private def expandDelayedAssigned? (t : Expr) : MetaM (Option Expr) := do let tFn := t.getAppFn if !tFn.isMVar then return none let some { fvars, mvarIdPending } ← getDelayedMVarAssignment? tFn.mvarId! | return none let tNew ← instantiateMVars t if tNew != t then return some tNew /- If `assignSyntheticOpaque` is true, we must follow the delayed assignment. Recall a delayed assignment `mvarId [xs] := mvarIdPending` is morally an assingment `mvarId := fun xs => mvarIdPending` where `xs` are free variables in the scope of `mvarIdPending`, but not in the scope of `mvarId`. We can only perform the abstraction when `mvarIdPending` has been fully synthesized. That is, `instantiateMVars (mkMVar mvarIdPending)` does not contain any expression metavariables. Here we just consume `fvar.size` arguments. That is, if `t` is of the form `mvarId as bs` where `as.size == fvars.size`, we return `mvarIdPending bs`. TODO: improve this transformation. Here is a possible improvement. Assume `t` is of the form `?m as` where `as` represent the arguments, and we are trying to solve `?m as =?= s[as]` where `s[as]` represents a term containing occurrences of `as`. We could try to compute the solution as usual `?m := fun ys => s[as/ys]` We also have the delayed assignment `?m [xs] := ?n`, where `xs` are variables in the scope of `?n`, and this delayed assignment is morally `?m := fun xs => ?n`. Thus, we can reduce `?m as =?= s[as]` to `?n =?= s[as/xs]`, and solve it using `?n`'s local context. This is more precise than simplying droping the arguments `as`. -/ unless (← getConfig).assignSyntheticOpaque do return none let tArgs := t.getAppArgs if tArgs.size < fvars.size then return none return some (mkAppRange (mkMVar mvarIdPending) fvars.size tArgs.size tArgs) private def isAssignable : Expr → MetaM Bool | Expr.mvar mvarId => do let b ← mvarId.isReadOnlyOrSyntheticOpaque; pure (!b) | _ => pure false private def etaEq (t s : Expr) : Bool := match t.etaExpanded? with | some t => t == s | none => false /-- Helper method for implementing `isDefEqProofIrrel`. Execute `k` with a transparency setting that is at least as strong as `.default`. This is important for modules that use the `.reducible` setting (e.g., `simp`, `rw`, etc). We added this feature to address issue #1302. ```lean @[simp] theorem get_cons_zero {as : List α} : (a :: as).get ⟨0, Nat.zero_lt_succ _⟩ = a := rfl example (a b c : α) : [a, b, c].get ⟨0, by simp⟩ = a := by simp ``` In the example above `simp` fails to use `get_cons_zero` because it fails to establish that the proof objects are definitionally equal using proof irrelevance. In this example, the propositions are ```lean 0 < Nat.succ (List.length [b, c]) =?= 0 < Nat.succ (Nat.succ (Nat.succ 0)) ``` So, unless we can unfold `List.length`, it fails. Remark: if this becomes a performance bottleneck, we should add a flag to control when it is used. Then, we can enable the flag only when applying `simp` and `rw` theorems. -/ private def withProofIrrelTransparency (k : MetaM α) : MetaM α := withAtLeastTransparency .default k private def isDefEqProofIrrel (t s : Expr) : MetaM LBool := do if (← getConfig).proofIrrelevance then match (← isProofQuick t) with | LBool.false => pure LBool.undef | LBool.true => let tType ← inferType t let sType ← inferType s toLBoolM <| withProofIrrelTransparency <| Meta.isExprDefEqAux tType sType | LBool.undef => let tType ← inferType t if (← isProp tType) then let sType ← inferType s toLBoolM <| withProofIrrelTransparency <| Meta.isExprDefEqAux tType sType else pure LBool.undef else pure LBool.undef /-- Try to solve constraint of the form `?m args₁ =?= ?m args₂`. - First try to unify `args₁` and `args₂`, and return true if successful - Otherwise, try to assign `?m` to a constant function of the form `fun x_1 ... x_n => ?n` where `?n` is a fresh metavariable. See `assignConst`. -/ private def isDefEqMVarSelf (mvar : Expr) (args₁ args₂ : Array Expr) : MetaM Bool := do if args₁.size != args₂.size then pure false else if (← isDefEqArgs mvar args₁ args₂) then pure true else if !(← isAssignable mvar) then pure false else let cfg ← getConfig let mvarId := mvar.mvarId! let mvarDecl ← mvarId.getDecl if mvarDecl.numScopeArgs == args₁.size || cfg.constApprox then let type ← inferType (mkAppN mvar args₁) let auxMVar ← mkAuxMVar mvarDecl.lctx mvarDecl.localInstances type assignConst mvar args₁.size auxMVar else pure false /-- Remove unnecessary let-decls -/ private def consumeLet : Expr → Expr | e@(Expr.letE _ _ _ b _) => if b.hasLooseBVars then e else consumeLet b | e => e mutual private partial def isDefEqQuick (t s : Expr) : MetaM LBool := let t := consumeLet t let s := consumeLet s match t, s with | .lit l₁, .lit l₂ => return (l₁ == l₂).toLBool | .sort u, .sort v => toLBoolM <| isLevelDefEqAux u v | .lam .., .lam .. => if t == s then pure LBool.true else toLBoolM <| isDefEqBinding t s | .forallE .., .forallE .. => if t == s then pure LBool.true else toLBoolM <| isDefEqBinding t s -- | Expr.mdata _ t _, s => isDefEqQuick t s -- | t, Expr.mdata _ s _ => isDefEqQuick t s | .fvar fvarId₁, .fvar fvarId₂ => do if (← fvarId₁.isLetVar <||> fvarId₂.isLetVar) then return LBool.undef else if fvarId₁ == fvarId₂ then return LBool.true else isDefEqProofIrrel t s | t, s => isDefEqQuickOther t s private partial def isDefEqQuickOther (t s : Expr) : MetaM LBool := do /- We used to eagerly consume all metadata (see commented lines at `isDefEqQuick`), but it was unnecessarily removing helpful annotations for the pretty-printer. For example, consider the following example. ``` constant p : Nat → Prop constant q : Nat → Prop theorem p_of_q : q x → p x := sorry theorem pletfun : p (let_fun x := 0; x + 1) := by -- ⊢ p (let_fun x := 0; x + 1) apply p_of_q -- If we eagerly consume all metadata, the let_fun annotation is lost during `isDefEq` -- ⊢ q ((fun x => x + 1) 0) sorry ``` However, pattern annotations (`inaccessible?` and `patternWithRef?`) must be consumed. The frontend relies on the fact that is must not be propagated by `isDefEq`. Thus, we consume it here. This is a bit hackish since it is very adhoc. We might other annotations in the future that we should not preserve. Perhaps, we should mark the annotation we do want to preserve ones (e.g., hints for the pretty printer), and consume all other -/ if let some t := patternAnnotation? t then isDefEqQuick t s else if let some s := patternAnnotation? s then isDefEqQuick t s else if t == s then return LBool.true else if etaEq t s || etaEq s t then return LBool.true -- t =?= (fun xs => t xs) else let tFn := t.getAppFn let sFn := s.getAppFn if !tFn.isMVar && !sFn.isMVar then return LBool.undef else if (← isAssigned tFn) then let t ← instantiateMVars t isDefEqQuick t s else if (← isAssigned sFn) then let s ← instantiateMVars s isDefEqQuick t s else if let some t ← expandDelayedAssigned? t then isDefEqQuick t s else if let some s ← expandDelayedAssigned? s then isDefEqQuick t s /- Remark: we do not eagerly synthesize synthetic metavariables when the constraint is not stuck. Reason: we may fail to solve a constraint of the form `?x =?= A` when the synthesized instance is not definitionally equal to `A`. We left the code here as a remainder of this issue. -/ -- else if (← isSynthetic tFn <&&> trySynthPending tFn) then -- let t ← instantiateMVars t -- isDefEqQuick t s -- else if (← isSynthetic sFn <&&> trySynthPending sFn) then -- let s ← instantiateMVars s -- isDefEqQuick t s else if tFn.isMVar && sFn.isMVar && tFn == sFn then Bool.toLBool <$> isDefEqMVarSelf tFn t.getAppArgs s.getAppArgs else let tAssign? ← isAssignable tFn let sAssign? ← isAssignable sFn let assignableMsg (b : Bool) := if b then "[assignable]" else "[nonassignable]" trace[Meta.isDefEq] "{t} {assignableMsg tAssign?} =?= {s} {assignableMsg sAssign?}" if tAssign? && !sAssign? then toLBoolM <| processAssignment' t s else if !tAssign? && sAssign? then toLBoolM <| processAssignment' s t else if !tAssign? && !sAssign? then /- Trying to unify `?m ... =?= ?n ...` where both `?m` and `?n` cannot be assigned. This can happen when both of them are `syntheticOpaque` (e.g., metavars associated with tactics), or a metavariables from previous levels. If their types are propositions and are defeq, we can solve the constraint by proof irrelevance. This test is important for fixing a performance problem exposed by test `isDefEqPerfIssue.lean`. Without the proof irrelevance check, this example timeouts. Recall that: 1- The elaborator has a pending list of things to do: Tactics, TC, etc. 2- The elaborator only tries tactics after it tried to solve pending TC problems, delayed elaboratio, etc. The motivation: avoid unassigned metavariables in goals. 3- Each pending tactic goal is represented as a metavariable. It is marked as `synthethicOpaque` to make it clear that it should not be assigned by unification. 4- When we abstract a term containing metavariables, we often create new metavariables. Example: when abstracting `x` at `f ?m`, we obtain `fun x => f (?m' x)`. If `x` is in the scope of `?m`. If `?m` is `syntheticOpaque`, so is `?m'`, and we also have the delayed assignment `?m' x := ?m` 5- When checking a metavariable assignment, `?m := v` we check whether the type of `?m` is defeq to type of `v` with default reducibility setting. Now consider the following fragment ``` let a' := g 100 a ⟨i, h⟩ ⟨i - Nat.zero.succ, by exact Nat.lt_of_le_of_lt (Nat.pred_le i) h⟩ have : a'.size - i >= 0 := sorry f (i+1) a' ``` The elaborator tries to synthesize the instance `OfNat Nat 1` before we generate the tactic proof for `by exact ...` (remark 2). The solution `instOfNatNat 1` is synthesized. Let `m? a i h a' this` be the "hole" associated with the pending instance. Then, `isDefEq` tries to assign `m? a i h a' this := instOfNatNat 1` which is reduced to `m? := mkLambdaFVars #[a, i, h, a', this] (instOfNatNat 1)`. Note that, this is an abstraction step (remark 4), and the type contains the `syntheticOpaque` metavariable for the pending tactic proof (remark 3). Thus, a new `syntheticOpaque` opaque is created (remark 4). Then, `isDefEq` must check whether the type of `?m` is defeq to `mkLambdaFVars #[a, i, h, a', this] (instOfNatNat 1)` (remark 5). The two types are almost identical, but they contain different `syntheticOpaque` in the subterm corresponding to the `by exact ...` tactic proof. Without the following proof irrelevance test, the check will fail, and `isDefEq` timeouts unfolding `g` and its dependencies. Note that this test does not prevent a similar performance problem in a usecase where the tactic is used to synthesize a term that is not a proof. TODO: add better support for checking the delayed assignments. This is not high priority because tactics are usually only used for synthesizing proofs. -/ match (← isDefEqProofIrrel t s) with | LBool.true => return LBool.true | LBool.false => return LBool.false | _ => if tFn.isMVar || sFn.isMVar then let ctx ← read if ctx.config.isDefEqStuckEx then do trace[Meta.isDefEq.stuck] "{t} =?= {s}" Meta.throwIsDefEqStuck else return LBool.false else return LBool.undef else isDefEqQuickMVarMVar t s /-- Both `t` and `s` are terms of the form `?m ...` -/ private partial def isDefEqQuickMVarMVar (t s : Expr) : MetaM LBool := do if s.isMVar && !t.isMVar then /- Solve `?m t =?= ?n` by trying first `?n := ?m t`. Reason: this assignment is precise. -/ if (← checkpointDefEq (processAssignment s t)) then return LBool.true else toLBoolM <| processAssignment t s else if (← checkpointDefEq (processAssignment t s)) then return LBool.true else toLBoolM <| processAssignment s t end @[inline] def whenUndefDo (x : MetaM LBool) (k : MetaM Bool) : MetaM Bool := do let status ← x match status with | LBool.true => pure true | LBool.false => pure false | LBool.undef => k @[specialize] private def unstuckMVar (e : Expr) (successK : Expr → MetaM Bool) (failK : MetaM Bool): MetaM Bool := do match (← getStuckMVar? e) with | some mvarId => trace[Meta.isDefEq.stuckMVar] "found stuck MVar {mkMVar mvarId} : {← inferType (mkMVar mvarId)}" if (← Meta.synthPending mvarId) then let e ← instantiateMVars e successK e else failK | none => failK private def isDefEqOnFailure (t s : Expr) : MetaM Bool := do trace[Meta.isDefEq.onFailure] "{t} =?= {s}" unstuckMVar t (fun t => Meta.isExprDefEqAux t s) <| unstuckMVar s (fun s => Meta.isExprDefEqAux t s) <| tryUnificationHints t s <||> tryUnificationHints s t private def isDefEqProj : Expr → Expr → MetaM Bool | Expr.proj _ i t, Expr.proj _ j s => pure (i == j) <&&> Meta.isExprDefEqAux t s | Expr.proj structName 0 s, v => isDefEqSingleton structName s v | v, Expr.proj structName 0 s => isDefEqSingleton structName s v | _, _ => pure false where /-- If `structName` is a structure with a single field and `(?m ...).1 =?= v`, then solve contraint as `?m ... =?= ⟨v⟩` -/ isDefEqSingleton (structName : Name) (s : Expr) (v : Expr) : MetaM Bool := do let ctorVal := getStructureCtor (← getEnv) structName if ctorVal.numFields != 1 then return false -- It is not a structure with a single field. let sType ← whnf (← inferType s) let sTypeFn := sType.getAppFn if !sTypeFn.isConstOf structName then return false let s ← whnf s let sFn := s.getAppFn if !sFn.isMVar then return false if (← isAssignable sFn) then let ctorApp := mkApp (mkAppN (mkConst ctorVal.name sTypeFn.constLevels!) sType.getAppArgs) v processAssignment' s ctorApp else return false /-- Given applications `t` and `s` that are in WHNF (modulo the current transparency setting), check whether they are definitionally equal or not. -/ private def isDefEqApp (t s : Expr) : MetaM Bool := do let tFn := t.getAppFn let sFn := s.getAppFn if tFn.isConst && sFn.isConst && tFn.constName! == sFn.constName! then /- See comment at `tryHeuristic` explaining why we processe arguments before universe levels. -/ if (← checkpointDefEq (isDefEqArgs tFn t.getAppArgs s.getAppArgs <&&> isListLevelDefEqAux tFn.constLevels! sFn.constLevels!)) then return true else isDefEqOnFailure t s else if (← checkpointDefEq (Meta.isExprDefEqAux tFn s.getAppFn <&&> isDefEqArgs tFn t.getAppArgs s.getAppArgs)) then return true else isDefEqOnFailure t s /-- Return `true` if the types of the given expressions is an inductive datatype with an inductive datatype with a single constructor with no fields. -/ private def isDefEqUnitLike (t : Expr) (s : Expr) : MetaM Bool := do let tType ← whnf (← inferType t) matchConstStruct tType.getAppFn (fun _ => return false) fun _ _ ctorVal => do if ctorVal.numFields != 0 then return false else if (← useEtaStruct ctorVal.induct) then Meta.isExprDefEqAux tType (← inferType s) else return false /-- The `whnf` procedure has support for unfolding class projections when the transparency mode is set to `.instances`. This method ensures the behavior of `whnf` and `isDefEq` is consistent in this transparency mode. -/ private def isDefEqProjInst (t : Expr) (s : Expr) : MetaM LBool := do if (← getTransparency) != .instances then return .undef let t? ← unfoldProjInstWhenIntances? t let s? ← unfoldProjInstWhenIntances? s if t?.isSome || s?.isSome then toLBoolM <| Meta.isExprDefEqAux (t?.getD t) (s?.getD s) else return .undef private def isExprDefEqExpensive (t : Expr) (s : Expr) : MetaM Bool := do if (← (isDefEqEta t s <||> isDefEqEta s t)) then return true -- TODO: investigate whether this is the place for putting this check if (← (isDefEqEtaStruct t s <||> isDefEqEtaStruct s t)) then return true if (← isDefEqProj t s) then return true let t' ← whnfCore t let s' ← whnfCore s if t != t' || s != s' then Meta.isExprDefEqAux t' s' else whenUndefDo (isDefEqNative t s) do whenUndefDo (isDefEqNat t s) do whenUndefDo (isDefEqOffset t s) do whenUndefDo (isDefEqDelta t s) do if t.isConst && s.isConst then if t.constName! == s.constName! then isListLevelDefEqAux t.constLevels! s.constLevels! else return false else if (← pure t.isApp <&&> pure s.isApp <&&> isDefEqApp t s) then return true else whenUndefDo (isDefEqProjInst t s) do whenUndefDo (isDefEqStringLit t s) do if (← isDefEqUnitLike t s) then return true else isDefEqOnFailure t s private def mkCacheKey (t : Expr) (s : Expr) : Expr × Expr := if Expr.quickLt t s then (t, s) else (s, t) private def getCachedResult (key : Expr × Expr) : MetaM LBool := do match (← get).cache.defEq.find? key with | some val => return val.toLBool | none => return .undef private def cacheResult (key : Expr × Expr) (result : Bool) : MetaM Unit := do modifyDefEqCache fun c => c.insert key result @[export lean_is_expr_def_eq] partial def isExprDefEqAuxImpl (t : Expr) (s : Expr) : MetaM Bool := withIncRecDepth do withTraceNode `Meta.isDefEq (return m!"{exceptBoolEmoji ·} {t} =?= {s}") do checkMaxHeartbeats "isDefEq" whenUndefDo (isDefEqQuick t s) do whenUndefDo (isDefEqProofIrrel t s) do -- We perform `whnfCore` again with `deltaAtProj := true` at `isExprDefEqExpensive` after `isDefEqProj` let t' ← whnfCore t (deltaAtProj := false) let s' ← whnfCore s (deltaAtProj := false) if t != t' || s != s' then isExprDefEqAuxImpl t' s' else /- TODO: check whether the following `instantiateMVar`s are expensive or not in practice. Lean 3 does not use them, and may miss caching opportunities since it is not safe to cache when `t` and `s` may contain mvars. The unit test `tryHeuristicPerfIssue2.lean` cannot be solved without these two `instantiateMVar`s. If it becomes a problem, we may use store a flag in the context indicating whether we have already used `instantiateMVar` in outer invocations or not. It is not perfect (we may assign mvars in nested calls), but it should work well enough in practice, and prevent repeated traversals in nested calls. -/ let t ← instantiateMVars t let s ← instantiateMVars s let numPostponed ← getNumPostponed let k := mkCacheKey t s match (← getCachedResult k) with | .true => trace[Meta.isDefEq.cache] "cache hit 'true' for {t} =?= {s}" return true | .false => trace[Meta.isDefEq.cache] "cache hit 'false' for {t} =?= {s}" return false | .undef => let result ← isExprDefEqExpensive t s if numPostponed == (← getNumPostponed) then trace[Meta.isDefEq.cache] "cache {result} for {t} =?= {s}" cacheResult k result return result builtin_initialize registerTraceClass `Meta.isDefEq registerTraceClass `Meta.isDefEq.foApprox registerTraceClass `Meta.isDefEq.constApprox registerTraceClass `Meta.isDefEq.delta (inherited := true) registerTraceClass `Meta.isDefEq.assign registerTraceClass `Meta.isDefEq.assign.checkTypes (inherited := true) registerTraceClass `Meta.isDefEq.eta.struct end Lean.Meta
665261a81771e8c37484ec03823a73fe596a8da8
c777c32c8e484e195053731103c5e52af26a25d1
/src/number_theory/ramification_inertia.lean
8c61439b6981fd6e357b04224fb2fa994d330f9f
[ "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
39,047
lean
/- Copyright (c) 2022 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import linear_algebra.free_module.finite.rank import ring_theory.dedekind_domain.ideal /-! # Ramification index and inertia degree Given `P : ideal S` lying over `p : ideal R` for the ring extension `f : R →+* S` (assuming `P` and `p` are prime or maximal where needed), the **ramification index** `ideal.ramification_idx f p P` is the multiplicity of `P` in `map f p`, and the **inertia degree** `ideal.inertia_deg f p P` is the degree of the field extension `(S / P) : (R / p)`. ## Main results The main theorem `ideal.sum_ramification_inertia` states that for all coprime `P` lying over `p`, `Σ P, ramification_idx f p P * inertia_deg f p P` equals the degree of the field extension `Frac(S) : Frac(R)`. ## Implementation notes Often the above theory is set up in the case where: * `R` is the ring of integers of a number field `K`, * `L` is a finite separable extension of `K`, * `S` is the integral closure of `R` in `L`, * `p` and `P` are maximal ideals, * `P` is an ideal lying over `p` We will try to relax the above hypotheses as much as possible. ## Notation In this file, `e` stands for the ramification index and `f` for the inertia degree of `P` over `p`, leaving `p` and `P` implicit. -/ namespace ideal universes u v variables {R : Type u} [comm_ring R] variables {S : Type v} [comm_ring S] (f : R →+* S) variables (p : ideal R) (P : ideal S) open finite_dimensional open unique_factorization_monoid section dec_eq open_locale classical /-- The ramification index of `P` over `p` is the largest exponent `n` such that `p` is contained in `P^n`. In particular, if `p` is not contained in `P^n`, then the ramification index is 0. If there is no largest such `n` (e.g. because `p = ⊥`), then `ramification_idx` is defined to be 0. -/ noncomputable def ramification_idx : ℕ := Sup {n | map f p ≤ P ^ n} variables {f p P} lemma ramification_idx_eq_find (h : ∃ n, ∀ k, map f p ≤ P ^ k → k ≤ n) : ramification_idx f p P = nat.find h := nat.Sup_def h lemma ramification_idx_eq_zero (h : ∀ n : ℕ, ∃ k, map f p ≤ P ^ k ∧ n < k) : ramification_idx f p P = 0 := dif_neg (by push_neg; exact h) lemma ramification_idx_spec {n : ℕ} (hle : map f p ≤ P ^ n) (hgt : ¬ map f p ≤ P ^ (n + 1)) : ramification_idx f p P = n := begin have : ∀ (k : ℕ), map f p ≤ P ^ k → k ≤ n, { intros k hk, refine le_of_not_lt (λ hnk, _), exact hgt (hk.trans (ideal.pow_le_pow hnk)) }, rw ramification_idx_eq_find ⟨n, this⟩, { refine le_antisymm (nat.find_min' _ this) (le_of_not_gt (λ (h : nat.find _ < n), _)), obtain this' := nat.find_spec ⟨n, this⟩, exact h.not_le (this' _ hle) }, end lemma ramification_idx_lt {n : ℕ} (hgt : ¬ (map f p ≤ P ^ n)) : ramification_idx f p P < n := begin cases n, { simpa using hgt }, rw nat.lt_succ_iff, have : ∀ k, map f p ≤ P ^ k → k ≤ n, { refine λ k hk, le_of_not_lt (λ hnk, _), exact hgt (hk.trans (ideal.pow_le_pow hnk)) }, rw ramification_idx_eq_find ⟨n, this⟩, exact nat.find_min' ⟨n, this⟩ this end @[simp] lemma ramification_idx_bot : ramification_idx f ⊥ P = 0 := dif_neg $ not_exists.mpr $ λ n hn, n.lt_succ_self.not_le (hn _ (by simp)) @[simp] lemma ramification_idx_of_not_le (h : ¬ map f p ≤ P) : ramification_idx f p P = 0 := ramification_idx_spec (by simp) (by simpa using h) lemma ramification_idx_ne_zero {e : ℕ} (he : e ≠ 0) (hle : map f p ≤ P ^ e) (hnle : ¬ map f p ≤ P ^ (e + 1)): ramification_idx f p P ≠ 0 := by rwa ramification_idx_spec hle hnle lemma le_pow_of_le_ramification_idx {n : ℕ} (hn : n ≤ ramification_idx f p P) : map f p ≤ P ^ n := begin contrapose! hn, exact ramification_idx_lt hn end lemma le_pow_ramification_idx : map f p ≤ P ^ ramification_idx f p P := le_pow_of_le_ramification_idx (le_refl _) lemma le_comap_pow_ramification_idx : p ≤ comap f (P ^ ramification_idx f p P) := map_le_iff_le_comap.mp le_pow_ramification_idx lemma le_comap_of_ramification_idx_ne_zero (h : ramification_idx f p P ≠ 0) : p ≤ comap f P := ideal.map_le_iff_le_comap.mp $ le_pow_ramification_idx.trans $ ideal.pow_le_self $ h namespace is_dedekind_domain variables [is_domain S] [is_dedekind_domain S] lemma ramification_idx_eq_normalized_factors_count (hp0 : map f p ≠ ⊥) (hP : P.is_prime) (hP0 : P ≠ ⊥) : ramification_idx f p P = (normalized_factors (map f p)).count P := begin have hPirr := (ideal.prime_of_is_prime hP0 hP).irreducible, refine ramification_idx_spec (ideal.le_of_dvd _) (mt ideal.dvd_iff_le.mpr _); rw [dvd_iff_normalized_factors_le_normalized_factors (pow_ne_zero _ hP0) hp0, normalized_factors_pow, normalized_factors_irreducible hPirr, normalize_eq, multiset.nsmul_singleton, ← multiset.le_count_iff_replicate_le], { exact (nat.lt_succ_self _).not_le }, end lemma ramification_idx_eq_factors_count (hp0 : map f p ≠ ⊥) (hP : P.is_prime) (hP0 : P ≠ ⊥) : ramification_idx f p P = (factors (map f p)).count P := by rw [is_dedekind_domain.ramification_idx_eq_normalized_factors_count hp0 hP hP0, factors_eq_normalized_factors] lemma ramification_idx_ne_zero (hp0 : map f p ≠ ⊥) (hP : P.is_prime) (le : map f p ≤ P) : ramification_idx f p P ≠ 0 := begin have hP0 : P ≠ ⊥, { unfreezingI { rintro rfl }, have := le_bot_iff.mp le, contradiction }, have hPirr := (ideal.prime_of_is_prime hP0 hP).irreducible, rw is_dedekind_domain.ramification_idx_eq_normalized_factors_count hp0 hP hP0, obtain ⟨P', hP', P'_eq⟩ := exists_mem_normalized_factors_of_dvd hp0 hPirr (ideal.dvd_iff_le.mpr le), rwa [multiset.count_ne_zero, associated_iff_eq.mp P'_eq], end end is_dedekind_domain variables (f p P) local attribute [instance] ideal.quotient.field /-- The inertia degree of `P : ideal S` lying over `p : ideal R` is the degree of the extension `(S / P) : (R / p)`. We do not assume `P` lies over `p` in the definition; we return `0` instead. See `inertia_deg_algebra_map` for the common case where `f = algebra_map R S` and there is an algebra structure `R / p → S / P`. -/ noncomputable def inertia_deg [hp : p.is_maximal] : ℕ := if hPp : comap f P = p then @finrank (R ⧸ p) (S ⧸ P) _ _ $ @algebra.to_module _ _ _ _ $ ring_hom.to_algebra $ ideal.quotient.lift p (P^.quotient.mk^.comp f) $ λ a ha, quotient.eq_zero_iff_mem.mpr $ mem_comap.mp $ hPp.symm ▸ ha else 0 -- Useful for the `nontriviality` tactic using `comap_eq_of_scalar_tower_quotient`. @[simp] lemma inertia_deg_of_subsingleton [hp : p.is_maximal] [hQ : subsingleton (S ⧸ P)] : inertia_deg f p P = 0 := begin have := ideal.quotient.subsingleton_iff.mp hQ, unfreezingI { subst this }, exact dif_neg (λ h, hp.ne_top $ h.symm.trans comap_top) end @[simp] lemma inertia_deg_algebra_map [algebra R S] [algebra (R ⧸ p) (S ⧸ P)] [is_scalar_tower R (R ⧸ p) (S ⧸ P)] [hp : p.is_maximal] : inertia_deg (algebra_map R S) p P = finrank (R ⧸ p) (S ⧸ P) := begin nontriviality (S ⧸ P) using [inertia_deg_of_subsingleton, finrank_zero_of_subsingleton], have := comap_eq_of_scalar_tower_quotient (algebra_map (R ⧸ p) (S ⧸ P)).injective, rw [inertia_deg, dif_pos this], congr, refine algebra.algebra_ext _ _ (λ x', quotient.induction_on' x' $ λ x, _), change ideal.quotient.lift p _ _ (ideal.quotient.mk p x) = algebra_map _ _ (ideal.quotient.mk p x), rw [ideal.quotient.lift_mk, ← ideal.quotient.algebra_map_eq, ← is_scalar_tower.algebra_map_eq, ← ideal.quotient.algebra_map_eq, ← is_scalar_tower.algebra_map_apply] end end dec_eq section finrank_quotient_map open_locale big_operators open_locale non_zero_divisors variables [algebra R S] variables {K : Type*} [field K] [algebra R K] [hRK : is_fraction_ring R K] variables {L : Type*} [field L] [algebra S L] [is_fraction_ring S L] variables {V V' V'' : Type*} variables [add_comm_group V] [module R V] [module K V] [is_scalar_tower R K V] variables [add_comm_group V'] [module R V'] [module S V'] [is_scalar_tower R S V'] variables [add_comm_group V''] [module R V''] variables (K) include hRK /-- Let `V` be a vector space over `K = Frac(R)`, `S / R` a ring extension and `V'` a module over `S`. If `b`, in the intersection `V''` of `V` and `V'`, is linear independent over `S` in `V'`, then it is linear independent over `R` in `V`. The statement we prove is actually slightly more general: * it suffices that the inclusion `algebra_map R S : R → S` is nontrivial * the function `f' : V'' → V'` doesn't need to be injective -/ lemma finrank_quotient_map.linear_independent_of_nontrivial [is_domain R] [is_dedekind_domain R] (hRS : (algebra_map R S).ker ≠ ⊤) (f : V'' →ₗ[R] V) (hf : function.injective f) (f' : V'' →ₗ[R] V') {ι : Type*} {b : ι → V''} (hb' : linear_independent S (f' ∘ b)) : linear_independent K (f ∘ b) := begin contrapose! hb' with hb, -- Informally, if we have a nontrivial linear dependence with coefficients `g` in `K`, -- then we can find a linear dependence with coefficients `I.quotient.mk g'` in `R/I`, -- where `I = ker (algebra_map R S)`. -- We make use of the same principle but stay in `R` everywhere. simp only [linear_independent_iff', not_forall] at hb ⊢, obtain ⟨s, g, eq, j', hj's, hj'g⟩ := hb, use s, obtain ⟨a, hag, j, hjs, hgI⟩ := ideal.exist_integer_multiples_not_mem hRS s g hj's hj'g, choose g'' hg'' using hag, letI := classical.prop_decidable, let g' := λ i, if h : i ∈ s then g'' i h else 0, have hg' : ∀ i ∈ s, algebra_map _ _ (g' i) = a * g i, { intros i hi, exact (congr_arg _ (dif_pos hi)).trans (hg'' i hi) }, -- Because `R/I` is nontrivial, we can lift `g` to a nontrivial linear dependence in `S`. have hgI : algebra_map R S (g' j) ≠ 0, { simp only [fractional_ideal.mem_coe_ideal, not_exists, not_and'] at hgI, exact hgI _ (hg' j hjs) }, refine ⟨λ i, algebra_map R S (g' i), _, j, hjs, hgI⟩, have eq : f (∑ i in s, g' i • (b i)) = 0, { rw [linear_map.map_sum, ← smul_zero a, ← eq, finset.smul_sum, finset.sum_congr rfl], intros i hi, rw [linear_map.map_smul, ← is_scalar_tower.algebra_map_smul K, hg' i hi, ← smul_assoc, smul_eq_mul], apply_instance }, simp only [is_scalar_tower.algebra_map_smul, ← linear_map.map_smul, ← linear_map.map_sum, (f.map_eq_zero_iff hf).mp eq, linear_map.map_zero], end open_locale matrix variables {K} omit hRK /-- If `b` mod `p` spans `S/p` as `R/p`-space, then `b` itself spans `Frac(S)` as `K`-space. Here, * `p` is an ideal of `R` such that `R / p` is nontrivial * `K` is a field that has an embedding of `R` (in particular we can take `K = Frac(R)`) * `L` is a field extension of `K` * `S` is the integral closure of `R` in `L` More precisely, we avoid quotients in this statement and instead require that `b ∪ pS` spans `S`. -/ lemma finrank_quotient_map.span_eq_top [is_domain R] [is_domain S] [algebra K L] [is_noetherian R S] [algebra R L] [is_scalar_tower R S L] [is_scalar_tower R K L] [is_integral_closure S R L] [no_zero_smul_divisors R K] (hp : p ≠ ⊤) (b : set S) (hb' : submodule.span R b ⊔ (p.map (algebra_map R S)).restrict_scalars R = ⊤) : submodule.span K (algebra_map S L '' b) = ⊤ := begin have hRL : function.injective (algebra_map R L), { rw is_scalar_tower.algebra_map_eq R K L, exact (algebra_map K L).injective.comp (no_zero_smul_divisors.algebra_map_injective R K) }, -- Let `M` be the `R`-module spanned by the proposed basis elements. set M : submodule R S := submodule.span R b with hM, -- Then `S / M` is generated by some finite set of `n` vectors `a`. letI h : module.finite R (S ⧸ M) := module.finite.of_surjective (submodule.mkq _) (submodule.quotient.mk_surjective _), obtain ⟨n, a, ha⟩ := @@module.finite.exists_fin _ _ _ h, -- Because the image of `p` in `S / M` is `⊤`, have smul_top_eq : p • (⊤ : submodule R (S ⧸ M)) = ⊤, { calc p • ⊤ = submodule.map M.mkq (p • ⊤) : by rw [submodule.map_smul'', submodule.map_top, M.range_mkq] ... = ⊤ : by rw [ideal.smul_top_eq_map, (submodule.map_mkq_eq_top M _).mpr hb'] }, -- we can write the elements of `a` as `p`-linear combinations of other elements of `a`. have exists_sum : ∀ x : (S ⧸ M), ∃ a' : fin n → R, (∀ i, a' i ∈ p) ∧ ∑ i, a' i • a i = x, { intro x, obtain ⟨a'', ha'', hx⟩ := (submodule.mem_ideal_smul_span_iff_exists_sum p a x).1 _, { refine ⟨λ i, a'' i, λ i, ha'' _, _⟩, rw [← hx, finsupp.sum_fintype], exact λ _, zero_smul _ _ }, { rw [ha, smul_top_eq], exact submodule.mem_top } }, choose A' hA'p hA' using λ i, exists_sum (a i), -- This gives us a(n invertible) matrix `A` such that `det A ∈ (M = span R b)`, let A : matrix (fin n) (fin n) R := A' - 1, let B := A.adjugate, have A_smul : ∀ i, ∑ j, A i j • a j = 0, { intros, simp only [A, pi.sub_apply, sub_smul, finset.sum_sub_distrib, hA', matrix.one_apply, ite_smul, one_smul, zero_smul, finset.sum_ite_eq, finset.mem_univ, if_true, sub_self] }, -- since `span S {det A} / M = 0`. have d_smul : ∀ i, A.det • a i = 0, { intro i, calc A.det • a i = ∑ j, (B ⬝ A) i j • a j : _ ... = ∑ k, B i k • ∑ j, (A k j • a j) : _ ... = 0 : finset.sum_eq_zero (λ k _, _), { simp only [matrix.adjugate_mul, pi.smul_apply, matrix.one_apply, mul_ite, ite_smul, smul_eq_mul, mul_one, mul_zero, one_smul, zero_smul, finset.sum_ite_eq, finset.mem_univ, if_true] }, { simp only [matrix.mul_apply, finset.smul_sum, finset.sum_smul, smul_smul], rw finset.sum_comm }, { rw [A_smul, smul_zero] } }, -- In the rings of integers we have the desired inclusion. have span_d : (submodule.span S ({algebra_map R S A.det} : set S)).restrict_scalars R ≤ M, { intros x hx, rw submodule.restrict_scalars_mem at hx, obtain ⟨x', rfl⟩ := submodule.mem_span_singleton.mp hx, rw [smul_eq_mul, mul_comm, ← algebra.smul_def] at ⊢ hx, rw [← submodule.quotient.mk_eq_zero, submodule.quotient.mk_smul], obtain ⟨a', _, quot_x_eq⟩ := exists_sum (submodule.quotient.mk x'), simp_rw [← quot_x_eq, finset.smul_sum, smul_comm A.det, d_smul, smul_zero, finset.sum_const_zero] }, -- So now we lift everything to the fraction field. refine top_le_iff.mp (calc ⊤ = (ideal.span {algebra_map R L A.det}).restrict_scalars K : _ ... ≤ submodule.span K (algebra_map S L '' b) : _), -- Because `det A ≠ 0`, we have `span L {det A} = ⊤`. { rw [eq_comm, submodule.restrict_scalars_eq_top_iff, ideal.span_singleton_eq_top], refine is_unit.mk0 _ ((map_ne_zero_iff ((algebra_map R L)) hRL).mpr ( @ne_zero_of_map _ _ _ _ _ _ (ideal.quotient.mk p) _ _)), haveI := ideal.quotient.nontrivial hp, calc ideal.quotient.mk p (A.det) = matrix.det ((ideal.quotient.mk p).map_matrix A) : by rw [ring_hom.map_det, ring_hom.map_matrix_apply] ... = matrix.det ((ideal.quotient.mk p).map_matrix (A' - 1)) : rfl ... = matrix.det (λ i j, (ideal.quotient.mk p) (A' i j) - (1 : matrix (fin n) (fin n) (R ⧸ p)) i j) : _ ... = matrix.det (-1 : matrix (fin n) (fin n) (R ⧸ p)) : _ ... = (-1 : R ⧸ p) ^ n : by rw [matrix.det_neg, fintype.card_fin, matrix.det_one, mul_one] ... ≠ 0 : is_unit.ne_zero (is_unit_one.neg.pow _), { refine congr_arg matrix.det (matrix.ext (λ i j, _)), rw [map_sub, ring_hom.map_matrix_apply, map_one], refl }, { refine congr_arg matrix.det (matrix.ext (λ i j, _)), rw [ideal.quotient.eq_zero_iff_mem.mpr (hA'p i j), zero_sub], refl } }, -- And we conclude `L = span L {det A} ≤ span K b`, so `span K b` spans everything. { intros x hx, rw [submodule.restrict_scalars_mem, is_scalar_tower.algebra_map_apply R S L] at hx, refine is_fraction_ring.ideal_span_singleton_map_subset R _ hRL span_d hx, haveI : no_zero_smul_divisors R L := no_zero_smul_divisors.of_algebra_map_injective hRL, rw ← is_fraction_ring.is_algebraic_iff' R S, intros x, exact is_integral.is_algebraic _ (is_integral_of_noetherian infer_instance _) }, end include hRK variables (K L) /-- If `p` is a maximal ideal of `R`, and `S` is the integral closure of `R` in `L`, then the dimension `[S/pS : R/p]` is equal to `[Frac(S) : Frac(R)]`. -/ lemma finrank_quotient_map [is_domain R] [is_domain S] [is_dedekind_domain R] [algebra K L] [algebra R L] [is_scalar_tower R K L] [is_scalar_tower R S L] [is_integral_closure S R L] [hp : p.is_maximal] [is_noetherian R S] : finrank (R ⧸ p) (S ⧸ map (algebra_map R S) p) = finrank K L := begin -- Choose an arbitrary basis `b` for `[S/pS : R/p]`. -- We'll use the previous results to turn it into a basis on `[Frac(S) : Frac(R)]`. letI : field (R ⧸ p) := ideal.quotient.field _, let ι := module.free.choose_basis_index (R ⧸ p) (S ⧸ map (algebra_map R S) p), let b : basis ι (R ⧸ p) (S ⧸ map (algebra_map R S) p) := module.free.choose_basis _ _, -- Namely, choose a representative `b' i : S` for each `b i : S / pS`. let b' : ι → S := λ i, (ideal.quotient.mk_surjective (b i)).some, have b_eq_b' : ⇑ b = (submodule.mkq _).restrict_scalars R ∘ b' := funext (λ i, (ideal.quotient.mk_surjective (b i)).some_spec.symm), -- We claim `b'` is a basis for `Frac(S)` over `Frac(R)` because it is linear independent -- and spans the whole of `Frac(S)`. let b'' : ι → L := algebra_map S L ∘ b', have b''_li : linear_independent _ b'' := _, have b''_sp : submodule.span _ (set.range b'') = ⊤ := _, -- Since the two bases have the same index set, the spaces have the same dimension. let c : basis ι K L := basis.mk b''_li b''_sp.ge, rw [finrank_eq_card_basis b, finrank_eq_card_basis c], -- It remains to show that the basis is indeed linear independent and spans the whole space. { rw set.range_comp, refine finrank_quotient_map.span_eq_top p hp.ne_top _ (top_le_iff.mp _), -- The nicest way to show `S ≤ span b' ⊔ pS` is by reducing both sides modulo pS. -- However, this would imply distinguishing between `pS` as `S`-ideal, -- and `pS` as `R`-submodule, since they have different (non-defeq) quotients. -- Instead we'll lift `x mod pS ∈ span b` to `y ∈ span b'` for some `y - x ∈ pS`. intros x hx, have mem_span_b : ((submodule.mkq (map (algebra_map R S) p)) x : S ⧸ map (algebra_map R S) p) ∈ submodule.span (R ⧸ p) (set.range b) := b.mem_span _, rw [← @submodule.restrict_scalars_mem R, submodule.restrict_scalars_span R (R ⧸ p) ideal.quotient.mk_surjective, b_eq_b', set.range_comp, ← submodule.map_span] at mem_span_b, obtain ⟨y, y_mem, y_eq⟩ := submodule.mem_map.mp mem_span_b, suffices : y + -(y - x) ∈ _, { simpa }, rw [linear_map.restrict_scalars_apply, submodule.mkq_apply, submodule.mkq_apply, submodule.quotient.eq] at y_eq, exact add_mem (submodule.mem_sup_left y_mem) (neg_mem $ submodule.mem_sup_right y_eq) }, { have := b.linear_independent, rw b_eq_b' at this, convert finrank_quotient_map.linear_independent_of_nontrivial K _ ((algebra.linear_map S L).restrict_scalars R) _ ((submodule.mkq _).restrict_scalars R) this, { rw [quotient.algebra_map_eq, ideal.mk_ker], exact hp.ne_top }, { exact is_fraction_ring.injective S L } }, end end finrank_quotient_map section fact_le_comap local notation `e` := ramification_idx f p P /-- `R / p` has a canonical map to `S / (P ^ e)`, where `e` is the ramification index of `P` over `p`. -/ noncomputable instance quotient.algebra_quotient_pow_ramification_idx : algebra (R ⧸ p) (S ⧸ (P ^ e)) := quotient.algebra_quotient_of_le_comap (ideal.map_le_iff_le_comap.mp le_pow_ramification_idx) @[simp] lemma quotient.algebra_map_quotient_pow_ramification_idx (x : R) : algebra_map (R ⧸ p) (S ⧸ P ^ e) (ideal.quotient.mk p x) = ideal.quotient.mk _ (f x) := rfl variables [hfp : ne_zero (ramification_idx f p P)] include hfp /-- If `P` lies over `p`, then `R / p` has a canonical map to `S / P`. This can't be an instance since the map `f : R → S` is generally not inferrable. -/ def quotient.algebra_quotient_of_ramification_idx_ne_zero : algebra (R ⧸ p) (S ⧸ P) := quotient.algebra_quotient_of_le_comap (le_comap_of_ramification_idx_ne_zero hfp.out) -- In this file, the value for `f` can be inferred. local attribute [instance] ideal.quotient.algebra_quotient_of_ramification_idx_ne_zero @[simp] lemma quotient.algebra_map_quotient_of_ramification_idx_ne_zero (x : R) : algebra_map (R ⧸ p) (S ⧸ P) (ideal.quotient.mk p x) = ideal.quotient.mk _ (f x) := rfl omit hfp /-- The inclusion `(P^(i + 1) / P^e) ⊂ (P^i / P^e)`. -/ @[simps] def pow_quot_succ_inclusion (i : ℕ) : ideal.map (P^e)^.quotient.mk (P ^ (i + 1)) →ₗ[R ⧸ p] ideal.map (P^e)^.quotient.mk (P ^ i) := { to_fun := λ x, ⟨x, ideal.map_mono (ideal.pow_le_pow i.le_succ) x.2⟩, map_add' := λ x y, rfl, map_smul' := λ c x, rfl } lemma pow_quot_succ_inclusion_injective (i : ℕ) : function.injective (pow_quot_succ_inclusion f p P i) := begin rw [← linear_map.ker_eq_bot, linear_map.ker_eq_bot'], rintro ⟨x, hx⟩ hx0, rw subtype.ext_iff at hx0 ⊢, rwa pow_quot_succ_inclusion_apply_coe at hx0 end /-- `S ⧸ P` embeds into the quotient by `P^(i+1) ⧸ P^e` as a subspace of `P^i ⧸ P^e`. See `quotient_to_quotient_range_pow_quot_succ` for this as a linear map, and `quotient_range_pow_quot_succ_inclusion_equiv` for this as a linear equivalence. -/ noncomputable def quotient_to_quotient_range_pow_quot_succ_aux {i : ℕ} {a : S} (a_mem : a ∈ P^i) : S ⧸ P → ((P ^ i).map (P ^ e)^.quotient.mk ⧸ (pow_quot_succ_inclusion f p P i).range) := quotient.map' (λ (x : S), ⟨_, ideal.mem_map_of_mem _ (ideal.mul_mem_left _ x a_mem)⟩) (λ x y h, begin rw submodule.quotient_rel_r_def at ⊢ h, simp only [_root_.map_mul, linear_map.mem_range], refine ⟨⟨_, ideal.mem_map_of_mem _ (ideal.mul_mem_mul h a_mem)⟩, _⟩, ext, rw [pow_quot_succ_inclusion_apply_coe, subtype.coe_mk, submodule.coe_sub, subtype.coe_mk, subtype.coe_mk, _root_.map_mul, map_sub, sub_mul] end) lemma quotient_to_quotient_range_pow_quot_succ_aux_mk {i : ℕ} {a : S} (a_mem : a ∈ P^i) (x : S) : quotient_to_quotient_range_pow_quot_succ_aux f p P a_mem (submodule.quotient.mk x) = submodule.quotient.mk ⟨_, ideal.mem_map_of_mem _ (ideal.mul_mem_left _ x a_mem)⟩ := by apply quotient.map'_mk' include hfp /-- `S ⧸ P` embeds into the quotient by `P^(i+1) ⧸ P^e` as a subspace of `P^i ⧸ P^e`. -/ noncomputable def quotient_to_quotient_range_pow_quot_succ {i : ℕ} {a : S} (a_mem : a ∈ P^i) : S ⧸ P →ₗ[R ⧸ p] ((P ^ i).map (P ^ e)^.quotient.mk ⧸ (pow_quot_succ_inclusion f p P i).range) := { to_fun := quotient_to_quotient_range_pow_quot_succ_aux f p P a_mem, map_add' := begin intros x y, refine quotient.induction_on' x (λ x, quotient.induction_on' y (λ y, _)), simp only [submodule.quotient.mk'_eq_mk, ← submodule.quotient.mk_add, quotient_to_quotient_range_pow_quot_succ_aux_mk, add_mul], refine congr_arg submodule.quotient.mk _, ext, refl end, map_smul' := begin intros x y, refine quotient.induction_on' x (λ x, quotient.induction_on' y (λ y, _)), simp only [submodule.quotient.mk'_eq_mk, ← submodule.quotient.mk_add, quotient_to_quotient_range_pow_quot_succ_aux_mk, ring_hom.id_apply], refine congr_arg submodule.quotient.mk _, ext, simp only [subtype.coe_mk, _root_.map_mul, algebra.smul_def, submodule.coe_mk, mul_assoc, ideal.quotient.mk_eq_mk, submodule.coe_smul_of_tower, ideal.quotient.algebra_map_quotient_pow_ramification_idx] end } lemma quotient_to_quotient_range_pow_quot_succ_mk {i : ℕ} {a : S} (a_mem : a ∈ P^i) (x : S) : quotient_to_quotient_range_pow_quot_succ f p P a_mem (submodule.quotient.mk x) = submodule.quotient.mk ⟨_, ideal.mem_map_of_mem _ (ideal.mul_mem_left _ x a_mem)⟩ := quotient_to_quotient_range_pow_quot_succ_aux_mk f p P a_mem x lemma quotient_to_quotient_range_pow_quot_succ_injective [is_domain S] [is_dedekind_domain S] [P.is_prime] {i : ℕ} (hi : i < e) {a : S} (a_mem : a ∈ P^i) (a_not_mem : a ∉ P^(i + 1)) : function.injective (quotient_to_quotient_range_pow_quot_succ f p P a_mem) := λ x, quotient.induction_on' x $ λ x y, quotient.induction_on' y $ λ y h, begin have Pe_le_Pi1 : P^e ≤ P^(i + 1) := ideal.pow_le_pow hi, simp only [submodule.quotient.mk'_eq_mk, quotient_to_quotient_range_pow_quot_succ_mk, submodule.quotient.eq, linear_map.mem_range, subtype.ext_iff, subtype.coe_mk, submodule.coe_sub] at ⊢ h, rcases h with ⟨⟨⟨z⟩, hz⟩, h⟩, rw [submodule.quotient.quot_mk_eq_mk, ideal.quotient.mk_eq_mk, ideal.mem_quotient_iff_mem_sup, sup_eq_left.mpr Pe_le_Pi1] at hz, rw [pow_quot_succ_inclusion_apply_coe, subtype.coe_mk, submodule.quotient.quot_mk_eq_mk, ideal.quotient.mk_eq_mk, ← map_sub, ideal.quotient.eq, ← sub_mul] at h, exact (ideal.is_prime.mul_mem_pow _ ((submodule.sub_mem_iff_right _ hz).mp (Pe_le_Pi1 h))).resolve_right a_not_mem, end lemma quotient_to_quotient_range_pow_quot_succ_surjective [is_domain S] [is_dedekind_domain S] (hP0 : P ≠ ⊥) [hP : P.is_prime] {i : ℕ} (hi : i < e) {a : S} (a_mem : a ∈ P^i) (a_not_mem : a ∉ P^(i + 1)) : function.surjective (quotient_to_quotient_range_pow_quot_succ f p P a_mem) := begin rintro ⟨⟨⟨x⟩, hx⟩⟩, have Pe_le_Pi : P^e ≤ P^i := ideal.pow_le_pow hi.le, have Pe_le_Pi1 : P^e ≤ P^(i + 1) := ideal.pow_le_pow hi, rw [submodule.quotient.quot_mk_eq_mk, ideal.quotient.mk_eq_mk, ideal.mem_quotient_iff_mem_sup, sup_eq_left.mpr Pe_le_Pi] at hx, suffices hx' : x ∈ ideal.span {a} ⊔ P^(i+1), { obtain ⟨y', hy', z, hz, rfl⟩ := submodule.mem_sup.mp hx', obtain ⟨y, rfl⟩ := ideal.mem_span_singleton.mp hy', refine ⟨submodule.quotient.mk y, _⟩, simp only [submodule.quotient.quot_mk_eq_mk, quotient_to_quotient_range_pow_quot_succ_mk, submodule.quotient.eq, linear_map.mem_range, subtype.ext_iff, subtype.coe_mk, submodule.coe_sub], refine ⟨⟨_, ideal.mem_map_of_mem _ (submodule.neg_mem _ hz)⟩, _⟩, rw [pow_quot_succ_inclusion_apply_coe, subtype.coe_mk, ideal.quotient.mk_eq_mk, map_add, mul_comm y a, sub_add_cancel', map_neg] }, letI := classical.dec_eq (ideal S), rw [sup_eq_prod_inf_factors _ (pow_ne_zero _ hP0), normalized_factors_pow, normalized_factors_irreducible ((ideal.prime_iff_is_prime hP0).mpr hP).irreducible, normalize_eq, multiset.nsmul_singleton, multiset.inter_replicate, multiset.prod_replicate], rw [← submodule.span_singleton_le_iff_mem, ideal.submodule_span_eq] at a_mem a_not_mem, rwa [ideal.count_normalized_factors_eq a_mem a_not_mem, min_eq_left i.le_succ], { intro ha, rw ideal.span_singleton_eq_bot.mp ha at a_not_mem, have := (P^(i+1)).zero_mem, contradiction }, end /-- Quotienting `P^i / P^e` by its subspace `P^(i+1) ⧸ P^e` is `R ⧸ p`-linearly isomorphic to `S ⧸ P`. -/ noncomputable def quotient_range_pow_quot_succ_inclusion_equiv [is_domain S] [is_dedekind_domain S] [P.is_prime] (hP : P ≠ ⊥) {i : ℕ} (hi : i < e) : ((P ^ i).map (P ^ e)^.quotient.mk ⧸ (pow_quot_succ_inclusion f p P i).range) ≃ₗ[R ⧸ p] S ⧸ P := begin choose a a_mem a_not_mem using set_like.exists_of_lt (ideal.strict_anti_pow P hP (ideal.is_prime.ne_top infer_instance) (le_refl i.succ)), refine (linear_equiv.of_bijective _ ⟨_, _⟩).symm, { exact quotient_to_quotient_range_pow_quot_succ f p P a_mem }, { exact quotient_to_quotient_range_pow_quot_succ_injective f p P hi a_mem a_not_mem }, { exact quotient_to_quotient_range_pow_quot_succ_surjective f p P hP hi a_mem a_not_mem } end /-- Since the inclusion `(P^(i + 1) / P^e) ⊂ (P^i / P^e)` has a kernel isomorphic to `P / S`, `[P^i / P^e : R / p] = [P^(i+1) / P^e : R / p] + [P / S : R / p]` -/ lemma rank_pow_quot_aux [is_domain S] [is_dedekind_domain S] [p.is_maximal] [P.is_prime] (hP0 : P ≠ ⊥) {i : ℕ} (hi : i < e) : module.rank (R ⧸ p) (ideal.map (P^e)^.quotient.mk (P ^ i)) = module.rank (R ⧸ p) (S ⧸ P) + module.rank (R ⧸ p) (ideal.map (P^e)^.quotient.mk (P ^ (i + 1))) := begin letI : field (R ⧸ p) := ideal.quotient.field _, rw [rank_eq_of_injective _ (pow_quot_succ_inclusion_injective f p P i), (quotient_range_pow_quot_succ_inclusion_equiv f p P hP0 hi).symm.rank_eq], exact (rank_quotient_add_rank (linear_map.range (pow_quot_succ_inclusion f p P i))).symm, end lemma rank_pow_quot [is_domain S] [is_dedekind_domain S] [p.is_maximal] [P.is_prime] (hP0 : P ≠ ⊥) (i : ℕ) (hi : i ≤ e) : module.rank (R ⧸ p) (ideal.map (P^e)^.quotient.mk (P ^ i)) = (e - i) • module.rank (R ⧸ p) (S ⧸ P) := begin refine @nat.decreasing_induction' _ i e (λ j lt_e le_j ih, _) hi _, { rw [rank_pow_quot_aux f p P _ lt_e, ih, ← succ_nsmul, nat.sub_succ, ← nat.succ_eq_add_one, nat.succ_pred_eq_of_pos (nat.sub_pos_of_lt lt_e)], assumption }, { rw [nat.sub_self, zero_nsmul, map_quotient_self], exact rank_bot (R ⧸ p) (S ⧸ (P^e)) } end omit hfp /-- If `p` is a maximal ideal of `R`, `S` extends `R` and `P^e` lies over `p`, then the dimension `[S/(P^e) : R/p]` is equal to `e * [S/P : R/p]`. -/ lemma rank_prime_pow_ramification_idx [is_domain S] [is_dedekind_domain S] [p.is_maximal] [P.is_prime] (hP0 : P ≠ ⊥) (he : e ≠ 0) : module.rank (R ⧸ p) (S ⧸ P^e) = e • @module.rank (R ⧸ p) (S ⧸ P) _ _ (@algebra.to_module _ _ _ _ $ @@quotient.algebra_quotient_of_ramification_idx_ne_zero _ _ _ _ _ ⟨he⟩) := begin letI : ne_zero e := ⟨he⟩, have := rank_pow_quot f p P hP0 0 (nat.zero_le e), rw [pow_zero, nat.sub_zero, ideal.one_eq_top, ideal.map_top] at this, exact (rank_top (R ⧸ p) _).symm.trans this end /-- If `p` is a maximal ideal of `R`, `S` extends `R` and `P^e` lies over `p`, then the dimension `[S/(P^e) : R/p]`, as a natural number, is equal to `e * [S/P : R/p]`. -/ lemma finrank_prime_pow_ramification_idx [is_domain S] [is_dedekind_domain S] (hP0 : P ≠ ⊥) [p.is_maximal] [P.is_prime] (he : e ≠ 0) : finrank (R ⧸ p) (S ⧸ P^e) = e * @finrank (R ⧸ p) (S ⧸ P) _ _ (@algebra.to_module _ _ _ _ $ @@quotient.algebra_quotient_of_ramification_idx_ne_zero _ _ _ _ _ ⟨he⟩) := begin letI : ne_zero e := ⟨he⟩, letI : algebra (R ⧸ p) (S ⧸ P) := quotient.algebra_quotient_of_ramification_idx_ne_zero f p P, letI := ideal.quotient.field p, have hdim := rank_prime_pow_ramification_idx _ _ _ hP0 he, by_cases hP : finite_dimensional (R ⧸ p) (S ⧸ P), { haveI := hP, haveI := (finite_dimensional_iff_of_rank_eq_nsmul he hdim).mpr hP, refine cardinal.nat_cast_injective _, rw [finrank_eq_rank', nat.cast_mul, finrank_eq_rank', hdim, nsmul_eq_mul] }, have hPe := mt (finite_dimensional_iff_of_rank_eq_nsmul he hdim).mp hP, simp only [finrank_of_infinite_dimensional hP, finrank_of_infinite_dimensional hPe, mul_zero], end end fact_le_comap section factors_map open_locale classical /-! ## Properties of the factors of `p.map (algebra_map R S)` -/ variables [is_domain S] [is_dedekind_domain S] [algebra R S] lemma factors.ne_bot (P : (factors (map (algebra_map R S) p)).to_finset) : (P : ideal S) ≠ ⊥ := (prime_of_factor _ (multiset.mem_to_finset.mp P.2)).ne_zero instance factors.is_prime (P : (factors (map (algebra_map R S) p)).to_finset) : is_prime (P : ideal S) := ideal.is_prime_of_prime (prime_of_factor _ (multiset.mem_to_finset.mp P.2)) lemma factors.ramification_idx_ne_zero (P : (factors (map (algebra_map R S) p)).to_finset) : ramification_idx (algebra_map R S) p P ≠ 0 := is_dedekind_domain.ramification_idx_ne_zero (ne_zero_of_mem_factors (multiset.mem_to_finset.mp P.2)) (factors.is_prime p P) (ideal.le_of_dvd (dvd_of_mem_factors (multiset.mem_to_finset.mp P.2))) instance factors.fact_ramification_idx_ne_zero (P : (factors (map (algebra_map R S) p)).to_finset) : ne_zero (ramification_idx (algebra_map R S) p P) := ⟨factors.ramification_idx_ne_zero p P⟩ local attribute [instance] quotient.algebra_quotient_of_ramification_idx_ne_zero instance factors.is_scalar_tower (P : (factors (map (algebra_map R S) p)).to_finset) : is_scalar_tower R (R ⧸ p) (S ⧸ (P : ideal S)) := is_scalar_tower.of_algebra_map_eq (λ x, by simp) local attribute [instance] ideal.quotient.field lemma factors.finrank_pow_ramification_idx [p.is_maximal] (P : (factors (map (algebra_map R S) p)).to_finset) : finrank (R ⧸ p) (S ⧸ (P : ideal S) ^ ramification_idx (algebra_map R S) p P) = ramification_idx (algebra_map R S) p P * inertia_deg (algebra_map R S) p P := begin rw [finrank_prime_pow_ramification_idx, inertia_deg_algebra_map], exact factors.ne_bot p P, end instance factors.finite_dimensional_quotient [is_noetherian R S] [p.is_maximal] (P : (factors (map (algebra_map R S) p)).to_finset) : finite_dimensional (R ⧸ p) (S ⧸ (P : ideal S)) := is_noetherian.iff_fg.mp $ is_noetherian_of_tower R $ is_noetherian_of_surjective S (ideal.quotient.mkₐ _ _).to_linear_map $ linear_map.range_eq_top.mpr ideal.quotient.mk_surjective lemma factors.inertia_deg_ne_zero [is_noetherian R S] [p.is_maximal] (P : (factors (map (algebra_map R S) p)).to_finset) : inertia_deg (algebra_map R S) p P ≠ 0 := by { rw inertia_deg_algebra_map, exact (finite_dimensional.finrank_pos_iff.mpr infer_instance).ne' } instance factors.finite_dimensional_quotient_pow [is_noetherian R S] [p.is_maximal] (P : (factors (map (algebra_map R S) p)).to_finset) : finite_dimensional (R ⧸ p) (S ⧸ (P : ideal S) ^ ramification_idx (algebra_map R S) p P) := begin refine finite_dimensional.finite_dimensional_of_finrank _, rw [pos_iff_ne_zero, factors.finrank_pow_ramification_idx], exact mul_ne_zero (factors.ramification_idx_ne_zero p P) (factors.inertia_deg_ne_zero p P) end universes w /-- **Chinese remainder theorem** for a ring of integers: if the prime ideal `p : ideal R` factors in `S` as `∏ i, P i ^ e i`, then `S ⧸ I` factors as `Π i, R ⧸ (P i ^ e i)`. -/ noncomputable def factors.pi_quotient_equiv (p : ideal R) (hp : map (algebra_map R S) p ≠ ⊥) : (S ⧸ map (algebra_map R S) p) ≃+* Π (P : (factors (map (algebra_map R S) p)).to_finset), S ⧸ ((P : ideal S) ^ ramification_idx (algebra_map R S) p P) := (is_dedekind_domain.quotient_equiv_pi_factors hp).trans $ (@ring_equiv.Pi_congr_right (factors (map (algebra_map R S) p)).to_finset (λ P, S ⧸ (P : ideal S) ^ (factors (map (algebra_map R S) p)).count P) (λ P, S ⧸ (P : ideal S) ^ ramification_idx (algebra_map R S) p P) _ _ (λ P : (factors (map (algebra_map R S) p)).to_finset, ideal.quot_equiv_of_eq $ by rw is_dedekind_domain.ramification_idx_eq_factors_count hp (factors.is_prime p P) (factors.ne_bot p P))) @[simp] lemma factors.pi_quotient_equiv_mk (p : ideal R) (hp : map (algebra_map R S) p ≠ ⊥) (x : S) : factors.pi_quotient_equiv p hp (ideal.quotient.mk _ x) = λ P, ideal.quotient.mk _ x := rfl @[simp] lemma factors.pi_quotient_equiv_map (p : ideal R) (hp : map (algebra_map R S) p ≠ ⊥) (x : R) : factors.pi_quotient_equiv p hp (algebra_map _ _ x) = λ P, ideal.quotient.mk _ (algebra_map _ _ x) := rfl variables (S) /-- **Chinese remainder theorem** for a ring of integers: if the prime ideal `p : ideal R` factors in `S` as `∏ i, P i ^ e i`, then `S ⧸ I` factors `R ⧸ I`-linearly as `Π i, R ⧸ (P i ^ e i)`. -/ noncomputable def factors.pi_quotient_linear_equiv (p : ideal R) (hp : map (algebra_map R S) p ≠ ⊥) : (S ⧸ map (algebra_map R S) p) ≃ₗ[R ⧸ p] Π (P : (factors (map (algebra_map R S) p)).to_finset), S ⧸ ((P : ideal S) ^ ramification_idx (algebra_map R S) p P) := { map_smul' := begin rintro ⟨c⟩ ⟨x⟩, ext P, simp only [ideal.quotient.mk_algebra_map, factors.pi_quotient_equiv_mk, factors.pi_quotient_equiv_map, submodule.quotient.quot_mk_eq_mk, pi.algebra_map_apply, ring_equiv.to_fun_eq_coe, pi.mul_apply, ideal.quotient.algebra_map_quotient_map_quotient, ideal.quotient.mk_eq_mk, algebra.smul_def, _root_.map_mul, ring_hom_comp_triple.comp_apply], congr end, .. factors.pi_quotient_equiv p hp } variables {S} open_locale big_operators /-- The **fundamental identity** of ramification index `e` and inertia degree `f`: for `P` ranging over the primes lying over `p`, `∑ P, e P * f P = [Frac(S) : Frac(R)]`; here `S` is a finite `R`-module (and thus `Frac(S) : Frac(R)` is a finite extension) and `p` is maximal. -/ theorem sum_ramification_inertia (K L : Type*) [field K] [field L] [is_domain R] [is_dedekind_domain R] [algebra R K] [is_fraction_ring R K] [algebra S L] [is_fraction_ring S L] [algebra K L] [algebra R L] [is_scalar_tower R S L] [is_scalar_tower R K L] [is_noetherian R S] [is_integral_closure S R L] [p.is_maximal] (hp0 : p ≠ ⊥) : ∑ P in (factors (map (algebra_map R S) p)).to_finset, ramification_idx (algebra_map R S) p P * inertia_deg (algebra_map R S) p P = finrank K L := begin set e := ramification_idx (algebra_map R S) p, set f := inertia_deg (algebra_map R S) p, have inj_RL : function.injective (algebra_map R L), { rw [is_scalar_tower.algebra_map_eq R K L, ring_hom.coe_comp], exact (ring_hom.injective _).comp (is_fraction_ring.injective R K) }, have inj_RS : function.injective (algebra_map R S), { refine function.injective.of_comp (show function.injective (algebra_map S L ∘ _), from _), rw [← ring_hom.coe_comp, ← is_scalar_tower.algebra_map_eq], exact inj_RL }, calc ∑ P in (factors (map (algebra_map R S) p)).to_finset, e P * f P = ∑ P in (factors (map (algebra_map R S) p)).to_finset.attach, finrank (R ⧸ p) (S ⧸ (P : ideal S)^(e P)) : _ ... = finrank (R ⧸ p) (Π P : (factors (map (algebra_map R S) p)).to_finset, (S ⧸ (P : ideal S)^(e P))) : (finrank_pi_fintype (R ⧸ p)).symm ... = finrank (R ⧸ p) (S ⧸ map (algebra_map R S) p) : _ ... = finrank K L : _, { rw ← finset.sum_attach, refine finset.sum_congr rfl (λ P _, _), rw factors.finrank_pow_ramification_idx }, { refine linear_equiv.finrank_eq (factors.pi_quotient_linear_equiv S p _).symm, rwa [ne.def, ideal.map_eq_bot_iff_le_ker, (ring_hom.injective_iff_ker_eq_bot _).mp inj_RS, le_bot_iff] }, { exact finrank_quotient_map p K L }, end end factors_map end ideal
adfa0d9e96d7cbc06b066779a35981a2976841e6
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/run/ind2.lean
d9a8dbcc957c1c5461253bbc2eaa81351213843e
[ "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
328
lean
inductive nat : Type := zero : nat, succ : nat → nat namespace nat end nat open nat inductive vector (A : Type) : nat → Type := vnil : vector A zero, vcons : Π {n : nat}, A → vector A n → vector A (succ n) namespace vector end vector open vector check vector.{1} check vnil.{1} check vcons.{1} check vector.rec.{1 1}
ff2c48a2e2068b9510c3e88adf708df9da1a9e6b
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/order/prime_ideal.lean
447452b0a847128a44859254bf15245f80bb108f
[ "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
6,261
lean
/- Copyright (c) 2021 Noam Atar. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Noam Atar -/ import order.basic import order.ideal import order.pfilter import order.boolean_algebra /-! # Prime ideals ## Main definitions Throughout this file, `P` is at least a preorder, but some sections require more structure, such as a bottom element, a top element, or a join-semilattice structure. - `order.ideal.prime_pair`: A pair of an `ideal` and a `pfilter` which form a partition of `P`. This is useful as giving the data of a prime ideal is the same as giving the data of a prime filter. - `order.ideal.is_prime`: a predicate for prime ideals. Dual to the notion of a prime filter. - `order.pfilter.is_prime`: a predicate for prime filters. Dual to the notion of a prime ideal. ## References - <https://en.wikipedia.org/wiki/Ideal_(order_theory)> ## Tags ideal, prime -/ open order.pfilter namespace order variables {P : Type*} namespace ideal /-- A pair of an `ideal` and a `pfilter` which form a partition of `P`. -/ @[nolint has_inhabited_instance] structure prime_pair (P : Type*) [preorder P] := (I : ideal P) (F : pfilter P) (is_compl_I_F : is_compl (I : set P) F) namespace prime_pair variables [preorder P] (IF : prime_pair P) lemma compl_I_eq_F : (IF.I : set P)ᶜ = IF.F := IF.is_compl_I_F.compl_eq lemma compl_F_eq_I : (IF.F : set P)ᶜ = IF.I := IF.is_compl_I_F.eq_compl.symm lemma I_is_proper : is_proper IF.I := begin cases IF.F.nonempty, apply is_proper_of_not_mem (_ : w ∉ IF.I), rwa ← IF.compl_I_eq_F at h, end lemma disjoint : disjoint (IF.I : set P) IF.F := IF.is_compl_I_F.disjoint lemma I_union_F : (IF.I : set P) ∪ IF.F = set.univ := IF.is_compl_I_F.sup_eq_top lemma F_union_I : (IF.F : set P) ∪ IF.I = set.univ := IF.is_compl_I_F.symm.sup_eq_top end prime_pair /-- An ideal `I` is prime if its complement is a filter. -/ @[mk_iff] class is_prime [preorder P] (I : ideal P) extends is_proper I : Prop := (compl_filter : is_pfilter (I : set P)ᶜ) section preorder variable [preorder P] /-- Create an element of type `order.ideal.prime_pair` from an ideal satisfying the predicate `order.ideal.is_prime`. -/ def is_prime.to_prime_pair {I : ideal P} (h : is_prime I) : prime_pair P := { I := I, F := h.compl_filter.to_pfilter, is_compl_I_F := is_compl_compl } lemma prime_pair.I_is_prime (IF : prime_pair P) : is_prime IF.I := { compl_filter := by { rw IF.compl_I_eq_F, exact IF.F.is_pfilter }, ..IF.I_is_proper } end preorder section semilattice_inf variables [semilattice_inf P] {x y : P} {I : ideal P} lemma is_prime.mem_or_mem (hI : is_prime I) {x y : P} : x ⊓ y ∈ I → x ∈ I ∨ y ∈ I := begin contrapose!, let F := hI.compl_filter.to_pfilter, show x ∈ F ∧ y ∈ F → x ⊓ y ∈ F, exact λ h, inf_mem _ _ h.1 h.2, end lemma is_prime.of_mem_or_mem [is_proper I] (hI : ∀ {x y : P}, x ⊓ y ∈ I → x ∈ I ∨ y ∈ I) : is_prime I := begin rw is_prime_iff, use ‹_›, apply is_pfilter.of_def, { exact set.nonempty_compl.2 (I.is_proper_iff.1 ‹_›) }, { intros x _ y _, refine ⟨x ⊓ y, _, inf_le_left, inf_le_right⟩, have := mt hI, tauto! }, { exact @mem_compl_of_ge _ _ _ } end lemma is_prime_iff_mem_or_mem [is_proper I] : is_prime I ↔ ∀ {x y : P}, x ⊓ y ∈ I → x ∈ I ∨ y ∈ I := ⟨is_prime.mem_or_mem, is_prime.of_mem_or_mem⟩ end semilattice_inf section distrib_lattice variables [distrib_lattice P] {I : ideal P} @[priority 100] instance is_maximal.is_prime [is_maximal I] : is_prime I := begin rw is_prime_iff_mem_or_mem, intros x y, contrapose!, rintro ⟨hx, hynI⟩ hxy, apply hynI, let J := I ⊔ principal x, have hJuniv : (J : set P) = set.univ := is_maximal.maximal_proper (lt_sup_principal_of_not_mem ‹_›), have hyJ : y ∈ ↑J := set.eq_univ_iff_forall.mp hJuniv y, rw coe_sup_eq at hyJ, rcases hyJ with ⟨a, ha, b, hb, hy⟩, rw hy, apply sup_mem _ _ ha, refine I.mem_of_le (le_inf hb _) hxy, rw hy, exact le_sup_right end end distrib_lattice section boolean_algebra variables [boolean_algebra P] {x : P} {I : ideal P} lemma is_prime.mem_or_compl_mem (hI : is_prime I) : x ∈ I ∨ xᶜ ∈ I := begin apply hI.mem_or_mem, rw inf_compl_eq_bot, exact bot_mem, end lemma is_prime.mem_compl_of_not_mem (hI : is_prime I) (hxnI : x ∉ I) : xᶜ ∈ I := hI.mem_or_compl_mem.resolve_left hxnI lemma is_prime_of_mem_or_compl_mem [is_proper I] (h : ∀ {x : P}, x ∈ I ∨ xᶜ ∈ I) : is_prime I := begin simp only [is_prime_iff_mem_or_mem, or_iff_not_imp_left], intros x y hxy hxI, have hxcI : xᶜ ∈ I := h.resolve_left hxI, have ass : (x ⊓ y) ⊔ (y ⊓ xᶜ) ∈ I := sup_mem _ _ hxy (mem_of_le I inf_le_right hxcI), rwa [inf_comm, sup_inf_inf_compl] at ass end lemma is_prime_iff_mem_or_compl_mem [is_proper I] : is_prime I ↔ ∀ {x : P}, x ∈ I ∨ xᶜ ∈ I := ⟨λ h _, h.mem_or_compl_mem, is_prime_of_mem_or_compl_mem⟩ @[priority 100] instance is_prime.is_maximal [is_prime I] : is_maximal I := begin simp only [is_maximal_iff, set.eq_univ_iff_forall, is_prime.to_is_proper, true_and], intros J hIJ x, rcases set.exists_of_ssubset hIJ with ⟨y, hyJ, hyI⟩, suffices ass : (x ⊓ y) ⊔ (x ⊓ yᶜ) ∈ J, { rwa sup_inf_inf_compl at ass }, exact sup_mem _ _ (J.mem_of_le inf_le_right hyJ) (hIJ.le (I.mem_of_le inf_le_right (is_prime.mem_compl_of_not_mem ‹_› hyI))), end end boolean_algebra end ideal namespace pfilter variable [preorder P] /-- A filter `F` is prime if its complement is an ideal. -/ @[mk_iff] class is_prime (F : pfilter P) : Prop := (compl_ideal : is_ideal (F : set P)ᶜ) /-- Create an element of type `order.ideal.prime_pair` from a filter satisfying the predicate `order.pfilter.is_prime`. -/ def is_prime.to_prime_pair {F : pfilter P} (h : is_prime F) : ideal.prime_pair P := { I := h.compl_ideal.to_ideal, F := F, is_compl_I_F := is_compl_compl.symm } lemma _root_.order.ideal.prime_pair.F_is_prime (IF : ideal.prime_pair P) : is_prime IF.F := { compl_ideal := by { rw IF.compl_F_eq_I, exact IF.I.is_ideal } } end pfilter end order
b2f0d930312d3d6ea09bc7d2fcae82aab668c566
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/src/Init/Data/Fin/Basic.lean
8bc19067ff5f089b92973c087d2153689a1ac24a
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,412
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import Init.Data.Nat.Div import Init.Data.Nat.Bitwise import Init.Coe open Nat namespace Fin instance coeToNat {n} : Coe (Fin n) Nat := ⟨fun v => v.val⟩ def elim0.{u} {α : Sort u} : Fin 0 → α | ⟨_, h⟩ => absurd h (notLtZero _) variable {n : Nat} protected def ofNat {n : Nat} (a : Nat) : Fin (succ n) := ⟨a % succ n, Nat.modLt _ (Nat.zeroLtSucc _)⟩ protected def ofNat' {n : Nat} (a : Nat) (h : n > 0) : Fin n := ⟨a % n, Nat.modLt _ h⟩ private theorem mlt {b : Nat} : {a : Nat} → a < n → b % n < n | 0, h => Nat.modLt _ h | a+1, h => have n > 0 from Nat.ltTrans (Nat.zeroLtSucc _) h; Nat.modLt _ this protected def add : Fin n → Fin n → Fin n | ⟨a, h⟩, ⟨b, _⟩ => ⟨(a + b) % n, mlt h⟩ protected def mul : Fin n → Fin n → Fin n | ⟨a, h⟩, ⟨b, _⟩ => ⟨(a * b) % n, mlt h⟩ protected def sub : Fin n → Fin n → Fin n | ⟨a, h⟩, ⟨b, _⟩ => ⟨(a + (n - b)) % n, mlt h⟩ /- Remark: mod/div/modn/land/lor can be defined without using (% n), but we are trying to minimize the number of Nat theorems needed to boostrap Lean. -/ protected def mod : Fin n → Fin n → Fin n | ⟨a, h⟩, ⟨b, _⟩ => ⟨(a % b) % n, mlt h⟩ protected def div : Fin n → Fin n → Fin n | ⟨a, h⟩, ⟨b, _⟩ => ⟨(a / b) % n, mlt h⟩ protected def modn : Fin n → Nat → Fin n | ⟨a, h⟩, m => ⟨(a % m) % n, mlt h⟩ def land : Fin n → Fin n → Fin n | ⟨a, h⟩, ⟨b, _⟩ => ⟨(Nat.land a b) % n, mlt h⟩ def lor : Fin n → Fin n → Fin n | ⟨a, h⟩, ⟨b, _⟩ => ⟨(Nat.lor a b) % n, mlt h⟩ instance : Add (Fin n) where add := Fin.add instance : Sub (Fin n) where sub := Fin.sub instance : Mul (Fin n) where mul := Fin.mul instance : Mod (Fin n) where mod := Fin.mod instance : Div (Fin n) where div := Fin.div instance : HMod (Fin n) Nat (Fin n) where hMod := Fin.modn instance : OfNat (Fin (noindex! (n+1))) i where ofNat := Fin.ofNat i theorem vneOfNe {i j : Fin n} (h : i ≠ j) : val i ≠ val j := fun h' => absurd (eqOfVeq h') h theorem modnLt : ∀ {m : Nat} (i : Fin n), m > 0 → (i % m).val < m | m, ⟨a, h⟩, hp => Nat.ltOfLeOfLt (modLe _ _) (modLt _ hp) end Fin open Fin
82bc9ed8189d21c86c4b400a96639406e8b753d4
8e381650eb2c1c5361be64ff97e47d956bf2ab9f
/src/sheaves/sheaf_of_rings_on_standard_basis.lean
504b0af644ccba15b051af099ce620b436eca348
[]
no_license
alreadydone/lean-scheme
04c51ab08eca7ccf6c21344d45d202780fa667af
52d7624f57415eea27ed4dfa916cd94189221a1c
refs/heads/master
1,599,418,221,423
1,562,248,559,000
1,562,248,559,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,847
lean
/- Extension of a sheaf of rings on the basis to a sheaf of rings on the whole space. https://stacks.math.columbia.edu/tag/009M https://stacks.math.columbia.edu/tag/009N TODO : Clean this up and split it in smaller files. -/ import topology.opens import sheaves.stalk_of_rings import sheaves.stalk_of_rings_on_standard_basis import sheaves.presheaf_of_rings_on_basis import sheaves.presheaf_of_rings_extension import sheaves.sheaf_on_basis import sheaves.sheaf_on_standard_basis import sheaves.sheaf_of_rings open topological_space classical noncomputable theory universe u section presheaf_of_rings_extension variables {α : Type u} [T : topological_space α] variables {B : set (opens α)} {HB : opens.is_basis B} variables (Bstd : opens.univ ∈ B ∧ ∀ {U V}, U ∈ B → V ∈ B → U ∩ V ∈ B) include Bstd theorem extension_is_sheaf_of_rings (F : presheaf_of_rings_on_basis α HB) (HF : sheaf_on_standard_basis.is_sheaf_on_standard_basis Bstd F.to_presheaf_on_basis) : is_sheaf_of_rings (F ᵣₑₓₜ Bstd) := begin show is_sheaf (F ᵣₑₓₜ Bstd).to_presheaf, constructor, { intros U OC s t Hres, apply subtype.eq, apply funext, intros x, apply funext, intros HxU, rw OC.Hcov.symm at HxU, rcases HxU with ⟨Uj1, ⟨⟨⟨Uj2, OUj⟩, ⟨⟨j, HUj⟩, Heq⟩⟩, HxUj⟩⟩, rcases Heq, rcases Heq, have Hstj := congr_fun (subtype.mk_eq_mk.1 (Hres j)), have HxUj1 : x ∈ OC.Uis j := HUj.symm ▸ HxUj, have Hstjx := congr_fun (Hstj x) HxUj1, exact Hstjx, }, { intros U OC s Hsec, existsi (global_section (F.to_presheaf_on_basis) U OC s Hsec), intros i, apply subtype.eq, apply funext, intros x, apply funext, intros HxUi, have HxU : x ∈ U := OC.Hcov ▸ (opens_supr_subset OC.Uis i) HxUi, let HyUi := λ t, ∃ (H : t ∈ set.range OC.Uis), x ∈ t, dunfold presheaf_of_rings_on_basis_to_presheaf_of_rings; dsimp, dunfold global_section; dsimp, -- Same process of dealing with subtype.rec. let HyUi := λ t, ∃ (H : t ∈ subtype.val '' set.range OC.Uis), x ∈ t, rcases (classical.indefinite_description HyUi _) with ⟨S, HS⟩; dsimp, let HyS := λ H : S ∈ subtype.val '' set.range OC.Uis, x ∈ S, rcases (classical.indefinite_description HyS HS) with ⟨HSUiR, HySUiR⟩; dsimp, let HOUksub := λ t : subtype is_open, t ∈ set.range (OC.Uis) ∧ t.val = S, rcases (classical.indefinite_description HOUksub _) with ⟨OUl, ⟨HOUl, HOUleq⟩⟩; dsimp, let HSUi := λ i, OC.Uis i = OUl, cases (classical.indefinite_description HSUi _) with l HSUil; dsimp, -- Now we just need to apply Hsec in the right way. dunfold presheaf_of_rings_on_basis_to_presheaf_of_rings at Hsec, dunfold res_to_inter_left at Hsec, dunfold res_to_inter_right at Hsec, dsimp at Hsec, replace Hsec := Hsec i l, rw subtype.ext at Hsec, dsimp at Hsec, replace Hsec := congr_fun Hsec x, dsimp at Hsec, replace Hsec := congr_fun Hsec, have HxOUk : x ∈ OUl.val := HOUleq.symm ▸ HySUiR, have HxUl : x ∈ OC.Uis l := HSUil.symm ▸ HxOUk, exact (Hsec ⟨HxUi, HxUl⟩).symm, }, end section extension_coincides -- The extension is done in a way that F(U) ≅ Fext(U). -- The map ψ : F(U) → Π x ∈ U, Fx def to_stalk_product (F : presheaf_on_basis α HB) {U : opens α} (BU : U ∈ B) : F.F BU → Π (x ∈ U), stalk_on_basis F x := λ s x Hx, ⟦{U := U, BU := BU, Hx := Hx, s := s}⟧ lemma to_stalk_product.injective (F : presheaf_on_basis α HB) (HF : sheaf_on_standard_basis.is_sheaf_on_standard_basis Bstd F) {U : opens α} (BU : U ∈ B) : function.injective (to_stalk_product Bstd F BU) := begin intros s₁ s₂ Hs, have Hsx := λ (HxU : U), congr_fun (congr_fun Hs HxU.1) HxU.2, let OC : covering_standard_basis B U := { γ := U, Uis := λ HxU, some (quotient.eq.1 (Hsx HxU)), BUis := λ HxU, some (some_spec (quotient.eq.1 (Hsx HxU))), Hcov := begin ext z, split, { rintros ⟨Ui, ⟨⟨OUi, ⟨⟨i, HUi⟩, HUival⟩⟩, HzUi⟩⟩, rw [←HUival, ←HUi] at HzUi, exact some (some_spec (some_spec (some_spec (quotient.eq.1 (Hsx i))))) HzUi, }, { intros Hz, use [(some (quotient.eq.1 (Hsx ⟨z, Hz⟩))).val], have Hin : (some (quotient.eq.1 (Hsx ⟨z, Hz⟩))).val ∈ subtype.val '' set.range (λ (HxU : U), some ((quotient.eq.1 (Hsx HxU)))), use [classical.some ((quotient.eq.1 (Hsx ⟨z, Hz⟩)))], split, { use ⟨z, Hz⟩, }, { refl, }, use Hin, exact some (some_spec (some_spec (quotient.eq.1 (Hsx ⟨z, Hz⟩)))), }, end, }, apply (HF BU OC).1, intros i, replace Hs := congr_fun (congr_fun Hs i.1) i.2, exact some_spec (some_spec (some_spec (some_spec (some_spec (quotient.eq.1 (Hsx i)))))), end -- The map φ : F(U) → im(ψ). def to_presheaf_of_rings_extension (F : presheaf_of_rings_on_basis α HB) {U : opens α} (BU : U ∈ B) : F.F BU → (F ᵣₑₓₜ Bstd).F U := λ s, ⟨to_stalk_product Bstd F.to_presheaf_on_basis BU s, λ x Hx, ⟨U, BU, Hx, s, λ y Hy, funext $ λ Hy', quotient.sound $ ⟨U, BU, Hy', set.subset.refl U, set.subset.refl U, rfl⟩⟩⟩ lemma to_presheaf_of_rings_extension.injective (F : presheaf_of_rings_on_basis α HB) (HF : sheaf_on_standard_basis.is_sheaf_on_standard_basis Bstd F.to_presheaf_on_basis) {U : opens α} (BU : U ∈ B) : function.injective (to_presheaf_of_rings_extension Bstd F BU) := begin intros s₁ s₂ Hs, erw subtype.mk_eq_mk at Hs, have Hinj := to_stalk_product.injective Bstd F.to_presheaf_on_basis (λ V BV OC, HF BV OC) BU, exact Hinj Hs, end lemma to_presheaf_of_rings_extension.surjective (F : presheaf_of_rings_on_basis α HB) (HF : sheaf_on_standard_basis.is_sheaf_on_standard_basis Bstd F.to_presheaf_on_basis) {U : opens α} (BU : U ∈ B) : function.surjective (to_presheaf_of_rings_extension Bstd F BU) := begin intros s, let V := λ (HxU : U), some (s.2 HxU.1 HxU.2), let BV := λ (HxU : U), some (some_spec (s.2 HxU.1 HxU.2)), let HxV := λ (HxU : U), some (some_spec (some_spec (s.2 HxU.1 HxU.2))), let σ := λ (HxU : U), some (some_spec (some_spec (some_spec (s.2 HxU.1 HxU.2)))), let Hσ := λ (HxU : U), some_spec (some_spec (some_spec (some_spec (s.2 HxU.1 HxU.2)))), let OC : covering_standard_basis B U := { γ := U, Uis := λ HxU, (V HxU) ∩ U, BUis := λ HxU, Bstd.2 (BV HxU) BU, Hcov := begin ext z, split, { rintros ⟨Ui, ⟨⟨OUi, ⟨⟨i, HUi⟩, HUival⟩⟩, HzUi⟩⟩, rw [←HUival, ←HUi] at HzUi, exact HzUi.2, }, { intros Hz, use [(some (s.2 z Hz) ∩ U).val], have Hin : (some (s.2 z Hz) ∩ U).val ∈ subtype.val '' set.range (λ (HxU : U), ((some (s.2 HxU.1 HxU.2) ∩ U : opens α))), use [(some (s.2 z Hz) ∩ U : opens α)], split, { use ⟨z, Hz⟩, }, { refl, }, use Hin, exact ⟨some (some_spec (some_spec (s.2 z Hz))), Hz⟩, }, end, }, -- Now let's try to apply sheaf condition. let res := λ (HxU : OC.γ), F.res (BV HxU) (Bstd.2 (BV HxU) BU) (set.inter_subset_left _ _), let sx := λ (HxU : OC.γ), res HxU (σ HxU), have Hglue := (HF BU OC).2 sx, have Hsx : ∀ j k, sheaf_on_standard_basis.res_to_inter_left Bstd F.to_presheaf_on_basis (OC.BUis j) (OC.BUis k) (sx j) = sheaf_on_standard_basis.res_to_inter_right Bstd F.to_presheaf_on_basis (OC.BUis j) (OC.BUis k) (sx k), intros j k, dsimp only [sheaf_on_standard_basis.res_to_inter_left], dsimp only [sheaf_on_standard_basis.res_to_inter_right], dsimp only [sx, res], iterate 2 { rw ←presheaf_on_basis.Hcomp', }, show (F.to_presheaf_on_basis).res (BV j) (Bstd.2 (OC.BUis j) (OC.BUis k)) _ (σ j) = (F.to_presheaf_on_basis).res (BV k) (Bstd.2 (OC.BUis j) (OC.BUis k)) _ (σ k), -- We can cover the U ∩ Vj ∩ Vk and use locality. -- But first let's check that all the stalks coincide in the intersectons. have Hstalks : ∀ {y} (Hy : y ∈ (OC.Uis j) ∩ (OC.Uis k)), (⟦{U := V j, BU := BV j, Hx := Hy.1.1, s := σ j}⟧ : stalk_on_basis F.to_presheaf_on_basis y) = ⟦{U := V k, BU := BV k, Hx := Hy.2.1, s := σ k}⟧, intros y Hy, have Hj := congr_fun (Hσ j y ⟨Hy.1.2, Hy.1.1⟩) Hy.1.2; dsimp at Hj, have Hk := congr_fun (Hσ k y ⟨Hy.2.2, Hy.2.1⟩) Hy.2.2; dsimp at Hk, erw [←Hj, ←Hk], -- Therefore there exists Wjk where σj|Wjk = σk|Wjk. We will use these as a cover. let Ujk : opens α := (OC.Uis j) ∩ (OC.Uis k), let BUjk := Bstd.2 (OC.BUis j) (OC.BUis k), -- let Hjk := λ (HxUjk : Ujk), quotient.eq.1 (Hstalks HxUjk.2), let Wjk := λ (HxUjk : Ujk), some (Hjk HxUjk) ∩ U, let BWjk := λ (HxUjk : Ujk), Bstd.2 (some (some_spec (Hjk HxUjk))) BU, let HxWjk := λ (HxUjk : Ujk), some (some_spec (some_spec (Hjk HxUjk))), let HWjkUj := λ (HxUjk : Ujk), some (some_spec (some_spec (some_spec (Hjk HxUjk)))), let HWjkUk := λ (HxUjk : Ujk), some (some_spec (some_spec (some_spec (some_spec (Hjk HxUjk))))), let HWjk := λ (HxUjk : Ujk), some_spec (some_spec (some_spec (some_spec (some_spec (Hjk HxUjk))))), let OCjk : covering_standard_basis B ((OC.Uis j) ∩ (OC.Uis k)) := { γ := Ujk, Uis := Wjk, BUis := BWjk, Hcov := begin ext z, split, { rintros ⟨W, ⟨⟨OW, ⟨⟨i, HWi⟩, HWival⟩⟩, HzW⟩⟩, rw [←HWival, ←HWi] at HzW, have HzUj := (HWjkUj i) HzW.1, have HzUk := (HWjkUk i) HzW.1, exact ⟨⟨HzUj, HzW.2⟩, ⟨HzUk, HzW.2⟩⟩, }, { intros Hz, use [(some (Hjk ⟨z, Hz⟩) ∩ U).val], have Hin : (some (Hjk ⟨z, Hz⟩) ∩ U).val ∈ subtype.val '' set.range (λ (HxUjk : Ujk), ((some (Hjk HxUjk) ∩ U : opens α))), use [(some (Hjk ⟨z, Hz⟩) ∩ U : opens α)], split, { use ⟨z, Hz⟩, }, { refl, }, use Hin, have HzWjk := HxWjk ⟨z, Hz⟩, have HzU := Hz.1.2, exact ⟨HzWjk, HzU⟩, } end, }, apply (HF BUjk OCjk).1, intros i, rw ←presheaf_on_basis.Hcomp', rw ←presheaf_on_basis.Hcomp', have Hres : F.res (some (some_spec (Hjk i))) (BWjk i) (set.inter_subset_left _ _) (F.res (BV j) (some (some_spec (Hjk i))) (HWjkUj i) (σ j)) = F.res (some (some_spec (Hjk i))) (BWjk i) (set.inter_subset_left _ _) (F.res (BV k) (some (some_spec (Hjk i))) (HWjkUk i) (σ k)), rw (HWjk i), rw ←presheaf_on_basis.Hcomp' at Hres, rw ←presheaf_on_basis.Hcomp' at Hres, use Hres, -- Ready... rcases (Hglue Hsx) with ⟨S, HS⟩, existsi S, apply subtype.eq, dsimp [to_presheaf_of_rings_extension], apply funext, intros x, dsimp [to_stalk_product], apply funext, intros Hx, replace HS := HS ⟨x, Hx⟩, dsimp [sx, res] at HS, rw Hσ ⟨x, Hx⟩, swap, { exact ⟨Hx, HxV ⟨x, Hx⟩⟩, }, dsimp, apply quotient.sound, use [(V ⟨x, Hx⟩) ∩ U], use [Bstd.2 (BV ⟨x, Hx⟩) BU], use [⟨HxV ⟨x, Hx⟩, Hx⟩], use [set.inter_subset_right _ _], use [set.inter_subset_left _ _], dsimp, erw HS, end lemma to_presheaf_of_rings_extension.bijective (F : presheaf_of_rings_on_basis α HB) (HF : sheaf_on_standard_basis.is_sheaf_on_standard_basis Bstd F.to_presheaf_on_basis) {U : opens α} (BU : U ∈ B) : function.bijective (to_presheaf_of_rings_extension Bstd F BU) := ⟨to_presheaf_of_rings_extension.injective Bstd F (λ U BU OC, HF BU OC) BU, to_presheaf_of_rings_extension.surjective Bstd F (λ U BU OC, HF BU OC) BU ⟩ lemma to_presheaf_of_rings_extension.equiv (F : presheaf_of_rings_on_basis α HB) (HF : sheaf_on_standard_basis.is_sheaf_on_standard_basis Bstd F.to_presheaf_on_basis) {U : opens α} (BU : U ∈ B) : F.F BU ≃ (F ᵣₑₓₜ Bstd).F U := equiv.of_bijective (to_presheaf_of_rings_extension.bijective Bstd F (λ U BU OC, HF BU OC) BU) -- We now that they are equivalent as sets. -- Now we to assert that they're isomorphic as rings. -- It suffices to show that it is a ring homomorphism. lemma to_presheaf_of_rings_extension.is_ring_hom (F : presheaf_of_rings_on_basis α HB) (HF : sheaf_on_standard_basis.is_sheaf_on_standard_basis Bstd F.to_presheaf_on_basis) {U : opens α} (BU : U ∈ B) : is_ring_hom (to_presheaf_of_rings_extension Bstd F BU) := { map_one := begin apply subtype.eq, funext x Hx, apply quotient.sound, use [U, BU, Hx, set.subset.refl _, set.subset_univ _], iterate 2 { erw (F.res_is_ring_hom _ _ _).map_one, }, end, map_mul := begin intros x y, apply subtype.eq, funext z Hz, apply quotient.sound, use [U, BU, Hz], use [set.subset.refl _, set.subset_inter (set.subset.refl _) (set.subset.refl _)], erw ←(F.res_is_ring_hom _ _ _).map_mul, erw ←presheaf_on_basis.Hcomp', end, map_add := begin intros x y, apply subtype.eq, funext z Hz, apply quotient.sound, use [U, BU, Hz], use [set.subset.refl _, set.subset_inter (set.subset.refl _) (set.subset.refl _)], erw ←(F.res_is_ring_hom _ _ _).map_add, erw ←presheaf_on_basis.Hcomp', end, } -- Moreover, for all x, Fₓ ≅ Fextₓ. This is crucial for open stalk_of_rings_on_standard_basis lemma to_stalk_extension (F : presheaf_of_rings_on_basis α HB) (HF : sheaf_on_standard_basis.is_sheaf_on_standard_basis Bstd F.to_presheaf_on_basis) (x : α) : stalk_of_rings_on_standard_basis Bstd F x → stalk_of_rings (F ᵣₑₓₜ Bstd) x := begin intros BUs, let Us := quotient.out BUs, exact ⟦{U := Us.U, HxU := Us.Hx, s := (to_presheaf_of_rings_extension Bstd F Us.BU) Us.s}⟧, end lemma to_stalk_extension.injective (F : presheaf_of_rings_on_basis α HB) (HF : sheaf_on_standard_basis.is_sheaf_on_standard_basis Bstd F.to_presheaf_on_basis) (x : α) : function.injective (to_stalk_extension Bstd F @HF x) := begin intros Us₁' Us₂', apply quotient.induction_on₂ Us₁' Us₂', rintros Us₁ Us₂ HUs, rcases (quotient.mk_out Us₁) with ⟨W₁, BW₁, HxW₁, HW₁Us₁, HW₁U₁, Hres₁⟩, rcases (quotient.mk_out Us₂) with ⟨W₂, BW₂, HxW₂, HW₂Us₂, HW₂U₂, Hres₂⟩, dunfold to_stalk_extension at HUs, rw quotient.eq at HUs, rcases HUs with ⟨W, HxW, HWU₁, HWU₂, Hres⟩, dsimp at HWU₁, dsimp at HWU₂, dunfold to_presheaf_of_rings_extension at Hres, dunfold to_stalk_product at Hres, erw subtype.mk.inj_eq at Hres, replace Hres := congr_fun (congr_fun Hres x) HxW, dsimp at Hres, rw quotient.eq at Hres, rcases Hres with ⟨W₃, BW₃, HxW₃, HW₃U₁, HW₃U₂, Hres₃⟩, dsimp at HW₃U₁, dsimp at HW₃U₂, dsimp at Hres₃, apply quotient.sound, have BW₁₂₃ : W₁ ∩ W₂ ∩ W₃ ∈ B := Bstd.2 (Bstd.2 BW₁ BW₂) BW₃, have HW₁₂₃U₁ : W₁ ∩ W₂ ∩ W₃ ⊆ Us₁.U := λ x Hx, HW₁U₁ Hx.1.1, have HW₁₂₃U₂ : W₁ ∩ W₂ ∩ W₃ ⊆ Us₂.U := λ x Hx, HW₂U₂ Hx.1.2, use [W₁ ∩ W₂ ∩ W₃, BW₁₂₃, ⟨⟨HxW₁, HxW₂⟩, HxW₃⟩, HW₁₂₃U₁, HW₁₂₃U₂], have HW₁W₁₂₃ : W₁ ∩ W₂ ∩ W₃ ⊆ W₁ := λ x Hx, Hx.1.1, have HW₂W₁₂₃ : W₁ ∩ W₂ ∩ W₃ ⊆ W₂ := λ x Hx, Hx.1.2, have HW₃W₁₂₃ : W₁ ∩ W₂ ∩ W₃ ⊆ W₃ := λ x Hx, Hx.2, replace Hres₁ := congr_arg (F.res BW₁ BW₁₂₃ HW₁W₁₂₃) Hres₁, replace Hres₂ := congr_arg (F.res BW₂ BW₁₂₃ HW₂W₁₂₃) Hres₂, replace Hres₃ := congr_arg (F.res BW₃ BW₁₂₃ HW₃W₁₂₃) Hres₃, iterate 2 { rw ←presheaf_on_basis.Hcomp' at Hres₁, }, iterate 2 { rw ←presheaf_on_basis.Hcomp' at Hres₂, }, iterate 2 { rw ←presheaf_on_basis.Hcomp' at Hres₃, }, erw [←Hres₁, ←Hres₂], exact Hres₃, end lemma to_stalk_extension.surjective (F : presheaf_of_rings_on_basis α HB) (HF : sheaf_on_standard_basis.is_sheaf_on_standard_basis Bstd F.to_presheaf_on_basis) (x : α) : function.surjective (to_stalk_extension Bstd F @HF x) := begin intros Us', apply quotient.induction_on Us', rintros ⟨U, HxU, s⟩, rcases (s.2 x HxU) with ⟨V, BV, HxV, t, Ht⟩, let Vt : stalk_on_basis.elem (F.to_presheaf_on_basis) x := {U := V, BU := BV, Hx := HxV, s := t}, use ⟦Vt⟧, dunfold to_stalk_extension, apply quotient.sound, rcases (quotient.mk_out Vt) with ⟨W, BW, HxW, HWVtV, HWV, Hres⟩, have HUVWV : U ∩ V ∩ W ⊆ (quotient.out ⟦Vt⟧).U := λ x Hx, HWVtV Hx.2, have HUVWU : U ∩ V ∩ W ⊆ U := λ x Hx, Hx.1.1, use [U ∩ V ∩ W, ⟨⟨HxU, HxV⟩, HxW⟩, HUVWV, HUVWU], apply subtype.eq, dsimp only [presheaf_of_rings_on_basis_to_presheaf_of_rings], dsimp only [to_presheaf_of_rings_extension], dsimp only [to_stalk_product], funext y Hy, rw (Ht y Hy.1), apply quotient.sound, have BVW : V ∩ W ∈ B := Bstd.2 BV BW, have HVWVtV : V ∩ W ⊆ (quotient.out ⟦Vt⟧).U := λ x Hx, HWVtV Hx.2, have HVWV : V ∩ W ⊆ V := λ x Hx, Hx.1, use [V ∩ W, BVW, ⟨Hy.1.2,Hy.2⟩, HVWVtV, HVWV], have HVWW : V ∩ W ⊆ W := λ x Hx, Hx.2, replace Hres := congr_arg (F.res BW BVW HVWW) Hres, iterate 2 { rw ←presheaf_on_basis.Hcomp' at Hres, }, exact Hres, end lemma to_stalk_extension.bijective (F : presheaf_of_rings_on_basis α HB) (HF : sheaf_on_standard_basis.is_sheaf_on_standard_basis Bstd F.to_presheaf_on_basis) (x : α) : function.bijective (to_stalk_extension Bstd F @HF x) := ⟨to_stalk_extension.injective Bstd F @HF x, to_stalk_extension.surjective Bstd F @HF x⟩ lemma to_stalk_extension.is_ring_hom (F : presheaf_of_rings_on_basis α HB) (HF : sheaf_on_standard_basis.is_sheaf_on_standard_basis Bstd F.to_presheaf_on_basis) (x : α) : is_ring_hom (to_stalk_extension Bstd F @HF x) := { map_one := begin dunfold to_stalk_extension, let one.elem : stalk_on_basis.elem F.to_presheaf_on_basis x := {U := opens.univ, BU := Bstd.1, Hx := trivial, s:= 1}, let one.stalk : stalk_of_rings_on_standard_basis Bstd F x := ⟦one.elem⟧, let one := quotient.out one.stalk, apply quotient.sound, rcases (quotient.mk_out one.elem) with ⟨W₁, BW₁, HxW₁, HW₁Uout, HW₁U, Hres₁⟩, have BUW₁ : one.U ∩ W₁ ∈ B := Bstd.2 one.BU BW₁, have HUUW₁ : one.U ∩ W₁ ⊆ one.U := set.inter_subset_left _ _, use [one.U ∩ W₁, ⟨one.Hx, HxW₁⟩, HUUW₁, set.subset_univ _], apply subtype.eq, dsimp only [presheaf_of_rings_on_basis_to_presheaf_of_rings], dsimp only [to_presheaf_of_rings_extension], dsimp only [to_stalk_product], funext z Hz, apply quotient.sound, use [one.U ∩ W₁, BUW₁, Hz, set.inter_subset_left _ _, set.subset_univ _], dsimp, have HUW₁W₁ : one.U ∩ W₁ ⊆ W₁ := set.inter_subset_right _ _, replace Hres₁ := congr_arg (F.res BW₁ BUW₁ HUW₁W₁) Hres₁, iterate 2 { rw ←presheaf_on_basis.Hcomp' at Hres₁, }, exact Hres₁, end, map_mul := begin intros y z, apply quotient.induction_on₂ y z, intros Us₁ Us₂, simp, let Us₃ : stalk_on_basis.elem F.to_presheaf_on_basis x := { U := Us₁.U ∩ Us₂.U, BU := Bstd.2 Us₁.BU Us₂.BU, Hx := ⟨Us₁.Hx, Us₂.Hx⟩, s := F.res Us₁.BU _ (set.inter_subset_left _ _) Us₁.s * F.res Us₂.BU _ (set.inter_subset_right _ _) Us₂.s }, dunfold to_stalk_extension, apply quotient.sound, rcases (quotient.mk_out Us₁) with ⟨W₁, BW₁, HxW₁, HW₁U₁out, HW₁U₁, Hres₁⟩, rcases (quotient.mk_out Us₂) with ⟨W₂, BW₂, HxW₂, HW₂U₂out, HW₂U₂, Hres₂⟩, rcases (quotient.mk_out Us₃) with ⟨W₃, BW₃, HxW₃, HW₃U₃out, HW₃U₃, Hres₃⟩, let W := W₁ ∩ W₂ ∩ W₃, have HxW : x ∈ W := ⟨⟨HxW₁, HxW₂⟩, HxW₃⟩, have HWW₁ : W ⊆ W₁ := λ x Hx, Hx.1.1, have HWW₂ : W ⊆ W₂ := λ x Hx, Hx.1.2, have HWW₃ : W ⊆ W₃ := λ x Hx, Hx.2, have HWU₁out : W ⊆ (quotient.out ⟦Us₁⟧).U := set.subset.trans HWW₁ HW₁U₁out, have HWU₂out : W ⊆ (quotient.out ⟦Us₂⟧).U := set.subset.trans HWW₂ HW₂U₂out, have HWU₃out : W ⊆ (quotient.out ⟦Us₃⟧).U := set.subset.trans HWW₃ HW₃U₃out, have HWU₁₂out : W ⊆ (quotient.out ⟦Us₁⟧).U ∩ (quotient.out ⟦Us₂⟧).U := set.subset_inter HWU₁out HWU₂out, use [W, HxW, HWU₃out, HWU₁₂out], apply subtype.eq, dsimp only [presheaf_of_rings_on_basis_to_presheaf_of_rings], dsimp only [to_presheaf_of_rings_extension], dsimp only [to_stalk_product], funext z HzW, apply quotient.sound, have BW : W ∈ B := Bstd.2 (Bstd.2 BW₁ BW₂) BW₃, use [W, BW, HzW, HWU₃out, HWU₁₂out], rw (presheaf_of_rings_on_basis.res_is_ring_hom _ _ _ _).map_mul, rw ←presheaf_on_basis.Hcomp', rw ←presheaf_on_basis.Hcomp', replace Hres₁ := congr_arg (F.res BW₁ BW HWW₁) Hres₁, replace Hres₂ := congr_arg (F.res BW₂ BW HWW₂) Hres₂, replace Hres₃ := congr_arg (F.res BW₃ BW HWW₃) Hres₃, iterate 2 { rw ←presheaf_on_basis.Hcomp' at Hres₁, }, iterate 2 { rw ←presheaf_on_basis.Hcomp' at Hres₂, }, iterate 2 { rw ←presheaf_on_basis.Hcomp' at Hres₃, }, erw [Hres₁, Hres₂, Hres₃], rw (presheaf_of_rings_on_basis.res_is_ring_hom _ _ _ _).map_mul, rw ←presheaf_on_basis.Hcomp', rw ←presheaf_on_basis.Hcomp', end, map_add := begin intros y z, apply quotient.induction_on₂ y z, intros Us₁ Us₂, simp, let Us₃ : stalk_on_basis.elem F.to_presheaf_on_basis x := { U := Us₁.U ∩ Us₂.U, BU := Bstd.2 Us₁.BU Us₂.BU, Hx := ⟨Us₁.Hx, Us₂.Hx⟩, s := F.res Us₁.BU _ (set.inter_subset_left _ _) Us₁.s + F.res Us₂.BU _ (set.inter_subset_right _ _) Us₂.s }, dunfold to_stalk_extension, apply quotient.sound, rcases (quotient.mk_out Us₁) with ⟨W₁, BW₁, HxW₁, HW₁U₁out, HW₁U₁, Hres₁⟩, rcases (quotient.mk_out Us₂) with ⟨W₂, BW₂, HxW₂, HW₂U₂out, HW₂U₂, Hres₂⟩, rcases (quotient.mk_out Us₃) with ⟨W₃, BW₃, HxW₃, HW₃U₃out, HW₃U₃, Hres₃⟩, let W := W₁ ∩ W₂ ∩ W₃, have HxW : x ∈ W := ⟨⟨HxW₁, HxW₂⟩, HxW₃⟩, have HWW₁ : W ⊆ W₁ := λ x Hx, Hx.1.1, have HWW₂ : W ⊆ W₂ := λ x Hx, Hx.1.2, have HWW₃ : W ⊆ W₃ := λ x Hx, Hx.2, have HWU₁out : W ⊆ (quotient.out ⟦Us₁⟧).U := set.subset.trans HWW₁ HW₁U₁out, have HWU₂out : W ⊆ (quotient.out ⟦Us₂⟧).U := set.subset.trans HWW₂ HW₂U₂out, have HWU₃out : W ⊆ (quotient.out ⟦Us₃⟧).U := set.subset.trans HWW₃ HW₃U₃out, have HWU₁₂out : W ⊆ (quotient.out ⟦Us₁⟧).U ∩ (quotient.out ⟦Us₂⟧).U := set.subset_inter HWU₁out HWU₂out, use [W, HxW, HWU₃out, HWU₁₂out], apply subtype.eq, dsimp only [presheaf_of_rings_on_basis_to_presheaf_of_rings], dsimp only [to_presheaf_of_rings_extension], dsimp only [to_stalk_product], funext z HzW, apply quotient.sound, have BW : W ∈ B := Bstd.2 (Bstd.2 BW₁ BW₂) BW₃, use [W, BW, HzW, HWU₃out, HWU₁₂out], rw (presheaf_of_rings_on_basis.res_is_ring_hom _ _ _ _).map_add, rw ←presheaf_on_basis.Hcomp', rw ←presheaf_on_basis.Hcomp', replace Hres₁ := congr_arg (F.res BW₁ BW HWW₁) Hres₁, replace Hres₂ := congr_arg (F.res BW₂ BW HWW₂) Hres₂, replace Hres₃ := congr_arg (F.res BW₃ BW HWW₃) Hres₃, iterate 2 { rw ←presheaf_on_basis.Hcomp' at Hres₁, }, iterate 2 { rw ←presheaf_on_basis.Hcomp' at Hres₂, }, iterate 2 { rw ←presheaf_on_basis.Hcomp' at Hres₃, }, erw [Hres₁, Hres₂, Hres₃], rw (presheaf_of_rings_on_basis.res_is_ring_hom _ _ _ _).map_add, rw ←presheaf_on_basis.Hcomp', rw ←presheaf_on_basis.Hcomp', end, } end extension_coincides end presheaf_of_rings_extension
fd4c19096f0bd9fae85b20e92a9cf407ec5a8b57
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/simplifier12.lean
0948a4bbb206e8cd462e1c55e3506b04811896de
[ "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
366
lean
import algebra.ring open algebra set_option simplify.max_steps 1000 universe l constants (T : Type.{l}) (s : comm_ring T) constants (x1 x2 x3 x4 : T) (f g : T → T) attribute s [instance] open simplifier.unit simplifier.ac simplifier.neg simplifier.distrib #simplify eq env 0 x2 + (1 * g x1 + 0 + (f x3 * 3 * 1 * (x2 + 0 + g x1 * 7) * x2 * 1)) + 5 * (x4 + f x1)
ad8161034a2c3c9e0eecea41cc6623422c352c93
abc24f6c7fc917103329a1d2b75463d93511f4ab
/src/euler.lean
af80d178b993ffbbf060e84ae2337946bfc835e7
[]
no_license
mmasdeu/euler
5073bb6b747aaca1a95692027de1f390b7648c28
a323d777dee611f2a06cc81e2f2567cd9522a381
refs/heads/main
1,682,109,127,673
1,620,655,192,000
1,620,655,192,000
323,932,638
1
0
null
null
null
null
UTF-8
Lean
false
false
15,291
lean
import tactic import analysis.special_functions.trigonometric import measure_theory.interval_integral import topology.basic import data.finset import .integrals noncomputable theory open_locale classical open_locale big_operators open interval_integral open filter open real open_locale topological_space /-! #### The proof of Euler summation : ∑ 1/n^2 = π^2/6 ## Strategy 1. Define sequences Aₙ = ∫ x in 0..π/2 (cos x)^(2*n) and Bₙ = ∫ x in 0..π/2 x^2 * (cos x)^(2*n). 2. Use integration by parts to prove recurrence formulas Aₙ₊₁ = (2 * n + 1) * (n+1) * Bₙ - 2*(n+1)^2 * Bₙ₊₁ and Aₙ₊₁ = (2*n + 1) * (Aₙ - Aₙ₊₁) 3. Express 1/((n+1)^2) in terms of two consecutive ratios: 1 / ((n +1)^2 = 2 * (Bₙ) / (Aₙ) - 2 * Bₙ₊₁ / Aₙ₊₁ 4. The partial sums telescope and yield ∑ k=0..(n-1) 1 / ((k+1)^2 = 2 * B₀ / A₀ - 2 * Bₙ/Aₙ = π^2 / 6 - 2 * Bₙ/Aₙ 5. Bound the error term using the fact that 2/π * x ≤ sin x. ## References Daniel Daners, A short elementary proof of ... Mathematics Magazine 85 (2012), 361-364. (MR 3007217, Zbl 1274.97037) * <http://talus.maths.usyd.edu.au/u/daners/publ/abstracts/zeta2/> ## Tags euler summation, number theory, reciprocals -/ def A : ℕ → ℝ := λ n, ∫ x in 0..real.pi/2, (cos x)^(2*n) def B : ℕ → ℝ := λ n, ∫ x in 0..real.pi/2, x^2 * (cos x)^(2*n) /- Evaluate A 0 and B 0, which will be useful later -/ lemma eval_A0 : A 0 = real.pi / (2 : ℝ) := begin unfold A, simp only [mul_zero, pow_zero], suffices : ∫ (x : ℝ) in 0..real.pi / 2, (1:ℝ) = (real.pi / 2 - 0) • 1, { rw this, simp only [mul_one, algebra.id.smul_eq_mul, sub_zero], }, apply interval_integral.integral_const, end lemma has_deriv_at_congr {f : ℝ → ℝ} {f' g' : ℝ} (x : ℝ) (h: f' = g') : has_deriv_at f f' x → has_deriv_at f g' x := (iff_of_eq (congr_fun (congr_arg (has_deriv_at f) h) x)).1 lemma eval_B0 : B 0 = real.pi^3 / (24 : ℝ) := begin unfold B, simp only [mul_one, mul_zero, pow_zero], have h : ∀ x ∈ set.interval 0 (real.pi/2), has_deriv_at (λ (x:ℝ), x^3/3) (x^2) x, { intros x hx, have hh : (3⁻¹ * (3 * x ^ 2)) = x^2 := by discrete_field, suffices : has_deriv_at (λ (x : ℝ), x ^ 3 / 3) (3⁻¹ * (3 * x ^ 2)) x, by exact has_deriv_at_congr x hh this, simp [div_eq_mul_inv, mul_comm], apply has_deriv_at.const_mul, apply_mod_cast (has_deriv_at_pow 3 x), }, rw integral_eq_sub_of_has_deriv_at h, { simp only [div_pow], ring }, { show_continuous }, end /- Show that B n is positive for all n. A similar proof works to show that A n is positive, but we decided to prove the latter one by induction, which we will do once we have an explicit recursive formula for A n. For B n, the proof just uses that the integrand is the square of a nonzero function. -/ lemma B_pos {n : ℕ} : 0 < B n := begin unfold B, have pi_pos := pi_pos, simp only [mul_comm, pow_mul, ←mul_pow], apply int_pos_of_square (real.pi/3) pi_div_two_pos, { show_continuous }, { -- Show here that the integrand is nonzero at π/3 repeat {split}, repeat {linarith}, rw cos_pi_div_three, field_simp [pi_ne_zero], } end lemma first_lemma' (n : ℕ) : A (n + 1)= (2*(n:ℝ)+1) * ∫ x in 0..real.pi/2, ((sin x)^2 * (cos x)^(2*n)) := begin calc A (n + 1) = ∫ x in 0..real.pi/2, (cos x)^(2*(n+1)) : by {unfold A} ... = ∫ x in 0..real.pi/2, (cos x)^(2*n+1) * (deriv sin x) : begin congr, ext1, rw real.deriv_sin, ring_nf, end ... = ∫ x in 0..real.pi/2, (2*n+1) * (sin x)^2 * (cos x)^(2*n) : begin rw int_by_parts, { suffices : ∫ x in 0..real.pi / 2, sin x * ((2*n + 1) * (cos x ^ (2 * n) * sin x)) = ∫ x in 0..real.pi / 2, (2*n + 1) * sin x^2 * cos x^(2 * n), by simpa, congr, ext1, ring, }, { apply differentiable.pow, apply differentiable.cos, exact differentiable_id }, { exact differentiable_sin }, { exact continuous_deriv_cospow (2*n) }, { rw real.deriv_sin, exact continuous_cos }, end ... = ∫ x in 0..real.pi/2, (2*(n:ℝ)+1) * ((sin x)^2 * (cos x)^(2*n)) : by {congr, ext1, ring} ... = (2*(n:ℝ)+1) * ∫ x in 0..real.pi/2, ((sin x)^2 * (cos x)^(2*n)) : by {simp [my_integral_smul]} end lemma first_lemma (n : ℕ) : A (n + 1) = (2*n + 1) * (A (n) - A (n+1)) := begin calc A (n + 1) = (2*(n:ℝ)+1) * ∫ x in 0..real.pi/2, ((sin x)^2 * (cos x)^(2*n)) : first_lemma' n ... = (2*(n:ℝ)+1) * ∫ x in 0..real.pi/2, (1- (cos x)^2) * (cos x)^(2*n) : begin congr, ext1, suffices : sin x^2 = 1 - cos x^2, rw this, simp only [eq_sub_iff_add_eq, sin_sq_add_cos_sq], end ... = (2*(n:ℝ)+1) * (A (n) - A (n+1)) :-- by {rw f5} begin unfold A, rw ←integral_sub, { congr, discrete_field }, all_goals { apply integrable_of_cont, apply continuous.pow continuous_cos, }, end end lemma first_lemma_cor (n : ℕ) : A (n+1) = (2 * n + 1) / (2 * n + 2) * A n := begin have h := first_lemma n, have h1 : 2 * (n : ℝ) + 1 ≠ 0 := by show_nonzero, have h2 : 2 * (n : ℝ) + 2 ≠ 0 := by show_nonzero, have h3 : 2 * (n : ℝ) + 2 = (2 * n + 1) + 1 := by ring, field_simp [h1, h2], rw [h3, mul_add, mul_one], nth_rewrite_lhs 1 h, ring, end /- The recurrence formula for A n directly gives positivity by induction. -/ lemma A_pos {n : ℕ} : 0 < A n := begin induction n with d hd, { rw eval_A0, exact pi_div_two_pos }, { rw_mod_cast first_lemma_cor d, show_pos }, end /- -/ lemma display4 (n : ℕ) : A (n+1) = (2 * n + 1) * (n+1) * B n - 2*(n+1)^2 * B (n+1) := begin calc A (n + 1) = ∫ x in 0..real.pi/2, (cos x)^(2*(n+1)) : by {unfold A} ... = ∫ x in 0..real.pi/2, (cos x)^(2*n+2) * ((deriv id) x) : by {discrete_field} -- Integrate by parts ... = -∫ x in 0..real.pi/2, x * (2*n+2) * (cos x)^(2*n+1) * (deriv cos) x : begin rw int_by_parts_zero_ends, { congr, discrete_field }, all_goals { discrete_field, try {show_continuous} }, end ... = ((n:ℝ)+1) * ∫ x in 0..real.pi/2, (2*x) * sin x * (cos x)^(2*n+1) : begin rw [←my_integral_smul, ←integral_neg], congr, discrete_field, end ... = (n+1) * ∫ x in 0..real.pi/2, sin x * (cos x)^(2*n+1) * deriv (λ x, x^2) x : begin congr, ext, simp only [mul_one, differentiable_at_id', deriv_pow'', nat.cast_bit0, deriv_id'', pow_one, nat.cast_one], linarith, end -- Integrate by parts a second time ... = (n+1) * -∫ x in 0..real.pi/2, x^2 * (deriv (λ x, sin x * (cos x)^(2*n+1))) x : begin rw int_by_parts_zero_ends, { show_differentiable }, { exact differentiable_pow }, { rw deriv_sin_cos, apply continuous.sub; exact continuous_cospow', }, all_goals { simp only [algebra.id.smul_eq_mul, pow_one, nat.cast_one, power_rule'', continuous_mul_left, sin_zero, zero_mul, cos_pi_div_two, zero_mul, add_eq_zero_iff, ne.def, not_false_iff, one_ne_zero, mul_zero, and_false, zero_pow'], }, end ... = (n+1) * -∫ x in 0..real.pi/2, x^2 * ((cos x)^(2*n+2) - (2*n+1) * (1 - cos x^2) * (cos x)^(2*n)) : begin congr, ext, congr, discrete_field, end ... = (n+1) * ((2 *n + 1) * B n - 2*(n+1) * B (n+1)) : begin congr, unfold B, rw ←integral_neg, repeat {rw_mod_cast ←my_integral_smul,}, rw ←integral_sub, { congr, ext, simp only [nat.cast_bit0, nat.cast_add, nat.cast_one, nat.cast_mul], ring_exp, }, all_goals { apply integrable_of_cont, show_continuous, }, end ... = (2 * n + 1) * (n+1) * B n - 2*(n+1)^2 * B (n+1) : by {ring} end lemma summand_expression (n : ℕ) : 1 / ((n : ℝ) + 1)^2 = 2 * (B n) / (A n) - 2 * B (n+1) / A (n+1) := begin have A_nonzero : ∀ (m:ℕ), A m ≠ 0, { intro m, apply norm_num.ne_zero_of_pos, exact A_pos, }, have nplusone_nonzero : (n:ℝ)+1 ≠ 0 := nat.cast_add_one_ne_zero n, have twonplusone_nonzero : 2*(n:ℝ)+1 ≠ 0, show_nonzero, have h_first_lemma := first_lemma n, calc 1 / ((n : ℝ) + 1)^2 = (A (n+1)) / (A (n+1) * ((n : ℝ) + 1)^2) : begin rw div_mul_right, exact A_nonzero (n+1), end ... = ((2 * n + 1) * (n+1) * (B n) - 2*(n+1)^2 * (B (n+1))) / (A (n+1) * ((n : ℝ) + 1)^2) : by {nth_rewrite 0 display4,} ... = ((2 * n + 1) * (n+1) * (B n)) / (A (n+1) * ((n : ℝ) + 1)^2) - (2*(n+1)^2 * (B (n+1))) / (A (n+1) * ((n : ℝ) + 1)^2) : by {rw sub_div} ... = ((2 * n + 1) * (B n)) / (A (n+1) * ((n : ℝ) + 1)) - 2 * (B (n+1)) / (A (n+1)) : by {field_simp *, ring} ... = 2 * (B n) / (A n) - 2 * B (n+1) / A (n+1) : begin have : (A (n+1) * ((n:ℝ) + 1)) = (2*n + 1) / 2 * (A n) := by discrete_field, rw this, discrete_field, end end lemma telescoping (n : ℕ) : ∑ k in (finset.range n), (1 : ℝ) / ((k+1)^2) = 2 * B 0 / A 0 - 2 * B n / A n := begin simp only [summand_expression], exact finset.sum_range_sub' (λ k, 2 * (B k) / (A k)) n, end /- The sin function is concave on the interval [0..pi/2]. -/ lemma sin_is_concave : concave_on (set.Icc 0 (real.pi/2)) sin := begin have h0 : -sin = λ y, -sin y := by refl, rw ←neg_convex_on_iff, apply convex_on_of_deriv2_nonneg (convex_Icc 0 (real.pi / 2)), { show_continuous }, { show_differentiable }, { simp only [h0], show_differentiable, }, { intros x hx, replace hx : 0 ≤ x ∧ x ≤ real.pi / 2 := set.mem_Icc.mp (interior_subset hx), suffices : 0 ≤ deriv (deriv (-sin)) x, by simpa, simp only [h0], suffices : 0 ≤ sin x, by simpa, apply sin_nonneg_of_nonneg_of_le_pi; linarith, } end /- Use concavity of sin on [0..pi/2] to bound it below. -/ lemma bound_sin {x : ℝ} (hx1 : 0 ≤ x) (hx2 : x ≤ real.pi / 2) : 2 / real.pi * x ≤ sin x := begin have h := sin_is_concave.2, dsimp at h, have pi_pos := pi_pos, have pi_nonzero := pi_ne_zero, have two_over_pi_pos : (0 :ℝ) < (2:ℝ) / real.pi := div_pos zero_lt_two pi_pos, have hzero : (0:ℝ) ∈ set.Icc 0 (real.pi / 2), { rw set.mem_Icc, split; linarith, }, have hpi2 : real.pi / 2 ∈ set.Icc 0 (real.pi / 2), { rw set.mem_Icc, split; linarith, }, replace h := h hzero hpi2, simp only [sin_zero, mul_one, zero_add, mul_zero, sin_pi_div_two] at h, have ha : 0 ≤ (1:ℝ) - 2 / real.pi * x, { simp only [sub_nonneg], refine (le_div_iff' two_over_pi_pos).mp _, simp only [one_div_div], exact hx2, }, have hb : 0 ≤ 2 / real.pi * x := (zero_le_mul_left two_over_pi_pos).mpr hx1, replace h := h ha hb, simp only [forall_prop_of_true, sub_add_cancel] at h, suffices : 2 / real.pi * x * (real.pi / 2) = x, { rw this at h, exact h, }, discrete_field, end lemma key_inequality {n : ℕ} {x : ℝ} (hx1 : 0 ≤ x) (hx2 : x ≤ real.pi /2) : x ^ 2 * cos x ^ (2 * n) ≤ (real.pi ^ 2 / 4) • (sin x ^ 2 * cos x ^ (2 * n)) := begin have key := bound_sin hx1 hx2, have cospos : (cos x)^(2*n) ≥ 0, { rw [mul_comm, pow_mul], apply pow_two_nonneg, }, have h : x^2 ≤ real.pi^2 / 4 * (sin x)^2, { rw [div_mul_eq_mul_div, div_le_iff pi_pos] at key, nlinarith, }, dsimp, nlinarith, end lemma BA_aux {n : ℕ} : ∫ (x : ℝ) in 0..real.pi / 2, x ^ 2 * cos x ^ (2 * n) < ∫ (x : ℝ) in 0..real.pi / 2, (real.pi ^ 2 / 4) * (sin x ^ 2 * cos x ^ (2 * n)) := begin have hsq2' : sqrt 2^2 = 2 := sq_sqrt zero_le_two, have hsq2 : sqrt 2 ^(2*n) = 2^n := by simp only [pow_mul, hsq2'], have pisqpos : 0 < real.pi^2 := pow_pos pi_pos 2, apply integral_strictly_monotone_of_cont, { show_continuous }, { show_continuous }, { exact pi_div_two_pos }, { apply key_inequality }, { use real.pi/4, repeat {split}, all_goals { try { linarith [pi_pos]}}, { simp only [cos_pi_div_four, sin_pi_div_four, hsq2, hsq2', algebra.id.smul_eq_mul, div_pow], rw [←mul_assoc, mul_lt_mul_right], all_goals {discrete_field}, }, } end lemma B_in_terms_of_A (n : ℕ) : B n < real.pi^2 / (8 * (n + 1)) * A n := begin have hh := first_lemma_cor n, calc B n = ∫ x in 0..(real.pi/2), x^2 * (cos x)^(2*n) : by {refl} ... < ∫ x in 0..(real.pi/2), (real.pi^2/ 4) • ((sin x)^2 * (cos x)^(2*n)) : by {exact BA_aux} ... = (real.pi^2/4) * (A (n+1) / (2*n + 1)) : by {rw [interval_integral.integral_smul,first_lemma'], discrete_field } ... = (real.pi^2) / (8 * (n+1)) * (A n) : by {discrete_field} end lemma B_in_terms_of_A' (n : ℕ) : 2 * B n / A n < real.pi ^ 2 / (4 *(n + 1)) := begin have h2 : 0 < (2:ℝ) := zero_lt_two, calc 2 * B n / A n = 2 * (B n / A n) : by {exact mul_div_assoc,} ... < 2 * (real.pi ^ 2 / (8 * (n + 1))) : by {simp only [mul_lt_mul_left h2, div_lt_iff A_pos, B_in_terms_of_A n]} ... = real.pi ^ 2 / (4 *(n + 1)) : by {discrete_field} end /- Bound the partial sums by a harmonic sequence. -/ lemma error_estimate {n : ℕ}: (-real.pi^2/4/(n+1) + real.pi^2/6) ≤ (∑ k in finset.range n, ((1:ℝ)/ (k+1)^2)) ∧ (∑ k in finset.range n, ((1:ℝ)/ (k+1)^2)) ≤ real.pi^2/4/(n+1) + real.pi^2/6 := begin rw [telescoping n, eval_A0, eval_B0], have quo_pos : 0 < 2 * B n / A n, { rw mul_div_assoc, exact mul_pos zero_lt_two (div_pos B_pos A_pos), }, have h := B_in_terms_of_A' n, have pi_ne_zero := pi_ne_zero, have : 2 * (real.pi ^ 3 / 24) / (real.pi / 2) = real.pi^2 / 6 := by {discrete_field}, rw this, field_simp *, split, all_goals {apply le_of_lt}, { calc (-(real.pi ^ 2 * 6) / (4 * (↑n + 1)) + real.pi ^ 2) / 6 = -(real.pi^2 / (4*((n:ℝ) + 1))) + real.pi^2 / 6 : by {discrete_field} ... < -(2 * B n / A n) + real.pi^2 / 6 : by {linarith [h]} ... = (real.pi ^ 2 - 6 * (2 * B n) / A n) / 6 : by {ring_exp} }, { calc (real.pi ^ 2 - 6 * (2 * B n) / A n) / 6 = real.pi ^ 2/ 6- (2 * B n / A n): by {discrete_field} ... < real.pi ^ 2 / (4 * (↑n + 1)) + real.pi ^ 2 / 6 : by {nlinarith} ... = (real.pi ^ 2 * 6 / (4 * (↑n + 1)) + real.pi ^ 2) / 6 : by {discrete_field} } end lemma tendsto_const_div_add_at_top_nhds_0_nat {C : ℝ} : tendsto (λ n : ℕ, (C / ((n : ℝ) + 1))) at_top (𝓝 0) := suffices tendsto (λ n : ℕ, C / (↑(n + 1) : ℝ)) at_top (𝓝 0), by simpa, (tendsto_add_at_top_iff_nat 1).2 (tendsto_const_div_at_top_nhds_0_nat C) lemma limit_below : tendsto (λ (n:ℕ),-real.pi^2/4/(n+1) + real.pi^2/6) at_top (𝓝 (real.pi^2/6)) := begin nth_rewrite 0 ←zero_add (real.pi^2/6), apply tendsto.add_const, apply tendsto_const_div_add_at_top_nhds_0_nat, end lemma limit_above : tendsto (λ (n:ℕ), real.pi^2/4/(n+1) + real.pi^2/6) at_top (𝓝 (real.pi^2/6)) := begin nth_rewrite 0 ←zero_add (real.pi^2/6), apply tendsto.add_const, apply tendsto_const_div_add_at_top_nhds_0_nat, end theorem euler_summation : tendsto (λ (n:ℕ), (∑ k in finset.range n, ((1:ℝ)/ (k+1)^2))) at_top (nhds (real.pi^2 / 6)) := begin apply tendsto_of_tendsto_of_tendsto_of_le_of_le limit_below limit_above, all_goals {rw pi.le_def, intro n}, exact error_estimate.1, exact error_estimate.2, end
5bf38070d456717266ed66adf5b147551da8cf8c
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/examples/targets/src/b.lean
bbb1432c98ae4155da82e05e7076379a1ecae727
[ "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
79
lean
import Bar import Baz def main : IO PUnit := IO.println s!"b: {bar}, {baz}"
8c16ac271f1544a867e9f8344add07a1a2367199
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/analysis/normed_space/finite_dimension.lean
6b054f3a1b5f1ba7bf2ff4c12f2cf337b5cafca4
[ "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
25,613
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 analysis.normed_space.affine_isometry import analysis.normed_space.operator_norm import analysis.asymptotics.asymptotic_equivalent import linear_algebra.finite_dimensional /-! # Finite dimensional normed spaces over complete fields Over a complete nondiscrete field, in finite dimension, all norms are equivalent and all linear maps are continuous. Moreover, a finite-dimensional subspace is always complete and closed. ## Main results: * `linear_map.continuous_of_finite_dimensional` : a linear map on a finite-dimensional space over a complete field is continuous. * `finite_dimensional.complete` : a finite-dimensional space over a complete field is complete. This is not registered as an instance, as the field would be an unknown metavariable in typeclass resolution. * `submodule.closed_of_finite_dimensional` : a finite-dimensional subspace over a complete field is closed * `finite_dimensional.proper` : a finite-dimensional space over a proper field is proper. This is not registered as an instance, as the field would be an unknown metavariable in typeclass resolution. It is however registered as an instance for `𝕜 = ℝ` and `𝕜 = ℂ`. As properness implies completeness, there is no need to also register `finite_dimensional.complete` on `ℝ` or `ℂ`. ## Implementation notes The fact that all norms are equivalent is not written explicitly, as it would mean having two norms on a single space, which is not the way type classes work. However, if one has a finite-dimensional vector space `E` with a norm, and a copy `E'` of this type with another norm, then the identities from `E` to `E'` and from `E'`to `E` are continuous thanks to `linear_map.continuous_of_finite_dimensional`. This gives the desired norm equivalence. -/ universes u v w x open set finite_dimensional topological_space filter asymptotics open_locale classical big_operators filter topological_space asymptotics noncomputable theory /-- A linear map on `ι → 𝕜` (where `ι` is a fintype) is continuous -/ lemma linear_map.continuous_on_pi {ι : Type w} [fintype ι] {𝕜 : Type u} [normed_field 𝕜] {E : Type v} [add_comm_group E] [module 𝕜 E] [topological_space E] [topological_add_group E] [has_continuous_smul 𝕜 E] (f : (ι → 𝕜) →ₗ[𝕜] E) : continuous f := begin -- for the proof, write `f` in the standard basis, and use that each coordinate is a continuous -- function. have : (f : (ι → 𝕜) → E) = (λx, ∑ i : ι, x i • (f (λj, if i = j then 1 else 0))), by { ext x, exact f.pi_apply_eq_sum_univ x }, rw this, refine continuous_finset_sum _ (λi hi, _), exact (continuous_apply i).smul continuous_const end section complete_field variables {𝕜 : Type u} [nondiscrete_normed_field 𝕜] {E : Type v} [normed_group E] [normed_space 𝕜 E] {F : Type w} [normed_group F] [normed_space 𝕜 F] {F' : Type x} [add_comm_group F'] [module 𝕜 F'] [topological_space F'] [topological_add_group F'] [has_continuous_smul 𝕜 F'] [complete_space 𝕜] /-- In finite dimension over a complete field, the canonical identification (in terms of a basis) with `𝕜^n` together with its sup norm is continuous. This is the nontrivial part in the fact that all norms are equivalent in finite dimension. This statement is superceded by the fact that every linear map on a finite-dimensional space is continuous, in `linear_map.continuous_of_finite_dimensional`. -/ lemma continuous_equiv_fun_basis {ι : Type v} [fintype ι] (ξ : basis ι 𝕜 E) : continuous ξ.equiv_fun := begin unfreezingI { induction hn : fintype.card ι with n IH generalizing ι E }, { apply linear_map.continuous_of_bound _ 0 (λx, _), have : ξ.equiv_fun x = 0, by { ext i, exact (fintype.card_eq_zero_iff.1 hn).elim i }, change ∥ξ.equiv_fun x∥ ≤ 0 * ∥x∥, rw this, simp [norm_nonneg] }, { haveI : finite_dimensional 𝕜 E := of_fintype_basis ξ, -- first step: thanks to the inductive assumption, any n-dimensional subspace is equivalent -- to a standard space of dimension n, hence it is complete and therefore closed. have H₁ : ∀s : submodule 𝕜 E, finrank 𝕜 s = n → is_closed (s : set E), { assume s s_dim, let b := basis.of_vector_space 𝕜 s, have U : uniform_embedding b.equiv_fun.symm.to_equiv, { have : fintype.card (basis.of_vector_space_index 𝕜 s) = n, by { rw ← s_dim, exact (finrank_eq_card_basis b).symm }, have : continuous b.equiv_fun := IH b this, exact b.equiv_fun.symm.uniform_embedding (linear_map.continuous_on_pi _) this }, have : is_complete (s : set E), from complete_space_coe_iff_is_complete.1 ((complete_space_congr U).1 (by apply_instance)), exact this.is_closed }, -- second step: any linear form is continuous, as its kernel is closed by the first step have H₂ : ∀f : E →ₗ[𝕜] 𝕜, continuous f, { assume f, have : finrank 𝕜 f.ker = n ∨ finrank 𝕜 f.ker = n.succ, { have Z := f.finrank_range_add_finrank_ker, rw [finrank_eq_card_basis ξ, hn] at Z, by_cases H : finrank 𝕜 f.range = 0, { right, rw H at Z, simpa using Z }, { left, have : finrank 𝕜 f.range = 1, { refine le_antisymm _ (zero_lt_iff.mpr H), simpa [finrank_self] using f.range.finrank_le }, rw [this, add_comm, nat.add_one] at Z, exact nat.succ.inj Z } }, have : is_closed (f.ker : set E), { cases this, { exact H₁ _ this }, { have : f.ker = ⊤, by { apply eq_top_of_finrank_eq, rw [finrank_eq_card_basis ξ, hn, this] }, simp [this] } }, exact linear_map.continuous_iff_is_closed_ker.2 this }, -- third step: applying the continuity to the linear form corresponding to a coefficient in the -- basis decomposition, deduce that all such coefficients are controlled in terms of the norm have : ∀i:ι, ∃C, 0 ≤ C ∧ ∀(x:E), ∥ξ.equiv_fun x i∥ ≤ C * ∥x∥, { assume i, let f : E →ₗ[𝕜] 𝕜 := (linear_map.proj i) ∘ₗ ↑ξ.equiv_fun, let f' : E →L[𝕜] 𝕜 := { cont := H₂ f, ..f }, exact ⟨∥f'∥, norm_nonneg _, λx, continuous_linear_map.le_op_norm f' x⟩ }, -- fourth step: combine the bound on each coefficient to get a global bound and the continuity choose C0 hC0 using this, let C := ∑ i, C0 i, have C_nonneg : 0 ≤ C := finset.sum_nonneg (λi hi, (hC0 i).1), have C0_le : ∀i, C0 i ≤ C := λi, finset.single_le_sum (λj hj, (hC0 j).1) (finset.mem_univ _), apply linear_map.continuous_of_bound _ C (λx, _), rw pi_semi_norm_le_iff, { exact λi, le_trans ((hC0 i).2 x) (mul_le_mul_of_nonneg_right (C0_le i) (norm_nonneg _)) }, { exact mul_nonneg C_nonneg (norm_nonneg _) } } end /-- Any linear map on a finite dimensional space over a complete field is continuous. -/ theorem linear_map.continuous_of_finite_dimensional [finite_dimensional 𝕜 E] (f : E →ₗ[𝕜] F') : continuous f := begin -- for the proof, go to a model vector space `b → 𝕜` thanks to `continuous_equiv_fun_basis`, and -- argue that all linear maps there are continuous. let b := basis.of_vector_space 𝕜 E, have A : continuous b.equiv_fun := continuous_equiv_fun_basis b, have B : continuous (f.comp (b.equiv_fun.symm : (basis.of_vector_space_index 𝕜 E → 𝕜) →ₗ[𝕜] E)) := linear_map.continuous_on_pi _, have : continuous ((f.comp (b.equiv_fun.symm : (basis.of_vector_space_index 𝕜 E → 𝕜) →ₗ[𝕜] E)) ∘ b.equiv_fun) := B.comp A, convert this, ext x, dsimp, rw [basis.equiv_fun_symm_apply, basis.sum_repr] end theorem affine_map.continuous_of_finite_dimensional {PE PF : Type*} [metric_space PE] [normed_add_torsor E PE] [metric_space PF] [normed_add_torsor F PF] [finite_dimensional 𝕜 E] (f : PE →ᵃ[𝕜] PF) : continuous f := affine_map.continuous_linear_iff.1 f.linear.continuous_of_finite_dimensional namespace linear_map variables [finite_dimensional 𝕜 E] /-- The continuous linear map induced by a linear map on a finite dimensional space -/ def to_continuous_linear_map : (E →ₗ[𝕜] F') ≃ₗ[𝕜] E →L[𝕜] F' := { to_fun := λ f, ⟨f, f.continuous_of_finite_dimensional⟩, inv_fun := coe, map_add' := λ f g, rfl, map_smul' := λ c f, rfl, left_inv := λ f, rfl, right_inv := λ f, continuous_linear_map.coe_injective rfl } @[simp] lemma coe_to_continuous_linear_map' (f : E →ₗ[𝕜] F') : ⇑f.to_continuous_linear_map = f := rfl @[simp] lemma coe_to_continuous_linear_map (f : E →ₗ[𝕜] F') : (f.to_continuous_linear_map : E →ₗ[𝕜] F') = f := rfl @[simp] lemma coe_to_continuous_linear_map_symm : ⇑(to_continuous_linear_map : (E →ₗ[𝕜] F') ≃ₗ[𝕜] E →L[𝕜] F').symm = coe := rfl end linear_map /-- The continuous linear equivalence induced by a linear equivalence on a finite dimensional space. -/ def linear_equiv.to_continuous_linear_equiv [finite_dimensional 𝕜 E] (e : E ≃ₗ[𝕜] F) : E ≃L[𝕜] F := { continuous_to_fun := e.to_linear_map.continuous_of_finite_dimensional, continuous_inv_fun := begin haveI : finite_dimensional 𝕜 F := e.finite_dimensional, exact e.symm.to_linear_map.continuous_of_finite_dimensional end, ..e } lemma linear_map.exists_antilipschitz_with [finite_dimensional 𝕜 E] (f : E →ₗ[𝕜] F) (hf : f.ker = ⊥) : ∃ K > 0, antilipschitz_with K f := begin cases subsingleton_or_nontrivial E; resetI, { exact ⟨1, zero_lt_one, antilipschitz_with.of_subsingleton⟩ }, { rw linear_map.ker_eq_bot at hf, let e : E ≃L[𝕜] f.range := (linear_equiv.of_injective f hf).to_continuous_linear_equiv, exact ⟨_, e.nnnorm_symm_pos, e.antilipschitz⟩ } end protected lemma linear_independent.eventually {ι} [fintype ι] {f : ι → E} (hf : linear_independent 𝕜 f) : ∀ᶠ g in 𝓝 f, linear_independent 𝕜 g := begin simp only [fintype.linear_independent_iff'] at hf ⊢, rcases linear_map.exists_antilipschitz_with _ hf with ⟨K, K0, hK⟩, have : tendsto (λ g : ι → E, ∑ i, ∥g i - f i∥) (𝓝 f) (𝓝 $ ∑ i, ∥f i - f i∥), from tendsto_finset_sum _ (λ i hi, tendsto.norm $ ((continuous_apply i).tendsto _).sub tendsto_const_nhds), simp only [sub_self, norm_zero, finset.sum_const_zero] at this, refine (this.eventually (gt_mem_nhds $ inv_pos.2 K0)).mono (λ g hg, _), replace hg : ∑ i, nnnorm (g i - f i) < K⁻¹, by { rw ← nnreal.coe_lt_coe, push_cast, exact hg }, rw linear_map.ker_eq_bot, refine (hK.add_sub_lipschitz_with (lipschitz_with.of_dist_le_mul $ λ v u, _) hg).injective, simp only [dist_eq_norm, linear_map.lsum_apply, pi.sub_apply, linear_map.sum_apply, linear_map.comp_apply, linear_map.proj_apply, linear_map.smul_right_apply, linear_map.id_apply, ← finset.sum_sub_distrib, ← smul_sub, ← sub_smul, nnreal.coe_sum, coe_nnnorm, finset.sum_mul], refine norm_sum_le_of_le _ (λ i _, _), rw [norm_smul, mul_comm], exact mul_le_mul_of_nonneg_left (norm_le_pi_norm (v - u) i) (norm_nonneg _) end lemma is_open_set_of_linear_independent {ι : Type*} [fintype ι] : is_open {f : ι → E | linear_independent 𝕜 f} := is_open_iff_mem_nhds.2 $ λ f, linear_independent.eventually lemma is_open_set_of_nat_le_rank (n : ℕ) : is_open {f : E →L[𝕜] F | ↑n ≤ rank (f : E →ₗ[𝕜] F)} := begin simp only [le_rank_iff_exists_linear_independent_finset, set_of_exists, ← exists_prop], refine is_open_bUnion (λ t ht, _), have : continuous (λ f : E →L[𝕜] F, (λ x : (t : set E), f x)), from continuous_pi (λ x, (continuous_linear_map.apply 𝕜 F (x : E)).continuous), exact is_open_set_of_linear_independent.preimage this end /-- Two finite-dimensional normed spaces are continuously linearly equivalent if they have the same (finite) dimension. -/ theorem finite_dimensional.nonempty_continuous_linear_equiv_of_finrank_eq [finite_dimensional 𝕜 E] [finite_dimensional 𝕜 F] (cond : finrank 𝕜 E = finrank 𝕜 F) : nonempty (E ≃L[𝕜] F) := (nonempty_linear_equiv_of_finrank_eq cond).map linear_equiv.to_continuous_linear_equiv /-- Two finite-dimensional normed spaces are continuously linearly equivalent if and only if they have the same (finite) dimension. -/ theorem finite_dimensional.nonempty_continuous_linear_equiv_iff_finrank_eq [finite_dimensional 𝕜 E] [finite_dimensional 𝕜 F] : nonempty (E ≃L[𝕜] F) ↔ finrank 𝕜 E = finrank 𝕜 F := ⟨ λ ⟨h⟩, h.to_linear_equiv.finrank_eq, λ h, finite_dimensional.nonempty_continuous_linear_equiv_of_finrank_eq h ⟩ /-- A continuous linear equivalence between two finite-dimensional normed spaces of the same (finite) dimension. -/ def continuous_linear_equiv.of_finrank_eq [finite_dimensional 𝕜 E] [finite_dimensional 𝕜 F] (cond : finrank 𝕜 E = finrank 𝕜 F) : E ≃L[𝕜] F := (linear_equiv.of_finrank_eq E F cond).to_continuous_linear_equiv variables {ι : Type*} [fintype ι] /-- Construct a continuous linear map given the value at a finite basis. -/ def basis.constrL (v : basis ι 𝕜 E) (f : ι → F) : E →L[𝕜] F := by haveI : finite_dimensional 𝕜 E := finite_dimensional.of_fintype_basis v; exact (v.constr 𝕜 f).to_continuous_linear_map @[simp, norm_cast] lemma basis.coe_constrL (v : basis ι 𝕜 E) (f : ι → F) : (v.constrL f : E →ₗ[𝕜] F) = v.constr 𝕜 f := rfl /-- The continuous linear equivalence between a vector space over `𝕜` with a finite basis and functions from its basis indexing type to `𝕜`. -/ def basis.equiv_funL (v : basis ι 𝕜 E) : E ≃L[𝕜] (ι → 𝕜) := { continuous_to_fun := begin haveI : finite_dimensional 𝕜 E := finite_dimensional.of_fintype_basis v, apply linear_map.continuous_of_finite_dimensional, end, continuous_inv_fun := begin change continuous v.equiv_fun.symm.to_fun, apply linear_map.continuous_of_finite_dimensional, end, ..v.equiv_fun } @[simp] lemma basis.constrL_apply (v : basis ι 𝕜 E) (f : ι → F) (e : E) : (v.constrL f) e = ∑ i, (v.equiv_fun e i) • f i := v.constr_apply_fintype 𝕜 _ _ @[simp] lemma basis.constrL_basis (v : basis ι 𝕜 E) (f : ι → F) (i : ι) : (v.constrL f) (v i) = f i := v.constr_basis 𝕜 _ _ lemma basis.sup_norm_le_norm (v : basis ι 𝕜 E) : ∃ C > (0 : ℝ), ∀ e : E, ∑ i, ∥v.equiv_fun e i∥ ≤ C * ∥e∥ := begin set φ := v.equiv_funL.to_continuous_linear_map, set C := ∥φ∥ * (fintype.card ι), use [max C 1, lt_of_lt_of_le (zero_lt_one) (le_max_right C 1)], intros e, calc ∑ i, ∥φ e i∥ ≤ ∑ i : ι, ∥φ e∥ : by { apply finset.sum_le_sum, exact λ i hi, norm_le_pi_norm (φ e) i } ... = ∥φ e∥*(fintype.card ι) : by simpa only [mul_comm, finset.sum_const, nsmul_eq_mul] ... ≤ ∥φ∥ * ∥e∥ * (fintype.card ι) : mul_le_mul_of_nonneg_right (φ.le_op_norm e) (fintype.card ι).cast_nonneg ... = ∥φ∥ * (fintype.card ι) * ∥e∥ : by ring ... ≤ max C 1 * ∥e∥ : mul_le_mul_of_nonneg_right (le_max_left _ _) (norm_nonneg _) end lemma basis.op_norm_le {ι : Type*} [fintype ι] (v : basis ι 𝕜 E) : ∃ C > (0 : ℝ), ∀ {u : E →L[𝕜] F} {M : ℝ}, 0 ≤ M → (∀ i, ∥u (v i)∥ ≤ M) → ∥u∥ ≤ C*M := begin obtain ⟨C, C_pos, hC⟩ : ∃ C > (0 : ℝ), ∀ (e : E), ∑ i, ∥v.equiv_fun e i∥ ≤ C * ∥e∥, from v.sup_norm_le_norm, use [C, C_pos], intros u M hM hu, apply u.op_norm_le_bound (mul_nonneg (le_of_lt C_pos) hM), intros e, calc ∥u e∥ = ∥u (∑ i, v.equiv_fun e i • v i)∥ : by rw [v.sum_equiv_fun] ... = ∥∑ i, (v.equiv_fun e i) • (u $ v i)∥ : by simp [u.map_sum, linear_map.map_smul] ... ≤ ∑ i, ∥(v.equiv_fun e i) • (u $ v i)∥ : norm_sum_le _ _ ... = ∑ i, ∥v.equiv_fun e i∥ * ∥u (v i)∥ : by simp only [norm_smul] ... ≤ ∑ i, ∥v.equiv_fun e i∥ * M : finset.sum_le_sum (λ i hi, mul_le_mul_of_nonneg_left (hu i) (norm_nonneg _)) ... = (∑ i, ∥v.equiv_fun e i∥) * M : finset.sum_mul.symm ... ≤ C * ∥e∥ * M : mul_le_mul_of_nonneg_right (hC e) hM ... = C * M * ∥e∥ : by ring end instance [finite_dimensional 𝕜 E] [second_countable_topology F] : second_countable_topology (E →L[𝕜] F) := begin set d := finite_dimensional.finrank 𝕜 E, suffices : ∀ ε > (0 : ℝ), ∃ n : (E →L[𝕜] F) → fin d → ℕ, ∀ (f g : E →L[𝕜] F), n f = n g → dist f g ≤ ε, from metric.second_countable_of_countable_discretization (λ ε ε_pos, ⟨fin d → ℕ, by apply_instance, this ε ε_pos⟩), intros ε ε_pos, obtain ⟨u : ℕ → F, hu : dense_range u⟩ := exists_dense_seq F, let v := finite_dimensional.fin_basis 𝕜 E, obtain ⟨C : ℝ, C_pos : 0 < C, hC : ∀ {φ : E →L[𝕜] F} {M : ℝ}, 0 ≤ M → (∀ i, ∥φ (v i)∥ ≤ M) → ∥φ∥ ≤ C * M⟩ := v.op_norm_le, have h_2C : 0 < 2*C := mul_pos zero_lt_two C_pos, have hε2C : 0 < ε/(2*C) := div_pos ε_pos h_2C, have : ∀ φ : E →L[𝕜] F, ∃ n : fin d → ℕ, ∥φ - (v.constrL $ u ∘ n)∥ ≤ ε/2, { intros φ, have : ∀ i, ∃ n, ∥φ (v i) - u n∥ ≤ ε/(2*C), { simp only [norm_sub_rev], intro i, have : φ (v i) ∈ closure (range u) := hu _, obtain ⟨n, hn⟩ : ∃ n, ∥u n - φ (v i)∥ < ε / (2 * C), { rw mem_closure_iff_nhds_basis metric.nhds_basis_ball at this, specialize this (ε/(2*C)) hε2C, simpa [dist_eq_norm] }, exact ⟨n, le_of_lt hn⟩ }, choose n hn using this, use n, replace hn : ∀ i : fin d, ∥(φ - (v.constrL $ u ∘ n)) (v i)∥ ≤ ε / (2 * C), by simp [hn], have : C * (ε / (2 * C)) = ε/2, { rw [eq_div_iff (two_ne_zero : (2 : ℝ) ≠ 0), mul_comm, ← mul_assoc, mul_div_cancel' _ (ne_of_gt h_2C)] }, specialize hC (le_of_lt hε2C) hn, rwa this at hC }, choose n hn using this, set Φ := λ φ : E →L[𝕜] F, (v.constrL $ u ∘ (n φ)), change ∀ z, dist z (Φ z) ≤ ε/2 at hn, use n, intros x y hxy, calc dist x y ≤ dist x (Φ x) + dist (Φ x) y : dist_triangle _ _ _ ... = dist x (Φ x) + dist y (Φ y) : by simp [Φ, hxy, dist_comm] ... ≤ ε : by linarith [hn x, hn y] end /-- Any finite-dimensional vector space over a complete field is complete. We do not register this as an instance to avoid an instance loop when trying to prove the completeness of `𝕜`, and the search for `𝕜` as an unknown metavariable. Declare the instance explicitly when needed. -/ variables (𝕜 E) lemma finite_dimensional.complete [finite_dimensional 𝕜 E] : complete_space E := begin set e := continuous_linear_equiv.of_finrank_eq (@finrank_fin_fun 𝕜 _ (finrank 𝕜 E)).symm, have : uniform_embedding e.to_linear_equiv.to_equiv.symm := e.symm.uniform_embedding, exact (complete_space_congr this).1 (by apply_instance) end variables {𝕜 E} /-- A finite-dimensional subspace is complete. -/ lemma submodule.complete_of_finite_dimensional (s : submodule 𝕜 E) [finite_dimensional 𝕜 s] : is_complete (s : set E) := complete_space_coe_iff_is_complete.1 (finite_dimensional.complete 𝕜 s) /-- A finite-dimensional subspace is closed. -/ lemma submodule.closed_of_finite_dimensional (s : submodule 𝕜 E) [finite_dimensional 𝕜 s] : is_closed (s : set E) := s.complete_of_finite_dimensional.is_closed lemma continuous_linear_map.exists_right_inverse_of_surjective [finite_dimensional 𝕜 F] (f : E →L[𝕜] F) (hf : f.range = ⊤) : ∃ g : F →L[𝕜] E, f.comp g = continuous_linear_map.id 𝕜 F := let ⟨g, hg⟩ := (f : E →ₗ[𝕜] F).exists_right_inverse_of_surjective hf in ⟨g.to_continuous_linear_map, continuous_linear_map.ext $ linear_map.ext_iff.1 hg⟩ lemma closed_embedding_smul_left {c : E} (hc : c ≠ 0) : closed_embedding (λ x : 𝕜, x • c) := begin haveI : finite_dimensional 𝕜 (submodule.span 𝕜 {c}) := finite_dimensional.span_of_finite 𝕜 (finite_singleton c), have m1 : closed_embedding (coe : submodule.span 𝕜 {c} → E) := (submodule.span 𝕜 {c}).closed_of_finite_dimensional.closed_embedding_subtype_coe, have m2 : closed_embedding (linear_equiv.to_span_nonzero_singleton 𝕜 E c hc : 𝕜 → submodule.span 𝕜 {c}) := (continuous_linear_equiv.to_span_nonzero_singleton 𝕜 c hc).to_homeomorph.closed_embedding, exact m1.comp m2 end /- `smul` is a closed map in the first argument. -/ lemma is_closed_map_smul_left (c : E) : is_closed_map (λ x : 𝕜, x • c) := begin by_cases hc : c = 0, { simp_rw [hc, smul_zero], exact is_closed_map_const }, { exact (closed_embedding_smul_left hc).is_closed_map } end end complete_field section proper_field variables (𝕜 : Type u) [nondiscrete_normed_field 𝕜] (E : Type v) [normed_group E] [normed_space 𝕜 E] [proper_space 𝕜] /-- Any finite-dimensional vector space over a proper field is proper. We do not register this as an instance to avoid an instance loop when trying to prove the properness of `𝕜`, and the search for `𝕜` as an unknown metavariable. Declare the instance explicitly when needed. -/ lemma finite_dimensional.proper [finite_dimensional 𝕜 E] : proper_space E := begin set e := continuous_linear_equiv.of_finrank_eq (@finrank_fin_fun 𝕜 _ (finrank 𝕜 E)).symm, exact e.symm.antilipschitz.proper_space e.symm.continuous e.symm.surjective end end proper_field /- Over the real numbers, we can register the previous statement as an instance as it will not cause problems in instance resolution since the properness of `ℝ` is already known. -/ instance finite_dimensional.proper_real (E : Type u) [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] : proper_space E := finite_dimensional.proper ℝ E attribute [instance, priority 900] finite_dimensional.proper_real /-- In a finite dimensional vector space over `ℝ`, the series `∑ x, ∥f x∥` is unconditionally summable if and only if the series `∑ x, f x` is unconditionally summable. One implication holds in any complete normed space, while the other holds only in finite dimensional spaces. -/ lemma summable_norm_iff {α E : Type*} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {f : α → E} : summable (λ x, ∥f x∥) ↔ summable f := begin refine ⟨summable_of_summable_norm, λ hf, _⟩, -- First we use a finite basis to reduce the problem to the case `E = fin N → ℝ` suffices : ∀ {N : ℕ} {g : α → fin N → ℝ}, summable g → summable (λ x, ∥g x∥), { obtain v := fin_basis ℝ E, set e := v.equiv_funL, have : summable (λ x, ∥e (f x)∥) := this (e.summable.2 hf), refine summable_of_norm_bounded _ (this.mul_left ↑(nnnorm (e.symm : (fin (finrank ℝ E) → ℝ) →L[ℝ] E))) (λ i, _), simpa using (e.symm : (fin (finrank ℝ E) → ℝ) →L[ℝ] E).le_op_norm (e $ f i) }, unfreezingI { clear_dependent E }, -- Now we deal with `g : α → fin N → ℝ` intros N g hg, have : ∀ i, summable (λ x, ∥g x i∥) := λ i, (pi.summable.1 hg i).abs, refine summable_of_norm_bounded _ (summable_sum (λ i (hi : i ∈ finset.univ), this i)) (λ x, _), rw [norm_norm, pi_norm_le_iff], { refine λ i, finset.single_le_sum (λ i hi, _) (finset.mem_univ i), exact norm_nonneg (g x i) }, { exact finset.sum_nonneg (λ _ _, norm_nonneg _) } end lemma summable_of_is_O' {ι E F : Type*} [normed_group E] [complete_space E] [normed_group F] [normed_space ℝ F] [finite_dimensional ℝ F] {f : ι → E} {g : ι → F} (hg : summable g) (h : is_O f g cofinite) : summable f := summable_of_is_O (summable_norm_iff.mpr hg) h.norm_right lemma summable_of_is_O_nat' {E F : Type*} [normed_group E] [complete_space E] [normed_group F] [normed_space ℝ F] [finite_dimensional ℝ F] {f : ℕ → E} {g : ℕ → F} (hg : summable g) (h : is_O f g at_top) : summable f := summable_of_is_O_nat (summable_norm_iff.mpr hg) h.norm_right lemma summable_of_is_equivalent {ι E : Type*} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {f : ι → E} {g : ι → E} (hg : summable g) (h : f ~[cofinite] g) : summable f := hg.trans_sub (summable_of_is_O' hg h.is_o.is_O) lemma summable_of_is_equivalent_nat {E : Type*} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {f : ℕ → E} {g : ℕ → E} (hg : summable g) (h : f ~[at_top] g) : summable f := hg.trans_sub (summable_of_is_O_nat' hg h.is_o.is_O) lemma is_equivalent.summable_iff {ι E : Type*} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {f : ι → E} {g : ι → E} (h : f ~[cofinite] g) : summable f ↔ summable g := ⟨λ hf, summable_of_is_equivalent hf h.symm, λ hg, summable_of_is_equivalent hg h⟩ lemma is_equivalent.summable_iff_nat {E : Type*} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {f : ℕ → E} {g : ℕ → E} (h : f ~[at_top] g) : summable f ↔ summable g := ⟨λ hf, summable_of_is_equivalent_nat hf h.symm, λ hg, summable_of_is_equivalent_nat hg h⟩
79a8946afa4032eae4c67b7fc9b8253cf18fed9a
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/padics/padic_norm.lean
511e69f8be376142091387985018b9f8ca9d7975
[]
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
17,470
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.ring_theory.int.basic import Mathlib.algebra.field_power import Mathlib.ring_theory.multiplicity import Mathlib.data.real.cau_seq import Mathlib.tactic.ring_exp import Mathlib.tactic.basic import Mathlib.PostPort namespace Mathlib /-! # p-adic norm This file defines the p-adic valuation and the p-adic norm on ℚ. The p-adic valuation on ℚ is the difference of the multiplicities of `p` in the numerator and denominator of `q`. This function obeys the standard properties of a valuation, with the appropriate assumptions on p. The valuation induces a norm on ℚ. This norm is a nonarchimedean absolute value. It takes values in {0} ∪ {1/p^k | k ∈ ℤ}. ## Notations This file uses the local notation `/.` for `rat.mk`. ## Implementation notes Much, but not all, of this file assumes that `p` is prime. This assumption is inferred automatically by taking `[fact (prime p)]` as a type class argument. ## References * [F. Q. Gouêva, *p-adic numbers*][gouvea1997] * [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019] * <https://en.wikipedia.org/wiki/P-adic_number> ## Tags p-adic, p adic, padic, norm, valuation -/ /-- For `p ≠ 1`, the p-adic valuation of an integer `z ≠ 0` is the largest natural number `n` such that p^n divides z. `padic_val_rat` defines the valuation of a rational `q` to be the valuation of `q.num` minus the valuation of `q.denom`. If `q = 0` or `p = 1`, then `padic_val_rat p q` defaults to 0. -/ def padic_val_rat (p : ℕ) (q : ℚ) : ℤ := dite (q ≠ 0 ∧ p ≠ 1) (fun (h : q ≠ 0 ∧ p ≠ 1) => ↑(roption.get (multiplicity (↑p) (rat.num q)) sorry) - ↑(roption.get (multiplicity ↑p ↑(rat.denom q)) sorry)) fun (h : ¬(q ≠ 0 ∧ p ≠ 1)) => 0 /-- A simplification of the definition of `padic_val_rat p q` when `q ≠ 0` and `p` is prime. -/ theorem padic_val_rat_def (p : ℕ) [hp : fact (nat.prime p)] {q : ℚ} (hq : q ≠ 0) : padic_val_rat p q = ↑(roption.get (multiplicity (↑p) (rat.num q)) (iff.mpr multiplicity.finite_int_iff { left := nat.prime.ne_one hp, right := rat.num_ne_zero_of_ne_zero hq })) - ↑(roption.get (multiplicity ↑p ↑(rat.denom q)) (iff.mpr multiplicity.finite_int_iff { left := nat.prime.ne_one hp, right := eq.mpr (id (Eq.trans ((fun (a a_1 : ℤ) (e_1 : a = a_1) (b b_1 : ℤ) (e_2 : b = b_1) => congr (congr_arg ne e_1) e_2) (↑(rat.denom q)) (↑(rat.denom q)) (Eq.refl ↑(rat.denom q)) 0 (↑0) (Eq.symm int.coe_nat_zero)) (Eq.trans (propext (ne_from_not_eq ↑(rat.denom q) ↑0)) ((fun (a a_1 : Prop) (e_1 : a = a_1) => congr_arg Not e_1) (↑(rat.denom q) = ↑0) (rat.denom q = 0) (propext int.coe_nat_inj'))))) (eq.mp (propext (ne_from_not_eq (rat.denom q) 0)) (rat.denom_ne_zero q)) })) := dif_pos { left := hq, right := nat.prime.ne_one hp } namespace padic_val_rat /-- `padic_val_rat p q` is symmetric in `q`. -/ @[simp] protected theorem neg {p : ℕ} (q : ℚ) : padic_val_rat p (-q) = padic_val_rat p q := sorry /-- `padic_val_rat p 1` is 0 for any `p`. -/ @[simp] protected theorem one {p : ℕ} : padic_val_rat p 1 = 0 := sorry /-- For `p ≠ 0, p ≠ 1, `padic_val_rat p p` is 1. -/ @[simp] theorem padic_val_rat_self {p : ℕ} (hp : 1 < p) : padic_val_rat p ↑p = 1 := sorry /-- The p-adic value of an integer `z ≠ 0` is the multiplicity of `p` in `z`. -/ theorem padic_val_rat_of_int {p : ℕ} (z : ℤ) (hp : p ≠ 1) (hz : z ≠ 0) : padic_val_rat p ↑z = ↑(roption.get (multiplicity (↑p) z) (iff.mpr multiplicity.finite_int_iff { left := hp, right := hz })) := sorry end padic_val_rat /-- A convenience function for the case of `padic_val_rat` when both inputs are natural numbers. -/ def padic_val_nat (p : ℕ) (n : ℕ) : ℕ := int.to_nat (padic_val_rat p ↑n) /-- `padic_val_nat` is defined as an `int.to_nat` cast; this lemma ensures that the cast is well-behaved. -/ theorem zero_le_padic_val_rat_of_nat (p : ℕ) (n : ℕ) : 0 ≤ padic_val_rat p ↑n := sorry /-- `padic_val_rat` coincides with `padic_val_nat`. -/ @[simp] theorem padic_val_rat_of_nat (p : ℕ) (n : ℕ) : ↑(padic_val_nat p n) = padic_val_rat p ↑n := sorry /-- A simplification of `padic_val_nat` when one input is prime, by analogy with `padic_val_rat_def`. -/ theorem padic_val_nat_def {p : ℕ} [hp : fact (nat.prime p)] {n : ℕ} (hn : n ≠ 0) : padic_val_nat p n = roption.get (multiplicity p n) (iff.mpr multiplicity.finite_nat_iff { left := nat.prime.ne_one hp, right := iff.mpr bot_lt_iff_ne_bot hn }) := sorry theorem one_le_padic_val_nat_of_dvd {n : ℕ} {p : ℕ} [prime : fact (nat.prime p)] (nonzero : n ≠ 0) (div : p ∣ n) : 1 ≤ padic_val_nat p n := sorry @[simp] theorem padic_val_nat_zero (m : ℕ) : padic_val_nat m 0 = 0 := eq.mpr (id (Eq.refl (padic_val_nat m 0 = 0))) (Eq.refl (padic_val_nat m 0)) @[simp] theorem padic_val_nat_one (m : ℕ) : padic_val_nat m 1 = 0 := sorry namespace padic_val_rat /-- The multiplicity of `p : ℕ` in `a : ℤ` is finite exactly when `a ≠ 0`. -/ theorem finite_int_prime_iff {p : ℕ} [p_prime : fact (nat.prime p)] {a : ℤ} : multiplicity.finite (↑p) a ↔ a ≠ 0 := sorry /-- A rewrite lemma for `padic_val_rat p q` when `q` is expressed in terms of `rat.mk`. -/ protected theorem defn (p : ℕ) [p_prime : fact (nat.prime p)] {q : ℚ} {n : ℤ} {d : ℤ} (hqz : q ≠ 0) (qdf : q = rat.mk n d) : padic_val_rat p q = ↑(roption.get (multiplicity (↑p) n) (iff.mpr multiplicity.finite_int_iff { left := ne.symm (ne_of_lt (nat.prime.one_lt p_prime)), right := fun (hn : n = 0) => False._oldrec (eq.mp (Eq.trans ((fun (a a_1 : ℚ) (e_1 : a = a_1) (ᾰ ᾰ_1 : ℚ) (e_2 : ᾰ = ᾰ_1) => congr (congr_arg Eq e_1) e_2) q q (Eq.refl q) (rat.mk n d) 0 (Eq.trans ((fun (ᾰ ᾰ_1 : ℤ) (e_1 : ᾰ = ᾰ_1) (ᾰ_2 ᾰ_3 : ℤ) (e_2 : ᾰ_2 = ᾰ_3) => congr (congr_arg rat.mk e_1) e_2) n 0 hn d d (Eq.refl d)) (rat.zero_mk d))) (propext (iff_false_intro hqz))) qdf) })) - ↑(roption.get (multiplicity (↑p) d) (iff.mpr multiplicity.finite_int_iff { left := ne.symm (ne_of_lt (nat.prime.one_lt p_prime)), right := fun (hd : d = 0) => False._oldrec (eq.mp (Eq.trans ((fun (a a_1 : ℚ) (e_1 : a = a_1) (ᾰ ᾰ_1 : ℚ) (e_2 : ᾰ = ᾰ_1) => congr (congr_arg Eq e_1) e_2) q q (Eq.refl q) (rat.mk n d) 0 (Eq.trans ((fun (ᾰ ᾰ_1 : ℤ) (e_1 : ᾰ = ᾰ_1) (ᾰ_2 ᾰ_3 : ℤ) (e_2 : ᾰ_2 = ᾰ_3) => congr (congr_arg rat.mk e_1) e_2) n n (Eq.refl n) d 0 hd) (rat.mk_zero n))) (propext (iff_false_intro hqz))) qdf) })) := sorry /-- A rewrite lemma for `padic_val_rat p (q * r)` with conditions `q ≠ 0`, `r ≠ 0`. -/ protected theorem mul (p : ℕ) [p_prime : fact (nat.prime p)] {q : ℚ} {r : ℚ} (hq : q ≠ 0) (hr : r ≠ 0) : padic_val_rat p (q * r) = padic_val_rat p q + padic_val_rat p r := sorry /-- A rewrite lemma for `padic_val_rat p (q^k) with condition `q ≠ 0`. -/ protected theorem pow (p : ℕ) [p_prime : fact (nat.prime p)] {q : ℚ} (hq : q ≠ 0) {k : ℕ} : padic_val_rat p (q ^ k) = ↑k * padic_val_rat p q := sorry /-- A rewrite lemma for `padic_val_rat p (q⁻¹)` with condition `q ≠ 0`. -/ protected theorem inv (p : ℕ) [p_prime : fact (nat.prime p)] {q : ℚ} (hq : q ≠ 0) : padic_val_rat p (q⁻¹) = -padic_val_rat p q := sorry /-- A rewrite lemma for `padic_val_rat p (q / r)` with conditions `q ≠ 0`, `r ≠ 0`. -/ protected theorem div (p : ℕ) [p_prime : fact (nat.prime p)] {q : ℚ} {r : ℚ} (hq : q ≠ 0) (hr : r ≠ 0) : padic_val_rat p (q / r) = padic_val_rat p q - padic_val_rat p r := sorry /-- A condition for `padic_val_rat p (n₁ / d₁) ≤ padic_val_rat p (n₂ / d₂), in terms of divisibility by `p^n`. -/ theorem padic_val_rat_le_padic_val_rat_iff (p : ℕ) [p_prime : fact (nat.prime p)] {n₁ : ℤ} {n₂ : ℤ} {d₁ : ℤ} {d₂ : ℤ} (hn₁ : n₁ ≠ 0) (hn₂ : n₂ ≠ 0) (hd₁ : d₁ ≠ 0) (hd₂ : d₂ ≠ 0) : padic_val_rat p (rat.mk n₁ d₁) ≤ padic_val_rat p (rat.mk n₂ d₂) ↔ ∀ (n : ℕ), ↑p ^ n ∣ n₁ * d₂ → ↑p ^ n ∣ n₂ * d₁ := sorry /-- Sufficient conditions to show that the p-adic valuation of `q` is less than or equal to the p-adic vlauation of `q + r`. -/ theorem le_padic_val_rat_add_of_le (p : ℕ) [p_prime : fact (nat.prime p)] {q : ℚ} {r : ℚ} (hq : q ≠ 0) (hr : r ≠ 0) (hqr : q + r ≠ 0) (h : padic_val_rat p q ≤ padic_val_rat p r) : padic_val_rat p q ≤ padic_val_rat p (q + r) := sorry /-- The minimum of the valuations of `q` and `r` is less than or equal to the valuation of `q + r`. -/ theorem min_le_padic_val_rat_add (p : ℕ) [p_prime : fact (nat.prime p)] {q : ℚ} {r : ℚ} (hq : q ≠ 0) (hr : r ≠ 0) (hqr : q + r ≠ 0) : min (padic_val_rat p q) (padic_val_rat p r) ≤ padic_val_rat p (q + r) := sorry /-- A finite sum of rationals with positive p-adic valuation has positive p-adic valuation (if the sum is non-zero). -/ theorem sum_pos_of_pos (p : ℕ) [p_prime : fact (nat.prime p)] {n : ℕ} {F : ℕ → ℚ} (hF : ∀ (i : ℕ), i < n → 0 < padic_val_rat p (F i)) (hn0 : (finset.sum (finset.range n) fun (i : ℕ) => F i) ≠ 0) : 0 < padic_val_rat p (finset.sum (finset.range n) fun (i : ℕ) => F i) := sorry end padic_val_rat namespace padic_val_nat /-- A rewrite lemma for `padic_val_nat p (q * r)` with conditions `q ≠ 0`, `r ≠ 0`. -/ protected theorem mul (p : ℕ) [p_prime : fact (nat.prime p)] {q : ℕ} {r : ℕ} (hq : q ≠ 0) (hr : r ≠ 0) : padic_val_nat p (q * r) = padic_val_nat p q + padic_val_nat p r := sorry /-- Dividing out by a prime factor reduces the padic_val_nat by 1. -/ protected theorem div {p : ℕ} [p_prime : fact (nat.prime p)] {b : ℕ} (dvd : p ∣ b) : padic_val_nat p (b / p) = padic_val_nat p b - 1 := sorry end padic_val_nat /-- If a prime doesn't appear in `n`, `padic_val_nat p n` is `0`. -/ theorem padic_val_nat_of_not_dvd {p : ℕ} [fact (nat.prime p)] {n : ℕ} (not_dvd : ¬p ∣ n) : padic_val_nat p n = 0 := sorry theorem dvd_of_one_le_padic_val_nat {n : ℕ} {p : ℕ} [prime : fact (nat.prime p)] (hp : 1 ≤ padic_val_nat p n) : p ∣ n := sorry theorem padic_val_nat_primes {p : ℕ} {q : ℕ} [p_prime : fact (nat.prime p)] [q_prime : fact (nat.prime q)] (neq : p ≠ q) : padic_val_nat p q = 0 := padic_val_nat_of_not_dvd (iff.mp (not_congr (iff.symm (nat.prime_dvd_prime_iff_eq p_prime q_prime))) neq) protected theorem padic_val_nat.div' {p : ℕ} [p_prime : fact (nat.prime p)] {m : ℕ} (cpm : nat.coprime p m) {b : ℕ} (dvd : m ∣ b) : padic_val_nat p (b / m) = padic_val_nat p b := sorry theorem padic_val_nat_eq_factors_count (p : ℕ) [hp : fact (nat.prime p)] (n : ℕ) : padic_val_nat p n = list.count p (nat.factors n) := sorry theorem prod_pow_prime_padic_val_nat (n : ℕ) (hn : n ≠ 0) (m : ℕ) (pr : n < m) : (finset.prod (finset.filter nat.prime (finset.range m)) fun (p : ℕ) => p ^ padic_val_nat p n) = n := sorry /-- If `q ≠ 0`, the p-adic norm of a rational `q` is `p ^ (-(padic_val_rat p q))`. If `q = 0`, the p-adic norm of `q` is 0. -/ def padic_norm (p : ℕ) (q : ℚ) : ℚ := ite (q = 0) 0 (↑p ^ (-padic_val_rat p q)) namespace padic_norm /-- Unfolds the definition of the p-adic norm of `q` when `q ≠ 0`. -/ @[simp] protected theorem eq_fpow_of_nonzero (p : ℕ) {q : ℚ} (hq : q ≠ 0) : padic_norm p q = ↑p ^ (-padic_val_rat p q) := sorry /-- The p-adic norm is nonnegative. -/ protected theorem nonneg (p : ℕ) (q : ℚ) : 0 ≤ padic_norm p q := sorry /-- The p-adic norm of 0 is 0. -/ @[simp] protected theorem zero (p : ℕ) : padic_norm p 0 = 0 := sorry /-- The p-adic norm of 1 is 1. -/ @[simp] protected theorem one (p : ℕ) : padic_norm p 1 = 1 := sorry /-- The p-adic norm of `p` is `1/p` if `p > 1`. See also `padic_norm.padic_norm_p_of_prime` for a version that assumes `p` is prime. -/ theorem padic_norm_p {p : ℕ} (hp : 1 < p) : padic_norm p ↑p = 1 / ↑p := sorry /-- The p-adic norm of `p` is `1/p` if `p` is prime. See also `padic_norm.padic_norm_p` for a version that assumes `1 < p`. -/ @[simp] theorem padic_norm_p_of_prime (p : ℕ) [fact (nat.prime p)] : padic_norm p ↑p = 1 / ↑p := padic_norm_p (nat.prime.one_lt _inst_1) /-- The p-adic norm of `p` is less than 1 if `1 < p`. See also `padic_norm.padic_norm_p_lt_one_of_prime` for a version assuming `prime p`. -/ theorem padic_norm_p_lt_one {p : ℕ} (hp : 1 < p) : padic_norm p ↑p < 1 := sorry /-- The p-adic norm of `p` is less than 1 if `p` is prime. See also `padic_norm.padic_norm_p_lt_one` for a version assuming `1 < p`. -/ theorem padic_norm_p_lt_one_of_prime (p : ℕ) [fact (nat.prime p)] : padic_norm p ↑p < 1 := padic_norm_p_lt_one (nat.prime.one_lt _inst_1) /-- `padic_norm p q` takes discrete values `p ^ -z` for `z : ℤ`. -/ protected theorem values_discrete (p : ℕ) {q : ℚ} (hq : q ≠ 0) : ∃ (z : ℤ), padic_norm p q = ↑p ^ (-z) := sorry /-- `padic_norm p` is symmetric. -/ @[simp] protected theorem neg (p : ℕ) (q : ℚ) : padic_norm p (-q) = padic_norm p q := sorry /-- If `q ≠ 0`, then `padic_norm p q ≠ 0`. -/ protected theorem nonzero (p : ℕ) [hp : fact (nat.prime p)] {q : ℚ} (hq : q ≠ 0) : padic_norm p q ≠ 0 := sorry /-- If the p-adic norm of `q` is 0, then `q` is 0. -/ theorem zero_of_padic_norm_eq_zero (p : ℕ) [hp : fact (nat.prime p)] {q : ℚ} (h : padic_norm p q = 0) : q = 0 := sorry /-- The p-adic norm is multiplicative. -/ @[simp] protected theorem mul (p : ℕ) [hp : fact (nat.prime p)] (q : ℚ) (r : ℚ) : padic_norm p (q * r) = padic_norm p q * padic_norm p r := sorry /-- The p-adic norm respects division. -/ @[simp] protected theorem div (p : ℕ) [hp : fact (nat.prime p)] (q : ℚ) (r : ℚ) : padic_norm p (q / r) = padic_norm p q / padic_norm p r := sorry /-- The p-adic norm of an integer is at most 1. -/ protected theorem of_int (p : ℕ) [hp : fact (nat.prime p)] (z : ℤ) : padic_norm p ↑z ≤ 1 := sorry /-- The p-adic norm is nonarchimedean: the norm of `p + q` is at most the max of the norm of `p` and the norm of `q`. -/ protected theorem nonarchimedean (p : ℕ) [hp : fact (nat.prime p)] {q : ℚ} {r : ℚ} : padic_norm p (q + r) ≤ max (padic_norm p q) (padic_norm p r) := sorry /-- The p-adic norm respects the triangle inequality: the norm of `p + q` is at most the norm of `p` plus the norm of `q`. -/ theorem triangle_ineq (p : ℕ) [hp : fact (nat.prime p)] (q : ℚ) (r : ℚ) : padic_norm p (q + r) ≤ padic_norm p q + padic_norm p r := le_trans (padic_norm.nonarchimedean p) (max_le_add_of_nonneg (padic_norm.nonneg p q) (padic_norm.nonneg p r)) /-- The p-adic norm of a difference is at most the max of each component. Restates the archimedean property of the p-adic norm. -/ protected theorem sub (p : ℕ) [hp : fact (nat.prime p)] {q : ℚ} {r : ℚ} : padic_norm p (q - r) ≤ max (padic_norm p q) (padic_norm p r) := sorry /-- If the p-adic norms of `q` and `r` are different, then the norm of `q + r` is equal to the max of the norms of `q` and `r`. -/ theorem add_eq_max_of_ne (p : ℕ) [hp : fact (nat.prime p)] {q : ℚ} {r : ℚ} (hne : padic_norm p q ≠ padic_norm p r) : padic_norm p (q + r) = max (padic_norm p q) (padic_norm p r) := sorry /-- The p-adic norm is an absolute value: positive-definite and multiplicative, satisfying the triangle inequality. -/ protected instance is_absolute_value (p : ℕ) [hp : fact (nat.prime p)] : is_absolute_value (padic_norm p) := is_absolute_value.mk (padic_norm.nonneg p) (fun (x : ℚ) => { mp := fun (ᾰ : padic_norm p x = 0) => zero_of_padic_norm_eq_zero p ᾰ, mpr := fun (ᾰ : x = 0) => eq.mpr (id (Eq.trans ((fun (a a_1 : ℚ) (e_1 : a = a_1) (ᾰ ᾰ_1 : ℚ) (e_2 : ᾰ = ᾰ_1) => congr (congr_arg Eq e_1) e_2) (padic_norm p x) 0 (Eq.trans ((fun (p p_1 : ℕ) (e_1 : p = p_1) (q q_1 : ℚ) (e_2 : q = q_1) => congr (congr_arg padic_norm e_1) e_2) p p (Eq.refl p) x 0 ᾰ) (padic_norm.zero p)) 0 0 (Eq.refl 0)) (propext (eq_self_iff_true 0)))) trivial }) (triangle_ineq p) (padic_norm.mul p) theorem dvd_iff_norm_le {p : ℕ} [hp : fact (nat.prime p)] {n : ℕ} {z : ℤ} : ↑(p ^ n) ∣ z ↔ padic_norm p ↑z ≤ ↑p ^ (-↑n) := sorry
d9664473b5dcb4c6715b37472a9645009a172ab7
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/letRecTheorem.lean
c15f0b1d3d062e757d263e389c6343c707ce5b9c
[ "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
84
lean
def foo : Fin 5 := let rec bla : 0 < 5 := by decide ⟨0, bla⟩ #print foo.bla
f61ff9ca614c20680d49def8fa25c82cc5c00388
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/DocString.lean
7e02121fa4fd4caffd9c246eda41b3dca8606e02
[ "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
3,895
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.DeclarationRange import Lean.MonadEnv namespace Lean private builtin_initialize builtinDocStrings : IO.Ref (NameMap String) ← IO.mkRef {} private builtin_initialize docStringExt : MapDeclarationExtension String ← mkMapDeclarationExtension `docstring private def findLeadingSpacesSize (s : String) : Nat := let it := s.iter let it := it.find (· == '\n') |>.next let (min, it) := it.foldUntil 0 fun num c => if c == ' ' || c == '\t' then some (num + 1) else none findNextLine it min where consumeSpaces (it : String.Iterator) (curr min : Nat) : Nat := if it.atEnd then min else if it.curr == ' ' || it.curr == '\t' then consumeSpaces it.next (curr + 1) min else findNextLine it.next (Nat.min curr min) findNextLine (it : String.Iterator) (min : Nat) : Nat := if it.atEnd then min else if it.curr == '\n' then consumeSpaces it.next 0 min else findNextLine it.next min private def removeNumLeadingSpaces (n : Nat) (s : String) : String := consumeSpaces n s.iter "" where consumeSpaces (n : Nat) (it : String.Iterator) (r : String) : String := match n with | 0 => saveLine it r | n+1 => if it.atEnd then r else if it.curr == ' ' || it.curr == '\t' then consumeSpaces n it.next r else saveLine it r saveLine (it : String.Iterator) (r : String) : String := if it.atEnd then r else if it.curr == '\n' then consumeSpaces n it.next (r.push '\n') else saveLine it.next (r.push it.curr) termination_by consumeSpaces n it r => (it, 1) saveLine it r => (it, 0) private def removeLeadingSpaces (s : String) : String := let n := findLeadingSpacesSize s if n == 0 then s else removeNumLeadingSpaces n s def addBuiltinDocString (declName : Name) (docString : String) : IO Unit := builtinDocStrings.modify (·.insert declName (removeLeadingSpaces docString)) def addDocString [MonadEnv m] (declName : Name) (docString : String) : m Unit := modifyEnv fun env => docStringExt.insert env declName (removeLeadingSpaces docString) def addDocString' [Monad m] [MonadEnv m] (declName : Name) (docString? : Option String) : m Unit := match docString? with | some docString => addDocString declName docString | none => return () def findDocString? (env : Environment) (declName : Name) : IO (Option String) := /- `docStringExt` should have precedence over `builtinDocStrings`, otherwise we would not be able to update the doc strings for builtin elaborators, parsers, macros, ... -/ match docStringExt.find? env declName with | some docStr => return some docStr | none => return (← builtinDocStrings.get).find? declName structure ModuleDoc where doc : String declarationRange : DeclarationRange private builtin_initialize moduleDocExt : SimplePersistentEnvExtension ModuleDoc (Std.PersistentArray ModuleDoc) ← registerSimplePersistentEnvExtension { name := `moduleDocExt addImportedFn := fun _ => {} addEntryFn := fun s e => s.push e toArrayFn := fun es => es.toArray } def addMainModuleDoc (env : Environment) (doc : ModuleDoc) : Environment := moduleDocExt.addEntry env doc def getMainModuleDoc (env : Environment) : Std.PersistentArray ModuleDoc := moduleDocExt.getState env def getModuleDoc? (env : Environment) (moduleName : Name) : Option (Array ModuleDoc) := env.getModuleIdx? moduleName |>.map fun modIdx => moduleDocExt.getModuleEntries env modIdx def getDocStringText [Monad m] [MonadError m] [MonadRef m] (stx : TSyntax `Lean.Parser.Command.docComment) : m String := match stx.raw[1] with | Syntax.atom _ val => return val.extract 0 (val.endPos - ⟨2⟩) | _ => throwErrorAt stx "unexpected doc string{indentD stx.raw[1]}" end Lean
44127472246ff86714cb84a6ee68c9048b223657
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/ring_theory/witt_vector/truncated.lean
307f5de57ef5df93c20d9df28dd7a92ffac34cec
[ "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
14,425
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Robert Y. Lewis -/ import ring_theory.witt_vector.init_tail /-! # Truncated Witt vectors The ring of truncated Witt vectors (of length `n`) is a quotient of the ring of Witt vectors. It retains the first `n` coefficients of each Witt vector. In this file, we set up the basic quotient API for this ring. The ring of Witt vectors is the projective limit of all the rings of truncated Witt vectors. ## Main declarations - `truncated_witt_vector`: the underlying type of the ring of truncated Witt vectors - `truncated_witt_vector.comm_ring`: the ring structure on truncated Witt vectors - `witt_vector.truncate`: the quotient homomorphism that truncates a Witt vector, to obtain a truncated Witt vector - `truncated_witt_vector.truncate`: the homomorphism that truncates a truncated Witt vector of length `n` to one of length `m` (for some `m ≤ n`) - `witt_vector.lift`: the unique ring homomorphism into the ring of Witt vectors that is compatible with a family of ring homomorphisms to the truncated Witt vectors: this realizes the ring of Witt vectors as projective limit of the rings of truncated Witt vectors ## References * [Hazewinkel, *Witt Vectors*][Haze09] * [Commelin and Lewis, *Formalizing the Ring of Witt Vectors*][CL21] -/ open function (injective surjective) noncomputable theory variables {p : ℕ} [hp : fact p.prime] (n : ℕ) (R : Type*) local notation `𝕎` := witt_vector p -- type as `\bbW` /-- A truncated Witt vector over `R` is a vector of elements of `R`, i.e., the first `n` coefficients of a Witt vector. We will define operations on this type that are compatible with the (untruncated) Witt vector operations. `truncated_witt_vector p n R` takes a parameter `p : ℕ` that is not used in the definition. In practice, this number `p` is assumed to be a prime number, and under this assumption we construct a ring structure on `truncated_witt_vector p n R`. (`truncated_witt_vector p₁ n R` and `truncated_witt_vector p₂ n R` are definitionally equal as types but will have different ring operations.) -/ @[nolint unused_arguments] def truncated_witt_vector (p : ℕ) (n : ℕ) (R : Type*) := fin n → R instance (p n : ℕ) (R : Type*) [inhabited R] : inhabited (truncated_witt_vector p n R) := ⟨λ _, default⟩ variables {n R} namespace truncated_witt_vector variables (p) /-- Create a `truncated_witt_vector` from a vector `x`. -/ def mk (x : fin n → R) : truncated_witt_vector p n R := x variables {p} /-- `x.coeff i` is the `i`th entry of `x`. -/ def coeff (i : fin n) (x : truncated_witt_vector p n R) : R := x i @[ext] lemma ext {x y : truncated_witt_vector p n R} (h : ∀ i, x.coeff i = y.coeff i) : x = y := funext h lemma ext_iff {x y : truncated_witt_vector p n R} : x = y ↔ ∀ i, x.coeff i = y.coeff i := ⟨λ h i, by rw h, ext⟩ @[simp] lemma coeff_mk (x : fin n → R) (i : fin n) : (mk p x).coeff i = x i := rfl @[simp] lemma mk_coeff (x : truncated_witt_vector p n R) : mk p (λ i, x.coeff i) = x := by { ext i, rw [coeff_mk] } variable [comm_ring R] /-- We can turn a truncated Witt vector `x` into a Witt vector by setting all coefficients after `x` to be 0. -/ def out (x : truncated_witt_vector p n R) : 𝕎 R := witt_vector.mk p $ λ i, if h : i < n then x.coeff ⟨i, h⟩ else 0 @[simp] lemma coeff_out (x : truncated_witt_vector p n R) (i : fin n) : x.out.coeff i = x.coeff i := by rw [out, witt_vector.coeff_mk, dif_pos i.is_lt, fin.eta] lemma out_injective : injective (@out p n R _) := begin intros x y h, ext i, rw [witt_vector.ext_iff] at h, simpa only [coeff_out] using h ↑i end end truncated_witt_vector namespace witt_vector variables {p} (n) section /-- `truncate_fun n x` uses the first `n` entries of `x` to construct a `truncated_witt_vector`, which has the same base `p` as `x`. This function is bundled into a ring homomorphism in `witt_vector.truncate` -/ def truncate_fun (x : 𝕎 R) : truncated_witt_vector p n R := truncated_witt_vector.mk p $ λ i, x.coeff i end variables {n} @[simp] lemma coeff_truncate_fun (x : 𝕎 R) (i : fin n) : (truncate_fun n x).coeff i = x.coeff i := by rw [truncate_fun, truncated_witt_vector.coeff_mk] variable [comm_ring R] @[simp] lemma out_truncate_fun (x : 𝕎 R) : (truncate_fun n x).out = init n x := begin ext i, dsimp [truncated_witt_vector.out, init, select], split_ifs with hi, swap, { refl }, rw [coeff_truncate_fun, fin.coe_mk], end end witt_vector namespace truncated_witt_vector variable [comm_ring R] @[simp] lemma truncate_fun_out (x : truncated_witt_vector p n R) : x.out.truncate_fun n = x := by simp only [witt_vector.truncate_fun, coeff_out, mk_coeff] open witt_vector variables (p n R) include hp instance : has_zero (truncated_witt_vector p n R) := ⟨truncate_fun n 0⟩ instance : has_one (truncated_witt_vector p n R) := ⟨truncate_fun n 1⟩ instance : has_add (truncated_witt_vector p n R) := ⟨λ x y, truncate_fun n (x.out + y.out)⟩ instance : has_mul (truncated_witt_vector p n R) := ⟨λ x y, truncate_fun n (x.out * y.out)⟩ instance : has_neg (truncated_witt_vector p n R) := ⟨λ x, truncate_fun n (- x.out)⟩ instance : has_sub (truncated_witt_vector p n R) := ⟨λ x y, truncate_fun n (x.out - y.out)⟩ @[simp] lemma coeff_zero (i : fin n) : (0 : truncated_witt_vector p n R).coeff i = 0 := begin show coeff i (truncate_fun _ 0 : truncated_witt_vector p n R) = 0, rw [coeff_truncate_fun, witt_vector.zero_coeff], end end truncated_witt_vector /-- A macro tactic used to prove that `truncate_fun` respects ring operations. -/ meta def tactic.interactive.witt_truncate_fun_tac : tactic unit := `[show _ = truncate_fun n _, apply truncated_witt_vector.out_injective, iterate { rw [out_truncate_fun] }, rw init_add <|> rw init_mul <|> rw init_neg <|> rw init_sub] namespace witt_vector variables (p n R) variable [comm_ring R] lemma truncate_fun_surjective : surjective (@truncate_fun p n R) := function.right_inverse.surjective truncated_witt_vector.truncate_fun_out include hp @[simp] lemma truncate_fun_zero : truncate_fun n (0 : 𝕎 R) = 0 := rfl @[simp] lemma truncate_fun_one : truncate_fun n (1 : 𝕎 R) = 1 := rfl variables {p R} @[simp] lemma truncate_fun_add (x y : 𝕎 R) : truncate_fun n (x + y) = truncate_fun n x + truncate_fun n y := by witt_truncate_fun_tac @[simp] lemma truncate_fun_mul (x y : 𝕎 R) : truncate_fun n (x * y) = truncate_fun n x * truncate_fun n y := by witt_truncate_fun_tac lemma truncate_fun_neg (x : 𝕎 R) : truncate_fun n (-x) = -truncate_fun n x := by witt_truncate_fun_tac lemma truncate_fun_sub (x y : 𝕎 R) : truncate_fun n (x - y) = truncate_fun n x - truncate_fun n y := by witt_truncate_fun_tac end witt_vector namespace truncated_witt_vector open witt_vector variables (p n R) variable [comm_ring R] include hp instance : comm_ring (truncated_witt_vector p n R) := (truncate_fun_surjective p n R).comm_ring _ (truncate_fun_zero p n R) (truncate_fun_one p n R) (truncate_fun_add n) (truncate_fun_mul n) (truncate_fun_neg n) (truncate_fun_sub n) end truncated_witt_vector namespace witt_vector open truncated_witt_vector variables (n) variable [comm_ring R] include hp /-- `truncate n` is a ring homomorphism that truncates `x` to its first `n` entries to obtain a `truncated_witt_vector`, which has the same base `p` as `x`. -/ def truncate : 𝕎 R →+* truncated_witt_vector p n R := { to_fun := truncate_fun n, map_zero' := truncate_fun_zero p n R, map_add' := truncate_fun_add n, map_one' := truncate_fun_one p n R, map_mul' := truncate_fun_mul n } variables (p n R) lemma truncate_surjective : surjective (truncate n : 𝕎 R → truncated_witt_vector p n R) := truncate_fun_surjective p n R variables {p n R} @[simp] lemma coeff_truncate (x : 𝕎 R) (i : fin n) : (truncate n x).coeff i = x.coeff i := coeff_truncate_fun _ _ variables (n) lemma mem_ker_truncate (x : 𝕎 R) : x ∈ (@truncate p _ n R _).ker ↔ ∀ i < n, x.coeff i = 0 := begin simp only [ring_hom.mem_ker, truncate, truncate_fun, ring_hom.coe_mk, truncated_witt_vector.ext_iff, truncated_witt_vector.coeff_mk, coeff_zero], exact subtype.forall end variables (p) @[simp] lemma truncate_mk (f : ℕ → R) : truncate n (mk p f) = truncated_witt_vector.mk _ (λ k, f k) := begin ext i, rw [coeff_truncate, coeff_mk, truncated_witt_vector.coeff_mk], end end witt_vector namespace truncated_witt_vector variable [comm_ring R] include hp /-- A ring homomorphism that truncates a truncated Witt vector of length `m` to a truncated Witt vector of length `n`, for `n ≤ m`. -/ def truncate {m : ℕ} (hm : n ≤ m) : truncated_witt_vector p m R →+* truncated_witt_vector p n R := ring_hom.lift_of_right_inverse (witt_vector.truncate m) out truncate_fun_out ⟨witt_vector.truncate n, begin intro x, simp only [witt_vector.mem_ker_truncate], intros h i hi, exact h i (lt_of_lt_of_le hi hm) end⟩ @[simp] lemma truncate_comp_witt_vector_truncate {m : ℕ} (hm : n ≤ m) : (@truncate p _ n R _ m hm).comp (witt_vector.truncate m) = witt_vector.truncate n := ring_hom.lift_of_right_inverse_comp _ _ _ _ @[simp] lemma truncate_witt_vector_truncate {m : ℕ} (hm : n ≤ m) (x : 𝕎 R) : truncate hm (witt_vector.truncate m x) = witt_vector.truncate n x := ring_hom.lift_of_right_inverse_comp_apply _ _ _ _ _ @[simp] lemma truncate_truncate {n₁ n₂ n₃ : ℕ} (h1 : n₁ ≤ n₂) (h2 : n₂ ≤ n₃) (x : truncated_witt_vector p n₃ R) : (truncate h1) (truncate h2 x) = truncate (h1.trans h2) x := begin obtain ⟨x, rfl⟩ := witt_vector.truncate_surjective p n₃ R x, simp only [truncate_witt_vector_truncate], end @[simp] lemma truncate_comp {n₁ n₂ n₃ : ℕ} (h1 : n₁ ≤ n₂) (h2 : n₂ ≤ n₃) : (@truncate p _ _ R _ _ h1).comp (truncate h2) = truncate (h1.trans h2) := begin ext1 x, simp only [truncate_truncate, function.comp_app, ring_hom.coe_comp] end lemma truncate_surjective {m : ℕ} (hm : n ≤ m) : surjective (@truncate p _ _ R _ _ hm) := begin intro x, obtain ⟨x, rfl⟩ := witt_vector.truncate_surjective p _ R x, exact ⟨witt_vector.truncate _ x, truncate_witt_vector_truncate _ _⟩ end @[simp] lemma coeff_truncate {m : ℕ} (hm : n ≤ m) (i : fin n) (x : truncated_witt_vector p m R) : (truncate hm x).coeff i = x.coeff (fin.cast_le hm i) := begin obtain ⟨y, rfl⟩ := witt_vector.truncate_surjective p _ _ x, simp only [truncate_witt_vector_truncate, witt_vector.coeff_truncate, fin.coe_cast_le], end section fintype omit hp instance {R : Type*} [fintype R] : fintype (truncated_witt_vector p n R) := pi.fintype variables (p n R) lemma card {R : Type*} [fintype R] : fintype.card (truncated_witt_vector p n R) = fintype.card R ^ n := by simp only [truncated_witt_vector, fintype.card_fin, fintype.card_fun] end fintype lemma infi_ker_truncate : (⨅ i : ℕ, (@witt_vector.truncate p _ i R _).ker) = ⊥ := begin rw [submodule.eq_bot_iff], intros x hx, ext, simp only [witt_vector.mem_ker_truncate, ideal.mem_infi, witt_vector.zero_coeff] at hx ⊢, exact hx _ _ (nat.lt_succ_self _) end end truncated_witt_vector namespace witt_vector open truncated_witt_vector (hiding truncate coeff) section lift variable [comm_ring R] variables {S : Type*} [semiring S] variable (f : Π k : ℕ, S →+* truncated_witt_vector p k R) variable f_compat : ∀ (k₁ k₂ : ℕ) (hk : k₁ ≤ k₂), (truncated_witt_vector.truncate hk).comp (f k₂) = f k₁ variables {p R} variable (n) /-- Given a family `fₖ : S → truncated_witt_vector p k R` and `s : S`, we produce a Witt vector by defining the `k`th entry to be the final entry of `fₖ s`. -/ def lift_fun (s : S) : 𝕎 R := witt_vector.mk p $ λ k, truncated_witt_vector.coeff (fin.last k) (f (k+1) s) variables {f} include f_compat @[simp] lemma truncate_lift_fun (s : S) : witt_vector.truncate n (lift_fun f s) = f n s := begin ext i, simp only [lift_fun, truncated_witt_vector.coeff_mk, witt_vector.truncate_mk], rw [← f_compat (i+1) n i.is_lt, ring_hom.comp_apply, truncated_witt_vector.coeff_truncate], -- this is a bit unfortunate congr' with _, simp only [fin.coe_last, fin.coe_cast_le], end variable (f) /-- Given compatible ring homs from `S` into `truncated_witt_vector n` for each `n`, we can lift these to a ring hom `S → 𝕎 R`. `lift` defines the universal property of `𝕎 R` as the inverse limit of `truncated_witt_vector n`. -/ def lift : S →+* 𝕎 R := by refine_struct { to_fun := lift_fun f }; { intros, rw [← sub_eq_zero, ← ideal.mem_bot, ← infi_ker_truncate, ideal.mem_infi], simp [ring_hom.mem_ker, f_compat] } variable {f} @[simp] lemma truncate_lift (s : S) : witt_vector.truncate n (lift _ f_compat s) = f n s := truncate_lift_fun _ f_compat s @[simp] lemma truncate_comp_lift : (witt_vector.truncate n).comp (lift _ f_compat) = f n := by { ext1, rw [ring_hom.comp_apply, truncate_lift] } /-- The uniqueness part of the universal property of `𝕎 R`. -/ lemma lift_unique (g : S →+* 𝕎 R) (g_compat : ∀ k, (witt_vector.truncate k).comp g = f k) : lift _ f_compat = g := begin ext1 x, rw [← sub_eq_zero, ← ideal.mem_bot, ← infi_ker_truncate, ideal.mem_infi], intro i, simp only [ring_hom.mem_ker, g_compat, ←ring_hom.comp_apply, truncate_comp_lift, ring_hom.map_sub, sub_self], end omit f_compat include hp /-- The universal property of `𝕎 R` as projective limit of truncated Witt vector rings. -/ @[simps] def lift_equiv : {f : Π k, S →+* truncated_witt_vector p k R // ∀ k₁ k₂ (hk : k₁ ≤ k₂), (truncated_witt_vector.truncate hk).comp (f k₂) = f k₁} ≃ (S →+* 𝕎 R) := { to_fun := λ f, lift f.1 f.2, inv_fun := λ g, ⟨λ k, (truncate k).comp g, by { intros _ _ h, simp only [←ring_hom.comp_assoc, truncate_comp_witt_vector_truncate] }⟩, left_inv := by { rintro ⟨f, hf⟩, simp only [truncate_comp_lift] }, right_inv := λ g, lift_unique _ _ $ λ _, rfl } lemma hom_ext (g₁ g₂ : S →+* 𝕎 R) (h : ∀ k, (truncate k).comp g₁ = (truncate k).comp g₂) : g₁ = g₂ := lift_equiv.symm.injective $ subtype.ext $ funext h end lift end witt_vector
258a7bf5e70dd7a9a03148520c34c51925c2a937
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/computability/halting.lean
72f98378201bbff1407f15f7bc77f40123644306
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
15,368
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import computability.partrec_code /-! # Computability theory and the halting problem > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A universal partial recursive function, Rice's theorem, and the halting problem. ## References * [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019] -/ open encodable denumerable namespace nat.partrec open computable part theorem merge' {f g} (hf : nat.partrec f) (hg : nat.partrec g) : ∃ h, nat.partrec h ∧ ∀ a, (∀ x ∈ h a, x ∈ f a ∨ x ∈ g a) ∧ ((h a).dom ↔ (f a).dom ∨ (g a).dom) := begin obtain ⟨cf, rfl⟩ := code.exists_code.1 hf, obtain ⟨cg, rfl⟩ := code.exists_code.1 hg, have : nat.partrec (λ n, (nat.rfind_opt (λ k, cf.evaln k n <|> cg.evaln k n))) := partrec.nat_iff.1 (partrec.rfind_opt $ primrec.option_orelse.to_comp.comp (code.evaln_prim.to_comp.comp $ (snd.pair (const cf)).pair fst) (code.evaln_prim.to_comp.comp $ (snd.pair (const cg)).pair fst)), refine ⟨_, this, λ n, _⟩, suffices, refine ⟨this, ⟨λ h, (this _ ⟨h, rfl⟩).imp Exists.fst Exists.fst, _⟩⟩, { intro h, rw nat.rfind_opt_dom, simp only [dom_iff_mem, code.evaln_complete, option.mem_def] at h, obtain ⟨x, k, e⟩ | ⟨x, k, e⟩ := h, { refine ⟨k, x, _⟩, simp only [e, option.some_orelse, option.mem_def] }, { refine ⟨k, _⟩, cases cf.evaln k n with y, { exact ⟨x, by simp only [e, option.mem_def, option.none_orelse]⟩ }, { exact ⟨y, by simp only [option.some_orelse, option.mem_def]⟩ } } }, intros x h, obtain ⟨k, e⟩ := nat.rfind_opt_spec h, revert e, simp only [option.mem_def]; cases e' : cf.evaln k n with y; simp; intro, { exact or.inr (code.evaln_sound e) }, { subst y, exact or.inl (code.evaln_sound e') } end end nat.partrec namespace partrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] open computable part nat.partrec (code) nat.partrec.code theorem merge' {f g : α →. σ} (hf : partrec f) (hg : partrec g) : ∃ k : α →. σ, partrec k ∧ ∀ a, (∀ x ∈ k a, x ∈ f a ∨ x ∈ g a) ∧ ((k a).dom ↔ (f a).dom ∨ (g a).dom) := let ⟨k, hk, H⟩ := nat.partrec.merge' (bind_decode₂_iff.1 hf) (bind_decode₂_iff.1 hg) in begin let k' := λ a, (k (encode a)).bind (λ n, decode σ n), refine ⟨k', ((nat_iff.2 hk).comp computable.encode).bind (computable.decode.of_option.comp snd).to₂, λ a, _⟩, suffices, refine ⟨this, ⟨λ h, (this _ ⟨h, rfl⟩).imp Exists.fst Exists.fst, _⟩⟩, { intro h, rw bind_dom, have hk : (k (encode a)).dom := (H _).2.2 (by simpa only [encodek₂, bind_some, coe_some] using h), existsi hk, simp only [exists_prop, mem_map_iff, mem_coe, mem_bind_iff, option.mem_def] at H, obtain ⟨a', ha', y, hy, e⟩ | ⟨a', ha', y, hy, e⟩ := (H _).1 _ ⟨hk, rfl⟩; { simp only [e.symm, encodek] } }, intros x h', simp only [k', exists_prop, mem_coe, mem_bind_iff, option.mem_def] at h', obtain ⟨n, hn, hx⟩ := h', have := (H _).1 _ hn, simp [mem_decode₂, encode_injective.eq_iff] at this, obtain ⟨a', ha, rfl⟩ | ⟨a', ha, rfl⟩ := this; simp only [encodek] at hx; rw hx at ha, { exact or.inl ha }, exact or.inr ha end theorem merge {f g : α →. σ} (hf : partrec f) (hg : partrec g) (H : ∀ a (x ∈ f a) (y ∈ g a), x = y) : ∃ k : α →. σ, partrec k ∧ ∀ a x, x ∈ k a ↔ x ∈ f a ∨ x ∈ g a := let ⟨k, hk, K⟩ := merge' hf hg in ⟨k, hk, λ a x, ⟨(K _).1 _, λ h, begin have : (k a).dom := (K _).2.2 (h.imp Exists.fst Exists.fst), refine ⟨this, _⟩, cases h with h h; cases (K _).1 _ ⟨this, rfl⟩ with h' h', { exact mem_unique h' h }, { exact (H _ _ h _ h').symm }, { exact H _ _ h' _ h }, { exact mem_unique h' h } end⟩⟩ theorem cond {c : α → bool} {f : α →. σ} {g : α →. σ} (hc : computable c) (hf : partrec f) (hg : partrec g) : partrec (λ a, cond (c a) (f a) (g a)) := let ⟨cf, ef⟩ := exists_code.1 hf, ⟨cg, eg⟩ := exists_code.1 hg in ((eval_part.comp (computable.cond hc (const cf) (const cg)) computable.id).bind ((@computable.decode σ _).comp snd).of_option.to₂).of_eq $ λ a, by cases c a; simp [ef, eg, encodek] theorem sum_cases {f : α → β ⊕ γ} {g : α → β →. σ} {h : α → γ →. σ} (hf : computable f) (hg : partrec₂ g) (hh : partrec₂ h) : @partrec _ σ _ _ (λ a, sum.cases_on (f a) (g a) (h a)) := option_some_iff.1 $ (cond (sum_cases hf (const tt).to₂ (const ff).to₂) (sum_cases_left hf (option_some_iff.2 hg).to₂ (const option.none).to₂) (sum_cases_right hf (const option.none).to₂ (option_some_iff.2 hh).to₂)) .of_eq $ λ a, by cases f a; simp only [bool.cond_tt, bool.cond_ff] end partrec /-- A computable predicate is one whose indicator function is computable. -/ def computable_pred {α} [primcodable α] (p : α → Prop) := ∃ [D : decidable_pred p], by exactI computable (λ a, to_bool (p a)) /-- A recursively enumerable predicate is one which is the domain of a computable partial function. -/ def re_pred {α} [primcodable α] (p : α → Prop) := partrec (λ a, part.assert (p a) (λ _, part.some ())) theorem re_pred.of_eq {α} [primcodable α] {p q : α → Prop} (hp : re_pred p) (H : ∀ a, p a ↔ q a) : re_pred q := (funext (λ a, propext (H a)) : p = q) ▸ hp theorem partrec.dom_re {α β} [primcodable α] [primcodable β] {f : α →. β} (h : partrec f) : re_pred (λ a, (f a).dom) := (h.map (computable.const ()).to₂).of_eq $ λ n, part.ext $ λ _, by simp [part.dom_iff_mem] theorem computable_pred.of_eq {α} [primcodable α] {p q : α → Prop} (hp : computable_pred p) (H : ∀ a, p a ↔ q a) : computable_pred q := (funext (λ a, propext (H a)) : p = q) ▸ hp namespace computable_pred variables {α : Type*} {σ : Type*} variables [primcodable α] [primcodable σ] open nat.partrec (code) nat.partrec.code computable theorem computable_iff {p : α → Prop} : computable_pred p ↔ ∃ f : α → bool, computable f ∧ p = λ a, f a := ⟨λ ⟨D, h⟩, by exactI ⟨_, h, funext $ λ a, propext (to_bool_iff _).symm⟩, by rintro ⟨f, h, rfl⟩; exact ⟨by apply_instance, by simpa using h⟩⟩ protected theorem not {p : α → Prop} (hp : computable_pred p) : computable_pred (λ a, ¬ p a) := by obtain ⟨f, hf, rfl⟩ := computable_iff.1 hp; exact ⟨by apply_instance, (cond hf (const ff) (const tt)).of_eq (λ n, by {dsimp, cases f n; refl})⟩ theorem to_re {p : α → Prop} (hp : computable_pred p) : re_pred p := begin obtain ⟨f, hf, rfl⟩ := computable_iff.1 hp, unfold re_pred, refine (partrec.cond hf (decidable.partrec.const' (part.some ())) partrec.none).of_eq (λ n, part.ext $ λ a, _), cases a, cases f n; simp end theorem rice (C : set (ℕ →. ℕ)) (h : computable_pred (λ c, eval c ∈ C)) {f g} (hf : nat.partrec f) (hg : nat.partrec g) (fC : f ∈ C) : g ∈ C := begin cases h with _ h, resetI, obtain ⟨c, e⟩ := fixed_point₂ (partrec.cond (h.comp fst) ((partrec.nat_iff.2 hg).comp snd).to₂ ((partrec.nat_iff.2 hf).comp snd).to₂).to₂, simp at e, by_cases H : eval c ∈ C, { simp only [H, if_true] at e, rwa ← e }, { simp only [H, if_false] at e, rw e at H, contradiction } end theorem rice₂ (C : set code) (H : ∀ cf cg, eval cf = eval cg → (cf ∈ C ↔ cg ∈ C)) : computable_pred (λ c, c ∈ C) ↔ C = ∅ ∨ C = set.univ := by classical; exact have hC : ∀ f, f ∈ C ↔ eval f ∈ eval '' C, from λ f, ⟨set.mem_image_of_mem _, λ ⟨g, hg, e⟩, (H _ _ e).1 hg⟩, ⟨λ h, or_iff_not_imp_left.2 $ λ C0, set.eq_univ_of_forall $ λ cg, let ⟨cf, fC⟩ := set.nonempty_iff_ne_empty.2 C0 in (hC _).2 $ rice (eval '' C) (h.of_eq hC) (partrec.nat_iff.1 $ eval_part.comp (const cf) computable.id) (partrec.nat_iff.1 $ eval_part.comp (const cg) computable.id) ((hC _).1 fC), λ h, by obtain rfl | rfl := h; simp [computable_pred, set.mem_empty_iff_false]; exact ⟨by apply_instance, computable.const _⟩⟩ theorem halting_problem_re (n) : re_pred (λ c, (eval c n).dom) := (eval_part.comp computable.id (computable.const _)).dom_re theorem halting_problem (n) : ¬ computable_pred (λ c, (eval c n).dom) | h := rice {f | (f n).dom} h nat.partrec.zero nat.partrec.none trivial -- Post's theorem on the equivalence of r.e., co-r.e. sets and -- computable sets. The assumption that p is decidable is required -- unless we assume Markov's principle or LEM. @[nolint decidable_classical] theorem computable_iff_re_compl_re {p : α → Prop} [decidable_pred p] : computable_pred p ↔ re_pred p ∧ re_pred (λ a, ¬ p a) := ⟨λ h, ⟨h.to_re, h.not.to_re⟩, λ ⟨h₁, h₂⟩, ⟨‹_›, begin obtain ⟨k, pk, hk⟩ := partrec.merge (h₁.map (computable.const tt).to₂) (h₂.map (computable.const ff).to₂) _, { refine partrec.of_eq pk (λ n, part.eq_some_iff.2 _), rw hk, simp, apply decidable.em }, { intros a x hx y hy, simp at hx hy, cases hy.1 hx.1 } end⟩⟩ theorem computable_iff_re_compl_re' {p : α → Prop} : computable_pred p ↔ re_pred p ∧ re_pred (λ a, ¬ p a) := by classical; exact computable_iff_re_compl_re theorem halting_problem_not_re (n) : ¬ re_pred (λ c, ¬ (eval c n).dom) | h := halting_problem _ $ computable_iff_re_compl_re'.2 ⟨halting_problem_re _, h⟩ end computable_pred namespace nat open vector part /-- A simplified basis for `partrec`. -/ inductive partrec' : ∀ {n}, (vector ℕ n →. ℕ) → Prop | prim {n f} : @primrec' n f → @partrec' n f | comp {m n f} (g : fin n → vector ℕ m →. ℕ) : partrec' f → (∀ i, partrec' (g i)) → partrec' (λ v, m_of_fn (λ i, g i v) >>= f) | rfind {n} {f : vector ℕ (n+1) → ℕ} : @partrec' (n+1) f → partrec' (λ v, rfind (λ n, some (f (n ::ᵥ v) = 0))) end nat namespace nat.partrec' open vector partrec computable nat (partrec') nat.partrec' theorem to_part {n f} (pf : @partrec' n f) : partrec f := begin induction pf, case nat.partrec'.prim : n f hf { exact hf.to_prim.to_comp }, case nat.partrec'.comp : m n f g _ _ hf hg { exact (vector_m_of_fn (λ i, hg i)).bind (hf.comp snd) }, case nat.partrec'.rfind : n f _ hf { have := ((primrec.eq.comp primrec.id (primrec.const 0)).to_comp.comp (hf.comp (vector_cons.comp snd fst))).to₂.partrec₂, exact this.rfind }, end theorem of_eq {n} {f g : vector ℕ n →. ℕ} (hf : partrec' f) (H : ∀ i, f i = g i) : partrec' g := (funext H : f = g) ▸ hf theorem of_prim {n} {f : vector ℕ n → ℕ} (hf : primrec f) : @partrec' n f := prim (nat.primrec'.of_prim hf) theorem head {n : ℕ} : @partrec' n.succ (@head ℕ n) := prim nat.primrec'.head theorem tail {n f} (hf : @partrec' n f) : @partrec' n.succ (λ v, f v.tail) := (hf.comp _ (λ i, @prim _ _ $ nat.primrec'.nth i.succ)).of_eq $ λ v, by simp; rw [← of_fn_nth v.tail]; congr; funext i; simp protected theorem bind {n f g} (hf : @partrec' n f) (hg : @partrec' (n+1) g) : @partrec' n (λ v, (f v).bind (λ a, g (a ::ᵥ v))) := (@comp n (n+1) g (λ i, fin.cases f (λ i v, some (v.nth i)) i) hg (λ i, begin refine fin.cases _ (λ i, _) i; simp *, exact prim (nat.primrec'.nth _) end)).of_eq $ λ v, by simp [m_of_fn, part.bind_assoc, pure] protected theorem map {n f} {g : vector ℕ (n+1) → ℕ} (hf : @partrec' n f) (hg : @partrec' (n+1) g) : @partrec' n (λ v, (f v).map (λ a, g (a ::ᵥ v))) := by simp [(part.bind_some_eq_map _ _).symm]; exact hf.bind hg local attribute [-instance] part.has_zero /-- Analogous to `nat.partrec'` for `ℕ`-valued functions, a predicate for partial recursive vector-valued functions.-/ def vec {n m} (f : vector ℕ n → vector ℕ m) := ∀ i, partrec' (λ v, (f v).nth i) theorem vec.prim {n m f} (hf : @nat.primrec'.vec n m f) : vec f := λ i, prim $ hf i protected theorem nil {n} : @vec n 0 (λ _, nil) := λ i, i.elim0 protected theorem cons {n m} {f : vector ℕ n → ℕ} {g} (hf : @partrec' n f) (hg : @vec n m g) : vec (λ v, f v ::ᵥ g v) := λ i, fin.cases (by simp *) (λ i, by simp only [hg i, nth_cons_succ]) i theorem idv {n} : @vec n n id := vec.prim nat.primrec'.idv theorem comp' {n m f g} (hf : @partrec' m f) (hg : @vec n m g) : partrec' (λ v, f (g v)) := (hf.comp _ hg).of_eq $ λ v, by simp theorem comp₁ {n} (f : ℕ →. ℕ) {g : vector ℕ n → ℕ} (hf : @partrec' 1 (λ v, f v.head)) (hg : @partrec' n g) : @partrec' n (λ v, f (g v)) := by simpa using hf.comp' (partrec'.cons hg partrec'.nil) theorem rfind_opt {n} {f : vector ℕ (n+1) → ℕ} (hf : @partrec' (n+1) f) : @partrec' n (λ v, nat.rfind_opt (λ a, of_nat (option ℕ) (f (a ::ᵥ v)))) := ((rfind $ (of_prim (primrec.nat_sub.comp (primrec.const 1) primrec.vector_head)) .comp₁ (λ n, part.some (1 - n)) hf) .bind ((prim nat.primrec'.pred).comp₁ nat.pred hf)).of_eq $ λ v, part.ext $ λ b, begin simp only [nat.rfind_opt, exists_prop, tsub_eq_zero_iff_le, pfun.coe_val, part.mem_bind_iff, part.mem_some_iff, option.mem_def, part.mem_coe], refine exists_congr (λ a, (and_congr (iff_of_eq _) iff.rfl).trans (and_congr_right (λ h, _))), { congr, funext n, simp only [part.some_inj, pfun.coe_val], cases f (n ::ᵥ v); simp [nat.succ_le_succ]; refl }, { have := nat.rfind_spec h, simp only [pfun.coe_val, part.mem_some_iff] at this, cases f (a ::ᵥ v) with c, {cases this}, rw [← option.some_inj, eq_comm], refl } end open nat.partrec.code theorem of_part : ∀ {n f}, partrec f → @partrec' n f := suffices ∀ f, nat.partrec f → @partrec' 1 (λ v, f v.head), from λ n f hf, begin let g, swap, exact (comp₁ g (this g hf) (prim nat.primrec'.encode)).of_eq (λ i, by dsimp only [g]; simp [encodek, part.map_id']), end, λ f hf, begin obtain ⟨c, rfl⟩ := exists_code.1 hf, simpa [eval_eq_rfind_opt] using (rfind_opt $ of_prim $ primrec.encode_iff.2 $ evaln_prim.comp $ (primrec.vector_head.pair (primrec.const c)).pair $ primrec.vector_head.comp primrec.vector_tail) end theorem part_iff {n f} : @partrec' n f ↔ partrec f := ⟨to_part, of_part⟩ theorem part_iff₁ {f : ℕ →. ℕ} : @partrec' 1 (λ v, f v.head) ↔ partrec f := part_iff.trans ⟨ λ h, (h.comp $ (primrec.vector_of_fn $ λ i, primrec.id).to_comp).of_eq (λ v, by simp only [id.def, head_of_fn]), λ h, h.comp vector_head⟩ theorem part_iff₂ {f : ℕ → ℕ →. ℕ} : @partrec' 2 (λ v, f v.head v.tail.head) ↔ partrec₂ f := part_iff.trans ⟨ λ h, (h.comp $ vector_cons.comp fst $ vector_cons.comp snd (const nil)).of_eq (λ v, by simp only [cons_head, cons_tail]), λ h, h.comp vector_head (vector_head.comp vector_tail)⟩ theorem vec_iff {m n f} : @vec m n f ↔ computable f := ⟨λ h, by simpa only [of_fn_nth] using vector_of_fn (λ i, to_part (h i)), λ h i, of_part $ vector_nth.comp h (const i)⟩ end nat.partrec'
be65b27ebfaf821e4e8e3501affeeb006d288003
130c49f47783503e462c16b2eff31933442be6ff
/stage0/src/Init/System/IO.lean
049c9d16808611889f4f796026c338d027c2a781
[ "Apache-2.0" ]
permissive
Hazel-Brown/lean4
8aa5860e282435ffc30dcdfccd34006c59d1d39c
79e6732fc6bbf5af831b76f310f9c488d44e7a16
refs/heads/master
1,689,218,208,951
1,629,736,869,000
1,629,736,896,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
20,718
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Luke Nelson, Jared Roesch, Leonardo de Moura, Sebastian Ullrich -/ prelude import Init.Control.EState import Init.Control.Reader import Init.Data.String import Init.Data.ByteArray import Init.System.IOError import Init.System.FilePath import Init.System.ST import Init.Data.ToString.Macro import Init.Data.Ord open System /-- Like https://hackage.haskell.org/package/ghc-Prim-0.5.2.0/docs/GHC-Prim.html#t:RealWorld. Makes sure we never reorder `IO` operations. TODO: mark opaque -/ def IO.RealWorld : Type := Unit /- TODO(Leo): mark it as an opaque definition. Reason: prevent functions defined in other modules from accessing `IO.RealWorld`. We don't want action such as ``` def getWorld : IO (IO.RealWorld) := get ``` -/ def EIO (ε : Type) : Type → Type := EStateM ε IO.RealWorld @[inline] def EIO.catchExceptions (x : EIO ε α) (h : ε → EIO Empty α) : EIO Empty α := fun s => match x s with | EStateM.Result.ok a s => EStateM.Result.ok a s | EStateM.Result.error ex s => h ex s instance : Monad (EIO ε) := inferInstanceAs (Monad (EStateM ε IO.RealWorld)) instance : MonadFinally (EIO ε) := inferInstanceAs (MonadFinally (EStateM ε IO.RealWorld)) instance : MonadExceptOf ε (EIO ε) := inferInstanceAs (MonadExceptOf ε (EStateM ε IO.RealWorld)) instance : OrElse (EIO ε α) := ⟨MonadExcept.orelse⟩ instance [Inhabited ε] : Inhabited (EIO ε α) := inferInstanceAs (Inhabited (EStateM ε IO.RealWorld α)) open IO (Error) in abbrev IO : Type → Type := EIO Error @[inline] def EIO.toIO (f : ε → IO.Error) (x : EIO ε α) : IO α := x.adaptExcept f @[inline] def EIO.toIO' (x : EIO ε α) : IO (Except ε α) := EIO.toIO (fun _ => unreachable!) (observing x) @[inline] def IO.toEIO (f : IO.Error → ε) (x : IO α) : EIO ε α := x.adaptExcept f /- After we inline `EState.run'`, the closed term `((), ())` is generated, where the second `()` represents the "initial world". We don't want to cache this closed term. So, we disable the "extract closed terms" optimization. -/ set_option compiler.extract_closed false in @[inline] unsafe def unsafeEIO (fn : EIO ε α) : Except ε α := match fn.run () with | EStateM.Result.ok a _ => Except.ok a | EStateM.Result.error e _ => Except.error e @[inline] unsafe def unsafeIO (fn : IO α) : Except IO.Error α := unsafeEIO fn @[extern "lean_io_timeit"] constant timeit (msg : @& String) (fn : IO α) : IO α @[extern "lean_io_allocprof"] constant allocprof (msg : @& String) (fn : IO α) : IO α /- Programs can execute IO actions during initialization that occurs before the `main` function is executed. The attribute `[init <action>]` specifies which IO action is executed to set the value of an opaque constant. The action `initializing` returns `true` iff it is invoked during initialization. -/ @[extern "lean_io_initializing"] constant IO.initializing : IO Bool namespace IO def ofExcept [ToString ε] (e : Except ε α) : IO α := match e with | Except.ok a => pure a | Except.error e => throw (IO.userError (toString e)) def lazyPure (fn : Unit → α) : IO α := pure (fn ()) /-- Monotonically increasing time since an unspecified past point in milliseconds. No relation to wall clock time. -/ @[extern "lean_io_mono_ms_now"] constant monoMsNow : IO Nat /-- Read bytes from a system entropy source. Not guaranteed to be cryptographically secure. If `nBytes = 0`, return immediately with an empty buffer. -/ @[extern "lean_io_get_random_bytes"] constant getRandomBytes (nBytes : USize) : IO ByteArray def sleep (ms : UInt32) : IO Unit := -- TODO: add a proper primitive for IO.sleep fun s => dbgSleep ms fun _ => EStateM.Result.ok () s /-- Run `act` in a separate `Task`. This is similar to Haskell's [`unsafeInterleaveIO`](http://hackage.haskell.org/package/base-4.14.0.0/docs/System-IO-Unsafe.html#v:unsafeInterleaveIO), except that the `Task` is started eagerly as usual. Thus pure accesses to the `Task` do not influence the impure `act` computation. Unlike with pure tasks created by `Task.mk`, tasks created by this function will be run even if the last reference to the task is dropped. `act` should manually check for cancellation via `IO.checkCanceled` if it wants to react to that. -/ @[extern "lean_io_as_task"] constant asTask (act : IO α) (prio := Task.Priority.default) : IO (Task (Except IO.Error α)) /-- See `IO.asTask`. -/ @[extern "lean_io_map_task"] constant mapTask (f : α → IO β) (t : Task α) (prio := Task.Priority.default) : IO (Task (Except IO.Error β)) /-- See `IO.asTask`. -/ @[extern "lean_io_bind_task"] constant bindTask (t : Task α) (f : α → IO (Task (Except IO.Error β))) (prio := Task.Priority.default) : IO (Task (Except IO.Error β)) def mapTasks (f : List α → IO β) (tasks : List (Task α)) (prio := Task.Priority.default) : IO (Task (Except IO.Error β)) := go tasks [] where go | t::ts, as => IO.bindTask t (fun a => go ts (a :: as)) prio | [], as => IO.asTask (f as.reverse) prio /-- Check if the task's cancellation flag has been set by calling `IO.cancel` or dropping the last reference to the task. -/ @[extern "lean_io_check_canceled"] constant checkCanceled : IO Bool /-- Request cooperative cancellation of the task. The task must explicitly call `IO.checkCanceled` to react to the cancellation. -/ @[extern "lean_io_cancel"] constant cancel : @& Task α → IO Unit /-- Check if the task has finished execution, at which point calling `Task.get` will return immediately. -/ @[extern "lean_io_has_finished"] constant hasFinished : @& Task α → IO Bool /-- Wait for the task to finish, then return its result. -/ @[extern "lean_io_wait"] constant wait : Task α → IO α /-- Wait until any of the tasks in the given list has finished, then return its result. -/ @[extern "lean_io_wait_any"] constant waitAny : @& List (Task α) → IO α /-- Helper method for implementing "deterministic" timeouts. It is the numbe of "small" memory allocations performed by the current execution thread. -/ @[extern "lean_io_get_num_heartbeats"] constant getNumHeartbeats : EIO ε Nat inductive FS.Mode where | read | write | readWrite | append constant FS.Handle : Type := Unit /-- A pure-Lean abstraction of POSIX streams. We use `Stream`s for the standard streams stdin/stdout/stderr so we can capture output of `#eval` commands into memory. -/ structure FS.Stream where isEof : IO Bool flush : IO Unit read : USize → IO ByteArray write : ByteArray → IO Unit getLine : IO String putStr : String → IO Unit open FS @[extern "lean_get_stdin"] constant getStdin : IO FS.Stream @[extern "lean_get_stdout"] constant getStdout : IO FS.Stream @[extern "lean_get_stderr"] constant getStderr : IO FS.Stream /-- Replaces the stdin stream of the current thread and returns its previous value. -/ @[extern "lean_get_set_stdin"] constant setStdin : FS.Stream → IO FS.Stream /-- Replaces the stdout stream of the current thread and returns its previous value. -/ @[extern "lean_get_set_stdout"] constant setStdout : FS.Stream → IO FS.Stream /-- Replaces the stderr stream of the current thread and returns its previous value. -/ @[extern "lean_get_set_stderr"] constant setStderr : FS.Stream → IO FS.Stream @[specialize] partial def iterate (a : α) (f : α → IO (Sum α β)) : IO β := do let v ← f a match v with | Sum.inl a => iterate a f | Sum.inr b => pure b namespace FS namespace Handle private def fopenFlags (m : FS.Mode) (b : Bool) : String := let mode := match m with | FS.Mode.read => "r" | FS.Mode.write => "w" | FS.Mode.readWrite => "r+" | FS.Mode.append => "a" ; let bin := if b then "b" else "t" mode ++ bin @[extern "lean_io_prim_handle_mk"] constant mkPrim (fn : @& FilePath) (mode : @& String) : IO Handle def mk (fn : FilePath) (Mode : Mode) (bin : Bool := true) : IO Handle := mkPrim fn (fopenFlags Mode bin) /-- Returns whether the end of the file has been reached while reading a file. `h.isEof` returns true /after/ the first attempt at reading past the end of `h`. Once `h.isEof` is true, reading `h` will always return an empty array. -/ @[extern "lean_io_prim_handle_is_eof"] constant isEof (h : @& Handle) : IO Bool @[extern "lean_io_prim_handle_flush"] constant flush (h : @& Handle) : IO Unit @[extern "lean_io_prim_handle_read"] constant read (h : @& Handle) (bytes : USize) : IO ByteArray @[extern "lean_io_prim_handle_write"] constant write (h : @& Handle) (buffer : @& ByteArray) : IO Unit @[extern "lean_io_prim_handle_get_line"] constant getLine (h : @& Handle) : IO String @[extern "lean_io_prim_handle_put_str"] constant putStr (h : @& Handle) (s : @& String) : IO Unit end Handle @[extern "lean_io_realpath"] constant realPath (fname : FilePath) : IO FilePath @[extern "lean_io_remove_file"] constant removeFile (fname : @& FilePath) : IO Unit @[extern "lean_io_create_dir"] constant createDir : @& FilePath → IO Unit end FS @[extern "lean_io_getenv"] constant getEnv (var : @& String) : IO (Option String) @[extern "lean_io_app_path"] constant appPath : IO FilePath @[extern "lean_io_current_dir"] constant currentDir : IO FilePath namespace FS @[inline] def withFile (fn : FilePath) (mode : Mode) (f : Handle → IO α) : IO α := Handle.mk fn mode >>= f def Handle.putStrLn (h : Handle) (s : String) : IO Unit := h.putStr (s.push '\n') partial def Handle.readBinToEnd (h : Handle) : IO ByteArray := do let rec loop (acc : ByteArray) : IO ByteArray := do let buf ← h.read 1024 if buf.isEmpty then return acc else loop (acc ++ buf) loop ByteArray.empty partial def Handle.readToEnd (h : Handle) : IO String := do let rec loop (s : String) := do let line ← h.getLine if line.isEmpty then return s else loop (s ++ line) loop "" def readBinFile (fname : FilePath) : IO ByteArray := do let h ← Handle.mk fname Mode.read true h.readBinToEnd def readFile (fname : FilePath) : IO String := do let h ← Handle.mk fname Mode.read false h.readToEnd partial def lines (fname : FilePath) : IO (Array String) := do let h ← Handle.mk fname Mode.read false let rec read (lines : Array String) := do let line ← h.getLine if line.length == 0 then pure lines else if line.back == '\n' then let line := line.dropRight 1 let line := if System.Platform.isWindows && line.back == '\x0d' then line.dropRight 1 else line read <| lines.push line else pure <| lines.push line read #[] def writeBinFile (fname : FilePath) (content : ByteArray) : IO Unit := do let h ← Handle.mk fname Mode.write true h.write content def writeFile (fname : FilePath) (content : String) : IO Unit := do let h ← Handle.mk fname Mode.write false h.putStr content def Stream.putStrLn (strm : FS.Stream) (s : String) : IO Unit := strm.putStr (s.push '\n') structure DirEntry where root : FilePath fileName : String deriving Repr def DirEntry.path (entry : DirEntry) : FilePath := entry.root / entry.fileName inductive FileType where | dir | file | symlink | other deriving Repr, BEq structure SystemTime where sec : Int nsec : UInt32 deriving Repr, BEq, Ord, Inhabited instance : LT SystemTime := ltOfOrd instance : LE SystemTime := leOfOrd structure Metadata where --permissions : ... accessed : SystemTime modified : SystemTime byteSize : UInt64 type : FileType deriving Repr end FS end IO namespace System.FilePath open IO @[extern "lean_io_read_dir"] constant readDir : @& FilePath → IO (Array IO.FS.DirEntry) @[extern "lean_io_metadata"] constant metadata : @& FilePath → IO IO.FS.Metadata def isDir (p : FilePath) : IO Bool := try return (← p.metadata).type == IO.FS.FileType.dir catch _ => return false def pathExists (p : FilePath) : IO Bool := (p.metadata *> pure true) <|> pure false end System.FilePath namespace IO def withStdin [Monad m] [MonadFinally m] [MonadLiftT IO m] (h : FS.Stream) (x : m α) : m α := do let prev ← setStdin h try x finally discard <| setStdin prev def withStdout [Monad m] [MonadFinally m] [MonadLiftT IO m] (h : FS.Stream) (x : m α) : m α := do let prev ← setStdout h try x finally discard <| setStdout prev def withStderr [Monad m] [MonadFinally m] [MonadLiftT IO m] (h : FS.Stream) (x : m α) : m α := do let prev ← setStderr h try x finally discard <| setStderr prev def print [ToString α] (s : α) : IO Unit := do let out ← getStdout out.putStr <| toString s def println [ToString α] (s : α) : IO Unit := print ((toString s).push '\n') def eprint [ToString α] (s : α) : IO Unit := do let out ← getStderr out.putStr <| toString s def eprintln [ToString α] (s : α) : IO Unit := eprint <| toString s |>.push '\n' @[export lean_io_eprintln] private def eprintlnAux (s : String) : IO Unit := eprintln s def appDir : IO FilePath := do let p ← appPath let some p ← pure p.parent | throw <| IO.userError s!"System.IO.appDir: unexpected filename '{p}'" FS.realPath p partial def FS.createDirAll (p : FilePath) : IO Unit := do if ← p.isDir then return () if let some parent := p.parent then createDirAll parent try createDir p catch | e => if ← p.isDir then pure () -- I guess someone else was faster else throw e namespace Process inductive Stdio where | piped | inherit | null def Stdio.toHandleType : Stdio → Type | Stdio.piped => FS.Handle | Stdio.inherit => Unit | Stdio.null => Unit structure StdioConfig where /- Configuration for the process' stdin handle. -/ stdin := Stdio.inherit /- Configuration for the process' stdout handle. -/ stdout := Stdio.inherit /- Configuration for the process' stderr handle. -/ stderr := Stdio.inherit structure SpawnArgs extends StdioConfig where /- Command name. -/ cmd : String /- Arguments for the process -/ args : Array String := #[] /- Working directory for the process. Inherit from current process if `none`. -/ cwd : Option FilePath := none /- Add or remove environment variables for the process. -/ env : Array (String × Option String) := #[] -- TODO(Sebastian): constructor must be private structure Child (cfg : StdioConfig) where stdin : cfg.stdin.toHandleType stdout : cfg.stdout.toHandleType stderr : cfg.stderr.toHandleType @[extern "lean_io_process_spawn"] constant spawn (args : SpawnArgs) : IO (Child args.toStdioConfig) @[extern "lean_io_process_child_wait"] constant Child.wait {cfg : @& StdioConfig} : @& Child cfg → IO UInt32 /-- Extract the `stdin` field from a `Child` object, allowing them to be freed independently. This operation is necessary for closing the child process' stdin while still holding on to a process handle, e.g. for `Child.wait`. A file handle is closed when all references to it are dropped, which without this operation includes the `Child` object. -/ @[extern "lean_io_process_child_take_stdin"] constant Child.takeStdin {cfg : @& StdioConfig} : Child cfg → IO (cfg.stdin.toHandleType × Child { cfg with stdin := Stdio.null }) structure Output where exitCode : UInt32 stdout : String stderr : String /-- Run process to completion and capture output. -/ def output (args : SpawnArgs) : IO Output := do let child ← spawn { args with stdout := Stdio.piped, stderr := Stdio.piped } let stdout ← IO.asTask child.stdout.readToEnd Task.Priority.dedicated let stderr ← child.stderr.readToEnd let exitCode ← child.wait let stdout ← IO.ofExcept stdout.get pure { exitCode := exitCode, stdout := stdout, stderr := stderr } /-- Run process to completion and return stdout on success. -/ def run (args : SpawnArgs) : IO String := do let out ← output args if out.exitCode != 0 then throw <| IO.userError <| "process '" ++ args.cmd ++ "' exited with code " ++ toString out.exitCode pure out.stdout @[extern "lean_io_exit"] constant exit : UInt8 → IO α end Process structure AccessRight where read : Bool := false write : Bool := false execution : Bool := false def AccessRight.flags (acc : AccessRight) : UInt32 := let r : UInt32 := if acc.read then 0x4 else 0 let w : UInt32 := if acc.write then 0x2 else 0 let x : UInt32 := if acc.execution then 0x1 else 0 r.lor <| w.lor x structure FileRight where user : AccessRight := {} group : AccessRight := {} other : AccessRight := {} def FileRight.flags (acc : FileRight) : UInt32 := let u : UInt32 := acc.user.flags.shiftLeft 6 let g : UInt32 := acc.group.flags.shiftLeft 3 let o : UInt32 := acc.other.flags u.lor <| g.lor o @[extern "lean_chmod"] constant Prim.setAccessRights (filename : @& FilePath) (mode : UInt32) : IO Unit def setAccessRights (filename : FilePath) (mode : FileRight) : IO Unit := Prim.setAccessRights filename mode.flags /- References -/ abbrev Ref (α : Type) := ST.Ref IO.RealWorld α instance : MonadLift (ST IO.RealWorld) (EIO ε) := ⟨fun x s => match x s with | EStateM.Result.ok a s => EStateM.Result.ok a s | EStateM.Result.error ex _ => nomatch ex⟩ def mkRef (a : α) : IO (IO.Ref α) := ST.mkRef a namespace FS namespace Stream @[export lean_stream_of_handle] def ofHandle (h : Handle) : Stream := { isEof := Handle.isEof h, flush := Handle.flush h, read := Handle.read h, write := Handle.write h, getLine := Handle.getLine h, putStr := Handle.putStr h, } structure Buffer where data : ByteArray := ByteArray.empty pos : Nat := 0 def ofBuffer (r : Ref Buffer) : Stream := { isEof := do let b ← r.get; pure <| b.pos >= b.data.size, flush := pure (), read := fun n => r.modifyGet fun b => let data := b.data.extract b.pos (b.pos + n.toNat) (data, { b with pos := b.pos + data.size }), write := fun data => r.modify fun b => -- set `exact` to `false` so that repeatedly writing to the stream does not impose quadratic run time { b with data := data.copySlice 0 b.data b.pos data.size false, pos := b.pos + data.size }, getLine := r.modifyGet fun b => let pos := match b.data.findIdx? (start := b.pos) fun u => u == 0 || u = '\n'.toNat.toUInt8 with -- include '\n', but not '\0' | some pos => if b.data.get! pos == 0 then pos else pos + 1 | none => b.data.size (String.fromUTF8Unchecked <| b.data.extract b.pos pos, { b with pos := pos }), putStr := fun s => r.modify fun b => let data := s.toUTF8 { b with data := data.copySlice 0 b.data b.pos data.size false, pos := b.pos + data.size }, } end Stream /-- Run action with `stdin` emptied and `stdout+stderr` captured into a `String`. -/ def withIsolatedStreams [Monad m] [MonadFinally m] [MonadExceptOf IO.Error m] [MonadLiftT IO m] (x : m α) : m (String × Except IO.Error α) := do let bIn ← mkRef { : Stream.Buffer } let bOut ← mkRef { : Stream.Buffer } let r ← withStdin (Stream.ofBuffer bIn) <| withStdout (Stream.ofBuffer bOut) <| withStderr (Stream.ofBuffer bOut) <| observing x let bOut ← liftM (m := IO) bOut.get let out := String.fromUTF8Unchecked bOut.data pure (out, r) end FS end IO universe u namespace Lean /-- Typeclass used for presenting the output of an `#eval` command. -/ class Eval (α : Type u) where -- We default `hideUnit` to `true`, but set it to `false` in the direct call from `#eval` -- so that `()` output is hidden in chained instances such as for some `IO Unit`. -- We take `Unit → α` instead of `α` because ‵α` may contain effectful debugging primitives (e.g., `dbg_trace`) eval : (Unit → α) → forall (hideUnit : optParam Bool true), IO Unit instance [ToString α] : Eval α := ⟨fun a _ => IO.println (toString (a ()))⟩ instance [Repr α] : Eval α := ⟨fun a _ => IO.println (repr (a ()))⟩ instance : Eval Unit := ⟨fun u hideUnit => if hideUnit then pure () else IO.println (repr (u ()))⟩ instance [Eval α] : Eval (IO α) := ⟨fun x _ => do let a ← x (); Eval.eval (fun _ => a)⟩ @[noinline, nospecialize] def runEval [Eval α] (a : Unit → α) : IO (String × Except IO.Error Unit) := IO.FS.withIsolatedStreams (Eval.eval a false) end Lean syntax "println! " (interpolatedStr(term) <|> term) : term macro_rules | `(println! $msg) => if msg.getKind == Lean.interpolatedStrKind then `((IO.println (s! $msg) : IO Unit)) else `((IO.println $msg : IO Unit))
0c34072813a5846bbf22040e5ca706203d3fa661
00de0c30dd1b090ed139f65c82ea6deb48c3f4c2
/src/algebra/char_p.lean
441f61f06fe841e1b0a48062cf7d1ae9f6649afc
[ "Apache-2.0" ]
permissive
paulvanwamelen/mathlib
4b9c5c19eec71b475f3dd515cd8785f1c8515f26
79e296bdc9f83b9447dc1b81730d36f63a99f72d
refs/heads/master
1,667,766,172,625
1,590,239,595,000
1,590,239,595,000
266,392,625
0
0
Apache-2.0
1,590,257,277,000
1,590,257,277,000
null
UTF-8
Lean
false
false
10,017
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Kenny Lau, Joey van Langen, Casper Putz Characteristic of semirings. -/ import data.fintype.basic import data.nat.choose import data.int.modeq import algebra.module universes u v /-- The generator of the kernel of the unique homomorphism ℕ → α for a semiring α -/ class char_p (α : Type u) [semiring α] (p : ℕ) : Prop := (cast_eq_zero_iff [] : ∀ x:ℕ, (x:α) = 0 ↔ p ∣ x) theorem char_p.cast_eq_zero (α : Type u) [semiring α] (p : ℕ) [char_p α p] : (p:α) = 0 := (char_p.cast_eq_zero_iff α p p).2 (dvd_refl p) lemma char_p.int_cast_eq_zero_iff (R : Type u) [ring R] (p : ℕ) [char_p R p] (a : ℤ) : (a : R) = 0 ↔ (p:ℤ) ∣ a := begin rcases lt_trichotomy a 0 with h|rfl|h, { rw [← neg_eq_zero, ← int.cast_neg, ← dvd_neg], lift -a to ℕ using neg_nonneg.mpr (le_of_lt h) with b, rw [int.cast_coe_nat, char_p.cast_eq_zero_iff R p, int.coe_nat_dvd] }, { simp only [int.cast_zero, eq_self_iff_true, dvd_zero] }, { lift a to ℕ using (le_of_lt h) with b, rw [int.cast_coe_nat, char_p.cast_eq_zero_iff R p, int.coe_nat_dvd] } end theorem char_p.eq (α : Type u) [semiring α] {p q : ℕ} (c1 : char_p α p) (c2 : char_p α q) : p = q := nat.dvd_antisymm ((char_p.cast_eq_zero_iff α p q).1 (char_p.cast_eq_zero _ _)) ((char_p.cast_eq_zero_iff α q p).1 (char_p.cast_eq_zero _ _)) instance char_p.of_char_zero (α : Type u) [semiring α] [char_zero α] : char_p α 0 := ⟨λ x, by rw [zero_dvd_iff, ← nat.cast_zero, nat.cast_inj]⟩ theorem char_p.exists (α : Type u) [semiring α] : ∃ p, char_p α p := by letI := classical.dec_eq α; exact classical.by_cases (assume H : ∀ p:ℕ, (p:α) = 0 → p = 0, ⟨0, ⟨λ x, by rw [zero_dvd_iff]; exact ⟨H x, by rintro rfl; refl⟩⟩⟩) (λ H, ⟨nat.find (classical.not_forall.1 H), ⟨λ x, ⟨λ H1, nat.dvd_of_mod_eq_zero (by_contradiction $ λ H2, nat.find_min (classical.not_forall.1 H) (nat.mod_lt x $ nat.pos_of_ne_zero $ not_of_not_imp $ nat.find_spec (classical.not_forall.1 H)) (not_imp_of_and_not ⟨by rwa [← nat.mod_add_div x (nat.find (classical.not_forall.1 H)), nat.cast_add, nat.cast_mul, of_not_not (not_not_of_not_imp $ nat.find_spec (classical.not_forall.1 H)), zero_mul, add_zero] at H1, H2⟩)), λ H1, by rw [← nat.mul_div_cancel' H1, nat.cast_mul, of_not_not (not_not_of_not_imp $ nat.find_spec (classical.not_forall.1 H)), zero_mul]⟩⟩⟩) theorem char_p.exists_unique (α : Type u) [semiring α] : ∃! p, char_p α p := let ⟨c, H⟩ := char_p.exists α in ⟨c, H, λ y H2, char_p.eq α H2 H⟩ /-- Noncomuptable function that outputs the unique characteristic of a semiring. -/ noncomputable def ring_char (α : Type u) [semiring α] : ℕ := classical.some (char_p.exists_unique α) theorem ring_char.spec (α : Type u) [semiring α] : ∀ x:ℕ, (x:α) = 0 ↔ ring_char α ∣ x := by letI := (classical.some_spec (char_p.exists_unique α)).1; unfold ring_char; exact char_p.cast_eq_zero_iff α (ring_char α) theorem ring_char.eq (α : Type u) [semiring α] {p : ℕ} (C : char_p α p) : p = ring_char α := (classical.some_spec (char_p.exists_unique α)).2 p C theorem add_pow_char (α : Type u) [comm_ring α] {p : ℕ} (hp : nat.prime p) [char_p α p] (x y : α) : (x + y)^p = x^p + y^p := begin rw [add_pow, finset.sum_range_succ, nat.sub_self, pow_zero, nat.choose_self], rw [nat.cast_one, mul_one, mul_one, add_right_inj], transitivity, { refine finset.sum_eq_single 0 _ _, { intros b h1 h2, have := nat.prime.dvd_choose_self (nat.pos_of_ne_zero h2) (finset.mem_range.1 h1) hp, rw [← nat.div_mul_cancel this, nat.cast_mul, char_p.cast_eq_zero α p], simp only [mul_zero] }, { intro H, exfalso, apply H, exact finset.mem_range.2 hp.pos } }, rw [pow_zero, nat.sub_zero, one_mul, nat.choose_zero_right, nat.cast_one, mul_one] end lemma eq_iff_modeq_int (R : Type*) [ring R] (p : ℕ) [char_p R p] (a b : ℤ) : (a : R) = b ↔ a ≡ b [ZMOD p] := by rw [eq_comm, ←sub_eq_zero, ←int.cast_sub, char_p.int_cast_eq_zero_iff R p, int.modeq.modeq_iff_dvd] section frobenius variables (R : Type u) [comm_ring R] {S : Type v} [comm_ring S] (f : R →* S) (g : R →+* S) (p : ℕ) [fact p.prime] [char_p R p] [char_p S p] (x y : R) /-- The frobenius map that sends x to x^p -/ def frobenius : R →+* R := { to_fun := λ x, x^p, map_one' := one_pow p, map_mul' := λ x y, mul_pow x y p, map_zero' := zero_pow (lt_trans zero_lt_one ‹nat.prime p›.one_lt), map_add' := add_pow_char R ‹nat.prime p› } variable {R} theorem frobenius_def : frobenius R p x = x ^ p := rfl theorem frobenius_mul : frobenius R p (x * y) = frobenius R p x * frobenius R p y := (frobenius R p).map_mul x y theorem frobenius_one : frobenius R p 1 = 1 := one_pow _ variable {R} theorem monoid_hom.map_frobenius : f (frobenius R p x) = frobenius S p (f x) := f.map_pow x p theorem ring_hom.map_frobenius : g (frobenius R p x) = frobenius S p (g x) := g.map_pow x p theorem monoid_hom.map_iterate_frobenius (n : ℕ) : f (frobenius R p^[n] x) = (frobenius S p^[n] (f x)) := (nat.iterate₁ $ λ x, (f.map_frobenius p x).symm).symm theorem ring_hom.map_iterate_frobenius (n : ℕ) : g (frobenius R p^[n] x) = (frobenius S p^[n] (g x)) := g.to_monoid_hom.map_iterate_frobenius p x n theorem monoid_hom.iterate_map_frobenius (f : R →* R) (p : ℕ) [fact p.prime] [char_p R p] (n : ℕ) : f^[n] (frobenius R p x) = frobenius R p (f^[n] x) := f.iterate_map_pow _ _ _ theorem ring_hom.iterate_map_frobenius (f : R →+* R) (p : ℕ) [fact p.prime] [char_p R p] (n : ℕ) : f^[n] (frobenius R p x) = frobenius R p (f^[n] x) := f.iterate_map_pow _ _ _ variable (R) theorem frobenius_zero : frobenius R p 0 = 0 := (frobenius R p).map_zero theorem frobenius_add : frobenius R p (x + y) = frobenius R p x + frobenius R p y := (frobenius R p).map_add x y theorem frobenius_neg : frobenius R p (-x) = -frobenius R p x := (frobenius R p).map_neg x theorem frobenius_sub : frobenius R p (x - y) = frobenius R p x - frobenius R p y := (frobenius R p).map_sub x y theorem frobenius_nat_cast (n : ℕ) : frobenius R p n = n := (frobenius R p).map_nat_cast n end frobenius theorem frobenius_inj (α : Type u) [integral_domain α] (p : ℕ) [fact p.prime] [char_p α p] : function.injective (frobenius α p) := λ x h H, by { rw ← sub_eq_zero at H ⊢, rw ← frobenius_sub at H, exact pow_eq_zero H } namespace char_p section variables (α : Type u) [ring α] lemma char_p_to_char_zero [char_p α 0] : char_zero α := add_group.char_zero_of_inj_zero $ λ n h0, eq_zero_of_zero_dvd ((cast_eq_zero_iff α 0 n).mp h0) lemma cast_eq_mod (p : ℕ) [char_p α p] (k : ℕ) : (k : α) = (k % p : ℕ) := calc (k : α) = ↑(k % p + p * (k / p)) : by rw [nat.mod_add_div] ... = ↑(k % p) : by simp[cast_eq_zero] theorem char_ne_zero_of_fintype (p : ℕ) [hc : char_p α p] [fintype α] : p ≠ 0 := assume h : p = 0, have char_zero α := @char_p_to_char_zero α _ (h ▸ hc), absurd (@nat.cast_injective α _ _ this) (not_injective_infinite_fintype coe) end section integral_domain open nat variables (α : Type u) [integral_domain α] theorem char_ne_one (p : ℕ) [hc : char_p α p] : p ≠ 1 := assume hp : p = 1, have ( 1 : α) = 0, by simpa using (cast_eq_zero_iff α p 1).mpr (hp ▸ dvd_refl p), absurd this one_ne_zero theorem char_is_prime_of_ge_two (p : ℕ) [hc : char_p α p] (hp : p ≥ 2) : nat.prime p := suffices ∀d ∣ p, d = 1 ∨ d = p, from ⟨hp, this⟩, assume (d : ℕ) (hdvd : ∃ e, p = d * e), let ⟨e, hmul⟩ := hdvd in have (p : α) = 0, from (cast_eq_zero_iff α p p).mpr (dvd_refl p), have (d : α) * e = 0, from (@cast_mul α _ d e) ▸ (hmul ▸ this), or.elim (no_zero_divisors.eq_zero_or_eq_zero_of_mul_eq_zero (d : α) e this) (assume hd : (d : α) = 0, have p ∣ d, from (cast_eq_zero_iff α p d).mp hd, show d = 1 ∨ d = p, from or.inr (dvd_antisymm ⟨e, hmul⟩ this)) (assume he : (e : α) = 0, have p ∣ e, from (cast_eq_zero_iff α p e).mp he, have e ∣ p, from dvd_of_mul_left_eq d (eq.symm hmul), have e = p, from dvd_antisymm ‹e ∣ p› ‹p ∣ e›, have h₀ : p > 0, from gt_of_ge_of_gt hp (nat.zero_lt_succ 1), have d * p = 1 * p, by rw ‹e = p› at hmul; rw [one_mul]; exact eq.symm hmul, show d = 1 ∨ d = p, from or.inl (eq_of_mul_eq_mul_right h₀ this)) theorem char_is_prime_or_zero (p : ℕ) [hc : char_p α p] : nat.prime p ∨ p = 0 := match p, hc with | 0, _ := or.inr rfl | 1, hc := absurd (eq.refl (1 : ℕ)) (@char_ne_one α _ (1 : ℕ) hc) | (m+2), hc := or.inl (@char_is_prime_of_ge_two α _ (m+2) hc (nat.le_add_left 2 m)) end lemma char_is_prime_of_pos (p : ℕ) [h : fact (0 < p)] [char_p α p] : fact p.prime := (char_p.char_is_prime_or_zero α _).resolve_right (nat.pos_iff_ne_zero.1 h) theorem char_is_prime [fintype α] (p : ℕ) [char_p α p] : p.prime := or.resolve_right (char_is_prime_or_zero α p) (char_ne_zero_of_fintype α p) end integral_domain section char_one variables {R : Type*} section prio set_option default_priority 100 -- see Note [default priority] instance [semiring R] [char_p R 1] : subsingleton R := subsingleton.intro $ suffices ∀ (r : R), r = 0, from assume a b, show a = b, by rw [this a, this b], assume r, calc r = 1 * r : by rw one_mul ... = (1 : ℕ) * r : by rw nat.cast_one ... = 0 * r : by rw char_p.cast_eq_zero ... = 0 : by rw zero_mul end prio lemma false_of_nonzero_of_char_one [nonzero_comm_ring R] [char_p R 1] : false := zero_ne_one $ show (0:R) = 1, from subsingleton.elim 0 1 lemma ring_char_ne_one [nonzero_semiring R] : ring_char R ≠ 1 := by { intros h, apply @zero_ne_one R, symmetry, rw [←nat.cast_one, ring_char.spec, h], } end char_one end char_p
a46a6a4904757ba048d77120386f3b5671686285
01ae0d022f2e2fefdaaa898938c1ac1fbce3b3ab
/categories/universal/monic.lean
83740800e457b77b7a288dae4f19e7541056a59c
[]
no_license
PatrickMassot/lean-category-theory
0f56a83464396a253c28a42dece16c93baf8ad74
ef239978e91f2e1c3b8e88b6e9c64c155dc56c99
refs/heads/master
1,629,739,187,316
1,512,422,659,000
1,512,422,659,000
113,098,786
0
0
null
1,512,424,022,000
1,512,424,022,000
null
UTF-8
Lean
false
false
1,092
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import .universal import ..monic open categories open categories.universal open categories.isomorphism namespace categories structure RegularMonic { C : Category } { X Y : C.Obj } ( f : C.Hom X Y ) := ( Z : C.Obj ) ( a b : C.Hom Y Z ) ( e : Equalizer a b ) ( i : Isomorphism C e.equalizer X ) ( w : e.inclusion = C.compose i.morphism f ) -- EXERCISE -- lemma SplitMonic_implies_RegularMonic -- { C : Category } -- { X Y : C.Obj } -- { f : C.Hom X Y } -- ( s : SplitMonic f ) : RegularMonic f := sorry -- EXERCISE -- lemma RegularMonic_implies_Monic -- { C : Category } -- { X Y : C.Obj } -- { f : C.Hom X Y } -- ( s : RegularMonic f ) : Monic f := sorry structure RegularEpic { C : Category } { Y Z : C.Obj } ( f : C.Hom Y Z ) := ( X : C.Obj ) ( a b : C.Hom X Y ) ( c : Coequalizer a b ) ( i : Isomorphism C c.coequalizer Z ) ( w : c.projection = C.compose f i.inverse ) end categories
6817f39a38d368c3db34e6addb72dcec1c091e85
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/eqn_compiler_variable_or_inaccessible.lean
87fc7872e62d50919cd524cb9fc73cdf050194a9
[ "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
169
lean
example {α : Type} {p q : α → Prop} {x : α} (h : ∀ y, p y → q y) (hx : q x) : ∀ y, x = y ∨ p y → q y | x (or.inr p) := h x p | ._ (or.inl rfl) := hx
1130731ee8bf64d25d8879dd002ba8c7c9d9597d
4950bf76e5ae40ba9f8491647d0b6f228ddce173
/src/tactic/ring.lean
6ae1f208158e1c39e69df5799cbe155bfc57fa0c
[ "Apache-2.0" ]
permissive
ntzwq/mathlib
ca50b21079b0a7c6781c34b62199a396dd00cee2
36eec1a98f22df82eaccd354a758ef8576af2a7f
refs/heads/master
1,675,193,391,478
1,607,822,996,000
1,607,822,996,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
28,777
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import tactic.norm_num import data.int.range /-! # `ring` Evaluate expressions in the language of commutative (semi)rings. Based on <http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf> . -/ namespace tactic namespace ring /-- The normal form that `ring` uses is mediated by the function `horner a x n b := a * x ^ n + b`. The reason we use a definition rather than the (more readable) expression on the right is because this expression contains a number of typeclass arguments in different positions, while `horner` contains only one `comm_semiring` instance at the top level. See also `horner_expr` for a description of normal form. -/ def horner {α} [comm_semiring α] (a x : α) (n : ℕ) (b : α) := a * x ^ n + b /-- This cache contains data required by the `ring` tactic during execution. -/ meta structure cache := (α : expr) (univ : level) (comm_semiring_inst : expr) (red : transparency) (ic : ref instance_cache) (nc : ref instance_cache) (atoms : ref (buffer expr)) /-- The monad that `ring` works in. This is a reader monad containing a mutable cache (using `ref` for mutability), as well as the list of atoms-up-to-defeq encountered thus far, used for atom sorting. -/ @[derive [monad, alternative]] meta def ring_m (α : Type) : Type := reader_t cache tactic α /-- Get the `ring` data from the monad. -/ meta def get_cache : ring_m cache := reader_t.read /-- Get an already encountered atom by its index. -/ meta def get_atom (n : ℕ) : ring_m expr := ⟨λ c, do es ← read_ref c.atoms, pure (es.read' n)⟩ /-- Get the index corresponding to an atomic expression, if it has already been encountered, or put it in the list of atoms and return the new index, otherwise. -/ meta def add_atom (e : expr) : ring_m ℕ := ⟨λ c, do let red := c.red, es ← read_ref c.atoms, es.iterate failed (λ n e' t, t <|> (is_def_eq e e' red $> n)) <|> (es.size <$ write_ref c.atoms (es.push_back e))⟩ /-- Lift a tactic into the `ring_m` monad. -/ @[inline] meta def lift {α} (m : tactic α) : ring_m α := reader_t.lift m /-- Run a `ring_m` tactic in the tactic monad. -/ meta def ring_m.run (red : transparency) (e : expr) {α} (m : ring_m α) : tactic α := do α ← infer_type e, u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, ic ← mk_instance_cache α, (ic, c) ← ic.get ``comm_semiring, nc ← mk_instance_cache `(ℕ), using_new_ref ic $ λ r, using_new_ref nc $ λ nr, using_new_ref mk_buffer $ λ atoms, reader_t.run m ⟨α, u, c, red, r, nr, atoms⟩ /-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This version is abstract over the instance cache in question (either the ring `α`, or `ℕ` for exponents). -/ @[inline] meta def ic_lift' (icf : cache → ref instance_cache) {α} (f : instance_cache → tactic (instance_cache × α)) : ring_m α := ⟨λ c, do let r := icf c, ic ← read_ref r, (ic', a) ← f ic, a <$ write_ref r ic'⟩ /-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This uses the instance cache corresponding to the ring `α`. -/ @[inline] meta def ic_lift {α} : (instance_cache → tactic (instance_cache × α)) → ring_m α := ic_lift' cache.ic /-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This uses the instance cache corresponding to `ℕ`, which is used for computations in the exponent. -/ @[inline] meta def nc_lift {α} : (instance_cache → tactic (instance_cache × α)) → ring_m α := ic_lift' cache.nc /-- Apply a theorem that expects a `comm_semiring` instance. This is a special case of `ic_lift mk_app`, but it comes up often because `horner` and all its theorems have this assumption; it also does not require the tactic monad which improves access speed a bit. -/ meta def cache.cs_app (c : cache) (n : name) : list expr → expr := (@expr.const tt n [c.univ] c.α c.comm_semiring_inst).mk_app /-- Every expression in the language of commutative semirings can be viewed as a sum of monomials, where each monomial is a product of powers of atoms. We fix a global order on atoms (up to definitional equality), and then separate the terms according to their smallest atom. So the top level expression is `a * x^n + b` where `x` is the smallest atom and `n > 0` is a numeral, and `n` is maximal (so `a` contains at least one monomial not containing an `x`), and `b` contains no monomials with an `x` (hence all atoms in `b` are larger than `x`). If there is no `x` satisfying these constraints, then the expression must be a numeral. Even though we are working over rings, we allow rational constants when these can be interpreted in the ring, so we can solve problems like `x / 3 = 1 / 3 * x` even though these are not technically in the language of rings. These constraints ensure that there is a unique normal form for each ring expression, and so the algorithm is simply to calculate the normal form of each side and compare for equality. To allow us to efficiently pattern match on normal forms, we maintain this inductive type that holds a normalized expression together with its structure. All the `expr`s in this type could be removed without loss of information, and conversely the `horner_expr` structure and the `ℕ` and `ℚ` values can be recovered from the top level `expr`, but we keep both in order to keep proof producing normalization functions efficient. -/ meta inductive horner_expr : Type | const (e : expr) (coeff : ℚ) : horner_expr | xadd (e : expr) (a : horner_expr) (x : expr × ℕ) (n : expr × ℕ) (b : horner_expr) : horner_expr /-- Get the expression corresponding to a `horner_expr`. This can be calculated recursively from the structure, but we cache the exprs in all subterms so that this function can be computed in constant time. -/ meta def horner_expr.e : horner_expr → expr | (horner_expr.const e _) := e | (horner_expr.xadd e _ _ _ _) := e /-- Is this expr the constant `0`? -/ meta def horner_expr.is_zero : horner_expr → bool | (horner_expr.const _ c) := c = 0 | _ := ff meta instance : has_coe horner_expr expr := ⟨horner_expr.e⟩ meta instance : has_coe_to_fun horner_expr := ⟨_, λ e, ((e : expr) : expr → expr)⟩ /-- Construct a `xadd` node, generating the cached expr using the input cache. -/ meta def horner_expr.xadd' (c : cache) (a : horner_expr) (x : expr × ℕ) (n : expr × ℕ) (b : horner_expr) : horner_expr := horner_expr.xadd (c.cs_app ``horner [a, x.1, n.1, b]) a x n b open horner_expr /-- Pretty printer for `horner_expr`. -/ meta def horner_expr.to_string : horner_expr → string | (const e c) := to_string (e, c) | (xadd e a x (_, n) b) := "(" ++ a.to_string ++ ") * (" ++ to_string x.1 ++ ")^" ++ to_string n ++ " + " ++ b.to_string /-- Pretty printer for `horner_expr`. -/ meta def horner_expr.pp : horner_expr → tactic format | (const e c) := pp (e, c) | (xadd e a x (_, n) b) := do pa ← a.pp, pb ← b.pp, px ← pp x.1, return $ "(" ++ pa ++ ") * (" ++ px ++ ")^" ++ to_string n ++ " + " ++ pb meta instance : has_to_tactic_format horner_expr := ⟨horner_expr.pp⟩ /-- Reflexivity conversion for a `horner_expr`. -/ meta def horner_expr.refl_conv (e : horner_expr) : ring_m (horner_expr × expr) := do p ← lift $ mk_eq_refl e, return (e, p) theorem zero_horner {α} [comm_semiring α] (x n b) : @horner α _ 0 x n b = b := by simp [horner] theorem horner_horner {α} [comm_semiring α] (a₁ x n₁ n₂ b n') (h : n₁ + n₂ = n') : @horner α _ (horner a₁ x n₁ 0) x n₂ b = horner a₁ x n' b := by simp [h.symm, horner, pow_add, mul_assoc] /-- Evaluate `horner a n x b` where `a` and `b` are already in normal form. -/ meta def eval_horner : horner_expr → expr × ℕ → expr × ℕ → horner_expr → ring_m (horner_expr × expr) | ha@(const a coeff) x n b := do c ← get_cache, if coeff = 0 then return (b, c.cs_app ``zero_horner [x.1, n.1, b]) else (xadd' c ha x n b).refl_conv | ha@(xadd a a₁ x₁ n₁ b₁) x n b := do c ← get_cache, if x₁.2 = x.2 ∧ b₁.e.to_nat = some 0 then do (n', h) ← nc_lift $ λ nc, norm_num.prove_add_nat' nc n₁.1 n.1, return (xadd' c a₁ x (n', n₁.2 + n.2) b, c.cs_app ``horner_horner [a₁, x.1, n₁.1, n.1, b, n', h]) else (xadd' c ha x n b).refl_conv theorem const_add_horner {α} [comm_semiring α] (k a x n b b') (h : k + b = b') : k + @horner α _ a x n b = horner a x n b' := by simp [h.symm, horner]; cc theorem horner_add_const {α} [comm_semiring α] (a x n b k b') (h : b + k = b') : @horner α _ a x n b + k = horner a x n b' := by simp [h.symm, horner, add_assoc] theorem horner_add_horner_lt {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ k a' b') (h₁ : n₁ + k = n₂) (h₂ : (a₁ + horner a₂ x k 0 : α) = a') (h₃ : b₁ + b₂ = b') : @horner α _ a₁ x n₁ b₁ + horner a₂ x n₂ b₂ = horner a' x n₁ b' := by simp [h₂.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]; cc theorem horner_add_horner_gt {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ k a' b') (h₁ : n₂ + k = n₁) (h₂ : (horner a₁ x k 0 + a₂ : α) = a') (h₃ : b₁ + b₂ = b') : @horner α _ a₁ x n₁ b₁ + horner a₂ x n₂ b₂ = horner a' x n₂ b' := by simp [h₂.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]; cc theorem horner_add_horner_eq {α} [comm_semiring α] (a₁ x n b₁ a₂ b₂ a' b' t) (h₁ : a₁ + a₂ = a') (h₂ : b₁ + b₂ = b') (h₃ : horner a' x n b' = t) : @horner α _ a₁ x n b₁ + horner a₂ x n b₂ = t := by simp [h₃.symm, h₂.symm, h₁.symm, horner, add_mul, mul_comm]; cc /-- Evaluate `a + b` where `a` and `b` are already in normal form. -/ meta def eval_add : horner_expr → horner_expr → ring_m (horner_expr × expr) | (const e₁ c₁) (const e₂ c₂) := ic_lift $ λ ic, do let n := c₁ + c₂, (ic, e) ← ic.of_rat n, (ic, p) ← norm_num.prove_add_rat ic e₁ e₂ e c₁ c₂ n, return (ic, const e n, p) | he₁@(const e₁ c₁) he₂@(xadd e₂ a x n b) := do c ← get_cache, if c₁ = 0 then ic_lift $ λ ic, do (ic, p) ← ic.mk_app ``zero_add [e₂], return (ic, he₂, p) else do (b', h) ← eval_add he₁ b, return (xadd' c a x n b', c.cs_app ``const_add_horner [e₁, a, x.1, n.1, b, b', h]) | he₁@(xadd e₁ a x n b) he₂@(const e₂ c₂) := do c ← get_cache, if c₂ = 0 then ic_lift $ λ ic, do (ic, p) ← ic.mk_app ``add_zero [e₁], return (ic, he₁, p) else do (b', h) ← eval_add b he₂, return (xadd' c a x n b', c.cs_app ``horner_add_const [a, x.1, n.1, b, e₂, b', h]) | he₁@(xadd e₁ a₁ x₁ n₁ b₁) he₂@(xadd e₂ a₂ x₂ n₂ b₂) := do c ← get_cache, if x₁.2 < x₂.2 then do (b', h) ← eval_add b₁ he₂, return (xadd' c a₁ x₁ n₁ b', c.cs_app ``horner_add_const [a₁, x₁.1, n₁.1, b₁, e₂, b', h]) else if x₁.2 ≠ x₂.2 then do (b', h) ← eval_add he₁ b₂, return (xadd' c a₂ x₂ n₂ b', c.cs_app ``const_add_horner [e₁, a₂, x₂.1, n₂.1, b₂, b', h]) else if n₁.2 < n₂.2 then do let k := n₂.2 - n₁.2, (ek, h₁) ← nc_lift (λ nc, do (nc, ek) ← nc.of_nat k, (nc, h₁) ← norm_num.prove_add_nat nc n₁.1 ek n₂.1, return (nc, ek, h₁)), α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], (a', h₂) ← eval_add a₁ (xadd' c a₂ x₁ (ek, k) (const α0 0)), (b', h₃) ← eval_add b₁ b₂, return (xadd' c a' x₁ n₁ b', c.cs_app ``horner_add_horner_lt [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, ek, a', b', h₁, h₂, h₃]) else if n₁.2 ≠ n₂.2 then do let k := n₁.2 - n₂.2, (ek, h₁) ← nc_lift (λ nc, do (nc, ek) ← nc.of_nat k, (nc, h₁) ← norm_num.prove_add_nat nc n₂.1 ek n₁.1, return (nc, ek, h₁)), α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], (a', h₂) ← eval_add (xadd' c a₁ x₁ (ek, k) (const α0 0)) a₂, (b', h₃) ← eval_add b₁ b₂, return (xadd' c a' x₁ n₂ b', c.cs_app ``horner_add_horner_gt [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, ek, a', b', h₁, h₂, h₃]) else do (a', h₁) ← eval_add a₁ a₂, (b', h₂) ← eval_add b₁ b₂, (t, h₃) ← eval_horner a' x₁ n₁ b', return (t, c.cs_app ``horner_add_horner_eq [a₁, x₁.1, n₁.1, b₁, a₂, b₂, a', b', t, h₁, h₂, h₃]) theorem horner_neg {α} [comm_ring α] (a x n b a' b') (h₁ : -a = a') (h₂ : -b = b') : -@horner α _ a x n b = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner]; cc /-- Evaluate `-a` where `a` is already in normal form. -/ meta def eval_neg : horner_expr → ring_m (horner_expr × expr) | (const e coeff) := do (e', p) ← ic_lift $ λ ic, norm_num.prove_neg ic e, return (const e' (-coeff), p) | (xadd e a x n b) := do c ← get_cache, (a', h₁) ← eval_neg a, (b', h₂) ← eval_neg b, p ← ic_lift $ λ ic, ic.mk_app ``horner_neg [a, x.1, n.1, b, a', b', h₁, h₂], return (xadd' c a' x n b', p) theorem horner_const_mul {α} [comm_semiring α] (c a x n b a' b') (h₁ : c * a = a') (h₂ : c * b = b') : c * @horner α _ a x n b = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner, mul_add, mul_assoc] theorem horner_mul_const {α} [comm_semiring α] (a x n b c a' b') (h₁ : a * c = a') (h₂ : b * c = b') : @horner α _ a x n b * c = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner, add_mul, mul_right_comm] /-- Evaluate `k * a` where `k` is a rational numeral and `a` is in normal form. -/ meta def eval_const_mul (k : expr × ℚ) : horner_expr → ring_m (horner_expr × expr) | (const e coeff) := do (e', p) ← ic_lift $ λ ic, norm_num.prove_mul_rat ic k.1 e k.2 coeff, return (const e' (k.2 * coeff), p) | (xadd e a x n b) := do c ← get_cache, (a', h₁) ← eval_const_mul a, (b', h₂) ← eval_const_mul b, return (xadd' c a' x n b', c.cs_app ``horner_const_mul [k.1, a, x.1, n.1, b, a', b', h₁, h₂]) theorem horner_mul_horner_zero {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ aa t) (h₁ : @horner α _ a₁ x n₁ b₁ * a₂ = aa) (h₂ : horner aa x n₂ 0 = t) : horner a₁ x n₁ b₁ * horner a₂ x n₂ 0 = t := by rw [← h₂, ← h₁]; simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc] theorem horner_mul_horner {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ aa haa ab bb t) (h₁ : @horner α _ a₁ x n₁ b₁ * a₂ = aa) (h₂ : horner aa x n₂ 0 = haa) (h₃ : a₁ * b₂ = ab) (h₄ : b₁ * b₂ = bb) (H : haa + horner ab x n₁ bb = t) : horner a₁ x n₁ b₁ * horner a₂ x n₂ b₂ = t := by rw [← H, ← h₂, ← h₁, ← h₃, ← h₄]; simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc] /-- Evaluate `a * b` where `a` and `b` are in normal form. -/ meta def eval_mul : horner_expr → horner_expr → ring_m (horner_expr × expr) | (const e₁ c₁) (const e₂ c₂) := do (e', p) ← ic_lift $ λ ic, norm_num.prove_mul_rat ic e₁ e₂ c₁ c₂, return (const e' (c₁ * c₂), p) | (const e₁ c₁) e₂ := if c₁ = 0 then do c ← get_cache, α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], p ← ic_lift $ λ ic, ic.mk_app ``zero_mul [e₂], return (const α0 0, p) else if c₁ = 1 then do p ← ic_lift $ λ ic, ic.mk_app ``one_mul [e₂], return (e₂, p) else eval_const_mul (e₁, c₁) e₂ | e₁ he₂@(const e₂ c₂) := do p₁ ← ic_lift $ λ ic, ic.mk_app ``mul_comm [e₁, e₂], (e', p₂) ← eval_mul he₂ e₁, p ← lift $ mk_eq_trans p₁ p₂, return (e', p) | he₁@(xadd e₁ a₁ x₁ n₁ b₁) he₂@(xadd e₂ a₂ x₂ n₂ b₂) := do c ← get_cache, if x₁.2 < x₂.2 then do (a', h₁) ← eval_mul a₁ he₂, (b', h₂) ← eval_mul b₁ he₂, return (xadd' c a' x₁ n₁ b', c.cs_app ``horner_mul_const [a₁, x₁.1, n₁.1, b₁, e₂, a', b', h₁, h₂]) else if x₁.2 ≠ x₂.2 then do (a', h₁) ← eval_mul he₁ a₂, (b', h₂) ← eval_mul he₁ b₂, return (xadd' c a' x₂ n₂ b', c.cs_app ``horner_const_mul [e₁, a₂, x₂.1, n₂.1, b₂, a', b', h₁, h₂]) else do (aa, h₁) ← eval_mul he₁ a₂, α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], (haa, h₂) ← eval_horner aa x₁ n₂ (const α0 0), if b₂.is_zero then return (haa, c.cs_app ``horner_mul_horner_zero [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, aa, haa, h₁, h₂]) else do (ab, h₃) ← eval_mul a₁ b₂, (bb, h₄) ← eval_mul b₁ b₂, (t, H) ← eval_add haa (xadd' c ab x₁ n₁ bb), return (t, c.cs_app ``horner_mul_horner [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, aa, haa, ab, bb, t, h₁, h₂, h₃, h₄, H]) theorem horner_pow {α} [comm_semiring α] (a x n m n' a') (h₁ : n * m = n') (h₂ : a ^ m = a') : @horner α _ a x n 0 ^ m = horner a' x n' 0 := by simp [h₁.symm, h₂.symm, horner, mul_pow, pow_mul] theorem pow_succ {α} [comm_semiring α] (a n b c) (h₁ : (a:α) ^ n = b) (h₂ : b * a = c) : a ^ (n + 1) = c := by rw [← h₂, ← h₁, pow_succ'] /-- Evaluate `a ^ n` where `a` is in normal form and `n` is a natural numeral. -/ meta def eval_pow : horner_expr → expr × ℕ → ring_m (horner_expr × expr) | e (_, 0) := do c ← get_cache, α1 ← ic_lift $ λ ic, ic.mk_app ``has_one.one [], p ← ic_lift $ λ ic, ic.mk_app ``pow_zero [e], return (const α1 1, p) | e (_, 1) := do p ← ic_lift $ λ ic, ic.mk_app ``pow_one [e], return (e, p) | (const e coeff) (e₂, m) := ic_lift $ λ ic, do (ic, e', p) ← norm_num.prove_pow e coeff ic e₂, return (ic, const e' (coeff ^ m), p) | he@(xadd e a x n b) m := do c ← get_cache, match b.e.to_nat with | some 0 := do (n', h₁) ← nc_lift $ λ nc, norm_num.prove_mul_rat nc n.1 m.1 n.2 m.2, (a', h₂) ← eval_pow a m, α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], return (xadd' c a' x (n', n.2 * m.2) (const α0 0), c.cs_app ``horner_pow [a, x.1, n.1, m.1, n', a', h₁, h₂]) | _ := do e₂ ← nc_lift $ λ nc, nc.of_nat (m.2-1), (tl, hl) ← eval_pow he (e₂, m.2-1), (t, p₂) ← eval_mul tl he, return (t, c.cs_app ``pow_succ [e, e₂, tl, t, hl, p₂]) end theorem horner_atom {α} [comm_semiring α] (x : α) : x = horner 1 x 1 0 := by simp [horner] /-- Evaluate `a` where `a` is an atom. -/ meta def eval_atom (e : expr) : ring_m (horner_expr × expr) := do c ← get_cache, i ← add_atom e, α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], α1 ← ic_lift $ λ ic, ic.mk_app ``has_one.one [], return (xadd' c (const α1 1) (e, i) (`(1), 1) (const α0 0), c.cs_app ``horner_atom [e]) lemma subst_into_pow {α} [monoid α] (l r tl tr t) (prl : (l : α) = tl) (prr : (r : ℕ) = tr) (prt : tl ^ tr = t) : l ^ r = t := by rw [prl, prr, prt] lemma unfold_sub {α} [add_group α] (a b c : α) (h : a + -b = c) : a - b = c := by rw [sub_eq_add_neg, h] lemma unfold_div {α} [division_ring α] (a b c : α) (h : a * b⁻¹ = c) : a / b = c := by rw [div_eq_mul_inv, h] /-- Evaluate a ring expression `e` recursively to normal form, together with a proof of equality. -/ meta def eval : expr → ring_m (horner_expr × expr) | `(%%e₁ + %%e₂) := do (e₁', p₁) ← eval e₁, (e₂', p₂) ← eval e₂, (e', p') ← eval_add e₁' e₂', p ← ic_lift $ λ ic, ic.mk_app ``norm_num.subst_into_add [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | e@`(@has_sub.sub %%α %%inst %%e₁ %%e₂) := mcond (succeeds (lift $ mk_app ``comm_ring [α] >>= mk_instance)) (do e₂' ← ic_lift $ λ ic, ic.mk_app ``has_neg.neg [e₂], e ← ic_lift $ λ ic, ic.mk_app ``has_add.add [e₁, e₂'], (e', p) ← eval e, p' ← ic_lift $ λ ic, ic.mk_app ``unfold_sub [e₁, e₂, e', p], return (e', if inst.const_name = `int.has_sub then `(norm_num.int_sub_hack).mk_app [e₁, e₂, e', p'] else p')) (eval_atom e) | `(- %%e) := do (e₁, p₁) ← eval e, (e₂, p₂) ← eval_neg e₁, p ← ic_lift $ λ ic, ic.mk_app ``norm_num.subst_into_neg [e, e₁, e₂, p₁, p₂], return (e₂, p) | `(%%e₁ * %%e₂) := do (e₁', p₁) ← eval e₁, (e₂', p₂) ← eval e₂, (e', p') ← eval_mul e₁' e₂', p ← ic_lift $ λ ic, ic.mk_app ``norm_num.subst_into_mul [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | e@`(has_inv.inv %%_) := (do (e', p) ← lift $ norm_num.derive e <|> refl_conv e, n ← lift $ e'.to_rat, return (const e' n, p)) <|> eval_atom e | e@`(@has_div.div _ %%inst %%e₁ %%e₂) := mcond (succeeds (do inst' ← ic_lift $ λ ic, ic.mk_app ``division_ring_has_div [], lift $ is_def_eq inst inst')) (do e₂' ← ic_lift $ λ ic, ic.mk_app ``has_inv.inv [e₂], e ← ic_lift $ λ ic, ic.mk_app ``has_mul.mul [e₁, e₂'], (e', p) ← eval e, p' ← ic_lift $ λ ic, ic.mk_app ``unfold_div [e₁, e₂, e', p], return (e', p')) (eval_atom e) | e@`(@has_pow.pow _ _ %%P %%e₁ %%e₂) := do (e₂', p₂) ← lift $ norm_num.derive e₂ <|> refl_conv e₂, match e₂'.to_nat, P with | some k, `(monoid.has_pow) := do (e₁', p₁) ← eval e₁, (e', p') ← eval_pow e₁' (e₂, k), p ← ic_lift $ λ ic, ic.mk_app ``subst_into_pow [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | _, _ := eval_atom e end | e := match e.to_nat with | some n := (const e (rat.of_int n)).refl_conv | none := eval_atom e end /-- Evaluate a ring expression `e` recursively to normal form, together with a proof of equality. -/ meta def eval' (red : transparency) (e : expr) : tactic (expr × expr) := ring_m.run red e $ do (e', p) ← eval e, return (e', p) theorem horner_def' {α} [comm_semiring α] (a x n b) : @horner α _ a x n b = x ^ n * a + b := by simp [horner, mul_comm] theorem mul_assoc_rev {α} [semigroup α] (a b c : α) : a * (b * c) = a * b * c := by simp [mul_assoc] theorem pow_add_rev {α} [monoid α] (a : α) (m n : ℕ) : a ^ m * a ^ n = a ^ (m + n) := by simp [pow_add] theorem pow_add_rev_right {α} [monoid α] (a b : α) (m n : ℕ) : b * a ^ m * a ^ n = b * a ^ (m + n) := by simp [pow_add, mul_assoc] theorem add_neg_eq_sub {α} [add_group α] (a b : α) : a + -b = a - b := (sub_eq_add_neg a b).symm /-- If `ring` fails to close the goal, it falls back on normalizing the expression to a "pretty" form so that you can see why it failed. This setting adjusts the resulting form: * `raw` is the form that `ring` actually uses internally, with iterated applications of `horner`. Not very readable but useful if you don't want any postprocessing. This results in terms like `horner (horner (horner 3 y 1 0) x 2 1) x 1 (horner 1 y 1 0)`. * `horner` maintains the Horner form structure, but it unfolds the `horner` definition itself, and tries to otherwise minimize parentheses. This results in terms like `(3 * x ^ 2 * y + 1) * x + y`. * `SOP` means sum of products form, expanding everything to monomials. This results in terms like `3 * x ^ 3 * y + x + y`. -/ @[derive has_reflect] inductive normalize_mode | raw | SOP | horner instance : inhabited normalize_mode := ⟨normalize_mode.horner⟩ /-- A `ring`-based normalization simplifier that rewrites ring expressions into the specified mode. * `raw` is the form that `ring` actually uses internally, with iterated applications of `horner`. Not very readable but useful if you don't want any postprocessing. This results in terms like `horner (horner (horner 3 y 1 0) x 2 1) x 1 (horner 1 y 1 0)`. * `horner` maintains the Horner form structure, but it unfolds the `horner` definition itself, and tries to otherwise minimize parentheses. This results in terms like `(3 * x ^ 2 * y + 1) * x + y`. * `SOP` means sum of products form, expanding everything to monomials. This results in terms like `3 * x ^ 3 * y + x + y`. -/ meta def normalize (red : transparency) (mode := normalize_mode.horner) (e : expr) : tactic (expr × expr) := do pow_lemma ← simp_lemmas.mk.add_simp ``pow_one, let lemmas := match mode with | normalize_mode.SOP := [``horner_def', ``add_zero, ``mul_one, ``mul_add, ``mul_sub, ``mul_assoc_rev, ``pow_add_rev, ``pow_add_rev_right, ``mul_neg_eq_neg_mul_symm, ``add_neg_eq_sub] | normalize_mode.horner := [``horner.equations._eqn_1, ``add_zero, ``one_mul, ``pow_one, ``neg_mul_eq_neg_mul_symm, ``add_neg_eq_sub] | _ := [] end, lemmas ← lemmas.mfoldl simp_lemmas.add_simp simp_lemmas.mk, (_, e', pr) ← ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ e, do (new_e, pr) ← match mode with | normalize_mode.raw := eval' red | normalize_mode.horner := trans_conv (eval' red) (simplify lemmas []) | normalize_mode.SOP := trans_conv (eval' red) $ trans_conv (simplify lemmas []) $ simp_bottom_up' (λ e, norm_num.derive e <|> pow_lemma.rewrite e) end e, guard (¬ new_e =ₐ e), return ((), new_e, some pr, ff)) (λ _ _ _ _ _, failed) `eq e, return (e', pr) end ring namespace interactive open interactive interactive.types lean.parser open tactic.ring local postfix `?`:9001 := optional /-- Tactic for solving equations in the language of *commutative* (semi)rings. This version of `ring` fails if the target is not an equality that is provable by the axioms of commutative (semi)rings. -/ meta def ring1 (red : parse (tk "!")?) : tactic unit := let transp := if red.is_some then semireducible else reducible in do `(%%e₁ = %%e₂) ← target, ((e₁', p₁), (e₂', p₂)) ← ring_m.run transp e₁ $ prod.mk <$> eval e₁ <*> eval e₂, is_def_eq e₁' e₂', p ← mk_eq_symm p₂ >>= mk_eq_trans p₁, tactic.exact p /-- Parser for `ring`'s `mode` argument, which can only be the "keywords" `raw`, `horner` or `SOP`. (Because these are not actually keywords we use a name parser and postprocess the result.) -/ meta def ring.mode : lean.parser ring.normalize_mode := with_desc "(SOP|raw|horner)?" $ do mode ← ident?, match mode with | none := return ring.normalize_mode.horner | some `horner := return ring.normalize_mode.horner | some `SOP := return ring.normalize_mode.SOP | some `raw := return ring.normalize_mode.raw | _ := failed end /-- Tactic for solving equations in the language of *commutative* (semi)rings. 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 ring expressions into a normal form. When writing a normal form, `ring SOP` will use sum-of-products form instead of horner form. `ring!` will use a more aggressive reducibility setting to identify atoms. Based on [Proving Equalities in a Commutative Ring Done Right in Coq](http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf) by Benjamin Grégoire and Assia Mahboubi. -/ meta def ring (red : parse (tk "!")?) (SOP : parse ring.mode) (loc : parse location) : tactic unit := match loc with | interactive.loc.ns [none] := instantiate_mvars_in_target >> ring1 red | _ := failed end <|> do ns ← loc.get_locals, let transp := if red.is_some then semireducible else reducible, tt ← tactic.replace_at (normalize transp SOP) ns loc.include_goal | fail "ring failed to simplify", when loc.include_goal $ try tactic.reflexivity add_hint_tactic "ring" add_tactic_doc { name := "ring", category := doc_category.tactic, decl_names := [`tactic.interactive.ring], tags := ["arithmetic", "simplification", "decision procedure"] } end interactive end tactic namespace conv.interactive open conv interactive open tactic tactic.interactive (ring.mode ring1) open tactic.ring (normalize) local postfix `?`:9001 := optional /-- Normalises expressions in commutative (semi-)rings inside of a `conv` block using the tactic `ring`. -/ meta def ring (red : parse (lean.parser.tk "!")?) (SOP : parse ring.mode) : conv unit := let transp := if red.is_some then semireducible else reducible in discharge_eq_lhs (ring1 red) <|> replace_lhs (normalize transp SOP) <|> fail "ring failed to simplify" end conv.interactive
fcb6b45342e46141deda0dc36a9075bf4027799d
8b9f17008684d796c8022dab552e42f0cb6fb347
/hott/algebra/precategory/iso.hlean
23866a458e5f6880a3f5577d5048cf6aaa52441c
[ "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
14,275
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: algebra.precategory.iso Author: Floris van Doorn, Jakob von Raumer -/ import algebra.precategory.basic types.sigma arity open eq category prod equiv is_equiv sigma sigma.ops is_trunc namespace iso structure split_mono [class] {ob : Type} [C : precategory ob] {a b : ob} (f : a ⟶ b) := {retraction_of : b ⟶ a} (retraction_comp : retraction_of ∘ f = id) structure split_epi [class] {ob : Type} [C : precategory ob] {a b : ob} (f : a ⟶ b) := {section_of : b ⟶ a} (comp_section : f ∘ section_of = id) structure is_iso [class] {ob : Type} [C : precategory ob] {a b : ob} (f : a ⟶ b) := {inverse : b ⟶ a} (left_inverse : inverse ∘ f = id) (right_inverse : f ∘ inverse = id) attribute is_iso.inverse [quasireducible] attribute is_iso [multiple-instances] open split_mono split_epi is_iso definition retraction_of [reducible] := @split_mono.retraction_of definition retraction_comp [reducible] := @split_mono.retraction_comp definition section_of [reducible] := @split_epi.section_of definition comp_section [reducible] := @split_epi.comp_section definition inverse [reducible] := @is_iso.inverse definition left_inverse [reducible] := @is_iso.left_inverse definition right_inverse [reducible] := @is_iso.right_inverse postfix `⁻¹` := inverse --a second notation for the inverse, which is not overloaded postfix [parsing-only] `⁻¹ʰ`:std.prec.max_plus := inverse -- input using \-1h variables {ob : Type} [C : precategory ob] variables {a b c : ob} {g : b ⟶ c} {f : a ⟶ b} {h : b ⟶ a} include C definition split_mono_of_is_iso [instance] [priority 300] [reducible] (f : a ⟶ b) [H : is_iso f] : split_mono f := split_mono.mk !left_inverse definition split_epi_of_is_iso [instance] [priority 300] [reducible] (f : a ⟶ b) [H : is_iso f] : split_epi f := split_epi.mk !right_inverse definition is_iso_id [instance] [priority 500] (a : ob) : is_iso (ID a) := is_iso.mk !id_comp !id_comp definition is_iso_inverse [instance] [priority 200] (f : a ⟶ b) [H : is_iso f] : is_iso f⁻¹ := is_iso.mk !right_inverse !left_inverse definition left_inverse_eq_right_inverse {f : a ⟶ b} {g g' : hom b a} (Hl : g ∘ f = id) (Hr : f ∘ g' = id) : g = g' := by rewrite [-(id_right g), -Hr, assoc, Hl, id_left] definition retraction_eq [H : split_mono f] (H2 : f ∘ h = id) : retraction_of f = h := left_inverse_eq_right_inverse !retraction_comp H2 definition section_eq [H : split_epi f] (H2 : h ∘ f = id) : section_of f = h := (left_inverse_eq_right_inverse H2 !comp_section)⁻¹ definition inverse_eq_right [H : is_iso f] (H2 : f ∘ h = id) : f⁻¹ = h := left_inverse_eq_right_inverse !left_inverse H2 definition inverse_eq_left [H : is_iso f] (H2 : h ∘ f = id) : f⁻¹ = h := (left_inverse_eq_right_inverse H2 !right_inverse)⁻¹ definition retraction_eq_section (f : a ⟶ b) [Hl : split_mono f] [Hr : split_epi f] : retraction_of f = section_of f := retraction_eq !comp_section definition is_iso_of_split_epi_of_split_mono (f : a ⟶ b) [Hl : split_mono f] [Hr : split_epi f] : is_iso f := is_iso.mk ((retraction_eq_section f) ▹ (retraction_comp f)) (comp_section f) definition inverse_unique (H H' : is_iso f) : @inverse _ _ _ _ f H = @inverse _ _ _ _ f H' := inverse_eq_left !left_inverse definition inverse_involutive (f : a ⟶ b) [H : is_iso f] [H : is_iso (f⁻¹)] : (f⁻¹)⁻¹ = f := inverse_eq_right !left_inverse definition retraction_id (a : ob) : retraction_of (ID a) = id := retraction_eq !id_comp definition section_id (a : ob) : section_of (ID a) = id := section_eq !id_comp definition id_inverse (a : ob) [H : is_iso (ID a)] : (ID a)⁻¹ = id := inverse_eq_left !id_comp definition split_mono_comp [instance] [priority 150] (g : b ⟶ c) (f : a ⟶ b) [Hf : split_mono f] [Hg : split_mono g] : split_mono (g ∘ f) := split_mono.mk (show (retraction_of f ∘ retraction_of g) ∘ g ∘ f = id, by rewrite [-assoc, assoc _ g f, retraction_comp, id_left, retraction_comp]) definition split_epi_comp [instance] [priority 150] (g : b ⟶ c) (f : a ⟶ b) [Hf : split_epi f] [Hg : split_epi g] : split_epi (g ∘ f) := split_epi.mk (show (g ∘ f) ∘ section_of f ∘ section_of g = id, by rewrite [-assoc, {f ∘ _}assoc, comp_section, id_left, comp_section]) definition is_iso_comp [instance] [priority 150] (g : b ⟶ c) (f : a ⟶ b) [Hf : is_iso f] [Hg : is_iso g] : is_iso (g ∘ f) := !is_iso_of_split_epi_of_split_mono -- "is_iso f" is equivalent to a certain sigma type -- definition is_iso.sigma_char (f : hom a b) : -- (Σ (g : hom b a), (g ∘ f = id) × (f ∘ g = id)) ≃ is_iso f := -- begin -- fapply equiv.MK, -- {intro S, apply is_iso.mk, -- exact (pr₁ S.2), -- exact (pr₂ S.2)}, -- {intro H, cases H with (g, η, ε), -- exact (sigma.mk g (pair η ε))}, -- {intro H, cases H, apply idp}, -- {intro S, cases S with (g, ηε), cases ηε, apply idp}, -- end definition is_hprop_is_iso [instance] (f : hom a b) : is_hprop (is_iso f) := begin apply is_hprop.mk, intros [H, H'], cases H with [g, li, ri], cases H' with [g', li', ri'], fapply (apD0111 (@is_iso.mk ob C a b f)), apply left_inverse_eq_right_inverse, apply li, apply ri', apply is_hprop.elim, apply is_hprop.elim, end /- iso objects -/ structure iso (a b : ob) := (to_hom : hom a b) [struct : is_iso to_hom] infix `≅`:50 := iso.iso attribute iso.struct [instance] [priority 400] namespace iso attribute to_hom [coercion] protected definition MK (f : a ⟶ b) (g : b ⟶ a) (H1 : g ∘ f = id) (H2 : f ∘ g = id) := @mk _ _ _ _ f (is_iso.mk H1 H2) definition to_inv (f : a ≅ b) : b ⟶ a := (to_hom f)⁻¹ protected definition refl (a : ob) : a ≅ a := mk (ID a) protected definition symm ⦃a b : ob⦄ (H : a ≅ b) : b ≅ a := mk (to_hom H)⁻¹ protected definition trans ⦃a b c : ob⦄ (H1 : a ≅ b) (H2 : b ≅ c) : a ≅ c := mk (to_hom H2 ∘ to_hom H1) protected definition eq_mk' {f f' : a ⟶ b} [H : is_iso f] [H' : is_iso f'] (p : f = f') : iso.mk f = iso.mk f' := apD011 iso.mk p !is_hprop.elim protected definition eq_mk {f f' : a ≅ b} (p : to_hom f = to_hom f') : f = f' := by (cases f; cases f'; apply (iso.eq_mk' p)) -- The structure for isomorphism can be characterized up to equivalence by a sigma type. definition sigma_char ⦃a b : ob⦄ : (Σ (f : hom a b), is_iso f) ≃ (a ≅ b) := begin fapply (equiv.mk), {intro S, apply iso.mk, apply (S.2)}, {fapply adjointify, {intro p, cases p with [f, H], exact (sigma.mk f H)}, {intro p, cases p, apply idp}, {intro S, cases S, apply idp}}, end end iso -- The type of isomorphisms between two objects is a set definition is_hset_iso [instance] : is_hset (a ≅ b) := begin apply is_trunc_is_equiv_closed, apply (equiv.to_is_equiv (!iso.sigma_char)), end definition iso_of_eq (p : a = b) : a ≅ b := eq.rec_on p (iso.refl a) definition hom_of_eq [reducible] (p : a = b) : a ⟶ b := iso.to_hom (iso_of_eq p) definition inv_of_eq [reducible] (p : a = b) : b ⟶ a := iso.to_inv (iso_of_eq p) definition iso_of_eq_inv (p : a = b) : iso_of_eq p⁻¹ = iso.symm (iso_of_eq p) := eq.rec_on p idp definition iso_of_eq_con (p : a = b) (q : b = c) : iso_of_eq (p ⬝ q) = iso.trans (iso_of_eq p) (iso_of_eq q) := eq.rec_on q (eq.rec_on p (iso.eq_mk !id_comp⁻¹)) section open funext variables {X : Type} {x y : X} {F G : X → ob} definition transport_hom_of_eq (p : F = G) (f : hom (F x) (F y)) : p ▹ f = hom_of_eq (apD10 p y) ∘ f ∘ inv_of_eq (apD10 p x) := eq.rec_on p !id_leftright⁻¹ definition transport_hom (p : F ∼ G) (f : hom (F x) (F y)) : eq_of_homotopy p ▹ f = hom_of_eq (p y) ∘ f ∘ inv_of_eq (p x) := calc eq_of_homotopy p ▹ f = hom_of_eq (apD10 (eq_of_homotopy p) y) ∘ f ∘ inv_of_eq (apD10 (eq_of_homotopy p) x) : transport_hom_of_eq ... = hom_of_eq (p y) ∘ f ∘ inv_of_eq (p x) : {retr apD10 p} end structure mono [class] (f : a ⟶ b) := (elim : ∀c (g h : hom c a), f ∘ g = f ∘ h → g = h) structure epi [class] (f : a ⟶ b) := (elim : ∀c (g h : hom b c), g ∘ f = h ∘ f → g = h) definition mono_of_split_mono [instance] (f : a ⟶ b) [H : split_mono f] : mono f := mono.mk (λ c g h H, calc g = id ∘ g : by rewrite id_left ... = (retraction_of f ∘ f) ∘ g : by rewrite retraction_comp ... = (retraction_of f ∘ f) ∘ h : by rewrite [-assoc, H, -assoc] ... = id ∘ h : by rewrite retraction_comp ... = h : by rewrite id_left) definition epi_of_split_epi [instance] (f : a ⟶ b) [H : split_epi f] : epi f := epi.mk (λ c g h H, calc g = g ∘ id : by rewrite id_right ... = g ∘ f ∘ section_of f : by rewrite -comp_section ... = h ∘ f ∘ section_of f : by rewrite [assoc, H, -assoc] ... = h ∘ id : by rewrite comp_section ... = h : by rewrite id_right) definition mono_comp [instance] (g : b ⟶ c) (f : a ⟶ b) [Hf : mono f] [Hg : mono g] : mono (g ∘ f) := mono.mk (λ d h₁ h₂ H, have H2 : g ∘ (f ∘ h₁) = g ∘ (f ∘ h₂), begin rewrite *assoc, exact H end, !mono.elim (!mono.elim H2)) definition epi_comp [instance] (g : b ⟶ c) (f : a ⟶ b) [Hf : epi f] [Hg : epi g] : epi (g ∘ f) := epi.mk (λ d h₁ h₂ H, have H2 : (h₁ ∘ g) ∘ f = (h₂ ∘ g) ∘ f, begin rewrite -*assoc, exact H end, !epi.elim (!epi.elim H2)) end iso namespace iso /- rewrite lemmas for inverses, modified from https://github.com/JasonGross/HoTT-categories/blob/master/theories/Categories/Category/Morphisms.v -/ section variables {ob : Type} [C : precategory ob] include C variables {a b c d : ob} (f : b ⟶ a) (r : c ⟶ d) (q : b ⟶ c) (p : a ⟶ b) (g : d ⟶ c) variable [Hq : is_iso q] include Hq definition comp.right_inverse : q ∘ q⁻¹ = id := !right_inverse definition comp.left_inverse : q⁻¹ ∘ q = id := !left_inverse definition inverse_comp_cancel_left : q⁻¹ ∘ (q ∘ p) = p := by rewrite [assoc, left_inverse, id_left] definition comp_inverse_cancel_left : q ∘ (q⁻¹ ∘ g) = g := by rewrite [assoc, right_inverse, id_left] definition comp_inverse_cancel_right : (r ∘ q) ∘ q⁻¹ = r := by rewrite [-assoc, right_inverse, id_right] definition inverse_comp_cancel_right : (f ∘ q⁻¹) ∘ q = f := by rewrite [-assoc, left_inverse, id_right] definition comp_inverse [Hp : is_iso p] [Hpq : is_iso (q ∘ p)] : (q ∘ p)⁻¹ʰ = p⁻¹ʰ ∘ q⁻¹ʰ := inverse_eq_left (show (p⁻¹ʰ ∘ q⁻¹ʰ) ∘ q ∘ p = id, from by rewrite [-assoc, inverse_comp_cancel_left, left_inverse]) definition inverse_comp_inverse_left [H' : is_iso g] : (q⁻¹ ∘ g)⁻¹ = g⁻¹ ∘ q := inverse_involutive q ▹ comp_inverse q⁻¹ g definition inverse_comp_inverse_right [H' : is_iso f] : (q ∘ f⁻¹)⁻¹ = f ∘ q⁻¹ := inverse_involutive f ▹ comp_inverse q f⁻¹ definition inverse_comp_inverse_inverse [H' : is_iso r] : (q⁻¹ ∘ r⁻¹)⁻¹ = r ∘ q := inverse_involutive r ▹ inverse_comp_inverse_left q r⁻¹ end section variables {ob : Type} {C : precategory ob} include C variables {d c b a : ob} {i : b ⟶ c} {f : b ⟶ a} {r : c ⟶ d} {q : b ⟶ c} {p : a ⟶ b} {g : d ⟶ c} {h : c ⟶ b} {x : b ⟶ d} {z : a ⟶ c} {y : d ⟶ b} {w : c ⟶ a} variable [Hq : is_iso q] include Hq definition comp_eq_of_eq_inverse_comp (H : y = q⁻¹ ∘ g) : q ∘ y = g := H⁻¹ ▹ comp_inverse_cancel_left q g definition comp_eq_of_eq_comp_inverse (H : w = f ∘ q⁻¹) : w ∘ q = f := H⁻¹ ▹ inverse_comp_cancel_right f q definition inverse_comp_eq_of_eq_comp (H : z = q ∘ p) : q⁻¹ ∘ z = p := H⁻¹ ▹ inverse_comp_cancel_left q p definition comp_inverse_eq_of_eq_comp (H : x = r ∘ q) : x ∘ q⁻¹ = r := H⁻¹ ▹ comp_inverse_cancel_right r q definition eq_comp_of_inverse_comp_eq (H : q⁻¹ ∘ g = y) : g = q ∘ y := (comp_eq_of_eq_inverse_comp H⁻¹)⁻¹ definition eq_comp_of_comp_inverse_eq (H : f ∘ q⁻¹ = w) : f = w ∘ q := (comp_eq_of_eq_comp_inverse H⁻¹)⁻¹ definition eq_inverse_comp_of_comp_eq (H : q ∘ p = z) : p = q⁻¹ ∘ z := (inverse_comp_eq_of_eq_comp H⁻¹)⁻¹ definition eq_comp_inverse_of_comp_eq (H : r ∘ q = x) : r = x ∘ q⁻¹ := (comp_inverse_eq_of_eq_comp H⁻¹)⁻¹ definition eq_inverse_of_comp_eq_id' (H : h ∘ q = id) : h = q⁻¹ := (inverse_eq_left H)⁻¹ definition eq_inverse_of_comp_eq_id (H : q ∘ h = id) : h = q⁻¹ := (inverse_eq_right H)⁻¹ definition eq_of_comp_inverse_eq_id (H : i ∘ q⁻¹ = id) : i = q := eq_inverse_of_comp_eq_id' H ⬝ inverse_involutive q definition eq_of_inverse_comp_eq_id (H : q⁻¹ ∘ i = id) : i = q := eq_inverse_of_comp_eq_id H ⬝ inverse_involutive q definition eq_of_id_eq_comp_inverse (H : id = i ∘ q⁻¹) : q = i := (eq_of_comp_inverse_eq_id H⁻¹)⁻¹ definition eq_of_id_eq_inverse_comp (H : id = q⁻¹ ∘ i) : q = i := (eq_of_inverse_comp_eq_id H⁻¹)⁻¹ definition inverse_eq_of_id_eq_comp (H : id = h ∘ q) : q⁻¹ = h := (eq_inverse_of_comp_eq_id' H⁻¹)⁻¹ definition inverse_eq_of_id_eq_comp' (H : id = q ∘ h) : q⁻¹ = h := (eq_inverse_of_comp_eq_id H⁻¹)⁻¹ end end iso
c1223b2340d17c3f28520df5965df27df6d3d7d7
b2fe74b11b57d362c13326bc5651244f111fa6f4
/src/group_theory/free_group.lean
d130ca2179ee5b247bbe35b66acbe88a10445b0f
[ "Apache-2.0" ]
permissive
midfield/mathlib
c4db5fa898b5ac8f2f80ae0d00c95eb6f745f4c7
775edc615ecec631d65b6180dbcc7bc26c3abc26
refs/heads/master
1,675,330,551,921
1,608,304,514,000
1,608,304,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
32,286
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Free groups as a quotient over the reduction relation `a * x * x⁻¹ * b = a * b`. First we introduce the one step reduction relation `free_group.red.step`: w * x * x⁻¹ * v ~> w * v its reflexive transitive closure: `free_group.red.trans` and proof that its join is an equivalence relation. Then we introduce `free_group α` as a quotient over `free_group.red.step`. -/ import data.fintype.basic import group_theory.subgroup open relation universes u v w variables {α : Type u} local attribute [simp] list.append_eq_has_append namespace free_group variables {L L₁ L₂ L₃ L₄ : list (α × bool)} /-- Reduction step: `w * x * x⁻¹ * v ~> w * v` -/ inductive red.step : list (α × bool) → list (α × bool) → Prop | bnot {L₁ L₂ x b} : red.step (L₁ ++ (x, b) :: (x, bnot b) :: L₂) (L₁ ++ L₂) attribute [simp] red.step.bnot /-- Reflexive-transitive closure of red.step -/ def red : list (α × bool) → list (α × bool) → Prop := refl_trans_gen red.step @[refl] lemma red.refl : red L L := refl_trans_gen.refl @[trans] lemma red.trans : red L₁ L₂ → red L₂ L₃ → red L₁ L₃ := refl_trans_gen.trans namespace red /-- Predicate asserting that word `w₁` can be reduced to `w₂` in one step, i.e. there are words `w₃ w₄` and letter `x` such that `w₁ = w₃xx⁻¹w₄` and `w₂ = w₃w₄` -/ theorem step.length : ∀ {L₁ L₂ : list (α × bool)}, step L₁ L₂ → L₂.length + 2 = L₁.length | _ _ (@red.step.bnot _ L1 L2 x b) := by rw [list.length_append, list.length_append]; refl @[simp] lemma step.bnot_rev {x b} : step (L₁ ++ (x, bnot b) :: (x, b) :: L₂) (L₁ ++ L₂) := by cases b; from step.bnot @[simp] lemma step.cons_bnot {x b} : red.step ((x, b) :: (x, bnot b) :: L) L := @step.bnot _ [] _ _ _ @[simp] lemma step.cons_bnot_rev {x b} : red.step ((x, bnot b) :: (x, b) :: L) L := @red.step.bnot_rev _ [] _ _ _ theorem step.append_left : ∀ {L₁ L₂ L₃ : list (α × bool)}, step L₂ L₃ → step (L₁ ++ L₂) (L₁ ++ L₃) | _ _ _ red.step.bnot := by rw [← list.append_assoc, ← list.append_assoc]; constructor theorem step.cons {x} (H : red.step L₁ L₂) : red.step (x :: L₁) (x :: L₂) := @step.append_left _ [x] _ _ H theorem step.append_right : ∀ {L₁ L₂ L₃ : list (α × bool)}, step L₁ L₂ → step (L₁ ++ L₃) (L₂ ++ L₃) | _ _ _ red.step.bnot := by simp lemma not_step_nil : ¬ step [] L := begin generalize h' : [] = L', assume h, cases h with L₁ L₂, simp [list.nil_eq_append_iff] at h', contradiction end lemma step.cons_left_iff {a : α} {b : bool} : step ((a, b) :: L₁) L₂ ↔ (∃L, step L₁ L ∧ L₂ = (a, b) :: L) ∨ (L₁ = (a, bnot b)::L₂) := begin split, { generalize hL : ((a, b) :: L₁ : list _) = L, assume h, rcases h with ⟨_ | ⟨p, s'⟩, e, a', b'⟩, { simp at hL, simp [*] }, { simp at hL, rcases hL with ⟨rfl, rfl⟩, refine or.inl ⟨s' ++ e, step.bnot, _⟩, simp } }, { assume h, rcases h with ⟨L, h, rfl⟩ | rfl, { exact step.cons h }, { exact step.cons_bnot } } end lemma not_step_singleton : ∀ {p : α × bool}, ¬ step [p] L | (a, b) := by simp [step.cons_left_iff, not_step_nil] lemma step.cons_cons_iff : ∀{p : α × bool}, step (p :: L₁) (p :: L₂) ↔ step L₁ L₂ := by simp [step.cons_left_iff, iff_def, or_imp_distrib] {contextual := tt} lemma step.append_left_iff : ∀L, step (L ++ L₁) (L ++ L₂) ↔ step L₁ L₂ | [] := by simp | (p :: l) := by simp [step.append_left_iff l, step.cons_cons_iff] private theorem step.diamond_aux : ∀ {L₁ L₂ L₃ L₄ : list (α × bool)} {x1 b1 x2 b2}, L₁ ++ (x1, b1) :: (x1, bnot b1) :: L₂ = L₃ ++ (x2, b2) :: (x2, bnot b2) :: L₄ → L₁ ++ L₂ = L₃ ++ L₄ ∨ ∃ L₅, red.step (L₁ ++ L₂) L₅ ∧ red.step (L₃ ++ L₄) L₅ | [] _ [] _ _ _ _ _ H := by injections; subst_vars; simp | [] _ [(x3,b3)] _ _ _ _ _ H := by injections; subst_vars; simp | [(x3,b3)] _ [] _ _ _ _ _ H := by injections; subst_vars; simp | [] _ ((x3,b3)::(x4,b4)::tl) _ _ _ _ _ H := by injections; subst_vars; simp; right; exact ⟨_, red.step.bnot, red.step.cons_bnot⟩ | ((x3,b3)::(x4,b4)::tl) _ [] _ _ _ _ _ H := by injections; subst_vars; simp; right; exact ⟨_, red.step.cons_bnot, red.step.bnot⟩ | ((x3,b3)::tl) _ ((x4,b4)::tl2) _ _ _ _ _ H := let ⟨H1, H2⟩ := list.cons.inj H in match step.diamond_aux H2 with | or.inl H3 := or.inl $ by simp [H1, H3] | or.inr ⟨L₅, H3, H4⟩ := or.inr ⟨_, step.cons H3, by simpa [H1] using step.cons H4⟩ end theorem step.diamond : ∀ {L₁ L₂ L₃ L₄ : list (α × bool)}, red.step L₁ L₃ → red.step L₂ L₄ → L₁ = L₂ → L₃ = L₄ ∨ ∃ L₅, red.step L₃ L₅ ∧ red.step L₄ L₅ | _ _ _ _ red.step.bnot red.step.bnot H := step.diamond_aux H lemma step.to_red : step L₁ L₂ → red L₁ L₂ := refl_trans_gen.single /-- Church-Rosser theorem for word reduction: If `w1 w2 w3` are words such that `w1` reduces to `w2` and `w3` respectively, then there is a word `w4` such that `w2` and `w3` reduce to `w4` respectively. -/ theorem church_rosser : red L₁ L₂ → red L₁ L₃ → join red L₂ L₃ := relation.church_rosser (assume a b c hab hac, match b, c, red.step.diamond hab hac rfl with | b, _, or.inl rfl := ⟨b, by refl, by refl⟩ | b, c, or.inr ⟨d, hbd, hcd⟩ := ⟨d, refl_gen.single hbd, hcd.to_red⟩ end) lemma cons_cons {p} : red L₁ L₂ → red (p :: L₁) (p :: L₂) := refl_trans_gen_lift (list.cons p) (assume a b, step.cons) lemma cons_cons_iff (p) : red (p :: L₁) (p :: L₂) ↔ red L₁ L₂ := iff.intro begin generalize eq₁ : (p :: L₁ : list _) = LL₁, generalize eq₂ : (p :: L₂ : list _) = LL₂, assume h, induction h using relation.refl_trans_gen.head_induction_on with L₁ L₂ h₁₂ h ih generalizing L₁ L₂, { subst_vars, cases eq₂, constructor }, { subst_vars, cases p with a b, rw [step.cons_left_iff] at h₁₂, rcases h₁₂ with ⟨L, h₁₂, rfl⟩ | rfl, { exact (ih rfl rfl).head h₁₂ }, { exact (cons_cons h).tail step.cons_bnot_rev } } end cons_cons lemma append_append_left_iff : ∀L, red (L ++ L₁) (L ++ L₂) ↔ red L₁ L₂ | [] := iff.rfl | (p :: L) := by simp [append_append_left_iff L, cons_cons_iff] lemma append_append (h₁ : red L₁ L₃) (h₂ : red L₂ L₄) : red (L₁ ++ L₂) (L₃ ++ L₄) := (refl_trans_gen_lift (λL, L ++ L₂) (assume a b, step.append_right) h₁).trans ((append_append_left_iff _).2 h₂) lemma to_append_iff : red L (L₁ ++ L₂) ↔ (∃L₃ L₄, L = L₃ ++ L₄ ∧ red L₃ L₁ ∧ red L₄ L₂) := iff.intro begin generalize eq : L₁ ++ L₂ = L₁₂, assume h, induction h with L' L₁₂ hLL' h ih generalizing L₁ L₂, { exact ⟨_, _, eq.symm, by refl, by refl⟩ }, { cases h with s e a b, rcases list.append_eq_append_iff.1 eq with ⟨s', rfl, rfl⟩ | ⟨e', rfl, rfl⟩, { have : L₁ ++ (s' ++ ((a, b) :: (a, bnot b) :: e)) = (L₁ ++ s') ++ ((a, b) :: (a, bnot b) :: e), { simp }, rcases ih this with ⟨w₁, w₂, rfl, h₁, h₂⟩, exact ⟨w₁, w₂, rfl, h₁, h₂.tail step.bnot⟩ }, { have : (s ++ ((a, b) :: (a, bnot b) :: e')) ++ L₂ = s ++ ((a, b) :: (a, bnot b) :: (e' ++ L₂)), { simp }, rcases ih this with ⟨w₁, w₂, rfl, h₁, h₂⟩, exact ⟨w₁, w₂, rfl, h₁.tail step.bnot, h₂⟩ }, } end (assume ⟨L₃, L₄, eq, h₃, h₄⟩, eq.symm ▸ append_append h₃ h₄) /-- The empty word `[]` only reduces to itself. -/ theorem nil_iff : red [] L ↔ L = [] := refl_trans_gen_iff_eq (assume l, red.not_step_nil) /-- A letter only reduces to itself. -/ theorem singleton_iff {x} : red [x] L₁ ↔ L₁ = [x] := refl_trans_gen_iff_eq (assume l, not_step_singleton) /-- If `x` is a letter and `w` is a word such that `xw` reduces to the empty word, then `w` reduces to `x⁻¹` -/ theorem cons_nil_iff_singleton {x b} : red ((x, b) :: L) [] ↔ red L [(x, bnot b)] := iff.intro (assume h, have h₁ : red ((x, bnot b) :: (x, b) :: L) [(x, bnot b)], from cons_cons h, have h₂ : red ((x, bnot b) :: (x, b) :: L) L, from refl_trans_gen.single step.cons_bnot_rev, let ⟨L', h₁, h₂⟩ := church_rosser h₁ h₂ in by rw [singleton_iff] at h₁; subst L'; assumption) (assume h, (cons_cons h).tail step.cons_bnot) theorem red_iff_irreducible {x1 b1 x2 b2} (h : (x1, b1) ≠ (x2, b2)) : red [(x1, bnot b1), (x2, b2)] L ↔ L = [(x1, bnot b1), (x2, b2)] := begin apply refl_trans_gen_iff_eq, generalize eq : [(x1, bnot b1), (x2, b2)] = L', assume L h', cases h', simp [list.cons_eq_append_iff, list.nil_eq_append_iff] at eq, rcases eq with ⟨rfl, ⟨rfl, rfl⟩, ⟨rfl, rfl⟩, rfl⟩, subst_vars, simp at h, contradiction end /-- If `x` and `y` are distinct letters and `w₁ w₂` are words such that `xw₁` reduces to `yw₂`, then `w₁` reduces to `x⁻¹yw₂`. -/ theorem inv_of_red_of_ne {x1 b1 x2 b2} (H1 : (x1, b1) ≠ (x2, b2)) (H2 : red ((x1, b1) :: L₁) ((x2, b2) :: L₂)) : red L₁ ((x1, bnot b1) :: (x2, b2) :: L₂) := begin have : red ((x1, b1) :: L₁) ([(x2, b2)] ++ L₂), from H2, rcases to_append_iff.1 this with ⟨_ | ⟨p, L₃⟩, L₄, eq, h₁, h₂⟩, { simp [nil_iff] at h₁, contradiction }, { cases eq, show red (L₃ ++ L₄) ([(x1, bnot b1), (x2, b2)] ++ L₂), apply append_append _ h₂, have h₁ : red ((x1, bnot b1) :: (x1, b1) :: L₃) [(x1, bnot b1), (x2, b2)], { exact cons_cons h₁ }, have h₂ : red ((x1, bnot b1) :: (x1, b1) :: L₃) L₃, { exact step.cons_bnot_rev.to_red }, rcases church_rosser h₁ h₂ with ⟨L', h₁, h₂⟩, rw [red_iff_irreducible H1] at h₁, rwa [h₁] at h₂ } end theorem step.sublist (H : red.step L₁ L₂) : L₂ <+ L₁ := by cases H; simp; constructor; constructor; refl /-- If `w₁ w₂` are words such that `w₁` reduces to `w₂`, then `w₂` is a sublist of `w₁`. -/ theorem sublist : red L₁ L₂ → L₂ <+ L₁ := refl_trans_gen_of_transitive_reflexive (λl, list.sublist.refl l) (λa b c hab hbc, list.sublist.trans hbc hab) (λa b, red.step.sublist) theorem sizeof_of_step : ∀ {L₁ L₂ : list (α × bool)}, step L₁ L₂ → L₂.sizeof < L₁.sizeof | _ _ (@step.bnot _ L1 L2 x b) := begin induction L1 with hd tl ih, case list.nil { dsimp [list.sizeof], have H : 1 + sizeof (x, b) + (1 + sizeof (x, bnot b) + list.sizeof L2) = (list.sizeof L2 + 1) + (sizeof (x, b) + sizeof (x, bnot b) + 1), { ac_refl }, rw H, exact nat.le_add_right _ _ }, case list.cons { dsimp [list.sizeof], exact nat.add_lt_add_left ih _ } end theorem length (h : red L₁ L₂) : ∃ n, L₁.length = L₂.length + 2 * n := begin induction h with L₂ L₃ h₁₂ h₂₃ ih, { exact ⟨0, rfl⟩ }, { rcases ih with ⟨n, eq⟩, existsi (1 + n), simp [mul_add, eq, (step.length h₂₃).symm, add_assoc] } end theorem antisymm (h₁₂ : red L₁ L₂) : red L₂ L₁ → L₁ = L₂ := match L₁, h₁₂.cases_head with | _, or.inl rfl := assume h, rfl | L₁, or.inr ⟨L₃, h₁₃, h₃₂⟩ := assume h₂₁, let ⟨n, eq⟩ := length (h₃₂.trans h₂₁) in have list.length L₃ + 0 = list.length L₃ + (2 * n + 2), by simpa [(step.length h₁₃).symm, add_comm, add_assoc] using eq, (nat.no_confusion $ nat.add_left_cancel this) end end red theorem equivalence_join_red : equivalence (join (@red α)) := equivalence_join_refl_trans_gen $ assume a b c hab hac, (match b, c, red.step.diamond hab hac rfl with | b, _, or.inl rfl := ⟨b, by refl, by refl⟩ | b, c, or.inr ⟨d, hbd, hcd⟩ := ⟨d, refl_gen.single hbd, refl_trans_gen.single hcd⟩ end) theorem join_red_of_step (h : red.step L₁ L₂) : join red L₁ L₂ := join_of_single reflexive_refl_trans_gen h.to_red theorem eqv_gen_step_iff_join_red : eqv_gen red.step L₁ L₂ ↔ join red L₁ L₂ := iff.intro (assume h, have eqv_gen (join red) L₁ L₂ := eqv_gen_mono (assume a b, join_red_of_step) h, (eqv_gen_iff_of_equivalence $ equivalence_join_red).1 this) (join_of_equivalence (eqv_gen.is_equivalence _) $ assume a b, refl_trans_gen_of_equivalence (eqv_gen.is_equivalence _) eqv_gen.rel) end free_group /-- The free group over a type, i.e. the words formed by the elements of the type and their formal inverses, quotient by one step reduction. -/ def free_group (α : Type u) : Type u := quot $ @free_group.red.step α namespace free_group variables {α} {L L₁ L₂ L₃ L₄ : list (α × bool)} /-- The canonical map from `list (α × bool)` to the free group on `α`. -/ def mk (L) : free_group α := quot.mk red.step L @[simp] lemma quot_mk_eq_mk : quot.mk red.step L = mk L := rfl @[simp] lemma quot_lift_mk (β : Type v) (f : list (α × bool) → β) (H : ∀ L₁ L₂, red.step L₁ L₂ → f L₁ = f L₂) : quot.lift f H (mk L) = f L := rfl @[simp] lemma quot_lift_on_mk (β : Type v) (f : list (α × bool) → β) (H : ∀ L₁ L₂, red.step L₁ L₂ → f L₁ = f L₂) : quot.lift_on (mk L) f H = f L := rfl instance : has_one (free_group α) := ⟨mk []⟩ lemma one_eq_mk : (1 : free_group α) = mk [] := rfl instance : inhabited (free_group α) := ⟨1⟩ instance : has_mul (free_group α) := ⟨λ x y, quot.lift_on x (λ L₁, quot.lift_on y (λ L₂, mk $ L₁ ++ L₂) (λ L₂ L₃ H, quot.sound $ red.step.append_left H)) (λ L₁ L₂ H, quot.induction_on y $ λ L₃, quot.sound $ red.step.append_right H)⟩ @[simp] lemma mul_mk : mk L₁ * mk L₂ = mk (L₁ ++ L₂) := rfl instance : has_inv (free_group α) := ⟨λx, quot.lift_on x (λ L, mk (L.map $ λ x : α × bool, (x.1, bnot x.2)).reverse) (assume a b h, quot.sound $ by cases h; simp)⟩ @[simp] lemma inv_mk : (mk L)⁻¹ = mk (L.map $ λ x : α × bool, (x.1, bnot x.2)).reverse := rfl instance : group (free_group α) := { mul := (*), one := 1, inv := has_inv.inv, mul_assoc := by rintros ⟨L₁⟩ ⟨L₂⟩ ⟨L₃⟩; simp, one_mul := by rintros ⟨L⟩; refl, mul_one := by rintros ⟨L⟩; simp [one_eq_mk], mul_left_inv := by rintros ⟨L⟩; exact (list.rec_on L rfl $ λ ⟨x, b⟩ tl ih, eq.trans (quot.sound $ by simp [one_eq_mk]) ih) } /-- `of x` is the canonical injection from the type to the free group over that type by sending each element to the equivalence class of the letter that is the element. -/ def of (x : α) : free_group α := mk [(x, tt)] theorem red.exact : mk L₁ = mk L₂ ↔ join red L₁ L₂ := calc (mk L₁ = mk L₂) ↔ eqv_gen red.step L₁ L₂ : iff.intro (quot.exact _) quot.eqv_gen_sound ... ↔ join red L₁ L₂ : eqv_gen_step_iff_join_red /-- The canonical injection from the type to the free group is an injection. -/ theorem of_injective : function.injective (@of α) := λ _ _ H, let ⟨L₁, hx, hy⟩ := red.exact.1 H in by simp [red.singleton_iff] at hx hy; cc section to_group variables {β : Type v} [group β] (f : α → β) {x y : free_group α} /-- Given `f : α → β` with `β` a group, the canonical map `list (α × bool) → β` -/ def to_group.aux : list (α × bool) → β := λ L, list.prod $ L.map $ λ x, cond x.2 (f x.1) (f x.1)⁻¹ theorem red.step.to_group {f : α → β} (H : red.step L₁ L₂) : to_group.aux f L₁ = to_group.aux f L₂ := by cases H with _ _ _ b; cases b; simp [to_group.aux] /-- If `β` is a group, then any function from `α` to `β` extends uniquely to a group homomorphism from the free group over `α` to `β`. Note that this is the bare function; the group homomorphism is `to_group`. -/ def to_group.to_fun : free_group α → β := quot.lift (to_group.aux f) $ λ L₁ L₂ H, red.step.to_group H /-- If `β` is a group, then any function from `α` to `β` extends uniquely to a group homomorphism from the free group over `α` to `β` -/ def to_group : free_group α →* β := monoid_hom.mk' (to_group.to_fun f) $ begin rintros ⟨L₁⟩ ⟨L₂⟩; simp [to_group.to_fun, to_group.aux], end variable {f} @[simp] lemma to_group.mk : to_group f (mk L) = list.prod (L.map $ λ x, cond x.2 (f x.1) (f x.1)⁻¹) := rfl @[simp] lemma to_group.of {x} : to_group f (of x) = f x := one_mul _ instance to_group.is_group_hom : is_group_hom (to_group f) := { map_mul := by rintros ⟨L₁⟩ ⟨L₂⟩; simp } @[simp] lemma to_group.mul : to_group f (x * y) = to_group f x * to_group f y := is_mul_hom.map_mul _ _ _ @[simp] lemma to_group.one : to_group f 1 = 1 := is_group_hom.map_one _ @[simp] lemma to_group.inv : to_group f x⁻¹ = (to_group f x)⁻¹ := is_group_hom.map_inv _ _ theorem to_group.unique (g : free_group α →* β) (hg : ∀ x, g (of x) = f x) : ∀{x}, g x = to_group f x := by rintros ⟨L⟩; exact list.rec_on L (is_group_hom.map_one g) (λ ⟨x, b⟩ t (ih : g (mk t) = _), bool.rec_on b (show g ((of x)⁻¹ * mk t) = to_group f (mk ((x, ff) :: t)), by simp [monoid_hom.map_mul g, monoid_hom.map_inv g, hg, ih, to_group.to_fun, to_group.aux]) (show g (of x * mk t) = to_group f (mk ((x, tt) :: t)), by simp [monoid_hom.map_mul g, monoid_hom.map_inv g, hg, ih, to_group.to_fun, to_group.aux])) theorem to_group.of_eq (x : free_group α) : to_group of x = x := eq.symm $ to_group.unique (monoid_hom.id _) (λ x, rfl) theorem to_group.range_subset {s : subgroup β} (H : set.range f ⊆ s) : set.range (to_group f) ⊆ s := by rintros _ ⟨⟨L⟩, rfl⟩; exact list.rec_on L s.one_mem (λ ⟨x, b⟩ tl ih, bool.rec_on b (by simp at ih ⊢; from s.mul_mem (s.inv_mem $ H ⟨x, rfl⟩) ih) (by simp at ih ⊢; from s.mul_mem (H ⟨x, rfl⟩) ih)) theorem closure_subset {G : Type*} [group G] {s : set G} {t : subgroup G} (h : s ⊆ t) : subgroup.closure s ≤ t := begin simp only [h, subgroup.closure_le], end theorem to_group.range_eq_closure : set.range (to_group f) = subgroup.closure (set.range f) := set.subset.antisymm (to_group.range_subset subgroup.subset_closure) begin suffices : (subgroup.closure (set.range f)) ≤ monoid_hom.range (to_group f), simpa, rw subgroup.closure_le, rintros y ⟨x, hx⟩, exact ⟨of x, by simpa⟩ end end to_group section map variables {β : Type v} (f : α → β) {x y : free_group α} /-- Given `f : α → β`, the canonical map `list (α × bool) → list (β × bool)`. -/ def map.aux (L : list (α × bool)) : list (β × bool) := L.map $ λ x, (f x.1, x.2) /-- Any function from `α` to `β` extends uniquely to a group homomorphism from the free group over `α` to the free group over `β`. Note that this is the bare function; for the group homomorphism use `map`. -/ def map.to_fun (x : free_group α) : free_group β := x.lift_on (λ L, mk $ map.aux f L) $ λ L₁ L₂ H, quot.sound $ by cases H; simp [map.aux] /-- Any function from `α` to `β` extends uniquely to a group homomorphism from the free group ver `α` to the free group over `β`. -/ def map : free_group α →* free_group β := monoid_hom.mk' (map.to_fun f) begin rintros ⟨L₁⟩ ⟨L₂⟩, simp [map.to_fun, map.aux] end --by rintros ⟨L₁⟩ ⟨L₂⟩; simp [map, map.aux] variable {f} @[simp] lemma map.mk : map f (mk L) = mk (L.map (λ x, (f x.1, x.2))) := rfl @[simp] lemma map.id : map id x = x := have H1 : (λ (x : α × bool), x) = id := rfl, by rcases x with ⟨L⟩; simp [H1] @[simp] lemma map.id' : map (λ z, z) x = x := map.id theorem map.comp {γ : Type w} {f : α → β} {g : β → γ} {x} : map g (map f x) = map (g ∘ f) x := by rcases x with ⟨L⟩; simp @[simp] lemma map.of {x} : map f (of x) = of (f x) := rfl @[simp] lemma map.mul : map f (x * y) = map f x * map f y := is_mul_hom.map_mul _ x y @[simp] lemma map.one : map f 1 = 1 := is_group_hom.map_one _ @[simp] lemma map.inv : map f x⁻¹ = (map f x)⁻¹ := is_group_hom.map_inv _ x theorem map.unique (g : free_group α → free_group β) [is_group_hom g] (hg : ∀ x, g (of x) = of (f x)) : ∀{x}, g x = map f x := by rintros ⟨L⟩; exact list.rec_on L (is_group_hom.map_one g) (λ ⟨x, b⟩ t (ih : g (mk t) = map f (mk t)), bool.rec_on b (show g ((of x)⁻¹ * mk t) = map f ((of x)⁻¹ * mk t), by simp [is_mul_hom.map_mul g, is_group_hom.map_inv g, hg, ih]) (show g (of x * mk t) = map f (of x * mk t), by simp [is_mul_hom.map_mul g, hg, ih])) /-- Equivalent types give rise to equivalent free groups. -/ def free_group_congr {α β} (e : α ≃ β) : free_group α ≃ free_group β := ⟨map e, map e.symm, λ x, by simp [function.comp, map.comp], λ x, by simp [function.comp, map.comp]⟩ theorem map_eq_to_group : map f x = to_group (of ∘ f) x := eq.symm $ map.unique _ $ λ x, by simp end map section prod variables [group α] (x y : free_group α) /-- If `α` is a group, then any function from `α` to `α` extends uniquely to a homomorphism from the free group over `α` to `α`. This is the multiplicative version of `sum`. -/ def prod : free_group α →* α := to_group id variables {x y} @[simp] lemma prod_mk : prod (mk L) = list.prod (L.map $ λ x, cond x.2 x.1 x.1⁻¹) := rfl @[simp] lemma prod.of {x : α} : prod (of x) = x := to_group.of @[simp] lemma prod.mul : prod (x * y) = prod x * prod y := to_group.mul @[simp] lemma prod.one : prod (1:free_group α) = 1 := to_group.one @[simp] lemma prod.inv : prod x⁻¹ = (prod x)⁻¹ := to_group.inv lemma prod.unique (g : free_group α →* α) (hg : ∀ x, g (of x) = x) {x} : g x = prod x := to_group.unique g hg end prod theorem to_group_eq_prod_map {β : Type v} [group β] {f : α → β} {x} : to_group f x = prod (map f x) := begin rw ←to_group.unique (prod.comp (map f)), { refl }, { simp } end section sum variables [add_group α] (x y : free_group α) /-- If `α` is a group, then any function from `α` to `α` extends uniquely to a homomorphism from the free group over `α` to `α`. This is the additive version of `prod`. -/ def sum : α := @prod (multiplicative _) _ x variables {x y} @[simp] lemma sum_mk : sum (mk L) = list.sum (L.map $ λ x, cond x.2 x.1 (-x.1)) := rfl @[simp] lemma sum.of {x : α} : sum (of x) = x := prod.of instance sum.is_group_hom : is_group_hom (@sum α _) := prod.is_group_hom @[simp] lemma sum.mul : sum (x * y) = sum x + sum y := prod.mul @[simp] lemma sum.one : sum (1:free_group α) = 0 := prod.one @[simp] lemma sum.inv : sum x⁻¹ = -sum x := prod.inv end sum /-- The bijection between the free group on the empty type, and a type with one element. -/ def free_group_empty_equiv_unit : free_group empty ≃ unit := { to_fun := λ _, (), inv_fun := λ _, 1, left_inv := by rintros ⟨_ | ⟨⟨⟨⟩, _⟩, _⟩⟩; refl, right_inv := λ ⟨⟩, rfl } /-- The bijection between the free group on a singleton, and the integers. -/ def free_group_unit_equiv_int : free_group unit ≃ int := { to_fun := λ x, sum begin revert x, apply monoid_hom.to_fun, apply map (λ _, (1 : ℤ)), end, inv_fun := λ x, of () ^ x, left_inv := begin rintros ⟨L⟩, refine list.rec_on L rfl _, exact (λ ⟨⟨⟩, b⟩ tl ih, by cases b; simp [gpow_add] at ih ⊢; rw ih; refl), end, right_inv := λ x, int.induction_on x (by simp) (λ i ih, by simp at ih; simp [gpow_add, ih]) (λ i ih, by simp at ih; simp [gpow_add, ih, sub_eq_add_neg]) } section category variables {β : Type u} instance : monad free_group.{u} := { pure := λ α, of, map := λ α β f, (map f), bind := λ α β x f, to_group f x } @[elab_as_eliminator] protected theorem induction_on {C : free_group α → Prop} (z : free_group α) (C1 : C 1) (Cp : ∀ x, C $ pure x) (Ci : ∀ x, C (pure x) → C (pure x)⁻¹) (Cm : ∀ x y, C x → C y → C (x * y)) : C z := quot.induction_on z $ λ L, list.rec_on L C1 $ λ ⟨x, b⟩ tl ih, bool.rec_on b (Cm _ _ (Ci _ $ Cp x) ih) (Cm _ _ (Cp x) ih) @[simp] lemma map_pure (f : α → β) (x : α) : f <$> (pure x : free_group α) = pure (f x) := map.of @[simp] lemma map_one (f : α → β) : f <$> (1 : free_group α) = 1 := map.one @[simp] lemma map_mul (f : α → β) (x y : free_group α) : f <$> (x * y) = f <$> x * f <$> y := map.mul @[simp] lemma map_inv (f : α → β) (x : free_group α) : f <$> (x⁻¹) = (f <$> x)⁻¹ := map.inv @[simp] lemma pure_bind (f : α → free_group β) (x) : pure x >>= f = f x := to_group.of @[simp] lemma one_bind (f : α → free_group β) : 1 >>= f = 1 := @@to_group.one _ f @[simp] lemma mul_bind (f : α → free_group β) (x y : free_group α) : x * y >>= f = (x >>= f) * (y >>= f) := to_group.mul @[simp] lemma inv_bind (f : α → free_group β) (x : free_group α) : x⁻¹ >>= f = (x >>= f)⁻¹ := to_group.inv instance : is_lawful_monad free_group.{u} := { id_map := λ α x, free_group.induction_on x (map_one id) (λ x, map_pure id x) (λ x ih, by rw [map_inv, ih]) (λ x y ihx ihy, by rw [map_mul, ihx, ihy]), pure_bind := λ α β x f, pure_bind f x, bind_assoc := λ α β γ x f g, free_group.induction_on x (by iterate 3 { rw one_bind }) (λ x, by iterate 2 { rw pure_bind }) (λ x ih, by iterate 3 { rw inv_bind }; rw ih) (λ x y ihx ihy, by iterate 3 { rw mul_bind }; rw [ihx, ihy]), bind_pure_comp_eq_map := λ α β f x, free_group.induction_on x (by rw [one_bind, map_one]) (λ x, by rw [pure_bind, map_pure]) (λ x ih, by rw [inv_bind, map_inv, ih]) (λ x y ihx ihy, by rw [mul_bind, map_mul, ihx, ihy]) } end category section reduce variable [decidable_eq α] /-- The maximal reduction of a word. It is computable iff `α` has decidable equality. -/ def reduce (L : list (α × bool)) : list (α × bool) := list.rec_on L [] $ λ hd1 tl1 ih, list.cases_on ih [hd1] $ λ hd2 tl2, if hd1.1 = hd2.1 ∧ hd1.2 = bnot hd2.2 then tl2 else hd1 :: hd2 :: tl2 @[simp] lemma reduce.cons (x) : reduce (x :: L) = list.cases_on (reduce L) [x] (λ hd tl, if x.1 = hd.1 ∧ x.2 = bnot hd.2 then tl else x :: hd :: tl) := rfl /-- The first theorem that characterises the function `reduce`: a word reduces to its maximal reduction. -/ theorem reduce.red : red L (reduce L) := begin induction L with hd1 tl1 ih, case list.nil { constructor }, case list.cons { dsimp, revert ih, generalize htl : reduce tl1 = TL, intro ih, cases TL with hd2 tl2, case list.nil { exact red.cons_cons ih }, case list.cons { dsimp, by_cases h : hd1.fst = hd2.fst ∧ hd1.snd = bnot (hd2.snd), { rw [if_pos h], transitivity, { exact red.cons_cons ih }, { cases hd1, cases hd2, cases h, dsimp at *, subst_vars, exact red.step.cons_bnot_rev.to_red } }, { rw [if_neg h], exact red.cons_cons ih } } } end theorem reduce.not {p : Prop} : ∀ {L₁ L₂ L₃ : list (α × bool)} {x b}, reduce L₁ = L₂ ++ (x, b) :: (x, bnot b) :: L₃ → p | [] L2 L3 _ _ := λ h, by cases L2; injections | ((x,b)::L1) L2 L3 x' b' := begin dsimp, cases r : reduce L1, { dsimp, intro h, have := congr_arg list.length h, simp [-add_comm] at this, exact absurd this dec_trivial }, cases hd with y c, by_cases x = y ∧ b = bnot c; simp [h]; intro H, { rw H at r, exact @reduce.not L1 ((y,c)::L2) L3 x' b' r }, rcases L2 with _|⟨a, L2⟩, { injections, subst_vars, simp at h, cc }, { refine @reduce.not L1 L2 L3 x' b' _, injection H with _ H, rw [r, H], refl } end /-- The second theorem that characterises the function `reduce`: the maximal reduction of a word only reduces to itself. -/ theorem reduce.min (H : red (reduce L₁) L₂) : reduce L₁ = L₂ := begin induction H with L1 L' L2 H1 H2 ih, { refl }, { cases H1 with L4 L5 x b, exact reduce.not H2 } end /-- `reduce` is idempotent, i.e. the maximal reduction of the maximal reduction of a word is the maximal reduction of the word. -/ theorem reduce.idem : reduce (reduce L) = reduce L := eq.symm $ reduce.min reduce.red theorem reduce.step.eq (H : red.step L₁ L₂) : reduce L₁ = reduce L₂ := let ⟨L₃, HR13, HR23⟩ := red.church_rosser reduce.red (reduce.red.head H) in (reduce.min HR13).trans (reduce.min HR23).symm /-- If a word reduces to another word, then they have a common maximal reduction. -/ theorem reduce.eq_of_red (H : red L₁ L₂) : reduce L₁ = reduce L₂ := let ⟨L₃, HR13, HR23⟩ := red.church_rosser reduce.red (red.trans H reduce.red) in (reduce.min HR13).trans (reduce.min HR23).symm /-- If two words correspond to the same element in the free group, then they have a common maximal reduction. This is the proof that the function that sends an element of the free group to its maximal reduction is well-defined. -/ theorem reduce.sound (H : mk L₁ = mk L₂) : reduce L₁ = reduce L₂ := let ⟨L₃, H13, H23⟩ := red.exact.1 H in (reduce.eq_of_red H13).trans (reduce.eq_of_red H23).symm /-- If two words have a common maximal reduction, then they correspond to the same element in the free group. -/ theorem reduce.exact (H : reduce L₁ = reduce L₂) : mk L₁ = mk L₂ := red.exact.2 ⟨reduce L₂, H ▸ reduce.red, reduce.red⟩ /-- A word and its maximal reduction correspond to the same element of the free group. -/ theorem reduce.self : mk (reduce L) = mk L := reduce.exact reduce.idem /-- If words `w₁ w₂` are such that `w₁` reduces to `w₂`, then `w₂` reduces to the maximal reduction of `w₁`. -/ theorem reduce.rev (H : red L₁ L₂) : red L₂ (reduce L₁) := (reduce.eq_of_red H).symm ▸ reduce.red /-- The function that sends an element of the free group to its maximal reduction. -/ def to_word : free_group α → list (α × bool) := quot.lift reduce $ λ L₁ L₂ H, reduce.step.eq H lemma to_word.mk : ∀{x : free_group α}, mk (to_word x) = x := by rintros ⟨L⟩; exact reduce.self lemma to_word.inj : ∀(x y : free_group α), to_word x = to_word y → x = y := by rintros ⟨L₁⟩ ⟨L₂⟩; exact reduce.exact /-- Constructive Church-Rosser theorem (compare `church_rosser`). -/ def reduce.church_rosser (H12 : red L₁ L₂) (H13 : red L₁ L₃) : { L₄ // red L₂ L₄ ∧ red L₃ L₄ } := ⟨reduce L₁, reduce.rev H12, reduce.rev H13⟩ instance : decidable_eq (free_group α) := function.injective.decidable_eq to_word.inj instance red.decidable_rel : decidable_rel (@red α) | [] [] := is_true red.refl | [] (hd2::tl2) := is_false $ λ H, list.no_confusion (red.nil_iff.1 H) | ((x,b)::tl) [] := match red.decidable_rel tl [(x, bnot b)] with | is_true H := is_true $ red.trans (red.cons_cons H) $ (@red.step.bnot _ [] [] _ _).to_red | is_false H := is_false $ λ H2, H $ red.cons_nil_iff_singleton.1 H2 end | ((x1,b1)::tl1) ((x2,b2)::tl2) := if h : (x1, b1) = (x2, b2) then match red.decidable_rel tl1 tl2 with | is_true H := is_true $ h ▸ red.cons_cons H | is_false H := is_false $ λ H2, H $ h ▸ (red.cons_cons_iff _).1 $ H2 end else match red.decidable_rel tl1 ((x1,bnot b1)::(x2,b2)::tl2) with | is_true H := is_true $ (red.cons_cons H).tail red.step.cons_bnot | is_false H := is_false $ λ H2, H $ red.inv_of_red_of_ne h H2 end /-- A list containing every word that `w₁` reduces to. -/ def red.enum (L₁ : list (α × bool)) : list (list (α × bool)) := list.filter (λ L₂, red L₁ L₂) (list.sublists L₁) theorem red.enum.sound (H : L₂ ∈ red.enum L₁) : red L₁ L₂ := list.of_mem_filter H theorem red.enum.complete (H : red L₁ L₂) : L₂ ∈ red.enum L₁ := list.mem_filter_of_mem (list.mem_sublists.2 $ red.sublist H) H instance : fintype { L₂ // red L₁ L₂ } := fintype.subtype (list.to_finset $ red.enum L₁) $ λ L₂, ⟨λ H, red.enum.sound $ list.mem_to_finset.1 H, λ H, list.mem_to_finset.2 $ red.enum.complete H⟩ end reduce end free_group
bde1a3acd5a54840fc8681db176ed1e9c8c09f48
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/unihint.lean
5b48ecab95415ed2818e9408683e3bd6afeb7e11
[ "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
856
lean
structure S where carrier : Type mul : carrier → carrier → carrier def Nat.S : S where carrier := Nat mul := (· * ·) def Int.S : S where carrier := Int mul := (· * ·) unif_hint (s : S) where s =?= Nat.S ⊢ s.carrier =?= Nat unif_hint (s : S) where s =?= Int.S ⊢ s.carrier =?= Int def mul {s : S} (a b : s.carrier) : s.carrier := s.mul a b def square (x : Nat) : Nat := mul x x set_option pp.all true #print square #check fun x : Nat => mul x x #check fun y : Int => mul y y def BV (n : Nat) := { a : Array Bool // a.size = n } def sext (x : BV s) (n : Nat) : BV (s+n) := ⟨mkArray (s+n) false, Array.size_mkArray ..⟩ def bvmul (x y : BV w) : BV w := x unif_hint (x : Nat) where x =?= 64 ⊢ Nat.add 64 x =?= 128 set_option pp.all false def tst (x y : BV 64) : BV 128 := bvmul (sext x 64) (sext y _)
53489adad467abb7de25cd5cebac96688661c889
07c6143268cfb72beccd1cc35735d424ebcb187b
/src/data/nat/cast.lean
f94d3bcbbd1a9fcb14b5b3d1c2235ef536169bb5
[ "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
5,097
lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Natural homomorphism from the natural numbers into a monoid with one. -/ import tactic.interactive algebra.order algebra.ordered_group algebra.ring import tactic.norm_cast namespace nat variables {α : Type*} section variables [has_zero α] [has_one α] [has_add α] /-- Canonical homomorphism from `ℕ` to a type `α` with `0`, `1` and `+`. -/ protected def cast : ℕ → α | 0 := 0 | (n+1) := cast n + 1 @[priority 10] instance cast_coe : has_coe ℕ α := ⟨nat.cast⟩ @[simp, norm_cast] theorem cast_zero : ((0 : ℕ) : α) = 0 := rfl theorem cast_add_one (n : ℕ) : ((n + 1 : ℕ) : α) = n + 1 := rfl @[simp, norm_cast, priority 500] theorem cast_succ (n : ℕ) : ((succ n : ℕ) : α) = n + 1 := rfl @[simp, norm_cast] theorem cast_ite (P : Prop) [decidable P] (m n : ℕ) : (((ite P m n) : ℕ) : α) = ite P (m : α) (n : α) := by { split_ifs; refl, } end @[simp, norm_cast] theorem cast_one [add_monoid α] [has_one α] : ((1 : ℕ) : α) = 1 := zero_add _ @[simp, norm_cast] theorem cast_add [add_monoid α] [has_one α] (m) : ∀ n, ((m + n : ℕ) : α) = m + n | 0 := (add_zero _).symm | (n+1) := show ((m + n : ℕ) : α) + 1 = m + (n + 1), by rw [cast_add n, add_assoc] /-- `coe : ℕ → α` as an `add_monoid_hom`. -/ def cast_add_monoid_hom (α : Type*) [add_monoid α] [has_one α] : ℕ →+ α := { to_fun := coe, map_add' := cast_add, map_zero' := cast_zero } lemma coe_cast_add_monoid_hom [add_monoid α] [has_one α] : (cast_add_monoid_hom α : ℕ → α) = coe := rfl @[simp, norm_cast] theorem cast_bit0 [add_monoid α] [has_one α] (n : ℕ) : ((bit0 n : ℕ) : α) = bit0 n := cast_add _ _ @[simp, norm_cast] theorem cast_bit1 [add_monoid α] [has_one α] (n : ℕ) : ((bit1 n : ℕ) : α) = bit1 n := by rw [bit1, cast_add_one, cast_bit0]; refl lemma cast_two {α : Type*} [semiring α] : ((2 : ℕ) : α) = 2 := by simp @[simp, norm_cast] theorem cast_pred [add_group α] [has_one α] : ∀ {n}, 0 < n → ((n - 1 : ℕ) : α) = n - 1 | (n+1) h := (add_sub_cancel (n:α) 1).symm @[simp, norm_cast] theorem cast_sub [add_group α] [has_one α] {m n} (h : m ≤ n) : ((n - m : ℕ) : α) = n - m := eq_sub_of_add_eq $ by rw [← cast_add, nat.sub_add_cancel h] @[simp, norm_cast] theorem cast_mul [semiring α] (m) : ∀ n, ((m * n : ℕ) : α) = m * n | 0 := (mul_zero _).symm | (n+1) := (cast_add _ _).trans $ show ((m * n : ℕ) : α) + m = m * (n + 1), by rw [cast_mul n, left_distrib, mul_one] /-- `coe : ℕ → α` as a `ring_hom` -/ def cast_ring_hom (α : Type*) [semiring α] : ℕ →+* α := { to_fun := coe, map_one' := cast_one, map_mul' := cast_mul, .. cast_add_monoid_hom α } lemma coe_cast_ring_hom [semiring α] : (cast_ring_hom α : ℕ → α) = coe := rfl theorem mul_cast_comm [semiring α] (a : α) (n : ℕ) : a * n = n * a := by induction n; simp [left_distrib, right_distrib, *] @[simp] theorem cast_nonneg [linear_ordered_semiring α] : ∀ n : ℕ, 0 ≤ (n : α) | 0 := le_refl _ | (n+1) := add_nonneg (cast_nonneg n) zero_le_one @[simp, norm_cast] theorem cast_le [linear_ordered_semiring α] : ∀ {m n : ℕ}, (m : α) ≤ n ↔ m ≤ n | 0 n := by simp [zero_le] | (m+1) 0 := by simpa [not_succ_le_zero] using lt_add_of_nonneg_of_lt (@cast_nonneg α _ m) zero_lt_one | (m+1) (n+1) := (add_le_add_iff_right 1).trans $ (@cast_le m n).trans $ (add_le_add_iff_right 1).symm @[simp, norm_cast] theorem cast_lt [linear_ordered_semiring α] {m n : ℕ} : (m : α) < n ↔ m < n := by simpa [-cast_le] using not_congr (@cast_le α _ n m) @[simp] theorem cast_pos [linear_ordered_semiring α] {n : ℕ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] lemma cast_add_one_pos [linear_ordered_semiring α] (n : ℕ) : 0 < (n : α) + 1 := add_pos_of_nonneg_of_pos n.cast_nonneg zero_lt_one @[simp, norm_cast] theorem cast_min [decidable_linear_ordered_semiring α] {a b : ℕ} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [h, min] @[simp, norm_cast] theorem cast_max [decidable_linear_ordered_semiring α] {a b : ℕ} : (↑(max a b) : α) = max a b := by by_cases a ≤ b; simp [h, max] @[simp, norm_cast] theorem abs_cast [decidable_linear_ordered_comm_ring α] (a : ℕ) : abs (a : α) = a := abs_of_nonneg (cast_nonneg a) end nat lemma add_monoid_hom.eq_nat_cast {A} [add_monoid A] [has_one A] (f : ℕ →+ A) (h1 : f 1 = 1) : ∀ n : ℕ, f n = n | 0 := by simp only [nat.cast_zero, f.map_zero] | (n+1) := by simp only [nat.cast_succ, f.map_add, add_monoid_hom.eq_nat_cast n, h1] @[simp] lemma ring_hom.eq_nat_cast {R} [semiring R] (f : ℕ →+* R) (n : ℕ) : f n = n := f.to_add_monoid_hom.eq_nat_cast f.map_one n @[simp] lemma ring_hom.map_nat_cast {R S} [semiring R] [semiring S] (f : R →+* S) (n : ℕ) : f n = n := (f.comp (nat.cast_ring_hom R)).eq_nat_cast n @[simp, norm_cast] theorem nat.cast_id (n : ℕ) : ↑n = n := ((ring_hom.id ℕ).eq_nat_cast n).symm
7f9ef398f8162e0aa4604198c76630f62d4b5716
9dc8cecdf3c4634764a18254e94d43da07142918
/src/combinatorics/configuration.lean
1c3de6a1590dc8323f6de84ceaa5f1c023accaf1
[ "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
23,701
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 algebra.big_operators.order import combinatorics.hall.basic import data.fintype.card import set_theory.cardinal.finite /-! # Configurations of Points and lines This file introduces abstract configurations of points and lines, and proves some basic properties. ## Main definitions * `configuration.nondegenerate`: Excludes certain degenerate configurations, and imposes uniqueness of intersection points. * `configuration.has_points`: A nondegenerate configuration in which every pair of lines has an intersection point. * `configuration.has_lines`: A nondegenerate configuration in which every pair of points has a line through them. * `configuration.line_count`: The number of lines through a given point. * `configuration.point_count`: The number of lines through a given line. ## Main statements * `configuration.has_lines.card_le`: `has_lines` implies `|P| ≤ |L|`. * `configuration.has_points.card_le`: `has_points` implies `|L| ≤ |P|`. * `configuration.has_lines.has_points`: `has_lines` and `|P| = |L|` implies `has_points`. * `configuration.has_points.has_lines`: `has_points` and `|P| = |L|` implies `has_lines`. Together, these four statements say that any two of the following properties imply the third: (a) `has_lines`, (b) `has_points`, (c) `|P| = |L|`. -/ open_locale big_operators namespace configuration universe u variables (P L : Type u) [has_mem P L] /-- A type synonym. -/ def dual := P instance [this : inhabited P] : inhabited (dual P) := this instance [finite P] : finite (dual P) := ‹finite P› instance [this : fintype P] : fintype (dual P) := this instance : has_mem (dual L) (dual P) := ⟨function.swap (has_mem.mem : P → L → Prop)⟩ /-- A configuration is nondegenerate if: 1) there does not exist a line that passes through all of the points, 2) there does not exist a point that is on all of the lines, 3) there is at most one line through any two points, 4) any two lines have at most one intersection point. Conditions 3 and 4 are equivalent. -/ class nondegenerate : Prop := (exists_point : ∀ l : L, ∃ p, p ∉ l) (exists_line : ∀ p, ∃ l : L, p ∉ l) (eq_or_eq : ∀ {p₁ p₂ : P} {l₁ l₂ : L}, p₁ ∈ l₁ → p₂ ∈ l₁ → p₁ ∈ l₂ → p₂ ∈ l₂ → p₁ = p₂ ∨ l₁ = l₂) /-- A nondegenerate configuration in which every pair of lines has an intersection point. -/ class has_points extends nondegenerate P L : Type u := (mk_point : ∀ {l₁ l₂ : L} (h : l₁ ≠ l₂), P) (mk_point_ax : ∀ {l₁ l₂ : L} (h : l₁ ≠ l₂), mk_point h ∈ l₁ ∧ mk_point h ∈ l₂) /-- A nondegenerate configuration in which every pair of points has a line through them. -/ class has_lines extends nondegenerate P L : Type u := (mk_line : ∀ {p₁ p₂ : P} (h : p₁ ≠ p₂), L) (mk_line_ax : ∀ {p₁ p₂ : P} (h : p₁ ≠ p₂), p₁ ∈ mk_line h ∧ p₂ ∈ mk_line h) open nondegenerate has_points has_lines instance [nondegenerate P L] : nondegenerate (dual L) (dual P) := { exists_point := @exists_line P L _ _, exists_line := @exists_point P L _ _, eq_or_eq := λ l₁ l₂ p₁ p₂ h₁ h₂ h₃ h₄, (@eq_or_eq P L _ _ p₁ p₂ l₁ l₂ h₁ h₃ h₂ h₄).symm } instance [has_points P L] : has_lines (dual L) (dual P) := { mk_line := @mk_point P L _ _, mk_line_ax := λ _ _, mk_point_ax } instance [has_lines P L] : has_points (dual L) (dual P) := { mk_point := @mk_line P L _ _, mk_point_ax := λ _ _, mk_line_ax } lemma has_points.exists_unique_point [has_points P L] (l₁ l₂ : L) (hl : l₁ ≠ l₂) : ∃! p, p ∈ l₁ ∧ p ∈ l₂ := ⟨mk_point hl, mk_point_ax hl, λ p hp, (eq_or_eq hp.1 (mk_point_ax hl).1 hp.2 (mk_point_ax hl).2).resolve_right hl⟩ lemma has_lines.exists_unique_line [has_lines P L] (p₁ p₂ : P) (hp : p₁ ≠ p₂) : ∃! l : L, p₁ ∈ l ∧ p₂ ∈ l := has_points.exists_unique_point (dual L) (dual P) p₁ p₂ hp variables {P L} /-- If a nondegenerate configuration has at least as many points as lines, then there exists an injective function `f` from lines to points, such that `f l` does not lie on `l`. -/ lemma nondegenerate.exists_injective_of_card_le [nondegenerate P L] [fintype P] [fintype L] (h : fintype.card L ≤ fintype.card P) : ∃ f : L → P, function.injective f ∧ ∀ l, (f l) ∉ l := begin classical, let t : L → finset P := λ l, (set.to_finset {p | p ∉ l}), suffices : ∀ s : finset L, s.card ≤ (s.bUnion t).card, -- Hall's marriage theorem { obtain ⟨f, hf1, hf2⟩ := (finset.all_card_le_bUnion_card_iff_exists_injective t).mp this, exact ⟨f, hf1, λ l, set.mem_to_finset.mp (hf2 l)⟩ }, intro s, by_cases hs₀ : s.card = 0, -- If `s = ∅`, then `s.card = 0 ≤ (s.bUnion t).card` { simp_rw [hs₀, zero_le] }, by_cases hs₁ : s.card = 1, -- If `s = {l}`, then pick a point `p ∉ l` { obtain ⟨l, rfl⟩ := finset.card_eq_one.mp hs₁, obtain ⟨p, hl⟩ := exists_point l, rw [finset.card_singleton, finset.singleton_bUnion, nat.one_le_iff_ne_zero], exact finset.card_ne_zero_of_mem (set.mem_to_finset.mpr hl) }, suffices : (s.bUnion t)ᶜ.card ≤ sᶜ.card, -- Rephrase in terms of complements (uses `h`) { rw [finset.card_compl, finset.card_compl, tsub_le_iff_left] at this, replace := h.trans this, rwa [←add_tsub_assoc_of_le s.card_le_univ, le_tsub_iff_left (le_add_left s.card_le_univ), add_le_add_iff_right] at this }, have hs₂ : (s.bUnion t)ᶜ.card ≤ 1, -- At most one line through two points of `s` { refine finset.card_le_one_iff.mpr (λ p₁ p₂ hp₁ hp₂, _), simp_rw [finset.mem_compl, finset.mem_bUnion, exists_prop, not_exists, not_and, set.mem_to_finset, set.mem_set_of_eq, not_not] at hp₁ hp₂, obtain ⟨l₁, l₂, hl₁, hl₂, hl₃⟩ := finset.one_lt_card_iff.mp (nat.one_lt_iff_ne_zero_and_ne_one.mpr ⟨hs₀, hs₁⟩), exact (eq_or_eq (hp₁ l₁ hl₁) (hp₂ l₁ hl₁) (hp₁ l₂ hl₂) (hp₂ l₂ hl₂)).resolve_right hl₃ }, by_cases hs₃ : sᶜ.card = 0, { rw [hs₃, le_zero_iff], rw [finset.card_compl, tsub_eq_zero_iff_le, has_le.le.le_iff_eq (finset.card_le_univ _), eq_comm, finset.card_eq_iff_eq_univ] at hs₃ ⊢, rw hs₃, rw finset.eq_univ_iff_forall at hs₃ ⊢, exact λ p, exists.elim (exists_line p) -- If `s = univ`, then show `s.bUnion t = univ` (λ l hl, finset.mem_bUnion.mpr ⟨l, finset.mem_univ l, set.mem_to_finset.mpr hl⟩) }, { exact hs₂.trans (nat.one_le_iff_ne_zero.mpr hs₃) }, -- If `s < univ`, then consequence of `hs₂` end variables {P} (L) /-- Number of points on a given line. -/ noncomputable def line_count (p : P) : ℕ := nat.card {l : L // p ∈ l} variables (P) {L} /-- Number of lines through a given point. -/ noncomputable def point_count (l : L) : ℕ := nat.card {p : P // p ∈ l} variables (P L) lemma sum_line_count_eq_sum_point_count [fintype P] [fintype L] : ∑ p : P, line_count L p = ∑ l : L, point_count P l := begin classical, simp only [line_count, point_count, nat.card_eq_fintype_card, ←fintype.card_sigma], apply fintype.card_congr, calc (Σ p, {l : L // p ∈ l}) ≃ {x : P × L // x.1 ∈ x.2} : (equiv.subtype_prod_equiv_sigma_subtype (∈)).symm ... ≃ {x : L × P // x.2 ∈ x.1} : (equiv.prod_comm P L).subtype_equiv (λ x, iff.rfl) ... ≃ (Σ l, {p // p ∈ l}) : equiv.subtype_prod_equiv_sigma_subtype (λ (l : L) (p : P), p ∈ l), end variables {P L} lemma has_lines.point_count_le_line_count [has_lines P L] {p : P} {l : L} (h : p ∉ l) [finite {l : L // p ∈ l}] : point_count P l ≤ line_count L p := begin by_cases hf : infinite {p : P // p ∈ l}, { exactI (le_of_eq nat.card_eq_zero_of_infinite).trans (zero_le (line_count L p)) }, haveI := fintype_of_not_infinite hf, casesI nonempty_fintype {l : L // p ∈ l}, rw [line_count, point_count, nat.card_eq_fintype_card, nat.card_eq_fintype_card], have : ∀ p' : {p // p ∈ l}, p ≠ p' := λ p' hp', h ((congr_arg (∈ l) hp').mpr p'.2), exact fintype.card_le_of_injective (λ p', ⟨mk_line (this p'), (mk_line_ax (this p')).1⟩) (λ p₁ p₂ hp, subtype.ext ((eq_or_eq p₁.2 p₂.2 (mk_line_ax (this p₁)).2 ((congr_arg _ (subtype.ext_iff.mp hp)).mpr (mk_line_ax (this p₂)).2)).resolve_right (λ h', (congr_arg _ h').mp h (mk_line_ax (this p₁)).1))), end lemma has_points.line_count_le_point_count [has_points P L] {p : P} {l : L} (h : p ∉ l) [hf : finite {p : P // p ∈ l}] : line_count L p ≤ point_count P l := @has_lines.point_count_le_line_count (dual L) (dual P) _ _ l p h hf variables (P L) /-- If a nondegenerate configuration has a unique line through any two points, then `|P| ≤ |L|`. -/ lemma has_lines.card_le [has_lines P L] [fintype P] [fintype L] : fintype.card P ≤ fintype.card L := begin classical, by_contradiction hc₂, obtain ⟨f, hf₁, hf₂⟩ := nondegenerate.exists_injective_of_card_le (le_of_not_le hc₂), have := calc ∑ p, line_count L p = ∑ l, point_count P l : sum_line_count_eq_sum_point_count P L ... ≤ ∑ l, line_count L (f l) : finset.sum_le_sum (λ l hl, has_lines.point_count_le_line_count (hf₂ l)) ... = ∑ p in finset.univ.image f, line_count L p : finset.sum_bij (λ l hl, f l) (λ l hl, finset.mem_image_of_mem f hl) (λ l hl, rfl) (λ l₁ l₂ hl₁ hl₂ hl₃, hf₁ hl₃) (λ p, by simp_rw [finset.mem_image, eq_comm, imp_self]) ... < ∑ p, line_count L p : _, { exact lt_irrefl _ this }, { obtain ⟨p, hp⟩ := not_forall.mp (mt (fintype.card_le_of_surjective f) hc₂), refine finset.sum_lt_sum_of_subset ((finset.univ.image f).subset_univ) (finset.mem_univ p) _ _ (λ p hp₁ hp₂, zero_le (line_count L p)), { simpa only [finset.mem_image, exists_prop, finset.mem_univ, true_and] }, { rw [line_count, nat.card_eq_fintype_card, fintype.card_pos_iff], obtain ⟨l, hl⟩ := @exists_line P L _ _ p, exact let this := not_exists.mp hp l in ⟨⟨mk_line this, (mk_line_ax this).2⟩⟩ } }, end /-- If a nondegenerate configuration has a unique point on any two lines, then `|L| ≤ |P|`. -/ lemma has_points.card_le [has_points P L] [fintype P] [fintype L] : fintype.card L ≤ fintype.card P := @has_lines.card_le (dual L) (dual P) _ _ _ _ variables {P L} lemma has_lines.exists_bijective_of_card_eq [has_lines P L] [fintype P] [fintype L] (h : fintype.card P = fintype.card L) : ∃ f : L → P, function.bijective f ∧ ∀ l, point_count P l = line_count L (f l) := begin classical, obtain ⟨f, hf1, hf2⟩ := nondegenerate.exists_injective_of_card_le (ge_of_eq h), have hf3 := (fintype.bijective_iff_injective_and_card f).mpr ⟨hf1, h.symm⟩, refine ⟨f, hf3, λ l, (finset.sum_eq_sum_iff_of_le (by exact λ l hl, has_lines.point_count_le_line_count (hf2 l))).mp ((sum_line_count_eq_sum_point_count P L).symm.trans ((finset.sum_bij (λ l hl, f l) (λ l hl, finset.mem_univ (f l)) (λ l hl, refl (line_count L (f l))) (λ l₁ l₂ hl₁ hl₂ hl, hf1 hl) (λ p hp, _)).symm)) l (finset.mem_univ l)⟩, obtain ⟨l, rfl⟩ := hf3.2 p, exact ⟨l, finset.mem_univ l, rfl⟩, end lemma has_lines.line_count_eq_point_count [has_lines P L] [fintype P] [fintype L] (hPL : fintype.card P = fintype.card L) {p : P} {l : L} (hpl : p ∉ l) : line_count L p = point_count P l := begin classical, obtain ⟨f, hf1, hf2⟩ := has_lines.exists_bijective_of_card_eq hPL, let s : finset (P × L) := set.to_finset {i | i.1 ∈ i.2}, have step1 : ∑ i : P × L, line_count L i.1 = ∑ i : P × L, point_count P i.2, { rw [←finset.univ_product_univ, finset.sum_product_right, finset.sum_product], simp_rw [finset.sum_const, finset.card_univ, hPL, sum_line_count_eq_sum_point_count] }, have step2 : ∑ i in s, line_count L i.1 = ∑ i in s, point_count P i.2, { rw [s.sum_finset_product finset.univ (λ p, set.to_finset {l | p ∈ l})], rw [s.sum_finset_product_right finset.univ (λ l, set.to_finset {p | p ∈ l})], refine (finset.sum_bij (λ l hl, f l) (λ l hl, finset.mem_univ (f l)) (λ l hl, _) (λ _ _ _ _ h, hf1.1 h) (λ p hp, _)).symm, { simp_rw [finset.sum_const, set.to_finset_card, ←nat.card_eq_fintype_card], change (point_count P l) • (point_count P l) = (line_count L (f l)) • (line_count L (f l)), rw hf2 }, { obtain ⟨l, hl⟩ := hf1.2 p, exact ⟨l, finset.mem_univ l, hl.symm⟩ }, all_goals { simp_rw [finset.mem_univ, true_and, set.mem_to_finset], exact λ p, iff.rfl } }, have step3 : ∑ i in sᶜ, line_count L i.1 = ∑ i in sᶜ, point_count P i.2, { rwa [←s.sum_add_sum_compl, ←s.sum_add_sum_compl, step2, add_left_cancel_iff] at step1 }, rw ← set.to_finset_compl at step3, exact ((finset.sum_eq_sum_iff_of_le (by exact λ i hi, has_lines.point_count_le_line_count (set.mem_to_finset.mp hi))).mp step3.symm (p, l) (set.mem_to_finset.mpr hpl)).symm, end lemma has_points.line_count_eq_point_count [has_points P L] [fintype P] [fintype L] (hPL : fintype.card P = fintype.card L) {p : P} {l : L} (hpl : p ∉ l) : line_count L p = point_count P l := (@has_lines.line_count_eq_point_count (dual L) (dual P) _ _ _ _ hPL.symm l p hpl).symm /-- If a nondegenerate configuration has a unique line through any two points, and if `|P| = |L|`, then there is a unique point on any two lines. -/ noncomputable def has_lines.has_points [has_lines P L] [fintype P] [fintype L] (h : fintype.card P = fintype.card L) : has_points P L := let this : ∀ l₁ l₂ : L, l₁ ≠ l₂ → ∃ p : P, p ∈ l₁ ∧ p ∈ l₂ := λ l₁ l₂ hl, begin classical, obtain ⟨f, hf1, hf2⟩ := has_lines.exists_bijective_of_card_eq h, haveI : nontrivial L := ⟨⟨l₁, l₂, hl⟩⟩, haveI := fintype.one_lt_card_iff_nontrivial.mp ((congr_arg _ h).mpr fintype.one_lt_card), have h₁ : ∀ p : P, 0 < line_count L p := λ p, exists.elim (exists_ne p) (λ q hq, (congr_arg _ nat.card_eq_fintype_card).mpr (fintype.card_pos_iff.mpr ⟨⟨mk_line hq, (mk_line_ax hq).2⟩⟩)), have h₂ : ∀ l : L, 0 < point_count P l := λ l, (congr_arg _ (hf2 l)).mpr (h₁ (f l)), obtain ⟨p, hl₁⟩ := fintype.card_pos_iff.mp ((congr_arg _ nat.card_eq_fintype_card).mp (h₂ l₁)), by_cases hl₂ : p ∈ l₂, exact ⟨p, hl₁, hl₂⟩, have key' : fintype.card {q : P // q ∈ l₂} = fintype.card {l : L // p ∈ l}, { exact ((has_lines.line_count_eq_point_count h hl₂).trans nat.card_eq_fintype_card).symm.trans nat.card_eq_fintype_card, }, have : ∀ q : {q // q ∈ l₂}, p ≠ q := λ q hq, hl₂ ((congr_arg (∈ l₂) hq).mpr q.2), let f : {q : P // q ∈ l₂} → {l : L // p ∈ l} := λ q, ⟨mk_line (this q), (mk_line_ax (this q)).1⟩, have hf : function.injective f := λ q₁ q₂ hq, subtype.ext ((eq_or_eq q₁.2 q₂.2 (mk_line_ax (this q₁)).2 ((congr_arg _ (subtype.ext_iff.mp hq)).mpr (mk_line_ax (this q₂)).2)).resolve_right (λ h, (congr_arg _ h).mp hl₂ (mk_line_ax (this q₁)).1)), have key' := ((fintype.bijective_iff_injective_and_card f).mpr ⟨hf, key'⟩).2, obtain ⟨q, hq⟩ := key' ⟨l₁, hl₁⟩, exact ⟨q, (congr_arg _ (subtype.ext_iff.mp hq)).mp (mk_line_ax (this q)).2, q.2⟩, end in { mk_point := λ l₁ l₂ hl, classical.some (this l₁ l₂ hl), mk_point_ax := λ l₁ l₂ hl, classical.some_spec (this l₁ l₂ hl) } /-- If a nondegenerate configuration has a unique point on any two lines, and if `|P| = |L|`, then there is a unique line through any two points. -/ noncomputable def has_points.has_lines [has_points P L] [fintype P] [fintype L] (h : fintype.card P = fintype.card L) : has_lines P L := let this := @has_lines.has_points (dual L) (dual P) _ _ _ _ h.symm in { mk_line := λ _ _, this.mk_point, mk_line_ax := λ _ _, this.mk_point_ax } variables (P L) /-- A projective plane is a nondegenerate configuration in which every pair of lines has an intersection point, every pair of points has a line through them, and which has three points in general position. -/ class projective_plane extends nondegenerate P L : Type u := (mk_point : ∀ {l₁ l₂ : L} (h : l₁ ≠ l₂), P) (mk_point_ax : ∀ {l₁ l₂ : L} (h : l₁ ≠ l₂), mk_point h ∈ l₁ ∧ mk_point h ∈ l₂) (mk_line : ∀ {p₁ p₂ : P} (h : p₁ ≠ p₂), L) (mk_line_ax : ∀ {p₁ p₂ : P} (h : p₁ ≠ p₂), p₁ ∈ mk_line h ∧ p₂ ∈ mk_line h) (exists_config : ∃ (p₁ p₂ p₃ : P) (l₁ l₂ l₃ : L), p₁ ∉ l₂ ∧ p₁ ∉ l₃ ∧ p₂ ∉ l₁ ∧ p₂ ∈ l₂ ∧ p₂ ∈ l₃ ∧ p₃ ∉ l₁ ∧ p₃ ∈ l₂ ∧ p₃ ∉ l₃) namespace projective_plane @[priority 100] -- see Note [lower instance priority] instance has_points [h : projective_plane P L] : has_points P L := { .. h } @[priority 100] -- see Note [lower instance priority] instance has_lines [h : projective_plane P L] : has_lines P L := { .. h } variables [projective_plane P L] instance : projective_plane (dual L) (dual P) := { mk_line := @mk_point P L _ _, mk_line_ax := λ _ _, mk_point_ax, mk_point := @mk_line P L _ _, mk_point_ax := λ _ _, mk_line_ax, exists_config := by { obtain ⟨p₁, p₂, p₃, l₁, l₂, l₃, h₁₂, h₁₃, h₂₁, h₂₂, h₂₃, h₃₁, h₃₂, h₃₃⟩ := @exists_config P L _ _, exact ⟨l₁, l₂, l₃, p₁, p₂, p₃, h₂₁, h₃₁, h₁₂, h₂₂, h₃₂, h₁₃, h₂₃, h₃₃⟩ }, .. dual.nondegenerate P L } /-- The order of a projective plane is one less than the number of lines through an arbitrary point. Equivalently, it is one less than the number of points on an arbitrary line. -/ noncomputable def order : ℕ := line_count L (classical.some (@exists_config P L _ _)) - 1 lemma card_points_eq_card_lines [fintype P] [fintype L] : fintype.card P = fintype.card L := le_antisymm (has_lines.card_le P L) (has_points.card_le P L) variables {P} (L) lemma line_count_eq_line_count [finite P] [finite L] (p q : P) : line_count L p = line_count L q := begin casesI nonempty_fintype P, casesI nonempty_fintype L, obtain ⟨p₁, p₂, p₃, l₁, l₂, l₃, h₁₂, h₁₃, h₂₁, h₂₂, h₂₃, h₃₁, h₃₂, h₃₃⟩ := exists_config, have h := card_points_eq_card_lines P L, let n := line_count L p₂, have hp₂ : line_count L p₂ = n := rfl, have hl₁ : point_count P l₁ = n := (has_lines.line_count_eq_point_count h h₂₁).symm.trans hp₂, have hp₃ : line_count L p₃ = n := (has_lines.line_count_eq_point_count h h₃₁).trans hl₁, have hl₃ : point_count P l₃ = n := (has_lines.line_count_eq_point_count h h₃₃).symm.trans hp₃, have hp₁ : line_count L p₁ = n := (has_lines.line_count_eq_point_count h h₁₃).trans hl₃, have hl₂ : point_count P l₂ = n := (has_lines.line_count_eq_point_count h h₁₂).symm.trans hp₁, suffices : ∀ p : P, line_count L p = n, { exact (this p).trans (this q).symm }, refine λ p, or_not.elim (λ h₂, _) (λ h₂, (has_lines.line_count_eq_point_count h h₂).trans hl₂), refine or_not.elim (λ h₃, _) (λ h₃, (has_lines.line_count_eq_point_count h h₃).trans hl₃), rwa (eq_or_eq h₂ h₂₂ h₃ h₂₃).resolve_right (λ h, h₃₃ ((congr_arg (has_mem.mem p₃) h).mp h₃₂)), end variables (P) {L} lemma point_count_eq_point_count [finite P] [finite L] (l m : L) : point_count P l = point_count P m := line_count_eq_line_count (dual P) l m variables {P L} lemma line_count_eq_point_count [finite P] [finite L] (p : P) (l : L) : line_count L p = point_count P l := exists.elim (exists_point l) $ λ q hq, (line_count_eq_line_count L p q).trans $ by { casesI nonempty_fintype P, casesI nonempty_fintype L, exact has_lines.line_count_eq_point_count (card_points_eq_card_lines P L) hq } variables (P L) lemma dual.order [finite P] [finite L] : order (dual L) (dual P) = order P L := congr_arg (λ n, n - 1) (line_count_eq_point_count _ _) variables {P} (L) lemma line_count_eq [finite P] [finite L] (p : P) : line_count L p = order P L + 1 := begin classical, obtain ⟨q, -, -, l, -, -, -, -, h, -⟩ := classical.some_spec (@exists_config P L _ _), casesI nonempty_fintype {l : L // q ∈ l}, rw [order, line_count_eq_line_count L p q, line_count_eq_line_count L (classical.some _) q, line_count, nat.card_eq_fintype_card, nat.sub_add_cancel], exact fintype.card_pos_iff.mpr ⟨⟨l, h⟩⟩, end variables (P) {L} lemma point_count_eq [finite P] [finite L] (l : L) : point_count P l = order P L + 1 := (line_count_eq (dual P) l).trans (congr_arg (λ n, n + 1) (dual.order P L)) variables (P L) lemma one_lt_order [finite P] [finite L] : 1 < order P L := begin obtain ⟨p₁, p₂, p₃, l₁, l₂, l₃, -, -, h₂₁, h₂₂, h₂₃, h₃₁, h₃₂, h₃₃⟩ := @exists_config P L _ _, classical, casesI nonempty_fintype {p : P // p ∈ l₂}, rw [←add_lt_add_iff_right, ←point_count_eq _ l₂, point_count, nat.card_eq_fintype_card], simp_rw [fintype.two_lt_card_iff, ne, subtype.ext_iff], have h := mk_point_ax (λ h, h₂₁ ((congr_arg _ h).mpr h₂₂)), exact ⟨⟨mk_point _, h.2⟩, ⟨p₂, h₂₂⟩, ⟨p₃, h₃₂⟩, ne_of_mem_of_not_mem h.1 h₂₁, ne_of_mem_of_not_mem h.1 h₃₁, ne_of_mem_of_not_mem h₂₃ h₃₃⟩, end variables {P} (L) lemma two_lt_line_count [finite P] [finite L] (p : P) : 2 < line_count L p := by simpa only [line_count_eq L p, nat.succ_lt_succ_iff] using one_lt_order P L variables (P) {L} lemma two_lt_point_count [finite P] [finite L] (l : L) : 2 < point_count P l := by simpa only [point_count_eq P l, nat.succ_lt_succ_iff] using one_lt_order P L variables (P) (L) lemma card_points [fintype P] [finite L] : fintype.card P = order P L ^ 2 + order P L + 1 := begin casesI nonempty_fintype L, obtain ⟨p, -⟩ := @exists_config P L _ _, let ϕ : {q // q ≠ p} ≃ Σ (l : {l : L // p ∈ l}), {q // q ∈ l.1 ∧ q ≠ p} := { to_fun := λ q, ⟨⟨mk_line q.2, (mk_line_ax q.2).2⟩, q, (mk_line_ax q.2).1, q.2⟩, inv_fun := λ lq, ⟨lq.2, lq.2.2.2⟩, left_inv := λ q, subtype.ext rfl, right_inv := λ lq, sigma.subtype_ext (subtype.ext ((eq_or_eq (mk_line_ax lq.2.2.2).1 (mk_line_ax lq.2.2.2).2 lq.2.2.1 lq.1.2).resolve_left lq.2.2.2)) rfl }, classical, have h1 : fintype.card {q // q ≠ p} + 1 = fintype.card P, { apply (eq_tsub_iff_add_eq_of_le (nat.succ_le_of_lt (fintype.card_pos_iff.mpr ⟨p⟩))).mp, convert (fintype.card_subtype_compl _).trans (congr_arg _ (fintype.card_subtype_eq p)) }, have h2 : ∀ l : {l : L // p ∈ l}, fintype.card {q // q ∈ l.1 ∧ q ≠ p} = order P L, { intro l, rw [←fintype.card_congr (equiv.subtype_subtype_equiv_subtype_inter _ _), fintype.card_subtype_compl (λ (x : subtype (∈ l.val)), x.val = p), ←nat.card_eq_fintype_card], refine tsub_eq_of_eq_add ((point_count_eq P l.1).trans _), rw ← fintype.card_subtype_eq (⟨p, l.2⟩ : {q : P // q ∈ l.1}), simp_rw subtype.ext_iff_val }, simp_rw [←h1, fintype.card_congr ϕ, fintype.card_sigma, h2, finset.sum_const, finset.card_univ], rw [←nat.card_eq_fintype_card, ←line_count, line_count_eq, smul_eq_mul, nat.succ_mul, sq], end lemma card_lines [finite P] [fintype L] : fintype.card L = order P L ^ 2 + order P L + 1 := (card_points (dual L) (dual P)).trans (congr_arg (λ n, n ^ 2 + n + 1) (dual.order P L)) end projective_plane end configuration
a9495a19249013cf1eb4b6dd0c05b5fa8a20895d
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/field_theory/separable.lean
b036be4c6df0383b6b858ec164dc4a2da1abb93c
[ "Apache-2.0" ]
permissive
DanielFabian/mathlib
efc3a50b5dde303c59eeb6353ef4c35a345d7112
f520d07eba0c852e96fe26da71d85bf6d40fcc2a
refs/heads/master
1,668,739,922,971
1,595,201,756,000
1,595,201,756,000
279,469,476
0
0
null
1,594,696,604,000
1,594,696,604,000
null
UTF-8
Lean
false
false
14,387
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau. -/ import ring_theory.polynomial /-! # Separable polynomials We define a polynomial to be separable if it is coprime with its derivative. We prove basic properties about separable polynomials here. ## Main definitions * `polynomial.separable f`: a polynomial `f` is separable iff it is coprime with its derivative. * `polynomial.expand R p f`: expand the polynomial `f` with coefficients in a commutative semiring `R` by a factor of p, so `expand R p (∑ aₙ xⁿ)` is `∑ aₙ xⁿᵖ`. * `polynomial.contract p f`: the opposite of `expand`, so it sends `∑ aₙ xⁿᵖ` to `∑ aₙ xⁿ`. -/ universes u v w open_locale classical namespace polynomial section comm_semiring variables {R : Type u} [comm_semiring R] {S : Type v} [comm_semiring S] /-- A polynomial is separable iff it is coprime with its derivative. -/ def separable (f : polynomial R) : Prop := is_coprime f f.derivative lemma separable_def (f : polynomial R) : f.separable ↔ is_coprime f f.derivative := iff.rfl lemma separable_def' (f : polynomial R) : f.separable ↔ ∃ a b : polynomial R, a * f + b * f.derivative = 1 := iff.rfl lemma separable_one : (1 : polynomial R).separable := is_coprime_one_left lemma separable_X_add_C (a : R) : (X + C a).separable := by { rw [separable_def, derivative_add, derivative_X, derivative_C, add_zero], exact is_coprime_one_right } lemma separable_X : (X : polynomial R).separable := by { rw [separable_def, derivative_X], exact is_coprime_one_right } lemma separable_C (r : R) : (C r).separable ↔ is_unit r := by rw [separable_def, derivative_C, is_coprime_zero_right, is_unit_C] lemma separable.of_mul_left {f g : polynomial R} (h : (f * g).separable) : f.separable := begin have := h.of_mul_left_left, rw derivative_mul at this, exact is_coprime.of_mul_right_left (is_coprime.of_add_mul_left_right this) end lemma separable.of_mul_right {f g : polynomial R} (h : (f * g).separable) : g.separable := by { rw mul_comm at h, exact h.of_mul_left } lemma separable.is_coprime {f g : polynomial R} (h : (f * g).separable) : is_coprime f g := begin have := h.of_mul_left_left, rw derivative_mul at this, exact is_coprime.of_mul_right_right (is_coprime.of_add_mul_left_right this) end theorem separable.of_pow' {f : polynomial R} : ∀ {n : ℕ} (h : (f ^ n).separable), is_unit f ∨ (f.separable ∧ n = 1) ∨ n = 0 | 0 := λ h, or.inr $ or.inr rfl | 1 := λ h, or.inr $ or.inl ⟨pow_one f ▸ h, rfl⟩ | (n+2) := λ h, or.inl $ is_coprime_self.1 h.is_coprime.of_mul_right_left theorem separable.of_pow {f : polynomial R} (hf : ¬is_unit f) {n : ℕ} (hn : n ≠ 0) (hfs : (f ^ n).separable) : f.separable ∧ n = 1 := (hfs.of_pow'.resolve_left hf).resolve_right hn theorem separable.map {p : polynomial R} (h : p.separable) {f : R →+* S} : (p.map f).separable := let ⟨a, b, H⟩ := h in ⟨a.map f, b.map f, by rw [derivative_map, ← map_mul, ← map_mul, ← map_add, H, map_one]⟩ variables (R) (p q : ℕ) /-- Expand the polynomial by a factor of p, so `∑ aₙ xⁿ` becomes `∑ aₙ xⁿᵖ`. -/ noncomputable def expand : polynomial R →ₐ[R] polynomial R := { commutes' := λ r, eval₂_C _ _, .. (eval₂_ring_hom C (X ^ p) : polynomial R →+* polynomial R) } lemma coe_expand : (expand R p : polynomial R → polynomial R) = eval₂ C (X ^ p) := rfl variables {R} @[simp] lemma expand_C (r : R) : expand R p (C r) = C r := eval₂_C _ _ @[simp] lemma expand_X : expand R p X = X ^ p := eval₂_X _ _ @[simp] lemma expand_monomial (r : R) : expand R p (monomial q r) = monomial (q * p) r := by simp_rw [monomial_eq_smul_X, alg_hom.map_smul, alg_hom.map_pow, expand_X, mul_comm, pow_mul] theorem expand_expand (f : polynomial R) : expand R p (expand R q f) = expand R (p * q) f := polynomial.induction_on f (λ r, by simp_rw expand_C) (λ f g ihf ihg, by simp_rw [alg_hom.map_add, ihf, ihg]) (λ n r ih, by simp_rw [alg_hom.map_mul, expand_C, alg_hom.map_pow, expand_X, alg_hom.map_pow, expand_X, pow_mul]) theorem expand_mul (f : polynomial R) : expand R (p * q) f = expand R p (expand R q f) := (expand_expand p q f).symm @[simp] theorem expand_one (f : polynomial R) : expand R 1 f = f := polynomial.induction_on f (λ r, by rw expand_C) (λ f g ihf ihg, by rw [alg_hom.map_add, ihf, ihg]) (λ n r ih, by rw [alg_hom.map_mul, expand_C, alg_hom.map_pow, expand_X, pow_one]) theorem expand_pow (f : polynomial R) : expand R (p ^ q) f = (expand R p ^[q] f) := nat.rec_on q (by rw [nat.pow_zero, expand_one, function.iterate_zero, id]) $ λ n ih, by rw [function.iterate_succ_apply', nat.pow_succ, mul_comm, expand_mul, ih] theorem derivative_expand (f : polynomial R) : (expand R p f).derivative = expand R p f.derivative * (p * X ^ (p - 1)) := by rw [coe_expand, derivative_eval₂_C, derivative_pow, derivative_X, mul_one] theorem coeff_expand {p : ℕ} (hp : 0 < p) (f : polynomial R) (n : ℕ) : (expand R p f).coeff n = if p ∣ n then f.coeff (n / p) else 0 := begin change (show ℕ →₀ R, from (f.sum (λ e a, C a * (X ^ p) ^ e) : polynomial R)) n = _, simp_rw [finsupp.sum_apply, finsupp.sum, ← pow_mul, C_mul', ← monomial_eq_smul_X, monomial, finsupp.single_apply], split_ifs with h, { rw [finset.sum_eq_single (n/p), nat.mul_div_cancel' h, if_pos rfl], refl, { intros b hb1 hb2, rw if_neg, intro hb3, apply hb2, rw [← hb3, nat.mul_div_cancel_left b hp] }, { intro hn, rw finsupp.not_mem_support_iff.1 hn, split_ifs; refl } }, { rw finset.sum_eq_zero, intros k hk, rw if_neg, exact λ hkn, h ⟨k, hkn.symm⟩, }, end @[simp] theorem coeff_expand_mul {p : ℕ} (hp : 0 < p) (f : polynomial R) (n : ℕ) : (expand R p f).coeff (n * p) = f.coeff n := by rw [coeff_expand hp, if_pos (dvd_mul_left _ _), nat.mul_div_cancel _ hp] @[simp] theorem coeff_expand_mul' {p : ℕ} (hp : 0 < p) (f : polynomial R) (n : ℕ) : (expand R p f).coeff (p * n) = f.coeff n := by rw [mul_comm, coeff_expand_mul hp] theorem expand_eq_map_domain (p : ℕ) (f : polynomial R) : expand R p f = f.map_domain (*p) := finsupp.induction f rfl $ λ n r f hf hr ih, by rw [finsupp.map_domain_add, finsupp.map_domain_single, alg_hom.map_add, ← monomial, expand_monomial, ← monomial, ih] theorem expand_inj {p : ℕ} (hp : 0 < p) {f g : polynomial R} : expand R p f = expand R p g ↔ f = g := ⟨λ H, ext $ λ n, by rw [← coeff_expand_mul hp, H, coeff_expand_mul hp], congr_arg _⟩ theorem expand_eq_zero {p : ℕ} (hp : 0 < p) {f : polynomial R} : expand R p f = 0 ↔ f = 0 := by rw [← (expand R p).map_zero, expand_inj hp, alg_hom.map_zero] theorem expand_eq_C {p : ℕ} (hp : 0 < p) {f : polynomial R} {r : R} : expand R p f = C r ↔ f = C r := by rw [← expand_C, expand_inj hp, expand_C] theorem nat_degree_expand (p : ℕ) (f : polynomial R) : (expand R p f).nat_degree = f.nat_degree * p := begin cases p.eq_zero_or_pos with hp hp, { rw [hp, coe_expand, pow_zero, mul_zero, ← C_1, eval₂_hom, nat_degree_C] }, by_cases hf : f = 0, { rw [hf, alg_hom.map_zero, nat_degree_zero, zero_mul] }, have hf1 : expand R p f ≠ 0 := mt (expand_eq_zero hp).1 hf, rw [← with_bot.coe_eq_coe, ← degree_eq_nat_degree hf1], refine le_antisymm ((degree_le_iff_coeff_zero _ _).2 $ λ n hn, _) _, { rw coeff_expand hp, split_ifs with hpn, { rw coeff_eq_zero_of_nat_degree_lt, contrapose! hn, rw [with_bot.coe_le_coe, ← nat.div_mul_cancel hpn], exact nat.mul_le_mul_right p hn }, { refl } }, { refine le_degree_of_ne_zero _, rw [coeff_expand_mul hp, ← leading_coeff], exact mt leading_coeff_eq_zero.1 hf } end end comm_semiring section comm_ring variables {R : Type u} [comm_ring R] lemma separable.mul {f g : polynomial R} (hf : f.separable) (hg : g.separable) (h : is_coprime f g) : (f * g).separable := by { rw [separable_def, derivative_mul], exact ((hf.mul_right h).add_mul_left_right _).mul_left ((h.symm.mul_right hg).mul_add_right_right _) } end comm_ring section integral_domain variables (R : Type u) [integral_domain R] theorem is_local_ring_hom_expand {p : ℕ} (hp : 0 < p) : is_local_ring_hom (↑(expand R p) : polynomial R →+* polynomial R) := begin refine ⟨λ f hf1, _⟩, rw ← coe_fn_coe_base at hf1, have hf2 := eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf1), rw [coeff_expand hp, if_pos (dvd_zero _), p.zero_div] at hf2, rw [hf2, is_unit_C] at hf1, rw expand_eq_C hp at hf2, rwa [hf2, is_unit_C] end end integral_domain section field variables {F : Type u} [field F] theorem separable_iff_derivative_ne_zero {f : polynomial F} (hf : irreducible f) : f.separable ↔ f.derivative ≠ 0 := ⟨λ h1 h2, hf.1 $ is_coprime_zero_right.1 $ h2 ▸ h1, λ h, is_coprime_of_dvd (mt and.right h) $ λ g hg1 hg2 ⟨p, hg3⟩ hg4, let ⟨u, hu⟩ := (hf.2 _ _ hg3).resolve_left hg1 in have f ∣ f.derivative, by { conv_lhs { rw [hg3, ← hu] }, rwa mul_unit_dvd_iff }, not_lt_of_le (nat_degree_le_of_dvd this h) $ nat_degree_derivative_lt h⟩ section char_p variables (p : ℕ) [hp : fact p.prime] include hp /-- The opposite of `expand`: sends `∑ aₙ xⁿᵖ` to `∑ aₙ xⁿ`. -/ noncomputable def contract (f : polynomial F) : polynomial F := ⟨@finset.preimage ℕ ℕ (*p) f.support $ λ _ _ _ _, (nat.mul_left_inj hp.pos).1, λ n, f.coeff (n * p), λ n, by { rw [finset.mem_preimage, finsupp.mem_support_iff], refl }⟩ theorem coeff_contract (f : polynomial F) (n : ℕ) : (contract p f).coeff n = f.coeff (n * p) := rfl theorem of_irreducible_expand {f : polynomial F} (hf : irreducible (expand F p f)) : irreducible f := @@of_irreducible_map _ _ _ (is_local_ring_hom_expand F hp.pos) hf theorem of_irreducible_expand_pow {f : polynomial F} {n : ℕ} : irreducible (expand F (p ^ n) f) → irreducible f := nat.rec_on n (λ hf, by rwa [nat.pow_zero, expand_one] at hf) $ λ n ih hf, ih $ of_irreducible_expand p $ by rwa [expand_expand, mul_comm] variables [HF : char_p F p] include HF theorem expand_contract {f : polynomial F} (hf : f.derivative = 0) : expand F p (contract p f) = f := begin ext n, rw [coeff_expand hp.pos, coeff_contract], split_ifs with h, { rw nat.div_mul_cancel h }, { cases n, { exact absurd (dvd_zero p) h }, have := coeff_derivative f n, rw [hf, coeff_zero, zero_eq_mul] at this, cases this, { rw this }, rw [← nat.cast_succ, char_p.cast_eq_zero_iff F p] at this, exact absurd this h } end theorem separable_or {f : polynomial F} (hf : irreducible f) : f.separable ∨ ¬f.separable ∧ ∃ g : polynomial F, irreducible g ∧ expand F p g = f := if H : f.derivative = 0 then or.inr ⟨by rw [separable_iff_derivative_ne_zero hf, not_not, H], contract p f, by haveI := is_local_ring_hom_expand F hp.pos; exact of_irreducible_map ↑(expand F p) (by rwa ← expand_contract p H at hf), expand_contract p H⟩ else or.inl $ (separable_iff_derivative_ne_zero hf).2 H theorem exists_separable_of_irreducible {f : polynomial F} (hf : irreducible f) (hf0 : f ≠ 0) : ∃ (n : ℕ) (g : polynomial F), g.separable ∧ expand F (p ^ n) g = f := begin generalize hn : f.nat_degree = N, unfreezingI { revert f }, apply nat.strong_induction_on N, intros N ih f hf hf0 hn, rcases separable_or p hf with h | ⟨h1, g, hg, hgf⟩, { refine ⟨0, f, h, _⟩, rw [nat.pow_zero, expand_one] }, { cases N with N, { rw [nat_degree_eq_zero_iff_degree_le_zero, degree_le_zero_iff] at hn, rw [hn, separable_C, is_unit_iff_ne_zero, not_not] at h1, rw [h1, C_0] at hn, exact absurd hn hf0 }, have hg1 : g.nat_degree * p = N.succ, { rwa [← nat_degree_expand, hgf] }, have hg2 : g.nat_degree ≠ 0, { intro this, rw [this, zero_mul] at hg1, cases hg1 }, have hg3 : g.nat_degree < N.succ, { rw [← mul_one g.nat_degree, ← hg1], exact nat.mul_lt_mul_of_pos_left hp.one_lt (nat.pos_of_ne_zero hg2) }, have hg4 : g ≠ 0, { rintro rfl, exact hg2 nat_degree_zero }, rcases ih _ hg3 hg hg4 rfl with ⟨n, g, hg5, rfl⟩, refine ⟨n+1, g, hg5, _⟩, rw [← hgf, expand_expand, nat.pow_succ, mul_comm] } end theorem is_unit_or_eq_zero_of_separable_expand {f : polynomial F} (n : ℕ) (hf : (expand F (p ^ n) f).separable) : is_unit f ∨ n = 0 := begin rw classical.or_iff_not_imp_right, intro hn, have hf2 : (expand F (p ^ n) f).derivative = 0, { by rw [derivative_expand, nat.cast_pow, char_p.cast_eq_zero, zero_pow (nat.pos_of_ne_zero hn), zero_mul, mul_zero] }, rw [separable_def, hf2, is_coprime_zero_right, is_unit_iff] at hf, rcases hf with ⟨r, hr, hrf⟩, rw [eq_comm, expand_eq_C (nat.pow_pos hp.pos _)] at hrf, rwa [hrf, is_unit_C] end theorem unique_separable_of_irreducible {f : polynomial F} (hf : irreducible f) (hf0 : f ≠ 0) (n₁ : ℕ) (g₁ : polynomial F) (hg₁ : g₁.separable) (hgf₁ : expand F (p ^ n₁) g₁ = f) (n₂ : ℕ) (g₂ : polynomial F) (hg₂ : g₂.separable) (hgf₂ : expand F (p ^ n₂) g₂ = f) : n₁ = n₂ ∧ g₁ = g₂ := begin revert g₁ g₂, wlog hn : n₁ ≤ n₂ := le_total n₁ n₂ using [n₁ n₂, n₂ n₁] tactic.skip, unfreezingI { intros, rw le_iff_exists_add at hn, rcases hn with ⟨k, rfl⟩, rw [← hgf₁, nat.pow_add, expand_mul, expand_inj (nat.pow_pos hp.pos n₁)] at hgf₂, subst hgf₂, subst hgf₁, rcases is_unit_or_eq_zero_of_separable_expand p k hg₁ with h | rfl, { rw is_unit_iff at h, rcases h with ⟨r, hr, rfl⟩, simp_rw expand_C at hf, exact absurd (is_unit_C.2 hr) hf.1 }, { rw [add_zero, nat.pow_zero, expand_one], split; refl } }, exact λ g₁ g₂ hg₁ hgf₁ hg₂ hgf₂, let ⟨hn, hg⟩ := this g₂ g₁ hg₂ hgf₂ hg₁ hgf₁ in ⟨hn.symm, hg.symm⟩ end end char_p end field end polynomial open polynomial theorem irreducible.separable {F : Type u} [field F] [char_zero F] {f : polynomial F} (hf : irreducible f) (hf0 : f ≠ 0) : f.separable := begin rw [separable_iff_derivative_ne_zero hf, ne, ← degree_eq_bot, degree_derivative_eq], rintro ⟨⟩, rw [nat.pos_iff_ne_zero, ne, nat_degree_eq_zero_iff_degree_le_zero, degree_le_zero_iff], refine λ hf1, hf.1 _, rw [hf1, is_unit_C, is_unit_iff_ne_zero], intro hf2, rw [hf2, C_0] at hf1, exact absurd hf1 hf0 end
91b3a61b40a7a7a976dd66125d9feb1fccef1ecc
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/data/sym.lean
88fd430b07addae4ed7abe14ae64d002d3e6f19d
[ "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
2,063
lean
/- Copyright (c) 2020 Kyle Miller All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Kyle Miller. -/ import data.multiset.basic import data.vector import tactic.tidy /-! # Symmetric powers This file defines symmetric powers of a type. The nth symmetric power consists of homogeneous n-tuples modulo permutations by the symmetric group. The special case of 2-tuples is called the symmetric square, which is addressed in more detail in `data.sym2`. TODO: This was created as supporting material for `data.sym2`; it needs a fleshed-out interface. ## Tags symmetric powers -/ /-- The nth symmetric power is n-tuples up to permutation. We define it as a subtype of `multiset` since these are well developed in the library. We also give a definition `sym.sym'` in terms of vectors, and we show these are equivalent in `sym.sym_equiv_sym'`. -/ def sym (α : Type*) (n : ℕ) := {s : multiset α // s.card = n} /-- This is the `list.perm` setoid lifted to `vector`. -/ def vector.perm.is_setoid (α : Type*) (n : ℕ) : setoid (vector α n) := { r := λ a b, list.perm a.1 b.1, iseqv := by { rcases list.perm.eqv α with ⟨hr, hs, ht⟩, tidy, } } local attribute [instance] vector.perm.is_setoid namespace sym /-- Another definition of the nth symmetric power, using vectors modulo permutations. (See `sym`.) -/ def sym' (α : Type*) (n : ℕ) := quotient (vector.perm.is_setoid α n) /-- Multisets of cardinality n are equivalent to length-n vectors up to permutations. -/ def sym_equiv_sym' (α : Type*) (n : ℕ) : sym α n ≃ sym' α n := equiv.subtype_quotient_equiv_quotient_subtype _ _ (λ _, by refl) (λ _ _, by refl) section inhabited -- Instances to make the linter happy variables (α : Type*) instance inhabited_sym [inhabited α] (n : ℕ) : inhabited (sym α n) := ⟨⟨multiset.repeat (default α) n, multiset.card_repeat _ _⟩⟩ instance inhabited_sym' [inhabited α] (n : ℕ) : inhabited (sym' α n) := ⟨quotient.mk' (vector.repeat (default α) n)⟩ end inhabited end sym
2b10a73b5d4f1a3469aef2819be00f03cb83386b
94e33a31faa76775069b071adea97e86e218a8ee
/src/algebra/group_power/basic.lean
14fbb60c631cc82bc82845bf5aed3d2ac2539776
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
11,647
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis -/ import algebra.divisibility import algebra.group.commute import data.nat.basic /-! # Power operations on monoids and groups The power operation on monoids and groups. We separate this from group, because it depends on `ℕ`, which in turn depends on other parts of algebra. This module contains lemmas about `a ^ n` and `n • a`, where `n : ℕ` or `n : ℤ`. Further lemmas can be found in `algebra.group_power.lemmas`. The analogous results for groups with zero can be found in `algebra.group_with_zero.power`. ## Notation - `a ^ n` is used as notation for `has_pow.pow a n`; in this file `n : ℕ` or `n : ℤ`. - `n • a` is used as notation for `has_smul.smul n a`; in this file `n : ℕ` or `n : ℤ`. ## Implementation details We adopt the convention that `0^0 = 1`. -/ universes u v w x y z u₁ u₂ variables {α : Type*} {M : Type u} {N : Type v} {G : Type w} {H : Type x} {A : Type y} {B : Type z} {R : Type u₁} {S : Type u₂} /-! ### Commutativity First we prove some facts about `semiconj_by` and `commute`. They do not require any theory about `pow` and/or `nsmul` and will be useful later in this file. -/ section has_pow variables [has_pow M ℕ] @[simp] lemma pow_ite (P : Prop) [decidable P] (a : M) (b c : ℕ) : a ^ (if P then b else c) = if P then a ^ b else a ^ c := by split_ifs; refl @[simp] lemma ite_pow (P : Prop) [decidable P] (a b : M) (c : ℕ) : (if P then a else b) ^ c = if P then a ^ c else b ^ c := by split_ifs; refl end has_pow section monoid variables [monoid M] [monoid N] [add_monoid A] [add_monoid B] @[simp, to_additive one_nsmul] theorem pow_one (a : M) : a^1 = a := by rw [pow_succ, pow_zero, mul_one] /-- Note that most of the lemmas about powers of two refer to it as `sq`. -/ @[to_additive two_nsmul, nolint to_additive_doc] theorem pow_two (a : M) : a^2 = a * a := by rw [pow_succ, pow_one] alias pow_two ← sq @[to_additive] theorem pow_mul_comm' (a : M) (n : ℕ) : a^n * a = a * a^n := commute.pow_self a n @[to_additive add_nsmul] theorem pow_add (a : M) (m n : ℕ) : a^(m + n) = a^m * a^n := by induction n with n ih; [rw [nat.add_zero, pow_zero, mul_one], rw [pow_succ', ← mul_assoc, ← ih, ← pow_succ', nat.add_assoc]] @[simp] lemma pow_boole (P : Prop) [decidable P] (a : M) : a ^ (if P then 1 else 0) = if P then a else 1 := by simp -- the attributes are intentionally out of order. `smul_zero` proves `nsmul_zero`. @[to_additive nsmul_zero, simp] theorem one_pow (n : ℕ) : (1 : M)^n = 1 := by induction n with n ih; [exact pow_zero _, rw [pow_succ, ih, one_mul]] @[to_additive mul_nsmul'] theorem pow_mul (a : M) (m n : ℕ) : a^(m * n) = (a^m)^n := begin induction n with n ih, { rw [nat.mul_zero, pow_zero, pow_zero] }, { rw [nat.mul_succ, pow_add, pow_succ', ih] } end @[to_additive nsmul_left_comm] lemma pow_right_comm (a : M) (m n : ℕ) : (a^m)^n = (a^n)^m := by rw [←pow_mul, nat.mul_comm, pow_mul] @[to_additive mul_nsmul] theorem pow_mul' (a : M) (m n : ℕ) : a^(m * n) = (a^n)^m := by rw [nat.mul_comm, pow_mul] @[to_additive nsmul_add_sub_nsmul] theorem pow_mul_pow_sub (a : M) {m n : ℕ} (h : m ≤ n) : a ^ m * a ^ (n - m) = a ^ n := by rw [←pow_add, nat.add_comm, tsub_add_cancel_of_le h] @[to_additive sub_nsmul_nsmul_add] theorem pow_sub_mul_pow (a : M) {m n : ℕ} (h : m ≤ n) : a ^ (n - m) * a ^ m = a ^ n := by rw [←pow_add, tsub_add_cancel_of_le h] /-- If `x ^ n = 1`, then `x ^ m` is the same as `x ^ (m % n)` -/ @[to_additive nsmul_eq_mod_nsmul "If `n • x = 0`, then `m • x` is the same as `(m % n) • x`"] lemma pow_eq_pow_mod {M : Type*} [monoid M] {x : M} (m : ℕ) {n : ℕ} (h : x ^ n = 1) : x ^ m = x ^ (m % n) := begin have t := congr_arg (λ a, x ^ a) (nat.div_add_mod m n).symm, dsimp at t, rw [t, pow_add, pow_mul, h, one_pow, one_mul], end @[to_additive bit0_nsmul] theorem pow_bit0 (a : M) (n : ℕ) : a ^ bit0 n = a^n * a^n := pow_add _ _ _ @[to_additive bit1_nsmul] theorem pow_bit1 (a : M) (n : ℕ) : a ^ bit1 n = a^n * a^n * a := by rw [bit1, pow_succ', pow_bit0] @[to_additive] theorem pow_mul_comm (a : M) (m n : ℕ) : a^m * a^n = a^n * a^m := commute.pow_pow_self a m n @[to_additive] lemma commute.mul_pow {a b : M} (h : commute a b) (n : ℕ) : (a * b) ^ n = a ^ n * b ^ n := nat.rec_on n (by simp only [pow_zero, one_mul]) $ λ n ihn, by simp only [pow_succ, ihn, ← mul_assoc, (h.pow_left n).right_comm] @[to_additive bit0_nsmul'] theorem pow_bit0' (a : M) (n : ℕ) : a ^ bit0 n = (a * a) ^ n := by rw [pow_bit0, (commute.refl a).mul_pow] @[to_additive bit1_nsmul'] theorem pow_bit1' (a : M) (n : ℕ) : a ^ bit1 n = (a * a) ^ n * a := by rw [bit1, pow_succ', pow_bit0'] lemma dvd_pow {x y : M} (hxy : x ∣ y) : ∀ {n : ℕ} (hn : n ≠ 0), x ∣ y^n | 0 hn := (hn rfl).elim | (n + 1) hn := by { rw pow_succ, exact hxy.mul_right _ } alias dvd_pow ← has_dvd.dvd.pow lemma dvd_pow_self (a : M) {n : ℕ} (hn : n ≠ 0) : a ∣ a^n := dvd_rfl.pow hn end monoid /-! ### Commutative (additive) monoid -/ section comm_monoid variables [comm_monoid M] [add_comm_monoid A] @[to_additive nsmul_add] theorem mul_pow (a b : M) (n : ℕ) : (a * b)^n = a^n * b^n := (commute.all a b).mul_pow n /-- The `n`th power map on a commutative monoid for a natural `n`, considered as a morphism of monoids. -/ @[to_additive "Multiplication by a natural `n` on a commutative additive monoid, considered as a morphism of additive monoids.", simps] def pow_monoid_hom (n : ℕ) : M →* M := { to_fun := (^ n), map_one' := one_pow _, map_mul' := λ a b, mul_pow a b n } -- the below line causes the linter to complain :-/ -- attribute [simps] pow_monoid_hom nsmul_add_monoid_hom end comm_monoid section div_inv_monoid variable [div_inv_monoid G] open int @[simp, to_additive one_zsmul] theorem zpow_one (a : G) : a ^ (1:ℤ) = a := by { convert pow_one a using 1, exact zpow_coe_nat a 1 } @[to_additive two_zsmul] theorem zpow_two (a : G) : a ^ (2 : ℤ) = a * a := by { convert pow_two a using 1, exact zpow_coe_nat a 2 } @[to_additive neg_one_zsmul] theorem zpow_neg_one (x : G) : x ^ (-1:ℤ) = x⁻¹ := (zpow_neg_succ_of_nat x 0).trans $ congr_arg has_inv.inv (pow_one x) @[to_additive] theorem zpow_neg_coe_of_pos (a : G) : ∀ {n : ℕ}, 0 < n → a ^ -(n:ℤ) = (a ^ n)⁻¹ | (n+1) _ := zpow_neg_succ_of_nat _ _ end div_inv_monoid section division_monoid variables [division_monoid α] {a b : α} @[simp, to_additive] lemma inv_pow (a : α) : ∀ n : ℕ, (a⁻¹) ^ n = (a ^ n)⁻¹ | 0 := by rw [pow_zero, pow_zero, inv_one] | (n + 1) := by rw [pow_succ', pow_succ, inv_pow, mul_inv_rev] -- the attributes are intentionally out of order. `smul_zero` proves `zsmul_zero`. @[to_additive zsmul_zero, simp] lemma one_zpow : ∀ (n : ℤ), (1 : α) ^ n = 1 | (n : ℕ) := by rw [zpow_coe_nat, one_pow] | -[1+ n] := by rw [zpow_neg_succ_of_nat, one_pow, inv_one] @[simp, to_additive neg_zsmul] lemma zpow_neg (a : α) : ∀ (n : ℤ), a ^ -n = (a ^ n)⁻¹ | (n+1:ℕ) := div_inv_monoid.zpow_neg' _ _ | 0 := by { change a ^ (0 : ℤ) = (a ^ (0 : ℤ))⁻¹, simp } | -[1+ n] := by { rw [zpow_neg_succ_of_nat, inv_inv, ← zpow_coe_nat], refl } @[to_additive neg_one_zsmul_add] lemma mul_zpow_neg_one (a b : α) : (a * b) ^ (-1 : ℤ) = b ^ (-1 : ℤ) * a ^ (-1 : ℤ) := by simp_rw [zpow_neg_one, mul_inv_rev] @[to_additive zsmul_neg] lemma inv_zpow (a : α) : ∀ n : ℤ, a⁻¹ ^ n = (a ^ n)⁻¹ | (n : ℕ) := by rw [zpow_coe_nat, zpow_coe_nat, inv_pow] | -[1+ n] := by rw [zpow_neg_succ_of_nat, zpow_neg_succ_of_nat, inv_pow] @[simp, to_additive zsmul_neg'] lemma inv_zpow' (a : α) (n : ℤ) : a⁻¹ ^ n = a ^ (-n) := by rw [inv_zpow, zpow_neg] @[to_additive nsmul_zero_sub] lemma one_div_pow (a : α) (n : ℕ) : (1 / a) ^ n = 1 / a ^ n := by simp_rw [one_div, inv_pow] @[to_additive zsmul_zero_sub] lemma one_div_zpow (a : α) (n : ℤ) : (1 / a) ^ n = 1 / a ^ n := by simp_rw [one_div, inv_zpow] @[to_additive add_commute.zsmul_add] protected lemma commute.mul_zpow (h : commute a b) : ∀ (i : ℤ), (a * b) ^ i = a ^ i * b ^ i | (n : ℕ) := by simp [h.mul_pow n] | -[1+n] := by simp [h.mul_pow, (h.pow_pow _ _).eq, mul_inv_rev] end division_monoid section division_comm_monoid variables [division_comm_monoid α] @[to_additive zsmul_add] lemma mul_zpow (a b : α) : ∀ n : ℤ, (a * b) ^ n = a ^ n * b ^ n := (commute.all a b).mul_zpow @[simp, to_additive nsmul_sub] lemma div_pow (a b : α) (n : ℕ) : (a / b) ^ n = a ^ n / b ^ n := by simp only [div_eq_mul_inv, mul_pow, inv_pow] @[simp, to_additive zsmul_sub] lemma div_zpow (a b : α) (n : ℤ) : (a / b) ^ n = a ^ n / b ^ n := by simp only [div_eq_mul_inv, mul_zpow, inv_zpow] /-- The `n`-th power map (for an integer `n`) on a commutative group, considered as a group homomorphism. -/ @[to_additive "Multiplication by an integer `n` on a commutative additive group, considered as an additive group homomorphism.", simps] def zpow_group_hom (n : ℤ) : α →* α := { to_fun := (^ n), map_one' := one_zpow n, map_mul' := λ a b, mul_zpow a b n } end division_comm_monoid section group variables [group G] [group H] [add_group A] [add_group B] @[to_additive sub_nsmul] lemma pow_sub (a : G) {m n : ℕ} (h : n ≤ m) : a^(m - n) = a^m * (a^n)⁻¹ := eq_mul_inv_of_mul_eq $ by rw [←pow_add, tsub_add_cancel_of_le h] @[to_additive] lemma pow_inv_comm (a : G) (m n : ℕ) : (a⁻¹)^m * a^n = a^n * (a⁻¹)^m := (commute.refl a).inv_left.pow_pow _ _ @[to_additive sub_nsmul_neg] lemma inv_pow_sub (a : G) {m n : ℕ} (h : n ≤ m) : a⁻¹^(m - n) = (a^m)⁻¹ * a^n := by rw [pow_sub a⁻¹ h, inv_pow, inv_pow, inv_inv] end group lemma pow_dvd_pow [monoid R] (a : R) {m n : ℕ} (h : m ≤ n) : a ^ m ∣ a ^ n := ⟨a ^ (n - m), by rw [← pow_add, nat.add_comm, tsub_add_cancel_of_le h]⟩ theorem pow_dvd_pow_of_dvd [comm_monoid R] {a b : R} (h : a ∣ b) : ∀ n : ℕ, a ^ n ∣ b ^ n | 0 := by rw [pow_zero, pow_zero] | (n+1) := by { rw [pow_succ, pow_succ], exact mul_dvd_mul h (pow_dvd_pow_of_dvd n) } lemma of_add_nsmul [add_monoid A] (x : A) (n : ℕ) : multiplicative.of_add (n • x) = (multiplicative.of_add x)^n := rfl lemma of_add_zsmul [sub_neg_monoid A] (x : A) (n : ℤ) : multiplicative.of_add (n • x) = (multiplicative.of_add x)^n := rfl lemma of_mul_pow [monoid A] (x : A) (n : ℕ) : additive.of_mul (x ^ n) = n • (additive.of_mul x) := rfl lemma of_mul_zpow [div_inv_monoid G] (x : G) (n : ℤ) : additive.of_mul (x ^ n) = n • additive.of_mul x := rfl @[simp, to_additive] lemma semiconj_by.zpow_right [group G] {a x y : G} (h : semiconj_by a x y) : ∀ m : ℤ, semiconj_by a (x^m) (y^m) | (n : ℕ) := by simp [zpow_coe_nat, h.pow_right n] | -[1+n] := by simp [(h.pow_right n.succ).inv_right] namespace commute variables [group G] {a b : G} @[simp, to_additive] lemma zpow_right (h : commute a b) (m : ℤ) : commute a (b^m) := h.zpow_right m @[simp, to_additive] lemma zpow_left (h : commute a b) (m : ℤ) : commute (a^m) b := (h.symm.zpow_right m).symm @[to_additive] lemma zpow_zpow (h : commute a b) (m n : ℤ) : commute (a^m) (b^n) := (h.zpow_left m).zpow_right n variables (a) (m n : ℤ) @[simp, to_additive] lemma self_zpow : commute a (a ^ n) := (commute.refl a).zpow_right n @[simp, to_additive] lemma zpow_self : commute (a ^ n) a := (commute.refl a).zpow_left n @[simp, to_additive] lemma zpow_zpow_self : commute (a ^ m) (a ^ n) := (commute.refl a).zpow_zpow m n end commute
c8710e5a1ddf3c80d9b7e4c82d08c8ee6e17dff6
82e44445c70db0f03e30d7be725775f122d72f3e
/src/algebra/module/pi.lean
aadeb77b47ef9b333859edfe521eb29e7b7bd9a1
[ "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
5,528
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot -/ import algebra.module.basic import algebra.ring.pi /-! # Pi instances for module and multiplicative actions This file defines instances for module, mul_action and related structures on Pi Types -/ namespace pi universes u v w variable {I : Type u} -- The indexing type variable {f : I → Type v} -- The family of types already equipped with instances variables (x y : Π i, f i) (i : I) instance has_scalar {α : Type*} [Π i, has_scalar α $ f i] : has_scalar α (Π i : I, f i) := ⟨λ s x, λ i, s • (x i)⟩ lemma smul_def {α : Type*} [Π i, has_scalar α $ f i] (s : α) : s • x = λ i, s • x i := rfl @[simp] lemma smul_apply {α : Type*} [Π i, has_scalar α $ f i] (s : α) : (s • x) i = s • x i := rfl instance has_scalar' {g : I → Type*} [Π i, has_scalar (f i) (g i)] : has_scalar (Π i, f i) (Π i : I, g i) := ⟨λ s x, λ i, (s i) • (x i)⟩ @[simp] lemma smul_apply' {g : I → Type*} [∀ i, has_scalar (f i) (g i)] (s : Π i, f i) (x : Π i, g i) : (s • x) i = s i • x i := rfl instance is_scalar_tower {α β : Type*} [has_scalar α β] [Π i, has_scalar β $ f i] [Π i, has_scalar α $ f i] [Π i, is_scalar_tower α β (f i)] : is_scalar_tower α β (Π i : I, f i) := ⟨λ x y z, funext $ λ i, smul_assoc x y (z i)⟩ instance is_scalar_tower' {g : I → Type*} {α : Type*} [Π i, has_scalar α $ f i] [Π i, has_scalar (f i) (g i)] [Π i, has_scalar α $ g i] [Π i, is_scalar_tower α (f i) (g i)] : is_scalar_tower α (Π i : I, f i) (Π i : I, g i) := ⟨λ x y z, funext $ λ i, smul_assoc x (y i) (z i)⟩ instance is_scalar_tower'' {g : I → Type*} {h : I → Type*} [Π i, has_scalar (f i) (g i)] [Π i, has_scalar (g i) (h i)] [Π i, has_scalar (f i) (h i)] [Π i, is_scalar_tower (f i) (g i) (h i)] : is_scalar_tower (Π i, f i) (Π i, g i) (Π i, h i) := ⟨λ x y z, funext $ λ i, smul_assoc (x i) (y i) (z i)⟩ instance smul_comm_class {α β : Type*} [Π i, has_scalar α $ f i] [Π i, has_scalar β $ f i] [∀ i, smul_comm_class α β (f i)] : smul_comm_class α β (Π i : I, f i) := ⟨λ x y z, funext $ λ i, smul_comm x y (z i)⟩ instance smul_comm_class' {g : I → Type*} {α : Type*} [Π i, has_scalar α $ g i] [Π i, has_scalar (f i) (g i)] [∀ i, smul_comm_class α (f i) (g i)] : smul_comm_class α (Π i : I, f i) (Π i : I, g i) := ⟨λ x y z, funext $ λ i, smul_comm x (y i) (z i)⟩ instance smul_comm_class'' {g : I → Type*} {h : I → Type*} [Π i, has_scalar (g i) (h i)] [Π i, has_scalar (f i) (h i)] [∀ i, smul_comm_class (f i) (g i) (h i)] : smul_comm_class (Π i, f i) (Π i, g i) (Π i, h i) := ⟨λ x y z, funext $ λ i, smul_comm (x i) (y i) (z i)⟩ instance mul_action (α) {m : monoid α} [Π i, mul_action α $ f i] : @mul_action α (Π i : I, f i) m := { smul := (•), mul_smul := λ r s f, funext $ λ i, mul_smul _ _ _, one_smul := λ f, funext $ λ i, one_smul α _ } instance mul_action' {g : I → Type*} {m : Π i, monoid (f i)} [Π i, mul_action (f i) (g i)] : @mul_action (Π i, f i) (Π i : I, g i) (@pi.monoid I f m) := { smul := (•), mul_smul := λ r s f, funext $ λ i, mul_smul _ _ _, one_smul := λ f, funext $ λ i, one_smul _ _ } instance distrib_mul_action (α) {m : monoid α} {n : ∀ i, add_monoid $ f i} [∀ i, distrib_mul_action α $ f i] : @distrib_mul_action α (Π i : I, f i) m (@pi.add_monoid I f n) := { smul_zero := λ c, funext $ λ i, smul_zero _, smul_add := λ c f g, funext $ λ i, smul_add _ _ _, ..pi.mul_action _ } instance distrib_mul_action' {g : I → Type*} {m : Π i, monoid (f i)} {n : Π i, add_monoid $ g i} [Π i, distrib_mul_action (f i) (g i)] : @distrib_mul_action (Π i, f i) (Π i : I, g i) (@pi.monoid I f m) (@pi.add_monoid I g n) := { smul_add := by { intros, ext x, apply smul_add }, smul_zero := by { intros, ext x, apply smul_zero } } lemma single_smul {α} [monoid α] [Π i, add_monoid $ f i] [Π i, distrib_mul_action α $ f i] [decidable_eq I] (i : I) (r : α) (x : f i) : single i (r • x) = r • single i x := single_op (λ i : I, ((•) r : f i → f i)) (λ j, smul_zero _) _ _ lemma single_smul' {g : I → Type*} [Π i, monoid_with_zero (f i)] [Π i, add_monoid (g i)] [Π i, distrib_mul_action (f i) (g i)] [decidable_eq I] (i : I) (r : f i) (x : g i) : single i (r • x) = single i r • single i x := single_op₂ (λ i : I, ((•) : f i → g i → g i)) (λ j, smul_zero _) _ _ _ variables (I f) instance module (α) {r : semiring α} {m : ∀ i, add_comm_monoid $ f i} [∀ i, module α $ f i] : @module α (Π i : I, f i) r (@pi.add_comm_monoid I f m) := { add_smul := λ c f g, funext $ λ i, add_smul _ _ _, zero_smul := λ f, funext $ λ i, zero_smul α _, ..pi.distrib_mul_action _ } variables {I f} instance module' {g : I → Type*} {r : Π i, semiring (f i)} {m : Π i, add_comm_monoid (g i)} [Π i, module (f i) (g i)] : module (Π i, f i) (Π i, g i) := { add_smul := by { intros, ext1, apply add_smul }, zero_smul := by { intros, ext1, apply zero_smul } } instance (α) {r : semiring α} {m : Π i, add_comm_monoid $ f i} [Π i, module α $ f i] [∀ i, no_zero_smul_divisors α $ f i] : no_zero_smul_divisors α (Π i : I, f i) := ⟨λ c x h, or_iff_not_imp_left.mpr (λ hc, funext (λ i, (smul_eq_zero.mp (congr_fun h i)).resolve_left hc))⟩ end pi
4c38ab7a2d38f95b88fa8f768377dde88f65189a
94637389e03c919023691dcd05bd4411b1034aa5
/src/inClassNotes/predicate_logic/impl.lean
67ced4963b2f98cbcaa9717ba961caffebf5f680
[]
no_license
kevinsullivan/complogic-s21
7c4eef2105abad899e46502270d9829d913e8afc
99039501b770248c8ceb39890be5dfe129dc1082
refs/heads/master
1,682,985,669,944
1,621,126,241,000
1,621,126,241,000
335,706,272
0
38
null
1,618,325,669,000
1,612,374,118,000
Lean
UTF-8
Lean
false
false
1,605
lean
/- If P and Q are propositions, then P → Q is a proposition, as well. We just such an implication to be true if whenever P is true Q must be true as well. To prove P → Q, we thus *assume* that P is true (and in constructive logic this means we assume we have a proof of it, p : P), and in the context of this assumption, we show that Q must be true, in the sense that we can produce evidence (q : Q) that this is the case. This is a long way of saying that to prove P → Q, we assume we have a proof of P and in this context we must produce a proof of Q. In the constructive logic of Lean, this means we prove P → Q by showing that there is a function of type P to Q! Of course a function of this type is really a function of type ∀ (p : P), Q, which is notation for Π (p : P), Q which is just a non-dependent function type, P → Q. It all makes sense! -/ lemma and_commutes' : ∀ {P Q : Prop}, P ∧ Q → Q ∧ P := λ P Q, λ h, and.intro (h.right) (h.left) /- This is the introduction rule for →. Assume you have a proof of the antcedent (P ∧ Q in this case) and show that in that context there is a proof of the conclusion (Q ∧ P). -/ /- Elimination -/ axioms (Person : Type) (fromCville : Person → Prop) axioms (Kevin Liu : Person) (kfc : fromCville Kevin) (lfc : fromCville Liu) -- let's construct a proof of fromCville Kevin ∧ fromCville Liu (P ∧ Q) theorem bfc : fromCville Kevin ∧ fromCville Liu := and.intro kfc lfc #check bfc #reduce bfc -- now we can *apply* and_commutes' to derive a proof of (Q ∧ P) #check and_commutes' bfc #reduce and_commutes' bfc
720cb7eeb4f33a16a2386fbae395757c779d1137
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/periodic.lean
1ea42572a7c38293542c900538660fd2abfb6029
[ "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
20,231
lean
/- Copyright (c) 2021 Benjamin Davidson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Benjamin Davidson -/ import algebra.field.opposite import algebra.module.basic import algebra.order.archimedean import data.int.parity import group_theory.coset /-! # Periodicity In this file we define and then prove facts about periodic and antiperiodic functions. ## Main definitions * `function.periodic`: A function `f` is *periodic* if `∀ x, f (x + c) = f x`. `f` is referred to as periodic with period `c` or `c`-periodic. * `function.antiperiodic`: A function `f` is *antiperiodic* if `∀ x, f (x + c) = -f x`. `f` is referred to as antiperiodic with antiperiod `c` or `c`-antiperiodic. Note that any `c`-antiperiodic function will necessarily also be `2*c`-periodic. ## Tags period, periodic, periodicity, antiperiodic -/ variables {α β γ : Type*} {f g : α → β} {c c₁ c₂ x : α} open_locale big_operators namespace function /-! ### Periodicity -/ /-- A function `f` is said to be `periodic` with period `c` if for all `x`, `f (x + c) = f x`. -/ @[simp] def periodic [has_add α] (f : α → β) (c : α) : Prop := ∀ x : α, f (x + c) = f x lemma periodic.funext [has_add α] (h : periodic f c) : (λ x, f (x + c)) = f := funext h lemma periodic.comp [has_add α] (h : periodic f c) (g : β → γ) : periodic (g ∘ f) c := by simp * at * lemma periodic.comp_add_hom [has_add α] [has_add γ] (h : periodic f c) (g : add_hom γ α) (g_inv : α → γ) (hg : right_inverse g_inv g) : periodic (f ∘ g) (g_inv c) := λ x, by simp only [hg c, h (g x), add_hom.map_add, comp_app] @[to_additive] lemma periodic.mul [has_add α] [has_mul β] (hf : periodic f c) (hg : periodic g c) : periodic (f * g) c := by simp * at * @[to_additive] lemma periodic.div [has_add α] [has_div β] (hf : periodic f c) (hg : periodic g c) : periodic (f / g) c := by simp * at * @[to_additive] lemma _root_.list.periodic_prod [has_add α] [comm_monoid β] (l : list (α → β)) (hl : ∀ f ∈ l, periodic f c) : periodic l.prod c := begin induction l with g l ih hl, { simp, }, { simp only [list.mem_cons_iff, forall_eq_or_imp] at hl, obtain ⟨hg, hl⟩ := hl, simp only [list.prod_cons], exact hg.mul (ih hl), }, end @[to_additive] lemma _root_.multiset.periodic_prod [has_add α] [comm_monoid β] (s : multiset (α → β)) (hs : ∀ f ∈ s, periodic f c) : periodic s.prod c := s.prod_to_list ▸ s.to_list.periodic_prod $ λ f hf, hs f $ multiset.mem_to_list.mp hf @[to_additive] lemma _root_.finset.periodic_prod [has_add α] [comm_monoid β] {ι : Type*} {f : ι → α → β} (s : finset ι) (hs : ∀ i ∈ s, periodic (f i) c) : periodic (∏ i in s, f i) c := s.prod_to_list f ▸ (s.to_list.map f).periodic_prod (by simpa [-periodic]) @[to_additive] lemma periodic.smul [has_add α] [has_smul γ β] (h : periodic f c) (a : γ) : periodic (a • f) c := by simp * at * lemma periodic.const_smul [add_monoid α] [group γ] [distrib_mul_action γ α] (h : periodic f c) (a : γ) : periodic (λ x, f (a • x)) (a⁻¹ • c) := λ x, by simpa only [smul_add, smul_inv_smul] using h (a • x) lemma periodic.const_smul₀ [add_comm_monoid α] [division_ring γ] [module γ α] (h : periodic f c) (a : γ) : periodic (λ x, f (a • x)) (a⁻¹ • c) := begin intro x, by_cases ha : a = 0, { simp only [ha, zero_smul] }, simpa only [smul_add, smul_inv_smul₀ ha] using h (a • x), end lemma periodic.const_mul [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (a * x)) (a⁻¹ * c) := h.const_smul₀ a lemma periodic.const_inv_smul [add_monoid α] [group γ] [distrib_mul_action γ α] (h : periodic f c) (a : γ) : periodic (λ x, f (a⁻¹ • x)) (a • c) := by simpa only [inv_inv] using h.const_smul a⁻¹ lemma periodic.const_inv_smul₀ [add_comm_monoid α] [division_ring γ] [module γ α] (h : periodic f c) (a : γ) : periodic (λ x, f (a⁻¹ • x)) (a • c) := by simpa only [inv_inv] using h.const_smul₀ a⁻¹ lemma periodic.const_inv_mul [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (a⁻¹ * x)) (a * c) := h.const_inv_smul₀ a lemma periodic.mul_const [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (x * a)) (c * a⁻¹) := h.const_smul₀ $ mul_opposite.op a lemma periodic.mul_const' [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (x * a)) (c / a) := by simpa only [div_eq_mul_inv] using h.mul_const a lemma periodic.mul_const_inv [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (x * a⁻¹)) (c * a) := h.const_inv_smul₀ $ mul_opposite.op a lemma periodic.div_const [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (x / a)) (c * a) := by simpa only [div_eq_mul_inv] using h.mul_const_inv a lemma periodic.add_period [add_semigroup α] (h1 : periodic f c₁) (h2 : periodic f c₂) : periodic f (c₁ + c₂) := by simp [*, ← add_assoc] at * lemma periodic.sub_eq [add_group α] (h : periodic f c) (x : α) : f (x - c) = f x := by simpa only [sub_add_cancel] using (h (x - c)).symm lemma periodic.sub_eq' [add_comm_group α] (h : periodic f c) : f (c - x) = f (-x) := by simpa only [sub_eq_neg_add] using h (-x) lemma periodic.neg [add_group α] (h : periodic f c) : periodic f (-c) := by simpa only [sub_eq_add_neg, periodic] using h.sub_eq lemma periodic.sub_period [add_comm_group α] (h1 : periodic f c₁) (h2 : periodic f c₂) : periodic f (c₁ - c₂) := let h := h2.neg in by simp [*, sub_eq_add_neg, add_comm c₁, ← add_assoc] at * lemma periodic.const_add [add_semigroup α] (h : periodic f c) (a : α) : periodic (λ x, f (a + x)) c := λ x, by simpa [add_assoc] using h (a + x) lemma periodic.add_const [add_comm_semigroup α] (h : periodic f c) (a : α) : periodic (λ x, f (x + a)) c := λ x, by simpa [add_assoc x c a, add_comm c, ←add_assoc x a c] using h (x + a) lemma periodic.const_sub [add_comm_group α] (h : periodic f c) (a : α) : periodic (λ x, f (a - x)) c := begin rw [←neg_neg c], refine periodic.neg _, intro x, simpa [sub_add_eq_sub_sub] using h (a - x) end lemma periodic.sub_const [add_comm_group α] (h : periodic f c) (a : α) : periodic (λ x, f (x - a)) c := λ x, by simpa [add_comm x c, add_sub_assoc, add_comm c (x - a)] using h (x - a) lemma periodic.nsmul [add_monoid α] (h : periodic f c) (n : ℕ) : periodic f (n • c) := by induction n; simp [nat.succ_eq_add_one, add_nsmul, ← add_assoc, zero_nsmul, *] at * lemma periodic.nat_mul [semiring α] (h : periodic f c) (n : ℕ) : periodic f (n * c) := by simpa only [nsmul_eq_mul] using h.nsmul n lemma periodic.neg_nsmul [add_group α] (h : periodic f c) (n : ℕ) : periodic f (-(n • c)) := (h.nsmul n).neg lemma periodic.neg_nat_mul [ring α] (h : periodic f c) (n : ℕ) : periodic f (-(n * c)) := (h.nat_mul n).neg lemma periodic.sub_nsmul_eq [add_group α] (h : periodic f c) (n : ℕ) : f (x - n • c) = f x := by simpa only [sub_eq_add_neg] using h.neg_nsmul n x lemma periodic.sub_nat_mul_eq [ring α] (h : periodic f c) (n : ℕ) : f (x - n * c) = f x := by simpa only [nsmul_eq_mul] using h.sub_nsmul_eq n lemma periodic.nsmul_sub_eq [add_comm_group α] (h : periodic f c) (n : ℕ) : f (n • c - x) = f (-x) := by simpa only [sub_eq_neg_add] using h.nsmul n (-x) lemma periodic.nat_mul_sub_eq [ring α] (h : periodic f c) (n : ℕ) : f (n * c - x) = f (-x) := by simpa only [sub_eq_neg_add] using h.nat_mul n (-x) lemma periodic.zsmul [add_group α] (h : periodic f c) (n : ℤ) : periodic f (n • c) := begin cases n, { simpa only [int.of_nat_eq_coe, coe_nat_zsmul] using h.nsmul n }, { simpa only [zsmul_neg_succ_of_nat] using (h.nsmul n.succ).neg }, end lemma periodic.int_mul [ring α] (h : periodic f c) (n : ℤ) : periodic f (n * c) := by simpa only [zsmul_eq_mul] using h.zsmul n lemma periodic.sub_zsmul_eq [add_group α] (h : periodic f c) (n : ℤ) : f (x - n • c) = f x := (h.zsmul n).sub_eq x lemma periodic.sub_int_mul_eq [ring α] (h : periodic f c) (n : ℤ) : f (x - n * c) = f x := (h.int_mul n).sub_eq x lemma periodic.zsmul_sub_eq [add_comm_group α] (h : periodic f c) (n : ℤ) : f (n • c - x) = f (-x) := by simpa only [sub_eq_neg_add] using h.zsmul n (-x) lemma periodic.int_mul_sub_eq [ring α] (h : periodic f c) (n : ℤ) : f (n * c - x) = f (-x) := by simpa only [sub_eq_neg_add] using h.int_mul n (-x) lemma periodic.eq [add_zero_class α] (h : periodic f c) : f c = f 0 := by simpa only [zero_add] using h 0 lemma periodic.neg_eq [add_group α] (h : periodic f c) : f (-c) = f 0 := h.neg.eq lemma periodic.nsmul_eq [add_monoid α] (h : periodic f c) (n : ℕ) : f (n • c) = f 0 := (h.nsmul n).eq lemma periodic.nat_mul_eq [semiring α] (h : periodic f c) (n : ℕ) : f (n * c) = f 0 := (h.nat_mul n).eq lemma periodic.zsmul_eq [add_group α] (h : periodic f c) (n : ℤ) : f (n • c) = f 0 := (h.zsmul n).eq lemma periodic.int_mul_eq [ring α] (h : periodic f c) (n : ℤ) : f (n * c) = f 0 := (h.int_mul n).eq /-- If a function `f` is `periodic` with positive period `c`, then for all `x` there exists some `y ∈ Ico 0 c` such that `f x = f y`. -/ lemma periodic.exists_mem_Ico₀ [linear_ordered_add_comm_group α] [archimedean α] (h : periodic f c) (hc : 0 < c) (x) : ∃ y ∈ set.Ico 0 c, f x = f y := let ⟨n, H, _⟩ := exists_unique_zsmul_near_of_pos' hc x in ⟨x - n • c, H, (h.sub_zsmul_eq n).symm⟩ /-- If a function `f` is `periodic` with positive period `c`, then for all `x` there exists some `y ∈ Ico a (a + c)` such that `f x = f y`. -/ lemma periodic.exists_mem_Ico [linear_ordered_add_comm_group α] [archimedean α] (h : periodic f c) (hc : 0 < c) (x a) : ∃ y ∈ set.Ico a (a + c), f x = f y := let ⟨n, H, _⟩ := exists_unique_add_zsmul_mem_Ico hc x a in ⟨x + n • c, H, (h.zsmul n x).symm⟩ /-- If a function `f` is `periodic` with positive period `c`, then for all `x` there exists some `y ∈ Ioc a (a + c)` such that `f x = f y`. -/ lemma periodic.exists_mem_Ioc [linear_ordered_add_comm_group α] [archimedean α] (h : periodic f c) (hc : 0 < c) (x a) : ∃ y ∈ set.Ioc a (a + c), f x = f y := let ⟨n, H, _⟩ := exists_unique_add_zsmul_mem_Ioc hc x a in ⟨x + n • c, H, (h.zsmul n x).symm⟩ lemma periodic.image_Ioc [linear_ordered_add_comm_group α] [archimedean α] (h : periodic f c) (hc : 0 < c) (a : α) : f '' set.Ioc a (a + c) = set.range f := (set.image_subset_range _ _).antisymm $ set.range_subset_iff.2 $ λ x, let ⟨y, hy, hyx⟩ := h.exists_mem_Ioc hc x a in ⟨y, hy, hyx.symm⟩ lemma periodic_with_period_zero [add_zero_class α] (f : α → β) : periodic f 0 := λ x, by rw add_zero lemma periodic.map_vadd_zmultiples [add_comm_group α] (hf : periodic f c) (a : add_subgroup.zmultiples c) (x : α) : f (a +ᵥ x) = f x := by { rcases a with ⟨_, m, rfl⟩, simp [add_subgroup.vadd_def, add_comm _ x, hf.zsmul m x] } lemma periodic.map_vadd_multiples [add_comm_monoid α] (hf : periodic f c) (a : add_submonoid.multiples c) (x : α) : f (a +ᵥ x) = f x := by { rcases a with ⟨_, m, rfl⟩, simp [add_submonoid.vadd_def, add_comm _ x, hf.nsmul m x] } /-- Lift a periodic function to a function from the quotient group. -/ def periodic.lift [add_group α] (h : periodic f c) (x : α ⧸ add_subgroup.zmultiples c) : β := quotient.lift_on' x f $ λ a b h', (begin rw quotient_add_group.left_rel_apply at h', obtain ⟨k, hk⟩ := h', exact (h.zsmul k _).symm.trans (congr_arg f (add_eq_of_eq_neg_add hk)), end) @[simp] lemma periodic.lift_coe [add_group α] (h : periodic f c) (a : α) : h.lift (a : α ⧸ add_subgroup.zmultiples c) = f a := rfl /-! ### Antiperiodicity -/ /-- A function `f` is said to be `antiperiodic` with antiperiod `c` if for all `x`, `f (x + c) = -f x`. -/ @[simp] def antiperiodic [has_add α] [has_neg β] (f : α → β) (c : α) : Prop := ∀ x : α, f (x + c) = -f x lemma antiperiodic.funext [has_add α] [has_neg β] (h : antiperiodic f c) : (λ x, f (x + c)) = -f := funext h lemma antiperiodic.funext' [has_add α] [has_involutive_neg β] (h : antiperiodic f c) : (λ x, -f (x + c)) = f := (eq_neg_iff_eq_neg.mp h.funext).symm /-- If a function is `antiperiodic` with antiperiod `c`, then it is also `periodic` with period `2 * c`. -/ lemma antiperiodic.periodic [semiring α] [has_involutive_neg β] (h : antiperiodic f c) : periodic f (2 * c) := by simp [two_mul, ← add_assoc, h _] lemma antiperiodic.eq [add_zero_class α] [has_neg β] (h : antiperiodic f c) : f c = -f 0 := by simpa only [zero_add] using h 0 lemma antiperiodic.nat_even_mul_periodic [semiring α] [has_involutive_neg β] (h : antiperiodic f c) (n : ℕ) : periodic f (n * (2 * c)) := h.periodic.nat_mul n lemma antiperiodic.nat_odd_mul_antiperiodic [semiring α] [has_involutive_neg β] (h : antiperiodic f c) (n : ℕ) : antiperiodic f (n * (2 * c) + c) := λ x, by rw [← add_assoc, h, h.periodic.nat_mul] lemma antiperiodic.int_even_mul_periodic [ring α] [has_involutive_neg β] (h : antiperiodic f c) (n : ℤ) : periodic f (n * (2 * c)) := h.periodic.int_mul n lemma antiperiodic.int_odd_mul_antiperiodic [ring α] [has_involutive_neg β] (h : antiperiodic f c) (n : ℤ) : antiperiodic f (n * (2 * c) + c) := λ x, by rw [← add_assoc, h, h.periodic.int_mul] lemma antiperiodic.nat_mul_eq_of_eq_zero [comm_semiring α] [subtraction_monoid β] (h : antiperiodic f c) (hi : f 0 = 0) (n : ℕ) : f (n * c) = 0 := begin rcases nat.even_or_odd n with ⟨k, rfl⟩ | ⟨k, rfl⟩; have hk : (k : α) * (2 * c) = 2 * k * c := by rw [mul_left_comm, ← mul_assoc], { simpa [← two_mul, hk, hi] using (h.nat_even_mul_periodic k).eq }, { simpa [add_mul, hk, hi] using (h.nat_odd_mul_antiperiodic k).eq }, end lemma antiperiodic.int_mul_eq_of_eq_zero [comm_ring α] [subtraction_monoid β] (h : antiperiodic f c) (hi : f 0 = 0) (n : ℤ) : f (n * c) = 0 := begin rcases int.even_or_odd n with ⟨k, rfl⟩ | ⟨k, rfl⟩; have hk : (k : α) * (2 * c) = 2 * k * c := by rw [mul_left_comm, ← mul_assoc], { simpa [← two_mul, hk, hi] using (h.int_even_mul_periodic k).eq }, { simpa [add_mul, hk, hi] using (h.int_odd_mul_antiperiodic k).eq }, end lemma antiperiodic.sub_eq [add_group α] [has_involutive_neg β] (h : antiperiodic f c) (x : α) : f (x - c) = -f x := by simp only [eq_neg_iff_eq_neg.mp (h (x - c)), sub_add_cancel] lemma antiperiodic.sub_eq' [add_comm_group α] [has_neg β] (h : antiperiodic f c) : f (c - x) = -f (-x) := by simpa only [sub_eq_neg_add] using h (-x) lemma antiperiodic.neg [add_group α] [has_involutive_neg β] (h : antiperiodic f c) : antiperiodic f (-c) := by simpa only [sub_eq_add_neg, antiperiodic] using h.sub_eq lemma antiperiodic.neg_eq [add_group α] [has_involutive_neg β] (h : antiperiodic f c) : f (-c) = -f 0 := by simpa only [zero_add] using h.neg 0 lemma antiperiodic.const_add [add_semigroup α] [has_neg β] (h : antiperiodic f c) (a : α) : antiperiodic (λ x, f (a + x)) c := λ x, by simpa [add_assoc] using h (a + x) lemma antiperiodic.add_const [add_comm_semigroup α] [has_neg β] (h : antiperiodic f c) (a : α) : antiperiodic (λ x, f (x + a)) c := λ x, by simpa [add_assoc x c a, add_comm c, ←add_assoc x a c] using h (x + a) lemma antiperiodic.const_sub [add_comm_group α] [has_involutive_neg β] (h : antiperiodic f c) (a : α) : antiperiodic (λ x, f (a - x)) c := begin rw [←neg_neg c], refine antiperiodic.neg _, intro x, simpa [sub_add_eq_sub_sub] using h (a - x) end lemma antiperiodic.sub_const [add_comm_group α] [has_neg β] (h : antiperiodic f c) (a : α) : antiperiodic (λ x, f (x - a)) c := λ x, by simpa [add_comm x c, add_sub_assoc, add_comm c (x - a)] using h (x - a) lemma antiperiodic.smul [has_add α] [monoid γ] [add_group β] [distrib_mul_action γ β] (h : antiperiodic f c) (a : γ) : antiperiodic (a • f) c := by simp * at * lemma antiperiodic.const_smul [add_monoid α] [has_neg β] [group γ] [distrib_mul_action γ α] (h : antiperiodic f c) (a : γ) : antiperiodic (λ x, f (a • x)) (a⁻¹ • c) := λ x, by simpa only [smul_add, smul_inv_smul] using h (a • x) lemma antiperiodic.const_smul₀ [add_comm_monoid α] [has_neg β] [division_ring γ] [module γ α] (h : antiperiodic f c) {a : γ} (ha : a ≠ 0) : antiperiodic (λ x, f (a • x)) (a⁻¹ • c) := λ x, by simpa only [smul_add, smul_inv_smul₀ ha] using h (a • x) lemma antiperiodic.const_mul [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (a * x)) (a⁻¹ * c) := h.const_smul₀ ha lemma antiperiodic.const_inv_smul [add_monoid α] [has_neg β] [group γ] [distrib_mul_action γ α] (h : antiperiodic f c) (a : γ) : antiperiodic (λ x, f (a⁻¹ • x)) (a • c) := by simpa only [inv_inv] using h.const_smul a⁻¹ lemma antiperiodic.const_inv_smul₀ [add_comm_monoid α] [has_neg β] [division_ring γ] [module γ α] (h : antiperiodic f c) {a : γ} (ha : a ≠ 0) : antiperiodic (λ x, f (a⁻¹ • x)) (a • c) := by simpa only [inv_inv] using h.const_smul₀ (inv_ne_zero ha) lemma antiperiodic.const_inv_mul [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (a⁻¹ * x)) (a * c) := h.const_inv_smul₀ ha lemma antiperiodic.mul_const [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (x * a)) (c * a⁻¹) := h.const_smul₀ $ (mul_opposite.op_ne_zero_iff a).mpr ha lemma antiperiodic.mul_const' [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (x * a)) (c / a) := by simpa only [div_eq_mul_inv] using h.mul_const ha lemma antiperiodic.mul_const_inv [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (x * a⁻¹)) (c * a) := h.const_inv_smul₀ $ (mul_opposite.op_ne_zero_iff a).mpr ha lemma antiperiodic.div_inv [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (x / a)) (c * a) := by simpa only [div_eq_mul_inv] using h.mul_const_inv ha lemma antiperiodic.add [add_group α] [has_involutive_neg β] (h1 : antiperiodic f c₁) (h2 : antiperiodic f c₂) : periodic f (c₁ + c₂) := by simp [*, ← add_assoc] at * lemma antiperiodic.sub [add_comm_group α] [has_involutive_neg β] (h1 : antiperiodic f c₁) (h2 : antiperiodic f c₂) : periodic f (c₁ - c₂) := let h := h2.neg in by simp [*, sub_eq_add_neg, add_comm c₁, ← add_assoc] at * lemma periodic.add_antiperiod [add_group α] [has_neg β] (h1 : periodic f c₁) (h2 : antiperiodic f c₂) : antiperiodic f (c₁ + c₂) := by simp [*, ← add_assoc] at * lemma periodic.sub_antiperiod [add_comm_group α] [has_involutive_neg β] (h1 : periodic f c₁) (h2 : antiperiodic f c₂) : antiperiodic f (c₁ - c₂) := let h := h2.neg in by simp [*, sub_eq_add_neg, add_comm c₁, ← add_assoc] at * lemma periodic.add_antiperiod_eq [add_group α] [has_neg β] (h1 : periodic f c₁) (h2 : antiperiodic f c₂) : f (c₁ + c₂) = -f 0 := (h1.add_antiperiod h2).eq lemma periodic.sub_antiperiod_eq [add_comm_group α] [has_involutive_neg β] (h1 : periodic f c₁) (h2 : antiperiodic f c₂) : f (c₁ - c₂) = -f 0 := (h1.sub_antiperiod h2).eq lemma antiperiodic.mul [has_add α] [has_mul β] [has_distrib_neg β] (hf : antiperiodic f c) (hg : antiperiodic g c) : periodic (f * g) c := by simp * at * lemma antiperiodic.div [has_add α] [division_monoid β] [has_distrib_neg β] (hf : antiperiodic f c) (hg : antiperiodic g c) : periodic (f / g) c := by simp [*, neg_div_neg_eq] at * end function lemma int.fract_periodic (α) [linear_ordered_ring α] [floor_ring α] : function.periodic int.fract (1 : α) := by exact_mod_cast λ a, int.fract_add_int a 1
45eda6200c10745f73cc6a9ce3cb9a342dfe5604
94e33a31faa76775069b071adea97e86e218a8ee
/src/analysis/convex/integral.lean
f9abe177f1bfda33066e52e70756ddc2c221ee15
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
21,765
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import analysis.convex.function import analysis.convex.strict_convex_space import measure_theory.function.ae_eq_of_integral import measure_theory.integral.average /-! # Jensen's inequality for integrals In this file we prove several forms of Jensen's inequality for integrals. - for convex sets: `convex.average_mem`, `convex.set_average_mem`, `convex.integral_mem`; - for convex functions: `convex.on.average_mem_epigraph`, `convex_on.map_average_le`, `convex_on.set_average_mem_epigraph`, `convex_on.map_set_average_le`, `convex_on.map_integral_le`; - for strictly convex sets: `strict_convex.ae_eq_const_or_average_mem_interior`; - for a closed ball in a strictly convex normed space: `ae_eq_const_or_norm_integral_lt_of_norm_le_const`; - for strictly convex functions: `strict_convex_on.ae_eq_const_or_map_average_lt`. ## TODO - Use a typeclass for strict convexity of a closed ball. ## Tags convex, integral, center mass, average value, Jensen's inequality -/ open measure_theory measure_theory.measure metric set filter topological_space function open_locale topological_space big_operators ennreal convex variables {α E F : Type*} {m0 : measurable_space α} [normed_group E] [normed_space ℝ E] [complete_space E] [normed_group F] [normed_space ℝ F] [complete_space F] {μ : measure α} {s : set E} {t : set α} {f : α → E} {g : E → ℝ} {C : ℝ} /-! ### Non-strict Jensen's inequality -/ /-- If `μ` is a probability measure on `α`, `s` is a convex closed set in `E`, and `f` is an integrable function sending `μ`-a.e. points to `s`, then the expected value of `f` belongs to `s`: `∫ x, f x ∂μ ∈ s`. See also `convex.sum_mem` for a finite sum version of this lemma. -/ lemma convex.integral_mem [is_probability_measure μ] (hs : convex ℝ s) (hsc : is_closed s) (hf : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) : ∫ x, f x ∂μ ∈ s := begin borelize E, rcases hfi.ae_strongly_measurable with ⟨g, hgm, hfg⟩, haveI : separable_space (range g ∩ s : set E) := (hgm.is_separable_range.mono (inter_subset_left _ _)).separable_space, obtain ⟨y₀, h₀⟩ : (range g ∩ s).nonempty, { rcases (hf.and hfg).exists with ⟨x₀, h₀⟩, exact ⟨f x₀, by simp only [h₀.2, mem_range_self], h₀.1⟩ }, rw [integral_congr_ae hfg], rw [integrable_congr hfg] at hfi, have hg : ∀ᵐ x ∂μ, g x ∈ closure (range g ∩ s), { filter_upwards [hfg.rw (λ x y, y ∈ s) hf] with x hx, apply subset_closure, exact ⟨mem_range_self _, hx⟩ }, set G : ℕ → simple_func α E := simple_func.approx_on _ hgm.measurable (range g ∩ s) y₀ h₀, have : tendsto (λ n, (G n).integral μ) at_top (𝓝 $ ∫ x, g x ∂μ), from tendsto_integral_approx_on_of_measurable hfi _ hg _ (integrable_const _), refine hsc.mem_of_tendsto this (eventually_of_forall $ λ n, hs.sum_mem _ _ _), { exact λ _ _, ennreal.to_real_nonneg }, { rw [← ennreal.to_real_sum, (G n).sum_range_measure_preimage_singleton, measure_univ, ennreal.one_to_real], exact λ _ _, measure_ne_top _ _ }, { simp only [simple_func.mem_range, forall_range_iff], assume x, apply inter_subset_right (range g), exact simple_func.approx_on_mem hgm.measurable _ _ _ }, end /-- If `μ` is a non-zero finite measure on `α`, `s` is a convex closed set in `E`, and `f` is an integrable function sending `μ`-a.e. points to `s`, then the average value of `f` belongs to `s`: `⨍ x, f x ∂μ ∈ s`. See also `convex.center_mass_mem` for a finite sum version of this lemma. -/ lemma convex.average_mem [is_finite_measure μ] (hs : convex ℝ s) (hsc : is_closed s) (hμ : μ ≠ 0) (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) : ⨍ x, f x ∂μ ∈ s := begin haveI : is_probability_measure ((μ univ)⁻¹ • μ), from is_probability_measure_smul hμ, refine hs.integral_mem hsc (ae_mono' _ hfs) hfi.to_average, exact absolutely_continuous.smul (refl _) _ end /-- If `μ` is a non-zero finite measure on `α`, `s` is a convex closed set in `E`, and `f` is an integrable function sending `μ`-a.e. points to `s`, then the average value of `f` belongs to `s`: `⨍ x, f x ∂μ ∈ s`. See also `convex.center_mass_mem` for a finite sum version of this lemma. -/ lemma convex.set_average_mem (hs : convex ℝ s) (hsc : is_closed s) (h0 : μ t ≠ 0) (ht : μ t ≠ ∞) (hfs : ∀ᵐ x ∂μ.restrict t, f x ∈ s) (hfi : integrable_on f t μ) : ⨍ x in t, f x ∂μ ∈ s := begin haveI : fact (μ t < ∞) := ⟨ht.lt_top⟩, refine hs.average_mem hsc _ hfs hfi, rwa [ne.def, restrict_eq_zero] end /-- If `μ` is a non-zero finite measure on `α`, `s` is a convex set in `E`, and `f` is an integrable function sending `μ`-a.e. points to `s`, then the average value of `f` belongs to `closure s`: `⨍ x, f x ∂μ ∈ s`. See also `convex.center_mass_mem` for a finite sum version of this lemma. -/ lemma convex.set_average_mem_closure (hs : convex ℝ s) (h0 : μ t ≠ 0) (ht : μ t ≠ ∞) (hfs : ∀ᵐ x ∂μ.restrict t, f x ∈ s) (hfi : integrable_on f t μ) : ⨍ x in t, f x ∂μ ∈ closure s := hs.closure.set_average_mem is_closed_closure h0 ht (hfs.mono $ λ x hx, subset_closure hx) hfi lemma convex_on.average_mem_epigraph [is_finite_measure μ] (hg : convex_on ℝ s g) (hgc : continuous_on g s) (hsc : is_closed s) (hμ : μ ≠ 0) (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) (hgi : integrable (g ∘ f) μ) : (⨍ x, f x ∂μ, ⨍ x, g (f x) ∂μ) ∈ {p : E × ℝ | p.1 ∈ s ∧ g p.1 ≤ p.2} := have ht_mem : ∀ᵐ x ∂μ, (f x, g (f x)) ∈ {p : E × ℝ | p.1 ∈ s ∧ g p.1 ≤ p.2}, from hfs.mono (λ x hx, ⟨hx, le_rfl⟩), by simpa only [average_pair hfi hgi] using hg.convex_epigraph.average_mem (hsc.epigraph hgc) hμ ht_mem (hfi.prod_mk hgi) lemma concave_on.average_mem_hypograph [is_finite_measure μ] (hg : concave_on ℝ s g) (hgc : continuous_on g s) (hsc : is_closed s) (hμ : μ ≠ 0) (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) (hgi : integrable (g ∘ f) μ) : (⨍ x, f x ∂μ, ⨍ x, g (f x) ∂μ) ∈ {p : E × ℝ | p.1 ∈ s ∧ p.2 ≤ g p.1} := by simpa only [mem_set_of_eq, pi.neg_apply, average_neg, neg_le_neg_iff] using hg.neg.average_mem_epigraph hgc.neg hsc hμ hfs hfi hgi.neg /-- **Jensen's inequality**: if a function `g : E → ℝ` is convex and continuous on a convex closed set `s`, `μ` is a finite non-zero measure on `α`, and `f : α → E` is a function sending `μ`-a.e. points to `s`, then the value of `g` at the average value of `f` is less than or equal to the average value of `g ∘ f` provided that both `f` and `g ∘ f` are integrable. See also `convex_on.map_center_mass_le` for a finite sum version of this lemma. -/ lemma convex_on.map_average_le [is_finite_measure μ] (hg : convex_on ℝ s g) (hgc : continuous_on g s) (hsc : is_closed s) (hμ : μ ≠ 0) (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) (hgi : integrable (g ∘ f) μ) : g (⨍ x, f x ∂μ) ≤ ⨍ x, g (f x) ∂μ := (hg.average_mem_epigraph hgc hsc hμ hfs hfi hgi).2 /-- **Jensen's inequality**: if a function `g : E → ℝ` is concave and continuous on a convex closed set `s`, `μ` is a finite non-zero measure on `α`, and `f : α → E` is a function sending `μ`-a.e. points to `s`, then the average value of `g ∘ f` is less than or equal to the value of `g` at the average value of `f` provided that both `f` and `g ∘ f` are integrable. See also `concave_on.le_map_center_mass` for a finite sum version of this lemma. -/ lemma concave_on.le_map_average [is_finite_measure μ] (hg : concave_on ℝ s g) (hgc : continuous_on g s) (hsc : is_closed s) (hμ : μ ≠ 0) (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) (hgi : integrable (g ∘ f) μ) : ⨍ x, g (f x) ∂μ ≤ g (⨍ x, f x ∂μ) := (hg.average_mem_hypograph hgc hsc hμ hfs hfi hgi).2 /-- **Jensen's inequality**: if a function `g : E → ℝ` is convex and continuous on a convex closed set `s`, `μ` is a finite non-zero measure on `α`, and `f : α → E` is a function sending `μ`-a.e. points of a set `t` to `s`, then the value of `g` at the average value of `f` over `t` is less than or equal to the average value of `g ∘ f` over `t` provided that both `f` and `g ∘ f` are integrable. -/ lemma convex_on.set_average_mem_epigraph (hg : convex_on ℝ s g) (hgc : continuous_on g s) (hsc : is_closed s) (h0 : μ t ≠ 0) (ht : μ t ≠ ∞) (hfs : ∀ᵐ x ∂μ.restrict t, f x ∈ s) (hfi : integrable_on f t μ) (hgi : integrable_on (g ∘ f) t μ) : (⨍ x in t, f x ∂μ, ⨍ x in t, g (f x) ∂μ) ∈ {p : E × ℝ | p.1 ∈ s ∧ g p.1 ≤ p.2} := begin haveI : fact (μ t < ∞) := ⟨ht.lt_top⟩, refine hg.average_mem_epigraph hgc hsc _ hfs hfi hgi, rwa [ne.def, restrict_eq_zero] end /-- **Jensen's inequality**: if a function `g : E → ℝ` is concave and continuous on a convex closed set `s`, `μ` is a finite non-zero measure on `α`, and `f : α → E` is a function sending `μ`-a.e. points of a set `t` to `s`, then the average value of `g ∘ f` over `t` is less than or equal to the value of `g` at the average value of `f` over `t` provided that both `f` and `g ∘ f` are integrable. -/ lemma concave_on.set_average_mem_hypograph (hg : concave_on ℝ s g) (hgc : continuous_on g s) (hsc : is_closed s) (h0 : μ t ≠ 0) (ht : μ t ≠ ∞) (hfs : ∀ᵐ x ∂μ.restrict t, f x ∈ s) (hfi : integrable_on f t μ) (hgi : integrable_on (g ∘ f) t μ) : (⨍ x in t, f x ∂μ, ⨍ x in t, g (f x) ∂μ) ∈ {p : E × ℝ | p.1 ∈ s ∧ p.2 ≤ g p.1} := by simpa only [mem_set_of_eq, pi.neg_apply, average_neg, neg_le_neg_iff] using hg.neg.set_average_mem_epigraph hgc.neg hsc h0 ht hfs hfi hgi.neg /-- **Jensen's inequality**: if a function `g : E → ℝ` is convex and continuous on a convex closed set `s`, `μ` is a finite non-zero measure on `α`, and `f : α → E` is a function sending `μ`-a.e. points of a set `t` to `s`, then the value of `g` at the average value of `f` over `t` is less than or equal to the average value of `g ∘ f` over `t` provided that both `f` and `g ∘ f` are integrable. -/ lemma convex_on.map_set_average_le (hg : convex_on ℝ s g) (hgc : continuous_on g s) (hsc : is_closed s) (h0 : μ t ≠ 0) (ht : μ t ≠ ∞) (hfs : ∀ᵐ x ∂μ.restrict t, f x ∈ s) (hfi : integrable_on f t μ) (hgi : integrable_on (g ∘ f) t μ) : g (⨍ x in t, f x ∂μ) ≤ ⨍ x in t, g (f x) ∂μ := (hg.set_average_mem_epigraph hgc hsc h0 ht hfs hfi hgi).2 /-- **Jensen's inequality**: if a function `g : E → ℝ` is concave and continuous on a convex closed set `s`, `μ` is a finite non-zero measure on `α`, and `f : α → E` is a function sending `μ`-a.e. points of a set `t` to `s`, then the average value of `g ∘ f` over `t` is less than or equal to the value of `g` at the average value of `f` over `t` provided that both `f` and `g ∘ f` are integrable. -/ lemma concave_on.le_map_set_average (hg : concave_on ℝ s g) (hgc : continuous_on g s) (hsc : is_closed s) (h0 : μ t ≠ 0) (ht : μ t ≠ ∞) (hfs : ∀ᵐ x ∂μ.restrict t, f x ∈ s) (hfi : integrable_on f t μ) (hgi : integrable_on (g ∘ f) t μ) : ⨍ x in t, g (f x) ∂μ ≤ g (⨍ x in t, f x ∂μ) := (hg.set_average_mem_hypograph hgc hsc h0 ht hfs hfi hgi).2 /-- **Jensen's inequality**: if a function `g : E → ℝ` is convex and continuous on a convex closed set `s`, `μ` is a probability measure on `α`, and `f : α → E` is a function sending `μ`-a.e. points to `s`, then the value of `g` at the expected value of `f` is less than or equal to the expected value of `g ∘ f` provided that both `f` and `g ∘ f` are integrable. See also `convex_on.map_center_mass_le` for a finite sum version of this lemma. -/ lemma convex_on.map_integral_le [is_probability_measure μ] (hg : convex_on ℝ s g) (hgc : continuous_on g s) (hsc : is_closed s) (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) (hgi : integrable (g ∘ f) μ) : g (∫ x, f x ∂μ) ≤ ∫ x, g (f x) ∂μ := by simpa only [average_eq_integral] using hg.map_average_le hgc hsc (is_probability_measure.ne_zero μ) hfs hfi hgi /-- **Jensen's inequality**: if a function `g : E → ℝ` is concave and continuous on a convex closed set `s`, `μ` is a probability measure on `α`, and `f : α → E` is a function sending `μ`-a.e. points to `s`, then the expected value of `g ∘ f` is less than or equal to the value of `g` at the expected value of `f` provided that both `f` and `g ∘ f` are integrable. -/ lemma concave_on.le_map_integral [is_probability_measure μ] (hg : concave_on ℝ s g) (hgc : continuous_on g s) (hsc : is_closed s) (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) (hgi : integrable (g ∘ f) μ) : ∫ x, g (f x) ∂μ ≤ g (∫ x, f x ∂μ) := by simpa only [average_eq_integral] using hg.le_map_average hgc hsc (is_probability_measure.ne_zero μ) hfs hfi hgi /-! ### Strict Jensen's inequality -/ /-- If `f : α → E` is an integrable function, then either it is a.e. equal to the constant `⨍ x, f x ∂μ` or there exists a measurable set such that `μ t ≠ 0`, `μ tᶜ ≠ 0`, and the average values of `f` over `t` and `tᶜ` are different. -/ lemma ae_eq_const_or_exists_average_ne_compl [is_finite_measure μ] (hfi : integrable f μ) : (f =ᵐ[μ] const α (⨍ x, f x ∂μ)) ∨ ∃ t, measurable_set t ∧ μ t ≠ 0 ∧ μ tᶜ ≠ 0 ∧ ⨍ x in t, f x ∂μ ≠ ⨍ x in tᶜ, f x ∂μ := begin refine or_iff_not_imp_right.mpr (λ H, _), push_neg at H, refine hfi.ae_eq_of_forall_set_integral_eq _ _ (integrable_const _) (λ t ht ht', _), clear ht', simp only [const_apply, set_integral_const], by_cases h₀ : μ t = 0, { rw [restrict_eq_zero.2 h₀, integral_zero_measure, h₀, ennreal.zero_to_real, zero_smul] }, by_cases h₀' : μ tᶜ = 0, { rw ← ae_eq_univ at h₀', rw [restrict_congr_set h₀', restrict_univ, measure_congr h₀', measure_smul_average] }, have := average_mem_open_segment_compl_self ht.null_measurable_set h₀ h₀' hfi, rw [← H t ht h₀ h₀', open_segment_same, mem_singleton_iff] at this, rw [this, measure_smul_set_average _ (measure_ne_top μ _)] end /-- If an integrable function `f : α → E` takes values in a convex set `s` and for some set `t` of positive measure, the average value of `f` over `t` belongs to the interior of `s`, then the average of `f` over the whole space belongs to the interior of `s`. -/ lemma convex.average_mem_interior_of_set [is_finite_measure μ] (hs : convex ℝ s) (h0 : μ t ≠ 0) (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) (ht : ⨍ x in t, f x ∂μ ∈ interior s) : ⨍ x, f x ∂μ ∈ interior s := begin rw ← measure_to_measurable at h0, rw ← restrict_to_measurable (measure_ne_top μ t) at ht, by_cases h0' : μ (to_measurable μ t)ᶜ = 0, { rw ← ae_eq_univ at h0', rwa [restrict_congr_set h0', restrict_univ] at ht }, exact hs.open_segment_interior_closure_subset_interior ht (hs.set_average_mem_closure h0' (measure_ne_top _ _) (ae_restrict_of_ae hfs) hfi.integrable_on) (average_mem_open_segment_compl_self (measurable_set_to_measurable μ t).null_measurable_set h0 h0' hfi) end /-- If an integrable function `f : α → E` takes values in a strictly convex closed set `s`, then either it is a.e. equal to its average value, or its average value belongs to the interior of `s`. -/ lemma strict_convex.ae_eq_const_or_average_mem_interior [is_finite_measure μ] (hs : strict_convex ℝ s) (hsc : is_closed s) (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) : f =ᵐ[μ] const α (⨍ x, f x ∂μ) ∨ ⨍ x, f x ∂μ ∈ interior s := begin have : ∀ {t}, μ t ≠ 0 → ⨍ x in t, f x ∂μ ∈ s, from λ t ht, hs.convex.set_average_mem hsc ht (measure_ne_top _ _) (ae_restrict_of_ae hfs) hfi.integrable_on, refine (ae_eq_const_or_exists_average_ne_compl hfi).imp_right _, rintro ⟨t, hm, h₀, h₀', hne⟩, exact hs.open_segment_subset (this h₀) (this h₀') hne (average_mem_open_segment_compl_self hm.null_measurable_set h₀ h₀' hfi) end /-- **Jensen's inequality**, strict version: if an integrable function `f : α → E` takes values in a convex closed set `s`, and `g : E → ℝ` is continuous and strictly convex on `s`, then either `f` is a.e. equal to its average value, or `g (⨍ x, f x ∂μ) < ⨍ x, g (f x) ∂μ`. -/ lemma strict_convex_on.ae_eq_const_or_map_average_lt [is_finite_measure μ] (hg : strict_convex_on ℝ s g) (hgc : continuous_on g s) (hsc : is_closed s) (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) (hgi : integrable (g ∘ f) μ) : f =ᵐ[μ] const α (⨍ x, f x ∂μ) ∨ g (⨍ x, f x ∂μ) < ⨍ x, g (f x) ∂μ := begin have : ∀ {t}, μ t ≠ 0 → ⨍ x in t, f x ∂μ ∈ s ∧ g (⨍ x in t, f x ∂μ) ≤ ⨍ x in t, g (f x) ∂μ, from λ t ht, hg.convex_on.set_average_mem_epigraph hgc hsc ht (measure_ne_top _ _) (ae_restrict_of_ae hfs) hfi.integrable_on hgi.integrable_on, refine (ae_eq_const_or_exists_average_ne_compl hfi).imp_right _, rintro ⟨t, hm, h₀, h₀', hne⟩, rcases average_mem_open_segment_compl_self hm.null_measurable_set h₀ h₀' (hfi.prod_mk hgi) with ⟨a, b, ha, hb, hab, h_avg⟩, simp only [average_pair hfi hgi, average_pair hfi.integrable_on hgi.integrable_on, prod.smul_mk, prod.mk_add_mk, prod.mk.inj_iff, (∘)] at h_avg, rw [← h_avg.1, ← h_avg.2], calc g (a • ⨍ x in t, f x ∂μ + b • ⨍ x in tᶜ, f x ∂μ) < a * g (⨍ x in t, f x ∂μ) + b * g (⨍ x in tᶜ, f x ∂μ) : hg.2 (this h₀).1 (this h₀').1 hne ha hb hab ... ≤ a * ⨍ x in t, g (f x) ∂μ + b * ⨍ x in tᶜ, g (f x) ∂μ : add_le_add (mul_le_mul_of_nonneg_left (this h₀).2 ha.le) (mul_le_mul_of_nonneg_left (this h₀').2 hb.le) end /-- **Jensen's inequality**, strict version: if an integrable function `f : α → E` takes values in a convex closed set `s`, and `g : E → ℝ` is continuous and strictly concave on `s`, then either `f` is a.e. equal to its average value, or `⨍ x, g (f x) ∂μ < g (⨍ x, f x ∂μ)`. -/ lemma strict_concave_on.ae_eq_const_or_lt_map_average [is_finite_measure μ] (hg : strict_concave_on ℝ s g) (hgc : continuous_on g s) (hsc : is_closed s) (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) (hgi : integrable (g ∘ f) μ) : f =ᵐ[μ] const α (⨍ x, f x ∂μ) ∨ ⨍ x, g (f x) ∂μ < g (⨍ x, f x ∂μ) := by simpa only [pi.neg_apply, average_neg, neg_lt_neg_iff] using hg.neg.ae_eq_const_or_map_average_lt hgc.neg hsc hfs hfi hgi.neg /-- If `E` is a strictly convex normed space and `f : α → E` is a function such that `∥f x∥ ≤ C` a.e., then either this function is a.e. equal to its average value, or the norm of its average value is strictly less than `C`. -/ lemma ae_eq_const_or_norm_average_lt_of_norm_le_const [strict_convex_space ℝ E] (h_le : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) : (f =ᵐ[μ] const α ⨍ x, f x ∂μ) ∨ ∥⨍ x, f x ∂μ∥ < C := begin cases le_or_lt C 0 with hC0 hC0, { have : f =ᵐ[μ] 0, from h_le.mono (λ x hx, norm_le_zero_iff.1 (hx.trans hC0)), simp only [average_congr this, pi.zero_apply, average_zero], exact or.inl this }, by_cases hfi : integrable f μ, swap, by simp [average_def', integral_undef hfi, hC0, ennreal.to_real_pos_iff], cases (le_top : μ univ ≤ ∞).eq_or_lt with hμt hμt, { simp [average_def', hμt, hC0] }, haveI : is_finite_measure μ := ⟨hμt⟩, replace h_le : ∀ᵐ x ∂μ, f x ∈ closed_ball (0 : E) C, by simpa only [mem_closed_ball_zero_iff], simpa only [interior_closed_ball _ hC0.ne', mem_ball_zero_iff] using (strict_convex_closed_ball ℝ (0 : E) C).ae_eq_const_or_average_mem_interior is_closed_ball h_le hfi end /-- If `E` is a strictly convex normed space and `f : α → E` is a function such that `∥f x∥ ≤ C` a.e., then either this function is a.e. equal to its average value, or the norm of its integral is strictly less than `(μ univ).to_real * C`. -/ lemma ae_eq_const_or_norm_integral_lt_of_norm_le_const [strict_convex_space ℝ E] [is_finite_measure μ] (h_le : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) : (f =ᵐ[μ] const α ⨍ x, f x ∂μ) ∨ ∥∫ x, f x ∂μ∥ < (μ univ).to_real * C := begin cases eq_or_ne μ 0 with h₀ h₀, { left, simp [h₀] }, have hμ : 0 < (μ univ).to_real, by simp [ennreal.to_real_pos_iff, pos_iff_ne_zero, h₀, measure_lt_top], refine (ae_eq_const_or_norm_average_lt_of_norm_le_const h_le).imp_right (λ H, _), rwa [average_def', norm_smul, norm_inv, real.norm_eq_abs, abs_of_pos hμ, ← div_eq_inv_mul, div_lt_iff' hμ] at H end /-- If `E` is a strictly convex normed space and `f : α → E` is a function such that `∥f x∥ ≤ C` a.e. on a set `t` of finite measure, then either this function is a.e. equal to its average value on `t`, or the norm of its integral over `t` is strictly less than `(μ t).to_real * C`. -/ lemma ae_eq_const_or_norm_set_integral_lt_of_norm_le_const [strict_convex_space ℝ E] (ht : μ t ≠ ∞) (h_le : ∀ᵐ x ∂μ.restrict t, ∥f x∥ ≤ C) : (f =ᵐ[μ.restrict t] const α ⨍ x in t, f x ∂μ) ∨ ∥∫ x in t, f x ∂μ∥ < (μ t).to_real * C := begin haveI := fact.mk ht.lt_top, rw [← restrict_apply_univ], exact ae_eq_const_or_norm_integral_lt_of_norm_le_const h_le end
c51403d0525c88ada02074f97ccf514b23b033df
63abd62053d479eae5abf4951554e1064a4c45b4
/src/tactic/linarith/frontend.lean
1f20148cd0bdbb1bc7472ab5b4bb6eb52a7121a1
[ "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
18,538
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis -/ import tactic.linarith.verification import tactic.linarith.preprocessing /-! # `linarith`: solving linear arithmetic goals `linarith` is a tactic for solving goals with linear arithmetic. Suppose we have a set of hypotheses in `n` variables `S = {a₁x₁ + a₂x₂ + ... + aₙxₙ R b₁x₁ + b₂x₂ + ... + bₙxₙ}`, where `R ∈ {<, ≤, =, ≥, >}`. Our goal is to determine if the inequalities in `S` are jointly satisfiable, that is, if there is an assignment of values to `x₁, ..., xₙ` such that every inequality in `S` is true. Specifically, we aim to show that they are *not* satisfiable. This amounts to proving a contradiction. If our goal is also a linear inequality, we negate it and move it to a hypothesis before trying to prove `false`. When the inequalities are over a dense linear order, `linarith` is a decision procedure: it will prove `false` if and only if the inequalities are unsatisfiable. `linarith` will also run on some types like `ℤ` that are not dense orders, but it will fail to prove `false` on some unsatisfiable problems. It will run over concrete types like `ℕ`, `ℚ`, and `ℝ`, as well as abstract types that are instances of `linear_ordered_comm_ring`. ## Algorithm sketch First, the inequalities in the set `S` are rearranged into the form `tᵢ Rᵢ 0`, where `Rᵢ ∈ {<, ≤, =}` and each `tᵢ` is of the form `∑ cⱼxⱼ`. `linarith` uses an untrusted oracle to search for a certificate of unsatisfiability. The oracle searches for a list of natural number coefficients `kᵢ` such that `∑ kᵢtᵢ = 0`, where for at least one `i`, `kᵢ > 0` and `Rᵢ = <`. Given a list of such coefficients, `linarith` verifies that `∑ kᵢtᵢ = 0` using a normalization tactic such as `ring`. It proves that `∑ kᵢtᵢ < 0` by transitivity, since each component of the sum is either equal to, less than or equal to, or less than zero by hypothesis. This produces a contradiction. ## Preprocessing `linarith` does some basic preprocessing before running. Most relevantly, inequalities over natural numbers are cast into inequalities about integers, and rational division by numerals is canceled into multiplication. We do this so that we can guarantee the coefficients in the certificate are natural numbers, which allows the tactic to solve goals over types that are not fields. Preprocessors are allowed to branch, that is, to case split on disjunctions. `linarith` will succeed overall if it succeeds in all cases. This leads to exponential blowup in the number of `linarith` calls, and should be used sparingly. The default preprocessor set does not include case splits. ## Fourier-Motzkin elimination The oracle implemented to search for certificates uses Fourier-Motzkin variable elimination. This technique transorms a set of inequalities in `n` variables to an equisatisfiable set in `n - 1` variables. Once all variables have been eliminated, we conclude that the original set was unsatisfiable iff the comparison `0 < 0` is in the resulting set. While performing this elimination, we track the history of each derived comparison. This allows us to represent any comparison at any step as a positive combination of comparisons from the original set. In particular, if we derive `0 < 0`, we can find our desired list of coefficients by counting how many copies of each original comparison appear in the history. ## Implementation details `linarith` homogenizes numerical constants: the expression `1` is treated as a variable `t₀`. Often `linarith` is called on goals that have comparison hypotheses over multiple types. This creates multiple `linarith` problems, each of which is handled separately; the goal is solved as soon as one problem is found to be contradictory. Disequality hypotheses `t ≠ 0` do not fit in this pattern. `linarith` will attempt to prove equality goals by splitting them into two weak inequalities and running twice. But it does not split disequality hypotheses, since this would lead to a number of runs exponential in the number of disequalities in the context. The Fourier-Motzkin oracle is very modular. It can easily be replaced with another function of type `certificate_oracle := list comp → ℕ → tactic (rb_map ℕ ℕ)`, which takes a list of comparisons and the largest variable index appearing in those comparisons, and returns a map from comparison indices to coefficients. An alternate oracle can be specified in the `linarith_config` object. A variant, `nlinarith`, adds an extra preprocessing step to handle some basic nonlinear goals. There is a hook in the `linarith_config` configuration object to add custom preprocessing routines. The certificate checking step is *not* by reflection. `linarith` converts the certificate into a proof term of type `false`. Some of the behavior of `linarith` can be inspected with the option `set_option trace.linarith true`. Because the variable elimination happens outside the tactic monad, we cannot trace intermediate steps there. ## File structure The components of `linarith` are spread between a number of files for the sake of organization. * `lemmas.lean` contains proofs of some arithmetic lemmas that are used in preprocessing and in verification. * `datatypes.lean` contains data structures that are used across multiple files, along with some useful auxiliary functions. * `preprocessing.lean` contains functions used at the beginning of the tactic to transform hypotheses into a shape suitable for the main routine. * `parsing.lean` contains functions used to compute the linear structure of an expression. * `elimination.lean` contains the Fourier-Motzkin elimination routine. * `verification.lean` contains the certificate checking functions that produce a proof of `false`. * `frontend.lean` contains the control methods and user-facing components of the tactic. ## Tags linarith, nlinarith, lra, nra, Fourier Motzkin, linear arithmetic, linear programming -/ open tactic native namespace linarith /-! ### Control -/ /-- If `e` is a comparison `a R b` or the negation of a comparison `¬ a R b`, found in the target, `get_contr_lemma_name_and_type e` returns the name of a lemma that will change the goal to an implication, along with the type of `a` and `b`. For example, if `e` is `(a : ℕ) < b`, returns ``(`lt_of_not_ge, ℕ)``. -/ meta def get_contr_lemma_name_and_type : expr → option (name × expr) | `(@has_lt.lt %%tp %%_ _ _) := return (`lt_of_not_ge, tp) | `(@has_le.le %%tp %%_ _ _) := return (`le_of_not_gt, tp) | `(@eq %%tp _ _) := return (``eq_of_not_lt_of_not_gt, tp) | `(@ne %%tp _ _) := return (`not.intro, tp) | `(@ge %%tp %%_ _ _) := return (`le_of_not_gt, tp) | `(@gt %%tp %%_ _ _) := return (`lt_of_not_ge, tp) | `(¬ @has_lt.lt %%tp %%_ _ _) := return (`not.intro, tp) | `(¬ @has_le.le %%tp %%_ _ _) := return (`not.intro, tp) | `(¬ @eq %%tp _ _) := return (``not.intro, tp) | `(¬ @ge %%tp %%_ _ _) := return (`not.intro, tp) | `(¬ @gt %%tp %%_ _ _) := return (`not.intro, tp) | _ := none /-- `apply_contr_lemma` inspects the target to see if it can be moved to a hypothesis by negation. For example, a goal `⊢ a ≤ b` can become `a > b ⊢ false`. If this is the case, it applies the appropriate lemma and introduces the new hypothesis. It returns the type of the terms in the comparison (e.g. the type of `a` and `b` above) and the newly introduced local constant. Otherwise returns `none`. -/ meta def apply_contr_lemma : tactic (option (expr × expr)) := do t ← target, match get_contr_lemma_name_and_type t with | some (nm, tp) := do refine ((expr.const nm []) pexpr.mk_placeholder), v ← intro1, return $ some (tp, v) | none := return none end /-- `partition_by_type l` takes a list `l` of proofs of comparisons. It sorts these proofs by the type of the variables in the comparison, e.g. `(a : ℚ) < 1` and `(b : ℤ) > c` will be separated. Returns a map from a type to a list of comparisons over that type. -/ meta def partition_by_type (l : list expr) : tactic (rb_lmap expr expr) := l.mfoldl (λ m h, do tp ← ineq_prf_tp h, return $ m.insert tp h) mk_rb_map /-- Given a list `ls` of lists of proofs of comparisons, `try_linarith_on_lists cfg ls` will try to prove `false` by calling `linarith` on each list in succession. It will stop at the first proof of `false`, and fail if no contradiction is found with any list. -/ meta def try_linarith_on_lists (cfg : linarith_config) (ls : list (list expr)) : tactic expr := (first $ ls.map $ prove_false_by_linarith cfg) <|> fail "linarith failed to find a contradiction" /-- Given a list `hyps` of proofs of comparisons, `run_linarith_on_pfs cfg hyps pref_type` preprocesses `hyps` according to the list of preprocessors in `cfg`. This results in a list of branches (typically only one), each of which must succeed in order to close the goal. In each branch, we partition the list of hypotheses by type, and run `linarith` on each class in the partition; one of these must succeed in order for `linarith` to succeed on this branch. If `pref_type` is given, it will first use the class of proofs of comparisons over that type. -/ meta def run_linarith_on_pfs (cfg : linarith_config) (hyps : list expr) (pref_type : option expr) : tactic unit := let single_process := λ hyps : list expr, do linarith_trace_proofs ("after preprocessing, linarith has " ++ to_string hyps.length ++ " facts:") hyps, hyp_set ← partition_by_type hyps, linarith_trace format!"hypotheses appear in {hyp_set.size} different types", match pref_type with | some t := prove_false_by_linarith cfg (hyp_set.ifind t) <|> try_linarith_on_lists cfg (rb_map.values (hyp_set.erase t)) | none := try_linarith_on_lists cfg (rb_map.values hyp_set) end in let preprocessors := cfg.preprocessors.get_or_else default_preprocessors, preprocessors := if cfg.split_ne then linarith.remove_ne::preprocessors else preprocessors in do hyps ← preprocess preprocessors hyps, hyps.mmap' $ λ hs, do set_goals [hs.1], single_process hs.2 >>= exact /-- `filter_hyps_to_type restr_type hyps` takes a list of proofs of comparisons `hyps`, and filters it to only those that are comparisons over the type `restr_type`. -/ meta def filter_hyps_to_type (restr_type : expr) (hyps : list expr) : tactic (list expr) := hyps.mfilter $ λ h, do ht ← infer_type h, match get_contr_lemma_name_and_type ht with | some (_, htype) := succeeds $ unify htype restr_type | none := return ff end /-- A hack to allow users to write `{restr_type := ℚ}` in configuration structures. -/ meta def get_restrict_type (e : expr) : tactic expr := do m ← mk_mvar, unify `(some %%m : option Type) e, instantiate_mvars m end linarith /-! ### User facing functions -/ open linarith /-- `linarith reduce_semi only_on hyps cfg` tries to close the goal using linear arithmetic. It fails if it does not succeed at doing this. * If `reduce_semi` is true, it will unfold semireducible definitions when trying to match atomic expressions. * `hyps` is a list of proofs of comparisons to include in the search. * If `only_on` is true, the search will be restricted to `hyps`. Otherwise it will use all comparisons in the local context. -/ meta def tactic.linarith (reduce_semi : bool) (only_on : bool) (hyps : list pexpr) (cfg : linarith_config := {}) : tactic unit := focus1 $ do t ← target, -- if the target is an equality, we run `linarith` twice, to prove ≤ and ≥. if t.is_eq.is_some then linarith_trace "target is an equality: splitting" >> seq' (applyc ``eq_of_not_lt_of_not_gt) tactic.linarith else do when cfg.split_hypotheses (linarith_trace "trying to split hypotheses" >> try auto.split_hyps), /- If we are proving a comparison goal (and not just `false`), we consider the type of the elements in the comparison to be the "preferred" type. That is, if we find comparison hypotheses in multiple types, we will run `linarith` on the goal type first. In this case we also recieve a new variable from moving the goal to a hypothesis. Otherwise, there is no preferred type and no new variable; we simply change the goal to `false`. -/ pref_type_and_new_var_from_tgt ← apply_contr_lemma, when pref_type_and_new_var_from_tgt.is_none $ if cfg.exfalso then linarith_trace "using exfalso" >> exfalso else fail "linarith failed: target is not a valid comparison", let cfg := cfg.update_reducibility reduce_semi, let (pref_type, new_var) := pref_type_and_new_var_from_tgt.elim (none, none) (λ ⟨a, b⟩, (some a, some b)), -- set up the list of hypotheses, considering the `only_on` and `restrict_type` options hyps ← hyps.mmap i_to_expr, hyps ← if only_on then return (new_var.elim [] singleton ++ hyps) else (++ hyps) <$> local_context, hyps ← (do t ← get_restrict_type cfg.restrict_type_reflect, filter_hyps_to_type t hyps) <|> return hyps, linarith_trace_proofs "linarith is running on the following hypotheses:" hyps, run_linarith_on_pfs cfg hyps pref_type setup_tactic_parser /-- Tries to prove a goal of `false` by linear arithmetic on hypotheses. If the goal is a linear (in)equality, tries to prove it by contradiction. If the goal is not `false` or an inequality, applies `exfalso` and tries linarith on the hypotheses. * `linarith` will use all relevant hypotheses in the local context. * `linarith [t1, t2, t3]` will add proof terms t1, t2, t3 to the local context. * `linarith only [h1, h2, h3, t1, t2, t3]` will use only the goal (if relevant), local hypotheses `h1`, `h2`, `h3`, and proofs `t1`, `t2`, `t3`. It will ignore the rest of the local context. * `linarith!` will use a stronger reducibility setting to identify atoms. Config options: * `linarith {exfalso := ff}` will fail on a goal that is neither an inequality nor `false` * `linarith {restrict_type := T}` will run only on hypotheses that are inequalities over `T` * `linarith {discharger := tac}` will use `tac` instead of `ring` for normalization. Options: `ring2`, `ring SOP`, `simp` * `linarith {split_hypotheses := ff}` will not destruct conjunctions in the context. -/ meta def tactic.interactive.linarith (red : parse ((tk "!")?)) (restr : parse ((tk "only")?)) (hyps : parse pexpr_list?) (cfg : linarith_config := {}) : tactic unit := tactic.linarith red.is_some restr.is_some (hyps.get_or_else []) cfg add_hint_tactic "linarith" /-- `linarith` attempts to find a contradiction between hypotheses that are linear (in)equalities. Equivalently, it can prove a linear inequality by assuming its negation and proving `false`. In theory, `linarith` should prove any goal that is true in the theory of linear arithmetic over the rationals. While there is some special handling for non-dense orders like `nat` and `int`, this tactic is not complete for these theories and will not prove every true goal. It will solve goals over arbitrary types that instantiate `linear_ordered_comm_ring`. An example: ```lean example (x y z : ℚ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : 12*y - 4* z < 0) : false := by linarith ``` `linarith` will use all appropriate hypotheses and the negation of the goal, if applicable. `linarith [t1, t2, t3]` will additionally use proof terms `t1, t2, t3`. `linarith only [h1, h2, h3, t1, t2, t3]` will use only the goal (if relevant), local hypotheses `h1`, `h2`, `h3`, and proofs `t1`, `t2`, `t3`. It will ignore the rest of the local context. `linarith!` will use a stronger reducibility setting to try to identify atoms. For example, ```lean example (x : ℚ) : id x ≥ x := by linarith ``` will fail, because `linarith` will not identify `x` and `id x`. `linarith!` will. This can sometimes be expensive. `linarith {discharger := tac, restrict_type := tp, exfalso := ff}` takes a config object with five optional arguments: * `discharger` specifies a tactic to be used for reducing an algebraic equation in the proof stage. The default is `ring`. Other options currently include `ring SOP` or `simp` for basic problems. * `restrict_type` will only use hypotheses that are inequalities over `tp`. This is useful if you have e.g. both integer and rational valued inequalities in the local context, which can sometimes confuse the tactic. * `transparency` controls how hard `linarith` will try to match atoms to each other. By default it will only unfold `reducible` definitions. * If `split_hypotheses` is true, `linarith` will split conjunctions in the context into separate hypotheses. * If `exfalso` is false, `linarith` will fail when the goal is neither an inequality nor `false`. (True by default.) A variant, `nlinarith`, does some basic preprocessing to handle some nonlinear goals. The option `set_option trace.linarith true` will trace certain intermediate stages of the `linarith` routine. -/ add_tactic_doc { name := "linarith", category := doc_category.tactic, decl_names := [`tactic.interactive.linarith], tags := ["arithmetic", "decision procedure", "finishing"] } /-- An extension of `linarith` with some preprocessing to allow it to solve some nonlinear arithmetic problems. (Based on Coq's `nra` tactic.) See `linarith` for the available syntax of options, which are inherited by `nlinarith`; that is, `nlinarith!` and `nlinarith only [h1, h2]` all work as in `linarith`. The preprocessing is as follows: * For every subterm `a ^ 2` or `a * a` in a hypothesis or the goal, the assumption `0 ≤ a ^ 2` or `0 ≤ a * a` is added to the context. * For every pair of hypotheses `a1 R1 b1`, `a2 R2 b2` in the context, `R1, R2 ∈ {<, ≤, =}`, the assumption `0 R' (b1 - a1) * (b2 - a2)` is added to the context (non-recursively), where `R ∈ {<, ≤, =}` is the appropriate comparison derived from `R1, R2`. -/ meta def tactic.interactive.nlinarith (red : parse ((tk "!")?)) (restr : parse ((tk "only")?)) (hyps : parse pexpr_list?) (cfg : linarith_config := {}) : tactic unit := tactic.linarith red.is_some restr.is_some (hyps.get_or_else []) { cfg with preprocessors := some $ cfg.preprocessors.get_or_else default_preprocessors ++ [nlinarith_extras] } add_hint_tactic "nlinarith" add_tactic_doc { name := "nlinarith", category := doc_category.tactic, decl_names := [`tactic.interactive.nlinarith], tags := ["arithmetic", "decision procedure", "finishing"] }
2c4615c5d5263bb747a27f815e40d6836ac7b6b7
6fbf10071e62af7238f2de8f9aa83d55d8763907
/src/2.1_logic_introduction.lean
e08852489686d590d6340ce9a720576dc0296201
[]
no_license
HasanMukati/uva-cs-dm-s19
ee5aad4568a3ca330c2738ed579c30e1308b03b0
3e7177682acdb56a2d16914e0344c10335583dcf
refs/heads/master
1,596,946,213,130
1,568,221,949,000
1,568,221,949,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,899
lean
/- Copyright 2019 Kevin Sullivan and Ben Hocking. -/ /- Inference rules. Introduction rules construct proofs that you don't yet have. Elimination rules extract information from proofs that you already have. -/ namespace Introduction.ex1 -- introduction: construct a proof def construct_a_proof (P Q : Prop) (p : P) (q : Q) : P ∧ Q := and.intro p q -- elimination: use a proof def use_a_proof (P Q : Prop) (p_and_q : P ∧ Q) : P := and.elim_left p_and_q end Introduction.ex1 /- Binding of names to values and the evaluation of names that are already bound to values. Names can be bound to values only once. There are no "variables" (no "mutable state") in Lean. -/ namespace Introduction.ex2 def x : nat := 5 -- bind the name x to the value, 5 #check x -- the type of the term x is now nat #reduce x -- evaluating x yields the value 5 def x := 6 -- we cannot bind a new value to x end Introduction.ex2 -- Function application expressions and evaluation #reduce 3 * 4 /- Terms have types, too. -/ #check 3 #check 3 * 4 /- Lean is stronly and statically typed. It will issue an error for the following code. -/ #check 3 * "Hello, Lean!" /- Lean does type inference. Type inference means that you can leave out explicit type declarations in cases where Lean can figure out what the types must be from context. -/ namespace Introduction.ex3 def x : nat := (1 : nat) def x' : nat := 1 def x'' := 1 #check x #check x' #check x'' end Introduction.ex3 /- All terms in Lean have types. -/ #check tt #check ff #check "Hello, Lean!" /- Types are values (terms) too -/ #check nat #check bool #check string /- You can check out the entire type hierarchy yourself. -/ #check 3 #check nat #check Type #check Type 0 #check Type 1 /- Propositions are types and proofs are values of these types. This principle is the basis for automated proof checking in Lean and in other constructive logic proof assistants such as Coq and Agda. -/ namespace Introduction.ex4 def p : true := true.intro end Introduction.ex4 /- Lean rejects proof terms that do not type check, just as it rejects ordinary computational values that do not typecheck, as illustrated in the example above. You will thus see an error in the following code. -/ namespace Introduction.ex5 def p : false := true.intro end Introduction.ex5 /- A formalized rendition of the famous example in which it is deduced that Socrates is mortal. You are not expected to fully understand this code at this point. -/ namespace Introduction.ex6 def modus_ponens (α : Type) (M : α → Prop) (h : ∀ a : α, M a) (w : α) : (M w) := (h w) axiom Person : Type axiom Mortal : Person → Prop axiom EveryoneIsMortal : ∀ p : Person, Mortal p axiom Socrates : Person theorem aProof : Mortal Socrates := modus_ponens Person Mortal EveryoneIsMortal Socrates end Introduction.ex6
8e8f666579d7313e7a0d8d2ad9a1a8fa9c4f0ec5
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/prop_instances.lean
b9269d8bc833797cd4235bb664445af826bfc106
[ "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
2,867
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 -/ import order.disjoint import order.with_bot /-! # The order on `Prop` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > https://github.com/leanprover-community/mathlib4/pull/792 > Any changes to this file require a corresponding PR to mathlib4. Instances on `Prop` such as `distrib_lattice`, `bounded_order`, `linear_order`. -/ /-- Propositions form a distributive lattice. -/ instance Prop.distrib_lattice : distrib_lattice Prop := { sup := or, le_sup_left := @or.inl, le_sup_right := @or.inr, sup_le := λ a b c, or.rec, inf := and, inf_le_left := @and.left, inf_le_right := @and.right, le_inf := λ a b c Hab Hac Ha, and.intro (Hab Ha) (Hac Ha), le_sup_inf := λ a b c, or_and_distrib_left.2, ..Prop.partial_order } /-- Propositions form a bounded order. -/ instance Prop.bounded_order : bounded_order Prop := { top := true, le_top := λ a Ha, true.intro, bot := false, bot_le := @false.elim } lemma Prop.bot_eq_false : (⊥ : Prop) = false := rfl lemma Prop.top_eq_true : (⊤ : Prop) = true := rfl instance Prop.le_is_total : is_total Prop (≤) := ⟨λ p q, by { change (p → q) ∨ (q → p), tauto! }⟩ noncomputable instance Prop.linear_order : linear_order Prop := by classical; exact lattice.to_linear_order Prop @[simp] lemma sup_Prop_eq : (⊔) = (∨) := rfl @[simp] lemma inf_Prop_eq : (⊓) = (∧) := rfl namespace pi variables {ι : Type*} {α' : ι → Type*} [Π i, partial_order (α' i)] lemma disjoint_iff [Π i, order_bot (α' i)] {f g : Π i, α' i} : disjoint f g ↔ ∀ i, disjoint (f i) (g i) := begin split, { intros h i x hf hg, refine (update_le_iff.mp $ -- this line doesn't work h (update_le_iff.mpr ⟨hf, λ _ _, _⟩) (update_le_iff.mpr ⟨hg, λ _ _, _⟩)).1, { exact ⊥}, { exact bot_le }, { exact bot_le }, }, { intros h x hf hg i, apply h i (hf i) (hg i) }, end lemma codisjoint_iff [Π i, order_top (α' i)] {f g : Π i, α' i} : codisjoint f g ↔ ∀ i, codisjoint (f i) (g i) := @disjoint_iff _ (λ i, (α' i)ᵒᵈ) _ _ _ _ lemma is_compl_iff [Π i, bounded_order (α' i)] {f g : Π i, α' i} : is_compl f g ↔ ∀ i, is_compl (f i) (g i) := by simp_rw [is_compl_iff, disjoint_iff, codisjoint_iff, forall_and_distrib] end pi @[simp] lemma Prop.disjoint_iff {P Q : Prop} : disjoint P Q ↔ ¬(P ∧ Q) := disjoint_iff_inf_le @[simp] lemma Prop.codisjoint_iff {P Q : Prop} : codisjoint P Q ↔ P ∨ Q := codisjoint_iff_le_sup.trans $ forall_const _ @[simp] lemma Prop.is_compl_iff {P Q : Prop} : is_compl P Q ↔ ¬(P ↔ Q) := begin rw [is_compl_iff, Prop.disjoint_iff, Prop.codisjoint_iff, not_iff], tauto, end
661f448afb7c18fd9f1ef028c2d10e1618f15bdf
367134ba5a65885e863bdc4507601606690974c1
/src/order/filter/indicator_function.lean
43567564001ea18613cb2ca3f597771d7818f1df
[ "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
3,249
lean
/- Copyright (c) 2020 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Yury Kudryashov -/ import data.indicator_function import order.filter.at_top_bot /-! # Indicator function and filters Properties of indicator functions involving `=ᶠ` and `≤ᶠ`. ## Tags indicator, characteristic, filter -/ variables {α β M E : Type*} open set filter classical open_locale filter classical section has_zero variables [has_zero M] {s t : set α} {f g : α → M} {a : α} {l : filter α} lemma indicator_eventually_eq (hf : f =ᶠ[l ⊓ 𝓟 s] g) (hs : s =ᶠ[l] t) : indicator s f =ᶠ[l] indicator t g := (eventually_inf_principal.1 hf).mp $ hs.mem_iff.mono $ λ x hst hfg, by_cases (λ hxs : x ∈ s, by simp only [*, hst.1 hxs, indicator_of_mem]) (λ hxs, by simp only [indicator_of_not_mem hxs, indicator_of_not_mem (mt hst.2 hxs)]) end has_zero section add_monoid variables [add_monoid M] {s t : set α} {f g : α → M} {a : α} {l : filter α} lemma indicator_union_eventually_eq (h : ∀ᶠ a in l, a ∉ s ∩ t) : indicator (s ∪ t) f =ᶠ[l] indicator s f + indicator t f := h.mono $ λ a ha, indicator_union_of_not_mem_inter ha _ end add_monoid section order variables [has_zero β] [preorder β] {s t : set α} {f g : α → β} {a : α} {l : filter α} lemma indicator_eventually_le_indicator (h : f ≤ᶠ[l ⊓ 𝓟 s] g) : indicator s f ≤ᶠ[l] indicator s g := (eventually_inf_principal.1 h).mono $ assume a h, indicator_rel_indicator (le_refl _) h end order lemma tendsto_indicator_of_monotone {ι} [preorder ι] [has_zero β] (s : ι → set α) (hs : monotone s) (f : α → β) (a : α) : tendsto (λi, indicator (s i) f a) at_top (pure $ indicator (⋃ i, s i) f a) := begin by_cases h : ∃i, a ∈ s i, { rcases h with ⟨i, hi⟩, refine tendsto_pure.2 ((eventually_ge_at_top i).mono $ assume n hn, _), rw [indicator_of_mem (hs hn hi) _, indicator_of_mem ((subset_Union _ _) hi) _] }, { rw [not_exists] at h, simp only [indicator_of_not_mem (h _)], convert tendsto_const_pure, apply indicator_of_not_mem, simpa only [not_exists, mem_Union] } end lemma tendsto_indicator_of_antimono {ι} [preorder ι] [has_zero β] (s : ι → set α) (hs : ∀⦃i j⦄, i ≤ j → s j ⊆ s i) (f : α → β) (a : α) : tendsto (λi, indicator (s i) f a) at_top (pure $ indicator (⋂ i, s i) f a) := begin by_cases h : ∃i, a ∉ s i, { rcases h with ⟨i, hi⟩, refine tendsto_pure.2 ((eventually_ge_at_top i).mono $ assume n hn, _), rw [indicator_of_not_mem _ _, indicator_of_not_mem _ _], { simp only [mem_Inter, not_forall], exact ⟨i, hi⟩ }, { assume h, have := hs hn h, contradiction } }, { push_neg at h, simp only [indicator_of_mem, h, (mem_Inter.2 h), tendsto_const_pure] } end lemma tendsto_indicator_bUnion_finset {ι} [has_zero β] (s : ι → set α) (f : α → β) (a : α) : tendsto (λ (n : finset ι), indicator (⋃i∈n, s i) f a) at_top (pure $ indicator (Union s) f a) := begin rw Union_eq_Union_finset s, refine tendsto_indicator_of_monotone (λ n : finset ι, ⋃ i ∈ n, s i) _ f a, exact λ t₁ t₂, bUnion_subset_bUnion_left end
64b318187c340a30a9c4d57d5d536a905d7ca449
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/run/expr_maps.lean
3487308fe21260bcc887d698a3025dfda8787fc4
[ "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
2,934
lean
import Init.Lean.Expr open Lean def exprType : Expr := mkSort levelOne def biDef := BinderInfo.default def exprNat := mkConst `Nat [] -- Type -> Type def TypeArrowType := mkForall `α biDef exprType exprType -- Type -> Type def TypeArrowType2 := mkForall `β biDef exprType exprType -- fun (x : Nat) => x def exprT1 := mkLambda `x biDef exprNat (mkBVar 0) -- fun (y : Nat) => x def exprT2 := mkLambda `y biDef exprNat (mkBVar 0) -- fun (x : Nat) => (f x) def exprT3 := mkLambda `x biDef exprNat (mkApp (mkConst `f []) (mkBVar 0)) -- fun (x : Nat) => (f x) def exprT4 := mkLambda `x BinderInfo.implicit exprNat (mkApp (mkConst `f []) (mkBVar 0)) def check (b : Bool) : IO Unit := unless b (throw $ IO.userError "failed") def tst1 : IO Unit := do IO.println TypeArrowType; IO.println exprT1; IO.println exprT2; IO.println exprT3; IO.println exprT4; check (TypeArrowType == TypeArrowType2); check (ExprStructEq.mk TypeArrowType != ExprStructEq.mk TypeArrowType2); check (!Expr.equal TypeArrowType TypeArrowType2); check (exprT1 == exprT2); check (ExprStructEq.mk exprT1 != ExprStructEq.mk exprT2); check (ExprStructEq.mk exprT1 == ExprStructEq.mk exprT1); check (exprT3 == exprT4); check (ExprStructEq.mk exprT3 != ExprStructEq.mk exprT4); pure () #eval tst1 def tst2 : IO Unit := do let m1 : ExprMap Nat := {}; let m1 := m1.insert exprT1 10; check (m1.find? exprT1 == some 10); check (m1.find? exprT2 == some 10); check (m1.find? exprT3 == none); let m1 := m1.insert exprT4 20; check (m1.find? exprT1 == some 10); check (m1.find? exprT3 == some 20); IO.println (m1.find? exprT1); pure () #eval tst2 def tst3 : IO Unit := do let m1 : ExprStructMap Nat := {}; let m1 := m1.insert exprT1 10; check (m1.find? exprT1 == some 10); check (m1.find? exprT2 == none); check (m1.find? exprT3 == none); let m1 := m1.insert exprT4 20; check (m1.find? exprT1 == some 10); check (m1.find? exprT4 == some 20); check (m1.find? exprT3 == none); IO.println (m1.find? exprT1); pure () #eval tst3 def tst4 : IO Unit := do let m1 : PersistentExprMap Nat := {}; let m1 := m1.insert exprT1 10; check (m1.find? exprT1 == some 10); check (m1.find? exprT2 == some 10); check (m1.find? exprT3 == none); let m1 := m1.insert exprT4 20; check (m1.find? exprT1 == some 10); check (m1.find? exprT3 == some 20); IO.println (m1.find? exprT1); pure () #eval tst4 def tst5 : IO Unit := do let m1 : PersistentExprStructMap Nat := {}; let m1 := m1.insert exprT1 10; check (m1.find? exprT1 == some 10); check (m1.find? exprT2 == none); check (m1.find? exprT3 == none); let m1 := m1.insert exprT4 20; check (m1.find? exprT1 == some 10); check (m1.find? exprT4 == some 20); check (m1.find? exprT3 == none); IO.println (m1.find? exprT1); pure () #eval tst5
b68a067c77a3531cfe9867adf06c4548ff0ab26c
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/CommutativeMagma.lean
adadde7e3ea4f951bb17e6e03140b7d602d0fb2e
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
6,143
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section CommutativeMagma structure CommutativeMagma (A : Type) : Type := (op : (A → (A → A))) (commutative_op : (∀ {x y : A} , (op x y) = (op y x))) open CommutativeMagma structure Sig (AS : Type) : Type := (opS : (AS → (AS → AS))) structure Product (A : Type) : Type := (opP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (commutative_opP : (∀ {xP yP : (Prod A A)} , (opP xP yP) = (opP yP xP))) structure Hom {A1 : Type} {A2 : Type} (Co1 : (CommutativeMagma A1)) (Co2 : (CommutativeMagma A2)) : Type := (hom : (A1 → A2)) (pres_op : (∀ {x1 x2 : A1} , (hom ((op Co1) x1 x2)) = ((op Co2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (Co1 : (CommutativeMagma A1)) (Co2 : (CommutativeMagma A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_op : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((op Co1) x1 x2) ((op Co2) y1 y2)))))) inductive CommutativeMagmaTerm : Type | opL : (CommutativeMagmaTerm → (CommutativeMagmaTerm → CommutativeMagmaTerm)) open CommutativeMagmaTerm inductive ClCommutativeMagmaTerm (A : Type) : Type | sing : (A → ClCommutativeMagmaTerm) | opCl : (ClCommutativeMagmaTerm → (ClCommutativeMagmaTerm → ClCommutativeMagmaTerm)) open ClCommutativeMagmaTerm inductive OpCommutativeMagmaTerm (n : ℕ) : Type | v : ((fin n) → OpCommutativeMagmaTerm) | opOL : (OpCommutativeMagmaTerm → (OpCommutativeMagmaTerm → OpCommutativeMagmaTerm)) open OpCommutativeMagmaTerm inductive OpCommutativeMagmaTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpCommutativeMagmaTerm2) | sing2 : (A → OpCommutativeMagmaTerm2) | opOL2 : (OpCommutativeMagmaTerm2 → (OpCommutativeMagmaTerm2 → OpCommutativeMagmaTerm2)) open OpCommutativeMagmaTerm2 def simplifyCl {A : Type} : ((ClCommutativeMagmaTerm A) → (ClCommutativeMagmaTerm A)) | (opCl x1 x2) := (opCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpCommutativeMagmaTerm n) → (OpCommutativeMagmaTerm n)) | (opOL x1 x2) := (opOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpCommutativeMagmaTerm2 n A) → (OpCommutativeMagmaTerm2 n A)) | (opOL2 x1 x2) := (opOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((CommutativeMagma A) → (CommutativeMagmaTerm → A)) | Co (opL x1 x2) := ((op Co) (evalB Co x1) (evalB Co x2)) def evalCl {A : Type} : ((CommutativeMagma A) → ((ClCommutativeMagmaTerm A) → A)) | Co (sing x1) := x1 | Co (opCl x1 x2) := ((op Co) (evalCl Co x1) (evalCl Co x2)) def evalOpB {A : Type} {n : ℕ} : ((CommutativeMagma A) → ((vector A n) → ((OpCommutativeMagmaTerm n) → A))) | Co vars (v x1) := (nth vars x1) | Co vars (opOL x1 x2) := ((op Co) (evalOpB Co vars x1) (evalOpB Co vars x2)) def evalOp {A : Type} {n : ℕ} : ((CommutativeMagma A) → ((vector A n) → ((OpCommutativeMagmaTerm2 n A) → A))) | Co vars (v2 x1) := (nth vars x1) | Co vars (sing2 x1) := x1 | Co vars (opOL2 x1 x2) := ((op Co) (evalOp Co vars x1) (evalOp Co vars x2)) def inductionB {P : (CommutativeMagmaTerm → Type)} : ((∀ (x1 x2 : CommutativeMagmaTerm) , ((P x1) → ((P x2) → (P (opL x1 x2))))) → (∀ (x : CommutativeMagmaTerm) , (P x))) | popl (opL x1 x2) := (popl _ _ (inductionB popl x1) (inductionB popl x2)) def inductionCl {A : Type} {P : ((ClCommutativeMagmaTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClCommutativeMagmaTerm A)) , ((P x1) → ((P x2) → (P (opCl x1 x2))))) → (∀ (x : (ClCommutativeMagmaTerm A)) , (P x)))) | psing popcl (sing x1) := (psing x1) | psing popcl (opCl x1 x2) := (popcl _ _ (inductionCl psing popcl x1) (inductionCl psing popcl x2)) def inductionOpB {n : ℕ} {P : ((OpCommutativeMagmaTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpCommutativeMagmaTerm n)) , ((P x1) → ((P x2) → (P (opOL x1 x2))))) → (∀ (x : (OpCommutativeMagmaTerm n)) , (P x)))) | pv popol (v x1) := (pv x1) | pv popol (opOL x1 x2) := (popol _ _ (inductionOpB pv popol x1) (inductionOpB pv popol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpCommutativeMagmaTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpCommutativeMagmaTerm2 n A)) , ((P x1) → ((P x2) → (P (opOL2 x1 x2))))) → (∀ (x : (OpCommutativeMagmaTerm2 n A)) , (P x))))) | pv2 psing2 popol2 (v2 x1) := (pv2 x1) | pv2 psing2 popol2 (sing2 x1) := (psing2 x1) | pv2 psing2 popol2 (opOL2 x1 x2) := (popol2 _ _ (inductionOp pv2 psing2 popol2 x1) (inductionOp pv2 psing2 popol2 x2)) def stageB : (CommutativeMagmaTerm → (Staged CommutativeMagmaTerm)) | (opL x1 x2) := (stage2 opL (codeLift2 opL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClCommutativeMagmaTerm A) → (Staged (ClCommutativeMagmaTerm A))) | (sing x1) := (Now (sing x1)) | (opCl x1 x2) := (stage2 opCl (codeLift2 opCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpCommutativeMagmaTerm n) → (Staged (OpCommutativeMagmaTerm n))) | (v x1) := (const (code (v x1))) | (opOL x1 x2) := (stage2 opOL (codeLift2 opOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpCommutativeMagmaTerm2 n A) → (Staged (OpCommutativeMagmaTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (opOL2 x1 x2) := (stage2 opOL2 (codeLift2 opOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (opT : ((Repr A) → ((Repr A) → (Repr A)))) end CommutativeMagma
02242d67b13f1c36a3da887c419e57cd145ad493
f1a12d4db0f46eee317d703e3336d33950a2fe7e
/dlo/dlo_qelim.lean
fca0c139d486c7ea2c183e17a746a9483576b0a8
[ "Apache-2.0" ]
permissive
avigad/qelim
bce89b79c717b7649860d41a41a37e37c982624f
b7d22864f1f0a2d21adad0f4fb3fc7ba665f8e60
refs/heads/master
1,584,548,938,232
1,526,773,708,000
1,526,773,708,000
134,967,693
2
0
null
null
null
null
UTF-8
Lean
false
false
7,987
lean
import .dlo variables {α β : Type} def dlo_qe_aux (as : list adlo) := -- (HZ) (H) := let prs := list.product (dlo_qe_lbs as) (dlo_qe_ubs as) in list_conj $ @list.map adlo (fm adlo) (@fm.atom adlo) (list.map (λ pr, (prod.fst pr <' prod.snd pr)) prs) def dlo_qe (β : Type) [atom_eq_type adlo β] (as : list adlo) : fm adlo := @ite (adlo.lt 0 0 ∈ as) (@list.decidable_mem adlo (atom_type.dec_eq _ β) (0 <' 0) as) _ ⊥' (@ite (list.allp is_b_atm as) (dec_allp _) _ (dlo_qe_aux as) (⊥') ) def dlo_qelim (β : Type) [atom_eq_type adlo β] : fm adlo → fm adlo := @lift_dnfeq_qe _ β _ (dlo_qe β) -- Q : Why doesn't `cases (dlo_dec_mem (0 <' 0) as)` simplify things here? lemma dlo_qe_qfree [HA : atom_eq_type adlo β] : ∀ (as : list adlo) (Has : allp (@atom_type.dep0 adlo β _) as), qfree (dlo_qe β as) := begin intros as Has, unfold dlo_qe, apply cases_ite, intro H, trivial, intro HM, apply cases_ite, intro Hlt, unfold dlo_qe_aux, simp, apply qfree_list_conj, intros x Hx, cases (list.exists_of_mem_map Hx) with y Hy, cases Hy with Hyl Hyr, rewrite Hyr, cases y, unfold function.comp, intro H, trivial end lemma btw_of_lt [dlo β] {m n} {bs : list β} (H : atom_type.val bs (m <' n)) : ∃ b, ((tval m bs < b) ∧ (b < tval n bs)) := begin cases (dlo.btw H) with b Hb, existsi b, apply Hb end #exit lemma is_b_atm_of [dlo β] : ∀ (a), (λ a', atom_type.dep0 β a' ∧ ¬atom_eq_type.solv0 β a' ∧ a' ≠ (0 <' 0)) a → is_b_atm a | (0 =' n ) h := begin exfalso, apply h^.elim_right^.elim_left, apply or.inl rfl end | (m =' 0 ) h := begin exfalso, apply h^.elim_right^.elim_left, apply or.inr rfl end | (m+1 =' n+1) h := begin exfalso, cases h^.elim_left with h h; cases h end | (0 <' 0 ) h := begin exfalso, apply h^.elim_right^.elim_right, refl end | (m+1 <' 0 ) h := begin existsi m, apply or.inl rfl end | (0 <' n+1) h := begin existsi n, apply or.inr rfl end | (m+1 <' n+1) h := begin exfalso, cases h^.elim_left with h h; cases h end lemma ex_high_lb_of_ex_lb [dlo β] {as : list adlo} (hlb : ∃ m, is_lb m as) (bs : list β) : ∃ k, (is_lb k as ∧ ∀ j, is_lb j as → dle j k bs) := begin cases hlb with m hm, have hi : list.map (λ n, tval n bs) (dlo_qe_lbs as) ≠ [], intro hc, have he := list.eq_nil_of_map_eq_nil hc, have hmm := mem_lbs_of_is_lb hm, rewrite he at hmm, cases hmm, cases (exists_maximum _ hi) with b hb, cases hb with hb1 hb2, cases (list.exists_of_mem_map hb1) with k hk, cases hk with hk1 hk2, existsi k, apply and.intro (is_lb_of_mem_lbs hk1), intros j hj, simp at hk2, unfold dle, rewrite eq.symm hk2, apply hb2, apply mem_map_of_mem, apply mem_lbs_of_is_lb hj end lemma ex_low_ub_of_ex_ub [dlo β] {as : list adlo} (hub : ∃ n, is_ub n as) (bs : list β) : ∃ k, (is_ub k as ∧ ∀ j, is_ub j as → dle k j bs) := begin cases hub with n hn, have hi : list.map (λ n, tval n bs) (dlo_qe_ubs as) ≠ [], intro hc, have he := list.eq_nil_of_map_eq_nil hc, have hnm := mem_ubs_of_is_ub hn, rewrite he at hnm, cases hnm, cases (exists_minimum _ hi) with b hb, cases hb with hb1 hb2, cases (list.exists_of_mem_map hb1) with k hk, cases hk with hk1 hk2, existsi k, apply and.intro (is_ub_of_mem_ubs hk1), intros j hj, simp at hk2, unfold dle, rewrite eq.symm hk2, apply hb2, apply mem_map_of_mem, apply mem_ubs_of_is_ub hj end lemma dlo_qe_is_dnf [HD : dlo β] : ∀ (as : list adlo), (∀ (a : adlo), a ∈ as → atom_type.dep0 β a ∧ ¬ atom_eq_type.solv0 β a) → qe_prsv β (dlo_qe β) as := begin intros as Has, unfold qe_prsv, intro bs, unfold dlo_qe, unfold dlo_qe_aux, simp, cases (@list.decidable_mem adlo (atom_type.dec_eq _ β) (0 <' 0) as) with Hc Hc, rewrite (exp_ite_eq_of_not), have HW : allp is_b_atm as := begin apply allp_of_allp is_b_atm_of, intros a' Ha', cases Has a' Ha' with Ha1' Ha2', apply and.intro Ha1', apply and.intro Ha2', intro HN, apply Hc, subst HN, apply Ha' end, clear Has, clear Hc, rewrite (exp_ite_eq_of), unfold function.comp, rewrite exp_I_list_conj, apply @classical.by_cases (∃ m, is_lb m as) ; intro Hlb, cases (ex_high_lb_of_ex_lb Hlb bs) with m Hm, clear Hlb, cases Hm with Hm1 Hm2, apply @classical.by_cases (∃ n, is_ub n as) ; intro Hub, cases (ex_low_ub_of_ex_ub Hub bs) with n Hn, clear Hub, cases Hn with Hn1 Hn2, apply @iff.trans _ (I (A' (m <' n)) bs), rewrite map_compose, apply iff.intro, intro HL, apply HL, apply @mem_map_of_mem _ _ (λ (x : ℕ × ℕ), I ((fm.atom ∘ λ (pr : ℕ × ℕ), pr.fst<' pr.snd) x) bs) _ (m,n), apply mem_product_of_mem_and_mem, apply mem_omap _ Hm1, refl, apply mem_omap _ Hn1, refl, intro HR, intros a Ha, cases (list.exists_of_mem_map Ha) with pr Hpr, cases Hpr with Hpr1 Hpr2, subst Hpr2, cases pr with x y, simp, simp at Ha, cases (list.exists_of_mem_map Ha) with xy Hxy, cases xy with x' y', simp at Hxy, cases Hxy with Hxy1 Hxy2, rewrite Hxy2, apply lt_of_le_of_lt (Hm2 _ _), apply lt_of_lt_of_le _ (Hn2 _ _), apply HR, have Hy := snd_mem_of_mem_product Hxy1, simp at Hy, apply is_ub_of_mem_ubs, apply Hy, have Hx := fst_mem_of_mem_product Hxy1, simp at Hx, apply is_lb_of_mem_lbs, apply Hx, apply iff.intro; intro H, cases (btw_of_lt H) with b Hb, cases Hb with Hb1 Hb2, existsi b, intros a Ha, cases (HW a Ha) with k Ha', cases Ha' with Ha' Ha'; subst Ha', unfold I, unfold interp, rewrite exp_val_lt, rewrite nth_dft_succ, rewrite nth_dft_head, apply lt_of_le_of_lt, apply (Hm2 k Ha), apply Hb1, unfold I, unfold interp, rewrite exp_val_lt, rewrite nth_dft_succ, rewrite nth_dft_head, apply lt_of_lt_of_le, apply Hb2, apply (Hn2 k Ha), cases H with b Hb, unfold I, unfold interp, have HE := (atom_type.decr_prsv (m+1 <' n+1) _ b bs), rewrite (exp_decr_lt (m+1) (n+1)) at HE, simp at HE, rewrite HE, clear HE, apply lt_trans, let Hbm := Hb _ Hm1, unfold I at Hbm, unfold interp at Hbm, apply Hbm, let Hbn := Hb _ Hn1, unfold I at Hbn, unfold interp at Hbn, apply Hbn, intro Hc', cases Hc' with Hc' Hc'; cases Hc', apply true_iff_true, rewrite (ubs_eq_nil_of_none_is_ub Hub), rewrite product_nil, simp, apply all_true_nil, cases (dlo.abv (tval m bs)) with u Hu, existsi u, intros a Ha, cases (HW a Ha) with k Ha', cases Ha' with Ha' Ha'; subst Ha', unfold I, unfold interp, rewrite exp_val_lt, rewrite nth_dft_succ, rewrite nth_dft_head, apply lt_of_le_of_lt, apply (Hm2 k Ha), apply Hu, exfalso, apply Hub, existsi k, apply Ha, apply @classical.by_cases (∃ n, is_ub n as) ; intro Hub, cases (ex_low_ub_of_ex_ub Hub bs) with n Hn, clear Hub, cases Hn with Hn1 Hn2, apply true_iff_true, rewrite (lbs_eq_nil_of_none_is_lb Hlb), simp, apply all_true_nil, cases (dlo.blw (tval n bs)) with l Hl, existsi l, intros a Ha, cases (HW a Ha) with k Ha', cases Ha' with Ha' Ha'; subst Ha', exfalso, apply Hlb, existsi k, apply Ha, unfold I, unfold interp, rewrite exp_val_lt, rewrite nth_dft_succ, rewrite nth_dft_head, apply lt_of_lt_of_le, apply Hl, apply (Hn2 k Ha), cases as with a, simp, unfold dlo_qe_lbs, unfold list.omap, unfold list.product, unfold list.map, apply true_iff_true, intros _ Hx, cases Hx, existsi (@dlo.inh β HD), trivial, cases (HW _ (or.inl rfl)) with k Hk, cases Hk with Hk Hk, exfalso, apply Hlb, existsi k, subst Hk, apply or.inl rfl, exfalso, apply Hub, existsi k, subst Hk, apply or.inl rfl, apply HW, apply Hc, rewrite exp_ite_eq_of, apply false_iff_false, intro h, apply h, intro h, cases h with b hb, apply (lt_irrefl b), apply (hb _ Hc), apply Hc end lemma dlo_qelim_prsv [dlo β] : ∀ (p : fm adlo) (bs : list β), I (dlo_qelim β p) bs ↔ I p bs := ldeq_prsv (dlo_qe β) dlo_qe_qfree dlo_qe_is_dnf
af6868c3e6fb7b1fd0f0a35350867c8d3a998e17
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/src/Init/Control/Except.lean
01554eb2d5f039bb411709916c06304276857290
[ "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
6,307
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jared Roesch, Sebastian Ullrich The Except monad transformer. -/ prelude import Init.Control.Basic import Init.Control.Id import Init.Coe namespace Except variable {ε : Type u} @[inline] protected def pure (a : α) : Except ε α := Except.ok a @[inline] protected def map (f : α → β) : Except ε α → Except ε β | Except.error err => Except.error err | Except.ok v => Except.ok <| f v @[simp] theorem map_id : Except.map (ε := ε) (α := α) (β := α) id = id := by apply funext intro e simp [Except.map]; cases e <;> rfl @[inline] protected def mapError (f : ε → ε') : Except ε α → Except ε' α | Except.error err => Except.error <| f err | Except.ok v => Except.ok v @[inline] protected def bind (ma : Except ε α) (f : α → Except ε β) : Except ε β := match ma with | Except.error err => Except.error err | Except.ok v => f v @[inline] protected def toBool : Except ε α → Bool | Except.ok _ => true | Except.error _ => false @[inline] protected def toOption : Except ε α → Option α | Except.ok a => some a | Except.error _ => none @[inline] protected def tryCatch (ma : Except ε α) (handle : ε → Except ε α) : Except ε α := match ma with | Except.ok a => Except.ok a | Except.error e => handle e def orElseLazy (x : Except ε α) (y : Unit → Except ε α) : Except ε α := match x with | Except.ok a => Except.ok a | Except.error e => y () instance : Monad (Except ε) where pure := Except.pure bind := Except.bind map := Except.map end Except def ExceptT (ε : Type u) (m : Type u → Type v) (α : Type u) : Type v := m (Except ε α) @[inline] def ExceptT.mk {ε : Type u} {m : Type u → Type v} {α : Type u} (x : m (Except ε α)) : ExceptT ε m α := x @[inline] def ExceptT.run {ε : Type u} {m : Type u → Type v} {α : Type u} (x : ExceptT ε m α) : m (Except ε α) := x namespace ExceptT variable {ε : Type u} {m : Type u → Type v} [Monad m] @[inline] protected def pure {α : Type u} (a : α) : ExceptT ε m α := ExceptT.mk <| pure (Except.ok a) @[inline] protected def bindCont {α β : Type u} (f : α → ExceptT ε m β) : Except ε α → m (Except ε β) | Except.ok a => f a | Except.error e => pure (Except.error e) @[inline] protected def bind {α β : Type u} (ma : ExceptT ε m α) (f : α → ExceptT ε m β) : ExceptT ε m β := ExceptT.mk <| ma >>= ExceptT.bindCont f @[inline] protected def map {α β : Type u} (f : α → β) (x : ExceptT ε m α) : ExceptT ε m β := ExceptT.mk <| x >>= fun a => match a with | (Except.ok a) => pure <| Except.ok (f a) | (Except.error e) => pure <| Except.error e @[inline] protected def lift {α : Type u} (t : m α) : ExceptT ε m α := ExceptT.mk <| Except.ok <$> t instance : MonadLift (Except ε) (ExceptT ε m) := ⟨fun e => ExceptT.mk <| pure e⟩ instance : MonadLift m (ExceptT ε m) := ⟨ExceptT.lift⟩ @[inline] protected def tryCatch {α : Type u} (ma : ExceptT ε m α) (handle : ε → ExceptT ε m α) : ExceptT ε m α := ExceptT.mk <| ma >>= fun res => match res with | Except.ok a => pure (Except.ok a) | Except.error e => (handle e) instance : MonadFunctor m (ExceptT ε m) := ⟨fun f x => f x⟩ instance : Monad (ExceptT ε m) where pure := ExceptT.pure bind := ExceptT.bind map := ExceptT.map @[inline] protected def adapt {ε' α : Type u} (f : ε → ε') : ExceptT ε m α → ExceptT ε' m α := fun x => ExceptT.mk <| Except.mapError f <$> x end ExceptT instance (m : Type u → Type v) (ε₁ : Type u) (ε₂ : Type u) [Monad m] [MonadExceptOf ε₁ m] : MonadExceptOf ε₁ (ExceptT ε₂ m) where throw e := ExceptT.mk <| throwThe ε₁ e tryCatch x handle := ExceptT.mk <| tryCatchThe ε₁ x handle instance (m : Type u → Type v) (ε : Type u) [Monad m] : MonadExceptOf ε (ExceptT ε m) where throw e := ExceptT.mk <| pure (Except.error e) tryCatch := ExceptT.tryCatch instance [Monad m] [Inhabited ε] : Inhabited (ExceptT ε m α) where default := throw arbitrary instance (ε) : MonadExceptOf ε (Except ε) where throw := Except.error tryCatch := Except.tryCatch namespace MonadExcept variable {ε : Type u} {m : Type v → Type w} /-- Alternative orelse operator that allows to select which exception should be used. The default is to use the first exception since the standard `orelse` uses the second. -/ @[inline] def orelse' [MonadExcept ε m] {α : Type v} (t₁ t₂ : m α) (useFirstEx := true) : m α := tryCatch t₁ fun e₁ => tryCatch t₂ fun e₂ => throw (if useFirstEx then e₁ else e₂) end MonadExcept @[inline] def observing {ε α : Type u} {m : Type u → Type v} [Monad m] [MonadExcept ε m] (x : m α) : m (Except ε α) := tryCatch (do let a ← x; pure (Except.ok a)) (fun ex => pure (Except.error ex)) instance (ε : Type u) (m : Type u → Type v) [Monad m] : MonadControl m (ExceptT ε m) where stM := Except ε liftWith f := liftM <| f fun x => x.run restoreM x := x class MonadFinally (m : Type u → Type v) where tryFinally' {α β} : m α → (Option α → m β) → m (α × β) export MonadFinally (tryFinally') /-- Execute `x` and then execute `finalizer` even if `x` threw an exception -/ @[inline] def tryFinally {m : Type u → Type v} {α β : Type u} [MonadFinally m] [Functor m] (x : m α) (finalizer : m β) : m α := let y := tryFinally' x (fun _ => finalizer) (·.1) <$> y instance Id.finally : MonadFinally Id where tryFinally' := fun x h => let a := x let b := h (some x) pure (a, b) instance ExceptT.finally {m : Type u → Type v} {ε : Type u} [MonadFinally m] [Monad m] : MonadFinally (ExceptT ε m) where tryFinally' := fun x h => ExceptT.mk do let r ← tryFinally' x fun e? => match e? with | some (Except.ok a) => h (some a) | _ => h none match r with | (Except.ok a, Except.ok b) => pure (Except.ok (a, b)) | (_, Except.error e) => pure (Except.error e) -- second error has precedence | (Except.error e, _) => pure (Except.error e)
7cf589648eb4e37340d913b7066fd3addac69db8
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/converter/interactive.lean
ab8c4d54cc7f505e8bba9be6d9e6c89cf797a0d1
[ "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
4,298
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Lucas Allen, Keeley Hoek, Leonardo de Moura Converter monad for building simplifiers. -/ import tactic.core import tactic.converter.old_conv namespace old_conv meta def save_info (p : pos) : old_conv unit := λ r lhs, do ts ← tactic.read, -- TODO(Leo): include context tactic.save_info_thunk p (λ _, ts.format_expr lhs) >> return ⟨(), lhs, none⟩ meta def step {α : Type} (c : old_conv α) : old_conv unit := c >> return () meta def istep {α : Type} (line0 col0 line col : nat) (c : old_conv α) : old_conv unit := λ r lhs ts, (@scope_trace _ line col (λ _, (c >> return ()) r lhs ts)).clamp_pos line0 line col meta def execute (c : old_conv unit) : tactic unit := conversion c namespace interactive open lean.parser open interactive open interactive.types meta def itactic : Type := old_conv unit meta def whnf : old_conv unit := old_conv.whnf meta def dsimp : old_conv unit := old_conv.dsimp meta def trace_state : old_conv unit := old_conv.trace_lhs meta def change (p : parse texpr) : old_conv unit := old_conv.change p meta def find (p : parse lean.parser.pexpr) (c : itactic) : old_conv unit := λ r lhs, do pat ← tactic.pexpr_to_pattern p, s ← simp_lemmas.mk_default, -- to be able to use congruence lemmas @[congr] (found, new_lhs, pr) ← tactic.ext_simplify_core ff {zeta := ff, beta := ff, single_pass := tt, eta := ff, proj := ff} s (λ u, return u) (λ found s r p e, do guard (not found), matched ← (tactic.match_pattern pat e >> return tt) <|> return ff, guard matched, ⟨u, new_e, pr⟩ ← c r e, return (tt, new_e, pr, ff)) (λ a s r p e, tactic.failed) r lhs, if not found then tactic.fail "find converter failed, pattern was not found" else return ⟨(), new_lhs, some pr⟩ end interactive end old_conv namespace conv open tactic meta def replace_lhs (tac : expr → tactic (expr × expr)) : conv unit := do (e, pf) ← lhs >>= tac, update_lhs e pf -- Attempts to discharge the equality of the current `lhs` using `tac`, -- moving to the next goal on success. meta def discharge_eq_lhs (tac : tactic unit) : conv unit := do pf ← lock_tactic_state (do m ← lhs >>= mk_meta_var, set_goals [m], tac >> done, instantiate_mvars m), congr, the_rhs ← rhs, update_lhs the_rhs pf, skip, skip namespace interactive open interactive open tactic.interactive (rw_rules) /-- The `conv` tactic provides a `conv` within a `conv`. It allows the user to return to a previous state of the outer conv block to continue editing an expression without having to start a new conv block. -/ protected meta def conv (t : conv.interactive.itactic) : conv unit := do transitivity, a :: rest ← get_goals, set_goals [a], t, all_goals reflexivity, set_goals rest meta def erw (q : parse rw_rules) (cfg : rewrite_cfg := {md := semireducible}) : conv unit := rw q cfg open interactive.types /-- `guard_target t` fails if the target of the conv goal is not `t`. We use this tactic for writing tests. -/ meta def guard_target (p : parse texpr) : conv unit := do `(%%t = _) ← target, tactic.interactive.guard_expr_eq t p end interactive end conv namespace tactic namespace interactive open lean open lean.parser open interactive local postfix `?`:9001 := optional meta def old_conv (c : old_conv.interactive.itactic) : tactic unit := do t ← target, (new_t, pr) ← c.to_tactic `eq t, replace_target new_t pr meta def find (p : parse lean.parser.pexpr) (c : old_conv.interactive.itactic) : tactic unit := old_conv $ old_conv.interactive.find p c meta def conv_lhs (loc : parse (tk "at" *> ident)?) (p : parse (tk "in" *> parser.pexpr)?) (c : conv.interactive.itactic) : tactic unit := conv loc p (conv.interactive.to_lhs >> c) meta def conv_rhs (loc : parse (tk "at" *> ident)?) (p : parse (tk "in" *> parser.pexpr)?) (c : conv.interactive.itactic) : tactic unit := conv loc p (conv.interactive.to_rhs >> c) end interactive end tactic
c45940047c9e1816101c2dbf38bd78c6cc28ed7f
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/script/reformat.lean
635443bfbba6d87cbeb65cf1ed24619c887837cf
[ "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
2,967
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import Lean open Lean Elab PrettyPrinter partial def getCommands (cmds : Syntax) : StateT (Array Syntax) Id Unit := do if cmds.getKind == nullKind || cmds.getKind == ``Parser.Module.header then for cmd in cmds.getArgs do getCommands cmd else modify (·.push cmds) partial def reprintCore : Syntax → Option Format | Syntax.missing => none | Syntax.atom _ val => val.trim | Syntax.ident _ rawVal _ _ => rawVal.toString | Syntax.node _ _ args => match args.toList.filterMap reprintCore with | [] => none | [arg] => arg | args => Format.group <| Format.nest 2 <| Format.line.joinSep args def reprint (stx : Syntax) : Format := reprintCore stx |>.getD "" def printCommands (cmds : Syntax) : CoreM Unit := do for cmd in getCommands cmds |>.run #[] |>.2 do try IO.println (← ppCommand ⟨cmd⟩).pretty catch e => IO.println f!"/-\ncannot print: {← e.toMessageData.format}\n{reprint cmd}\n-/" def failWith (msg : String) (exitCode : UInt8 := 1) : IO α := do (← IO.getStderr).putStrLn msg IO.Process.exit exitCode structure CommandSyntax where env : Environment currNamespace : Name := Name.anonymous openDecls : List OpenDecl := [] stx : Syntax def parseModule (input : String) (fileName : String) (opts : Options := {}) (trustLevel : UInt32 := 1024) : IO <| Array CommandSyntax := do let mainModuleName := Name.anonymous -- FIXME let inputCtx := Parser.mkInputContext input fileName let (header, parserState, messages) ← Parser.parseHeader inputCtx let (env, messages) ← processHeader header opts messages inputCtx trustLevel let env := env.setMainModule mainModuleName let env0 := env let s ← IO.processCommands inputCtx parserState { Command.mkState env messages opts with infoState := { enabled := true } } let topLevelCmds : Array CommandSyntax ← s.commandState.infoState.trees.toArray.mapM fun | InfoTree.context { env, currNamespace, openDecls, .. } (InfoTree.node (Info.ofCommandInfo {stx, ..}) _) => pure {env, currNamespace, openDecls, stx} | _ => failWith "unknown info tree" return #[{ env := env0, stx := header : CommandSyntax }] ++ topLevelCmds unsafe def main (args : List String) : IO Unit := do let [fileName] := args | failWith "Usage: reformat file" initSearchPath (← findSysroot) let input ← IO.FS.readFile fileName let moduleStx ← parseModule input fileName let leadingUpdated := mkNullNode (moduleStx.map (·.stx)) |>.updateLeading |>.getArgs let mut first := true for {env, currNamespace, openDecls, ..} in moduleStx, stx in leadingUpdated do if first then first := false else IO.print "\n" let _ ← printCommands stx |>.toIO {fileName, fileMap := FileMap.ofString input, currNamespace, openDecls} {env}
c99264fe0bbf08ba71ef1eefff2fd30f89dd0bfe
af6139dd14451ab8f69cf181cf3a20f22bd699be
/library/init/data/option/basic.lean
3cb249209792a0a8baec7c967914e0c64a310157
[ "Apache-2.0" ]
permissive
gitter-badger/lean-1
1cca01252d3113faa45681b6a00e1b5e3a0f6203
5c7ade4ee4f1cdf5028eabc5db949479d6737c85
refs/heads/master
1,611,425,383,521
1,487,871,140,000
1,487,871,140,000
82,995,612
0
0
null
1,487,905,618,000
1,487,905,618,000
null
UTF-8
Lean
false
false
3,339
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.logic init.category open decidable universes u v namespace option def to_monad {m : Type → Type} [monad m] [alternative m] {A} : option A → m A | none := failure | (some a) := return a def get_or_else {α : Type u} : option α → α → α | (some x) _ := x | none e := e def is_some {α : Type u} : option α → bool | (some _) := tt | none := ff def is_none {α : Type u} : option α → bool | (some _) := ff | none := tt end option instance (α : Type u) : inhabited (option α) := ⟨none⟩ instance {α : Type u} [d : decidable_eq α] : decidable_eq (option α) | none none := is_true rfl | none (some v₂) := is_false (λ h, option.no_confusion h) | (some v₁) none := is_false (λ h, option.no_confusion h) | (some v₁) (some v₂) := match (d v₁ v₂) with | (is_true e) := is_true (congr_arg (@some α) e) | (is_false n) := is_false (λ h, option.no_confusion h (λ e, absurd e n)) end @[inline] def option_fmap {α : Type u} {β : Type v} (f : α → β) : option α → option β | none := none | (some a) := some (f a) @[inline] def option_bind {α : Type u} {β : Type v} : option α → (α → option β) → option β | none b := none | (some a) b := b a instance : monad option := {map := @option_fmap, ret := @some, bind := @option_bind} def option_orelse {α : Type u} : option α → option α → option α | (some a) o := some a | none (some a) := some a | none none := none instance : alternative option := alternative.mk @option_fmap @some (@fapp _ _) @none @option_orelse def option_t (m : Type u → Type v) [monad m] (α : Type u) : Type v := m (option α) @[inline] def option_t_fmap {m : Type u → Type v} [monad m] {α β : Type u} (f : α → β) (e : option_t m α) : option_t m β := show m (option β), from do o ← e, match o with | none := return none | (some a) := return (some (f a)) end @[inline] def option_t_bind {m : Type u → Type v} [monad m] {α β : Type u} (a : option_t m α) (b : α → option_t m β) : option_t m β := show m (option β), from do o ← a, match o with | none := return none | (some a) := b a end @[inline] def option_t_return {m : Type u → Type v} [monad m] {α : Type u} (a : α) : option_t m α := show m (option α), from return (some a) instance {m : Type u → Type v} [monad m] : monad (option_t m) := {map := @option_t_fmap m _, ret := @option_t_return m _, bind := @option_t_bind m _} def option_t_orelse {m : Type u → Type v} [monad m] {α : Type u} (a : option_t m α) (b : option_t m α) : option_t m α := show m (option α), from do o ← a, match o with | none := b | (some v) := return (some v) end def option_t_fail {m : Type u → Type v} [monad m] {α : Type u} : option_t m α := show m (option α), from return none instance {m : Type u → Type v} [monad m] : alternative (option_t m) := {map := @option_t_fmap m _, pure := @option_t_return m _, seq := @fapp (option_t m) (@option_t.monad m _), failure := @option_t_fail m _, orelse := @option_t_orelse m _}
9840923d5e1507b903f2017cd2efe6928577f090
b815abf92ce063fe0d1fabf5b42da483552aa3e8
/library/init/meta/declaration.lean
e9a7b9a4c5f8a41ce32e5c7fb0a51a387032d602
[ "Apache-2.0" ]
permissive
yodalee/lean
a368d842df12c63e9f79414ed7bbee805b9001ef
317989bf9ef6ae1dec7488c2363dbfcdc16e0756
refs/heads/master
1,610,551,176,860
1,481,430,138,000
1,481,646,441,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,882
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.expr init.meta.name init.meta.task /- Reducibility hints are used in the convertibility checker. When trying to solve a constraint such a (f ...) =?= (g ...) where f and g are definitions, the checker has to decide which one will be unfolded. If f (g) is opaque, then g (f) is unfolded if it is also not marked as opaque, Else if f (g) is abbrev, then f (g) is unfolded if g (f) is also not marked as abbrev, Else if f and g are regular, then we unfold the one with the biggest definitional height. Otherwise both are unfolded. The arguments of the `regular` constructor are: the definitional height and the flag `self_opt`. The definitional height is by default computed by the kernel. It only takes into account other regular definitions used in a definition. When creating declarations using meta-programming, we can specify the definitional depth manually. For definitions marked as regular, we also have a hint for constraints such as (f a) =?= (f b) if self_opt == true, then checker will first try to solve (a =?= b), only if it fails, it unfolds f. Remark: the hint only affects performance. None of the hints prevent the kernel from unfolding a declaration during type checking. Remark: the reducibility_hints are not related to the attributes: reducible/irrelevance/semireducible. These attributes are used by the elaborator. The reducibility_hints are used by the kernel (and elaborator). Moreover, the reducibility_hints cannot be changed after a declaration is added to the kernel. -/ inductive reducibility_hints | opaque : reducibility_hints | abbrev : reducibility_hints | regular : nat → bool → reducibility_hints /- Reflect a C++ declaration object. The VM replaces it with the C++ implementation. -/ meta inductive declaration /- definition: name, list universe parameters, type, value, is_trusted -/ | defn : name → list name → expr → expr → reducibility_hints → bool → declaration /- theorem: name, list universe parameters, type, value (remark: theorems are always trusted) -/ | thm : name → list name → expr → task expr → declaration /- constant assumption: name, list universe parameters, type, is_trusted -/ | cnst : name → list name → expr → bool → declaration /- axiom : name → list universe parameters, type (remark: axioms are always trusted) -/ | ax : name → list name → expr → declaration meta def declaration.to_name : declaration → name | (declaration.defn n ls t v h tr) := n | (declaration.thm n ls t v) := n | (declaration.cnst n ls t tr) := n | (declaration.ax n ls t) := n meta def declaration.univ_params : declaration → list name | (declaration.defn n ls t v h tr) := ls | (declaration.thm n ls t v) := ls | (declaration.cnst n ls t tr) := ls | (declaration.ax n ls t) := ls meta def declaration.type : declaration → expr | (declaration.defn n ls t v h tr) := t | (declaration.thm n ls t v) := t | (declaration.cnst n ls t tr) := t | (declaration.ax n ls t) := t meta def declaration.update_type : declaration → expr → declaration | (declaration.defn n ls t v h tr) new_t := declaration.defn n ls new_t v h tr | (declaration.thm n ls t v) new_t := declaration.thm n ls new_t v | (declaration.cnst n ls t tr) new_t := declaration.cnst n ls new_t tr | (declaration.ax n ls t) new_t := declaration.ax n ls new_t meta def declaration.update_name : declaration → name → declaration | (declaration.defn n ls t v h tr) new_n := declaration.defn new_n ls t v h tr | (declaration.thm n ls t v) new_n := declaration.thm new_n ls t v | (declaration.cnst n ls t tr) new_n := declaration.cnst new_n ls t tr | (declaration.ax n ls t) new_n := declaration.ax new_n ls t meta def declaration.update_value : declaration → expr → declaration | (declaration.defn n ls t v h tr) new_v := declaration.defn n ls t new_v h tr | (declaration.thm n ls t v) new_v := declaration.thm n ls t (task.pure new_v) | d new_v := d meta def declaration.to_definition : declaration → declaration | (declaration.cnst n ls t tr) := declaration.defn n ls t (default expr) reducibility_hints.abbrev tr | (declaration.ax n ls t) := declaration.thm n ls t (task.pure (default expr)) | d := d /- Instantiate a universe polymorphic declaration type with the given universes. -/ meta constant declaration.instantiate_type_univ_params : declaration → list level → option expr /- Instantiate a universe polymorphic declaration value with the given universes. -/ meta constant declaration.instantiate_value_univ_params : declaration → list level → option expr
954555312ff453abedc37c115f1690cae621a6d3
f618aea02cb4104ad34ecf3b9713065cc0d06103
/src/data/real/ennreal.lean
214df344530fd77d228212552f2223dcf59865f2
[ "Apache-2.0" ]
permissive
joehendrix/mathlib
84b6603f6be88a7e4d62f5b1b0cbb523bb82b9a5
c15eab34ad754f9ecd738525cb8b5a870e834ddc
refs/heads/master
1,589,606,591,630
1,555,946,393,000
1,555,946,393,000
182,813,854
0
0
null
1,555,946,309,000
1,555,946,308,000
null
UTF-8
Lean
false
false
26,832
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 Extended non-negative reals -/ import data.real.nnreal order.bounds tactic.norm_num noncomputable theory open classical set lattice local attribute [instance] prop_decidable local attribute [instance, priority 0] nat.cast_coe local attribute [instance, priority 0] rat.cast_coe variables {α : Type*} {β : Type*} /-- The extended nonnegative real numbers. This is usually denoted [0, ∞], and is relevant as the codomain of a measure. -/ def ennreal := with_top nnreal local notation `∞` := (⊤ : ennreal) namespace ennreal variables {a b c d : ennreal} {r p q : nnreal} instance : canonically_ordered_comm_semiring ennreal := by unfold ennreal; apply_instance instance : decidable_linear_order ennreal := by unfold ennreal; apply_instance instance : complete_linear_order ennreal := by unfold ennreal; apply_instance instance : inhabited ennreal := ⟨0⟩ instance : densely_ordered ennreal := with_top.densely_ordered instance : has_coe nnreal ennreal := ⟨ option.some ⟩ lemma none_eq_top : (none : ennreal) = (⊤ : ennreal) := rfl lemma some_eq_coe (a : nnreal) : (some a : ennreal) = (↑a : ennreal) := rfl /-- `to_nnreal x` returns `x` if it is real, otherwise 0. -/ protected def to_nnreal : ennreal → nnreal | (some r) := r | none := 0 /-- `to_real x` returns `x` if it is real, `0` otherwise. -/ protected def to_real (a : ennreal) : real := coe (a.to_nnreal) /-- `of_real x` returns `x` if it is nonnegative, `0` otherwise. -/ protected def of_real (r : real) : ennreal := coe (nnreal.of_real r) @[simp] lemma to_nnreal_coe : (r : ennreal).to_nnreal = r := rfl @[simp] lemma coe_to_nnreal : ∀{a:ennreal}, a ≠ ∞ → ↑(a.to_nnreal) = a | (some r) h := rfl | none h := (h rfl).elim @[simp] lemma of_real_to_real {a : ennreal} (h : a ≠ ∞) : ennreal.of_real (a.to_real) = a := by simp [ennreal.to_real, ennreal.of_real, h] @[simp] lemma to_real_of_real {r : real} (h : 0 ≤ r) : ennreal.to_real (ennreal.of_real r) = r := by simp [ennreal.to_real, ennreal.of_real, nnreal.coe_of_real _ h] lemma coe_to_nnreal_le_self : ∀{a:ennreal}, ↑(a.to_nnreal) ≤ a | (some r) := by rw [some_eq_coe, to_nnreal_coe]; exact le_refl _ | none := le_top @[simp] lemma coe_zero : ↑(0 : nnreal) = (0 : ennreal) := rfl @[simp] lemma coe_one : ↑(1 : nnreal) = (1 : ennreal) := rfl @[simp] lemma to_real_nonneg {a : ennreal} : 0 ≤ a.to_real := by simp [ennreal.to_real] @[simp] lemma top_to_nnreal : ∞.to_nnreal = 0 := rfl @[simp] lemma top_to_real : ∞.to_real = 0 := rfl @[simp] lemma zero_to_nnreal : (0 : ennreal).to_nnreal = 0 := rfl @[simp] lemma zero_to_real : (0 : ennreal).to_real = 0 := rfl @[simp] lemma of_real_zero : ennreal.of_real (0 : ℝ) = 0 := by simp [ennreal.of_real]; refl @[simp] lemma of_real_one : ennreal.of_real (1 : ℝ) = (1 : ennreal) := by simp [ennreal.of_real] lemma forall_ennreal {p : ennreal → Prop} : (∀a, p a) ↔ (∀r:nnreal, p r) ∧ p ∞ := ⟨assume h, ⟨assume r, h _, h _⟩, assume ⟨h₁, h₂⟩ a, match a with some r := h₁ _ | none := h₂ end⟩ lemma to_nnreal_eq_zero_iff (x : ennreal) : x.to_nnreal = 0 ↔ x = 0 ∨ x = ⊤ := ⟨begin cases x, { simp [none_eq_top] }, { have A : some (0:nnreal) = (0:ennreal) := rfl, simp [ennreal.to_nnreal, A] {contextual := tt} } end, by intro h; cases h; simp [h]⟩ lemma to_real_eq_zero_iff (x : ennreal) : x.to_real = 0 ↔ x = 0 ∨ x = ⊤ := by simp [ennreal.to_real, to_nnreal_eq_zero_iff] @[simp] lemma coe_ne_top : (r : ennreal) ≠ ∞ := with_top.coe_ne_top @[simp] lemma top_ne_coe : ∞ ≠ (r : ennreal) := with_top.top_ne_coe @[simp] lemma of_real_ne_top {r : ℝ} : ennreal.of_real r ≠ ∞ := by simp [ennreal.of_real] @[simp] lemma top_ne_of_real {r : ℝ} : ∞ ≠ ennreal.of_real r := by simp [ennreal.of_real] @[simp] lemma zero_ne_top : 0 ≠ ∞ := coe_ne_top @[simp] lemma top_ne_zero : ∞ ≠ 0 := top_ne_coe @[simp] lemma one_ne_top : 1 ≠ ∞ := coe_ne_top @[simp] lemma top_ne_one : ∞ ≠ 1 := top_ne_coe @[simp] lemma coe_eq_coe : (↑r : ennreal) = ↑q ↔ r = q := with_top.coe_eq_coe @[simp] lemma coe_le_coe : (↑r : ennreal) ≤ ↑q ↔ r ≤ q := with_top.coe_le_coe @[simp] lemma coe_lt_coe : (↑r : ennreal) < ↑q ↔ r < q := with_top.coe_lt_coe @[simp] lemma coe_eq_zero : (↑r : ennreal) = 0 ↔ r = 0 := coe_eq_coe @[simp] lemma zero_eq_coe : 0 = (↑r : ennreal) ↔ 0 = r := coe_eq_coe @[simp] lemma coe_eq_one : (↑r : ennreal) = 1 ↔ r = 1 := coe_eq_coe @[simp] lemma one_eq_coe : 1 = (↑r : ennreal) ↔ 1 = r := coe_eq_coe @[simp] lemma coe_nonneg : 0 ≤ (↑r : ennreal) ↔ 0 ≤ r := coe_le_coe @[simp] lemma coe_pos : 0 < (↑r : ennreal) ↔ 0 < r := coe_lt_coe @[simp] lemma coe_add : ↑(r + p) = (r + p : ennreal) := with_top.coe_add @[simp] lemma coe_mul : ↑(r * p) = (r * p : ennreal) := with_top.coe_mul @[simp] lemma coe_bit0 : (↑(bit0 r) : ennreal) = bit0 r := coe_add @[simp] lemma coe_bit1 : (↑(bit1 r) : ennreal) = bit1 r := by simp [bit1] @[simp] lemma add_top : a + ∞ = ∞ := with_top.add_top @[simp] lemma top_add : ∞ + a = ∞ := with_top.top_add instance : is_semiring_hom (coe : nnreal → ennreal) := by refine_struct {..}; simp lemma add_eq_top : a + b = ∞ ↔ a = ∞ ∨ b = ∞ := with_top.add_eq_top _ _ lemma add_lt_top : a + b < ∞ ↔ a < ∞ ∧ b < ∞ := with_top.add_lt_top _ _ lemma to_nnreal_add {r₁ r₂ : ennreal} (h₁ : r₁ < ⊤) (h₂ : r₂ < ⊤) : (r₁ + r₂).to_nnreal = r₁.to_nnreal + r₂.to_nnreal := begin rw [← coe_eq_coe, coe_add, coe_to_nnreal, coe_to_nnreal, coe_to_nnreal]; apply @ne_top_of_lt ennreal _ _ ⊤, exact h₂, exact h₁, exact add_lt_top.2 ⟨h₁, h₂⟩ end /- rw has trouble with the generic lt_top_iff_ne_top and bot_lt_iff_ne_bot (contrary to erw). This is solved with the next lemmas -/ protected lemma lt_top_iff_ne_top : a < ∞ ↔ a ≠ ∞ := lt_top_iff_ne_top protected lemma bot_lt_iff_ne_bot : 0 < a ↔ a ≠ 0 := bot_lt_iff_ne_bot lemma mul_top : a * ∞ = (if a = 0 then 0 else ∞) := begin split_ifs, { simp [h] }, { exact with_top.mul_top h } end lemma top_mul : ∞ * a = (if a = 0 then 0 else ∞) := begin split_ifs, { simp [h] }, { exact with_top.top_mul h } end @[simp] lemma top_mul_top : ∞ * ∞ = ∞ := with_top.top_mul_top lemma mul_eq_top {a b : ennreal} : a * b = ⊤ ↔ (a ≠ 0 ∧ b = ⊤) ∨ (a = ⊤ ∧ b ≠ 0) := with_top.mul_eq_top_iff lemma mul_lt_top {a b : ennreal} : a < ⊤ → b < ⊤ → a * b < ⊤ := by simp [ennreal.lt_top_iff_ne_top, (≠), mul_eq_top] {contextual := tt} @[simp] lemma coe_finset_sum {s : finset α} {f : α → nnreal} : ↑(s.sum f) = (s.sum (λa, f a) : ennreal) := (finset.sum_hom coe).symm @[simp] lemma coe_finset_prod {s : finset α} {f : α → nnreal} : ↑(s.prod f) = (s.prod (λa, f a) : ennreal) := (finset.prod_hom coe).symm @[simp] lemma bot_eq_zero : (⊥ : ennreal) = 0 := rfl section order @[simp] lemma coe_lt_top : coe r < ∞ := with_top.coe_lt_top r @[simp] lemma not_top_le_coe : ¬ (⊤:ennreal) ≤ ↑r := with_top.not_top_le_coe r @[simp] lemma zero_lt_coe_iff : 0 < (↑p : ennreal) ↔ 0 < p := coe_lt_coe @[simp] lemma one_le_coe_iff : (1:ennreal) ≤ ↑r ↔ 1 ≤ r := coe_le_coe @[simp] lemma coe_le_one_iff : ↑r ≤ (1:ennreal) ↔ r ≤ 1 := coe_le_coe @[simp] lemma coe_lt_one_iff : (↑p : ennreal) < 1 ↔ p < 1 := coe_lt_coe @[simp] lemma one_lt_zero_iff : 1 < (↑p : ennreal) ↔ 1 < p := coe_lt_coe @[simp] lemma coe_nat (n : nat) : ((n : nnreal) : ennreal) = n := with_top.coe_nat n @[simp] lemma nat_ne_top (n : nat) : (n : ennreal) ≠ ⊤ := with_top.nat_ne_top n @[simp] lemma top_ne_nat (n : nat) : (⊤ : ennreal) ≠ n := with_top.top_ne_nat n lemma le_coe_iff : a ≤ ↑r ↔ (∃p:nnreal, a = p ∧ p ≤ r) := with_top.le_coe_iff r a lemma coe_le_iff : ↑r ≤ a ↔ (∀p:nnreal, a = p → r ≤ p) := with_top.coe_le_iff r a lemma lt_iff_exists_coe : a < b ↔ (∃p:nnreal, a = p ∧ ↑p < b) := with_top.lt_iff_exists_coe a b -- TODO: move to canonically ordered semiring ... protected lemma zero_lt_one : 0 < (1 : ennreal) := zero_lt_coe_iff.mpr zero_lt_one @[simp] lemma not_lt_zero : ¬ a < 0 := by simp lemma add_lt_add_iff_left : a < ⊤ → (a + c < a + b ↔ c < b) := with_top.add_lt_add_iff_left lemma add_lt_add_iff_right : a < ⊤ → (c + a < b + a ↔ c < b) := with_top.add_lt_add_iff_right lemma lt_add_right (ha : a < ⊤) (hb : 0 < b) : a < a + b := by rwa [← add_lt_add_iff_left ha, add_zero] at hb lemma le_of_forall_epsilon_le : ∀{a b : ennreal}, (∀ε:nnreal, ε > 0 → b < ∞ → a ≤ b + ε) → a ≤ b | a none h := le_top | none (some a) h := have (⊤:ennreal) ≤ ↑a + ↑(1:nnreal), from h 1 zero_lt_one coe_lt_top, by rw [← coe_add] at this; exact (not_top_le_coe this).elim | (some a) (some b) h := by simp only [none_eq_top, some_eq_coe, coe_add.symm, coe_le_coe, coe_lt_top, true_implies_iff] at *; exact nnreal.le_of_forall_epsilon_le h lemma lt_iff_exists_rat_btwn : a < b ↔ (∃q:ℚ, 0 ≤ q ∧ a < nnreal.of_real q ∧ (nnreal.of_real q:ennreal) < b) := ⟨λ h, begin rcases lt_iff_exists_coe.1 h with ⟨p, rfl, _⟩, rcases dense h with ⟨c, pc, cb⟩, rcases lt_iff_exists_coe.1 cb with ⟨r, rfl, _⟩, rcases (nnreal.lt_iff_exists_rat_btwn _ _).1 (coe_lt_coe.1 pc) with ⟨q, hq0, pq, qr⟩, exact ⟨q, hq0, coe_lt_coe.2 pq, lt_trans (coe_lt_coe.2 qr) cb⟩ end, λ ⟨q, q0, qa, qb⟩, lt_trans qa qb⟩ lemma lt_iff_exists_real_btwn : a < b ↔ (∃r:ℝ, 0 ≤ r ∧ a < ennreal.of_real r ∧ (ennreal.of_real r:ennreal) < b) := ⟨λ h, let ⟨q, q0, aq, qb⟩ := ennreal.lt_iff_exists_rat_btwn.1 h in ⟨q, rat.cast_nonneg.2 q0, aq, qb⟩, λ ⟨q, q0, qa, qb⟩, lt_trans qa qb⟩ protected lemma exists_nat_gt {r : ennreal} (h : r ≠ ⊤) : ∃n:ℕ, r < n := begin rcases lt_iff_exists_coe.1 (lt_top_iff_ne_top.2 h) with ⟨r, rfl, hb⟩, rcases exists_nat_gt r with ⟨n, hn⟩, refine ⟨n, _⟩, rwa [← ennreal.coe_nat, ennreal.coe_lt_coe], end lemma add_lt_add (ac : a < c) (bd : b < d) : a + b < c + d := begin rcases dense ac with ⟨a', aa', a'c⟩, rcases lt_iff_exists_coe.1 aa' with ⟨aR, rfl, _⟩, rcases lt_iff_exists_coe.1 a'c with ⟨a'R, rfl, _⟩, rcases dense bd with ⟨b', bb', b'd⟩, rcases lt_iff_exists_coe.1 bb' with ⟨bR, rfl, _⟩, rcases lt_iff_exists_coe.1 b'd with ⟨b'R, rfl, _⟩, have I : ↑aR + ↑bR < ↑a'R + ↑b'R := begin rw [← coe_add, ← coe_add, coe_lt_coe], apply add_lt_add (coe_lt_coe.1 aa') (coe_lt_coe.1 bb') end, have J : ↑a'R + ↑b'R ≤ c + d := add_le_add' (le_of_lt a'c) (le_of_lt b'd), apply lt_of_lt_of_le I J end end order section complete_lattice lemma coe_Sup {s : set nnreal} : bdd_above s → (↑(Sup s) : ennreal) = (⨆a∈s, ↑a) := with_top.coe_Sup lemma coe_Inf {s : set nnreal} : s ≠ ∅ → (↑(Inf s) : ennreal) = (⨅a∈s, ↑a) := with_top.coe_Inf @[simp] lemma top_mem_upper_bounds {s : set ennreal} : ∞ ∈ upper_bounds s := assume x hx, le_top lemma coe_mem_upper_bounds {s : set nnreal} : ↑r ∈ upper_bounds ((coe : nnreal → ennreal) '' s) ↔ r ∈ upper_bounds s := by simp [upper_bounds, ball_image_iff, -mem_image, *] {contextual := tt} lemma infi_ennreal {α : Type*} [complete_lattice α] {f : ennreal → α} : (⨅n, f n) = (⨅n:nnreal, f n) ⊓ f ⊤ := le_antisymm (le_inf (le_infi $ assume i, infi_le _ _) (infi_le _ _)) (le_infi $ forall_ennreal.2 ⟨assume r, inf_le_left_of_le $ infi_le _ _, inf_le_right⟩) end complete_lattice section mul lemma mul_eq_mul_left : a ≠ 0 → a ≠ ⊤ → (a * b = a * c ↔ b = c) := begin cases a; cases b; cases c; simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm, nnreal.mul_eq_mul_left] {contextual := tt}, end lemma mul_le_mul_left : a ≠ 0 → a ≠ ⊤ → (a * b ≤ a * c ↔ b ≤ c) := begin cases a; cases b; cases c; simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm] {contextual := tt}, assume h, exact mul_le_mul_left (zero_lt_iff_ne_zero.2 h) end lemma mul_eq_zero {a b : ennreal} : a * b = 0 ↔ a = 0 ∨ b = 0 := canonically_ordered_comm_semiring.mul_eq_zero_iff _ _ end mul section sub instance : has_sub ennreal := ⟨λa b, Inf {d | a ≤ d + b}⟩ lemma coe_sub : ↑(p - r) = (↑p:ennreal) - r := le_antisymm (le_Inf $ assume b (hb : ↑p ≤ b + r), coe_le_iff.2 $ by rintros d rfl; rwa [← coe_add, coe_le_coe, ← nnreal.sub_le_iff_le_add] at hb) (Inf_le $ show (↑p : ennreal) ≤ ↑(p - r) + ↑r, by rw [← coe_add, coe_le_coe, ← nnreal.sub_le_iff_le_add]) @[simp] lemma top_sub_coe : ∞ - ↑r = ∞ := top_unique $ le_Inf $ by simp [add_eq_top] @[simp] lemma sub_eq_zero_of_le (h : a ≤ b) : a - b = 0 := le_antisymm (Inf_le $ le_add_left h) (zero_le _) @[simp] lemma zero_sub : 0 - a = 0 := le_antisymm (Inf_le $ zero_le _) (zero_le _) @[simp] lemma sub_infty : a - ∞ = 0 := le_antisymm (Inf_le $ by simp) (zero_le _) lemma sub_le_sub (h₁ : a ≤ b) (h₂ : d ≤ c) : a - c ≤ b - d := Inf_le_Inf $ assume e (h : b ≤ e + d), calc a ≤ b : h₁ ... ≤ e + d : h ... ≤ e + c : add_le_add' (le_refl _) h₂ @[simp] lemma add_sub_self : ∀{a b : ennreal}, b < ∞ → (a + b) - b = a | a none := by simp [none_eq_top] | none (some b) := by simp [none_eq_top, some_eq_coe] | (some a) (some b) := by simp [some_eq_coe]; rw [← coe_add, ← coe_sub, coe_eq_coe, nnreal.add_sub_cancel] @[simp] lemma add_sub_self' (h : a < ∞) : (a + b) - a = b := by rw [add_comm, add_sub_self h] lemma add_left_inj (h : a < ∞) : a + b = a + c ↔ b = c := ⟨λ e, by simpa [h] using congr_arg (λ x, x - a) e, congr_arg _⟩ lemma add_right_inj (h : a < ∞) : b + a = c + a ↔ b = c := by rw [add_comm, add_comm c, add_left_inj h] @[simp] lemma sub_add_cancel_of_le : ∀{a b : ennreal}, b ≤ a → (a - b) + b = a := begin simp [forall_ennreal, le_coe_iff, -add_comm] {contextual := tt}, rintros r p x rfl h, rw [← coe_sub, ← coe_add, nnreal.sub_add_cancel_of_le h] end @[simp] lemma add_sub_cancel_of_le (h : b ≤ a) : b + (a - b) = a := by rwa [add_comm, sub_add_cancel_of_le] lemma sub_add_self_eq_max : (a - b) + b = max a b := match le_total a b with | or.inl h := by simp [h, max_eq_right] | or.inr h := by simp [h, max_eq_left] end @[simp] protected lemma sub_le_iff_le_add : a - b ≤ c ↔ a ≤ c + b := iff.intro (assume h : a - b ≤ c, calc a ≤ (a - b) + b : by rw [sub_add_self_eq_max]; exact le_max_left _ _ ... ≤ c + b : add_le_add' h (le_refl _)) (assume h : a ≤ c + b, calc a - b ≤ (c + b) - b : sub_le_sub h (le_refl _) ... ≤ c : Inf_le (le_refl (c + b))) @[simp] lemma sub_eq_zero_iff_le : a - b = 0 ↔ a ≤ b := by simpa [-ennreal.sub_le_iff_le_add] using @ennreal.sub_le_iff_le_add a b 0 @[simp] lemma zero_lt_sub_iff_lt : 0 < a - b ↔ b < a := by simpa [ennreal.bot_lt_iff_ne_bot, -sub_eq_zero_iff_le] using not_iff_not.2 (@sub_eq_zero_iff_le a b) lemma sub_le_self (a b : ennreal) : a - b ≤ a := ennreal.sub_le_iff_le_add.2 $ le_add_of_nonneg_right' $ zero_le _ @[simp] lemma sub_zero : a - 0 = a := eq.trans (add_zero (a - 0)).symm $ by simp lemma sub_sub_cancel (h : a < ∞) (h2 : b ≤ a) : a - (a - b) = b := by rw [← add_right_inj (lt_of_le_of_lt (sub_le_self _ _) h), sub_add_cancel_of_le (sub_le_self _ _), add_sub_cancel_of_le h2] end sub section bit @[simp] lemma bit0_inj : bit0 a = bit0 b ↔ a = b := ⟨λh, begin rcases (lt_trichotomy a b) with h₁| h₂| h₃, { exact (absurd h (ne_of_lt (add_lt_add h₁ h₁))) }, { exact h₂ }, { exact (absurd h.symm (ne_of_lt (add_lt_add h₃ h₃))) } end, λh, congr_arg _ h⟩ @[simp] lemma bit0_eq_zero_iff : bit0 a = 0 ↔ a = 0 := by simpa only [bit0_zero] using @bit0_inj a 0 @[simp] lemma bit0_eq_top_iff : bit0 a = ∞ ↔ a = ∞ := by rw [bit0, add_eq_top, or_self] @[simp] lemma bit1_inj : bit1 a = bit1 b ↔ a = b := ⟨λh, begin unfold bit1 at h, rwa [add_right_inj, bit0_inj] at h, simp [lt_top_iff_ne_top] end, λh, congr_arg _ h⟩ @[simp] lemma bit1_ne_zero : bit1 a ≠ 0 := by unfold bit1; simp @[simp] lemma bit1_eq_one_iff : bit1 a = 1 ↔ a = 0 := by simpa only [bit1_zero] using @bit1_inj a 0 @[simp] lemma bit1_eq_top_iff : bit1 a = ∞ ↔ a = ∞ := by unfold bit1; rw add_eq_top; simp end bit section inv instance : has_inv ennreal := ⟨λa, Inf {b | 1 ≤ a * b}⟩ instance : has_div ennreal := ⟨λa b, a * b⁻¹⟩ lemma div_def : a / b = a * b⁻¹ := rfl @[simp] lemma inv_zero : (0 : ennreal)⁻¹ = ∞ := show Inf {b : ennreal | 1 ≤ 0 * b} = ∞, by simp; refl @[simp] lemma inv_top : (∞ : ennreal)⁻¹ = 0 := bot_unique $ le_of_forall_le_of_dense $ λ a (h : a > 0), Inf_le $ by simp [*, ne_of_gt h, top_mul] @[simp] lemma coe_inv (hr : r ≠ 0) : (↑r⁻¹ : ennreal) = (↑r)⁻¹ := le_antisymm (le_Inf $ assume b (hb : 1 ≤ ↑r * b), coe_le_iff.2 $ by rintros b rfl; rwa [← coe_mul, ← coe_one, coe_le_coe, ← nnreal.inv_le hr] at hb) (Inf_le $ by simp; rw [← coe_mul, nnreal.mul_inv_cancel hr]; exact le_refl 1) @[simp] lemma coe_div (hr : r ≠ 0) : (↑(p / r) : ennreal) = p / r := show ↑(p * r⁻¹) = ↑p * (↑r)⁻¹, by rw [coe_mul, coe_inv hr] @[simp] lemma inv_inv : (a⁻¹)⁻¹ = a := by by_cases a = 0; cases a; simp [*, none_eq_top, some_eq_coe, -coe_inv, (coe_inv _).symm] at * @[simp] lemma inv_eq_top : a⁻¹ = ∞ ↔ a = 0 := by by_cases a = 0; cases a; simp [*, none_eq_top, some_eq_coe, -coe_inv, (coe_inv _).symm] at * lemma inv_ne_top : a⁻¹ ≠ ∞ ↔ a ≠ 0 := by simp @[simp] lemma inv_eq_zero : a⁻¹ = 0 ↔ a = ∞ := by rw [← inv_eq_top, inv_inv] lemma inv_ne_zero : a⁻¹ ≠ 0 ↔ a ≠ ∞ := by simp lemma le_div_iff_mul_le : ∀{b}, b ≠ 0 → b ≠ ⊤ → (a ≤ c / b ↔ a * b ≤ c) | none h0 ht := (ht rfl).elim | (some r) h0 ht := begin have hr : r ≠ 0, from mt coe_eq_coe.2 h0, rw [← ennreal.mul_le_mul_left h0 ht], suffices : ↑r * a ≤ (↑r * ↑r⁻¹) * c ↔ a * ↑r ≤ c, { simpa [some_eq_coe, div_def, hr, mul_left_comm, mul_comm, mul_assoc] }, rw [← coe_mul, nnreal.mul_inv_cancel hr, coe_one, one_mul, mul_comm] end lemma div_le_iff_le_mul (hb0 : b ≠ 0) (hbt : b ≠ ⊤) : a / b ≤ c ↔ a ≤ c * b := suffices a * b⁻¹ ≤ c ↔ a ≤ c / b⁻¹, by simpa [div_def], (le_div_iff_mul_le (inv_ne_zero.2 hbt) (inv_ne_top.2 hb0)).symm lemma inv_le_iff_le_mul : (b = ⊤ → a ≠ 0) → (a = ⊤ → b ≠ 0) → (a⁻¹ ≤ b ↔ 1 ≤ a * b) := begin cases a; cases b; simp [none_eq_top, some_eq_coe, mul_top, top_mul] {contextual := tt}, by_cases a = 0; simp [*, -coe_mul, coe_mul.symm, -coe_inv, (coe_inv _).symm, nnreal.inv_le] end @[simp] lemma le_inv_iff_mul_le : a ≤ b⁻¹ ↔ a * b ≤ 1 := begin cases b, { by_cases a = 0; simp [*, none_eq_top, mul_top] }, by_cases b = 0; simp [*, some_eq_coe, le_div_iff_mul_le], suffices : a ≤ 1 / b ↔ a * b ≤ 1, { simpa [div_def, h] }, exact le_div_iff_mul_le (mt coe_eq_coe.1 h) coe_ne_top end lemma mul_inv_cancel : ∀{r : ennreal}, r ≠ 0 → r ≠ ⊤ → r * r⁻¹ = 1 := begin refine forall_ennreal.2 ⟨λ r, _, _⟩; simp [-coe_inv, (coe_inv _).symm] {contextual := tt}, assume h, rw [← ennreal.coe_mul, nnreal.mul_inv_cancel h, coe_one] end lemma mul_le_if_le_inv {a b r : ennreal} (hr₀ : r ≠ 0) (hr₁ : r ≠ ⊤) : (r * a ≤ b ↔ a ≤ r⁻¹ * b) := by rw [← @ennreal.mul_le_mul_left _ a _ hr₀ hr₁, ← mul_assoc, mul_inv_cancel hr₀ hr₁, one_mul] lemma le_of_forall_lt_one_mul_lt : ∀{x y : ennreal}, (∀a<1, a * x ≤ y) → x ≤ y := forall_ennreal.2 $ and.intro (assume r, forall_ennreal.2 $ and.intro (assume q h, coe_le_coe.2 $ nnreal.le_of_forall_lt_one_mul_lt $ assume a ha, begin rw [← coe_le_coe, coe_mul], exact h _ (coe_lt_coe.2 ha) end) (assume h, le_top)) (assume r hr, have ((1 / 2 : nnreal) : ennreal) * ⊤ ≤ r := hr _ (coe_lt_coe.2 ((@nnreal.coe_lt (1/2) 1).2 one_half_lt_one)), have ne : ((1 / 2 : nnreal) : ennreal) ≠ 0, begin rw [(≠), coe_eq_zero], refine zero_lt_iff_ne_zero.1 _, show 0 < (1 / 2 : ℝ), exact div_pos zero_lt_one two_pos end, by rwa [mul_top, if_neg ne] at this) lemma div_add_div_same {a b c : ennreal} : a / c + b / c = (a + b) / c := eq.symm $ right_distrib a b (c⁻¹) lemma div_self {a : ennreal} (h0 : a ≠ 0) (hI : a ≠ ∞) : a / a = 1 := have A : 1 ≤ a / a := by simp [le_div_iff_mul_le h0 hI, le_refl], have B : a / a ≤ 1 := by simp [div_le_iff_le_mul h0 hI, le_refl], le_antisymm B A lemma add_halves (a : ennreal) : a / 2 + a / 2 = a := have ¬((2 : nnreal) : ennreal) = (0 : nnreal) := by rw [coe_eq_coe]; norm_num, have A : (2:ennreal) * 2⁻¹ = 1 := by rw [←div_def, div_self]; [assumption, apply coe_ne_top], calc a / 2 + a / 2 = (a + a) / 2 : by rw div_add_div_same ... = (a * 1 + a * 1) / 2 : by rw mul_one ... = (a * (1 + 1)) / 2 : by rw left_distrib ... = (a * 2) / 2 : by rw one_add_one_eq_two ... = (a * 2) * 2⁻¹ : by rw div_def ... = a * (2 * 2⁻¹) : by rw mul_assoc ... = a * 1 : by rw A ... = a : by rw mul_one @[simp] lemma div_zero_iff {a b : ennreal} : a / b = 0 ↔ a = 0 ∨ b = ⊤ := by simp [div_def, mul_eq_zero] @[simp] lemma div_pos_iff {a b : ennreal} : 0 < a / b ↔ a ≠ 0 ∧ b ≠ ⊤ := by simp [zero_lt_iff_ne_zero, not_or_distrib] lemma half_pos {a : ennreal} (h : 0 < a) : 0 < a / 2 := by simp [ne_of_gt h] lemma half_lt_self {a : ennreal} (hz : a ≠ 0) (ht : a ≠ ⊤) : a / 2 < a := begin cases a, { cases ht none_eq_top }, { simp [some_eq_coe] at hz, simpa [-coe_lt_coe, coe_div two_ne_zero'] using coe_lt_coe.2 (nnreal.half_lt_self hz) } end lemma exists_inv_nat_lt {a : ennreal} (h : a ≠ 0) : ∃n:ℕ, (n:ennreal)⁻¹ < a := begin rcases dense (bot_lt_iff_ne_bot.2 h) with ⟨b, bz, ba⟩, have bz' : b ≠ 0 := bot_lt_iff_ne_bot.1 bz, have : b⁻¹ ≠ ⊤ := by simp [bz'], rcases ennreal.exists_nat_gt this with ⟨n, bn⟩, have I : ((n : ℕ) : ennreal)⁻¹ ≤ b := begin rw [ennreal.inv_le_iff_le_mul, mul_comm, ← ennreal.inv_le_iff_le_mul], exact le_of_lt bn, simp only [h, ennreal.nat_ne_top, forall_prop_of_false, ne.def, not_false_iff], exact λ_, ne_bot_of_gt bn, exact λ_, ne_bot_of_gt bn, exact λ_, bz' end, exact ⟨n, lt_of_le_of_lt I ba⟩ end end inv section real lemma to_real_add (ha : a ≠ ⊤) (hb : b ≠ ⊤) : (a+b).to_real = a.to_real + b.to_real := begin cases a, { simpa [none_eq_top] using ha }, cases b, { simpa [none_eq_top] using hb }, refl end lemma of_real_add {p q : ℝ} (hp : 0 ≤ p) (hq : 0 ≤ q) : ennreal.of_real (p + q) = ennreal.of_real p + ennreal.of_real q := by rw [ennreal.of_real, ennreal.of_real, ennreal.of_real, ← coe_add, coe_eq_coe, nnreal.of_real_add hp hq] @[simp] lemma to_real_le_to_real (ha : a ≠ ⊤) (hb : b ≠ ⊤) : a.to_real ≤ b.to_real ↔ a ≤ b := begin cases a, { simpa [none_eq_top] using ha }, cases b, { simpa [none_eq_top] using hb }, simp only [ennreal.to_real, nnreal.coe_le.symm, with_top.some_le_some], refl end @[simp] lemma to_real_lt_to_real (ha : a ≠ ⊤) (hb : b ≠ ⊤) : a.to_real < b.to_real ↔ a < b := begin cases a, { simpa [none_eq_top] using ha }, cases b, { simpa [none_eq_top] using hb }, rw [with_top.some_lt_some], refl end lemma of_real_le_of_real {p q : ℝ} (h : p ≤ q) : ennreal.of_real p ≤ ennreal.of_real q := by simp [ennreal.of_real, nnreal.of_real_le_of_real h] @[simp] lemma of_real_le_of_real_iff {p q : ℝ} (h : 0 ≤ q) : ennreal.of_real p ≤ ennreal.of_real q ↔ p ≤ q := by rw [ennreal.of_real, ennreal.of_real, coe_le_coe, nnreal.of_real_le_of_real_iff h] @[simp] lemma of_real_lt_of_real_iff {p q : ℝ} (h : 0 < q) : ennreal.of_real p < ennreal.of_real q ↔ p < q := by rw [ennreal.of_real, ennreal.of_real, coe_lt_coe, nnreal.of_real_lt_of_real_iff h] @[simp] lemma of_real_pos {p : ℝ} : 0 < ennreal.of_real p ↔ 0 < p := by simp [ennreal.of_real] @[simp] lemma of_real_eq_zero {p : ℝ} : ennreal.of_real p = 0 ↔ p ≤ 0 := by simp [ennreal.of_real] end real section infi variables {ι : Sort*} {f g : ι → ennreal} lemma infi_add : infi f + a = ⨅i, f i + a := le_antisymm (le_infi $ assume i, add_le_add' (infi_le _ _) $ le_refl _) (ennreal.sub_le_iff_le_add.1 $ le_infi $ assume i, ennreal.sub_le_iff_le_add.2 $ infi_le _ _) lemma supr_sub : (⨆i, f i) - a = (⨆i, f i - a) := le_antisymm (ennreal.sub_le_iff_le_add.2 $ supr_le $ assume i, ennreal.sub_le_iff_le_add.1 $ le_supr _ i) (supr_le $ assume i, ennreal.sub_le_sub (le_supr _ _) (le_refl a)) lemma sub_infi : a - (⨅i, f i) = (⨆i, a - f i) := begin refine (eq_of_forall_ge_iff $ λ c, _), rw [ennreal.sub_le_iff_le_add, add_comm, infi_add], simp [ennreal.sub_le_iff_le_add] end lemma Inf_add {s : set ennreal} : Inf s + a = ⨅b∈s, b + a := by simp [Inf_eq_infi, infi_add] lemma add_infi {a : ennreal} : a + infi f = ⨅b, a + f b := by rw [add_comm, infi_add]; simp lemma infi_add_infi (h : ∀i j, ∃k, f k + g k ≤ f i + g j) : infi f + infi g = (⨅a, f a + g a) := suffices (⨅a, f a + g a) ≤ infi f + infi g, from le_antisymm (le_infi $ assume a, add_le_add' (infi_le _ _) (infi_le _ _)) this, calc (⨅a, f a + g a) ≤ (⨅ a a', f a + g a') : le_infi $ assume a, le_infi $ assume a', let ⟨k, h⟩ := h a a' in infi_le_of_le k h ... ≤ infi f + infi g : by simp [add_infi, infi_add, -add_comm, -le_infi_iff]; exact le_refl _ lemma infi_sum {f : ι → α → ennreal} {s : finset α} [nonempty ι] (h : ∀(t : finset α) (i j : ι), ∃k, ∀a∈t, f k a ≤ f i a ∧ f k a ≤ f j a) : (⨅i, s.sum (f i)) = s.sum (λa, ⨅i, f i a) := finset.induction_on s (by simp) $ assume a s ha ih, have ∀ (i j : ι), ∃ (k : ι), f k a + s.sum (f k) ≤ f i a + s.sum (f j), from assume i j, let ⟨k, hk⟩ := h (insert a s) i j in ⟨k, add_le_add' (hk a (finset.mem_insert_self _ _)).left $ finset.sum_le_sum' $ assume a ha, (hk _ $ finset.mem_insert_of_mem ha).right⟩, by simp [ha, ih.symm, infi_add_infi this] end infi section supr lemma supr_coe_nat : (⨆n:ℕ, (n : ennreal)) = ⊤ := (lattice.supr_eq_top _).2 $ assume b hb, ennreal.exists_nat_gt (lt_top_iff_ne_top.1 hb) end supr end ennreal
6b57ccf2c814deb94fcb145064d7d07596f04713
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/group/semiconj.lean
fc54fd649ee717a08e889012014b8b18e26feda3
[ "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
7,801
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov Some proofs and docs came from `algebra/commute` (c) Neil Strickland -/ import algebra.group.units /-! # Semiconjugate elements of a semigroup > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Main definitions We say that `x` is semiconjugate to `y` by `a` (`semiconj_by a x y`), if `a * x = y * a`. In this file we provide operations on `semiconj_by _ _ _`. In the names of these operations, we treat `a` as the “left” argument, and both `x` and `y` as “right” arguments. This way most names in this file agree with the names of the corresponding lemmas for `commute a b = semiconj_by a b b`. As a side effect, some lemmas have only `_right` version. Lean does not immediately recognise these terms as equations, so for rewriting we need syntax like `rw [(h.pow_right 5).eq]` rather than just `rw [h.pow_right 5]`. This file provides only basic operations (`mul_left`, `mul_right`, `inv_right` etc). Other operations (`pow_right`, field inverse etc) are in the files that define corresponding notions. -/ universes u v variables {G : Type*} /-- `x` is semiconjugate to `y` by `a`, if `a * x = y * a`. -/ @[to_additive add_semiconj_by "`x` is additive semiconjugate to `y` by `a` if `a + x = y + a`"] def semiconj_by {M : Type u} [has_mul M] (a x y : M) : Prop := a * x = y * a namespace semiconj_by /-- Equality behind `semiconj_by a x y`; useful for rewriting. -/ @[to_additive "Equality behind `add_semiconj_by a x y`; useful for rewriting."] protected lemma eq {S : Type u} [has_mul S] {a x y : S} (h : semiconj_by a x y) : a * x = y * a := h section semigroup variables {S : Type u} [semigroup S] {a b x y z x' y' : S} /-- If `a` semiconjugates `x` to `y` and `x'` to `y'`, then it semiconjugates `x * x'` to `y * y'`. -/ @[simp, to_additive "If `a` semiconjugates `x` to `y` and `x'` to `y'`, then it semiconjugates `x + x'` to `y + y'`."] lemma mul_right (h : semiconj_by a x y) (h' : semiconj_by a x' y') : semiconj_by a (x * x') (y * y') := by unfold semiconj_by; assoc_rw [h.eq, h'.eq] /-- If both `a` and `b` semiconjugate `x` to `y`, then so does `a * b`. -/ @[to_additive "If both `a` and `b` semiconjugate `x` to `y`, then so does `a + b`."] lemma mul_left (ha : semiconj_by a y z) (hb : semiconj_by b x y) : semiconj_by (a * b) x z := by unfold semiconj_by; assoc_rw [hb.eq, ha.eq, mul_assoc] /-- The relation “there exists an element that semiconjugates `a` to `b`” on a semigroup is transitive. -/ @[to_additive "The relation “there exists an element that semiconjugates `a` to `b`” on an additive semigroup is transitive."] protected lemma transitive : transitive (λ a b : S, ∃ c, semiconj_by c a b) := λ a b c ⟨x, hx⟩ ⟨y, hy⟩, ⟨y * x, hy.mul_left hx⟩ end semigroup section mul_one_class variables {M : Type u} [mul_one_class M] /-- Any element semiconjugates `1` to `1`. -/ @[simp, to_additive "Any element additively semiconjugates `0` to `0`."] lemma one_right (a : M) : semiconj_by a 1 1 := by rw [semiconj_by, mul_one, one_mul] /-- One semiconjugates any element to itself. -/ @[simp, to_additive "Zero additively semiconjugates any element to itself."] lemma one_left (x : M) : semiconj_by 1 x x := eq.symm $ one_right x /-- The relation “there exists an element that semiconjugates `a` to `b`” on a monoid (or, more generally, on ` mul_one_class` type) is reflexive. -/ @[to_additive "The relation “there exists an element that semiconjugates `a` to `b`” on an additive monoid (or, more generally, on a `add_zero_class` type) is reflexive."] protected lemma reflexive : reflexive (λ a b : M, ∃ c, semiconj_by c a b) := λ a, ⟨1, one_left a⟩ end mul_one_class section monoid variables {M : Type u} [monoid M] /-- If `a` semiconjugates a unit `x` to a unit `y`, then it semiconjugates `x⁻¹` to `y⁻¹`. -/ @[to_additive "If `a` semiconjugates an additive unit `x` to an additive unit `y`, then it semiconjugates `-x` to `-y`."] lemma units_inv_right {a : M} {x y : Mˣ} (h : semiconj_by a x y) : semiconj_by a ↑x⁻¹ ↑y⁻¹ := calc a * ↑x⁻¹ = ↑y⁻¹ * (y * a) * ↑x⁻¹ : by rw [units.inv_mul_cancel_left] ... = ↑y⁻¹ * a : by rw [← h.eq, mul_assoc, units.mul_inv_cancel_right] @[simp, to_additive] lemma units_inv_right_iff {a : M} {x y : Mˣ} : semiconj_by a ↑x⁻¹ ↑y⁻¹ ↔ semiconj_by a x y := ⟨units_inv_right, units_inv_right⟩ /-- If a unit `a` semiconjugates `x` to `y`, then `a⁻¹` semiconjugates `y` to `x`. -/ @[to_additive "If an additive unit `a` semiconjugates `x` to `y`, then `-a` semiconjugates `y` to `x`."] lemma units_inv_symm_left {a : Mˣ} {x y : M} (h : semiconj_by ↑a x y) : semiconj_by ↑a⁻¹ y x := calc ↑a⁻¹ * y = ↑a⁻¹ * (y * a * ↑a⁻¹) : by rw [units.mul_inv_cancel_right] ... = x * ↑a⁻¹ : by rw [← h.eq, ← mul_assoc, units.inv_mul_cancel_left] @[simp, to_additive] lemma units_inv_symm_left_iff {a : Mˣ} {x y : M} : semiconj_by ↑a⁻¹ y x ↔ semiconj_by ↑a x y := ⟨units_inv_symm_left, units_inv_symm_left⟩ @[to_additive] theorem units_coe {a x y : Mˣ} (h : semiconj_by a x y) : semiconj_by (a : M) x y := congr_arg units.val h @[to_additive] theorem units_of_coe {a x y : Mˣ} (h : semiconj_by (a : M) x y) : semiconj_by a x y := units.ext h @[simp, to_additive] theorem units_coe_iff {a x y : Mˣ} : semiconj_by (a : M) x y ↔ semiconj_by a x y := ⟨units_of_coe, units_coe⟩ @[simp, to_additive] lemma pow_right {a x y : M} (h : semiconj_by a x y) (n : ℕ) : semiconj_by a (x^n) (y^n) := begin induction n with n ih, { rw [pow_zero, pow_zero], exact semiconj_by.one_right _ }, { rw [pow_succ, pow_succ], exact h.mul_right ih } end end monoid section division_monoid variables [division_monoid G] {a x y : G} @[simp, to_additive] lemma inv_inv_symm_iff : semiconj_by a⁻¹ x⁻¹ y⁻¹ ↔ semiconj_by a y x := inv_involutive.injective.eq_iff.symm.trans $ by simp_rw [mul_inv_rev, inv_inv, eq_comm, semiconj_by] @[to_additive] lemma inv_inv_symm : semiconj_by a x y → semiconj_by a⁻¹ y⁻¹ x⁻¹ := inv_inv_symm_iff.2 end division_monoid section group variables [group G] {a x y : G} @[simp, to_additive] lemma inv_right_iff : semiconj_by a x⁻¹ y⁻¹ ↔ semiconj_by a x y := @units_inv_right_iff G _ a ⟨x, x⁻¹, mul_inv_self x, inv_mul_self x⟩ ⟨y, y⁻¹, mul_inv_self y, inv_mul_self y⟩ @[to_additive] lemma inv_right : semiconj_by a x y → semiconj_by a x⁻¹ y⁻¹ := inv_right_iff.2 @[simp, to_additive] lemma inv_symm_left_iff : semiconj_by a⁻¹ y x ↔ semiconj_by a x y := @units_inv_symm_left_iff G _ ⟨a, a⁻¹, mul_inv_self a, inv_mul_self a⟩ _ _ @[to_additive] lemma inv_symm_left : semiconj_by a x y → semiconj_by a⁻¹ y x := inv_symm_left_iff.2 /-- `a` semiconjugates `x` to `a * x * a⁻¹`. -/ @[to_additive "`a` semiconjugates `x` to `a + x + -a`."] lemma conj_mk (a x : G) : semiconj_by a x (a * x * a⁻¹) := by unfold semiconj_by; rw [mul_assoc, inv_mul_self, mul_one] end group end semiconj_by @[simp, to_additive add_semiconj_by_iff_eq] lemma semiconj_by_iff_eq {M : Type u} [cancel_comm_monoid M] {a x y : M} : semiconj_by a x y ↔ x = y := ⟨λ h, mul_left_cancel (h.trans (mul_comm _ _)), λ h, by rw [h, semiconj_by, mul_comm] ⟩ /-- `a` semiconjugates `x` to `a * x * a⁻¹`. -/ @[to_additive "`a` semiconjugates `x` to `a + x + -a`."] lemma units.mk_semiconj_by {M : Type u} [monoid M] (u : Mˣ) (x : M) : semiconj_by ↑u x (u * x * ↑u⁻¹) := by unfold semiconj_by; rw [units.inv_mul_cancel_right]
4b0a2ece84cde288d5d323704e9c4e242bd58a74
95dcf8dea2baf2b4b0a60d438f27c35ae3dd3990
/src/data/nat/cast.lean
cdb7033faaff54ef104fce4aec15e9178f9d00d3
[ "Apache-2.0" ]
permissive
uniformity1/mathlib
829341bad9dfa6d6be9adaacb8086a8a492e85a4
dd0e9bd8f2e5ec267f68e72336f6973311909105
refs/heads/master
1,588,592,015,670
1,554,219,842,000
1,554,219,842,000
179,110,702
0
0
Apache-2.0
1,554,220,076,000
1,554,220,076,000
null
UTF-8
Lean
false
false
4,080
lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Natural homomorphism from the natural numbers into a monoid with one. -/ import tactic.interactive algebra.order algebra.ordered_group algebra.ring namespace nat variables {α : Type*} section variables [has_zero α] [has_one α] [has_add α] /-- Canonical homomorphism from `ℕ` to a type `α` with `0`, `1` and `+`. -/ protected def cast : ℕ → α | 0 := 0 | (n+1) := cast n + 1 @[priority 0] instance cast_coe : has_coe ℕ α := ⟨nat.cast⟩ @[simp] theorem cast_zero : ((0 : ℕ) : α) = 0 := rfl theorem cast_add_one (n : ℕ) : ((n + 1 : ℕ) : α) = n + 1 := rfl @[simp] theorem cast_succ (n : ℕ) : ((succ n : ℕ) : α) = n + 1 := rfl end @[simp] theorem cast_one [add_monoid α] [has_one α] : ((1 : ℕ) : α) = 1 := zero_add _ @[simp] theorem cast_add [add_monoid α] [has_one α] (m) : ∀ n, ((m + n : ℕ) : α) = m + n | 0 := (add_zero _).symm | (n+1) := show ((m + n : ℕ) : α) + 1 = m + (n + 1), by rw [cast_add n, add_assoc] instance [add_monoid α] [has_one α] : is_add_monoid_hom (coe : ℕ → α) := by refine_struct {..}; simp @[simp] theorem cast_bit0 [add_monoid α] [has_one α] (n : ℕ) : ((bit0 n : ℕ) : α) = bit0 n := cast_add _ _ @[simp] theorem cast_bit1 [add_monoid α] [has_one α] (n : ℕ) : ((bit1 n : ℕ) : α) = bit1 n := by rw [bit1, cast_add_one, cast_bit0]; refl lemma cast_two {α : Type*} [semiring α] : ((2 : ℕ) : α) = 2 := by simp @[simp] theorem cast_pred [add_group α] [has_one α] : ∀ {n}, n > 0 → ((n - 1 : ℕ) : α) = n - 1 | (n+1) h := (add_sub_cancel (n:α) 1).symm @[simp] theorem cast_sub [add_group α] [has_one α] {m n} (h : m ≤ n) : ((n - m : ℕ) : α) = n - m := eq_sub_of_add_eq $ by rw [← cast_add, nat.sub_add_cancel h] @[simp] theorem cast_mul [semiring α] (m) : ∀ n, ((m * n : ℕ) : α) = m * n | 0 := (mul_zero _).symm | (n+1) := (cast_add _ _).trans $ show ((m * n : ℕ) : α) + m = m * (n + 1), by rw [cast_mul n, left_distrib, mul_one] instance [semiring α] : is_semiring_hom (coe : ℕ → α) := by refine_struct {..}; simp theorem mul_cast_comm [semiring α] (a : α) (n : ℕ) : a * n = n * a := by induction n; simp [left_distrib, right_distrib, *] @[simp] theorem cast_nonneg [linear_ordered_semiring α] : ∀ n : ℕ, 0 ≤ (n : α) | 0 := le_refl _ | (n+1) := add_nonneg (cast_nonneg n) zero_le_one @[simp] theorem cast_le [linear_ordered_semiring α] : ∀ {m n : ℕ}, (m : α) ≤ n ↔ m ≤ n | 0 n := by simp [zero_le] | (m+1) 0 := by simpa [not_succ_le_zero] using lt_add_of_lt_of_nonneg zero_lt_one (@cast_nonneg α _ m) | (m+1) (n+1) := (add_le_add_iff_right 1).trans $ (@cast_le m n).trans $ (add_le_add_iff_right 1).symm @[simp] theorem cast_lt [linear_ordered_semiring α] {m n : ℕ} : (m : α) < n ↔ m < n := by simpa [-cast_le] using not_congr (@cast_le α _ n m) @[simp] theorem cast_pos [linear_ordered_semiring α] {n : ℕ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] theorem eq_cast [add_monoid α] [has_one α] (f : ℕ → α) (H0 : f 0 = 0) (H1 : f 1 = 1) (Hadd : ∀ x y, f (x + y) = f x + f y) : ∀ n : ℕ, f n = n | 0 := H0 | (n+1) := by rw [Hadd, H1, eq_cast]; refl theorem eq_cast' [add_group α] [has_one α] (f : ℕ → α) (H1 : f 1 = 1) (Hadd : ∀ x y, f (x + y) = f x + f y) : ∀ n : ℕ, f n = n := eq_cast _ (by rw [← add_left_inj (f 0), add_zero, ← Hadd]) H1 Hadd @[simp] theorem cast_id (n : ℕ) : ↑n = n := (eq_cast id rfl rfl (λ _ _, rfl) n).symm @[simp] theorem cast_min [decidable_linear_ordered_semiring α] {a b : ℕ} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [h, min] @[simp] theorem cast_max [decidable_linear_ordered_semiring α] {a b : ℕ} : (↑(max a b) : α) = max a b := by by_cases a ≤ b; simp [h, max] @[simp] theorem abs_cast [decidable_linear_ordered_comm_ring α] (a : ℕ) : abs (a : α) = a := abs_of_nonneg (cast_nonneg a) end nat
c3196c10d365d5930803e621a82aa64df4575bb1
c777c32c8e484e195053731103c5e52af26a25d1
/src/data/pnat/interval.lean
6d2ecf63145a6beed7867105c284809b2cc37ecc
[ "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
2,633
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.nat.interval import data.pnat.defs /-! # Finite intervals of positive naturals > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file proves that `ℕ+` is a `locally_finite_order` and calculates the cardinality of its intervals as finsets and fintypes. -/ open finset pnat instance : locally_finite_order ℕ+ := subtype.locally_finite_order _ namespace pnat variables (a b : ℕ+) lemma Icc_eq_finset_subtype : Icc a b = (Icc (a : ℕ) b).subtype (λ (n : ℕ), 0 < n) := rfl lemma Ico_eq_finset_subtype : Ico a b = (Ico (a : ℕ) b).subtype (λ (n : ℕ), 0 < n) := rfl lemma Ioc_eq_finset_subtype : Ioc a b = (Ioc (a : ℕ) b).subtype (λ (n : ℕ), 0 < n) := rfl lemma Ioo_eq_finset_subtype : Ioo a b = (Ioo (a : ℕ) b).subtype (λ (n : ℕ), 0 < n) := rfl lemma map_subtype_embedding_Icc : (Icc a b).map (function.embedding.subtype _) = Icc (a : ℕ) b := map_subtype_embedding_Icc _ _ _ (λ c _ x hx _ hc _, hc.trans_le hx) lemma map_subtype_embedding_Ico : (Ico a b).map (function.embedding.subtype _) = Ico (a : ℕ) b := map_subtype_embedding_Ico _ _ _ (λ c _ x hx _ hc _, hc.trans_le hx) lemma map_subtype_embedding_Ioc : (Ioc a b).map (function.embedding.subtype _) = Ioc (a : ℕ) b := map_subtype_embedding_Ioc _ _ _ (λ c _ x hx _ hc _, hc.trans_le hx) lemma map_subtype_embedding_Ioo : (Ioo a b).map (function.embedding.subtype _) = Ioo (a : ℕ) b := map_subtype_embedding_Ioo _ _ _ (λ c _ x hx _ hc _, hc.trans_le hx) @[simp] lemma card_Icc : (Icc a b).card = b + 1 - a := by rw [←nat.card_Icc, ←map_subtype_embedding_Icc, card_map] @[simp] lemma card_Ico : (Ico a b).card = b - a := by rw [←nat.card_Ico, ←map_subtype_embedding_Ico, card_map] @[simp] lemma card_Ioc : (Ioc a b).card = b - a := by rw [←nat.card_Ioc, ←map_subtype_embedding_Ioc, card_map] @[simp] lemma card_Ioo : (Ioo a b).card = b - a - 1 := by rw [←nat.card_Ioo, ←map_subtype_embedding_Ioo, card_map] @[simp] lemma card_fintype_Icc : fintype.card (set.Icc a b) = b + 1 - a := by rw [←card_Icc, fintype.card_of_finset] @[simp] lemma card_fintype_Ico : fintype.card (set.Ico a b) = b - a := by rw [←card_Ico, fintype.card_of_finset] @[simp] lemma card_fintype_Ioc : fintype.card (set.Ioc a b) = b - a := by rw [←card_Ioc, fintype.card_of_finset] @[simp] lemma card_fintype_Ioo : fintype.card (set.Ioo a b) = b - a - 1 := by rw [←card_Ioo, fintype.card_of_finset] end pnat
a087add7cfb8422266327b03d358d60ec8297001
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/order/rearrangement.lean
04d825f8964107ebfbff78652d7bb222181eb055
[ "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
27,908
lean
/- Copyright (c) 2022 Mantas Bakšys. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mantas Bakšys -/ import algebra.order.module import data.prod.lex import group_theory.perm.support import order.monovary import tactic.abel /-! # Rearrangement inequality This file proves the rearrangement inequality and deduces the conditions for equality and strict inequality. The rearrangement inequality tells you that for two functions `f g : ι → α`, the sum `∑ i, f i * g (σ i)` is maximized over all `σ : perm ι` when `g ∘ σ` monovaries with `f` and minimized when `g ∘ σ` antivaries with `f`. The inequality also tells you that `∑ i, f i * g (σ i) = ∑ i, f i * g i` if and only if `g ∘ σ` monovaries with `f` when `g` monovaries with `f`. The above equality also holds if and only if `g ∘ σ` antivaries with `f` when `g` antivaries with `f`. From the above two statements, we deduce that the inequality is strict if and only if `g ∘ σ` does not monovary with `f` when `g` monovaries with `f`. Analogously, the inequality is strict if and only if `g ∘ σ` does not antivary with `f` when `g` antivaries with `f`. ## Implementation notes In fact, we don't need much compatibility between the addition and multiplication of `α`, so we can actually decouple them by replacing multiplication with scalar multiplication and making `f` and `g` land in different types. As a bonus, this makes the dual statement trivial. The multiplication versions are provided for convenience. The case for `monotone`/`antitone` pairs of functions over a `linear_order` is not deduced in this file because it is easily deducible from the `monovary` API. -/ open equiv equiv.perm finset function order_dual open_locale big_operators variables {ι α β : Type*} /-! ### Scalar multiplication versions -/ section smul variables [linear_ordered_ring α] [linear_ordered_add_comm_group β] [module α β] [ordered_smul α β] {s : finset ι} {σ : perm ι} {f : ι → α} {g : ι → β} /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary_on.sum_smul_comp_perm_le_sum_smul (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g (σ i) ≤ ∑ i in s, f i • g i := begin classical, revert hσ σ hfg, apply finset.induction_on_max_value (λ i, to_lex (g i, f i)) s, { simp only [le_rfl, finset.sum_empty, implies_true_iff] }, intros a s has hamax hind σ hfg hσ, set τ : perm ι := σ.trans (swap a (σ a)) with hτ, have hτs : {x | τ x ≠ x} ⊆ s, { intros x hx, simp only [ne.def, set.mem_set_of_eq, equiv.coe_trans, equiv.swap_comp_apply] at hx, split_ifs at hx with h₁ h₂ h₃, { obtain rfl | hax := eq_or_ne x a, { contradiction }, { exact mem_of_mem_insert_of_ne (hσ $ λ h, hax $ h.symm.trans h₁) hax } }, { exact (hx $ σ.injective h₂.symm).elim }, { exact mem_of_mem_insert_of_ne (hσ hx) (ne_of_apply_ne _ h₂) } }, specialize hind (hfg.subset $ subset_insert _ _) hτs, simp_rw sum_insert has, refine le_trans _ (add_le_add_left hind _), obtain hσa | hσa := eq_or_ne a (σ a), { rw [hτ, ←hσa, swap_self, trans_refl] }, have h1s : σ⁻¹ a ∈ s, { rw [ne.def, ←inv_eq_iff_eq] at hσa, refine mem_of_mem_insert_of_ne (hσ $ λ h, hσa _) hσa, rwa [apply_inv_self, eq_comm] at h }, simp only [← s.sum_erase_add _ h1s, add_comm], rw [← add_assoc, ← add_assoc], simp only [hτ, swap_apply_left, function.comp_app, equiv.coe_trans, apply_inv_self], refine add_le_add (smul_add_smul_le_smul_add_smul' _ _) (sum_congr rfl $ λ x hx, _).le, { specialize hamax (σ⁻¹ a) h1s, rw prod.lex.le_iff at hamax, cases hamax, { exact hfg (mem_insert_of_mem h1s) (mem_insert_self _ _) hamax }, { exact hamax.2 } }, { specialize hamax (σ a) (mem_of_mem_insert_of_ne (hσ $ σ.injective.ne hσa.symm) hσa.symm), rw prod.lex.le_iff at hamax, cases hamax, { exact hamax.le }, { exact hamax.1.le } }, { rw [mem_erase, ne.def, eq_inv_iff_eq] at hx, rw swap_apply_of_ne_of_ne hx.1 (σ.injective.ne _), rintro rfl, exact has hx.2 } end /-- **Equality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary_on.sum_smul_comp_perm_eq_sum_smul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g (σ i) = ∑ i in s, f i • g i ↔ monovary_on f (g ∘ σ) s := begin classical, refine ⟨not_imp_not.1 $ λ h, _, λ h, (hfg.sum_smul_comp_perm_le_sum_smul hσ).antisymm _⟩, { rw monovary_on at h, push_neg at h, obtain ⟨x, hx, y, hy, hgxy, hfxy⟩ := h, set τ : perm ι := (swap x y).trans σ, have hτs : {x | τ x ≠ x} ⊆ s, { refine (set_support_mul_subset σ $ swap x y).trans (set.union_subset hσ $ λ z hz, _), obtain ⟨_, rfl | rfl⟩ := swap_apply_ne_self_iff.1 hz; assumption }, refine ((hfg.sum_smul_comp_perm_le_sum_smul hτs).trans_lt' _).ne, obtain rfl | hxy := eq_or_ne x y, { cases lt_irrefl _ hfxy }, simp only [←s.sum_erase_add _ hx, ←(s.erase x).sum_erase_add _ (mem_erase.2 ⟨hxy.symm, hy⟩), add_assoc, equiv.coe_trans, function.comp_app, swap_apply_right, swap_apply_left], refine add_lt_add_of_le_of_lt (finset.sum_congr rfl $ λ z hz, _).le (smul_add_smul_lt_smul_add_smul hfxy hgxy), simp_rw mem_erase at hz, rw swap_apply_of_ne_of_ne hz.2.1 hz.1 }, { convert h.sum_smul_comp_perm_le_sum_smul ((set_support_inv_eq _).subset.trans hσ) using 1, simp_rw [function.comp_app, apply_inv_self] } end /-- **Strict inequality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not monovary together. Stated by permuting the entries of `g`. -/ lemma monovary_on.sum_smul_comp_perm_lt_sum_smul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g (σ i) < ∑ i in s, f i • g i ↔ ¬ monovary_on f (g ∘ σ) s := by simp [←hfg.sum_smul_comp_perm_eq_sum_smul_iff hσ, lt_iff_le_and_ne, hfg.sum_smul_comp_perm_le_sum_smul hσ] /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `f`. -/ lemma monovary_on.sum_comp_perm_smul_le_sum_smul (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) • g i ≤ ∑ i in s, f i • g i := begin convert hfg.sum_smul_comp_perm_le_sum_smul (show {x | σ⁻¹ x ≠ x} ⊆ s, by simp only [set_support_inv_eq, hσ]) using 1, exact σ.sum_comp' s (λ i j, f i • g j) hσ, end /-- **Equality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` monovary together. Stated by permuting the entries of `f`. -/ lemma monovary_on.sum_comp_perm_smul_eq_sum_smul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) • g i = ∑ i in s, f i • g i ↔ monovary_on (f ∘ σ) g s := begin have hσinv : {x | σ⁻¹ x ≠ x} ⊆ s := (set_support_inv_eq _).subset.trans hσ, refine (iff.trans _ $ hfg.sum_smul_comp_perm_eq_sum_smul_iff hσinv).trans ⟨λ h, _, λ h, _⟩, { simpa only [σ.sum_comp' s (λ i j, f i • g j) hσ] }, { convert h.comp_right σ, { rw [comp.assoc, inv_def, symm_comp_self, comp.right_id] }, { rw [σ.eq_preimage_iff_image_eq, set.image_perm hσ] } }, { convert h.comp_right σ.symm, { rw [comp.assoc, self_comp_symm, comp.right_id] }, { rw σ.symm.eq_preimage_iff_image_eq, exact set.image_perm hσinv } } end /-- **Strict inequality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f ∘ σ` and `g` do not monovary together. Stated by permuting the entries of `f`. -/ lemma monovary_on.sum_comp_perm_smul_lt_sum_smul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) • g i < ∑ i in s, f i • g i ↔ ¬ monovary_on (f ∘ σ) g s := by simp [←hfg.sum_comp_perm_smul_eq_sum_smul_iff hσ, lt_iff_le_and_ne, hfg.sum_comp_perm_smul_le_sum_smul hσ] /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary_on.sum_smul_le_sum_smul_comp_perm (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g i ≤ ∑ i in s, f i • g (σ i) := hfg.dual_right.sum_smul_comp_perm_le_sum_smul hσ /-- **Equality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary_on.sum_smul_eq_sum_smul_comp_perm_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g (σ i) = ∑ i in s, f i • g i ↔ antivary_on f (g ∘ σ) s := (hfg.dual_right.sum_smul_comp_perm_eq_sum_smul_iff hσ).trans monovary_on_to_dual_right /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not antivary together. Stated by permuting the entries of `g`. -/ lemma antivary_on.sum_smul_lt_sum_smul_comp_perm_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g i < ∑ i in s, f i • g (σ i) ↔ ¬ antivary_on f (g ∘ σ) s := by simp [←hfg.sum_smul_eq_sum_smul_comp_perm_iff hσ, lt_iff_le_and_ne, eq_comm, hfg.sum_smul_le_sum_smul_comp_perm hσ] /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary_on.sum_smul_le_sum_comp_perm_smul (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g i ≤ ∑ i in s, f (σ i) • g i := hfg.dual_right.sum_comp_perm_smul_le_sum_smul hσ /-- **Equality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary_on.sum_smul_eq_sum_comp_perm_smul_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) • g i = ∑ i in s, f i • g i ↔ antivary_on (f ∘ σ) g s := (hfg.dual_right.sum_comp_perm_smul_eq_sum_smul_iff hσ).trans monovary_on_to_dual_right /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f ∘ σ` and `g` do not antivary together. Stated by permuting the entries of `f`. -/ lemma antivary_on.sum_smul_lt_sum_comp_perm_smul_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g i < ∑ i in s, f (σ i) • g i ↔ ¬ antivary_on (f ∘ σ) g s := by simp [←hfg.sum_smul_eq_sum_comp_perm_smul_iff hσ, eq_comm, lt_iff_le_and_ne, hfg.sum_smul_le_sum_comp_perm_smul hσ] variables [fintype ι] /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_smul_comp_perm_le_sum_smul (hfg : monovary f g) : ∑ i, f i • g (σ i) ≤ ∑ i, f i • g i := (hfg.monovary_on _).sum_smul_comp_perm_le_sum_smul $ λ i _, mem_univ _ /-- **Equality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_smul_comp_perm_eq_sum_smul_iff (hfg : monovary f g) : ∑ i, f i • g (σ i) = ∑ i, f i • g i ↔ monovary f (g ∘ σ) := by simp [(hfg.monovary_on _).sum_smul_comp_perm_eq_sum_smul_iff (λ i _, mem_univ _)] /-- **Strict inequality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_smul_comp_perm_lt_sum_smul_iff (hfg : monovary f g) : ∑ i, f i • g (σ i) < ∑ i, f i • g i ↔ ¬ monovary f (g ∘ σ) := by simp [(hfg.monovary_on _).sum_smul_comp_perm_lt_sum_smul_iff (λ i _, mem_univ _)] /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `f`. -/ lemma monovary.sum_comp_perm_smul_le_sum_smul (hfg : monovary f g) : ∑ i, f (σ i) • g i ≤ ∑ i, f i • g i := (hfg.monovary_on _).sum_comp_perm_smul_le_sum_smul $ λ i _, mem_univ _ /-- **Equality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_comp_perm_smul_eq_sum_smul_iff (hfg : monovary f g) : ∑ i, f (σ i) • g i = ∑ i, f i • g i ↔ monovary (f ∘ σ) g := by simp [(hfg.monovary_on _).sum_comp_perm_smul_eq_sum_smul_iff (λ i _, mem_univ _)] /-- **Strict inequality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_comp_perm_smul_lt_sum_smul_iff (hfg : monovary f g) : ∑ i, f (σ i) • g i < ∑ i, f i • g i ↔ ¬ monovary (f ∘ σ) g := by simp [(hfg.monovary_on _).sum_comp_perm_smul_lt_sum_smul_iff (λ i _, mem_univ _)] /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary.sum_smul_le_sum_smul_comp_perm (hfg : antivary f g) : ∑ i, f i • g i ≤ ∑ i, f i • g (σ i) := (hfg.antivary_on _).sum_smul_le_sum_smul_comp_perm $ λ i _, mem_univ _ /-- **Equality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary.sum_smul_eq_sum_smul_comp_perm_iff (hfg : antivary f g) : ∑ i, f i • g (σ i) = ∑ i, f i • g i ↔ antivary f (g ∘ σ) := by simp [(hfg.antivary_on _).sum_smul_eq_sum_smul_comp_perm_iff (λ i _, mem_univ _)] /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not antivary together. Stated by permuting the entries of `g`. -/ lemma antivary.sum_smul_lt_sum_smul_comp_perm_iff (hfg : antivary f g) : ∑ i, f i • g i < ∑ i, f i • g (σ i) ↔ ¬ antivary f (g ∘ σ) := by simp [(hfg.antivary_on _).sum_smul_lt_sum_smul_comp_perm_iff (λ i _, mem_univ _)] /-- **Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary.sum_smul_le_sum_comp_perm_smul (hfg : antivary f g) : ∑ i, f i • g i ≤ ∑ i, f (σ i) • g i := (hfg.antivary_on _).sum_smul_le_sum_comp_perm_smul $ λ i _, mem_univ _ /-- **Equality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary.sum_smul_eq_sum_comp_perm_smul_iff (hfg : antivary f g) : ∑ i, f (σ i) • g i = ∑ i, f i • g i ↔ antivary (f ∘ σ) g := by simp [(hfg.antivary_on _).sum_smul_eq_sum_comp_perm_smul_iff (λ i _, mem_univ _)] /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f ∘ σ` and `g` do not antivary together. Stated by permuting the entries of `f`. -/ lemma antivary.sum_smul_lt_sum_comp_perm_smul_iff (hfg : antivary f g) : ∑ i, f i • g i < ∑ i, f (σ i) • g i ↔ ¬ antivary (f ∘ σ) g := by simp [(hfg.antivary_on _).sum_smul_lt_sum_comp_perm_smul_iff (λ i _, mem_univ _)] end smul /-! ### Multiplication versions Special cases of the above when scalar multiplication is actually multiplication. -/ section mul variables [linear_ordered_ring α] {s : finset ι} {σ : perm ι} {f g : ι → α} /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary_on.sum_mul_comp_perm_le_sum_mul (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i * g (σ i) ≤ ∑ i in s, f i * g i := hfg.sum_smul_comp_perm_le_sum_smul hσ /-- **Equality case of Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary_on.sum_mul_comp_perm_eq_sum_mul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i * g (σ i) = ∑ i in s, f i * g i ↔ monovary_on f (g ∘ σ) s := hfg.sum_smul_comp_perm_eq_sum_smul_iff hσ /-- **Strict inequality case of Rearrangement Inequality**: Pointwise scalar multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not monovary together. Stated by permuting the entries of `g`. -/ lemma monovary_on.sum_mul_comp_perm_lt_sum_mul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i • g (σ i) < ∑ i in s, f i • g i ↔ ¬ monovary_on f (g ∘ σ) s := hfg.sum_smul_comp_perm_lt_sum_smul_iff hσ /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `f`. -/ lemma monovary_on.sum_comp_perm_mul_le_sum_mul (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) * g i ≤ ∑ i in s, f i * g i := hfg.sum_comp_perm_smul_le_sum_smul hσ /-- **Equality case of Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` monovary together. Stated by permuting the entries of `f`. -/ lemma monovary_on.sum_comp_perm_mul_eq_sum_mul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) * g i = ∑ i in s, f i * g i ↔ monovary_on (f ∘ σ) g s := hfg.sum_comp_perm_smul_eq_sum_smul_iff hσ /-- **Strict inequality case of Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f ∘ σ` and `g` do not monovary together. Stated by permuting the entries of `f`. -/ lemma monovary_on.sum_comp_perm_mul_lt_sum_mul_iff (hfg : monovary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) * g i < ∑ i in s, f i * g i ↔ ¬ monovary_on (f ∘ σ) g s := hfg.sum_comp_perm_smul_lt_sum_smul_iff hσ /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary_on.sum_mul_le_sum_mul_comp_perm (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i * g i ≤ ∑ i in s, f i * g (σ i) := hfg.sum_smul_le_sum_smul_comp_perm hσ /-- **Equality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary_on.sum_mul_eq_sum_mul_comp_perm_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i * g (σ i) = ∑ i in s, f i * g i ↔ antivary_on f (g ∘ σ) s := hfg.sum_smul_eq_sum_smul_comp_perm_iff hσ /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not antivary together. Stated by permuting the entries of `g`. -/ lemma antivary_on.sum_mul_lt_sum_mul_comp_perm_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i * g i < ∑ i in s, f i * g (σ i) ↔ ¬ antivary_on f (g ∘ σ) s := hfg.sum_smul_lt_sum_smul_comp_perm_iff hσ /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary_on.sum_mul_le_sum_comp_perm_mul (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i * g i ≤ ∑ i in s, f (σ i) * g i := hfg.sum_smul_le_sum_comp_perm_smul hσ /-- **Equality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary_on.sum_mul_eq_sum_comp_perm_mul_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f (σ i) * g i = ∑ i in s, f i * g i ↔ antivary_on (f ∘ σ) g s := hfg.sum_smul_eq_sum_comp_perm_smul_iff hσ /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f ∘ σ` and `g` do not antivary together. Stated by permuting the entries of `f`. -/ lemma antivary_on.sum_mul_lt_sum_comp_perm_mul_iff (hfg : antivary_on f g s) (hσ : {x | σ x ≠ x} ⊆ s) : ∑ i in s, f i * g i < ∑ i in s, f (σ i) * g i ↔ ¬ antivary_on (f ∘ σ) g s := hfg.sum_smul_lt_sum_comp_perm_smul_iff hσ variables [fintype ι] /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_mul_comp_perm_le_sum_mul (hfg : monovary f g) : ∑ i, f i * g (σ i) ≤ ∑ i, f i * g i := hfg.sum_smul_comp_perm_le_sum_smul /-- **Equality case of Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_mul_comp_perm_eq_sum_mul_iff (hfg : monovary f g) : ∑ i, f i * g (σ i) = ∑ i, f i * g i ↔ monovary f (g ∘ σ) := hfg.sum_smul_comp_perm_eq_sum_smul_iff /-- **Strict inequality case of Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_mul_comp_perm_lt_sum_mul_iff (hfg : monovary f g) : ∑ i, f i * g (σ i) < ∑ i, f i * g i ↔ ¬ monovary f (g ∘ σ) := hfg.sum_smul_comp_perm_lt_sum_smul_iff /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is maximized when `f` and `g` monovary together. Stated by permuting the entries of `f`. -/ lemma monovary.sum_comp_perm_mul_le_sum_mul (hfg : monovary f g) : ∑ i, f (σ i) * g i ≤ ∑ i, f i * g i := hfg.sum_comp_perm_smul_le_sum_smul /-- **Equality case of Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which monovary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_comp_perm_mul_eq_sum_mul_iff (hfg : monovary f g) : ∑ i, f (σ i) * g i = ∑ i, f i * g i ↔ monovary (f ∘ σ) g := hfg.sum_comp_perm_smul_eq_sum_smul_iff /-- **Strict inequality case of Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which monovary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not monovary together. Stated by permuting the entries of `g`. -/ lemma monovary.sum_comp_perm_mul_lt_sum_mul_iff (hfg : monovary f g) : ∑ i, f (σ i) * g i < ∑ i, f i * g i ↔ ¬ monovary (f ∘ σ) g := hfg.sum_comp_perm_smul_lt_sum_smul_iff /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary.sum_mul_le_sum_mul_comp_perm (hfg : antivary f g) : ∑ i, f i * g i ≤ ∑ i, f i * g (σ i) := hfg.sum_smul_le_sum_smul_comp_perm /-- **Equality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f` and `g ∘ σ` antivary together. Stated by permuting the entries of `g`. -/ lemma antivary.sum_mul_eq_sum_mul_comp_perm_iff (hfg : antivary f g) : ∑ i, f i * g (σ i) = ∑ i, f i * g i ↔ antivary f (g ∘ σ) := hfg.sum_smul_eq_sum_smul_comp_perm_iff /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f` and `g ∘ σ` do not antivary together. Stated by permuting the entries of `g`. -/ lemma antivary.sum_mul_lt_sum_mul_comp_perm_iff (hfg : antivary f g) : ∑ i, f i • g i < ∑ i, f i • g (σ i) ↔ ¬ antivary f (g ∘ σ) := hfg.sum_smul_lt_sum_smul_comp_perm_iff /-- **Rearrangement Inequality**: Pointwise multiplication of `f` and `g` is minimized when `f` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary.sum_mul_le_sum_comp_perm_mul (hfg : antivary f g) : ∑ i, f i * g i ≤ ∑ i, f (σ i) * g i := hfg.sum_smul_le_sum_comp_perm_smul /-- **Equality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is unchanged by a permutation if and only if `f ∘ σ` and `g` antivary together. Stated by permuting the entries of `f`. -/ lemma antivary.sum_mul_eq_sum_comp_perm_mul_iff (hfg : antivary f g) : ∑ i, f (σ i) * g i = ∑ i, f i * g i ↔ antivary (f ∘ σ) g := hfg.sum_smul_eq_sum_comp_perm_smul_iff /-- **Strict inequality case of the Rearrangement Inequality**: Pointwise multiplication of `f` and `g`, which antivary together, is strictly decreased by a permutation if and only if `f ∘ σ` and `g` do not antivary together. Stated by permuting the entries of `f`. -/ lemma antivary.sum_mul_lt_sum_comp_perm_mul_iff (hfg : antivary f g) : ∑ i, f i * g i < ∑ i, f (σ i) * g i ↔ ¬ antivary (f ∘ σ) g := hfg.sum_smul_lt_sum_comp_perm_smul_iff end mul
bd6cedeae190bc86a3c85233c15416c3b24618c1
63abd62053d479eae5abf4951554e1064a4c45b4
/src/geometry/euclidean/circumcenter.lean
0ef2aa17c6f4219bf185a1176a93f20650982195
[ "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
38,190
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 geometry.euclidean.basic import linear_algebra.affine_space.finite_dimensional import tactic.derive_fintype noncomputable theory open_locale big_operators open_locale classical open_locale real open_locale real_inner_product_space /-! # Circumcenter and circumradius This file proves some lemmas on points equidistant from a set of points, and defines the circumradius and circumcenter of a simplex. There are also some definitions for use in calculations where it is convenient to work with affine combinations of vertices together with the circumcenter. ## Main definitions * `circumcenter` and `circumradius` are the circumcenter and circumradius of a simplex. ## References * https://en.wikipedia.org/wiki/Circumscribed_circle -/ namespace euclidean_geometry open inner_product_geometry variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V open affine_subspace /-- `p` is equidistant from two points in `s` if and only if its `orthogonal_projection` is. -/ lemma dist_eq_iff_dist_orthogonal_projection_eq {s : affine_subspace ℝ P} {p1 p2 : P} (p3 : P) (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) : dist p1 p3 = dist p2 p3 ↔ dist p1 (orthogonal_projection s p3) = dist p2 (orthogonal_projection s p3) := begin rw [←mul_self_inj_of_nonneg dist_nonneg dist_nonneg, ←mul_self_inj_of_nonneg dist_nonneg dist_nonneg, dist_square_eq_dist_orthogonal_projection_square_add_dist_orthogonal_projection_square p3 hp1, dist_square_eq_dist_orthogonal_projection_square_add_dist_orthogonal_projection_square p3 hp2], simp end /-- `p` is equidistant from a set of points in `s` if and only if its `orthogonal_projection` is. -/ lemma dist_set_eq_iff_dist_orthogonal_projection_eq {s : affine_subspace ℝ P} {ps : set P} (hps : ps ⊆ s) (p : P) : (set.pairwise_on ps (λ p1 p2, dist p1 p = dist p2 p) ↔ (set.pairwise_on ps (λ p1 p2, dist p1 (orthogonal_projection s p) = dist p2 (orthogonal_projection s p)))) := ⟨λ h p1 hp1 p2 hp2 hne, (dist_eq_iff_dist_orthogonal_projection_eq p (hps hp1) (hps hp2)).1 (h p1 hp1 p2 hp2 hne), λ h p1 hp1 p2 hp2 hne, (dist_eq_iff_dist_orthogonal_projection_eq p (hps hp1) (hps hp2)).2 (h p1 hp1 p2 hp2 hne)⟩ /-- There exists `r` such that `p` has distance `r` from all the points of a set of points in `s` if and only if there exists (possibly different) `r` such that its `orthogonal_projection` has that distance from all the points in that set. -/ lemma exists_dist_eq_iff_exists_dist_orthogonal_projection_eq {s : affine_subspace ℝ P} {ps : set P} (hps : ps ⊆ s) (p : P) : (∃ r, ∀ p1 ∈ ps, dist p1 p = r) ↔ ∃ r, ∀ p1 ∈ ps, dist p1 (orthogonal_projection s p) = r := begin have h := dist_set_eq_iff_dist_orthogonal_projection_eq hps p, simp_rw set.pairwise_on_eq_iff_exists_eq at h, exact h end /-- The induction step for the existence and uniqueness of the circumcenter. Given a nonempty set of points in a nonempty affine subspace whose direction is complete, such that there is a unique (circumcenter, circumradius) pair for those points in that subspace, and a point `p` not in that subspace, there is a unique (circumcenter, circumradius) pair for the set with `p` added, in the span of the subspace with `p` added. -/ lemma exists_unique_dist_eq_of_insert {s : affine_subspace ℝ P} (hc : is_complete (s.direction : set V)) {ps : set P} (hnps : ps.nonempty) {p : P} (hps : ps ⊆ s) (hp : p ∉ s) (hu : ∃! cccr : (P × ℝ), cccr.fst ∈ s ∧ ∀ p1 ∈ ps, dist p1 cccr.fst = cccr.snd) : ∃! cccr₂ : (P × ℝ), cccr₂.fst ∈ affine_span ℝ (insert p (s : set P)) ∧ ∀ p1 ∈ insert p ps, dist p1 cccr₂.fst = cccr₂.snd := begin have hn : (s : set P).nonempty := hnps.mono hps, rcases hu with ⟨⟨cc, cr⟩, ⟨hcc, hcr⟩, hcccru⟩, simp only [prod.fst, prod.snd] at hcc hcr hcccru, let x := dist cc (orthogonal_projection s p), let y := dist p (orthogonal_projection s p), have hy0 : y ≠ 0 := dist_orthogonal_projection_ne_zero_of_not_mem hn hc hp, let ycc₂ := (x * x + y * y - cr * cr) / (2 * y), let cc₂ := (ycc₂ / y) • (p -ᵥ orthogonal_projection s p : V) +ᵥ cc, let cr₂ := real.sqrt (cr * cr + ycc₂ * ycc₂), use (cc₂, cr₂), simp only [prod.fst, prod.snd], have hpo : p = (1 : ℝ) • (p -ᵥ orthogonal_projection s p : V) +ᵥ orthogonal_projection s p, { simp }, split, { split, { refine vadd_mem_of_mem_direction _ (mem_affine_span ℝ (set.mem_insert_of_mem _ hcc)), rw direction_affine_span, exact submodule.smul_mem _ _ (vsub_mem_vector_span ℝ (set.mem_insert _ _) (set.mem_insert_of_mem _ (orthogonal_projection_mem hn hc _))) }, { intros p1 hp1, rw [←mul_self_inj_of_nonneg dist_nonneg (real.sqrt_nonneg _), real.mul_self_sqrt (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _))], cases hp1, { rw hp1, rw [hpo, dist_square_smul_orthogonal_vadd_smul_orthogonal_vadd (orthogonal_projection_mem hn hc p) hcc _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s p), ←dist_eq_norm_vsub V p, dist_comm _ cc], field_simp [hy0], ring }, { rw [dist_square_eq_dist_orthogonal_projection_square_add_dist_orthogonal_projection_square _ (hps hp1), orthogonal_projection_vadd_smul_vsub_orthogonal_projection hc _ _ hcc, hcr p1 hp1, dist_eq_norm_vsub V cc₂ cc, vadd_vsub, norm_smul, ←dist_eq_norm_vsub V, real.norm_eq_abs, abs_div, abs_of_nonneg dist_nonneg, div_mul_cancel _ hy0, abs_mul_abs_self] } } }, { rintros ⟨cc₃, cr₃⟩ ⟨hcc₃, hcr₃⟩, simp only [prod.fst, prod.snd] at hcc₃ hcr₃, rw mem_affine_span_insert_iff (orthogonal_projection_mem hn hc p) at hcc₃, rcases hcc₃ with ⟨t₃, cc₃', hcc₃', hcc₃⟩, have hcr₃' : ∃ r, ∀ p1 ∈ ps, dist p1 cc₃ = r := ⟨cr₃, λ p1 hp1, hcr₃ p1 (set.mem_insert_of_mem _ hp1)⟩, rw [exists_dist_eq_iff_exists_dist_orthogonal_projection_eq hps cc₃, hcc₃, orthogonal_projection_vadd_smul_vsub_orthogonal_projection hc _ _ hcc₃'] at hcr₃', cases hcr₃' with cr₃' hcr₃', have hu := hcccru (cc₃', cr₃'), simp only [prod.fst, prod.snd] at hu, replace hu := hu ⟨hcc₃', hcr₃'⟩, rw prod.ext_iff at hu, simp only [prod.fst, prod.snd] at hu, cases hu with hucc hucr, substs hucc hucr, have hcr₃val : cr₃ = real.sqrt (cr₃' * cr₃' + (t₃ * y) * (t₃ * y)), { cases hnps with p0 hp0, rw [←hcr₃ p0 (set.mem_insert_of_mem _ hp0), hcc₃, ←mul_self_inj_of_nonneg dist_nonneg (real.sqrt_nonneg _), real.mul_self_sqrt (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _)), dist_square_eq_dist_orthogonal_projection_square_add_dist_orthogonal_projection_square _ (hps hp0), orthogonal_projection_vadd_smul_vsub_orthogonal_projection hc _ _ hcc₃', hcr p0 hp0, dist_eq_norm_vsub V _ cc₃', vadd_vsub, norm_smul, ←dist_eq_norm_vsub V p, real.norm_eq_abs, ←mul_assoc, mul_comm _ (abs t₃), ←mul_assoc, abs_mul_abs_self], ring }, replace hcr₃ := hcr₃ p (set.mem_insert _ _), rw [hpo, hcc₃, hcr₃val, ←mul_self_inj_of_nonneg dist_nonneg (real.sqrt_nonneg _), dist_square_smul_orthogonal_vadd_smul_orthogonal_vadd (orthogonal_projection_mem hn hc p) hcc₃' _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s p), dist_comm, ←dist_eq_norm_vsub V p, real.mul_self_sqrt (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _))] at hcr₃, change x * x + _ * (y * y) = _ at hcr₃, rw [(show x * x + (1 - t₃) * (1 - t₃) * (y * y) = x * x + y * y - 2 * y * (t₃ * y) + t₃ * y * (t₃ * y), by ring), add_left_inj] at hcr₃, have ht₃ : t₃ = ycc₂ / y, { field_simp [←hcr₃, hy0], ring }, subst ht₃, change cc₃ = cc₂ at hcc₃, congr', rw hcr₃val, congr' 2, field_simp [hy0], ring } end /-- Given a finite nonempty affinely independent family of points, there is a unique (circumcenter, circumradius) pair for those points in the affine subspace they span. -/ lemma exists_unique_dist_eq_of_affine_independent {ι : Type*} [hne : nonempty ι] [fintype ι] {p : ι → P} (ha : affine_independent ℝ p) : ∃! cccr : (P × ℝ), cccr.fst ∈ affine_span ℝ (set.range p) ∧ ∀ i, dist (p i) cccr.fst = cccr.snd := begin generalize' hn : fintype.card ι = n, unfreezingI { induction n with m hm generalizing ι }, { exfalso, have h := fintype.card_pos_iff.2 hne, rw hn at h, exact lt_irrefl 0 h }, { cases m, { rw fintype.card_eq_one_iff at hn, cases hn with i hi, haveI : unique ι := ⟨⟨i⟩, hi⟩, use (p i, 0), simp only [prod.fst, prod.snd, set.range_unique, affine_subspace.mem_affine_span_singleton], split, { simp_rw [hi (default ι)], use rfl, intro i1, rw hi i1, exact dist_self _ }, { rintros ⟨cc, cr⟩, simp only [prod.fst, prod.snd], rintros ⟨rfl, hdist⟩, rw hi (default ι), congr', rw ←hdist (default ι), exact dist_self _ } }, { have i := hne.some, let ι2 := {x // x ≠ i}, have hc : fintype.card ι2 = m + 1, { rw fintype.card_of_subtype (finset.univ.filter (λ x, x ≠ i)), { rw finset.filter_not, simp_rw eq_comm, rw [finset.filter_eq, if_pos (finset.mem_univ _), finset.card_sdiff (finset.subset_univ _), finset.card_singleton, finset.card_univ, hn], simp }, { simp } }, haveI : nonempty ι2 := fintype.card_pos_iff.1 (hc.symm ▸ nat.zero_lt_succ _), have ha2 : affine_independent ℝ (λ i2 : ι2, p i2) := affine_independent_subtype_of_affine_independent ha _, replace hm := hm ha2 hc, have hr : set.range p = insert (p i) (set.range (λ i2 : ι2, p i2)), { change _ = insert _ (set.range (λ i2 : {x | x ≠ i}, p i2)), rw [←set.image_eq_range, ←set.image_univ, ←set.image_insert_eq], congr' with j, simp [classical.em] }, change ∃! (cccr : P × ℝ), (_ ∧ ∀ i2, (λ q, dist q cccr.fst = cccr.snd) (p i2)), conv { congr, funext, conv { congr, skip, rw ←set.forall_range_iff } }, dsimp only, rw hr, change ∃! (cccr : P × ℝ), (_ ∧ ∀ (i2 : ι2), (λ q, dist q cccr.fst = cccr.snd) (p i2)) at hm, conv at hm { congr, funext, conv { congr, skip, rw ←set.forall_range_iff } }, rw ←affine_span_insert_affine_span, refine exists_unique_dist_eq_of_insert (submodule.complete_of_finite_dimensional _) (set.range_nonempty _) (subset_span_points ℝ _) _ hm, convert not_mem_affine_span_diff_of_affine_independent ha i set.univ, change set.range (λ i2 : {x | x ≠ i}, p i2) = _, rw ←set.image_eq_range, congr' with j, simp, refl } } end end euclidean_geometry namespace affine namespace simplex open finset affine_subspace euclidean_geometry variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V /-- The pair (circumcenter, circumradius) of a simplex. -/ def circumcenter_circumradius {n : ℕ} (s : simplex ℝ P n) : (P × ℝ) := (exists_unique_dist_eq_of_affine_independent s.independent).some /-- The property satisfied by the (circumcenter, circumradius) pair. -/ lemma circumcenter_circumradius_unique_dist_eq {n : ℕ} (s : simplex ℝ P n) : (s.circumcenter_circumradius.fst ∈ affine_span ℝ (set.range s.points) ∧ ∀ i, dist (s.points i) s.circumcenter_circumradius.fst = s.circumcenter_circumradius.snd) ∧ (∀ cccr : (P × ℝ), (cccr.fst ∈ affine_span ℝ (set.range s.points) ∧ ∀ i, dist (s.points i) cccr.fst = cccr.snd) → cccr = s.circumcenter_circumradius) := (exists_unique_dist_eq_of_affine_independent s.independent).some_spec /-- The circumcenter of a simplex. -/ def circumcenter {n : ℕ} (s : simplex ℝ P n) : P := s.circumcenter_circumradius.fst /-- The circumradius of a simplex. -/ def circumradius {n : ℕ} (s : simplex ℝ P n) : ℝ := s.circumcenter_circumradius.snd /-- The circumcenter lies in the affine span. -/ lemma circumcenter_mem_affine_span {n : ℕ} (s : simplex ℝ P n) : s.circumcenter ∈ affine_span ℝ (set.range s.points) := s.circumcenter_circumradius_unique_dist_eq.1.1 /-- All points have distance from the circumcenter equal to the circumradius. -/ @[simp] lemma dist_circumcenter_eq_circumradius {n : ℕ} (s : simplex ℝ P n) : ∀ i, dist (s.points i) s.circumcenter = s.circumradius := s.circumcenter_circumradius_unique_dist_eq.1.2 /-- All points have distance to the circumcenter equal to the circumradius. -/ @[simp] lemma dist_circumcenter_eq_circumradius' {n : ℕ} (s : simplex ℝ P n) : ∀ i, dist s.circumcenter (s.points i) = s.circumradius := begin intro i, rw dist_comm, exact dist_circumcenter_eq_circumradius _ _ end /-- Given a point in the affine span from which all the points are equidistant, that point is the circumcenter. -/ lemma eq_circumcenter_of_dist_eq {n : ℕ} (s : simplex ℝ P n) {p : P} (hp : p ∈ affine_span ℝ (set.range s.points)) {r : ℝ} (hr : ∀ i, dist (s.points i) p = r) : p = s.circumcenter := begin have h := s.circumcenter_circumradius_unique_dist_eq.2 (p, r), simp only [hp, hr, forall_const, eq_self_iff_true, and_self, prod.ext_iff] at h, exact h.1 end /-- Given a point in the affine span from which all the points are equidistant, that distance is the circumradius. -/ lemma eq_circumradius_of_dist_eq {n : ℕ} (s : simplex ℝ P n) {p : P} (hp : p ∈ affine_span ℝ (set.range s.points)) {r : ℝ} (hr : ∀ i, dist (s.points i) p = r) : r = s.circumradius := begin have h := s.circumcenter_circumradius_unique_dist_eq.2 (p, r), simp only [hp, hr, forall_const, eq_self_iff_true, and_self, prod.ext_iff] at h, exact h.2 end /-- The circumradius is non-negative. -/ lemma circumradius_nonneg {n : ℕ} (s : simplex ℝ P n) : 0 ≤ s.circumradius := s.dist_circumcenter_eq_circumradius 0 ▸ dist_nonneg /-- The circumradius of a simplex with at least two points is positive. -/ lemma circumradius_pos {n : ℕ} (s : simplex ℝ P (n + 1)) : 0 < s.circumradius := begin refine lt_of_le_of_ne s.circumradius_nonneg _, intro h, have hr := s.dist_circumcenter_eq_circumradius, simp_rw [←h, dist_eq_zero] at hr, have h01 := (injective_of_affine_independent s.independent).ne (dec_trivial : (0 : fin (n + 2)) ≠ 1), simpa [hr] using h01 end /-- The circumcenter of a 0-simplex equals its unique point. -/ lemma circumcenter_eq_point (s : simplex ℝ P 0) (i : fin 1) : s.circumcenter = s.points i := begin have h := s.circumcenter_mem_affine_span, rw [set.range_unique, mem_affine_span_singleton] at h, rw h, congr end /-- The circumcenter of a 1-simplex equals its centroid. -/ lemma circumcenter_eq_centroid (s : simplex ℝ P 1) : s.circumcenter = finset.univ.centroid ℝ s.points := begin have hr : set.pairwise_on set.univ (λ i j : fin 2, dist (s.points i) (finset.univ.centroid ℝ s.points) = dist (s.points j) (finset.univ.centroid ℝ s.points)), { intros i hi j hj hij, rw [finset.centroid_insert_singleton_fin, dist_eq_norm_vsub V (s.points i), dist_eq_norm_vsub V (s.points j), vsub_vadd_eq_vsub_sub, vsub_vadd_eq_vsub_sub, ←one_smul ℝ (s.points i -ᵥ s.points 0), ←one_smul ℝ (s.points j -ᵥ s.points 0)], fin_cases i; fin_cases j; simp [-one_smul, ←sub_smul]; norm_num }, rw set.pairwise_on_eq_iff_exists_eq at hr, cases hr with r hr, exact (s.eq_circumcenter_of_dist_eq (centroid_mem_affine_span_of_card_eq_add_one ℝ _ (finset.card_fin 2)) (λ i, hr i (set.mem_univ _))).symm end /-- If there exists a distance that a point has from all vertices of a simplex, the orthogonal projection of that point onto the subspace spanned by that simplex is its circumcenter. -/ lemma orthogonal_projection_eq_circumcenter_of_exists_dist_eq {n : ℕ} (s : simplex ℝ P n) {p : P} (hr : ∃ r, ∀ i, dist (s.points i) p = r) : orthogonal_projection (affine_span ℝ (set.range s.points)) p = s.circumcenter := begin change ∃ r : ℝ, ∀ i, (λ x, dist x p = r) (s.points i) at hr, conv at hr { congr, funext, rw ←set.forall_range_iff }, rw exists_dist_eq_iff_exists_dist_orthogonal_projection_eq (subset_affine_span ℝ _) p at hr, cases hr with r hr, rw set.forall_range_iff at hr, exact s.eq_circumcenter_of_dist_eq (orthogonal_projection_mem ((affine_span_nonempty ℝ _).2 (set.range_nonempty _)) (submodule.complete_of_finite_dimensional _) p) hr end /-- If a point has the same distance from all vertices of a simplex, the orthogonal projection of that point onto the subspace spanned by that simplex is its circumcenter. -/ lemma orthogonal_projection_eq_circumcenter_of_dist_eq {n : ℕ} (s : simplex ℝ P n) {p : P} {r : ℝ} (hr : ∀ i, dist (s.points i) p = r) : orthogonal_projection (affine_span ℝ (set.range s.points)) p = s.circumcenter := s.orthogonal_projection_eq_circumcenter_of_exists_dist_eq ⟨r, hr⟩ /-- The orthogonal projection of the circumcenter onto a face is the circumcenter of that face. -/ lemma orthogonal_projection_circumcenter {n : ℕ} (s : simplex ℝ P n) {fs : finset (fin (n + 1))} {m : ℕ} (h : fs.card = m + 1) : orthogonal_projection (affine_span ℝ (s.points '' ↑fs)) s.circumcenter = (s.face h).circumcenter := begin have hr : ∃ r, ∀ i, dist ((s.face h).points i) s.circumcenter = r, { use s.circumradius, simp [face_points] }, rw [←range_face_points, orthogonal_projection_eq_circumcenter_of_exists_dist_eq _ hr] end /-- Two simplices with the same points have the same circumcenter. -/ lemma circumcenter_eq_of_range_eq {n : ℕ} {s₁ s₂ : simplex ℝ P n} (h : set.range s₁.points = set.range s₂.points) : s₁.circumcenter = s₂.circumcenter := begin have hs : s₁.circumcenter ∈ affine_span ℝ (set.range s₂.points) := h ▸ s₁.circumcenter_mem_affine_span, have hr : ∀ i, dist (s₂.points i) s₁.circumcenter = s₁.circumradius, { intro i, have hi : s₂.points i ∈ set.range s₂.points := set.mem_range_self _, rw [←h, set.mem_range] at hi, rcases hi with ⟨j, hj⟩, rw [←hj, s₁.dist_circumcenter_eq_circumradius j] }, exact s₂.eq_circumcenter_of_dist_eq hs hr end omit V /-- An index type for the vertices of a simplex plus its circumcenter. This is for use in calculations where it is convenient to work with affine combinations of vertices together with the circumcenter. (An equivalent form sometimes used in the literature is placing the circumcenter at the origin and working with vectors for the vertices.) -/ @[derive fintype] inductive points_with_circumcenter_index (n : ℕ) | point_index : fin (n + 1) → points_with_circumcenter_index | circumcenter_index : points_with_circumcenter_index open points_with_circumcenter_index instance points_with_circumcenter_index_inhabited (n : ℕ) : inhabited (points_with_circumcenter_index n) := ⟨circumcenter_index⟩ /-- `point_index` as an embedding. -/ def point_index_embedding (n : ℕ) : fin (n + 1) ↪ points_with_circumcenter_index n := ⟨λ i, point_index i, λ _ _ h, by injection h⟩ /-- The sum of a function over `points_with_circumcenter_index`. -/ lemma sum_points_with_circumcenter {α : Type*} [add_comm_monoid α] {n : ℕ} (f : points_with_circumcenter_index n → α) : ∑ i, f i = (∑ (i : fin (n + 1)), f (point_index i)) + f circumcenter_index := begin have h : univ = insert circumcenter_index (univ.map (point_index_embedding n)), { ext x, refine ⟨λ h, _, λ _, mem_univ _⟩, cases x with i, { exact mem_insert_of_mem (mem_map_of_mem _ (mem_univ i)) }, { exact mem_insert_self _ _ } }, change _ = ∑ i, f (point_index_embedding n i) + _, rw [add_comm, h, ←sum_map, sum_insert], simp_rw [mem_map, not_exists], intros x hx h, injection h end include V /-- The vertices of a simplex plus its circumcenter. -/ def points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) : points_with_circumcenter_index n → P | (point_index i) := s.points i | circumcenter_index := s.circumcenter /-- `points_with_circumcenter`, applied to a `point_index` value, equals `points` applied to that value. -/ @[simp] lemma points_with_circumcenter_point {n : ℕ} (s : simplex ℝ P n) (i : fin (n + 1)) : s.points_with_circumcenter (point_index i) = s.points i := rfl /-- `points_with_circumcenter`, applied to `circumcenter_index`, equals the circumcenter. -/ @[simp] lemma points_with_circumcenter_eq_circumcenter {n : ℕ} (s : simplex ℝ P n) : s.points_with_circumcenter circumcenter_index = s.circumcenter := rfl omit V /-- The weights for a single vertex of a simplex, in terms of `points_with_circumcenter`. -/ def point_weights_with_circumcenter {n : ℕ} (i : fin (n + 1)) : points_with_circumcenter_index n → ℝ | (point_index j) := if j = i then 1 else 0 | circumcenter_index := 0 /-- `point_weights_with_circumcenter` sums to 1. -/ @[simp] lemma sum_point_weights_with_circumcenter {n : ℕ} (i : fin (n + 1)) : ∑ j, point_weights_with_circumcenter i j = 1 := begin convert sum_ite_eq' univ (point_index i) (function.const _ (1 : ℝ)), { ext j, cases j ; simp [point_weights_with_circumcenter] }, { simp } end include V /-- A single vertex, in terms of `points_with_circumcenter`. -/ lemma point_eq_affine_combination_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) (i : fin (n + 1)) : s.points i = (univ : finset (points_with_circumcenter_index n)).affine_combination s.points_with_circumcenter (point_weights_with_circumcenter i) := begin rw ←points_with_circumcenter_point, symmetry, refine affine_combination_of_eq_one_of_eq_zero _ _ _ (mem_univ _) (by simp [point_weights_with_circumcenter]) _, intros i hi hn, cases i, { have h : i_1 ≠ i := λ h, hn (h ▸ rfl), simp [point_weights_with_circumcenter, h] }, { refl } end omit V /-- The weights for the centroid of some vertices of a simplex, in terms of `points_with_circumcenter`. -/ def centroid_weights_with_circumcenter {n : ℕ} (fs : finset (fin (n + 1))) : points_with_circumcenter_index n → ℝ | (point_index i) := if i ∈ fs then ((card fs : ℝ) ⁻¹) else 0 | circumcenter_index := 0 /-- `centroid_weights_with_circumcenter` sums to 1, if the `finset` is nonempty. -/ @[simp] lemma sum_centroid_weights_with_circumcenter {n : ℕ} {fs : finset (fin (n + 1))} (h : fs.nonempty) : ∑ i, centroid_weights_with_circumcenter fs i = 1 := begin simp_rw [sum_points_with_circumcenter, centroid_weights_with_circumcenter, add_zero, ←fs.sum_centroid_weights_eq_one_of_nonempty ℝ h, set.sum_indicator_subset _ fs.subset_univ], rcongr end include V /-- The centroid of some vertices of a simplex, in terms of `points_with_circumcenter`. -/ lemma centroid_eq_affine_combination_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) (fs : finset (fin (n + 1))) : fs.centroid ℝ s.points = (univ : finset (points_with_circumcenter_index n)).affine_combination s.points_with_circumcenter (centroid_weights_with_circumcenter fs) := begin simp_rw [centroid_def, affine_combination_apply, weighted_vsub_of_point_apply, sum_points_with_circumcenter, centroid_weights_with_circumcenter, points_with_circumcenter_point, zero_smul, add_zero, centroid_weights, set.sum_indicator_subset_of_eq_zero (function.const (fin (n + 1)) ((card fs : ℝ)⁻¹)) (λ i wi, wi • (s.points i -ᵥ classical.choice add_torsor.nonempty)) fs.subset_univ (λ i, zero_smul ℝ _), set.indicator_apply], rcongr end omit V /-- The weights for the circumcenter of a simplex, in terms of `points_with_circumcenter`. -/ def circumcenter_weights_with_circumcenter (n : ℕ) : points_with_circumcenter_index n → ℝ | (point_index i) := 0 | circumcenter_index := 1 /-- `circumcenter_weights_with_circumcenter` sums to 1. -/ @[simp] lemma sum_circumcenter_weights_with_circumcenter (n : ℕ) : ∑ i, circumcenter_weights_with_circumcenter n i = 1 := begin convert sum_ite_eq' univ circumcenter_index (function.const _ (1 : ℝ)), { ext ⟨j⟩ ; simp [circumcenter_weights_with_circumcenter] }, { simp }, { exact classical.dec_eq _ } end include V /-- The circumcenter of a simplex, in terms of `points_with_circumcenter`. -/ lemma circumcenter_eq_affine_combination_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) : s.circumcenter = (univ : finset (points_with_circumcenter_index n)).affine_combination s.points_with_circumcenter (circumcenter_weights_with_circumcenter n) := begin rw ←points_with_circumcenter_eq_circumcenter, symmetry, refine affine_combination_of_eq_one_of_eq_zero _ _ _ (mem_univ _) rfl _, rintros ⟨i⟩ hi hn ; tauto end omit V /-- The weights for the reflection of the circumcenter in an edge of a simplex. This definition is only valid with `i₁ ≠ i₂`. -/ def reflection_circumcenter_weights_with_circumcenter {n : ℕ} (i₁ i₂ : fin (n + 1)) : points_with_circumcenter_index n → ℝ | (point_index i) := if i = i₁ ∨ i = i₂ then 1 else 0 | circumcenter_index := -1 /-- `reflection_circumcenter_weights_with_circumcenter` sums to 1. -/ @[simp] lemma sum_reflection_circumcenter_weights_with_circumcenter {n : ℕ} {i₁ i₂ : fin (n + 1)} (h : i₁ ≠ i₂) : ∑ i, reflection_circumcenter_weights_with_circumcenter i₁ i₂ i = 1 := begin simp_rw [sum_points_with_circumcenter, reflection_circumcenter_weights_with_circumcenter, sum_ite, sum_const, filter_or, filter_eq'], rw card_union_eq, { simp }, { simp [h.symm] } end include V /-- The reflection of the circumcenter of a simplex in an edge, in terms of `points_with_circumcenter`. -/ lemma reflection_circumcenter_eq_affine_combination_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) {i₁ i₂ : fin (n + 1)} (h : i₁ ≠ i₂) : reflection (affine_span ℝ (s.points '' {i₁, i₂})) s.circumcenter = (univ : finset (points_with_circumcenter_index n)).affine_combination s.points_with_circumcenter (reflection_circumcenter_weights_with_circumcenter i₁ i₂) := begin have hc : card ({i₁, i₂} : finset (fin (n + 1))) = 2, { simp [h] }, rw [reflection_apply, ←coe_singleton, ←coe_insert, s.orthogonal_projection_circumcenter hc, circumcenter_eq_centroid, s.face_centroid_eq_centroid hc, centroid_eq_affine_combination_of_points_with_circumcenter, circumcenter_eq_affine_combination_of_points_with_circumcenter, ←@vsub_eq_zero_iff_eq V, affine_combination_vsub, weighted_vsub_vadd_affine_combination, affine_combination_vsub, weighted_vsub_apply, sum_points_with_circumcenter], simp_rw [pi.sub_apply, pi.add_apply, pi.sub_apply, sub_smul, add_smul, sub_smul, centroid_weights_with_circumcenter, circumcenter_weights_with_circumcenter, reflection_circumcenter_weights_with_circumcenter, ite_smul, zero_smul, sub_zero, apply_ite2 (+), add_zero, ←add_smul, hc, zero_sub, neg_smul, sub_self, add_zero], convert sum_const_zero, norm_num end end simplex end affine namespace euclidean_geometry open affine affine_subspace finite_dimensional variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V /-- Given a nonempty affine subspace, whose direction is complete, that contains a set of points, those points are cospherical if and only if they are equidistant from some point in that subspace. -/ lemma cospherical_iff_exists_mem_of_complete {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) (hn : (s : set P).nonempty) (hc : is_complete (s.direction : set V)) : cospherical ps ↔ ∃ (center ∈ s) (radius : ℝ), ∀ p ∈ ps, dist p center = radius := begin split, { rintro ⟨c, hcr⟩, rw exists_dist_eq_iff_exists_dist_orthogonal_projection_eq h c at hcr, exact ⟨orthogonal_projection s c, orthogonal_projection_mem hn hc _, hcr⟩ }, { exact λ ⟨c, hc, hd⟩, ⟨c, hd⟩ } end /-- Given a nonempty affine subspace, whose direction is finite-dimensional, that contains a set of points, those points are cospherical if and only if they are equidistant from some point in that subspace. -/ lemma cospherical_iff_exists_mem_of_finite_dimensional {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) (hn : (s : set P).nonempty) [finite_dimensional ℝ s.direction] : cospherical ps ↔ ∃ (center ∈ s) (radius : ℝ), ∀ p ∈ ps, dist p center = radius := cospherical_iff_exists_mem_of_complete h hn (submodule.complete_of_finite_dimensional _) /-- All n-simplices among cospherical points in an n-dimensional subspace have the same circumradius. -/ lemma exists_circumradius_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) (hn : (s : set P).nonempty) {n : ℕ} [finite_dimensional ℝ s.direction] (hd : findim ℝ s.direction = n) (hc : cospherical ps) : ∃ r : ℝ, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumradius = r := begin rw cospherical_iff_exists_mem_of_finite_dimensional h hn at hc, rcases hc with ⟨c, hc, r, hcr⟩, use r, intros sx hsxps, have hsx : affine_span ℝ (set.range sx.points) = s, { refine affine_span_eq_of_le_of_affine_independent_of_card_eq_findim_add_one sx.independent (span_points_subset_coe_of_subset_coe (set.subset.trans hsxps h)) _, simp [hd] }, have hc : c ∈ affine_span ℝ (set.range sx.points) := hsx.symm ▸ hc, exact (sx.eq_circumradius_of_dist_eq hc (λ i, hcr (sx.points i) (hsxps (set.mem_range_self i)))).symm end /-- Two n-simplices among cospherical points in an n-dimensional subspace have the same circumradius. -/ lemma circumradius_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) (hn : (s : set P).nonempty) {n : ℕ} [finite_dimensional ℝ s.direction] (hd : findim ℝ s.direction = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n} (hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) : sx₁.circumradius = sx₂.circumradius := begin rcases exists_circumradius_eq_of_cospherical_subset h hn hd hc with ⟨r, hr⟩, rw [hr sx₁ hsx₁, hr sx₂ hsx₂] end /-- All n-simplices among cospherical points in n-space have the same circumradius. -/ lemma exists_circumradius_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V] (hd : findim ℝ V = n) (hc : cospherical ps) : ∃ r : ℝ, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumradius = r := begin rw [←findim_top, ←direction_top ℝ V P] at hd, refine exists_circumradius_eq_of_cospherical_subset _ ⟨add_torsor.nonempty.some, mem_top _ _ _⟩ hd hc, exact set.subset_univ _ end /-- Two n-simplices among cospherical points in n-space have the same circumradius. -/ lemma circumradius_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V] (hd : findim ℝ V = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n} (hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) : sx₁.circumradius = sx₂.circumradius := begin rcases exists_circumradius_eq_of_cospherical hd hc with ⟨r, hr⟩, rw [hr sx₁ hsx₁, hr sx₂ hsx₂] end /-- All n-simplices among cospherical points in an n-dimensional subspace have the same circumcenter. -/ lemma exists_circumcenter_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) (hn : (s : set P).nonempty) {n : ℕ} [finite_dimensional ℝ s.direction] (hd : findim ℝ s.direction = n) (hc : cospherical ps) : ∃ c : P, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumcenter = c := begin rw cospherical_iff_exists_mem_of_finite_dimensional h hn at hc, rcases hc with ⟨c, hc, r, hcr⟩, use c, intros sx hsxps, have hsx : affine_span ℝ (set.range sx.points) = s, { refine affine_span_eq_of_le_of_affine_independent_of_card_eq_findim_add_one sx.independent (span_points_subset_coe_of_subset_coe (set.subset.trans hsxps h)) _, simp [hd] }, have hc : c ∈ affine_span ℝ (set.range sx.points) := hsx.symm ▸ hc, exact (sx.eq_circumcenter_of_dist_eq hc (λ i, hcr (sx.points i) (hsxps (set.mem_range_self i)))).symm end /-- Two n-simplices among cospherical points in an n-dimensional subspace have the same circumcenter. -/ lemma circumcenter_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) (hn : (s : set P).nonempty) {n : ℕ} [finite_dimensional ℝ s.direction] (hd : findim ℝ s.direction = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n} (hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) : sx₁.circumcenter = sx₂.circumcenter := begin rcases exists_circumcenter_eq_of_cospherical_subset h hn hd hc with ⟨r, hr⟩, rw [hr sx₁ hsx₁, hr sx₂ hsx₂] end /-- All n-simplices among cospherical points in n-space have the same circumcenter. -/ lemma exists_circumcenter_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V] (hd : findim ℝ V = n) (hc : cospherical ps) : ∃ c : P, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumcenter = c := begin rw [←findim_top, ←direction_top ℝ V P] at hd, refine exists_circumcenter_eq_of_cospherical_subset _ ⟨add_torsor.nonempty.some, mem_top _ _ _⟩ hd hc, exact set.subset_univ _ end /-- Two n-simplices among cospherical points in n-space have the same circumcenter. -/ lemma circumcenter_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V] (hd : findim ℝ V = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n} (hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) : sx₁.circumcenter = sx₂.circumcenter := begin rcases exists_circumcenter_eq_of_cospherical hd hc with ⟨r, hr⟩, rw [hr sx₁ hsx₁, hr sx₂ hsx₂] end /-- Suppose all distances from `p₁` and `p₂` to the points of a simplex are equal, and that `p₁` and `p₂` lie in the affine span of `p` with the vertices of that simplex. Then `p₁` and `p₂` are equal or reflections of each other in the affine span of the vertices of the simplex. -/ lemma eq_or_eq_reflection_of_dist_eq {n : ℕ} {s : simplex ℝ P n} {p p₁ p₂ : P} {r : ℝ} (hp₁ : p₁ ∈ affine_span ℝ (insert p (set.range s.points))) (hp₂ : p₂ ∈ affine_span ℝ (insert p (set.range s.points))) (h₁ : ∀ i, dist (s.points i) p₁ = r) (h₂ : ∀ i, dist (s.points i) p₂ = r) : p₁ = p₂ ∨ p₁ = reflection (affine_span ℝ (set.range s.points)) p₂ := begin let span_s := affine_span ℝ (set.range s.points), have h₁' := s.orthogonal_projection_eq_circumcenter_of_dist_eq h₁, have h₂' := s.orthogonal_projection_eq_circumcenter_of_dist_eq h₂, have hn : (span_s : set P).nonempty := (affine_span_nonempty ℝ _).2 (set.range_nonempty _), have hc : is_complete (span_s.direction : set V) := submodule.complete_of_finite_dimensional _, rw [←affine_span_insert_affine_span, mem_affine_span_insert_iff (orthogonal_projection_mem hn hc p)] at hp₁ hp₂, obtain ⟨r₁, p₁o, hp₁o, hp₁⟩ := hp₁, obtain ⟨r₂, p₂o, hp₂o, hp₂⟩ := hp₂, obtain rfl : orthogonal_projection span_s p₁ = p₁o, { rw hp₁, exact orthogonal_projection_vadd_smul_vsub_orthogonal_projection hc _ _ hp₁o }, rw h₁' at hp₁, obtain rfl : orthogonal_projection span_s p₂ = p₂o, { rw hp₂, exact orthogonal_projection_vadd_smul_vsub_orthogonal_projection hc _ _ hp₂o }, rw h₂' at hp₂, have h : s.points 0 ∈ span_s := mem_affine_span ℝ (set.mem_range_self _), have hd₁ : dist p₁ s.circumcenter * dist p₁ s.circumcenter = r * r - s.circumradius * s.circumradius, { rw [dist_comm, ←h₁ 0, dist_square_eq_dist_orthogonal_projection_square_add_dist_orthogonal_projection_square p₁ h], simp [h₁', dist_comm p₁] }, have hd₂ : dist p₂ s.circumcenter * dist p₂ s.circumcenter = r * r - s.circumradius * s.circumradius, { rw [dist_comm, ←h₂ 0, dist_square_eq_dist_orthogonal_projection_square_add_dist_orthogonal_projection_square p₂ h], simp [h₂', dist_comm p₂] }, rw [←hd₂, hp₁, hp₂, dist_eq_norm_vsub V _ s.circumcenter, dist_eq_norm_vsub V _ s.circumcenter, vadd_vsub, vadd_vsub, ←real_inner_self_eq_norm_square, ←real_inner_self_eq_norm_square, real_inner_smul_left, real_inner_smul_left, real_inner_smul_right, real_inner_smul_right, ←mul_assoc, ←mul_assoc] at hd₁, by_cases hp : p = orthogonal_projection span_s p, { rw [hp₁, hp₂, ←hp], simp }, { have hz : ⟪p -ᵥ orthogonal_projection span_s p, p -ᵥ orthogonal_projection span_s p⟫ ≠ 0, { simpa using hp }, rw [mul_left_inj' hz, mul_self_eq_mul_self_iff] at hd₁, rw [hp₁, hp₂], cases hd₁, { left, rw hd₁ }, { right, rw [hd₁, reflection_vadd_smul_vsub_orthogonal_projection hc p r₂ s.circumcenter_mem_affine_span, neg_smul] } } end end euclidean_geometry
d4701ccc28c8760aeeffe9c0561bbfbf1f994553
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/tactic/auto_cases.lean
aea99d2432ad36643d2a0a706a7d35578a34c3b6
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
1,722
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import logic.basic import tactic.core import data.option.defs import tactic.hint open tactic meta def auto_cases_at (h : expr) : tactic string := do t' ← infer_type h, t' ← whnf t', let use_cases := match t' with | `(empty) := tt | `(pempty) := tt | `(false) := tt | `(unit) := tt | `(punit) := tt | `(ulift _) := tt | `(plift _) := tt | `(prod _ _) := tt | `(and _ _) := tt | `(sigma _) := tt | `(psigma _) := tt | `(subtype _) := tt | `(Exists _) := tt | `(fin 0) := tt | `(sum _ _) := tt -- This is perhaps dangerous! | `(or _ _) := tt -- This is perhaps dangerous! | `(iff _ _) := tt -- This is perhaps dangerous! | _ := ff end, if use_cases then do cases h, pp ← pp h, return ("cases " ++ pp.to_string) else match t' with -- `cases` can be dangerous on `eq` and `quot`, producing mysterious errors during type checking. -- instead we attempt `induction` | `(eq _ _) := do induction h, pp ← pp h, return ("induction " ++ pp.to_string) | `(quot _) := do induction h, pp ← pp h, return ("induction " ++ pp.to_string) | _ := failed end /-- Applies `cases` or `induction` on certain hypotheses. -/ @[hint_tactic] meta def auto_cases : tactic string := do l ← local_context, results ← successes (l.reverse.map(λ h, auto_cases_at h)), when (results.empty) (fail "`auto_cases` did not find any hypotheses to apply `cases` or `induction` to"), return (string.intercalate ", " results)
552fb8566c81e281d65b05dc89cf6b96aa3d58b8
94096349332b0a0e223a22a3917c8f253cd39235
/src/solutions/world3_le.lean
523424b273c5b9dcd7021b89309f4a6cf6d6816e
[]
no_license
robertylewis/natural_number_game
26156e10ef7b45248549915cc4d1ab3d8c3afc85
b210c05cd627242f791db1ee3f365ee7829674c9
refs/heads/master
1,598,964,725,038
1,572,602,236,000
1,572,602,236,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,102
lean
import mynat.le import solutions.world2_multiplication import tactic.interactive #check tactic.interactive.rintro meta def less_leaky.interactive.rintro := tactic.interactive.rintro namespace mynat theorem le_refl (a : mynat) : a ≤ a := begin use 0, rw add_zero, end -- ignore this; it's making the "refl" tactic work with goals of the form a ≤ a attribute [_refl_lemma] le_refl theorem le_succ {a b : mynat} (h : a ≤ b) : a ≤ (succ b) := begin cases h with c hc, use (succ c), rw add_succ, rw hc, end example : one ≤ one := le_refl one lemma zero_le (a : mynat) : 0 ≤ a := begin use a, rw' zero_add a, refl end lemma le_zero {a : mynat} : a ≤ 0 → a = 0 := begin intro h, cases h with c hc, rw add_comm at hc, cases a with b, refl, exfalso, rw add_succ at hc, rw eq_comm at hc, exact succ_ne_zero hc, end theorem le_trans ⦃a b c : mynat⦄ (hab : a ≤ b) (hbc : b ≤ c) : a ≤ c := begin -- again no induction cases hab with x hx, cases hbc with y hy, use (x + y), rw ←add_assoc, rw ←hx, assumption, end instance : preorder mynat := by structure_helper theorem lt_iff_le_not_le {a b : mynat} : a < b ↔ a ≤ b ∧ ¬ b ≤ a := iff.rfl theorem le_antisymm : ∀ {{a b : mynat}}, a ≤ b → b ≤ a → a = b := begin intros a b hab hba, cases hab with c hc, cases hba with d hd, rw hc at hd, rw add_assoc at hd, rw eq_comm at hd, have H := eq_zero_of_add_right_eq_self hd, rw eq_comm at hc, convert hc, symmetry, convert add_zero a, exact add_right_eq_zero H, end instance : partial_order mynat := by structure_helper theorem lt_iff_le_and_ne ⦃a b : mynat⦄ : a < b ↔ a ≤ b ∧ a ≠ b := begin split, { intro h, rw lt_iff_le_not_le at h, cases h with hab hba, split, exact hab, intro h, apply hba, rw' h, apply le_refl, }, { intro h, cases h with hab hne, rw lt_iff_le_not_le, split, assumption, intro hba, apply hne, apply le_antisymm hab hba, } end lemma succ_le_succ {a b : mynat} (h : a ≤ b) : succ a ≤ succ b := begin cases h with c hc, use c, rw succ_add, rw hc, end theorem le_total (a b : mynat) : a ≤ b ∨ b ≤ a := begin revert a, induction' b with c hc, intro a, right, apply zero_le, intro a, induction' a with d hd, left, apply zero_le, cases hc d with h h, left, exact succ_le_succ h, right, exact succ_le_succ h, end instance : linear_order mynat := by structure_helper theorem add_le_add_right (a b : mynat) : a ≤ b → ∀ t, (a + t) ≤ (b + t) := begin intros h t, induction' t with d hd, { rw add_zero, rw add_zero, assumption }, { rw add_succ, rw add_succ, exact succ_le_succ hd } end theorem le_succ_self (a : mynat) : a ≤ succ a := begin apply le_succ, apply le_refl end theorem le_of_succ_le_succ {a b : mynat} : succ a ≤ succ b → a ≤ b := begin intro h, cases h with c hc, use c, rw succ_add at hc, exact succ_inj hc, end theorem not_succ_le_self {{d : mynat}} (h : succ d ≤ d) : false := begin cases h with c hc, rw ←add_one_eq_succ at hc, rw add_assoc at hc, rw eq_comm at hc, have h := eq_zero_of_add_right_eq_self hc, rw add_comm at h, rw add_one_eq_succ at h, apply zero_ne_succ c, symmetry, assumption, end theorem add_le_add_left : ∀ (a b : mynat), a ≤ b → ∀ (c : mynat), c + a ≤ c + b := begin intros a b hab c, rw add_comm, rw add_comm c, apply add_le_add_right, assumption end def succ_le_succ_iff (a b : mynat) : succ a ≤ succ b ↔ a ≤ b := begin split, { intro h, cases h with c hc, use c, apply succ_inj, convert hc, rw' succ_add, refl }, { intro h, cases h with c hc, use c, rw succ_add, rw' hc, refl, } end def succ_lt_succ_iff (a b : mynat) : succ a < succ b ↔ a < b := begin rw lt_iff_le_not_le, rw lt_iff_le_not_le, split, intro h, cases h, split, rwa succ_le_succ_iff at h_left, intro h, apply h_right, rwa succ_le_succ_iff, intro h, cases h, split, rwa succ_le_succ_iff, intro h, apply h_right, rwa succ_le_succ_iff at h, end theorem lt_of_add_lt_add_left : ∀ {{a b c : mynat}}, a + b < a + c → b < c := begin intros a b c, intro h, rw add_comm at h, rw add_comm a at h, revert b c, induction a with d hd, intros a b h, exact h, intros b c h, rw [add_succ, add_succ] at h, apply hd, rwa succ_lt_succ_iff at h, end theorem le_iff_exists_add : ∀ (a b : mynat), a ≤ b ↔ ∃ (c : mynat), b = a + c := begin intros a b, refl, end theorem zero_ne_one : (0 : mynat) ≠ 1 := begin symmetry, rw one_eq_succ_zero, apply succ_ne_zero, end instance : ordered_comm_monoid mynat := by structure_helper theorem le_of_add_le_add_left ⦃ a b c : mynat⦄ : a + b ≤ a + c → b ≤ c := begin intro h, cases h with d hd, use d, rw add_assoc at hd, exact add_left_cancel hd end instance : ordered_cancel_comm_monoid mynat := by structure_helper theorem mul_le_mul_of_nonneg_left ⦃a b c : mynat⦄ : a ≤ b → 0 ≤ c → c * a ≤ c * b := begin intro hab, intro hc, cases hab with d hd, rw hd, use c * d, rw' mul_add, refl end theorem mul_le_mul_of_nonneg_right ⦃a b c : mynat⦄ : a ≤ b → 0 ≤ c → a * c ≤ b * c := begin rw mul_comm, rw mul_comm b, apply mul_le_mul_of_nonneg_left end theorem ne_zero_of_pos ⦃a : mynat⦄ : 0 < a → a ≠ 0 := begin intro ha, intro h, rw h at ha, rw lt_iff_le_and_ne at ha, cases ha with h1 h2, apply h2, refl, end theorem mul_lt_mul_of_pos_left ⦃a b c : mynat⦄ : a < b → 0 < c → c * a < c * b := begin intros hab hc, cases' hab with hab hba, rw lt_iff_le_and_ne, split, { cases hab with d hd, use c * d, rw hd, rw' mul_add, refl, }, { intro h, apply hba, have h2 := mul_left_cancel (ne_zero_of_pos hc) h, rw' h2, refl } end theorem mul_lt_mul_of_pos_right ⦃a b c : mynat⦄ : a < b → 0 < c → a * c < b * c := begin rw mul_comm, rw mul_comm b, apply mul_lt_mul_of_pos_left, end instance : ordered_semiring mynat := by structure_helper theorem not_lt_zero ⦃a : mynat⦄ : ¬(a < 0) := begin [less_leaky] -- rintro ⟨ha, hna⟩, -- *TODO* -- rintro doesn't work?? intro h, cases h with ha hna, apply hna, clear hna, --apply le_zero at ha, replace ha := le_zero ha, rw ha, refl, end #check @nat.lt_succ_iff #check @nat.succ_eq_add_one /- nat.lt_succ_iff : ∀ {m n : ℕ}, m < nat.succ n ↔ m ≤ n -/ theorem lt_succ_self (n : mynat) : n < succ n := begin [less_leaky] rw lt_iff_le_and_ne, split, use 1, apply succ_eq_add_one, intro h, exact ne_succ_self n h end theorem lt_succ_iff (m n : mynat) : m < succ n ↔ m ≤ n := begin [less_leaky] rw lt_iff_le_and_ne, split, { rintro ⟨h1, h2⟩, cases h1 with c hc, cases c with d, exfalso, apply h2, rw hc, rw add_zero,refl, use d, apply succ_inj, rw hc, apply add_succ, }, { rintro ⟨c, hc⟩, split, { use succ c, rw hc, rw add_succ, refl }, { rw hc, apply ne_of_lt, rw lt_iff_le_and_ne, split, use succ c, rw add_succ, refl, intro h, rw [succ_eq_add_one, add_assoc] at h, -- doesn't' work yet -- symmetry at h, rw eq_comm at h, replace h := eq_zero_of_add_right_eq_self h, apply zero_ne_succ c, rw ←h, apply add_one_eq_succ } } end -- is this right? @[elab_as_eliminator] theorem strong_induction (P : mynat → Prop) (IH : ∀ m : mynat, (∀ d : mynat, d < m → P d) → P m) : ∀ n, P n := begin [less_leaky] let Q : mynat → Prop := λ m, ∀ d < m, P d, have hQ : ∀ n, Q n, { intro n, induction n with d hd, { intros m hm, exfalso, exact not_lt_zero hm, }, { intro m, intro hm, rw lt_succ_iff at hm, apply IH, intros e he, apply hd, exact lt_of_lt_of_le he hm, } }, intro n, apply hQ (succ n), apply lt_succ_self end lemma lt_irrefl (a : mynat) : ¬ (a < a) := begin intro h, rw lt_iff_le_and_ne at h, cases h with h1 h2, apply h2, refl, end end mynat /- instance : canonically_ordered_comm_semiring mynat := { add := (+), add_assoc := add_assoc, zero := 0, zero_add := zero_add, add_zero := add_zero, add_comm := add_comm, le := (≤), le_refl := le_refl, le_trans := le_trans, le_antisymm := le_antisymm, add_le_add_left := add_le_add_left, lt_of_add_lt_add_left := lt_of_add_lt_add_left, bot := 0, bot_le := zero_le, le_iff_exists_add := le_iff_exists_add, mul := (*), mul_assoc := mul_assoc, one := 1, one_mul := one_mul, mul_one := mul_one, left_distrib := left_distrib, right_distrib := right_distrib, zero_mul := zero_mul, mul_zero := mul_zero, mul_comm := mul_comm, zero_ne_one := zero_ne_one, mul_eq_zero_iff := mul_eq_zero_iff } -/
3d7ea9138fac7d33e79e4e35c98e5ef5ab37631e
56f08640ead9fe2e27938d1d9eee365a2a2d2a57
/library/init/category/state.lean
03c0dc797a4ccb72e8366231283f1beece4edcbb
[ "Apache-2.0" ]
permissive
jean-lucas/lean
06cb5dc6422ae8be50685a2f09be7fc237ac5be6
7c63b2f046ea67ba61b9050bc683520209dc18e3
refs/heads/master
1,629,407,462,945
1,511,782,697,000
1,511,782,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,646
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.interactive universes u v def state (σ α : Type u) : Type u := σ → α × σ section variables {σ α β : Type u} @[inline] def state_return (a : α) : state σ α := λ s, (a, s) @[inline] def state_bind (a : state σ α) (b : α → state σ β) : state σ β := λ s, match (a s) with (a', s') := b a' s' end instance (σ : Type u) : monad (state σ) := {pure := @state_return σ, bind := @state_bind σ, id_map := begin intros, apply funext, intro s, simp [state_bind], cases x s, apply rfl end, pure_bind := by intros; apply rfl, bind_assoc := begin intros, apply funext, intro s, simp [state_bind], cases x s, apply rfl end} end namespace state @[inline] def read {σ : Type u} : state σ σ := λ s, (s, s) @[inline] def write {σ : Type} : σ → state σ unit := λ s' s, ((), s') @[inline] def write' {σ : Type u} : σ → state σ punit := λ s' s, (punit.star, s') end state def state_t (σ : Type u) (m : Type u → Type v) [monad m] (α : Type u) : Type (max u v) := σ → m (α × σ) section variable {σ : Type u} variable {m : Type u → Type v} variable [monad m] variables {α β : Type u} def state_t_return (a : α) : state_t σ m α := λ s, show m (α × σ), from return (a, s) def state_t_bind (act₁ : state_t σ m α) (act₂ : α → state_t σ m β) : state_t σ m β := λ s, show m (β × σ), from do (a, new_s) ← act₁ s, act₂ a new_s end instance (σ : Type u) (m : Type u → Type v) [monad m] : monad (state_t σ m) := {pure := @state_t_return σ m _, bind := @state_t_bind σ m _, id_map := begin intros, apply funext, intro, simp [state_t_bind, state_t_return, function.comp, return], have h : state_t_bind._match_1 (λ (x : α) (s : σ), @pure m _ _ (x, s)) = pure, { apply funext, intro s, cases s, apply rfl }, { rw h, apply @monad.bind_pure _ σ }, end, pure_bind := begin intros, apply funext, intro, simp [state_t_bind, state_t_return, monad.pure_bind] end, bind_assoc := begin intros, apply funext, intro, simp [state_t_bind, state_t_return, monad.bind_assoc], apply congr_arg, apply funext, intro r, cases r, refl end} section variable {σ : Type u} variable {m : Type u → Type v} variable [monad m] variable [alternative m] variable {α : Type u} def state_t_orelse (act₁ act₂ : state_t σ m α) : state_t σ m α := λ s, act₁ s <|> act₂ s def state_t_failure : state_t σ m α := λ s, failure end instance (σ : Type u) (m : Type u → Type v) [alternative m] [monad m] : alternative (state_t σ m) := { failure := @state_t_failure σ m _ _, orelse := @state_t_orelse σ m _ _, ..state_t.monad σ m } namespace state_t def read {σ : Type u} {m : Type u → Type v} [monad m] : state_t σ m σ := λ s, return (s, s) def write {σ : Type} {m : Type → Type v} [monad m] : σ → state_t σ m unit := λ s' s, return ((), s') def write' {σ : Type u} {m : Type u → Type v} [monad m] : σ → state_t σ m punit := λ s' s, return (punit.star, s') def modify {σ : Type} {m : Type → Type v} [monad m] (f : σ → σ) : state_t σ m unit := do s ← read, write (f s) def modify' {σ : Type u} {m : Type u → Type v} [monad m] (f : σ → σ) : state_t σ m punit := do s ← read, write' (f s) def lift {α σ : Type u} {m : Type u → Type v} [monad m] (t : m α) : state_t σ m α := λ s, do a ← t, return (a, s) end state_t
aaffc6b9ebe39d47e0452a574896660e0099de2b
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/group_theory/submonoid/membership.lean
77939521078e88e8552b971664ab4195ae0e8d02
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,109
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Kenny Lau, Johan Commelin, Mario Carneiro, Kevin Buzzard, Amelia Livingston, Yury Kudryashov -/ import group_theory.submonoid.operations import algebra.big_operators.basic import algebra.free_monoid /-! # Submonoids: membership criteria In this file we prove various facts about membership in a submonoid: * `list_prod_mem`, `multiset_prod_mem`, `prod_mem`: if each element of a collection belongs to a multiplicative submonoid, then so does their product; * `list_sum_mem`, `multiset_sum_mem`, `sum_mem`: if each element of a collection belongs to an additive submonoid, then so does their sum; * `pow_mem`, `nsmul_mem`: if `x ∈ S` where `S` is a multiplicative (resp., additive) submonoid and `n` is a natural number, then `x^n` (resp., `n • x`) belongs to `S`; * `mem_supr_of_directed`, `coe_supr_of_directed`, `mem_Sup_of_directed_on`, `coe_Sup_of_directed_on`: the supremum of a directed collection of submonoid is their union. * `sup_eq_range`, `mem_sup`: supremum of two submonoids `S`, `T` of a commutative monoid is the set of products; * `closure_singleton_eq`, `mem_closure_singleton`: the multiplicative (resp., additive) closure of `{x}` consists of powers (resp., natural multiples) of `x`. ## Tags submonoid, submonoids -/ open_locale big_operators variables {M : Type*} variables {A : Type*} namespace submonoid section assoc variables [monoid M] (S : submonoid M) @[simp, norm_cast, to_additive coe_nsmul] theorem coe_pow (x : S) (n : ℕ) : ↑(x ^ n) = (x ^ n : M) := S.subtype.map_pow x n @[simp, norm_cast, to_additive] theorem coe_list_prod (l : list S) : (l.prod : M) = (l.map coe).prod := S.subtype.map_list_prod l @[simp, norm_cast, to_additive] theorem coe_multiset_prod {M} [comm_monoid M] (S : submonoid M) (m : multiset S) : (m.prod : M) = (m.map coe).prod := S.subtype.map_multiset_prod m @[simp, norm_cast, to_additive] theorem coe_finset_prod {ι M} [comm_monoid M] (S : submonoid M) (f : ι → S) (s : finset ι) : ↑(∏ i in s, f i) = (∏ i in s, f i : M) := S.subtype.map_prod f s /-- Product of a list of elements in a submonoid is in the submonoid. -/ @[to_additive "Sum of a list of elements in an `add_submonoid` is in the `add_submonoid`."] lemma list_prod_mem {l : list M} (hl : ∀ x ∈ l, x ∈ S) : l.prod ∈ S := by { lift l to list S using hl, rw ← coe_list_prod, exact l.prod.coe_prop } /-- Product of a multiset of elements in a submonoid of a `comm_monoid` is in the submonoid. -/ @[to_additive "Sum of a multiset of elements in an `add_submonoid` of an `add_comm_monoid` is in the `add_submonoid`."] lemma multiset_prod_mem {M} [comm_monoid M] (S : submonoid M) (m : multiset M) (hm : ∀ a ∈ m, a ∈ S) : m.prod ∈ S := by { lift m to multiset S using hm, rw ← coe_multiset_prod, exact m.prod.coe_prop } /-- Product of elements of a submonoid of a `comm_monoid` indexed by a `finset` is in the submonoid. -/ @[to_additive "Sum of elements in an `add_submonoid` of an `add_comm_monoid` indexed by a `finset` is in the `add_submonoid`."] lemma prod_mem {M : Type*} [comm_monoid M] (S : submonoid M) {ι : Type*} {t : finset ι} {f : ι → M} (h : ∀c ∈ t, f c ∈ S) : ∏ c in t, f c ∈ S := S.multiset_prod_mem (t.1.map f) $ λ x hx, let ⟨i, hi, hix⟩ := multiset.mem_map.1 hx in hix ▸ h i hi @[to_additive nsmul_mem] lemma pow_mem {x : M} (hx : x ∈ S) (n : ℕ) : x ^ n ∈ S := by simpa only [coe_pow] using ((⟨x, hx⟩ : S) ^ n).coe_prop end assoc section non_assoc variables [mul_one_class M] (S : submonoid M) open set @[to_additive] lemma mem_supr_of_directed {ι} [hι : nonempty ι] {S : ι → submonoid M} (hS : directed (≤) S) {x : M} : x ∈ (⨆ i, S i) ↔ ∃ i, x ∈ S i := begin refine ⟨_, λ ⟨i, hi⟩, (set_like.le_def.1 $ le_supr S i) hi⟩, suffices : x ∈ closure (⋃ i, (S i : set M)) → ∃ i, x ∈ S i, by simpa only [closure_Union, closure_eq (S _)] using this, refine (λ hx, closure_induction hx (λ _, mem_Union.1) _ _), { exact hι.elim (λ i, ⟨i, (S i).one_mem⟩) }, { rintros x y ⟨i, hi⟩ ⟨j, hj⟩, rcases hS i j with ⟨k, hki, hkj⟩, exact ⟨k, (S k).mul_mem (hki hi) (hkj hj)⟩ } end @[to_additive] lemma coe_supr_of_directed {ι} [nonempty ι] {S : ι → submonoid M} (hS : directed (≤) S) : ((⨆ i, S i : submonoid M) : set M) = ⋃ i, ↑(S i) := set.ext $ λ x, by simp [mem_supr_of_directed hS] @[to_additive] lemma mem_Sup_of_directed_on {S : set (submonoid M)} (Sne : S.nonempty) (hS : directed_on (≤) S) {x : M} : x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s := begin haveI : nonempty S := Sne.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed hS.directed_coe, set_coe.exists, subtype.coe_mk] end @[to_additive] lemma coe_Sup_of_directed_on {S : set (submonoid M)} (Sne : S.nonempty) (hS : directed_on (≤) S) : (↑(Sup S) : set M) = ⋃ s ∈ S, ↑s := set.ext $ λ x, by simp [mem_Sup_of_directed_on Sne hS] @[to_additive] lemma mem_sup_left {S T : submonoid M} : ∀ {x : M}, x ∈ S → x ∈ S ⊔ T := show S ≤ S ⊔ T, from le_sup_left @[to_additive] lemma mem_sup_right {S T : submonoid M} : ∀ {x : M}, x ∈ T → x ∈ S ⊔ T := show T ≤ S ⊔ T, from le_sup_right @[to_additive] lemma mul_mem_sup {S T : submonoid M} {x y : M} (hx : x ∈ S) (hy : y ∈ T) : x * y ∈ S ⊔ T := (S ⊔ T).mul_mem (mem_sup_left hx) (mem_sup_right hy) @[to_additive] lemma mem_supr_of_mem {ι : Type*} {S : ι → submonoid M} (i : ι) : ∀ {x : M}, x ∈ S i → x ∈ supr S := show S i ≤ supr S, from le_supr _ _ @[to_additive] lemma mem_Sup_of_mem {S : set (submonoid M)} {s : submonoid M} (hs : s ∈ S) : ∀ {x : M}, x ∈ s → x ∈ Sup S := show s ≤ Sup S, from le_Sup hs end non_assoc end submonoid namespace free_monoid variables {α : Type*} open submonoid @[to_additive] theorem closure_range_of : closure (set.range $ @of α) = ⊤ := eq_top_iff.2 $ λ x hx, free_monoid.rec_on x (one_mem _) $ λ x xs hxs, mul_mem _ (subset_closure $ set.mem_range_self _) hxs end free_monoid namespace submonoid variables [monoid M] open monoid_hom lemma closure_singleton_eq (x : M) : closure ({x} : set M) = (powers_hom M x).mrange := closure_eq_of_le (set.singleton_subset_iff.2 ⟨multiplicative.of_add 1, pow_one x⟩) $ λ x ⟨n, hn⟩, hn ▸ pow_mem _ (subset_closure $ set.mem_singleton _) _ /-- The submonoid generated by an element of a monoid equals the set of natural number powers of the element. -/ lemma mem_closure_singleton {x y : M} : y ∈ closure ({x} : set M) ↔ ∃ n:ℕ, x^n=y := by rw [closure_singleton_eq, mem_mrange]; refl lemma mem_closure_singleton_self {y : M} : y ∈ closure ({y} : set M) := mem_closure_singleton.2 ⟨1, pow_one y⟩ lemma closure_singleton_one : closure ({1} : set M) = ⊥ := by simp [eq_bot_iff_forall, mem_closure_singleton] @[to_additive] lemma closure_eq_mrange (s : set M) : closure s = (free_monoid.lift (coe : s → M)).mrange := by rw [mrange_eq_map, ← free_monoid.closure_range_of, map_mclosure, ← set.range_comp, free_monoid.lift_comp_of, subtype.range_coe] @[to_additive] lemma exists_list_of_mem_closure {s : set M} {x : M} (hx : x ∈ closure s) : ∃ (l : list M) (hl : ∀ y ∈ l, y ∈ s), l.prod = x := begin rw [closure_eq_mrange, mem_mrange] at hx, rcases hx with ⟨l, hx⟩, exact ⟨list.map coe l, λ y hy, let ⟨z, hz, hy⟩ := list.mem_map.1 hy in hy ▸ z.2, hx⟩ end /-- The submonoid generated by an element. -/ def powers (n : M) : submonoid M := submonoid.copy (powers_hom M n).mrange (set.range ((^) n : ℕ → M)) $ set.ext (λ n, exists_congr $ λ i, by simp; refl) @[simp] lemma mem_powers (n : M) : n ∈ powers n := ⟨1, pow_one _⟩ lemma mem_powers_iff (x z : M) : x ∈ powers z ↔ ∃ n : ℕ, z ^ n = x := iff.rfl lemma powers_eq_closure (n : M) : powers n = closure {n} := by { ext, exact mem_closure_singleton.symm } lemma powers_subset {n : M} {P : submonoid M} (h : n ∈ P) : powers n ≤ P := λ x hx, match x, hx with _, ⟨i, rfl⟩ := P.pow_mem h i end /-- Exponentiation map from natural numbers to powers. -/ def pow (n : M) (m : ℕ) : powers n := ⟨n ^ m, m, rfl⟩ /-- Logarithms from powers to natural numbers. -/ def log [decidable_eq M] {n : M} (p : powers n) : ℕ := nat.find $ (mem_powers_iff p.val n).mp p.prop @[simp] theorem pow_log_eq_self [decidable_eq M] {n : M} (p : powers n) : pow n (log p) = p := subtype.ext $ nat.find_spec p.prop lemma pow_right_injective_iff_pow_injective {n : M} : function.injective (λ m : ℕ, n ^ m) ↔ function.injective (pow n) := subtype.coe_injective.of_comp_iff (pow n) theorem log_pow_eq_self [decidable_eq M] {n : M} (h : function.injective (λ m : ℕ, n ^ m)) (m : ℕ) : log (pow n m) = m := pow_right_injective_iff_pow_injective.mp h $ pow_log_eq_self _ theorem log_pow_int_eq_self {x : ℤ} (h : 1 < x.nat_abs) (m : ℕ) : log (pow x m) = m := log_pow_eq_self (int.pow_right_injective h) _ end submonoid namespace submonoid variables {N : Type*} [comm_monoid N] open monoid_hom @[to_additive] lemma sup_eq_range (s t : submonoid N) : s ⊔ t = (s.subtype.coprod t.subtype).mrange := by rw [mrange_eq_map, ← mrange_inl_sup_mrange_inr, map_sup, map_mrange, coprod_comp_inl, map_mrange, coprod_comp_inr, range_subtype, range_subtype] @[to_additive] lemma mem_sup {s t : submonoid N} {x : N} : x ∈ s ⊔ t ↔ ∃ (y ∈ s) (z ∈ t), y * z = x := by simp only [sup_eq_range, mem_mrange, coprod_apply, prod.exists, set_like.exists, coe_subtype, subtype.coe_mk] end submonoid namespace add_submonoid variables [add_monoid A] open set lemma closure_singleton_eq (x : A) : closure ({x} : set A) = (multiples_hom A x).mrange := closure_eq_of_le (set.singleton_subset_iff.2 ⟨1, one_nsmul x⟩) $ λ x ⟨n, hn⟩, hn ▸ nsmul_mem _ (subset_closure $ set.mem_singleton _) _ /-- The `add_submonoid` generated by an element of an `add_monoid` equals the set of natural number multiples of the element. -/ lemma mem_closure_singleton {x y : A} : y ∈ closure ({x} : set A) ↔ ∃ n:ℕ, n • x = y := by rw [closure_singleton_eq, add_monoid_hom.mem_mrange]; refl lemma closure_singleton_zero : closure ({0} : set A) = ⊥ := by simp [eq_bot_iff_forall, mem_closure_singleton, nsmul_zero] /-- The additive submonoid generated by an element. -/ def multiples (x : A) : add_submonoid A := add_submonoid.copy (multiples_hom A x).mrange (set.range (λ i, i • x : ℕ → A)) $ set.ext (λ n, exists_congr $ λ i, by simp; refl) @[simp] lemma mem_multiples (x : A) : x ∈ multiples x := ⟨1, one_nsmul _⟩ lemma mem_multiples_iff (x z : A) : x ∈ multiples z ↔ ∃ n : ℕ, n • z = x := iff.rfl lemma multiples_eq_closure (x : A) : multiples x = closure {x} := by { ext, exact mem_closure_singleton.symm } lemma multiples_subset {x : A} {P : add_submonoid A} (h : x ∈ P) : multiples x ≤ P := λ x hx, match x, hx with _, ⟨i, rfl⟩ := P.nsmul_mem h i end attribute [to_additive add_submonoid.multiples] submonoid.powers attribute [to_additive add_submonoid.mem_multiples] submonoid.mem_powers attribute [to_additive add_submonoid.mem_multiples_iff] submonoid.mem_powers_iff attribute [to_additive add_submonoid.multiples_eq_closure] submonoid.powers_eq_closure attribute [to_additive add_submonoid.multiples_subset] submonoid.powers_subset end add_submonoid /-! Lemmas about additive closures of `submonoid`. -/ namespace submonoid variables {R : Type*} [non_assoc_semiring R] (S : submonoid R) {a b : R} /-- The product of an element of the additive closure of a multiplicative submonoid `M` and an element of `M` is contained in the additive closure of `M`. -/ lemma mul_right_mem_add_closure (ha : a ∈ add_submonoid.closure (S : set R)) (hb : b ∈ S) : a * b ∈ add_submonoid.closure (S : set R) := begin revert b, refine add_submonoid.closure_induction ha _ _ _; clear ha a, { exact λ r hr b hb, add_submonoid.mem_closure.mpr (λ y hy, hy (S.mul_mem hr hb)) }, { exact λ b hb, by simp only [zero_mul, (add_submonoid.closure (S : set R)).zero_mem] }, { simp_rw add_mul, exact λ r s hr hs b hb, (add_submonoid.closure (S : set R)).add_mem (hr hb) (hs hb) } end /-- The product of two elements of the additive closure of a submonoid `M` is an element of the additive closure of `M`. -/ lemma mul_mem_add_closure (ha : a ∈ add_submonoid.closure (S : set R)) (hb : b ∈ add_submonoid.closure (S : set R)) : a * b ∈ add_submonoid.closure (S : set R) := begin revert a, refine add_submonoid.closure_induction hb _ _ _; clear hb b, { exact λ r hr b hb, S.mul_right_mem_add_closure hb hr }, { exact λ b hb, by simp only [mul_zero, (add_submonoid.closure (S : set R)).zero_mem] }, { simp_rw mul_add, exact λ r s hr hs b hb, (add_submonoid.closure (S : set R)).add_mem (hr hb) (hs hb) } end /-- The product of an element of `S` and an element of the additive closure of a multiplicative submonoid `S` is contained in the additive closure of `S`. -/ lemma mul_left_mem_add_closure (ha : a ∈ S) (hb : b ∈ add_submonoid.closure (S : set R)) : a * b ∈ add_submonoid.closure (S : set R) := S.mul_mem_add_closure (add_submonoid.mem_closure.mpr (λ sT hT, hT ha)) hb end submonoid section mul_add lemma of_mul_image_powers_eq_multiples_of_mul [monoid M] {x : M} : additive.of_mul '' ((submonoid.powers x) : set M) = add_submonoid.multiples (additive.of_mul x) := begin ext, split, { rintros ⟨y, ⟨n, hy1⟩, hy2⟩, use n, simpa [← of_mul_pow, hy1] }, { rintros ⟨n, hn⟩, refine ⟨x ^ n, ⟨n, rfl⟩, _⟩, rwa of_mul_pow } end lemma of_add_image_multiples_eq_powers_of_add [add_monoid A] {x : A} : multiplicative.of_add '' ((add_submonoid.multiples x) : set A) = submonoid.powers (multiplicative.of_add x) := begin symmetry, rw equiv.eq_image_iff_symm_image_eq, exact of_mul_image_powers_eq_multiples_of_mul, end end mul_add
0a1802b0782b67cb090b875e9ee4cb317a4dc28b
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/stage0/src/Lean/Meta/MatchUtil.lean
7f32902ec9ab72d3829f6c707061702d5918492d
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
407
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.Recognizers import Lean.Meta.Basic namespace Lean.Meta def matchEq? (e : Expr) : MetaM (Option (Expr × Expr × Expr)) := do match e.eq? with | r@(some _) => pure r | none => pure (← whnf e).eq? end Lean.Meta
aae0785ed111d26bca29e6af6253aefc2f3d6aad
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/doc/demo/even.lean
badf9c228f40dcc4a3f30000c1d1a81b4b29ebe5
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
3,169
lean
import macros import tactic using Nat -- In this example, we prove two simple theorems about even/odd numbers. -- First, we define the predicates even and odd. definition even (a : Nat) := ∃ b, a = 2*b definition odd (a : Nat) := ∃ b, a = 2*b + 1 -- Prove that the sum of two even numbers is even. -- -- Notes: we use the macro -- obtain [bindings] ',' 'from' [expr]_1 ',' [expr]_2 -- -- It is syntax sugar for existential elimination. -- It expands to -- -- exists_elim [expr]_1 (fun [binding], [expr]_2) -- -- It is defined in the file macros.lua. -- -- We also use the calculational proof style. -- See doc/lean/calc.md for more information. -- -- We use the first two obtain-expressions to extract the -- witnesses w1 and w2 s.t. a = 2*w1 and b = 2*w2. -- We can do that because H1 and H2 are evidence/proof for the -- fact that 'a' and 'b' are even. -- -- We use a calculational proof 'calc' expression to derive -- the witness w1+w2 for the fact that a+b is also even. -- That is, we provide a derivation showing that a+b = 2*(w1 + w2) theorem EvenPlusEven {a b : Nat} (H1 : even a) (H2 : even b) : even (a + b) := obtain (w1 : Nat) (Hw1 : a = 2*w1), from H1, obtain (w2 : Nat) (Hw2 : b = 2*w2), from H2, exists_intro (w1 + w2) (calc a + b = 2*w1 + b : { Hw1 } ... = 2*w1 + 2*w2 : { Hw2 } ... = 2*(w1 + w2) : symm (distributer 2 w1 w2)) exit rewrite_set basic add_rewrite distributer eq_id : basic theorem EvenPlusEven2 {a b : Nat} (H1 : even a) (H2 : even b) : even (a + b) := obtain (w1 : Nat) (Hw1 : a = 2*w1), from H1, obtain (w2 : Nat) (Hw2 : b = 2*w2), from H2, exists_intro (w1 + w2) (calc a + b = 2*(w1 + w2) : by simp basic) -- In the following example, we omit the arguments for add_assoc, refl and distribute. -- Lean can infer them automatically. -- -- refl is the reflexivity proof. (refl a) is a proof that two -- definitionally equal terms are indeed equal. -- "definitionally equal" means that they have the same normal form. -- We can also view it as "Proof by computation". -- The normal form of (1+1), and 2*1 is 2. -- -- Another remark: '2*w + 1 + 1' is not definitionally equal to '2*w + 2*1'. -- The gotcha is that '2*w + 1 + 1' is actually '(2*w + 1) + 1' since + -- is left associative. Moreover, Lean normalizer does not use -- any theorems such as + associativity. theorem OddPlusOne {a : Nat} (H : odd a) : even (a + 1) := obtain (w : Nat) (Hw : a = 2*w + 1), from H, exists_intro (w + 1) (calc a + 1 = 2*w + 1 + 1 : { Hw } ... = 2*w + (1 + 1) : add_assoc _ _ _ ... = 2*w + 2*1 : refl _ ... = 2*(w + 1) : symm (distributer _ _ _)) -- The following command displays the proof object produced by Lean after -- expanding macros, and infering implicit/missing arguments. print environment 2 -- By default, Lean does not display implicit arguments. -- The following command will force it to display them. set_option pp::implicit true print environment 2 -- As an exercise, prove that the sum of two odd numbers is even, -- and other similar theorems.
98ca67c9faf4abd5715ef624120b6c2f29e49748
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/matrix/basis.lean
f31d5780b8bbadbfc29cc5a700489e1dd6df6991
[ "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,177
lean
/- Copyright (c) 2020 Jalex Stark. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jalex Stark, Scott Morrison, Eric Wieser, Oliver Nash -/ import data.matrix.basic import linear_algebra.matrix.trace /-! # Matrices with a single non-zero element. This file provides `matrix.std_basis_matrix`. The matrix `matrix.std_basis_matrix i j c` has `c` at position `(i, j)`, and zeroes elsewhere. -/ variables {l m n : Type*} variables {R α : Type*} namespace matrix open_locale matrix open_locale big_operators variables [decidable_eq l] [decidable_eq m] [decidable_eq n] variables [semiring α] /-- `std_basis_matrix i j a` is the matrix with `a` in the `i`-th row, `j`-th column, and zeroes elsewhere. -/ def std_basis_matrix (i : m) (j : n) (a : α) : matrix m n α := (λ i' j', if i = i' ∧ j = j' then a else 0) @[simp] lemma smul_std_basis_matrix (i : m) (j : n) (a b : α) : b • std_basis_matrix i j a = std_basis_matrix i j (b • a) := by { unfold std_basis_matrix, ext, simp } @[simp] lemma std_basis_matrix_zero (i : m) (j : n) : std_basis_matrix i j (0 : α) = 0 := by { unfold std_basis_matrix, ext, simp } lemma std_basis_matrix_add (i : m) (j : n) (a b : α) : std_basis_matrix i j (a + b) = std_basis_matrix i j a + std_basis_matrix i j b := begin unfold std_basis_matrix, ext, split_ifs with h; simp [h], end lemma matrix_eq_sum_std_basis (x : matrix n m α) [fintype n] [fintype m] : x = ∑ (i : n) (j : m), std_basis_matrix i j (x i j) := begin ext, symmetry, iterate 2 { rw finset.sum_apply }, convert fintype.sum_eq_single i _, { simp [std_basis_matrix] }, { intros j hj, simp [std_basis_matrix, hj], } end -- TODO: tie this up with the `basis` machinery of linear algebra -- this is not completely trivial because we are indexing by two types, instead of one -- TODO: add `std_basis_vec` lemma std_basis_eq_basis_mul_basis (i : m) (j : n) : std_basis_matrix i j 1 = vec_mul_vec (λ i', ite (i = i') 1 0) (λ j', ite (j = j') 1 0) := begin ext, norm_num [std_basis_matrix, vec_mul_vec], split_ifs; tauto, end -- todo: the old proof used fintypes, I don't know `finsupp` but this feels generalizable @[elab_as_eliminator] protected lemma induction_on' [fintype m] [fintype n] {P : matrix m n α → Prop} (M : matrix m n α) (h_zero : P 0) (h_add : ∀ p q, P p → P q → P (p + q)) (h_std_basis : ∀ (i : m) (j : n) (x : α), P (std_basis_matrix i j x)) : P M := begin rw [matrix_eq_sum_std_basis M, ← finset.sum_product'], apply finset.sum_induction _ _ h_add h_zero, { intros, apply h_std_basis, } end @[elab_as_eliminator] protected lemma induction_on [fintype m] [fintype n] [nonempty m] [nonempty n] {P : matrix m n α → Prop} (M : matrix m n α) (h_add : ∀ p q, P p → P q → P (p + q)) (h_std_basis : ∀ i j x, P (std_basis_matrix i j x)) : P M := matrix.induction_on' M begin inhabit m, inhabit n, simpa using h_std_basis (default m) (default n) 0, end h_add h_std_basis namespace std_basis_matrix section variables (i : m) (j : n) (c : α) (i' : m) (j' : n) @[simp] lemma apply_same : std_basis_matrix i j c i j = c := if_pos (and.intro rfl rfl) @[simp] lemma apply_of_ne (h : ¬((i = i') ∧ (j = j'))) : std_basis_matrix i j c i' j' = 0 := by { simp only [std_basis_matrix, and_imp, ite_eq_right_iff], tauto } @[simp] lemma apply_of_row_ne {i i' : m} (hi : i ≠ i') (j j' : n) (a : α) : std_basis_matrix i j a i' j' = 0 := by simp [hi] @[simp] lemma apply_of_col_ne (i i' : m) {j j' : n} (hj : j ≠ j') (a : α) : std_basis_matrix i j a i' j' = 0 := by simp [hj] end section variables (i j : n) (c : α) (i' j' : n) @[simp] lemma diag_zero (h : j ≠ i) : diag n α α (std_basis_matrix i j c) = 0 := funext $ λ k, if_neg $ λ ⟨e₁, e₂⟩, h (e₂.trans e₁.symm) variable [fintype n] lemma trace_zero (h : j ≠ i) : trace n α α (std_basis_matrix i j c) = 0 := by simp [h] @[simp] lemma mul_left_apply_same (b : n) (M : matrix n n α) : (std_basis_matrix i j c ⬝ M) i b = c * M j b := by simp [mul_apply, std_basis_matrix] @[simp] lemma mul_right_apply_same (a : n) (M : matrix n n α) : (M ⬝ std_basis_matrix i j c) a j = M a i * c := by simp [mul_apply, std_basis_matrix, mul_comm] @[simp] lemma mul_left_apply_of_ne (a b : n) (h : a ≠ i) (M : matrix n n α) : (std_basis_matrix i j c ⬝ M) a b = 0 := by simp [mul_apply, h.symm] @[simp] lemma mul_right_apply_of_ne (a b : n) (hbj : b ≠ j) (M : matrix n n α) : (M ⬝ std_basis_matrix i j c) a b = 0 := by simp [mul_apply, hbj.symm] @[simp] lemma mul_same (k : n) (d : α) : std_basis_matrix i j c ⬝ std_basis_matrix j k d = std_basis_matrix i k (c * d) := begin ext a b, simp only [mul_apply, std_basis_matrix, boole_mul], by_cases h₁ : i = a; by_cases h₂ : k = b; simp [h₁, h₂], end @[simp] lemma mul_of_ne {k l : n} (h : j ≠ k) (d : α) : std_basis_matrix i j c ⬝ std_basis_matrix k l d = 0 := begin ext a b, simp only [mul_apply, dmatrix.zero_apply, boole_mul, std_basis_matrix], by_cases h₁ : i = a; simp [h₁, h, h.symm], end end end std_basis_matrix end matrix