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
93f51b1d721732b79d659becbd0d05fc3b07ef33
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/vm_noncomputable_real.lean
eee6251cba7248253c0870311240c9ca8b827f48
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
338
lean
def ℝ := set ℕ constant ℝ.sub' : ℝ → ℝ → ℝ noncomputable def ℝ.sub (a b : ℝ) := (λ b, a.sub' b) b noncomputable instance : has_sub ℝ := ⟨ℝ.sub⟩ constant ℝ.nonneg : ℝ → Prop -- This instance is computable, and the VM code generator should accept it. instance : has_le ℝ := ⟨λ a b, (b - a).nonneg⟩
821ad03d9f0caab3a7ceb2c27f439a319ff74742
f20db13587f4dd28a4b1fbd31953afd491691fa0
/tests/lean/with_cases.lean
9a70d1189bced9f1429dd0792fd6c1bccf08a73f
[ "Apache-2.0" ]
permissive
AHartNtkn/lean
9a971edfc6857c63edcbf96bea6841b9a84cf916
0d83a74b26541421fc1aa33044c35b03759710ed
refs/heads/master
1,620,592,591,236
1,516,749,881,000
1,516,749,881,000
118,697,288
1
0
null
1,516,759,470,000
1,516,759,470,000
null
UTF-8
Lean
false
false
478
lean
open tactic example (p q : Prop) [s₁ : decidable p] [s₂ : decidable q] : true := begin with_cases { cases s₁; cases s₂ }, trace_state, all_goals { intros, trivial } end def split (p : Prop) {q : Prop} [decidable p] (pos : p → q) (neg : ¬ p → q) : q := decidable.by_cases pos neg example (p q : Prop) [decidable p] [decidable q] : true := begin with_cases { apply split p; apply split q; intros hq hp }, trace_state, all_goals { intros, trivial } end
70a32d263546a89a99bdbfea4f28234c0357fb49
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/category/Ring/constructions.lean
9e9dc9e24b5035939150cc46e185eace8af83e25
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
7,763
lean
/- Copyright (c) 2021 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import category_theory.limits.shapes.pullbacks import ring_theory.tensor_product import algebra.category.Ring.limits import algebra.category.Ring.colimits import category_theory.limits.shapes.strict_initial import ring_theory.subring.basic import ring_theory.ideal.local_ring import category_theory.limits.preserves.limits /-! # Constructions of (co)limits in CommRing In this file we provide the explicit (co)cones for various (co)limits in `CommRing`, including * tensor product is the pushout * `Z` is the initial object * `0` is the strict terminal object * cartesian product is the product * `ring_hom.eq_locus` is the equalizer -/ universes u u' open category_theory category_theory.limits open_locale tensor_product namespace CommRing section pushout variables {R A B : CommRing.{u}} (f : R ⟶ A) (g : R ⟶ B) /-- The explicit cocone with tensor products as the fibered product in `CommRing`. -/ def pushout_cocone : limits.pushout_cocone f g := begin letI := ring_hom.to_algebra f, letI := ring_hom.to_algebra g, apply limits.pushout_cocone.mk, show CommRing, from CommRing.of (A ⊗[R] B), show A ⟶ _, from algebra.tensor_product.include_left.to_ring_hom, show B ⟶ _, from algebra.tensor_product.include_right.to_ring_hom, ext r, transitivity algebra_map R (A ⊗[R] B) r, { exact algebra.tensor_product.include_left.commutes r }, { exact (algebra.tensor_product.include_right.commutes r).symm } end @[simp] lemma pushout_cocone_inl : (pushout_cocone f g).inl = (by { letI := f.to_algebra, letI := g.to_algebra, exactI algebra.tensor_product.include_left.to_ring_hom }) := rfl @[simp] lemma pushout_cocone_inr : (pushout_cocone f g).inr = (by { letI := f.to_algebra, letI := g.to_algebra, exactI algebra.tensor_product.include_right.to_ring_hom }) := rfl @[simp] lemma pushout_cocone_X : (pushout_cocone f g).X = (by { letI := f.to_algebra, letI := g.to_algebra, exactI CommRing.of (A ⊗[R] B) }) := rfl /-- Verify that the `pushout_cocone` is indeed the colimit. -/ def pushout_cocone_is_colimit : limits.is_colimit (pushout_cocone f g) := limits.pushout_cocone.is_colimit_aux' _ (λ s, begin letI := ring_hom.to_algebra f, letI := ring_hom.to_algebra g, letI := ring_hom.to_algebra (f ≫ s.inl), let f' : A →ₐ[R] s.X := { commutes' := λ r, by { change s.inl.to_fun (f r) = (f ≫ s.inl) r, refl }, ..s.inl }, let g' : B →ₐ[R] s.X := { commutes' := λ r, by { change (g ≫ s.inr) r = (f ≫ s.inl) r, congr' 1, exact (s.ι.naturality limits.walking_span.hom.snd).trans (s.ι.naturality limits.walking_span.hom.fst).symm }, ..s.inr }, /- The factor map is a ⊗ b ↦ f(a) * g(b). -/ use alg_hom.to_ring_hom (algebra.tensor_product.product_map f' g'), simp only [pushout_cocone_inl, pushout_cocone_inr], split, { ext x, exact algebra.tensor_product.product_map_left_apply _ _ x, }, split, { ext x, exact algebra.tensor_product.product_map_right_apply _ _ x, }, intros h eq1 eq2, let h' : (A ⊗[R] B) →ₐ[R] s.X := { commutes' := λ r, by { change h ((f r) ⊗ₜ[R] 1) = s.inl (f r), rw ← eq1, simp }, ..h }, suffices : h' = algebra.tensor_product.product_map f' g', { ext x, change h' x = algebra.tensor_product.product_map f' g' x, rw this }, apply algebra.tensor_product.ext, intros a b, simp [← eq1, ← eq2, ← h.map_mul], end) end pushout section terminal /-- The trivial ring is the (strict) terminal object of `CommRing`. -/ def punit_is_terminal : is_terminal (CommRing.of.{u} punit) := begin apply_with is_terminal.of_unique { instances := ff }, tidy end instance CommRing_has_strict_terminal_objects : has_strict_terminal_objects CommRing.{u} := begin apply has_strict_terminal_objects_of_terminal_is_strict (CommRing.of punit), intros X f, refine ⟨⟨by tidy, by ext, _⟩⟩, ext, have e : (0 : X) = 1 := by { rw [← f.map_one, ← f.map_zero], congr }, replace e : 0 * x = 1 * x := congr_arg (λ a, a * x) e, rw [one_mul, zero_mul, ← f.map_zero] at e, exact e, end lemma subsingleton_of_is_terminal {X : CommRing} (hX : is_terminal X) : subsingleton X := (hX.unique_up_to_iso punit_is_terminal).CommRing_iso_to_ring_equiv.to_equiv .subsingleton_congr.mpr (show subsingleton punit, by apply_instance) /-- `ℤ` is the initial object of `CommRing`. -/ def Z_is_initial : is_initial (CommRing.of ℤ) := begin apply_with is_initial.of_unique { instances := ff }, exact λ R, ⟨⟨int.cast_ring_hom R⟩, λ a, a.ext_int _⟩, end end terminal section product variables (A B : CommRing.{u}) /-- The product in `CommRing` is the cartesian product. This is the binary fan. -/ @[simps X] def prod_fan : binary_fan A B := binary_fan.mk (CommRing.of_hom $ ring_hom.fst A B) (CommRing.of_hom $ ring_hom.snd A B) /-- The product in `CommRing` is the cartesian product. -/ def prod_fan_is_limit : is_limit (prod_fan A B) := { lift := λ c, ring_hom.prod (c.π.app walking_pair.left) (c.π.app walking_pair.right), fac' := λ c j, by { ext, cases j; simpa only [binary_fan.π_app_left, binary_fan.π_app_right, comp_apply, ring_hom.prod_apply] }, uniq' := λ s m h, by { ext, { simpa using congr_hom (h walking_pair.left) x }, { simpa using congr_hom (h walking_pair.right) x } } } end product section equalizer variables {A B : CommRing.{u}} (f g : A ⟶ B) /-- The equalizer in `CommRing` is the equalizer as sets. This is the equalizer fork. -/ def equalizer_fork : fork f g := fork.of_ι (CommRing.of_hom (ring_hom.eq_locus f g).subtype) (by { ext ⟨x, e⟩, simpa using e }) /-- The equalizer in `CommRing` is the equalizer as sets. -/ def equalizer_fork_is_limit : is_limit (equalizer_fork f g) := begin fapply fork.is_limit.mk', intro s, use s.ι.cod_restrict' _ (λ x, (concrete_category.congr_hom s.condition x : _)), split, { ext, refl }, { intros m hm, ext x, exact concrete_category.congr_hom hm x } end instance : is_local_ring_hom (equalizer_fork f g).ι := begin constructor, rintros ⟨a, (h₁ : _ = _)⟩ (⟨⟨x,y,h₃,h₄⟩,(rfl : x = _)⟩ : is_unit a), have : y ∈ ring_hom.eq_locus f g, { apply (f.is_unit_map ⟨⟨x,y,h₃,h₄⟩,rfl⟩ : is_unit (f x)).mul_left_inj.mp, conv_rhs { rw h₁ }, rw [← f.map_mul, ← g.map_mul, h₄, f.map_one, g.map_one] }, rw is_unit_iff_exists_inv, exact ⟨⟨y, this⟩, subtype.eq h₃⟩, end instance equalizer_ι_is_local_ring_hom (F : walking_parallel_pair.{u} ⥤ CommRing.{u}) : is_local_ring_hom (limit.π F walking_parallel_pair.zero) := begin have := lim_map_π (diagram_iso_parallel_pair F).hom walking_parallel_pair.zero, rw ← is_iso.comp_inv_eq at this, rw ← this, rw ← limit.iso_limit_cone_hom_π ⟨_, equalizer_fork_is_limit (F.map walking_parallel_pair_hom.left) (F.map walking_parallel_pair_hom.right)⟩ walking_parallel_pair.zero, change is_local_ring_hom ((lim.map _ ≫ _ ≫ (equalizer_fork _ _).ι) ≫ _), apply_instance end open category_theory.limits.walking_parallel_pair opposite open category_theory.limits.walking_parallel_pair_hom instance equalizer_ι_is_local_ring_hom' (F : walking_parallel_pair.{u}ᵒᵖ ⥤ CommRing.{u}) : is_local_ring_hom (limit.π F (opposite.op walking_parallel_pair.one)) := begin have : _ = limit.π F (walking_parallel_pair_op_equiv.{u u}.functor.obj _) := (limit.iso_limit_cone_inv_π ⟨_, is_limit.whisker_equivalence (limit.is_limit F) walking_parallel_pair_op_equiv⟩ walking_parallel_pair.zero : _), erw ← this, apply_instance end end equalizer end CommRing
b0e135cf93e5627b1d609e81cc9f449744ceab94
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/group_with_zero/commute.lean
d6fe3e0815dc6f6d09b28c54b0b8e6dda83b9b64
[ "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
2,409
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import algebra.group_with_zero.semiconj import algebra.group.commute import tactic.nontriviality /-! # Lemmas about commuting elements in a `monoid_with_zero` or a `group_with_zero`. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ variables {α M₀ G₀ M₀' G₀' F F' : Type*} variables [monoid_with_zero M₀] namespace ring open_locale classical lemma mul_inverse_rev' {a b : M₀} (h : commute a b) : inverse (a * b) = inverse b * inverse a := begin by_cases hab : is_unit (a * b), { obtain ⟨⟨a, rfl⟩, b, rfl⟩ := h.is_unit_mul_iff.mp hab, rw [←units.coe_mul, inverse_unit, inverse_unit, inverse_unit, ←units.coe_mul, mul_inv_rev], }, obtain ha | hb := not_and_distrib.mp (mt h.is_unit_mul_iff.mpr hab), { rw [inverse_non_unit _ hab, inverse_non_unit _ ha, mul_zero]}, { rw [inverse_non_unit _ hab, inverse_non_unit _ hb, zero_mul]}, end lemma mul_inverse_rev {M₀} [comm_monoid_with_zero M₀] (a b : M₀) : ring.inverse (a * b) = inverse b * inverse a := mul_inverse_rev' (commute.all _ _) end ring lemma commute.ring_inverse_ring_inverse {a b : M₀} (h : commute a b) : commute (ring.inverse a) (ring.inverse b) := (ring.mul_inverse_rev' h.symm).symm.trans $ (congr_arg _ h.symm.eq).trans $ ring.mul_inverse_rev' h namespace commute @[simp] theorem zero_right [mul_zero_class G₀] (a : G₀) : commute a 0 := semiconj_by.zero_right a @[simp] theorem zero_left [mul_zero_class G₀] (a : G₀) : commute 0 a := semiconj_by.zero_left a a variables [group_with_zero G₀] {a b c : G₀} @[simp] theorem inv_left_iff₀ : commute a⁻¹ b ↔ commute a b := semiconj_by.inv_symm_left_iff₀ theorem inv_left₀ (h : commute a b) : commute a⁻¹ b := inv_left_iff₀.2 h @[simp] theorem inv_right_iff₀ : commute a b⁻¹ ↔ commute a b := semiconj_by.inv_right_iff₀ theorem inv_right₀ (h : commute a b) : commute a b⁻¹ := inv_right_iff₀.2 h @[simp] theorem div_right (hab : commute a b) (hac : commute a c) : commute a (b / c) := hab.div_right hac @[simp] theorem div_left (hac : commute a c) (hbc : commute b c) : commute (a / b) c := by { rw div_eq_mul_inv, exact hac.mul_left hbc.inv_left₀ } end commute
84008fcd0e5ad4e20faf8b8d8be6186fad8eed68
b2e508d02500f1512e1618150413e6be69d9db10
/src/data/rat/denumerable.lean
63e0b84eeff4a0c1d9a452effc4dda3486796b7c
[ "Apache-2.0" ]
permissive
callum-sutton/mathlib
c3788f90216e9cd43eeffcb9f8c9f959b3b01771
afd623825a3ac6bfbcc675a9b023edad3f069e89
refs/heads/master
1,591,371,888,053
1,560,990,690,000
1,560,990,690,000
192,476,045
0
0
Apache-2.0
1,568,941,843,000
1,560,837,965,000
Lean
UTF-8
Lean
false
false
945
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Chris Hughes -/ import data.rat.basic data.equiv.denumerable namespace rat open denumerable instance : infinite ℚ := infinite.of_injective (coe : ℕ → ℚ) nat.cast_injective private def denumerable_aux : ℚ ≃ { x : ℤ × ℕ // 0 < x.2 ∧ x.1.nat_abs.coprime x.2 } := { to_fun := λ x, ⟨⟨x.1, x.2⟩, x.3, x.4⟩, inv_fun := λ x, ⟨x.1.1, x.1.2, x.2.1, x.2.2⟩, left_inv := λ ⟨_, _, _, _⟩, rfl, right_inv := λ ⟨⟨_, _⟩, _, _⟩, rfl } instance : denumerable ℚ := begin let T := { x : ℤ × ℕ // 0 < x.2 ∧ x.1.nat_abs.coprime x.2 }, letI : infinite T := infinite.of_injective _ denumerable_aux.injective, letI : encodable T := encodable.subtype, letI : denumerable T := of_encodable_of_infinite T, exact denumerable.of_equiv T denumerable_aux end end rat
a9e94b78bf7af58662d8511ce3c623f2d3c0ea3e
205f0fc16279a69ea36e9fd158e3a97b06834ce2
/src/05_Functions/functions.lean
218128e9a923d42c3aabcc748667f3c626934fcc
[]
no_license
kevinsullivan/cs-dm-lean
b21d3ca1a9b2a0751ba13fcb4e7b258010a5d124
a06a94e98be77170ca1df486c8189338b16cf6c6
refs/heads/master
1,585,948,743,595
1,544,339,346,000
1,544,339,346,000
155,570,767
1
3
null
1,541,540,372,000
1,540,995,993,000
Lean
UTF-8
Lean
false
false
5,862
lean
/- If P and Q are of type Prop, we think of P → Q as a proposition in the form of an implication. Moreover, as we've seen, the way that we give a proof of P → Q in the logic of Lean is to produce a function that, if given a proof of P returns a proof of Q. On the other hand, nothing in Lean will prevent our using types such as nat and bool as P and Q. In this case we'd say that P → Q, or nat → bool, is a type: a type of functions from P → Q, e.g., from nat to bool. EXERCISE: Give two or three examples of interesting functions from nat to bool. A program that takes any natural number as an argument and always returns a Boolean value as a result is a value (a "function", or it would be better to say, a lambda expression) of this type, ℕ → bool. -/ def zero_nat (n : ℕ) : ℕ := 0 -- explicit return type #check zero_nat #check zero_nat 5 #reduce zero_nat 5 def zero_nat': ℕ → ℕ := λ n : nat, (0 : nat) def zero_nat'': ℕ → ℕ := λ n, 0 def zero_nat''' := λ n : nat, 0 /- EXERCISE: define a function, one_nat that takes any natural number as an argument and always returns the natural number 1. Write it in traditional function definition notation and using lambda expressions and type inference. -/ def one_nat' : ℕ → ℕ := λ n : nat, 1 def identity_nat (n : ℕ) : nat := n --explicit return type #check identity_nat #check identity_nat 5 #reduce identity_nat 5 /- EXERCISE: define the same function, call it identity_nat' and write it using a lambda expression. -/ def double (n : ℕ) := 2 * n -- return type inferred #check double #check double 3 #reduce double 3 def double' : ℕ → ℕ := λ n , 2 * n /- EXERCISE: Write it using a lambda expression. -/ def square (n: ℕ) := n * n -- return type inferred #check square #check square 3 #reduce square 3 def square' : ℤ → ℤ := λ n, n * n #reduce square' (-3) -- #reduce square (-3) -- Nope /- EXERCISE: Write it using a lambda expression. -/ def isPositive (n: nat) : bool := n > 0 -- if n > 0 then tt else ff #check isPositive #check isPositive 0 #check isPositive 1 #check isPositive 2 #reduce isPositive 0 #reduce isPositive 1 #reduce isPositive 2 /- EXERCISE: Write it using a lambda expression. -/ /- Here's a function that returns boolean true (tt) if a given natural number n is greater than or equal to zero and less than 2^32. It is given using lambda notation. Write it with a prime on its name using ordinary function definition notation (as the functions above are written). -/ def uint32: ℕ → bool := λ n, if n >= 0 ∧ n < 2^32 then tt else ff #check uint32 /- An equivalent function definition with a type declaration using arrow notation, and an explicit lambda expression as a value. -/ def positive' : nat → bool := λ n : nat, (if n > 0 then tt else ff : bool) #check positive' #check λ n : nat, (if n > 0 then tt else ff : bool) #check λ n, (if n > 0 then tt else ff) #check λ n, n > 0 /- Read the first line as saying positive' is a proof of (a value of type) nat → bool. There are many values of this type: they are all the functions taking nat arguments and returning bool results. The specific value that we use here to "prove the type" is the function that returns true if the argument is strictly greater than zero, otherwise is returns false. Read the lambda expression as follows: A function that takes an argument, n, of type nat, and that returns the result of evaluating the expression, involving n, after the comma: here, true if n > 0, and false otherwise. Here's an equivalent expression using type inference to skip declaring the type of n. -/ def positive'' : nat → bool := λ n, if n > 0 then tt else ff /- Here we use type inference to skip declaring the function type, while still using a lambda expression for the program. -/ def positive''' := λ n, if n > 0 then tt else ff #check positive''' #reduce positive''' 3 #reduce positive''' 0 theorem pos_is_pos : isPositive = positive''' := rfl def my_pow (x: nat) (y: nat) := x^y #eval my_pow 2 16 /- EXERCISE: Give two or three examples of interesting functions from nat to nat. A program that takes any natural number as an argument and always returns a natural as a result is a value (a "function", or it would be better to say, a lambda expression) of this type, ℕ → ℕ -/ /- We can also pass functions as arguments to other functions! -/ def compose (f: ℕ → ℕ) (g: ℕ → ℕ) (x: ℕ) : ℕ := f (g x) #check compose #check compose square double #reduce compose double double 3 #reduce compose square double 3 #reduce square (double 3) def do_twice (f : ℕ → ℕ) (x: ℕ) : ℕ := f (f x) #check do_twice #reduce do_twice square 3 /- Let's write this as a lambda expression and see what we get. -/ def do_twice' : (ℕ → ℕ) → ℕ → ℕ := λ (f: ℕ → ℕ) (x: ℕ), f (f x) /- And that's a shorthand for this! -/ def do_twice'' : (ℕ → ℕ) → ℕ → ℕ := λ (f : ℕ → ℕ), λ (x : ℕ), f (f x) def foo := (do_twice'' double) #check foo #eval foo 5 def sub_do_twice (f: ℕ → ℕ) := λ (x : ℕ), f (f x) #check sub_do_twice def call_sub_do_twice := sub_do_twice (λ (x: ℕ), x + 1) #check call_sub_do_twice #reduce call_sub_do_twice 2 theorem dt_eq_dt : do_twice = do_twice'' := rfl /- Inception! Here we define a function that takes as an argument a function that takes as an argument a function (and a natural number) -/ def do_twice''' (f: (ℕ → ℕ) → ℕ → ℕ) (x: (ℕ → ℕ)) : (ℕ → ℕ) := f (f x) #check do_twice''' #check do_twice''' do_twice #reduce do_twice''' /- Use #eval instead of #reduce because #reduce will have recursion problems unless we increase our stack space. -/ #eval (do_twice''' do_twice) square 2 #eval 2^16
582ae5d3c28fd421581e59cba19ca8ac90906725
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/topology/metric_space/closeds.lean
77a2002d81514f093c1d8e58bf9dc2e4eb280681
[ "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
21,299
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 topology.metric_space.hausdorff_distance import topology.compacts import analysis.specific_limits /-! # Closed subsets This file defines the metric and emetric space structure on the types of closed subsets and nonempty compact subsets of a metric or emetric space. The Hausdorff distance induces an emetric space structure on the type of closed subsets of an emetric space, called `closeds`. Its completeness, resp. compactness, resp. second-countability, follow from the corresponding properties of the original space. In a metric space, the type of nonempty compact subsets (called `nonempty_compacts`) also inherits a metric space structure from the Hausdorff distance, as the Hausdorff edistance is always finite in this context. -/ noncomputable theory open_locale classical topological_space ennreal universe u open classical set function topological_space filter namespace emetric section variables {α : Type u} [emetric_space α] {s : set α} /-- In emetric spaces, the Hausdorff edistance defines an emetric space structure on the type of closed subsets -/ instance closeds.emetric_space : emetric_space (closeds α) := { edist := λs t, Hausdorff_edist s.val t.val, edist_self := λs, Hausdorff_edist_self, edist_comm := λs t, Hausdorff_edist_comm, edist_triangle := λs t u, Hausdorff_edist_triangle, eq_of_edist_eq_zero := λs t h, subtype.eq ((Hausdorff_edist_zero_iff_eq_of_closed s.property t.property).1 h) } /-- The edistance to a closed set depends continuously on the point and the set -/ lemma continuous_inf_edist_Hausdorff_edist : continuous (λp : α × (closeds α), inf_edist p.1 (p.2).val) := begin refine continuous_of_le_add_edist 2 (by simp) _, rintros ⟨x, s⟩ ⟨y, t⟩, calc inf_edist x (s.val) ≤ inf_edist x (t.val) + Hausdorff_edist (t.val) (s.val) : inf_edist_le_inf_edist_add_Hausdorff_edist ... ≤ (inf_edist y (t.val) + edist x y) + Hausdorff_edist (t.val) (s.val) : add_le_add_right inf_edist_le_inf_edist_add_edist _ ... = inf_edist y (t.val) + (edist x y + Hausdorff_edist (s.val) (t.val)) : by simp [add_comm, add_left_comm, Hausdorff_edist_comm, -subtype.val_eq_coe] ... ≤ inf_edist y (t.val) + (edist (x, s) (y, t) + edist (x, s) (y, t)) : add_le_add_left (add_le_add (le_max_left _ _) (le_max_right _ _)) _ ... = inf_edist y (t.val) + 2 * edist (x, s) (y, t) : by rw [← mul_two, mul_comm] end /-- Subsets of a given closed subset form a closed set -/ lemma is_closed_subsets_of_is_closed (hs : is_closed s) : is_closed {t : closeds α | t.val ⊆ s} := begin refine is_closed_of_closure_subset (λt ht x hx, _), -- t : closeds α, ht : t ∈ closure {t : closeds α | t.val ⊆ s}, -- x : α, hx : x ∈ t.val -- goal : x ∈ s have : x ∈ closure s, { refine mem_closure_iff.2 (λε εpos, _), rcases mem_closure_iff.1 ht ε εpos with ⟨u, hu, Dtu⟩, -- u : closeds α, hu : u ∈ {t : closeds α | t.val ⊆ s}, hu' : edist t u < ε rcases exists_edist_lt_of_Hausdorff_edist_lt hx Dtu with ⟨y, hy, Dxy⟩, -- y : α, hy : y ∈ u.val, Dxy : edist x y < ε exact ⟨y, hu hy, Dxy⟩ }, rwa hs.closure_eq at this, end /-- By definition, the edistance on `closeds α` is given by the Hausdorff edistance -/ lemma closeds.edist_eq {s t : closeds α} : edist s t = Hausdorff_edist s.val t.val := rfl /-- In a complete space, the type of closed subsets is complete for the Hausdorff edistance. -/ instance closeds.complete_space [complete_space α] : complete_space (closeds α) := begin /- We will show that, if a sequence of sets `s n` satisfies `edist (s n) (s (n+1)) < 2^{-n}`, then it converges. This is enough to guarantee completeness, by a standard completeness criterion. We use the shorthand `B n = 2^{-n}` in ennreal. -/ let B : ℕ → ℝ≥0∞ := λ n, (2⁻¹)^n, have B_pos : ∀ n, (0:ℝ≥0∞) < B n, by simp [B, ennreal.pow_pos], have B_ne_top : ∀ n, B n ≠ ⊤, by simp [B, ennreal.pow_ne_top], /- Consider a sequence of closed sets `s n` with `edist (s n) (s (n+1)) < B n`. We will show that it converges. The limit set is t0 = ⋂n, closure (⋃m≥n, s m). We will have to show that a point in `s n` is close to a point in `t0`, and a point in `t0` is close to a point in `s n`. The completeness then follows from a standard criterion. -/ refine complete_of_convergent_controlled_sequences B B_pos (λs hs, _), let t0 := ⋂n, closure (⋃m≥n, (s m).val), let t : closeds α := ⟨t0, is_closed_Inter (λ_, is_closed_closure)⟩, use t, -- The inequality is written this way to agree with `edist_le_of_edist_le_geometric_of_tendsto₀` have I1 : ∀n:ℕ, ∀x ∈ (s n).val, ∃y ∈ t0, edist x y ≤ 2 * B n, { /- This is the main difficulty of the proof. Starting from `x ∈ s n`, we want to find a point in `t0` which is close to `x`. Define inductively a sequence of points `z m` with `z n = x` and `z m ∈ s m` and `edist (z m) (z (m+1)) ≤ B m`. This is possible since the Hausdorff distance between `s m` and `s (m+1)` is at most `B m`. This sequence is a Cauchy sequence, therefore converging as the space is complete, to a limit which satisfies the required properties. -/ assume n x hx, obtain ⟨z, hz₀, hz⟩ : ∃ z : Π l, (s (n+l)).val, (z 0:α) = x ∧ ∀ k, edist (z k:α) (z (k+1):α) ≤ B n / 2^k, { -- We prove existence of the sequence by induction. have : ∀ (l : ℕ) (z : (s (n+l)).val), ∃ z' : (s (n+l+1)).val, edist (z:α) z' ≤ B n / 2^l, { assume l z, obtain ⟨z', z'_mem, hz'⟩ : ∃ z' ∈ (s (n+l+1)).val, edist (z:α) z' < B n / 2^l, { apply exists_edist_lt_of_Hausdorff_edist_lt z.2, simp only [B, ennreal.inv_pow, div_eq_mul_inv], rw [← pow_add], apply hs; simp }, exact ⟨⟨z', z'_mem⟩, le_of_lt hz'⟩ }, use [λ k, nat.rec_on k ⟨x, hx⟩ (λl z, some (this l z)), rfl], exact λ k, some_spec (this k _) }, -- it follows from the previous bound that `z` is a Cauchy sequence have : cauchy_seq (λ k, ((z k):α)), from cauchy_seq_of_edist_le_geometric_two (B n) (B_ne_top n) hz, -- therefore, it converges rcases cauchy_seq_tendsto_of_complete this with ⟨y, y_lim⟩, use y, -- the limit point `y` will be the desired point, in `t0` and close to our initial point `x`. -- First, we check it belongs to `t0`. have : y ∈ t0 := mem_Inter.2 (λk, mem_closure_of_tendsto y_lim begin simp only [exists_prop, set.mem_Union, filter.eventually_at_top, set.mem_preimage, set.preimage_Union], exact ⟨k, λ m hm, ⟨n+m, zero_add k ▸ add_le_add (zero_le n) hm, (z m).2⟩⟩ end), use this, -- Then, we check that `y` is close to `x = z n`. This follows from the fact that `y` -- is the limit of `z k`, and the distance between `z n` and `z k` has already been estimated. rw [← hz₀], exact edist_le_of_edist_le_geometric_two_of_tendsto₀ (B n) hz y_lim }, have I2 : ∀n:ℕ, ∀x ∈ t0, ∃y ∈ (s n).val, edist x y ≤ 2 * B n, { /- For the (much easier) reverse inequality, we start from a point `x ∈ t0` and we want to find a point `y ∈ s n` which is close to `x`. `x` belongs to `t0`, the intersection of the closures. In particular, it is well approximated by a point `z` in `⋃m≥n, s m`, say in `s m`. Since `s m` and `s n` are close, this point is itself well approximated by a point `y` in `s n`, as required. -/ assume n x xt0, have : x ∈ closure (⋃m≥n, (s m).val), by apply mem_Inter.1 xt0 n, rcases mem_closure_iff.1 this (B n) (B_pos n) with ⟨z, hz, Dxz⟩, -- z : α, Dxz : edist x z < B n, simp only [exists_prop, set.mem_Union] at hz, rcases hz with ⟨m, ⟨m_ge_n, hm⟩⟩, -- m : ℕ, m_ge_n : m ≥ n, hm : z ∈ (s m).val have : Hausdorff_edist (s m).val (s n).val < B n := hs n m n m_ge_n (le_refl n), rcases exists_edist_lt_of_Hausdorff_edist_lt hm this with ⟨y, hy, Dzy⟩, -- y : α, hy : y ∈ (s n).val, Dzy : edist z y < B n exact ⟨y, hy, calc edist x y ≤ edist x z + edist z y : edist_triangle _ _ _ ... ≤ B n + B n : add_le_add (le_of_lt Dxz) (le_of_lt Dzy) ... = 2 * B n : (two_mul _).symm ⟩ }, -- Deduce from the above inequalities that the distance between `s n` and `t0` is at most `2 B n`. have main : ∀n:ℕ, edist (s n) t ≤ 2 * B n := λn, Hausdorff_edist_le_of_mem_edist (I1 n) (I2 n), -- from this, the convergence of `s n` to `t0` follows. refine tendsto_at_top.2 (λε εpos, _), have : tendsto (λn, 2 * B n) at_top (𝓝 (2 * 0)), from ennreal.tendsto.const_mul (ennreal.tendsto_pow_at_top_nhds_0_of_lt_1 $ by simp [ennreal.one_lt_two]) (or.inr $ by simp), rw mul_zero at this, obtain ⟨N, hN⟩ : ∃ N, ∀ b ≥ N, ε > 2 * B b, from ((tendsto_order.1 this).2 ε εpos).exists_forall_of_at_top, exact ⟨N, λn hn, lt_of_le_of_lt (main n) (hN n hn)⟩ end /-- In a compact space, the type of closed subsets is compact. -/ instance closeds.compact_space [compact_space α] : compact_space (closeds α) := ⟨begin /- by completeness, it suffices to show that it is totally bounded, i.e., for all ε>0, there is a finite set which is ε-dense. start from a set `s` which is ε-dense in α. Then the subsets of `s` are finitely many, and ε-dense for the Hausdorff distance. -/ refine compact_of_totally_bounded_is_closed (emetric.totally_bounded_iff.2 (λε εpos, _)) is_closed_univ, rcases exists_between εpos with ⟨δ, δpos, δlt⟩, rcases emetric.totally_bounded_iff.1 (compact_iff_totally_bounded_complete.1 (@compact_univ α _ _)).1 δ δpos with ⟨s, fs, hs⟩, -- s : set α, fs : finite s, hs : univ ⊆ ⋃ (y : α) (H : y ∈ s), eball y δ -- we first show that any set is well approximated by a subset of `s`. have main : ∀ u : set α, ∃v ⊆ s, Hausdorff_edist u v ≤ δ, { assume u, let v := {x : α | x ∈ s ∧ ∃y∈u, edist x y < δ}, existsi [v, ((λx hx, hx.1) : v ⊆ s)], refine Hausdorff_edist_le_of_mem_edist _ _, { assume x hx, have : x ∈ ⋃y ∈ s, ball y δ := hs (by simp), rcases mem_bUnion_iff.1 this with ⟨y, ys, dy⟩, have : edist y x < δ := by simp at dy; rwa [edist_comm] at dy, exact ⟨y, ⟨ys, ⟨x, hx, this⟩⟩, le_of_lt dy⟩ }, { rintros x ⟨hx1, ⟨y, yu, hy⟩⟩, exact ⟨y, yu, le_of_lt hy⟩ }}, -- introduce the set F of all subsets of `s` (seen as members of `closeds α`). let F := {f : closeds α | f.val ⊆ s}, use F, split, -- `F` is finite { apply @finite_of_finite_image _ _ F (λf, f.val), { exact subtype.val_injective.inj_on F }, { refine fs.finite_subsets.subset (λb, _), simp only [and_imp, set.mem_image, set.mem_set_of_eq, exists_imp_distrib], assume x hx hx', rwa hx' at hx }}, -- `F` is ε-dense { assume u _, rcases main u.val with ⟨t0, t0s, Dut0⟩, have : is_closed t0 := (fs.subset t0s).is_compact.is_closed, let t : closeds α := ⟨t0, this⟩, have : t ∈ F := t0s, have : edist u t < ε := lt_of_le_of_lt Dut0 δlt, apply mem_bUnion_iff.2, exact ⟨t, ‹t ∈ F›, this⟩ } end⟩ /-- In an emetric space, the type of non-empty compact subsets is an emetric space, where the edistance is the Hausdorff edistance -/ instance nonempty_compacts.emetric_space : emetric_space (nonempty_compacts α) := { edist := λs t, Hausdorff_edist s.val t.val, edist_self := λs, Hausdorff_edist_self, edist_comm := λs t, Hausdorff_edist_comm, edist_triangle := λs t u, Hausdorff_edist_triangle, eq_of_edist_eq_zero := λs t h, subtype.eq $ begin have : closure (s.val) = closure (t.val) := Hausdorff_edist_zero_iff_closure_eq_closure.1 h, rwa [s.property.2.is_closed.closure_eq, t.property.2.is_closed.closure_eq] at this, end } /-- `nonempty_compacts.to_closeds` is a uniform embedding (as it is an isometry) -/ lemma nonempty_compacts.to_closeds.uniform_embedding : uniform_embedding (@nonempty_compacts.to_closeds α _ _) := isometry.uniform_embedding $ λx y, rfl /-- The range of `nonempty_compacts.to_closeds` is closed in a complete space -/ lemma nonempty_compacts.is_closed_in_closeds [complete_space α] : is_closed (range $ @nonempty_compacts.to_closeds α _ _) := begin have : range nonempty_compacts.to_closeds = {s : closeds α | s.val.nonempty ∧ is_compact s.val}, from range_inclusion _, rw this, refine is_closed_of_closure_subset (λs hs, ⟨_, _⟩), { -- take a set set t which is nonempty and at a finite distance of s rcases mem_closure_iff.1 hs ⊤ ennreal.coe_lt_top with ⟨t, ht, Dst⟩, rw edist_comm at Dst, -- since `t` is nonempty, so is `s` exact nonempty_of_Hausdorff_edist_ne_top ht.1 (ne_of_lt Dst) }, { refine compact_iff_totally_bounded_complete.2 ⟨_, s.property.is_complete⟩, refine totally_bounded_iff.2 (λε εpos, _), -- we have to show that s is covered by finitely many eballs of radius ε -- pick a nonempty compact set t at distance at most ε/2 of s rcases mem_closure_iff.1 hs (ε/2) (ennreal.half_pos εpos) with ⟨t, ht, Dst⟩, -- cover this space with finitely many balls of radius ε/2 rcases totally_bounded_iff.1 (compact_iff_totally_bounded_complete.1 ht.2).1 (ε/2) (ennreal.half_pos εpos) with ⟨u, fu, ut⟩, refine ⟨u, ⟨fu, λx hx, _⟩⟩, -- u : set α, fu : finite u, ut : t.val ⊆ ⋃ (y : α) (H : y ∈ u), eball y (ε / 2) -- then s is covered by the union of the balls centered at u of radius ε rcases exists_edist_lt_of_Hausdorff_edist_lt hx Dst with ⟨z, hz, Dxz⟩, rcases mem_bUnion_iff.1 (ut hz) with ⟨y, hy, Dzy⟩, have : edist x y < ε := calc edist x y ≤ edist x z + edist z y : edist_triangle _ _ _ ... < ε/2 + ε/2 : ennreal.add_lt_add Dxz Dzy ... = ε : ennreal.add_halves _, exact mem_bUnion hy this }, end /-- In a complete space, the type of nonempty compact subsets is complete. This follows from the same statement for closed subsets -/ instance nonempty_compacts.complete_space [complete_space α] : complete_space (nonempty_compacts α) := (complete_space_iff_is_complete_range nonempty_compacts.to_closeds.uniform_embedding.to_uniform_inducing).2 $ nonempty_compacts.is_closed_in_closeds.is_complete /-- In a compact space, the type of nonempty compact subsets is compact. This follows from the same statement for closed subsets -/ instance nonempty_compacts.compact_space [compact_space α] : compact_space (nonempty_compacts α) := ⟨begin rw nonempty_compacts.to_closeds.uniform_embedding.embedding.is_compact_iff_is_compact_image, rw [image_univ], exact nonempty_compacts.is_closed_in_closeds.is_compact end⟩ /-- In a second countable space, the type of nonempty compact subsets is second countable -/ instance nonempty_compacts.second_countable_topology [second_countable_topology α] : second_countable_topology (nonempty_compacts α) := begin haveI : separable_space (nonempty_compacts α) := begin /- To obtain a countable dense subset of `nonempty_compacts α`, start from a countable dense subset `s` of α, and then consider all its finite nonempty subsets. This set is countable and made of nonempty compact sets. It turns out to be dense: by total boundedness, any compact set `t` can be covered by finitely many small balls, and approximations in `s` of the centers of these balls give the required finite approximation of `t`. -/ rcases exists_countable_dense α with ⟨s, cs, s_dense⟩, let v0 := {t : set α | finite t ∧ t ⊆ s}, let v : set (nonempty_compacts α) := {t : nonempty_compacts α | t.val ∈ v0}, refine ⟨⟨v, ⟨_, _⟩⟩⟩, { have : countable (subtype.val '' v), { refine (countable_set_of_finite_subset cs).mono (λx hx, _), rcases (mem_image _ _ _).1 hx with ⟨y, ⟨hy, yx⟩⟩, rw ← yx, exact hy }, apply countable_of_injective_of_countable_image _ this, apply subtype.val_injective.inj_on }, { refine λt, mem_closure_iff.2 (λε εpos, _), -- t is a compact nonempty set, that we have to approximate uniformly by a a set in `v`. rcases exists_between εpos with ⟨δ, δpos, δlt⟩, -- construct a map F associating to a point in α an approximating point in s, up to δ/2. have Exy : ∀x, ∃y, y ∈ s ∧ edist x y < δ/2, { assume x, rcases mem_closure_iff.1 (s_dense x) (δ/2) (ennreal.half_pos δpos) with ⟨y, ys, hy⟩, exact ⟨y, ⟨ys, hy⟩⟩ }, let F := λx, some (Exy x), have Fspec : ∀x, F x ∈ s ∧ edist x (F x) < δ/2 := λx, some_spec (Exy x), -- cover `t` with finitely many balls. Their centers form a set `a` have : totally_bounded t.val := (compact_iff_totally_bounded_complete.1 t.property.2).1, rcases totally_bounded_iff.1 this (δ/2) (ennreal.half_pos δpos) with ⟨a, af, ta⟩, -- a : set α, af : finite a, ta : t.val ⊆ ⋃ (y : α) (H : y ∈ a), eball y (δ / 2) -- replace each center by a nearby approximation in `s`, giving a new set `b` let b := F '' a, have : finite b := af.image _, have tb : ∀x ∈ t.val, ∃y ∈ b, edist x y < δ, { assume x hx, rcases mem_bUnion_iff.1 (ta hx) with ⟨z, za, Dxz⟩, existsi [F z, mem_image_of_mem _ za], calc edist x (F z) ≤ edist x z + edist z (F z) : edist_triangle _ _ _ ... < δ/2 + δ/2 : ennreal.add_lt_add Dxz (Fspec z).2 ... = δ : ennreal.add_halves _ }, -- keep only the points in `b` that are close to point in `t`, yielding a new set `c` let c := {y ∈ b | ∃x∈t.val, edist x y < δ}, have : finite c := ‹finite b›.subset (λx hx, hx.1), -- points in `t` are well approximated by points in `c` have tc : ∀x ∈ t.val, ∃y ∈ c, edist x y ≤ δ, { assume x hx, rcases tb x hx with ⟨y, yv, Dxy⟩, have : y ∈ c := by simp [c, -mem_image]; exact ⟨yv, ⟨x, hx, Dxy⟩⟩, exact ⟨y, this, le_of_lt Dxy⟩ }, -- points in `c` are well approximated by points in `t` have ct : ∀y ∈ c, ∃x ∈ t.val, edist y x ≤ δ, { rintros y ⟨hy1, ⟨x, xt, Dyx⟩⟩, have : edist y x ≤ δ := calc edist y x = edist x y : edist_comm _ _ ... ≤ δ : le_of_lt Dyx, exact ⟨x, xt, this⟩ }, -- it follows that their Hausdorff distance is small have : Hausdorff_edist t.val c ≤ δ := Hausdorff_edist_le_of_mem_edist tc ct, have Dtc : Hausdorff_edist t.val c < ε := lt_of_le_of_lt this δlt, -- the set `c` is not empty, as it is well approximated by a nonempty set have hc : c.nonempty, from nonempty_of_Hausdorff_edist_ne_top t.property.1 (ne_top_of_lt Dtc), -- let `d` be the version of `c` in the type `nonempty_compacts α` let d : nonempty_compacts α := ⟨c, ⟨hc, ‹finite c›.is_compact⟩⟩, have : c ⊆ s, { assume x hx, rcases (mem_image _ _ _).1 hx.1 with ⟨y, ⟨ya, yx⟩⟩, rw ← yx, exact (Fspec y).1 }, have : d ∈ v := ⟨‹finite c›, this⟩, -- we have proved that `d` is a good approximation of `t` as requested exact ⟨d, ‹d ∈ v›, Dtc⟩ }, end, apply second_countable_of_separable, end end --section end emetric --namespace namespace metric section variables {α : Type u} [metric_space α] /-- `nonempty_compacts α` inherits a metric space structure, as the Hausdorff edistance between two such sets is finite. -/ instance nonempty_compacts.metric_space : metric_space (nonempty_compacts α) := emetric_space.to_metric_space $ λx y, Hausdorff_edist_ne_top_of_nonempty_of_bounded x.2.1 y.2.1 (bounded_of_compact x.2.2) (bounded_of_compact y.2.2) /-- The distance on `nonempty_compacts α` is the Hausdorff distance, by construction -/ lemma nonempty_compacts.dist_eq {x y : nonempty_compacts α} : dist x y = Hausdorff_dist x.val y.val := rfl lemma lipschitz_inf_dist_set (x : α) : lipschitz_with 1 (λ s : nonempty_compacts α, inf_dist x s.val) := lipschitz_with.of_le_add $ assume s t, by { rw dist_comm, exact inf_dist_le_inf_dist_add_Hausdorff_dist (edist_ne_top t s) } lemma lipschitz_inf_dist : lipschitz_with 2 (λ p : α × (nonempty_compacts α), inf_dist p.1 p.2.val) := @lipschitz_with.uncurry _ _ _ _ _ _ (λ (x : α) (s : nonempty_compacts α), inf_dist x s.val) 1 1 (λ s, lipschitz_inf_dist_pt s.val) lipschitz_inf_dist_set lemma uniform_continuous_inf_dist_Hausdorff_dist : uniform_continuous (λp : α × (nonempty_compacts α), inf_dist p.1 (p.2).val) := lipschitz_inf_dist.uniform_continuous end --section end metric --namespace
79c35e419687cdbf19421ac2367870a1a80497d9
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebra/big_operators/multiset.lean
ad0a50629b95ef92dfeb83bb8d4213ab1acee2b2
[ "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,892
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import algebra.group_with_zero.power import data.list.prod_monoid import data.multiset.basic /-! # Sums and products over multisets In this file we define products and sums indexed by multisets. This is later used to define products and sums indexed by finite sets. ## Main declarations * `multiset.prod`: `s.prod f` is the product of `f i` over all `i ∈ s`. Not to be mistaken with the cartesian product `multiset.product`. * `multiset.sum`: `s.sum f` is the sum of `f i` over all `i ∈ s`. -/ variables {ι α β γ : Type*} namespace multiset section comm_monoid variables [comm_monoid α] {s t : multiset α} {a : α} {m : multiset ι} {f g : ι → α} /-- Product of a multiset given a commutative monoid structure on `α`. `prod {a, b, c} = a * b * c` -/ @[to_additive "Sum of a multiset given a commutative additive monoid structure on `α`. `sum {a, b, c} = a + b + c`"] def prod : multiset α → α := foldr (*) (λ x y z, by simp [mul_left_comm]) 1 @[to_additive] lemma prod_eq_foldr (s : multiset α) : prod s = foldr (*) (λ x y z, by simp [mul_left_comm]) 1 s := rfl @[to_additive] lemma prod_eq_foldl (s : multiset α) : prod s = foldl (*) (λ x y z, by simp [mul_right_comm]) 1 s := (foldr_swap _ _ _ _).trans (by simp [mul_comm]) @[simp, norm_cast, to_additive] lemma coe_prod (l : list α) : prod ↑l = l.prod := prod_eq_foldl _ @[simp, to_additive] lemma prod_to_list (s : multiset α) : s.to_list.prod = s.prod := begin conv_rhs { rw ←coe_to_list s }, rw coe_prod, end @[simp, to_additive] lemma prod_zero : @prod α _ 0 = 1 := rfl @[simp, to_additive] lemma prod_cons (a : α) (s) : prod (a ::ₘ s) = a * prod s := foldr_cons _ _ _ _ _ @[simp, to_additive] lemma prod_singleton (a : α) : prod {a} = a := by simp only [mul_one, prod_cons, singleton_eq_cons, eq_self_iff_true, prod_zero] @[simp, to_additive] lemma prod_add (s t : multiset α) : prod (s + t) = prod s * prod t := quotient.induction_on₂ s t $ λ l₁ l₂, by simp lemma prod_nsmul (m : multiset α) : ∀ (n : ℕ), (n • m).prod = m.prod ^ n | 0 := by { rw [zero_nsmul, pow_zero], refl } | (n + 1) := by rw [add_nsmul, one_nsmul, pow_add, pow_one, prod_add, prod_nsmul n] @[simp, to_additive] lemma prod_repeat (a : α) (n : ℕ) : (repeat a n).prod = a ^ n := by simp [repeat, list.prod_repeat] @[to_additive nsmul_count] lemma pow_count [decidable_eq α] (a : α) : a ^ s.count a = (s.filter (eq a)).prod := by rw [filter_eq, prod_repeat] @[to_additive] lemma prod_hom [comm_monoid β] (s : multiset α) (f : α →* β) : (s.map f).prod = f s.prod := quotient.induction_on s $ λ l, by simp only [l.prod_hom f, quot_mk_to_coe, coe_map, coe_prod] @[to_additive] lemma prod_hom' [comm_monoid β] (s : multiset ι) (f : α →* β) (g : ι → α) : (s.map $ λ i, f $ g i).prod = f (s.map g).prod := by { convert (s.map g).prod_hom f, exact (map_map _ _ _).symm } @[to_additive] lemma prod_hom₂ [comm_monoid β] [comm_monoid γ] (s : multiset ι) (f : α → β → γ) (hf : ∀ a b c d, f (a * b) (c * d) = f a c * f b d) (hf' : f 1 1 = 1) (f₁ : ι → α) (f₂ : ι → β) : (s.map $ λ i, f (f₁ i) (f₂ i)).prod = f (s.map f₁).prod (s.map f₂).prod := quotient.induction_on s $ λ l, by simp only [l.prod_hom₂ f hf hf', quot_mk_to_coe, coe_map, coe_prod] @[to_additive] lemma prod_hom_rel [comm_monoid β] (s : multiset ι) {r : α → β → Prop} {f : ι → α} {g : ι → β} (h₁ : r 1 1) (h₂ : ∀ ⦃a b c⦄, r b c → r (f a * b) (g a * c)) : r (s.map f).prod (s.map g).prod := quotient.induction_on s $ λ l, by simp only [l.prod_hom_rel h₁ h₂, quot_mk_to_coe, coe_map, coe_prod] @[to_additive] lemma prod_map_one : prod (m.map (λ i, (1 : α))) = 1 := by rw [map_const, prod_repeat, one_pow] @[simp, to_additive] lemma prod_map_mul : (m.map $ λ i, f i * g i).prod = (m.map f).prod * (m.map g).prod := m.prod_hom₂ (*) mul_mul_mul_comm (mul_one _) _ _ @[to_additive sum_map_nsmul] lemma prod_map_pow {n : ℕ} : (m.map $ λ i, f i ^ n).prod = (m.map f).prod ^ n := m.prod_hom' (pow_monoid_hom n) _ @[to_additive] lemma prod_map_prod_map (m : multiset β) (n : multiset γ) {f : β → γ → α} : prod (m.map $ λ a, prod $ n.map $ λ b, f a b) = prod (n.map $ λ b, prod $ m.map $ λ a, f a b) := multiset.induction_on m (by simp) (λ a m ih, by simp [ih]) @[to_additive] lemma prod_induction (p : α → Prop) (s : multiset α) (p_mul : ∀ a b, p a → p b → p (a * b)) (p_one : p 1) (p_s : ∀ a ∈ s, p a) : p s.prod := begin rw prod_eq_foldr, exact foldr_induction (*) (λ x y z, by simp [mul_left_comm]) 1 p s p_mul p_one p_s, end @[to_additive] lemma prod_induction_nonempty (p : α → Prop) (p_mul : ∀ a b, p a → p b → p (a * b)) (hs : s ≠ ∅) (p_s : ∀ a ∈ s, p a) : p s.prod := begin revert s, refine multiset.induction _ _, { intro h, exfalso, simpa using h }, intros a s hs hsa hpsa, rw prod_cons, by_cases hs_empty : s = ∅, { simp [hs_empty, hpsa a] }, have hps : ∀ x, x ∈ s → p x, from λ x hxs, hpsa x (mem_cons_of_mem hxs), exact p_mul a s.prod (hpsa a (mem_cons_self a s)) (hs hs_empty hps), end lemma dvd_prod : a ∈ s → a ∣ s.prod := quotient.induction_on s (λ l a h, by simpa using list.dvd_prod h) a lemma prod_dvd_prod_of_le (h : s ≤ t) : s.prod ∣ t.prod := begin obtain ⟨z, rfl⟩ := multiset.le_iff_exists_add.1 h, simp only [prod_add, dvd_mul_right], end end comm_monoid lemma prod_dvd_prod_of_dvd [comm_monoid β] {S : multiset α} (g1 g2 : α → β) (h : ∀ a ∈ S, g1 a ∣ g2 a) : (multiset.map g1 S).prod ∣ (multiset.map g2 S).prod := begin apply multiset.induction_on' S, { simp }, intros a T haS _ IH, simp [mul_dvd_mul (h a haS) IH] end section add_comm_monoid variables [add_comm_monoid α] /-- `multiset.sum`, the sum of the elements of a multiset, promoted to a morphism of `add_comm_monoid`s. -/ def sum_add_monoid_hom : multiset α →+ α := { to_fun := sum, map_zero' := sum_zero, map_add' := sum_add } @[simp] lemma coe_sum_add_monoid_hom : (sum_add_monoid_hom : multiset α → α) = sum := rfl end add_comm_monoid section comm_monoid_with_zero variables [comm_monoid_with_zero α] lemma prod_eq_zero {s : multiset α} (h : (0 : α) ∈ s) : s.prod = 0 := begin rcases multiset.exists_cons_of_mem h with ⟨s', hs'⟩, simp [hs', multiset.prod_cons] end variables [no_zero_divisors α] [nontrivial α] {s : multiset α} lemma prod_eq_zero_iff : s.prod = 0 ↔ (0 : α) ∈ s := quotient.induction_on s $ λ l, by { rw [quot_mk_to_coe, coe_prod], exact list.prod_eq_zero_iff } lemma prod_ne_zero (h : (0 : α) ∉ s) : s.prod ≠ 0 := mt prod_eq_zero_iff.1 h end comm_monoid_with_zero section comm_group variables [comm_group α] {m : multiset ι} {f g : ι → α} @[simp, to_additive] lemma prod_map_inv' : (m.map $ λ i, (f i)⁻¹).prod = (m.map f).prod ⁻¹ := by { convert (m.map f).prod_hom comm_group.inv_monoid_hom, rw map_map, refl } @[simp, to_additive] lemma prod_map_div : (m.map $ λ i, f i / g i).prod = (m.map f).prod / (m.map g).prod := m.prod_hom₂ (/) mul_div_comm' (div_one' _) _ _ @[to_additive] lemma prod_map_zpow {n : ℤ} : (m.map $ λ i, f i ^ n).prod = (m.map f).prod ^ n := by { convert (m.map f).prod_hom (zpow_group_hom _), rw map_map, refl } @[simp] lemma coe_inv_monoid_hom : (comm_group.inv_monoid_hom : α → α) = has_inv.inv := rfl @[simp, to_additive] lemma prod_map_inv (m : multiset α) : (m.map has_inv.inv).prod = m.prod⁻¹ := m.prod_hom comm_group.inv_monoid_hom end comm_group section comm_group_with_zero variables [comm_group_with_zero α] {m : multiset ι} {f g : ι → α} @[simp] lemma prod_map_inv₀ : (m.map $ λ i, (f i)⁻¹).prod = (m.map f).prod ⁻¹ := by { convert (m.map f).prod_hom inv_monoid_with_zero_hom.to_monoid_hom, rw map_map, refl } @[simp] lemma prod_map_div₀ : (m.map $ λ i, f i / g i).prod = (m.map f).prod / (m.map g).prod := m.prod_hom₂ (/) (λ _ _ _ _, (div_mul_div _ _ _ _).symm) (div_one _) _ _ lemma prod_map_zpow₀ {n : ℤ} : prod (m.map $ λ i, f i ^ n) = (m.map f).prod ^ n := by { convert (m.map f).prod_hom (zpow_group_hom₀ _), rw map_map, refl } end comm_group_with_zero section semiring variables [semiring α] {a : α} {s : multiset ι} {f : ι → α} lemma sum_map_mul_left : sum (s.map (λ i, a * f i)) = a * sum (s.map f) := multiset.induction_on s (by simp) (λ i s ih, by simp [ih, mul_add]) lemma sum_map_mul_right : sum (s.map (λ i, f i * a)) = sum (s.map f) * a := multiset.induction_on s (by simp) (λ a s ih, by simp [ih, add_mul]) end semiring section comm_semiring variables [comm_semiring α] lemma dvd_sum {a : α} {s : multiset α} : (∀ x ∈ s, a ∣ x) → a ∣ s.sum := multiset.induction_on s (λ _, dvd_zero _) (λ x s ih h, by { rw sum_cons, exact dvd_add (h _ (mem_cons_self _ _)) (ih $ λ y hy, h _ $ mem_cons.2 $ or.inr hy) }) end comm_semiring /-! ### Order -/ section ordered_comm_monoid variables [ordered_comm_monoid α] {s t : multiset α} {a : α} @[to_additive sum_nonneg] lemma one_le_prod_of_one_le : (∀ x ∈ s, (1 : α) ≤ x) → 1 ≤ s.prod := quotient.induction_on s $ λ l hl, by simpa using list.one_le_prod_of_one_le hl @[to_additive] lemma single_le_prod : (∀ x ∈ s, (1 : α) ≤ x) → ∀ x ∈ s, x ≤ s.prod := quotient.induction_on s $ λ l hl x hx, by simpa using list.single_le_prod hl x hx @[to_additive] lemma prod_le_of_forall_le (s : multiset α) (n : α) (h : ∀ x ∈ s, x ≤ n) : s.prod ≤ n ^ s.card := begin induction s using quotient.induction_on, simpa using list.prod_le_of_forall_le _ _ h, end @[to_additive all_zero_of_le_zero_le_of_sum_eq_zero] lemma all_one_of_le_one_le_of_prod_eq_one : (∀ x ∈ s, (1 : α) ≤ x) → s.prod = 1 → ∀ x ∈ s, x = (1 : α) := begin apply quotient.induction_on s, simp only [quot_mk_to_coe, coe_prod, mem_coe], exact λ l, list.all_one_of_le_one_le_of_prod_eq_one, end @[to_additive] lemma prod_le_prod_of_rel_le (h : s.rel (≤) t) : s.prod ≤ t.prod := begin induction h with _ _ _ _ rh _ rt, { refl }, { rw [prod_cons, prod_cons], exact mul_le_mul' rh rt } end @[to_additive] lemma prod_map_le_prod (f : α → α) (h : ∀ x, x ∈ s → f x ≤ x) : (s.map f).prod ≤ s.prod := prod_le_prod_of_rel_le $ rel_map_left.2 $ rel_refl_of_refl_on h @[to_additive] lemma prod_le_sum_prod (f : α → α) (h : ∀ x, x ∈ s → x ≤ f x) : s.prod ≤ (s.map f).prod := @prod_map_le_prod (order_dual α) _ _ f h @[to_additive card_nsmul_le_sum] lemma pow_card_le_prod (h : ∀ x ∈ s, a ≤ x) : a ^ s.card ≤ s.prod := by { rw [←multiset.prod_repeat, ←multiset.map_const], exact prod_map_le_prod _ h } @[to_additive sum_le_card_nsmul] lemma prod_le_pow_card (h : ∀ x ∈ s, x ≤ a) : s.prod ≤ a ^ s.card := @pow_card_le_prod (order_dual α) _ _ _ h end ordered_comm_monoid lemma prod_nonneg [ordered_comm_semiring α] {m : multiset α} (h : ∀ a ∈ m, (0 : α) ≤ a) : 0 ≤ m.prod := begin revert h, refine m.induction_on _ _, { rintro -, rw prod_zero, exact zero_le_one }, intros a s hs ih, rw prod_cons, exact mul_nonneg (ih _ $ mem_cons_self _ _) (hs $ λ a ha, ih _ $ mem_cons_of_mem ha), end @[to_additive] lemma prod_eq_one_iff [canonically_ordered_monoid α] {m : multiset α} : m.prod = 1 ↔ ∀ x ∈ m, x = (1 : α) := quotient.induction_on m $ λ l, by simpa using list.prod_eq_one_iff l @[to_additive] lemma le_prod_of_mem [canonically_ordered_monoid α] {m : multiset α} {a : α} (h : a ∈ m) : a ≤ m.prod := begin obtain ⟨m', rfl⟩ := exists_cons_of_mem h, rw [prod_cons], exact _root_.le_mul_right (le_refl a), end @[to_additive le_sum_of_subadditive_on_pred] lemma le_prod_of_submultiplicative_on_pred [comm_monoid α] [ordered_comm_monoid β] (f : α → β) (p : α → Prop) (h_one : f 1 = 1) (hp_one : p 1) (h_mul : ∀ a b, p a → p b → f (a * b) ≤ f a * f b) (hp_mul : ∀ a b, p a → p b → p (a * b)) (s : multiset α) (hps : ∀ a, a ∈ s → p a) : f s.prod ≤ (s.map f).prod := begin revert s, refine multiset.induction _ _, { simp [le_of_eq h_one] }, intros a s hs hpsa, have hps : ∀ x, x ∈ s → p x, from λ x hx, hpsa x (mem_cons_of_mem hx), have hp_prod : p s.prod, from prod_induction p s hp_mul hp_one hps, rw [prod_cons, map_cons, prod_cons], exact (h_mul a s.prod (hpsa a (mem_cons_self a s)) hp_prod).trans (mul_le_mul_left' (hs hps) _), end @[to_additive le_sum_of_subadditive] lemma le_prod_of_submultiplicative [comm_monoid α] [ordered_comm_monoid β] (f : α → β) (h_one : f 1 = 1) (h_mul : ∀ a b, f (a * b) ≤ f a * f b) (s : multiset α) : f s.prod ≤ (s.map f).prod := le_prod_of_submultiplicative_on_pred f (λ i, true) h_one trivial (λ x y _ _ , h_mul x y) (by simp) s (by simp) @[to_additive le_sum_nonempty_of_subadditive_on_pred] lemma le_prod_nonempty_of_submultiplicative_on_pred [comm_monoid α] [ordered_comm_monoid β] (f : α → β) (p : α → Prop) (h_mul : ∀ a b, p a → p b → f (a * b) ≤ f a * f b) (hp_mul : ∀ a b, p a → p b → p (a * b)) (s : multiset α) (hs_nonempty : s ≠ ∅) (hs : ∀ a, a ∈ s → p a) : f s.prod ≤ (s.map f).prod := begin revert s, refine multiset.induction _ _, { intro h, exfalso, exact h rfl }, rintros a s hs hsa_nonempty hsa_prop, rw [prod_cons, map_cons, prod_cons], by_cases hs_empty : s = ∅, { simp [hs_empty] }, have hsa_restrict : (∀ x, x ∈ s → p x), from λ x hx, hsa_prop x (mem_cons_of_mem hx), have hp_sup : p s.prod, from prod_induction_nonempty p hp_mul hs_empty hsa_restrict, have hp_a : p a, from hsa_prop a (mem_cons_self a s), exact (h_mul a _ hp_a hp_sup).trans (mul_le_mul_left' (hs hs_empty hsa_restrict) _), end @[to_additive le_sum_nonempty_of_subadditive] lemma le_prod_nonempty_of_submultiplicative [comm_monoid α] [ordered_comm_monoid β] (f : α → β) (h_mul : ∀ a b, f (a * b) ≤ f a * f b) (s : multiset α) (hs_nonempty : s ≠ ∅) : f s.prod ≤ (s.map f).prod := le_prod_nonempty_of_submultiplicative_on_pred f (λ i, true) (by simp [h_mul]) (by simp) s hs_nonempty (by simp) @[simp] lemma sum_map_singleton (s : multiset α) : (s.map (λ a, ({a} : multiset α))).sum = s := multiset.induction_on s (by simp) (by simp [singleton_eq_cons]) lemma abs_sum_le_sum_abs [linear_ordered_add_comm_group α] {s : multiset α} : abs s.sum ≤ (s.map abs).sum := le_sum_of_subadditive _ abs_zero abs_add s end multiset @[to_additive] lemma monoid_hom.map_multiset_prod [comm_monoid α] [comm_monoid β] (f : α →* β) (s : multiset α) : f s.prod = (s.map f).prod := (s.prod_hom f).symm
2a7c738fd01a6a955a29951f8f211e55048b5ff8
ac1c2a2f522b0fdf854095ba00f882ca849669e7
/library/init/meta/constructor_tactic.lean
332f67a6ce6792678f0d46221b5c65568a0be57b
[ "Apache-2.0" ]
permissive
abliss/lean
b8b336abc8d50dbb0726dcff9dd16793c23bfbe1
fb24cc99573c153f97a1951ee94bbbdda300b6be
refs/heads/master
1,611,536,584,520
1,497,811,981,000
1,497,811,981,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,770
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.tactic init.function namespace tactic meta def get_constructors_for (e : expr) : tactic (list name) := do env ← get_env, I ← return e.get_app_fn.const_name, when (¬env.is_inductive I) (fail "constructor tactic failed, target is not an inductive datatype"), return $ env.constructors_of I private meta def try_constructors : list name → tactic unit | [] := fail "constructor tactic failed, none of the constructors is applicable" | (c::cs) := (mk_const c >>= apply) <|> try_constructors cs meta def constructor : tactic unit := target >>= instantiate_mvars >>= get_constructors_for >>= try_constructors meta def left : tactic unit := do tgt ← target, [c₁, c₂] ← get_constructors_for tgt | fail "left tactic failed, target is not an inductive datatype with two constructors", mk_const c₁ >>= apply meta def right : tactic unit := do tgt ← target, [c₁, c₂] ← get_constructors_for tgt | fail "left tactic failed, target is not an inductive datatype with two constructors", mk_const c₂ >>= apply meta def constructor_idx (idx : nat) : tactic unit := do cs ← target >>= get_constructors_for, some c ← return $ cs.nth (idx - 1) | fail "constructor_idx tactic failed, target is an inductive datatype, but it does not have sufficient constructors", mk_const c >>= apply meta def split : tactic unit := do [c] ← target >>= get_constructors_for | fail "split tactic failed, target is not an inductive datatype with only one constructor", mk_const c >>= apply open expr private meta def apply_num_metavars : expr → expr → nat → tactic expr | f ftype 0 := return f | f ftype (n+1) := do pi m bi d b ← whnf ftype, a ← mk_meta_var d, new_f ← return $ f a, new_ftype ← return $ b.instantiate_var a, apply_num_metavars new_f new_ftype n meta def existsi (e : expr) : tactic unit := do [c] ← target >>= get_constructors_for | fail "existsi tactic failed, target is not an inductive datatype with only one constructor", fn ← mk_const c, fn_type ← infer_type fn, n ← get_arity fn, when (n < 2) (fail "existsi tactic failed, constructor must have at least two arguments"), t ← apply_num_metavars fn fn_type (n - 2), apply (app t e), t_type ← infer_type t >>= whnf, e_type ← infer_type e, (guard t_type.is_pi <|> fail "existsi tactic failed, failed to infer type"), (unify t_type.binding_domain e_type <|> fail "existsi tactic failed, type mismatch between given term witness and expected type") end tactic
67dd417c9df8af60d32b0393c84388f3585b889f
63abd62053d479eae5abf4951554e1064a4c45b4
/src/tactic/ext.lean
71af952c8f7f291bbfbd3f950163796365b03b72
[ "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
15,410
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import tactic.rcases import data.sum import logic.function.basic universes u₁ u₂ open interactive interactive.types open lean.parser nat tactic /-- `derive_struct_ext_lemma n` generates two extensionality lemmas based on the equality of all non-propositional projections. On the following: ```lean @[ext] structure foo (α : Type*) := (x y : ℕ) (z : {z // z < x}) (k : α) (h : x < y) ``` `derive_struct_lemma` generates: ```lean lemma foo.ext : ∀ {α : Type u_1} (x y : foo α), x.x = y.x → x.y = y.y → x.z == y.z → x.k = y.k → x = y lemma foo.ext_iff : ∀ {α : Type u_1} (x y : foo α), x = y ↔ x.x = y.x ∧ x.y = y.y ∧ x.z == y.z ∧ x.k = y.k ``` -/ meta def derive_struct_ext_lemma (n : name) : tactic name := do e ← get_env, fs ← e.structure_fields n, d ← get_decl n, n ← resolve_constant n, let r := @expr.const tt n $ d.univ_params.map level.param, (args,_) ← infer_type r >>= open_pis, let args := args.map expr.to_implicit_local_const, let t := r.mk_app args, x ← mk_local_def `x t, y ← mk_local_def `y t, let args_x := args ++ [x], let args_y := args ++ [y], bs ← fs.mmap $ λ f, do { d ← get_decl (n ++ f), let a := @expr.const tt (n ++ f) $ d.univ_params.map level.param, t ← infer_type a, s ← infer_type t, if s ≠ `(Prop) then do let x := a.mk_app args_x, let y := a.mk_app args_y, t ← infer_type x, t' ← infer_type y, some <$> if t = t' then mk_app `eq [x,y] >>= mk_local_def `h else mk_mapp `heq [none,x,none,y] >>= mk_local_def `h else pure none }, let bs := bs.filter_map id, eq_t ← mk_app `eq [x,y], t ← pis (args ++ [x,y] ++ bs) eq_t, pr ← run_async $ do { (_,pr) ← solve_aux t (do { args ← intron args.length, x ← intro1, y ← intro1, cases x, cases y, bs.mmap' (λ _, do e ← intro1, cases e), reflexivity }), instantiate_mvars pr }, let decl_n := n <.> "ext", add_decl (declaration.thm decl_n d.univ_params t pr), bs ← bs.mmap infer_type, let rhs := expr.mk_and_lst bs, iff_t ← mk_app `iff [eq_t,rhs], t ← pis (args ++ [x,y]) iff_t, pr ← run_async $ do { (_,pr) ← solve_aux t $ do { args ← intron args.length, x ← intro1, y ← intro1, cases x, cases y, split, solve1 $ do { h ← intro1, hs ← injection h, subst_vars, repeat (refine ``( and.intro _ _ ) >> reflexivity ), done <|> reflexivity }, solve1 $ do { repeat (do refine ``(and_imp.mpr _), h ← intro1, cases h, skip ), h ← intro1, cases h, reflexivity } }, instantiate_mvars pr }, add_decl (declaration.thm (n <.> "ext_iff") d.univ_params t pr), pure decl_n meta def get_ext_subject : expr → tactic name | (expr.pi n bi d b) := do v ← mk_local' n bi d, b' ← whnf $ b.instantiate_var v, get_ext_subject b' | (expr.app _ e) := do t ← infer_type e >>= instantiate_mvars >>= head_beta, if t.get_app_fn.is_constant then pure $ t.get_app_fn.const_name else if t.is_pi then pure $ name.mk_numeral 0 name.anonymous else if t.is_sort then pure $ name.mk_numeral 1 name.anonymous else do t ← pp t, fail format!"only constants and Pi types are supported: {t}" | e := fail format!"Only expressions of the form `_ → _ → ... → R ... e are supported: {e}" open native @[reducible] def ext_param_type := option name ⊕ option name meta def opt_minus : lean.parser (option name → ext_param_type) := sum.inl <$ tk "-" <|> pure sum.inr meta def ext_param := opt_minus <*> ( name.mk_numeral 0 name.anonymous <$ brackets "(" ")" (tk "→" <|> tk "->") <|> none <$ tk "*" <|> some <$> ident ) meta def saturate_fun : name → tactic expr | (name.mk_numeral 0 name.anonymous) := do v₀ ← mk_mvar, v₁ ← mk_mvar, return $ v₀.imp v₁ | (name.mk_numeral 1 name.anonymous) := do u ← mk_meta_univ, pure $ expr.sort u | n := do e ← resolve_constant n >>= mk_const, a ← get_arity e, e.mk_app <$> (list.iota a).mmap (λ _, mk_mvar) meta def equiv_type_constr (n n' : name) : tactic unit := do e ← saturate_fun n, e' ← saturate_fun n', unify e e' <|> fail format!"{n} and {n'} are not definitionally equal types" section performance_hack /-- For performance reasons, it is inadvisable to use `user_attribute.get_param`. The parameter is stored as a reflected expression. When calling `get_param`, the stored parameter is evaluated using `eval_expr`, which first compiles the expression into VM bytecode. The unevaluated expression is available using `user_attribute.get_param_untyped`. In particular, `user_attribute.get_param` MUST NEVER BE USED in the implementation of an attribute cache. This is because calling `eval_expr` disables the attribute cache. There are several possible workarounds: 1. Set a different attribute depending on the parameter. 2. Use your own evaluation function instead of `eval_expr`, such as e.g. `expr.to_nat`. 3. Write your own `has_reflect Param` instance (using a more efficient serialization format). The `user_attribute` code unfortunately checks whether the expression has the correct type, but you can use `` `(id %%e : Param) `` to pretend that your expression `e` has type `Param`. -/ library_note "user attribute parameters" /-! For performance reasons, the parameters of the `@[ext]` attribute are stored in two auxiliary attributes: ```lean attribute [ext [thunk]] funext -- is turned into attribute [_ext_core (@id name @funext)] thunk attribute [_ext_lemma_core] funext ``` see Note [user attribute parameters] -/ local attribute [semireducible] reflected local attribute [instance, priority 9000] private meta def hacky_name_reflect : has_reflect name := λ n, `(id %%(expr.const n []) : name) @[user_attribute] private meta def ext_attr_core : user_attribute (name_map name) name := { name := `_ext_core, descr := "(internal attribute used by ext)", cache_cfg := { dependencies := [], mk_cache := λ ns, do attrs ← ns.mmap (λ n, do ext_l ← ext_attr_core.get_param_untyped n, pure (n, ext_l.app_arg.const_name)), pure $ rb_map.of_list attrs }, parser := failure } end performance_hack /-- Private attribute used to tag extensionality lemmas. -/ @[user_attribute] private meta def ext_lemma_attr_core : user_attribute := { name := `_ext_lemma_core, descr := "(internal attribute used by ext)", parser := failure } /-- Returns the extensionality lemmas in the environment, as a map from structure name to lemma name. -/ meta def get_ext_lemmas : tactic (name_map name) := ext_attr_core.get_cache /-- Returns the extensionality lemmas in the environment, as a list of lemma names. -/ meta def get_ext_lemma_names : tactic (list name) := attribute.get_instances ext_lemma_attr_core.name /-- Tag lemmas of the form: ```lean @[ext] lemma my_collection.ext (a b : my_collection) (h : ∀ x, a.lookup x = b.lookup y) : a = b := ... ``` The attribute indexes extensionality lemma using the type of the objects (i.e. `my_collection`) which it gets from the statement of the lemma. In some cases, the same lemma can be used to state the extensionality of multiple types that are definitionally equivalent. ```lean attribute [ext [(→),thunk,stream]] funext ``` Those parameters are cumulative. The following are equivalent: ```lean attribute [ext [(→),thunk]] funext attribute [ext [stream]] funext ``` and ```lean attribute [ext [(→),thunk,stream]] funext ``` One removes type names from the list for one lemma with: ```lean attribute [ext [-stream,-thunk]] funext ``` Also, the following: ```lean @[ext] lemma my_collection.ext (a b : my_collection) (h : ∀ x, a.lookup x = b.lookup y) : a = b := ... ``` is equivalent to ```lean @[ext *] lemma my_collection.ext (a b : my_collection) (h : ∀ x, a.lookup x = b.lookup y) : a = b := ... ``` This allows us specify type synonyms along with the type that is referred to in the lemma statement. ```lean @[ext [*,my_type_synonym]] lemma my_collection.ext (a b : my_collection) (h : ∀ x, a.lookup x = b.lookup y) : a = b := ... ``` The `ext` attribute can be applied to a structure to generate its extensionality lemmas: ```lean @[ext] structure foo (α : Type*) := (x y : ℕ) (z : {z // z < x}) (k : α) (h : x < y) ``` will generate: ```lean @[ext] lemma foo.ext : ∀ {α : Type u_1} (x y : foo α), x.x = y.x → x.y = y.y → x.z == y.z → x.k = y.k → x = y lemma foo.ext_iff : ∀ {α : Type u_1} (x y : foo α), x = y ↔ x.x = y.x ∧ x.y = y.y ∧ x.z == y.z ∧ x.k = y.k ``` -/ @[user_attribute] meta def extensional_attribute : user_attribute unit (list ext_param_type) := { name := `ext, descr := "lemmas usable by `ext` tactic", parser := pure <$> ext_param <|> list_of ext_param <|> pure [], after_set := some $ λ n prio b, do ls ← extensional_attribute.get_param n, e ← get_env, n ← if (e.structure_fields n).is_some then derive_struct_ext_lemma n else pure n, s ← mk_const n >>= infer_type >>= get_ext_subject, let (rs,ls'') := if ls.empty then ([],[s]) else ls.partition_map (sum.map (flip option.get_or_else s) (flip option.get_or_else s)), ls''.mmap' (equiv_type_constr s), ls' ← get_ext_lemmas, let l := ls'' ∪ (ls'.to_list.filter $ λ l, prod.snd l = n).map prod.fst \ rs, l.mmap' $ λ l, do ext_attr_core.set l n b prio, ext_lemma_attr_core.set n () b prio } add_tactic_doc { name := "ext", category := doc_category.attr, decl_names := [`extensional_attribute], tags := ["rewrite", "logic"] } -- We mark some existing extensionality lemmas. attribute [ext] array.ext propext function.hfunext attribute [ext [(→),thunk]] _root_.funext -- We create some extensionality lemmas for existing structures. attribute [ext] ulift namespace plift -- This is stronger than the one generated automatically. @[ext] lemma ext {P : Prop} (a b : plift P) : a = b := begin cases a, cases b, refl end end plift -- Conservatively, we'll only add extensionality lemmas for `has_*` structures -- as they become useful. attribute [ext] has_zero @[ext] lemma unit.ext {x y : unit} : x = y := by { cases x, cases y, refl, } @[ext] lemma punit.ext {x y : punit} : x = y := by { cases x, cases y, refl, } namespace tactic /-- Try to introduce as many arguments as possible, using the given patterns to destruct the introduced variables. Returns the unused patterns. -/ meta def try_intros : list rcases_patt → tactic (list rcases_patt) | [] := try intros $> [] | (x::xs) := do tgt ← target >>= whnf, if tgt.is_pi then rintro [x] >> try_intros xs else pure (x :: xs) /-- Apply one extensionality lemma, and destruct the arguments using the given patterns. Returns the unused patterns. -/ meta def ext1 (xs : list rcases_patt) (cfg : apply_cfg := {}) : tactic (list rcases_patt) := do subject ← target >>= get_ext_subject, m ← get_ext_lemmas, do { rule ← m.find subject, applyc rule cfg } <|> do { ls ← get_ext_lemma_names, ls.any_of (λ n, applyc n cfg) } <|> fail format!"no applicable extensionality rule found for {subject}", try_intros xs /-- Apply multiple extensionality lemmas, destructing the arguments using the given patterns. `ext ps (some n)` applies at most `n` extensionality lemmas. Returns the unused patterns. -/ meta def ext : list rcases_patt → option ℕ → tactic (list rcases_patt) | xs (some 0) := return xs | xs n := focus1 $ do ys ← ext1 xs, (ext ys (nat.pred <$> n) <|> return ys) local postfix `?`:9001 := optional local postfix *:9001 := many /-- `ext1 id` selects and apply one extensionality lemma (with attribute `ext`), using `id`, if provided, to name a local constant introduced by the lemma. If `id` is omitted, the local constant is named automatically, as per `intro`. -/ meta def interactive.ext1 (xs : parse (rcases_patt_parse tt)*) : tactic unit := ext1 xs $> () /-- - `ext` applies as many extensionality lemmas as possible; - `ext ids`, with `ids` a list of identifiers, finds extentionality and applies them until it runs out of identifiers in `ids` to name the local constants. - `ext` can also be given an `rcases` pattern in place of an identifier. This will destruct the introduced local constant. When trying to prove: ```lean α β : Type, f g : α → set β ⊢ f = g ``` applying `ext x y` yields: ```lean α β : Type, f g : α → set β, x : α, y : β ⊢ y ∈ f x ↔ y ∈ f x ``` by applying functional extensionality and set extensionality. When trying to prove: ```lean α β γ : Type f g : α × β → γ ⊢ f = g ``` applying `ext ⟨a, b⟩` yields: ```lean α β γ : Type, f g : α × β → γ, a : α, b : β ⊢ f (a, b) = g (a, b) ``` by applying functional extensionality and destructing the introduced pair. A maximum depth can be provided with `ext x y z : 3`. -/ meta def interactive.ext : parse (rcases_patt_parse tt)* → parse (tk ":" *> small_nat)? → tactic unit | [] (some n) := iterate_range 1 n (ext1 [] $> ()) | [] none := repeat1 (ext1 [] $> ()) | xs n := tactic.ext xs n $> () /-- * `ext1 id` selects and apply one extensionality lemma (with attribute `ext`), using `id`, if provided, to name a local constant introduced by the lemma. If `id` is omitted, the local constant is named automatically, as per `intro`. * `ext` applies as many extensionality lemmas as possible; * `ext ids`, with `ids` a list of identifiers, finds extensionality lemmas and applies them until it runs out of identifiers in `ids` to name the local constants. * `ext` can also be given an `rcases` pattern in place of an identifier. This will destruct the introduced local constant. When trying to prove: ```lean α β : Type, f g : α → set β ⊢ f = g ``` applying `ext x y` yields: ```lean α β : Type, f g : α → set β, x : α, y : β ⊢ y ∈ f x ↔ y ∈ g x ``` by applying functional extensionality and set extensionality. When trying to prove: ```lean α β γ : Type f g : α × β → γ ⊢ f = g ``` applying `ext ⟨a, b⟩` yields: ```lean α β γ : Type, f g : α × β → γ, a : α, b : β ⊢ f (a, b) = g (a, b) ``` by applying functional extensionality and destructing the introduced pair. A maximum depth can be provided with `ext x y z : 3`. -/ add_tactic_doc { name := "ext1 / ext", category := doc_category.tactic, decl_names := [`tactic.interactive.ext1, `tactic.interactive.ext], tags := ["rewriting", "logic"] } end tactic
778c59750615dfa500be4b33a9eff8a50c253c72
618003631150032a5676f229d13a079ac875ff77
/src/control/basic.lean
030f31e86dbb7063294b38ccc52587755095b937
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
6,816
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 Extends the theory on functors, applicatives and monads. -/ universes u v w variables {α β γ : Type u} notation a ` $< `:1 f:1 := f a section functor variables {f : Type u → Type v} [functor f] [is_lawful_functor f] run_cmd mk_simp_attr `functor_norm run_cmd tactic.add_doc_string `simp_attr.functor_norm "Simp set for functor_norm" @[functor_norm] protected theorem map_map (m : α → β) (g : β → γ) (x : f α) : g <$> (m <$> x) = (g ∘ m) <$> x := (comp_map _ _ _).symm @[simp] theorem id_map' (x : f α) : (λa, a) <$> x = x := id_map _ end functor section applicative variables {F : Type u → Type v} [applicative F] def mzip_with {α₁ α₂ φ : Type u} (f : α₁ → α₂ → F φ) : Π (ma₁ : list α₁) (ma₂: list α₂), F (list φ) | (x :: xs) (y :: ys) := (::) <$> f x y <*> mzip_with xs ys | _ _ := pure [] def mzip_with' (f : α → β → F γ) : list α → list β → F punit | (x :: xs) (y :: ys) := f x y *> mzip_with' xs ys | [] _ := pure punit.star | _ [] := pure punit.star variables [is_lawful_applicative F] attribute [functor_norm] seq_assoc pure_seq_eq_map @[simp] theorem pure_id'_seq (x : F α) : pure (λx, x) <*> x = x := pure_id_seq x attribute [functor_norm] seq_assoc pure_seq_eq_map @[functor_norm] theorem seq_map_assoc (x : F (α → β)) (f : γ → α) (y : F γ) : (x <*> (f <$> y)) = (λ(m:α→β), m ∘ f) <$> x <*> y := begin simp [(pure_seq_eq_map _ _).symm], simp [seq_assoc, (comp_map _ _ _).symm, (∘)], simp [pure_seq_eq_map] end @[functor_norm] theorem map_seq (f : β → γ) (x : F (α → β)) (y : F α) : (f <$> (x <*> y)) = ((∘) f) <$> x <*> y := by simp [(pure_seq_eq_map _ _).symm]; simp [seq_assoc] end applicative -- TODO: setup `functor_norm` for `monad` laws attribute [functor_norm] pure_bind bind_assoc bind_pure section monad variables {m : Type u → Type v} [monad m] [is_lawful_monad m] open list def list.mpartition {f : Type → Type} [monad f] {α : Type} (p : α → f bool) : list α → f (list α × list α) | [] := pure ([],[]) | (x :: xs) := mcond (p x) (prod.map (cons x) id <$> list.mpartition xs) (prod.map id (cons x) <$> list.mpartition xs) lemma map_bind (x : m α) {g : α → m β} {f : β → γ} : f <$> (x >>= g) = (x >>= λa, f <$> g a) := by rw [← bind_pure_comp_eq_map,bind_assoc]; simp [bind_pure_comp_eq_map] lemma seq_bind_eq (x : m α) {g : β → m γ} {f : α → β} : (f <$> x) >>= g = (x >>= g ∘ f) := show bind (f <$> x) g = bind x (g ∘ f), by rw [← bind_pure_comp_eq_map, bind_assoc]; simp [pure_bind] lemma seq_eq_bind_map {x : m α} {f : m (α → β)} : f <*> x = (f >>= (<$> x)) := (bind_map_eq_seq f x).symm /-- This is the Kleisli composition -/ @[reducible] def fish {m} [monad m] {α β γ} (f : α → m β) (g : β → m γ) := λ x, f x >>= g -- >=> is already defined in the core library but it is unusable -- because of its precedence (it is defined with precedence 2) and -- because it is defined as a lambda instead of having a named -- function infix ` >=> `:55 := fish @[functor_norm] lemma fish_pure {α β} (f : α → m β) : f >=> pure = f := by simp only [(>=>)] with functor_norm @[functor_norm] lemma fish_pipe {α β} (f : α → m β) : pure >=> f = f := by simp only [(>=>)] with functor_norm @[functor_norm] lemma fish_assoc {α β γ φ} (f : α → m β) (g : β → m γ) (h : γ → m φ) : (f >=> g) >=> h = f >=> (g >=> h) := by simp only [(>=>)] with functor_norm variables {β' γ' : Type v} variables {m' : Type v → Type w} [monad m'] def list.mmap_accumr (f : α → β' → m' (β' × γ')) : β' → list α → m' (β' × list γ') | a [] := pure (a,[]) | a (x :: xs) := do (a',ys) ← list.mmap_accumr a xs, (a'',y) ← f x a', pure (a'',y::ys) def list.mmap_accuml (f : β' → α → m' (β' × γ')) : β' → list α → m' (β' × list γ') | a [] := pure (a,[]) | a (x :: xs) := do (a',y) ← f a x, (a'',ys) ← list.mmap_accuml a' xs, pure (a'',y :: ys) end monad section variables {m : Type u → Type u} [monad m] [is_lawful_monad m] lemma mjoin_map_map {α β : Type u} (f : α → β) (a : m (m α)) : mjoin (functor.map f <$> a) = f <$> (mjoin a) := by simp only [mjoin, (∘), id.def, (bind_pure_comp_eq_map _ _).symm, bind_assoc, map_bind, pure_bind] lemma mjoin_map_mjoin {α : Type u} (a : m (m (m α))) : mjoin (mjoin <$> a) = mjoin (mjoin a) := by simp only [mjoin, (∘), id.def, map_bind, (bind_pure_comp_eq_map _ _).symm, bind_assoc, pure_bind] @[simp] lemma mjoin_map_pure {α : Type u} (a : m α) : mjoin (pure <$> a) = a := by simp only [mjoin, (∘), id.def, map_bind, (bind_pure_comp_eq_map _ _).symm, bind_assoc, pure_bind, bind_pure] @[simp] lemma mjoin_pure {α : Type u} (a : m α) : mjoin (pure a) = a := is_lawful_monad.pure_bind a id end section alternative variables {F : Type → Type v} [alternative F] def succeeds {α} (x : F α) : F bool := (x $> tt) <|> pure ff def mtry {α} (x : F α) : F unit := (x $> ()) <|> pure () @[simp] theorem guard_true {h : decidable true} : @guard F _ true h = pure () := by simp [guard] @[simp] theorem guard_false {h : decidable false} : @guard F _ false h = failure := by simp [guard] end alternative namespace sum variables {e : Type v} protected def bind {α β} : e ⊕ α → (α → e ⊕ β) → e ⊕ β | (inl x) _ := inl x | (inr x) f := f x instance : monad (sum.{v u} e) := { pure := @sum.inr e, bind := @sum.bind e } instance : is_lawful_functor (sum.{v u} e) := by refine { .. }; intros; casesm _ ⊕ _; refl instance : is_lawful_monad (sum.{v u} e) := { bind_assoc := by { intros, casesm _ ⊕ _; refl }, pure_bind := by { intros, refl }, bind_pure_comp_eq_map := by { intros, casesm _ ⊕ _; refl }, bind_map_eq_seq := by { intros, cases f; refl } } end sum section prio set_option default_priority 100 -- see Note [default priority] class is_comm_applicative (m : Type* → Type*) [applicative m] extends is_lawful_applicative m : Prop := (commutative_prod : ∀{α β} (a : m α) (b : m β), prod.mk <$> a <*> b = (λb a, (a, b)) <$> b <*> a) end prio lemma is_comm_applicative.commutative_map {m : Type* → Type*} [applicative m] [is_comm_applicative m] {α β γ} (a : m α) (b : m β) {f : α → β → γ} : f <$> a <*> b = flip f <$> b <*> a := calc f <$> a <*> b = (λp:α×β, f p.1 p.2) <$> (prod.mk <$> a <*> b) : by simp [seq_map_assoc, map_seq, seq_assoc, seq_pure, map_map] ... = (λb a, f a b) <$> b <*> a : by rw [is_comm_applicative.commutative_prod]; simp [seq_map_assoc, map_seq, seq_assoc, seq_pure, map_map]
c2fa3afcc4e0641ac1659817009a239e218f73d9
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/loop2.lean
9fc6e08bf4ddefe0f7d9d723c03218f63b71d2b9
[ "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
252
lean
import Int. (* function add_paren(code) return "(" .. "* " .. code .. " *" .. ")" end parse_lean_cmds(add_paren([[ local env = get_environment() env:add_var("x", Const("Int")) print(env:find_object("x")) ]])) print("done") *)
f40c21fcab3e33f40613177fb5fe1e9f4a181636
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Compiler/Specialize.lean
37e8b1852556e929813b4f90a1cd6dbcd9764752
[ "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,953
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.Attributes namespace Lean.Compiler inductive SpecializeAttributeKind where | specialize | nospecialize deriving Inhabited, BEq builtin_initialize specializeAttrs : EnumAttributes SpecializeAttributeKind ← registerEnumAttributes `specializeAttrs [(`specialize, "mark definition to always be specialized", SpecializeAttributeKind.specialize), (`nospecialize, "mark definition to never be specialized", SpecializeAttributeKind.nospecialize) ] /- TODO: fix the following hack. We need to use the following hack because the equation compiler generates auxiliary definitions that are compiled before we even finish the elaboration of the current command. So, if the current command is a `@[specialize] def foo ...`, we must set the attribute `[specialize]` before we start elaboration, otherwise when we compile the auxiliary definitions we will not be able to test whether `@[specialize]` has been set or not. In the new equation compiler we should pass all attributes and allow it to apply them to auxiliary definitions. In the current implementation, we workaround this issue by using functions such as `hasSpecializeAttrAux`. -/ (applicationTime := .beforeElaboration) private partial def hasSpecializeAttrAux (env : Environment) (kind : SpecializeAttributeKind) (n : Name) : Bool := match specializeAttrs.getValue env n with | some k => kind == k | none => if n.isInternal then hasSpecializeAttrAux env kind n.getPrefix else false @[export lean_has_specialize_attribute] def hasSpecializeAttribute (env : Environment) (n : Name) : Bool := hasSpecializeAttrAux env SpecializeAttributeKind.specialize n @[export lean_has_nospecialize_attribute] def hasNospecializeAttribute (env : Environment) (n : Name) : Bool := hasSpecializeAttrAux env SpecializeAttributeKind.nospecialize n inductive SpecArgKind where | fixed | fixedNeutral -- computationally neutral | fixedHO -- higher order | fixedInst -- type class instance | other deriving Inhabited structure SpecInfo where mutualDecls : List Name argKinds : SpecArgKind deriving Inhabited structure SpecState where specInfo : SMap Name SpecInfo := {} cache : SMap Expr Name := {} deriving Inhabited inductive SpecEntry where | info (name : Name) (info : SpecInfo) | cache (key : Expr) (fn : Name) deriving Inhabited namespace SpecState def addEntry (s : SpecState) (e : SpecEntry) : SpecState := match e with | SpecEntry.info name info => { s with specInfo := s.specInfo.insert name info } | SpecEntry.cache key fn => { s with cache := s.cache.insert key fn } def switch : SpecState → SpecState | ⟨m₁, m₂⟩ => ⟨m₁.switch, m₂.switch⟩ end SpecState builtin_initialize specExtension : SimplePersistentEnvExtension SpecEntry SpecState ← registerSimplePersistentEnvExtension { name := `specialize, addEntryFn := SpecState.addEntry, addImportedFn := fun es => (mkStateFromImportedEntries SpecState.addEntry {} es).switch } @[export lean_add_specialization_info] def addSpecializationInfo (env : Environment) (fn : Name) (info : SpecInfo) : Environment := specExtension.addEntry env (SpecEntry.info fn info) @[export lean_get_specialization_info] def getSpecializationInfo (env : Environment) (fn : Name) : Option SpecInfo := (specExtension.getState env).specInfo.find? fn @[export lean_cache_specialization] def cacheSpecialization (env : Environment) (e : Expr) (fn : Name) : Environment := specExtension.addEntry env (SpecEntry.cache e fn) @[export lean_get_cached_specialization] def getCachedSpecialization (env : Environment) (e : Expr) : Option Name := (specExtension.getState env).cache.find? e end Lean.Compiler
63d28ca50e0287d7cca84a00369a1e00888461bd
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/tree.lean
efbc1650619792b97c99f2cd8cf65671ec91f25f
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
2,424
lean
/- Copyright (c) 2019 Mathlib Authors. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Wojciech Nawrocki -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.num.basic import Mathlib.PostPort universes u l u_1 namespace Mathlib /-! # Binary tree Provides binary tree storage for values of any type, with O(lg n) retrieval. See also `data.rbtree` for red-black trees - this version allows more operations to be defined and is better suited for in-kernel computation. ## References <https://leanprover-community.github.io/archive/113488general/62193tacticquestion.html> -/ /-- A binary tree with values stored in non-leaf nodes. -/ inductive tree (α : Type u) where | nil : tree α | node : α → tree α → tree α → tree α namespace tree /-- Construct a string representation of a tree. Provides a `has_repr` instance. -/ def repr {α : Type u} [has_repr α] : tree α → string := sorry protected instance has_repr {α : Type u} [has_repr α] : has_repr (tree α) := has_repr.mk repr protected instance inhabited {α : Type u} : Inhabited (tree α) := { default := nil } /-- Makes a `tree α` out of a red-black tree. -/ def of_rbnode {α : Type u} : rbnode α → tree α := sorry /-- Finds the index of an element in the tree assuming the tree has been constructed according to the provided decidable order on its elements. If it hasn't, the result will be incorrect. If it has, but the element is not in the tree, returns none. -/ def index_of {α : Type u} (lt : α → α → Prop) [DecidableRel lt] (x : α) : tree α → Option pos_num := sorry /-- Retrieves an element uniquely determined by a `pos_num` from the tree, taking the following path to get to the element: - `bit0` - go to left child - `bit1` - go to right child - `pos_num.one` - retrieve from here -/ def get {α : Type u} : pos_num → tree α → Option α := sorry /-- Retrieves an element from the tree, or the provided default value if the index is invalid. See `tree.get`. -/ def get_or_else {α : Type u} (n : pos_num) (t : tree α) (v : α) : α := option.get_or_else (get n t) v /-- Apply a function to each value in the tree. This is the `map` function for the `tree` functor. TODO: implement `traversable tree`. -/ def map {α : Type u} {β : Type u_1} (f : α → β) : tree α → tree β := sorry
6b37b219dc5dacd946a9d382172733d2826d2ea7
618003631150032a5676f229d13a079ac875ff77
/src/category_theory/hom_functor.lean
b169dd7400e8da8f90680951007600149921960d
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
876
lean
/- Copyright (c) 2018 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Scott Morrison -/ import category_theory.products.basic /-! The hom functor, sending `(X, Y)` to the type `X ⟶ Y`. -/ universes v u open opposite open category_theory namespace category_theory.functor variables (C : Type u) [category.{v} C] /-- `functor.hom` is the hom-pairing, sending (X,Y) to X → Y, contravariant in X and covariant in Y. -/ definition hom : Cᵒᵖ × C ⥤ Type v := { obj := λ p, unop p.1 ⟶ p.2, map := λ X Y f, λ h, f.1.unop ≫ h ≫ f.2 } @[simp] lemma hom_obj (X : Cᵒᵖ × C) : (hom C).obj X = (unop X.1 ⟶ X.2) := rfl @[simp] lemma hom_pairing_map {X Y : Cᵒᵖ × C} (f : X ⟶ Y) : (hom C).map f = λ h, f.1.unop ≫ h ≫ f.2 := rfl end category_theory.functor
59fe30f46c8ccae81cb2740942e8be1af5133b07
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Elab/PreDefinition/Structural/FindRecArg.lean
f1d150ae6eb35b6773f4ab0fa78dbd4e5396dff7
[ "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
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
6,516
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.PreDefinition.Structural.Basic namespace Lean.Elab.Structural open Meta private def getIndexMinPos (xs : Array Expr) (indices : Array Expr) : Nat := Id.run <| do let mut minPos := xs.size for index in indices do match xs.indexOf? index with | some pos => if pos.val < minPos then minPos := pos.val | _ => pure () return minPos -- Indices can only depend on other indices private def hasBadIndexDep? (ys : Array Expr) (indices : Array Expr) : MetaM (Option (Expr × Expr)) := do for index in indices do let indexType ← inferType index for y in ys do if !indices.contains y && (← dependsOn indexType y.fvarId!) then return some (index, y) return none -- Inductive datatype parameters cannot depend on ys private def hasBadParamDep? (ys : Array Expr) (indParams : Array Expr) : MetaM (Option (Expr × Expr)) := do for p in indParams do let pType ← inferType p for y in ys do if ← dependsOn pType y.fvarId! then return some (p, y) return none private def throwStructuralFailed : MetaM α := throwError "structural recursion cannot be used" private def orelse' (x y : M α) : M α := do let saveState ← get orelseMergeErrors x (do set saveState; y) /-- Try to find an argument that is structurally smaller in every recursive application. We use this argument to justify termination using the auxiliary `brecOn` construction. We give preference for arguments that are *not* indices of inductive types of other arguments. See issue #837 for an example where we can show termination using the index of an inductive family, but we don't get the desired definitional equalities. We perform two passes. In the first-pass, we only consider arguments that are not indices. In the second pass, we consider them. TODO: explore whether there are better solutions, and whether there are other ways to break the heuristic used for creating the smart unfolding auxiliary definition. -/ partial def findRecArg (numFixed : Nat) (xs : Array Expr) (k : RecArgInfo → M α) : M α := do /- Collect arguments that are indices. See comment above. -/ let indicesRef : IO.Ref FVarIdSet ← IO.mkRef {} for x in xs do let xType ← inferType x /- Traverse all sub-expressions in the type of `x` -/ forEachExpr xType fun e => /- If `e` is an inductive family, we store in `indicesRef` all variables in `xs` that occur in "index positions". -/ matchConstInduct e.getAppFn (fun _ => pure ()) fun info _ => do if info.numIndices > 0 && info.numParams + info.numIndices == e.getAppNumArgs then for arg in e.getAppArgs[:info.numIndices] do forEachExpr arg fun e => do if e.isFVar && xs.any (. == e) then indicesRef.modify fun indices => indices.insert e.fvarId! let indices ← indicesRef.get /- We perform two passes. See comment above. -/ let rec go (i : Nat) (firstPass : Bool) : M α := do if h : i < xs.size then let x := xs.get ⟨i, h⟩ let localDecl ← getFVarLocalDecl x if localDecl.isLet then throwStructuralFailed else if firstPass == indices.contains localDecl.fvarId then go (i+1) firstPass else let xType ← whnfD localDecl.type matchConstInduct xType.getAppFn (fun _ => go (i+1) firstPass) fun indInfo us => do if !(← hasConst (mkBRecOnName indInfo.name)) then go (i+1) firstPass else if indInfo.isReflexive && !(← hasConst (mkBInductionOnName indInfo.name)) then go (i+1) firstPass else let indArgs := xType.getAppArgs let indParams := indArgs.extract 0 indInfo.numParams let indIndices := indArgs.extract indInfo.numParams indArgs.size if !indIndices.all Expr.isFVar then orelse' (throwError "argument #{i+1} was not used because its type is an inductive family and indices are not variables{indentExpr xType}") (go (i+1) firstPass) else if !indIndices.allDiff then orelse' (throwError "argument #{i+1} was not used because its type is an inductive family and indices are not pairwise distinct{indentExpr xType}") (go (i+1) firstPass) else let indexMinPos := getIndexMinPos xs indIndices let numFixed := if indexMinPos < numFixed then indexMinPos else numFixed let fixedParams := xs.extract 0 numFixed let ys := xs.extract numFixed xs.size match (← hasBadIndexDep? ys indIndices) with | some (index, y) => orelse' (throwError "argument #{i+1} was not used because its type is an inductive family{indentExpr xType}\nand index{indentExpr index}\ndepends on the non index{indentExpr y}") (go (i+1) firstPass) | none => match (← hasBadParamDep? ys indParams) with | some (indParam, y) => orelse' (throwError "argument #{i+1} was not used because its type is an inductive datatype{indentExpr xType}\nand parameter{indentExpr indParam}\ndepends on{indentExpr y}") (go (i+1) firstPass) | none => let indicesPos := indIndices.map fun index => match ys.indexOf? index with | some i => i.val | none => unreachable! orelse' (mapError (k { fixedParams := fixedParams ys := ys pos := i - fixedParams.size indicesPos := indicesPos indName := indInfo.name indLevels := us indParams := indParams indIndices := indIndices reflexive := indInfo.isReflexive indPred := ←isInductivePredicate indInfo.name }) (fun msg => m!"argument #{i+1} was not used for structural recursion{indentD msg}")) (go (i+1) firstPass) else if firstPass then go (i := numFixed) (firstPass := false) else throwStructuralFailed go (i := numFixed) (firstPass := true) end Lean.Elab.Structural
aaca3d49c44e34f5be822087db5901247bf4c560
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/dep_subst.lean
fccd1e928d9e5581307b4aa0dc210d0769f0ad72
[ "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
780
lean
import data.finset open subtype setoid finset set inductive finite_set [class] {T : Type} (xs : set T) := | mk : ∀ (fxs : finset T), to_set fxs = xs → finite_set xs definition card {T : Type} (xs : set T) [fn : finite_set xs] : nat := begin induction fn, exact finset.card fxs end example {T : Type} (xs : set T) [fn₁ : finite_set xs] [fn₂ : finite_set xs] : @card T xs fn₁ = @card T xs fn₂ := begin induction fn₁ with fxs₁ h₁, induction fn₂ with fxs₂ h₂, subst xs, apply sorry end example {T : Type} (xs : set T) [fn₁ : finite_set xs] [fn₂ : finite_set xs] : @card T xs fn₁ = @card T xs fn₂ := begin induction fn₁ with fxs₁ h₁, induction fn₂ with fxs₂ h₂, subst xs, note aux := to_set.inj h₂, subst aux end
d970a6eb159ff49bd12d0f63d62a934cff6f3dc6
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Std/Data/RBMap.lean
d3143107e26b827153f1dfe2a35e3e31021fcb05
[ "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
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
13,936
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 -/ namespace Std universe u v w w' inductive Rbcolor where | red | black inductive RBNode (α : Type u) (β : α → Type v) where | leaf : RBNode α β | node (color : Rbcolor) (lchild : RBNode α β) (key : α) (val : β key) (rchild : RBNode α β) : RBNode α β namespace RBNode variable {α : Type u} {β : α → Type v} {σ : Type w} open Std.Rbcolor Nat def depth (f : Nat → Nat → Nat) : RBNode α β → Nat | leaf => 0 | node _ l _ _ r => succ (f (depth f l) (depth f r)) protected def min : RBNode α β → Option (Sigma (fun k => β k)) | leaf => none | node _ leaf k v _ => some ⟨k, v⟩ | node _ l k v _ => RBNode.min l protected def max : RBNode α β → Option (Sigma (fun k => β k)) | leaf => none | node _ _ k v leaf => some ⟨k, v⟩ | node _ _ k v r => RBNode.max r @[specialize] def fold (f : σ → (k : α) → β k → σ) : (init : σ) → RBNode α β → σ | b, leaf => b | b, node _ l k v r => fold f (f (fold f b l) k v) r @[specialize] def forM [Monad m] (f : (k : α) → β k → m Unit) : RBNode α β → m Unit | leaf => pure () | node _ l k v r => do forM f l; f k v; forM f r @[specialize] def foldM [Monad m] (f : σ → (k : α) → β k → m σ) : (init : σ) → RBNode α β → m σ | b, leaf => pure b | b, node _ l k v r => do let b ← foldM f b l let b ← f b k v foldM f b r @[inline] protected def forIn [Monad m] (as : RBNode α β) (init : σ) (f : (k : α) → β k → σ → m (ForInStep σ)) : m σ := do let rec @[specialize] visit : RBNode α β → σ → m (ForInStep σ) | leaf, b => return ForInStep.yield b | node _ l k v r, b => do match (← visit l b) with | r@(ForInStep.done _) => return r | ForInStep.yield b => match (← f k v b) with | r@(ForInStep.done _) => return r | ForInStep.yield b => visit r b match (← visit as init) with | ForInStep.done b => pure b | ForInStep.yield b => pure b @[specialize] def revFold (f : σ → (k : α) → β k → σ) : (init : σ) → RBNode α β → σ | b, leaf => b | b, node _ l k v r => revFold f (f (revFold f b r) k v) l @[specialize] def all (p : (k : α) → β k → Bool) : RBNode α β → Bool | leaf => true | node _ l k v r => p k v && all p l && all p r @[specialize] def any (p : (k : α) → β k → Bool) : RBNode α β → Bool | leaf => false | node _ l k v r => p k v || any p l || any p r def singleton (k : α) (v : β k) : RBNode α β := node red leaf k v leaf @[inline] def balance1 : (a : α) → β a → RBNode α β → RBNode α β → RBNode α β | 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 -- unreachable @[inline] def balance2 : RBNode α β → (a : α) → β a → RBNode α β → RBNode α β | 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 -- unreachable def isRed : RBNode α β → Bool | node red .. => true | _ => false def isBlack : RBNode α β → Bool | node black .. => true | _ => false section Insert variable (cmp : α → α → Ordering) @[specialize] def ins : RBNode α β → (k : α) → β k → RBNode α β | leaf, kx, vx => node red leaf kx vx leaf | node red a ky vy b, kx, vx => match cmp kx ky with | Ordering.lt => node red (ins a kx vx) ky vy b | Ordering.gt => node red a ky vy (ins b kx vx) | Ordering.eq => node red a kx vx b | node black a ky vy b, kx, vx => match cmp kx ky with | Ordering.lt => if isRed a then balance1 ky vy b (ins a kx vx) else node black (ins a kx vx) ky vy b | Ordering.gt => if isRed b then balance2 a ky vy (ins b kx vx) else node black a ky vy (ins b kx vx) | Ordering.eq => node black a kx vx b def setBlack : RBNode α β → RBNode α β | node _ l k v r => node black l k v r | e => e @[specialize] def insert (t : RBNode α β) (k : α) (v : β k) : RBNode α β := if isRed t then setBlack (ins cmp t k v) else ins cmp t k v end Insert def balance₃ (a : RBNode α β) (k : α) (v : β k) (d : RBNode α β) : RBNode α β := match a with | node red (node red a kx vx b) ky vy c => node red (node black a kx vx b) ky vy (node black c k v d) | node red a kx vx (node red b ky vy c) => node red (node black a kx vx b) ky vy (node black c k v d) | a => match d with | node red b ky vy (node red c kz vz d) => node red (node black a k v b) ky vy (node black c kz vz d) | node red (node red b ky vy c) kz vz d => node red (node black a k v b) ky vy (node black c kz vz d) | _ => node black a k v d def setRed : RBNode α β → RBNode α β | node _ a k v b => node red a k v b | e => e def balLeft : RBNode α β → (k : α) → β k → RBNode α β → RBNode α β | node red a kx vx b, k, v, r => node red (node black a kx vx b) k v r | l, k, v, node black a ky vy b => balance₃ l k v (node red a ky vy b) | l, k, v, node red (node black a ky vy b) kz vz c => node red (node black l k v a) ky vy (balance₃ b kz vz (setRed c)) | l, k, v, r => node red l k v r -- unreachable def balRight (l : RBNode α β) (k : α) (v : β k) (r : RBNode α β) : RBNode α β := match r with | (node red b ky vy c) => node red l k v (node black b ky vy c) | _ => match l with | node black a kx vx b => balance₃ (node red a kx vx b) k v r | node red a kx vx (node black b ky vy c) => node red (balance₃ (setRed a) kx vx b) ky vy (node black c k v r) | _ => node red l k v r -- unreachable -- TODO: use wellfounded recursion partial def appendTrees : RBNode α β → RBNode α β → RBNode α β | leaf, x => x | x, leaf => x | node red a kx vx b, node red c ky vy d => match appendTrees b c with | node red b' kz vz c' => node red (node red a kx vx b') kz vz (node red c' ky vy d) | bc => node red a kx vx (node red bc ky vy d) | node black a kx vx b, node black c ky vy d => match appendTrees b c with | node red b' kz vz c' => node red (node black a kx vx b') kz vz (node black c' ky vy d) | bc => balLeft a kx vx (node black bc ky vy d) | a, node red b kx vx c => node red (appendTrees a b) kx vx c | node red a kx vx b, c => node red a kx vx (appendTrees b c) section Erase variable (cmp : α → α → Ordering) @[specialize] def del (x : α) : RBNode α β → RBNode α β | leaf => leaf | node _ a y v b => match cmp x y with | Ordering.lt => if a.isBlack then balLeft (del x a) y v b else node red (del x a) y v b | Ordering.gt => if b.isBlack then balRight a y v (del x b) else node red a y v (del x b) | Ordering.eq => appendTrees a b @[specialize] def erase (x : α) (t : RBNode α β) : RBNode α β := let t := del cmp x t; t.setBlack end Erase section Membership variable (cmp : α → α → Ordering) @[specialize] def findCore : RBNode α β → (k : α) → Option (Sigma (fun k => β k)) | leaf, x => none | node _ a ky vy b, x => match cmp x ky with | Ordering.lt => findCore a x | Ordering.gt => findCore b x | Ordering.eq => some ⟨ky, vy⟩ @[specialize] def find {β : Type v} : RBNode α (fun _ => β) → α → Option β | leaf, x => none | node _ a ky vy b, x => match cmp x ky with | Ordering.lt => find a x | Ordering.gt => find b x | Ordering.eq => some vy @[specialize] def lowerBound : RBNode α β → α → Option (Sigma β) → Option (Sigma β) | leaf, x, lb => lb | node _ a ky vy b, x, lb => match cmp x ky with | Ordering.lt => lowerBound a x lb | Ordering.gt => lowerBound b x (some ⟨ky, vy⟩) | Ordering.eq => some ⟨ky, vy⟩ end Membership inductive WellFormed (cmp : α → α → Ordering) : RBNode α β → Prop where | leafWff : WellFormed cmp leaf | insertWff {n n' : RBNode α β} {k : α} {v : β k} : WellFormed cmp n → n' = insert cmp n k v → WellFormed cmp n' | eraseWff {n n' : RBNode α β} {k : α} : WellFormed cmp n → n' = erase cmp k n → WellFormed cmp n' end RBNode open Std.RBNode /- TODO(Leo): define dRBMap -/ def RBMap (α : Type u) (β : Type v) (cmp : α → α → Ordering) : Type (max u v) := {t : RBNode α (fun _ => β) // t.WellFormed cmp } @[inline] def mkRBMap (α : Type u) (β : Type v) (cmp : α → α → Ordering) : RBMap α β cmp := ⟨leaf, WellFormed.leafWff⟩ @[inline] def RBMap.empty {α : Type u} {β : Type v} {cmp : α → α → Ordering} : RBMap α β cmp := mkRBMap .. instance (α : Type u) (β : Type v) (cmp : α → α → Ordering) : EmptyCollection (RBMap α β cmp) := ⟨RBMap.empty⟩ namespace RBMap variable {α : Type u} {β : Type v} {σ : Type w} {cmp : α → α → Ordering} def depth (f : Nat → Nat → Nat) (t : RBMap α β cmp) : Nat := t.val.depth f @[inline] def fold (f : σ → α → β → σ) : (init : σ) → RBMap α β cmp → σ | b, ⟨t, _⟩ => t.fold f b @[inline] def revFold (f : σ → α → β → σ) : (init : σ) → RBMap α β cmp → σ | b, ⟨t, _⟩ => t.revFold f b @[inline] def foldM [Monad m] (f : σ → α → β → m σ) : (init : σ) → RBMap α β cmp → m σ | b, ⟨t, _⟩ => t.foldM f b @[inline] def forM [Monad m] (f : α → β → m PUnit) (t : RBMap α β cmp) : m PUnit := t.foldM (fun _ k v => f k v) ⟨⟩ @[inline] protected def forIn [Monad m] (t : RBMap α β cmp) (init : σ) (f : (α × β) → σ → m (ForInStep σ)) : m σ := t.val.forIn init (fun a b acc => f (a, b) acc) instance : ForIn m (RBMap α β cmp) (α × β) where forIn := RBMap.forIn @[inline] def isEmpty : RBMap α β cmp → Bool | ⟨leaf, _⟩ => true | _ => false @[specialize] def toList : RBMap α β cmp → List (α × β) | ⟨t, _⟩ => t.revFold (fun ps k v => (k, v)::ps) [] @[inline] protected def min : RBMap α β cmp → Option (α × β) | ⟨t, _⟩ => match t.min with | some ⟨k, v⟩ => some (k, v) | none => none @[inline] protected def max : RBMap α β cmp → Option (α × β) | ⟨t, _⟩ => match t.max with | some ⟨k, v⟩ => some (k, v) | none => none instance [Repr α] [Repr β] : Repr (RBMap α β cmp) where reprPrec m prec := Repr.addAppParen ("Std.rbmapOf " ++ repr m.toList) prec @[inline] def insert : RBMap α β cmp → α → β → RBMap α β cmp | ⟨t, w⟩, k, v => ⟨t.insert cmp k v, WellFormed.insertWff w rfl⟩ @[inline] def erase : RBMap α β cmp → α → RBMap α β cmp | ⟨t, w⟩, k => ⟨t.erase cmp k, WellFormed.eraseWff w rfl⟩ @[specialize] def ofList : List (α × β) → RBMap α β cmp | [] => mkRBMap .. | ⟨k,v⟩::xs => (ofList xs).insert k v @[inline] def findCore? : RBMap α β cmp → α → Option (Sigma (fun (k : α) => β)) | ⟨t, _⟩, x => t.findCore cmp x @[inline] def find? : RBMap α β cmp → α → Option β | ⟨t, _⟩, x => t.find cmp x @[inline] def findD (t : RBMap α β cmp) (k : α) (v₀ : β) : β := (t.find? k).getD v₀ /-- (lowerBound k) retrieves the kv pair of the largest key smaller than or equal to `k`, if it exists. -/ @[inline] def lowerBound : RBMap α β cmp → α → Option (Sigma (fun (k : α) => β)) | ⟨t, _⟩, x => t.lowerBound cmp x none @[inline] def contains (t : RBMap α β cmp) (a : α) : Bool := (t.find? a).isSome @[inline] def fromList (l : List (α × β)) (cmp : α → α → Ordering) : RBMap α β cmp := l.foldl (fun r p => r.insert p.1 p.2) (mkRBMap α β cmp) @[inline] def all : RBMap α β cmp → (α → β → Bool) → Bool | ⟨t, _⟩, p => t.all p @[inline] def any : RBMap α β cmp → (α → β → Bool) → Bool | ⟨t, _⟩, p => t.any p def size (m : RBMap α β cmp) : Nat := m.fold (fun sz _ _ => sz+1) 0 def maxDepth (t : RBMap α β cmp) : Nat := t.val.depth Nat.max @[inline] def min! [Inhabited α] [Inhabited β] (t : RBMap α β cmp) : α × β := match t.min with | some p => p | none => panic! "map is empty" @[inline] def max! [Inhabited α] [Inhabited β] (t : RBMap α β cmp) : α × β := match t.max with | some p => p | none => panic! "map is empty" @[inline] def find! [Inhabited β] (t : RBMap α β cmp) (k : α) : β := match t.find? k with | some b => b | none => panic! "key is not in the map" end RBMap def rbmapOf {α : Type u} {β : Type v} (l : List (α × β)) (cmp : α → α → Ordering) : RBMap α β cmp := RBMap.fromList l cmp end Std
19bf577f007cb41b4c0ef634f7276b7fbb6f168d
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Compiler/LCNF/Simp/Basic.lean
d17549d6f015c50c22588ed9d98bfa68f733a90e
[ "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
1,726
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Instances import Lean.Compiler.InlineAttrs import Lean.Compiler.Specialize import Lean.Compiler.LCNF.CompilerM namespace Lean.Compiler.LCNF /-- Return `true` if the arrow type contains an instance implicit argument. -/ def hasLocalInst (type : Expr) : Bool := match type with | .forallE _ _ b bi => bi.isInstImplicit || hasLocalInst b | _ => false /-- Return `true` if `decl` is supposed to be inlined/specialized. -/ def Decl.isTemplateLike (decl : Decl) : CoreM Bool := do if hasLocalInst decl.type then return true -- `decl` applications will be specialized else if (← Meta.isInstance decl.name) then return true -- `decl` is "fuel" for code specialization else if hasInlineAttribute (← getEnv) decl.name || hasSpecializeAttribute (← getEnv) decl.name then return true -- `decl` is going to be inlined or specialized else return false namespace Simp partial def findExpr (e : Expr) (skipMData := true) : CompilerM Expr := do match e with | .fvar fvarId => let some decl ← findLetDecl? fvarId | return e findExpr decl.value | .mdata _ e' => if skipMData then findExpr e' else return e | _ => return e partial def findFunDecl? (e : Expr) : CompilerM (Option FunDecl) := do match e with | .fvar fvarId => if let some decl ← LCNF.findFunDecl? fvarId then return some decl else if let some decl ← findLetDecl? fvarId then findFunDecl? decl.value else return none | .mdata _ e => findFunDecl? e | _ => return none end Simp end Lean.Compiler.LCNF
a11c63e74de8519240a7dd229956998efdafb104
03bd658c402412f41d3026d1040ee8ca8c0fc579
/src/game/value.lean
46097980a9da0e69470f2f845804d7ab51d13362
[]
no_license
ImperialCollegeLondon/dots_and_boxes
c205f6dbad8af9625f56715e4d1bed96b0ac1022
f7bd0b1603674a657170c5395adb717c4f670220
refs/heads/master
1,663,752,058,476
1,591,438,614,000
1,591,438,614,000
139,707,103
2
0
null
null
null
null
UTF-8
Lean
false
false
2,806
lean
import game.basic import list.min.basic open list open game /--the value of a non-empty game consisting of loops and chains-/ def game.value : game 2 → ℤ := @game.rec_on_size2 (λ G, ℤ) (0 : ℤ) $ λ n hn G hG, list.min (list.bind [(0 : fin 2), (1 : fin 2)] (λ j, list.of_fn $ λ (i : fin (G.f j).length), (G.f j).nth_le i.val i.is_lt - (2 * j.val + 2) + abs (2 * j.val + 2 - hn (G.remove j i) (by rw [game.size2_remove, hG, nat.add_sub_cancel])) --last bracket proves size2 (remove G j i) = n )) begin /- we need to prove list.bind [0, 1] (λ (j : fin 2), of_fn (λ (i : fin (length (G.f j))), nth_le (G.f j) (i.val) _ - (2 * ↑(j.val) + 2) + abs (2 * ↑(j.val) + 2 - hn (remove G j i) _))) ≠ nil for list.min (as it is not defined for empty lists-/ intro h, -- a ≠ b is the same as (a = b) → false so h is ... = nil /- we simplify h to sum [length (G.f 0), length (G.f 1)] = 0-/ rw [←list.length_eq_zero, list.length_bind] at h, dsimp at h, rw [list.length_of_fn, list.length_of_fn] at h, change size G = 0 at h, -- now this cannot be true as size G = n + 1 by one of our assumptions rw [size_eq_size2, hG] at h, revert h, exact dec_trivial, end /- Note (2 * j.val + 2) is 2 if j corresponds to chains (j.val = 0) and 4 if j corresponds to loops (j.val = 1) The value was defined recursively on the number of components using our recursor from game.basic-/ /--equivalence to a simpler definition given the size of the game-/ theorem game.value_def (G : game 2) (n : ℕ) (hG : G.size2 = nat.succ n): game.value G = list.min (list.bind [(0 : fin 2), (1 : fin 2)] (λ j, list.of_fn $ λ (i : fin (G.f j).length), (G.f j).nth_le i.val i.is_lt - (2 * j.val + 2) + abs (2 * j.val + 2 - game.value (G.remove j i)))) begin -- for list.min. see proof above intro h, rw [←list.length_eq_zero, list.length_bind] at h, dsimp at h, rw [list.length_of_fn, list.length_of_fn] at h, change size G = 0 at h, rw [size_eq_size2, hG] at h, revert h, exact dec_trivial, end := begin unfold game.value, unfold game.rec_on_size2, unfold game.rec_on_size2', simp only [hG], congr', --can prove the lists are the same which then implies the minimums are /-reduce outrageously long goal-/ ext i n0 n1, --apply extensionality lemmas congr', ext j, --apply extensionality lemmas congr', /- goal is n = size2 (remove G i j), which implies the previous one (goal was of form g(n) = g (size2 (remove G i j)) for some function g)-/ rw game.size2_remove, -- see game.basic rw hG, exact (nat.add_sub_cancel n 1).symm, -- as nat.succ n is defined as n + 1, +1 and -1 cancel end
875494d439b22fe15700854524c9317924d61d7a
3268ab3a126f0fef71459fbf170dc38efe5d0506
/algebra/free_abelian_group.hlean
24328ed082be79566d180ff80f1493b8838fb853
[ "Apache-2.0" ]
permissive
soraismus/Spectral
f043fed1a4e02ddfeba531769b2980eb817471f4
32512bf47db3a1b932856e7ed7c7830b1fc07ef0
refs/heads/master
1,585,628,705,579
1,538,609,948,000
1,538,609,974,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,788
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Egbert Rijke Constructions with groups -/ import algebra.group_theory hit.set_quotient types.list types.sum .free_group open eq algebra is_trunc set_quotient relation sigma sigma.ops prod sum list trunc function equiv trunc_index group namespace group variables {G G' : Group} {g g' h h' k : G} {A B : AbGroup} variables (X : Type) {Y : Type} [is_set X] [is_set Y] {l l' : list (X ⊎ X)} /- Free Abelian Group of a set -/ namespace free_ab_group inductive fcg_rel : list (X ⊎ X) → list (X ⊎ X) → Type := | rrefl : Πl, fcg_rel l l | cancel1 : Πx, fcg_rel [inl x, inr x] [] | cancel2 : Πx, fcg_rel [inr x, inl x] [] | rflip : Πx y, fcg_rel [x, y] [y, x] | resp_append : Π{l₁ l₂ l₃ l₄}, fcg_rel l₁ l₂ → fcg_rel l₃ l₄ → fcg_rel (l₁ ++ l₃) (l₂ ++ l₄) | rtrans : Π{l₁ l₂ l₃}, fcg_rel l₁ l₂ → fcg_rel l₂ l₃ → fcg_rel l₁ l₃ open fcg_rel local abbreviation R [reducible] := fcg_rel attribute fcg_rel.rrefl [refl] attribute fcg_rel.rtrans [trans] definition fcg_carrier [reducible] : Type := set_quotient (λx y, ∥R X x y∥) local abbreviation FG := fcg_carrier definition is_reflexive_R : is_reflexive (λx y, ∥R X x y∥) := begin constructor, intro s, apply tr, unfold R end local attribute is_reflexive_R [instance] variable {X} theorem rel_respect_flip (r : R X l l') : R X (map sum.flip l) (map sum.flip l') := begin induction r with l x x x y l₁ l₂ l₃ l₄ r₁ r₂ IH₁ IH₂ l₁ l₂ l₃ r₁ r₂ IH₁ IH₂, { reflexivity}, { repeat esimp [map], exact cancel2 x}, { repeat esimp [map], exact cancel1 x}, { repeat esimp [map], apply fcg_rel.rflip}, { rewrite [+map_append], exact resp_append IH₁ IH₂}, { exact rtrans IH₁ IH₂} end theorem rel_respect_reverse (r : R X l l') : R X (reverse l) (reverse l') := begin induction r with l x x x y l₁ l₂ l₃ l₄ r₁ r₂ IH₁ IH₂ l₁ l₂ l₃ r₁ r₂ IH₁ IH₂, { reflexivity}, { repeat esimp [map], exact cancel2 x}, { repeat esimp [map], exact cancel1 x}, { repeat esimp [map], apply fcg_rel.rflip}, { rewrite [+reverse_append], exact resp_append IH₂ IH₁}, { exact rtrans IH₁ IH₂} end theorem rel_cons_concat (l s) : R X (s :: l) (concat s l) := begin induction l with t l IH, { reflexivity}, { rewrite [concat_cons], transitivity (t :: s :: l), { exact resp_append !rflip !rrefl}, { exact resp_append (rrefl [t]) IH}} end definition fcg_one [constructor] : FG X := class_of [] definition fcg_inv [unfold 3] : FG X → FG X := quotient_unary_map (reverse ∘ map sum.flip) (λl l', trunc_functor -1 (rel_respect_reverse ∘ rel_respect_flip)) definition fcg_mul [unfold 3 4] : FG X → FG X → FG X := quotient_binary_map append (λl l', trunc.elim (λr m m', trunc.elim (λs, tr (resp_append r s)))) section local notation 1 := fcg_one local postfix ⁻¹ := fcg_inv local infix * := fcg_mul theorem fcg_mul_assoc (g₁ g₂ g₃ : FG X) : g₁ * g₂ * g₃ = g₁ * (g₂ * g₃) := begin refine set_quotient.rec_prop _ g₁, refine set_quotient.rec_prop _ g₂, refine set_quotient.rec_prop _ g₃, clear g₁ g₂ g₃, intro g₁ g₂ g₃, exact ap class_of !append.assoc end theorem fcg_one_mul (g : FG X) : 1 * g = g := begin refine set_quotient.rec_prop _ g, clear g, intro g, exact ap class_of !append_nil_left end theorem fcg_mul_one (g : FG X) : g * 1 = g := begin refine set_quotient.rec_prop _ g, clear g, intro g, exact ap class_of !append_nil_right end theorem fcg_mul_left_inv (g : FG X) : g⁻¹ * g = 1 := begin refine set_quotient.rec_prop _ g, clear g, intro g, apply eq_of_rel, apply tr, induction g with s l IH, { reflexivity}, { rewrite [▸*, map_cons, reverse_cons, concat_append], refine rtrans _ IH, apply resp_append, reflexivity, change R X ([flip s, s] ++ l) ([] ++ l), apply resp_append, induction s, apply cancel2, apply cancel1, reflexivity} end theorem fcg_mul_comm (g h : FG X) : g * h = h * g := begin refine set_quotient.rec_prop _ g, clear g, intro g, refine set_quotient.rec_prop _ h, clear h, intro h, apply eq_of_rel, apply tr, revert h, induction g with s l IH: intro h, { rewrite [append_nil_left, append_nil_right]}, { rewrite [append_cons,-concat_append], transitivity concat s (l ++ h), apply rel_cons_concat, rewrite [-append_concat], apply IH} end end end free_ab_group open free_ab_group variables (X) definition group_free_ab_group [constructor] : ab_group (fcg_carrier X) := ab_group.mk _ fcg_mul fcg_mul_assoc fcg_one fcg_one_mul fcg_mul_one fcg_inv fcg_mul_left_inv fcg_mul_comm definition free_ab_group [constructor] : AbGroup := AbGroup.mk _ (group_free_ab_group X) /- The universal property of the free commutative group -/ variables {X A} definition free_ab_group_inclusion [constructor] (x : X) : free_ab_group X := class_of [inl x] theorem fgh_helper_respect_fcg_rel (f : X → A) (r : fcg_rel X l l') : Π(g : A), foldl (fgh_helper f) g l = foldl (fgh_helper f) g l' := begin induction r with l x x x y l₁ l₂ l₃ l₄ r₁ r₂ IH₁ IH₂ l₁ l₂ l₃ r₁ r₂ IH₁ IH₂: intro g, { reflexivity}, { unfold [foldl], apply mul_inv_cancel_right}, { unfold [foldl], apply inv_mul_cancel_right}, { unfold [foldl, fgh_helper], apply mul.right_comm}, { rewrite [+foldl_append, IH₁, IH₂]}, { exact !IH₁ ⬝ !IH₂} end definition free_ab_group_elim [constructor] (f : X → A) : free_ab_group X →g A := begin fapply homomorphism.mk, { intro g, refine set_quotient.elim _ _ g, { intro l, exact foldl (fgh_helper f) 1 l}, { intro l l' r, esimp at *, refine trunc.rec _ r, clear r, intro r, exact fgh_helper_respect_fcg_rel f r 1}}, { refine set_quotient.rec_prop _, intro l, refine set_quotient.rec_prop _, intro l', esimp, refine !foldl_append ⬝ _, esimp, apply fgh_helper_mul} end definition fn_of_free_ab_group_elim [unfold_full] (φ : free_ab_group X →g A) : X → A := φ ∘ free_ab_group_inclusion definition free_ab_group_elim_unique [constructor] (f : X → A) (k : free_ab_group X →g A) (H : k ∘ free_ab_group_inclusion ~ f) : k ~ free_ab_group_elim f := begin refine set_quotient.rec_prop _, intro l, esimp, induction l with s l IH, { esimp [foldl], exact to_respect_one k}, { rewrite [foldl_cons, fgh_helper_mul], refine to_respect_mul k (class_of [s]) (class_of l) ⬝ _, rewrite [IH], apply ap (λx, x * _), induction s: rewrite [▸*, one_mul, -H a], apply to_respect_inv } end variables (X A) definition free_ab_group_elim_equiv_fn [constructor] : (free_ab_group X →g A) ≃ (X → A) := begin fapply equiv.MK, { exact fn_of_free_ab_group_elim}, { exact free_ab_group_elim}, { intro f, apply eq_of_homotopy, intro x, esimp, unfold [foldl], apply one_mul}, { intro k, symmetry, apply homomorphism_eq, apply free_ab_group_elim_unique, reflexivity } end definition free_ab_group_functor (f : X → Y) : free_ab_group X →g free_ab_group Y := free_ab_group_elim (free_ab_group_inclusion ∘ f) -- set_option pp.all true -- definition free_ab_group.rec {P : free_ab_group X → Type} [H : Πg, is_prop (P g)] -- (h₁ : Πx, P (free_ab_group_inclusion x)) -- (h₂ : P 0) -- (h₃ : Πg h, P g → P h → P (g * h)) -- (h₄ : Πg, P g → P g⁻¹) : -- Πg, P g := -- begin -- refine @set_quotient.rec_prop _ _ _ H _, -- refine @set_quotient.rec_prop _ _ _ (λx, !H) _, -- esimp, intro l, induction l with s l ih, -- exact h₂, -- induction s with v v, -- induction v with i y, -- exact h₃ _ _ (h₁ i y) ih, -- induction v with i y, -- refine h₃ (gqg_map _ _ (class_of [inr ⟨i, y⟩])) _ _ ih, -- refine transport P _ (h₁ i y⁻¹), -- refine _ ⬝ !mul_one, -- refine _ ⬝ ap (mul _) (to_respect_one (dirsum_incl i)), -- apply gqg_eq_of_rel', -- apply tr, esimp, -- refine transport dirsum_rel _ (dirsum_rel.rmk i y⁻¹ y), -- rewrite [mul.left_inv, mul.assoc], -- apply ap (mul _), -- refine _ ⬝ (mul_inv (class_of [inr ⟨i, y⟩]) (ι ⟨i, 1⟩))⁻¹ᵖ, -- refine ap011 mul _ _, -- end end group
75f87ce968cf9067050e8f98d25a0eea6b4c9a4b
07c76fbd96ea1786cc6392fa834be62643cea420
/hott/types/int/default.hlean
dd18be80ac75269025581b4f63da459371cfed1e
[ "Apache-2.0" ]
permissive
fpvandoorn/lean2
5a430a153b570bf70dc8526d06f18fc000a60ad9
0889cf65b7b3cebfb8831b8731d89c2453dd1e9f
refs/heads/master
1,592,036,508,364
1,545,093,958,000
1,545,093,958,000
75,436,854
0
0
null
1,480,718,780,000
1,480,718,780,000
null
UTF-8
Lean
false
false
186
hlean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import .basic .hott .order
d9e90441b53f1b844fbb0e24c89ea0f4819a6b69
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/topology/discrete_quotient.lean
241f099157c138f9a58819c2d49f58f521b8ac31
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,818
lean
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Calle Sönne, Adam Topaz -/ import topology.separation import topology.subset_properties import topology.locally_constant.basic /-! # Discrete quotients of a topological space. This file defines the type of discrete quotients of a topological space, denoted `discrete_quotient X`. To avoid quantifying over types, we model such quotients as setoids whose equivalence classes are clopen. ## Definitions 1. `discrete_quotient X` is the type of discrete quotients of `X`. It is endowed with a coercion to `Type`, which is defined as the quotient associated to the setoid in question, and each such quotient is endowed with the discrete topology. 2. Given `S : discrete_quotient X`, the projection `X → S` is denoted `S.proj`. 3. When `X` is compact and `S : discrete_quotient X`, the space `S` is endowed with a `fintype` instance. ## Order structure The type `discrete_quotient X` is endowed with an instance of a `semilattice_inf_top`. The partial ordering `A ≤ B` mathematically means that `B.proj` factors through `A.proj`. The top element `⊤` is the trivial quotient, meaning that every element of `X` is collapsed to a point. Given `h : A ≤ B`, the map `A → B` is `discrete_quotient.of_le h`. ## Theorems The two main results proved in this file are: 1. `discrete_quotient.eq_of_proj_eq` which states that when `X` is compact, t2 and totally disconnected, any two elements of `X` agree if their projections in `Q` agree for all `Q : discrete_quotient X`. 2. `discrete_quotient.exists_of_compat` which states that when `X` is compact, then any system of elements of `Q` as `Q : discrete_quotient X` varies, which is compatible with respect to `discrete_quotient.of_le`, must arise from some element of `X`. ## Remarks The constructions in this file will be used to show that any profinite space is a limit of finite discrete spaces. -/ variables (X : Type*) [topological_space X] /-- The type of discrete quotients of a topological space. -/ @[ext] structure discrete_quotient := (rel : X → X → Prop) (equiv : equivalence rel) (clopen : ∀ x, is_clopen (set_of (rel x))) namespace discrete_quotient variables {X} (S : discrete_quotient X) /-- Construct a discrete quotient from a clopen set. -/ def of_clopen {A : set X} (h : is_clopen A) : discrete_quotient X := { rel := λ x y, x ∈ A ∧ y ∈ A ∨ x ∉ A ∧ y ∉ A, equiv := ⟨by tauto!, by tauto!, by tauto!⟩, clopen := begin intros x, by_cases hx : x ∈ A, { apply is_clopen_union, { convert h, ext, exact ⟨λ i, i.2, λ i, ⟨hx,i⟩⟩ }, { convert is_clopen_empty, tidy } }, { apply is_clopen_union, { convert is_clopen_empty, tidy }, { convert is_clopen_compl h, ext, exact ⟨λ i, i.2, λ i, ⟨hx, i⟩⟩ } }, end } lemma refl : ∀ x : X, S.rel x x := S.equiv.1 lemma symm : ∀ x y : X, S.rel x y → S.rel y x := S.equiv.2.1 lemma trans : ∀ x y z : X, S.rel x y → S.rel y z → S.rel x z := S.equiv.2.2 /-- The setoid whose quotient yields the discrete quotient. -/ def setoid : setoid X := ⟨S.rel, S.equiv⟩ instance : has_coe_to_sort (discrete_quotient X) := ⟨Type*, λ S, quotient S.setoid⟩ instance : topological_space S := ⊥ /-- The projection from `X` to the given discrete quotient. -/ def proj : X → S := quotient.mk' lemma proj_surjective : function.surjective S.proj := quotient.surjective_quotient_mk' lemma fiber_eq (x : X) : S.proj ⁻¹' {S.proj x} = set_of (S.rel x) := begin ext1 y, simp only [set.mem_preimage, set.mem_singleton_iff, quotient.eq', discrete_quotient.proj.equations._eqn_1, set.mem_set_of_eq], exact ⟨λ h, S.symm _ _ h, λ h, S.symm _ _ h⟩, end lemma proj_is_locally_constant : is_locally_constant S.proj := begin rw (is_locally_constant.tfae S.proj).out 0 3, intros x, rcases S.proj_surjective x with ⟨x,rfl⟩, simp [fiber_eq, (S.clopen x).1], end lemma proj_continuous : continuous S.proj := is_locally_constant.continuous $ proj_is_locally_constant _ lemma fiber_closed (A : set S) : is_closed (S.proj ⁻¹' A) := is_closed.preimage S.proj_continuous ⟨trivial⟩ lemma fiber_open (A : set S) : is_open (S.proj ⁻¹' A) := is_open.preimage S.proj_continuous trivial lemma fiber_clopen (A : set S) : is_clopen (S.proj ⁻¹' A) := ⟨fiber_open _ _, fiber_closed _ _⟩ /-- Comap a discrete quotient along a continuous map. -/ def comap {Y : Type*} [topological_space Y] {f : Y → X} (cont : continuous f) : discrete_quotient Y := { rel := λ a b, S.rel (f a) (f b), equiv := ⟨λ a, S.refl _, λ a b h, S.symm _ _ h, λ a b c h1 h2, S.trans _ _ _ h1 h2⟩, clopen := λ y, ⟨is_open.preimage cont (S.clopen _).1, is_closed.preimage cont (S.clopen _).2⟩ } instance : semilattice_inf_top (discrete_quotient X) := { top := ⟨λ a b, true, ⟨by tauto, by tauto, by tauto⟩, λ _, is_clopen_univ⟩, inf := λ A B, { rel := λ x y, A.rel x y ∧ B.rel x y, equiv := ⟨λ a, ⟨A.refl _,B.refl _⟩, λ a b h, ⟨A.symm _ _ h.1, B.symm _ _ h.2⟩, λ a b c h1 h2, ⟨A.trans _ _ _ h1.1 h2.1, B.trans _ _ _ h1.2 h2.2⟩⟩, clopen := λ x, is_clopen_inter (A.clopen _) (B.clopen _) }, le := λ A B, ∀ x y : X, A.rel x y → B.rel x y, le_refl := λ a, by tauto, le_trans := λ a b c h1 h2, by tauto, le_antisymm := λ a b h1 h2, by { ext, tauto }, inf_le_left := λ a b, by tauto, inf_le_right := λ a b, by tauto, le_inf := λ a b c h1 h2, by tauto, le_top := λ a, by tauto } instance : inhabited (discrete_quotient X) := ⟨⊤⟩ /-- The map induced by a refinement of a discrete quotient. -/ def of_le {A B : discrete_quotient X} (h : A ≤ B) : A → B := λ a, quotient.lift_on' a (λ x, B.proj x) (λ a b i, quotient.sound' (h _ _ i)) lemma of_le_continuous {A B : discrete_quotient X} (h : A ≤ B) : continuous (of_le h) := continuous_of_discrete_topology @[simp] lemma of_le_proj {A B : discrete_quotient X} (h : A ≤ B) : of_le h ∘ A.proj = B.proj := by {ext, exact quotient.sound' (B.refl _)} @[simp] lemma of_le_proj_apply {A B : discrete_quotient X} (h : A ≤ B) (x : X) : of_le h (A.proj x) = B.proj x := by {change (of_le h ∘ A.proj) x = _, simp} lemma eq_of_proj_eq [t2_space X] [compact_space X] [disc : totally_disconnected_space X] {x y : X} : (∀ Q : discrete_quotient X, Q.proj x = Q.proj y) → x = y := begin intro h, change x ∈ ({y} : set X), rw totally_disconnected_space_iff_connected_component_singleton at disc, rw [← disc y, connected_component_eq_Inter_clopen], rintros U ⟨⟨U, hU1, hU2⟩, rfl⟩, replace h : _ ∨ _ := quotient.exact' (h (of_clopen hU1)), tauto, end lemma fiber_le_of_le {A B : discrete_quotient X} (h : A ≤ B) (a : A) : A.proj ⁻¹' {a} ≤ B.proj ⁻¹' {of_le h a} := begin induction a, erw [fiber_eq, fiber_eq], tidy, end lemma exists_of_compat [compact_space X] (Qs : Π (Q : discrete_quotient X), Q) (compat : ∀ (A B : discrete_quotient X) (h : A ≤ B), of_le h (Qs _) = Qs _) : ∃ x : X, ∀ Q : discrete_quotient X, Q.proj x = Qs _ := begin obtain ⟨x,hx⟩ := is_compact.nonempty_Inter_of_directed_nonempty_compact_closed (λ (Q : discrete_quotient X), Q.proj ⁻¹' {Qs _}) (λ A B, _) (λ i, _) (λ i, is_closed.compact (fiber_closed _ _)) (λ i, fiber_closed _ _), { refine ⟨x, λ Q, _⟩, specialize hx _ ⟨Q,rfl⟩, dsimp at hx, rcases proj_surjective _ (Qs Q) with ⟨y,hy⟩, rw ← hy at *, rw fiber_eq at hx, exact quotient.sound' (Q.symm y x hx) }, { refine ⟨A ⊓ B, λ a ha, _, λ a ha, _⟩, { dsimp only, erw ← compat (A ⊓ B) A inf_le_left, exact fiber_le_of_le _ _ ha }, { dsimp only, erw ← compat (A ⊓ B) B inf_le_right, exact fiber_le_of_le _ _ ha } }, { obtain ⟨x,hx⟩ := i.proj_surjective (Qs i), refine ⟨x,_⟩, dsimp only, rw [← hx, fiber_eq], apply i.refl }, end noncomputable instance [compact_space X] : fintype S := begin have cond : is_compact (⊤ : set X) := compact_univ, rw compact_iff_finite_subcover at cond, have h := @cond S (λ s, S.proj ⁻¹' {s}) (λ s, fiber_open _ _) (λ x hx, ⟨S.proj ⁻¹' {S.proj x}, ⟨S.proj x, rfl⟩, rfl⟩), let T := classical.some h, have hT := classical.some_spec h, refine ⟨T,λ s, _⟩, rcases S.proj_surjective s with ⟨x,rfl⟩, rcases hT (by tauto : x ∈ ⊤) with ⟨j, ⟨j,rfl⟩, h1, ⟨hj, rfl⟩, h2⟩, dsimp only at h2, suffices : S.proj x = j, by rwa this, rcases j with ⟨j⟩, apply quotient.sound', erw fiber_eq at h2, exact S.symm _ _ h2 end end discrete_quotient
0a6a18908049320f2bb8d17e5e080fbde1033298
ec62863c729b7eedee77b86d974f2c529fa79d25
/15/b.lean
3ea5f1872970ec781e35fa70b789d12926771b2f
[]
no_license
rwbarton/advent-of-lean-4
2ac9b17ba708f66051e3d8cd694b0249bc433b65
417c7e2718253ba7148c0279fcb251b6fc291477
refs/heads/main
1,675,917,092,057
1,609,864,581,000
1,609,864,581,000
317,700,289
24
0
null
null
null
null
UTF-8
Lean
false
false
594
lean
import Std.Data.HashMap def solve (inlst : List Nat) : Int := do let mut t : Std.HashMap Nat Nat := Std.HashMap.empty let mut last : Nat := 0 let mut nextj : Option Nat := none for ⟨i, n⟩ in inlst.enum do nextj := t.find? n t := t.insert n i last := n for j in [inlst.length:30000000] do last := match nextj with | none => 0 | some i => j-i-1 nextj := t.find? last t := t.insert last j last def main : IO Unit := do let lines ← IO.FS.lines "a.in" let vals := ((lines.get! 0).splitOn ",").map String.toNat! IO.print s!"{solve vals}"
f835fc6a8dad4fa61171c4e1f98cf4b109e5f3f7
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/library/tools/tactic.lean
e040dda4078c7ba4c6b1230a432c59af8b8e4e92
[ "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,921
lean
---------------------------------------------------------------------------------------------------- -- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Leonardo de Moura ---------------------------------------------------------------------------------------------------- import data.string.decl data.num.decl -- This is just a trick to embed the 'tactic language' as a -- Lean expression. We should view 'tactic' as automation -- that when execute produces a term. -- tactic.builtin is just a "dummy" for creating the -- definitions that are actually implemented in C++ inductive tactic : Type := builtin : tactic namespace tactic -- Remark the following names are not arbitrary, the tactic module -- uses them when converting Lean expressions into actual tactic objects. -- The bultin 'by' construct triggers the process of converting a -- a term of type 'tactic' into a tactic that sythesizes a term opaque definition and_then (t1 t2 : tactic) : tactic := builtin opaque definition or_else (t1 t2 : tactic) : tactic := builtin opaque definition append (t1 t2 : tactic) : tactic := builtin opaque definition interleave (t1 t2 : tactic) : tactic := builtin opaque definition par (t1 t2 : tactic) : tactic := builtin opaque definition fixpoint (f : tactic → tactic) : tactic := builtin opaque definition repeat (t : tactic) : tactic := builtin opaque definition at_most (t : tactic) (k : num) : tactic := builtin opaque definition discard (t : tactic) (k : num) : tactic := builtin opaque definition focus_at (t : tactic) (i : num) : tactic := builtin opaque definition try_for (t : tactic) (ms : num) : tactic := builtin opaque definition now : tactic := builtin opaque definition assumption : tactic := builtin opaque definition eassumption : tactic := builtin opaque definition state : tactic := builtin opaque definition fail : tactic := builtin opaque definition id : tactic := builtin opaque definition beta : tactic := builtin opaque definition info : tactic := builtin opaque definition whnf : tactic := builtin opaque definition rotate_left (k : num) := builtin opaque definition rotate_right (k : num) := builtin definition rotate (k : num) := rotate_left k -- This is just a trick to embed expressions into tactics. -- The nested expressions are "raw". They tactic should -- elaborate them when it is executed. inductive expr : Type := builtin : expr opaque definition apply (e : expr) : tactic := builtin opaque definition rapply (e : expr) : tactic := builtin opaque definition rename (a b : expr) : tactic := builtin opaque definition intro (e : expr) : tactic := builtin opaque definition generalize (e : expr) : tactic := builtin inductive expr_list : Type := nil : expr_list, cons : expr → expr_list → expr_list opaque definition intro_list (es : expr_list) : tactic := builtin notation `intros` := intro_list expr_list.nil notation `intros` `(` l:(foldr `,` (h t, expr_list.cons h t) expr_list.nil) `)` := intro_list l opaque definition generalize_list (es : expr_list) : tactic := builtin notation `generalizes` `(` l:(foldr `,` (h t, expr_list.cons h t) expr_list.nil) `)` := generalize_list l opaque definition clear (e : expr) : tactic := builtin opaque definition unfold (e : expr) : tactic := builtin opaque definition exact (e : expr) : tactic := builtin opaque definition trace (s : string) : tactic := builtin infixl `;`:15 := and_then notation `[` h:10 `|`:10 r:(foldl 10 `|` (e r, or_else r e) h) `]` := r definition try (t : tactic) : tactic := [t | id] definition repeat1 (t : tactic) : tactic := t ; repeat t definition focus (t : tactic) : tactic := focus_at t 0 definition determ (t : tactic) : tactic := at_most t 1 end tactic
2b8ee5d1fe9ef3b0141713eff5d2ffcf880c84f0
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/run/derivingRpcEncoding.lean
87171eca6e2f9900996a1d74402149abd4d0b945
[ "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
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
442
lean
import Lean.Server.Rpc.Basic open Lean Server structure FooRef where a : Array Nat deriving RpcEncoding with { withRef := true } structure FooJson where s : String deriving FromJson, ToJson structure Bar where fooRef : WithRpcRef FooRef fooJson : FooJson deriving RpcEncoding structure BarTrans where bar : Bar deriving RpcEncoding structure Baz where arr : Array String -- non-constant field deriving RpcEncoding
676ea37022bcdfbdcb24a734eaae673b01eb12c1
0d4c30038160d9c35586ce4dace36fe26a35023b
/src/measure_theory/bochner_integration.lean
ba96c9bcc399303b4fb6d8aa8127b4ba7ca79f65
[ "Apache-2.0" ]
permissive
b-mehta/mathlib
b0c8ec929ec638447e4262f7071570d23db52e14
ce72cde867feabe5bb908cf9e895acc0e11bf1eb
refs/heads/master
1,599,457,264,781
1,586,969,260,000
1,586,969,260,000
220,672,634
0
0
Apache-2.0
1,583,944,480,000
1,573,317,991,000
Lean
UTF-8
Lean
false
false
55,221
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import measure_theory.simple_func_dense import analysis.normed_space.bounded_linear_maps /-! # Bochner integral The Bochner integral extends the definition of the Lebesgue integral to functions that map from a measure space into a Banach space (complete normed vector space). It is constructed here by extending the integral on simple functions. ## Main definitions The Bochner integral is defined following these steps: 1. Define the integral on simple functions of the type `simple_func α β` (notation : `α →ₛ β`) where `β` is a real normed space. (See `simple_func.bintegral` and section `bintegral` for details. Also see `simple_func.integral` for the integral on simple functions of the type `simple_func α ennreal`.) 2. Use `simple_func α β` to cut out the simple functions from L1 functions, and define integral on these. The type of simple functions in L1 space is written as `α →₁ₛ β`. 3. Show that the embedding of `α →₁ₛ β` into L1 is a dense and uniform one. 4. Show that the integral defined on `α →₁ₛ β` is a continuous linear map. 5. Define the Bochner integral on L1 functions by extending the integral on integrable simple functions `α →₁ₛ β` using `continuous_linear_map.extend`. Define the Bochner integral on functions as the Bochner integral of its equivalence class in L1 space. ## Main statements 1. Basic properties of the Bochner integral on functions of type `α → β`, where `α` is a measure space and `β` is a real normed space. * `integral_zero` : `∫ 0 = 0` * `integral_add` : `∫ f + g = ∫ f + ∫ g` * `integral_neg` : `∫ -f = - ∫ f` * `integral_sub` : `∫ f - g = ∫ f - ∫ g` * `integral_smul` : `∫ r • f = r • ∫ f` * `integral_congr_ae` : `∀ₘ a, f a = g a → ∫ f = ∫ g` * `norm_integral_le_integral_norm` : `∥∫ f∥ ≤ ∫ ∥f∥` 2. Basic properties of the Bochner integral on functions of type `α → ℝ`, where `α` is a measure space. * `integral_nonneg_of_ae` : `∀ₘ a, 0 ≤ f a → 0 ≤ ∫ f` * `integral_nonpos_of_nonpos_ae` : `∀ₘ a, f a ≤ 0 → ∫ f ≤ 0` * `integral_le_integral_of_le_ae` : `∀ₘ a, f a ≤ g a → ∫ f ≤ ∫ g` 3. Propositions connecting the Bochner integral with the integral on `ennreal`-valued functions, which is called `lintegral` and has the notation `∫⁻`. * `integral_eq_lintegral_max_sub_lintegral_min` : `∫ f = ∫⁻ f⁺ - ∫⁻ f⁻`, where `f⁺` is the positive part of `f` and `f⁻` is the negative part of `f`. * `integral_eq_lintegral_of_nonneg_ae` : `∀ₘ a, 0 ≤ f a → ∫ f = ∫⁻ f` 4. `tendsto_integral_of_dominated_convergence` : the Lebesgue dominated convergence theorem ## Notes Some tips on how to prove a proposition if the API for the Bochner integral is not enough so that you need to unfold the definition of the Bochner integral and go back to simple functions. See `integral_eq_lintegral_max_sub_lintegral_min` for a complicated example, which proves that `∫ f = ∫⁻ f⁺ - ∫⁻ f⁻`, with the first integral sign being the Bochner integral of a real-valued function f : α → ℝ, and second and third integral sign being the integral on ennreal-valued functions (called `lintegral`). The proof of `integral_eq_lintegral_max_sub_lintegral_min` is scattered in sections with the name `pos_part`. Here are the usual steps of proving that a property `p`, say `∫ f = ∫⁻ f⁺ - ∫⁻ f⁻`, holds for all functions : 1. First go to the `L¹` space. For example, if you see `ennreal.to_real (∫⁻ a, ennreal.of_real $ ∥f a∥)`, that is the norm of `f` in `L¹` space. Rewrite using `l1.norm_of_fun_eq_lintegral_norm`. 2. Show that the set `{f ∈ L¹ | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻}` is closed in `L¹` using `is_closed_eq`. 3. Show that the property holds for all simple functions `s` in `L¹` space. Typically, you need to convert various notions to their `simple_func` counterpart, using lemmas like `l1.integral_coe_eq_integral`. 4. Since simple functions are dense in `L¹`, ``` univ = closure {s simple} = closure {s simple | ∫ s = ∫⁻ s⁺ - ∫⁻ s⁻} : the property holds for all simple functions ⊆ closure {f | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻} = {f | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻} : closure of a closed set is itself ``` Use `is_closed_property` or `dense_range.induction_on` for this argument. ## Notations * `α →ₛ β` : simple functions (defined in `measure_theory/integration`) * `α →₁ β` : functions in L1 space, i.e., equivalence classes of integrable functions (defined in `measure_theory/l1_space`) * `α →₁ₛ β` : simple functions in L1 space, i.e., equivalence classes of integrable simple functions Note : `ₛ` is typed using `\_s`. Sometimes it shows as a box if font is missing. ## Tags Bochner integral, simple function, function space, Lebesgue dominated convergence theorem -/ noncomputable theory open_locale classical topological_space set_option class.instance_max_depth 100 -- Typeclass inference has difficulty finding `has_scalar ℝ β` where `β` is a `normed_space` on `ℝ` local attribute [instance, priority 10000] mul_action.to_has_scalar distrib_mul_action.to_mul_action add_comm_group.to_add_comm_monoid normed_group.to_add_comm_group normed_space.to_module module.to_semimodule namespace measure_theory universes u v w variables {α : Type u} [measurable_space α] {β : Type v} [decidable_linear_order β] [has_zero β] local infixr ` →ₛ `:25 := simple_func namespace simple_func section pos_part /-- Positive part of a simple function. -/ def pos_part (f : α →ₛ β) : α →ₛ β := f.map (λb, max b 0) /-- Negative part of a simple function. -/ def neg_part [has_neg β] (f : α →ₛ β) : α →ₛ β := pos_part (-f) lemma pos_part_map_norm (f : α →ₛ ℝ) : (pos_part f).map norm = pos_part f := begin ext, rw [map_apply, real.norm_eq_abs, abs_of_nonneg], rw [pos_part, map_apply], exact le_max_right _ _ end lemma neg_part_map_norm (f : α →ₛ ℝ) : (neg_part f).map norm = neg_part f := by { rw neg_part, exact pos_part_map_norm _ } lemma pos_part_sub_neg_part (f : α →ₛ ℝ) : f.pos_part - f.neg_part = f := begin simp only [pos_part, neg_part], ext, exact max_zero_sub_eq_self (f a) end end pos_part end simple_func end measure_theory namespace measure_theory open set filter topological_space ennreal emetric universes u v w variables {α : Type u} [measure_space α] {β : Type v} {γ : Type w} local infixr ` →ₛ `:25 := simple_func namespace simple_func section bintegral /-! ### The Bochner integral of simple functions Define the Bochner integral of simple functions of the type `α →ₛ β` where `β` is a normed group, and prove basic property of this integral. -/ open finset variables [normed_group β] [normed_group γ] lemma integrable_iff_integral_lt_top {f : α →ₛ β} : integrable f ↔ integral (f.map (coe ∘ nnnorm)) < ⊤ := by { rw [integrable, ← lintegral_eq_integral, lintegral_map] } lemma fin_vol_supp_of_integrable {f : α →ₛ β} (hf : integrable f) : f.fin_vol_supp := begin rw [integrable_iff_integral_lt_top] at hf, have hf := fin_vol_supp_of_integral_lt_top hf, refine fin_vol_supp_of_fin_vol_supp_map f hf _, assume b, simp [nnnorm_eq_zero] end lemma integrable_of_fin_vol_supp {f : α →ₛ β} (h : f.fin_vol_supp) : integrable f := by { rw [integrable_iff_integral_lt_top], exact integral_map_coe_lt_top h nnnorm_zero } /-- For simple functions with a `normed_group` as codomain, being integrable is the same as having finite volume support. -/ lemma integrable_iff_fin_vol_supp (f : α →ₛ β) : integrable f ↔ f.fin_vol_supp := iff.intro fin_vol_supp_of_integrable integrable_of_fin_vol_supp lemma integrable_pair {f : α →ₛ β} {g : α →ₛ γ} (hf : integrable f) (hg : integrable g) : integrable (pair f g) := by { rw integrable_iff_fin_vol_supp at *, apply fin_vol_supp_pair; assumption } variables [normed_space ℝ γ] /-- Bochner integral of simple functions whose codomain is a real `normed_space`. The name `simple_func.integral` has been taken in the file `integration.lean`, which calculates the integral of a simple function with type `α → ennreal`. The name `bintegral` stands for Bochner integral. -/ def bintegral [normed_space ℝ β] (f : α →ₛ β) : β := f.range.sum (λ x, (ennreal.to_real (volume (f ⁻¹' {x}))) • x) /-- Calculate the integral of `g ∘ f : α →ₛ γ`, where `f` is an integrable function from `α` to `β` and `g` is a function from `β` to `γ`. We require `g 0 = 0` so that `g ∘ f` is integrable. -/ lemma map_bintegral (f : α →ₛ β) (g : β → γ) (hf : integrable f) (hg : g 0 = 0) : (f.map g).bintegral = f.range.sum (λ x, (ennreal.to_real (volume (f ⁻¹' {x}))) • (g x)) := begin /- Just a complicated calculation with `finset.sum`. Real work is done by `map_preimage_singleton`, `simple_func.volume_bUnion_preimage` and `ennreal.to_real_sum` -/ rw integrable_iff_fin_vol_supp at hf, simp only [bintegral, range_map], refine finset.sum_image' _ (assume b hb, _), rcases mem_range.1 hb with ⟨a, rfl⟩, let s' := f.range.filter (λb, g b = g (f a)), calc (ennreal.to_real (volume ((f.map g) ⁻¹' {g (f a)}))) • (g (f a)) = (ennreal.to_real (volume (⋃b∈s', f ⁻¹' {b}))) • (g (f a)) : by rw map_preimage_singleton ... = (ennreal.to_real (s'.sum (λb, volume (f ⁻¹' {b})))) • (g (f a)) : by rw volume_bUnion_preimage ... = (s'.sum (λb, ennreal.to_real (volume (f ⁻¹' {b})))) • (g (f a)) : begin by_cases h : g (f a) = 0, { rw [h, smul_zero, smul_zero] }, { rw ennreal.to_real_sum, simp only [mem_filter], rintros b ⟨_, hb⟩, have : b ≠ 0, { assume hb', rw [← hb, hb'] at h, contradiction }, apply hf, assumption } end ... = s'.sum (λb, (ennreal.to_real (volume (f ⁻¹' {b}))) • (g (f a))) : finset.sum_smul ... = s'.sum (λb, (ennreal.to_real (volume (f ⁻¹' {b}))) • (g b)) : finset.sum_congr rfl $ by { assume x, simp only [mem_filter], rintro ⟨_, h⟩, rw h } end /-- `simple_func.bintegral` and `simple_func.integral` agree when the integrand has type `α →ₛ ennreal`. But since `ennreal` is not a `normed_space`, we need some form of coercion. See `bintegral_eq_integral'` for a simpler version. -/ lemma bintegral_eq_integral {f : α →ₛ β} {g : β → ennreal} (hf : integrable f) (hg0 : g 0 = 0) (hgt : ∀b, g b < ⊤): (f.map (ennreal.to_real ∘ g)).bintegral = ennreal.to_real (f.map g).integral := begin have hf' : f.fin_vol_supp, { rwa integrable_iff_fin_vol_supp at hf }, rw [map_bintegral f _ hf, map_integral, ennreal.to_real_sum], { refine finset.sum_congr rfl (λb hb, _), rw [smul_eq_mul], rw [to_real_mul_to_real, mul_comm] }, { assume a ha, by_cases a0 : a = 0, { rw [a0, hg0, zero_mul], exact with_top.zero_lt_top }, apply mul_lt_top (hgt a) (hf' _ a0) }, { simp [hg0] } end /-- `simple_func.bintegral` and `lintegral : (α → ennreal) → ennreal` are the same when the integrand has type `α →ₛ ennreal`. But since `ennreal` is not a `normed_space`, we need some form of coercion. See `bintegral_eq_lintegral'` for a simpler version. -/ lemma bintegral_eq_lintegral (f : α →ₛ β) (g : β → ennreal) (hf : integrable f) (hg0 : g 0 = 0) (hgt : ∀b, g b < ⊤): (f.map (ennreal.to_real ∘ g)).bintegral = ennreal.to_real (∫⁻ a, g (f a)) := by { rw [bintegral_eq_integral hf hg0 hgt, ← lintegral_eq_integral], refl } variables [normed_space ℝ β] lemma bintegral_congr {f g : α →ₛ β} (hf : integrable f) (hg : integrable g) (h : ∀ₘ a, f a = g a): bintegral f = bintegral g := show ((pair f g).map prod.fst).bintegral = ((pair f g).map prod.snd).bintegral, from begin have inte := integrable_pair hf hg, rw [map_bintegral (pair f g) _ inte prod.fst_zero, map_bintegral (pair f g) _ inte prod.snd_zero], refine finset.sum_congr rfl (assume p hp, _), rcases mem_range.1 hp with ⟨a, rfl⟩, by_cases eq : f a = g a, { dsimp only [pair_apply], rw eq }, { have : volume ((pair f g) ⁻¹' {(f a, g a)}) = 0, { refine volume_mono_null (assume a' ha', _) h, simp only [set.mem_preimage, mem_singleton_iff, pair_apply, prod.mk.inj_iff] at ha', show f a' ≠ g a', rwa [ha'.1, ha'.2] }, simp only [this, pair_apply, zero_smul, ennreal.zero_to_real] }, end /-- `simple_func.bintegral` and `simple_func.integral` agree when the integrand has type `α →ₛ ennreal`. But since `ennreal` is not a `normed_space`, we need some form of coercion. -/ lemma bintegral_eq_integral' {f : α →ₛ ℝ} (hf : integrable f) (h_pos : ∀ₘ a, 0 ≤ f a) : f.bintegral = ennreal.to_real (f.map ennreal.of_real).integral := begin have : ∀ₘ a, f a = (f.map (ennreal.to_real ∘ ennreal.of_real)) a, { filter_upwards [h_pos], assume a, simp only [mem_set_of_eq, map_apply, function.comp_apply], assume h, exact (ennreal.to_real_of_real h).symm }, rw ← bintegral_eq_integral hf, { refine bintegral_congr hf _ this, exact integrable_of_ae_eq hf this }, { exact ennreal.of_real_zero }, { assume b, rw ennreal.lt_top_iff_ne_top, exact ennreal.of_real_ne_top } end /-- `simple_func.bintegral` and `lintegral : (α → ennreal) → ennreal` agree when the integrand has type `α →ₛ ennreal`. But since `ennreal` is not a `normed_space`, we need some form of coercion. -/ lemma bintegral_eq_lintegral' {f : α →ₛ ℝ} (hf : integrable f) (h_pos : ∀ₘ a, 0 ≤ f a) : f.bintegral = ennreal.to_real (∫⁻ a, (f.map ennreal.of_real a)) := by rw [bintegral_eq_integral' hf h_pos, ← lintegral_eq_integral] lemma bintegral_add {f g : α →ₛ β} (hf : integrable f) (hg : integrable g) : bintegral (f + g) = bintegral f + bintegral g := calc bintegral (f + g) = (pair f g).range.sum (λx, ennreal.to_real (volume ((pair f g) ⁻¹' {x})) • (x.fst + x.snd)) : begin rw [add_eq_map₂, map_bintegral (pair f g)], { exact integrable_pair hf hg }, { simp only [add_zero, prod.fst_zero, prod.snd_zero] } end ... = (pair f g).range.sum (λx, ennreal.to_real (volume ((pair f g) ⁻¹' {x})) • x.fst + ennreal.to_real (volume ((pair f g) ⁻¹' {x})) • x.snd) : finset.sum_congr rfl $ assume a ha, smul_add _ _ _ ... = (simple_func.range (pair f g)).sum (λ (x : β × β), ennreal.to_real (volume ((pair f g) ⁻¹' {x})) • x.fst) + (simple_func.range (pair f g)).sum (λ (x : β × β), ennreal.to_real (volume ((pair f g) ⁻¹' {x})) • x.snd) : by rw finset.sum_add_distrib ... = ((pair f g).map prod.fst).bintegral + ((pair f g).map prod.snd).bintegral : begin rw [map_bintegral (pair f g), map_bintegral (pair f g)], { exact integrable_pair hf hg }, { refl }, { exact integrable_pair hf hg }, { refl } end ... = bintegral f + bintegral g : rfl lemma bintegral_neg {f : α →ₛ β} (hf : integrable f) : bintegral (-f) = - bintegral f := calc bintegral (-f) = bintegral (f.map (has_neg.neg)) : rfl ... = - bintegral f : begin rw [map_bintegral f _ hf neg_zero, bintegral, ← sum_neg_distrib], refine finset.sum_congr rfl (λx h, smul_neg _ _), end lemma bintegral_sub {f g : α →ₛ β} (hf : integrable f) (hg : integrable g) : bintegral (f - g) = bintegral f - bintegral g := begin have : f - g = f + (-g) := rfl, rw [this, bintegral_add hf _, bintegral_neg hg], { refl }, exact hg.neg end lemma bintegral_smul (r : ℝ) {f : α →ₛ β} (hf : integrable f) : bintegral (r • f) = r • bintegral f := calc bintegral (r • f) = f.range.sum (λx, ennreal.to_real (volume (f ⁻¹' {x})) • r • x) : by rw [smul_eq_map r f, map_bintegral f _ hf (smul_zero _)] ... = f.range.sum (λ (x : β), ((ennreal.to_real (volume (f ⁻¹' {x}))) * r) • x) : finset.sum_congr rfl $ λb hb, by apply smul_smul ... = r • bintegral f : begin rw [bintegral, smul_sum], refine finset.sum_congr rfl (λb hb, _), rw [smul_smul, mul_comm] end lemma norm_bintegral_le_bintegral_norm (f : α →ₛ β) (hf : integrable f) : ∥f.bintegral∥ ≤ (f.map norm).bintegral := begin rw map_bintegral f norm hf norm_zero, rw bintegral, calc ∥f.range.sum (λx, ennreal.to_real (volume (f ⁻¹' {x})) • x)∥ ≤ f.range.sum (λx, ∥ennreal.to_real (volume (f ⁻¹' {x})) • x∥) : norm_sum_le _ _ ... = f.range.sum (λx, ennreal.to_real (volume (f ⁻¹' {x})) • ∥x∥) : begin refine finset.sum_congr rfl (λb hb, _), rw [norm_smul, smul_eq_mul, real.norm_eq_abs, abs_of_nonneg to_real_nonneg] end end end bintegral end simple_func namespace l1 open ae_eq_fun variables [normed_group β] [second_countable_topology β] [measurable_space β] [borel_space β] [normed_group γ] [second_countable_topology γ] [measurable_space γ] [borel_space γ] variables (α β) /-- `l1.simple_func` is a subspace of L1 consisting of equivalence classes of an integrable simple function. -/ def simple_func : Type (max u v) := { f : α →₁ β // ∃ (s : α →ₛ β), integrable s ∧ ae_eq_fun.mk s s.measurable = f} -- TODO: it seems that `ae_eq_fun.mk s s.measurable = f` implies `integrable s` variables {α β} infixr ` →₁ₛ `:25 := measure_theory.l1.simple_func namespace simple_func section instances /-! Simple functions in L1 space form a `normed_space`. -/ instance : has_coe (α →₁ₛ β) (α →₁ β) := ⟨subtype.val⟩ protected lemma eq {f g : α →₁ₛ β} : (f : α →₁ β) = (g : α →₁ β) → f = g := subtype.eq protected lemma eq' {f g : α →₁ₛ β} : (f : α →ₘ β) = (g : α →ₘ β) → f = g := subtype.eq ∘ subtype.eq @[elim_cast] protected lemma eq_iff {f g : α →₁ₛ β} : (f : α →₁ β) = (g : α →₁ β) ↔ f = g := iff.intro (subtype.eq) (congr_arg coe) @[elim_cast] protected lemma eq_iff' {f g : α →₁ₛ β} : (f : α →ₘ β) = (g : α →ₘ β) ↔ f = g := iff.intro (simple_func.eq') (congr_arg _) /-- L1 simple functions forms a `emetric_space`, with the emetric being inherited from L1 space, i.e., `edist f g = ∫⁻ a, edist (f a) (g a)`. Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner integral. -/ protected def emetric_space : emetric_space (α →₁ₛ β) := subtype.emetric_space /-- L1 simple functions forms a `metric_space`, with the metric being inherited from L1 space, i.e., `dist f g = ennreal.to_real (∫⁻ a, edist (f a) (g a)`). Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner integral. -/ protected def metric_space : metric_space (α →₁ₛ β) := subtype.metric_space local attribute [instance] protected lemma is_add_subgroup : is_add_subgroup (λf:α →₁ β, ∃ (s : α →ₛ β), integrable s ∧ ae_eq_fun.mk s s.measurable = f) := { zero_mem := ⟨0, integrable_zero _ _, rfl⟩, add_mem := begin rintros f g ⟨s, hsi, hs⟩ ⟨t, hti, ht⟩, use s + t, split, { exact hsi.add s.measurable t.measurable hti }, { rw [coe_add, ← hs, ← ht], refl } end, neg_mem := begin rintros f ⟨s, hsi, hs⟩, use -s, split, { exact hsi.neg }, { rw [coe_neg, ← hs], refl } end } /-- Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner integral. -/ protected def add_comm_group : add_comm_group (α →₁ₛ β) := subtype.add_comm_group local attribute [instance] simple_func.add_comm_group simple_func.metric_space simple_func.emetric_space instance : inhabited (α →₁ₛ β) := ⟨0⟩ @[simp, elim_cast] lemma coe_zero : ((0 : α →₁ₛ β) : α →₁ β) = 0 := rfl @[simp, move_cast] lemma coe_add (f g : α →₁ₛ β) : ((f + g : α →₁ₛ β) : α →₁ β) = f + g := rfl @[simp, move_cast] lemma coe_neg (f : α →₁ₛ β) : ((-f : α →₁ₛ β) : α →₁ β) = -f := rfl @[simp, move_cast] lemma coe_sub (f g : α →₁ₛ β) : ((f - g : α →₁ₛ β) : α →₁ β) = f - g := rfl @[simp] lemma edist_eq (f g : α →₁ₛ β) : edist f g = edist (f : α →₁ β) (g : α →₁ β) := rfl @[simp] lemma dist_eq (f g : α →₁ₛ β) : dist f g = dist (f : α →₁ β) (g : α →₁ β) := rfl /-- The norm on `α →₁ₛ β` is inherited from L1 space. That is, `∥f∥ = ∫⁻ a, edist (f a) 0`. Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner integral. -/ protected def has_norm : has_norm (α →₁ₛ β) := ⟨λf, ∥(f : α →₁ β)∥⟩ local attribute [instance] simple_func.has_norm lemma norm_eq (f : α →₁ₛ β) : ∥f∥ = ∥(f : α →₁ β)∥ := rfl lemma norm_eq' (f : α →₁ₛ β) : ∥f∥ = ennreal.to_real (edist (f : α →ₘ β) 0) := rfl /-- Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner integral. -/ protected def normed_group : normed_group (α →₁ₛ β) := normed_group.of_add_dist (λ x, rfl) $ by { intros, simp only [dist_eq, coe_add, l1.dist_eq, l1.coe_add], rw edist_eq_add_add } variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] /-- Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner integral. -/ protected def has_scalar : has_scalar 𝕜 (α →₁ₛ β) := ⟨λk f, ⟨k • f, begin rcases f with ⟨f, ⟨s, hsi, hs⟩⟩, use k • s, split, { exact integrable.smul _ hsi }, { rw [coe_smul, subtype.coe_mk, ← hs], refl } end ⟩⟩ local attribute [instance, priority 10000] simple_func.has_scalar @[simp, move_cast] lemma coe_smul (c : 𝕜) (f : α →₁ₛ β) : ((c • f : α →₁ₛ β) : α →₁ β) = c • (f : α →₁ β) := rfl /-- Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner integral. -/ protected def semimodule : semimodule 𝕜 (α →₁ₛ β) := { one_smul := λf, simple_func.eq (by { simp only [coe_smul], exact one_smul _ _ }), mul_smul := λx y f, simple_func.eq (by { simp only [coe_smul], exact mul_smul _ _ _ }), smul_add := λx f g, simple_func.eq (by { simp only [coe_smul, coe_add], exact smul_add _ _ _ }), smul_zero := λx, simple_func.eq (by { simp only [coe_zero, coe_smul], exact smul_zero _ }), add_smul := λx y f, simple_func.eq (by { simp only [coe_smul], exact add_smul _ _ _ }), zero_smul := λf, simple_func.eq (by { simp only [coe_smul], exact zero_smul _ _ }) } /-- Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner integral. -/ protected def module : module 𝕜 (α →₁ₛ β) := { .. simple_func.semimodule } /-- Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner integral. -/ protected def vector_space : vector_space 𝕜 (α →₁ₛ β) := { .. simple_func.semimodule } local attribute [instance] simple_func.vector_space simple_func.normed_group /-- Not declared as an instance as `α →₁ₛ β` will only be useful in the construction of the bochner integral. -/ protected def normed_space : normed_space 𝕜 (α →₁ₛ β) := ⟨ λc f, by { rw [norm_eq, norm_eq, coe_smul, norm_smul] } ⟩ end instances local attribute [instance] simple_func.normed_group simple_func.normed_space section of_simple_func /-- Construct the equivalence class `[f]` of an integrable simple function `f`. -/ @[reducible] def of_simple_func (f : α →ₛ β) (hf : integrable f) : (α →₁ₛ β) := ⟨l1.of_fun f f.measurable hf, ⟨f, ⟨hf, rfl⟩⟩⟩ lemma of_simple_func_eq_of_fun (f : α →ₛ β) (hf : integrable f) : (of_simple_func f hf : α →₁ β) = l1.of_fun f f.measurable hf := rfl lemma of_simple_func_eq_mk (f : α →ₛ β) (hf : integrable f) : (of_simple_func f hf : α →ₘ β) = ae_eq_fun.mk f f.measurable := rfl lemma of_simple_func_zero : of_simple_func (0 : α →ₛ β) (integrable_zero α β) = 0 := rfl lemma of_simple_func_add (f g : α →ₛ β) (hf hg) : of_simple_func (f + g) (integrable.add f.measurable hf g.measurable hg) = of_simple_func f hf + of_simple_func g hg := rfl lemma of_simple_func_neg (f : α →ₛ β) (hf) : of_simple_func (-f) (integrable.neg hf) = -of_simple_func f hf := rfl lemma of_simple_func_sub (f g : α →ₛ β) (hf hg) : of_simple_func (f - g) (integrable.sub f.measurable hf g.measurable hg) = of_simple_func f hf - of_simple_func g hg := rfl variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma of_simple_func_smul (f : α →ₛ β) (hf) (c : 𝕜) : of_simple_func (c • f) (integrable.smul _ hf) = c • of_simple_func f hf := rfl lemma norm_of_simple_func (f : α →ₛ β) (hf) : ∥of_simple_func f hf∥ = ennreal.to_real (∫⁻ a, edist (f a) 0) := rfl end of_simple_func section to_simple_func /-- Find a representative of a `l1.simple_func`. -/ def to_simple_func (f : α →₁ₛ β) : α →ₛ β := classical.some f.2 /-- `f.to_simple_func` is measurable. -/ protected lemma measurable (f : α →₁ₛ β) : measurable f.to_simple_func := f.to_simple_func.measurable /-- `f.to_simple_func` is integrable. -/ protected lemma integrable (f : α →₁ₛ β) : integrable f.to_simple_func := let ⟨h, _⟩ := classical.some_spec f.2 in h lemma of_simple_func_to_simple_func (f : α →₁ₛ β) : of_simple_func (f.to_simple_func) f.integrable = f := by { rw ← simple_func.eq_iff', exact (classical.some_spec f.2).2 } lemma to_simple_func_of_simple_func (f : α →ₛ β) (hfi) : ∀ₘ a, (of_simple_func f hfi).to_simple_func a = f a := by { rw ← mk_eq_mk, exact (classical.some_spec (of_simple_func f hfi).2).2 } lemma to_simple_func_eq_to_fun (f : α →₁ₛ β) : ∀ₘ a, (f.to_simple_func) a = (f : α →₁ β).to_fun a := begin rw [← of_fun_eq_of_fun (f.to_simple_func) (f : α →₁ β).to_fun f.measurable f.integrable (f:α→₁β).measurable (f:α→₁β).integrable, ← l1.eq_iff], simp only [of_fun_eq_mk], rcases classical.some_spec f.2 with ⟨_, h⟩, convert h, rw mk_to_fun, refl end variables (α β) lemma zero_to_simple_func : ∀ₘ a, (0 : α →₁ₛ β).to_simple_func a = 0 := begin filter_upwards [to_simple_func_eq_to_fun (0 : α →₁ₛ β), l1.zero_to_fun α β], assume a, simp only [mem_set_of_eq], assume h, rw h, assume h, exact h end variables {α β} lemma add_to_simple_func (f g : α →₁ₛ β) : ∀ₘ a, (f + g).to_simple_func a = f.to_simple_func a + g.to_simple_func a := begin filter_upwards [to_simple_func_eq_to_fun (f + g), to_simple_func_eq_to_fun f, to_simple_func_eq_to_fun g, l1.add_to_fun (f:α→₁β) g], assume a, simp only [mem_set_of_eq], repeat { assume h, rw h }, assume h, rw ← h, refl end lemma neg_to_simple_func (f : α →₁ₛ β) : ∀ₘ a, (-f).to_simple_func a = - f.to_simple_func a := begin filter_upwards [to_simple_func_eq_to_fun (-f), to_simple_func_eq_to_fun f, l1.neg_to_fun (f:α→₁β)], assume a, simp only [mem_set_of_eq], repeat { assume h, rw h }, assume h, rw ← h, refl end lemma sub_to_simple_func (f g : α →₁ₛ β) : ∀ₘ a, (f - g).to_simple_func a = f.to_simple_func a - g.to_simple_func a := begin filter_upwards [to_simple_func_eq_to_fun (f - g), to_simple_func_eq_to_fun f, to_simple_func_eq_to_fun g, l1.sub_to_fun (f:α→₁β) g], assume a, simp only [mem_set_of_eq], repeat { assume h, rw h }, assume h, rw ← h, refl end variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma smul_to_simple_func (k : 𝕜) (f : α →₁ₛ β) : ∀ₘ a, (k • f).to_simple_func a = k • f.to_simple_func a := begin filter_upwards [to_simple_func_eq_to_fun (k • f), to_simple_func_eq_to_fun f, l1.smul_to_fun k (f:α→₁β)], assume a, simp only [mem_set_of_eq], repeat { assume h, rw h }, assume h, rw ← h, refl end lemma lintegral_edist_to_simple_func_lt_top (f g : α →₁ₛ β) : (∫⁻ (x : α), edist ((to_simple_func f) x) ((to_simple_func g) x)) < ⊤ := begin rw lintegral_rw₂ (to_simple_func_eq_to_fun f) (to_simple_func_eq_to_fun g), exact lintegral_edist_to_fun_lt_top _ _ end lemma dist_to_simple_func (f g : α →₁ₛ β) : dist f g = ennreal.to_real (∫⁻ x, edist (f.to_simple_func x) (g.to_simple_func x)) := begin rw [dist_eq, l1.dist_to_fun, ennreal.to_real_eq_to_real], { rw lintegral_rw₂, repeat { exact all_ae_eq_symm (to_simple_func_eq_to_fun _) } }, { exact l1.lintegral_edist_to_fun_lt_top _ _ }, { exact lintegral_edist_to_simple_func_lt_top _ _ } end lemma norm_to_simple_func (f : α →₁ₛ β) : ∥f∥ = ennreal.to_real (∫⁻ (a : α), nnnorm ((to_simple_func f) a)) := calc ∥f∥ = ennreal.to_real (∫⁻x, edist (f.to_simple_func x) ((0 : α →₁ₛ β).to_simple_func x)) : begin rw [← dist_zero_right, dist_to_simple_func] end ... = ennreal.to_real (∫⁻ (x : α), (coe ∘ nnnorm) (f.to_simple_func x)) : begin rw lintegral_nnnorm_eq_lintegral_edist, have : (∫⁻ (x : α), edist ((to_simple_func f) x) ((to_simple_func (0:α→₁ₛβ)) x)) = ∫⁻ (x : α), edist ((to_simple_func f) x) 0, { apply lintegral_congr_ae, filter_upwards [zero_to_simple_func α β], assume a, simp only [mem_set_of_eq], assume h, rw h }, rw [ennreal.to_real_eq_to_real], { exact this }, { exact lintegral_edist_to_simple_func_lt_top _ _ }, { rw ← this, exact lintegral_edist_to_simple_func_lt_top _ _ } end lemma norm_eq_bintegral (f : α →₁ₛ β) : ∥f∥ = (f.to_simple_func.map norm).bintegral := calc ∥f∥ = ennreal.to_real (∫⁻ (x : α), (coe ∘ nnnorm) (f.to_simple_func x)) : by { rw norm_to_simple_func } ... = (f.to_simple_func.map norm).bintegral : begin rw ← f.to_simple_func.bintegral_eq_lintegral (coe ∘ nnnorm) f.integrable, { congr }, { simp only [nnnorm_zero, function.comp_app, ennreal.coe_zero] }, { assume b, exact coe_lt_top } end end to_simple_func section coe_to_l1 /-! The embedding of integrable simple functions `α →₁ₛ β` into L1 is a uniform and dense embedding. -/ lemma exists_simple_func_near (f : α →₁ β) {ε : ℝ} (ε0 : 0 < ε) : ∃ s : α →₁ₛ β, dist f s < ε := begin rcases f with ⟨⟨f, hfm⟩, hfi⟩, simp only [integrable_mk, quot_mk_eq_mk] at hfi, rcases simple_func_sequence_tendsto' hfm hfi with ⟨F, ⟨h₁, h₂⟩⟩, rw ennreal.tendsto_at_top at h₂, rcases h₂ (ennreal.of_real (ε/2)) (of_real_pos.2 $ half_pos ε0) with ⟨N, hN⟩, have : (∫⁻ (x : α), nndist (F N x) (f x)) < ennreal.of_real ε := calc (∫⁻ (x : α), nndist (F N x) (f x)) ≤ 0 + ennreal.of_real (ε/2) : (hN N (le_refl _)).2 ... < ennreal.of_real ε : by { simp only [zero_add, of_real_lt_of_real_iff ε0], exact half_lt_self ε0 }, { refine ⟨of_simple_func (F N) (h₁ N), _⟩, rw dist_comm, rw lt_of_real_iff_to_real_lt _ at this, { simpa [edist_mk_mk', of_simple_func, l1.of_fun, l1.dist_eq] }, rw ← lt_top_iff_ne_top, exact lt_trans this (by simp [lt_top_iff_ne_top, of_real_ne_top]) }, { exact zero_ne_top } end protected lemma uniform_continuous : uniform_continuous (coe : (α →₁ₛ β) → (α →₁ β)) := uniform_continuous_comap protected lemma uniform_embedding : uniform_embedding (coe : (α →₁ₛ β) → (α →₁ β)) := uniform_embedding_comap subtype.val_injective protected lemma uniform_inducing : uniform_inducing (coe : (α →₁ₛ β) → (α →₁ β)) := simple_func.uniform_embedding.to_uniform_inducing protected lemma dense_embedding : dense_embedding (coe : (α →₁ₛ β) → (α →₁ β)) := simple_func.uniform_embedding.dense_embedding $ λ f, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε,ε0, hε⟩ := metric.mem_nhds_iff.1 ht in let ⟨s, h⟩ := exists_simple_func_near f ε0 in ⟨_, hε (metric.mem_ball'.2 h), s, rfl⟩ protected lemma dense_inducing : dense_inducing (coe : (α →₁ₛ β) → (α →₁ β)) := simple_func.dense_embedding.to_dense_inducing protected lemma dense_range : dense_range (coe : (α →₁ₛ β) → (α →₁ β)) := simple_func.dense_inducing.dense variables (𝕜 : Type*) [normed_field 𝕜] [normed_space 𝕜 β] variables (α β) /-- The uniform and dense embedding of L1 simple functions into L1 functions. -/ def coe_to_l1 : (α →₁ₛ β) →L[𝕜] (α →₁ β) := { to_fun := (coe : (α →₁ₛ β) → (α →₁ β)), add := λf g, rfl, smul := λk f, rfl, cont := l1.simple_func.uniform_continuous.continuous, } variables {α β 𝕜} end coe_to_l1 section pos_part /-- Positive part of a simple function in L1 space. -/ def pos_part (f : α →₁ₛ ℝ) : α →₁ₛ ℝ := ⟨l1.pos_part (f : α →₁ ℝ), begin rcases f with ⟨f, s, hsi, hsf⟩, use s.pos_part, split, { exact integrable.max_zero hsi }, { simp only [subtype.coe_mk], rw [l1.coe_pos_part, ← hsf, ae_eq_fun.pos_part, ae_eq_fun.zero_def, comp₂_mk_mk, mk_eq_mk], filter_upwards [], simp only [mem_set_of_eq], assume a, refl } end ⟩ /-- Negative part of a simple function in L1 space. -/ def neg_part (f : α →₁ₛ ℝ) : α →₁ₛ ℝ := pos_part (-f) @[move_cast] lemma coe_pos_part (f : α →₁ₛ ℝ) : (f.pos_part : α →₁ ℝ) = (f : α →₁ ℝ).pos_part := rfl @[move_cast] lemma coe_neg_part (f : α →₁ₛ ℝ) : (f.neg_part : α →₁ ℝ) = (f : α →₁ ℝ).neg_part := rfl end pos_part section simple_func_integral /-! Define the Bochner integral on `α →₁ₛ β` and prove basic properties of this integral. -/ variables [normed_space ℝ β] /-- The Bochner integral over simple functions in l1 space. -/ def integral (f : α →₁ₛ β) : β := (f.to_simple_func).bintegral lemma integral_eq_bintegral (f : α →₁ₛ β) : integral f = (f.to_simple_func).bintegral := rfl lemma integral_eq_lintegral {f : α →₁ₛ ℝ} (h_pos : ∀ₘ a, 0 ≤ f.to_simple_func a) : integral f = ennreal.to_real (∫⁻ a, ennreal.of_real (f.to_simple_func a)) := by { rw [integral, simple_func.bintegral_eq_lintegral' f.integrable h_pos], refl } lemma integral_congr (f g : α →₁ₛ β) (h : ∀ₘ a, f.to_simple_func a = g.to_simple_func a) : integral f = integral g := by { simp only [integral], apply simple_func.bintegral_congr f.integrable g.integrable, exact h } lemma integral_add (f g : α →₁ₛ β) : integral (f + g) = integral f + integral g := begin simp only [integral], rw ← simple_func.bintegral_add f.integrable g.integrable, apply simple_func.bintegral_congr (f + g).integrable, { exact f.integrable.add f.measurable g.measurable g.integrable }, { apply add_to_simple_func }, end lemma integral_smul (r : ℝ) (f : α →₁ₛ β) : integral (r • f) = r • integral f := begin simp only [integral], rw ← simple_func.bintegral_smul _ f.integrable, apply simple_func.bintegral_congr (r • f).integrable, { exact integrable.smul _ f.integrable }, { apply smul_to_simple_func } end lemma norm_integral_le_norm (f : α →₁ₛ β) : ∥ integral f ∥ ≤ ∥f∥ := begin rw [integral, norm_eq_bintegral], exact f.to_simple_func.norm_bintegral_le_bintegral_norm f.integrable end /-- The Bochner integral over simple functions in l1 space as a continuous linear map. -/ def integral_clm : (α →₁ₛ β) →L[ℝ] β := linear_map.mk_continuous ⟨integral, integral_add, integral_smul⟩ 1 (λf, le_trans (norm_integral_le_norm _) $ by rw one_mul) local notation `Integral` := @integral_clm α _ β _ _ _ _ _ open continuous_linear_map lemma norm_Integral_le_one : ∥Integral∥ ≤ 1 := linear_map.mk_continuous_norm_le _ (zero_le_one) _ section pos_part lemma pos_part_to_simple_func (f : α →₁ₛ ℝ) : ∀ₘ a, f.pos_part.to_simple_func a = f.to_simple_func.pos_part a := begin have eq : ∀ a, f.to_simple_func.pos_part a = max (f.to_simple_func a) 0 := λa, rfl, have ae_eq : ∀ₘ a, f.pos_part.to_simple_func a = max (f.to_simple_func a) 0, { filter_upwards [to_simple_func_eq_to_fun f.pos_part, pos_part_to_fun (f : α →₁ ℝ), to_simple_func_eq_to_fun f], simp only [mem_set_of_eq], assume a h₁ h₂ h₃, rw [h₁, coe_pos_part, h₂, ← h₃] }, filter_upwards [ae_eq], simp only [mem_set_of_eq], assume a h, rw [h, eq] end lemma neg_part_to_simple_func (f : α →₁ₛ ℝ) : ∀ₘ a, f.neg_part.to_simple_func a = f.to_simple_func.neg_part a := begin rw [simple_func.neg_part, measure_theory.simple_func.neg_part], filter_upwards [pos_part_to_simple_func (-f), neg_to_simple_func f], simp only [mem_set_of_eq], assume a h₁ h₂, rw h₁, show max _ _ = max _ _, rw h₂, refl end lemma integral_eq_norm_pos_part_sub (f : α →₁ₛ ℝ) : f.integral = ∥f.pos_part∥ - ∥f.neg_part∥ := begin -- Convert things in `L¹` to their `simple_func` counterpart have ae_eq₁ : ∀ₘ a, f.to_simple_func.pos_part a = (f.pos_part).to_simple_func.map norm a, { filter_upwards [pos_part_to_simple_func f], simp only [mem_set_of_eq], assume a h, rw [simple_func.map_apply, h], conv_lhs { rw [← simple_func.pos_part_map_norm, simple_func.map_apply] } }, -- Convert things in `L¹` to their `simple_func` counterpart have ae_eq₂ : ∀ₘ a, f.to_simple_func.neg_part a = (f.neg_part).to_simple_func.map norm a, { filter_upwards [neg_part_to_simple_func f], simp only [mem_set_of_eq], assume a h, rw [simple_func.map_apply, h], conv_lhs { rw [← simple_func.neg_part_map_norm, simple_func.map_apply] } }, -- Convert things in `L¹` to their `simple_func` counterpart have ae_eq : ∀ₘ a, f.to_simple_func.pos_part a - f.to_simple_func.neg_part a = (f.pos_part).to_simple_func.map norm a - (f.neg_part).to_simple_func.map norm a, { filter_upwards [ae_eq₁, ae_eq₂], simp only [mem_set_of_eq], assume a h₁ h₂, rw [h₁, h₂] }, rw [integral, norm_eq_bintegral, norm_eq_bintegral, ← simple_func.bintegral_sub], { show f.to_simple_func.bintegral = ((f.pos_part.to_simple_func).map norm - f.neg_part.to_simple_func.map norm).bintegral, apply simple_func.bintegral_congr f.integrable, { show integrable (f.pos_part.to_simple_func.map norm - f.neg_part.to_simple_func.map norm), refine integrable_of_ae_eq _ _, { exact (f.to_simple_func.pos_part - f.to_simple_func.neg_part) }, { exact (integrable.max_zero f.integrable).sub f.to_simple_func.pos_part.measurable f.to_simple_func.neg_part.measurable (integrable.max_zero f.integrable.neg) }, exact ae_eq }, filter_upwards [ae_eq₁, ae_eq₂], simp only [mem_set_of_eq], assume a h₁ h₂, show _ = _ - _, rw [← h₁, ← h₂], have := f.to_simple_func.pos_part_sub_neg_part, conv_lhs {rw ← this}, refl }, { refine integrable_of_ae_eq (integrable.max_zero f.integrable) ae_eq₁ }, { refine integrable_of_ae_eq (integrable.max_zero f.integrable.neg) ae_eq₂ } end end pos_part end simple_func_integral end simple_func open simple_func variables [normed_space ℝ β] [normed_space ℝ γ] [complete_space β] section integration_in_l1 local notation `to_l1` := coe_to_l1 α β ℝ local attribute [instance] simple_func.normed_group simple_func.normed_space open continuous_linear_map /-- The Bochner integral in l1 space as a continuous linear map. -/ def integral_clm : (α →₁ β) →L[ℝ] β := integral_clm.extend to_l1 simple_func.dense_range simple_func.uniform_inducing /-- The Bochner integral in l1 space -/ def integral (f : α →₁ β) : β := (integral_clm).to_fun f lemma integral_eq (f : α →₁ β) : integral f = (integral_clm).to_fun f := rfl @[elim_cast] lemma simple_func.integral_eq_integral (f : α →₁ₛ β) : integral (f : α →₁ β) = f.integral := by { refine uniformly_extend_of_ind _ _ _ _, exact simple_func.integral_clm.uniform_continuous } variables (α β) @[simp] lemma integral_zero : integral (0 : α →₁ β) = 0 := map_zero integral_clm variables {α β} lemma integral_add (f g : α →₁ β) : integral (f + g) = integral f + integral g := map_add integral_clm f g lemma integral_neg (f : α →₁ β) : integral (-f) = - integral f := map_neg integral_clm f lemma integral_sub (f g : α →₁ β) : integral (f - g) = integral f - integral g := map_sub integral_clm f g lemma integral_smul (r : ℝ) (f : α →₁ β) : integral (r • f) = r • integral f := map_smul r integral_clm f local notation `Integral` := @integral_clm α _ β _ _ _ _ _ _ local notation `sIntegral` := @simple_func.integral_clm α _ β _ _ _ _ _ lemma norm_Integral_le_one : ∥Integral∥ ≤ 1 := calc ∥Integral∥ ≤ (1 : nnreal) * ∥sIntegral∥ : op_norm_extend_le _ _ _ $ λs, by {rw [nnreal.coe_one, one_mul], refl} ... = ∥sIntegral∥ : one_mul _ ... ≤ 1 : norm_Integral_le_one lemma norm_integral_le (f : α →₁ β) : ∥integral f∥ ≤ ∥f∥ := calc ∥integral f∥ = ∥Integral f∥ : rfl ... ≤ ∥Integral∥ * ∥f∥ : le_op_norm _ _ ... ≤ 1 * ∥f∥ : mul_le_mul_of_nonneg_right norm_Integral_le_one $ norm_nonneg _ ... = ∥f∥ : one_mul _ section pos_part lemma integral_eq_norm_pos_part_sub (f : α →₁ ℝ) : integral f = ∥pos_part f∥ - ∥neg_part f∥ := begin -- Use `is_closed_property` and `is_closed_eq` refine @is_closed_property _ _ _ (coe : (α →₁ₛ ℝ) → (α →₁ ℝ)) (λ f : α →₁ ℝ, integral f = ∥pos_part f∥ - ∥neg_part f∥) l1.simple_func.dense_range (is_closed_eq _ _) _ f, { exact cont _ }, { refine continuous.sub (continuous_norm.comp l1.continuous_pos_part) (continuous_norm.comp l1.continuous_neg_part) }, -- Show that the property holds for all simple functions in the `L¹` space. { assume s, norm_cast, rw [← simple_func.norm_eq, ← simple_func.norm_eq], exact simple_func.integral_eq_norm_pos_part_sub _} end end pos_part end integration_in_l1 end l1 variables [normed_group β] [second_countable_topology β] [normed_space ℝ β] [complete_space β] [measurable_space β] [borel_space β] [normed_group γ] [second_countable_topology γ] [normed_space ℝ γ] [complete_space γ] [measurable_space γ] [borel_space γ] /-- The Bochner integral -/ def integral (f : α → β) : β := if hf : measurable f ∧ integrable f then (l1.of_fun f hf.1 hf.2).integral else 0 notation `∫` binders `, ` r:(scoped f, integral f) := r section properties open continuous_linear_map measure_theory.simple_func variables {f g : α → β} lemma integral_eq (f : α → β) (h₁ : measurable f) (h₂ : integrable f) : (∫ a, f a) = (l1.of_fun f h₁ h₂).integral := dif_pos ⟨h₁, h₂⟩ lemma integral_undef (h : ¬ (measurable f ∧ integrable f)) : (∫ a, f a) = 0 := dif_neg h lemma integral_non_integrable (h : ¬ integrable f) : (∫ a, f a) = 0 := integral_undef $ not_and_of_not_right _ h lemma integral_non_measurable (h : ¬ measurable f) : (∫ a, f a) = 0 := integral_undef $ not_and_of_not_left _ h variables (α β) @[simp] lemma integral_zero : (∫ a : α, (0:β)) = 0 := by rw [integral_eq, l1.of_fun_zero, l1.integral_zero] variables {α β} lemma integral_add (hfm : measurable f) (hfi : integrable f) (hgm : measurable g) (hgi : integrable g) : (∫ a, f a + g a) = (∫ a, f a) + (∫ a, g a) := by rw [integral_eq, integral_eq f hfm hfi, integral_eq g hgm hgi, l1.of_fun_add, l1.integral_add] lemma integral_neg (f : α → β) : (∫ a, -f a) = - (∫ a, f a) := begin by_cases hf : measurable f ∧ integrable f, { rw [integral_eq f hf.1 hf.2, integral_eq (λa, - f a) hf.1.neg hf.2.neg, l1.of_fun_neg, l1.integral_neg] }, { have hf' : ¬(measurable (λa, -f a) ∧ integrable (λa, -f a)), { rwa [measurable_neg_iff, integrable_neg_iff] }, rw [integral_undef hf, integral_undef hf', neg_zero] } end lemma integral_sub (hfm : measurable f) (hfi : integrable f) (hgm : measurable g) (hgi : integrable g) : (∫ a, f a - g a) = (∫ a, f a) - (∫ a, g a) := by { rw [sub_eq_add_neg, ← integral_neg], exact integral_add hfm hfi hgm.neg hgi.neg } lemma integral_smul (r : ℝ) (f : α → β) : (∫ a, r • (f a)) = r • (∫ a, f a) := begin by_cases hf : measurable f ∧ integrable f, { rw [integral_eq f hf.1 hf.2, integral_eq (λa, r • (f a)), l1.of_fun_smul, l1.integral_smul] }, { by_cases hr : r = 0, { simp only [hr, measure_theory.integral_zero, zero_smul] }, have hf' : ¬(measurable (λa, r • f a) ∧ integrable (λa, r • f a)), { rwa [measurable_const_smul_iff hr, integrable_smul_iff hr f]; apply_instance }, rw [integral_undef hf, integral_undef hf', smul_zero] } end lemma integral_mul_left (r : ℝ) (f : α → ℝ) : (∫ a, r * (f a)) = r * (∫ a, f a) := integral_smul r f lemma integral_mul_right (r : ℝ) (f : α → ℝ) : (∫ a, (f a) * r) = (∫ a, f a) * r := by { simp only [mul_comm], exact integral_mul_left r f } lemma integral_div (r : ℝ) (f : α → ℝ) : (∫ a, (f a) / r) = (∫ a, f a) / r := integral_mul_right r⁻¹ f lemma integral_congr_ae (hfm : measurable f) (hgm : measurable g) (h : ∀ₘ a, f a = g a) : (∫ a, f a) = (∫ a, g a) := begin by_cases hfi : integrable f, { have hgi : integrable g := integrable_of_ae_eq hfi h, rw [integral_eq f hfm hfi, integral_eq g hgm hgi, (l1.of_fun_eq_of_fun f g hfm hfi hgm hgi).2 h] }, { have hgi : ¬ integrable g, { rw integrable_congr_ae h at hfi, exact hfi }, rw [integral_non_integrable hfi, integral_non_integrable hgi] }, end lemma norm_integral_le_lintegral_norm (f : α → β) : ∥(∫ a, f a)∥ ≤ ennreal.to_real (∫⁻ a, ennreal.of_real ∥f a∥) := begin by_cases hf : measurable f ∧ integrable f, { rw [integral_eq f hf.1 hf.2, ← l1.norm_of_fun_eq_lintegral_norm f hf.1 hf.2], exact l1.norm_integral_le _ }, { rw [integral_undef hf, _root_.norm_zero], exact to_real_nonneg } end /-- Lebesgue dominated convergence theorem provides sufficient conditions under which almost everywhere convergence of a sequence of functions implies the convergence of their integrals. -/ theorem tendsto_integral_of_dominated_convergence {F : ℕ → α → β} {f : α → β} (bound : α → ℝ) (F_measurable : ∀ n, measurable (F n)) (f_measurable : measurable f) (bound_integrable : integrable bound) (h_bound : ∀ n, ∀ₘ a, ∥F n a∥ ≤ bound a) (h_lim : ∀ₘ a, tendsto (λ n, F n a) at_top (𝓝 (f a))) : tendsto (λn, ∫ a, F n a) at_top (𝓝 $ (∫ a, f a)) := begin /- To show `(∫ a, F n a) --> (∫ f)`, suffices to show `∥∫ a, F n a - ∫ f∥ --> 0` -/ rw tendsto_iff_norm_tendsto_zero, /- But `0 ≤ ∥∫ a, F n a - ∫ f∥ = ∥∫ a, (F n a - f a) ∥ ≤ ∫ a, ∥F n a - f a∥, and thus we apply the sandwich theorem and prove that `∫ a, ∥F n a - f a∥ --> 0` -/ have lintegral_norm_tendsto_zero : tendsto (λn, ennreal.to_real $ ∫⁻ a, ennreal.of_real ∥F n a - f a∥) at_top (𝓝 0) := (tendsto_to_real (zero_ne_top)).comp (tendsto_lintegral_norm_of_dominated_convergence F_measurable f_measurable bound_integrable h_bound h_lim), -- Use the sandwich theorem refine squeeze_zero (λ n, norm_nonneg _) _ lintegral_norm_tendsto_zero, -- Show `∥∫ a, F n a - ∫ f∥ ≤ ∫ a, ∥F n a - f a∥` for all `n` { assume n, have h₁ : integrable (F n) := integrable_of_integrable_bound bound_integrable (h_bound _), have h₂ : integrable f := integrable_of_dominated_convergence bound_integrable h_bound h_lim, rw ← integral_sub (F_measurable _) h₁ f_measurable h₂, exact norm_integral_le_lintegral_norm _ } end /-- Lebesgue dominated convergence theorem for filters with a countable basis -/ lemma tendsto_integral_filter_of_dominated_convergence {ι} {l : filter ι} {F : ι → α → β} {f : α → β} (bound : α → ℝ) (hl_cb : l.is_countably_generated) (hF_meas : ∀ᶠ n in l, measurable (F n)) (f_measurable : measurable f) (h_bound : ∀ᶠ n in l, ∀ₘ a, ∥F n a∥ ≤ bound a) (bound_integrable : integrable bound) (h_lim : ∀ₘ a, tendsto (λ n, F n a) l (𝓝 (f a))) : tendsto (λn, ∫ a, F n a) l (𝓝 $ (∫ a, f a)) := begin rw hl_cb.tendsto_iff_seq_tendsto, { intros x xl, have hxl, { rw tendsto_at_top' at xl, exact xl }, have h := inter_mem_sets hF_meas h_bound, replace h := hxl _ h, rcases h with ⟨k, h⟩, rw ← tendsto_add_at_top_iff_nat k, refine tendsto_integral_of_dominated_convergence _ _ _ _ _ _, { exact bound }, { intro, refine (h _ _).1, exact nat.le_add_left _ _ }, { assumption }, { assumption }, { intro, refine (h _ _).2, exact nat.le_add_left _ _ }, { filter_upwards [h_lim], simp only [mem_set_of_eq], assume a h_lim, apply @tendsto.comp _ _ _ (λn, x (n + k)) (λn, F n a), { assumption }, rw tendsto_add_at_top_iff_nat, assumption } }, end /-- The Bochner integral of a real-valued function `f : α → ℝ` is the difference between the integral of the positive part of `f` and the integral of the negative part of `f`. -/ lemma integral_eq_lintegral_max_sub_lintegral_min {f : α → ℝ} (hfm : measurable f) (hfi : integrable f) : (∫ a, f a) = ennreal.to_real (∫⁻ a, ennreal.of_real $ max (f a) 0) - ennreal.to_real (∫⁻ a, ennreal.of_real $ - min (f a) 0) := let f₁ : α →₁ ℝ := l1.of_fun f hfm hfi in -- Go to the `L¹` space have eq₁ : ennreal.to_real (∫⁻ a, ennreal.of_real $ max (f a) 0) = ∥l1.pos_part f₁∥ := begin rw l1.norm_eq_norm_to_fun, congr' 1, apply lintegral_congr_ae, filter_upwards [l1.pos_part_to_fun f₁, l1.to_fun_of_fun f hfm hfi], simp only [mem_set_of_eq], assume a h₁ h₂, rw [h₁, h₂, real.norm_eq_abs, abs_of_nonneg], exact le_max_right _ _ end, -- Go to the `L¹` space have eq₂ : ennreal.to_real (∫⁻ a, ennreal.of_real $ -min (f a) 0) = ∥l1.neg_part f₁∥ := begin rw l1.norm_eq_norm_to_fun, congr' 1, apply lintegral_congr_ae, filter_upwards [l1.neg_part_to_fun_eq_min f₁, l1.to_fun_of_fun f hfm hfi], simp only [mem_set_of_eq], assume a h₁ h₂, rw [h₁, h₂, real.norm_eq_abs, abs_of_nonneg], rw [min_eq_neg_max_neg_neg, _root_.neg_neg, neg_zero], exact le_max_right _ _ end, begin rw [eq₁, eq₂, integral, dif_pos], exact l1.integral_eq_norm_pos_part_sub _, { exact ⟨hfm, hfi⟩ } end lemma integral_eq_lintegral_of_nonneg_ae {f : α → ℝ} (hf : ∀ₘ a, 0 ≤ f a) (hfm : measurable f) : (∫ a, f a) = ennreal.to_real (∫⁻ a, ennreal.of_real $ f a) := begin by_cases hfi : integrable f, { rw integral_eq_lintegral_max_sub_lintegral_min hfm hfi, have h_min : (∫⁻ a, ennreal.of_real (-min (f a) 0)) = 0, { rw lintegral_eq_zero_iff, { filter_upwards [hf], simp only [mem_set_of_eq], assume a h, simp only [min_eq_right h, neg_zero, ennreal.of_real_zero] }, { refine measurable_of_real.comp ((measurable.neg measurable_id).comp $ measurable.min hfm measurable_const) } }, have h_max : (∫⁻ a, ennreal.of_real (max (f a) 0)) = (∫⁻ a, ennreal.of_real $ f a), { apply lintegral_congr_ae, filter_upwards [hf], simp only [mem_set_of_eq], assume a h, rw max_eq_left h }, rw [h_min, h_max, zero_to_real, _root_.sub_zero] }, { rw integral_non_integrable hfi, rw [integrable_iff_norm, lt_top_iff_ne_top, ne.def, not_not] at hfi, have : (∫⁻ (a : α), ennreal.of_real (f a)) = (∫⁻ a, ennreal.of_real ∥f a∥), { apply lintegral_congr_ae, filter_upwards [hf], simp only [mem_set_of_eq], assume a h, rw [real.norm_eq_abs, abs_of_nonneg h] }, rw [this, hfi], refl } end lemma integral_nonneg_of_ae {f : α → ℝ} (hf : ∀ₘ a, 0 ≤ f a) : 0 ≤ (∫ a, f a) := begin by_cases hfm : measurable f, { rw integral_eq_lintegral_of_nonneg_ae hf hfm, exact to_real_nonneg }, { rw integral_non_measurable hfm } end lemma integral_nonpos_of_nonpos_ae {f : α → ℝ} (hf : ∀ₘ a, f a ≤ 0) : (∫ a, f a) ≤ 0 := begin have hf : ∀ₘ a, 0 ≤ (-f) a, { filter_upwards [hf], simp only [mem_set_of_eq], assume a h, rwa [pi.neg_apply, neg_nonneg] }, have : 0 ≤ (∫ a, -f a) := integral_nonneg_of_ae hf, rwa [integral_neg, neg_nonneg] at this, end lemma integral_le_integral_ae {f g : α → ℝ} (hfm : measurable f) (hfi : integrable f) (hgm : measurable g) (hgi : integrable g) (h : ∀ₘ a, f a ≤ g a) : (∫ a, f a) ≤ (∫ a, g a) := le_of_sub_nonneg begin rw ← integral_sub hgm hgi hfm hfi, apply integral_nonneg_of_ae, filter_upwards [h], simp only [mem_set_of_eq], assume a, exact sub_nonneg_of_le end lemma integral_le_integral {f g : α → ℝ} (hfm : measurable f) (hfi : integrable f) (hgm : measurable g) (hgi : integrable g) (h : ∀ a, f a ≤ g a) : (∫ a, f a) ≤ (∫ a, g a) := integral_le_integral_ae hfm hfi hgm hgi $ univ_mem_sets' h lemma norm_integral_le_integral_norm (f : α → β) : ∥(∫ a, f a)∥ ≤ ∫ a, ∥f a∥ := have le_ae : ∀ₘ (a : α), 0 ≤ ∥f a∥ := by filter_upwards [] λa, norm_nonneg _, classical.by_cases ( λh : measurable f, calc ∥(∫ a, f a)∥ ≤ ennreal.to_real (∫⁻ a, ennreal.of_real ∥f a∥) : norm_integral_le_lintegral_norm _ ... = ∫ a, ∥f a∥ : (integral_eq_lintegral_of_nonneg_ae le_ae $ measurable.norm h).symm ) ( λh : ¬measurable f, begin rw [integral_non_measurable h, _root_.norm_zero], exact integral_nonneg_of_ae le_ae end ) lemma integral_finset_sum {ι} (s : finset ι) {f : ι → α → β} (hfm : ∀ i, measurable (f i)) (hfi : ∀ i, integrable (f i)) : (∫ a, s.sum (λ i, f i a)) = s.sum (λ i, ∫ a, f i a) := begin refine finset.induction_on s _ _, { simp only [integral_zero, finset.sum_empty] }, { assume i s his ih, simp only [his, finset.sum_insert, not_false_iff], rw [integral_add (hfm _) (hfi _) (s.measurable_sum hfm) (integrable_finset_sum s hfm hfi), ih] } end end properties mk_simp_attribute integral_simps "Simp set for integral rules." attribute [integral_simps] integral_neg integral_smul l1.integral_add l1.integral_sub l1.integral_smul l1.integral_neg attribute [irreducible] integral l1.integral end measure_theory
5d59ab19473dd986820cd55cde34c310c083be88
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/stage0/src/Lean/Meta/Tactic/Apply.lean
676606648fe46a5c9b19d24eb71d33cfab3d3f8e
[ "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
4,937
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.FindMVar import Lean.Meta.ExprDefEq import Lean.Meta.SynthInstance import Lean.Meta.CollectMVars import Lean.Meta.Tactic.Util namespace Lean.Meta /- Compute the number of expected arguments and whether the result type is of the form (?m ...) where ?m is an unassigned metavariable. -/ def getExpectedNumArgsAux (e : Expr) : MetaM (Nat × Bool) := withDefault <| forallTelescopeReducing e fun xs body => pure (xs.size, body.getAppFn.isMVar) def getExpectedNumArgs (e : Expr) : MetaM Nat := do let (numArgs, _) ← getExpectedNumArgsAux e pure numArgs private def throwApplyError {α} (mvarId : MVarId) (eType : Expr) (targetType : Expr) : MetaM α := throwTacticEx `apply mvarId m!"failed to unify{indentExpr eType}\nwith{indentExpr targetType}" def synthAppInstances (tacticName : Name) (mvarId : MVarId) (newMVars : Array Expr) (binderInfos : Array BinderInfo) : MetaM Unit := newMVars.size.forM fun i => do if binderInfos[i].isInstImplicit then let mvar := newMVars[i] let mvarType ← inferType mvar let mvarVal ← synthInstance mvarType unless (← isDefEq mvar mvarVal) do throwTacticEx tacticName mvarId "failed to assign synthesized instance" def appendParentTag (mvarId : MVarId) (newMVars : Array Expr) (binderInfos : Array BinderInfo) : MetaM Unit := do let parentTag ← getMVarTag mvarId if newMVars.size == 1 then -- if there is only one subgoal, we inherit the parent tag setMVarTag newMVars[0].mvarId! parentTag else unless parentTag.isAnonymous do newMVars.size.forM fun i => do let newMVarId := newMVars[i].mvarId! unless (← isExprMVarAssigned newMVarId) do unless binderInfos[i].isInstImplicit do let currTag ← getMVarTag newMVarId setMVarTag newMVarId (appendTag parentTag currTag) def postprocessAppMVars (tacticName : Name) (mvarId : MVarId) (newMVars : Array Expr) (binderInfos : Array BinderInfo) : MetaM Unit := do synthAppInstances tacticName mvarId newMVars binderInfos -- TODO: default and auto params appendParentTag mvarId newMVars binderInfos private def dependsOnOthers (mvar : Expr) (otherMVars : Array Expr) : MetaM Bool := otherMVars.anyM fun otherMVar => do if mvar == otherMVar then pure false else let otherMVarType ← inferType otherMVar return (otherMVarType.findMVar? fun mvarId => mvarId == mvar.mvarId!).isSome private def reorderNonDependentFirst (newMVars : Array Expr) : MetaM (List MVarId) := do let (nonDeps, deps) ← newMVars.foldlM (init := (#[], #[])) fun (nonDeps, deps) mvar => do let currMVarId := mvar.mvarId! if (← dependsOnOthers mvar newMVars) then pure (nonDeps, deps.push currMVarId) else pure (nonDeps.push currMVarId, deps) return nonDeps.toList ++ deps.toList inductive ApplyNewGoals where | nonDependentFirst | nonDependentOnly | all def apply (mvarId : MVarId) (e : Expr) : MetaM (List MVarId) := withMVarContext mvarId do checkNotAssigned mvarId `apply let targetType ← getMVarType mvarId let eType ← inferType e let mut (numArgs, hasMVarHead) ← getExpectedNumArgsAux eType unless hasMVarHead do let targetTypeNumArgs ← getExpectedNumArgs targetType numArgs := numArgs - targetTypeNumArgs let (newMVars, binderInfos, eType) ← forallMetaTelescopeReducing eType (some numArgs) unless (← isDefEq eType targetType) do throwApplyError mvarId eType targetType postprocessAppMVars `apply mvarId newMVars binderInfos let e ← instantiateMVars e assignExprMVar mvarId (mkAppN e newMVars) let newMVars ← newMVars.filterM fun mvar => not <$> isExprMVarAssigned mvar.mvarId! let otherMVarIds ← getMVarsNoDelayed e -- TODO: add option `ApplyNewGoals` and implement other orders let newMVarIds ← reorderNonDependentFirst newMVars let otherMVarIds := otherMVarIds.filter fun mvarId => !newMVarIds.contains mvarId let result := newMVarIds ++ otherMVarIds.toList result.forM headBetaMVarType return result def splitAnd (mvarId : MVarId) : MetaM (List MVarId) := do saturate mvarId fun mvarId => observing? <| apply mvarId (mkConst ``And.intro) def applyRefl (mvarId : MVarId) (msg : MessageData := "refl failed") : MetaM Unit := withMVarContext mvarId do let some [] ← observing? do apply mvarId (mkConst ``Eq.refl [← mkFreshLevelMVar]) | throwTacticEx `refl mvarId msg def exfalso (mvarId : MVarId) (msg : MessageData := "exfalso failed") : MetaM MVarId := withMVarContext mvarId do let some [mvarId] ← observing? do apply mvarId (mkConst ``False.elim [← mkFreshLevelMVar]) | throwTacticEx `exfalso mvarId msg return mvarId end Lean.Meta
2f9099f51436b712671f880e3a84ec0f54e89310
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/topology/algebra/affine.lean
2df7d8a5d3e4ce8638b83d03ec84ba59851fcf79
[ "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
1,332
lean
/- Copyright (c) 2020 Frédéric Dupuis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Frédéric Dupuis -/ import topology.algebra.continuous_functions import linear_algebra.affine_space.basic /-! # Topological properties of affine spaces and maps For now, this contains only a few facts regarding the continuity of affine maps in the special case when the point space and vector space are the same. -/ variables {R E F : Type*} [ring R] [add_comm_group E] [semimodule R E] [topological_space E] [add_comm_group F] [semimodule R F] [topological_space F] [topological_add_group F] namespace affine_map /- TODO: Deal with the case where the point spaces are different from the vector spaces. -/ /-- An affine map is continuous iff its underlying linear map is continuous. -/ lemma continuous_iff {f : affine_map R E F} : continuous f ↔ continuous f.linear := begin split, { intro hc, rw decomp' f, exact hc.sub continuous_const }, { intro hc, rw decomp f, exact hc.add continuous_const } end /-- The line map is continuous. -/ lemma line_map_continuous [topological_space R] [topological_semimodule R F] {p v : F} : continuous ⇑(line_map p v : affine_map R R F) := continuous_iff.mpr $ continuous_id.smul continuous_const end affine_map
eacc689ceafe8bb7d90eaec891509e582e5abdca
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/ordering/default.lean
4c7fc9bd2185dc667f998f385e71bb7205a5b473
[]
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
308
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 -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.data.ordering.basic import Mathlib.Lean3Lib.init.data.ordering.lemmas namespace Mathlib
57d72a4041c7c497bb7c1e42a0dc8bc229610d5f
f313d4982feee650661f61ed73f0cb6635326350
/Mathlib/Tactic/Block.lean
73075aeda1aa7fbca6f81b609682563d4ea030f3
[ "Apache-2.0" ]
permissive
shingtaklam1324/mathlib4
38c6e172eec1385944db5a70a3b5545c924980ee
50610c343b7065e8eec056d641f859ceed608e69
refs/heads/master
1,683,032,333,313
1,621,942,699,000
1,621,942,699,000
371,130,608
0
0
Apache-2.0
1,622,053,166,000
1,622,053,166,000
null
UTF-8
Lean
false
false
2,232
lean
/- Copyright (c) 2021 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import Mathlib.Tactic.OpenPrivate import Lean.Elab.Tactic.Basic /- This file adds support for a block structuring tactic. Blocks are started by an initial `-` and all tactics in the same indentation level are part of a block: ``` - tac1 tac2 tac3 ``` In this version, `tac1` produces two subgoals that are handled by `tac2` and `tac3` respectively: ``` - tac1 - tac2 - tac3 ``` Blocks are a simple way to make it clear where and how goals are produced and discharged. Furthermore, errors in one block do not affect the processing of the rest of the proof: every block always discharges the goal it is tasked with, and will report a (non-fatal) error if not all subgoals are handled. Note: until https://github.com/leanprover/lean4/issues/451 is resolved, tactics that end in an expression will break this parser, so you have to put parentheses around the tactic like so: ``` (apply And.intro) - subgoal - subgoal ``` -/ namespace Lean namespace Elab namespace Tactic /- Close the main goal using the given tactic. If it fails, log the error and `admit` all remaining goals -/ def closeAllOrAdmit : TacticM Unit := do let gs ← getUnsolvedGoals unless gs.isEmpty do try Term.reportUnsolvedGoals gs catch ex => logException ex for g in gs do admitGoal g setGoals [] /- Focus the goal, i.e. suppress all goals except the main goal, run `tac`, then admit any unproven goals and restore the remaining goals. -/ def focusAndBlock (tac : TacticM Unit) : TacticM Unit := do let mvarId :: mvarIds ← getUnsolvedGoals | throwNoGoalsToBeSolved setGoals [mvarId] try tac catch ex => logException ex closeAllOrAdmit setGoals mvarIds open private evalManyTacticOptSemi in evalTacticSeq1Indented in -- TODO: why doesn't `tacticSeq?` work here? elab (name := block) "-"%tk tacs:optional(tacticSeq) : tactic => withRef tk $ do focusAndBlock $ do if let some stx := tacs then evalTacticSeq stx end Tactic end Elab end Lean /- example : (0 < 1 ∧ 2 < 3) ∧ 3 < 4 := by split - split - decide - decide - decide -/
e185bd9d77a6dfda03f69784181fea7d44b9d636
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/tropical/basic.lean
7de3e71929503b5258045e99011eb9cb7d7dcbea
[ "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
12,136
lean
/- Copyright (c) 2021 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import algebra.group_power.order import algebra.smul_with_zero /-! # Tropical algebraic structures This file defines algebraic structures of the (min-)tropical numbers, up to the tropical semiring. Some basic lemmas about conversion from the base type `R` to `tropical R` are provided, as well as the expected implementations of tropical addition and tropical multiplication. ## Main declarations * `tropical R`: The type synonym of the tropical interpretation of `R`. If `[linear_order R]`, then addition on `R` is via `min`. * `semiring (tropical R)`: A `linear_ordered_add_comm_monoid_with_top R` induces a `semiring (tropical R)`. If one solely has `[linear_ordered_add_comm_monoid R]`, then the "tropicalization of `R`" would be `tropical (with_top R)`. ## Implementation notes The tropical structure relies on `has_top` and `min`. For the max-tropical numbers, use `order_dual R`. Inspiration was drawn from the implementation of `additive`/`multiplicative`/`opposite`, where a type synonym is created with some barebones API, and quickly made irreducible. Algebraic structures are provided with as few typeclass assumptions as possible, even though most references rely on `semiring (tropical R)` for building up the whole theory. ## References followed * https://arxiv.org/pdf/math/0408099.pdf * https://www.mathenjeans.fr/sites/default/files/sujets/tropical_geometry_-_casagrande.pdf -/ universes u v variables (R : Type u) /-- The tropicalization of a type `R`. -/ def tropical : Type u := R variables {R} namespace tropical /-- Reinterpret `x : R` as an element of `tropical R`. See `tropical.trop_equiv` for the equivalence. -/ @[pp_nodot] def trop : R → tropical R := id /-- Reinterpret `x : tropical R` as an element of `R`. See `tropical.trop_equiv` for the equivalence. -/ @[pp_nodot] def untrop : tropical R → R := id lemma trop_injective : function.injective (trop : R → tropical R) := λ _ _, id lemma untrop_injective : function.injective (untrop : tropical R → R) := λ _ _, id @[simp] lemma trop_inj_iff (x y : R) : trop x = trop y ↔ x = y := iff.rfl @[simp] lemma untrop_inj_iff (x y : tropical R) : untrop x = untrop y ↔ x = y := iff.rfl @[simp] lemma trop_untrop (x : tropical R) : trop (untrop x) = x := rfl @[simp] lemma untrop_trop (x : R) : untrop (trop x) = x := rfl lemma left_inverse_trop : function.left_inverse (trop : R → tropical R) untrop := trop_untrop lemma right_inverse_trop : function.right_inverse (trop : R → tropical R) untrop := trop_untrop attribute [irreducible] tropical /-- Reinterpret `x : R` as an element of `tropical R`. See `tropical.trop_order_iso` for the order-preserving equivalence. -/ def trop_equiv : R ≃ tropical R := { to_fun := trop, inv_fun := untrop, left_inv := untrop_trop, right_inv := trop_untrop } @[simp] lemma trop_equiv_coe_fn : (trop_equiv : R → tropical R) = trop := rfl @[simp] lemma trop_equiv_symm_coe_fn : (trop_equiv.symm : tropical R → R) = untrop := rfl lemma trop_eq_iff_eq_untrop {x : R} {y} : trop x = y ↔ x = untrop y := trop_equiv.apply_eq_iff_eq_symm_apply lemma untrop_eq_iff_eq_trop {x} {y : R} : untrop x = y ↔ x = trop y := trop_equiv.symm.apply_eq_iff_eq_symm_apply lemma injective_trop : function.injective (trop : R → tropical R) := trop_equiv.injective lemma injective_untrop : function.injective (untrop : tropical R → R) := trop_equiv.symm.injective lemma surjective_trop : function.surjective (trop : R → tropical R) := trop_equiv.surjective lemma surjective_untrop : function.surjective (untrop : tropical R → R) := trop_equiv.symm.surjective instance [inhabited R] : inhabited (tropical R) := ⟨trop (default _)⟩ /-- Recursing on a `x' : tropical R` is the same as recursing on an `x : R` reinterpreted as a term of `tropical R` via `trop x`. -/ @[simp] def trop_rec {F : Π (X : tropical R), Sort v} (h : Π X, F (trop X)) : Π X, F X := λ X, h (untrop X) section order instance [preorder R] : preorder (tropical R) := { le := λ x y, untrop x ≤ untrop y, le_refl := λ _, le_refl _, le_trans := λ _ _ _ h h', le_trans h h', } @[simp] lemma untrop_le_iff [preorder R] {x y : tropical R} : untrop x ≤ untrop y ↔ x ≤ y := iff.rfl /-- Reinterpret `x : R` as an element of `tropical R`, preserving the order. -/ def trop_order_iso [preorder R] : R ≃o tropical R := { map_rel_iff' := λ _ _, untrop_le_iff, ..trop_equiv } @[simp] lemma trop_order_iso_coe_fn [preorder R] : (trop_order_iso : R → tropical R) = trop := rfl @[simp] lemma trop_order_iso_symm_coe_fn [preorder R] : (trop_order_iso.symm : tropical R → R) = untrop := rfl instance [partial_order R] : partial_order (tropical R) := { le_antisymm := λ _ _ h h', untrop_injective (le_antisymm h h'), ..tropical.preorder } instance [has_top R] : has_zero (tropical R) := ⟨trop ⊤⟩ instance [has_top R] : has_top (tropical R) := ⟨0⟩ @[simp] lemma untrop_zero [has_top R] : untrop (0 : tropical R) = ⊤ := rfl @[simp] lemma trop_top [has_top R] : trop (⊤ : R) = 0 := rfl @[simp] lemma trop_coe_ne_zero (x : R) : trop (x : with_top R) ≠ 0 . @[simp] lemma zero_ne_trop_coe (x : R) : (0 : tropical (with_top R)) ≠ trop x . -- TODO: generalize to `has_le` @[simp] lemma le_zero [preorder R] [order_top R] (x : tropical R) : x ≤ 0 := le_top instance [partial_order R] : order_top (tropical (with_top R)) := { le_top := λ a a' h, option.no_confusion h, ..tropical.partial_order, ..tropical.has_top } variable [linear_order R] /-- Tropical addition is the minimum of two underlying elements of `R`. -/ protected def add (x y : tropical R) : tropical R := trop (min (untrop x) (untrop y)) instance : add_comm_semigroup (tropical R) := { add := tropical.add, add_assoc := λ _ _ _, untrop_injective (min_assoc _ _ _), add_comm := λ _ _, untrop_injective (min_comm _ _) } instance : linear_order (tropical R) := { le_total := λ a b, le_total (untrop a) (untrop b), decidable_le := λ x y, if h : (untrop x) ≤ (untrop y) then is_true h else is_false h, ..tropical.partial_order } @[simp] lemma untrop_add (x y : tropical R) : untrop (x + y) = min (untrop x) (untrop y) := rfl lemma trop_add_def (x y : tropical R) : x + y = trop (min (untrop x) (untrop y)) := rfl @[simp] lemma add_eq_left ⦃x y : tropical R⦄ (h : x ≤ y) : x + y = x := untrop_injective (by simpa using h) @[simp] lemma add_eq_right ⦃x y : tropical R⦄ (h : y ≤ x) : x + y = y := untrop_injective (by simpa using h) @[simp] lemma add_self (x : tropical R) : x + x = x := untrop_injective (min_eq_right le_rfl) @[simp] lemma bit0 (x : tropical R) : bit0 x = x := add_self x lemma add_eq_iff {x y z : tropical R} : x + y = z ↔ x = z ∧ x ≤ y ∨ y = z ∧ y ≤ x := by simp [trop_add_def, trop_eq_iff_eq_untrop, min_eq_iff] @[simp] lemma add_eq_zero_iff {a b : tropical (with_top R)} : a + b = 0 ↔ a = 0 ∧ b = 0 := begin rw add_eq_iff, split, { rintro (⟨rfl, h⟩|⟨rfl, h⟩), { exact ⟨rfl, le_antisymm (le_zero _) h⟩ }, { exact ⟨le_antisymm (le_zero _) h, rfl⟩ } }, { rintro ⟨rfl, rfl⟩, simp } end -- We cannot define `add_comm_monoid` here because there is no class that is solely -- `[linear_order R] [order_top R]` end order section monoid /-- Tropical multiplication is the addition in the underlying `R`. -/ protected def mul [has_add R] (x y : tropical R) : tropical R := trop (untrop x + untrop y) instance [has_add R] : has_mul (tropical R) := ⟨tropical.mul⟩ @[simp] lemma untrop_mul [has_add R] (x y : tropical R) : untrop (x * y) = untrop x + untrop y := rfl lemma trop_mul_def [has_add R] (x y : tropical R) : x * y = trop (untrop x + untrop y) := rfl instance [has_zero R] : has_one (tropical R) := ⟨trop 0⟩ instance [has_zero R] : nontrivial (tropical (with_top R)) := ⟨⟨0, 1, trop_injective.ne with_top.top_ne_coe⟩⟩ instance [has_neg R] : has_inv (tropical R) := ⟨λ x, trop (- untrop x)⟩ @[simp] lemma untrop_inv [has_neg R] (x : tropical R) : untrop x⁻¹ = - untrop x := rfl instance [has_sub R] : has_div (tropical R) := ⟨λ x y, trop (untrop x - untrop y)⟩ @[simp] lemma untrop_div [has_sub R] (x y : tropical R) : untrop (x / y) = untrop x - untrop y := rfl instance [add_semigroup R] : semigroup (tropical R) := { mul := tropical.mul, mul_assoc := λ _ _ _, untrop_injective (add_assoc _ _ _) } instance [add_comm_semigroup R] : comm_semigroup (tropical R) := { mul_comm := λ _ _, untrop_injective (add_comm _ _), ..tropical.semigroup } instance [add_monoid R] : monoid (tropical R) := { one := trop 0, one_mul := λ _, untrop_injective (zero_add _), mul_one := λ _, untrop_injective (add_zero _), ..tropical.semigroup } @[simp] lemma untrop_one [add_monoid R] : untrop (1 : tropical R) = 0 := rfl @[simp] lemma untrop_pow [add_monoid R] (x : tropical R) (n : ℕ) : untrop (x ^ n) = n • untrop x := begin induction n with n IH, { simp, }, { rw [pow_succ, untrop_mul, IH, succ_nsmul] } end @[simp] lemma trop_nsmul [add_monoid R] (x : R) (n : ℕ) : trop (n • x) = trop x ^ n := by simp [trop_eq_iff_eq_untrop] instance [add_comm_monoid R] : comm_monoid (tropical R) := { ..tropical.monoid, ..tropical.comm_semigroup } instance [add_group R] : group (tropical R) := { inv := λ x, trop (- untrop x), mul_left_inv := λ _, untrop_injective (add_left_neg _), ..tropical.monoid } instance [add_comm_group R] : comm_group (tropical R) := { mul_comm := λ _ _, untrop_injective (add_comm _ _), ..tropical.group } end monoid section distrib instance covariant_mul [preorder R] [has_add R] [covariant_class R R (+) (≤)] : covariant_class (tropical R) (tropical R) (*) (≤) := ⟨λ x y z h, add_le_add_left h _⟩ instance covariant_swap_mul [preorder R] [has_add R] [covariant_class R R (function.swap (+)) (≤)] : covariant_class (tropical R) (tropical R) (function.swap (*)) (≤) := ⟨λ x y z h, add_le_add_right h _⟩ instance [linear_order R] [has_add R] [covariant_class R R (+) (≤)] [covariant_class R R (function.swap (+)) (≤)] : distrib (tropical R) := { mul := tropical.mul, add := tropical.add, left_distrib := λ _ _ _, untrop_injective (min_add_add_left _ _ _).symm, right_distrib := λ _ _ _, untrop_injective (min_add_add_right _ _ _).symm } @[simp] lemma add_pow [linear_order R] [add_monoid R] [covariant_class R R (+) (≤)] [covariant_class R R (function.swap (+)) (≤)] (x y : tropical R) (n : ℕ) : (x + y) ^ n = x ^ n + y ^ n := begin cases le_total x y with h h, { rw [add_eq_left h, add_eq_left (pow_le_pow_of_le_left' h _)] }, { rw [add_eq_right h, add_eq_right (pow_le_pow_of_le_left' h _)] } end end distrib section semiring variable [linear_ordered_add_comm_monoid_with_top R] instance : comm_semiring (tropical R) := { zero_add := λ _, untrop_injective (min_top_left _), add_zero := λ _, untrop_injective (min_top_right _), zero_mul := λ _, untrop_injective (top_add _), mul_zero := λ _, untrop_injective (add_top _), ..tropical.has_zero, ..tropical.distrib, ..tropical.add_comm_semigroup, ..tropical.comm_monoid } -- This could be stated on something like `linear_order_with_top α` if that existed @[simp] lemma succ_nsmul (x : tropical R) (n : ℕ) : (n + 1) • x = x := begin induction n with n IH, { simp }, { rw [add_nsmul, IH, one_nsmul, add_self] } end -- TODO: find/create the right classes to make this hold (for enat, ennreal, etc) -- Requires `zero_eq_bot` to be true -- lemma add_eq_zero_iff {a b : tropical R} : -- a + b = 1 ↔ a = 1 ∨ b = 1 := sorry @[simp] lemma mul_eq_zero_iff {R : Type*} [linear_ordered_add_comm_monoid R] {a b : tropical (with_top R)} : a * b = 0 ↔ a = 0 ∨ b = 0 := by simp [←untrop_inj_iff, with_top.add_eq_top] instance {R : Type*} [linear_ordered_add_comm_monoid R] : no_zero_divisors (tropical (with_top R)) := ⟨λ _ _, mul_eq_zero_iff.mp⟩ end semiring end tropical
b675adc0089795a2d24e9111372658104ad6ae9e
fecda8e6b848337561d6467a1e30cf23176d6ad0
/src/dynamics/circle/rotation_number/translation_number.lean
de5ebee5653d76482c809646bab5e7e68d680a52
[ "Apache-2.0" ]
permissive
spolu/mathlib
bacf18c3d2a561d00ecdc9413187729dd1f705ed
480c92cdfe1cf3c2d083abded87e82162e8814f4
refs/heads/master
1,671,684,094,325
1,600,736,045,000
1,600,736,045,000
297,564,749
1
0
null
1,600,758,368,000
1,600,758,367,000
null
UTF-8
Lean
false
false
28,243
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Yury G. Kudryashov -/ import analysis.specific_limits import order.iterate import algebra.iterate_hom /-! # Translation number of a monotone real map that commutes with `x ↦ x + 1` Let `f : ℝ → ℝ` be a monotone map such that `f (x + 1) = f x + 1` for all `x`. Then the limit $$ \tau(f)=\lim_{n\to\infty}{f^n(x)-x}{n} $$ exists and does not depend on `x`. This number is called the *translation number* of `f`. Different authors use different notation for this number: `τ`, `ρ`, `rot`, etc In this file we define a structure `circle_deg1_lift` for bundled maps with these properties, define translation number of `f : circle_deg1_lift`, prove some estimates relating `f^n(x)-x` to `τ(f)`. In case of a continuous map `f` we also prove that `f` admits a point `x` such that `f^n(x)=x+m` if and only if `τ(f)=m/n`. Maps of this type naturally appear as lifts of orientation preserving circle homeomorphisms. More precisely, let `f` be an orientation preserving homeomorphism of the circle $S^1=ℝ/ℤ$, and consider a real number `a` such that `⟦a⟧ = f 0`, where `⟦⟧` means the natural projection `ℝ → ℝ/ℤ`. Then there exists a unique continuous function `F : ℝ → ℝ` such that `F 0 = a` and `⟦F x⟧ = f ⟦x⟧` for all `x` (this fact is not formalized yet). This function is strictly monotone, continuous, and satisfies `F (x + 1) = F x + 1`. The number `⟦τ F⟧ : ℝ / ℤ` is called the *rotation number* of `f`. It does not depend on the choice of `a`. We chose to define translation number for a wider class of maps `f : ℝ → ℝ` for two reasons: * non-strictly monotone circle self-maps with discontinuities naturally appear as Poincaré maps for some flows on the two-torus (e.g., one can take a constant flow and glue in a few Cherry cells); * definition and some basic properties still work for this class. ## Notation We use a local notation `τ` for the translation number of `f : circle_deg1_lift`. ## Tags circle homeomorphism, rotation number -/ open filter set open_locale topological_space classical /-! ### Definition and monoid structure -/ /-- A lift of a monotone degree one map `S¹ → S¹`. -/ structure circle_deg1_lift : Type := (to_fun : ℝ → ℝ) (monotone' : monotone to_fun) (map_add_one' : ∀ x, to_fun (x + 1) = to_fun x + 1) namespace circle_deg1_lift instance : has_coe_to_fun circle_deg1_lift := ⟨λ _, ℝ → ℝ, circle_deg1_lift.to_fun⟩ @[simp] lemma coe_mk (f h₁ h₂) : ⇑(mk f h₁ h₂) = f := rfl variables (f g : circle_deg1_lift) protected lemma monotone : monotone f := f.monotone' @[mono] lemma mono {x y} (h : x ≤ y) : f x ≤ f y := f.monotone h @[simp] lemma map_add_one : ∀ x, f (x + 1) = f x + 1 := f.map_add_one' @[simp] lemma map_one_add (x : ℝ) : f (1 + x) = 1 + f x := by rw [add_comm, map_add_one, add_comm] theorem coe_inj : ∀ ⦃f g : circle_deg1_lift ⦄, (f : ℝ → ℝ) = g → f = g := assume ⟨f, fm, fd⟩ ⟨g, gm, gd⟩ h, by congr; exact h @[ext] theorem ext ⦃f g : circle_deg1_lift ⦄ (h : ∀ x, f x = g x) : f = g := coe_inj $ funext h theorem ext_iff {f g : circle_deg1_lift} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ instance : monoid circle_deg1_lift := { mul := λ f g, { to_fun := f ∘ g, monotone' := f.monotone.comp g.monotone, map_add_one' := λ x, by simp [map_add_one] }, one := ⟨id, monotone_id, λ _, rfl⟩, mul_one := λ f, coe_inj $ function.comp.right_id f, one_mul := λ f, coe_inj $ function.comp.left_id f, mul_assoc := λ f₁ f₂ f₃, coe_inj rfl } instance : inhabited circle_deg1_lift := ⟨1⟩ @[simp] lemma coe_mul : ⇑(f * g) = f ∘ g := rfl lemma mul_apply (x) : (f * g) x = f (g x) := rfl @[simp] lemma coe_one : ⇑(1 : circle_deg1_lift) = id := rfl instance units_has_coe_to_fun : has_coe_to_fun (units circle_deg1_lift) := ⟨λ _, ℝ → ℝ, λ f, ⇑(f : circle_deg1_lift)⟩ @[simp, norm_cast] lemma units_coe (f : units circle_deg1_lift) : ⇑(f : circle_deg1_lift) = f := rfl lemma coe_pow : ∀ n : ℕ, ⇑(f^n) = (f^[n]) | 0 := rfl | (n+1) := by {ext x, simp [coe_pow n, pow_succ'] } lemma semiconj_by_iff_semiconj {f g₁ g₂ : circle_deg1_lift} : semiconj_by f g₁ g₂ ↔ function.semiconj f g₁ g₂ := ext_iff lemma commute_iff_commute {f g : circle_deg1_lift} : commute f g ↔ function.commute f g := ext_iff /-! ### Translate by a constant -/ /-- The map `y ↦ x + y` as a `circle_deg1_lift`. More precisely, we define a homomorphism from `multiplicative ℝ` to `units circle_deg1_lift`, so the translation by `x` is `translation (multiplicative.of_add x)`. -/ def translate : multiplicative ℝ →* units circle_deg1_lift := by refine (units.map _).comp to_units.to_monoid_hom; exact { to_fun := λ x, ⟨λ y, x.to_add + y, λ y₁ y₂ h, add_le_add_left h _, λ y, (add_assoc _ _ _).symm⟩, map_one' := ext $ zero_add, map_mul' := λ x y, ext $ add_assoc _ _ } @[simp] lemma translate_apply (x y : ℝ) : translate (multiplicative.of_add x) y = x + y := rfl @[simp] lemma translate_inv_apply (x y : ℝ) : (translate $ multiplicative.of_add x)⁻¹ y = -x + y := rfl @[simp] lemma translate_gpow (x : ℝ) (n : ℤ) : (translate (multiplicative.of_add x))^n = translate (multiplicative.of_add $ n * x) := by simp only [← gsmul_eq_mul, of_add_gsmul, monoid_hom.map_gpow] @[simp] lemma translate_pow (x : ℝ) (n : ℕ) : (translate (multiplicative.of_add x))^n = translate (multiplicative.of_add $ n * x) := translate_gpow x n @[simp] lemma translate_iterate (x : ℝ) (n : ℕ) : (translate (multiplicative.of_add x))^[n] = translate (multiplicative.of_add $ n * x) := by rw [← units_coe, ← coe_pow, ← units.coe_pow, translate_pow, units_coe] /-! ### Commutativity with integer translations In this section we prove that `f` commutes with translations by an integer number. First we formulate these statements (for a natural or an integer number, addition on the left or on the right, addition or subtraction) using `function.commute`, then reformulate as `simp` lemmas `map_int_add` etc. -/ lemma commute_nat_add (n : ℕ) : function.commute f ((+) n) := by simpa only [nsmul_one, add_left_iterate] using function.commute.iterate_right f.map_one_add n lemma commute_add_nat (n : ℕ) : function.commute f (λ x, x + n) := by simp only [add_comm _ (n:ℝ), f.commute_nat_add n] lemma commute_sub_nat (n : ℕ) : function.commute f (λ x, x - n) := (f.commute_add_nat n).inverses_right (equiv.add_right _).right_inv (equiv.add_right _).left_inv lemma commute_add_int : ∀ n : ℤ, function.commute f (λ x, x + n) | (n:ℕ) := f.commute_add_nat n | -[1+n] := f.commute_sub_nat (n + 1) lemma commute_int_add (n : ℤ) : function.commute f ((+) n) := by simpa only [add_comm _ (n:ℝ)] using f.commute_add_int n lemma commute_sub_int (n : ℤ) : function.commute f (λ x, x - n) := (f.commute_add_int n).inverses_right (equiv.add_right _).right_inv (equiv.add_right _).left_inv @[simp] lemma map_int_add (m : ℤ) (x : ℝ) : f (m + x) = m + f x := f.commute_int_add m x @[simp] lemma map_add_int (x : ℝ) (m : ℤ) : f (x + m) = f x + m := f.commute_add_int m x @[simp] lemma map_sub_int (x : ℝ) (n : ℤ) : f (x - n) = f x - n := f.commute_sub_int n x @[simp] lemma map_add_nat (x : ℝ) (n : ℕ) : f (x + n) = f x + n := f.map_add_int x n @[simp] lemma map_nat_add (n : ℕ) (x : ℝ) : f (n + x) = n + f x := f.map_int_add n x @[simp] lemma map_sub_nat (x : ℝ) (n : ℕ) : f (x - n) = f x - n := f.map_sub_int x n lemma map_int_of_map_zero (n : ℤ) : f n = f 0 + n := by rw [← f.map_add_int, zero_add] @[simp] lemma map_fract_sub_fract_eq (x : ℝ) : f (fract x) - fract x = f x - x := by conv_rhs { rw [← fract_add_floor x, f.map_add_int, add_sub_comm, sub_self, add_zero] } /-! ### Pointwise order on circle maps -/ /-- Monotone circle maps form a lattice with respect to the pointwise order -/ noncomputable instance : lattice circle_deg1_lift := { sup := λ f g, { to_fun := λ x, max (f x) (g x), monotone' := λ x y h, max_le_max (f.mono h) (g.mono h), -- TODO: generalize to `monotone.max` map_add_one' := λ x, by simp [max_add_add_right] }, le := λ f g, ∀ x, f x ≤ g x, le_refl := λ f x, le_refl (f x), le_trans := λ f₁ f₂ f₃ h₁₂ h₂₃ x, le_trans (h₁₂ x) (h₂₃ x), le_antisymm := λ f₁ f₂ h₁₂ h₂₁, ext $ λ x, le_antisymm (h₁₂ x) (h₂₁ x), le_sup_left := λ f g x, le_max_left (f x) (g x), le_sup_right := λ f g x, le_max_right (f x) (g x), sup_le := λ f₁ f₂ f₃ h₁ h₂ x, max_le (h₁ x) (h₂ x), inf := λ f g, { to_fun := λ x, min (f x) (g x), monotone' := λ x y h, min_le_min (f.mono h) (g.mono h), map_add_one' := λ x, by simp [min_add_add_right] }, inf_le_left := λ f g x, min_le_left (f x) (g x), inf_le_right := λ f g x, min_le_right (f x) (g x), le_inf := λ f₁ f₂ f₃ h₂ h₃ x, le_min (h₂ x) (h₃ x) } @[simp] lemma sup_apply (x : ℝ) : (f ⊔ g) x = max (f x) (g x) := rfl @[simp] lemma inf_apply (x : ℝ) : (f ⊓ g) x = min (f x) (g x) := rfl lemma iterate_monotone (n : ℕ) : monotone (λ f : circle_deg1_lift, f^[n]) := λ f g h, f.monotone.iterate_le_of_le h _ lemma iterate_mono {f g : circle_deg1_lift} (h : f ≤ g) (n : ℕ) : f^[n] ≤ (g^[n]) := iterate_monotone n h lemma pow_mono {f g : circle_deg1_lift} (h : f ≤ g) (n : ℕ) : f^n ≤ g^n := λ x, by simp only [coe_pow, iterate_mono h n x] lemma pow_monotone (n : ℕ) : monotone (λ f : circle_deg1_lift, f^n) := λ f g h, pow_mono h n /-! ### Estimates on `(f * g) 0` We prove the estimates `f 0 + ⌊g 0⌋ ≤ f (g 0) ≤ f 0 + ⌈g 0⌉` and some corollaries with added/removed floors and ceils. We also prove that for two semiconjugate maps `g₁`, `g₂`, the distance between `g₁ 0` and `g₂ 0` is less than two. -/ lemma map_le_of_map_zero (x : ℝ) : f x ≤ f 0 + ⌈x⌉ := calc f x ≤ f ⌈x⌉ : f.monotone $ le_ceil _ ... = f 0 + ⌈x⌉ : f.map_int_of_map_zero _ lemma map_map_zero_le : f (g 0) ≤ f 0 + ⌈g 0⌉ := f.map_le_of_map_zero (g 0) lemma floor_map_map_zero_le : ⌊f (g 0)⌋ ≤ ⌊f 0⌋ + ⌈g 0⌉ := calc ⌊f (g 0)⌋ ≤ ⌊f 0 + ⌈g 0⌉⌋ : floor_mono $ f.map_map_zero_le g ... = ⌊f 0⌋ + ⌈g 0⌉ : floor_add_int _ _ lemma ceil_map_map_zero_le : ⌈f (g 0)⌉ ≤ ⌈f 0⌉ + ⌈g 0⌉ := calc ⌈f (g 0)⌉ ≤ ⌈f 0 + ⌈g 0⌉⌉ : ceil_mono $ f.map_map_zero_le g ... = ⌈f 0⌉ + ⌈g 0⌉ : ceil_add_int _ _ lemma map_map_zero_lt : f (g 0) < f 0 + g 0 + 1 := calc f (g 0) ≤ f 0 + ⌈g 0⌉ : f.map_map_zero_le g ... < f 0 + (g 0 + 1) : add_lt_add_left (ceil_lt_add_one _) _ ... = f 0 + g 0 + 1 : (add_assoc _ _ _).symm lemma le_map_of_map_zero (x : ℝ) : f 0 + ⌊x⌋ ≤ f x := calc f 0 + ⌊x⌋ = f ⌊x⌋ : (f.map_int_of_map_zero _).symm ... ≤ f x : f.monotone $ floor_le _ lemma le_map_map_zero : f 0 + ⌊g 0⌋ ≤ f (g 0) := f.le_map_of_map_zero (g 0) lemma le_floor_map_map_zero : ⌊f 0⌋ + ⌊g 0⌋ ≤ ⌊f (g 0)⌋ := calc ⌊f 0⌋ + ⌊g 0⌋ = ⌊f 0 + ⌊g 0⌋⌋ : (floor_add_int _ _).symm ... ≤ ⌊f (g 0)⌋ : floor_mono $ f.le_map_map_zero g lemma le_ceil_map_map_zero : ⌈f 0⌉ + ⌊g 0⌋ ≤ ⌈(f * g) 0⌉ := calc ⌈f 0⌉ + ⌊g 0⌋ = ⌈f 0 + ⌊g 0⌋⌉ : (ceil_add_int _ _).symm ... ≤ ⌈f (g 0)⌉ : ceil_mono $ f.le_map_map_zero g lemma lt_map_map_zero : f 0 + g 0 - 1 < f (g 0) := calc f 0 + g 0 - 1 = f 0 + (g 0 - 1) : add_assoc _ _ _ ... < f 0 + ⌊g 0⌋ : add_lt_add_left (sub_one_lt_floor _) _ ... ≤ f (g 0) : f.le_map_map_zero g lemma dist_map_map_zero_lt : dist (f 0 + g 0) (f (g 0)) < 1 := begin rw [dist_comm, real.dist_eq, abs_lt, lt_sub_iff_add_lt', sub_lt_iff_lt_add'], exact ⟨f.lt_map_map_zero g, f.map_map_zero_lt g⟩ end lemma dist_map_zero_lt_of_semiconj {f g₁ g₂ : circle_deg1_lift} (h : function.semiconj f g₁ g₂) : dist (g₁ 0) (g₂ 0) < 2 := calc dist (g₁ 0) (g₂ 0) ≤ dist (g₁ 0) (f (g₁ 0) - f 0) + dist _ (g₂ 0) : dist_triangle _ _ _ ... = dist (f 0 + g₁ 0) (f (g₁ 0)) + dist (g₂ 0 + f 0) (g₂ (f 0)) : by simp only [h.eq, real.dist_eq, sub_sub, add_comm (f 0), sub_sub_assoc_swap, abs_sub (g₂ (f 0))] ... < 2 : add_lt_add (f.dist_map_map_zero_lt g₁) (g₂.dist_map_map_zero_lt f) lemma dist_map_zero_lt_of_semiconj_by {f g₁ g₂ : circle_deg1_lift} (h : semiconj_by f g₁ g₂) : dist (g₁ 0) (g₂ 0) < 2 := dist_map_zero_lt_of_semiconj $ semiconj_by_iff_semiconj.1 h /-! ### Estimates on `(f^n) x` If we know that `f x` is `≤`/`<`/`≥`/`>`/`=` to `x + m`, then we have a similar estimate on `f^[n] x` and `x + n * m`. For `≤`, `≥`, and `=` we formulate both `of` (implication) and `iff` versions because implications work for `n = 0`. For `<` and `>` we formulate only `iff` versions. -/ lemma iterate_le_of_map_le_add_int {x : ℝ} {m : ℤ} (h : f x ≤ x + m) (n : ℕ) : f^[n] x ≤ x + n * m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_le_of_map_le f.monotone (monotone_id.add_const m) h n lemma le_iterate_of_add_int_le_map {x : ℝ} {m : ℤ} (h : x + m ≤ f x) (n : ℕ) : x + n * m ≤ (f^[n]) x := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).symm.iterate_le_of_map_le (monotone_id.add_const m) f.monotone h n lemma iterate_eq_of_map_eq_add_int {x : ℝ} {m : ℤ} (h : f x = x + m) (n : ℕ) : f^[n] x = x + n * m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_eq_of_map_eq n h lemma iterate_pos_le_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : f^[n] x ≤ x + n * m ↔ f x ≤ x + m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_pos_le_iff_map_le f.monotone (strict_mono_id.add_const m) hn lemma iterate_pos_lt_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : f^[n] x < x + n * m ↔ f x < x + m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_pos_lt_iff_map_lt f.monotone (strict_mono_id.add_const m) hn lemma iterate_pos_eq_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : f^[n] x = x + n * m ↔ f x = x + m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_pos_eq_iff_map_eq f.monotone (strict_mono_id.add_const m) hn lemma le_iterate_pos_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : x + n * m ≤ (f^[n]) x ↔ x + m ≤ f x := by simpa only [not_lt] using not_congr (f.iterate_pos_lt_iff hn) lemma lt_iterate_pos_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : x + n * m < (f^[n]) x ↔ x + m < f x := by simpa only [not_le] using not_congr (f.iterate_pos_le_iff hn) lemma mul_floor_map_zero_le_floor_iterate_zero (n : ℕ) : ↑n * ⌊f 0⌋ ≤ ⌊(f^[n] 0)⌋ := begin rw [le_floor, int.cast_mul, int.cast_coe_nat, ← zero_add ((n : ℝ) * _)], apply le_iterate_of_add_int_le_map, simp [floor_le] end /-! ### Definition of translation number -/ noncomputable theory /-- An auxiliary sequence used to define the translation number. -/ def transnum_aux_seq (n : ℕ) : ℝ := (f^(2^n)) 0 / 2^n /-- The translation number of a `circle_deg1_lift`, $τ(f)=\lim_{n→∞}\frac{f^n(x)-x}{n}$. We use an auxiliary sequence `\frac{f^{2^n}(0)}{2^n}` to define `τ(f)` because some proofs are simpler this way. -/ def translation_number : ℝ := lim at_top f.transnum_aux_seq -- TODO: choose two different symbols for `circle_deg1_lift.translation_number` and the future -- `circle_mono_homeo.rotation_number`, then make them `localized notation`s local notation `τ` := translation_number lemma transnum_aux_seq_def : f.transnum_aux_seq = λ n : ℕ, (f^(2^n)) 0 / 2^n := rfl lemma translation_number_eq_of_tendsto_aux {τ' : ℝ} (h : tendsto f.transnum_aux_seq at_top (𝓝 τ')) : τ f = τ' := h.lim_eq lemma translation_number_eq_of_tendsto₀ {τ' : ℝ} (h : tendsto (λ n:ℕ, f^[n] 0 / n) at_top (𝓝 τ')) : τ f = τ' := f.translation_number_eq_of_tendsto_aux $ by simpa [(∘), transnum_aux_seq_def, coe_pow] using h.comp (nat.tendsto_pow_at_top_at_top_of_one_lt one_lt_two) lemma translation_number_eq_of_tendsto₀' {τ' : ℝ} (h : tendsto (λ n:ℕ, f^[n + 1] 0 / (n + 1)) at_top (𝓝 τ')) : τ f = τ' := f.translation_number_eq_of_tendsto₀ $ (tendsto_add_at_top_iff_nat 1).1 h lemma transnum_aux_seq_zero : f.transnum_aux_seq 0 = f 0 := by simp [transnum_aux_seq] lemma transnum_aux_seq_dist_lt (n : ℕ) : dist (f.transnum_aux_seq n) (f.transnum_aux_seq (n+1)) < (1 / 2) / (2^n) := begin have : 0 < (2^(n+1):ℝ) := pow_pos zero_lt_two _, rw [div_div_eq_div_mul, ← pow_succ, ← abs_of_pos this], replace := abs_pos_iff.2 (ne_of_gt this), convert (div_lt_div_right this).2 ((f^(2^n)).dist_map_map_zero_lt (f^(2^n))), simp_rw [transnum_aux_seq, real.dist_eq], rw [← abs_div, sub_div, nat.pow_succ, pow_succ, ← two_mul, mul_div_mul_left _ _ (@two_ne_zero ℝ _), pow_mul, pow_two, mul_apply] end lemma tendsto_translation_number_aux : tendsto f.transnum_aux_seq at_top (𝓝 $ τ f) := (cauchy_seq_of_le_geometric_two 1 (λ n, le_of_lt $ f.transnum_aux_seq_dist_lt n)).tendsto_lim lemma dist_map_zero_translation_number_le : dist (f 0) (τ f) ≤ 1 := f.transnum_aux_seq_zero ▸ dist_le_of_le_geometric_two_of_tendsto₀ 1 (λ n, le_of_lt $ f.transnum_aux_seq_dist_lt n) f.tendsto_translation_number_aux lemma tendsto_translation_number_of_dist_bounded_aux (x : ℕ → ℝ) (C : ℝ) (H : ∀ n : ℕ, dist ((f^n) 0) (x n) ≤ C) : tendsto (λ n : ℕ, x (2^n) / (2^n)) at_top (𝓝 $ τ f) := begin refine f.tendsto_translation_number_aux.congr_dist (squeeze_zero (λ _, dist_nonneg) _ _), { exact λ n, C / 2^n }, { intro n, have : 0 < (2^n:ℝ) := pow_pos zero_lt_two _, convert (div_le_div_right this).2 (H (2^n)), rw [transnum_aux_seq, real.dist_eq, ← sub_div, abs_div, abs_of_pos this, real.dist_eq] }, { exact mul_zero C ▸ tendsto_const_nhds.mul (tendsto_inv_at_top_zero.comp $ tendsto_pow_at_top_at_top_of_one_lt one_lt_two) } end lemma translation_number_eq_of_dist_bounded {f g : circle_deg1_lift} (C : ℝ) (H : ∀ n : ℕ, dist ((f^n) 0) ((g^n) 0) ≤ C) : τ f = τ g := eq.symm $ g.translation_number_eq_of_tendsto_aux $ f.tendsto_translation_number_of_dist_bounded_aux _ C H @[simp] lemma translation_number_map_id : τ 1 = 0 := translation_number_eq_of_tendsto₀ _ $ by simp [tendsto_const_nhds] lemma translation_number_eq_of_semiconj_by {f g₁ g₂ : circle_deg1_lift} (H : semiconj_by f g₁ g₂) : τ g₁ = τ g₂ := translation_number_eq_of_dist_bounded 2 $ λ n, le_of_lt $ dist_map_zero_lt_of_semiconj_by $ H.pow_right n lemma translation_number_eq_of_semiconj {f g₁ g₂ : circle_deg1_lift} (H : function.semiconj f g₁ g₂) : τ g₁ = τ g₂ := translation_number_eq_of_semiconj_by $ semiconj_by_iff_semiconj.2 H lemma translation_number_mul_of_commute {f g : circle_deg1_lift} (h : commute f g) : τ (f * g) = τ f + τ g := begin have : tendsto (λ n : ℕ, ((λ k, (f^k) 0 + (g^k) 0) (2^n)) / (2^n)) at_top (𝓝 $ τ f + τ g) := ((f.tendsto_translation_number_aux.add g.tendsto_translation_number_aux).congr $ λ n, (add_div ((f^(2^n)) 0) ((g^(2^n)) 0) ((2:ℝ)^n)).symm), refine tendsto_nhds_unique ((f * g).tendsto_translation_number_of_dist_bounded_aux _ 1 (λ n, _)) this, rw [h.mul_pow, dist_comm], exact le_of_lt ((f^n).dist_map_map_zero_lt (g^n)) end @[simp] lemma translation_number_pow : ∀ n : ℕ, τ (f^n) = n * τ f | 0 := by simp | (n+1) := by rw [pow_succ', translation_number_mul_of_commute (commute.pow_self f n), translation_number_pow n, nat.cast_add_one, add_mul, one_mul] @[simp] lemma translation_number_conj_eq (f : units circle_deg1_lift) (g : circle_deg1_lift) : τ (↑f * g * ↑(f⁻¹)) = τ g := (translation_number_eq_of_semiconj_by (f.mk_semiconj_by g)).symm @[simp] lemma translation_number_conj_eq' (f : units circle_deg1_lift) (g : circle_deg1_lift) : τ (↑(f⁻¹) * g * f) = τ g := translation_number_conj_eq f⁻¹ g lemma dist_pow_map_zero_mul_translation_number_le (n:ℕ) : dist ((f^n) 0) (n * f.translation_number) ≤ 1 := f.translation_number_pow n ▸ (f^n).dist_map_zero_translation_number_le lemma tendsto_translation_number₀' : tendsto (λ n:ℕ, (f^(n+1)) 0 / (n+1)) at_top (𝓝 $ τ f) := begin refine (tendsto_iff_dist_tendsto_zero.2 $ squeeze_zero (λ _, dist_nonneg) (λ n, _) ((tendsto_const_div_at_top_nhds_0_nat 1).comp (tendsto_add_at_top_nat 1))), dsimp, have : (0:ℝ) < n + 1 := n.cast_add_one_pos, rw [real.dist_eq, div_sub' _ _ _ (ne_of_gt this), abs_div, ← real.dist_eq, abs_of_pos this, div_le_div_right this, ← nat.cast_add_one], apply dist_pow_map_zero_mul_translation_number_le end lemma tendsto_translation_number₀ : tendsto (λ n:ℕ, ((f^n) 0) / n) at_top (𝓝 $ τ f) := (tendsto_add_at_top_iff_nat 1).1 f.tendsto_translation_number₀' /-- For any `x : ℝ` the sequence $\frac{f^n(x)-x}{n}$ tends to the translation number of `f`. In particular, this limit does not depend on `x`. -/ lemma tendsto_translation_number (x : ℝ) : tendsto (λ n:ℕ, ((f^n) x - x) / n) at_top (𝓝 $ τ f) := begin rw [← translation_number_conj_eq' (translate $ multiplicative.of_add x)], convert tendsto_translation_number₀ _, ext n, simp [sub_eq_neg_add, units.conj_pow'] end lemma tendsto_translation_number' (x : ℝ) : tendsto (λ n:ℕ, ((f^(n+1)) x - x) / (n+1)) at_top (𝓝 $ τ f) := (tendsto_add_at_top_iff_nat 1).2 (f.tendsto_translation_number x) lemma translation_number_mono : monotone τ := λ f g h, le_of_tendsto_of_tendsto' f.tendsto_translation_number₀ g.tendsto_translation_number₀ $ λ n, div_le_div_of_le_of_nonneg (pow_mono h n 0) n.cast_nonneg lemma translation_number_translate (x : ℝ) : τ (translate $ multiplicative.of_add x) = x := translation_number_eq_of_tendsto₀' _ $ by simp [nat.cast_add_one_ne_zero, mul_div_cancel_left, tendsto_const_nhds] lemma translation_number_le_of_le_add {z : ℝ} (hz : ∀ x, f x ≤ x + z) : τ f ≤ z := translation_number_translate z ▸ translation_number_mono (λ x, trans_rel_left _ (hz x) (add_comm _ _)) lemma le_translation_number_of_add_le {z : ℝ} (hz : ∀ x, x + z ≤ f x) : z ≤ τ f := translation_number_translate z ▸ translation_number_mono (λ x, trans_rel_right _ (add_comm _ _) (hz x)) lemma translation_number_le_of_le_add_int {x : ℝ} {m : ℤ} (h : f x ≤ x + m) : τ f ≤ m := le_of_tendsto' (f.tendsto_translation_number' x) $ λ n, (div_le_iff' (n.cast_add_one_pos : (0 : ℝ) < _)).mpr $ sub_le_iff_le_add'.2 $ (coe_pow f (n + 1)).symm ▸ f.iterate_le_of_map_le_add_int h (n + 1) lemma translation_number_le_of_le_add_nat {x : ℝ} {m : ℕ} (h : f x ≤ x + m) : τ f ≤ m := @translation_number_le_of_le_add_int f x m h lemma le_translation_number_of_add_int_le {x : ℝ} {m : ℤ} (h : x + m ≤ f x) : ↑m ≤ τ f := ge_of_tendsto' (f.tendsto_translation_number' x) $ λ n, (le_div_iff (n.cast_add_one_pos : (0 : ℝ) < _)).mpr $ le_sub_iff_add_le'.2 $ by simp only [coe_pow, mul_comm (m:ℝ), ← nat.cast_add_one, f.le_iterate_of_add_int_le_map h] lemma le_translation_number_of_add_nat_le {x : ℝ} {m : ℕ} (h : x + m ≤ f x) : ↑m ≤ τ f := @le_translation_number_of_add_int_le f x m h /-- If `f x - x` is an integer number `m` for some point `x`, then `τ f = m`. On the circle this means that a map with a fixed point has rotation number zero. -/ lemma translation_number_of_eq_add_int {x : ℝ} {m : ℤ} (h : f x = x + m) : τ f = m := le_antisymm (translation_number_le_of_le_add_int f $ le_of_eq h) (le_translation_number_of_add_int_le f $ le_of_eq h.symm) lemma floor_sub_le_translation_number (x : ℝ) : ↑⌊f x - x⌋ ≤ τ f := le_translation_number_of_add_int_le f $ le_sub_iff_add_le'.1 (floor_le $ f x - x) lemma translation_number_le_ceil_sub (x : ℝ) : τ f ≤ ⌈f x - x⌉ := translation_number_le_of_le_add_int f $ sub_le_iff_le_add'.1 (le_ceil $ f x - x) lemma map_lt_of_translation_number_lt_int {n : ℤ} (h : τ f < n) (x : ℝ) : f x < x + n := not_le.1 $ mt f.le_translation_number_of_add_int_le $ not_le.2 h lemma map_lt_of_translation_number_lt_nat {n : ℕ} (h : τ f < n) (x : ℝ) : f x < x + n := @map_lt_of_translation_number_lt_int f n h x lemma lt_map_of_int_lt_translation_number {n : ℤ} (h : ↑n < τ f) (x : ℝ) : x + n < f x := not_le.1 $ mt f.translation_number_le_of_le_add_int $ not_le.2 h lemma lt_map_of_nat_lt_translation_number {n : ℕ} (h : ↑n < τ f) (x : ℝ) : x + n < f x := @lt_map_of_int_lt_translation_number f n h x /-- If `f^n x - x`, `n > 0`, is an integer number `m` for some point `x`, then `τ f = m / n`. On the circle this means that a map with a periodic orbit has a rational rotation number. -/ lemma translation_number_of_map_pow_eq_add_int {x : ℝ} {n : ℕ} {m : ℤ} (h : (f^n) x = x + m) (hn : 0 < n) : τ f = m / n := begin have := (f^n).translation_number_of_eq_add_int h, rwa [translation_number_pow, mul_comm, ← eq_div_iff] at this, exact nat.cast_ne_zero.2 (ne_of_gt hn) end /-- If a predicate depends only on `f x - x` and holds for all `0 ≤ x ≤ 1`, then it holds for all `x`. -/ lemma forall_map_sub_of_Icc (P : ℝ → Prop) (h : ∀ x ∈ Icc (0:ℝ) 1, P (f x - x)) (x : ℝ) : P (f x - x) := f.map_fract_sub_fract_eq x ▸ h _ ⟨fract_nonneg _, le_of_lt (fract_lt_one _)⟩ lemma translation_number_lt_of_forall_lt_add (hf : continuous f) {z : ℝ} (hz : ∀ x, f x < x + z) : τ f < z := begin obtain ⟨x, xmem, hx⟩ : ∃ x ∈ Icc (0:ℝ) 1, ∀ y ∈ Icc (0:ℝ) 1, f y - y ≤ f x - x, from compact_Icc.exists_forall_ge (nonempty_Icc.2 zero_le_one) (hf.sub continuous_id).continuous_on, refine lt_of_le_of_lt _ (sub_lt_iff_lt_add'.2 $ hz x), apply translation_number_le_of_le_add, simp only [← sub_le_iff_le_add'], exact f.forall_map_sub_of_Icc (λ a, a ≤ f x - x) hx end lemma lt_translation_number_of_forall_add_lt (hf : continuous f) {z : ℝ} (hz : ∀ x, x + z < f x) : z < τ f := begin obtain ⟨x, xmem, hx⟩ : ∃ x ∈ Icc (0:ℝ) 1, ∀ y ∈ Icc (0:ℝ) 1, f x - x ≤ f y - y, from compact_Icc.exists_forall_le (nonempty_Icc.2 zero_le_one) (hf.sub continuous_id).continuous_on, refine lt_of_lt_of_le (lt_sub_iff_add_lt'.2 $ hz x) _, apply le_translation_number_of_add_le, simp only [← le_sub_iff_add_le'], exact f.forall_map_sub_of_Icc _ hx end /-- If `f` is a continuous monotone map `ℝ → ℝ`, `f (x + 1) = f x + 1`, then there exists `x` such that `f x = x + τ f`. -/ lemma exists_eq_add_translation_number (hf : continuous f) : ∃ x, f x = x + τ f := begin obtain ⟨a, ha⟩ : ∃ x, f x ≤ x + f.translation_number, { by_contradiction H, push_neg at H, exact lt_irrefl _ (f.lt_translation_number_of_forall_add_lt hf H) }, obtain ⟨b, hb⟩ : ∃ x, x + τ f ≤ f x, { by_contradiction H, push_neg at H, exact lt_irrefl _ (f.translation_number_lt_of_forall_lt_add hf H) }, exact intermediate_value_univ₂ hf (continuous_id.add continuous_const) ha hb end lemma translation_number_eq_int_iff (hf : continuous f) {m : ℤ} : τ f = m ↔ ∃ x, f x = x + m := begin refine ⟨λ h, h ▸ f.exists_eq_add_translation_number hf, _⟩, rintros ⟨x, hx⟩, exact f.translation_number_of_eq_add_int hx end lemma continuous_pow (hf : continuous f) (n : ℕ) : continuous ⇑(f^n : circle_deg1_lift) := by { rw coe_pow, exact hf.iterate n } lemma translation_number_eq_rat_iff (hf : continuous f) {m : ℤ} {n : ℕ} (hn : 0 < n) : τ f = m / n ↔ ∃ x, (f^n) x = x + m := begin rw [eq_div_iff, mul_comm, ← translation_number_pow]; [skip, exact ne_of_gt (nat.cast_pos.2 hn)], exact (f^n).translation_number_eq_int_iff (f.continuous_pow hf n) end end circle_deg1_lift
2fae07af649ea378f944667189b27b3e4892a3c9
60bf3fa4185ec5075eaea4384181bfbc7e1dc319
/src/game/series/tempLevel03.lean
781bb13a25924d70aaccd3088a9d9d65253f1860
[ "Apache-2.0" ]
permissive
anrddh/real-number-game
660f1127d03a78fd35986c771d65c3132c5f4025
c708c4e02ec306c657e1ea67862177490db041b0
refs/heads/master
1,668,214,277,092
1,593,105,075,000
1,593,105,075,000
264,269,218
0
0
null
1,589,567,264,000
1,589,567,264,000
null
UTF-8
Lean
false
false
365
lean
import game.series.L01defs variable X : Type --hide /- Idea 03: comparison test -/ /- Lemma If $A$ and $B$ are sets of any type $X$, then $$ A \subseteq A\cup B.$$ -/ theorem subset_union_left (A B : set X) : A ⊆ A ∪ B := begin --change ∀ (x : α), x ∈ A → x ∈ A ∪ B, --they may want to do this intros x hx, left, exact hx, done end
92adfd443ed46395405183e814dfcbe7670326e1
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/finite/set.lean
fbce2f946fef965c42ff732744bced1b7b01bcc3
[ "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
795
lean
/- Copyright (c) 2022 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import data.finite.basic import data.set.finite /-! # Lemmas about `finite` and `set`s In this file we prove two lemmas about `finite` and `set`s. ## Tags finiteness, finite sets -/ open set universes u v w x variables {α : Type u} {β : Type v} {ι : Sort w} lemma finite.set.finite_of_finite_image (s : set α) {f : α → β} (h : s.inj_on f) [finite (f '' s)] : finite s := finite.of_equiv _ (equiv.of_bijective _ h.bij_on_image.bijective).symm lemma finite.of_injective_finite_range {f : ι → α} (hf : function.injective f) [finite (range f)] : finite ι := finite.of_injective (set.range_factorization f) (hf.cod_restrict _)
021195c3c3a5e6c3268c6e213946c1263c5b2da8
618003631150032a5676f229d13a079ac875ff77
/src/category_theory/limits/shapes/zero.lean
c0d82a4d90491c5c99fdf172a5e5c4ad95aba4d5
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
8,305
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.shapes.binary_products import category_theory.epi_mono import category_theory.punit /-! # Zero morphisms and zero objects A category "has zero morphisms" if there is a designated "zero morphism" in each morphism space, and compositions of zero morphisms with anything give the zero morphism. (Notice this is extra structure, not merely a property.) A category "has a zero object" if it has an object which is both initial and terminal. Having a zero object provides zero morphisms, as the unique morphisms factoring through the zero object. ## References * https://en.wikipedia.org/wiki/Zero_morphism * [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2] -/ universes v u open category_theory namespace category_theory.limits variables (C : Type u) [category.{v} C] /-- A category "has zero morphisms" if there is a designated "zero morphism" in each morphism space, and compositions of zero morphisms with anything give the zero morphism. -/ class has_zero_morphisms := [has_zero : Π X Y : C, has_zero (X ⟶ Y)] (comp_zero' : ∀ {X Y : C} (f : X ⟶ Y) (Z : C), f ≫ (0 : Y ⟶ Z) = (0 : X ⟶ Z) . obviously) (zero_comp' : ∀ (X : C) {Y Z : C} (f : Y ⟶ Z), (0 : X ⟶ Y) ≫ f = (0 : X ⟶ Z) . obviously) attribute [instance] has_zero_morphisms.has_zero restate_axiom has_zero_morphisms.comp_zero' attribute [simp] has_zero_morphisms.comp_zero restate_axiom has_zero_morphisms.zero_comp' attribute [simp, reassoc] has_zero_morphisms.zero_comp instance has_zero_morphisms_pempty : has_zero_morphisms.{v} pempty.{v+1} := { has_zero := by tidy } instance has_zero_morphisms_punit : has_zero_morphisms.{v} punit.{v+1} := { has_zero := λ X Y, { zero := punit.star, } } namespace has_zero_morphisms variables {C} /-- This lemma will be immediately superseded by `ext`, below. -/ private lemma ext_aux (I J : has_zero_morphisms.{v} C) (w : ∀ X Y : C, (@has_zero_morphisms.has_zero.{v} _ _ I X Y).zero = (@has_zero_morphisms.has_zero.{v} _ _ J X Y).zero) : I = J := begin resetI, cases I, cases J, congr, { ext X Y, exact w X Y }, { apply proof_irrel_heq, }, { apply proof_irrel_heq, } end /-- If you're tempted to use this lemma "in the wild", you should probably carefully consider whether you've made a mistake in allowing two instances of `has_zero_morphisms` to exist at all. See, particularly, the note on `zero_morphisms_of_zero_object` below. -/ lemma ext (I J : has_zero_morphisms.{v} C) : I = J := begin apply ext_aux, intros X Y, rw ←@has_zero_morphisms.comp_zero _ _ I X X (@has_zero_morphisms.has_zero _ _ J X X).zero, rw @has_zero_morphisms.zero_comp _ _ J, end instance : subsingleton (has_zero_morphisms.{v} C) := ⟨ext⟩ end has_zero_morphisms open has_zero_morphisms section variables {C} [has_zero_morphisms.{v} C] lemma zero_of_comp_mono {X Y Z : C} {f : X ⟶ Y} (g : Y ⟶ Z) [mono g] (h : f ≫ g = 0) : f = 0 := by { rw [←zero_comp.{v} X g, cancel_mono] at h, exact h } lemma zero_of_epi_comp {X Y Z : C} (f : X ⟶ Y) {g : Y ⟶ Z} [epi f] (h : f ≫ g = 0) : g = 0 := by { rw [←comp_zero.{v} f Z, cancel_epi] at h, exact h } end section universes v' u' variables (D : Type u') [category.{v'} D] variables [has_zero_morphisms.{v} C] [has_zero_morphisms.{v'} D] @[simp] lemma equivalence_preserves_zero_morphisms (F : C ≌ D) (X Y : C) : F.functor.map (0 : X ⟶ Y) = (0 : F.functor.obj X ⟶ F.functor.obj Y) := begin have t : F.functor.map (0 : X ⟶ Y) = F.functor.map (0 : X ⟶ Y) ≫ (0 : F.functor.obj Y ⟶ F.functor.obj Y), { apply faithful.injectivity (F.inverse), rw [functor.map_comp, equivalence.inv_fun_map], dsimp, rw [zero_comp, comp_zero, zero_comp], }, exact t.trans (by simp) end end /-- A category "has a zero object" if it has an object which is both initial and terminal. -/ class has_zero_object := (zero : C) (unique_to : Π X : C, unique (zero ⟶ X)) (unique_from : Π X : C, unique (X ⟶ zero)) instance has_zero_object_punit : has_zero_object.{v} punit.{v+1} := { zero := punit.star, unique_to := by tidy, unique_from := by tidy, } variables {C} namespace has_zero_object variables [has_zero_object.{v} C] /-- Construct a `has_zero C` for a category with a zero object. This can not be a global instance as it will trigger for every `has_zero C` typeclass search. -/ protected def has_zero : has_zero C := { zero := has_zero_object.zero.{v} } local attribute [instance] has_zero_object.has_zero local attribute [instance] has_zero_object.unique_to has_zero_object.unique_from /-- A category with a zero object has zero morphisms. It is rarely a good idea to use this. Many categories that have a zero object have zero morphisms for some other reason, for example from additivity. Library code that uses `zero_morphisms_of_zero_object` will then be incompatible with these categories because the `has_zero_morphisms` instances will not be definitionally equal. For this reason library code should generally ask for an instance of `has_zero_morphisms` separately, even if it already asks for an instance of `has_zero_objects`. -/ def zero_morphisms_of_zero_object : has_zero_morphisms.{v} C := { has_zero := λ X Y, { zero := inhabited.default (X ⟶ 0) ≫ inhabited.default (0 ⟶ Y) }, zero_comp' := λ X Y Z f, by { dunfold has_zero.zero, rw category.assoc, congr, }, comp_zero' := λ X Y Z f, by { dunfold has_zero.zero, rw ←category.assoc, congr, }} section variable [has_zero_morphisms.{v} C] /-- An arrow ending in the zero object is zero -/ @[ext] lemma zero_of_to_zero {X : C} (f : X ⟶ 0) : f = 0 := begin rw (has_zero_object.unique_from.{v} X).uniq f, rw (has_zero_object.unique_from.{v} X).uniq (0 : X ⟶ 0) end /-- An arrow starting at the zero object is zero -/ @[ext] lemma zero_of_from_zero {X : C} (f : 0 ⟶ X) : f = 0 := begin rw (has_zero_object.unique_to.{v} X).uniq f, rw (has_zero_object.unique_to.{v} X).uniq (0 : 0 ⟶ X) end end /-- A zero object is in particular initial. -/ def has_initial_of_has_zero_object : has_initial.{v} C := has_initial_of_unique 0 /-- A zero object is in particular terminal. -/ def has_terminal_of_has_zero_object : has_terminal.{v} C := has_terminal_of_unique 0 end has_zero_object /-- In the presence of zero morphisms, coprojections into a coproduct are (split) monomorphisms. -/ instance split_mono_sigma_ι {β : Type v} [decidable_eq β] [has_zero_morphisms.{v} C] (f : β → C) [has_colimit (functor.of_function f)] (b : β) : split_mono (sigma.ι f b) := { retraction := sigma.desc (λ b', if h : b' = b then eq_to_hom (congr_arg f h) else 0), } /-- In the presence of zero morphisms, projections into a product are (split) epimorphisms. -/ instance split_epi_pi_π {β : Type v} [decidable_eq β] [has_zero_morphisms.{v} C] (f : β → C) [has_limit (functor.of_function f)] (b : β) : split_epi (pi.π f b) := { section_ := pi.lift (λ b', if h : b = b' then eq_to_hom (congr_arg f h) else 0), } /-- In the presence of zero morphisms, coprojections into a coproduct are (split) monomorphisms. -/ instance split_mono_coprod_inl [has_zero_morphisms.{v} C] {X Y : C} [has_colimit (pair X Y)] : split_mono (coprod.inl : X ⟶ X ⨿ Y) := { retraction := coprod.desc (𝟙 X) 0, } /-- In the presence of zero morphisms, coprojections into a coproduct are (split) monomorphisms. -/ instance split_mono_coprod_inr [has_zero_morphisms.{v} C] {X Y : C} [has_colimit (pair X Y)] : split_mono (coprod.inr : Y ⟶ X ⨿ Y) := { retraction := coprod.desc 0 (𝟙 Y), } /-- In the presence of zero morphisms, projections into a product are (split) epimorphisms. -/ instance split_epi_prod_fst [has_zero_morphisms.{v} C] {X Y : C} [has_limit (pair X Y)] : split_epi (prod.fst : X ⨯ Y ⟶ X) := { section_ := prod.lift (𝟙 X) 0, } /-- In the presence of zero morphisms, projections into a product are (split) epimorphisms. -/ instance split_epi_prod_snd [has_zero_morphisms.{v} C] {X Y : C} [has_limit (pair X Y)] : split_epi (prod.snd : X ⨯ Y ⟶ Y) := { section_ := prod.lift 0 (𝟙 Y), } end category_theory.limits
cc08a0adb71d50529fcd01e359cdcf15eb149d2b
5e3548e65f2c037cb94cd5524c90c623fbd6d46a
/src_icannos_totilas/anneaux/cpge_anneaux_2.lean
2b15ff4789e4a49df87e958ce3ec8e54a31f6414
[]
no_license
ahayat16/lean_exos
d4f08c30adb601a06511a71b5ffb4d22d12ef77f
682f2552d5b04a8c8eb9e4ab15f875a91b03845c
refs/heads/main
1,693,101,073,585
1,636,479,336,000
1,636,479,336,000
415,000,441
0
0
null
null
null
null
UTF-8
Lean
false
false
243
lean
import ring_theory.non_zero_divisors import algebra.ring.basic theorem cpge_anneaux_2 {A :Type*} [ring A] (a b : A): (ring.inverse (a*b) ) ≠ 0 ∧ b ∈ non_zero_divisors A → (ring.inverse a ≠ 0) ∧ (ring.inverse b ≠ 0) := sorry
9774de55ac12212e7e5236b3193d27f172e7be57
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/whnf.lean
76efca6072576d26367cb5c669d386665d4341c2
[ "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
136
lean
open nat eval [whnf] (fun x, x + 1) (2:nat) eval (fun x, x + 1) (2:nat) variable a : nat eval [whnf] a + succ zero eval a + succ zero
39997bc076ccbe01e7fd57afb6160142da635558
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/src/topology/uniform_space/completion.lean
17a7c6512711d407058d715e1f25013327a0508c
[ "Apache-2.0" ]
permissive
johoelzl/mathlib
253f46daa30b644d011e8e119025b01ad69735c4
592e3c7a2dfbd5826919b4605559d35d4d75938f
refs/heads/master
1,625,657,216,488
1,551,374,946,000
1,551,374,946,000
98,915,829
0
0
Apache-2.0
1,522,917,267,000
1,501,524,499,000
Lean
UTF-8
Lean
false
false
55,307
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl Hausdorff completions of uniform spaces; lifting the group and ring structure. The goal is to construct a left-adjoint to the inclusion of complete Hausdorff uniform spaces into all uniform spaces. Any uniform space `α` gets a completion `completion α` and a morphism (ie. uniformly continuous map) `completion : α → completion α` which solves the universal mapping problem of factorizing morphisms from `α` to any complete Hausdorff uniform space `β`. It means any uniformly continuous `f : α → β` gives rise to a unique morphism `completion.map f : completion α → β` such that `f = completion.extension f ∘ completion α`. Actually `completion.extension f` is defined for all maps from `α` to `β` but it has the desired properties only if `f` is uniformly continuous. Beware that `completion α` is not injective if `α` is not Hausdorff. But its image is always dense. The adjoint functor acting on morphisms is then constructed by the usual abstract nonsense. For every uniform spaces `α` and `β`, it turns `f : α → β` into a morphism `completion.map f : completion α → completion β` such that `coe ∘ f = (completion.map f) ∘ coe` provided `f` is uniformly continuous. This construction is compatible with composition. In this file we introduce the following concepts: * `separation_setoid α`: to construct the quotient over all elements which are topologically not distinguishable. * `Cauchy α` the uniform completion of the uniform space `α` (using Cauchy filters). These are not minimal filters. * `completion α := quotient (separation_setoid (Cauchy α))` the Hausdorff completion. * lift topological groups (using `uniform_add_group`) to the complete group structure. * lift topological rings (using `uniform_add_group` and `topological_ring`) to the complete ring structure. This formalization is mostly based on N. Bourbaki: General Topology I. M. James: Topologies and Uniformities From a slightly different perspective in order to reuse material in topology.uniform_space.basic. -/ import data.set.basic data.set.function import algebra.pi_instances import topology.uniform_space.basic topology.algebra.topological_structures import ring_theory.ideals noncomputable theory local attribute [instance] classical.prop_decidable open filter set universes u v w x /- separation space -/ namespace uniform_space variables {α : Type u} {β : Type v} {γ : Type w} variables [uniform_space α] [uniform_space β] [uniform_space γ] def separation_setoid (α : Type u) [uniform_space α] : setoid α := ⟨λx y, (x, y) ∈ separation_rel α, separated_equiv⟩ local attribute [instance] separation_setoid instance {α : Type u} [u : uniform_space α] : uniform_space (quotient (separation_setoid α)) := { to_topological_space := u.to_topological_space.coinduced (λx, ⟦x⟧), uniformity := map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) uniformity, refl := le_trans (by simp [quotient.exists_rep]) (filter.map_mono refl_le_uniformity), symm := tendsto_map' $ by simp [prod.swap, (∘)]; exact tendsto_swap_uniformity.comp tendsto_map, comp := calc (map (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) uniformity).lift' (λs, comp_rel s s) = uniformity.lift' ((λs, comp_rel s s) ∘ image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧))) : map_lift'_eq2 $ monotone_comp_rel monotone_id monotone_id ... ≤ uniformity.lift' (image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ∘ (λs:set (α×α), comp_rel s (comp_rel s s))) : lift'_mono' $ assume s hs ⟨a, b⟩ ⟨c, ⟨⟨a₁, a₂⟩, ha, a_eq⟩, ⟨⟨b₁, b₂⟩, hb, b_eq⟩⟩, begin simp at a_eq, simp at b_eq, have h : ⟦a₂⟧ = ⟦b₁⟧, { rw [a_eq.right, b_eq.left] }, have h : (a₂, b₁) ∈ separation_rel α := quotient.exact h, simp [function.comp, set.image, comp_rel, and.comm, and.left_comm, and.assoc], exact ⟨a₁, a_eq.left, b₂, b_eq.right, a₂, ha, b₁, h s hs, hb⟩ end ... = map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) (uniformity.lift' (λs:set (α×α), comp_rel s (comp_rel s s))) : by rw [map_lift'_eq]; exact monotone_comp_rel monotone_id (monotone_comp_rel monotone_id monotone_id) ... ≤ map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) uniformity : map_mono comp_le_uniformity3, is_open_uniformity := assume s, have ∀a, ⟦a⟧ ∈ s → ({p:α×α | p.1 = a → ⟦p.2⟧ ∈ s} ∈ (@uniformity α _).sets ↔ {p:α×α | p.1 ≈ a → ⟦p.2⟧ ∈ s} ∈ (@uniformity α _).sets), from assume a ha, ⟨assume h, let ⟨t, ht, hts⟩ := comp_mem_uniformity_sets h in have hts : ∀{a₁ a₂}, (a, a₁) ∈ t → (a₁, a₂) ∈ t → ⟦a₂⟧ ∈ s, from assume a₁ a₂ ha₁ ha₂, @hts (a, a₂) ⟨a₁, ha₁, ha₂⟩ rfl, have ht' : ∀{a₁ a₂}, a₁ ≈ a₂ → (a₁, a₂) ∈ t, from assume a₁ a₂ h, sInter_subset_of_mem ht h, uniformity.sets_of_superset ht $ assume ⟨a₁, a₂⟩ h₁ h₂, hts (ht' $ setoid.symm h₂) h₁, assume h, uniformity.sets_of_superset h $ by simp {contextual := tt}⟩, begin simp [topological_space.coinduced, u.is_open_uniformity, uniformity, forall_quotient_iff], exact ⟨λh a ha, (this a ha).mp $ h a ha, λh a ha, (this a ha).mpr $ h a ha⟩ end } lemma uniformity_quotient : @uniformity (quotient (separation_setoid α)) _ = uniformity.map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) := rfl lemma uniform_continuous_quotient_mk : uniform_continuous (quotient.mk : α → quotient (separation_setoid α)) := le_refl _ lemma uniform_continuous_quotient {f : quotient (separation_setoid α) → β} (hf : uniform_continuous (λx, f ⟦x⟧)) : uniform_continuous f := hf lemma uniform_continuous_quotient_lift {f : α → β} {h : ∀a b, (a, b) ∈ separation_rel α → f a = f b} (hf : uniform_continuous f) : uniform_continuous (λa, quotient.lift f h a) := uniform_continuous_quotient hf lemma uniform_continuous_quotient_lift₂ [uniform_space γ] {f : α → β → γ} {h : ∀a c b d, (a, b) ∈ separation_rel α → (c, d) ∈ separation_rel β → f a c = f b d} (hf : uniform_continuous (λp:α×β, f p.1 p.2)) : uniform_continuous (λp:_×_, quotient.lift₂ f h p.1 p.2) := begin rw [uniform_continuous, uniformity_prod_eq_prod, uniformity_quotient, uniformity_quotient, filter.prod_map_map_eq, filter.tendsto_map'_iff, filter.tendsto_map'_iff], rwa [uniform_continuous, uniformity_prod_eq_prod, filter.tendsto_map'_iff] at hf end lemma comap_quotient_le_uniformity : uniformity.comap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ≤ uniformity := assume t' ht', let ⟨t, ht, tt_t'⟩ := comp_mem_uniformity_sets ht' in let ⟨s, hs, ss_t⟩ := comp_mem_uniformity_sets ht in ⟨(λp:α×α, (⟦p.1⟧, ⟦p.2⟧)) '' s, (@uniformity α _).sets_of_superset hs $ assume x hx, ⟨x, hx, rfl⟩, assume ⟨a₁, a₂⟩ ⟨⟨b₁, b₂⟩, hb, ab_eq⟩, have ⟦b₁⟧ = ⟦a₁⟧ ∧ ⟦b₂⟧ = ⟦a₂⟧, from prod.mk.inj ab_eq, have b₁ ≈ a₁ ∧ b₂ ≈ a₂, from and.imp quotient.exact quotient.exact this, have ab₁ : (a₁, b₁) ∈ t, from (setoid.symm this.left) t ht, have ba₂ : (b₂, a₂) ∈ s, from this.right s hs, tt_t' ⟨b₁, show ((a₁, a₂).1, b₁) ∈ t, from ab₁, ss_t ⟨b₂, show ((b₁, a₂).1, b₂) ∈ s, from hb, ba₂⟩⟩⟩ lemma comap_quotient_eq_uniformity : uniformity.comap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) = uniformity := le_antisymm comap_quotient_le_uniformity le_comap_map instance complete_space_separation [h : complete_space α] : complete_space (quotient (separation_setoid α)) := ⟨assume f, assume hf : cauchy f, have cauchy (f.comap (λx, ⟦x⟧)), from cauchy_comap comap_quotient_le_uniformity hf $ comap_neq_bot_of_surj hf.left $ assume b, quotient.exists_rep _, let ⟨x, (hx : f.comap (λx, ⟦x⟧) ≤ nhds x)⟩ := complete_space.complete this in ⟨⟦x⟧, calc f = map (λx, ⟦x⟧) (f.comap (λx, ⟦x⟧)) : (map_comap $ univ_mem_sets' $ assume b, quotient.exists_rep _).symm ... ≤ map (λx, ⟦x⟧) (nhds x) : map_mono hx ... ≤ _ : continuous_iff_continuous_at.mp uniform_continuous_quotient_mk.continuous _⟩⟩ instance separated_separation : separated (quotient (separation_setoid α)) := set.ext $ assume ⟨a, b⟩, quotient.induction_on₂ a b $ assume a b, ⟨assume h, have a ≈ b, from assume s hs, have s ∈ (uniformity.comap (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧))).sets, from comap_quotient_le_uniformity hs, let ⟨t, ht, hts⟩ := this in hts begin dsimp, exact h t ht end, show ⟦a⟧ = ⟦b⟧, from quotient.sound this, assume heq : ⟦a⟧ = ⟦b⟧, assume h hs, heq ▸ refl_mem_uniformity hs⟩ lemma separated_of_uniform_continuous {f : α → β} {x y : α} (H : uniform_continuous f) (h : x ≈ y) : f x ≈ f y := assume _ h', h _ (H h') lemma eq_of_separated_of_uniform_continuous [separated β] {f : α → β} {x y : α} (H : uniform_continuous f) (h : x ≈ y) : f x = f y := separated_def.1 (by apply_instance) _ _ $ separated_of_uniform_continuous H h def separation_quotient (α : Type*) [uniform_space α] := quotient (separation_setoid α) namespace separation_quotient instance : uniform_space (separation_quotient α) := by dunfold separation_quotient ; apply_instance instance : separated (separation_quotient α) := by dunfold separation_quotient ; apply_instance def lift [separated β] (f : α → β) : (separation_quotient α → β) := if h : uniform_continuous f then quotient.lift f (λ x y, eq_of_separated_of_uniform_continuous h) else λ x, f (classical.inhabited_of_nonempty $ (nonempty_quotient_iff $ separation_setoid α).1 ⟨x⟩).default lemma lift_mk [separated β] {f : α → β} (h : uniform_continuous f) (a : α) : lift f ⟦a⟧ = f a := by rw [lift, dif_pos h]; refl lemma uniform_continuous_lift [separated β] (f : α → β) : uniform_continuous (lift f) := begin by_cases hf : uniform_continuous f, { rw [lift, dif_pos hf], exact uniform_continuous_quotient_lift hf }, { rw [lift, dif_neg hf], exact uniform_continuous_of_const (assume a b, rfl) } end def map (f : α → β) : separation_quotient α → separation_quotient β := lift (quotient.mk ∘ f) lemma map_mk {f : α → β} (h : uniform_continuous f) (a : α) : map f ⟦a⟧ = ⟦f a⟧ := by rw [map, lift_mk (h.comp uniform_continuous_quotient_mk)] lemma uniform_continuous_map (f : α → β): uniform_continuous (map f) := uniform_continuous_lift (quotient.mk ∘ f) lemma map_unique {f : α → β} (hf : uniform_continuous f) {g : separation_quotient α → separation_quotient β} (comm : quotient.mk ∘ f = g ∘ quotient.mk) : map f = g := by ext ⟨a⟩; calc map f ⟦a⟧ = ⟦f a⟧ : map_mk hf a ... = g ⟦a⟧ : congr_fun comm a lemma map_id : map (@id α) = id := map_unique uniform_continuous_id rfl lemma map_comp {f : α → β} {g : β → γ} (hf : uniform_continuous f) (hg : uniform_continuous g) : map g ∘ map f = map (g ∘ f) := (map_unique (hf.comp hg) $ by simp only [(∘), map_mk, hf, hg]).symm end separation_quotient lemma separation_prod {a₁ a₂ : α} {b₁ b₂ : β} : (a₁, b₁) ≈ (a₂, b₂) ↔ a₁ ≈ a₂ ∧ b₁ ≈ b₂ := begin split, { assume h, exact ⟨separated_of_uniform_continuous uniform_continuous_fst h, separated_of_uniform_continuous uniform_continuous_snd h⟩ }, { rintros ⟨eqv_α, eqv_β⟩ r r_in, rw uniformity_prod at r_in, rcases r_in with ⟨t_α, ⟨r_α, r_α_in, h_α⟩, t_β, ⟨r_β, r_β_in, h_β⟩, H⟩, let p_α := λ(p : (α × β) × (α × β)), (p.1.1, p.2.1), let p_β := λ(p : (α × β) × (α × β)), (p.1.2, p.2.2), have key_α : p_α ((a₁, b₁), (a₂, b₂)) ∈ r_α, { simp [p_α, eqv_α r_α r_α_in] }, have key_β : p_β ((a₁, b₁), (a₂, b₂)) ∈ r_β, { simp [p_β, eqv_β r_β r_β_in] }, exact H ⟨h_α key_α, h_β key_β⟩ }, end instance separated.prod [separated α] [separated β] : separated (α × β) := separated_def.2 $ assume x y H, prod.ext (eq_of_separated_of_uniform_continuous uniform_continuous_fst H) (eq_of_separated_of_uniform_continuous uniform_continuous_snd H) end uniform_space /-- Space of Cauchy filters This is essentially the completion of a uniform space. The embeddings are the neighbourhood filters. This space is not minimal, the separated uniform space (i.e. quotiented on the intersection of all entourages) is necessary for this. -/ def Cauchy (α : Type u) [uniform_space α] : Type u := { f : filter α // cauchy f } namespace Cauchy section parameters {α : Type u} [uniform_space α] variables {β : Type v} {γ : Type w} variables [uniform_space β] [uniform_space γ] def gen (s : set (α × α)) : set (Cauchy α × Cauchy α) := {p | s ∈ (filter.prod (p.1.val) (p.2.val)).sets } lemma monotone_gen : monotone gen := monotone_set_of $ assume p, @monotone_mem_sets (α×α) (filter.prod (p.1.val) (p.2.val)) private lemma symm_gen : map prod.swap (uniformity.lift' gen) ≤ uniformity.lift' gen := calc map prod.swap (uniformity.lift' gen) = uniformity.lift' (λs:set (α×α), {p | s ∈ (filter.prod (p.2.val) (p.1.val)).sets }) : begin delta gen, simp [map_lift'_eq, monotone_set_of, monotone_mem_sets, function.comp, image_swap_eq_preimage_swap] end ... ≤ uniformity.lift' gen : uniformity_lift_le_swap (monotone_comp (monotone_set_of $ assume p, @monotone_mem_sets (α×α) ((filter.prod ((p.2).val) ((p.1).val)))) monotone_principal) begin have h := λ(p:Cauchy α×Cauchy α), @filter.prod_comm _ _ (p.2.val) (p.1.val), simp [function.comp, h], exact le_refl _ end private lemma comp_rel_gen_gen_subset_gen_comp_rel {s t : set (α×α)} : comp_rel (gen s) (gen t) ⊆ (gen (comp_rel s t) : set (Cauchy α × Cauchy α)) := assume ⟨f, g⟩ ⟨h, h₁, h₂⟩, let ⟨t₁, (ht₁ : t₁ ∈ f.val.sets), t₂, (ht₂ : t₂ ∈ h.val.sets), (h₁ : set.prod t₁ t₂ ⊆ s)⟩ := mem_prod_iff.mp h₁ in let ⟨t₃, (ht₃ : t₃ ∈ h.val.sets), t₄, (ht₄ : t₄ ∈ g.val.sets), (h₂ : set.prod t₃ t₄ ⊆ t)⟩ := mem_prod_iff.mp h₂ in have t₂ ∩ t₃ ∈ h.val.sets, from inter_mem_sets ht₂ ht₃, let ⟨x, xt₂, xt₃⟩ := inhabited_of_mem_sets (h.property.left) this in (filter.prod f.val g.val).sets_of_superset (prod_mem_prod ht₁ ht₄) (assume ⟨a, b⟩ ⟨(ha : a ∈ t₁), (hb : b ∈ t₄)⟩, ⟨x, h₁ (show (a, x) ∈ set.prod t₁ t₂, from ⟨ha, xt₂⟩), h₂ (show (x, b) ∈ set.prod t₃ t₄, from ⟨xt₃, hb⟩)⟩) private lemma comp_gen : (uniformity.lift' gen).lift' (λs, comp_rel s s) ≤ uniformity.lift' gen := calc (uniformity.lift' gen).lift' (λs, comp_rel s s) = uniformity.lift' (λs, comp_rel (gen s) (gen s)) : begin rw [lift'_lift'_assoc], exact monotone_gen, exact (monotone_comp_rel monotone_id monotone_id) end ... ≤ uniformity.lift' (λs, gen $ comp_rel s s) : lift'_mono' $ assume s hs, comp_rel_gen_gen_subset_gen_comp_rel ... = (uniformity.lift' $ λs:set(α×α), comp_rel s s).lift' gen : begin rw [lift'_lift'_assoc], exact (monotone_comp_rel monotone_id monotone_id), exact monotone_gen end ... ≤ uniformity.lift' gen : lift'_mono comp_le_uniformity (le_refl _) instance : uniform_space (Cauchy α) := uniform_space.of_core { uniformity := uniformity.lift' gen, refl := principal_le_lift' $ assume s hs ⟨a, b⟩ (a_eq_b : a = b), a_eq_b ▸ a.property.right hs, symm := symm_gen, comp := comp_gen } theorem mem_uniformity {s : set (Cauchy α × Cauchy α)} : s ∈ (@uniformity (Cauchy α) _).sets ↔ ∃ t ∈ (@uniformity α _).sets, gen t ⊆ s := mem_lift'_sets monotone_gen theorem mem_uniformity' {s : set (Cauchy α × Cauchy α)} : s ∈ (@uniformity (Cauchy α) _).sets ↔ ∃ t ∈ (@uniformity α _).sets, ∀ f g : Cauchy α, t ∈ (filter.prod f.1 g.1).sets → (f, g) ∈ s := mem_uniformity.trans $ bex_congr $ λ t h, prod.forall /-- Embedding of `α` into its completion -/ def pure_cauchy (a : α) : Cauchy α := ⟨pure a, cauchy_pure⟩ lemma uniform_embedding_pure_cauchy : uniform_embedding (pure_cauchy : α → Cauchy α) := ⟨assume a₁ a₂ h, have (pure_cauchy a₁).val = (pure_cauchy a₂).val, from congr_arg _ h, have {a₁} = ({a₂} : set α), from principal_eq_iff_eq.mp this, by simp at this; assumption, have (preimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) = id, from funext $ assume s, set.ext $ assume ⟨a₁, a₂⟩, by simp [preimage, gen, pure_cauchy, prod_principal_principal], calc comap (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) (uniformity.lift' gen) = uniformity.lift' (preimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) : comap_lift'_eq monotone_gen ... = uniformity : by simp [this]⟩ lemma pure_cauchy_dense : ∀x, x ∈ closure (range pure_cauchy) := assume f, have h_ex : ∀s∈(@uniformity (Cauchy α) _).sets, ∃y:α, (f, pure_cauchy y) ∈ s, from assume s hs, let ⟨t'', ht''₁, (ht''₂ : gen t'' ⊆ s)⟩ := (mem_lift'_sets monotone_gen).mp hs in let ⟨t', ht'₁, ht'₂⟩ := comp_mem_uniformity_sets ht''₁ in have t' ∈ (filter.prod (f.val) (f.val)).sets, from f.property.right ht'₁, let ⟨t, ht, (h : set.prod t t ⊆ t')⟩ := mem_prod_same_iff.mp this in let ⟨x, (hx : x ∈ t)⟩ := inhabited_of_mem_sets f.property.left ht in have t'' ∈ (filter.prod f.val (pure x)).sets, from mem_prod_iff.mpr ⟨t, ht, {y:α | (x, y) ∈ t'}, assume y, begin simp, intro h, simp [h], exact refl_mem_uniformity ht'₁ end, assume ⟨a, b⟩ ⟨(h₁ : a ∈ t), (h₂ : (x, b) ∈ t')⟩, ht'₂ $ prod_mk_mem_comp_rel (@h (a, x) ⟨h₁, hx⟩) h₂⟩, ⟨x, ht''₂ $ by dsimp [gen]; exact this⟩, begin simp [closure_eq_nhds, nhds_eq_uniformity, lift'_inf_principal_eq, set.inter_comm], exact (lift'_neq_bot_iff $ monotone_inter monotone_const monotone_preimage).mpr (assume s hs, let ⟨y, hy⟩ := h_ex s hs in have pure_cauchy y ∈ range pure_cauchy ∩ {y : Cauchy α | (f, y) ∈ s}, from ⟨mem_range_self y, hy⟩, ne_empty_of_mem this) end lemma dense_embedding_pure_cauchy : dense_embedding pure_cauchy := uniform_embedding_pure_cauchy.dense_embedding pure_cauchy_dense lemma nonempty_Cauchy_iff : nonempty (Cauchy α) ↔ nonempty α := begin split ; rintro ⟨c⟩, { have := eq_univ_iff_forall.1 dense_embedding_pure_cauchy.closure_range c, have := mem_closure_iff.1 this _ is_open_univ trivial, rcases exists_mem_of_ne_empty this with ⟨_, ⟨_, a, _⟩⟩, exact ⟨a⟩ }, { exact ⟨pure_cauchy c⟩ } end section set_option eqn_compiler.zeta true instance : complete_space (Cauchy α) := complete_space_extension uniform_embedding_pure_cauchy pure_cauchy_dense $ assume f hf, let f' : Cauchy α := ⟨f, hf⟩ in have map pure_cauchy f ≤ uniformity.lift' (preimage (prod.mk f')), from le_lift' $ assume s hs, let ⟨t, ht₁, (ht₂ : gen t ⊆ s)⟩ := (mem_lift'_sets monotone_gen).mp hs in let ⟨t', ht', (h : set.prod t' t' ⊆ t)⟩ := mem_prod_same_iff.mp (hf.right ht₁) in have t' ⊆ { y : α | (f', pure_cauchy y) ∈ gen t }, from assume x hx, (filter.prod f (pure x)).sets_of_superset (prod_mem_prod ht' $ mem_pure hx) h, f.sets_of_superset ht' $ subset.trans this (preimage_mono ht₂), ⟨f', by simp [nhds_eq_uniformity]; assumption⟩ end instance [inhabited α] : inhabited (Cauchy α) := ⟨pure_cauchy $ default α⟩ instance [h : nonempty α] : nonempty (Cauchy α) := h.rec_on $ assume a, nonempty.intro $ Cauchy.pure_cauchy a section extend variables [_root_.complete_space β] [separated β] def extend (f : α → β) : (Cauchy α → β) := if uniform_continuous f then dense_embedding_pure_cauchy.extend f else λ x, f (classical.inhabited_of_nonempty $ nonempty_Cauchy_iff.1 ⟨x⟩).default lemma extend_pure_cauchy {f : α → β} (hf : uniform_continuous f) (a : α) : extend f (pure_cauchy a) = f a := begin rw [extend, if_pos hf], exact uniformly_extend_of_emb uniform_embedding_pure_cauchy pure_cauchy_dense _ end lemma uniform_continuous_extend {f : α → β} : uniform_continuous (extend f) := begin by_cases hf : uniform_continuous f, { rw [extend, if_pos hf], exact uniform_continuous_uniformly_extend uniform_embedding_pure_cauchy pure_cauchy_dense hf }, { rw [extend, if_neg hf], exact uniform_continuous_of_const (assume a b, by congr) } end end extend end theorem Cauchy_eq {α : Type*} [inhabited α] [uniform_space α] [complete_space α] [separated α] {f g : Cauchy α} : lim f.1 = lim g.1 ↔ (f, g) ∈ separation_rel (Cauchy α) := begin split, { intros e s hs, rcases Cauchy.mem_uniformity'.1 hs with ⟨t, tu, ts⟩, apply ts, rcases comp_mem_uniformity_sets tu with ⟨d, du, dt⟩, refine mem_prod_iff.2 ⟨_, le_nhds_lim_of_cauchy f.2 (mem_nhds_right (lim f.1) du), _, le_nhds_lim_of_cauchy g.2 (mem_nhds_left (lim g.1) du), λ x h, _⟩, cases x with a b, cases h with h₁ h₂, rw ← e at h₂, exact dt ⟨_, h₁, h₂⟩ }, { intros H, refine separated_def.1 (by apply_instance) _ _ (λ t tu, _), rcases mem_uniformity_is_closed tu with ⟨d, du, dc, dt⟩, refine H {p | (lim p.1.1, lim p.2.1) ∈ t} (Cauchy.mem_uniformity'.2 ⟨d, du, λ f g h, _⟩), rcases mem_prod_iff.1 h with ⟨x, xf, y, yg, h⟩, have limc : ∀ (f : Cauchy α) (x ∈ f.1.sets), lim f.1 ∈ closure x, { intros f x xf, rw closure_eq_nhds, exact lattice.neq_bot_of_le_neq_bot f.2.1 (lattice.le_inf (le_nhds_lim_of_cauchy f.2) (le_principal_iff.2 xf)) }, have := (closure_subset_iff_subset_of_is_closed dc).2 h, rw closure_prod_eq at this, refine dt (this ⟨_, _⟩); dsimp; apply limc; assumption } end section local attribute [instance] uniform_space.separation_setoid lemma injective_separated_pure_cauchy {α : Type*} [uniform_space α] [s : separated α] : function.injective (λa:α, ⟦pure_cauchy a⟧) | a b h := separated_def.1 s _ _ $ assume s hs, let ⟨t, ht, hts⟩ := by rw [← (@uniform_embedding_pure_cauchy α _).right, filter.mem_comap_sets] at hs; exact hs in have (pure_cauchy a, pure_cauchy b) ∈ t, from quotient.exact h t ht, @hts (a, b) this end section prod variables {α : Type*} {β : Type*} [uniform_space α] [uniform_space β] def prod : Cauchy α × Cauchy β → Cauchy (α × β) := dense_embedding.extend (dense_embedding_pure_cauchy.prod dense_embedding_pure_cauchy) pure_cauchy lemma prod_pure_cauchy_pure_cauchy (a : α) (b :β) : prod (pure_cauchy a, pure_cauchy b) = pure_cauchy (a, b) := uniformly_extend_of_emb (uniform_embedding_pure_cauchy.prod uniform_embedding_pure_cauchy) (dense_embedding_pure_cauchy.prod dense_embedding_pure_cauchy).dense (a, b) lemma uniform_continuous_prod : uniform_continuous (@prod α β _ _) := uniform_continuous_uniformly_extend (uniform_embedding_pure_cauchy.prod uniform_embedding_pure_cauchy) (dense_embedding_pure_cauchy.prod dense_embedding_pure_cauchy).dense uniform_embedding_pure_cauchy.uniform_continuous end prod end Cauchy local attribute [instance] uniform_space.separation_setoid open Cauchy set namespace uniform_space variables (α : Type*) [uniform_space α] variables {β : Type*} [uniform_space β] variables {γ : Type*} [uniform_space γ] /-- Hausdorff completion of `α` -/ def completion := quotient (separation_setoid $ Cauchy α) namespace completion @[priority 50] instance : uniform_space (completion α) := by dunfold completion ; apply_instance instance : complete_space (completion α) := by dunfold completion ; apply_instance instance : separated (completion α) := by dunfold completion ; apply_instance instance : t2_space (completion α) := separated_t2 instance : regular_space (completion α) := separated_regular /-- Automatic coercion from `α` to its completion. Not always injective. -/ instance : has_coe α (completion α) := ⟨quotient.mk ∘ pure_cauchy⟩ protected lemma coe_eq : (coe : α → completion α) = quotient.mk ∘ pure_cauchy := rfl lemma uniform_continuous_coe : uniform_continuous (coe : α → completion α) := uniform_continuous.comp uniform_embedding_pure_cauchy.uniform_continuous uniform_continuous_quotient_mk lemma continuous_coe : continuous (coe : α → completion α) := uniform_continuous.continuous (uniform_continuous_coe α) lemma comap_coe_eq_uniformity : uniformity.comap (λ(p:α×α), ((p.1 : completion α), (p.2 : completion α))) = uniformity := begin have : (λx:α×α, ((x.1 : completion α), (x.2 : completion α))) = (λx:(Cauchy α)×(Cauchy α), (⟦x.1⟧, ⟦x.2⟧)) ∘ (λx:α×α, (pure_cauchy x.1, pure_cauchy x.2)), { ext ⟨a, b⟩; simp; refl }, rw [this, ← filter.comap_comap_comp, comap_quotient_eq_uniformity, uniform_embedding_pure_cauchy.2] end lemma uniform_embedding_coe [separated α] : uniform_embedding (coe : α → completion α) := ⟨injective_separated_pure_cauchy, comap_coe_eq_uniformity α⟩ variable {α} lemma dense : closure (range (coe : α → completion α)) = univ := by rw [completion.coe_eq, range_comp]; exact quotient_dense_of_dense pure_cauchy_dense lemma dense_embedding_coe [separated α]: dense_embedding (coe : α → completion α) := (uniform_embedding_coe α).dense_embedding (assume x, by rw [dense]; exact mem_univ _) lemma dense₂ : closure (range (λx:α × β, ((x.1 : completion α), (x.2 : completion β)))) = univ := by rw [← set.prod_range_range_eq, closure_prod_eq, dense, dense, univ_prod_univ] lemma dense₃ : closure (range (λx:α × (β × γ), ((x.1 : completion α), ((x.2.1 : completion β), (x.2.2 : completion γ))))) = univ := let a : α → completion α := coe, bc := λp:β × γ, ((p.1 : completion β), (p.2 : completion γ)) in show closure (range (λx:α × (β × γ), (a x.1, bc x.2))) = univ, begin rw [← set.prod_range_range_eq, @closure_prod_eq _ _ _ _ (range a) (range bc), ← univ_prod_univ], congr, exact dense, exact dense₂ end @[elab_as_eliminator] lemma induction_on {p : completion α → Prop} (a : completion α) (hp : is_closed {a | p a}) (ih : ∀a:α, p a) : p a := is_closed_property dense hp ih a @[elab_as_eliminator] lemma induction_on₂ {p : completion α → completion β → Prop} (a : completion α) (b : completion β) (hp : is_closed {x : completion α × completion β | p x.1 x.2}) (ih : ∀(a:α) (b:β), p a b) : p a b := have ∀x : completion α × completion β, p x.1 x.2, from is_closed_property dense₂ hp $ assume ⟨a, b⟩, ih a b, this (a, b) @[elab_as_eliminator] lemma induction_on₃ {p : completion α → completion β → completion γ → Prop} (a : completion α) (b : completion β) (c : completion γ) (hp : is_closed {x : completion α × completion β × completion γ | p x.1 x.2.1 x.2.2}) (ih : ∀(a:α) (b:β) (c:γ), p a b c) : p a b c := have ∀x : completion α × completion β × completion γ, p x.1 x.2.1 x.2.2, from is_closed_property dense₃ hp $ assume ⟨a, b, c⟩, ih a b c, this (a, b, c) @[elab_as_eliminator] lemma induction_on₄ {δ : Type*} [uniform_space δ] {p : completion α → completion β → completion γ → completion δ → Prop} (a : completion α) (b : completion β) (c : completion γ) (d : completion δ) (hp : is_closed {x : (completion α × completion β) × (completion γ × completion δ) | p x.1.1 x.1.2 x.2.1 x.2.2}) (ih : ∀(a:α) (b:β) (c:γ) (d : δ), p ↑a ↑b ↑c ↑d) : p a b c d := let ab := λp:α × β, ((p.1 : completion α), (p.2 : completion β)), cd := λp:γ × δ, ((p.1 : completion γ), (p.2 : completion δ)) in have dense₄ : closure (range (λx:(α × β) × (γ × δ), (ab x.1, cd x.2))) = univ, begin rw [← set.prod_range_range_eq, @closure_prod_eq _ _ _ _ (range ab) (range cd), ← univ_prod_univ], congr, exact dense₂, exact dense₂ end, have ∀x:(completion α × completion β) × (completion γ × completion δ), p x.1.1 x.1.2 x.2.1 x.2.2, from is_closed_property dense₄ hp (assume p:(α×β)×(γ×δ), ih p.1.1 p.1.2 p.2.1 p.2.2), this ((a, b), (c, d)) lemma ext [t2_space β] {f g : completion α → β} (hf : continuous f) (hg : continuous g) (h : ∀a:α, f a = g a) : f = g := funext $ assume a, completion.induction_on a (is_closed_eq hf hg) h section extension variables {f : α → β} variables [complete_space β] [separated β] /-- "Extension" to the completion. Based on `Cauchy.extend`, which is defined for any map `f` but returns an arbitrary constant value if `f` is not uniformly continuous -/ protected def extension (f : α → β) : completion α → β := quotient.lift (extend f) $ assume a b, eq_of_separated_of_uniform_continuous uniform_continuous_extend lemma uniform_continuous_extension : uniform_continuous (completion.extension f) := uniform_continuous_quotient_lift uniform_continuous_extend lemma continuous_extension : continuous (completion.extension f) := uniform_continuous_extension.continuous @[simp] lemma extension_coe (hf : uniform_continuous f) (a : α) : (completion.extension f) a = f a := extend_pure_cauchy hf a end extension section map variables {f : α → β} /-- Completion functor acting on morphisms -/ protected def map (f : α → β) : completion α → completion β := completion.extension (coe ∘ f) lemma uniform_continuous_map : uniform_continuous (completion.map f) := uniform_continuous_quotient_lift uniform_continuous_extend lemma continuous_map : continuous (completion.map f) := uniform_continuous_extension.continuous @[simp] lemma map_coe (hf : uniform_continuous f) (a : α) : (completion.map f) a = f a := by rw [completion.map, extension_coe]; from hf.comp (uniform_continuous_coe β) lemma map_unique {f : α → β} {g : completion α → completion β} (hg : uniform_continuous g) (h : ∀a:α, ↑(f a) = g a) : completion.map f = g := completion.ext continuous_map hg.continuous $ begin intro a, simp only [completion.map, (∘), h], rw [extension_coe ((uniform_continuous_coe α).comp hg)] end lemma map_id : completion.map (@id α) = id := map_unique uniform_continuous_id (assume a, rfl) lemma extension_map [complete_space γ] [separated γ] {f : β → γ} {g : α → β} (hf : uniform_continuous f) (hg : uniform_continuous g) : completion.extension f ∘ completion.map g = completion.extension (f ∘ g) := completion.ext (continuous_map.comp continuous_extension) continuous_extension $ by intro a; simp only [hg, hf, hg.comp hf, (∘), map_coe, extension_coe] lemma map_comp {f : α → β} {g : β → γ} (hf : uniform_continuous f) (hg : uniform_continuous g) : completion.map g ∘ completion.map f = completion.map (g ∘ f) := extension_map (hg.comp (uniform_continuous_coe _)) hf end map /- In this section we construct isomorphisms between the completion of a uniform space and the completion of its separation quotient -/ section separation_quotient_completion def completion_separation_quotient_equiv (α : Type u) [uniform_space α] : completion (separation_quotient α) ≃ completion α := begin refine ⟨completion.extension (separation_quotient.lift (coe : α → completion α)), completion.map quotient.mk, _, _⟩, { assume a, refine completion.induction_on a (is_closed_eq (continuous_extension.comp continuous_map) continuous_id) _, rintros ⟨a⟩, show completion.map quotient.mk (completion.extension (separation_quotient.lift coe) ↑⟦a⟧) = ↑⟦a⟧, rw [extension_coe (separation_quotient.uniform_continuous_lift _), separation_quotient.lift_mk (uniform_continuous_coe α), completion.map_coe uniform_continuous_quotient_mk] }, { assume a, refine completion.induction_on a (is_closed_eq (continuous_map.comp continuous_extension) continuous_id) _, assume a, rw [map_coe uniform_continuous_quotient_mk, extension_coe (separation_quotient.uniform_continuous_lift _), separation_quotient.lift_mk (uniform_continuous_coe α) _] } end lemma uniform_continuous_completion_separation_quotient_equiv : uniform_continuous ⇑(completion_separation_quotient_equiv α) := uniform_continuous_extension lemma uniform_continuous_completion_separation_quotient_equiv_symm : uniform_continuous ⇑(completion_separation_quotient_equiv α).symm := uniform_continuous_map end separation_quotient_completion section prod variables [uniform_space β] protected def prod {α β} [uniform_space α] [uniform_space β] (p : completion α × completion β) : completion (α × β) := quotient.lift_on₂ p.1 p.2 (λa b, ⟦Cauchy.prod (a, b)⟧) $ assume a b c d hab hcd, quotient.sound $ separated_of_uniform_continuous uniform_continuous_prod $ separation_prod.2 ⟨hab, hcd⟩ lemma uniform_continuous_prod : uniform_continuous (@completion.prod α β _ _) := uniform_continuous_quotient_lift₂ $ suffices uniform_continuous (quotient.mk ∘ Cauchy.prod), { convert this, ext ⟨a, b⟩, refl }, Cauchy.uniform_continuous_prod.comp uniform_continuous_quotient_mk lemma prod_coe_coe (a : α) (b : β) : completion.prod ((a : completion α), (b : completion β)) = (a, b) := congr_arg quotient.mk $ Cauchy.prod_pure_cauchy_pure_cauchy a b end prod section map₂ protected def map₂ (f : α → β → γ) (a : completion α) (b : completion β) : completion γ := completion.map (λp:α×β, f p.1 p.2) (completion.prod (a, b)) lemma uniform_continuous_map₂' (f : α → β → γ) : uniform_continuous (λp:completion α×completion β, completion.map₂ f p.1 p.2) := uniform_continuous.comp uniform_continuous_prod completion.uniform_continuous_map lemma continuous_map₂ {δ} [topological_space δ] {f : α → β → γ} {a : δ → completion α} {b : δ → completion β} (ha : continuous a) (hb : continuous b) : continuous (λd:δ, completion.map₂ f (a d) (b d)) := (continuous.prod_mk ha hb).comp (uniform_continuous_map₂' f).continuous lemma map₂_coe_coe (a : α) (b : β) (f : α → β → γ) (hf : uniform_continuous (λp:α×β, f p.1 p.2)) : completion.map₂ f (a : completion α) (b : completion β) = f a b := by rw [completion.map₂, completion.prod_coe_coe, completion.map_coe hf] end map₂ section group instance [has_zero α] : has_zero (completion α) := ⟨(0 : α)⟩ instance [has_neg α] : has_neg (completion α) := ⟨completion.map (λa, -a : α → α)⟩ instance [has_add α] : has_add (completion α) := ⟨completion.map₂ (+)⟩ lemma coe_zero [has_zero α] : ((0 : α) : completion α) = 0 := rfl section uniform_add_group variables [add_group α] [uniform_add_group α] lemma coe_neg (a : α) : ((- a : α) : completion α) = - a := (map_coe uniform_continuous_neg' a).symm lemma coe_add (a b : α) : ((a + b : α) : completion α) = a + b := (map₂_coe_coe a b (+) uniform_continuous_add').symm instance : add_group (completion α) := { zero_add := assume a, completion.induction_on a (is_closed_eq (continuous_map₂ continuous_const continuous_id) continuous_id) (assume a, show 0 + (a : completion α) = a, by rw [← coe_zero, ← coe_add, zero_add]), add_zero := assume a, completion.induction_on a (is_closed_eq (continuous_map₂ continuous_id continuous_const) continuous_id) (assume a, show (a : completion α) + 0 = a, by rw [← coe_zero, ← coe_add, add_zero]), add_left_neg := assume a, completion.induction_on a (is_closed_eq (continuous_map₂ completion.continuous_map continuous_id) continuous_const) (assume a, show - (a : completion α) + a = 0, by rw [← coe_neg, ← coe_add, add_left_neg, coe_zero]), add_assoc := assume a b c, completion.induction_on₃ a b c (is_closed_eq (continuous_map₂ (continuous_map₂ continuous_fst (continuous_snd.comp continuous_fst)) (continuous_snd.comp continuous_snd)) (continuous_map₂ continuous_fst (continuous_map₂ (continuous_snd.comp continuous_fst) (continuous_snd.comp continuous_snd)))) (assume a b c, show (a : completion α) + b + c = a + (b + c), by repeat { rw [← coe_add] }; rw [add_assoc]), .. completion.has_zero, .. completion.has_neg, ..completion.has_add } instance : uniform_add_group (completion α) := ⟨ (uniform_continuous.prod_mk uniform_continuous_fst (uniform_continuous_snd.comp uniform_continuous_map)).comp (uniform_continuous_map₂' (+)) ⟩ instance is_add_group_hom_coe : is_add_group_hom (coe : α → completion α) := ⟨ coe_add ⟩ lemma is_add_group_hom_extension [add_group β] [uniform_add_group β] [complete_space β] [separated β] {f : α → β} [is_add_group_hom f] (hf : continuous f) : is_add_group_hom (completion.extension f) := have hf : uniform_continuous f, from uniform_continuous_of_continuous hf, ⟨assume a b, completion.induction_on₂ a b (is_closed_eq (continuous_add'.comp continuous_extension) (continuous_add (continuous_fst.comp continuous_extension) (continuous_snd.comp continuous_extension))) (assume a b, by rw [← coe_add, extension_coe hf, extension_coe hf, extension_coe hf, is_add_group_hom.add f])⟩ lemma is_add_group_hom_map [add_group β] [uniform_add_group β] {f : α → β} [is_add_group_hom f] (hf : continuous f) : is_add_group_hom (completion.map f) := is_add_group_hom_extension (hf.comp (continuous_coe _)) section instance_max_depth -- TODO: continuous_add requires some long proofs through -- uniform_add_group / topological_add_group w.r.t prod / completion etc set_option class.instance_max_depth 52 -- set_option trace.class_instances true lemma is_add_group_hom_prod [add_group β] [uniform_add_group β] : is_add_group_hom (@completion.prod α β _ _) := ⟨assume ⟨a₁, a₂⟩ ⟨b₁, b₂⟩, begin refine completion.induction_on₄ a₁ a₂ b₁ b₂ (is_closed_eq _ _) _, { refine continuous.comp _ uniform_continuous_prod.continuous, refine continuous_add _ _, exact continuous.prod_mk (continuous_fst.comp continuous_fst) (continuous_fst.comp continuous_snd), exact continuous.prod_mk (continuous_snd.comp continuous_fst) (continuous_snd.comp continuous_snd) }, { refine continuous_add _ _, refine continuous.comp _ uniform_continuous_prod.continuous, exact continuous.prod_mk (continuous_fst.comp continuous_fst) (continuous_fst.comp continuous_snd), refine continuous.comp _ uniform_continuous_prod.continuous, exact continuous.prod_mk (continuous_snd.comp continuous_fst) (continuous_snd.comp continuous_snd) }, { assume a b c d, show completion.prod (↑a + ↑c, ↑b + ↑d) = completion.prod (↑a, ↑b) + completion.prod (↑c, ↑d), rw [← coe_add, ← coe_add, prod_coe_coe, prod_coe_coe, prod_coe_coe, ← coe_add], refl } end⟩ end instance_max_depth end uniform_add_group instance [add_comm_group α] [uniform_add_group α] : add_comm_group (completion α) := { add_comm := assume a b, completion.induction_on₂ a b (is_closed_eq (continuous_map₂ continuous_fst continuous_snd) (continuous_map₂ continuous_snd continuous_fst)) (assume a b, by rw [← coe_add, ← coe_add, add_comm]), .. completion.add_group } end group end completion end uniform_space namespace add_comm_group variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} variables [add_comm_group α] [add_comm_group β] [add_comm_group γ] /- TODO: when modules are changed to have more explicit base ring, then change replace `is_Z_bilin` by using `is_bilinear_map ℤ` from `tensor_product`. -/ class is_Z_bilin (f : α × β → γ) : Prop := (add_left : ∀ a a' b, f (a + a', b) = f (a, b) + f (a', b)) (add_right : ∀ a b b', f (a, b + b') = f (a, b) + f (a, b')) variables (f : α × β → γ) [is_Z_bilin f] instance is_Z_bilin.comp_hom {g : γ → δ} [add_comm_group δ] [is_add_group_hom g] : is_Z_bilin (g ∘ f) := by constructor; simp [(∘), is_Z_bilin.add_left f, is_Z_bilin.add_right f, is_add_group_hom.add g] instance is_Z_bilin.comp_swap : is_Z_bilin (f ∘ prod.swap) := ⟨λ a a' b, is_Z_bilin.add_right f b a a', λ a b b', is_Z_bilin.add_left f b b' a⟩ lemma is_Z_bilin.zero_left : ∀ b, f (0, b) = 0 := begin intro b, apply add_self_iff_eq_zero.1, rw ←is_Z_bilin.add_left f, simp end lemma is_Z_bilin.zero_right : ∀ a, f (a, 0) = 0 := is_Z_bilin.zero_left (f ∘ prod.swap) lemma is_Z_bilin.zero : f (0, 0) = 0 := is_Z_bilin.zero_left f 0 lemma is_Z_bilin.neg_left : ∀ a b, f (-a, b) = -f (a, b) := begin intros a b, apply eq_of_sub_eq_zero, rw [sub_eq_add_neg, neg_neg, ←is_Z_bilin.add_left f, neg_add_self, is_Z_bilin.zero_left f] end lemma is_Z_bilin.neg_right : ∀ a b, f (a, -b) = -f (a, b) := assume a b, is_Z_bilin.neg_left (f ∘ prod.swap) b a lemma is_Z_bilin.sub_left : ∀ a a' b, f (a - a', b) = f (a, b) - f (a', b) := begin intros, dsimp [algebra.sub], rw [is_Z_bilin.add_left f, is_Z_bilin.neg_left f] end lemma is_Z_bilin.sub_right : ∀ a b b', f (a, b - b') = f (a, b) - f (a,b') := assume a b b', is_Z_bilin.sub_left (f ∘ prod.swap) b b' a end add_comm_group open add_comm_group filter set function section variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} -- α, β and G are abelian topological groups, G is complete Hausdorff variables [topological_space α] [add_comm_group α] [topological_add_group α] variables [topological_space β] [add_comm_group β] [topological_add_group β] variables {G : Type*} [uniform_space G] [add_comm_group G] [uniform_add_group G] [complete_space G] [separated G] variables {ψ : α × β → G} (hψ : continuous ψ) [ψbilin : is_Z_bilin ψ] include hψ ψbilin lemma is_Z_bilin.tendsto_zero_left (x₁ : α) : tendsto ψ (nhds (x₁, 0)) (nhds 0) := begin have := continuous.tendsto hψ (x₁, 0), rwa [is_Z_bilin.zero_right ψ] at this end lemma is_Z_bilin.tendsto_zero_right (y₁ : β) : tendsto ψ (nhds (0, y₁)) (nhds 0) := begin have := continuous.tendsto hψ (0, y₁), rwa [is_Z_bilin.zero_left ψ] at this end end section variables {α : Type u} {β : Type v} variables [topological_space α] [add_comm_group α] [topological_add_group α] -- β is a dense subgroup of α, inclusion is denoted by e variables [topological_space β] [add_comm_group β] [topological_add_group β] variables {e : β → α} [is_add_group_hom e] (de : dense_embedding e) include de lemma tendsto_sub_comap_self (x₀ : α) : tendsto (λt:β×β, t.2 - t.1) (comap (λp:β×β, (e p.1, e p.2)) $ nhds (x₀, x₀)) (nhds 0) := begin have comm : (λx:α×α, x.2-x.1) ∘ (λt:β×β, (e t.1, e t.2)) = e ∘ (λt:β×β, t.2 - t.1), { ext t, change e t.2 - e t.1 = e (t.2 - t.1), rwa ← is_add_group_hom.sub e t.2 t.1 }, have lim : tendsto (λ x : α × α, x.2-x.1) (nhds (x₀, x₀)) (nhds (e 0)), { have := continuous.tendsto (continuous.comp continuous_swap continuous_sub') (x₀, x₀), simpa [-sub_eq_add_neg, sub_self, eq.symm (is_add_group_hom.zero e)] using this }, have := de.tendsto_comap_nhds_nhds lim comm, simp [-sub_eq_add_neg, this] end end namespace dense_embedding variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} variables {G : Type*} -- β is a dense subgroup of α, inclusion is denoted by e -- δ is a dense subgroup of γ, inclusion is denoted by f variables [topological_space α] [add_comm_group α] [topological_add_group α] variables [topological_space β] [add_comm_group β] [topological_add_group β] variables [topological_space γ] [add_comm_group γ] [topological_add_group γ] variables [topological_space δ] [add_comm_group δ] [topological_add_group δ] variables [uniform_space G] [add_comm_group G] [uniform_add_group G] [separated G] [complete_space G] variables {e : β → α} [is_add_group_hom e] (de : dense_embedding e) variables {f : δ → γ} [is_add_group_hom f] (df : dense_embedding f) variables {φ : β × δ → G} (hφ : continuous φ) [bilin : is_Z_bilin φ] include de df hφ bilin variables {W' : set G} (W'_nhd : W' ∈ (nhds (0 : G)).sets) include W'_nhd private lemma extend_Z_bilin_aux (x₀ : α) (y₁ : δ) : ∃ U₂ ∈ (comap e (nhds x₀)).sets, ∀ x x' ∈ U₂, φ (x' - x, y₁) ∈ W' := begin let Nx := nhds x₀, let ee := λ u : β × β, (e u.1, e u.2), have lim1 : tendsto (λ a : β × β, (a.2 - a.1, y₁)) (filter.prod (comap e Nx) (comap e Nx)) (nhds (0, y₁)), { have := tendsto.prod_mk (tendsto_sub_comap_self de x₀) (tendsto_const_nhds : tendsto (λ (p : β × β), y₁) (comap ee $ nhds (x₀, x₀)) (nhds y₁)), rw [nhds_prod_eq, prod_comap_comap_eq, ←nhds_prod_eq], exact (this : _) }, have lim := tendsto.comp lim1 (is_Z_bilin.tendsto_zero_right hφ y₁), rw tendsto_prod_self_iff at lim, exact lim W' W'_nhd, end private lemma extend_Z_bilin_key (x₀ : α) (y₀ : γ) : ∃ U ∈ (comap e (nhds x₀)).sets, ∃ V ∈ (comap f (nhds y₀)).sets, ∀ x x' ∈ U, ∀ y y' ∈ V, φ (x', y') - φ (x, y) ∈ W' := begin let Nx := nhds x₀, let Ny := nhds y₀, let dp := dense_embedding.prod de df, let ee := λ u : β × β, (e u.1, e u.2), let ff := λ u : δ × δ, (f u.1, f u.2), have lim_φ : filter.tendsto φ (nhds (0, 0)) (nhds 0), { have := continuous.tendsto hφ (0, 0), rwa [is_Z_bilin.zero φ] at this }, have lim_φ_sub_sub : tendsto (λ (p : (β × β) × (δ × δ)), φ (p.1.2 - p.1.1, p.2.2 - p.2.1)) (filter.prod (comap ee $ nhds (x₀, x₀)) (comap ff $ nhds (y₀, y₀))) (nhds 0), { have lim_sub_sub : tendsto (λ (p : (β × β) × δ × δ), (p.1.2 - p.1.1, p.2.2 - p.2.1)) (filter.prod (comap ee (nhds (x₀, x₀))) (comap ff (nhds (y₀, y₀)))) (filter.prod (nhds 0) (nhds 0)), { have := filter.prod_mono (tendsto_sub_comap_self de x₀) (tendsto_sub_comap_self df y₀), rwa prod_map_map_eq at this }, rw ← nhds_prod_eq at lim_sub_sub, exact tendsto.comp lim_sub_sub lim_φ }, rcases exists_nhds_quarter W'_nhd with ⟨W, W_nhd, W4⟩, have : ∃ U₁ ∈ (comap e (nhds x₀)).sets, ∃ V₁ ∈ (comap f (nhds y₀)).sets, ∀ x x' ∈ U₁, ∀ y y' ∈ V₁, φ (x'-x, y'-y) ∈ W, { have := tendsto_prod_iff.1 lim_φ_sub_sub W W_nhd, repeat { rw [nhds_prod_eq, ←prod_comap_comap_eq] at this }, rcases this with ⟨U, U_in, V, V_in, H⟩, rw [mem_prod_same_iff] at U_in V_in, rcases U_in with ⟨U₁, U₁_in, HU₁⟩, rcases V_in with ⟨V₁, V₁_in, HV₁⟩, existsi [U₁, U₁_in, V₁, V₁_in], intros x x' x_in x'_in y y' y_in y'_in, exact H _ _ (HU₁ (mk_mem_prod x_in x'_in)) (HV₁ (mk_mem_prod y_in y'_in)) }, rcases this with ⟨U₁, U₁_nhd, V₁, V₁_nhd, H⟩, have : ∃ x₁, x₁ ∈ U₁ := exists_mem_of_ne_empty (forall_sets_neq_empty_iff_neq_bot.2 de.comap_nhds_neq_bot U₁ U₁_nhd), rcases this with ⟨x₁, x₁_in⟩, have : ∃ y₁, y₁ ∈ V₁ := exists_mem_of_ne_empty (forall_sets_neq_empty_iff_neq_bot.2 df.comap_nhds_neq_bot V₁ V₁_nhd), rcases this with ⟨y₁, y₁_in⟩, rcases (extend_Z_bilin_aux de df hφ W_nhd x₀ y₁) with ⟨U₂, U₂_nhd, HU⟩, rcases (extend_Z_bilin_aux df de (continuous.comp continuous_swap hφ) W_nhd y₀ x₁) with ⟨V₂, V₂_nhd, HV⟩, existsi [U₁ ∩ U₂, inter_mem_sets U₁_nhd U₂_nhd, V₁ ∩ V₂, inter_mem_sets V₁_nhd V₂_nhd], rintros x x' ⟨xU₁, xU₂⟩ ⟨x'U₁, x'U₂⟩ y y' ⟨yV₁, yV₂⟩ ⟨y'V₁, y'V₂⟩, have key_formula : φ(x', y') - φ(x, y) = φ(x' - x, y₁) + φ(x' - x, y' - y₁) + φ(x₁, y' - y) + φ(x - x₁, y' - y), { repeat { rw is_Z_bilin.sub_left φ }, repeat { rw is_Z_bilin.sub_right φ }, apply eq_of_sub_eq_zero, simp }, rw key_formula, have h₁ := HU x x' xU₂ x'U₂, have h₂ := H x x' xU₁ x'U₁ y₁ y' y₁_in y'V₁, have h₃ := HV y y' yV₂ y'V₂, have h₄ := H x₁ x x₁_in xU₁ y y' yV₁ y'V₁, exact W4 h₁ h₂ h₃ h₄ end omit W'_nhd /-- Bourbaki GT III.6.5 Theorem I: ℤ-bilinear continuous maps from dense sub-groups into a complete Hausdorff group extend by continuity. Note: Bourbaki assumes that α and β are also complete Hausdorff, but this is not necessary. -/ theorem extend_Z_bilin : continuous (extend (dense_embedding.prod de df) φ) := begin let dp := dense_embedding.prod de df, refine dense_embedding.continuous_extend_of_cauchy (dense_embedding.prod de df) _, rintro ⟨x₀, y₀⟩, split, { apply map_ne_bot, apply comap_neq_bot, intros U h, rcases exists_mem_of_ne_empty (mem_closure_iff_nhds.1 (dp.dense (x₀, y₀)) U h) with ⟨x, x_in, ⟨z, z_x⟩⟩, existsi z, cc }, { suffices : map (λ (p : (β × δ) × (β × δ)), φ p.2 - φ p.1) (comap (λ (p : (β × δ) × β × δ), ((e p.1.1, f p.1.2), (e p.2.1, f p.2.2))) (filter.prod (nhds (x₀, y₀)) (nhds (x₀, y₀)))) ≤ nhds 0, by rwa [uniformity_eq_comap_nhds_zero G, prod_map_map_eq, ←map_le_iff_le_comap, filter.map_map, prod_comap_comap_eq], intros W' W'_nhd, have key := extend_Z_bilin_key de df hφ W'_nhd x₀ y₀, rcases key with ⟨U, U_nhd, V, V_nhd, h⟩, rw mem_comap_sets at U_nhd, rcases U_nhd with ⟨U', U'_nhd, U'_sub⟩, rw mem_comap_sets at V_nhd, rcases V_nhd with ⟨V', V'_nhd, V'_sub⟩, rw [mem_map, mem_comap_sets, nhds_prod_eq], existsi set.prod (set.prod U' V') (set.prod U' V'), rw mem_prod_same_iff, simp only [exists_prop], split, { have := prod_mem_prod U'_nhd V'_nhd, tauto }, { intros p h', simp only [set.mem_preimage_eq, set.prod_mk_mem_set_prod_eq] at h', rcases p with ⟨⟨x, y⟩, ⟨x', y'⟩⟩, apply h ; tauto } } end end dense_embedding namespace uniform_space.completion open dense_embedding uniform_space variables (α : Type u) [ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] [separated α] instance is_Z_bilin_mul : is_Z_bilin (λp:α×α, p.1 * p.2) := ⟨assume a a' b, add_mul a a' b, assume a b b', mul_add a b b'⟩ instance : has_one (completion α) := ⟨(1:α)⟩ instance : has_mul (completion α) := ⟨λa b, extend (dense_embedding_coe.prod dense_embedding_coe) ((coe : α → completion α) ∘ (λp:α×α, p.1 * p.2)) (a, b)⟩ lemma coe_one : ((1 : α) : completion α) = 1 := rfl lemma continuous_mul' : continuous (λp:completion α×completion α, p.1 * p.2) := suffices continuous $ extend (dense_embedding_coe.prod dense_embedding_coe) $ ((coe : α → completion α) ∘ (λp:α×α, p.1 * p.2)), { convert this, ext ⟨a, b⟩, refl }, extend_Z_bilin dense_embedding_coe dense_embedding_coe (continuous.comp continuous_mul' (continuous_coe α)) section rules variables {α} lemma coe_mul (a b : α) : ((a * b : α) : completion α) = a * b := eq.symm (extend_e_eq (dense_embedding_coe.prod dense_embedding_coe) (a, b)) lemma continuous_mul {β : Type v} [topological_space β] {f g : β → completion α} (hf : continuous f) (hg : continuous g) : continuous (λb, f b * g b) := (continuous.prod_mk hf hg).comp (continuous_mul' α) end rules instance : ring (completion α) := { one_mul := assume a, completion.induction_on a (is_closed_eq (continuous_mul continuous_const continuous_id) continuous_id) (assume a, by rw [← coe_one, ← coe_mul, one_mul]), mul_one := assume a, completion.induction_on a (is_closed_eq (continuous_mul continuous_id continuous_const) continuous_id) (assume a, by rw [← coe_one, ← coe_mul, mul_one]), mul_assoc := assume a b c, completion.induction_on₃ a b c (is_closed_eq (continuous_mul (continuous_mul continuous_fst (continuous_snd.comp continuous_fst)) (continuous_snd.comp continuous_snd)) (continuous_mul continuous_fst (continuous_mul (continuous_snd.comp continuous_fst) (continuous_snd.comp continuous_snd)))) (assume a b c, by rw [← coe_mul, ← coe_mul, ← coe_mul, ← coe_mul, mul_assoc]), left_distrib := assume a b c, completion.induction_on₃ a b c (is_closed_eq (continuous_mul continuous_fst (continuous_add (continuous_snd.comp continuous_fst) (continuous_snd.comp continuous_snd))) (continuous_add (continuous_mul continuous_fst (continuous_snd.comp continuous_fst)) (continuous_mul continuous_fst (continuous_snd.comp continuous_snd)))) (assume a b c, by rw [← coe_add, ← coe_mul, ← coe_mul, ← coe_mul, ←coe_add, mul_add]), right_distrib := assume a b c, completion.induction_on₃ a b c (is_closed_eq (continuous_mul (continuous_add continuous_fst (continuous_snd.comp continuous_fst)) (continuous_snd.comp continuous_snd)) (continuous_add (continuous_mul continuous_fst (continuous_snd.comp continuous_snd)) (continuous_mul (continuous_snd.comp continuous_fst) (continuous_snd.comp continuous_snd)))) (assume a b c, by rw [← coe_add, ← coe_mul, ← coe_mul, ← coe_mul, ←coe_add, add_mul]), ..completion.add_comm_group, ..completion.has_mul α, ..completion.has_one α } instance is_ring_hom_coe : is_ring_hom (coe : α → completion α) := ⟨coe_one α, assume a b, coe_mul a b, assume a b, coe_add a b⟩ instance is_ring_hom_extension {β : Type v} [uniform_space β] [ring β] [uniform_add_group β] [topological_ring β] [complete_space β] [separated β] {f : α → β} [is_ring_hom f] (hf : continuous f) : is_ring_hom (completion.extension f) := have hf : uniform_continuous f, from uniform_continuous_of_continuous hf, { map_one := by rw [← coe_one, extension_coe hf, is_ring_hom.map_one f], map_add := assume a b, completion.induction_on₂ a b (is_closed_eq (continuous_add'.comp continuous_extension) (continuous_add (continuous_fst.comp continuous_extension) (continuous_snd.comp continuous_extension))) (assume a b, by rw [← coe_add, extension_coe hf, extension_coe hf, extension_coe hf, is_add_group_hom.add f]), map_mul := assume a b, completion.induction_on₂ a b (is_closed_eq ((continuous_mul' α).comp continuous_extension) (_root_.continuous_mul (continuous_fst.comp continuous_extension) (continuous_snd.comp continuous_extension))) (assume a b, by rw [← coe_mul, extension_coe hf, extension_coe hf, extension_coe hf, is_ring_hom.map_mul f]) } end uniform_space.completion
0fb20a9b9c72ba980546521393524fec9cdc12f0
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/multiset/default.lean
965e0313a2ee3cea9569f50a99ab4a33577b2dbf
[ "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
414
lean
import data.multiset.antidiagonal import data.multiset.basic import data.multiset.erase_dup import data.multiset.finset_ops import data.multiset.fold import data.multiset.functor import data.multiset.intervals import data.multiset.lattice import data.multiset.nat_antidiagonal import data.multiset.nodup import data.multiset.pi import data.multiset.powerset import data.multiset.sections import data.multiset.sort
9d847ba90f13150b8f89501c1d36ee24ecd11f99
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/field_theory/splitting_field.lean
f37128d6410b69b1a8510215f016ea8ec36daefe
[ "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
38,124
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 ring_theory.adjoin_root import ring_theory.algebra_tower import ring_theory.algebraic import ring_theory.polynomial import field_theory.minpoly import linear_algebra.finite_dimensional import tactic.field_simp import algebra.polynomial.big_operators /-! # Splitting fields This file introduces the notion of a splitting field of a polynomial and provides an embedding from a splitting field to any field that splits the polynomial. A polynomial `f : polynomial K` splits over a field extension `L` of `K` if it is zero or all of its irreducible factors over `L` have degree `1`. A field extension of `K` of a polynomial `f : polynomial K` is called a splitting field if it is the smallest field extension of `K` such that `f` splits. ## Main definitions * `polynomial.splits i f`: A predicate on a field homomorphism `i : K → L` and a polynomial `f` saying that `f` is zero or all of its irreducible factors over `L` have degree `1`. * `polynomial.splitting_field f`: A fixed splitting field of the polynomial `f`. * `polynomial.is_splitting_field`: A predicate on a field to be a splitting field of a polynomial `f`. ## Main statements * `polynomial.C_leading_coeff_mul_prod_multiset_X_sub_C`: If a polynomial has as many roots as its degree, it can be written as the product of its leading coefficient with `∏ (X - a)` where `a` ranges through its roots. * `lift_of_splits`: If `K` and `L` are field extensions of a field `F` and for some finite subset `S` of `K`, the minimal polynomial of every `x ∈ K` splits as a polynomial with coefficients in `L`, then `algebra.adjoin F S` embeds into `L`. * `polynomial.is_splitting_field.lift`: An embedding of a splitting field of the polynomial `f` into another field such that `f` splits. * `polynomial.is_splitting_field.alg_equiv`: Every splitting field of a polynomial `f` is isomorpic to `splitting_field f` and thus, being a splitting field is unique up to isomorphism. -/ noncomputable theory open_locale classical big_operators universes u v w variables {F : Type u} {K : Type v} {L : Type w} namespace polynomial variables [field K] [field L] [field F] open polynomial section splits variables (i : K →+* L) /-- A polynomial `splits` iff it is zero or all of its irreducible factors have `degree` 1. -/ def splits (f : polynomial K) : Prop := f = 0 ∨ ∀ {g : polynomial L}, irreducible g → g ∣ f.map i → degree g = 1 @[simp] lemma splits_zero : splits i (0 : polynomial K) := or.inl rfl @[simp] lemma splits_C (a : K) : splits i (C a) := if ha : a = 0 then ha.symm ▸ (@C_0 K _).symm ▸ splits_zero i else have hia : i a ≠ 0, from mt ((i.injective_iff).1 i.injective _) ha, or.inr $ λ g hg ⟨p, hp⟩, absurd hg.1 (not_not.2 (is_unit_iff_degree_eq_zero.2 $ by have := congr_arg degree hp; simp [degree_C hia, @eq_comm (with_bot ℕ) 0, nat.with_bot.add_eq_zero_iff] at this; clear _fun_match; tauto)) lemma splits_of_degree_eq_one {f : polynomial K} (hf : degree f = 1) : splits i f := or.inr $ λ g hg ⟨p, hp⟩, by have := congr_arg degree hp; simp [nat.with_bot.add_eq_one_iff, hf, @eq_comm (with_bot ℕ) 1, mt is_unit_iff_degree_eq_zero.2 hg.1] at this; clear _fun_match; tauto lemma splits_of_degree_le_one {f : polynomial K} (hf : degree f ≤ 1) : splits i f := begin cases h : degree f with n, { rw [degree_eq_bot.1 h]; exact splits_zero i }, { cases n with n, { rw [eq_C_of_degree_le_zero (trans_rel_right (≤) h (le_refl _))]; exact splits_C _ _ }, { have hn : n = 0, { rw h at hf, cases n, { refl }, { exact absurd hf dec_trivial } }, exact splits_of_degree_eq_one _ (by rw [h, hn]; refl) } } end lemma splits_of_nat_degree_le_one {f : polynomial K} (hf : nat_degree f ≤ 1) : splits i f := splits_of_degree_le_one i (degree_le_of_nat_degree_le hf) lemma splits_of_nat_degree_eq_one {f : polynomial K} (hf : nat_degree f = 1) : splits i f := splits_of_nat_degree_le_one i (le_of_eq hf) lemma splits_mul {f g : polynomial K} (hf : splits i f) (hg : splits i g) : splits i (f * g) := if h : f * g = 0 then by simp [h] else or.inr $ λ p hp hpf, ((principal_ideal_ring.irreducible_iff_prime.1 hp).2.2 _ _ (show p ∣ map i f * map i g, by convert hpf; rw polynomial.map_mul)).elim (hf.resolve_left (λ hf, by simpa [hf] using h) hp) (hg.resolve_left (λ hg, by simpa [hg] using h) hp) lemma splits_of_splits_mul {f g : polynomial K} (hfg : f * g ≠ 0) (h : splits i (f * g)) : splits i f ∧ splits i g := ⟨or.inr $ λ g hgi hg, or.resolve_left h hfg hgi (by rw map_mul; exact hg.trans (dvd_mul_right _ _)), or.inr $ λ g hgi hg, or.resolve_left h hfg hgi (by rw map_mul; exact hg.trans (dvd_mul_left _ _))⟩ lemma splits_of_splits_of_dvd {f g : polynomial K} (hf0 : f ≠ 0) (hf : splits i f) (hgf : g ∣ f) : splits i g := by { obtain ⟨f, rfl⟩ := hgf, exact (splits_of_splits_mul i hf0 hf).1 } lemma splits_of_splits_gcd_left {f g : polynomial K} (hf0 : f ≠ 0) (hf : splits i f) : splits i (euclidean_domain.gcd f g) := polynomial.splits_of_splits_of_dvd i hf0 hf (euclidean_domain.gcd_dvd_left f g) lemma splits_of_splits_gcd_right {f g : polynomial K} (hg0 : g ≠ 0) (hg : splits i g) : splits i (euclidean_domain.gcd f g) := polynomial.splits_of_splits_of_dvd i hg0 hg (euclidean_domain.gcd_dvd_right f g) lemma splits_map_iff (j : L →+* F) {f : polynomial K} : splits j (f.map i) ↔ splits (j.comp i) f := by simp [splits, polynomial.map_map] theorem splits_one : splits i 1 := splits_C i 1 theorem splits_of_is_unit {u : polynomial K} (hu : is_unit u) : u.splits i := splits_of_splits_of_dvd i one_ne_zero (splits_one _) $ is_unit_iff_dvd_one.1 hu theorem splits_X_sub_C {x : K} : (X - C x).splits i := splits_of_degree_eq_one _ $ degree_X_sub_C x theorem splits_X : X.splits i := splits_of_degree_eq_one _ $ degree_X theorem splits_id_iff_splits {f : polynomial K} : (f.map i).splits (ring_hom.id L) ↔ f.splits i := by rw [splits_map_iff, ring_hom.id_comp] theorem splits_mul_iff {f g : polynomial K} (hf : f ≠ 0) (hg : g ≠ 0) : (f * g).splits i ↔ f.splits i ∧ g.splits i := ⟨splits_of_splits_mul i (mul_ne_zero hf hg), λ ⟨hfs, hgs⟩, splits_mul i hfs hgs⟩ theorem splits_prod {ι : Type u} {s : ι → polynomial K} {t : finset ι} : (∀ j ∈ t, (s j).splits i) → (∏ x in t, s x).splits i := begin refine finset.induction_on t (λ _, splits_one i) (λ a t hat ih ht, _), rw finset.forall_mem_insert at ht, rw finset.prod_insert hat, exact splits_mul i ht.1 (ih ht.2) end lemma splits_pow {f : polynomial K} (hf : f.splits i) (n : ℕ) : (f ^ n).splits i := begin rw [←finset.card_range n, ←finset.prod_const], exact splits_prod i (λ j hj, hf), end lemma splits_X_pow (n : ℕ) : (X ^ n).splits i := splits_pow i (splits_X i) n theorem splits_prod_iff {ι : Type u} {s : ι → polynomial K} {t : finset ι} : (∀ j ∈ t, s j ≠ 0) → ((∏ x in t, s x).splits i ↔ ∀ j ∈ t, (s j).splits i) := begin refine finset.induction_on t (λ _, ⟨λ _ _ h, h.elim, λ _, splits_one i⟩) (λ a t hat ih ht, _), rw finset.forall_mem_insert at ht ⊢, rw [finset.prod_insert hat, splits_mul_iff i ht.1 (finset.prod_ne_zero_iff.2 ht.2), ih ht.2] end lemma degree_eq_one_of_irreducible_of_splits {p : polynomial L} (h_nz : p ≠ 0) (hp : irreducible p) (hp_splits : splits (ring_hom.id L) p) : p.degree = 1 := begin rcases hp_splits, { contradiction }, { apply hp_splits hp, simp } end lemma exists_root_of_splits {f : polynomial K} (hs : splits i f) (hf0 : degree f ≠ 0) : ∃ x, eval₂ i x f = 0 := if hf0 : f = 0 then ⟨37, by simp [hf0]⟩ else let ⟨g, hg⟩ := wf_dvd_monoid.exists_irreducible_factor (show ¬ is_unit (f.map i), from mt is_unit_iff_degree_eq_zero.1 (by rwa degree_map)) (map_ne_zero hf0) in let ⟨x, hx⟩ := exists_root_of_degree_eq_one (hs.resolve_left hf0 hg.1 hg.2) in let ⟨i, hi⟩ := hg.2 in ⟨x, by rw [← eval_map, hi, eval_mul, show _ = _, from hx, zero_mul]⟩ lemma exists_multiset_of_splits {f : polynomial K} : splits i f → ∃ (s : multiset L), f.map i = C (i f.leading_coeff) * (s.map (λ a : L, (X : polynomial L) - C a)).prod := suffices splits (ring_hom.id _) (f.map i) → ∃ s : multiset L, f.map i = (C (f.map i).leading_coeff) * (s.map (λ a : L, (X : polynomial L) - C a)).prod, by rwa [splits_map_iff, leading_coeff_map i] at this, wf_dvd_monoid.induction_on_irreducible (f.map i) (λ _, ⟨{37}, by simp [i.map_zero]⟩) (λ u hu _, ⟨0, by conv_lhs { rw eq_C_of_degree_eq_zero (is_unit_iff_degree_eq_zero.1 hu) }; simp [leading_coeff, nat_degree_eq_of_degree_eq_some (is_unit_iff_degree_eq_zero.1 hu)]⟩) (λ f p hf0 hp ih hfs, have hpf0 : p * f ≠ 0, from mul_ne_zero hp.ne_zero hf0, let ⟨s, hs⟩ := ih (splits_of_splits_mul _ hpf0 hfs).2 in ⟨-(p * norm_unit p).coeff 0 ::ₘ s, have hp1 : degree p = 1, from hfs.resolve_left hpf0 hp (by simp), begin rw [multiset.map_cons, multiset.prod_cons, leading_coeff_mul, C_mul, mul_assoc, mul_left_comm (C f.leading_coeff), ← hs, ← mul_assoc, mul_left_inj' hf0], conv_lhs {rw eq_X_add_C_of_degree_eq_one hp1}, simp only [mul_add, coe_norm_unit_of_ne_zero hp.ne_zero, mul_comm p, coeff_neg, C_neg, sub_eq_add_neg, neg_neg, coeff_C_mul, (mul_assoc _ _ _).symm, C_mul.symm, mul_inv_cancel (show p.leading_coeff ≠ 0, from mt leading_coeff_eq_zero.1 hp.ne_zero), one_mul], end⟩) /-- Pick a root of a polynomial that splits. -/ def root_of_splits {f : polynomial K} (hf : f.splits i) (hfd : f.degree ≠ 0) : L := classical.some $ exists_root_of_splits i hf hfd theorem map_root_of_splits {f : polynomial K} (hf : f.splits i) (hfd) : f.eval₂ i (root_of_splits i hf hfd) = 0 := classical.some_spec $ exists_root_of_splits i hf hfd theorem roots_map {f : polynomial K} (hf : f.splits $ ring_hom.id K) : (f.map i).roots = (f.roots).map i := if hf0 : f = 0 then by rw [hf0, map_zero, roots_zero, roots_zero, multiset.map_zero] else have hmf0 : f.map i ≠ 0 := map_ne_zero hf0, let ⟨m, hm⟩ := exists_multiset_of_splits _ hf in have h1 : (0 : polynomial K) ∉ m.map (λ r, X - C r), from zero_nmem_multiset_map_X_sub_C _ _, have h2 : (0 : polynomial L) ∉ m.map (λ r, X - C (i r)), from zero_nmem_multiset_map_X_sub_C _ _, begin rw map_id at hm, rw hm at hf0 hmf0 ⊢, rw map_mul at hmf0 ⊢, rw [roots_mul hf0, roots_mul hmf0, map_C, roots_C, zero_add, roots_C, zero_add, map_multiset_prod, multiset.map_map], simp_rw [(∘), map_sub, map_X, map_C], rw [roots_multiset_prod _ h2, multiset.bind_map, roots_multiset_prod _ h1, multiset.bind_map], simp_rw roots_X_sub_C, rw [multiset.bind_singleton, multiset.bind_singleton, multiset.map_id'] end lemma eq_prod_roots_of_splits {p : polynomial K} {i : K →+* L} (hsplit : splits i p) : p.map i = C (i p.leading_coeff) * ((p.map i).roots.map (λ a, X - C a)).prod := begin by_cases p_eq_zero : p = 0, { rw [p_eq_zero, map_zero, leading_coeff_zero, i.map_zero, C.map_zero, zero_mul] }, obtain ⟨s, hs⟩ := exists_multiset_of_splits i hsplit, have map_ne_zero : p.map i ≠ 0 := map_ne_zero (p_eq_zero), have prod_ne_zero : C (i p.leading_coeff) * (multiset.map (λ a, X - C a) s).prod ≠ 0 := by rwa hs at map_ne_zero, have zero_nmem : (0 : polynomial L) ∉ s.map (λ a, X - C a), from zero_nmem_multiset_map_X_sub_C _ _, have map_bind_roots_eq : (s.map (λ a, X - C a)).bind (λ a, a.roots) = s, { refine multiset.induction_on s (by rw [multiset.map_zero, multiset.zero_bind]) _, intros a s ih, rw [multiset.map_cons, multiset.cons_bind, ih, roots_X_sub_C, multiset.singleton_add] }, rw [hs, roots_mul prod_ne_zero, roots_C, zero_add, roots_multiset_prod _ zero_nmem, map_bind_roots_eq] end lemma eq_prod_roots_of_splits_id {p : polynomial K} (hsplit : splits (ring_hom.id K) p) : p = C (p.leading_coeff) * (p.roots.map (λ a, X - C a)).prod := by simpa using eq_prod_roots_of_splits hsplit lemma eq_prod_roots_of_monic_of_splits_id {p : polynomial K} (m : monic p) (hsplit : splits (ring_hom.id K) p) : p = (p.roots.map (λ a, X - C a)).prod := begin convert eq_prod_roots_of_splits_id hsplit, simp [m], end lemma eq_X_sub_C_of_splits_of_single_root {x : K} {h : polynomial K} (h_splits : splits i h) (h_roots : (h.map i).roots = {i x}) : h = (C (leading_coeff h)) * (X - C x) := begin apply polynomial.map_injective _ i.injective, rw [eq_prod_roots_of_splits h_splits, h_roots], simp, end lemma nat_degree_eq_card_roots {p : polynomial K} {i : K →+* L} (hsplit : splits i p) : p.nat_degree = (p.map i).roots.card := begin by_cases p_eq_zero : p = 0, { rw [p_eq_zero, nat_degree_zero, map_zero, roots_zero, multiset.card_zero] }, have map_ne_zero : p.map i ≠ 0 := map_ne_zero (p_eq_zero), rw eq_prod_roots_of_splits hsplit at map_ne_zero, conv_lhs { rw [← nat_degree_map i, eq_prod_roots_of_splits hsplit] }, have : (0 : polynomial L) ∉ (map i p).roots.map (λ a, X - C a), from zero_nmem_multiset_map_X_sub_C _ _, simp [nat_degree_mul (left_ne_zero_of_mul map_ne_zero) (right_ne_zero_of_mul map_ne_zero), nat_degree_multiset_prod _ this] end lemma degree_eq_card_roots {p : polynomial K} {i : K →+* L} (p_ne_zero : p ≠ 0) (hsplit : splits i p) : p.degree = (p.map i).roots.card := by rw [degree_eq_nat_degree p_ne_zero, nat_degree_eq_card_roots hsplit] section UFD local attribute [instance, priority 10] principal_ideal_ring.to_unique_factorization_monoid local infix ` ~ᵤ ` : 50 := associated open unique_factorization_monoid associates lemma splits_of_exists_multiset {f : polynomial K} {s : multiset L} (hs : f.map i = C (i f.leading_coeff) * (s.map (λ a : L, (X : polynomial L) - C a)).prod) : splits i f := if hf0 : f = 0 then or.inl hf0 else or.inr $ λ p hp hdp, have ht : multiset.rel associated (normalized_factors (f.map i)) (s.map (λ a : L, (X : polynomial L) - C a)) := factors_unique (λ p hp, irreducible_of_normalized_factor _ hp) (λ p' m, begin obtain ⟨a,m,rfl⟩ := multiset.mem_map.1 m, exact irreducible_of_degree_eq_one (degree_X_sub_C _), end) (associated.symm $ calc _ ~ᵤ f.map i : ⟨(units.map C.to_monoid_hom : units L →* units (polynomial L)) (units.mk0 (f.map i).leading_coeff (mt leading_coeff_eq_zero.1 (map_ne_zero hf0))), by conv_rhs { rw [hs, ← leading_coeff_map i, mul_comm] }; refl⟩ ... ~ᵤ _ : (unique_factorization_monoid.normalized_factors_prod (by simpa using hf0)).symm), let ⟨q, hq, hpq⟩ := exists_mem_normalized_factors_of_dvd (by simpa) hp hdp in let ⟨q', hq', hqq'⟩ := multiset.exists_mem_of_rel_of_mem ht hq in let ⟨a, ha⟩ := multiset.mem_map.1 hq' in by rw [← degree_X_sub_C a, ha.2]; exact degree_eq_degree_of_associated (hpq.trans hqq') lemma splits_of_splits_id {f : polynomial K} : splits (ring_hom.id _) f → splits i f := unique_factorization_monoid.induction_on_prime f (λ _, splits_zero _) (λ _ hu _, splits_of_degree_le_one _ ((is_unit_iff_degree_eq_zero.1 hu).symm ▸ dec_trivial)) (λ a p ha0 hp ih hfi, splits_mul _ (splits_of_degree_eq_one _ ((splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).1.resolve_left hp.1 hp.irreducible (by rw map_id))) (ih (splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).2)) end UFD lemma splits_iff_exists_multiset {f : polynomial K} : splits i f ↔ ∃ (s : multiset L), f.map i = C (i f.leading_coeff) * (s.map (λ a : L, (X : polynomial L) - C a)).prod := ⟨exists_multiset_of_splits i, λ ⟨s, hs⟩, splits_of_exists_multiset i hs⟩ lemma splits_comp_of_splits (j : L →+* F) {f : polynomial K} (h : splits i f) : splits (j.comp i) f := begin change i with ((ring_hom.id _).comp i) at h, rw [← splits_map_iff], rw [← splits_map_iff i] at h, exact splits_of_splits_id _ h end /-- A monic polynomial `p` that has as many roots as its degree can be written `p = ∏(X - a)`, for `a` in `p.roots`. -/ lemma prod_multiset_X_sub_C_of_monic_of_roots_card_eq {p : polynomial K} (hmonic : p.monic) (hroots : p.roots.card = p.nat_degree) : (multiset.map (λ (a : K), X - C a) p.roots).prod = p := begin have hprodmonic : (multiset.map (λ (a : K), X - C a) p.roots).prod.monic, { simp only [prod_multiset_root_eq_finset_root (ne_zero_of_monic hmonic), monic_prod_of_monic, monic_X_sub_C, monic_pow, forall_true_iff] }, have hdegree : (multiset.map (λ (a : K), X - C a) p.roots).prod.nat_degree = p.nat_degree, { rw [← hroots, nat_degree_multiset_prod _ (zero_nmem_multiset_map_X_sub_C _ (λ a : K, a))], simp only [eq_self_iff_true, mul_one, nat.cast_id, nsmul_eq_mul, multiset.sum_repeat, multiset.map_const,nat_degree_X_sub_C, function.comp, multiset.map_map] }, obtain ⟨q, hq⟩ := prod_multiset_X_sub_C_dvd p, have qzero : q ≠ 0, { rintro rfl, apply hmonic.ne_zero, simpa only [mul_zero] using hq }, have degp : p.nat_degree = (multiset.map (λ (a : K), X - C a) p.roots).prod.nat_degree + q.nat_degree, { nth_rewrite 0 [hq], simp only [nat_degree_mul (ne_zero_of_monic hprodmonic) qzero] }, have degq : q.nat_degree = 0, { rw hdegree at degp, exact (add_right_inj p.nat_degree).mp (tactic.ring_exp.add_pf_sum_z degp rfl).symm }, obtain ⟨u, hu⟩ := is_unit_iff_degree_eq_zero.2 ((degree_eq_iff_nat_degree_eq qzero).2 degq), have hassoc : associated (multiset.map (λ (a : K), X - C a) p.roots).prod p, { rw associated, use u, rw [hu, ← hq] }, exact eq_of_monic_of_associated hprodmonic hmonic hassoc end /-- A polynomial `p` that has as many roots as its degree can be written `p = p.leading_coeff * ∏(X - a)`, for `a` in `p.roots`. -/ lemma C_leading_coeff_mul_prod_multiset_X_sub_C {p : polynomial K} (hroots : p.roots.card = p.nat_degree) : (C p.leading_coeff) * (multiset.map (λ (a : K), X - C a) p.roots).prod = p := begin by_cases hzero : p = 0, { rw [hzero, leading_coeff_zero, ring_hom.map_zero, zero_mul], }, { have hcoeff : p.leading_coeff ≠ 0, { intro h, exact hzero (leading_coeff_eq_zero.1 h) }, have hrootsnorm : (normalize p).roots.card = (normalize p).nat_degree, { rw [roots_normalize, normalize_apply, nat_degree_mul hzero (units.ne_zero _), hroots, coe_norm_unit, nat_degree_C, add_zero], }, have hprod := prod_multiset_X_sub_C_of_monic_of_roots_card_eq (monic_normalize hzero) hrootsnorm, rw [roots_normalize, normalize_apply, coe_norm_unit_of_ne_zero hzero] at hprod, calc (C p.leading_coeff) * (multiset.map (λ (a : K), X - C a) p.roots).prod = p * C ((p.leading_coeff)⁻¹ * p.leading_coeff) : by rw [hprod, mul_comm, mul_assoc, ← C_mul] ... = p * C 1 : by field_simp ... = p : by simp only [mul_one, ring_hom.map_one], }, end /-- A polynomial splits if and only if it has as many roots as its degree. -/ lemma splits_iff_card_roots {p : polynomial K} : splits (ring_hom.id K) p ↔ p.roots.card = p.nat_degree := begin split, { intro H, rw [nat_degree_eq_card_roots H, map_id] }, { intro hroots, apply (splits_iff_exists_multiset (ring_hom.id K)).2, use p.roots, simp only [ring_hom.id_apply, map_id], exact (C_leading_coeff_mul_prod_multiset_X_sub_C hroots).symm }, end lemma aeval_root_derivative_of_splits [algebra K L] {P : polynomial K} (hmo : P.monic) (hP : P.splits (algebra_map K L)) {r : L} (hr : r ∈ (P.map (algebra_map K L)).roots) : aeval r P.derivative = (multiset.map (λ a, r - a) ((P.map (algebra_map K L)).roots.erase r)).prod := begin replace hmo := monic_map (algebra_map K L) hmo, replace hP := (splits_id_iff_splits (algebra_map K L)).2 hP, rw [aeval_def, ← eval_map, ← derivative_map], nth_rewrite 0 [eq_prod_roots_of_monic_of_splits_id hmo hP], rw [eval_multiset_prod_X_sub_C_derivative hr] end end splits end polynomial section embeddings variables (F) [field F] /-- If `p` is the minimal polynomial of `a` over `F` then `F[a] ≃ₐ[F] F[x]/(p)` -/ def alg_equiv.adjoin_singleton_equiv_adjoin_root_minpoly {R : Type*} [comm_ring R] [algebra F R] (x : R) : algebra.adjoin F ({x} : set R) ≃ₐ[F] adjoin_root (minpoly F x) := alg_equiv.symm $ alg_equiv.of_bijective (alg_hom.cod_restrict (adjoin_root.lift_hom _ x $ minpoly.aeval F x) _ (λ p, adjoin_root.induction_on _ p $ λ p, (algebra.adjoin_singleton_eq_range_aeval F x).symm ▸ (polynomial.aeval _).mem_range.mpr ⟨p, rfl⟩)) ⟨(alg_hom.injective_cod_restrict _ _ _).2 $ (alg_hom.injective_iff _).2 $ λ p, adjoin_root.induction_on _ p $ λ p hp, ideal.quotient.eq_zero_iff_mem.2 $ ideal.mem_span_singleton.2 $ minpoly.dvd F x hp, λ y, let ⟨p, hp⟩ := (set_like.ext_iff.1 (algebra.adjoin_singleton_eq_range_aeval F x) (y : R)).1 y.2 in ⟨adjoin_root.mk _ p, subtype.eq hp⟩⟩ open finset /-- If a `subalgebra` is finite_dimensional as a submodule then it is `finite_dimensional`. -/ lemma finite_dimensional.of_subalgebra_to_submodule {K V : Type*} [field K] [ring V] [algebra K V] {s : subalgebra K V} (h : finite_dimensional K s.to_submodule) : finite_dimensional K s := h /-- If `K` and `L` are field extensions of `F` and we have `s : finset K` such that the minimal polynomial of each `x ∈ s` splits in `L` then `algebra.adjoin F s` embeds in `L`. -/ theorem lift_of_splits {F K L : Type*} [field F] [field K] [field L] [algebra F K] [algebra F L] (s : finset K) : (∀ x ∈ s, is_integral F x ∧ polynomial.splits (algebra_map F L) (minpoly F x)) → nonempty (algebra.adjoin F (↑s : set K) →ₐ[F] L) := begin refine finset.induction_on s (λ H, _) (λ a s has ih H, _), { rw [coe_empty, algebra.adjoin_empty], exact ⟨(algebra.of_id F L).comp (algebra.bot_equiv F K)⟩ }, rw forall_mem_insert at H, rcases H with ⟨⟨H1, H2⟩, H3⟩, cases ih H3 with f, choose H3 H4 using H3, rw [coe_insert, set.insert_eq, set.union_comm, algebra.adjoin_union_eq_adjoin_adjoin], letI := (f : algebra.adjoin F (↑s : set K) →+* L).to_algebra, haveI : finite_dimensional F (algebra.adjoin F (↑s : set K)) := ( (submodule.fg_iff_finite_dimensional _).1 (fg_adjoin_of_finite (set.finite_mem_finset s) H3)).of_subalgebra_to_submodule, letI := field_of_finite_dimensional F (algebra.adjoin F (↑s : set K)), have H5 : is_integral (algebra.adjoin F (↑s : set K)) a := is_integral_of_is_scalar_tower a H1, have H6 : (minpoly (algebra.adjoin F (↑s : set K)) a).splits (algebra_map (algebra.adjoin F (↑s : set K)) L), { refine polynomial.splits_of_splits_of_dvd _ (polynomial.map_ne_zero $ minpoly.ne_zero H1 : polynomial.map (algebra_map _ _) _ ≠ 0) ((polynomial.splits_map_iff _ _).2 _) (minpoly.dvd _ _ _), { rw ← is_scalar_tower.algebra_map_eq, exact H2 }, { rw [← is_scalar_tower.aeval_apply, minpoly.aeval] } }, obtain ⟨y, hy⟩ := polynomial.exists_root_of_splits _ H6 (ne_of_lt (minpoly.degree_pos H5)).symm, refine ⟨subalgebra.of_restrict_scalars _ _ _⟩, refine (adjoin_root.lift_hom (minpoly (algebra.adjoin F (↑s : set K)) a) y hy).comp _, exact alg_equiv.adjoin_singleton_equiv_adjoin_root_minpoly (algebra.adjoin F (↑s : set K)) a end end embeddings namespace polynomial variables [field K] [field L] [field F] open polynomial section splitting_field /-- Non-computably choose an irreducible factor from a polynomial. -/ def factor (f : polynomial K) : polynomial K := if H : ∃ g, irreducible g ∧ g ∣ f then classical.some H else X instance irreducible_factor (f : polynomial K) : irreducible (factor f) := begin rw factor, split_ifs with H, { exact (classical.some_spec H).1 }, { exact irreducible_X } end theorem factor_dvd_of_not_is_unit {f : polynomial K} (hf1 : ¬is_unit f) : factor f ∣ f := begin by_cases hf2 : f = 0, { rw hf2, exact dvd_zero _ }, rw [factor, dif_pos (wf_dvd_monoid.exists_irreducible_factor hf1 hf2)], exact (classical.some_spec $ wf_dvd_monoid.exists_irreducible_factor hf1 hf2).2 end theorem factor_dvd_of_degree_ne_zero {f : polynomial K} (hf : f.degree ≠ 0) : factor f ∣ f := factor_dvd_of_not_is_unit (mt degree_eq_zero_of_is_unit hf) theorem factor_dvd_of_nat_degree_ne_zero {f : polynomial K} (hf : f.nat_degree ≠ 0) : factor f ∣ f := factor_dvd_of_degree_ne_zero (mt nat_degree_eq_of_degree_eq_some hf) /-- Divide a polynomial f by X - C r where r is a root of f in a bigger field extension. -/ def remove_factor (f : polynomial K) : polynomial (adjoin_root $ factor f) := map (adjoin_root.of f.factor) f /ₘ (X - C (adjoin_root.root f.factor)) theorem X_sub_C_mul_remove_factor (f : polynomial K) (hf : f.nat_degree ≠ 0) : (X - C (adjoin_root.root f.factor)) * f.remove_factor = map (adjoin_root.of f.factor) f := let ⟨g, hg⟩ := factor_dvd_of_nat_degree_ne_zero hf in mul_div_by_monic_eq_iff_is_root.2 $ by rw [is_root.def, eval_map, hg, eval₂_mul, ← hg, adjoin_root.eval₂_root, zero_mul] theorem nat_degree_remove_factor (f : polynomial K) : f.remove_factor.nat_degree = f.nat_degree - 1 := by rw [remove_factor, nat_degree_div_by_monic _ (monic_X_sub_C _), nat_degree_map, nat_degree_X_sub_C] theorem nat_degree_remove_factor' {f : polynomial K} {n : ℕ} (hfn : f.nat_degree = n+1) : f.remove_factor.nat_degree = n := by rw [nat_degree_remove_factor, hfn, n.add_sub_cancel] /-- Auxiliary construction to a splitting field of a polynomial. Uses induction on the degree. -/ def splitting_field_aux (n : ℕ) : Π {K : Type u} [field K], by exactI Π (f : polynomial K), f.nat_degree = n → Type u := nat.rec_on n (λ K _ _ _, K) $ λ n ih K _ f hf, by exactI ih f.remove_factor (nat_degree_remove_factor' hf) namespace splitting_field_aux theorem succ (n : ℕ) (f : polynomial K) (hfn : f.nat_degree = n + 1) : splitting_field_aux (n+1) f hfn = splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn) := rfl instance field (n : ℕ) : Π {K : Type u} [field K], by exactI Π {f : polynomial K} (hfn : f.nat_degree = n), field (splitting_field_aux n f hfn) := nat.rec_on n (λ K _ _ _, ‹field K›) $ λ n ih K _ f hf, ih _ instance inhabited {n : ℕ} {f : polynomial K} (hfn : f.nat_degree = n) : inhabited (splitting_field_aux n f hfn) := ⟨37⟩ instance algebra (n : ℕ) : Π {K : Type u} [field K], by exactI Π {f : polynomial K} (hfn : f.nat_degree = n), algebra K (splitting_field_aux n f hfn) := nat.rec_on n (λ K _ _ _, by exactI algebra.id K) $ λ n ih K _ f hfn, by exactI @@restrict_scalars.algebra _ _ _ _ _ (ih _) _ _ instance algebra' {n : ℕ} {f : polynomial K} (hfn : f.nat_degree = n + 1) : algebra (adjoin_root f.factor) (splitting_field_aux _ _ hfn) := splitting_field_aux.algebra n _ instance algebra'' {n : ℕ} {f : polynomial K} (hfn : f.nat_degree = n + 1) : algebra K (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)) := splitting_field_aux.algebra (n+1) hfn instance algebra''' {n : ℕ} {f : polynomial K} (hfn : f.nat_degree = n + 1) : algebra (adjoin_root f.factor) (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)) := splitting_field_aux.algebra n _ instance scalar_tower {n : ℕ} {f : polynomial K} (hfn : f.nat_degree = n + 1) : is_scalar_tower K (adjoin_root f.factor) (splitting_field_aux _ _ hfn) := is_scalar_tower.of_algebra_map_eq $ λ x, rfl instance scalar_tower' {n : ℕ} {f : polynomial K} (hfn : f.nat_degree = n + 1) : is_scalar_tower K (adjoin_root f.factor) (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)) := is_scalar_tower.of_algebra_map_eq $ λ x, rfl theorem algebra_map_succ (n : ℕ) (f : polynomial K) (hfn : f.nat_degree = n + 1) : by exact algebra_map K (splitting_field_aux _ _ hfn) = (algebra_map (adjoin_root f.factor) (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn))).comp (adjoin_root.of f.factor) := rfl protected theorem splits (n : ℕ) : ∀ {K : Type u} [field K], by exactI ∀ (f : polynomial K) (hfn : f.nat_degree = n), splits (algebra_map K $ splitting_field_aux n f hfn) f := nat.rec_on n (λ K _ _ hf, by exactI splits_of_degree_le_one _ (le_trans degree_le_nat_degree $ hf.symm ▸ with_bot.coe_le_coe.2 zero_le_one)) $ λ n ih K _ f hf, by { resetI, rw [← splits_id_iff_splits, algebra_map_succ, ← map_map, splits_id_iff_splits, ← X_sub_C_mul_remove_factor f (λ h, by { rw h at hf, cases hf })], exact splits_mul _ (splits_X_sub_C _) (ih _ _) } theorem exists_lift (n : ℕ) : ∀ {K : Type u} [field K], by exactI ∀ (f : polynomial K) (hfn : f.nat_degree = n) {L : Type*} [field L], by exactI ∀ (j : K →+* L) (hf : splits j f), ∃ k : splitting_field_aux n f hfn →+* L, k.comp (algebra_map _ _) = j := nat.rec_on n (λ K _ _ _ L _ j _, by exactI ⟨j, j.comp_id⟩) $ λ n ih K _ f hf L _ j hj, by exactI have hndf : f.nat_degree ≠ 0, by { intro h, rw h at hf, cases hf }, have hfn0 : f ≠ 0, by { intro h, rw h at hndf, exact hndf rfl }, let ⟨r, hr⟩ := exists_root_of_splits _ (splits_of_splits_of_dvd j hfn0 hj (factor_dvd_of_nat_degree_ne_zero hndf)) (mt is_unit_iff_degree_eq_zero.2 f.irreducible_factor.1) in have hmf0 : map (adjoin_root.of f.factor) f ≠ 0, from map_ne_zero hfn0, have hsf : splits (adjoin_root.lift j r hr) f.remove_factor, by { rw ← X_sub_C_mul_remove_factor _ hndf at hmf0, refine (splits_of_splits_mul _ hmf0 _).2, rwa [X_sub_C_mul_remove_factor _ hndf, ← splits_id_iff_splits, map_map, adjoin_root.lift_comp_of, splits_id_iff_splits] }, let ⟨k, hk⟩ := ih f.remove_factor (nat_degree_remove_factor' hf) (adjoin_root.lift j r hr) hsf in ⟨k, by rw [algebra_map_succ, ← ring_hom.comp_assoc, hk, adjoin_root.lift_comp_of]⟩ theorem adjoin_roots (n : ℕ) : ∀ {K : Type u} [field K], by exactI ∀ (f : polynomial K) (hfn : f.nat_degree = n), algebra.adjoin K (↑(f.map $ algebra_map K $ splitting_field_aux n f hfn).roots.to_finset : set (splitting_field_aux n f hfn)) = ⊤ := nat.rec_on n (λ K _ f hf, by exactI algebra.eq_top_iff.2 (λ x, subalgebra.range_le _ ⟨x, rfl⟩)) $ λ n ih K _ f hfn, by exactI have hndf : f.nat_degree ≠ 0, by { intro h, rw h at hfn, cases hfn }, have hfn0 : f ≠ 0, by { intro h, rw h at hndf, exact hndf rfl }, have hmf0 : map (algebra_map K (splitting_field_aux n.succ f hfn)) f ≠ 0 := map_ne_zero hfn0, by { rw [algebra_map_succ, ← map_map, ← X_sub_C_mul_remove_factor _ hndf, map_mul] at hmf0 ⊢, rw [roots_mul hmf0, map_sub, map_X, map_C, roots_X_sub_C, multiset.to_finset_add, finset.coe_union, multiset.to_finset_singleton, finset.coe_singleton, algebra.adjoin_union_eq_adjoin_adjoin, ← set.image_singleton, algebra.adjoin_algebra_map K (adjoin_root f.factor) (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)), adjoin_root.adjoin_root_eq_top, algebra.map_top, is_scalar_tower.adjoin_range_to_alg_hom K (adjoin_root f.factor) (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)), ih, subalgebra.restrict_scalars_top] } end splitting_field_aux /-- A splitting field of a polynomial. -/ def splitting_field (f : polynomial K) := splitting_field_aux _ f rfl namespace splitting_field variables (f : polynomial K) instance : field (splitting_field f) := splitting_field_aux.field _ _ instance inhabited : inhabited (splitting_field f) := ⟨37⟩ instance : algebra K (splitting_field f) := splitting_field_aux.algebra _ _ protected theorem splits : splits (algebra_map K (splitting_field f)) f := splitting_field_aux.splits _ _ _ variables [algebra K L] (hb : splits (algebra_map K L) f) /-- Embeds the splitting field into any other field that splits the polynomial. -/ def lift : splitting_field f →ₐ[K] L := { commutes' := λ r, by { have := classical.some_spec (splitting_field_aux.exists_lift _ _ _ _ hb), exact ring_hom.ext_iff.1 this r }, .. classical.some (splitting_field_aux.exists_lift _ _ _ _ hb) } theorem adjoin_roots : algebra.adjoin K (↑(f.map (algebra_map K $ splitting_field f)).roots.to_finset : set (splitting_field f)) = ⊤ := splitting_field_aux.adjoin_roots _ _ _ theorem adjoin_root_set : algebra.adjoin K (f.root_set f.splitting_field) = ⊤ := adjoin_roots f end splitting_field variables (K L) [algebra K L] /-- Typeclass characterising splitting fields. -/ class is_splitting_field (f : polynomial K) : Prop := (splits [] : splits (algebra_map K L) f) (adjoin_roots [] : algebra.adjoin K (↑(f.map (algebra_map K L)).roots.to_finset : set L) = ⊤) namespace is_splitting_field variables {K} instance splitting_field (f : polynomial K) : is_splitting_field K (splitting_field f) f := ⟨splitting_field.splits f, splitting_field.adjoin_roots f⟩ section scalar_tower variables {K L F} [algebra F K] [algebra F L] [is_scalar_tower F K L] variables {K} instance map (f : polynomial F) [is_splitting_field F L f] : is_splitting_field K L (f.map $ algebra_map F K) := ⟨by { rw [splits_map_iff, ← is_scalar_tower.algebra_map_eq], exact splits L f }, subalgebra.restrict_scalars_injective F $ by { rw [map_map, ← is_scalar_tower.algebra_map_eq, subalgebra.restrict_scalars_top, eq_top_iff, ← adjoin_roots L f, algebra.adjoin_le_iff], exact λ x hx, @algebra.subset_adjoin K _ _ _ _ _ _ hx }⟩ variables {K} (L) theorem splits_iff (f : polynomial K) [is_splitting_field K L f] : polynomial.splits (ring_hom.id K) f ↔ (⊤ : subalgebra K L) = ⊥ := ⟨λ h, eq_bot_iff.2 $ adjoin_roots L f ▸ (roots_map (algebra_map K L) h).symm ▸ algebra.adjoin_le_iff.2 (λ y hy, let ⟨x, hxs, hxy⟩ := finset.mem_image.1 (by rwa multiset.to_finset_map at hy) in hxy ▸ set_like.mem_coe.2 $ subalgebra.algebra_map_mem _ _), λ h, @ring_equiv.to_ring_hom_refl K _ ▸ ring_equiv.trans_symm (ring_equiv.of_bijective _ $ algebra.bijective_algebra_map_iff.2 h) ▸ by { rw ring_equiv.to_ring_hom_trans, exact splits_comp_of_splits _ _ (splits L f) }⟩ theorem mul (f g : polynomial F) (hf : f ≠ 0) (hg : g ≠ 0) [is_splitting_field F K f] [is_splitting_field K L (g.map $ algebra_map F K)] : is_splitting_field F L (f * g) := ⟨(is_scalar_tower.algebra_map_eq F K L).symm ▸ splits_mul _ (splits_comp_of_splits _ _ (splits K f)) ((splits_map_iff _ _).1 (splits L $ g.map $ algebra_map F K)), by rw [map_mul, roots_mul (mul_ne_zero (map_ne_zero hf : f.map (algebra_map F L) ≠ 0) (map_ne_zero hg)), multiset.to_finset_add, finset.coe_union, algebra.adjoin_union_eq_adjoin_adjoin, is_scalar_tower.algebra_map_eq F K L, ← map_map, roots_map (algebra_map K L) ((splits_id_iff_splits $ algebra_map F K).2 $ splits K f), multiset.to_finset_map, finset.coe_image, algebra.adjoin_algebra_map, adjoin_roots, algebra.map_top, is_scalar_tower.adjoin_range_to_alg_hom, ← map_map, adjoin_roots, subalgebra.restrict_scalars_top]⟩ end scalar_tower /-- Splitting field of `f` embeds into any field that splits `f`. -/ def lift [algebra K F] (f : polynomial K) [is_splitting_field K L f] (hf : polynomial.splits (algebra_map K F) f) : L →ₐ[K] F := if hf0 : f = 0 then (algebra.of_id K F).comp $ (algebra.bot_equiv K L : (⊥ : subalgebra K L) →ₐ[K] K).comp $ by { rw ← (splits_iff L f).1 (show f.splits (ring_hom.id K), from hf0.symm ▸ splits_zero _), exact algebra.to_top } else alg_hom.comp (by { rw ← adjoin_roots L f, exact classical.choice (lift_of_splits _ $ λ y hy, have aeval y f = 0, from (eval₂_eq_eval_map _).trans $ (mem_roots $ by exact map_ne_zero hf0).1 (multiset.mem_to_finset.mp hy), ⟨(is_algebraic_iff_is_integral _).1 ⟨f, hf0, this⟩, splits_of_splits_of_dvd _ hf0 hf $ minpoly.dvd _ _ this⟩) }) algebra.to_top theorem finite_dimensional (f : polynomial K) [is_splitting_field K L f] : finite_dimensional K L := ⟨@algebra.top_to_submodule K L _ _ _ ▸ adjoin_roots L f ▸ fg_adjoin_of_finite (set.finite_mem_finset _) (λ y hy, if hf : f = 0 then by { rw [hf, map_zero, roots_zero] at hy, cases hy } else (is_algebraic_iff_is_integral _).1 ⟨f, hf, (eval₂_eq_eval_map _).trans $ (mem_roots $ by exact map_ne_zero hf).1 (multiset.mem_to_finset.mp hy)⟩)⟩ instance (f : polynomial K) : _root_.finite_dimensional K f.splitting_field := finite_dimensional f.splitting_field f /-- Any splitting field is isomorphic to `splitting_field f`. -/ def alg_equiv (f : polynomial K) [is_splitting_field K L f] : L ≃ₐ[K] splitting_field f := begin refine alg_equiv.of_bijective (lift L f $ splits (splitting_field f) f) ⟨ring_hom.injective (lift L f $ splits (splitting_field f) f).to_ring_hom, _⟩, haveI := finite_dimensional (splitting_field f) f, haveI := finite_dimensional L f, have : finite_dimensional.finrank K L = finite_dimensional.finrank K (splitting_field f) := le_antisymm (linear_map.finrank_le_finrank_of_injective (show function.injective (lift L f $ splits (splitting_field f) f).to_linear_map, from ring_hom.injective (lift L f $ splits (splitting_field f) f : L →+* f.splitting_field))) (linear_map.finrank_le_finrank_of_injective (show function.injective (lift (splitting_field f) f $ splits L f).to_linear_map, from ring_hom.injective (lift (splitting_field f) f $ splits L f : f.splitting_field →+* L))), change function.surjective (lift L f $ splits (splitting_field f) f).to_linear_map, refine (linear_map.injective_iff_surjective_of_finrank_eq_finrank this).1 _, exact ring_hom.injective (lift L f $ splits (splitting_field f) f : L →+* f.splitting_field) end end is_splitting_field end splitting_field end polynomial
50d2789d9850ea61481fb188336f21ae4060ada1
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/category_theory/abelian/pseudoelements.lean
055e4785eb1ae4a48e3414ab724b68729d0d7274
[ "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
18,860
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import category_theory.abelian.exact import category_theory.over /-! # Pseudoelements in abelian categories A *pseudoelement* of an object `X` in an abelian category `C` is an equivalence class of arrows ending in `X`, where two arrows are considered equivalent if we can find two epimorphisms with a common domain making a commutative square with the two arrows. While the construction shows that pseudoelements are actually subobjects of `X` rather than "elements", it is possible to chase these pseudoelements through commutative diagrams in an abelian category to prove exactness properties. This is done using some "diagram-chasing metatheorems" proved in this file. In many cases, a proof in the category of abelian groups can more or less directly be converted into a proof using pseudoelements. A classic application of pseudoelements are diagram lemmas like the four lemma or the snake lemma. Pseudoelements are in some ways weaker than actual elements in a concrete category. The most important limitation is that there is no extensionality principle: If `f g : X ⟶ Y`, then `∀ x ∈ X, f x = g x` does not necessarily imply that `f = g` (however, if `f = 0` or `g = 0`, it does). A corollary of this is that we can not define arrows in abelian categories by dictating their action on pseudoelements. Thus, a usual style of proofs in abelian categories is this: First, we construct some morphism using universal properties, and then we use diagram chasing of pseudoelements to verify that is has some desirable property such as exactness. It should be noted that the Freyd-Mitchell embedding theorem gives a vastly stronger notion of pseudoelement (in particular one that gives extensionality). However, this theorem is quite difficult to prove and probably out of reach for a formal proof for the time being. ## Main results We define the type of pseudoelements of an object and, in particular, the zero pseudoelement. We prove that every morphism maps the zero pseudoelement to the zero pseudoelement (`apply_zero`) and that a zero morphism maps every pseudoelement to the zero pseudoelement (`zero_apply`) Here are the metatheorems we provide: * A morphism `f` is zero if and only if it is the zero function on pseudoelements. * A morphism `f` is an epimorphism if and only if it is surjective on pseudoelements. * A morphism `f` is a monomorphism if and only if it is injective on pseudoelements if and only if `∀ a, f a = 0 → f = 0`. * A sequence `f, g` of morphisms is exact if and only if `∀ a, g (f a) = 0` and `∀ b, g b = 0 → ∃ a, f a = b`. * If `f` is a morphism and `a, a'` are such that `f a = f a'`, then there is some pseudoelement `a''` such that `f a'' = 0` and for every `g` we have `g a' = 0 → g a = g a''`. We can think of `a''` as `a - a'`, but don't get too carried away by that: pseudoelements of an object do not form an abelian group. ## Notations We introduce coercions from an object of an abelian category to the set of its pseudoelements and from a morphism to the function it induces on pseudoelements. These coercions must be explicitly enabled via local instances: `local attribute [instance] object_to_sort hom_to_fun` ## Implementation notes It appears that sometimes the coercion from morphisms to functions does not work, i.e., writing `g a` raises a "function expected" error. This error can be fixed by writing `(g : X ⟶ Y) a`. ## References * [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2] -/ open category_theory open category_theory.limits open category_theory.abelian open category_theory.preadditive universes v u namespace category_theory.abelian variables {C : Type u} [category.{v} C] local attribute [instance] over.coe_from_hom /-- This is just composition of morphisms in `C`. Another way to express this would be `(over.map f).obj a`, but our definition has nicer definitional properties. -/ def app {P Q : C} (f : P ⟶ Q) (a : over P) : over Q := a.hom ≫ f @[simp] lemma app_hom {P Q : C} (f : P ⟶ Q) (a : over P) : (app f a).hom = a.hom ≫ f := rfl /-- Two arrows `f : X ⟶ P` and `g : Y ⟶ P` are called pseudo-equal if there is some object `R` and epimorphisms `p : R ⟶ X` and `q : R ⟶ Y` such that `p ≫ f = q ≫ g`. -/ def pseudo_equal (P : C) (f g : over P) : Prop := ∃ (R : C) (p : R ⟶ f.1) (q : R ⟶ g.1) (_ : epi p) (_ : epi q), p ≫ f.hom = q ≫ g.hom lemma pseudo_equal_refl {P : C} : reflexive (pseudo_equal P) := λ f, ⟨f.1, 𝟙 f.1, 𝟙 f.1, by apply_instance, by apply_instance, by simp⟩ lemma pseudo_equal_symm {P : C} : symmetric (pseudo_equal P) := λ f g ⟨R, p, q, ep, eq, comm⟩, ⟨R, q, p, eq, ep, comm.symm⟩ variables [abelian.{v} C] section /-- Pseudoequality is transitive: Just take the pullback. The pullback morphisms will be epimorphisms since in an abelian category, pullbacks of epimorphisms are epimorphisms. -/ lemma pseudo_equal_trans {P : C} : transitive (pseudo_equal P) := λ f g h ⟨R, p, q, ep, eq, comm⟩ ⟨R', p', q', ep', eq', comm'⟩, begin refine ⟨pullback q p', pullback.fst ≫ p, pullback.snd ≫ q', _, _, _⟩, { resetI, exact epi_comp _ _ }, { resetI, exact epi_comp _ _ }, { rw [category.assoc, comm, ←category.assoc, pullback.condition, category.assoc, comm', category.assoc] } end end /-- The arrows with codomain `P` equipped with the equivalence relation of being pseudo-equal. -/ def pseudoelement.setoid (P : C) : setoid (over P) := ⟨_, ⟨pseudo_equal_refl, pseudo_equal_symm, pseudo_equal_trans⟩⟩ local attribute [instance] pseudoelement.setoid /-- A `pseudoelement` of `P` is just an equivalence class of arrows ending in `P` by being pseudo-equal. -/ def pseudoelement (P : C) : Type (max u v) := quotient (pseudoelement.setoid P) namespace pseudoelement /-- A coercion from an object of an abelian category to its pseudoelements. -/ def object_to_sort : has_coe_to_sort C (Type (max u v)) := ⟨λ P, pseudoelement P⟩ local attribute [instance] object_to_sort /-- A coercion from an arrow with codomain `P` to its associated pseudoelement. -/ def over_to_sort {P : C} : has_coe (over P) (pseudoelement P) := ⟨quot.mk (pseudo_equal P)⟩ local attribute [instance] over_to_sort lemma over_coe_def {P Q : C} (a : Q ⟶ P) : (a : pseudoelement P) = ⟦a⟧ := rfl /-- If two elements are pseudo-equal, then their composition with a morphism is, too. -/ lemma pseudo_apply_aux {P Q : C} (f : P ⟶ Q) (a b : over P) : a ≈ b → app f a ≈ app f b := λ ⟨R, p, q, ep, eq, comm⟩, ⟨R, p, q, ep, eq, show p ≫ a.hom ≫ f = q ≫ b.hom ≫ f, by rw reassoc_of comm⟩ /-- A morphism `f` induces a function `pseudo_apply f` on pseudoelements. -/ def pseudo_apply {P Q : C} (f : P ⟶ Q) : P → Q := quotient.map (λ (g : over P), app f g) (pseudo_apply_aux f) /-- A coercion from morphisms to functions on pseudoelements -/ def hom_to_fun {P Q : C} : has_coe_to_fun (P ⟶ Q) (λ _, P → Q) := ⟨pseudo_apply⟩ local attribute [instance] hom_to_fun lemma pseudo_apply_mk {P Q : C} (f : P ⟶ Q) (a : over P) : f ⟦a⟧ = ⟦a.hom ≫ f⟧ := rfl /-- Applying a pseudoelement to a composition of morphisms is the same as composing with each morphism. Sadly, this is not a definitional equality, but at least it is true. -/ theorem comp_apply {P Q R : C} (f : P ⟶ Q) (g : Q ⟶ R) (a : P) : (f ≫ g) a = g (f a) := quotient.induction_on a $ λ x, quotient.sound $ by { unfold app, rw [←category.assoc, over.coe_hom] } /-- Composition of functions on pseudoelements is composition of morphisms. -/ theorem comp_comp {P Q R : C} (f : P ⟶ Q) (g : Q ⟶ R) : g ∘ f = f ≫ g := funext $ λ x, (comp_apply _ _ _).symm section zero /-! In this section we prove that for every `P` there is an equivalence class that contains precisely all the zero morphisms ending in `P` and use this to define *the* zero pseudoelement. -/ section local attribute [instance] has_binary_biproducts.of_has_binary_products /-- The arrows pseudo-equal to a zero morphism are precisely the zero morphisms -/ lemma pseudo_zero_aux {P : C} (Q : C) (f : over P) : f ≈ (0 : Q ⟶ P) ↔ f.hom = 0 := ⟨λ ⟨R, p, q, ep, eq, comm⟩, by exactI zero_of_epi_comp p (by simp [comm]), λ hf, ⟨biprod f.1 Q, biprod.fst, biprod.snd, by apply_instance, by apply_instance, by rw [hf, over.coe_hom, has_zero_morphisms.comp_zero, has_zero_morphisms.comp_zero]⟩⟩ end lemma zero_eq_zero' {P Q R : C} : ⟦((0 : Q ⟶ P) : over P)⟧ = ⟦((0 : R ⟶ P) : over P)⟧ := quotient.sound $ (pseudo_zero_aux R _).2 rfl /-- The zero pseudoelement is the class of a zero morphism -/ def pseudo_zero {P : C} : P := ⟦(0 : P ⟶ P)⟧ /-- We can not use `pseudo_zero` as a global `has_zero` instance, as it would trigger on any type class search for `has_zero` applied to a `coe_sort`. This would be too expensive. -/ def has_zero {P : C} : has_zero P := ⟨pseudo_zero⟩ localized "attribute [instance] category_theory.abelian.pseudoelement.has_zero" in pseudoelement instance {P : C} : inhabited (pseudoelement P) := ⟨0⟩ lemma pseudo_zero_def {P : C} : (0 : pseudoelement P) = ⟦(0 : P ⟶ P)⟧ := rfl @[simp] lemma zero_eq_zero {P Q : C} : ⟦((0 : Q ⟶ P) : over P)⟧ = (0 : pseudoelement P) := zero_eq_zero' /-- The pseudoelement induced by an arrow is zero precisely when that arrow is zero -/ lemma pseudo_zero_iff {P : C} (a : over P) : (a : P) = 0 ↔ a.hom = 0 := by { rw ←pseudo_zero_aux P a, exact quotient.eq } end zero open_locale pseudoelement /-- Morphisms map the zero pseudoelement to the zero pseudoelement -/ @[simp] theorem apply_zero {P Q : C} (f : P ⟶ Q) : f 0 = 0 := by { rw [pseudo_zero_def, pseudo_apply_mk], simp } /-- The zero morphism maps every pseudoelement to 0. -/ @[simp] theorem zero_apply {P : C} (Q : C) (a : P) : (0 : P ⟶ Q) a = 0 := quotient.induction_on a $ λ a', by { rw [pseudo_zero_def, pseudo_apply_mk], simp } /-- An extensionality lemma for being the zero arrow. -/ @[ext] theorem zero_morphism_ext {P Q : C} (f : P ⟶ Q) : (∀ a, f a = 0) → f = 0 := λ h, by { rw ←category.id_comp f, exact (pseudo_zero_iff ((𝟙 P ≫ f) : over Q)).1 (h (𝟙 P)) } @[ext] theorem zero_morphism_ext' {P Q : C} (f : P ⟶ Q) : (∀ a, f a = 0) → 0 = f := eq.symm ∘ zero_morphism_ext f theorem eq_zero_iff {P Q : C} (f : P ⟶ Q) : f = 0 ↔ ∀ a, f a = 0 := ⟨λ h a, by simp [h], zero_morphism_ext _⟩ /-- A monomorphism is injective on pseudoelements. -/ theorem pseudo_injective_of_mono {P Q : C} (f : P ⟶ Q) [mono f] : function.injective f := λ abar abar', quotient.induction_on₂ abar abar' $ λ a a' ha, quotient.sound $ have ⟦(a.hom ≫ f : over Q)⟧ = ⟦a'.hom ≫ f⟧, by convert ha, match quotient.exact this with ⟨R, p, q, ep, eq, comm⟩ := ⟨R, p, q, ep, eq, (cancel_mono f).1 $ by { simp only [category.assoc], exact comm }⟩ end /-- A morphism that is injective on pseudoelements only maps the zero element to zero. -/ lemma zero_of_map_zero {P Q : C} (f : P ⟶ Q) : function.injective f → ∀ a, f a = 0 → a = 0 := λ h a ha, by { rw ←apply_zero f at ha, exact h ha } /-- A morphism that only maps the zero pseudoelement to zero is a monomorphism. -/ theorem mono_of_zero_of_map_zero {P Q : C} (f : P ⟶ Q) : (∀ a, f a = 0 → a = 0) → mono f := λ h, (mono_iff_cancel_zero _).2 $ λ R g hg, (pseudo_zero_iff (g : over P)).1 $ h _ $ show f g = 0, from (pseudo_zero_iff (g ≫ f : over Q)).2 hg section /-- An epimorphism is surjective on pseudoelements. -/ theorem pseudo_surjective_of_epi {P Q : C} (f : P ⟶ Q) [epi f] : function.surjective f := λ qbar, quotient.induction_on qbar $ λ q, ⟨((pullback.fst : pullback f q.hom ⟶ P) : over P), quotient.sound $ ⟨pullback f q.hom, 𝟙 (pullback f q.hom), pullback.snd, by apply_instance, by apply_instance, by rw [category.id_comp, ←pullback.condition, app_hom, over.coe_hom]⟩⟩ end /-- A morphism that is surjective on pseudoelements is an epimorphism. -/ theorem epi_of_pseudo_surjective {P Q : C} (f : P ⟶ Q) : function.surjective f → epi f := λ h, match h (𝟙 Q) with ⟨pbar, hpbar⟩ := match quotient.exists_rep pbar with ⟨p, hp⟩ := have ⟦(p.hom ≫ f : over Q)⟧ = ⟦𝟙 Q⟧, by { rw ←hp at hpbar, exact hpbar }, match quotient.exact this with ⟨R, x, y, ex, ey, comm⟩ := @epi_of_epi_fac _ _ _ _ _ (x ≫ p.hom) f y ey $ by { dsimp at comm, rw [category.assoc, comm], apply category.comp_id } end end end section /-- Two morphisms in an exact sequence are exact on pseudoelements. -/ theorem pseudo_exact_of_exact {P Q R : C} {f : P ⟶ Q} {g : Q ⟶ R} [exact f g] : (∀ a, g (f a) = 0) ∧ (∀ b, g b = 0 → ∃ a, f a = b) := ⟨λ a, by { rw [←comp_apply, exact.w], exact zero_apply _ _ }, λ b', quotient.induction_on b' $ λ b hb, have hb' : b.hom ≫ g = 0, from (pseudo_zero_iff _).1 hb, begin -- By exactness, b factors through im f = ker g via some c obtain ⟨c, hc⟩ := kernel_fork.is_limit.lift' (is_limit_image f g) _ hb', -- We compute the pullback of the map into the image and c. -- The pseudoelement induced by the first pullback map will be our preimage. use (pullback.fst : pullback (images.factor_thru_image f) c ⟶ P), -- It remains to show that the image of this element under f is pseudo-equal to b. apply quotient.sound, -- pullback.snd is an epimorphism because the map onto the image is! refine ⟨pullback (images.factor_thru_image f) c, 𝟙 _, pullback.snd, by apply_instance, by apply_instance, _⟩, -- Now we can verify that the diagram commutes. calc 𝟙 (pullback (images.factor_thru_image f) c) ≫ pullback.fst ≫ f = pullback.fst ≫ f : category.id_comp _ ... = pullback.fst ≫ images.factor_thru_image f ≫ kernel.ι (cokernel.π f) : by rw images.image.fac ... = (pullback.snd ≫ c) ≫ kernel.ι (cokernel.π f) : by rw [←category.assoc, pullback.condition] ... = pullback.snd ≫ b.hom : by { rw category.assoc, congr' } end⟩ end lemma apply_eq_zero_of_comp_eq_zero {P Q R : C} (f : Q ⟶ R) (a : P ⟶ Q) : a ≫ f = 0 → f a = 0 := λ h, by simp [over_coe_def, pseudo_apply_mk, over.coe_hom, h] section /-- If two morphisms are exact on pseudoelements, they are exact. -/ theorem exact_of_pseudo_exact {P Q R : C} (f : P ⟶ Q) (g : Q ⟶ R) : (∀ a, g (f a) = 0) ∧ (∀ b, g b = 0 → ∃ a, f a = b) → exact f g := λ ⟨h₁, h₂⟩, (abelian.exact_iff _ _).2 ⟨zero_morphism_ext _ $ λ a, by rw [comp_apply, h₁ a], begin -- If we apply g to the pseudoelement induced by its kernel, we get 0 (of course!). have : g (kernel.ι g) = 0 := apply_eq_zero_of_comp_eq_zero _ _ (kernel.condition _), -- By pseudo-exactness, we get a preimage. obtain ⟨a', ha⟩ := h₂ _ this, obtain ⟨a, ha'⟩ := quotient.exists_rep a', rw ←ha' at ha, obtain ⟨Z, r, q, er, eq, comm⟩ := quotient.exact ha, -- Consider the pullback of kernel.ι (cokernel.π f) and kernel.ι g. -- The commutative diagram given by the pseudo-equality f a = b induces -- a cone over this pullback, so we get a factorization z. obtain ⟨z, hz₁, hz₂⟩ := @pullback.lift' _ _ _ _ _ _ (kernel.ι (cokernel.π f)) (kernel.ι g) _ (r ≫ a.hom ≫ images.factor_thru_image f) q (by { simp only [category.assoc, images.image.fac], exact comm }), -- Let's give a name to the second pullback morphism. let j : pullback (kernel.ι (cokernel.π f)) (kernel.ι g) ⟶ kernel g := pullback.snd, -- Since q is an epimorphism, in particular this means that j is an epimorphism. haveI pe : epi j := by exactI epi_of_epi_fac hz₂, -- But is is also a monomorphism, because kernel.ι (cokernel.π f) is: A kernel is -- always a monomorphism and the pullback of a monomorphism is a monomorphism. -- But mono + epi = iso, so j is an isomorphism. haveI : is_iso j := is_iso_of_mono_of_epi _, -- But then kernel.ι g can be expressed using all of the maps of the pullback square, and we -- are done. rw (iso.eq_inv_comp (as_iso j)).2 pullback.condition.symm, simp only [category.assoc, kernel.condition, has_zero_morphisms.comp_zero] end⟩ end /-- If two pseudoelements `x` and `y` have the same image under some morphism `f`, then we can form their "difference" `z`. This pseudoelement has the properties that `f z = 0` and for all morphisms `g`, if `g y = 0` then `g z = g x`. -/ theorem sub_of_eq_image {P Q : C} (f : P ⟶ Q) (x y : P) : f x = f y → ∃ z, f z = 0 ∧ ∀ (R : C) (g : P ⟶ R), (g : P ⟶ R) y = 0 → g z = g x := quotient.induction_on₂ x y $ λ a a' h, match quotient.exact h with ⟨R, p, q, ep, eq, comm⟩ := let a'' : R ⟶ P := p ≫ a.hom - q ≫ a'.hom in ⟨a'', ⟨show ⟦((p ≫ a.hom - q ≫ a'.hom) ≫ f : over Q)⟧ = ⟦(0 : Q ⟶ Q)⟧, by { dsimp at comm, simp [sub_eq_zero.2 comm] }, λ Z g hh, begin obtain ⟨X, p', q', ep', eq', comm'⟩ := quotient.exact hh, have : a'.hom ≫ g = 0, { apply (epi_iff_cancel_zero _).1 ep' _ (a'.hom ≫ g), simpa using comm' }, apply quotient.sound, -- Can we prevent quotient.sound from giving us this weird `coe_b` thingy? change app g (a'' : over P) ≈ app g a, exact ⟨R, 𝟙 R, p, by apply_instance, ep, by simp [sub_eq_add_neg, this]⟩ end⟩⟩ end variable [limits.has_pullbacks C] /-- If `f : P ⟶ R` and `g : Q ⟶ R` are morphisms and `p : P` and `q : Q` are pseudoelements such that `f p = g q`, then there is some `s : pullback f g` such that `fst s = p` and `snd s = q`. Remark: Borceux claims that `s` is unique. I was unable to transform his proof sketch into a pen-and-paper proof of this fact, so naturally I was not able to formalize the proof. -/ theorem pseudo_pullback {P Q R : C} {f : P ⟶ R} {g : Q ⟶ R} {p : P} {q : Q} : f p = g q → ∃ s, (pullback.fst : pullback f g ⟶ P) s = p ∧ (pullback.snd : pullback f g ⟶ Q) s = q := quotient.induction_on₂ p q $ λ x y h, begin obtain ⟨Z, a, b, ea, eb, comm⟩ := quotient.exact h, obtain ⟨l, hl₁, hl₂⟩ := @pullback.lift' _ _ _ _ _ _ f g _ (a ≫ x.hom) (b ≫ y.hom) (by { simp only [category.assoc], exact comm }), exact ⟨l, ⟨quotient.sound ⟨Z, 𝟙 Z, a, by apply_instance, ea, by rwa category.id_comp⟩, quotient.sound ⟨Z, 𝟙 Z, b, by apply_instance, eb, by rwa category.id_comp⟩⟩⟩ end end pseudoelement end category_theory.abelian
e3d815b6ccab8844121c5bda811c8dbeb050766f
bb31430994044506fa42fd667e2d556327e18dfe
/src/analysis/convex/between.lean
11d1e62efd2cce816f11f56df1928506ddc25294
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
33,365
lean
/- Copyright (c) 2022 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import data.set.intervals.group import analysis.convex.segment import linear_algebra.affine_space.finite_dimensional import tactic.field_simp /-! # Betweenness in affine spaces This file defines notions of a point in an affine space being between two given points. ## Main definitions * `affine_segment R x y`: The segment of points weakly between `x` and `y`. * `wbtw R x y z`: The point `y` is weakly between `x` and `z`. * `sbtw R x y z`: The point `y` is strictly between `x` and `z`. -/ variables (R : Type*) {V V' P P' : Type*} open affine_equiv affine_map open_locale big_operators section ordered_ring variables [ordered_ring R] [add_comm_group V] [module R V] [add_torsor V P] variables [add_comm_group V'] [module R V'] [add_torsor V' P'] include V /-- The segment of points weakly between `x` and `y`. When convexity is refactored to support abstract affine combination spaces, this will no longer need to be a separate definition from `segment`. However, lemmas involving `+ᵥ` or `-ᵥ` will still be relevant after such a refactoring, as distinct from versions involving `+` or `-` in a module. -/ def affine_segment (x y : P) := line_map x y '' (set.Icc (0 : R) 1) lemma affine_segment_eq_segment (x y : V) : affine_segment R x y = segment R x y := by rw [segment_eq_image_line_map, affine_segment] lemma affine_segment_comm (x y : P) : affine_segment R x y = affine_segment R y x := begin refine set.ext (λ z, _), split; { rintro ⟨t, ht, hxy⟩, refine ⟨1 - t, _, _⟩, { rwa [set.sub_mem_Icc_iff_right, sub_self, sub_zero] }, { rwa [line_map_apply_one_sub] } }, end lemma left_mem_affine_segment (x y : P) : x ∈ affine_segment R x y := ⟨0, set.left_mem_Icc.2 zero_le_one, line_map_apply_zero _ _⟩ lemma right_mem_affine_segment (x y : P) : y ∈ affine_segment R x y := ⟨1, set.right_mem_Icc.2 zero_le_one, line_map_apply_one _ _⟩ include V' variables {R} @[simp] lemma affine_segment_image (f : P →ᵃ[R] P') (x y : P) : f '' affine_segment R x y = affine_segment R (f x) (f y) := begin rw [affine_segment, affine_segment, set.image_image, ←comp_line_map], refl end omit V' variables (R) @[simp] lemma affine_segment_const_vadd_image (x y : P) (v : V) : ((+ᵥ) v) '' affine_segment R x y = affine_segment R (v +ᵥ x) (v +ᵥ y) := affine_segment_image (affine_equiv.const_vadd R P v : P →ᵃ[R] P) x y @[simp] lemma affine_segment_vadd_const_image (x y : V) (p : P) : (+ᵥ p) '' affine_segment R x y = affine_segment R (x +ᵥ p) (y +ᵥ p) := affine_segment_image (affine_equiv.vadd_const R p : V →ᵃ[R] P) x y @[simp] lemma affine_segment_const_vsub_image (x y p : P) : ((-ᵥ) p) '' affine_segment R x y = affine_segment R (p -ᵥ x) (p -ᵥ y) := affine_segment_image (affine_equiv.const_vsub R p : P →ᵃ[R] V) x y @[simp] lemma affine_segment_vsub_const_image (x y p : P) : (-ᵥ p) '' affine_segment R x y = affine_segment R (x -ᵥ p) (y -ᵥ p) := affine_segment_image ((affine_equiv.vadd_const R p).symm : P →ᵃ[R] V) x y variables {R} @[simp] lemma mem_const_vadd_affine_segment {x y z : P} (v : V) : v +ᵥ z ∈ affine_segment R (v +ᵥ x) (v +ᵥ y) ↔ z ∈ affine_segment R x y := by rw [←affine_segment_const_vadd_image, (add_action.injective v).mem_set_image] @[simp] lemma mem_vadd_const_affine_segment {x y z : V} (p : P) : z +ᵥ p ∈ affine_segment R (x +ᵥ p) (y +ᵥ p) ↔ z ∈ affine_segment R x y := by rw [←affine_segment_vadd_const_image, (vadd_right_injective p).mem_set_image] variables {R} @[simp] lemma mem_const_vsub_affine_segment {x y z : P} (p : P) : p -ᵥ z ∈ affine_segment R (p -ᵥ x) (p -ᵥ y) ↔ z ∈ affine_segment R x y := by rw [←affine_segment_const_vsub_image, (vsub_right_injective p).mem_set_image] @[simp] lemma mem_vsub_const_affine_segment {x y z : P} (p : P) : z -ᵥ p ∈ affine_segment R (x -ᵥ p) (y -ᵥ p) ↔ z ∈ affine_segment R x y := by rw [←affine_segment_vsub_const_image, (vsub_left_injective p).mem_set_image] variables (R) /-- The point `y` is weakly between `x` and `z`. -/ def wbtw (x y z : P) : Prop := y ∈ affine_segment R x z /-- The point `y` is strictly between `x` and `z`. -/ def sbtw (x y z : P) : Prop := wbtw R x y z ∧ y ≠ x ∧ y ≠ z variables {R} include V' lemma wbtw.map {x y z : P} (h : wbtw R x y z) (f : P →ᵃ[R] P') : wbtw R (f x) (f y) (f z) := begin rw [wbtw, ←affine_segment_image], exact set.mem_image_of_mem _ h end lemma function.injective.wbtw_map_iff {x y z : P} {f : P →ᵃ[R] P'} (hf : function.injective f) : wbtw R (f x) (f y) (f z) ↔ wbtw R x y z := begin refine ⟨λ h, _, λ h, h.map _⟩, rwa [wbtw, ←affine_segment_image, hf.mem_set_image] at h end lemma function.injective.sbtw_map_iff {x y z : P} {f : P →ᵃ[R] P'} (hf : function.injective f) : sbtw R (f x) (f y) (f z) ↔ sbtw R x y z := by simp_rw [sbtw, hf.wbtw_map_iff, hf.ne_iff] @[simp] lemma affine_equiv.wbtw_map_iff {x y z : P} (f : P ≃ᵃ[R] P') : wbtw R (f x) (f y) (f z) ↔ wbtw R x y z := begin refine function.injective.wbtw_map_iff (_ : function.injective f.to_affine_map), exact f.injective end @[simp] lemma affine_equiv.sbtw_map_iff {x y z : P} (f : P ≃ᵃ[R] P') : sbtw R (f x) (f y) (f z) ↔ sbtw R x y z := begin refine function.injective.sbtw_map_iff (_ : function.injective f.to_affine_map), exact f.injective end omit V' @[simp] lemma wbtw_const_vadd_iff {x y z : P} (v : V) : wbtw R (v +ᵥ x) (v +ᵥ y) (v +ᵥ z) ↔ wbtw R x y z := mem_const_vadd_affine_segment _ @[simp] lemma wbtw_vadd_const_iff {x y z : V} (p : P) : wbtw R (x +ᵥ p) (y +ᵥ p) (z +ᵥ p) ↔ wbtw R x y z := mem_vadd_const_affine_segment _ @[simp] lemma wbtw_const_vsub_iff {x y z : P} (p : P) : wbtw R (p -ᵥ x) (p -ᵥ y) (p -ᵥ z) ↔ wbtw R x y z := mem_const_vsub_affine_segment _ @[simp] lemma wbtw_vsub_const_iff {x y z : P} (p : P) : wbtw R (x -ᵥ p) (y -ᵥ p) (z -ᵥ p) ↔ wbtw R x y z := mem_vsub_const_affine_segment _ @[simp] lemma sbtw_const_vadd_iff {x y z : P} (v : V) : sbtw R (v +ᵥ x) (v +ᵥ y) (v +ᵥ z) ↔ sbtw R x y z := by simp_rw [sbtw, wbtw_const_vadd_iff, (add_action.injective v).ne_iff] @[simp] lemma sbtw_vadd_const_iff {x y z : V} (p : P) : sbtw R (x +ᵥ p) (y +ᵥ p) (z +ᵥ p) ↔ sbtw R x y z := by simp_rw [sbtw, wbtw_vadd_const_iff, (vadd_right_injective p).ne_iff] @[simp] lemma sbtw_const_vsub_iff {x y z : P} (p : P) : sbtw R (p -ᵥ x) (p -ᵥ y) (p -ᵥ z) ↔ sbtw R x y z := by simp_rw [sbtw, wbtw_const_vsub_iff, (vsub_right_injective p).ne_iff] @[simp] lemma sbtw_vsub_const_iff {x y z : P} (p : P) : sbtw R (x -ᵥ p) (y -ᵥ p) (z -ᵥ p) ↔ sbtw R x y z := by simp_rw [sbtw, wbtw_vsub_const_iff, (vsub_left_injective p).ne_iff] lemma sbtw.wbtw {x y z : P} (h : sbtw R x y z) : wbtw R x y z := h.1 lemma sbtw.ne_left {x y z : P} (h : sbtw R x y z) : y ≠ x := h.2.1 lemma sbtw.left_ne {x y z : P} (h : sbtw R x y z) : x ≠ y := h.2.1.symm lemma sbtw.ne_right {x y z : P} (h : sbtw R x y z) : y ≠ z := h.2.2 lemma sbtw.right_ne {x y z : P} (h : sbtw R x y z) : z ≠ y := h.2.2.symm lemma sbtw.mem_image_Ioo {x y z : P} (h : sbtw R x y z) : y ∈ line_map x z '' (set.Ioo (0 : R) 1) := begin rcases h with ⟨⟨t, ht, rfl⟩, hyx, hyz⟩, rcases set.eq_endpoints_or_mem_Ioo_of_mem_Icc ht with rfl|rfl|ho, { exfalso, simpa using hyx }, { exfalso, simpa using hyz }, { exact ⟨t, ho, rfl⟩ } end lemma wbtw.mem_affine_span {x y z : P} (h : wbtw R x y z) : y ∈ line[R, x, z] := begin rcases h with ⟨r, ⟨-, rfl⟩⟩, exact line_map_mem_affine_span_pair _ _ _ end lemma wbtw_comm {x y z : P} : wbtw R x y z ↔ wbtw R z y x := by rw [wbtw, wbtw, affine_segment_comm] alias wbtw_comm ↔ wbtw.symm _ lemma sbtw_comm {x y z : P} : sbtw R x y z ↔ sbtw R z y x := by rw [sbtw, sbtw, wbtw_comm, ←and_assoc, ←and_assoc, and.right_comm] alias sbtw_comm ↔ sbtw.symm _ variables (R) @[simp] lemma wbtw_self_left (x y : P) : wbtw R x x y := left_mem_affine_segment _ _ _ @[simp] lemma wbtw_self_right (x y : P) : wbtw R x y y := right_mem_affine_segment _ _ _ @[simp] lemma wbtw_self_iff {x y : P} : wbtw R x y x ↔ y = x := begin refine ⟨λ h, _, λ h, _⟩, { simpa [wbtw, affine_segment] using h }, { rw h, exact wbtw_self_left R x x } end @[simp] lemma not_sbtw_self_left (x y : P) : ¬ sbtw R x x y := λ h, h.ne_left rfl @[simp] lemma not_sbtw_self_right (x y : P) : ¬ sbtw R x y y := λ h, h.ne_right rfl variables {R} lemma wbtw.left_ne_right_of_ne_left {x y z : P} (h : wbtw R x y z) (hne : y ≠ x) : x ≠ z := begin rintro rfl, rw wbtw_self_iff at h, exact hne h end lemma wbtw.left_ne_right_of_ne_right {x y z : P} (h : wbtw R x y z) (hne : y ≠ z) : x ≠ z := begin rintro rfl, rw wbtw_self_iff at h, exact hne h end lemma sbtw.left_ne_right {x y z : P} (h : sbtw R x y z) : x ≠ z := h.wbtw.left_ne_right_of_ne_left h.2.1 lemma sbtw_iff_mem_image_Ioo_and_ne [no_zero_smul_divisors R V] {x y z : P} : sbtw R x y z ↔ y ∈ line_map x z '' (set.Ioo (0 : R) 1) ∧ x ≠ z := begin refine ⟨λ h, ⟨h.mem_image_Ioo, h.left_ne_right⟩, λ h, _⟩, rcases h with ⟨⟨t, ht, rfl⟩, hxz⟩, refine ⟨⟨t, set.mem_Icc_of_Ioo ht, rfl⟩, _⟩, rw [line_map_apply, ←@vsub_ne_zero V, ←@vsub_ne_zero V _ _ _ _ z, vadd_vsub_assoc, vadd_vsub_assoc, ←neg_vsub_eq_vsub_rev z x, ←@neg_one_smul R, ←add_smul, ←sub_eq_add_neg], simp [smul_ne_zero, hxz.symm, sub_eq_zero, ht.1.ne.symm, ht.2.ne] end variables (R) @[simp] lemma not_sbtw_self (x y : P) : ¬ sbtw R x y x := λ h, h.left_ne_right rfl lemma wbtw_swap_left_iff [no_zero_smul_divisors R V] {x y : P} (z : P) : (wbtw R x y z ∧ wbtw R y x z) ↔ x = y := begin split, { rintro ⟨hxyz, hyxz⟩, rcases hxyz with ⟨ty, hty, rfl⟩, rcases hyxz with ⟨tx, htx, hx⟩, simp_rw [line_map_apply, ←add_vadd] at hx, rw [←@vsub_eq_zero_iff_eq V, vadd_vsub, vsub_vadd_eq_vsub_sub, smul_sub, smul_smul, ←sub_smul, ←add_smul, smul_eq_zero] at hx, rcases hx with h|h, { nth_rewrite 0 ←mul_one tx at h, rw [←mul_sub, add_eq_zero_iff_neg_eq] at h, have h' : ty = 0, { refine le_antisymm _ hty.1, rw [←h, left.neg_nonpos_iff], exact mul_nonneg htx.1 (sub_nonneg.2 hty.2) }, simp [h'] }, { rw vsub_eq_zero_iff_eq at h, simp [h] } }, { rintro rfl, exact ⟨wbtw_self_left _ _ _, wbtw_self_left _ _ _⟩ } end lemma wbtw_swap_right_iff [no_zero_smul_divisors R V] (x : P) {y z : P} : (wbtw R x y z ∧ wbtw R x z y) ↔ y = z := begin nth_rewrite 0 wbtw_comm, nth_rewrite 1 wbtw_comm, rw eq_comm, exact wbtw_swap_left_iff R x end lemma wbtw_rotate_iff [no_zero_smul_divisors R V] (x : P) {y z : P} : (wbtw R x y z ∧ wbtw R z x y) ↔ x = y := by rw [wbtw_comm, wbtw_swap_right_iff, eq_comm] variables {R} lemma wbtw.swap_left_iff [no_zero_smul_divisors R V] {x y z : P} (h : wbtw R x y z) : wbtw R y x z ↔ x = y := by rw [←wbtw_swap_left_iff R z, and_iff_right h] lemma wbtw.swap_right_iff [no_zero_smul_divisors R V] {x y z : P} (h : wbtw R x y z) : wbtw R x z y ↔ y = z := by rw [←wbtw_swap_right_iff R x, and_iff_right h] lemma wbtw.rotate_iff [no_zero_smul_divisors R V] {x y z : P} (h : wbtw R x y z) : wbtw R z x y ↔ x = y := by rw [←wbtw_rotate_iff R x, and_iff_right h] lemma sbtw.not_swap_left [no_zero_smul_divisors R V] {x y z : P} (h : sbtw R x y z) : ¬ wbtw R y x z := λ hs, h.left_ne (h.wbtw.swap_left_iff.1 hs) lemma sbtw.not_swap_right [no_zero_smul_divisors R V] {x y z : P} (h : sbtw R x y z) : ¬ wbtw R x z y := λ hs, h.ne_right (h.wbtw.swap_right_iff.1 hs) lemma sbtw.not_rotate [no_zero_smul_divisors R V] {x y z : P} (h : sbtw R x y z) : ¬ wbtw R z x y := λ hs, h.left_ne (h.wbtw.rotate_iff.1 hs) @[simp] lemma wbtw_line_map_iff [no_zero_smul_divisors R V] {x y : P} {r : R} : wbtw R x (line_map x y r) y ↔ x = y ∨ r ∈ set.Icc (0 : R) 1 := begin by_cases hxy : x = y, { simp [hxy] }, rw [or_iff_right hxy, wbtw, affine_segment, (line_map_injective R hxy).mem_set_image] end @[simp] lemma sbtw_line_map_iff [no_zero_smul_divisors R V] {x y : P} {r : R} : sbtw R x (line_map x y r) y ↔ x ≠ y ∧ r ∈ set.Ioo (0 : R) 1 := begin rw [sbtw_iff_mem_image_Ioo_and_ne, and_comm, and_congr_right], intro hxy, rw (line_map_injective R hxy).mem_set_image end omit V @[simp] lemma wbtw_mul_sub_add_iff [no_zero_divisors R] {x y r : R} : wbtw R x (r * (y - x) + x) y ↔ x = y ∨ r ∈ set.Icc (0 : R) 1 := wbtw_line_map_iff @[simp] lemma sbtw_mul_sub_add_iff [no_zero_divisors R] {x y r : R} : sbtw R x (r * (y - x) + x) y ↔ x ≠ y ∧ r ∈ set.Ioo (0 : R) 1 := sbtw_line_map_iff @[simp] lemma wbtw_zero_one_iff {x : R} : wbtw R 0 x 1 ↔ x ∈ set.Icc (0 : R) 1 := begin simp_rw [wbtw, affine_segment, set.mem_image, line_map_apply_ring], simp end @[simp] lemma wbtw_one_zero_iff {x : R} : wbtw R 1 x 0 ↔ x ∈ set.Icc (0 : R) 1 := by rw [wbtw_comm, wbtw_zero_one_iff] @[simp] lemma sbtw_zero_one_iff {x : R} : sbtw R 0 x 1 ↔ x ∈ set.Ioo (0 : R) 1 := begin rw [sbtw, wbtw_zero_one_iff, set.mem_Icc, set.mem_Ioo], exact ⟨λ h, ⟨h.1.1.lt_of_ne (ne.symm h.2.1), h.1.2.lt_of_ne h.2.2⟩, λ h, ⟨⟨h.1.le, h.2.le⟩, h.1.ne', h.2.ne⟩⟩ end @[simp] lemma sbtw_one_zero_iff {x : R} : sbtw R 1 x 0 ↔ x ∈ set.Ioo (0 : R) 1 := by rw [sbtw_comm, sbtw_zero_one_iff] include V lemma wbtw.trans_left {w x y z : P} (h₁ : wbtw R w y z) (h₂ : wbtw R w x y) : wbtw R w x z := begin rcases h₁ with ⟨t₁, ht₁, rfl⟩, rcases h₂ with ⟨t₂, ht₂, rfl⟩, refine ⟨t₂ * t₁, ⟨mul_nonneg ht₂.1 ht₁.1, mul_le_one ht₂.2 ht₁.1 ht₁.2⟩, _⟩, simp [line_map_apply, smul_smul] end lemma wbtw.trans_right {w x y z : P} (h₁ : wbtw R w x z) (h₂ : wbtw R x y z) : wbtw R w y z := begin rw wbtw_comm at *, exact h₁.trans_left h₂ end lemma wbtw.trans_sbtw_left [no_zero_smul_divisors R V] {w x y z : P} (h₁ : wbtw R w y z) (h₂ : sbtw R w x y) : sbtw R w x z := begin refine ⟨h₁.trans_left h₂.wbtw, h₂.ne_left, _⟩, rintro rfl, exact h₂.right_ne ((wbtw_swap_right_iff R w).1 ⟨h₁, h₂.wbtw⟩) end lemma wbtw.trans_sbtw_right [no_zero_smul_divisors R V] {w x y z : P} (h₁ : wbtw R w x z) (h₂ : sbtw R x y z) : sbtw R w y z := begin rw wbtw_comm at *, rw sbtw_comm at *, exact h₁.trans_sbtw_left h₂ end lemma sbtw.trans_left [no_zero_smul_divisors R V] {w x y z : P} (h₁ : sbtw R w y z) (h₂ : sbtw R w x y) : sbtw R w x z := h₁.wbtw.trans_sbtw_left h₂ lemma sbtw.trans_right [no_zero_smul_divisors R V] {w x y z : P} (h₁ : sbtw R w x z) (h₂ : sbtw R x y z) : sbtw R w y z := h₁.wbtw.trans_sbtw_right h₂ lemma wbtw.trans_left_ne [no_zero_smul_divisors R V] {w x y z : P} (h₁ : wbtw R w y z) (h₂ : wbtw R w x y) (h : y ≠ z) : x ≠ z := begin rintro rfl, exact h (h₁.swap_right_iff.1 h₂) end lemma wbtw.trans_right_ne [no_zero_smul_divisors R V] {w x y z : P} (h₁ : wbtw R w x z) (h₂ : wbtw R x y z) (h : w ≠ x) : w ≠ y := begin rintro rfl, exact h (h₁.swap_left_iff.1 h₂) end lemma sbtw.trans_wbtw_left_ne [no_zero_smul_divisors R V] {w x y z : P} (h₁ : sbtw R w y z) (h₂ : wbtw R w x y) : x ≠ z := h₁.wbtw.trans_left_ne h₂ h₁.ne_right lemma sbtw.trans_wbtw_right_ne [no_zero_smul_divisors R V] {w x y z : P} (h₁ : sbtw R w x z) (h₂ : wbtw R x y z) : w ≠ y := h₁.wbtw.trans_right_ne h₂ h₁.left_ne /- Calls to `affine_combination` are slow to elaborate (generally, not just for this lemma), and without the use of `@finset.affine_combination R V _ _ _ _ _ _` for at least three of the six calls in this lemma statement, elaboration of the statement times out (even if the proof is replaced by `sorry`). -/ lemma sbtw.affine_combination_of_mem_affine_span_pair [no_zero_divisors R] [no_zero_smul_divisors R V] {ι : Type*} {p : ι → P} (ha : affine_independent R p) {w w₁ w₂ : ι → R} {s : finset ι} (hw : ∑ i in s, w i = 1) (hw₁ : ∑ i in s, w₁ i = 1) (hw₂ : ∑ i in s, w₂ i = 1) (h : s.affine_combination p w ∈ line[R, s.affine_combination p w₁, s.affine_combination p w₂]) {i : ι} (his : i ∈ s) (hs : sbtw R (w₁ i) (w i) (w₂ i)) : sbtw R (@finset.affine_combination R V _ _ _ _ _ _ s p w₁) (@finset.affine_combination R V _ _ _ _ _ _ s p w) (@finset.affine_combination R V _ _ _ _ _ _ s p w₂) := begin rw affine_combination_mem_affine_span_pair ha hw hw₁ hw₂ at h, rcases h with ⟨r, hr⟩, dsimp only at hr, rw [hr i his, sbtw_mul_sub_add_iff] at hs, change ∀ i ∈ s, w i = ((r • (w₂ - w₁) + w₁) i) at hr, rw s.affine_combination_congr hr (λ _ _, rfl), dsimp only, rw [←s.weighted_vsub_vadd_affine_combination, s.weighted_vsub_const_smul, ←s.affine_combination_vsub, ←line_map_apply, sbtw_line_map_iff, and_iff_left hs.2, ←@vsub_ne_zero V, s.affine_combination_vsub], intro hz, have hw₁w₂ : ∑ i in s, (w₁ - w₂) i = 0, { simp_rw [pi.sub_apply, finset.sum_sub_distrib, hw₁, hw₂, sub_self] }, refine hs.1 _, have ha' := ha s (w₁ - w₂) hw₁w₂ hz i his, rwa [pi.sub_apply, sub_eq_zero] at ha' end end ordered_ring section strict_ordered_comm_ring variables [strict_ordered_comm_ring R] [add_comm_group V] [module R V] [add_torsor V P] include V variables {R} lemma wbtw.same_ray_vsub {x y z : P} (h : wbtw R x y z) : same_ray R (y -ᵥ x) (z -ᵥ y) := begin rcases h with ⟨t, ⟨ht0, ht1⟩, rfl⟩, simp_rw line_map_apply, rcases ht0.lt_or_eq with ht0' | rfl, swap, { simp }, rcases ht1.lt_or_eq with ht1' | rfl, swap, { simp }, refine or.inr (or.inr ⟨1 - t, t, sub_pos.2 ht1', ht0', _⟩), simp [vsub_vadd_eq_vsub_sub, smul_sub, smul_smul, ←sub_smul], ring_nf end lemma wbtw.same_ray_vsub_left {x y z : P} (h : wbtw R x y z) : same_ray R (y -ᵥ x) (z -ᵥ x) := begin rcases h with ⟨t, ⟨ht0, ht1⟩, rfl⟩, simpa [line_map_apply] using same_ray_nonneg_smul_left (z -ᵥ x) ht0 end lemma wbtw.same_ray_vsub_right {x y z : P} (h : wbtw R x y z) : same_ray R (z -ᵥ x) (z -ᵥ y) := begin rcases h with ⟨t, ⟨ht0, ht1⟩, rfl⟩, simpa [line_map_apply, vsub_vadd_eq_vsub_sub, sub_smul] using same_ray_nonneg_smul_right (z -ᵥ x) (sub_nonneg.2 ht1) end end strict_ordered_comm_ring section linear_ordered_ring variables [linear_ordered_ring R] [add_comm_group V] [module R V] [add_torsor V P] include V variables {R} /-- Suppose lines from two vertices of a triangle to interior points of the opposite side meet at `p`. Then `p` lies in the interior of the first (and by symmetry the other) segment from a vertex to the point on the opposite side. -/ lemma sbtw_of_sbtw_of_sbtw_of_mem_affine_span_pair [no_zero_smul_divisors R V] {t : affine.triangle R P} {i₁ i₂ i₃ : fin 3} (h₁₂ : i₁ ≠ i₂) {p₁ p₂ p : P} (h₁ : sbtw R (t.points i₂) p₁ (t.points i₃)) (h₂ : sbtw R (t.points i₁) p₂ (t.points i₃)) (h₁' : p ∈ line[R, t.points i₁, p₁]) (h₂' : p ∈ line[R, t.points i₂, p₂]) : sbtw R (t.points i₁) p p₁ := begin -- Should not be needed; see comments on local instances in `data.sign`. letI : decidable_rel ((<) : R → R → Prop) := linear_ordered_ring.decidable_lt, have h₁₃ : i₁ ≠ i₃, { rintro rfl, simpa using h₂ }, have h₂₃ : i₂ ≠ i₃, { rintro rfl, simpa using h₁ }, have h3 : ∀ i : fin 3, i = i₁ ∨ i = i₂ ∨ i = i₃, { clear h₁ h₂ h₁' h₂', dec_trivial! }, have hu : (finset.univ : finset (fin 3)) = {i₁, i₂, i₃}, { clear h₁ h₂ h₁' h₂', dec_trivial! }, have hp : p ∈ affine_span R (set.range t.points), { have hle : line[R, t.points i₁, p₁] ≤ affine_span R (set.range t.points), { refine affine_span_pair_le_of_mem_of_mem (mem_affine_span _ (set.mem_range_self _)) _, have hle : line[R, t.points i₂, t.points i₃] ≤ affine_span R (set.range t.points), { refine affine_span_mono _ _, simp [set.insert_subset] }, rw affine_subspace.le_def' at hle, exact hle _ h₁.wbtw.mem_affine_span }, rw affine_subspace.le_def' at hle, exact hle _ h₁' }, have h₁i := h₁.mem_image_Ioo, have h₂i := h₂.mem_image_Ioo, rw set.mem_image at h₁i h₂i, rcases h₁i with ⟨r₁, ⟨hr₁0, hr₁1⟩, rfl⟩, rcases h₂i with ⟨r₂, ⟨hr₂0, hr₂1⟩, rfl⟩, rcases eq_affine_combination_of_mem_affine_span_of_fintype hp with ⟨w, hw, rfl⟩, have h₁s := sign_eq_of_affine_combination_mem_affine_span_single_line_map t.independent hw (finset.mem_univ _) (finset.mem_univ _) (finset.mem_univ _) h₁₂ h₁₃ h₂₃ hr₁0 hr₁1 h₁', have h₂s := sign_eq_of_affine_combination_mem_affine_span_single_line_map t.independent hw (finset.mem_univ _) (finset.mem_univ _) (finset.mem_univ _) h₁₂.symm h₂₃ h₁₃ hr₂0 hr₂1 h₂', dsimp only at h₁s h₂s, rw [←finset.univ.affine_combination_affine_combination_single_weights R t.points (finset.mem_univ i₁), ←finset.univ.affine_combination_affine_combination_line_map_weights t.points (finset.mem_univ _) (finset.mem_univ _)] at ⊢ h₁', refine sbtw.affine_combination_of_mem_affine_span_pair t.independent hw (finset.univ.sum_affine_combination_single_weights R (finset.mem_univ _)) (finset.univ.sum_affine_combination_line_map_weights (finset.mem_univ _) (finset.mem_univ _) _) h₁' (finset.mem_univ i₁) _, rw [finset.affine_combination_single_weights_apply_self, finset.affine_combination_line_map_weights_apply_of_ne h₁₂ h₁₃, sbtw_one_zero_iff], have hs : ∀ i : fin 3, sign (w i) = sign (w i₃), { intro i, rcases h3 i with rfl | rfl | rfl, { exact h₂s }, { exact h₁s }, { refl } }, have hss : sign (∑ i, w i) = 1, { simp [hw] }, have hs' := sign_sum (finset.univ_nonempty) (sign (w i₃)) (λ i _, hs i), rw hs' at hss, simp_rw [hss, sign_eq_one_iff] at hs, refine ⟨hs i₁, _⟩, rw hu at hw, rw [finset.sum_insert, finset.sum_insert, finset.sum_singleton] at hw, { by_contra hle, rw not_lt at hle, exact (hle.trans_lt (lt_add_of_pos_right _ (left.add_pos (hs i₂) (hs i₃)))).ne' hw }, { simp [h₂₃] }, { simp [h₁₂, h₁₃] } end end linear_ordered_ring section linear_ordered_field variables [linear_ordered_field R] [add_comm_group V] [module R V] [add_torsor V P] include V variables {R} lemma wbtw_iff_left_eq_or_right_mem_image_Ici {x y z : P} : wbtw R x y z ↔ x = y ∨ z ∈ line_map x y '' (set.Ici (1 : R)) := begin refine ⟨λ h, _, λ h, _⟩, { rcases h with ⟨r, ⟨hr0, hr1⟩, rfl⟩, rcases hr0.lt_or_eq with hr0' | rfl, { rw set.mem_image, refine or.inr ⟨r⁻¹, one_le_inv hr0' hr1, _⟩, simp only [line_map_apply, smul_smul, vadd_vsub], rw [inv_mul_cancel hr0'.ne', one_smul, vsub_vadd] }, { simp } }, { rcases h with rfl | ⟨r, ⟨hr, rfl⟩⟩, { exact wbtw_self_left _ _ _ }, { rw set.mem_Ici at hr, refine ⟨r⁻¹, ⟨inv_nonneg.2 (zero_le_one.trans hr), inv_le_one hr⟩, _⟩, simp only [line_map_apply, smul_smul, vadd_vsub], rw [inv_mul_cancel (one_pos.trans_le hr).ne', one_smul, vsub_vadd] } } end lemma wbtw.right_mem_image_Ici_of_left_ne {x y z : P} (h : wbtw R x y z) (hne : x ≠ y) : z ∈ line_map x y '' (set.Ici (1 : R)) := (wbtw_iff_left_eq_or_right_mem_image_Ici.1 h).resolve_left hne lemma wbtw.right_mem_affine_span_of_left_ne {x y z : P} (h : wbtw R x y z) (hne : x ≠ y) : z ∈ line[R, x, y] := begin rcases h.right_mem_image_Ici_of_left_ne hne with ⟨r, ⟨-, rfl⟩⟩, exact line_map_mem_affine_span_pair _ _ _ end lemma sbtw_iff_left_ne_and_right_mem_image_IoI {x y z : P} : sbtw R x y z ↔ x ≠ y ∧ z ∈ line_map x y '' (set.Ioi (1 : R)) := begin refine ⟨λ h, ⟨h.left_ne, _⟩, λ h, _⟩, { obtain ⟨r, ⟨hr, rfl⟩⟩ := h.wbtw.right_mem_image_Ici_of_left_ne h.left_ne, rw [set.mem_Ici] at hr, rcases hr.lt_or_eq with hrlt | rfl, { exact set.mem_image_of_mem _ hrlt }, { exfalso, simpa using h } }, { rcases h with ⟨hne, r, hr, rfl⟩, rw set.mem_Ioi at hr, refine ⟨wbtw_iff_left_eq_or_right_mem_image_Ici.2 (or.inr (set.mem_image_of_mem _ (set.mem_of_mem_of_subset hr set.Ioi_subset_Ici_self))), hne.symm, _⟩, rw [line_map_apply, ←@vsub_ne_zero V, vsub_vadd_eq_vsub_sub], nth_rewrite 0 ←one_smul R (y -ᵥ x), rw [←sub_smul, smul_ne_zero_iff, vsub_ne_zero, sub_ne_zero], exact ⟨hr.ne, hne.symm⟩ } end lemma sbtw.right_mem_image_Ioi {x y z : P} (h : sbtw R x y z) : z ∈ line_map x y '' (set.Ioi (1 : R)) := (sbtw_iff_left_ne_and_right_mem_image_IoI.1 h).2 lemma sbtw.right_mem_affine_span {x y z : P} (h : sbtw R x y z) : z ∈ line[R, x, y] := h.wbtw.right_mem_affine_span_of_left_ne h.left_ne lemma wbtw_iff_right_eq_or_left_mem_image_Ici {x y z : P} : wbtw R x y z ↔ z = y ∨ x ∈ line_map z y '' (set.Ici (1 : R)) := by rw [wbtw_comm, wbtw_iff_left_eq_or_right_mem_image_Ici] lemma wbtw.left_mem_image_Ici_of_right_ne {x y z : P} (h : wbtw R x y z) (hne : z ≠ y) : x ∈ line_map z y '' (set.Ici (1 : R)) := h.symm.right_mem_image_Ici_of_left_ne hne lemma wbtw.left_mem_affine_span_of_right_ne {x y z : P} (h : wbtw R x y z) (hne : z ≠ y) : x ∈ line[R, z, y] := h.symm.right_mem_affine_span_of_left_ne hne lemma sbtw_iff_right_ne_and_left_mem_image_IoI {x y z : P} : sbtw R x y z ↔ z ≠ y ∧ x ∈ line_map z y '' (set.Ioi (1 : R)) := by rw [sbtw_comm, sbtw_iff_left_ne_and_right_mem_image_IoI] lemma sbtw.left_mem_image_Ioi {x y z : P} (h : sbtw R x y z) : x ∈ line_map z y '' (set.Ioi (1 : R)) := h.symm.right_mem_image_Ioi lemma sbtw.left_mem_affine_span {x y z : P} (h : sbtw R x y z) : x ∈ line[R, z, y] := h.symm.right_mem_affine_span lemma wbtw_smul_vadd_smul_vadd_of_nonneg_of_le (x : P) (v : V) {r₁ r₂ : R} (hr₁ : 0 ≤ r₁) (hr₂ : r₁ ≤ r₂) : wbtw R x (r₁ • v +ᵥ x) (r₂ • v +ᵥ x) := begin refine ⟨r₁ / r₂, ⟨div_nonneg hr₁ (hr₁.trans hr₂), div_le_one_of_le hr₂ (hr₁.trans hr₂)⟩, _⟩, by_cases h : r₁ = 0, { simp [h] }, simp [line_map_apply, smul_smul, ((hr₁.lt_of_ne' h).trans_le hr₂).ne.symm] end lemma wbtw_or_wbtw_smul_vadd_of_nonneg (x : P) (v : V) {r₁ r₂ : R} (hr₁ : 0 ≤ r₁) (hr₂ : 0 ≤ r₂) : wbtw R x (r₁ • v +ᵥ x) (r₂ • v +ᵥ x) ∨ wbtw R x (r₂ • v +ᵥ x) (r₁ • v +ᵥ x) := begin rcases le_total r₁ r₂ with h|h, { exact or.inl (wbtw_smul_vadd_smul_vadd_of_nonneg_of_le x v hr₁ h) }, { exact or.inr (wbtw_smul_vadd_smul_vadd_of_nonneg_of_le x v hr₂ h) } end lemma wbtw_smul_vadd_smul_vadd_of_nonpos_of_le (x : P) (v : V) {r₁ r₂ : R} (hr₁ : r₁ ≤ 0) (hr₂ : r₂ ≤ r₁) : wbtw R x (r₁ • v +ᵥ x) (r₂ • v +ᵥ x) := begin convert wbtw_smul_vadd_smul_vadd_of_nonneg_of_le x (-v) (left.nonneg_neg_iff.2 hr₁) (neg_le_neg_iff.2 hr₂) using 1; rw neg_smul_neg end lemma wbtw_or_wbtw_smul_vadd_of_nonpos (x : P) (v : V) {r₁ r₂ : R} (hr₁ : r₁ ≤ 0) (hr₂ : r₂ ≤ 0) : wbtw R x (r₁ • v +ᵥ x) (r₂ • v +ᵥ x) ∨ wbtw R x (r₂ • v +ᵥ x) (r₁ • v +ᵥ x) := begin rcases le_total r₁ r₂ with h|h, { exact or.inr (wbtw_smul_vadd_smul_vadd_of_nonpos_of_le x v hr₂ h) }, { exact or.inl (wbtw_smul_vadd_smul_vadd_of_nonpos_of_le x v hr₁ h) } end lemma wbtw_smul_vadd_smul_vadd_of_nonpos_of_nonneg (x : P) (v : V) {r₁ r₂ : R} (hr₁ : r₁ ≤ 0) (hr₂ : 0 ≤ r₂) : wbtw R (r₁ • v +ᵥ x) x (r₂ • v +ᵥ x) := begin convert wbtw_smul_vadd_smul_vadd_of_nonneg_of_le (r₁ • v +ᵥ x) v (left.nonneg_neg_iff.2 hr₁) (neg_le_sub_iff_le_add.2 ((le_add_iff_nonneg_left r₁).2 hr₂)) using 1; simp [sub_smul, ←add_vadd] end lemma wbtw_smul_vadd_smul_vadd_of_nonneg_of_nonpos (x : P) (v : V) {r₁ r₂ : R} (hr₁ : 0 ≤ r₁) (hr₂ : r₂ ≤ 0) : wbtw R (r₁ • v +ᵥ x) x (r₂ • v +ᵥ x) := begin rw wbtw_comm, exact wbtw_smul_vadd_smul_vadd_of_nonpos_of_nonneg x v hr₂ hr₁ end lemma wbtw.trans_left_right {w x y z : P} (h₁ : wbtw R w y z) (h₂ : wbtw R w x y) : wbtw R x y z := begin rcases h₁ with ⟨t₁, ht₁, rfl⟩, rcases h₂ with ⟨t₂, ht₂, rfl⟩, refine ⟨(t₁ - t₂ * t₁) / (1 - t₂ * t₁), ⟨div_nonneg (sub_nonneg.2 (mul_le_of_le_one_left ht₁.1 ht₂.2)) (sub_nonneg.2 (mul_le_one ht₂.2 ht₁.1 ht₁.2)), div_le_one_of_le (sub_le_sub_right ht₁.2 _) (sub_nonneg.2 (mul_le_one ht₂.2 ht₁.1 ht₁.2))⟩, _⟩, simp only [line_map_apply, smul_smul, ←add_vadd, vsub_vadd_eq_vsub_sub, smul_sub, ←sub_smul, ←add_smul, vadd_vsub, vadd_right_cancel_iff, div_mul_eq_mul_div, div_sub_div_same], nth_rewrite 0 [←mul_one (t₁ - t₂ * t₁)], rw [←mul_sub, mul_div_assoc], by_cases h : 1 - t₂ * t₁ = 0, { rw [sub_eq_zero, eq_comm] at h, rw h, suffices : t₁ = 1, by simp [this], exact eq_of_le_of_not_lt ht₁.2 (λ ht₁lt, (mul_lt_one_of_nonneg_of_lt_one_right ht₂.2 ht₁.1 ht₁lt).ne h) }, { rw div_self h, ring_nf } end lemma wbtw.trans_right_left {w x y z : P} (h₁ : wbtw R w x z) (h₂ : wbtw R x y z) : wbtw R w x y := begin rw wbtw_comm at *, exact h₁.trans_left_right h₂ end lemma sbtw.trans_left_right {w x y z : P} (h₁ : sbtw R w y z) (h₂ : sbtw R w x y) : sbtw R x y z := ⟨h₁.wbtw.trans_left_right h₂.wbtw, h₂.right_ne, h₁.ne_right⟩ lemma sbtw.trans_right_left {w x y z : P} (h₁ : sbtw R w x z) (h₂ : sbtw R x y z) : sbtw R w x y := ⟨h₁.wbtw.trans_right_left h₂.wbtw, h₁.ne_left, h₂.left_ne⟩ lemma wbtw.collinear {x y z : P} (h : wbtw R x y z) : collinear R ({x, y, z} : set P) := begin rw collinear_iff_exists_forall_eq_smul_vadd, refine ⟨x, z -ᵥ x, _⟩, intros p hp, simp_rw [set.mem_insert_iff, set.mem_singleton_iff] at hp, rcases hp with rfl|rfl|rfl, { refine ⟨0, _⟩, simp }, { rcases h with ⟨t, -, rfl⟩, exact ⟨t, rfl⟩ }, { refine ⟨1, _⟩, simp } end lemma collinear.wbtw_or_wbtw_or_wbtw {x y z : P} (h : collinear R ({x, y, z} : set P)) : wbtw R x y z ∨ wbtw R y z x ∨ wbtw R z x y := begin rw collinear_iff_of_mem (set.mem_insert _ _) at h, rcases h with ⟨v, h⟩, simp_rw [set.mem_insert_iff, set.mem_singleton_iff] at h, have hy := h y (or.inr (or.inl rfl)), have hz := h z (or.inr (or.inr rfl)), rcases hy with ⟨ty, rfl⟩, rcases hz with ⟨tz, rfl⟩, rcases lt_trichotomy ty 0 with hy0|rfl|hy0, { rcases lt_trichotomy tz 0 with hz0|rfl|hz0, { nth_rewrite 1 wbtw_comm, rw ←or_assoc, exact or.inl (wbtw_or_wbtw_smul_vadd_of_nonpos _ _ hy0.le hz0.le) }, { simp }, { exact or.inr (or.inr (wbtw_smul_vadd_smul_vadd_of_nonneg_of_nonpos _ _ hz0.le hy0.le)) } }, { simp }, { rcases lt_trichotomy tz 0 with hz0|rfl|hz0, { refine or.inr (or.inr (wbtw_smul_vadd_smul_vadd_of_nonpos_of_nonneg _ _ hz0.le hy0.le)) }, { simp }, { nth_rewrite 1 wbtw_comm, rw ←or_assoc, exact or.inl (wbtw_or_wbtw_smul_vadd_of_nonneg _ _ hy0.le hz0.le) } } end lemma wbtw_iff_same_ray_vsub {x y z : P} : wbtw R x y z ↔ same_ray R (y -ᵥ x) (z -ᵥ y) := begin refine ⟨wbtw.same_ray_vsub, λ h, _⟩, rcases h with h | h | ⟨r₁, r₂, hr₁, hr₂, h⟩, { rw vsub_eq_zero_iff_eq at h, simp [h] }, { rw vsub_eq_zero_iff_eq at h, simp [h] }, { refine ⟨r₂ / (r₁ + r₂), ⟨div_nonneg hr₂.le (add_nonneg hr₁.le hr₂.le), div_le_one_of_le (le_add_of_nonneg_left hr₁.le) (add_nonneg hr₁.le hr₂.le)⟩, _⟩, have h' : z = r₂⁻¹ • r₁ • (y -ᵥ x) +ᵥ y, { simp [h, hr₂.ne'] }, rw eq_comm, simp only [line_map_apply, h', vadd_vsub_assoc, smul_smul, ←add_smul, eq_vadd_iff_vsub_eq, smul_add], convert (one_smul _ _).symm, field_simp [(add_pos hr₁ hr₂).ne', hr₂.ne'], ring } end variables (R) lemma wbtw_point_reflection (x y : P) : wbtw R y x (point_reflection R x y) := begin refine ⟨2⁻¹, ⟨by norm_num, by norm_num⟩, _⟩, rw [line_map_apply, point_reflection_apply, vadd_vsub_assoc, ←two_smul R (x -ᵥ y)], simp end lemma sbtw_point_reflection_of_ne {x y : P} (h : x ≠ y) : sbtw R y x (point_reflection R x y) := begin refine ⟨wbtw_point_reflection _ _ _, h, _⟩, nth_rewrite 0 [←point_reflection_self R x], exact (point_reflection_involutive R x).injective.ne h end lemma wbtw_midpoint (x y : P) : wbtw R x (midpoint R x y) y := by { convert wbtw_point_reflection R (midpoint R x y) x, simp } lemma sbtw_midpoint_of_ne {x y : P} (h : x ≠ y) : sbtw R x (midpoint R x y) y := begin have h : midpoint R x y ≠ x, { simp [h] }, convert sbtw_point_reflection_of_ne R h, simp end end linear_ordered_field
670ab60e0da4d41bc0fa63feff25ef8882499201
0845ae2ca02071debcfd4ac24be871236c01784f
/library/init/lean/format.lean
dd41cd6cbda13beef8ccacdb873da77e9f66de24
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
7,390
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.lean.options init.data.array universes u v namespace Lean inductive Format | nil : Format | line : Format | text : String → Format | nest : Nat → Format → Format | compose : Bool → Format → Format → Format | choice : Format → Format → Format namespace Format @[export lean.format_append_core] protected def append (a b : Format) : Format := compose false a b instance : HasAppend Format := ⟨Format.append⟩ instance : HasCoe String Format := ⟨text⟩ instance : Inhabited Format := ⟨nil⟩ def join (xs : List Format) : Format := xs.foldl HasAppend.append "" def isNil : Format → Bool | nil := true | _ := false def flatten : Format → Format | nil := nil | line := text " " | f@(text _) := f | (nest _ f) := flatten f | (choice f _) := flatten f | f@(compose true _ _) := f | f@(compose false f₁ f₂) := compose true (flatten f₁) (flatten f₂) @[export lean.format_group_core] def group : Format → Format | nil := nil | f@(text _) := f | f@(compose true _ _) := f | f := choice (flatten f) f structure SpaceResult := (found := false) (exceeded := false) (space := 0) @[inline] private def merge (w : Nat) (r₁ : SpaceResult) (r₂ : Thunk SpaceResult) : SpaceResult := if r₁.exceeded || r₁.found then r₁ else let y := r₂.get; if y.exceeded || y.found then y else let newSpace := r₁.space + y.space; { space := newSpace, exceeded := newSpace > w } def spaceUptoLine : Format → Nat → SpaceResult | nil w := {} | line w := { found := true } | (text s) w := { space := s.length, exceeded := s.length > w } | (compose _ f₁ f₂) w := merge w (spaceUptoLine f₁ w) (spaceUptoLine f₂ w) | (nest _ f) w := spaceUptoLine f w | (choice f₁ f₂) w := spaceUptoLine f₂ w def spaceUptoLine' : List (Nat × Format) → Nat → SpaceResult | [] w := {} | (p::ps) w := merge w (spaceUptoLine p.2 w) (spaceUptoLine' ps w) partial def be : Nat → Nat → String → List (Nat × Format) → String | w k out [] := out | w k out ((i, nil)::z) := be w k out z | w k out ((i, (compose _ f₁ f₂))::z) := be w k out ((i, f₁)::(i, f₂)::z) | w k out ((i, (nest n f))::z) := be w k out ((i+n, f)::z) | w k out ((i, text s)::z) := be w (k + s.length) (out ++ s) z | w k out ((i, line)::z) := be w i ((out ++ "\n").pushn ' ' i) z | w k out ((i, choice f₁ f₂)::z) := let r := merge w (spaceUptoLine f₁ w) (spaceUptoLine' z w); if r.exceeded then be w k out ((i, f₂)::z) else be w k out ((i, f₁)::z) @[inline] def bracket (l : String) (f : Format) (r : String) : Format := group (nest l.length $ l ++ f ++ r) @[inline] def paren (f : Format) : Format := bracket "(" f ")" @[inline] def sbracket (f : Format) : Format := bracket "[" f "]" def defIndent := 4 def defUnicode := true def defWidth := 120 def getWidth (o : Options) : Nat := o.get `format.width defWidth def getIndent (o : Options) : Nat := o.get `format.indent defIndent def getUnicode (o : Options) : Bool := o.get `format.unicode defUnicode @[init] def indentOption : IO Unit := registerOption `format.indent { defValue := defIndent, group := "format", descr := "indentation" } @[init] def unicodeOption : IO Unit := registerOption `format.unicode { defValue := defUnicode, group := "format", descr := "unicode characters" } @[init] def widthOption : IO Unit := registerOption `format.width { defValue := defWidth, group := "format", descr := "line width" } @[export lean.format_pretty_core] def prettyAux (f : Format) (w : Nat := defWidth) : String := be w 0 "" [(0, f)] def pretty (f : Format) (o : Options := {}) : String := prettyAux f (getWidth o) end Format open Lean.Format class HasFormat (α : Type u) := (format : α → Format) export Lean.HasFormat (format) def fmt {α : Type u} [HasFormat α] : α → Format := format instance toStringToFormat {α : Type u} [HasToString α] : HasFormat α := ⟨text ∘ toString⟩ -- note: must take precendence over the above instance to avoid premature formatting instance formatHasFormat : HasFormat Format := ⟨id⟩ instance stringHasFormat : HasFormat String := ⟨Format.text⟩ def Format.joinSep {α : Type u} [HasFormat α] : List α → Format → Format | [] sep := nil | [a] sep := format a | (a::as) sep := format a ++ sep ++ Format.joinSep as sep def Format.prefixJoin {α : Type u} [HasFormat α] (pre : Format) : List α → Format | [] := nil | (a::as) := pre ++ format a ++ Format.prefixJoin as def Format.joinSuffix {α : Type u} [HasFormat α] : List α → Format → Format | [] suffix := nil | (a::as) suffix := format a ++ suffix ++ Format.joinSuffix as suffix def List.format {α : Type u} [HasFormat α] : List α → Format | [] := "[]" | xs := sbracket $ Format.joinSep xs ("," ++ line) instance listHasFormat {α : Type u} [HasFormat α] : HasFormat (List α) := ⟨List.format⟩ instance prodHasFormat {α : Type u} {β : Type v} [HasFormat α] [HasFormat β] : HasFormat (Prod α β) := ⟨fun ⟨a, b⟩ => paren $ format a ++ "," ++ line ++ format b⟩ def Format.joinArraySep {α : Type u} [HasFormat α] (a : Array α) (sep : Format) : Format := a.iterate nil (fun i a r => if i.val > 0 then r ++ sep ++ format a else r ++ format a) instance natHasFormat : HasFormat Nat := ⟨fun n => toString n⟩ instance uint16HasFormat : HasFormat UInt16 := ⟨fun n => toString n⟩ instance uint32HasFormat : HasFormat UInt32 := ⟨fun n => toString n⟩ instance uint64HasFormat : HasFormat UInt64 := ⟨fun n => toString n⟩ instance usizeHasFormat : HasFormat USize := ⟨fun n => toString n⟩ instance nameHasFormat : HasFormat Name := ⟨fun n => n.toString⟩ protected def Format.repr : Format → Format | nil := "Format.nil" | line := "Format.line" | (text s) := paren $ "Format.text" ++ line ++ repr s | (nest n f) := paren $ "Format.nest" ++ line ++ repr n ++ line ++ Format.repr f | (compose b f₁ f₂) := paren $ "Format.compose " ++ repr b ++ line ++ Format.repr f₁ ++ line ++ Format.repr f₂ | (choice f₁ f₂) := paren $ "Format.choice" ++ line ++ Format.repr f₁ ++ line ++ Format.repr f₂ instance formatHasToString : HasToString Format := ⟨Format.pretty⟩ instance : HasRepr Format := ⟨Format.pretty ∘ Format.repr⟩ def formatDataValue : DataValue → Format | (DataValue.ofString v) := format (repr v) | (DataValue.ofBool v) := format v | (DataValue.ofName v) := "`" ++ format v | (DataValue.ofNat v) := format v | (DataValue.ofInt v) := format v instance dataValueHasFormat : HasFormat DataValue := ⟨formatDataValue⟩ def formatEntry : Name × DataValue → Format | (n, v) := format n ++ " := " ++ format v instance entryHasFormat : HasFormat (Name × DataValue) := ⟨formatEntry⟩ def formatKVMap (m : KVMap) : Format := sbracket (Format.joinSep m.entries ", ") instance kvMapHasFormat : HasFormat KVMap := ⟨formatKVMap⟩ end Lean
567ec51c9865d428b62aa092ea9a33e766a71180
8e691ffe296a38e3e9dc95845e5b607422c3c973
/test/fin_cases.lean
c3fcd92ee459ec6565b4f3cad9b60fd38c61aafb
[ "Apache-2.0" ]
permissive
jmvlangen/mathlib
8d847f7831f0e8ddebc99568704530af7c9e1a50
82f79a58df3047b8002bbaf90ce50da2a978e114
refs/heads/master
1,588,094,154,678
1,552,412,266,000
1,552,412,266,000
175,439,673
0
0
null
null
null
null
UTF-8
Lean
false
false
1,841
lean
import tactic.fin_cases import data.nat.prime import group_theory.perm import tactic.norm_num example (f : ℕ → Prop) (p : fin 3) (h0 : f 0) (h1 : f 1) (h2 : f 2) : f p.val := begin fin_cases *, simp, assumption, simp, assumption, simp, assumption, end example (x2 : fin 2) (x3 : fin 3) (n : nat) (y : fin n) : x2.val * x3.val = x3.val * x2.val := begin fin_cases x2; fin_cases x3, success_if_fail { fin_cases * }, success_if_fail { fin_cases y }, all_goals { simp }, end open finset example (x : ℕ) (h : x ∈ Ico 2 5) : x = 2 ∨ x = 3 ∨ x = 4 := begin fin_cases h, all_goals { simp } end open nat example (x : ℕ) (h : x ∈ [2,3,5,7]) : x = 2 ∨ x = 3 ∨ x = 5 ∨ x = 7 := begin fin_cases h, all_goals { simp } end example (x : ℕ) (h : x ∈ [2,3,5,7]) : true := begin success_if_fail { fin_cases h with [3,3,5,7] }, trivial end example (x : list ℕ) (h : x ∈ [[1],[2]]) : x.length = 1 := begin fin_cases h with [[1],[1+1]], simp, guard_target (list.length [1 + 1] = 1), simp end -- testing that `with` arguments are elaborated with respect to the expected type: example (x : ℤ) (h : x ∈ ([2,3] : list ℤ)) : x = 2 ∨ x = 3:= begin fin_cases h with [2,3], all_goals { simp } end instance (n : ℕ) : decidable (prime n) := decidable_prime_1 n example (x : ℕ) (h : x ∈ (range 10).filter prime) : x = 2 ∨ x = 3 ∨ x = 5 ∨ x = 7 := begin fin_cases h; exact dec_trivial end open equiv.perm example (x : (Σ (a : fin 4), fin 4)) (h : x ∈ fin_pairs_lt 4) : x.1.val < 4 := begin fin_cases h; simp, any_goals { exact dec_trivial }, end example (x : fin 3) : x.val < 5 := begin fin_cases x; exact dec_trivial end example (f : ℕ → Prop) (p : fin 3) (h0 : f 0) (h1 : f 1) (h2 : f 2) : f p.val := begin fin_cases *, all_goals { assumption } end
732ebf47727a7bfe24e3dac829189f2549118e7f
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/user_cmd_go_to_def.lean
038fa54f2a11aeeab6408bd0bcf5b24a67eca541
[ "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
334
lean
open lean open lean.parser open interactive open tactic @[user_command] meta def foo_cmd (_ : parse $ tk "mk_foo") : parser unit := add_decl $ declaration.defn `foo [] `(ℕ) `(42) reducibility_hints.abbrev tt. mk_foo -- should be at the line of `mk_foo` #eval (flip environment.decl_pos ``foo <$> tactic.get_env) >>= tactic.trace
5cc0d7475c3401dfcca8660c11b78915ec47dd4c
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/src/Lean/Elab/Tactic/Conv/Congr.lean
4b9dae53599fdb1169d462e945270ade4d6691ed
[ "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
Kha/lean4
1005785d2c8797ae266a303968848e5f6ce2fe87
b99e11346948023cd6c29d248cd8f3e3fb3474cf
refs/heads/master
1,693,355,498,027
1,669,080,461,000
1,669,113,138,000
184,748,176
0
0
Apache-2.0
1,665,995,520,000
1,556,884,930,000
Lean
UTF-8
Lean
false
false
8,085
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Tactic.Simp.Main import Lean.Meta.Tactic.Congr import Lean.Elab.Tactic.Conv.Basic namespace Lean.Elab.Tactic.Conv open Meta private def congrImplies (mvarId : MVarId) : MetaM (List MVarId) := do let [mvarId₁, mvarId₂, _, _] ← mvarId.apply (← mkConstWithFreshMVarLevels ``implies_congr) | throwError "'apply implies_congr' unexpected result" let mvarId₁ ← markAsConvGoal mvarId₁ let mvarId₂ ← markAsConvGoal mvarId₂ return [mvarId₁, mvarId₂] private def isImplies (e : Expr) : MetaM Bool := if e.isArrow then isProp e.bindingDomain! <&&> isProp e.bindingBody! else return false def congr (mvarId : MVarId) (addImplicitArgs := false) (nameSubgoals := true) : MetaM (List (Option MVarId)) := mvarId.withContext do let origTag ← mvarId.getTag let (lhs, rhs) ← getLhsRhsCore mvarId let lhs := (← instantiateMVars lhs).cleanupAnnotations if (← isImplies lhs) then return (← congrImplies mvarId).map Option.some else if lhs.isApp then let funInfo ← getFunInfo lhs.getAppFn let args := lhs.getAppArgs let some congrThm ← mkCongrSimp? lhs.getAppFn (subsingletonInstImplicitRhs := false) | throwError "'congr' conv tactic failed to create congruence theorem" unless args.size == congrThm.argKinds.size do throwError "'congr' conv tactic failed, unexpected number of arguments in congruence theorem" let mut proof := congrThm.proof let mut mvarIdsNew := #[] let mut mvarIdsNewInsts := #[] for i in [:args.size] do let arg := args[i]! let argInfo := funInfo.paramInfo[i]! match congrThm.argKinds[i]! with | .fixed | .cast => proof := mkApp proof arg; if addImplicitArgs || argInfo.isExplicit then mvarIdsNew := mvarIdsNew.push none | .eq => if addImplicitArgs || argInfo.isExplicit then let tag ← if nameSubgoals then pure (origTag ++ (← whnf (← inferType proof)).bindingName!) else pure origTag let (rhs, mvarNew) ← mkConvGoalFor arg tag proof := mkApp3 proof arg rhs mvarNew mvarIdsNew := mvarIdsNew.push (some mvarNew.mvarId!) else proof := mkApp3 proof arg arg (← mkEqRefl arg) | .subsingletonInst => proof := mkApp proof arg let rhs ← mkFreshExprMVar (← whnf (← inferType proof)).bindingDomain! proof := mkApp proof rhs mvarIdsNewInsts := mvarIdsNewInsts.push (some rhs.mvarId!) | .heq | .fixedNoParam => unreachable! let some (_, _, rhs') := (← whnf (← inferType proof)).eq? | throwError "'congr' conv tactic failed, equality expected" unless (← isDefEqGuarded rhs rhs') do throwError "invalid 'congr' conv tactic, failed to resolve{indentExpr rhs}\n=?={indentExpr rhs'}" mvarId.assign proof return mvarIdsNew.toList ++ mvarIdsNewInsts.toList else throwError "invalid 'congr' conv tactic, application or implication expected{indentExpr lhs}" @[builtin_tactic Lean.Parser.Tactic.Conv.congr] def evalCongr : Tactic := fun _ => do replaceMainGoal <| List.filterMap id (← congr (← getMainGoal)) private def selectIdx (tacticName : String) (mvarIds : List (Option MVarId)) (i : Int) : TacticM Unit := do if i >= 0 then let i := i.toNat if h : i < mvarIds.length then for mvarId? in mvarIds, j in [:mvarIds.length] do match mvarId? with | none => pure () | some mvarId => if i != j then mvarId.refl match mvarIds[i] with | none => throwError "cannot select argument" | some mvarId => replaceMainGoal [mvarId] return () throwError "invalid '{tacticName}' conv tactic, application has only {mvarIds.length} (nondependent) argument(s)" @[builtin_tactic Lean.Parser.Tactic.Conv.skip] def evalSkip : Tactic := fun _ => pure () @[builtin_tactic Lean.Parser.Tactic.Conv.lhs] def evalLhs : Tactic := fun _ => do let mvarIds ← congr (← getMainGoal) (nameSubgoals := false) selectIdx "lhs" mvarIds ((mvarIds.length : Int) - 2) @[builtin_tactic Lean.Parser.Tactic.Conv.rhs] def evalRhs : Tactic := fun _ => do let mvarIds ← congr (← getMainGoal) (nameSubgoals := false) selectIdx "rhs" mvarIds ((mvarIds.length : Int) - 1) @[builtin_tactic Lean.Parser.Tactic.Conv.arg] def evalArg : Tactic := fun stx => do match stx with | `(conv| arg $[@%$tk?]? $i:num) => let i := i.getNat if i == 0 then throwError "invalid 'arg' conv tactic, index must be greater than 0" let i := i - 1 let mvarIds ← congr (← getMainGoal) (addImplicitArgs := tk?.isSome) (nameSubgoals := false) selectIdx "arg" mvarIds i | _ => throwUnsupportedSyntax def extLetBodyCongr? (mvarId : MVarId) (lhs rhs : Expr) : MetaM (Option MVarId) := do match lhs with | .letE n t v b _ => let u₁ ← getLevel t let f := mkLambda n .default t b unless (← isTypeCorrect f) do throwError "failed to abstract let-expression, result is not type correct" let (β, u₂, f') ← withLocalDeclD n t fun a => do let type ← inferType (mkApp f a) let β ← mkLambdaFVars #[a] type let u₂ ← getLevel type let rhsBody ← mkFreshExprMVar type let f' ← mkLambdaFVars #[a] rhsBody let rhs' := mkLet n t v f'.bindingBody! unless (← isDefEq rhs rhs') do throwError "failed to go inside let-declaration, type error" return (β, u₂, f') let (arg, mvarId') ← withLocalDeclD n t fun x => do let eqLhs := f.beta #[x] let eqRhs := f'.beta #[x] let mvarNew ← mkFreshExprSyntheticOpaqueMVar (← mkEq eqLhs eqRhs) let arg ← mkLambdaFVars #[x] mvarNew return (arg, mvarNew.mvarId!) let val := mkApp6 (mkConst ``let_body_congr [u₁, u₂]) t β f f' v arg mvarId.assign val return some (← markAsConvGoal mvarId') | _ => return none private def extCore (mvarId : MVarId) (userName? : Option Name) : MetaM MVarId := mvarId.withContext do let (lhs, rhs) ← getLhsRhsCore mvarId let lhs := (← instantiateMVars lhs).cleanupAnnotations if let .forallE n d b bi := lhs then let u ← getLevel d let p : Expr := .lam n d b bi let userName ← if let some userName := userName? then pure userName else mkFreshBinderNameForTactic n let (q, h, mvarNew) ← withLocalDecl userName bi d fun a => do let pa := b.instantiate1 a let (qa, mvarNew) ← mkConvGoalFor pa let q ← mkLambdaFVars #[a] qa let h ← mkLambdaFVars #[a] mvarNew let rhs' ← mkForallFVars #[a] qa unless (← isDefEqGuarded rhs rhs') do throwError "invalid 'ext' conv tactic, failed to resolve{indentExpr rhs}\n=?={indentExpr rhs'}" return (q, h, mvarNew) let proof := mkApp4 (mkConst ``forall_congr [u]) d p q h mvarId.assign proof return mvarNew.mvarId! else if let some mvarId ← extLetBodyCongr? mvarId lhs rhs then return mvarId else let lhsType ← whnfD (← inferType lhs) unless lhsType.isForall do throwError "invalid 'ext' conv tactic, function or arrow expected{indentD m!"{lhs} : {lhsType}"}" let [mvarId] ← mvarId.apply (← mkConstWithFreshMVarLevels ``funext) | throwError "'apply funext' unexpected result" let userNames := if let some userName := userName? then [userName] else [] let (_, mvarId) ← mvarId.introN 1 userNames markAsConvGoal mvarId private def ext (userName? : Option Name) : TacticM Unit := do replaceMainGoal [← extCore (← getMainGoal) userName?] @[builtin_tactic Lean.Parser.Tactic.Conv.ext] def evalExt : Tactic := fun stx => do let ids := stx[1].getArgs if ids.isEmpty then ext none else for id in ids do withRef id <| ext id.getId end Lean.Elab.Tactic.Conv
5e3eb80f99b59b769f060b96772f7d3074a63740
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/playground/webserver/Webserver.lean
55dafc7e9c582448bcbe4bb78950038c51634be9
[ "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
5,470
lean
-- -*- origami-fold-style: triple-braces -*- import Lean -- namespace Webserver {{{ namespace Webserver structure State := (verb : String) (path : String) (status := "200 OK") (outHeaders : Array String := #[]) (out : String := "") (tryNextHandler := false) abbrev HandlerM := StateT State IO abbrev Handler := HandlerM Unit def checkVerb (verb : String) : Handler := do let st ← get if st.verb != verb then throw $ IO.userError "invalid verb" def checkPathLiteral (p : String) : Handler := do let st ← get if p.isPrefixOf st.path then set { st with path := st.path.extract p.bsize st.path.bsize } else throw $ IO.userError "invalid path" def getPathPart : HandlerM String := do let st ← get let stop := st.path.posOf '/' set { st with path := st.path.extract stop st.path.bsize } pure $ st.path.extract 0 stop def checkPathConsumed : Handler := do let st ← get if st.path != "" then throw $ IO.userError "invalid path" def write (out : String) : Handler := do modify fun st => { st with out := st.out ++ out } def redirect (url : String) : Handler := do modify fun st => { st with status := "307 Temporary Redirect", outHeaders := #["Location: " ++ url] } def notFound : Handler := do modify fun st => { st with status := "404 Not Found" } write "whoops" def mkHandlersRef : IO (IO.Ref (List Handler)) := IO.mkRef ∅ @[init mkHandlersRef] constant handlersRef : IO.Ref (List Handler) def registerHandler (h : Handler) : IO Unit := do handlersRef.modify fun hs => h::hs partial def parseHeaders (hIn : IO.FS.Stream) : IO Unit := do let line ← hIn.getLine if line == "" || line == "\r\n" then pure () else parseHeaders hIn partial def run (hIn hOut : IO.FS.Stream) : IO Unit := do let line ← hIn.getLine if line != "" then let [verb, path, proto] ← line.splitOn " " | panic! "failed to parse request: " ++ line let stderr ← IO.getStderr stderr.putStrLn $ "=> " ++ verb ++ " " ++ path let headers ← parseHeaders hIn let handlers ← handlersRef.get let (_, st) ← handlers.foldr (· <|> ·) notFound { verb, path } stderr.putStrLn $ "<= " ++ st.status hOut.putStrLn $ "HTTP/1.1 " ++ st.status hOut.putStrLn "Content-Type: text/html" hOut.putStrLn $ "Content-Length: " ++ toString st.out.bsize st.outHeaders.forM hOut.putStrLn hOut.putStrLn "" hOut.putStr st.out hOut.flush run hIn hOut end Webserver --}}} open Lean open Lean.Parser open Lean.PrettyPrinter -- declare_syntax_cat element {{{ declare_syntax_cat element declare_syntax_cat child syntax "<" ident "/>" : element syntax "<" ident ">" child* "</" ident ">" : element -- "JSXTextCharacter : SourceCharacter but not one of {, <, > or }" def text : Parser := -- {{{ withAntiquot (mkAntiquot "text" `LX.text) { fn := fun c s => let startPos := s.pos let s := takeWhile1Fn (not ∘ "{<>}$".contains) "HTML text" c s mkNodeToken `LX.text startPos c s } -- }}} @[combinatorFormatter text] def text.formatter : Formatter := pure () @[combinatorParenthesizer text] def text.parenthesizer : Parenthesizer := pure () syntax text : child syntax "{" term "}" : child syntax element : child syntax:max element : term macro_rules | `(<$n/>) => quote ("<" ++ toString n.getId ++ "/>") | `(<$n>$cs*</$m>) => -- {{{ if n.getId == m.getId then do let cs ← cs.mapM fun c => match c with | `(child|$t:text) => pure $ quote t[0].getAtomVal! | `(child|{$t}) => pure t | `(child|$e:element) => `($e:element) | _ => unreachable! let cs := cs.push (quote ("</" ++ toString m.getId ++ ">")) cs.foldlM (fun s e => `($s ++ $e)) (quote ("<" ++ toString n.getId ++ ">")) else Macro.throwError ("expected </" ++ toString n.getId ++ ">") -- }}} -- }}} -- open Webserver {{{ open Webserver def pathLiteral : Parser := -- {{{ withAntiquot (mkAntiquot "pathLiteral" `pathLiteral) { fn := fun c s => let startPos := s.pos let s := takeWhile1Fn (fun c => c == '/' || c.isAlphanum) "URL path" c s mkNodeToken `pathLiteral startPos c s } -- }}} @[combinatorFormatter pathLiteral] def pathLiteral.formatter : Formatter := pure () @[combinatorParenthesizer pathLiteral] def pathLiteral.parenthesizer : Parenthesizer := pure () declare_syntax_cat pathItem syntax pathLiteral : pathItem syntax "{" ident "}" : pathItem declare_syntax_cat path syntax pathItem* : path declare_syntax_cat verb syntax "GET" : verb syntax "POST" : verb macro v:verb p:path " => " t:term : command => do -- {{{ let `(path| $[$pis:pathItem]* ) ← p | unreachable! let t ← `(do checkPathConsumed; $t:term) let t ← pis.foldrM (fun pi t => match pi with | `(pathItem|$l:pathLiteral) => `(do checkPathLiteral $(quote l[0].getAtomVal!); $t:term) | `(pathItem|{$id}) => `(do let $id:ident ← getPathPart; $t:term) | _ => Macro.throwError s!"unknown pathItem '{Syntax.formatStx pi}'") t `(def handler : Handler := do checkVerb $(quote v[0].getAtomVal!) $t:term @[init] def reg : IO Unit := registerHandler handler) -- }}} GET / => redirect "/greet/stranger" GET /greet/{name} => write <html> <h1>Hello, {name}!</h1> </html> def main : IO Unit := do let hIn ← IO.getStdin let hOut ← IO.getStdout Webserver.run hIn hOut -- }}} #check let name := "PLDI" (<h1>Hello, {name}!</h1>)
b867c168275a01abb88bdcde9ebae8670f2a2b59
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/run/eqThm.lean
7ef40eb1572867059ee54ba5a15285dc746f3010
[ "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
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
1,424
lean
def f : Nat → Bool → Nat | 0, true => 1 | 0, false => 2 | 1, true => 3 | 1, _ => 4 | x+2, true => f x true | x+2, b => f x (not b) macro "urfl" : tactic => `(set_option smartUnfolding false in rfl) theorem f_main_eq : f x b = f.match_1 (fun _ _ => Nat) x b (fun _ => 1) (fun _ => 2) (fun _ => 3) (fun _ => 4) (fun x => f x true) (fun x b => f x (not b)) := by split <;> (first | rfl | (conv => lhs; delta f; whnf; simp_match); try urfl) #check @f_main_eq def g : List Nat → List Nat → Nat | [], y::ys => y | [], ys => 0 | x1::x2::xs, ys => g xs ys | x::xs, y::ys => g xs ys + y | x::xs, [] => g xs [] theorem g_main_eq (xs ys : List Nat) : g xs ys = g.match_1 (fun _ _ => Nat) xs ys (fun y ys => y) (fun _ => 0) (fun _ _ xs ys => g xs ys) (fun _ xs y ys => g xs ys + y) (fun _ xs => g xs []) := by split <;> (first | rfl | (conv => lhs; delta g; whnf; simp_match); try urfl) #check @g_main_eq def foo (xs : List Nat) : List Nat := match xs with | [] => [] | x::xs => let y := 2 * x; match xs with | [] => [] | x::xs => (y + x) :: foo xs theorem foo_main_eq (xs : List Nat) : foo xs = foo.match_1 (fun _ => List Nat) xs (fun _ => []) (fun x xs => let y := 2*x; foo.match_1 (fun _ => List Nat) xs (fun _ => []) (fun x xs => (y + x)::foo xs)) := by split . rfl . split . rfl . rfl #check @foo_main_eq
ca850ca182c5263ed929f62fbaf901026fbe9bfb
367134ba5a65885e863bdc4507601606690974c1
/src/order/omega_complete_partial_order.lean
54d05bcd0c3acc006a3685d2486e576a6199adae
[ "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
30,592
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon -/ import data.pfun import order.preorder_hom import tactic.wlog import tactic.monotonicity /-! # Omega Complete Partial Orders An omega-complete partial order is a partial order with a supremum operation on increasing sequences indexed by natural numbers (which we call `ωSup`). In this sense, it is strictly weaker than join complete semi-lattices as only ω-sized totally ordered sets have a supremum. The concept of an omega-complete partial order (ωCPO) is useful for the formalization of the semantics of programming languages. Its notion of supremum helps define the meaning of recursive procedures. ## Main definitions * class `omega_complete_partial_order` * `ite`, `map`, `bind`, `seq` as continuous morphisms ## Instances of `omega_complete_partial_order` * `roption` * every `complete_lattice` * pi-types * product types * `monotone_hom` * `continuous_hom` (with notation →𝒄) * an instance of `omega_complete_partial_order (α →𝒄 β)` * `continuous_hom.of_fun` * `continuous_hom.of_mono` * continuous functions: * `id` * `ite` * `const` * `roption.bind` * `roption.map` * `roption.seq` ## References * [G. Markowsky, *Chain-complete posets and directed sets with applications*, https://doi.org/10.1007/BF02485815][markowsky] * [J. M. Cadiou and Zohar Manna, *Recursive definitions of partial functions and their computations.*, https://doi.org/10.1145/942580.807072][cadiou] * [Carl A. Gunter, *Semantics of Programming Languages: Structures and Techniques*, ISBN: 0262570955][gunter] -/ universes u v local attribute [-simp] roption.bind_eq_bind roption.map_eq_map open_locale classical namespace preorder_hom variables (α : Type*) (β : Type*) {γ : Type*} {φ : Type*} variables [preorder α] [preorder β] [preorder γ] [preorder φ] variables {β γ} /-- The constant function, as a monotone function. -/ @[simps] def const (f : β) : α →ₘ β := { to_fun := function.const _ f, monotone' := assume x y h, le_refl _} variables {α} {α' : Type*} {β' : Type*} [preorder α'] [preorder β'] /-- The diagonal function, as a monotone function. -/ @[simps] def prod.diag : α →ₘ (α × α) := { to_fun := λ x, (x,x), monotone' := λ x y h, ⟨h,h⟩ } /-- The `prod.map` function, as a monotone function. -/ @[simps] def prod.map (f : α →ₘ β) (f' : α' →ₘ β') : (α × α') →ₘ (β × β') := { to_fun := prod.map f f', monotone' := λ ⟨x,x'⟩ ⟨y,y'⟩ ⟨h,h'⟩, ⟨f.monotone h,f'.monotone h'⟩ } /-- The `prod.fst` projection, as a monotone function. -/ @[simps] def prod.fst : (α × β) →ₘ α := { to_fun := prod.fst, monotone' := λ ⟨x,x'⟩ ⟨y,y'⟩ ⟨h,h'⟩, h } /-- The `prod.snd` projection, as a monotone function. -/ @[simps] def prod.snd : (α × β) →ₘ β := { to_fun := prod.snd, monotone' := λ ⟨x,x'⟩ ⟨y,y'⟩ ⟨h,h'⟩, h' } /-- The `prod` constructor, as a monotone function. -/ @[simps] def prod.zip (f : α →ₘ β) (g : α →ₘ γ) : α →ₘ (β × γ) := (prod.map f g).comp prod.diag /-- `roption.bind` as a monotone function -/ @[simps] def bind {β γ} (f : α →ₘ roption β) (g : α →ₘ β → roption γ) : α →ₘ roption γ := { to_fun := λ x, f x >>= g x, monotone' := begin intros x y h a, simp only [and_imp, exists_prop, roption.bind_eq_bind, roption.mem_bind_iff, exists_imp_distrib], intros b hb ha, refine ⟨b, f.monotone h _ hb, g.monotone h _ _ ha⟩, end } end preorder_hom namespace omega_complete_partial_order /-- A chain is a monotonically increasing sequence. See the definition on page 114 of [gunter]. -/ def chain (α : Type u) [preorder α] := ℕ →ₘ α namespace chain variables {α : Type u} {β : Type v} {γ : Type*} variables [preorder α] [preorder β] [preorder γ] instance : has_coe_to_fun (chain α) := @infer_instance (has_coe_to_fun $ ℕ →ₘ α) _ instance [inhabited α] : inhabited (chain α) := ⟨ ⟨ λ _, default _, λ _ _ _, le_refl _ ⟩ ⟩ instance : has_mem α (chain α) := ⟨λa (c : ℕ →ₘ α), ∃ i, a = c i⟩ variables (c c' : chain α) variables (f : α →ₘ β) variables (g : β →ₘ γ) instance : has_le (chain α) := { le := λ x y, ∀ i, ∃ j, x i ≤ y j } /-- `map` function for `chain` -/ @[simps] def map : chain β := f.comp c variables {f} lemma mem_map (x : α) : x ∈ c → f x ∈ chain.map c f := λ ⟨i,h⟩, ⟨i, h.symm ▸ rfl⟩ lemma exists_of_mem_map {b : β} : b ∈ c.map f → ∃ a, a ∈ c ∧ f a = b := λ ⟨i,h⟩, ⟨c i, ⟨i, rfl⟩, h.symm⟩ lemma mem_map_iff {b : β} : b ∈ c.map f ↔ ∃ a, a ∈ c ∧ f a = b := ⟨ exists_of_mem_map _, λ h, by { rcases h with ⟨w,h,h'⟩, subst b, apply mem_map c _ h, } ⟩ @[simp] lemma map_id : c.map preorder_hom.id = c := preorder_hom.comp_id _ lemma map_comp : (c.map f).map g = c.map (g.comp f) := rfl @[mono] lemma map_le_map {g : α →ₘ β} (h : f ≤ g) : c.map f ≤ c.map g := λ i, by simp [mem_map_iff]; intros; existsi i; apply h /-- `chain.zip` pairs up the elements of two chains that have the same index -/ @[simps] def zip (c₀ : chain α) (c₁ : chain β) : chain (α × β) := preorder_hom.prod.zip c₀ c₁ end chain end omega_complete_partial_order open omega_complete_partial_order section prio set_option extends_priority 50 /-- An omega-complete partial order is a partial order with a supremum operation on increasing sequences indexed by natural numbers (which we call `ωSup`). In this sense, it is strictly weaker than join complete semi-lattices as only ω-sized totally ordered sets have a supremum. See the definition on page 114 of [gunter]. -/ class omega_complete_partial_order (α : Type*) extends partial_order α := (ωSup : chain α → α) (le_ωSup : ∀(c:chain α), ∀ i, c i ≤ ωSup c) (ωSup_le : ∀(c:chain α) x, (∀ i, c i ≤ x) → ωSup c ≤ x) end prio namespace omega_complete_partial_order variables {α : Type u} {β : Type v} {γ : Type*} variables [omega_complete_partial_order α] /-- Transfer a `omega_complete_partial_order` on `β` to a `omega_complete_partial_order` on `α` using a strictly monotone function `f : β →ₘ α`, a definition of ωSup and a proof that `f` is continuous with regard to the provided `ωSup` and the ωCPO on `α`. -/ @[reducible] protected def lift [partial_order β] (f : β →ₘ α) (ωSup₀ : chain β → β) (h : ∀ x y, f x ≤ f y → x ≤ y) (h' : ∀ c, f (ωSup₀ c) = ωSup (c.map f)) : omega_complete_partial_order β := { ωSup := ωSup₀, ωSup_le := λ c x hx, h _ _ (by rw h'; apply ωSup_le; intro; apply f.monotone (hx i)), le_ωSup := λ c i, h _ _ (by rw h'; apply le_ωSup (c.map f)) } lemma le_ωSup_of_le {c : chain α} {x : α} (i : ℕ) (h : x ≤ c i) : x ≤ ωSup c := le_trans h (le_ωSup c _) lemma ωSup_total {c : chain α} {x : α} (h : ∀ i, c i ≤ x ∨ x ≤ c i) : ωSup c ≤ x ∨ x ≤ ωSup c := classical.by_cases (assume : ∀ i, c i ≤ x, or.inl (ωSup_le _ _ this)) (assume : ¬ ∀ i, c i ≤ x, have ∃ i, ¬ c i ≤ x, by simp only [not_forall] at this ⊢; assumption, let ⟨i, hx⟩ := this in have x ≤ c i, from (h i).resolve_left hx, or.inr $ le_ωSup_of_le _ this) @[mono] lemma ωSup_le_ωSup_of_le {c₀ c₁ : chain α} (h : c₀ ≤ c₁) : ωSup c₀ ≤ ωSup c₁ := ωSup_le _ _ $ λ i, Exists.rec_on (h i) $ λ j h, le_trans h (le_ωSup _ _) lemma ωSup_le_iff (c : chain α) (x : α) : ωSup c ≤ x ↔ (∀ i, c i ≤ x) := begin split; intros, { transitivity ωSup c, exact le_ωSup _ _, assumption }, exact ωSup_le _ _ ‹_›, end /-- A subset `p : α → Prop` of the type closed under `ωSup` induces an `omega_complete_partial_order` on the subtype `{a : α // p a}`. -/ def subtype {α : Type*} [omega_complete_partial_order α] (p : α → Prop) (hp : ∀ (c : chain α), (∀ i ∈ c, p i) → p (ωSup c)) : omega_complete_partial_order (subtype p) := omega_complete_partial_order.lift (preorder_hom.subtype.val p) (λ c, ⟨ωSup _, hp (c.map (preorder_hom.subtype.val p)) (λ i ⟨n, q⟩, q.symm ▸ (c n).2)⟩) (λ x y h, h) (λ c, rfl) section continuity open chain variables [omega_complete_partial_order β] variables [omega_complete_partial_order γ] /-- A monotone function `f : α →ₘ β` is continuous if it distributes over ωSup. In order to distinguish it from the (more commonly used) continuity from topology (see topology/basic.lean), the present definition is often referred to as "Scott-continuity" (referring to Dana Scott). It corresponds to continuity in Scott topological spaces (not defined here). -/ def continuous (f : α →ₘ β) : Prop := ∀ c : chain α, f (ωSup c) = ωSup (c.map f) /-- `continuous' f` asserts that `f` is both monotone and continuous. -/ def continuous' (f : α → β) : Prop := ∃ hf : monotone f, continuous ⟨f, hf⟩ lemma continuous.to_monotone {f : α → β} (hf : continuous' f) : monotone f := hf.fst lemma continuous.of_bundled (f : α → β) (hf : monotone f) (hf' : continuous ⟨f, hf⟩) : continuous' f := ⟨hf, hf'⟩ lemma continuous.of_bundled' (f : α →ₘ β) (hf' : continuous f) : continuous' f := ⟨f.monotone, hf'⟩ lemma continuous.to_bundled (f : α → β) (hf : continuous' f) : continuous ⟨f, continuous.to_monotone hf⟩ := hf.snd variables (f : α →ₘ β) (g : β →ₘ γ) lemma continuous_id : continuous (@preorder_hom.id α _) := by intro; rw c.map_id; refl lemma continuous_comp (hfc : continuous f) (hgc : continuous g) : continuous (g.comp f):= begin dsimp [continuous] at *, intro, rw [hfc,hgc,chain.map_comp] end lemma id_continuous' : continuous' (@id α) := continuous.of_bundled _ (λ a b h, h) begin intro c, apply eq_of_forall_ge_iff, intro z, simp [ωSup_le_iff,function.const], end lemma const_continuous' (x: β) : continuous' (function.const α x) := continuous.of_bundled _ (λ a b h, le_refl _) begin intro c, apply eq_of_forall_ge_iff, intro z, simp [ωSup_le_iff,function.const], end end continuity end omega_complete_partial_order namespace roption variables {α : Type u} {β : Type v} {γ : Type*} open omega_complete_partial_order lemma eq_of_chain {c : chain (roption α)} {a b : α} (ha : some a ∈ c) (hb : some b ∈ c) : a = b := begin cases ha with i ha, replace ha := ha.symm, cases hb with j hb, replace hb := hb.symm, wlog h : i ≤ j := le_total i j using [a b i j, b a j i], rw [eq_some_iff] at ha hb, have := c.monotone h _ ha, apply mem_unique this hb end /-- The (noncomputable) `ωSup` definition for the `ω`-CPO structure on `roption α`. -/ protected noncomputable def ωSup (c : chain (roption α)) : roption α := if h : ∃a, some a ∈ c then some (classical.some h) else none lemma ωSup_eq_some {c : chain (roption α)} {a : α} (h : some a ∈ c) : roption.ωSup c = some a := have ∃a, some a ∈ c, from ⟨a, h⟩, have a' : some (classical.some this) ∈ c, from classical.some_spec this, calc roption.ωSup c = some (classical.some this) : dif_pos this ... = some a : congr_arg _ (eq_of_chain a' h) lemma ωSup_eq_none {c : chain (roption α)} (h : ¬∃a, some a ∈ c) : roption.ωSup c = none := dif_neg h lemma mem_chain_of_mem_ωSup {c : chain (roption α)} {a : α} (h : a ∈ roption.ωSup c) : some a ∈ c := begin simp [roption.ωSup] at h, split_ifs at h, { have h' := classical.some_spec h_1, rw ← eq_some_iff at h, rw ← h, exact h' }, { rcases h with ⟨ ⟨ ⟩ ⟩ } end noncomputable instance omega_complete_partial_order : omega_complete_partial_order (roption α) := { ωSup := roption.ωSup, le_ωSup := λ c i, by { intros x hx, rw ← eq_some_iff at hx ⊢, rw [ωSup_eq_some, ← hx], rw ← hx, exact ⟨i,rfl⟩ }, ωSup_le := by { rintros c x hx a ha, replace ha := mem_chain_of_mem_ωSup ha, cases ha with i ha, apply hx i, rw ← ha, apply mem_some } } section inst lemma mem_ωSup (x : α) (c : chain (roption α)) : x ∈ ωSup c ↔ some x ∈ c := begin simp [omega_complete_partial_order.ωSup,roption.ωSup], split, { split_ifs, swap, rintro ⟨⟨⟩⟩, intro h', have hh := classical.some_spec h, simp at h', subst x, exact hh }, { intro h, have h' : ∃ (a : α), some a ∈ c := ⟨_,h⟩, rw dif_pos h', have hh := classical.some_spec h', rw eq_of_chain hh h, simp } end end inst end roption namespace pi variables {α : Type*} {β : α → Type*} {γ : Type*} /-- Function application `λ f, f a` is monotone with respect to `f` for fixed `a`. -/ @[simps] def monotone_apply [∀a, partial_order (β a)] (a : α) : (Πa, β a) →ₘ β a := { to_fun := (λf:Πa, β a, f a), monotone' := assume f g hfg, hfg a } open omega_complete_partial_order omega_complete_partial_order.chain instance [∀a, omega_complete_partial_order (β a)] : omega_complete_partial_order (Πa, β a) := { ωSup := λc a, ωSup (c.map (monotone_apply a)), ωSup_le := assume c f hf a, ωSup_le _ _ $ by { rintro i, apply hf }, le_ωSup := assume c i x, le_ωSup_of_le _ $ le_refl _ } namespace omega_complete_partial_order variables [∀ x, omega_complete_partial_order $ β x] variables [omega_complete_partial_order γ] lemma flip₁_continuous' (f : ∀ x : α, γ → β x) (a : α) (hf : continuous' (λ x y, f y x)) : continuous' (f a) := continuous.of_bundled _ (λ x y h, continuous.to_monotone hf h a) (λ c, congr_fun (continuous.to_bundled _ hf c) a) lemma flip₂_continuous' (f : γ → Π x, β x) (hf : ∀ x, continuous' (λ g, f g x)) : continuous' f := continuous.of_bundled _ (λ x y h a, continuous.to_monotone (hf a) h) (by intro c; ext a; apply continuous.to_bundled _ (hf a) c) end omega_complete_partial_order end pi namespace prod open omega_complete_partial_order variables {α : Type*} {β : Type*} {γ : Type*} variables [omega_complete_partial_order α] variables [omega_complete_partial_order β] variables [omega_complete_partial_order γ] /-- The supremum of a chain in the product `ω`-CPO. -/ @[simps] protected def ωSup (c : chain (α × β)) : α × β := (ωSup (c.map preorder_hom.prod.fst), ωSup (c.map preorder_hom.prod.snd)) @[simps ωSup_fst ωSup_snd] instance : omega_complete_partial_order (α × β) := { ωSup := prod.ωSup, ωSup_le := λ c ⟨x,x'⟩ h, ⟨ωSup_le _ _ $ λ i, (h i).1, ωSup_le _ _ $ λ i, (h i).2⟩, le_ωSup := λ c i, ⟨le_ωSup (c.map preorder_hom.prod.fst) i, le_ωSup (c.map preorder_hom.prod.snd) i⟩ } end prod namespace complete_lattice variables (α : Type u) /-- Any complete lattice has an `ω`-CPO structure where the countable supremum is a special case of arbitrary suprema. -/ @[priority 100] -- see Note [lower instance priority] instance [complete_lattice α] : omega_complete_partial_order α := { ωSup := λc, ⨆ i, c i, ωSup_le := λ ⟨c, _⟩ s hs, by simp only [supr_le_iff, preorder_hom.coe_fun_mk] at ⊢ hs; intros i; apply hs i, le_ωSup := assume ⟨c, _⟩ i, by simp only [preorder_hom.coe_fun_mk]; apply le_supr_of_le i; refl } variables {α} {β : Type v} [omega_complete_partial_order α] [complete_lattice β] open omega_complete_partial_order lemma inf_continuous [is_total β (≤)] (f g : α →ₘ β) (hf : continuous f) (hg : continuous g) : continuous (f ⊓ g) := begin intro c, apply eq_of_forall_ge_iff, intro z, simp only [inf_le_iff, hf c, hg c, ωSup_le_iff, ←forall_or_distrib_left, ←forall_or_distrib_right, chain.map_to_fun, function.comp_app, preorder_hom.has_inf_inf_to_fun], split, { introv h, apply h }, { intros h i j, apply or.imp _ _ (h (max i j)); apply le_trans; mono*, { apply le_max_left }, { apply le_max_right }, }, end lemma Sup_continuous (s : set $ α →ₘ β) (hs : ∀ f ∈ s, continuous f) : continuous (Sup s) := begin intro c, apply eq_of_forall_ge_iff, intro z, simp only [ωSup_le_iff, and_imp, preorder_hom.complete_lattice_Sup, set.mem_image, chain.map_to_fun, function.comp_app, Sup_le_iff, preorder_hom.has_Sup_Sup_to_fun, exists_imp_distrib], split; introv h hx hb; subst b, { apply le_trans _ (h _ _ hx rfl), mono, apply le_ωSup }, { rw [hs _ hx c, ωSup_le_iff], intro, apply h i _ x hx rfl, } end theorem Sup_continuous' : ∀s : set (α → β), (∀t∈s, omega_complete_partial_order.continuous' t) → omega_complete_partial_order.continuous' (Sup s) := begin introv ht, dsimp [continuous'], have : monotone (Sup s), { intros x y h, apply Sup_le_Sup_of_forall_exists_le, intro, simp only [and_imp, exists_prop, set.mem_range, set_coe.exists, subtype.coe_mk, exists_imp_distrib], intros f hfs hfx, subst hfx, refine ⟨f y, ⟨f, hfs, rfl⟩, _⟩, cases ht _ hfs with hf, apply hf h }, existsi this, let s' : set (α →ₘ β) := { f | ⇑f ∈ s }, suffices : omega_complete_partial_order.continuous (Sup s'), { convert this, ext, simp only [supr, has_Sup.Sup, Sup, set.image, set.mem_set_of_eq], congr, ext, simp only [exists_prop, set.mem_range, set_coe.exists, set.mem_set_of_eq, subtype.coe_mk], split, { rintro ⟨y,hy,hy'⟩, cases ht _ hy, refine ⟨⟨_, w⟩, hy, hy'⟩ }, tauto }, apply complete_lattice.Sup_continuous, intros f hf, specialize ht f hf, cases ht, exact ht_h, end lemma sup_continuous {f g : α →ₘ β} (hf : continuous f) (hg : continuous g) : continuous (f ⊔ g) := begin rw ← Sup_pair, apply Sup_continuous, simp only [or_imp_distrib, forall_and_distrib, set.mem_insert_iff, set.mem_singleton_iff, forall_eq], split; assumption, end lemma top_continuous : continuous (⊤ : α →ₘ β) := begin intro c, apply eq_of_forall_ge_iff, intro z, simp only [ωSup_le_iff, forall_const, chain.map_to_fun, function.comp_app, preorder_hom.has_top_top_to_fun], end lemma bot_continuous : continuous (⊥ : α →ₘ β) := begin intro c, apply eq_of_forall_ge_iff, intro z, simp only [ωSup_le_iff, forall_const, chain.map_to_fun, function.comp_app, preorder_hom.has_bot_bot_to_fun], end end complete_lattice namespace omega_complete_partial_order variables {α : Type u} {α' : Type*} {β : Type v} {β' : Type*} {γ : Type*} {φ : Type*} variables [omega_complete_partial_order α] [omega_complete_partial_order β] variables [omega_complete_partial_order γ] [omega_complete_partial_order φ] variables [omega_complete_partial_order α'] [omega_complete_partial_order β'] namespace preorder_hom /-- Function application `λ f, f a` (for fixed `a`) is a monotone function from the monotone function space `α →ₘ β` to `β`. -/ @[simps] def monotone_apply (a : α) : (α →ₘ β) →ₘ β := { to_fun := (λf : α →ₘ β, f a), monotone' := assume f g hfg, hfg a } /-- The "forgetful functor" from `α →ₘ β` to `α → β` that takes the underlying function, is monotone. -/ def to_fun_hom : (α →ₘ β) →ₘ (α → β) := { to_fun := λ f, f.to_fun, monotone' := λ x y h, h } /-- The `ωSup` operator for monotone functions. -/ @[simps] protected def ωSup (c : chain (α →ₘ β)) : α →ₘ β := { to_fun := λ a, ωSup (c.map (monotone_apply a)), monotone' := λ x y h, ωSup_le_ωSup_of_le (chain.map_le_map _ $ λ a, a.monotone h) } @[simps ωSup_to_fun] instance omega_complete_partial_order : omega_complete_partial_order (α →ₘ β) := omega_complete_partial_order.lift preorder_hom.to_fun_hom preorder_hom.ωSup (λ x y h, h) (λ c, rfl) end preorder_hom section old_struct set_option old_structure_cmd true variables (α β) /-- A monotone function on `ω`-continuous partial orders is said to be continuous if for every chain `c : chain α`, `f (⊔ i, c i) = ⊔ i, f (c i)`. This is just the bundled version of `preorder_hom.continuous`. -/ structure continuous_hom extends preorder_hom α β := (cont : continuous (preorder_hom.mk to_fun monotone')) attribute [nolint doc_blame] continuous_hom.to_preorder_hom infixr ` →𝒄 `:25 := continuous_hom -- Input: \r\MIc instance : has_coe_to_fun (α →𝒄 β) := { F := λ _, α → β, coe := continuous_hom.to_fun } instance : has_coe (α →𝒄 β) (α →ₘ β) := { coe := continuous_hom.to_preorder_hom } instance : partial_order (α →𝒄 β) := partial_order.lift continuous_hom.to_fun $ by rintro ⟨⟩ ⟨⟩ h; congr; exact h end old_struct namespace continuous_hom theorem congr_fun {f g : α →𝒄 β} (h : f = g) (x : α) : f x = g x := congr_arg (λ h : α →𝒄 β, h x) h theorem congr_arg (f : α →𝒄 β) {x y : α} (h : x = y) : f x = f y := congr_arg (λ x : α, f x) h @[mono] lemma monotone (f : α →𝒄 β) : monotone f := continuous_hom.monotone' f lemma ite_continuous' {p : Prop} [hp : decidable p] (f g : α → β) (hf : continuous' f) (hg : continuous' g) : continuous' (λ x, if p then f x else g x) := by split_ifs; simp * lemma ωSup_bind {β γ : Type v} (c : chain α) (f : α →ₘ roption β) (g : α →ₘ β → roption γ) : ωSup (c.map (f.bind g)) = ωSup (c.map f) >>= ωSup (c.map g) := begin apply eq_of_forall_ge_iff, intro x, simp only [ωSup_le_iff, roption.bind_le, chain.mem_map_iff, and_imp, preorder_hom.bind_to_fun, exists_imp_distrib], split; intro h''', { intros b hb, apply ωSup_le _ _ _, rintros i y hy, simp only [roption.mem_ωSup] at hb, rcases hb with ⟨j,hb⟩, replace hb := hb.symm, simp only [roption.eq_some_iff, chain.map_to_fun, function.comp_app, pi.monotone_apply_to_fun] at hy hb, replace hb : b ∈ f (c (max i j)) := f.monotone (c.monotone (le_max_right i j)) _ hb, replace hy : y ∈ g (c (max i j)) b := g.monotone (c.monotone (le_max_left i j)) _ _ hy, apply h''' (max i j), simp only [exists_prop, roption.bind_eq_bind, roption.mem_bind_iff, chain.map_to_fun, function.comp_app, preorder_hom.bind_to_fun], exact ⟨_,hb,hy⟩, }, { intros i, intros y hy, simp only [exists_prop, roption.bind_eq_bind, roption.mem_bind_iff, chain.map_to_fun, function.comp_app, preorder_hom.bind_to_fun] at hy, rcases hy with ⟨b,hb₀,hb₁⟩, apply h''' b _, { apply le_ωSup (c.map g) _ _ _ hb₁ }, { apply le_ωSup (c.map f) i _ hb₀ } }, end lemma bind_continuous' {β γ : Type v} (f : α → roption β) (g : α → β → roption γ) : continuous' f → continuous' g → continuous' (λ x, f x >>= g x) | ⟨hf,hf'⟩ ⟨hg,hg'⟩ := continuous.of_bundled' (preorder_hom.bind ⟨f,hf⟩ ⟨g,hg⟩) (by intro c; rw [ωSup_bind, ← hf', ← hg']; refl) lemma map_continuous' {β γ : Type v} (f : β → γ) (g : α → roption β) (hg : continuous' g) : continuous' (λ x, f <$> g x) := by simp only [map_eq_bind_pure_comp]; apply bind_continuous' _ _ hg; apply const_continuous' lemma seq_continuous' {β γ : Type v} (f : α → roption (β → γ)) (g : α → roption β) (hf : continuous' f) (hg : continuous' g) : continuous' (λ x, f x <*> g x) := by simp only [seq_eq_bind_map]; apply bind_continuous' _ _ hf; apply pi.omega_complete_partial_order.flip₂_continuous'; intro; apply map_continuous' _ _ hg lemma continuous (F : α →𝒄 β) (C : chain α) : F (ωSup C) = ωSup (C.map F) := continuous_hom.cont _ _ /-- Construct a continuous function from a bare function, a continuous function, and a proof that they are equal. -/ @[simps, reducible] def of_fun (f : α → β) (g : α →𝒄 β) (h : f = g) : α →𝒄 β := by refine {to_fun := f, ..}; subst h; cases g; assumption /-- Construct a continuous function from a monotone function with a proof of continuity. -/ @[simps, reducible] def of_mono (f : α →ₘ β) (h : ∀ c : chain α, f (ωSup c) = ωSup (c.map f)) : α →𝒄 β := { to_fun := f, monotone' := f.monotone, cont := h } /-- The identity as a continuous function. -/ @[simps] def id : α →𝒄 α := of_mono preorder_hom.id (by intro; rw [chain.map_id]; refl) /-- The composition of continuous functions. -/ @[simps] def comp (f : β →𝒄 γ) (g : α →𝒄 β) : α →𝒄 γ := of_mono (preorder_hom.comp (↑f) (↑g)) (by intro; rw [preorder_hom.comp, ← preorder_hom.comp, ← chain.map_comp, ← f.continuous, ← g.continuous]; refl) @[ext] protected lemma ext (f g : α →𝒄 β) (h : ∀ x, f x = g x) : f = g := by cases f; cases g; congr; ext; apply h protected lemma coe_inj (f g : α →𝒄 β) (h : (f : α → β) = g) : f = g := continuous_hom.ext _ _ $ _root_.congr_fun h @[simp] lemma comp_id (f : β →𝒄 γ) : f.comp id = f := by ext; refl @[simp] lemma id_comp (f : β →𝒄 γ) : id.comp f = f := by ext; refl @[simp] lemma comp_assoc (f : γ →𝒄 φ) (g : β →𝒄 γ) (h : α →𝒄 β) : f.comp (g.comp h) = (f.comp g).comp h := by ext; refl @[simp] lemma coe_apply (a : α) (f : α →𝒄 β) : (f : α →ₘ β) a = f a := rfl /-- `function.const` is a continuous function. -/ def const (f : β) : α →𝒄 β := of_mono (preorder_hom.const _ f) begin intro c, apply le_antisymm, { simp only [function.const, preorder_hom.const_to_fun], apply le_ωSup_of_le 0, refl }, { apply ωSup_le, simp only [preorder_hom.const_to_fun, chain.map_to_fun, function.comp_app], intros, refl }, end @[simp] theorem const_apply (f : β) (a : α) : const f a = f := rfl instance [inhabited β] : inhabited (α →𝒄 β) := ⟨ const (default β) ⟩ namespace prod /-- The application of continuous functions as a monotone function. (It would make sense to make it a continuous function, but we are currently constructing a `omega_complete_partial_order` instance for `α →𝒄 β`, and we cannot use it as the domain or image of a continuous function before we do.) -/ @[simps] def apply : (α →𝒄 β) × α →ₘ β := { to_fun := λ f, f.1 f.2, monotone' := λ x y h, by dsimp; transitivity y.fst x.snd; [apply h.1, apply y.1.monotone h.2] } end prod /-- The map from continuous functions to monotone functions is itself a monotone function. -/ @[simps] def to_mono : (α →𝒄 β) →ₘ (α →ₘ β) := { to_fun := λ f, f, monotone' := λ x y h, h } /-- When proving that a chain of applications is below a bound `z`, it suffices to consider the functions and values being selected from the same index in the chains. This lemma is more specific than necessary, i.e. `c₀` only needs to be a chain of monotone functions, but it is only used with continuous functions. -/ @[simp] lemma forall_forall_merge (c₀ : chain (α →𝒄 β)) (c₁ : chain α) (z : β) : (∀ (i j : ℕ), (c₀ i) (c₁ j) ≤ z) ↔ ∀ (i : ℕ), (c₀ i) (c₁ i) ≤ z := begin split; introv h, { apply h }, { apply le_trans _ (h (max i j)), transitivity c₀ i (c₁ (max i j)), { apply (c₀ i).monotone, apply c₁.monotone, apply le_max_right }, { apply c₀.monotone, apply le_max_left } } end @[simp] lemma forall_forall_merge' (c₀ : chain (α →𝒄 β)) (c₁ : chain α) (z : β) : (∀ (j i : ℕ), (c₀ i) (c₁ j) ≤ z) ↔ ∀ (i : ℕ), (c₀ i) (c₁ i) ≤ z := by rw [forall_swap,forall_forall_merge] /-- The `ωSup` operator for continuous functions, which takes the pointwise countable supremum of the functions in the `ω`-chain. -/ @[simps] protected def ωSup (c : chain (α →𝒄 β)) : α →𝒄 β := continuous_hom.of_mono (ωSup $ c.map to_mono) begin intro c', apply eq_of_forall_ge_iff, intro z, simp only [ωSup_le_iff, (c _).continuous, chain.map_to_fun, preorder_hom.monotone_apply_to_fun, to_mono_to_fun, coe_apply, preorder_hom.omega_complete_partial_order_ωSup_to_fun, forall_forall_merge, forall_forall_merge', function.comp_app], end @[simps ωSup] instance : omega_complete_partial_order (α →𝒄 β) := omega_complete_partial_order.lift continuous_hom.to_mono continuous_hom.ωSup (λ x y h, h) (λ c, rfl) lemma ωSup_def (c : chain (α →𝒄 β)) (x : α) : ωSup c x = continuous_hom.ωSup c x := rfl lemma ωSup_ωSup (c₀ : chain (α →𝒄 β)) (c₁ : chain α) : ωSup c₀ (ωSup c₁) = ωSup (continuous_hom.prod.apply.comp $ c₀.zip c₁) := begin apply eq_of_forall_ge_iff, intro z, simp only [ωSup_le_iff, (c₀ _).continuous, chain.map_to_fun, to_mono_to_fun, coe_apply, preorder_hom.omega_complete_partial_order_ωSup_to_fun, ωSup_def, forall_forall_merge, chain.zip_to_fun, preorder_hom.prod.map_to_fun, preorder_hom.prod.diag_to_fun, prod.map_mk, preorder_hom.monotone_apply_to_fun, function.comp_app, prod.apply_to_fun, preorder_hom.comp_to_fun, ωSup_to_fun], end /-- A family of continuous functions yields a continuous family of functions. -/ @[simps] def flip {α : Type*} (f : α → β →𝒄 γ) : β →𝒄 α → γ := { to_fun := λ x y, f y x, monotone' := λ x y h a, (f a).monotone h, cont := by intro; ext; change f x _ = _; rw [(f x).continuous ]; refl, } /-- `roption.bind` as a continuous function. -/ @[simps { rhs_md := reducible }] noncomputable def bind {β γ : Type v} (f : α →𝒄 roption β) (g : α →𝒄 β → roption γ) : α →𝒄 roption γ := of_mono (preorder_hom.bind (↑f) (↑g)) $ λ c, begin rw [preorder_hom.bind, ← preorder_hom.bind, ωSup_bind, ← f.continuous, ← g.continuous], refl end /-- `roption.map` as a continuous function. -/ @[simps {rhs_md := reducible}] noncomputable def map {β γ : Type v} (f : β → γ) (g : α →𝒄 roption β) : α →𝒄 roption γ := of_fun (λ x, f <$> g x) (bind g (const (pure ∘ f))) $ by ext; simp only [map_eq_bind_pure_comp, bind_to_fun, preorder_hom.bind_to_fun, const_apply, preorder_hom.const_to_fun, coe_apply] /-- `roption.seq` as a continuous function. -/ @[simps {rhs_md := reducible}] noncomputable def seq {β γ : Type v} (f : α →𝒄 roption (β → γ)) (g : α →𝒄 roption β) : α →𝒄 roption γ := of_fun (λ x, f x <*> g x) (bind f $ (flip $ _root_.flip map g)) (by ext; simp only [seq_eq_bind_map, flip, roption.bind_eq_bind, map_to_fun, roption.mem_bind_iff, bind_to_fun, preorder_hom.bind_to_fun, coe_apply, flip_to_fun]; refl) end continuous_hom end omega_complete_partial_order
eaae66ea88972ab125f57023cc1baf14a9659aa3
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/computability/partrec_code.lean
766b429a9f17b96e27aa10a3da1bd75a7b88a23a
[ "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
43,299
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 /-! # Gödel Numbering for Partial Recursive Functions. This file defines `nat.partrec.code`, an inductive datatype describing code for partial recursive functions on ℕ. It defines an encoding for these codes, and proves that the constructors are primitive recursive with respect to the encoding. It also defines the evalution of these codes as partial functions using `pfun`, and proves that a function is partially recursive (as defined by `nat.partrec`) if and only if it is the evaluation of some code. ## Main Definitions * `nat.partrec.code`: Inductive datatype for partial recursive codes. * `nat.partrec.code.encode_code`: A (computable) encoding of codes as natural numbers. * `nat.partrec.code.of_nat_code`: The inverse of this encoding. * `nat.partrec.code.eval`: The interpretation of a `nat.partrec.code` as a partial function. ## Main Results * `nat.partrec.code.rec_prim`: Recursion on `nat.partrec.code` is primitive recursive. * `nat.partrec.code.rec_computable`: Recursion on `nat.partrec.code` is computable. * `nat.partrec.code.smn`: The $S_n^m$ theorem. * `nat.partrec.code.exists_code`: Partial recursiveness is equivalent to being the eval of a code. * `nat.partrec.code.evaln_prim`: `evaln` is primitive recursive. * `nat.partrec.code.fixed_point`: Roger's fixed point theorem. ## References * [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019] -/ open encodable denumerable namespace nat.partrec open nat (mkpair) theorem rfind' {f} (hf : nat.partrec f) : nat.partrec (nat.unpaired (λ a m, (nat.rfind (λ n, (λ m, m = 0) <$> f (mkpair a (n + m)))).map (+ m))) := partrec₂.unpaired'.2 $ begin refine partrec.map ((@partrec₂.unpaired' (λ (a b : ℕ), nat.rfind (λ n, (λ m, m = 0) <$> f (mkpair a (n + b))))).1 _) (primrec.nat_add.comp primrec.snd $ primrec.snd.comp primrec.fst).to_comp.to₂, have := rfind (partrec₂.unpaired'.2 ((partrec.nat_iff.2 hf).comp (primrec₂.mkpair.comp (primrec.fst.comp $ primrec.unpair.comp primrec.fst) (primrec.nat_add.comp primrec.snd (primrec.snd.comp $ primrec.unpair.comp primrec.fst))).to_comp).to₂), simp at this, exact this end /-- Code for partial recursive functions from ℕ to ℕ. See `nat.partrec.code.eval` for the interpretation of these constructors. -/ inductive code : Type | zero : code | succ : code | left : code | right : code | pair : code → code → code | comp : code → code → code | prec : code → code → code | rfind' : code → code end nat.partrec namespace nat.partrec.code open nat (mkpair unpair) open nat.partrec (code) instance : inhabited code := ⟨zero⟩ /-- Returns a code for the constant function outputting a particular natural. -/ protected def const : ℕ → code | 0 := zero | (n+1) := comp succ (const n) theorem const_inj : Π {n₁ n₂}, nat.partrec.code.const n₁ = nat.partrec.code.const n₂ → n₁ = n₂ | 0 0 h := by simp | (n₁+1) (n₂+1) h := by { dsimp [nat.partrec.code.const] at h, injection h with h₁ h₂, simp only [const_inj h₂] } /-- A code for the identity function. -/ protected def id : code := pair left right /-- Given a code `c` taking a pair as input, returns a code using `n` as the first argument to `c`. -/ def curry (c : code) (n : ℕ) : code := comp c (pair (code.const n) code.id) /-- An encoding of a `nat.partrec.code` as a ℕ. -/ def encode_code : code → ℕ | zero := 0 | succ := 1 | left := 2 | right := 3 | (pair cf cg) := bit0 (bit0 $ mkpair (encode_code cf) (encode_code cg)) + 4 | (comp cf cg) := bit0 (bit1 $ mkpair (encode_code cf) (encode_code cg)) + 4 | (prec cf cg) := bit1 (bit0 $ mkpair (encode_code cf) (encode_code cg)) + 4 | (rfind' cf) := bit1 (bit1 $ encode_code cf) + 4 /-- A decoder for `nat.partrec.code.encode_code`, taking any ℕ to the `nat.partrec.code` it represents. -/ def of_nat_code : ℕ → code | 0 := zero | 1 := succ | 2 := left | 3 := right | (n+4) := let m := n.div2.div2 in have hm : m < n + 4, by simp [m, nat.div2_val]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_left_le hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_right_le hm, match n.bodd, n.div2.bodd with | ff, ff := pair (of_nat_code m.unpair.1) (of_nat_code m.unpair.2) | ff, tt := comp (of_nat_code m.unpair.1) (of_nat_code m.unpair.2) | tt, ff := prec (of_nat_code m.unpair.1) (of_nat_code m.unpair.2) | tt, tt := rfind' (of_nat_code m) end /-- Proof that `nat.partrec.code.of_nat_code` is the inverse of `nat.partrec.code.encode_code`-/ private theorem encode_of_nat_code : ∀ n, encode_code (of_nat_code n) = n | 0 := by simp [of_nat_code, encode_code] | 1 := by simp [of_nat_code, encode_code] | 2 := by simp [of_nat_code, encode_code] | 3 := by simp [of_nat_code, encode_code] | (n+4) := let m := n.div2.div2 in have hm : m < n + 4, by simp [m, nat.div2_val]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_left_le hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_right_le hm, have IH : _ := encode_of_nat_code m, have IH1 : _ := encode_of_nat_code m.unpair.1, have IH2 : _ := encode_of_nat_code m.unpair.2, begin transitivity, swap, rw [← nat.bit_decomp n, ← nat.bit_decomp n.div2], simp [encode_code, of_nat_code, -add_comm], cases n.bodd; cases n.div2.bodd; simp [encode_code, of_nat_code, -add_comm, IH, IH1, IH2, m, nat.bit] end instance : denumerable code := mk' ⟨encode_code, of_nat_code, λ c, by induction c; try {refl}; simp [ encode_code, of_nat_code, -add_comm, *], encode_of_nat_code⟩ theorem encode_code_eq : encode = encode_code := rfl theorem of_nat_code_eq : of_nat code = of_nat_code := rfl theorem encode_lt_pair (cf cg) : encode cf < encode (pair cf cg) ∧ encode cg < encode (pair cf cg) := begin simp [encode_code_eq, encode_code, -add_comm], have := nat.mul_le_mul_right _ (dec_trivial : 1 ≤ 2*2), rw [one_mul, mul_assoc, ← bit0_eq_two_mul, ← bit0_eq_two_mul] at this, have := lt_of_le_of_lt this (lt_add_of_pos_right _ (dec_trivial:0<4)), exact ⟨ lt_of_le_of_lt (nat.left_le_mkpair _ _) this, lt_of_le_of_lt (nat.right_le_mkpair _ _) this⟩ end theorem encode_lt_comp (cf cg) : encode cf < encode (comp cf cg) ∧ encode cg < encode (comp cf cg) := begin suffices, exact (encode_lt_pair cf cg).imp (λ h, lt_trans h this) (λ h, lt_trans h this), change _, simp [encode_code_eq, encode_code] end theorem encode_lt_prec (cf cg) : encode cf < encode (prec cf cg) ∧ encode cg < encode (prec cf cg) := begin suffices, exact (encode_lt_pair cf cg).imp (λ h, lt_trans h this) (λ h, lt_trans h this), change _, simp [encode_code_eq, encode_code], end theorem encode_lt_rfind' (cf) : encode cf < encode (rfind' cf) := begin simp [encode_code_eq, encode_code, -add_comm], have := nat.mul_le_mul_right _ (dec_trivial : 1 ≤ 2*2), rw [one_mul, mul_assoc, ← bit0_eq_two_mul, ← bit0_eq_two_mul] at this, refine lt_of_le_of_lt (le_trans this _) (lt_add_of_pos_right _ (dec_trivial:0<4)), exact le_of_lt (nat.bit0_lt_bit1 $ le_of_lt $ nat.bit0_lt_bit1 $ le_rfl), end section open primrec theorem pair_prim : primrec₂ pair := primrec₂.of_nat_iff.2 $ primrec₂.encode_iff.1 $ nat_add.comp (nat_bit0.comp $ nat_bit0.comp $ primrec₂.mkpair.comp (encode_iff.2 $ (primrec.of_nat code).comp fst) (encode_iff.2 $ (primrec.of_nat code).comp snd)) (primrec₂.const 4) theorem comp_prim : primrec₂ comp := primrec₂.of_nat_iff.2 $ primrec₂.encode_iff.1 $ nat_add.comp (nat_bit0.comp $ nat_bit1.comp $ primrec₂.mkpair.comp (encode_iff.2 $ (primrec.of_nat code).comp fst) (encode_iff.2 $ (primrec.of_nat code).comp snd)) (primrec₂.const 4) theorem prec_prim : primrec₂ prec := primrec₂.of_nat_iff.2 $ primrec₂.encode_iff.1 $ nat_add.comp (nat_bit1.comp $ nat_bit0.comp $ primrec₂.mkpair.comp (encode_iff.2 $ (primrec.of_nat code).comp fst) (encode_iff.2 $ (primrec.of_nat code).comp snd)) (primrec₂.const 4) theorem rfind_prim : primrec rfind' := of_nat_iff.2 $ encode_iff.1 $ nat_add.comp (nat_bit1.comp $ nat_bit1.comp $ encode_iff.2 $ primrec.of_nat code) (const 4) theorem rec_prim' {α σ} [primcodable α] [primcodable σ] {c : α → code} (hc : primrec c) {z : α → σ} (hz : primrec z) {s : α → σ} (hs : primrec s) {l : α → σ} (hl : primrec l) {r : α → σ} (hr : primrec r) {pr : α → code × code × σ × σ → σ} (hpr : primrec₂ pr) {co : α → code × code × σ × σ → σ} (hco : primrec₂ co) {pc : α → code × code × σ × σ → σ} (hpc : primrec₂ pc) {rf : α → code × σ → σ} (hrf : primrec₂ rf) : let PR (a) := λ cf cg hf hg, pr a (cf, cg, hf, hg), CO (a) := λ cf cg hf hg, co a (cf, cg, hf, hg), PC (a) := λ cf cg hf hg, pc a (cf, cg, hf, hg), RF (a) := λ cf hf, rf a (cf, hf), F (a : α) (c : code) : σ := nat.partrec.code.rec_on c (z a) (s a) (l a) (r a) (PR a) (CO a) (PC a) (RF a) in primrec (λ a, F a (c a) : α → σ) := begin intros, let G₁ : (α × list σ) × ℕ × ℕ → option σ := λ p, let a := p.1.1, IH := p.1.2, n := p.2.1, m := p.2.2 in (IH.nth m).bind $ λ s, (IH.nth m.unpair.1).bind $ λ s₁, (IH.nth m.unpair.2).map $ λ s₂, cond n.bodd (cond n.div2.bodd (rf a (of_nat code m, s)) (pc a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂))) (cond n.div2.bodd (co a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂)) (pr a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂))), have : primrec G₁, { refine option_bind (list_nth.comp (snd.comp fst) (snd.comp snd)) _, refine option_bind ((list_nth.comp (snd.comp fst) (fst.comp $ primrec.unpair.comp (snd.comp snd))).comp fst) _, refine option_map ((list_nth.comp (snd.comp fst) (snd.comp $ primrec.unpair.comp (snd.comp snd))).comp $ fst.comp fst) _, have a := fst.comp (fst.comp $ fst.comp $ fst.comp fst), have n := fst.comp (snd.comp $ fst.comp $ fst.comp fst), have m := snd.comp (snd.comp $ fst.comp $ fst.comp fst), have m₁ := fst.comp (primrec.unpair.comp m), have m₂ := snd.comp (primrec.unpair.comp m), have s := snd.comp (fst.comp fst), have s₁ := snd.comp fst, have s₂ := snd, exact (nat_bodd.comp n).cond ((nat_bodd.comp $ nat_div2.comp n).cond (hrf.comp a (((primrec.of_nat code).comp m).pair s)) (hpc.comp a (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂))) (primrec.cond (nat_bodd.comp $ nat_div2.comp n) (hco.comp a (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂)) (hpr.comp a (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂))) }, let G : α → list σ → option σ := λ a IH, IH.length.cases (some (z a)) $ λ n, n.cases (some (s a)) $ λ n, n.cases (some (l a)) $ λ n, n.cases (some (r a)) $ λ n, G₁ ((a, IH), n, n.div2.div2), have : primrec₂ G := (nat_cases (list_length.comp snd) (option_some_iff.2 (hz.comp fst)) $ nat_cases snd (option_some_iff.2 (hs.comp (fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hl.comp (fst.comp $ fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hr.comp (fst.comp $ fst.comp $ fst.comp fst))) (this.comp $ ((fst.pair snd).comp $ fst.comp $ fst.comp $ fst.comp $ fst).pair $ snd.pair $ nat_div2.comp $ nat_div2.comp snd)), refine ((nat_strong_rec (λ a n, F a (of_nat code n)) this.to₂ $ λ a n, _).comp primrec.id $ encode_iff.2 hc).of_eq (λ a, by simp), simp, iterate 4 {cases n with n, {simp [of_nat_code_eq, of_nat_code]; refl}}, simp [G], rw [list.length_map, list.length_range], let m := n.div2.div2, show G₁ ((a, (list.range (n+4)).map (λ n, F a (of_nat code n))), n, m) = some (F a (of_nat code (n+4))), have hm : m < n + 4, by simp [nat.div2_val, m]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_left_le hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_right_le hm, simp [G₁], simp [list.nth_map, list.nth_range, hm, m1, m2], change of_nat code (n+4) with of_nat_code (n+4), simp [of_nat_code], cases n.bodd; cases n.div2.bodd; refl end /-- Recursion on `nat.partrec.code` is primitive recursive. -/ theorem rec_prim {α σ} [primcodable α] [primcodable σ] {c : α → code} (hc : primrec c) {z : α → σ} (hz : primrec z) {s : α → σ} (hs : primrec s) {l : α → σ} (hl : primrec l) {r : α → σ} (hr : primrec r) {pr : α → code → code → σ → σ → σ} (hpr : primrec (λ a : α × code × code × σ × σ, pr a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2)) {co : α → code → code → σ → σ → σ} (hco : primrec (λ a : α × code × code × σ × σ, co a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2)) {pc : α → code → code → σ → σ → σ} (hpc : primrec (λ a : α × code × code × σ × σ, pc a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2)) {rf : α → code → σ → σ} (hrf : primrec (λ a : α × code × σ, rf a.1 a.2.1 a.2.2)) : let F (a : α) (c : code) : σ := nat.partrec.code.rec_on c (z a) (s a) (l a) (r a) (pr a) (co a) (pc a) (rf a) in primrec (λ a, F a (c a)) := begin intros, let G₁ : (α × list σ) × ℕ × ℕ → option σ := λ p, let a := p.1.1, IH := p.1.2, n := p.2.1, m := p.2.2 in (IH.nth m).bind $ λ s, (IH.nth m.unpair.1).bind $ λ s₁, (IH.nth m.unpair.2).map $ λ s₂, cond n.bodd (cond n.div2.bodd (rf a (of_nat code m) s) (pc a (of_nat code m.unpair.1) (of_nat code m.unpair.2) s₁ s₂)) (cond n.div2.bodd (co a (of_nat code m.unpair.1) (of_nat code m.unpair.2) s₁ s₂) (pr a (of_nat code m.unpair.1) (of_nat code m.unpair.2) s₁ s₂)), have : primrec G₁, { refine option_bind (list_nth.comp (snd.comp fst) (snd.comp snd)) _, refine option_bind ((list_nth.comp (snd.comp fst) (fst.comp $ primrec.unpair.comp (snd.comp snd))).comp fst) _, refine option_map ((list_nth.comp (snd.comp fst) (snd.comp $ primrec.unpair.comp (snd.comp snd))).comp $ fst.comp fst) _, have a := fst.comp (fst.comp $ fst.comp $ fst.comp fst), have n := fst.comp (snd.comp $ fst.comp $ fst.comp fst), have m := snd.comp (snd.comp $ fst.comp $ fst.comp fst), have m₁ := fst.comp (primrec.unpair.comp m), have m₂ := snd.comp (primrec.unpair.comp m), have s := snd.comp (fst.comp fst), have s₁ := snd.comp fst, have s₂ := snd, exact (nat_bodd.comp n).cond ((nat_bodd.comp $ nat_div2.comp n).cond (hrf.comp $ a.pair (((primrec.of_nat code).comp m).pair s)) (hpc.comp $ a.pair (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂))) (primrec.cond (nat_bodd.comp $ nat_div2.comp n) (hco.comp $ a.pair (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂)) (hpr.comp $ a.pair (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp m₂).pair $ s₁.pair s₂))) }, let G : α → list σ → option σ := λ a IH, IH.length.cases (some (z a)) $ λ n, n.cases (some (s a)) $ λ n, n.cases (some (l a)) $ λ n, n.cases (some (r a)) $ λ n, G₁ ((a, IH), n, n.div2.div2), have : primrec₂ G := (nat_cases (list_length.comp snd) (option_some_iff.2 (hz.comp fst)) $ nat_cases snd (option_some_iff.2 (hs.comp (fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hl.comp (fst.comp $ fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hr.comp (fst.comp $ fst.comp $ fst.comp fst))) (this.comp $ ((fst.pair snd).comp $ fst.comp $ fst.comp $ fst.comp $ fst).pair $ snd.pair $ nat_div2.comp $ nat_div2.comp snd)), refine ((nat_strong_rec (λ a n, F a (of_nat code n)) this.to₂ $ λ a n, _).comp primrec.id $ encode_iff.2 hc).of_eq (λ a, by simp), simp, iterate 4 {cases n with n, {simp [of_nat_code_eq, of_nat_code]; refl}}, simp [G], rw [list.length_map, list.length_range], let m := n.div2.div2, show G₁ ((a, (list.range (n+4)).map (λ n, F a (of_nat code n))), n, m) = some (F a (of_nat code (n+4))), have hm : m < n + 4, by simp [nat.div2_val, m]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_left_le hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_right_le hm, simp [G₁], simp [list.nth_map, list.nth_range, hm, m1, m2], change of_nat code (n+4) with of_nat_code (n+4), simp [of_nat_code], cases n.bodd; cases n.div2.bodd; refl end end section open computable /-- Recursion on `nat.partrec.code` is computable. -/ theorem rec_computable {α σ} [primcodable α] [primcodable σ] {c : α → code} (hc : computable c) {z : α → σ} (hz : computable z) {s : α → σ} (hs : computable s) {l : α → σ} (hl : computable l) {r : α → σ} (hr : computable r) {pr : α → code × code × σ × σ → σ} (hpr : computable₂ pr) {co : α → code × code × σ × σ → σ} (hco : computable₂ co) {pc : α → code × code × σ × σ → σ} (hpc : computable₂ pc) {rf : α → code × σ → σ} (hrf : computable₂ rf) : let PR (a) := λ cf cg hf hg, pr a (cf, cg, hf, hg), CO (a) := λ cf cg hf hg, co a (cf, cg, hf, hg), PC (a) := λ cf cg hf hg, pc a (cf, cg, hf, hg), RF (a) := λ cf hf, rf a (cf, hf), F (a : α) (c : code) : σ := nat.partrec.code.rec_on c (z a) (s a) (l a) (r a) (PR a) (CO a) (PC a) (RF a) in computable (λ a, F a (c a)) := begin -- TODO(Mario): less copy-paste from previous proof intros, let G₁ : (α × list σ) × ℕ × ℕ → option σ := λ p, let a := p.1.1, IH := p.1.2, n := p.2.1, m := p.2.2 in (IH.nth m).bind $ λ s, (IH.nth m.unpair.1).bind $ λ s₁, (IH.nth m.unpair.2).map $ λ s₂, cond n.bodd (cond n.div2.bodd (rf a (of_nat code m, s)) (pc a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂))) (cond n.div2.bodd (co a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂)) (pr a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, s₂))), have : computable G₁, { refine option_bind (list_nth.comp (snd.comp fst) (snd.comp snd)) _, refine option_bind ((list_nth.comp (snd.comp fst) (fst.comp $ computable.unpair.comp (snd.comp snd))).comp fst) _, refine option_map ((list_nth.comp (snd.comp fst) (snd.comp $ computable.unpair.comp (snd.comp snd))).comp $ fst.comp fst) _, have a := fst.comp (fst.comp $ fst.comp $ fst.comp fst), have n := fst.comp (snd.comp $ fst.comp $ fst.comp fst), have m := snd.comp (snd.comp $ fst.comp $ fst.comp fst), have m₁ := fst.comp (computable.unpair.comp m), have m₂ := snd.comp (computable.unpair.comp m), have s := snd.comp (fst.comp fst), have s₁ := snd.comp fst, have s₂ := snd, exact (nat_bodd.comp n).cond ((nat_bodd.comp $ nat_div2.comp n).cond (hrf.comp a (((computable.of_nat code).comp m).pair s)) (hpc.comp a (((computable.of_nat code).comp m₁).pair $ ((computable.of_nat code).comp m₂).pair $ s₁.pair s₂))) (computable.cond (nat_bodd.comp $ nat_div2.comp n) (hco.comp a (((computable.of_nat code).comp m₁).pair $ ((computable.of_nat code).comp m₂).pair $ s₁.pair s₂)) (hpr.comp a (((computable.of_nat code).comp m₁).pair $ ((computable.of_nat code).comp m₂).pair $ s₁.pair s₂))) }, let G : α → list σ → option σ := λ a IH, IH.length.cases (some (z a)) $ λ n, n.cases (some (s a)) $ λ n, n.cases (some (l a)) $ λ n, n.cases (some (r a)) $ λ n, G₁ ((a, IH), n, n.div2.div2), have : computable₂ G := (nat_cases (list_length.comp snd) (option_some_iff.2 (hz.comp fst)) $ nat_cases snd (option_some_iff.2 (hs.comp (fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hl.comp (fst.comp $ fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hr.comp (fst.comp $ fst.comp $ fst.comp fst))) (this.comp $ ((fst.pair snd).comp $ fst.comp $ fst.comp $ fst.comp $ fst).pair $ snd.pair $ nat_div2.comp $ nat_div2.comp snd)), refine ((nat_strong_rec (λ a n, F a (of_nat code n)) this.to₂ $ λ a n, _).comp computable.id $ encode_iff.2 hc).of_eq (λ a, by simp), simp, iterate 4 {cases n with n, {simp [of_nat_code_eq, of_nat_code]; refl}}, simp [G], rw [list.length_map, list.length_range], let m := n.div2.div2, show G₁ ((a, (list.range (n+4)).map (λ n, F a (of_nat code n))), n, m) = some (F a (of_nat code (n+4))), have hm : m < n + 4, by simp [nat.div2_val, m]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_left_le hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_right_le hm, simp [G₁], simp [list.nth_map, list.nth_range, hm, m1, m2], change of_nat code (n+4) with of_nat_code (n+4), simp [of_nat_code], cases n.bodd; cases n.div2.bodd; refl end end /-- The interpretation of a `nat.partrec.code` as a partial function. * `nat.partrec.code.zero`: The constant zero function. * `nat.partrec.code.succ`: The successor function. * `nat.partrec.code.left`: Left unpairing of a pair of ℕ (encoded by `nat.mkpair`) * `nat.partrec.code.right`: Right unpairing of a pair of ℕ (encoded by `nat.mkpair`) * `nat.partrec.code.pair`: Pairs the outputs of argument codes using `nat.mkpair`. * `nat.partrec.code.comp`: Composition of two argument codes. * `nat.partrec.code.prec`: Primitive recursion. Given an argument of the form `nat.mkpair a n`: * If `n = 0`, returns `eval cf a`. * If `n = succ k`, returns `eval cg (mkpair a (mkpair k (eval (prec cf cg) (mkpair a k))))` * `nat.partrec.code.rfind'`: Minimization. For `f` an argument of the form `nat.mkpair a m`, `rfind' f m` returns the least `a` such that `f a m = 0`, if one exists and `f b m` terminates for `b < a` -/ def eval : code → ℕ →. ℕ | zero := pure 0 | succ := nat.succ | left := ↑(λ n : ℕ, n.unpair.1) | right := ↑(λ n : ℕ, n.unpair.2) | (pair cf cg) := λ n, mkpair <$> eval cf n <*> eval cg n | (comp cf cg) := λ n, eval cg n >>= eval cf | (prec cf cg) := nat.unpaired (λ a n, n.elim (eval cf a) (λ y IH, do i ← IH, eval cg (mkpair a (mkpair y i)))) | (rfind' cf) := nat.unpaired (λ a m, (nat.rfind (λ n, (λ m, m = 0) <$> eval cf (mkpair a (n + m)))).map (+ m)) /-- Helper lemma for the evaluation of `prec` in the base case. -/ @[simp] lemma eval_prec_zero (cf cg : code) (a : ℕ) : eval (prec cf cg) (mkpair a 0) = eval cf a := by rw [eval, nat.unpaired, nat.unpair_mkpair, nat.elim_zero] /-- Helper lemma for the evaluation of `prec` in the recursive case. -/ lemma eval_prec_succ (cf cg : code) (a k : ℕ) : eval (prec cf cg) (mkpair a (nat.succ k)) = do ih <- eval (prec cf cg) (mkpair a k), eval cg (mkpair a (mkpair k ih)) := begin rw [eval, nat.unpaired, part.bind_eq_bind, nat.unpair_mkpair, nat.elim_succ], simp, end instance : has_mem (ℕ →. ℕ) code := ⟨λ f c, eval c = f⟩ @[simp] theorem eval_const : ∀ n m, eval (code.const n) m = part.some n | 0 m := rfl | (n+1) m := by simp! * @[simp] theorem eval_id (n) : eval code.id n = part.some n := by simp! [(<*>)] @[simp] theorem eval_curry (c n x) : eval (curry c n) x = eval c (mkpair n x) := by simp! [(<*>)] theorem const_prim : primrec code.const := (primrec.id.nat_iterate (primrec.const zero) (comp_prim.comp (primrec.const succ) primrec.snd).to₂).of_eq $ λ n, by simp; induction n; simp [*, code.const, function.iterate_succ'] theorem curry_prim : primrec₂ curry := comp_prim.comp primrec.fst $ pair_prim.comp (const_prim.comp primrec.snd) (primrec.const code.id) theorem curry_inj {c₁ c₂ n₁ n₂} (h : curry c₁ n₁ = curry c₂ n₂) : c₁ = c₂ ∧ n₁ = n₂ := ⟨by injection h, by { injection h, injection h with h₁ h₂, injection h₂ with h₃ h₄, exact const_inj h₃ }⟩ /-- The $S_n^m$ theorem: There is a computable function, namely `nat.partrec.code.curry`, that takes a program and a ℕ `n`, and returns a new program using `n` as the first argument. -/ theorem smn : ∃ f : code → ℕ → code, computable₂ f ∧ ∀ c n x, eval (f c n) x = eval c (mkpair n x) := ⟨curry, primrec₂.to_comp curry_prim, eval_curry⟩ /-- A function is partial recursive if and only if there is a code implementing it. -/ theorem exists_code {f : ℕ →. ℕ} : nat.partrec f ↔ ∃ c : code, eval c = f := ⟨λ h, begin induction h, case nat.partrec.zero { exact ⟨zero, rfl⟩ }, case nat.partrec.succ { exact ⟨succ, rfl⟩ }, case nat.partrec.left { exact ⟨left, rfl⟩ }, case nat.partrec.right { exact ⟨right, rfl⟩ }, case nat.partrec.pair : f g pf pg hf hg { rcases hf with ⟨cf, rfl⟩, rcases hg with ⟨cg, rfl⟩, exact ⟨pair cf cg, rfl⟩ }, case nat.partrec.comp : f g pf pg hf hg { rcases hf with ⟨cf, rfl⟩, rcases hg with ⟨cg, rfl⟩, exact ⟨comp cf cg, rfl⟩ }, case nat.partrec.prec : f g pf pg hf hg { rcases hf with ⟨cf, rfl⟩, rcases hg with ⟨cg, rfl⟩, exact ⟨prec cf cg, rfl⟩ }, case nat.partrec.rfind : f pf hf { rcases hf with ⟨cf, rfl⟩, refine ⟨comp (rfind' cf) (pair code.id zero), _⟩, simp [eval, (<*>), pure, pfun.pure, part.map_id'] }, end, λ h, begin rcases h with ⟨c, rfl⟩, induction c, case nat.partrec.code.zero { exact nat.partrec.zero }, case nat.partrec.code.succ { exact nat.partrec.succ }, case nat.partrec.code.left { exact nat.partrec.left }, case nat.partrec.code.right { exact nat.partrec.right }, case nat.partrec.code.pair : cf cg pf pg { exact pf.pair pg }, case nat.partrec.code.comp : cf cg pf pg { exact pf.comp pg }, case nat.partrec.code.prec : cf cg pf pg { exact pf.prec pg }, case nat.partrec.code.rfind' : cf pf { exact pf.rfind' }, end⟩ /-- A modified evaluation for the code which returns an `option ℕ` instead of a `part ℕ`. To avoid undecidability, `evaln` takes a parameter `k` and fails if it encounters a number ≥ k in the course of its execution. Other than this, the semantics are the same as in `nat.partrec.code.eval`. -/ def evaln : ∀ k : ℕ, code → ℕ → option ℕ | 0 _ := λ m, none | (k+1) zero := λ n, guard (n ≤ k) >> pure 0 | (k+1) succ := λ n, guard (n ≤ k) >> pure (nat.succ n) | (k+1) left := λ n, guard (n ≤ k) >> pure n.unpair.1 | (k+1) right := λ n, guard (n ≤ k) >> pure n.unpair.2 | (k+1) (pair cf cg) := λ n, guard (n ≤ k) >> mkpair <$> evaln (k+1) cf n <*> evaln (k+1) cg n | (k+1) (comp cf cg) := λ n, guard (n ≤ k) >> do x ← evaln (k+1) cg n, evaln (k+1) cf x | (k+1) (prec cf cg) := λ n, guard (n ≤ k) >> n.unpaired (λ a n, n.cases (evaln (k+1) cf a) $ λ y, do i ← evaln k (prec cf cg) (mkpair a y), evaln (k+1) cg (mkpair a (mkpair y i))) | (k+1) (rfind' cf) := λ n, guard (n ≤ k) >> n.unpaired (λ a m, do x ← evaln (k+1) cf (mkpair a m), if x = 0 then pure m else evaln k (rfind' cf) (mkpair a (m+1))) theorem evaln_bound : ∀ {k c n x}, x ∈ evaln k c n → n < k | 0 c n x h := by simp [evaln] at h; cases h | (k+1) c n x h := begin suffices : ∀ {o : option ℕ}, x ∈ guard (n ≤ k) >> o → n < k + 1, { cases c; rw [evaln] at h; exact this h }, simpa [(>>)] using nat.lt_succ_of_le end theorem evaln_mono : ∀ {k₁ k₂ c n x}, k₁ ≤ k₂ → x ∈ evaln k₁ c n → x ∈ evaln k₂ c n | 0 k₂ c n x hl h := by simp [evaln] at h; cases h | (k+1) (k₂+1) c n x hl h := begin have hl' := nat.le_of_succ_le_succ hl, have : ∀ {k k₂ n x : ℕ} {o₁ o₂ : option ℕ}, k ≤ k₂ → (x ∈ o₁ → x ∈ o₂) → x ∈ guard (n ≤ k) >> o₁ → x ∈ guard (n ≤ k₂) >> o₂, { simp [(>>)], introv h h₁ h₂ h₃, exact ⟨le_trans h₂ h, h₁ h₃⟩ }, simp at h ⊢, induction c with cf cg hf hg cf cg hf hg cf cg hf hg cf hf generalizing x n; rw [evaln] at h ⊢; refine this hl' (λ h, _) h, iterate 4 {exact h}, { -- pair cf cg simp [(<*>)] at h ⊢, exact h.imp (λ a, and.imp (hf _ _) $ Exists.imp $ λ b, and.imp_left (hg _ _)) }, { -- comp cf cg simp at h ⊢, exact h.imp (λ a, and.imp (hg _ _) (hf _ _)) }, { -- prec cf cg revert h, simp, induction n.unpair.2; simp, { apply hf }, { exact λ y h₁ h₂, ⟨y, evaln_mono hl' h₁, hg _ _ h₂⟩ } }, { -- rfind' cf simp at h ⊢, refine h.imp (λ x, and.imp (hf _ _) _), by_cases x0 : x = 0; simp [x0], exact evaln_mono hl' } end theorem evaln_sound : ∀ {k c n x}, x ∈ evaln k c n → x ∈ eval c n | 0 _ n x h := by simp [evaln] at h; cases h | (k+1) c n x h := begin induction c with cf cg hf hg cf cg hf hg cf cg hf hg cf hf generalizing x n; simp [eval, evaln, (>>), (<*>)] at h ⊢; cases h with _ h, iterate 4 {simpa [pure, pfun.pure, eq_comm] using h}, { -- pair cf cg rcases h with ⟨y, ef, z, eg, rfl⟩, exact ⟨_, hf _ _ ef, _, hg _ _ eg, rfl⟩ }, { --comp hf hg rcases h with ⟨y, eg, ef⟩, exact ⟨_, hg _ _ eg, hf _ _ ef⟩ }, { -- prec cf cg revert h, induction n.unpair.2 with m IH generalizing x; simp, { apply hf }, { refine λ y h₁ h₂, ⟨y, IH _ _, _⟩, { have := evaln_mono k.le_succ h₁, simp [evaln, (>>)] at this, exact this.2 }, { exact hg _ _ h₂ } } }, { -- rfind' cf rcases h with ⟨m, h₁, h₂⟩, by_cases m0 : m = 0; simp [m0] at h₂, { exact ⟨0, ⟨by simpa [m0] using hf _ _ h₁, λ m, (nat.not_lt_zero _).elim⟩, by injection h₂ with h₂; simp [h₂]⟩ }, { have := evaln_sound h₂, simp [eval] at this, rcases this with ⟨y, ⟨hy₁, hy₂⟩, rfl⟩, refine ⟨ y+1, ⟨by simpa [add_comm, add_left_comm] using hy₁, λ i im, _⟩, by simp [add_comm, add_left_comm] ⟩, cases i with i, { exact ⟨m, by simpa using hf _ _ h₁, m0⟩ }, { rcases hy₂ (nat.lt_of_succ_lt_succ im) with ⟨z, hz, z0⟩, exact ⟨z, by simpa [nat.succ_eq_add_one, add_comm, add_left_comm] using hz, z0⟩ } } } end theorem evaln_complete {c n x} : x ∈ eval c n ↔ ∃ k, x ∈ evaln k c n := ⟨λ h, begin rsuffices ⟨k, h⟩ : ∃ k, x ∈ evaln (k+1) c n, { exact ⟨k + 1, h⟩ }, induction c generalizing n x; simp [eval, evaln, pure, pfun.pure, (<*>), (>>)] at h ⊢, iterate 4 { exact ⟨⟨_, le_rfl⟩, h.symm⟩ }, case nat.partrec.code.pair : cf cg hf hg { rcases h with ⟨x, hx, y, hy, rfl⟩, rcases hf hx with ⟨k₁, hk₁⟩, rcases hg hy with ⟨k₂, hk₂⟩, refine ⟨max k₁ k₂, _⟩, refine ⟨le_max_of_le_left $ nat.le_of_lt_succ $ evaln_bound hk₁, _, evaln_mono (nat.succ_le_succ $ le_max_left _ _) hk₁, _, evaln_mono (nat.succ_le_succ $ le_max_right _ _) hk₂, rfl⟩ }, case nat.partrec.code.comp : cf cg hf hg { rcases h with ⟨y, hy, hx⟩, rcases hg hy with ⟨k₁, hk₁⟩, rcases hf hx with ⟨k₂, hk₂⟩, refine ⟨max k₁ k₂, _⟩, exact ⟨le_max_of_le_left $ nat.le_of_lt_succ $ evaln_bound hk₁, _, evaln_mono (nat.succ_le_succ $ le_max_left _ _) hk₁, evaln_mono (nat.succ_le_succ $ le_max_right _ _) hk₂⟩ }, case nat.partrec.code.prec : cf cg hf hg { revert h, generalize : n.unpair.1 = n₁, generalize : n.unpair.2 = n₂, induction n₂ with m IH generalizing x n; simp, { intro, rcases hf h with ⟨k, hk⟩, exact ⟨_, le_max_left _ _, evaln_mono (nat.succ_le_succ $ le_max_right _ _) hk⟩ }, { intros y hy hx, rcases IH hy with ⟨k₁, nk₁, hk₁⟩, rcases hg hx with ⟨k₂, hk₂⟩, refine ⟨(max k₁ k₂).succ, nat.le_succ_of_le $ le_max_of_le_left $ le_trans (le_max_left _ (mkpair n₁ m)) nk₁, y, evaln_mono (nat.succ_le_succ $ le_max_left _ _) _, evaln_mono (nat.succ_le_succ $ nat.le_succ_of_le $ le_max_right _ _) hk₂⟩, simp [evaln, (>>)], exact ⟨le_trans (le_max_right _ _) nk₁, hk₁⟩ } }, case nat.partrec.code.rfind' : cf hf { rcases h with ⟨y, ⟨hy₁, hy₂⟩, rfl⟩, suffices : ∃ k, y + n.unpair.2 ∈ evaln (k+1) (rfind' cf) (mkpair n.unpair.1 n.unpair.2), {simpa [evaln, (>>)]}, revert hy₁ hy₂, generalize : n.unpair.2 = m, intros, induction y with y IH generalizing m; simp [evaln, (>>)], { simp at hy₁, rcases hf hy₁ with ⟨k, hk⟩, exact ⟨_, nat.le_of_lt_succ $ evaln_bound hk, _, hk, by simp; refl⟩ }, { rcases hy₂ (nat.succ_pos _) with ⟨a, ha, a0⟩, rcases hf ha with ⟨k₁, hk₁⟩, rcases IH m.succ (by simpa [nat.succ_eq_add_one, add_comm, add_left_comm] using hy₁) (λ i hi, by simpa [nat.succ_eq_add_one, add_comm, add_left_comm] using hy₂ (nat.succ_lt_succ hi)) with ⟨k₂, hk₂⟩, use (max k₁ k₂).succ, rw [zero_add] at hk₁, use (nat.le_succ_of_le $ le_max_of_le_left $ nat.le_of_lt_succ $ evaln_bound hk₁), use a, use evaln_mono (nat.succ_le_succ $ nat.le_succ_of_le $ le_max_left _ _) hk₁, simpa [nat.succ_eq_add_one, a0, -max_eq_left, -max_eq_right, add_comm, add_left_comm] using evaln_mono (nat.succ_le_succ $ le_max_right _ _) hk₂ } } end, λ ⟨k, h⟩, evaln_sound h⟩ section open primrec private def lup (L : list (list (option ℕ))) (p : ℕ × code) (n : ℕ) := do l ← L.nth (encode p), o ← l.nth n, o private lemma hlup : primrec (λ p:_×(_×_)×_, lup p.1 p.2.1 p.2.2) := option_bind (list_nth.comp fst (primrec.encode.comp $ fst.comp snd)) (option_bind (list_nth.comp snd $ snd.comp $ snd.comp fst) snd) private def G (L : list (list (option ℕ))) : option (list (option ℕ)) := option.some $ let a := of_nat (ℕ × code) L.length, k := a.1, c := a.2 in (list.range k).map (λ n, k.cases none $ λ k', nat.partrec.code.rec_on c (some 0) -- zero (some (nat.succ n)) (some n.unpair.1) (some n.unpair.2) (λ cf cg _ _, do x ← lup L (k, cf) n, y ← lup L (k, cg) n, some (mkpair x y)) (λ cf cg _ _, do x ← lup L (k, cg) n, lup L (k, cf) x) (λ cf cg _ _, let z := n.unpair.1 in n.unpair.2.cases (lup L (k, cf) z) (λ y, do i ← lup L (k', c) (mkpair z y), lup L (k, cg) (mkpair z (mkpair y i)))) (λ cf _, let z := n.unpair.1, m := n.unpair.2 in do x ← lup L (k, cf) (mkpair z m), x.cases (some m) (λ _, lup L (k', c) (mkpair z (m+1))))) private lemma hG : primrec G := begin have a := (primrec.of_nat (ℕ × code)).comp list_length, have k := fst.comp a, refine option_some.comp (list_map (list_range.comp k) (_ : primrec _)), replace k := k.comp fst, have n := snd, refine nat_cases k (const none) (_ : primrec _), have k := k.comp fst, have n := n.comp fst, have k' := snd, have c := snd.comp (a.comp $ fst.comp fst), apply rec_prim c (const (some 0)) (option_some.comp (primrec.succ.comp n)) (option_some.comp (fst.comp $ primrec.unpair.comp n)) (option_some.comp (snd.comp $ primrec.unpair.comp n)), { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have cg := (fst.comp snd).comp snd, exact option_bind (hlup.comp $ L.pair $ (k.pair cf).pair n) (option_map ((hlup.comp $ L.pair $ (k.pair cg).pair n).comp fst) (primrec₂.mkpair.comp (snd.comp fst) snd)) }, { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have cg := (fst.comp snd).comp snd, exact option_bind (hlup.comp $ L.pair $ (k.pair cg).pair n) (hlup.comp ((L.comp fst).pair $ ((k.pair cf).comp fst).pair snd)) }, { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have cg := (fst.comp snd).comp snd, have z := fst.comp (primrec.unpair.comp n), refine nat_cases (snd.comp (primrec.unpair.comp n)) (hlup.comp $ L.pair $ (k.pair cf).pair z) (_ : primrec _), have L := L.comp fst, have z := z.comp fst, have y := snd, refine option_bind (hlup.comp $ L.pair $ (((k'.pair c).comp fst).comp fst).pair (primrec₂.mkpair.comp z y)) (_ : primrec _), have z := z.comp fst, have y := y.comp fst, have i := snd, exact hlup.comp ((L.comp fst).pair $ ((k.pair cg).comp $ fst.comp fst).pair $ primrec₂.mkpair.comp z $ primrec₂.mkpair.comp y i) }, { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have z := fst.comp (primrec.unpair.comp n), have m := snd.comp (primrec.unpair.comp n), refine option_bind (hlup.comp $ L.pair $ (k.pair cf).pair (primrec₂.mkpair.comp z m)) (_ : primrec _), have m := m.comp fst, exact nat_cases snd (option_some.comp m) ((hlup.comp ((L.comp fst).pair $ ((k'.pair c).comp $ fst.comp fst).pair (primrec₂.mkpair.comp (z.comp fst) (primrec.succ.comp m)))).comp fst) } end private lemma evaln_map (k c n) : (((list.range k).nth n).map (evaln k c)).bind (λ b, b) = evaln k c n := begin by_cases kn : n < k, { simp [list.nth_range kn] }, { rw list.nth_len_le, { cases e : evaln k c n, {refl}, exact kn.elim (evaln_bound e) }, simpa using kn } end /-- The `nat.partrec.code.evaln` function is primitive recursive. -/ theorem evaln_prim : primrec (λ (a : (ℕ × code) × ℕ), evaln a.1.1 a.1.2 a.2) := have primrec₂ (λ (_:unit) (n : ℕ), let a := of_nat (ℕ × code) n in (list.range a.1).map (evaln a.1 a.2)), from primrec.nat_strong_rec _ (hG.comp snd).to₂ $ λ _ p, begin simp [G], rw (_ : (of_nat (ℕ × code) _).snd = of_nat code p.unpair.2), swap, {simp}, apply list.map_congr (λ n, _), rw (by simp : list.range p = list.range (mkpair p.unpair.1 (encode (of_nat code p.unpair.2)))), generalize : p.unpair.1 = k, generalize : of_nat code p.unpair.2 = c, intro nk, cases k with k', {simp [evaln]}, let k := k'+1, change k'.succ with k, simp [nat.lt_succ_iff] at nk, have hg : ∀ {k' c' n}, mkpair k' (encode c') < mkpair k (encode c) → lup ((list.range (mkpair k (encode c))).map (λ n, (list.range n.unpair.1).map (evaln n.unpair.1 (of_nat code n.unpair.2)))) (k', c') n = evaln k' c' n, { intros k₁ c₁ n₁ hl, simp [lup, list.nth_range hl, evaln_map, (>>=)] }, cases c with cf cg cf cg cf cg cf; simp [evaln, nk, (>>), (>>=), (<$>), (<*>), pure], { cases encode_lt_pair cf cg with lf lg, rw [hg (nat.mkpair_lt_mkpair_right _ lf), hg (nat.mkpair_lt_mkpair_right _ lg)], cases evaln k cf n, {refl}, cases evaln k cg n; refl }, { cases encode_lt_comp cf cg with lf lg, rw hg (nat.mkpair_lt_mkpair_right _ lg), cases evaln k cg n, {refl}, simp [hg (nat.mkpair_lt_mkpair_right _ lf)] }, { cases encode_lt_prec cf cg with lf lg, rw hg (nat.mkpair_lt_mkpair_right _ lf), cases n.unpair.2, {refl}, simp, rw hg (nat.mkpair_lt_mkpair_left _ k'.lt_succ_self), cases evaln k' _ _, {refl}, simp [hg (nat.mkpair_lt_mkpair_right _ lg)] }, { have lf := encode_lt_rfind' cf, rw hg (nat.mkpair_lt_mkpair_right _ lf), cases evaln k cf n with x, {refl}, simp, cases x; simp [nat.succ_ne_zero], rw hg (nat.mkpair_lt_mkpair_left _ k'.lt_succ_self) } end, (option_bind (list_nth.comp (this.comp (const ()) (encode_iff.2 fst)) snd) snd.to₂).of_eq $ λ ⟨⟨k, c⟩, n⟩, by simp [evaln_map] end section open partrec computable theorem eval_eq_rfind_opt (c n) : eval c n = nat.rfind_opt (λ k, evaln k c n) := part.ext $ λ x, begin refine evaln_complete.trans (nat.rfind_opt_mono _).symm, intros a m n hl, apply evaln_mono hl, end theorem eval_part : partrec₂ eval := (rfind_opt (evaln_prim.to_comp.comp ((snd.pair (fst.comp fst)).pair (snd.comp fst))).to₂).of_eq $ λ a, by simp [eval_eq_rfind_opt] /-- Roger's fixed-point theorem: Any total, computable `f` has a fixed point: That is, under the interpretation given by `nat.partrec.code.eval`, there is a code `c` such that `c` and `f c` have the same evaluation. -/ theorem fixed_point {f : code → code} (hf : computable f) : ∃ c : code, eval (f c) = eval c := let g (x y : ℕ) : part ℕ := eval (of_nat code x) x >>= λ b, eval (of_nat code b) y in have partrec₂ g := (eval_part.comp ((computable.of_nat _).comp fst) fst).bind (eval_part.comp ((computable.of_nat _).comp snd) (snd.comp fst)).to₂, let ⟨cg, eg⟩ := exists_code.1 this in have eg' : ∀ a n, eval cg (mkpair a n) = part.map encode (g a n) := by simp [eg], let F (x : ℕ) : code := f (curry cg x) in have computable F := hf.comp (curry_prim.comp (primrec.const cg) primrec.id).to_comp, let ⟨cF, eF⟩ := exists_code.1 this in have eF' : eval cF (encode cF) = part.some (encode (F (encode cF))), by simp [eF], ⟨curry cg (encode cF), funext (λ n, show eval (f (curry cg (encode cF))) n = eval (curry cg (encode cF)) n, by simp [eg', eF', part.map_id', g])⟩ theorem fixed_point₂ {f : code → ℕ →. ℕ} (hf : partrec₂ f) : ∃ c : code, eval c = f c := let ⟨cf, ef⟩ := exists_code.1 hf in (fixed_point (curry_prim.comp (primrec.const cf) primrec.encode).to_comp).imp $ λ c e, funext $ λ n, by simp [e.symm, ef, part.map_id'] end end nat.partrec.code
c2a5871b57fb111b1320da7084218eb2324fe7af
2a44f685380c1a89f9e3b6e5e37ec65d74ec5010
/src/uniq/default.lean
81577fcf8e914e0bf46306a7e25c9a8dd5fdbfcd
[ "Apache-2.0" ]
permissive
fgdorais/uniq
0a4c50ae1df37687f38d65b9cd462b3bdf83dbff
87072ea6292436500370ebfc4bd140b1dae704fd
refs/heads/master
1,584,872,936,588
1,530,977,726,000
1,530,977,726,000
139,905,607
1
0
null
null
null
null
UTF-8
Lean
false
false
46
lean
import .uniq import .inverse import .bijection
463ae91d23819cfc56b0535cd5584e9c47e40945
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/group_theory/perm/sign.lean
e469926511817ebcd8b2bc020b55caf9f51ed914
[ "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
32,983
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 data.fintype universes u v open equiv function fintype finset variables {α : Type u} {β : Type v} namespace equiv.perm def subtype_perm (f : perm α) {p : α → Prop} (h : ∀ x, p x ↔ p (f x)) : perm {x // p x} := ⟨λ x, ⟨f x, (h _).1 x.2⟩, λ x, ⟨f⁻¹ x, (h (f⁻¹ x)).2 $ by simpa using x.2⟩, λ _, by simp, λ _, by simp⟩ @[simp] lemma subtype_perm_one (p : α → Prop) (h : ∀ x, p x ↔ p ((1 : perm α) x)) : @subtype_perm α 1 p h = 1 := equiv.ext _ _ $ λ ⟨_, _⟩, rfl def of_subtype {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) : perm α := ⟨λ x, if h : p x then f ⟨x, h⟩ else x, λ x, if h : p x then f⁻¹ ⟨x, h⟩ else x, λ x, have h : ∀ h : p x, p (f ⟨x, h⟩), from λ h, (f ⟨x, h⟩).2, by simp; split_ifs at *; simp * at *, λ x, have h : ∀ h : p x, p (f⁻¹ ⟨x, h⟩), from λ h, (f⁻¹ ⟨x, h⟩).2, by simp; split_ifs at *; simp * at *⟩ instance of_subtype.is_group_hom {p : α → Prop} [decidable_pred p] : is_group_hom (@of_subtype α p _) := { map_mul := λ f g, equiv.ext _ _ $ λ x, begin rw [of_subtype, of_subtype, of_subtype], by_cases h : p x, { have h₁ : p (f (g ⟨x, h⟩)), from (f (g ⟨x, h⟩)).2, have h₂ : p (g ⟨x, h⟩), from (g ⟨x, h⟩).2, simp [h, h₁, h₂] }, { simp [h] } end } @[simp] lemma of_subtype_one (p : α → Prop) [decidable_pred p] : @of_subtype α p _ 1 = 1 := is_group_hom.map_one of_subtype lemma eq_inv_iff_eq {f : perm α} {x y : α} : x = f⁻¹ y ↔ f x = y := by conv {to_lhs, rw [← injective.eq_iff f.injective, apply_inv_self]} lemma inv_eq_iff_eq {f : perm α} {x y : α} : f⁻¹ x = y ↔ x = f y := by rw [eq_comm, eq_inv_iff_eq, eq_comm] def disjoint (f g : perm α) := ∀ x, f x = x ∨ g x = x @[symm] lemma disjoint.symm {f g : perm α} : disjoint f g → disjoint g f := by simp [disjoint, or.comm] lemma disjoint_comm {f g : perm α} : disjoint f g ↔ disjoint g f := ⟨disjoint.symm, disjoint.symm⟩ lemma disjoint_mul_comm {f g : perm α} (h : disjoint f g) : f * g = g * f := equiv.ext _ _ $ λ x, (h x).elim (λ hf, (h (g x)).elim (λ hg, by simp [mul_apply, hf, hg]) (λ hg, by simp [mul_apply, hf, g.injective hg])) (λ hg, (h (f x)).elim (λ hf, by simp [mul_apply, f.injective hf, hg]) (λ hf, by simp [mul_apply, hf, hg])) @[simp] lemma disjoint_one_left (f : perm α) : disjoint 1 f := λ _, or.inl rfl @[simp] lemma disjoint_one_right (f : perm α) : disjoint f 1 := λ _, or.inr rfl lemma disjoint_mul_left {f g h : perm α} (H1 : disjoint f h) (H2 : disjoint g h) : disjoint (f * g) h := λ x, by cases H1 x; cases H2 x; simp * lemma disjoint_mul_right {f g h : perm α} (H1 : disjoint f g) (H2 : disjoint f h) : disjoint f (g * h) := by rw disjoint_comm; exact disjoint_mul_left H1.symm H2.symm lemma disjoint_prod_right {f : perm α} (l : list (perm α)) (h : ∀ g ∈ l, disjoint f g) : disjoint f l.prod := begin induction l with g l ih, { exact disjoint_one_right _ }, { rw list.prod_cons; exact disjoint_mul_right (h _ (list.mem_cons_self _ _)) (ih (λ g hg, h g (list.mem_cons_of_mem _ hg))) } end lemma disjoint_prod_perm {l₁ l₂ : list (perm α)} (hl : l₁.pairwise disjoint) (hp : l₁ ~ l₂) : l₁.prod = l₂.prod := begin induction hp, { refl }, { rw [list.prod_cons, list.prod_cons, hp_ih (list.pairwise_cons.1 hl).2] }, { simp [list.prod_cons, disjoint_mul_comm, (mul_assoc _ _ _).symm, *, list.pairwise_cons] at * }, { rw [hp_ih_a hl, hp_ih_a_1 ((list.perm_pairwise (λ x y (h : disjoint x y), disjoint.symm h) hp_a).1 hl)] } end lemma of_subtype_subtype_perm {f : perm α} {p : α → Prop} [decidable_pred p] (h₁ : ∀ x, p x ↔ p (f x)) (h₂ : ∀ x, f x ≠ x → p x) : of_subtype (subtype_perm f h₁) = f := equiv.ext _ _ $ λ x, begin rw [of_subtype, subtype_perm], by_cases hx : p x, { simp [hx] }, { haveI := classical.prop_decidable, simp [hx, not_not.1 (mt (h₂ x) hx)] } end lemma of_subtype_apply_of_not_mem {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) {x : α} (hx : ¬ p x) : of_subtype f x = x := dif_neg hx lemma mem_iff_of_subtype_apply_mem {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) (x : α) : p x ↔ p ((of_subtype f : α → α) x) := if h : p x then by dsimp [of_subtype]; simpa [h] using (f ⟨x, h⟩).2 else by simp [h, of_subtype_apply_of_not_mem f h] @[simp] lemma subtype_perm_of_subtype {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) : subtype_perm (of_subtype f) (mem_iff_of_subtype_apply_mem f) = f := equiv.ext _ _ $ λ ⟨x, hx⟩, by dsimp [subtype_perm, of_subtype]; simp [show p x, from hx] lemma pow_apply_eq_self_of_apply_eq_self {f : perm α} {x : α} (hfx : f x = x) : ∀ n : ℕ, (f ^ n) x = x | 0 := rfl | (n+1) := by rw [pow_succ', mul_apply, hfx, pow_apply_eq_self_of_apply_eq_self] lemma gpow_apply_eq_self_of_apply_eq_self {f : perm α} {x : α} (hfx : f x = x) : ∀ n : ℤ, (f ^ n) x = x | (n : ℕ) := pow_apply_eq_self_of_apply_eq_self hfx n | -[1+ n] := by rw [gpow_neg_succ, inv_eq_iff_eq, pow_apply_eq_self_of_apply_eq_self hfx] lemma pow_apply_eq_of_apply_apply_eq_self {f : perm α} {x : α} (hffx : f (f x) = x) : ∀ n : ℕ, (f ^ n) x = x ∨ (f ^ n) x = f x | 0 := or.inl rfl | (n+1) := (pow_apply_eq_of_apply_apply_eq_self n).elim (λ h, or.inr (by rw [pow_succ, mul_apply, h])) (λ h, or.inl (by rw [pow_succ, mul_apply, h, hffx])) lemma gpow_apply_eq_of_apply_apply_eq_self {f : perm α} {x : α} (hffx : f (f x) = x) : ∀ i : ℤ, (f ^ i) x = x ∨ (f ^ i) x = f x | (n : ℕ) := pow_apply_eq_of_apply_apply_eq_self hffx n | -[1+ n] := by rw [gpow_neg_succ, inv_eq_iff_eq, ← injective.eq_iff f.injective, ← mul_apply, ← pow_succ, eq_comm, inv_eq_iff_eq, ← mul_apply, ← pow_succ', @eq_comm _ x, or.comm]; exact pow_apply_eq_of_apply_apply_eq_self hffx _ variable [decidable_eq α] def support [fintype α] (f : perm α) := univ.filter (λ x, f x ≠ x) @[simp] lemma mem_support [fintype α] {f : perm α} {x : α} : x ∈ f.support ↔ f x ≠ x := by simp [support] def is_swap (f : perm α) := ∃ x y, x ≠ y ∧ f = swap x y lemma swap_mul_eq_mul_swap (f : perm α) (x y : α) : swap x y * f = f * swap (f⁻¹ x) (f⁻¹ y) := equiv.ext _ _ $ λ z, begin simp [mul_apply, swap_apply_def], split_ifs; simp [*, eq_inv_iff_eq] at * <|> cc end lemma mul_swap_eq_swap_mul (f : perm α) (x y : α) : f * swap x y = swap (f x) (f y) * f := by rw [swap_mul_eq_mul_swap, inv_apply_self, inv_apply_self] @[simp] lemma swap_mul_self (i j : α) : equiv.swap i j * equiv.swap i j = 1 := equiv.swap_swap i j @[simp] lemma swap_swap_apply (i j k : α) : equiv.swap i j (equiv.swap i j k) = k := equiv.swap_core_swap_core k i j lemma is_swap_of_subtype {p : α → Prop} [decidable_pred p] {f : perm (subtype p)} (h : is_swap f) : is_swap (of_subtype f) := let ⟨⟨x, hx⟩, ⟨y, hy⟩, hxy⟩ := h in ⟨x, y, by simp at hxy; tauto, equiv.ext _ _ $ λ z, begin rw [hxy.2, of_subtype], simp [swap_apply_def], split_ifs; cc <|> simp * at * end⟩ lemma ne_and_ne_of_swap_mul_apply_ne_self {f : perm α} {x y : α} (hy : (swap x (f x) * f) y ≠ y) : f y ≠ y ∧ y ≠ x := begin simp only [swap_apply_def, mul_apply, injective.eq_iff f.injective] at *, by_cases h : f y = x, { split; intro; simp * at * }, { split_ifs at hy; cc } end lemma support_swap_mul_eq [fintype α] {f : perm α} {x : α} (hffx : f (f x) ≠ x) : (swap x (f x) * f).support = f.support.erase x := have hfx : f x ≠ x, from λ hfx, by simpa [hfx] using hffx, finset.ext.2 $ λ y, ⟨λ hy, have hy' : (swap x (f x) * f) y ≠ y, from mem_support.1 hy, mem_erase.2 ⟨λ hyx, by simp [hyx, mul_apply, *] at *, mem_support.2 $ λ hfy, by simp only [mul_apply, swap_apply_def, hfy] at hy'; split_ifs at hy'; simp * at *⟩, λ hy, by simp only [mem_erase, mem_support, swap_apply_def, mul_apply] at *; intro; split_ifs at *; simp * at *⟩ lemma card_support_swap_mul [fintype α] {f : perm α} {x : α} (hx : f x ≠ x) : (swap x (f x) * f).support.card < f.support.card := finset.card_lt_card ⟨λ z hz, mem_support.2 (ne_and_ne_of_swap_mul_apply_ne_self (mem_support.1 hz)).1, λ h, absurd (h (mem_support.2 hx)) (mt mem_support.1 (by simp))⟩ def swap_factors_aux : Π (l : list α) (f : perm α), (∀ {x}, f x ≠ x → x ∈ l) → {l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} | [] := λ f h, ⟨[], equiv.ext _ _ $ λ x, by rw [list.prod_nil]; exact eq.symm (not_not.1 (mt h (list.not_mem_nil _))), by simp⟩ | (x :: l) := λ f h, if hfx : x = f x then swap_factors_aux l f (λ y hy, list.mem_of_ne_of_mem (λ h : y = x, by simpa [h, hfx.symm] using hy) (h hy)) else let m := swap_factors_aux l (swap x (f x) * f) (λ y hy, have f y ≠ y ∧ y ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hy, list.mem_of_ne_of_mem this.2 (h this.1)) in ⟨swap x (f x) :: m.1, by rw [list.prod_cons, m.2.1, ← mul_assoc, mul_def (swap x (f x)), swap_swap, ← one_def, one_mul], λ g hg, ((list.mem_cons_iff _ _ _).1 hg).elim (λ h, ⟨x, f x, hfx, h⟩) (m.2.2 _)⟩ /-- `swap_factors` represents a permutation as a product of a list of transpositions. The representation is non unique and depends on the linear order structure. For types without linear order `trunc_swap_factors` can be used -/ def swap_factors [fintype α] [decidable_linear_order α] (f : perm α) : {l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} := swap_factors_aux ((@univ α _).sort (≤)) f (λ _ _, (mem_sort _).2 (mem_univ _)) def trunc_swap_factors [fintype α] (f : perm α) : trunc {l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} := quotient.rec_on_subsingleton (@univ α _).1 (λ l h, trunc.mk (swap_factors_aux l f h)) (show ∀ x, f x ≠ x → x ∈ (@univ α _).1, from λ _ _, mem_univ _) @[elab_as_eliminator] lemma swap_induction_on [fintype α] {P : perm α → Prop} (f : perm α) : P 1 → (∀ f x y, x ≠ y → P f → P (swap x y * f)) → P f := begin cases trunc.out (trunc_swap_factors f) with l hl, induction l with g l ih generalizing f, { simp [hl.1.symm] {contextual := tt} }, { assume h1 hmul_swap, rcases hl.2 g (by simp) with ⟨x, y, hxy⟩, rw [← hl.1, list.prod_cons, hxy.2], exact hmul_swap _ _ _ hxy.1 (ih _ ⟨rfl, λ v hv, hl.2 _ (list.mem_cons_of_mem _ hv)⟩ h1 hmul_swap) } end lemma swap_mul_swap_mul_swap {x y z : α} (hwz: x ≠ y) (hxz : x ≠ z) : swap y z * swap x y * swap y z = swap z x := equiv.ext _ _ $ λ n, by simp only [swap_apply_def, mul_apply]; split_ifs; cc lemma is_conj_swap {w x y z : α} (hwx : w ≠ x) (hyz : y ≠ z) : is_conj (swap w x) (swap y z) := have h : ∀ {y z : α}, y ≠ z → w ≠ z → (swap w y * swap x z) * swap w x * (swap w y * swap x z)⁻¹ = swap y z := λ y z hyz hwz, by rw [mul_inv_rev, swap_inv, swap_inv, mul_assoc (swap w y), mul_assoc (swap w y), ← mul_assoc _ (swap x z), swap_mul_swap_mul_swap hwx hwz, ← mul_assoc, swap_mul_swap_mul_swap hwz.symm hyz.symm], if hwz : w = z then have hwy : w ≠ y, by cc, ⟨swap w z * swap x y, by rw [swap_comm y z, h hyz.symm hwy]⟩ else ⟨swap w y * swap x z, h hyz hwz⟩ /-- set of all pairs (⟨a, b⟩ : Σ a : fin n, fin n) such that b < a -/ def fin_pairs_lt (n : ℕ) : finset (Σ a : fin n, fin n) := (univ : finset (fin n)).sigma (λ a, (range a.1).attach_fin (λ m hm, lt_trans (mem_range.1 hm) a.2)) lemma mem_fin_pairs_lt {n : ℕ} {a : Σ a : fin n, fin n} : a ∈ fin_pairs_lt n ↔ a.2 < a.1 := by simp [fin_pairs_lt, fin.lt_def] def sign_aux {n : ℕ} (a : perm (fin n)) : units ℤ := (fin_pairs_lt n).prod (λ x, if a x.1 ≤ a x.2 then -1 else 1) @[simp] lemma sign_aux_one (n : ℕ) : sign_aux (1 : perm (fin n)) = 1 := begin unfold sign_aux, conv { to_rhs, rw ← @finset.prod_const_one _ (units ℤ) (fin_pairs_lt n) }, exact finset.prod_congr rfl (λ a ha, if_neg (not_le_of_gt (mem_fin_pairs_lt.1 ha))) end def sign_bij_aux {n : ℕ} (f : perm (fin n)) (a : Σ a : fin n, fin n) : Σ a : fin n, fin n := if hxa : f a.2 < f a.1 then ⟨f a.1, f a.2⟩ else ⟨f a.2, f a.1⟩ lemma sign_bij_aux_inj {n : ℕ} {f : perm (fin n)} : ∀ a b : Σ a : fin n, fin n, a ∈ fin_pairs_lt n → b ∈ fin_pairs_lt n → sign_bij_aux f a = sign_bij_aux f b → a = b := λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h, begin unfold sign_bij_aux at h, rw mem_fin_pairs_lt at *, have : ¬b₁ < b₂ := not_lt_of_ge (le_of_lt hb), split_ifs at h; simp [*, injective.eq_iff f.injective, sigma.mk.inj_eq] at * end lemma sign_bij_aux_surj {n : ℕ} {f : perm (fin n)} : ∀ a ∈ fin_pairs_lt n, ∃ b ∈ fin_pairs_lt n, a = sign_bij_aux f b := λ ⟨a₁, a₂⟩ ha, if hxa : f⁻¹ a₂ < f⁻¹ a₁ then ⟨⟨f⁻¹ a₁, f⁻¹ a₂⟩, mem_fin_pairs_lt.2 hxa, by dsimp [sign_bij_aux]; rw [apply_inv_self, apply_inv_self, dif_pos (mem_fin_pairs_lt.1 ha)]⟩ else ⟨⟨f⁻¹ a₂, f⁻¹ a₁⟩, mem_fin_pairs_lt.2 $ lt_of_le_of_ne (le_of_not_gt hxa) $ λ h, by simpa [mem_fin_pairs_lt, (f⁻¹).injective h, lt_irrefl] using ha, by dsimp [sign_bij_aux]; rw [apply_inv_self, apply_inv_self, dif_neg (not_lt_of_ge (le_of_lt (mem_fin_pairs_lt.1 ha)))]⟩ lemma sign_bij_aux_mem {n : ℕ} {f : perm (fin n)}: ∀ a : Σ a : fin n, fin n, a ∈ fin_pairs_lt n → sign_bij_aux f a ∈ fin_pairs_lt n := λ ⟨a₁, a₂⟩ ha, begin unfold sign_bij_aux, split_ifs with h, { exact mem_fin_pairs_lt.2 h }, { exact mem_fin_pairs_lt.2 (lt_of_le_of_ne (le_of_not_gt h) (λ h, ne_of_lt (mem_fin_pairs_lt.1 ha) (f.injective h.symm))) } end @[simp] lemma sign_aux_inv {n : ℕ} (f : perm (fin n)) : sign_aux f⁻¹ = sign_aux f := prod_bij (λ a ha, sign_bij_aux f⁻¹ a) sign_bij_aux_mem (λ ⟨a, b⟩ hab, if h : f⁻¹ b < f⁻¹ a then by rw [sign_bij_aux, dif_pos h, if_neg (not_le_of_gt h), apply_inv_self, apply_inv_self, if_neg (not_le_of_gt $ mem_fin_pairs_lt.1 hab)] else by rw [sign_bij_aux, if_pos (le_of_not_gt h), dif_neg h, apply_inv_self, apply_inv_self, if_pos (le_of_lt $ mem_fin_pairs_lt.1 hab)]) sign_bij_aux_inj sign_bij_aux_surj lemma sign_aux_mul {n : ℕ} (f g : perm (fin n)) : sign_aux (f * g) = sign_aux f * sign_aux g := begin rw ← sign_aux_inv g, unfold sign_aux, rw ← prod_mul_distrib, refine prod_bij (λ a ha, sign_bij_aux g a) sign_bij_aux_mem _ sign_bij_aux_inj sign_bij_aux_surj, rintros ⟨a, b⟩ hab, rw [sign_bij_aux, mul_apply, mul_apply], rw mem_fin_pairs_lt at hab, by_cases h : g b < g a, { rw dif_pos h, simp [not_le_of_gt hab]; congr }, { rw [dif_neg h, inv_apply_self, inv_apply_self, if_pos (le_of_lt hab)], by_cases h₁ : f (g b) ≤ f (g a), { have : f (g b) ≠ f (g a), { rw [ne.def, injective.eq_iff f.injective, injective.eq_iff g.injective]; exact ne_of_lt hab }, rw [if_pos h₁, if_neg (not_le_of_gt (lt_of_le_of_ne h₁ this))], refl }, { rw [if_neg h₁, if_pos (le_of_lt (lt_of_not_ge h₁))], refl } } end instance sign_aux.is_group_hom {n : ℕ} : is_group_hom (@sign_aux n) := { map_mul := sign_aux_mul } private lemma sign_aux_swap_zero_one {n : ℕ} (hn : 2 ≤ n) : sign_aux (swap (⟨0, lt_of_lt_of_le dec_trivial hn⟩ : fin n) ⟨1, lt_of_lt_of_le dec_trivial hn⟩) = -1 := let zero : fin n := ⟨0, lt_of_lt_of_le dec_trivial hn⟩ in let one : fin n := ⟨1, lt_of_lt_of_le dec_trivial hn⟩ in have hzo : zero < one := dec_trivial, show _ = (finset.singleton (⟨one, zero⟩ : Σ a : fin n, fin n)).prod (λ x : Σ a : fin n, fin n, if (equiv.swap zero one) x.1 ≤ swap zero one x.2 then (-1 : units ℤ) else 1), begin refine eq.symm (prod_subset (λ ⟨x₁, x₂⟩, by simp [mem_fin_pairs_lt, hzo] {contextual := tt}) (λ a ha₁ ha₂, _)), rcases a with ⟨⟨a₁, ha₁⟩, ⟨a₂, ha₂⟩⟩, replace ha₁ : a₂ < a₁ := mem_fin_pairs_lt.1 ha₁, simp only [swap_apply_def], have : ¬ 1 ≤ a₂ → a₂ = 0, from λ h, nat.le_zero_iff.1 (nat.le_of_lt_succ (lt_of_not_ge h)), have : a₁ ≤ 1 → a₁ = 0 ∨ a₁ = 1, from nat.cases_on a₁ (λ _, or.inl rfl) (λ a₁, nat.cases_on a₁ (λ _, or.inr rfl) (λ _ h, absurd h dec_trivial)), split_ifs; simp [*, lt_irrefl, -not_lt, not_le.symm, -not_le, le_refl, fin.lt_def, fin.le_def, nat.zero_le, zero, one, iff.intro fin.veq_of_eq fin.eq_of_veq, nat.le_zero_iff] at *, end lemma sign_aux_swap : ∀ {n : ℕ} {x y : fin n} (hxy : x ≠ y), sign_aux (swap x y) = -1 | 0 := dec_trivial | 1 := dec_trivial | (n+2) := λ x y hxy, have h2n : 2 ≤ n + 2 := dec_trivial, by rw [← is_conj_iff_eq, ← sign_aux_swap_zero_one h2n]; exact is_group_hom.is_conj _ (is_conj_swap hxy dec_trivial) def sign_aux2 : list α → perm α → units ℤ | [] f := 1 | (x::l) f := if x = f x then sign_aux2 l f else -sign_aux2 l (swap x (f x) * f) lemma sign_aux_eq_sign_aux2 {n : ℕ} : ∀ (l : list α) (f : perm α) (e : α ≃ fin n) (h : ∀ x, f x ≠ x → x ∈ l), sign_aux ((e.symm.trans f).trans e) = sign_aux2 l f | [] f e h := have f = 1, from equiv.ext _ _ $ λ y, not_not.1 (mt (h y) (list.not_mem_nil _)), by rw [this, one_def, equiv.trans_refl, equiv.symm_trans, ← one_def, sign_aux_one, sign_aux2] | (x::l) f e h := begin rw sign_aux2, by_cases hfx : x = f x, { rw if_pos hfx, exact sign_aux_eq_sign_aux2 l f _ (λ y (hy : f y ≠ y), list.mem_of_ne_of_mem (λ h : y = x, by simpa [h, hfx.symm] using hy) (h y hy) ) }, { have hy : ∀ y : α, (swap x (f x) * f) y ≠ y → y ∈ l, from λ y hy, have f y ≠ y ∧ y ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hy, list.mem_of_ne_of_mem this.2 (h _ this.1), have : (e.symm.trans (swap x (f x) * f)).trans e = (swap (e x) (e (f x))) * (e.symm.trans f).trans e, from equiv.ext _ _ (λ z, by rw ← equiv.symm_trans_swap_trans; simp [mul_def]), have hefx : e x ≠ e (f x), from mt (injective.eq_iff e.injective).1 hfx, rw [if_neg hfx, ← sign_aux_eq_sign_aux2 _ _ e hy, this, sign_aux_mul, sign_aux_swap hefx], simp } end def sign_aux3 [fintype α] (f : perm α) {s : multiset α} : (∀ x, x ∈ s) → units ℤ := quotient.hrec_on s (λ l h, sign_aux2 l f) (trunc.induction_on (equiv_fin α) (λ e l₁ l₂ h, function.hfunext (show (∀ x, x ∈ l₁) = ∀ x, x ∈ l₂, by simp [list.mem_of_perm h]) (λ h₁ h₂ _, by rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, h₁ _), ← sign_aux_eq_sign_aux2 _ _ e (λ _ _, h₂ _)]))) lemma sign_aux3_mul_and_swap [fintype α] (f g : perm α) (s : multiset α) (hs : ∀ x, x ∈ s) : sign_aux3 (f * g) hs = sign_aux3 f hs * sign_aux3 g hs ∧ ∀ x y, x ≠ y → sign_aux3 (swap x y) hs = -1 := let ⟨l, hl⟩ := quotient.exists_rep s in let ⟨e, _⟩ := trunc.exists_rep (equiv_fin α) in begin clear _let_match _let_match, subst hl, show sign_aux2 l (f * g) = sign_aux2 l f * sign_aux2 l g ∧ ∀ x y, x ≠ y → sign_aux2 l (swap x y) = -1, have hfg : (e.symm.trans (f * g)).trans e = (e.symm.trans f).trans e * (e.symm.trans g).trans e, from equiv.ext _ _ (λ h, by simp [mul_apply]), split, { rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), ← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), ← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), hfg, sign_aux_mul] }, { assume x y hxy, have hexy : e x ≠ e y, from mt (injective.eq_iff e.injective).1 hxy, rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), equiv.symm_trans_swap_trans, sign_aux_swap hexy] } end /-- `sign` of a permutation returns the signature or parity of a permutation, `1` for even permutations, `-1` for odd permutations. It is the unique surjective group homomorphism from `perm α` to the group with two elements.-/ def sign [fintype α] (f : perm α) := sign_aux3 f mem_univ instance sign.is_group_hom [fintype α] : is_group_hom (@sign α _ _) := { map_mul := λ f g, (sign_aux3_mul_and_swap f g _ mem_univ).1 } section sign variable [fintype α] @[simp] lemma sign_mul (f g : perm α) : sign (f * g) = sign f * sign g := is_mul_hom.map_mul sign _ _ @[simp] lemma sign_one : (sign (1 : perm α)) = 1 := is_group_hom.map_one sign @[simp] lemma sign_refl : sign (equiv.refl α) = 1 := is_group_hom.map_one sign @[simp] lemma sign_inv (f : perm α) : sign f⁻¹ = sign f := by rw [is_group_hom.map_inv sign, int.units_inv_eq_self]; apply_instance lemma sign_swap {x y : α} (h : x ≠ y) : sign (swap x y) = -1 := (sign_aux3_mul_and_swap 1 1 _ mem_univ).2 x y h @[simp] lemma sign_swap' {x y : α} : (swap x y).sign = if x = y then 1 else -1 := if H : x = y then by simp [H, swap_self] else by simp [sign_swap H, H] lemma sign_eq_of_is_swap {f : perm α} (h : is_swap f) : sign f = -1 := let ⟨x, y, hxy⟩ := h in hxy.2.symm ▸ sign_swap hxy.1 lemma sign_aux3_symm_trans_trans [decidable_eq β] [fintype β] (f : perm α) (e : α ≃ β) {s : multiset α} {t : multiset β} (hs : ∀ x, x ∈ s) (ht : ∀ x, x ∈ t) : sign_aux3 ((e.symm.trans f).trans e) ht = sign_aux3 f hs := quotient.induction_on₂ t s (λ l₁ l₂ h₁ h₂, show sign_aux2 _ _ = sign_aux2 _ _, from let n := trunc.out (equiv_fin β) in by rw [← sign_aux_eq_sign_aux2 _ _ n (λ _ _, h₁ _), ← sign_aux_eq_sign_aux2 _ _ (e.trans n) (λ _ _, h₂ _)]; exact congr_arg sign_aux (equiv.ext _ _ (λ x, by simp))) ht hs lemma sign_symm_trans_trans [decidable_eq β] [fintype β] (f : perm α) (e : α ≃ β) : sign ((e.symm.trans f).trans e) = sign f := sign_aux3_symm_trans_trans f e mem_univ mem_univ lemma sign_prod_list_swap {l : list (perm α)} (hl : ∀ g ∈ l, is_swap g) : sign l.prod = -1 ^ l.length := have h₁ : l.map sign = list.repeat (-1) l.length := list.eq_repeat.2 ⟨by simp, λ u hu, let ⟨g, hg⟩ := list.mem_map.1 hu in hg.2 ▸ sign_eq_of_is_swap (hl _ hg.1)⟩, by rw [← list.prod_repeat, ← h₁, ← is_group_hom.map_prod (@sign α _ _)] lemma sign_surjective (hα : 1 < fintype.card α) : function.surjective (sign : perm α → units ℤ) := λ a, (int.units_eq_one_or a).elim (λ h, ⟨1, by simp [h]⟩) (λ h, let ⟨x⟩ := fintype.card_pos_iff.1 (lt_trans zero_lt_one hα) in let ⟨y, hxy⟩ := fintype.exists_ne_of_card_gt_one hα x in ⟨swap y x, by rw [sign_swap hxy, h]⟩ ) lemma eq_sign_of_surjective_hom {s : perm α → units ℤ} [is_group_hom s] (hs : surjective s) : s = sign := have ∀ {f}, is_swap f → s f = -1 := λ f ⟨x, y, hxy, hxy'⟩, hxy'.symm ▸ by_contradiction (λ h, have ∀ f, is_swap f → s f = 1 := λ f ⟨a, b, hab, hab'⟩, by rw [← is_conj_iff_eq, ← or.resolve_right (int.units_eq_one_or _) h, hab']; exact is_group_hom.is_conj _ (is_conj_swap hab hxy), let ⟨g, hg⟩ := hs (-1) in let ⟨l, hl⟩ := trunc.out (trunc_swap_factors g) in have ∀ a ∈ l.map s, a = (1 : units ℤ) := λ a ha, let ⟨g, hg⟩ := list.mem_map.1 ha in hg.2 ▸ this _ (hl.2 _ hg.1), have s l.prod = 1, by rw [is_group_hom.map_prod s, list.eq_repeat'.2 this, list.prod_repeat, one_pow], by rw [hl.1, hg] at this; exact absurd this dec_trivial), funext $ λ f, let ⟨l, hl₁, hl₂⟩ := trunc.out (trunc_swap_factors f) in have hsl : ∀ a ∈ l.map s, a = (-1 : units ℤ) := λ a ha, let ⟨g, hg⟩ := list.mem_map.1 ha in hg.2 ▸ this (hl₂ _ hg.1), by rw [← hl₁, is_group_hom.map_prod s, list.eq_repeat'.2 hsl, list.length_map, list.prod_repeat, sign_prod_list_swap hl₂] lemma sign_subtype_perm (f : perm α) {p : α → Prop} [decidable_pred p] (h₁ : ∀ x, p x ↔ p (f x)) (h₂ : ∀ x, f x ≠ x → p x) : sign (subtype_perm f h₁) = sign f := let l := trunc.out (trunc_swap_factors (subtype_perm f h₁)) in have hl' : ∀ g' ∈ l.1.map of_subtype, is_swap g' := λ g' hg', let ⟨g, hg⟩ := list.mem_map.1 hg' in hg.2 ▸ is_swap_of_subtype (l.2.2 _ hg.1), have hl'₂ : (l.1.map of_subtype).prod = f, by rw [← is_group_hom.map_prod of_subtype l.1, l.2.1, of_subtype_subtype_perm _ h₂], by conv {congr, rw ← l.2.1, skip, rw ← hl'₂}; rw [sign_prod_list_swap l.2.2, sign_prod_list_swap hl', list.length_map] @[simp] lemma sign_of_subtype {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) : sign (of_subtype f) = sign f := have ∀ x, of_subtype f x ≠ x → p x, from λ x, not_imp_comm.1 (of_subtype_apply_of_not_mem f), by conv {to_rhs, rw [← subtype_perm_of_subtype f, sign_subtype_perm _ _ this]} lemma sign_eq_sign_of_equiv [decidable_eq β] [fintype β] (f : perm α) (g : perm β) (e : α ≃ β) (h : ∀ x, e (f x) = g (e x)) : sign f = sign g := have hg : g = (e.symm.trans f).trans e, from equiv.ext _ _ $ by simp [h], by rw [hg, sign_symm_trans_trans] lemma sign_bij [decidable_eq β] [fintype β] {f : perm α} {g : perm β} (i : Π x : α, f x ≠ x → β) (h : ∀ x hx hx', i (f x) hx' = g (i x hx)) (hi : ∀ x₁ x₂ hx₁ hx₂, i x₁ hx₁ = i x₂ hx₂ → x₁ = x₂) (hg : ∀ y, g y ≠ y → ∃ x hx, i x hx = y) : sign f = sign g := calc sign f = sign (@subtype_perm _ f (λ x, f x ≠ x) (by simp)) : eq.symm (sign_subtype_perm _ _ (λ _, id)) ... = sign (@subtype_perm _ g (λ x, g x ≠ x) (by simp)) : sign_eq_sign_of_equiv _ _ (equiv.of_bijective (show function.bijective (λ x : {x // f x ≠ x}, (⟨i x.1 x.2, have f (f x) ≠ f x, from mt (λ h, f.injective h) x.2, by rw [← h _ x.2 this]; exact mt (hi _ _ this x.2) x.2⟩ : {y // g y ≠ y})), from ⟨λ ⟨x, hx⟩ ⟨y, hy⟩ h, subtype.eq (hi _ _ _ _ (subtype.mk.inj h)), λ ⟨y, hy⟩, let ⟨x, hfx, hx⟩ := hg y hy in ⟨⟨x, hfx⟩, subtype.eq hx⟩⟩)) (λ ⟨x, _⟩, subtype.eq (h x _ _)) ... = sign g : sign_subtype_perm _ _ (λ _, id) def is_cycle (f : perm β) := ∃ x, f x ≠ x ∧ ∀ y, f y ≠ y → ∃ i : ℤ, (f ^ i) x = y lemma is_cycle_swap {x y : α} (hxy : x ≠ y) : is_cycle (swap x y) := ⟨y, by rwa swap_apply_right, λ a (ha : ite (a = x) y (ite (a = y) x a) ≠ a), if hya : y = a then ⟨0, hya⟩ else ⟨1, by rw [gpow_one, swap_apply_def]; split_ifs at *; cc⟩⟩ lemma is_cycle_inv {f : perm β} (hf : is_cycle f) : is_cycle (f⁻¹) := let ⟨x, hx⟩ := hf in ⟨x, by simp [eq_inv_iff_eq, inv_eq_iff_eq, *] at *; cc, λ y hy, let ⟨i, hi⟩ := hx.2 y (by simp [eq_inv_iff_eq, inv_eq_iff_eq, *] at *; cc) in ⟨-i, by rwa [gpow_neg, inv_gpow, inv_inv]⟩⟩ lemma exists_gpow_eq_of_is_cycle {f : perm β} (hf : is_cycle f) {x y : β} (hx : f x ≠ x) (hy : f y ≠ y) : ∃ i : ℤ, (f ^ i) x = y := let ⟨g, hg⟩ := hf in let ⟨a, ha⟩ := hg.2 x hx in let ⟨b, hb⟩ := hg.2 y hy in ⟨b - a, by rw [← ha, ← mul_apply, ← gpow_add, sub_add_cancel, hb]⟩ lemma is_cycle_swap_mul_aux₁ : ∀ (n : ℕ) {b x : α} {f : perm α} (hb : (swap x (f x) * f) b ≠ b) (h : (f ^ n) (f x) = b), ∃ i : ℤ, ((swap x (f x) * f) ^ i) (f x) = b | 0 := λ b x f hb h, ⟨0, h⟩ | (n+1 : ℕ) := λ b x f hb h, if hfbx : f x = b then ⟨0, hfbx⟩ else have f b ≠ b ∧ b ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hb, have hb' : (swap x (f x) * f) (f⁻¹ b) ≠ f⁻¹ b, by rw [mul_apply, apply_inv_self, swap_apply_of_ne_of_ne this.2 (ne.symm hfbx), ne.def, ← injective.eq_iff f.injective, apply_inv_self]; exact this.1, let ⟨i, hi⟩ := is_cycle_swap_mul_aux₁ n hb' (f.injective $ by rw [apply_inv_self]; rwa [pow_succ, mul_apply] at h) in ⟨i + 1, by rw [add_comm, gpow_add, mul_apply, hi, gpow_one, mul_apply, apply_inv_self, swap_apply_of_ne_of_ne (ne_and_ne_of_swap_mul_apply_ne_self hb).2 (ne.symm hfbx)]⟩ lemma is_cycle_swap_mul_aux₂ : ∀ (n : ℤ) {b x : α} {f : perm α} (hb : (swap x (f x) * f) b ≠ b) (h : (f ^ n) (f x) = b), ∃ i : ℤ, ((swap x (f x) * f) ^ i) (f x) = b | (n : ℕ) := λ b x f, is_cycle_swap_mul_aux₁ n | -[1+ n] := λ b x f hb h, if hfbx : f⁻¹ x = b then ⟨-1, by rwa [gpow_neg, gpow_one, mul_inv_rev, mul_apply, swap_inv, swap_apply_right]⟩ else if hfbx' : f x = b then ⟨0, hfbx'⟩ else have f b ≠ b ∧ b ≠ x := ne_and_ne_of_swap_mul_apply_ne_self hb, have hb : (swap x (f⁻¹ x) * f⁻¹) (f⁻¹ b) ≠ f⁻¹ b, by rw [mul_apply, swap_apply_def]; split_ifs; simp [inv_eq_iff_eq, eq_inv_iff_eq] at *; cc, let ⟨i, hi⟩ := is_cycle_swap_mul_aux₁ n hb (show (f⁻¹ ^ n) (f⁻¹ x) = f⁻¹ b, by rw [← gpow_coe_nat, ← h, ← mul_apply, ← mul_apply, ← mul_apply, gpow_neg_succ, ← inv_pow, pow_succ', mul_assoc, mul_assoc, inv_mul_self, mul_one, gpow_coe_nat, ← pow_succ', ← pow_succ]) in have h : (swap x (f⁻¹ x) * f⁻¹) (f x) = f⁻¹ x, by rw [mul_apply, inv_apply_self, swap_apply_left], ⟨-i, by rw [← add_sub_cancel i 1, neg_sub, sub_eq_add_neg, gpow_add, gpow_one, gpow_neg, ← inv_gpow, mul_inv_rev, swap_inv, mul_swap_eq_swap_mul, inv_apply_self, swap_comm _ x, gpow_add, gpow_one, mul_apply, mul_apply (_ ^ i), h, hi, mul_apply, apply_inv_self, swap_apply_of_ne_of_ne this.2 (ne.symm hfbx')]⟩ lemma eq_swap_of_is_cycle_of_apply_apply_eq_self {f : perm α} (hf : is_cycle f) {x : α} (hfx : f x ≠ x) (hffx : f (f x) = x) : f = swap x (f x) := equiv.ext _ _ $ λ y, let ⟨z, hz⟩ := hf in let ⟨i, hi⟩ := hz.2 x hfx in if hyx : y = x then by simp [hyx] else if hfyx : y = f x then by simp [hfyx, hffx] else begin rw [swap_apply_of_ne_of_ne hyx hfyx], refine by_contradiction (λ hy, _), cases hz.2 y hy with j hj, rw [← sub_add_cancel j i, gpow_add, mul_apply, hi] at hj, cases gpow_apply_eq_of_apply_apply_eq_self hffx (j - i) with hji hji, { rw [← hj, hji] at hyx, cc }, { rw [← hj, hji] at hfyx, cc } end lemma is_cycle_swap_mul {f : perm α} (hf : is_cycle f) {x : α} (hx : f x ≠ x) (hffx : f (f x) ≠ x) : is_cycle (swap x (f x) * f) := ⟨f x, by simp only [swap_apply_def, mul_apply]; split_ifs; simp [injective.eq_iff f.injective] at *; cc, λ y hy, let ⟨i, hi⟩ := exists_gpow_eq_of_is_cycle hf hx (ne_and_ne_of_swap_mul_apply_ne_self hy).1 in have hi : (f ^ (i - 1)) (f x) = y, from calc (f ^ (i - 1)) (f x) = (f ^ (i - 1) * f ^ (1 : ℤ)) x : by rw [gpow_one, mul_apply] ... = y : by rwa [← gpow_add, sub_add_cancel], is_cycle_swap_mul_aux₂ (i - 1) hy hi⟩ @[simp] lemma support_swap [fintype α] {x y : α} (hxy : x ≠ y) : (swap x y).support = {x, y} := finset.ext.2 $ λ a, by simp [swap_apply_def]; split_ifs; cc lemma card_support_swap [fintype α] {x y : α} (hxy : x ≠ y) : (swap x y).support.card = 2 := show (swap x y).support.card = finset.card ⟨x::y::0, by simp [hxy]⟩, from congr_arg card $ by rw [support_swap hxy]; simp [*, finset.ext]; cc lemma sign_cycle [fintype α] : ∀ {f : perm α} (hf : is_cycle f), sign f = -(-1 ^ f.support.card) | f := λ hf, let ⟨x, hx⟩ := hf in calc sign f = sign (swap x (f x) * (swap x (f x) * f)) : by rw [← mul_assoc, mul_def, mul_def, swap_swap, trans_refl] ... = -(-1 ^ f.support.card) : if h1 : f (f x) = x then have h : swap x (f x) * f = 1, by conv in (f) {rw eq_swap_of_is_cycle_of_apply_apply_eq_self hf hx.1 h1 }; simp [mul_def, one_def], by rw [sign_mul, sign_swap hx.1.symm, h, sign_one, eq_swap_of_is_cycle_of_apply_apply_eq_self hf hx.1 h1, card_support_swap hx.1.symm]; refl else have h : card (support (swap x (f x) * f)) + 1 = card (support f), by rw [← insert_erase (mem_support.2 hx.1), support_swap_mul_eq h1, card_insert_of_not_mem (not_mem_erase _ _)], have wf : card (support (swap x (f x) * f)) < card (support f), from card_support_swap_mul hx.1, by rw [sign_mul, sign_swap hx.1.symm, sign_cycle (is_cycle_swap_mul hf hx.1 h1), ← h]; simp [pow_add] using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ f, f.support.card)⟩]} end sign end equiv.perm lemma finset.prod_univ_perm [fintype α] [comm_monoid β] {f : α → β} (σ : perm α) : (univ : finset α).prod f = univ.prod (λ z, f (σ z)) := eq.symm $ prod_bij (λ z _, σ z) (λ _ _, mem_univ _) (λ _ _, rfl) (λ _ _ _ _ H, σ.injective H) (λ b _, ⟨σ⁻¹ b, mem_univ _, by simp⟩) lemma finset.sum_univ_perm [fintype α] [add_comm_monoid β] {f : α → β} (σ : perm α) : (univ : finset α).sum f = univ.sum (λ z, f (σ z)) := @finset.prod_univ_perm _ (multiplicative β) _ _ f σ attribute [to_additive finset.sum_univ_perm] finset.prod_univ_perm
a3798b6f0873dd22d75a9498ae028a953366bd73
2c2aac4ae1d23cd0d1f9bf0f8c04b05427d38103
/src/category_theory/limits/shapes/binary_products.lean
5478102252c98e90f552ca7f767d774cc3246f3e
[ "Apache-2.0" ]
permissive
egsgaard/mathlib
3f733823fbc8d34f8e104bf6f5d2d55f150c774e
8e8037f5ce6f1633dba7f8b284a92a6dc2941abc
refs/heads/master
1,650,473,269,445
1,586,936,514,000
1,586,936,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,985
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.shapes.finite_products import category_theory.limits.shapes.terminal import category_theory.discrete_category /-! # Binary (co)products We define a category `walking_pair`, which is the index category for a binary (co)product diagram. A convenience method `pair X Y` constructs the functor from the walking pair, hitting the given objects. We define `prod X Y` and `coprod X Y` as limits and colimits of such functors. Typeclasses `has_binary_products` and `has_binary_coproducts` assert the existence of (co)limits shaped as walking pairs. -/ universes v u open category_theory namespace category_theory.limits /-- The type of objects for the diagram indexing a binary (co)product. -/ @[derive decidable_eq] inductive walking_pair : Type v | left | right open walking_pair instance fintype_walking_pair : fintype walking_pair := { elems := [left, right].to_finset, complete := λ x, by { cases x; simp } } variables {C : Type u} [𝒞 : category.{v} C] include 𝒞 /-- The diagram on the walking pair, sending the two points to `X` and `Y`. -/ def pair (X Y : C) : discrete walking_pair ⥤ C := functor.of_function (λ j, walking_pair.cases_on j X Y) @[simp] lemma pair_obj_left (X Y : C) : (pair X Y).obj left = X := rfl @[simp] lemma pair_obj_right (X Y : C) : (pair X Y).obj right = Y := rfl section variables {F G : discrete walking_pair.{v} ⥤ C} (f : F.obj left ⟶ G.obj left) (g : F.obj right ⟶ G.obj right) /-- The natural transformation between two functors out of the walking pair, specified by its components. -/ def map_pair : F ⟶ G := { app := λ j, match j with | left := f | right := g end } @[simp] lemma map_pair_left : (map_pair f g).app left = f := rfl @[simp] lemma map_pair_right : (map_pair f g).app right = g := rfl /-- The natural isomorphism between two functors out of the walking pair, specified by its components. -/ @[simps] def map_pair_iso (f : F.obj left ≅ G.obj left) (g : F.obj right ≅ G.obj right) : F ≅ G := { hom := map_pair f.hom g.hom, inv := map_pair f.inv g.inv, hom_inv_id' := begin ext j, cases j; { dsimp, simp, } end, inv_hom_id' := begin ext j, cases j; { dsimp, simp, } end } end section variables {D : Type u} [𝒟 : category.{v} D] include 𝒟 /-- The natural isomorphism between `pair X Y ⋙ F` and `pair (F.obj X) (F.obj Y)`. -/ def pair_comp (X Y : C) (F : C ⥤ D) : pair X Y ⋙ F ≅ pair (F.obj X) (F.obj Y) := map_pair_iso (eq_to_iso rfl) (eq_to_iso rfl) end /-- Every functor out of the walking pair is naturally isomorphic (actually, equal) to a `pair` -/ def diagram_iso_pair (F : discrete walking_pair ⥤ C) : F ≅ pair (F.obj walking_pair.left) (F.obj walking_pair.right) := map_pair_iso (eq_to_iso rfl) (eq_to_iso rfl) abbreviation binary_fan (X Y : C) := cone (pair X Y) abbreviation binary_cofan (X Y : C) := cocone (pair X Y) variables {X Y : C} def binary_fan.mk {P : C} (π₁ : P ⟶ X) (π₂ : P ⟶ Y) : binary_fan X Y := { X := P, π := { app := λ j, walking_pair.cases_on j π₁ π₂ }} def binary_cofan.mk {P : C} (ι₁ : X ⟶ P) (ι₂ : Y ⟶ P) : binary_cofan X Y := { X := P, ι := { app := λ j, walking_pair.cases_on j ι₁ ι₂ }} @[simp] lemma binary_fan.mk_π_app_left {P : C} (π₁ : P ⟶ X) (π₂ : P ⟶ Y) : (binary_fan.mk π₁ π₂).π.app walking_pair.left = π₁ := rfl @[simp] lemma binary_fan.mk_π_app_right {P : C} (π₁ : P ⟶ X) (π₂ : P ⟶ Y) : (binary_fan.mk π₁ π₂).π.app walking_pair.right = π₂ := rfl @[simp] lemma binary_cofan.mk_ι_app_left {P : C} (ι₁ : X ⟶ P) (ι₂ : Y ⟶ P) : (binary_cofan.mk ι₁ ι₂).ι.app walking_pair.left = ι₁ := rfl @[simp] lemma binary_cofan.mk_ι_app_right {P : C} (ι₁ : X ⟶ P) (ι₂ : Y ⟶ P) : (binary_cofan.mk ι₁ ι₂).ι.app walking_pair.right = ι₂ := rfl abbreviation prod (X Y : C) [has_limit (pair X Y)] := limit (pair X Y) abbreviation coprod (X Y : C) [has_colimit (pair X Y)] := colimit (pair X Y) notation X ` ⨯ `:20 Y:20 := prod X Y notation X ` ⨿ `:20 Y:20 := coprod X Y abbreviation prod.fst {X Y : C} [has_limit (pair X Y)] : X ⨯ Y ⟶ X := limit.π (pair X Y) walking_pair.left abbreviation prod.snd {X Y : C} [has_limit (pair X Y)] : X ⨯ Y ⟶ Y := limit.π (pair X Y) walking_pair.right abbreviation coprod.inl {X Y : C} [has_colimit (pair X Y)] : X ⟶ X ⨿ Y := colimit.ι (pair X Y) walking_pair.left abbreviation coprod.inr {X Y : C} [has_colimit (pair X Y)] : Y ⟶ X ⨿ Y := colimit.ι (pair X Y) walking_pair.right abbreviation prod.lift {W X Y : C} [has_limit (pair X Y)] (f : W ⟶ X) (g : W ⟶ Y) : W ⟶ X ⨯ Y := limit.lift _ (binary_fan.mk f g) abbreviation coprod.desc {W X Y : C} [has_colimit (pair X Y)] (f : X ⟶ W) (g : Y ⟶ W) : X ⨿ Y ⟶ W := colimit.desc _ (binary_cofan.mk f g) instance prod.mono_lift_of_mono_left {W X Y : C} [has_limit (pair X Y)] (f : W ⟶ X) (g : W ⟶ Y) [mono f] : mono (prod.lift f g) := mono_of_mono_fac $ show prod.lift f g ≫ prod.fst = f, by simp instance prod.mono_lift_of_mono_right {W X Y : C} [has_limit (pair X Y)] (f : W ⟶ X) (g : W ⟶ Y) [mono g] : mono (prod.lift f g) := mono_of_mono_fac $ show prod.lift f g ≫ prod.snd = g, by simp instance coprod.epi_desc_of_epi_left {W X Y : C} [has_colimit (pair X Y)] (f : X ⟶ W) (g : Y ⟶ W) [epi f] : epi (coprod.desc f g) := epi_of_epi_fac $ show coprod.inl ≫ coprod.desc f g = f, by simp instance coprod.epi_desc_of_epi_right {W X Y : C} [has_colimit (pair X Y)] (f : X ⟶ W) (g : Y ⟶ W) [epi g] : epi (coprod.desc f g) := epi_of_epi_fac $ show coprod.inr ≫ coprod.desc f g = g, by simp abbreviation prod.map {W X Y Z : C} [has_limits_of_shape.{v} (discrete walking_pair) C] (f : W ⟶ Y) (g : X ⟶ Z) : W ⨯ X ⟶ Y ⨯ Z := lim.map (map_pair f g) abbreviation coprod.map {W X Y Z : C} [has_colimits_of_shape.{v} (discrete walking_pair) C] (f : W ⟶ Y) (g : X ⟶ Z) : W ⨿ X ⟶ Y ⨿ Z := colim.map (map_pair f g) variables (C) class has_binary_products := (has_limits_of_shape : has_limits_of_shape.{v} (discrete walking_pair) C) class has_binary_coproducts := (has_colimits_of_shape : has_colimits_of_shape.{v} (discrete walking_pair) C) attribute [instance] has_binary_products.has_limits_of_shape has_binary_coproducts.has_colimits_of_shape @[priority 100] -- see Note [lower instance priority] instance [has_finite_products.{v} C] : has_binary_products.{v} C := { has_limits_of_shape := by apply_instance } @[priority 100] -- see Note [lower instance priority] instance [has_finite_coproducts.{v} C] : has_binary_coproducts.{v} C := { has_colimits_of_shape := by apply_instance } /-- If `C` has all limits of diagrams `pair X Y`, then it has all binary products -/ def has_binary_products_of_has_limit_pair [Π {X Y : C}, has_limit (pair X Y)] : has_binary_products.{v} C := { has_limits_of_shape := { has_limit := λ F, has_limit_of_iso (diagram_iso_pair F).symm } } /-- If `C` has all colimits of diagrams `pair X Y`, then it has all binary coproducts -/ def has_binary_coproducts_of_has_colimit_pair [Π {X Y : C}, has_colimit (pair X Y)] : has_binary_coproducts.{v} C := { has_colimits_of_shape := { has_colimit := λ F, has_colimit_of_iso (diagram_iso_pair F) } } @[ext] lemma prod.hom_ext [has_binary_products.{v} C] {Y A B : C} {a b : Y ⟶ A ⨯ B} (h1 : a ≫ prod.fst = b ≫ prod.fst) (h2 : a ≫ prod.snd = b ≫ prod.snd) : a = b := limit.hom_ext (by rintros (_ | _); simpa) @[simp, reassoc] lemma prod.lift_fst [has_binary_products.{v} C] {Y A B : C} (f : Y ⟶ A) (g : Y ⟶ B) : prod.lift f g ≫ prod.fst = f := limit.lift_π _ _ @[simp, reassoc] lemma prod.lift_snd {Y A B : C} [has_binary_products.{v} C] (f : Y ⟶ A) (g : Y ⟶ B) : prod.lift f g ≫ prod.snd = g := limit.lift_π _ _ @[ext] lemma coprod.hom_ext [has_binary_coproducts.{v} C] {Y A B : C} {a b : A ⨿ B ⟶ Y} (h1 : coprod.inl ≫ a = coprod.inl ≫ b) (h2 : coprod.inr ≫ a = coprod.inr ≫ b) : a = b := colimit.hom_ext (by rintros (_ | _); simpa) @[simp, reassoc] lemma coprod.inl_desc [has_binary_coproducts.{v} C] {Y A B : C} (f : A ⟶ Y) (g : B ⟶ Y) : coprod.inl ≫ coprod.desc f g = f := colimit.ι_desc _ _ @[simp, reassoc] lemma coprod.inr_desc {Y A B : C} [has_binary_coproducts.{v} C] (f : A ⟶ Y) (g : B ⟶ Y) : coprod.inr ≫ coprod.desc f g = g := colimit.ι_desc _ _ section variables {C} [has_binary_products.{v} C] local attribute [tidy] tactic.case_bash /-- The braiding isomorphism which swaps a binary product. -/ @[simps] def prod.braiding (P Q : C) : P ⨯ Q ≅ Q ⨯ P := { hom := prod.lift prod.snd prod.fst, inv := prod.lift prod.snd prod.fst } @[simp] lemma prod.symmetry' (P Q : C) : prod.lift prod.snd prod.fst ≫ prod.lift prod.snd prod.fst = 𝟙 (P ⨯ Q) := by tidy /-- The braiding isomorphism is symmetric. -/ lemma prod.symmetry (P Q : C) : (prod.braiding P Q).hom ≫ (prod.braiding Q P).hom = 𝟙 _ := by simp /-- The associator isomorphism for binary products. -/ @[simps] def prod.associator (P Q R : C) : (P ⨯ Q) ⨯ R ≅ P ⨯ (Q ⨯ R) := { hom := prod.lift (prod.fst ≫ prod.fst) (prod.lift (prod.fst ≫ prod.snd) prod.snd), inv := prod.lift (prod.lift prod.fst (prod.snd ≫ prod.fst)) (prod.snd ≫ prod.snd) } lemma prod.pentagon (W X Y Z : C) : prod.map ((prod.associator W X Y).hom) (𝟙 Z) ≫ (prod.associator W (X ⨯ Y) Z).hom ≫ prod.map (𝟙 W) ((prod.associator X Y Z).hom) = (prod.associator (W ⨯ X) Y Z).hom ≫ (prod.associator W X (Y⨯Z)).hom := by tidy lemma prod.associator_naturality {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) : prod.map (prod.map f₁ f₂) f₃ ≫ (prod.associator Y₁ Y₂ Y₃).hom = (prod.associator X₁ X₂ X₃).hom ≫ prod.map f₁ (prod.map f₂ f₃) := by tidy variables [has_terminal.{v} C] /-- The left unitor isomorphism for binary products with the terminal object. -/ @[simps] def prod.left_unitor (P : C) : ⊤_ C ⨯ P ≅ P := { hom := prod.snd, inv := prod.lift (terminal.from P) (𝟙 _) } /-- The right unitor isomorphism for binary products with the terminal object. -/ @[simps] def prod.right_unitor (P : C) : P ⨯ ⊤_ C ≅ P := { hom := prod.fst, inv := prod.lift (𝟙 _) (terminal.from P) } lemma prod.triangle (X Y : C) : (prod.associator X (⊤_ C) Y).hom ≫ prod.map (𝟙 X) ((prod.left_unitor Y).hom) = prod.map ((prod.right_unitor X).hom) (𝟙 Y) := by tidy end section variables {C} [has_binary_coproducts.{v} C] local attribute [tidy] tactic.case_bash /-- The braiding isomorphism which swaps a binary coproduct. -/ @[simps] def coprod.braiding (P Q : C) : P ⨿ Q ≅ Q ⨿ P := { hom := coprod.desc coprod.inr coprod.inl, inv := coprod.desc coprod.inr coprod.inl } @[simp] lemma coprod.symmetry' (P Q : C) : coprod.desc coprod.inr coprod.inl ≫ coprod.desc coprod.inr coprod.inl = 𝟙 (P ⨿ Q) := by tidy /-- The braiding isomorphism is symmetric. -/ lemma coprod.symmetry (P Q : C) : (coprod.braiding P Q).hom ≫ (coprod.braiding Q P).hom = 𝟙 _ := by simp /-- The associator isomorphism for binary coproducts. -/ @[simps] def coprod.associator (P Q R : C) : (P ⨿ Q) ⨿ R ≅ P ⨿ (Q ⨿ R) := { hom := coprod.desc (coprod.desc coprod.inl (coprod.inl ≫ coprod.inr)) (coprod.inr ≫ coprod.inr), inv := coprod.desc (coprod.inl ≫ coprod.inl) (coprod.desc (coprod.inr ≫ coprod.inl) coprod.inr) } lemma coprod.pentagon (W X Y Z : C) : coprod.map ((coprod.associator W X Y).hom) (𝟙 Z) ≫ (coprod.associator W (X⨿Y) Z).hom ≫ coprod.map (𝟙 W) ((coprod.associator X Y Z).hom) = (coprod.associator (W⨿X) Y Z).hom ≫ (coprod.associator W X (Y⨿Z)).hom := by tidy lemma coprod.associator_naturality {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) : coprod.map (coprod.map f₁ f₂) f₃ ≫ (coprod.associator Y₁ Y₂ Y₃).hom = (coprod.associator X₁ X₂ X₃).hom ≫ coprod.map f₁ (coprod.map f₂ f₃) := by tidy variables [has_initial.{v} C] /-- The left unitor isomorphism for binary coproducts with the initial object. -/ @[simps] def coprod.left_unitor (P : C) : ⊥_ C ⨿ P ≅ P := { hom := coprod.desc (initial.to P) (𝟙 _), inv := coprod.inr } /-- The right unitor isomorphism for binary coproducts with the initial object. -/ @[simps] def coprod.right_unitor (P : C) : P ⨿ ⊥_ C ≅ P := { hom := coprod.desc (𝟙 _) (initial.to P), inv := coprod.inl } lemma coprod.triangle (X Y : C) : (coprod.associator X (⊥_ C) Y).hom ≫ coprod.map (𝟙 X) ((coprod.left_unitor Y).hom) = coprod.map ((coprod.right_unitor X).hom) (𝟙 Y) := by tidy end end category_theory.limits
73570106235518c53e34f3e62d99201884be1b96
8cb37a089cdb4af3af9d8bf1002b417e407a8e9e
/tests/lean/simp_subsingleton.lean
002f5b64885077561501023bc23ee2682067d013
[ "Apache-2.0" ]
permissive
kbuzzard/lean
ae3c3db4bb462d750dbf7419b28bafb3ec983ef7
ed1788fd674bb8991acffc8fca585ec746711928
refs/heads/master
1,620,983,366,617
1,618,937,600,000
1,618,937,600,000
359,886,396
1
0
Apache-2.0
1,618,936,987,000
1,618,936,987,000
null
UTF-8
Lean
false
false
1,331
lean
inductive some_subsingleton : Type | canonical open some_subsingleton instance : subsingleton some_subsingleton := ⟨λ a b, by cases a; cases b; refl⟩ -- Note that ⟨λ a b, refl a⟩ does not work as a valid instance: -- the type is a subsingleton, but not definitionally! def some_function : some_subsingleton → some_subsingleton := λ x, x @[simp] lemma some_function_lemma {a : some_subsingleton} : some_function a = canonical := by cases a; refl -- Motivating example: -- example (a : some_subsingleton) : some_function a = canonical := by simp only [some_function_lemma] example (a : some_subsingleton) : some_function a = canonical := by {(do t <- tactic.target, c <- tactic.mk_specialized_congr_lemma_simp t, tactic.trace c.arg_kinds), simp } example : cond (to_bool (2 = 2)) 0 1 = 0 := by {(do `((cond %%t %%i %%e) = _) <- tactic.target, c <- tactic.mk_specialized_congr_lemma_simp t, tactic.trace c.arg_kinds), simp } constants (γ : Type) (f : Π (α : Type*) (β : Sort*), α → β → γ) (X : Type) (X_ss : subsingleton X) (Y : Prop) attribute [instance] X_ss example (x₁ x₂ : X) (y₁ y₂ : Y) : f X Y x₁ y₁ = f X Y x₂ y₂ := by { (do `(%%t = _) <- tactic.target, cs <- tactic.mk_specialized_congr_lemma_simp t, tactic.trace cs.arg_kinds), congr }
5ee7e2eac06053454a207d52b00dbc398c19e0b9
398b53a5e02ce35196531591f84bb2f6b034ce5a
/homotopy/problem11.lean
b44a39cb5febb8d5037d8415e4458702dc6a07a5
[ "MIT" ]
permissive
crockeo/math-exercises
64f07a9371a72895bbd97f49a854dcb6821b18ab
cf9150ef9e025f1b7929ba070a783e7a71f24f31
refs/heads/master
1,607,910,221,030
1,581,231,762,000
1,581,231,762,000
234,595,189
0
0
null
null
null
null
UTF-8
Lean
false
false
333
lean
def compose (A B C : Type) (g : B -> C) (f : A -> B) := fun x : A, g (f x) lemma associative_compose (A B C D : Type) (f : A -> B) (g : B -> C) (h : C -> D) : compose A C D h (compose A B C g f) = compose A B D (compose B C D h g) f := begin rw [compose, compose, compose, compose], end
02942eedf6c5575d80aa57e46f77e92160416074
9dc8cecdf3c4634764a18254e94d43da07142918
/src/topology/metric_space/polish.lean
4898fcf3f297c861ffada5d0333157fffde685bd
[ "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
22,603
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 -/ import analysis.normed_space.basic import topology.metric_space.pi_nat import topology.metric_space.isometry import topology.metric_space.gluing /-! # Polish spaces A topological space is Polish if its topology is second-countable and there exists a compatible complete metric. This is the class of spaces that is well-behaved with respect to measure theory. In this file, we establish the basic properties of Polish spaces. ## Main definitions and results * `polish_space α` is a mixin typeclass on a topological space, requiring that the topology is second-countable and compatible with a complete metric. To endow the space with such a metric, use in a proof `letI := upgrade_polish_space α`. We register an instance from complete second-countable metric spaces to Polish spaces, not the other way around. * We register that countable products and sums of Polish spaces are Polish. * `is_closed.polish_space`: a closed subset of a Polish space is Polish. * `is_open.polish_space`: an open subset of a Polish space is Polish. * `exists_nat_nat_continuous_surjective`: any nonempty Polish space is the continuous image of the fundamental Polish space `ℕ → ℕ`. A fundamental property of Polish spaces is that one can put finer topologies, still Polish, with additional properties: * `exists_polish_space_forall_le`: on a topological space, consider countably many topologies `t n`, all Polish and finer than the original topology. Then there exists another Polish topology which is finer than all the `t n`. * `is_clopenable s` is a property of a subset `s` of a topological space, requiring that there exists a finer topology, which is Polish, for which `s` becomes open and closed. We show that this property is satisfied for open sets, closed sets, for complements, and for countable unions. Once Borel-measurable sets are defined in later files, it will follow that any Borel-measurable set is clopenable. Once the Lusin-Souslin theorem is proved using analytic sets, we will even show that a set is clopenable if and only if it is Borel-measurable, see `is_clopenable_iff_measurable_set`. -/ noncomputable theory open_locale classical topological_space filter open topological_space set metric filter function variables {α : Type*} {β : Type*} /-! ### Basic properties of Polish spaces -/ /-- A Polish space is a topological space with second countable topology, that can be endowed with a metric for which it is complete. We register an instance from complete second countable metric space to polish space, and not the other way around as this is the most common use case. To endow a Polish space with a complete metric space structure, do `letI := upgrade_polish_space α`. -/ class polish_space (α : Type*) [h : topological_space α] : Prop := (second_countable [] : second_countable_topology α) (complete : ∃ m : metric_space α, m.to_uniform_space.to_topological_space = h ∧ @complete_space α m.to_uniform_space) /-- A convenience class, for a Polish space endowed with a complete metric. No instance of this class should be registered: It should be used as `letI := upgrade_polish_space α` to endow a Polish space with a complete metric. -/ class upgraded_polish_space (α : Type*) extends metric_space α, second_countable_topology α, complete_space α @[priority 100] instance polish_space_of_complete_second_countable [m : metric_space α] [h : second_countable_topology α] [h' : complete_space α] : polish_space α := { second_countable := h, complete := ⟨m, rfl, h'⟩ } /-- Construct on a Polish space a metric (compatible with the topology) which is complete. -/ def polish_space_metric (α : Type*) [ht : topological_space α] [h : polish_space α] : metric_space α := h.complete.some.replace_topology h.complete.some_spec.1.symm lemma complete_polish_space_metric (α : Type*) [ht : topological_space α] [h : polish_space α] : @complete_space α (polish_space_metric α).to_uniform_space := begin convert h.complete.some_spec.2, exact metric_space.replace_topology_eq _ _ end /-- This definition endows a Polish space with a complete metric. Use it as: `letI := upgrade_polish_space α`. -/ def upgrade_polish_space (α : Type*) [ht : topological_space α] [h : polish_space α] : upgraded_polish_space α := begin letI := polish_space_metric α, exact { .. complete_polish_space_metric α, .. polish_space.second_countable α } end namespace polish_space @[priority 100] instance t2_space (α : Type*) [topological_space α] [polish_space α] : t2_space α := by { letI := upgrade_polish_space α, apply_instance } /-- A countable product of Polish spaces is Polish. -/ instance pi_countable {ι : Type*} [countable ι] {E : ι → Type*} [∀ i, topological_space (E i)] [∀ i, polish_space (E i)] : polish_space (Π i, E i) := begin casesI nonempty_encodable ι, letI := λ i, upgrade_polish_space (E i), letI : metric_space (Π i, E i) := pi_countable.metric_space, apply_instance, end /-- Without this instance, `polish_space (ℕ → ℕ)` is not found by typeclass inference. -/ instance nat_fun [topological_space α] [polish_space α] : polish_space (ℕ → α) := by apply_instance /-- A countable disjoint union of Polish spaces is Polish. -/ instance sigma {ι : Type*} [countable ι] {E : ι → Type*} [∀ n, topological_space (E n)] [∀ n, polish_space (E n)] : polish_space (Σ n, E n) := begin letI := λ n, upgrade_polish_space (E n), letI : metric_space (Σ n, E n) := sigma.metric_space, haveI : complete_space (Σ n, E n) := sigma.complete_space, apply_instance end /-- The disjoint union of two Polish spaces is Polish. -/ instance sum [topological_space α] [polish_space α] [topological_space β] [polish_space β] : polish_space (α ⊕ β) := begin letI := upgrade_polish_space α, letI := upgrade_polish_space β, letI : metric_space (α ⊕ β) := metric_space_sum, apply_instance end /-- Any nonempty Polish space is the continuous image of the fundamental space `ℕ → ℕ`. -/ lemma exists_nat_nat_continuous_surjective (α : Type*) [topological_space α] [polish_space α] [nonempty α] : ∃ (f : (ℕ → ℕ) → α), continuous f ∧ surjective f := begin letI := upgrade_polish_space α, exact exists_nat_nat_continuous_surjective_of_complete_space α end /-- Given a closed embedding into a Polish space, the source space is also Polish. -/ lemma _root_.closed_embedding.polish_space [topological_space α] [topological_space β] [polish_space β] {f : α → β} (hf : closed_embedding f) : polish_space α := begin letI := upgrade_polish_space β, letI : metric_space α := hf.to_embedding.comap_metric_space f, haveI : second_countable_topology α := hf.to_embedding.second_countable_topology, haveI : complete_space α, { rw complete_space_iff_is_complete_range hf.to_embedding.to_isometry.uniform_inducing, apply is_closed.is_complete, exact hf.closed_range }, apply_instance end /-- Pulling back a Polish topology under an equiv gives again a Polish topology. -/ lemma _root_.equiv.polish_space_induced [t : topological_space β] [polish_space β] (f : α ≃ β) : @polish_space α (t.induced f) := begin letI : topological_space α := t.induced f, exact (f.to_homeomorph_of_inducing ⟨rfl⟩).closed_embedding.polish_space, end /-- A closed subset of a Polish space is also Polish. -/ lemma _root_.is_closed.polish_space {α : Type*} [topological_space α] [polish_space α] {s : set α} (hs : is_closed s) : polish_space s := (is_closed.closed_embedding_subtype_coe hs).polish_space /-- A sequence of type synonyms of a given type `α`, useful in the proof of `exists_polish_space_forall_le` to endow each copy with a different topology. -/ @[nolint unused_arguments has_nonempty_instance] def aux_copy (α : Type*) {ι : Type*} (i : ι) : Type* := α /-- Given a Polish space, and countably many finer Polish topologies, there exists another Polish topology which is finer than all of them. -/ lemma exists_polish_space_forall_le {ι : Type*} [countable ι] [t : topological_space α] [p : polish_space α] (m : ι → topological_space α) (hm : ∀ n, m n ≤ t) (h'm : ∀ n, @polish_space α (m n)) : ∃ (t' : topological_space α), (∀ n, t' ≤ m n) ∧ (t' ≤ t) ∧ @polish_space α t' := begin rcases is_empty_or_nonempty ι with hι|hι, { exact ⟨t, λ i, (is_empty.elim hι i : _), le_rfl, p⟩ }, unfreezingI { inhabit ι }, /- Consider the product of infinitely many copies of `α`, each endowed with the topology `m n`. This is a Polish space, as a product of Polish spaces. Pulling back this topology under the diagonal embedding of `α`, one gets a Polish topology which is finer than all the `m n`. -/ letI : ∀ (n : ι), topological_space (aux_copy α n) := λ n, m n, haveI : ∀ (n : ι), polish_space (aux_copy α n) := λ n, h'm n, letI T : topological_space (Π (n : ι), aux_copy α n) := by apply_instance, let f : α → Π (n : ι), aux_copy α n := λ x n, x, -- show that the induced topology is finer than all the `m n`. have T_le_m : ∀ n, T.induced f ≤ m n, { assume n s hs, refine ⟨set.pi ({n} : set ι) (λ i, s), _, _⟩, { apply is_open_set_pi (finite_singleton _), assume a ha, rw mem_singleton_iff.1 ha, exact hs }, { ext x, simp only [singleton_pi, mem_preimage] } }, refine ⟨T.induced f, λ n, T_le_m n, (T_le_m default).trans (hm default), _⟩, -- show that the new topology is Polish, as the pullback of a Polish topology under a closed -- embedding. have A : range f = ⋂ n, {x | x n = x default}, { ext x, split, { rintros ⟨y, rfl⟩, exact mem_Inter.2 (λ n, by simp only [mem_set_of_eq]) }, { assume hx, refine ⟨x default, _⟩, ext1 n, symmetry, exact (mem_Inter.1 hx n : _) } }, have f_closed : is_closed (range f), { rw A, apply is_closed_Inter (λ n, _), have C : ∀ (i : ι), continuous (λ (x : Π n, aux_copy α n), (id (x i) : α)), { assume i, apply continuous.comp _ (continuous_apply i), apply continuous_def.2 (λ s hs, _), exact hm i s hs }, apply is_closed_eq (C n) (C default) }, have K : @_root_.embedding _ _ (T.induced f) T f, { apply function.injective.embedding_induced, assume x y hxy, have : f x default = f y default, by rw hxy, exact this }, have L : @closed_embedding _ _ (T.induced f) T f, { split, { exact K }, { exact f_closed } }, exact @closed_embedding.polish_space _ _ (T.induced f) T (by apply_instance) _ L end /-! ### An open subset of a Polish space is Polish To prove this fact, one needs to construct another metric, giving rise to the same topology, for which the open subset is complete. This is not obvious, as for instance `(0,1) ⊆ ℝ` is not complete for the usual metric of `ℝ`: one should build a new metric that blows up close to the boundary. -/ section complete_copy variables [metric_space α] {s : set α} /-- A type synonym for a subset `s` of a metric space, on which we will construct another metric for which it will be complete. -/ @[nolint has_nonempty_instance] def complete_copy {α : Type*} (s : set α) : Type* := s /-- A distance on a subset `s` of a metric space, designed to make it complete if `s` is open. It is given by `dist' x y = dist x y + |1 / dist x sᶜ - 1 / dist y sᶜ|`, where the second term blows up close to the boundary to ensure that Cauchy sequences for `dist'` remain well inside `s`. -/ def has_dist_complete_copy (s : set α) : has_dist (complete_copy s) := ⟨λ x y, dist x.1 y.1 + abs (1 / inf_dist x.1 sᶜ - 1 / inf_dist y.1 sᶜ)⟩ local attribute [instance] has_dist_complete_copy lemma dist_complete_copy_eq (x y : complete_copy s) : dist x y = dist x.1 y.1 + abs (1/inf_dist x.1 sᶜ - 1 / inf_dist y.1 sᶜ) := rfl lemma dist_le_dist_complete_copy (x y : complete_copy s) : dist x.1 y.1 ≤ dist x y := (le_add_iff_nonneg_right _).2 (abs_nonneg _) /-- A metric space structure on a subset `s` of a metric space, designed to make it complete if `s` is open. It is given by `dist' x y = dist x y + |1 / dist x sᶜ - 1 / dist y sᶜ|`, where the second term blows up close to the boundary to ensure that Cauchy sequences for `dist'` remain well inside `s`. -/ def complete_copy_metric_space (s : set α) : metric_space (complete_copy s) := { dist_self := λ x, by simp [dist_complete_copy_eq], dist_comm := λ x y, by simp [dist_complete_copy_eq, dist_comm, abs_sub_comm], dist_triangle := λ x y z, calc dist x z = dist x.1 z.1 + abs (1 / inf_dist x.1 sᶜ - 1 / inf_dist z.1 sᶜ) : rfl ... ≤ (dist x.1 y.1 + dist y.1 z.1) + (abs (1 / inf_dist x.1 sᶜ - 1 / inf_dist y.1 sᶜ) + abs (1 / inf_dist y.1 sᶜ - 1 / inf_dist z.1 sᶜ)) : begin rw [← real.dist_eq, ← real.dist_eq, ← real.dist_eq], exact add_le_add (dist_triangle _ _ _) (dist_triangle _ _ _) end ... = dist x y + dist y z : by { rw [dist_complete_copy_eq, dist_complete_copy_eq], abel }, eq_of_dist_eq_zero := begin assume x y hxy, apply subtype.coe_injective, refine dist_le_zero.1 _, rw ← hxy, exact dist_le_dist_complete_copy x y end } local attribute [instance] complete_copy_metric_space /-- The identity between the type synonym `complete_copy s` (with its modified metric) and the original subtype `s` is a homeomorphism. -/ def complete_copy_id_homeo (hs : is_open s) (h's : sᶜ.nonempty) : complete_copy s ≃ₜ s := { to_fun := id, inv_fun := id, left_inv := λ x, rfl, right_inv := λ x, rfl, continuous_to_fun := begin have : lipschitz_with 1 (λ (x : complete_copy s), (id x : s)), { apply lipschitz_with.mk_one, exact dist_le_dist_complete_copy }, exact this.continuous, end, continuous_inv_fun := begin apply continuous_iff_continuous_at.2 (λ x, _), suffices H : tendsto (λ (b : s), dist b.1 x.1 + |1 / inf_dist b.1 sᶜ - 1 / inf_dist x.1 sᶜ|) (𝓝 x) (𝓝 (dist x.1 x.1 + abs (1 / inf_dist x.1 sᶜ - 1 / inf_dist x.1 sᶜ))), { rw [continuous_at, tendsto_iff_dist_tendsto_zero], simpa only [sub_self, abs_zero, add_zero, dist_self] using H }, have I : 0 < inf_dist x.val sᶜ, { rw ← hs.is_closed_compl.not_mem_iff_inf_dist_pos h's, simp }, apply tendsto.add, { apply continuous.tendsto, exact continuous_subtype_coe.dist continuous_const }, { refine (tendsto.sub_const _ _).abs, refine tendsto.div tendsto_const_nhds _ I.ne', exact ((continuous_inf_dist_pt _).comp continuous_subtype_coe).tendsto _ } end } lemma complete_space_complete_copy [complete_space α] (hs : is_open s) (h's : sᶜ.nonempty) : complete_space (complete_copy s) := begin refine metric.complete_of_convergent_controlled_sequences (λ n, (1/2)^n) (by simp) _, assume u hu, have A : cauchy_seq (λ n, (u n).1), { apply cauchy_seq_of_le_tendsto_0 (λ (n : ℕ), (1/2)^n) (λ n m N hNn hNm, _) _, { exact (dist_le_dist_complete_copy (u n) (u m)).trans (hu N n m hNn hNm).le }, { exact tendsto_pow_at_top_nhds_0_of_lt_1 (by norm_num) (by norm_num) } }, obtain ⟨x, xlim⟩ : ∃ x, tendsto (λ n, (u n).1) at_top (𝓝 x), { haveI : nonempty α := ⟨(u 0).1⟩, exact ⟨_, A.tendsto_lim⟩ }, suffices xs : x ∈ s, { refine ⟨⟨x, xs⟩, _⟩, have L : tendsto (λ n, (id ⟨(u n).1, (u n).2⟩ : s)) at_top (𝓝 (⟨x, xs⟩)), { apply embedding_subtype_coe.tendsto_nhds_iff.2, exact xlim }, convert ((complete_copy_id_homeo hs h's).symm.continuous.tendsto _).comp L, ext1 n, simp [complete_copy_id_homeo] }, obtain ⟨C, hC⟩ : ∃ C, ∀ n, 1 / inf_dist (u n).1 sᶜ < C, { refine ⟨(1/2)^0 + dist (1 / inf_dist (u 0).1 sᶜ) 0, λ n, _⟩, calc 1 / inf_dist (u n).val sᶜ ≤ dist (1 / inf_dist (u n).val sᶜ) 0 : by { rw real.dist_0_eq_abs, exact le_abs_self _ } ... ≤ dist (1 / inf_dist (u n).1 sᶜ) (1 / inf_dist (u 0).1 sᶜ) + dist (1 / inf_dist (u 0).1 sᶜ) 0 : dist_triangle _ _ _ ... ≤ (dist (u n).1 (u 0).1 + dist (1 / inf_dist (u n).1 sᶜ) (1 / inf_dist (u 0).1 sᶜ)) + dist (1 / inf_dist (u 0).1 sᶜ) 0 : add_le_add (le_add_of_nonneg_left dist_nonneg) le_rfl ... = dist (u n) (u 0) + dist (1 / inf_dist (u 0).1 sᶜ) 0 : rfl ... < (1/2)^0 + dist (1 / inf_dist (u 0).1 sᶜ) 0 : add_lt_add_right (hu 0 n 0 (zero_le _) le_rfl) _ }, have Cpos : 0 < C, { apply lt_of_le_of_lt _ (hC 0), simp [inf_dist_nonneg] }, have I : ∀ n, 1/C ≤ inf_dist (u n).1 sᶜ, { assume n, have : 0 < inf_dist (u n).val sᶜ, { apply (hs.is_closed_compl.not_mem_iff_inf_dist_pos h's).1, simp }, rw div_le_iff' Cpos, exact (div_le_iff this).1 (hC n).le }, have I' : 1/C ≤ inf_dist x sᶜ, { have : tendsto (λ n, inf_dist (u n).1 sᶜ) at_top (𝓝 (inf_dist x sᶜ)) := ((continuous_inf_dist_pt sᶜ).tendsto x).comp xlim, exact ge_of_tendsto' this I }, suffices : x ∉ sᶜ, by simpa, apply (hs.is_closed_compl.not_mem_iff_inf_dist_pos h's).2 (lt_of_lt_of_le _ I'), simp [Cpos], end /-- An open subset of a Polish space is also Polish. -/ lemma _root_.is_open.polish_space {α : Type*} [topological_space α] [polish_space α] {s : set α} (hs : is_open s) : polish_space s := begin rcases eq_empty_or_nonempty sᶜ with h's|h's, { simp at h's, apply is_closed.polish_space, rw h's, exact is_closed_univ }, { letI := upgrade_polish_space α, haveI : complete_space (complete_copy s) := complete_space_complete_copy hs h's, haveI : second_countable_topology (complete_copy s) := (complete_copy_id_homeo hs h's).embedding.second_countable_topology, exact (complete_copy_id_homeo hs h's).symm.closed_embedding.polish_space } end end complete_copy /-! ### Clopenable sets in Polish spaces -/ /-- A set in a topological space is clopenable if there exists a finer Polish topology for which this set is open and closed. It turns out that this notion is equivalent to being Borel-measurable, but this is nontrivial (see `is_clopenable_iff_measurable_set`). -/ def is_clopenable [t : topological_space α] (s : set α) : Prop := ∃ (t' : topological_space α), t' ≤ t ∧ @polish_space α t' ∧ @is_closed α t' s ∧ @is_open α t' s /-- Given a closed set `s` in a Polish space, one can construct a finer Polish topology for which `s` is both open and closed. -/ lemma _root_.is_closed.is_clopenable [topological_space α] [polish_space α] {s : set α} (hs : is_closed s) : is_clopenable s := begin /- Both sets `s` and `sᶜ` admit a Polish topology. So does their disjoint union `s ⊕ sᶜ`. Pulling back this topology by the canonical bijection with `α` gives the desired Polish topology in which `s` is both open and closed. -/ haveI : polish_space s := hs.polish_space, let t : set α := sᶜ, haveI : polish_space t := hs.is_open_compl.polish_space, let f : α ≃ (s ⊕ t) := (equiv.set.sum_compl s).symm, letI T : topological_space (s ⊕ t) := by apply_instance, let t' : topological_space α := T.induced f, let g := @equiv.to_homeomorph_of_inducing _ _ t' T f { induced := rfl }, have A : g ⁻¹' (range (sum.inl : s → s ⊕ t)) = s, { ext x, by_cases h : x ∈ s, { simp only [equiv.set.sum_compl_symm_apply_of_mem, h, mem_preimage, equiv.to_fun_as_coe, mem_range_self, equiv.to_homeomorph_of_inducing_apply]}, { simp only [equiv.set.sum_compl_symm_apply_of_not_mem, h, not_false_iff, mem_preimage, equiv.to_homeomorph_of_inducing_apply, equiv.to_fun_as_coe, mem_range, exists_false]} }, refine ⟨t', _, f.polish_space_induced, _, _⟩, { assume u hu, change ∃ (s' : set (↥s ⊕ ↥t)), T.is_open s' ∧ f ⁻¹' s' = u, refine ⟨f.symm ⁻¹' u, _, by simp only [equiv.symm_symm, equiv.symm_preimage_preimage]⟩, refine is_open_sum_iff.2 ⟨_, _⟩, { have : is_open ((coe : s → α) ⁻¹' u) := is_open.preimage continuous_subtype_coe hu, have : sum.inl ⁻¹' (⇑(f.symm) ⁻¹' u) = (coe : s → α) ⁻¹' u, by { ext x, simp only [equiv.symm_symm, mem_preimage, equiv.set.sum_compl_apply_inl] }, rwa this }, { have : is_open ((coe : t → α) ⁻¹' u) := is_open.preimage continuous_subtype_coe hu, have : sum.inr ⁻¹' (⇑(f.symm) ⁻¹' u) = (coe : t → α) ⁻¹' u, by { ext x, simp only [equiv.symm_symm, mem_preimage, equiv.set.sum_compl_apply_inr] }, rwa this } }, { have : @is_closed α t' (g ⁻¹' (range (sum.inl : s → s ⊕ t))), { apply is_closed.preimage, { exact @homeomorph.continuous _ _ t' _ g }, { exact is_closed_range_inl } }, convert this, exact A.symm }, { have : @is_open α t' (g ⁻¹' (range (sum.inl : s → s ⊕ t))), { apply is_open.preimage, { exact @homeomorph.continuous _ _ t' _ g }, { exact is_open_range_inl } }, convert this, exact A.symm }, end lemma is_clopenable.compl [topological_space α] {s : set α} (hs : is_clopenable s) : is_clopenable sᶜ := begin rcases hs with ⟨t, t_le, t_polish, h, h'⟩, exact ⟨t, t_le, t_polish, @is_open.is_closed_compl α t s h', @is_closed.is_open_compl α t s h⟩, end lemma _root_.is_open.is_clopenable [topological_space α] [polish_space α] {s : set α} (hs : is_open s) : is_clopenable s := by simpa using hs.is_closed_compl.is_clopenable.compl lemma is_clopenable.Union [t : topological_space α] [polish_space α] {s : ℕ → set α} (hs : ∀ n, is_clopenable (s n)) : is_clopenable (⋃ n, s n) := begin choose m mt m_polish m_closed m_open using hs, obtain ⟨t', t'm, -, t'_polish⟩ : ∃ (t' : topological_space α), (∀ (n : ℕ), t' ≤ m n) ∧ (t' ≤ t) ∧ @polish_space α t' := exists_polish_space_forall_le m mt m_polish, have A : @is_open α t' (⋃ n, s n), { apply is_open_Union, assume n, apply t'm n, exact m_open n }, obtain ⟨t'', t''_le, t''_polish, h1, h2⟩ : ∃ (t'' : topological_space α), t'' ≤ t' ∧ @polish_space α t'' ∧ @is_closed α t'' (⋃ n, s n) ∧ @is_open α t'' (⋃ n, s n) := @is_open.is_clopenable α t' t'_polish _ A, exact ⟨t'', t''_le.trans ((t'm 0).trans (mt 0)), t''_polish, h1, h2⟩, end end polish_space
5161af7f758750abd6ace8e5cd3c5491c9de2484
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/logic/unnamed_916.lean
8e41343fd294201e488721819b1868f6f4993a99
[]
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
211
lean
import tactic variables {a b c : ℕ} -- BEGIN example (divab : a ∣ b) (divbc : b ∣ c) : a ∣ c := begin cases divab with d beq, cases divbc with e ceq, rw [ceq, beq], use (d * e), ring end -- END
dc5a4cefc5bb3a95ef789e9f6cadc30205a45a60
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/src/Init/Coe.lean
472b056f0c9bcdccd073a8e609d8732f7b9eff5f
[ "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
Kha/lean4
1005785d2c8797ae266a303968848e5f6ce2fe87
b99e11346948023cd6c29d248cd8f3e3fb3474cf
refs/heads/master
1,693,355,498,027
1,669,080,461,000
1,669,113,138,000
184,748,176
0
0
Apache-2.0
1,665,995,520,000
1,556,884,930,000
Lean
UTF-8
Lean
false
false
11,922
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, Mario Carneiro -/ prelude import Init.Prelude set_option linter.missingDocs true -- keep it documented /-! # Coercion Lean uses a somewhat elaborate system of typeclasses to drive the coercion system. Here a *coercion* means an invisible function that is automatically inserted to fix what would otherwise be a type error. For example, if we have: ``` def f (x : Nat) : Int := x ``` then this is clearly not type correct as is, because `x` has type `Nat` but type `Int` is expected, and normally you will get an error message saying exactly that. But before it shows that message, it will attempt to synthesize an instance of `CoeT Nat x Int`, which will end up going through all the other typeclasses defined below, to discover that there is an instance of `Coe Nat Int` defined. This instance is defined as: ``` instance : Coe Nat Int := ⟨Int.ofNat⟩ ``` so Lean will elaborate the original function `f` as if it said: ``` def f (x : Nat) : Int := Int.ofNat x ``` which is not a type error anymore. You can also use the `↑` operator to explicitly indicate a coercion. Using `↑x` instead of `x` in the example will result in the same output. Because there are many polymorphic functions in Lean, it is often ambiguous where the coercion can go. For example: ``` def f (x y : Nat) : Int := x + y ``` This could be either `↑x + ↑y` where `+` is the addition on `Int`, or `↑(x + y)` where `+` is addition on `Nat`, or even `x + y` using a heterogeneous addition with the type `Nat → Nat → Int`. You can use the `↑` operator to disambiguate between these possibilities, but generally Lean will elaborate working from the "outside in", meaning that it will first look at the expression `_ + _ : Int` and assign the `+` to be the one for `Int`, and then need to insert coercions for the subterms `↑x : Int` and `↑y : Int`, resulting in the `↑x + ↑y` version. ## Important typeclasses * `Coe α β` is the most basic class, and the usual one you will want to use when implementing a coercion for your own types. * `CoeDep α (x : α) β` allows `β` to depend not only on `α` but on the value `x : α` itself. This is useful when the coercion function is dependent. An example of a dependent coercion is the instance for `Prop → Bool`, because it only holds for `Decidable` propositions. It is defined as: ``` instance (p : Prop) [Decidable p] : CoeDep Prop p Bool := ... ``` * `CoeFun α (γ : α → Sort v)` is a coercion to a function. `γ a` should be a (coercion-to-)function type, and this is triggered whenever an element `f : α` appears in an application like `f x` which would not make sense since `f` does not have a function type. This is automatically turned into `CoeFun.coe f x`. * `CoeSort α β` is a coercion to a sort. `β` must be a universe, and if `a : α` appears in a place where a type is expected, like `(x : a)` or `a → a`, then it will be turned into `(x : CoeSort.coe a)`. * `CoeHead` is like `Coe`, but while `Coe` can be transitively chained in the `CoeT` class, `CoeHead` can only appear once and only at the start of such a chain. This is useful when the transitive instances are not well behaved. * `CoeTail` is similar: it can only appear at the end of a chain of coercions. * `CoeT α (x : α) β` itself is the combination of all the aforementioned classes (except `CoeSort` and `CoeFun` which have different triggers). You can implement `CoeT` if you do not want this coercion to be transitively composed with any other coercions. Note that unlike most operators like `+`, `↑` is always eagerly unfolded at parse time into its definition. So if we look at the definition of `f` from before, we see no trace of the `CoeT.coe` function: ``` def f (x : Nat) : Int := x #print f -- def f : Nat → Int := -- fun (x : Nat) => Int.ofNat x ``` -/ universe u v w w' /-- `Coe α β` is the typeclass for coercions from `α` to `β`. It can be transitively chained with other `Coe` instances, and coercion is automatically used when `x` has type `α` but it is used in a context where `β` is expected. You can use the `↑x` operator to explicitly trigger coercion. -/ class Coe (α : Sort u) (β : Sort v) where /-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`, or by double type ascription `((x : α) : β)`. -/ coe : α → β /-- Auxiliary class that contains the transitive closure of `Coe`. Users should generally not implement this directly. -/ class CoeTC (α : Sort u) (β : Sort v) where /-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`, or by double type ascription `((x : α) : β)`. -/ coe : α → β /-- `CoeHead α β` is for coercions that can only appear at the beginning of a sequence of coercions. That is, `β` can be further coerced via `Coe β γ` and `CoeTail γ δ` instances but `α` will only be the inferred type of the input. -/ class CoeHead (α : Sort u) (β : Sort v) where /-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`, or by double type ascription `((x : α) : β)`. -/ coe : α → β /-- `CoeTail α β` is for coercions that can only appear at the end of a sequence of coercions. That is, `α` can be further coerced via `Coe σ α` and `CoeHead τ σ` instances but `β` will only be the expected type of the expression. -/ class CoeTail (α : Sort u) (β : Sort v) where /-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`, or by double type ascription `((x : α) : β)`. -/ coe : α → β /-- Auxiliary class that contains `CoeHead` + `CoeTC` + `CoeTail`. A `CoeHTCT` chain has the "grammar" `(CoeHead)? (Coe)* (CoeTail)?`, except that the empty sequence is not allowed. -/ class CoeHTCT (α : Sort u) (β : Sort v) where /-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`, or by double type ascription `((x : α) : β)`. -/ coe : α → β /-- `CoeDep α (x : α) β` is a typeclass for dependent coercions, that is, the type `β` can depend on `x` (or rather, the value of `x` is available to typeclass search so an instance that relates `β` to `x` is allowed). Dependent coercions do not participate in the transitive chaining process of regular coercions: they must exactly match the type mismatch on both sides. -/ class CoeDep (α : Sort u) (_ : α) (β : Sort v) where /-- The resulting value of type `β`. The input `x : α` is a parameter to the type class, so the value of type `β` may possibly depend on additional typeclasses on `x`. -/ coe : β /-- `CoeT` is the core typeclass which is invoked by Lean to resolve a type error. It can also be triggered explicitly with the notation `↑x` or by double type ascription `((x : α) : β)`. A `CoeT` chain has the "grammar" `(CoeHead)? (Coe)* (CoeTail)? | CoeDep`, except that the empty sequence is not allowed (identity coercions don't need the coercion system at all). -/ class CoeT (α : Sort u) (_ : α) (β : Sort v) where /-- The resulting value of type `β`. The input `x : α` is a parameter to the type class, so the value of type `β` may possibly depend on additional typeclasses on `x`. -/ coe : β /-- `CoeFun α (γ : α → Sort v)` is a coercion to a function. `γ a` should be a (coercion-to-)function type, and this is triggered whenever an element `f : α` appears in an application like `f x` which would not make sense since `f` does not have a function type. This is automatically turned into `CoeFun.coe f x`. -/ class CoeFun (α : Sort u) (γ : outParam (α → Sort v)) where /-- Coerces a value `f : α` to type `γ f`, which should be either be a function type or another `CoeFun` type, in order to resolve a mistyped application `f x`. -/ coe : (f : α) → γ f /-- `CoeSort α β` is a coercion to a sort. `β` must be a universe, and if `a : α` appears in a place where a type is expected, like `(x : a)` or `a → a`, then it will be turned into `(x : CoeSort.coe a)`. -/ class CoeSort (α : Sort u) (β : outParam (Sort v)) where /-- Coerces a value of type `α` to `β`, which must be a universe. -/ coe : α → β /-- `↑x` represents a coercion, which converts `x` of type `α` to type `β`, using typeclasses to resolve a suitable conversion function. You can often leave the `↑` off entirely, since coercion is triggered implicitly whenever there is a type error, but in ambiguous cases it can be useful to use `↑` to disambiguate between e.g. `↑x + ↑y` and `↑(x + y)`. -/ syntax:1024 (name := coeNotation) "↑" term:1024 : term instance coeTrans {α : Sort u} {β : Sort v} {δ : Sort w} [Coe β δ] [CoeTC α β] : CoeTC α δ where coe a := Coe.coe (CoeTC.coe a : β) instance coeBase {α : Sort u} {β : Sort v} [Coe α β] : CoeTC α β where coe a := Coe.coe a instance coeOfHeafOfTCOfTail {α : Sort u} {β : Sort v} {δ : Sort w} {γ : Sort w'} [CoeHead α β] [CoeTail δ γ] [CoeTC β δ] : CoeHTCT α γ where coe a := CoeTail.coe (CoeTC.coe (CoeHead.coe a : β) : δ) instance coeOfHeadOfTC {α : Sort u} {β : Sort v} {δ : Sort w} [CoeHead α β] [CoeTC β δ] : CoeHTCT α δ where coe a := CoeTC.coe (CoeHead.coe a : β) instance coeOfTCOfTail {α : Sort u} {β : Sort v} {δ : Sort w} [CoeTail β δ] [CoeTC α β] : CoeHTCT α δ where coe a := CoeTail.coe (CoeTC.coe a : β) instance coeOfHeadOfTail {α : Sort u} {β : Sort v} {γ : Sort w} [CoeHead α β] [CoeTail β γ] : CoeHTCT α γ where coe a := CoeTail.coe (CoeHead.coe a : β) instance coeOfHead {α : Sort u} {β : Sort v} [CoeHead α β] : CoeHTCT α β where coe a := CoeHead.coe a instance coeOfTail {α : Sort u} {β : Sort v} [CoeTail α β] : CoeHTCT α β where coe a := CoeTail.coe a instance coeOfTC {α : Sort u} {β : Sort v} [CoeTC α β] : CoeHTCT α β where coe a := CoeTC.coe a instance coeOfHTCT {α : Sort u} {β : Sort v} [CoeHTCT α β] (a : α) : CoeT α a β where coe := CoeHTCT.coe a instance coeOfDep {α : Sort u} {β : Sort v} (a : α) [CoeDep α a β] : CoeT α a β where coe := CoeDep.coe a instance coeId {α : Sort u} (a : α) : CoeT α a α where coe := a instance coeSortToCoeTail [inst : CoeSort α β] : CoeTail α β where coe := inst.coe /-! # Basic instances -/ instance boolToProp : Coe Bool Prop where coe b := Eq b true instance boolToSort : CoeSort Bool Prop where coe b := Eq b true instance decPropToBool (p : Prop) [Decidable p] : CoeDep Prop p Bool where coe := decide p instance optionCoe {α : Type u} : CoeTail α (Option α) where coe := some instance subtypeCoe {α : Sort u} {p : α → Prop} : CoeHead (Subtype p) α where coe v := v.val /-! # Coe bridge -/ /-- Helper definition used by the elaborator. It is not meant to be used directly by users. This is used for coercions between monads, in the case where we want to apply a monad lift and a coercion on the result type at the same time. -/ @[inline] def Lean.Internal.liftCoeM {m : Type u → Type v} {n : Type u → Type w} {α β : Type u} [MonadLiftT m n] [∀ a, CoeT α a β] [Monad n] (x : m α) : n β := do let a ← liftM x pure (CoeT.coe a) /-- Helper definition used by the elaborator. It is not meant to be used directly by users. This is used for coercing the result type under a monad. -/ @[inline] def Lean.Internal.coeM {m : Type u → Type v} {α β : Type u} [∀ a, CoeT α a β] [Monad m] (x : m α) : m β := do let a ← x pure (CoeT.coe a) instance [CoeFun α β] (a : α) : CoeDep α a (β a) where coe := CoeFun.coe a instance [CoeFun α (fun _ => β)] : CoeTail α β where coe a := CoeFun.coe a instance [CoeSort α β] : CoeTail α β where coe a := CoeSort.coe a
e42d742f2f98a97e9c0717bc1de7dd438c416551
5c508618e029e31b823bb6ba3d05d513a3bc3f40
/src/refactor.lean
9a62a3da20538e20e6dcbfaa1570be39a77166d7
[]
no_license
JasonKYi/dual_maps
01f49d1fbd2d1ed3e92882101a81ed51dc9589c6
612d23c3be8b484d0bc9840e1395d3e5c67b0eec
refs/heads/main
1,680,308,911,793
1,617,022,546,000
1,617,022,546,000
350,137,505
0
0
null
null
null
null
UTF-8
Lean
false
false
7,360
lean
import linear_algebra.bilinear_form universes u v w variables {R : Type u} [comm_ring R] {M₁ : Type v} {M₂ : Type w} variables [add_comm_group M₁] [module R M₁] [add_comm_group M₂] [module R M₂] variables {K : Type v} [field K] {V₁ : Type u} {V₂ : Type w} variables [add_comm_group V₁] [vector_space K V₁] [add_comm_group V₂] [vector_space K V₂] variables [finite_dimensional K V₁] [finite_dimensional K V₂] open module /-- Given `f : M₁ ≃ₗ[R] M₂` and `U` a submodule of `M₂`, `f.comap U` is the induced `linear_equiv` from `U.comap f.to_linear_map` to `U`. -/ def linear_equiv.comap (f : M₁ ≃ₗ[R] M₂) (U : submodule R M₂) : U.comap f.to_linear_map ≃ₗ[R] U := f.of_submodules _ _ begin ext x, simp_rw [submodule.mem_map, submodule.mem_comap], split; intro hx, { rcases hx with ⟨y, hy, rfl⟩, exact hy }, { refine ⟨f.inv_fun x, _⟩, simpa } end /-- Given `p` a submodule of the module `M` and `q` a submodule of `p`, `p.equiv_subtype_map q` is the natural `linear_equiv` between `q` and `q.map p.subtype`. -/ def submodule.equiv_subtype_map (p : submodule R M₁) (q : submodule R p) : q ≃ₗ[R] q.map p.subtype := { inv_fun := begin rintro ⟨x, hx⟩, refine ⟨⟨x, _⟩, _⟩; rcases hx with ⟨⟨_, h⟩, _, rfl⟩; assumption end, left_inv := λ ⟨⟨_, _⟩, _⟩, rfl, right_inv := λ ⟨x, ⟨_, h⟩, _, rfl⟩, rfl, .. (p.subtype.dom_restrict q).cod_restrict _ begin rintro ⟨x, hx⟩, refine ⟨x, hx, rfl⟩, end } lemma finite_dimensional.subtype_eq_findim_eq (p : subspace K V₁) (q : subspace K p) : finite_dimensional.findim K (q.map p.subtype) = finite_dimensional.findim K q := linear_equiv.findim_eq (p.equiv_subtype_map q).symm /-- The pullback of a submodule in the dual space along the evaluation map. -/ def submodule.dual_annihilator_comap (Φ : submodule R (module.dual R M₁)) : submodule R M₁ := Φ.dual_annihilator.comap (dual.eval R M₁) lemma submodule.mem_dual_annihilator_comap_iff {Φ : submodule R (module.dual R M₁)} (x : M₁) : x ∈ Φ.dual_annihilator_comap ↔ ∀ φ : Φ, φ x = 0 := begin simp_rw [submodule.dual_annihilator_comap, submodule.mem_comap, submodule.mem_dual_annihilator], split; intros h φ, { exact h φ.1 φ.2 }, { intro hφ, exact h ⟨φ, hφ⟩ } end lemma submodule.dual_annihilator_comp_findim_eq {Φ : submodule K (dual K V₁)} : finite_dimensional.findim K Φ.dual_annihilator_comap = finite_dimensional.findim K Φ.dual_annihilator := begin rw [submodule.dual_annihilator_comap, show dual.eval K V₁ = vector_space.eval_equiv.to_linear_map, by refl], apply linear_equiv.findim_eq, apply linear_equiv.comap, end lemma submodule.findim_add_findim_dual_annihilator_comap_eq (W : subspace K (module.dual K V₁)) : finite_dimensional.findim K W + finite_dimensional.findim K W.dual_annihilator_comap = finite_dimensional.findim K V₁ := begin rw [submodule.dual_annihilator_comp_findim_eq, W.quot_equiv_annihilator.findim_eq.symm, add_comm, submodule.findim_quotient_add_findim, subspace.dual_findim_eq], end namespace bilin_form section finite_dimensional open finite_dimensional bilin_form /-- The restriction of a nondegenerate bilinear form `B` onto a submodule `W` is nondegenerate if `W ⊓ B.orthogonal W ≤ ⊥`. -/ lemma nondegenerate_restrict_of_inf_orthogonal_le_bot (B : bilin_form R M₁) (hB : sym_bilin_form.is_sym B) {W : submodule R M₁} (hW : W ⊓ B.orthogonal W ≤ ⊥) : (B.restrict W).nondegenerate := begin rintro ⟨x, hx⟩ hB₁, rw [submodule.mk_eq_zero, ← submodule.mem_bot R], refine hW ⟨hx, λ y hy, _⟩, specialize hB₁ ⟨y, hy⟩, rwa [restrict_apply, submodule.coe_mk, submodule.coe_mk, hB] at hB₁ end lemma to_lin_restrict_ker_eq_inf_orthogonal (B : bilin_form K V₁) (W : subspace K V₁) (hB : sym_bilin_form.is_sym B) : (B.to_lin.dom_restrict W).ker.map W.subtype = (W ⊓ B.orthogonal ⊤ : subspace K V₁) := begin ext x, split; intro hx, { rcases hx with ⟨⟨x, hx⟩, hker, rfl⟩, erw linear_map.mem_ker at hker, split, { simp [hx] }, { intros y _, rw [is_ortho, hB], change (B.to_lin.dom_restrict W) ⟨x, hx⟩ y = 0, rw hker, refl } }, { simp_rw [submodule.mem_map, linear_map.mem_ker], refine ⟨⟨x, hx.1⟩, _, rfl⟩, ext y, change B x y = 0, rw hB, exact hx.2 _ submodule.mem_top } end lemma to_lin_restrict_range_eq_dual_annihilator (B : bilin_form K V₁) (W : subspace K V₁) (hB : sym_bilin_form.is_sym B) : (B.to_lin.dom_restrict W).range.dual_annihilator_comap = B.orthogonal W := begin ext x, split; rw [mem_orthogonal_iff]; intro hx, { intros y hy, rw submodule.mem_dual_annihilator_comap_iff at hx, refine hx ⟨B.to_lin.dom_restrict W ⟨y, hy⟩, ⟨y, hy⟩, _, rfl⟩, simp only [submodule.top_coe] }, { rw submodule.mem_dual_annihilator_comap_iff, rintro ⟨_, ⟨w, hw⟩, _, rfl⟩, exact hx w hw } end lemma findim_add_findim_orthogonal {B : bilin_form K V₁} {W : subspace K V₁} (hB₁ : sym_bilin_form.is_sym B) : findim K W + findim K (B.orthogonal W) = findim K V₁ + findim K (W ⊓ B.orthogonal ⊤ : subspace K V₁) := begin rw [← to_lin_restrict_ker_eq_inf_orthogonal _ _ hB₁, ← to_lin_restrict_range_eq_dual_annihilator _ _ hB₁, ← (B.to_lin.dom_restrict W).range.findim_add_findim_dual_annihilator_comap_eq, subtype_eq_findim_eq], conv_rhs { rw [add_comm, ← add_assoc, add_comm (findim K ↥((B.to_lin.dom_restrict W).ker)), linear_map.findim_range_add_findim_ker] }, end /-- A subspace is complement to its orthogonal complement with respect to some bilinear form if that bilinear form restricted on to the subspace is nondegenerate. -/ lemma restrict_nondegenerate_of_is_compl_orthogonal {B : bilin_form K V₁} {W : subspace K V₁} (hB₁ : sym_bilin_form.is_sym B) (hB₂ : (B.restrict W).nondegenerate) : is_compl W (B.orthogonal W) := begin have : W ⊓ B.orthogonal W = ⊥, { rw eq_bot_iff, intros x hx, obtain ⟨hx₁, hx₂⟩ := submodule.mem_inf.1 hx, refine subtype.mk_eq_mk.1 (hB₂ ⟨x, hx₁⟩ _), rintro ⟨n, hn⟩, rw [restrict_apply, submodule.coe_mk, submodule.coe_mk, hB₁], exact hx₂ n hn }, refine ⟨this ▸ le_refl _, _⟩, { rw top_le_iff, refine finite_dimensional.eq_top_of_findim_eq _, refine le_antisymm (submodule.findim_le _) _, conv_rhs { rw ← add_zero (findim K _) }, rw [← findim_bot K V₁, ← this, submodule.dim_sup_add_dim_inf_eq, findim_add_findim_orthogonal hB₁], exact nat.le.intro rfl } end /-- A subspace is complement to its orthogonal complement with respect to some bilinear form if and only if that bilinear form restricted on to the subspace is nondegenerate. -/ theorem restrict_nondegenerate_iff_is_compl_orthogonal {B : bilin_form K V₁} {W : subspace K V₁} (hB₁ : sym_bilin_form.is_sym B) : (B.restrict W).nondegenerate ↔ is_compl W (B.orthogonal W) := ⟨ λ hB₂, restrict_nondegenerate_of_is_compl_orthogonal hB₁ hB₂, λ h, B.nondegenerate_restrict_of_inf_orthogonal_le_bot hB₁ h.1⟩ end finite_dimensional end bilin_form
9399beb11bc0394a43dab8f49e1241639d4e748a
c777c32c8e484e195053731103c5e52af26a25d1
/src/probability/density.lean
2e622d3848004c8cd0d3824b4851a7a6c02bc5f4
[ "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
19,168
lean
/- Copyright (c) 2021 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import measure_theory.decomposition.radon_nikodym import measure_theory.measure.haar_of_basis /-! # Probability density function This file defines the probability density function of random variables, by which we mean measurable functions taking values in a Borel space. In particular, a measurable function `f` is said to the probability density function of a random variable `X` if for all measurable sets `S`, `ℙ(X ∈ S) = ∫ x in S, f x dx`. Probability density functions are one way of describing the distribution of a random variable, and are useful for calculating probabilities and finding moments (although the latter is better achieved with moment generating functions). This file also defines the continuous uniform distribution and proves some properties about random variables with this distribution. ## Main definitions * `measure_theory.has_pdf` : A random variable `X : Ω → E` is said to `has_pdf` with respect to the measure `ℙ` on `Ω` and `μ` on `E` if there exists a measurable function `f` such that the push-forward measure of `ℙ` along `X` equals `μ.with_density f`. * `measure_theory.pdf` : If `X` is a random variable that `has_pdf X ℙ μ`, then `pdf X` is the measurable function `f` such that the push-forward measure of `ℙ` along `X` equals `μ.with_density f`. * `measure_theory.pdf.uniform` : A random variable `X` is said to follow the uniform distribution if it has a constant probability density function with a compact, non-null support. ## Main results * `measure_theory.pdf.integral_fun_mul_eq_integral` : Law of the unconscious statistician, i.e. if a random variable `X : Ω → E` has pdf `f`, then `𝔼(g(X)) = ∫ x, g x * f x dx` for all measurable `g : E → ℝ`. * `measure_theory.pdf.integral_mul_eq_integral` : A real-valued random variable `X` with pdf `f` has expectation `∫ x, x * f x dx`. * `measure_theory.pdf.uniform.integral_eq` : If `X` follows the uniform distribution with its pdf having support `s`, then `X` has expectation `(λ s)⁻¹ * ∫ x in s, x dx` where `λ` is the Lebesgue measure. ## TODOs Ultimately, we would also like to define characteristic functions to describe distributions as it exists for all random variables. However, to define this, we will need Fourier transforms which we currently do not have. -/ noncomputable theory open_locale classical measure_theory nnreal ennreal namespace measure_theory open topological_space measure_theory.measure variables {Ω E : Type*} [measurable_space E] /-- A random variable `X : Ω → E` is said to `has_pdf` with respect to the measure `ℙ` on `Ω` and `μ` on `E` if there exists a measurable function `f` such that the push-forward measure of `ℙ` along `X` equals `μ.with_density f`. -/ class has_pdf {m : measurable_space Ω} (X : Ω → E) (ℙ : measure Ω) (μ : measure E . volume_tac) : Prop := (pdf' : measurable X ∧ ∃ (f : E → ℝ≥0∞), measurable f ∧ map X ℙ = μ.with_density f) @[measurability] lemma has_pdf.measurable {m : measurable_space Ω} (X : Ω → E) (ℙ : measure Ω) (μ : measure E . volume_tac) [hX : has_pdf X ℙ μ] : measurable X := hX.pdf'.1 /-- If `X` is a random variable that `has_pdf X ℙ μ`, then `pdf X` is the measurable function `f` such that the push-forward measure of `ℙ` along `X` equals `μ.with_density f`. -/ def pdf {m : measurable_space Ω} (X : Ω → E) (ℙ : measure Ω) (μ : measure E . volume_tac) := if hX : has_pdf X ℙ μ then classical.some hX.pdf'.2 else 0 lemma pdf_undef {m : measurable_space Ω} {ℙ : measure Ω} {μ : measure E} {X : Ω → E} (h : ¬ has_pdf X ℙ μ) : pdf X ℙ μ = 0 := by simp only [pdf, dif_neg h] lemma has_pdf_of_pdf_ne_zero {m : measurable_space Ω} {ℙ : measure Ω} {μ : measure E} {X : Ω → E} (h : pdf X ℙ μ ≠ 0) : has_pdf X ℙ μ := begin by_contra hpdf, rw [pdf, dif_neg hpdf] at h, exact hpdf (false.rec (has_pdf X ℙ μ) (h rfl)) end lemma pdf_eq_zero_of_not_measurable {m : measurable_space Ω} {ℙ : measure Ω} {μ : measure E} {X : Ω → E} (hX : ¬ measurable X) : pdf X ℙ μ = 0 := pdf_undef (λ hpdf, hX hpdf.pdf'.1) lemma measurable_of_pdf_ne_zero {m : measurable_space Ω} {ℙ : measure Ω} {μ : measure E} (X : Ω → E) (h : pdf X ℙ μ ≠ 0) : measurable X := by { by_contra hX, exact h (pdf_eq_zero_of_not_measurable hX) } @[measurability] lemma measurable_pdf {m : measurable_space Ω} (X : Ω → E) (ℙ : measure Ω) (μ : measure E . volume_tac) : measurable (pdf X ℙ μ) := begin by_cases hX : has_pdf X ℙ μ, { rw [pdf, dif_pos hX], exact (classical.some_spec hX.pdf'.2).1 }, { rw [pdf, dif_neg hX], exact measurable_zero } end lemma map_eq_with_density_pdf {m : measurable_space Ω} (X : Ω → E) (ℙ : measure Ω) (μ : measure E . volume_tac) [hX : has_pdf X ℙ μ] : measure.map X ℙ = μ.with_density (pdf X ℙ μ) := begin rw [pdf, dif_pos hX], exact (classical.some_spec hX.pdf'.2).2 end lemma map_eq_set_lintegral_pdf {m : measurable_space Ω} (X : Ω → E) (ℙ : measure Ω) (μ : measure E . volume_tac) [hX : has_pdf X ℙ μ] {s : set E} (hs : measurable_set s) : measure.map X ℙ s = ∫⁻ x in s, pdf X ℙ μ x ∂μ := by rw [← with_density_apply _ hs, map_eq_with_density_pdf X ℙ μ] namespace pdf variables {m : measurable_space Ω} {ℙ : measure Ω} {μ : measure E} lemma lintegral_eq_measure_univ {X : Ω → E} [has_pdf X ℙ μ] : ∫⁻ x, pdf X ℙ μ x ∂μ = ℙ set.univ := begin rw [← set_lintegral_univ, ← map_eq_set_lintegral_pdf X ℙ μ measurable_set.univ, measure.map_apply (has_pdf.measurable X ℙ μ) measurable_set.univ, set.preimage_univ], end lemma ae_lt_top [is_finite_measure ℙ] {μ : measure E} {X : Ω → E} : ∀ᵐ x ∂μ, pdf X ℙ μ x < ∞ := begin by_cases hpdf : has_pdf X ℙ μ, { haveI := hpdf, refine ae_lt_top (measurable_pdf X ℙ μ) _, rw lintegral_eq_measure_univ, exact (measure_lt_top _ _).ne }, { rw [pdf, dif_neg hpdf], exact filter.eventually_of_forall (λ x, with_top.zero_lt_top) } end lemma of_real_to_real_ae_eq [is_finite_measure ℙ] {X : Ω → E} : (λ x, ennreal.of_real (pdf X ℙ μ x).to_real) =ᵐ[μ] pdf X ℙ μ := of_real_to_real_ae_eq ae_lt_top lemma integrable_iff_integrable_mul_pdf [is_finite_measure ℙ] {X : Ω → E} [has_pdf X ℙ μ] {f : E → ℝ} (hf : measurable f) : integrable (λ x, f (X x)) ℙ ↔ integrable (λ x, f x * (pdf X ℙ μ x).to_real) μ := begin rw [← integrable_map_measure hf.ae_strongly_measurable (has_pdf.measurable X ℙ μ).ae_measurable, map_eq_with_density_pdf X ℙ μ, integrable_with_density_iff (measurable_pdf _ _ _) ae_lt_top], apply_instance end /-- **The Law of the Unconscious Statistician**: Given a random variable `X` and a measurable function `f`, `f ∘ X` is a random variable with expectation `∫ x, f x * pdf X ∂μ` where `μ` is a measure on the codomain of `X`. -/ lemma integral_fun_mul_eq_integral [is_finite_measure ℙ] {X : Ω → E} [has_pdf X ℙ μ] {f : E → ℝ} (hf : measurable f) : ∫ x, f x * (pdf X ℙ μ x).to_real ∂μ = ∫ x, f (X x) ∂ℙ := begin by_cases hpdf : integrable (λ x, f x * (pdf X ℙ μ x).to_real) μ, { rw [← integral_map (has_pdf.measurable X ℙ μ).ae_measurable hf.ae_strongly_measurable, map_eq_with_density_pdf X ℙ μ, integral_eq_lintegral_pos_part_sub_lintegral_neg_part hpdf, integral_eq_lintegral_pos_part_sub_lintegral_neg_part, lintegral_with_density_eq_lintegral_mul _ (measurable_pdf X ℙ μ) hf.neg.ennreal_of_real, lintegral_with_density_eq_lintegral_mul _ (measurable_pdf X ℙ μ) hf.ennreal_of_real], { congr' 2, { have : ∀ x, ennreal.of_real (f x * (pdf X ℙ μ x).to_real) = ennreal.of_real (pdf X ℙ μ x).to_real * ennreal.of_real (f x), { intro x, rw [mul_comm, ennreal.of_real_mul ennreal.to_real_nonneg] }, simp_rw [this], exact lintegral_congr_ae (filter.eventually_eq.mul of_real_to_real_ae_eq (ae_eq_refl _)) }, { have : ∀ x, ennreal.of_real (- (f x * (pdf X ℙ μ x).to_real)) = ennreal.of_real (pdf X ℙ μ x).to_real * ennreal.of_real (-f x), { intro x, rw [neg_mul_eq_neg_mul, mul_comm, ennreal.of_real_mul ennreal.to_real_nonneg] }, simp_rw [this], exact lintegral_congr_ae (filter.eventually_eq.mul of_real_to_real_ae_eq (ae_eq_refl _)) } }, { refine ⟨hf.ae_strongly_measurable, _⟩, rw [has_finite_integral, lintegral_with_density_eq_lintegral_mul _ (measurable_pdf _ _ _) hf.nnnorm.coe_nnreal_ennreal], have : (λ x, (pdf X ℙ μ * λ x, ↑‖f x‖₊) x) =ᵐ[μ] (λ x, ‖f x * (pdf X ℙ μ x).to_real‖₊), { simp_rw [← smul_eq_mul, nnnorm_smul, ennreal.coe_mul], rw [smul_eq_mul, mul_comm], refine filter.eventually_eq.mul (ae_eq_refl _) (ae_eq_trans of_real_to_real_ae_eq.symm _), convert ae_eq_refl _, ext1 x, exact real.ennnorm_eq_of_real ennreal.to_real_nonneg }, rw lintegral_congr_ae this, exact hpdf.2 } }, { rw [integral_undef hpdf, integral_undef], rwa ← integrable_iff_integrable_mul_pdf hf at hpdf, all_goals { apply_instance } } end lemma map_absolutely_continuous {X : Ω → E} [has_pdf X ℙ μ] : map X ℙ ≪ μ := by { rw map_eq_with_density_pdf X ℙ μ, exact with_density_absolutely_continuous _ _, } /-- A random variable that `has_pdf` is quasi-measure preserving. -/ lemma to_quasi_measure_preserving {X : Ω → E} [has_pdf X ℙ μ] : quasi_measure_preserving X ℙ μ := { measurable := has_pdf.measurable X ℙ μ, absolutely_continuous := map_absolutely_continuous, } lemma have_lebesgue_decomposition_of_has_pdf {X : Ω → E} [hX' : has_pdf X ℙ μ] : (map X ℙ).have_lebesgue_decomposition μ := ⟨⟨⟨0, pdf X ℙ μ⟩, by simp only [zero_add, measurable_pdf X ℙ μ, true_and, mutually_singular.zero_left, map_eq_with_density_pdf X ℙ μ] ⟩⟩ lemma has_pdf_iff {X : Ω → E} : has_pdf X ℙ μ ↔ measurable X ∧ (map X ℙ).have_lebesgue_decomposition μ ∧ map X ℙ ≪ μ := begin split, { intro hX', exactI ⟨hX'.pdf'.1, have_lebesgue_decomposition_of_has_pdf, map_absolutely_continuous⟩ }, { rintros ⟨hX, h_decomp, h⟩, haveI := h_decomp, refine ⟨⟨hX, (measure.map X ℙ).rn_deriv μ, measurable_rn_deriv _ _, _⟩⟩, rwa with_density_rn_deriv_eq } end lemma has_pdf_iff_of_measurable {X : Ω → E} (hX : measurable X) : has_pdf X ℙ μ ↔ (map X ℙ).have_lebesgue_decomposition μ ∧ map X ℙ ≪ μ := by { rw has_pdf_iff, simp only [hX, true_and], } section variables {F : Type*} [measurable_space F] {ν : measure F} /-- A random variable that `has_pdf` transformed under a `quasi_measure_preserving` map also `has_pdf` if `(map g (map X ℙ)).have_lebesgue_decomposition μ`. `quasi_measure_preserving_has_pdf'` is more useful in the case we are working with a probability measure and a real-valued random variable. -/ lemma quasi_measure_preserving_has_pdf {X : Ω → E} [has_pdf X ℙ μ] {g : E → F} (hg : quasi_measure_preserving g μ ν) (hmap : (map g (map X ℙ)).have_lebesgue_decomposition ν) : has_pdf (g ∘ X) ℙ ν := begin rw [has_pdf_iff, ← map_map hg.measurable (has_pdf.measurable X ℙ μ)], refine ⟨hg.measurable.comp (has_pdf.measurable X ℙ μ), hmap, _⟩, rw [map_eq_with_density_pdf X ℙ μ], refine absolutely_continuous.mk (λ s hsm hs, _), rw [map_apply hg.measurable hsm, with_density_apply _ (hg.measurable hsm)], have := hg.absolutely_continuous hs, rw map_apply hg.measurable hsm at this, exact set_lintegral_measure_zero _ _ this, end lemma quasi_measure_preserving_has_pdf' [is_finite_measure ℙ] [sigma_finite ν] {X : Ω → E} [has_pdf X ℙ μ] {g : E → F} (hg : quasi_measure_preserving g μ ν) : has_pdf (g ∘ X) ℙ ν := quasi_measure_preserving_has_pdf hg infer_instance end section real variables [is_finite_measure ℙ] {X : Ω → ℝ} /-- A real-valued random variable `X` `has_pdf X ℙ λ` (where `λ` is the Lebesgue measure) if and only if the push-forward measure of `ℙ` along `X` is absolutely continuous with respect to `λ`. -/ lemma real.has_pdf_iff_of_measurable (hX : measurable X) : has_pdf X ℙ ↔ map X ℙ ≪ volume := begin rw [has_pdf_iff_of_measurable hX, and_iff_right_iff_imp], exact λ h, infer_instance, end lemma real.has_pdf_iff : has_pdf X ℙ ↔ measurable X ∧ map X ℙ ≪ volume := begin by_cases hX : measurable X, { rw [real.has_pdf_iff_of_measurable hX, iff_and_self], exact λ h, hX, apply_instance }, { exact ⟨λ h, false.elim (hX h.pdf'.1), λ h, false.elim (hX h.1)⟩, } end /-- If `X` is a real-valued random variable that has pdf `f`, then the expectation of `X` equals `∫ x, x * f x ∂λ` where `λ` is the Lebesgue measure. -/ lemma integral_mul_eq_integral [has_pdf X ℙ] : ∫ x, x * (pdf X ℙ volume x).to_real = ∫ x, X x ∂ℙ := integral_fun_mul_eq_integral measurable_id lemma has_finite_integral_mul {f : ℝ → ℝ} {g : ℝ → ℝ≥0∞} (hg : pdf X ℙ =ᵐ[volume] g) (hgi : ∫⁻ x, ‖f x‖₊ * g x ≠ ∞) : has_finite_integral (λ x, f x * (pdf X ℙ volume x).to_real) := begin rw has_finite_integral, have : (λ x, ↑‖f x‖₊ * g x) =ᵐ[volume] (λ x, ‖f x * (pdf X ℙ volume x).to_real‖₊), { refine ae_eq_trans (filter.eventually_eq.mul (ae_eq_refl (λ x, ‖f x‖₊)) (ae_eq_trans hg.symm of_real_to_real_ae_eq.symm)) _, simp_rw [← smul_eq_mul, nnnorm_smul, ennreal.coe_mul, smul_eq_mul], refine filter.eventually_eq.mul (ae_eq_refl _) _, convert ae_eq_refl _, ext1 x, exact real.ennnorm_eq_of_real ennreal.to_real_nonneg }, rwa [lt_top_iff_ne_top, ← lintegral_congr_ae this], end end real section /-! **Uniform Distribution** -/ /-- A random variable `X` has uniform distribution if it has a probability density function `f` with support `s` such that `f = (μ s)⁻¹ 1ₛ` a.e. where `1ₛ` is the indicator function for `s`. -/ def is_uniform {m : measurable_space Ω} (X : Ω → E) (support : set E) (ℙ : measure Ω) (μ : measure E . volume_tac) := pdf X ℙ μ =ᵐ[μ] support.indicator ((μ support)⁻¹ • 1) namespace is_uniform lemma has_pdf {m : measurable_space Ω} {X : Ω → E} {ℙ : measure Ω} {μ : measure E} {s : set E} (hns : μ s ≠ 0) (hnt : μ s ≠ ∞) (hu : is_uniform X s ℙ μ) : has_pdf X ℙ μ := has_pdf_of_pdf_ne_zero begin intro hpdf, rw [is_uniform, hpdf] at hu, suffices : μ (s ∩ function.support ((μ s)⁻¹ • 1)) = 0, { have heq : function.support ((μ s)⁻¹ • (1 : E → ℝ≥0∞)) = set.univ, { ext x, rw [function.mem_support], simp [hnt] }, rw [heq, set.inter_univ] at this, exact hns this }, exact set.indicator_ae_eq_zero hu.symm, end lemma pdf_to_real_ae_eq {m : measurable_space Ω} {X : Ω → E} {ℙ : measure Ω} {μ : measure E} {s : set E} (hX : is_uniform X s ℙ μ) : (λ x, (pdf X ℙ μ x).to_real) =ᵐ[μ] (λ x, (s.indicator ((μ s)⁻¹ • (1 : E → ℝ≥0∞)) x).to_real) := filter.eventually_eq.fun_comp hX ennreal.to_real lemma measure_preimage {m : measurable_space Ω} {X : Ω → E} {ℙ : measure Ω} {μ : measure E} {s : set E} (hns : μ s ≠ 0) (hnt : μ s ≠ ∞) (hms : measurable_set s) (hu : is_uniform X s ℙ μ) {A : set E} (hA : measurable_set A) : ℙ (X ⁻¹' A) = μ (s ∩ A) / μ s := begin haveI := hu.has_pdf hns hnt, rw [←measure.map_apply (has_pdf.measurable X ℙ μ) hA, map_eq_set_lintegral_pdf X ℙ μ hA, lintegral_congr_ae hu.restrict], simp only [hms, hA, lintegral_indicator, pi.smul_apply, pi.one_apply, algebra.id.smul_eq_mul, mul_one, lintegral_const, restrict_apply', set.univ_inter], rw ennreal.div_eq_inv_mul, end lemma is_probability_measure {m : measurable_space Ω} {X : Ω → E} {ℙ : measure Ω} {μ : measure E} {s : set E} (hns : μ s ≠ 0) (hnt : μ s ≠ ∞) (hms : measurable_set s) (hu : is_uniform X s ℙ μ) : is_probability_measure ℙ := ⟨begin have : X ⁻¹' set.univ = set.univ, { simp only [set.preimage_univ] }, rw [←this, hu.measure_preimage hns hnt hms measurable_set.univ, set.inter_univ, ennreal.div_self hns hnt], end⟩ variables {X : Ω → ℝ} {s : set ℝ} (hms : measurable_set s) (hns : volume s ≠ 0) include hms hns lemma mul_pdf_integrable [is_finite_measure ℙ] (hcs : is_compact s) (huX : is_uniform X s ℙ) : integrable (λ x : ℝ, x * (pdf X ℙ volume x).to_real) := begin by_cases hsupp : volume s = ∞, { have : pdf X ℙ =ᵐ[volume] 0, { refine ae_eq_trans huX _, simp [hsupp] }, refine integrable.congr (integrable_zero _ _ _) _, rw [(by simp : (λ x, 0 : ℝ → ℝ) = (λ x, x * (0 : ℝ≥0∞).to_real))], refine filter.eventually_eq.mul (ae_eq_refl _) (filter.eventually_eq.fun_comp this.symm ennreal.to_real) }, refine ⟨ae_strongly_measurable_id.mul (measurable_pdf X ℙ).ae_measurable.ennreal_to_real.ae_strongly_measurable, _⟩, refine has_finite_integral_mul huX _, set ind := (volume s)⁻¹ • (1 : ℝ → ℝ≥0∞) with hind, have : ∀ x, ↑‖x‖₊ * s.indicator ind x = s.indicator (λ x, ‖x‖₊ * ind x) x := λ x, (s.indicator_mul_right (λ x, ↑‖x‖₊) ind).symm, simp only [this, lintegral_indicator _ hms, hind, mul_one, algebra.id.smul_eq_mul, pi.one_apply, pi.smul_apply], rw lintegral_mul_const _ measurable_nnnorm.coe_nnreal_ennreal, { refine (ennreal.mul_lt_top (set_lintegral_lt_top_of_is_compact hsupp hcs continuous_nnnorm).ne (ennreal.inv_lt_top.2 (pos_iff_ne_zero.mpr hns)).ne).ne }, { apply_instance } end /-- A real uniform random variable `X` with support `s` has expectation `(λ s)⁻¹ * ∫ x in s, x ∂λ` where `λ` is the Lebesgue measure. -/ lemma integral_eq (hnt : volume s ≠ ∞) (huX : is_uniform X s ℙ) : ∫ x, X x ∂ℙ = (volume s)⁻¹.to_real * ∫ x in s, x := begin haveI := has_pdf hns hnt huX, haveI := huX.is_probability_measure hns hnt hms, rw ← integral_mul_eq_integral, rw integral_congr_ae (filter.eventually_eq.mul (ae_eq_refl _) (pdf_to_real_ae_eq huX)), have : ∀ x, x * (s.indicator ((volume s)⁻¹ • (1 : ℝ → ℝ≥0∞)) x).to_real = x * (s.indicator ((volume s)⁻¹.to_real • (1 : ℝ → ℝ)) x), { refine λ x, congr_arg ((*) x) _, by_cases hx : x ∈ s, { simp [set.indicator_of_mem hx] }, { simp [set.indicator_of_not_mem hx] }}, simp_rw [this, ← s.indicator_mul_right (λ x, x), integral_indicator hms], change ∫ x in s, x * ((volume s)⁻¹.to_real • 1) ∂(volume) = _, rw [integral_mul_right, mul_comm, algebra.id.smul_eq_mul, mul_one], end . end is_uniform end end pdf end measure_theory
13e58ffc4182c9e8e0012a2337e423f9d425dab8
3f1a1d97c03bb24b55a1b9969bb4b3c619491d5a
/library/data/rbtree/insert.lean
b07ec88fb7ef3aca3e630a8ec3b9770ecdfbebab
[ "Apache-2.0" ]
permissive
praveenmunagapati/lean
00c3b4496cef8e758396005013b9776bb82c4f56
fc760f57d20e0a486d14bc8a08d89147b60f530c
refs/heads/master
1,630,692,342,183
1,515,626,222,000
1,515,626,222,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
33,547
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 -/ import data.rbtree.find universes u v local attribute [simp] rbnode.lift namespace rbnode variables {α : Type u} open color @[simp] lemma balance1_eq₁ (l : rbnode α) (x r₁ y r₂ v t) : balance1 (red_node l x r₁) y r₂ v t = red_node (black_node l x r₁) y (black_node r₂ v t) := begin cases r₂; refl end @[simp] lemma balance1_eq₂ (l₁ : rbnode α) (y l₂ x r v t) : get_color l₁ ≠ red → balance1 l₁ y (red_node l₂ x r) v t = red_node (black_node l₁ y l₂) x (black_node r v t) := begin cases l₁; simp [get_color, balance1] end @[simp] lemma balance1_eq₃ (l : rbnode α) (y r v t) : get_color l ≠ red → get_color r ≠ red → balance1 l y r v t = black_node (red_node l y r) v t := begin cases l; cases r; simp [get_color, balance1] end @[simp] lemma balance2_eq₁ (l : rbnode α) (x₁ r₁ y r₂ v t) : balance2 (red_node l x₁ r₁) y r₂ v t = red_node (black_node t v l) x₁ (black_node r₁ y r₂) := by cases r₂; refl @[simp] lemma balance2_eq₂ (l₁ : rbnode α) (y l₂ x₂ r₂ v t) : get_color l₁ ≠ red → balance2 l₁ y (red_node l₂ x₂ r₂) v t = red_node (black_node t v l₁) y (black_node l₂ x₂ r₂) := begin cases l₁; simp [get_color, balance2] end @[simp] lemma balance2_eq₃ (l : rbnode α) (y r v t) : get_color l ≠ red → get_color r ≠ red → balance2 l y r v t = black_node t v (red_node l y r) := begin cases l; cases r; simp [get_color, balance2] end /- We can use the same induction principle for balance1 and balance2 -/ lemma balance.cases {p : rbnode α → α → rbnode α → Prop} (l y r) (red_left : ∀ l x r₁ y r₂, p (red_node l x r₁) y r₂) (red_right : ∀ l₁ y l₂ x r, get_color l₁ ≠ red → p l₁ y (red_node l₂ x r)) (other : ∀ l y r, get_color l ≠ red → get_color r ≠ red → p l y r) : p l y r := begin cases l; cases r, any_goals { apply red_left }, any_goals { apply red_right; simp [get_color]; contradiction; done }, any_goals { apply other; simp [get_color]; contradiction; done }, end lemma balance1_ne_leaf (l : rbnode α) (x r v t) : balance1 l x r v t ≠ leaf := by apply balance.cases l x r; intros; simp [*]; contradiction lemma balance1_node_ne_leaf {s : rbnode α} (a : α) (t : rbnode α) : s ≠ leaf → balance1_node s a t ≠ leaf := begin intro h, cases s, { contradiction }, all_goals { simp [balance1_node], apply balance1_ne_leaf } end lemma balance2_ne_leaf (l : rbnode α) (x r v t) : balance2 l x r v t ≠ leaf := by apply balance.cases l x r; intros; simp [*]; contradiction lemma balance2_node_ne_leaf {s : rbnode α} (a : α) (t : rbnode α) : s ≠ leaf → balance2_node s a t ≠ leaf := begin intro h, cases s, { contradiction }, all_goals { simp [balance2_node], apply balance2_ne_leaf } end variables (lt : α → α → Prop) [decidable_rel lt] @[elab_as_eliminator] lemma ins.induction {p : rbnode α → Prop} (t x) (is_leaf : p leaf) (is_red_lt : ∀ a y b (hc : cmp_using lt x y = ordering.lt) (ih : p a), p (red_node a y b)) (is_red_eq : ∀ a y b (hc : cmp_using lt x y = ordering.eq), p (red_node a y b)) (is_red_gt : ∀ a y b (hc : cmp_using lt x y = ordering.gt) (ih : p b), p (red_node a y b)) (is_black_lt_red : ∀ a y b (hc : cmp_using lt x y = ordering.lt) (hr : get_color a = red) (ih : p a), p (black_node a y b)) (is_black_lt_not_red : ∀ a y b (hc : cmp_using lt x y = ordering.lt) (hnr : get_color a ≠ red) (ih : p a), p (black_node a y b)) (is_black_eq : ∀ a y b (hc : cmp_using lt x y = ordering.eq), p (black_node a y b)) (is_black_gt_red : ∀ a y b (hc : cmp_using lt x y = ordering.gt) (hr : get_color b = red) (ih : p b), p (black_node a y b)) (is_black_gt_not_red : ∀ a y b (hc : cmp_using lt x y = ordering.gt) (hnr : get_color b ≠ red) (ih : p b), p (black_node a y b)) : p t := begin induction t, case leaf { apply is_leaf }, case red_node : a y b { cases h : cmp_using lt x y, case ordering.lt { apply is_red_lt; assumption }, case ordering.eq { apply is_red_eq; assumption }, case ordering.gt { apply is_red_gt; assumption }, }, case black_node : a y b { cases h : cmp_using lt x y, case ordering.lt { by_cases get_color a = red, { apply is_black_lt_red; assumption }, { apply is_black_lt_not_red; assumption }, }, case ordering.eq { apply is_black_eq; assumption }, case ordering.gt { by_cases get_color b = red, { apply is_black_gt_red; assumption }, { apply is_black_gt_not_red; assumption }, } } end lemma is_searchable_balance1 {l y r v t lo hi} : is_searchable lt l lo (some y) → is_searchable lt r (some y) (some v) → is_searchable lt t (some v) hi → is_searchable lt (balance1 l y r v t) lo hi := by apply balance.cases l y r; intros; simp [*]; is_searchable_tactic lemma is_searchable_balance1_node {t} [is_trans α lt] : ∀ {y s lo hi}, is_searchable lt t lo (some y) → is_searchable lt s (some y) hi → is_searchable lt (balance1_node t y s) lo hi := begin cases t; simp [balance1_node]; intros; is_searchable_tactic, { cases lo, { apply is_searchable_none_low_of_is_searchable_some_low, assumption }, { simp at *, apply is_searchable_some_low_of_is_searchable_of_lt; assumption } }, all_goals { apply is_searchable_balance1; assumption } end lemma is_searchable_balance2 {l y r v t lo hi} : is_searchable lt t lo (some v) → is_searchable lt l (some v) (some y) → is_searchable lt r (some y) hi → is_searchable lt (balance2 l y r v t) lo hi := by apply balance.cases l y r; intros; simp [*]; is_searchable_tactic lemma is_searchable_balance2_node {t} [is_trans α lt] : ∀ {y s lo hi}, is_searchable lt s lo (some y) → is_searchable lt t (some y) hi → is_searchable lt (balance2_node t y s) lo hi := begin induction t; simp [balance2_node]; intros; is_searchable_tactic, { cases hi, { apply is_searchable_none_high_of_is_searchable_some_high, assumption }, { simp at *, apply is_searchable_some_high_of_is_searchable_of_lt, assumption' } }, all_goals { apply is_searchable_balance2, assumption' } end lemma is_searchable_ins {t x} [is_strict_weak_order α lt] : ∀ {lo hi} (h : is_searchable lt t lo hi), lift lt lo (some x) → lift lt (some x) hi → is_searchable lt (ins lt t x) lo hi := begin with_cases { apply ins.induction lt t x; intros; simp [ins, *] at * {eta := ff}; is_searchable_tactic }, case is_red_lt { apply ih h_hs₁, assumption, simp [*] }, case is_red_eq hs₁ { apply is_searchable_of_is_searchable_of_incomp hc, assumption }, case is_red_eq hs₂ { apply is_searchable_of_incomp_of_is_searchable hc, assumption }, case is_red_gt { apply ih h_hs₂, cases hi; simp [*], assumption }, case is_black_lt_red { apply is_searchable_balance1_node, apply ih h_hs₁, assumption, simp [*], assumption }, case is_black_lt_not_red { apply ih h_hs₁, assumption, simp [*] }, case is_black_eq hs₁ { apply is_searchable_of_is_searchable_of_incomp hc, assumption }, case is_black_eq hs₂ { apply is_searchable_of_incomp_of_is_searchable hc, assumption }, case is_black_gt_red { apply is_searchable_balance2_node, assumption, apply ih h_hs₂, simp [*], assumption }, case is_black_gt_not_red { apply ih h_hs₂, assumption, simp [*] } end lemma is_searchable_mk_insert_result {c t} : is_searchable lt t none none → is_searchable lt (mk_insert_result c t) none none := begin cases c; cases t; simp [mk_insert_result], any_goals { exact id }, { intro h, is_searchable_tactic } end lemma is_searchable_insert {t x} [is_strict_weak_order α lt] : is_searchable lt t none none → is_searchable lt (insert lt t x) none none := begin intro h, simp [insert], apply is_searchable_mk_insert_result, apply is_searchable_ins; { assumption <|> simp } end end rbnode namespace rbnode section membership_lemmas parameters {α : Type u} (lt : α → α → Prop) [decidable_rel lt] local attribute [simp] mem balance1_node balance2_node local infix `∈` := mem lt lemma mem_balance1_node_of_mem_left {x s} (v) (t : rbnode α) : x ∈ s → x ∈ balance1_node s v t := begin cases s; simp, all_goals { apply balance.cases s_lchild s_val s_rchild; intros; simp at *; blast_disjs; simp [*] } end lemma mem_balance2_node_of_mem_left {x s} (v) (t : rbnode α) : x ∈ s → x ∈ balance2_node s v t := begin cases s; simp, all_goals { apply balance.cases s_lchild s_val s_rchild; intros; simp at *; blast_disjs; simp [*] } end lemma mem_balance1_node_of_mem_right {x t} (v) (s : rbnode α) : x ∈ t → x ∈ balance1_node s v t := begin intros, cases s; simp [*], all_goals { apply balance.cases s_lchild s_val s_rchild; intros; simp [*] } end lemma mem_balance2_node_of_mem_right {x t} (v) (s : rbnode α) : x ∈ t → x ∈ balance2_node s v t := begin intros, cases s; simp [*], all_goals { apply balance.cases s_lchild s_val s_rchild; intros; simp [*] } end lemma mem_balance1_node_of_incomp {x v} (s t) : (¬ lt x v ∧ ¬ lt v x) → s ≠ leaf → x ∈ balance1_node s v t := begin intros, cases s; simp, { contradiction }, all_goals { apply balance.cases s_lchild s_val s_rchild; intros; simp [*] } end lemma mem_balance2_node_of_incomp {x v} (s t) : (¬ lt v x ∧ ¬ lt x v) → s ≠ leaf → x ∈ balance2_node s v t := begin intros, cases s; simp, { contradiction }, all_goals { apply balance.cases s_lchild s_val s_rchild; intros; simp [*] } end lemma ins_ne_leaf (t : rbnode α) (x : α) : t.ins lt x ≠ leaf := begin apply ins.induction lt t x, any_goals { intros, simp [ins, *], contradiction}, { intros, simp [ins, *], apply balance1_node_ne_leaf, assumption }, { intros, simp [ins, *], apply balance2_node_ne_leaf, assumption }, end lemma insert_ne_leaf (t : rbnode α) (x : α) : insert lt t x ≠ leaf := begin simp [insert], cases he : ins lt t x; cases get_color t; simp [mk_insert_result], { have := ins_ne_leaf lt t x, contradiction }, any_goals { contradiction }, { exact absurd he (ins_ne_leaf _ _ _) } end lemma mem_ins_of_incomp (t : rbnode α) {x y : α} : ∀ h : ¬ lt x y ∧ ¬ lt y x, x ∈ t.ins lt y := begin with_cases { apply ins.induction lt t y; intros; simp [ins, *] }, case is_black_lt_red { have := ih h, apply mem_balance1_node_of_mem_left, assumption }, case is_black_gt_red { have := ih h, apply mem_balance2_node_of_mem_left, assumption } end lemma mem_ins_of_mem [is_strict_weak_order α lt] {t : rbnode α} (z : α) : ∀ {x} (h : x ∈ t), x ∈ t.ins lt z := begin with_cases { apply ins.induction lt t z; intros; simp [ins, *] at *; try { contradiction }; blast_disjs }, case is_red_eq or.inr or.inl { have := incomp_trans_of lt h ⟨hc.2, hc.1⟩, simp [this] }, case is_black_lt_red or.inl { apply mem_balance1_node_of_mem_left, apply ih h }, case is_black_lt_red or.inr or.inl { have := ins_ne_leaf lt a z, apply mem_balance1_node_of_incomp, cases h, all_goals { simp [*] } }, case is_black_lt_red or.inr or.inr { apply mem_balance1_node_of_mem_right, assumption }, case is_black_eq or.inr or.inl { have := incomp_trans_of lt hc ⟨h.2, h.1⟩, simp [this] }, case is_black_gt_red or.inl { apply mem_balance2_node_of_mem_right, assumption }, case is_black_gt_red or.inr or.inl { have := ins_ne_leaf lt a z, apply mem_balance2_node_of_incomp, cases h, simp [*], apply ins_ne_leaf }, case is_black_gt_red or.inr or.inr { apply mem_balance2_node_of_mem_left, apply ih h }, -- remaining cases are easy any_goals { intros, simp [h], done }, all_goals { intros, simp [ih h], done }, end lemma mem_mk_insert_result {a t} (c) : mem lt a t → mem lt a (mk_insert_result c t) := by intros; cases c; cases t; simp [mk_insert_result, mem, *] at * lemma mem_of_mem_mk_insert_result {a t c} : mem lt a (mk_insert_result c t) → mem lt a t := by cases t; cases c; simp [mk_insert_result, mem]; intros; assumption lemma mem_insert_of_incomp (t : rbnode α) {x y : α} : ∀ h : ¬ lt x y ∧ ¬ lt y x, x ∈ t.insert lt y := by intros; unfold insert; apply mem_mk_insert_result; apply mem_ins_of_incomp; assumption lemma mem_insert_of_mem [is_strict_weak_order α lt] {t x} (z) : x ∈ t → x ∈ t.insert lt z := by intros; apply mem_mk_insert_result; apply mem_ins_of_mem; assumption lemma of_mem_balance1_node [is_strict_weak_order α lt] {x s v t} : x ∈ balance1_node s v t → x ∈ s ∨ (¬ lt x v ∧ ¬ lt v x) ∨ x ∈ t := begin cases s; simp, { intros, simp [*] }, all_goals { apply balance.cases s_lchild s_val s_rchild; intros; simp [*] at *; blast_disjs; simp [*] } end lemma of_mem_balance2_node [is_strict_weak_order α lt] {x s v t} : x ∈ balance2_node s v t → x ∈ s ∨ (¬ lt x v ∧ ¬ lt v x) ∨ x ∈ t := begin cases s; simp, { intros, simp [*] }, all_goals { apply balance.cases s_lchild s_val s_rchild; intros; simp [*] at *; blast_disjs; simp [*] } end lemma equiv_or_mem_of_mem_ins [is_strict_weak_order α lt] {t : rbnode α} {x z} : ∀ (h : x ∈ t.ins lt z), x ≈[lt] z ∨ x ∈ t := begin with_cases { apply ins.induction lt t z; intros; simp [ins, strict_weak_order.equiv, *] at *; blast_disjs }, case is_black_lt_red { have h' := of_mem_balance1_node lt h, blast_disjs, have := ih h', blast_disjs, all_goals { simp [h, *] } }, case is_black_gt_red { have h' := of_mem_balance2_node lt h, blast_disjs, have := ih h', blast_disjs, all_goals { simp [h, *] }}, -- All other goals can be solved by the following tactics any_goals { intros, simp [h] }, all_goals { intros, have ih := ih h, cases ih; simp [*], done }, end lemma equiv_or_mem_of_mem_insert [is_strict_weak_order α lt] {t : rbnode α} {x z} : ∀ (h : x ∈ t.insert lt z), x ≈[lt] z ∨ x ∈ t := begin simp [insert], intros, apply equiv_or_mem_of_mem_ins, exact mem_of_mem_mk_insert_result lt h end local attribute [simp] mem_exact lemma mem_exact_balance1_node_of_mem_exact {x s} (v) (t : rbnode α) : mem_exact x s → mem_exact x (balance1_node s v t) := begin cases s; simp, all_goals { apply balance.cases s_lchild s_val s_rchild; intros; simp [*] at *; blast_disjs; simp [*] } end lemma mem_exact_balance2_node_of_mem_exact {x s} (v) (t : rbnode α) : mem_exact x s → mem_exact x (balance2_node s v t) := begin cases s; simp, all_goals { apply balance.cases s_lchild s_val s_rchild; intros; simp [*] at *; blast_disjs; simp [*] } end lemma find_balance1_node [is_strict_weak_order α lt] {x y z t s} : ∀ {lo hi}, is_searchable lt t lo (some z) → is_searchable lt s (some z) hi → find lt t y = some x → y ≈[lt] x → find lt (balance1_node t z s) y = some x := begin intros _ _ hs₁ hs₂ heq heqv, have hs := is_searchable_balance1_node lt hs₁ hs₂, have := eq.trans (find_eq_find_of_eqv hs₁ heqv.symm) heq, have := iff.mpr (find_correct_exact hs₁) this, have := mem_exact_balance1_node_of_mem_exact z s this, have := iff.mp (find_correct_exact hs) this, exact eq.trans (find_eq_find_of_eqv hs heqv) this end lemma find_balance2_node [is_strict_weak_order α lt] {x y z s t} [is_trans α lt] : ∀ {lo hi}, is_searchable lt s lo (some z) → is_searchable lt t (some z) hi → find lt t y = some x → y ≈[lt] x → find lt (balance2_node t z s) y = some x := begin intros _ _ hs₁ hs₂ heq heqv, have hs := is_searchable_balance2_node lt hs₁ hs₂, have := eq.trans (find_eq_find_of_eqv hs₂ heqv.symm) heq, have := iff.mpr (find_correct_exact hs₂) this, have := mem_exact_balance2_node_of_mem_exact z s this, have := iff.mp (find_correct_exact hs) this, exact eq.trans (find_eq_find_of_eqv hs heqv) this end /- Auxiliary lemma -/ lemma ite_eq_of_not_lt [is_strict_order α lt] {a b} {β : Type v} (t s : β) (h : lt b a) : (if lt a b then t else s) = s := begin have := not_lt_of_lt h, simp [*] end local attribute [simp] ite_eq_of_not_lt private meta def simp_fi : tactic unit := `[simp [find, ins, *, cmp_using]] lemma find_ins_of_eqv [is_strict_weak_order α lt] {x y : α} {t : rbnode α} (he : x ≈[lt] y) : ∀ {lo hi} (hs : is_searchable lt t lo hi) (hlt₁ : lift lt lo (some x)) (hlt₂ : lift lt (some x) hi), find lt (ins lt t x) y = some x := begin simp [strict_weak_order.equiv] at he, apply ins.induction lt t x; intros, { simp_fi }, all_goals { simp at hc, cases hs }, { have := lt_of_incomp_of_lt he.swap hc, have := ih hs_hs₁ hlt₁ hc, simp_fi }, { simp_fi }, { have := lt_of_lt_of_incomp hc he, have := ih hs_hs₂ hc hlt₂, simp_fi }, { simp_fi, have := is_searchable_ins lt hs_hs₁ hlt₁ hc, apply find_balance1_node lt this hs_hs₂ (ih hs_hs₁ hlt₁ hc) he.symm }, { have := lt_of_incomp_of_lt he.swap hc, have := ih hs_hs₁ hlt₁ hc, simp_fi }, { simp_fi }, { simp_fi, have := is_searchable_ins lt hs_hs₂ hc hlt₂, apply find_balance2_node lt hs_hs₁ this (ih hs_hs₂ hc hlt₂) he.symm }, { have := lt_of_lt_of_incomp hc he, have := ih hs_hs₂ hc hlt₂, simp_fi } end lemma find_mk_insert_result (c : color) (t : rbnode α) (x : α) : find lt (mk_insert_result c t) x = find lt t x := begin cases t; cases c; simp [mk_insert_result], { simp [find], cases cmp_using lt x t_val; simp [find] } end lemma find_insert_of_eqv [is_strict_weak_order α lt] {x y : α} {t : rbnode α} (he : x ≈[lt] y) : is_searchable lt t none none → find lt (insert lt t x) y = some x := begin intro hs, simp [insert, find_mk_insert_result], apply find_ins_of_eqv lt he hs; simp end lemma weak_trichotomous (x y) {p : Prop} (is_lt : ∀ h : lt x y, p) (is_eqv : ∀ h : ¬ lt x y ∧ ¬ lt y x, p) (is_gt : ∀ h : lt y x, p) : p := begin by_cases lt x y; by_cases lt y x, any_goals { apply is_lt; assumption }, any_goals { apply is_gt; assumption }, any_goals { apply is_eqv, constructor; assumption } end section find_ins_of_not_eqv section simp_aux_lemmas lemma find_black_eq_find_red {l y r x} : find lt (black_node l y r) x = find lt (red_node l y r) x := begin simp [find], all_goals { cases cmp_using lt x y; simp [find] } end lemma find_red_of_lt {l y r x} (h : lt x y) : find lt (red_node l y r) x = find lt l x := by simp [find, cmp_using, *] lemma find_red_of_gt [is_strict_order α lt] {l y r x} (h : lt y x) : find lt (red_node l y r) x = find lt r x := begin have := not_lt_of_lt h, simp [find, cmp_using, *] end lemma find_red_of_incomp {l y r x} (h : ¬ lt x y ∧ ¬ lt y x) : find lt (red_node l y r) x = some y := by simp [find, cmp_using, *] end simp_aux_lemmas local attribute [simp] find_black_eq_find_red find_red_of_lt find_red_of_lt find_red_of_gt find_red_of_incomp variable [is_strict_weak_order α lt] lemma find_balance1_lt {l r t v x y lo hi} (h : lt x y) (hl : is_searchable lt l lo (some v)) (hr : is_searchable lt r (some v) (some y)) (ht : is_searchable lt t (some y) hi) : find lt (balance1 l v r y t) x = find lt (red_node l v r) x := begin with_cases { revert hl hr ht, apply balance.cases l v r; intros; simp [*]; is_searchable_tactic }, case red_left : _ _ _ z r { apply weak_trichotomous lt z x; intros; simp [*] }, case red_right : l_left l_val l_right z r { with_cases { apply weak_trichotomous lt z x; intro h' }, case is_lt { have := trans_of lt (lo_lt_hi hr_hs₁) h', simp [*] }, case is_eqv { have : lt l_val x := lt_of_lt_of_incomp (lo_lt_hi hr_hs₁) h', simp [*] }, case is_gt { apply weak_trichotomous lt l_val x; intros; simp [*] } } end meta def ins_ne_leaf_tac := `[apply ins_ne_leaf] lemma find_balance1_node_lt {t s x y lo hi} (hlt : lt y x) (ht : is_searchable lt t lo (some x)) (hs : is_searchable lt s (some x) hi) (hne : t ≠ leaf . ins_ne_leaf_tac) : find lt (balance1_node t x s) y = find lt t y := begin cases t; simp [balance1_node], { contradiction }, all_goals { intros, is_searchable_tactic, apply find_balance1_lt, assumption' } end lemma find_balance1_gt {l r t v x y lo hi} (h : lt y x) (hl : is_searchable lt l lo (some v)) (hr : is_searchable lt r (some v) (some y)) (ht : is_searchable lt t (some y) hi) : find lt (balance1 l v r y t) x = find lt t x := begin with_cases { revert hl hr ht, apply balance.cases l v r; intros; simp [*]; is_searchable_tactic }, case red_left : _ _ _ z { have := trans_of lt (lo_lt_hi hr) h, simp [*] }, case red_right : _ _ _ z { have := trans_of lt (lo_lt_hi hr_hs₂) h, simp [*] } end lemma find_balance1_node_gt {t s x y lo hi} (h : lt x y) (ht : is_searchable lt t lo (some x)) (hs : is_searchable lt s (some x) hi) (hne : t ≠ leaf . ins_ne_leaf_tac) : find lt (balance1_node t x s) y = find lt s y := begin cases t; simp [balance1_node], all_goals { intros, is_searchable_tactic, apply find_balance1_gt, assumption' } end lemma find_balance1_eqv {l r t v x y lo hi} (h : ¬ lt x y ∧ ¬ lt y x) (hl : is_searchable lt l lo (some v)) (hr : is_searchable lt r (some v) (some y)) (ht : is_searchable lt t (some y) hi) : find lt (balance1 l v r y t) x = some y := begin with_cases { revert hl hr ht, apply balance.cases l v r; intros; simp [*]; is_searchable_tactic }, case red_left : _ _ _ z { have : lt z x := lt_of_lt_of_incomp (lo_lt_hi hr) h.swap, simp [*] }, case red_right : _ _ _ z { have : lt z x := lt_of_lt_of_incomp (lo_lt_hi hr_hs₂) h.swap, simp [*] } end lemma find_balance1_node_eqv {t s x y lo hi} (h : ¬ lt x y ∧ ¬ lt y x) (ht : is_searchable lt t lo (some y)) (hs : is_searchable lt s (some y) hi) (hne : t ≠ leaf . ins_ne_leaf_tac) : find lt (balance1_node t y s) x = some y := begin cases t; simp [balance1_node], { contradiction }, all_goals { intros, is_searchable_tactic, apply find_balance1_eqv, assumption' } end lemma find_balance2_lt {l v r t x y lo hi} (h : lt x y) (hl : is_searchable lt l (some y) (some v)) (hr : is_searchable lt r (some v) hi) (ht : is_searchable lt t lo (some y)) : find lt (balance2 l v r y t) x = find lt t x := begin with_cases { revert hl hr ht, apply balance.cases l v r; intros; simp [*]; is_searchable_tactic }, case red_left { have := trans h (lo_lt_hi hl_hs₁), simp [*] }, case red_right { have := trans h (lo_lt_hi hl), simp [*] } end lemma find_balance2_node_lt {s t x y lo hi} (h : lt x y) (ht : is_searchable lt t (some y) hi) (hs : is_searchable lt s lo (some y)) (hne : t ≠ leaf . ins_ne_leaf_tac) : find lt (balance2_node t y s) x = find lt s x := begin cases t; simp [balance2_node], all_goals { intros, is_searchable_tactic, apply find_balance2_lt, assumption' } end lemma find_balance2_gt {l v r t x y lo hi} (h : lt y x) (hl : is_searchable lt l (some y) (some v)) (hr : is_searchable lt r (some v) hi) (ht : is_searchable lt t lo (some y)) : find lt (balance2 l v r y t) x = find lt (red_node l v r) x := begin with_cases { revert hl hr ht, apply balance.cases l v r; intros; simp [*]; is_searchable_tactic }, case red_left : _ val _ z { with_cases { apply weak_trichotomous lt val x; intro h'; simp [*] }, case is_lt { apply weak_trichotomous lt z x; intros; simp [*] }, case is_eqv { have : lt x z := lt_of_incomp_of_lt h'.swap (lo_lt_hi hl_hs₂), simp [*] }, case is_gt { have := trans h' (lo_lt_hi hl_hs₂), simp [*] } }, case red_right : _ val { apply weak_trichotomous lt val x; intros; simp [*] } end lemma find_balance2_node_gt {s t x y lo hi} (h : lt y x) (ht : is_searchable lt t (some y) hi) (hs : is_searchable lt s lo (some y)) (hne : t ≠ leaf . ins_ne_leaf_tac) : find lt (balance2_node t y s) x = find lt t x := begin cases t; simp [balance2_node], { contradiction }, all_goals { intros, is_searchable_tactic, apply find_balance2_gt, assumption' } end lemma find_balance2_eqv {l v r t x y lo hi} (h : ¬ lt x y ∧ ¬ lt y x) (hl : is_searchable lt l (some y) (some v)) (hr : is_searchable lt r (some v) hi) (ht : is_searchable lt t lo (some y)) : find lt (balance2 l v r y t) x = some y := begin with_cases { revert hl hr ht, apply balance.cases l v r; intros; simp [*]; is_searchable_tactic }, case red_left { have := lt_of_incomp_of_lt h (lo_lt_hi hl_hs₁), simp [*] }, case red_right { have := lt_of_incomp_of_lt h (lo_lt_hi hl), simp [*] } end lemma find_balance2_node_eqv {t s x y lo hi} (h : ¬ lt x y ∧ ¬ lt y x) (ht : is_searchable lt t (some y) hi) (hs : is_searchable lt s lo (some y)) (hne : t ≠ leaf . ins_ne_leaf_tac) : find lt (balance2_node t y s) x = some y := begin cases t; simp [balance2_node], { contradiction }, all_goals { intros, is_searchable_tactic, apply find_balance2_eqv, assumption' } end lemma find_ins_of_disj {x y : α} {t : rbnode α} (hn : lt x y ∨ lt y x) : ∀ {lo hi} (hs : is_searchable lt t lo hi) (hlt₁ : lift lt lo (some x)) (hlt₂ : lift lt (some x) hi), find lt (ins lt t x) y = find lt t y := begin apply ins.induction lt t x; intros, { cases hn, all_goals { simp [find, ins, cmp_using, *] } }, all_goals { simp at hc, cases hs }, { have := ih hs_hs₁ hlt₁ hc, simp_fi }, { cases hn, { have := lt_of_incomp_of_lt hc.symm hn, simp_fi }, { have := lt_of_lt_of_incomp hn hc, simp_fi } }, { have := ih hs_hs₂ hc hlt₂, cases hn, { have := trans hc hn, simp_fi }, { simp_fi } }, { have ih := ih hs_hs₁ hlt₁ hc, cases hn, { cases hc' : cmp_using lt y y_1; simp at hc', { have hsi := is_searchable_ins lt hs_hs₁ hlt₁ (trans_of lt hn hc'), have := find_balance1_node_lt lt hc' hsi hs_hs₂, simp_fi }, { have hlt := lt_of_lt_of_incomp hn hc', have hsi := is_searchable_ins lt hs_hs₁ hlt₁ hlt, have := find_balance1_node_eqv lt hc' hsi hs_hs₂, simp_fi }, { have hsi := is_searchable_ins lt hs_hs₁ hlt₁ hc, have := find_balance1_node_gt lt hc' hsi hs_hs₂, simp [*], simp_fi } }, { have hlt := trans hn hc, have hsi := is_searchable_ins lt hs_hs₁ hlt₁ hc, have := find_balance1_node_lt lt hlt hsi hs_hs₂, simp_fi } }, { have := ih hs_hs₁ hlt₁ hc, simp_fi }, { cases hn, { have := lt_of_incomp_of_lt hc.swap hn, simp_fi }, { have := lt_of_lt_of_incomp hn hc, simp_fi } }, { have ih := ih hs_hs₂ hc hlt₂, cases hn, { have hlt := trans hc hn, simp_fi, have hsi := is_searchable_ins lt hs_hs₂ hc hlt₂, have := find_balance2_node_gt lt hlt hsi hs_hs₁, simp_fi }, { simp_fi, cases hc' : cmp_using lt y y_1; simp at hc', { have hsi := is_searchable_ins lt hs_hs₂ hc hlt₂, have := find_balance2_node_lt lt hc' hsi hs_hs₁, simp_fi }, { have hlt := lt_of_incomp_of_lt hc'.swap hn, have hsi := is_searchable_ins lt hs_hs₂ hlt hlt₂, have := find_balance2_node_eqv lt hc' hsi hs_hs₁, simp_fi }, { have hsi := is_searchable_ins lt hs_hs₂ hc hlt₂, have := find_balance2_node_gt lt hc' hsi hs_hs₁, simp_fi } } }, { cases hn, { have := trans hc hn, have := ih hs_hs₂ hc hlt₂, simp_fi }, { have ih := ih hs_hs₂ hc hlt₂, simp_fi } } end end find_ins_of_not_eqv lemma find_insert_of_disj [is_strict_weak_order α lt] {x y : α} {t : rbnode α} (hd : lt x y ∨ lt y x) : is_searchable lt t none none → find lt (insert lt t x) y = find lt t y := begin intro hs, simp [insert, find_mk_insert_result], apply find_ins_of_disj lt hd hs; simp end lemma find_insert_of_not_eqv [is_strict_weak_order α lt] {x y : α} {t : rbnode α} (hn : ¬ x ≈[lt] y) : is_searchable lt t none none → find lt (insert lt t x) y = find lt t y := begin intro hs, simp [insert, find_mk_insert_result], have he : lt x y ∨ lt y x, { simp [strict_weak_order.equiv, decidable.not_and_iff_or_not, decidable.not_not_iff] at hn, assumption }, apply find_ins_of_disj lt he hs; simp end end membership_lemmas section is_red_black variables {α : Type u} open nat color inductive is_bad_red_black : rbnode α → nat → Prop | bad_red {c₁ c₂ n l r v} (rb_l : is_red_black l c₁ n) (rb_r : is_red_black r c₂ n) : is_bad_red_black (red_node l v r) n lemma balance1_rb {l r t : rbnode α} {y v : α} {c_l c_r c_t n} : is_red_black l c_l n → is_red_black r c_r n → is_red_black t c_t n → ∃ c, is_red_black (balance1 l y r v t) c (succ n) := by intros h₁ h₂ _; cases h₁; cases h₂; repeat { assumption <|> constructor } lemma balance2_rb {l r t : rbnode α} {y v : α} {c_l c_r c_t n} : is_red_black l c_l n → is_red_black r c_r n → is_red_black t c_t n → ∃ c, is_red_black (balance2 l y r v t) c (succ n) := by intros h₁ h₂ _; cases h₁; cases h₂; repeat { assumption <|> constructor } lemma balance1_node_rb {t s : rbnode α} {y : α} {c n} : is_bad_red_black t n → is_red_black s c n → ∃ c, is_red_black (balance1_node t y s) c (succ n) := by intros h _; cases h; simp [balance1_node]; apply balance1_rb; assumption' lemma balance2_node_rb {t s : rbnode α} {y : α} {c n} : is_bad_red_black t n → is_red_black s c n → ∃ c, is_red_black (balance2_node t y s) c (succ n) := by intros h _; cases h; simp [balance2_node]; apply balance2_rb; assumption' def ins_rb_result : rbnode α → color → nat → Prop | t red n := is_bad_red_black t n | t black n := ∃ c, is_red_black t c n variables {lt : α → α → Prop} [decidable_rel lt] lemma of_get_color_eq_red {t : rbnode α} {c n} : get_color t = red → is_red_black t c n → c = red := begin intros h₁ h₂, cases h₂; simp [get_color] at h₁; contradiction end lemma of_get_color_ne_red {t : rbnode α} {c n} : get_color t ≠ red → is_red_black t c n → c = black := begin intros h₁ h₂, cases h₂; simp [get_color] at h₁; contradiction end variable (lt) lemma ins_rb {t : rbnode α} (x) : ∀ {c n} (h : is_red_black t c n), ins_rb_result (ins lt t x) c n := begin apply ins.induction lt t x; intros; cases h; simp [ins, *, ins_rb_result], { repeat { constructor } }, { specialize ih h_rb_l, cases ih, constructor; assumption }, { constructor; assumption }, { specialize ih h_rb_r, cases ih, constructor; assumption }, { specialize ih h_rb_l, have := of_get_color_eq_red hr h_rb_l, subst h_c₁, simp [ins_rb_result] at ih, apply balance1_node_rb; assumption }, { specialize ih h_rb_l, have := of_get_color_ne_red hnr h_rb_l, subst h_c₁, simp [ins_rb_result] at ih, cases ih, constructor, constructor; assumption }, { constructor, constructor; assumption }, { specialize ih h_rb_r, have := of_get_color_eq_red hr h_rb_r, subst h_c₂, simp [ins_rb_result] at ih, apply balance2_node_rb; assumption }, { specialize ih h_rb_r, have := of_get_color_ne_red hnr h_rb_r, subst h_c₂, simp [ins_rb_result] at ih, cases ih, constructor, constructor; assumption } end def insert_rb_result : rbnode α → color → nat → Prop | t red n := is_red_black t black (succ n) | t black n := ∃ c, is_red_black t c n lemma insert_rb {t : rbnode α} (x) {c n} (h : is_red_black t c n) : insert_rb_result (insert lt t x) c n := begin simp [insert], have hi := ins_rb lt x h, generalize he : ins lt t x = r, simp [he] at hi, cases h; simp [get_color, ins_rb_result, insert_rb_result, mk_insert_result] at *, assumption', { cases hi, simp [mk_insert_result], constructor; assumption } end lemma insert_is_red_black {t : rbnode α} {c n} (x) : is_red_black t c n → ∃ c n, is_red_black (insert lt t x) c n := begin intro h, have := insert_rb lt x h, cases c; simp [insert_rb_result] at this, { constructor, constructor, assumption }, { cases this, constructor, constructor, assumption } end end is_red_black end rbnode
0830f598de0996819f32093083ef13eddef61a5c
e5c11e5a7d990ce404047c2bd848eeafac3c0a85
/src/noetherian.lean
e6aa496e260dd756f860a8c435df85213a44e882
[ "LPPL-1.3c" ]
permissive
lean-forward/class-number
9ec63c24845e46efc8fa8b15324d0815918292c7
4fccf36d5e0e16accae84c16df77a3839ad964e4
refs/heads/main
1,686,927,014,542
1,624,886,724,000
1,624,886,724,000
327,319,245
2
0
null
null
null
null
UTF-8
Lean
false
false
30,497
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 algebraic_geometry.prime_spectrum import data.multiset.finset_ops import linear_algebra.linear_independent import order.order_iso_nat import order.compactly_generated import ring_theory.ideal.operations /-! # 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] * [samuel] ## 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 lemma singleton_span_is_compact_element (x : M) : complete_lattice.is_compact_element (span R {x} : submodule R M) := begin rw complete_lattice.is_compact_element_iff_le_of_directed_Sup_le, intros d hemp hdir hsup, have : x ∈ Sup d, from (le_def.mp hsup) (mem_span_singleton_self x), obtain ⟨y, ⟨hyd, hxy⟩⟩ := (mem_Sup_of_directed hemp hdir).mp this, exact ⟨y, ⟨hyd, by simpa only [span_le, singleton_subset_iff]⟩⟩, end /-- Finitely generated submodules are precisely compact elements in the submodule lattice -/ theorem fg_iff_compact (s : submodule R M) : s.fg ↔ complete_lattice.is_compact_element s := begin classical, -- Introduce shorthand for span of an element let sp : M → submodule R M := λ a, span R {a}, -- Trivial rewrite lemma; a small hack since simp (only) & rw can't accomplish this smoothly. have supr_rw : ∀ t : finset M, (⨆ x ∈ t, sp x) = (⨆ x ∈ (↑t : set M), sp x), from λ t, by refl, split, { rintro ⟨t, rfl⟩, rw [span_eq_supr_of_singleton_spans, ←supr_rw, ←(finset.sup_eq_supr t sp)], apply complete_lattice.finset_sup_compact_of_compact, exact λ n _, singleton_span_is_compact_element n, }, { intro h, -- s is the Sup of the spans of its elements. have sSup : s = Sup (sp '' ↑s), by rw [Sup_eq_supr, supr_image, ←span_eq_supr_of_singleton_spans, eq_comm, span_eq], -- by h, s is then below (and equal to) the sup of the spans of finitely many elements. obtain ⟨u, ⟨huspan, husup⟩⟩ := h (sp '' ↑s) (le_of_eq sSup), have ssup : s = u.sup id, { suffices : u.sup id ≤ s, from le_antisymm husup this, rw [sSup, finset.sup_eq_Sup], exact Sup_le_Sup huspan, }, obtain ⟨t, ⟨hts, rfl⟩⟩ := finset.subset_image_iff.mp huspan, rw [←finset.sup_finset_image, function.comp.left_id, finset.sup_eq_supr, supr_rw, ←span_eq_supr_of_singleton_spans, eq_comm] at ssup, exact ⟨t, ssup⟩, }, end instance : is_compactly_generated (submodule R M) := ⟨λ s, ⟨(λ x, span R {x}) '' s, ⟨λ t ht, begin rcases (set.mem_image _ _ _).1 ht with ⟨x, hx, rfl⟩, apply singleton_span_is_compact_element, end, by rw [Sup_eq_supr, supr_image, ←span_eq_supr_of_singleton_spans, span_eq]⟩⟩⟩ 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_is_noetherian_top (h : is_noetherian R (⊤ : submodule R M)) : is_noetherian R M := is_noetherian_of_linear_equiv (linear_equiv.of_top _ rfl) 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 refine rel_embedding.well_founded_iff_no_descending_seq.2 _, 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.2)).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.2 (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'] /-- If `∀ I > J, P I` implies `P J`, then `P` holds for all submodules. -/ lemma is_noetherian.induction {R M} [ring R] [add_comm_group M] [module R M] [is_noetherian R M] {P : submodule R M → Prop} (hgt : ∀ I, (∀ J > I, P J) → P I) (I : submodule R M) : P I := well_founded.recursion (well_founded_submodule_gt R M) I hgt /-- A ring is Noetherian if it is Noetherian as a module over itself, i.e. all its ideals are finitely generated. -/ class is_noetherian_ring (R) [ring R] extends is_noetherian R R : Prop theorem is_noetherian_ring_iff {R} [ring R] : is_noetherian_ring R ↔ is_noetherian R R := ⟨λ h, h.1, @is_noetherian_ring.mk _ _⟩ @[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 is_noetherian_ring_iff.2 (ring.is_noetherian_of_fintype R R) 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_is_scalar_tower (R) {S M} [comm_ring R] [ring S] [add_comm_group M] [algebra R S] [module S M] [module R M] [is_scalar_tower R S M] (h : is_noetherian R M) : is_noetherian S M := begin rw is_noetherian_iff_well_founded at h ⊢, exact (@scalar_tower_order_embedding R _ S _ _ M _ _ _ _).dual.well_founded 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_iff, is_noetherian_iff_well_founded] at H ⊢, exact order_embedding.well_founded (ideal.order_embedding_of_surjective f hf).dual H, end section local attribute [instance] subset.comm_ring 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 end 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 section primes variables {R : Type*} [comm_ring R] [is_noetherian_ring R] /--In a noetherian ring, every ideal contains a product of prime ideals ([samuel, § 3.3, Lemma 3])-/ lemma exists_prime_spectrum_prod_le (I : ideal R) : ∃ (Z : multiset (prime_spectrum R)), multiset.prod (Z.map (coe : subtype _ → ideal R)) ≤ I := begin refine is_noetherian.induction (λ (M : ideal R) hgt, _) I, by_cases h_prM : M.is_prime, { use {⟨M, h_prM⟩}, rw [multiset.map_singleton, multiset.singleton_eq_singleton, multiset.prod_singleton, subtype.coe_mk], exact le_rfl }, by_cases htop : M = ⊤, { rw htop, exact ⟨0, le_top⟩ }, have lt_add : ∀ z ∉ M, M < M + span R {z}, { intros z hz, refine lt_of_le_of_ne le_sup_left (λ m_eq, hz _), rw m_eq, exact mem_sup_right (mem_span_singleton_self z) }, obtain ⟨x, hx, y, hy, hxy⟩ := (ideal.not_is_prime_iff.mp h_prM).resolve_left htop, obtain ⟨Wx, h_Wx⟩ := hgt (M + span R {x}) (lt_add _ hx), obtain ⟨Wy, h_Wy⟩ := hgt (M + span R {y}) (lt_add _ hy), use Wx + Wy, rw [multiset.map_add, multiset.prod_add], apply le_trans (submodule.mul_le_mul h_Wx h_Wy), rw add_mul, apply sup_le (show M * (M + span R {y}) ≤ M, from ideal.mul_le_right), rw mul_add, apply sup_le (show span R {x} * M ≤ M, from ideal.mul_le_left), rwa [span_mul_span, singleton_mul_singleton, span_singleton_le_iff_mem], end variables {A : Type*} [integral_domain A] [is_noetherian_ring A] /--In a noetherian integral domain which is not a field, every non-zero ideal contains a non-zero product of prime ideals; in a field, the whole ring is a non-zero ideal containing only 0 as product or prime ideals ([samuel, § 3.3, Lemma 3]) -/ lemma exists_prime_spectrum_prod_le_and_ne_bot_of_domain (h_fA : ¬ is_field A) {I : ideal A} (h_nzI: I ≠ ⊥) : ∃ (Z : multiset (prime_spectrum A)), multiset.prod (Z.map (coe : subtype _ → ideal A)) ≤ I ∧ multiset.prod (Z.map (coe : subtype _ → ideal A)) ≠ ⊥ := begin revert h_nzI, refine is_noetherian.induction (λ (M : ideal A) hgt, _) I, intro h_nzM, have hA_nont : nontrivial A, apply is_integral_domain.to_nontrivial (integral_domain.to_is_integral_domain A), by_cases h_topM : M = ⊤, { rcases h_topM with rfl, obtain ⟨p_id, h_nzp, h_pp⟩ : ∃ (p : ideal A), p ≠ ⊥ ∧ p.is_prime, { apply ring.not_is_field_iff_exists_prime.mp h_fA }, use [({⟨p_id, h_pp⟩} : multiset (prime_spectrum A)), le_top], rwa [multiset.map_singleton, multiset.singleton_eq_singleton, multiset.prod_singleton, subtype.coe_mk] }, by_cases h_prM : M.is_prime, { use ({⟨M, h_prM⟩} : multiset (prime_spectrum A)), rw [multiset.map_singleton, multiset.singleton_eq_singleton, multiset.prod_singleton, subtype.coe_mk], exact ⟨le_rfl, h_nzM⟩ }, obtain ⟨x, hx, y, hy, h_xy⟩ := (ideal.not_is_prime_iff.mp h_prM).resolve_left h_topM, have lt_add : ∀ z ∉ M, M < M + span A {z}, { intros z hz, refine lt_of_le_of_ne le_sup_left (λ m_eq, hz _), rw m_eq, exact mem_sup_right (mem_span_singleton_self z) }, obtain ⟨Wx, h_Wx_le, h_Wx_ne⟩ := hgt (M + span A {x}) (lt_add _ hx) (ne_bot_of_gt (lt_add _ hx)), obtain ⟨Wy, h_Wy_le, h_Wx_ne⟩ := hgt (M + span A {y}) (lt_add _ hy) (ne_bot_of_gt (lt_add _ hy)), use Wx + Wy, rw [multiset.map_add, multiset.prod_add], refine ⟨le_trans (submodule.mul_le_mul h_Wx_le h_Wy_le) _, mt ideal.mul_eq_bot.mp _⟩, { rw add_mul, apply sup_le (show M * (M + span A {y}) ≤ M, from ideal.mul_le_right), rw mul_add, apply sup_le (show span A {x} * M ≤ M, from ideal.mul_le_left), rwa [span_mul_span, singleton_mul_singleton, span_singleton_le_iff_mem] }, { rintro (hx | hy); contradiction }, end end primes
f474a718066788557549401c8fc124f3887c7ba8
c82208eb338381e9469e9825729c5ffa58a7a338
/library.lean
35984a046ef5b31b684bc51902bd51b5a50d5c1f
[]
no_license
johoelzl/tc-log-parser
3c41db7db649d050caf3ce0ba06ea967df3d83ea
c27b5839f3941d63bb01750c7eefa95e94e83eed
refs/heads/master
1,587,954,495,855
1,553,252,706,000
1,553,252,706,000
173,995,391
0
0
null
null
null
null
UTF-8
Lean
false
false
912
lean
import linear_algebra.matrix import linear_algebra.dimension import algebra.pi_instances import linear_algebra.basic import topology.instances.nnreal import analysis.normed_space.basic class test (α : Type*) class mark (b : bool) instance test_init (α : Type*) [decidable_eq α] [mark ff] : test α := test.mk _ instance mark_tt : mark tt := mark.mk _ set_option trace.class_instances true set_option pp.proofs true example {α : Type} [fintype α] [discrete_field α] (n : ℕ) (A : finset (fin n → α)) : test (fin n) := begin tactic.trace "pre", apply_instance end /- instance t₁ (α : Type*) (x : α) (A : finset α) [decidable_eq α] [inhabited empty] : test {x // x ∈ A} := test.mk _ example {α : Type} [fintype α] [discrete_field α] (n : ℕ) (A : finset (fin n → α)) : normed_group (Π (i : {x // x ∈ A}), (λ (a : {x // x ∈ A}), α) i) := -- by apply_instance -/
f00c82d53597d5278004e1c4210f768ff5f7d219
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/analysis/measure_theory/borel_space.lean
4c50f6b9693a45c618b2e7b9aea5fc12c59fe926
[ "Apache-2.0" ]
permissive
kckennylau/mathlib
21fb810b701b10d6606d9002a4004f7672262e83
47b3477e20ffb5a06588dd3abb01fe0fe3205646
refs/heads/master
1,634,976,409,281
1,542,042,832,000
1,542,319,733,000
109,560,458
0
0
Apache-2.0
1,542,369,208,000
1,509,867,494,000
Lean
UTF-8
Lean
false
false
13,725
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 Borel (measurable) space -- the smallest σ-algebra generated by open sets It would be nice to encode this in the topological space type class, i.e. each topological space carries a measurable space, the Borel space. This would be similar how each uniform space carries a topological space. The idea is to allow definitional equality for product instances. We would like to have definitional equality for borel t₁ × borel t₂ = borel (t₁ × t₂) Unfortunately, this only holds if t₁ and t₂ are second-countable topologies. -/ import analysis.measure_theory.measurable_space analysis.real open classical set lattice real local attribute [instance] prop_decidable universes u v w x y variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} {ι : Sort y} {s t u : set α} namespace measure_theory open measurable_space topological_space @[instance] def borel (α : Type u) [topological_space α] : measurable_space α := generate_from {s : set α | is_open s} lemma borel_eq_generate_from_of_subbasis {s : set (set α)} [t : topological_space α] [second_countable_topology α] (hs : t = generate_from s) : borel α = generate_from s := le_antisymm (generate_from_le $ assume u (hu : t.is_open u), begin rw [hs] at hu, induction hu, case generate_open.basic : u hu { exact generate_measurable.basic u hu }, case generate_open.univ { exact @is_measurable.univ α (generate_from s) }, case generate_open.inter : s₁ s₂ _ _ hs₁ hs₂ { exact @is_measurable.inter α (generate_from s) _ _ hs₁ hs₂ }, case generate_open.sUnion : f hf ih { rcases is_open_sUnion_countable f (by rwa hs) with ⟨v, hv, vf, vu⟩, rw ← vu, exact @is_measurable.sUnion α (generate_from s) _ hv (λ x xv, ih _ (vf xv)) } end) (generate_from_le $ assume u hu, generate_measurable.basic _ $ show t.is_open u, by rw [hs]; exact generate_open.basic _ hu) lemma borel_eq_generate_Iio (α) [topological_space α] [second_countable_topology α] [linear_order α] [orderable_topology α] : borel α = generate_from (range Iio) := begin refine le_antisymm _ (generate_from_le _), { rw borel_eq_generate_from_of_subbasis (orderable_topology.topology_eq_generate_intervals α), have H : ∀ a:α, is_measurable (measurable_space.generate_from (range Iio)) (Iio a) := λ a, generate_measurable.basic _ ⟨_, rfl⟩, refine generate_from_le _, rintro _ ⟨a, rfl | rfl⟩; [skip, apply H], by_cases h : ∃ a', ∀ b, a < b ↔ a' ≤ b, { rcases h with ⟨a', ha'⟩, rw (_ : {b | a < b} = -Iio a'), {exact (H _).compl _}, simp [set.ext_iff, ha'] }, { rcases is_open_Union_countable (λ a' : {a' : α // a < a'}, {b | a'.1 < b}) (λ a', is_open_lt' _) with ⟨v, ⟨hv⟩, vu⟩, simp [set.ext_iff] at vu, have : {b | a < b} = ⋃ x : v, -Iio x.1.1, { simp [set.ext_iff], refine λ x, ⟨λ ax, _, λ ⟨a', ⟨h, av⟩, ax⟩, lt_of_lt_of_le h ax⟩, rcases (vu x).2 _ with ⟨a', h₁, h₂⟩, { exact ⟨a', h₁, le_of_lt h₂⟩ }, refine not_imp_comm.1 (λ h, _) h, exact ⟨x, λ b, ⟨λ ab, le_of_not_lt (λ h', h ⟨b, ab, h'⟩), lt_of_lt_of_le ax⟩⟩ }, rw this, resetI, apply is_measurable.Union, exact λ _, (H _).compl _ } }, { simp, rintro _ a rfl, exact generate_measurable.basic _ is_open_Iio } end lemma borel_eq_generate_Ioi (α) [topological_space α] [second_countable_topology α] [linear_order α] [orderable_topology α] : borel α = generate_from (range (λ a, {x | a < x})) := begin refine le_antisymm _ (generate_from_le _), { rw borel_eq_generate_from_of_subbasis (orderable_topology.topology_eq_generate_intervals α), have H : ∀ a:α, is_measurable (measurable_space.generate_from (range (λ a, {x | a < x}))) {x | a < x} := λ a, generate_measurable.basic _ ⟨_, rfl⟩, refine generate_from_le _, rintro _ ⟨a, rfl | rfl⟩, {apply H}, by_cases h : ∃ a', ∀ b, b < a ↔ b ≤ a', { rcases h with ⟨a', ha'⟩, rw (_ : {b | b < a} = -{x | a' < x}), {exact (H _).compl _}, simp [set.ext_iff, ha'] }, { rcases is_open_Union_countable (λ a' : {a' : α // a' < a}, {b | b < a'.1}) (λ a', is_open_gt' _) with ⟨v, ⟨hv⟩, vu⟩, simp [set.ext_iff] at vu, have : {b | b < a} = ⋃ x : v, -{b | x.1.1 < b}, { simp [set.ext_iff], refine λ x, ⟨λ ax, _, λ ⟨a', ⟨h, av⟩, ax⟩, lt_of_le_of_lt ax h⟩, rcases (vu x).2 _ with ⟨a', h₁, h₂⟩, { exact ⟨a', h₁, le_of_lt h₂⟩ }, refine not_imp_comm.1 (λ h, _) h, exact ⟨x, λ b, ⟨λ ab, le_of_not_lt (λ h', h ⟨b, ab, h'⟩), λ h, lt_of_le_of_lt h ax⟩⟩ }, rw this, resetI, apply is_measurable.Union, exact λ _, (H _).compl _ } }, { simp, rintro _ a rfl, exact generate_measurable.basic _ (is_open_lt' _) } end lemma borel_comap {f : α → β} {t : topological_space β} : @borel α (t.induced f) = (@borel β t).comap f := calc @borel α (t.induced f) = measurable_space.generate_from (preimage f '' {s | is_open s }) : congr_arg measurable_space.generate_from $ set.ext $ assume s : set α, show (t.induced f).is_open s ↔ s ∈ preimage f '' {s | is_open s}, by simp [topological_space.induced, set.image, eq_comm]; refl ... = (@borel β t).comap f : comap_generate_from.symm section variables [topological_space α] lemma is_measurable_of_is_open : is_open s → is_measurable s := generate_measurable.basic s lemma is_measurable_interior : is_measurable (interior s) := is_measurable_of_is_open is_open_interior lemma is_measurable_of_is_closed (h : is_closed s) : is_measurable s := is_measurable.compl_iff.1 $ is_measurable_of_is_open h lemma is_measurable_closure : is_measurable (closure s) := is_measurable_of_is_closed is_closed_closure lemma measurable_of_continuous [topological_space β] {f : α → β} (h : continuous f) : measurable f := measurable_generate_from $ assume t ht, is_measurable_of_is_open $ h t ht lemma borel_prod_le [topological_space β] : prod.measurable_space ≤ borel (α × β) := sup_le (comap_le_iff_le_map.mpr $ measurable_of_continuous continuous_fst) (comap_le_iff_le_map.mpr $ measurable_of_continuous continuous_snd) lemma borel_prod [second_countable_topology α] [topological_space β] [second_countable_topology β] : prod.measurable_space = borel (α × β) := let ⟨a, ha₁, ha₂, ha₃, ha₄, ha₅⟩ := @is_open_generated_countable_inter α _ _ in let ⟨b, hb₁, hb₂, hb₃, hb₄, hb₅⟩ := @is_open_generated_countable_inter β _ _ in le_antisymm borel_prod_le begin have : prod.topological_space = generate_from {g | ∃u∈a, ∃v∈b, g = set.prod u v}, { rw [ha₅, hb₅], exact prod_generate_from_generate_from_eq ha₄ hb₄ }, rw [borel_eq_generate_from_of_subbasis this], exact generate_from_le (assume p ⟨u, hu, v, hv, eq⟩, have hu : is_open u, by rw [ha₅]; exact generate_open.basic _ hu, have hv : is_open v, by rw [hb₅]; exact generate_open.basic _ hv, eq.symm ▸ is_measurable_set_prod (is_measurable_of_is_open hu) (is_measurable_of_is_open hv)) end lemma measurable_of_continuous2 [topological_space α] [second_countable_topology α] [topological_space β] [second_countable_topology β] [topological_space γ] [measurable_space δ] {f : δ → α} {g : δ → β} {c : α → β → γ} (h : continuous (λp:α×β, c p.1 p.2)) (hf : measurable f) (hg : measurable g) : measurable (λa, c (f a) (g a)) := show measurable ((λp:α×β, c p.1 p.2) ∘ (λa, (f a, g a))), begin apply measurable.comp, { rw ← borel_prod, exact measurable_prod_mk hf hg }, { exact measurable_of_continuous h } end lemma measurable_add [add_monoid α] [topological_add_monoid α] [second_countable_topology α] [measurable_space β] {f : β → α} {g : β → α} : measurable f → measurable g → measurable (λa, f a + g a) := measurable_of_continuous2 continuous_add' lemma measurable_neg [add_group α] [topological_add_group α] [measurable_space β] {f : β → α} (hf : measurable f) : measurable (λa, - f a) := hf.comp (measurable_of_continuous continuous_neg') lemma measurable_sub [add_group α] [topological_add_group α] [second_countable_topology α] [measurable_space β] {f : β → α} {g : β → α} : measurable f → measurable g → measurable (λa, f a - g a) := measurable_of_continuous2 continuous_sub' lemma measurable_mul [monoid α] [topological_monoid α] [second_countable_topology α] [measurable_space β] {f : β → α} {g : β → α} : measurable f → measurable g → measurable (λa, f a * g a) := measurable_of_continuous2 continuous_mul' lemma measurable_le {α β} [topological_space α] [partial_order α] [ordered_topology α] [second_countable_topology α] [measurable_space β] {f : β → α} {g : β → α} (hf : measurable f) (hg : measurable g) : is_measurable {a | f a ≤ g a} := have is_measurable {p : α × α | p.1 ≤ p.2}, from is_measurable_of_is_closed (ordered_topology.is_closed_le' _), show is_measurable {a | (f a, g a).1 ≤ (f a, g a).2}, begin refine measurable.preimage _ this, rw ← borel_prod, exact measurable_prod_mk hf hg end -- generalize lemma measurable_coe_int_real : measurable (λa, a : ℤ → ℝ) := assume s (hs : is_measurable s), is_measurable_of_is_open $ by trivial section ordered_topology variables [linear_order α] [topological_space α] [ordered_topology α] {a b c : α} lemma is_measurable_Ioo : is_measurable (Ioo a b) := is_measurable_of_is_open is_open_Ioo lemma is_measurable_Iio : is_measurable (Iio a) := is_measurable_of_is_open is_open_Iio lemma is_measurable_Ico : is_measurable (Ico a b) := (is_measurable_of_is_closed $ is_closed_le continuous_const continuous_id).inter is_measurable_Iio end ordered_topology lemma measurable.is_lub {α} [topological_space α] [linear_order α] [orderable_topology α] [second_countable_topology α] {β} [measurable_space β] {ι} [encodable ι] {f : ι → β → α} {g : β → α} (hf : ∀ i, measurable (f i)) (hg : ∀ b, is_lub {a | ∃ i, f i b = a} (g b)) : measurable g := begin rw borel_eq_generate_Ioi α, apply measurable_generate_from, rintro _ ⟨a, rfl⟩, have : {b | a < g b} = ⋃ i, {b | a < f i b}, { simp [set.ext_iff], intro b, rw [lt_is_lub_iff (hg b)], exact ⟨λ ⟨_, ⟨i, rfl⟩, h⟩, ⟨i, h⟩, λ ⟨i, h⟩, ⟨_, ⟨i, rfl⟩, h⟩⟩ }, show is_measurable {b | a < g b}, rw this, exact is_measurable.Union (λ i, hf i _ (is_measurable_of_is_open (is_open_lt' _))) end lemma measurable.is_glb {α} [topological_space α] [linear_order α] [orderable_topology α] [second_countable_topology α] {β} [measurable_space β] {ι} [encodable ι] {f : ι → β → α} {g : β → α} (hf : ∀ i, measurable (f i)) (hg : ∀ b, is_glb {a | ∃ i, f i b = a} (g b)) : measurable g := begin rw borel_eq_generate_Iio α, apply measurable_generate_from, rintro _ ⟨a, rfl⟩, have : {b | g b < a} = ⋃ i, {b | f i b < a}, { simp [set.ext_iff], intro b, rw [is_glb_lt_iff (hg b)], exact ⟨λ ⟨_, ⟨i, rfl⟩, h⟩, ⟨i, h⟩, λ ⟨i, h⟩, ⟨_, ⟨i, rfl⟩, h⟩⟩ }, show is_measurable {b | g b < a}, rw this, exact is_measurable.Union (λ i, hf i _ (is_measurable_of_is_open (is_open_gt' _))) end lemma measurable.supr {α} [topological_space α] [complete_linear_order α] [orderable_topology α] [second_countable_topology α] {β} [measurable_space β] {ι} [encodable ι] {f : ι → β → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨆ i, f i b) := measurable.is_lub hf $ λ b, is_lub_supr lemma measurable.infi {α} [topological_space α] [complete_linear_order α] [orderable_topology α] [second_countable_topology α] {β} [measurable_space β] {ι} [encodable ι] {f : ι → β → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨅ i, f i b) := measurable.is_glb hf $ λ b, is_glb_infi end end measure_theory namespace real open measure_theory measurable_space lemma borel_eq_generate_from_Ioo_rat : borel ℝ = generate_from (⋃(a b : ℚ) (h : a < b), {Ioo a b}) := borel_eq_generate_from_of_subbasis is_topological_basis_Ioo_rat.2.2 lemma borel_eq_generate_from_Iio_rat : borel ℝ = generate_from (⋃a:ℚ, {Iio a}) := begin let g, swap, apply le_antisymm (_ : _ ≤ g) (measurable_space.generate_from_le (λ t, _)), { rw borel_eq_generate_from_Ioo_rat, refine generate_from_le (λ t, _), simp only [mem_Union], rintro ⟨a, b, h, rfl|⟨⟨⟩⟩⟩, rw (set.ext (λ x, _) : Ioo (a:ℝ) b = (⋃c>a, - Iio c) ∩ Iio b), { have hg : ∀q:ℚ, g.is_measurable (Iio q) := λ q, generate_measurable.basic _ (by simp; exact ⟨_, rfl⟩), refine @is_measurable.inter _ g _ _ _ (hg _), refine @is_measurable.bUnion _ _ g _ _ (countable_encodable _) (λ c h, _), exact @is_measurable.compl _ _ g (hg _) }, { simp [Ioo, Iio], refine and_congr _ iff.rfl, exact ⟨λ h, let ⟨c, ac, cx⟩ := exists_rat_btwn h in ⟨c, rat.cast_lt.1 ac, le_of_lt cx⟩, λ ⟨c, ac, cx⟩, lt_of_lt_of_le (rat.cast_lt.2 ac) cx⟩ } }, { simp, rintro r rfl, exact is_measurable_of_is_open (is_open_gt' _) } end end real
4b81371ce501ecab5ac3dcb444509e9358d77934
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/fourier/add_circle.lean
b4b0ece6ab1a5e1e149165c01c7fa1fe010437df
[ "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
14,689
lean
/- Copyright (c) 2021 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth, David Loeffler -/ import analysis.special_functions.complex.circle import topology.instances.add_circle import analysis.inner_product_space.l2_space import measure_theory.function.continuous_map_dense import measure_theory.function.l2_space import measure_theory.group.integration import measure_theory.integral.periodic import topology.continuous_function.stone_weierstrass /-! # Fourier analysis on the additive circle This file contains basic results on Fourier series for functions on the additive circle `add_circle T = ℝ / ℤ • T`. ## Main definitions * `haar_add_circle`, Haar measure on `add_circle T`, normalized to have total measure `1`. (Note that this is not the same normalisation as the standard measure defined in `integral.periodic`, so we do not declare it as a `measure_space` instance, to avoid confusion.) * for `n : ℤ`, `fourier n` is the monomial `λ x, exp (2 π i n x / T)`, bundled as a continuous map from `add_circle T` to `ℂ`. * for `n : ℤ` and `p : ℝ≥0∞`, `fourier_Lp p n` is an abbreviation for the monomial `fourier n` considered as an element of the Lᵖ-space `Lp ℂ p haar_add_circle`, via the embedding `continuous_map.to_Lp`. * `fourier_series` is the canonical isometric isomorphism from `Lp ℂ 2 haar_add_circle` to `ℓ²(ℤ, ℂ)` induced by taking Fourier coefficients. ## Main statements The theorem `span_fourier_closure_eq_top` states that the span of the monomials `fourier n` is dense in `C(add_circle T, ℂ)`, i.e. that its `submodule.topological_closure` is `⊤`. This follows from the Stone-Weierstrass theorem after checking that it is a subalgebra, closed under conjugation, and separates points. The theorem `span_fourier_Lp_closure_eq_top` states that for `1 ≤ p < ∞` the span of the monomials `fourier_Lp` is dense in the Lᵖ space of `add_circle T`, i.e. that its `submodule.topological_closure` is `⊤`. This follows from the previous theorem using general theory on approximation of Lᵖ functions by continuous functions. The theorem `orthonormal_fourier` states that the monomials `fourier_Lp 2 n` form an orthonormal set (in the L² space of `add_circle T` with respect to `haar_add_circle`). The last two results together provide that the functions `fourier_Lp 2 n` form a Hilbert basis for L²; this is named as `fourier_series`. Parseval's identity, `tsum_sq_fourier_series_repr`, is a direct consequence of the construction of this Hilbert basis. -/ noncomputable theory open_locale ennreal complex_conjugate classical real open topological_space continuous_map measure_theory measure_theory.measure algebra submodule set variables {T : ℝ} namespace add_circle /-! ### Map from `add_circle` to `circle` -/ lemma scaled_exp_map_periodic : function.periodic (λ x, exp_map_circle (2 * π / T * x)) T := begin -- The case T = 0 is not interesting, but it is true, so we prove it to save hypotheses rcases eq_or_ne T 0 with rfl | hT, { intro x, simp }, { intro x, simp_rw mul_add, rw [div_mul_cancel _ hT, periodic_exp_map_circle] } end /-- The canonical map `λ x, exp (2 π i x / T)` from `ℝ / ℤ • T` to the unit circle in `ℂ`. If `T = 0` we understand this as the constant function 1. -/ def to_circle : add_circle T → circle := (@scaled_exp_map_periodic T).lift lemma to_circle_add (x : add_circle T) (y : add_circle T) : to_circle (x + y) = to_circle x * to_circle y := begin induction x using quotient_add_group.induction_on', induction y using quotient_add_group.induction_on', simp_rw [←quotient_add_group.coe_add, to_circle, function.periodic.lift_coe, mul_add, exp_map_circle_add], end lemma continuous_to_circle : continuous (@to_circle T) := continuous_coinduced_dom.mpr (exp_map_circle.continuous.comp $ continuous_const.mul continuous_id') lemma injective_to_circle (hT : T ≠ 0) : function.injective (@to_circle T) := begin intros a b h, induction a using quotient_add_group.induction_on', induction b using quotient_add_group.induction_on', simp_rw [to_circle, function.periodic.lift_coe] at h, obtain ⟨m, hm⟩ := exp_map_circle_eq_exp_map_circle.mp h.symm, simp_rw [quotient_add_group.eq, add_subgroup.mem_zmultiples_iff, zsmul_eq_mul], use m, field_simp [real.two_pi_pos.ne'] at hm, rw ← mul_right_inj' real.two_pi_pos.ne', linarith end /-! ### Measure on `add_circle T` In this file we use the Haar measure on `add_circle T` normalised to have total measure 1 (which is **not** the same as the standard measure defined in `topology.instances.add_circle`). -/ variables [hT : fact (0 < T)] include hT /-- Haar measure on the additive circle, normalised to have total measure 1. -/ @[derive is_add_haar_measure] def haar_add_circle : measure (add_circle T) := add_haar_measure ⊤ instance : is_probability_measure (@haar_add_circle T _) := is_probability_measure.mk add_haar_measure_self lemma volume_eq_smul_haar_add_circle : (volume : measure (add_circle T)) = ennreal.of_real T • haar_add_circle := rfl end add_circle open add_circle section monomials /-- The family of exponential monomials `λ x, exp (2 π i n x / T)`, parametrized by `n : ℤ` and considered as bundled continuous maps from `ℝ / ℤ • T` to `ℂ`. -/ def fourier (n : ℤ) : C(add_circle T, ℂ) := { to_fun := λ x, to_circle (n • x), continuous_to_fun := continuous_induced_dom.comp $ continuous_to_circle.comp $ continuous_zsmul _} @[simp] lemma fourier_apply {n : ℤ} {x : add_circle T} : fourier n x = to_circle (n • x) := rfl @[simp] lemma fourier_zero {x : add_circle T} : fourier 0 x = 1 := begin induction x using quotient_add_group.induction_on', rw [fourier_apply, to_circle, zero_zsmul, ←quotient_add_group.coe_zero, function.periodic.lift_coe, mul_zero, exp_map_circle_zero, coe_one_unit_sphere], end @[simp] lemma fourier_one {x : add_circle T} : fourier 1 x = to_circle x := by rw [fourier_apply, one_zsmul] @[simp] lemma fourier_neg {n : ℤ} {x : add_circle T} : fourier (-n) x = conj (fourier n x) := begin induction x using quotient_add_group.induction_on', simp_rw [fourier_apply, to_circle, ←quotient_add_group.coe_zsmul, function.periodic.lift_coe, ←coe_inv_circle_eq_conj, ←exp_map_circle_neg, neg_smul, mul_neg], end @[simp] lemma fourier_add {m n : ℤ} {x : add_circle T} : fourier (m + n) x = (fourier m x) * (fourier n x) := by simp_rw [fourier_apply, add_zsmul, to_circle_add, coe_mul_unit_sphere] /-- For `n ≠ 0`, a translation by `T / 2 / n` negates the function `fourier n`. -/ lemma fourier_add_half_inv_index {n : ℤ} (hn : n ≠ 0) (hT : 0 < T) (x : add_circle T) : fourier n (x + ((T / 2 / n) : ℝ)) = - fourier n x := begin rw [fourier_apply, zsmul_add, ←quotient_add_group.coe_zsmul, to_circle_add, coe_mul_unit_sphere], have : (n : ℂ) ≠ 0 := by simpa using hn, have : ((@to_circle T ((n • (T / 2 / n)) : ℝ)) : ℂ) = -1, { rw [zsmul_eq_mul, to_circle, function.periodic.lift_coe, exp_map_circle_apply], replace hT := complex.of_real_ne_zero.mpr hT.ne', convert complex.exp_pi_mul_I using 3, field_simp, ring, }, rw this, simp, end /-- The subalgebra of `C(add_circle T, ℂ)` generated by `fourier n` for `n ∈ ℤ` . -/ def fourier_subalgebra : subalgebra ℂ C(add_circle T, ℂ) := algebra.adjoin ℂ (range fourier) /-- The subalgebra of `C(add_circle T, ℂ)` generated by `fourier n` for `n ∈ ℤ` is in fact the linear span of these functions. -/ lemma fourier_subalgebra_coe : (@fourier_subalgebra T).to_submodule = span ℂ (range fourier) := begin apply adjoin_eq_span_of_subset, refine subset.trans _ submodule.subset_span, intros x hx, apply submonoid.closure_induction hx (λ _, id) ⟨0, _⟩, { rintros _ _ ⟨m, rfl⟩ ⟨n, rfl⟩, refine ⟨m + n, _⟩, ext1 z, exact fourier_add }, { ext1 z, exact fourier_zero } end /-- The subalgebra of `C(add_circle T, ℂ)` generated by `fourier n` for `n ∈ ℤ` is invariant under complex conjugation. -/ lemma fourier_subalgebra_conj_invariant : conj_invariant_subalgebra ((@fourier_subalgebra T).restrict_scalars ℝ) := begin apply subalgebra_conj_invariant, rintros _ ⟨n, rfl⟩, exact ⟨-n, ext (λ _, fourier_neg)⟩ end variables [hT : fact (0 < T)] include hT /-- The subalgebra of `C(add_circle T, ℂ)` generated by `fourier n` for `n ∈ ℤ` separates points. -/ lemma fourier_subalgebra_separates_points : (@fourier_subalgebra T).separates_points := begin intros x y hxy, refine ⟨_, ⟨fourier 1, subset_adjoin ⟨1, rfl⟩, rfl⟩, _⟩, dsimp only, rw [fourier_one, fourier_one], contrapose! hxy, rw subtype.coe_inj at hxy, exact injective_to_circle hT.elim.ne' hxy, end /-- The subalgebra of `C(add_circle T, ℂ)` generated by `fourier n` for `n ∈ ℤ` is dense. -/ lemma fourier_subalgebra_closure_eq_top : (@fourier_subalgebra T).topological_closure = ⊤ := continuous_map.subalgebra_is_R_or_C_topological_closure_eq_top_of_separates_points fourier_subalgebra fourier_subalgebra_separates_points fourier_subalgebra_conj_invariant /-- The linear span of the monomials `fourier n` is dense in `C(add_circle T, ℂ)`. -/ lemma span_fourier_closure_eq_top : (span ℂ (range $ @fourier T)).topological_closure = ⊤ := begin rw ← fourier_subalgebra_coe, exact congr_arg subalgebra.to_submodule fourier_subalgebra_closure_eq_top, end /-- The family of monomials `fourier n`, parametrized by `n : ℤ` and considered as elements of the `Lp` space of functions `add_circle T → ℂ`. -/ abbreviation fourier_Lp (p : ℝ≥0∞) [fact (1 ≤ p)] (n : ℤ) : Lp ℂ p (@haar_add_circle T hT) := to_Lp p haar_add_circle ℂ (fourier n) lemma coe_fn_fourier_Lp (p : ℝ≥0∞) [fact (1 ≤ p)] (n : ℤ) : (@fourier_Lp T hT p _ n) =ᵐ[haar_add_circle] fourier n := coe_fn_to_Lp haar_add_circle (fourier n) /-- For each `1 ≤ p < ∞`, the linear span of the monomials `fourier n` is dense in `Lp ℂ p haar_circle`. -/ lemma span_fourier_Lp_closure_eq_top {p : ℝ≥0∞} [fact (1 ≤ p)] (hp : p ≠ ∞) : (span ℂ (range (@fourier_Lp T _ p _))).topological_closure = ⊤ := begin convert (continuous_map.to_Lp_dense_range ℂ hp (@haar_add_circle T hT) ℂ ).topological_closure_map_submodule (span_fourier_closure_eq_top), rw [map_span, range_comp], simp only [continuous_linear_map.coe_coe], end /-- The monomials `fourier n` are an orthonormal set with respect to normalised Haar measure. -/ lemma orthonormal_fourier : orthonormal ℂ (@fourier_Lp T _ 2 _) := begin rw orthonormal_iff_ite, intros i j, rw continuous_map.inner_to_Lp (@haar_add_circle T hT) (fourier i) (fourier j), simp_rw [←fourier_neg, ←fourier_add], split_ifs, { simp_rw [h, neg_add_self], have : ⇑(@fourier T 0) = (λ x, 1 : (add_circle T) → ℂ), { ext1, exact fourier_zero }, rw [this, integral_const, measure_univ, ennreal.one_to_real, complex.real_smul, complex.of_real_one, mul_one] }, have hij : -i + j ≠ 0, { rw add_comm, exact sub_ne_zero.mpr (ne.symm h) }, convert integral_eq_zero_of_add_right_eq_neg (fourier_add_half_inv_index hij hT.elim), exact is_add_left_invariant.is_add_right_invariant end end monomials section fourier variables [hT : fact (0 < T)] include hT /-- We define `fourier_series` to be a `ℤ`-indexed Hilbert basis for `Lp ℂ 2 haar_add_circle`, which by definition is an isometric isomorphism from `Lp ℂ 2 haar_add_circle` to `ℓ²(ℤ, ℂ)`. -/ def fourier_series : hilbert_basis ℤ ℂ (Lp ℂ 2 $ @haar_add_circle T hT) := hilbert_basis.mk orthonormal_fourier (span_fourier_Lp_closure_eq_top (by norm_num)).ge /-- The elements of the Hilbert basis `fourier_series` are the functions `fourier_Lp 2`, i.e. the monomials `fourier n` on the circle considered as elements of `L²`. -/ @[simp] lemma coe_fourier_series : ⇑(@fourier_series _ hT) = fourier_Lp 2:= hilbert_basis.coe_mk _ _ /-- Under the isometric isomorphism `fourier_series` from `Lp ℂ 2 haar_circle` to `ℓ²(ℤ, ℂ)`, the `i`-th coefficient is the integral over `add_circle T` of `λ t, fourier (-i) t * f t`. -/ lemma fourier_series_repr (f : Lp ℂ 2 $ @haar_add_circle T hT) (i : ℤ) : fourier_series.repr f i = ∫ (t : add_circle T), fourier (-i) t * f t ∂ haar_add_circle := begin transitivity ∫ (t : add_circle T), conj (((@fourier_Lp T hT 2 _ i) : add_circle T → ℂ) t) * f t ∂ haar_add_circle, { simp [fourier_series.repr_apply_apply f i, measure_theory.L2.inner_def] }, { apply integral_congr_ae, filter_upwards [coe_fn_fourier_Lp 2 i] with _ ht, rw [ht, ←fourier_neg] } end /-- The Fourier series of an `L2` function `f` sums to `f`, in the `L²` space of `add_circle T`. -/ lemma has_sum_fourier_series (f : Lp ℂ 2 $ @haar_add_circle T hT) : has_sum (λ i, fourier_series.repr f i • fourier_Lp 2 i) f := by simpa using hilbert_basis.has_sum_repr fourier_series f /-- **Parseval's identity**: for an `L²` function `f` on `add_circle T`, the sum of the squared norms of the Fourier coefficients equals the `L²` norm of `f`. -/ lemma tsum_sq_fourier_series_repr (f : Lp ℂ 2 $ @haar_add_circle T hT) : ∑' i : ℤ, ‖fourier_series.repr f i‖ ^ 2 = ∫ (t : add_circle T), ‖f t‖ ^ 2 ∂ haar_add_circle := begin have H₁ : ‖fourier_series.repr f‖ ^ 2 = ∑' i, ‖fourier_series.repr f i‖ ^ 2, { exact_mod_cast lp.norm_rpow_eq_tsum _ (fourier_series.repr f), norm_num }, have H₂ : ‖fourier_series.repr f‖ ^ 2 = ‖f‖ ^ 2 := by simp, have H₃ := congr_arg is_R_or_C.re (@L2.inner_def (add_circle T) ℂ ℂ _ _ _ _ f f), rw ← integral_re at H₃, { simp only [← norm_sq_eq_inner] at H₃, rw [← H₁, H₂, H₃], }, { exact L2.integrable_inner f f }, end /-- The Fourier coefficients are given by integrating over the interval `[a, a + T] ⊂ ℝ`. -/ lemma fourier_series_repr' (f : Lp ℂ 2 $ @haar_add_circle T hT) (n : ℤ) (a : ℝ): fourier_series.repr f n = 1 / T * ∫ x in a .. a + T, @fourier T (-n) x * f x := begin have ha : ae_strongly_measurable (λ (t : add_circle T), fourier (-n) t * f t) haar_add_circle := (map_continuous _).ae_strongly_measurable.mul (Lp.ae_strongly_measurable _), rw [fourier_series_repr, add_circle.interval_integral_preimage T a (ha.smul_measure _), volume_eq_smul_haar_add_circle, integral_smul_measure], have : (T : ℂ) ≠ 0 := by exact_mod_cast hT.out.ne', field_simp [ennreal.to_real_of_real hT.out.le, complex.real_smul], ring, end end fourier
384497a8e9b7d695ae3fef02273133264fe19b58
4fa161becb8ce7378a709f5992a594764699e268
/src/ring_theory/eisenstein_criterion.lean
59f6b98f8a7774a198f437f0ae27c42bdab8ffdd
[ "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
5,483
lean
/- Copyright (c) 2020 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import ring_theory.ideal_operations import data.polynomial import tactic.apply_fun import ring_theory.prime /-! # Eisenstein's criterion A proof of a slight generalisation of Eisenstein's criterion for the irreducibility of a polynomial over an integral domain. -/ open polynomial ideal.quotient variables {R : Type*} [integral_domain R] namespace polynomial namespace eisenstein_criterion_aux /- Section for auxiliary lemmas used in the proof of `irreducible_of_eisenstein_criterion`-/ lemma map_eq_C_mul_X_pow_of_forall_coeff_mem {f : polynomial R} {P : ideal R} (hfP : ∀ (n : ℕ), ↑n < f.degree → f.coeff n ∈ P) (hf0 : f ≠ 0) : map (mk_hom P) f = C ((mk_hom P) f.leading_coeff) * X ^ f.nat_degree := polynomial.ext (λ n, begin rcases lt_trichotomy ↑n (degree f) with h | h | h, { erw [coeff_map, ← mk_eq_mk_hom, eq_zero_iff_mem.2 (hfP n h), coeff_C_mul, coeff_X_pow, if_neg, mul_zero], rintro rfl, exact not_lt_of_ge degree_le_nat_degree h }, { have : nat_degree f = n, from nat_degree_eq_of_degree_eq_some h.symm, rw [coeff_C_mul, coeff_X_pow, if_pos this.symm, mul_one, leading_coeff, this, coeff_map] }, { rw [coeff_eq_zero_of_degree_lt, coeff_eq_zero_of_degree_lt], { refine lt_of_le_of_lt (degree_C_mul_X_pow_le _ _) _, rwa ← degree_eq_nat_degree hf0 }, { exact lt_of_le_of_lt (degree_map_le _) h } } end) lemma le_nat_degree_of_map_eq_mul_X_pow {n : ℕ} {P : ideal R} (hP : P.is_prime) {q : polynomial R} {c : polynomial P.quotient} (hq : map (mk_hom P) q = c * X ^ n) (hc0 : c.degree = 0) : n ≤ q.nat_degree := with_bot.coe_le_coe.1 (calc ↑n = degree (q.map (mk_hom P)) : by rw [hq, degree_mul_eq, hc0, zero_add, degree_pow_eq, degree_X, nsmul_one, nat.cast_with_bot] ... ≤ degree q : degree_map_le _ ... ≤ nat_degree q : degree_le_nat_degree) lemma eval_zero_mem_ideal_of_eq_mul_X_pow {n : ℕ} {P : ideal R} {q : polynomial R} {c : polynomial P.quotient} (hq : map (mk_hom P) q = c * X ^ n) (hn0 : 0 < n) : eval 0 q ∈ P := by rw [← coeff_zero_eq_eval_zero, ← eq_zero_iff_mem, mk_eq_mk_hom, ← coeff_map, coeff_zero_eq_eval_zero, hq, eval_mul, eval_pow, eval_X, zero_pow hn0, mul_zero] lemma is_unit_of_nat_degree_eq_zero_of_forall_dvd_is_unit {p q : polynomial R} (hu : ∀ (x : R), C x ∣ p * q → is_unit x) (hpm : p.nat_degree = 0) : is_unit p := begin rw [eq_C_of_degree_le_zero (nat_degree_eq_zero_iff_degree_le_zero.1 hpm), is_unit_C], refine hu _ _, rw [← eq_C_of_degree_le_zero (nat_degree_eq_zero_iff_degree_le_zero.1 hpm)], exact dvd_mul_right _ _ end end eisenstein_criterion_aux open eisenstein_criterion_aux /-- If `f` is a non constant polynomial with coefficients in `R`, and `P` is a prime ideal in `R`, then if every coefficient in `R` except the leading coefficient is in `P`, and the trailing coefficient is not in `P^2` and no non units in `R` divide `f`, then `f` is irreducible. -/ theorem irreducible_of_eisenstein_criterion {f : polynomial R} {P : ideal R} (hP : P.is_prime) (hfl : f.leading_coeff ∉ P) (hfP : ∀ n : ℕ, ↑n < degree f → f.coeff n ∈ P) (hfd0 : 0 < degree f) (h0 : f.coeff 0 ∉ P^2) (hu : ∀ x : R, C x ∣ f → is_unit x) : irreducible f := have hf0 : f ≠ 0, from λ _, by simp only [*, not_true, submodule.zero_mem, coeff_zero] at *, have hf : f.map (mk_hom P) = C (mk_hom P (leading_coeff f)) * X ^ nat_degree f, from map_eq_C_mul_X_pow_of_forall_coeff_mem hfP hf0, have hfd0 : 0 < f.nat_degree, from with_bot.coe_lt_coe.1 (lt_of_lt_of_le hfd0 degree_le_nat_degree), ⟨mt degree_eq_zero_of_is_unit (λ h, by simp only [*, lt_irrefl] at *), begin rintros p q rfl, rw [map_mul] at hf, rcases mul_eq_mul_prime_pow (show prime (X : polynomial (ideal.quotient P)), from prime_of_degree_eq_one_of_monic degree_X monic_X) hf with ⟨m, n, b, c, hmnd, hbc, hp, hq⟩, have hmn : 0 < m → 0 < n → false, { assume hm0 hn0, refine h0 _, rw [coeff_zero_eq_eval_zero, eval_mul, pow_two], exact ideal.mul_mem_mul (eval_zero_mem_ideal_of_eq_mul_X_pow hp hm0) (eval_zero_mem_ideal_of_eq_mul_X_pow hq hn0) }, have hpql0 : (mk_hom P) (p * q).leading_coeff ≠ 0, { rwa [← mk_eq_mk_hom, ne.def, eq_zero_iff_mem] }, have hp0 : p ≠ 0, from λ h, by simp only [*, zero_mul, eq_self_iff_true, not_true, ne.def] at *, have hq0 : q ≠ 0, from λ h, by simp only [*, eq_self_iff_true, not_true, ne.def, mul_zero] at *, have hbc0 : degree b = 0 ∧ degree c = 0, { apply_fun degree at hbc, rwa [degree_C hpql0, degree_mul_eq, eq_comm, nat.with_bot.add_eq_zero_iff] at hbc }, have hmp : m ≤ nat_degree p, from le_nat_degree_of_map_eq_mul_X_pow hP hp hbc0.1, have hnq : n ≤ nat_degree q, from le_nat_degree_of_map_eq_mul_X_pow hP hq hbc0.2, have hpmqn : p.nat_degree = m ∧ q.nat_degree = n, { rw [nat_degree_mul_eq hp0 hq0] at hmnd, clear_except hmnd hmp hnq, omega }, obtain rfl | rfl : m = 0 ∨ n = 0, { rwa [nat.pos_iff_ne_zero, nat.pos_iff_ne_zero, imp_false, not_not, ← or_iff_not_imp_left] at hmn }, { exact or.inl (is_unit_of_nat_degree_eq_zero_of_forall_dvd_is_unit hu hpmqn.1) }, { exact or.inr (is_unit_of_nat_degree_eq_zero_of_forall_dvd_is_unit (by simpa only [mul_comm] using hu) hpmqn.2) } end⟩ end polynomial
cf58c7bc48458e3133ea148da4a6dba5a95b7468
c31182a012eec69da0a1f6c05f42b0f0717d212d
/src/for_mathlib/Profinite/arrow_limit.lean
4c80fab4eaa17b684891b7955693fe5ce745a0a2
[]
no_license
Ja1941/lean-liquid
fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc
8e80ed0cbdf5145d6814e833a674eaf05a1495c1
refs/heads/master
1,689,437,983,362
1,628,362,719,000
1,628,362,719,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,007
lean
import category_theory.limits.concrete_category import topology.category.Profinite.as_limit import for_mathlib.Profinite.compat_discrete_quotient import for_mathlib.Cech.split noncomputable theory open category_theory universe u namespace Profinite variables (F : arrow Profinite.{u}) (surj : function.surjective F.hom) open discrete_quotient /-- A diagram of arrows construction from discrete quotients of F.left. -/ @[simps] def fintype_arrow_diagram : discrete_quotient F.left ⥤ arrow Fintype.{u} := { obj := λ S, { left := Fintype.of S, right := Fintype.of $ S.make F.hom surj, hom := discrete_quotient.map (S.make_le_comap _ _) }, map := λ S T f, { left := of_le $ le_of_hom f, right := of_le $ make_right_mono F.hom surj S T $ le_of_hom f } }. /-- A diagram of arrows construction from discrete quotients of F.left. -/ @[simps] def arrow_diagram : discrete_quotient F.left ⥤ arrow Profinite.{u} := fintype_arrow_diagram F surj ⋙ Fintype.to_Profinite.map_arrow /-- The left diagram associated to arrow_diagram. -/ abbreviation left_arrow_diagram : discrete_quotient F.left ⥤ Profinite.{u} := arrow_diagram F surj ⋙ arrow.left_func /-- The right diagram associated to arrow_diagram. -/ abbreviation right_arrow_diagram : discrete_quotient F.left ⥤ Profinite.{u} := arrow_diagram F surj ⋙ arrow.right_func lemma arrow_diagram_surjective (S : discrete_quotient F.left) : function.surjective ((arrow_diagram F surj).obj S).hom := begin rintro ⟨x⟩, obtain ⟨x,rfl⟩ := surj x, exact ⟨S.proj x,rfl⟩, end instance (S : discrete_quotient F.left) : arrow.split ((arrow_diagram F surj).obj S) := { σ := ⟨λ x, classical.some (arrow_diagram_surjective F surj S x), continuous_of_discrete_topology⟩, is_splitting' := begin ext x, erw classical.some_spec (arrow_diagram_surjective F surj S x), refl, end } /-- A cone which is a limit expressing an arrow as a limit. -/ @[simps] def arrow_cone : limits.cone (arrow_diagram F surj) := { X := F, π := { app := λ S, { left := ⟨S.proj, S.proj_continuous⟩, right := ⟨(S.make _ surj).proj, (S.make _ surj).proj_continuous⟩ } } } /-- A helper definition used for `arrow_limit_cone`. -/ def arrow_diagram_snd_preserves : limits.preserves_limit (arrow_diagram F surj ⋙ comma.snd _ _) (𝟭 _) := begin have h := limits.id_preserves_limits.preserves_limits_of_shape, have hh := h.preserves_limit, exact hh, end /-- the limit cone assocciated to arrow_diagram -/ @[simps] def arrow_limit_cone : limits.limit_cone (arrow_diagram F surj) := { cone := @comma.cone_of_preserves _ _ _ _ _ _ _ _ _ _ _ (arrow_diagram_snd_preserves _ _) (limit_cone _) _ (limit_cone_is_limit _), is_limit := @comma.cone_of_preserves_is_limit _ _ _ _ _ _ _ _ _ _ _ (arrow_diagram_snd_preserves _ _) _ (limit_cone_is_limit _) _ _ } /-- lifing arrow_cone gives an isomorphism on the left -/ instance arrow_is_iso_lift_left : is_iso ((arrow_limit_cone F surj).is_limit.lift (arrow_cone F surj)).left := Profinite.is_iso_as_limit_cone_lift _ /-- lifing arrow_cone gives an isomorphism on the right -/ instance arrow_is_iso_lift_right : is_iso ((arrow_limit_cone F surj).is_limit.lift (arrow_cone F surj)).right := is_iso_of_bijective _ begin split, { intros x y h, apply discrete_quotient.eq_of_proj_eq, intros S, apply_fun subtype.val at h, let T : discrete_quotient F.left := S.comap F.hom.continuous, let R : discrete_quotient F.right := T.make F.hom surj, have hR : R ≤ S, { apply discrete_quotient.make_right_le, tauto }, apply_fun (λ e, e T) at h, have := discrete_quotient.of_le_proj_apply hR, rw [← this, ← this], congr' 1 }, { intros x, cases x with x hx, dsimp at x hx, let Us : Π (I : discrete_quotient F.right), I := λ I, of_le (make_right_le _ _ _ _ (by tauto)) (x $ I.comap F.hom.continuous), rcases discrete_quotient.exists_of_compat Us _ with ⟨y,hy⟩, { refine ⟨y,_⟩, ext I : 2, dsimp at *, let J : discrete_quotient F.right := (I.make F.hom surj), let II : discrete_quotient F.left := J.comap F.hom.continuous ⊓ I, have h1 : II ≤ I := inf_le_right, have h2 : II ≤ J.comap F.hom.continuous := inf_le_left, rw ← hx (hom_of_le h1), dsimp [comma.cone_of_preserves_is_limit, limit_cone_is_limit, CompHaus.limit_cone_is_limit, Top.limit_cone_is_limit], rw hy, dsimp [Us], rw ← hx (hom_of_le h2), rw ← of_le_comp_apply }, { intros A B h, dsimp [Us], have := comap_mono F.hom.continuous h, rw ← hx (hom_of_le this), rw [← of_le_comp_apply, ← of_le_comp_apply] } }, end @[simps] def left_arrow_cone : limits.cone (left_arrow_diagram F surj) := functor.map_cone _ (arrow_cone F surj) @[simps] def right_arrow_cone : limits.cone (right_arrow_diagram F surj) := functor.map_cone _ (arrow_cone F surj) instance left_arrow_cone_lift_is_iso : is_iso $ (limit_cone_is_limit $ left_arrow_diagram F surj).lift (left_arrow_cone F surj) := Profinite.arrow_is_iso_lift_left _ _ instance right_arrow_cone_lift_is_iso : is_iso $ (limit_cone_is_limit $ right_arrow_diagram F surj).lift (right_arrow_cone F surj) := Profinite.arrow_is_iso_lift_right _ _ @[simps] def left_arrow_cone_iso : left_arrow_cone F surj ≅ (limit_cone $ left_arrow_diagram F surj) := limits.cones.ext (as_iso $ (limit_cone_is_limit $ left_arrow_diagram F surj).lift _) (λ _ , rfl) @[simps] def right_arrow_cone_iso : right_arrow_cone F surj ≅ (limit_cone $ right_arrow_diagram F surj) := limits.cones.ext (as_iso $ (limit_cone_is_limit $ right_arrow_diagram F surj).lift _) (λ _ , rfl) /-- The isomorphism of cones showing that arrow_cone is a limit cone. -/ @[simps] def arrow_cone_iso : arrow_cone F surj ≅ (arrow_limit_cone F surj).cone := limits.cones.ext (as_iso $ (arrow_limit_cone F surj).is_limit.lift (arrow_cone F surj)) (λ _, rfl) /-- arrow_cone is a limit cone. -/ @[simps] def is_limit_arrow_cone : limits.is_limit (arrow_cone F surj) := limits.is_limit.of_iso_limit (arrow_limit_cone F surj).is_limit (arrow_cone_iso F surj).symm @[simps] def is_limit_left_arrow_cone : limits.is_limit (left_arrow_cone F surj) := limits.is_limit.of_iso_limit (limit_cone_is_limit $ left_arrow_diagram F surj) (left_arrow_cone_iso _ _).symm @[simps] def is_limit_right_arrow_cone : limits.is_limit (right_arrow_cone F surj) := limits.is_limit.of_iso_limit (limit_cone_is_limit $ right_arrow_diagram F surj) (right_arrow_cone_iso _ _).symm open opposite open_locale simplicial @[simps] def Cech_cone_diagram (n : ℕ) : discrete_quotient F.left ⥤ Profinite.{u} := arrow_diagram F surj ⋙ simplicial_object.cech_nerve ⋙ (evaluation _ _).obj (op [n]) def Cech_cone_diagram_proj (n : ℕ) (S : discrete_quotient F.left) (i : fin (n+1)) : (Cech_cone_diagram F surj n).obj S ⟶ Profinite.of S := limits.wide_pullback.π _ ⟨i⟩ def Cech_cone_diagram_inclusion (n : ℕ) (S : discrete_quotient F.left) : (Cech_cone_diagram F surj n).obj S → fin (n+1) → S := λ a i, Cech_cone_diagram_proj F surj n S i a lemma Cech_cone_diagram_inclusion_injective (n : ℕ) (S : discrete_quotient F.left) : function.injective (Cech_cone_diagram_inclusion F surj n S) := begin intros a b h, apply category_theory.limits.concrete.wide_pullback_ext', rintros ⟨j⟩, apply_fun (λ e, e j) at h, exact h, end instance Cech_cone_diagram_fintype (n : ℕ) (S : discrete_quotient F.left) : fintype ((Cech_cone_diagram F surj n).obj S) := fintype.of_injective (Cech_cone_diagram_inclusion F surj n S) (Cech_cone_diagram_inclusion_injective F surj n S) @[simps] def Cech_cone (n : ℕ) : limits.cone (Cech_cone_diagram F surj n) := functor.map_cone _ (arrow_cone F surj) @[simps] def swap_cone_right (n : ℕ) (S : limits.cone (Cech_cone_diagram F surj n)) : limits.cone (right_arrow_diagram F surj) := { X := S.X, π := { app := λ T, S.π.app T ≫ limits.wide_pullback.base _, naturality' := begin intros X Y f, dsimp, simp [← S.w f], end } } @[simps] def swap_cone_left (n : ℕ) (i : ulift.{u} (fin (n+1))) (S : limits.cone (Cech_cone_diagram F surj n)) : limits.cone (left_arrow_diagram F surj) := { X := S.X, π := { app := λ T, S.π.app T ≫ limits.wide_pullback.π _ i, naturality' := begin intros X Y f, dsimp, simp [← S.w f], end } } @[simps] def Cech_cone_is_limit (n : ℕ) : limits.is_limit (Cech_cone F surj n) := { lift := λ S, limits.wide_pullback.lift ((is_limit_right_arrow_cone F surj).lift $ swap_cone_right _ _ _ _) (λ i, (is_limit_left_arrow_cone F surj).lift $ swap_cone_left _ _ _ i _) begin intros i, apply (is_limit_right_arrow_cone F surj).hom_ext, intros T, simp, have : (arrow_cone F surj).X.hom ≫ (right_arrow_cone F surj).π.app T = (left_arrow_cone F surj).π.app T ≫ (whisker_left (arrow_diagram F surj) arrow.left_to_right).app T, by refl, erw [this, ← category.assoc, (is_limit_left_arrow_cone F surj).fac (swap_cone_left F surj n i S) T], simp, end, fac' := begin intros S T, apply limits.wide_pullback.hom_ext, { intro i, dsimp, simp, have := (is_limit_left_arrow_cone F surj).fac, erw this, refl }, { dsimp, simp, erw (is_limit_right_arrow_cone F surj).fac, refl } end, uniq' := begin intros S f h, apply limits.wide_pullback.hom_ext, { dsimp, simp, intros i, apply (is_limit_left_arrow_cone F surj).hom_ext, intros T, simp, erw [← h T, category.assoc, limits.wide_pullback.lift_π], refl }, { dsimp, simp, apply (is_limit_right_arrow_cone F surj).hom_ext, intros T, simp, erw [← h T, category.assoc, limits.wide_pullback.lift_base], refl } end }. end Profinite
580cf95f5607a53bd75efa0266c89c9e74457f7e
947b78d97130d56365ae2ec264df196ce769371a
/src/Lean/Data/Lsp/Utf16.lean
b4db02772f824994bb548050906d5accfff980bf
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,690
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga, Wojciech Nawrocki -/ import Init.Data.String import Init.Data.Array import Lean.Data.Lsp.Basic import Lean.Data.Position /-! LSP uses UTF-16 for indexing, so we need to provide some primitives to interact with Lean strings using UTF-16 indices. -/ namespace Char def utf16Size (c : Char) : UInt32 := if c.val ≤ 0xFFFF then 1 else 2 end Char namespace String private def csize (c : Char) : Nat := c.utf16Size.toNat def utf16Length (s : String) : Nat := s.foldr (fun c acc => csize c + acc) 0 private def codepointPosToUtf16PosFromAux (s : String) : Nat → Pos → Nat → Nat | 0, utf8pos, utf16pos => utf16pos | cp+1, utf8pos, utf16pos => codepointPosToUtf16PosFromAux cp (s.next utf8pos) (utf16pos + csize (s.get utf8pos)) /-- Computes the UTF-16 offset of the `n`-th Unicode codepoint in the substring of `s` starting at UTF-8 offset `off`. Yes, this is actually useful.-/ def codepointPosToUtf16PosFrom (s : String) (n : Nat) (off : Pos) : Nat := codepointPosToUtf16PosFromAux s n off 0 def codepointPosToUtf16Pos (s : String) (pos : Nat) : Nat := codepointPosToUtf16PosFrom s pos 0 private partial def utf16PosToCodepointPosFromAux (s : String) : Nat → Pos → Nat → Nat | 0, utf8pos, cp => cp | utf16pos, utf8pos, cp => utf16PosToCodepointPosFromAux (utf16pos - csize (s.get utf8pos)) (s.next utf8pos) (cp + 1) /-- Computes the position of the Unicode codepoint at UTF-16 offset `utf16pos` in the substring of `s` starting at UTF-8 offset `off`. -/ def utf16PosToCodepointPosFrom (s : String) (utf16pos : Nat) (off : Pos) : Nat := utf16PosToCodepointPosFromAux s utf16pos off 0 def utf16PosToCodepointPos (s : String) (pos : Nat) : Nat := utf16PosToCodepointPosFrom s pos 0 /-- Starting at `utf8pos`, finds the UTF-8 offset of the `p`-th codepoint. -/ def codepointPosToUtf8PosFrom (s : String) : String.Pos → Nat → String.Pos | utf8pos, 0 => utf8pos | utf8pos, p+1 => codepointPosToUtf8PosFrom (s.next utf8pos) p end String namespace Lean namespace FileMap /-- Computes an UTF-8 offset into `text.source` from an LSP-style 0-indexed (ln, col) position. -/ def lspPosToUtf8Pos (text : FileMap) (pos : Lsp.Position) : String.Pos := let colPos := text.positions.get! (pos.line); let chr := text.source.utf16PosToCodepointPosFrom pos.character colPos; text.source.codepointPosToUtf8PosFrom colPos chr def leanPosToLspPos (text : FileMap) : Lean.Position → Lsp.Position | ⟨ln, col⟩ => ⟨ln-1, text.source.codepointPosToUtf16PosFrom col (text.positions.get! $ ln - 1)⟩ end FileMap end Lean
671f920441993b064ee0bbc5986627a6b519f9d6
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/buffer/parser/basic.lean
ddccfc07a2548fc1d09cca3781e12471eb30c903
[]
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
31,832
lean
/- Copyright (c) 2020 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.string.basic import Mathlib.PostPort namespace Mathlib /-! # Parsers `parser α` is the type that describes a computation that can ingest a `char_buffer` and output, if successful, a term of type `α`. This file expands on the definitions in the core library, proving that all the core library parsers are `valid`. There are also lemmas on the composability of parsers. ## Main definitions * `parse_result.pos` : The position of a `char_buffer` at which a `parser α` has finished. * `parser.valid` : The property that a parser only moves forward within a buffer, in both cases of success or failure. ## Implementation details Lemmas about how parsers are valid are in the `valid` namespace. That allows using projection notation for shorter term proofs that are parallel to the definitions of the parsers in structure. -/ /-- For some `parse_result α`, give the position at which the result was provided, in either the `done` or the `fail` case. -/ @[simp] def parse_result.pos {α : Type} : parse_result α → ℕ := sorry namespace parser /-- A `parser α` is defined to be `valid` if the result `p cb n` it gives, for some `cb : char_buffer` and `n : ℕ`, (whether `done` or `fail`), is always at a `parse_result.pos` that is at least `n`. Additionally, if the position of the result of the parser was within the size of the `cb`, then the input to the parser must have been within `cb.size` too. -/ def valid {α : Type} (p : parser α) := ∀ (cb : char_buffer) (n : ℕ), n ≤ parse_result.pos (p cb n) ∧ (parse_result.pos (p cb n) ≤ buffer.size cb → n ≤ buffer.size cb) theorem fail_iff {α : Type} (p : parser α) (cb : char_buffer) (n : ℕ) : (∀ (pos' : ℕ) (result : α), p cb n ≠ parse_result.done pos' result) ↔ ∃ (pos' : ℕ), ∃ (err : dlist string), p cb n = parse_result.fail pos' err := sorry theorem success_iff {α : Type} (p : parser α) (cb : char_buffer) (n : ℕ) : (∀ (pos' : ℕ) (err : dlist string), p cb n ≠ parse_result.fail pos' err) ↔ ∃ (pos' : ℕ), ∃ (result : α), p cb n = parse_result.done pos' result := sorry theorem decorate_errors_fail {α : Type} {msgs : thunk (List string)} {p : parser α} {cb : char_buffer} {n : ℕ} {n' : ℕ} {err : dlist string} (h : p cb n = parse_result.fail n' err) : decorate_errors msgs p cb n = parse_result.fail n (dlist.lazy_of_list fun (_ : Unit) => msgs Unit.unit) := sorry theorem decorate_errors_success {α : Type} {msgs : thunk (List string)} {p : parser α} {cb : char_buffer} {n : ℕ} {n' : ℕ} {a : α} (h : p cb n = parse_result.done n' a) : decorate_errors msgs p cb n = parse_result.done n' a := sorry theorem decorate_error_fail {α : Type} {msg : thunk string} {p : parser α} {cb : char_buffer} {n : ℕ} {n' : ℕ} {err : dlist string} (h : p cb n = parse_result.fail n' err) : decorate_error msg p cb n = parse_result.fail n (dlist.lazy_of_list fun (_ : Unit) => [msg Unit.unit]) := decorate_errors_fail h theorem decorate_error_success {α : Type} {msg : thunk string} {p : parser α} {cb : char_buffer} {n : ℕ} {n' : ℕ} {a : α} (h : p cb n = parse_result.done n' a) : decorate_error msg p cb n = parse_result.done n' a := decorate_errors_success h @[simp] theorem decorate_errors_eq_done {α : Type} {msgs : thunk (List string)} {p : parser α} {cb : char_buffer} {n : ℕ} {n' : ℕ} {a : α} : decorate_errors msgs p cb n = parse_result.done n' a ↔ p cb n = parse_result.done n' a := sorry @[simp] theorem decorate_error_eq_done {α : Type} {msg : thunk string} {p : parser α} {cb : char_buffer} {n : ℕ} {n' : ℕ} {a : α} : decorate_error msg p cb n = parse_result.done n' a ↔ p cb n = parse_result.done n' a := decorate_errors_eq_done @[simp] theorem decorate_errors_eq_fail {α : Type} {msgs : thunk (List string)} {p : parser α} {cb : char_buffer} {n : ℕ} {err : dlist string} : decorate_errors msgs p cb n = parse_result.fail n err ↔ (err = dlist.lazy_of_list fun (_ : Unit) => msgs Unit.unit) ∧ ∃ (np : ℕ), ∃ (err' : dlist string), p cb n = parse_result.fail np err' := sorry @[simp] theorem decorate_error_eq_fail {α : Type} {msg : thunk string} {p : parser α} {cb : char_buffer} {n : ℕ} {err : dlist string} : decorate_error msg p cb n = parse_result.fail n err ↔ (err = dlist.lazy_of_list fun (_ : Unit) => [msg Unit.unit]) ∧ ∃ (np : ℕ), ∃ (err' : dlist string), p cb n = parse_result.fail np err' := decorate_errors_eq_fail @[simp] theorem return_eq_pure {α : Type} {a : α} : return a = pure a := rfl theorem pure_eq_done {α : Type} {a : α} : pure a = fun (_x : char_buffer) (n : ℕ) => parse_result.done n a := rfl @[simp] theorem pure_ne_fail {α : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {err : dlist string} {a : α} : pure a cb n ≠ parse_result.fail n' err := sorry @[simp] theorem bind_eq_bind {α : Type} {β : Type} {p : parser α} (f : α → parser β) : parser.bind p f = p >>= f := rfl @[simp] theorem bind_eq_done {α : Type} {β : Type} {p : parser α} {cb : char_buffer} {n : ℕ} {n' : ℕ} {b : β} {f : α → parser β} : bind p f cb n = parse_result.done n' b ↔ ∃ (np : ℕ), ∃ (a : α), p cb n = parse_result.done np a ∧ f a cb np = parse_result.done n' b := sorry @[simp] theorem bind_eq_fail {α : Type} {β : Type} {p : parser α} {cb : char_buffer} {n : ℕ} {n' : ℕ} {err : dlist string} {f : α → parser β} : bind p f cb n = parse_result.fail n' err ↔ p cb n = parse_result.fail n' err ∨ ∃ (np : ℕ), ∃ (a : α), p cb n = parse_result.done np a ∧ f a cb np = parse_result.fail n' err := sorry @[simp] theorem and_then_eq_bind {α : Type} {β : Type} {m : Type → Type} [Monad m] (a : m α) (b : m β) : a >> b = do a b := rfl theorem and_then_fail {α : Type} {p : parser α} {cb : char_buffer} {n : ℕ} {n' : ℕ} {err : dlist string} : has_bind.and_then p (return Unit.unit) cb n = parse_result.fail n' err ↔ p cb n = parse_result.fail n' err := sorry theorem and_then_success {α : Type} {p : parser α} {cb : char_buffer} {n : ℕ} {n' : ℕ} : has_bind.and_then p (return Unit.unit) cb n = parse_result.done n' Unit.unit ↔ ∃ (a : α), p cb n = parse_result.done n' a := sorry @[simp] theorem map_eq_done {α : Type} {β : Type} {p : parser α} {cb : char_buffer} {n : ℕ} {n' : ℕ} {b : β} {f : α → β} : Functor.map f p cb n = parse_result.done n' b ↔ ∃ (a : α), p cb n = parse_result.done n' a ∧ f a = b := sorry @[simp] theorem map_eq_fail {α : Type} {β : Type} {p : parser α} {cb : char_buffer} {n : ℕ} {n' : ℕ} {err : dlist string} {f : α → β} : Functor.map f p cb n = parse_result.fail n' err ↔ p cb n = parse_result.fail n' err := sorry @[simp] theorem map_const_eq_done {α : Type} {β : Type} {p : parser α} {cb : char_buffer} {n : ℕ} {n' : ℕ} {b : β} {b' : β} : Functor.mapConst b p cb n = parse_result.done n' b' ↔ ∃ (a : α), p cb n = parse_result.done n' a ∧ b = b' := sorry @[simp] theorem map_const_eq_fail {α : Type} {β : Type} {p : parser α} {cb : char_buffer} {n : ℕ} {n' : ℕ} {err : dlist string} {b : β} : Functor.mapConst b p cb n = parse_result.fail n' err ↔ p cb n = parse_result.fail n' err := sorry theorem map_const_rev_eq_done {α : Type} {β : Type} {p : parser α} {cb : char_buffer} {n : ℕ} {n' : ℕ} {b : β} {b' : β} : functor.map_const_rev p b cb n = parse_result.done n' b' ↔ ∃ (a : α), p cb n = parse_result.done n' a ∧ b = b' := map_const_eq_done theorem map_rev_const_eq_fail {α : Type} {β : Type} {p : parser α} {cb : char_buffer} {n : ℕ} {n' : ℕ} {err : dlist string} {b : β} : functor.map_const_rev p b cb n = parse_result.fail n' err ↔ p cb n = parse_result.fail n' err := map_const_eq_fail @[simp] theorem orelse_eq_orelse {α : Type} {p : parser α} {q : parser α} : parser.orelse p q = (p <|> q) := rfl @[simp] theorem orelse_eq_done {α : Type} {p : parser α} {q : parser α} {cb : char_buffer} {n : ℕ} {n' : ℕ} {a : α} : has_orelse.orelse p q cb n = parse_result.done n' a ↔ p cb n = parse_result.done n' a ∨ q cb n = parse_result.done n' a ∧ ∃ (err : dlist string), p cb n = parse_result.fail n err := sorry @[simp] theorem orelse_eq_fail_eq {α : Type} {p : parser α} {q : parser α} {cb : char_buffer} {n : ℕ} {err : dlist string} : has_orelse.orelse p q cb n = parse_result.fail n err ↔ (p cb n = parse_result.fail n err ∧ ∃ (nq : ℕ), ∃ (errq : dlist string), n < nq ∧ q cb n = parse_result.fail nq errq) ∨ ∃ (errp : dlist string), ∃ (errq : dlist string), p cb n = parse_result.fail n errp ∧ q cb n = parse_result.fail n errq ∧ errp ++ errq = err := sorry theorem orelse_eq_fail_invalid_lt {α : Type} {p : parser α} {q : parser α} {cb : char_buffer} {n : ℕ} {n' : ℕ} {err : dlist string} (hn : n' < n) : has_orelse.orelse p q cb n = parse_result.fail n' err ↔ p cb n = parse_result.fail n' err ∨ q cb n = parse_result.fail n' err ∧ ∃ (errp : dlist string), p cb n = parse_result.fail n errp := sorry theorem orelse_eq_fail_of_valid_ne {α : Type} {p : parser α} {q : parser α} {cb : char_buffer} {n : ℕ} {n' : ℕ} {err : dlist string} (hv : valid q) (hn : n ≠ n') : has_orelse.orelse p q cb n = parse_result.fail n' err ↔ p cb n = parse_result.fail n' err := sorry @[simp] theorem failure_eq_failure {α : Type} : parser.failure = failure := rfl @[simp] theorem failure_def {α : Type} {cb : char_buffer} {n : ℕ} : failure cb n = parse_result.fail n dlist.empty := rfl theorem not_failure_eq_done {α : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {a : α} : ¬failure cb n = parse_result.done n' a := sorry theorem failure_eq_fail {α : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {err : dlist string} : failure cb n = parse_result.fail n' err ↔ n = n' ∧ err = dlist.empty := sorry theorem seq_eq_done {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {b : β} {f : parser (α → β)} {p : parser α} : Seq.seq f p cb n = parse_result.done n' b ↔ ∃ (nf : ℕ), ∃ (f' : α → β), ∃ (a : α), f cb n = parse_result.done nf f' ∧ p cb nf = parse_result.done n' a ∧ f' a = b := sorry theorem seq_eq_fail {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {err : dlist string} {f : parser (α → β)} {p : parser α} : Seq.seq f p cb n = parse_result.fail n' err ↔ f cb n = parse_result.fail n' err ∨ ∃ (nf : ℕ), ∃ (f' : α → β), f cb n = parse_result.done nf f' ∧ p cb nf = parse_result.fail n' err := sorry theorem seq_left_eq_done {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {a : α} {p : parser α} {q : parser β} : SeqLeft.seqLeft p q cb n = parse_result.done n' a ↔ ∃ (np : ℕ), ∃ (b : β), p cb n = parse_result.done np a ∧ q cb np = parse_result.done n' b := sorry theorem seq_left_eq_fail {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {err : dlist string} {p : parser α} {q : parser β} : SeqLeft.seqLeft p q cb n = parse_result.fail n' err ↔ p cb n = parse_result.fail n' err ∨ ∃ (np : ℕ), ∃ (a : α), p cb n = parse_result.done np a ∧ q cb np = parse_result.fail n' err := sorry theorem seq_right_eq_done {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {b : β} {p : parser α} {q : parser β} : SeqRight.seqRight p q cb n = parse_result.done n' b ↔ ∃ (np : ℕ), ∃ (a : α), p cb n = parse_result.done np a ∧ q cb np = parse_result.done n' b := sorry theorem seq_right_eq_fail {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {err : dlist string} {p : parser α} {q : parser β} : SeqRight.seqRight p q cb n = parse_result.fail n' err ↔ p cb n = parse_result.fail n' err ∨ ∃ (np : ℕ), ∃ (a : α), p cb n = parse_result.done np a ∧ q cb np = parse_result.fail n' err := sorry theorem mmap_eq_done {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {f : α → parser β} {a : α} {l : List α} {b : β} {l' : List β} : mmap f (a :: l) cb n = parse_result.done n' (b :: l') ↔ ∃ (np : ℕ), f a cb n = parse_result.done np b ∧ mmap f l cb np = parse_result.done n' l' := sorry theorem mmap'_eq_done {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {f : α → parser β} {a : α} {l : List α} : mmap' f (a :: l) cb n = parse_result.done n' Unit.unit ↔ ∃ (np : ℕ), ∃ (b : β), f a cb n = parse_result.done np b ∧ mmap' f l cb np = parse_result.done n' Unit.unit := sorry theorem guard_eq_done {cb : char_buffer} {n : ℕ} {n' : ℕ} {p : Prop} [Decidable p] : guard p cb n = parse_result.done n' Unit.unit ↔ p ∧ n = n' := sorry theorem guard_eq_fail {cb : char_buffer} {n : ℕ} {n' : ℕ} {err : dlist string} {p : Prop} [Decidable p] : guard p cb n = parse_result.fail n' err ↔ ¬p ∧ n = n' ∧ err = dlist.empty := sorry namespace valid theorem mono_done {α : Type} {p : parser α} {cb : char_buffer} {n : ℕ} {n' : ℕ} {a : α} (hp : valid p) (h : p cb n = parse_result.done n' a) : n ≤ n' := sorry theorem mono_fail {α : Type} {p : parser α} {cb : char_buffer} {n : ℕ} {n' : ℕ} {err : dlist string} (hp : valid p) (h : p cb n = parse_result.fail n' err) : n ≤ n' := sorry theorem pure {α : Type} {a : α} : valid (pure a) := sorry @[simp] theorem bind {α : Type} {β : Type} {p : parser α} {f : α → parser β} (hp : valid p) (hf : ∀ (a : α), valid (f a)) : valid (p >>= f) := sorry theorem and_then {α : Type} {β : Type} {p : parser α} {q : parser β} (hp : valid p) (hq : valid q) : valid (p >> q) := bind hp fun (_x : α) => hq @[simp] theorem map {α : Type} {β : Type} {p : parser α} (hp : valid p) {f : α → β} : valid (f <$> p) := bind hp fun (_x : α) => pure @[simp] theorem seq {α : Type} {β : Type} {p : parser α} {f : parser (α → β)} (hf : valid f) (hp : valid p) : valid (f <*> p) := bind hf fun (_x : α → β) => map hp @[simp] theorem mmap {α : Type} {β : Type} {l : List α} {f : α → parser β} (h : ∀ (a : α), a ∈ l → valid (f a)) : valid (mmap f l) := sorry @[simp] theorem mmap' {α : Type} {β : Type} {l : List α} {f : α → parser β} (h : ∀ (a : α), a ∈ l → valid (f a)) : valid (mmap' f l) := sorry @[simp] theorem failure {α : Type} : valid failure := sorry @[simp] theorem guard {p : Prop} [Decidable p] : valid (guard p) := sorry @[simp] theorem orelse {α : Type} {p : parser α} {q : parser α} (hp : valid p) (hq : valid q) : valid (p <|> q) := sorry @[simp] theorem decorate_errors {α : Type} {msgs : thunk (List string)} {p : parser α} (hp : valid p) : valid (decorate_errors msgs p) := sorry @[simp] theorem decorate_error {α : Type} {msg : thunk string} {p : parser α} (hp : valid p) : valid (decorate_error msg p) := decorate_errors hp @[simp] theorem any_char : valid any_char := sorry @[simp] theorem sat {p : char → Prop} [decidable_pred p] : valid (sat p) := sorry @[simp] theorem eps : valid eps := pure theorem ch {c : char} : valid (ch c) := decorate_error (and_then sat eps) theorem char_buf {s : char_buffer} : valid (char_buf s) := decorate_error (mmap' fun (_x : char) (_x_1 : _x ∈ buffer.to_list s) => ch) theorem one_of {cs : List char} : valid (one_of cs) := decorate_errors sat theorem one_of' {cs : List char} : valid (one_of' cs) := and_then one_of eps theorem str {s : string} : valid (str s) := decorate_error (mmap' fun (_x : char) (_x_1 : _x ∈ string.to_list s) => ch) theorem remaining : valid remaining := fun (_x : char_buffer) (_x_1 : ℕ) => { left := le_refl _x_1, right := fun (h : parse_result.pos (remaining _x _x_1) ≤ buffer.size _x) => h } theorem eof : valid eof := decorate_error (bind remaining fun (_x : ℕ) => guard) theorem foldr_core_zero {α : Type} {β : Type} {p : parser α} {f : α → β → β} {b : β} : valid (foldr_core f p b 0) := failure theorem foldr_core {α : Type} {β : Type} {p : parser α} {f : α → β → β} {b : β} (hp : valid p) {reps : ℕ} : valid (foldr_core f p b reps) := sorry theorem foldr {α : Type} {β : Type} {p : parser α} {b : β} {f : α → β → β} (hp : valid p) : valid (foldr f p b) := fun (_x : char_buffer) (_x_1 : ℕ) => foldr_core hp _x _x_1 theorem foldl_core_zero {α : Type} {β : Type} {p : parser α} {f : β → α → β} {b : β} : valid (foldl_core f b p 0) := failure theorem foldl_core {α : Type} {β : Type} {f : α → β → α} {p : parser β} (hp : valid p) {a : α} {reps : ℕ} : valid (foldl_core f a p reps) := sorry theorem foldl {α : Type} {β : Type} {a : α} {f : α → β → α} {p : parser β} (hp : valid p) : valid (foldl f a p) := fun (_x : char_buffer) (_x_1 : ℕ) => foldl_core hp _x _x_1 theorem many {α : Type} {p : parser α} (hp : valid p) : valid (many p) := foldr hp theorem many_char {p : parser char} (hp : valid p) : valid (many_char p) := map (many hp) theorem many' {α : Type} {p : parser α} (hp : valid p) : valid (many' p) := and_then (many hp) eps theorem many1 {α : Type} {p : parser α} (hp : valid p) : valid (many1 p) := seq (map hp) (many hp) theorem many_char1 {p : parser char} (hp : valid p) : valid (many_char1 p) := map (many1 hp) theorem sep_by1 {α : Type} {p : parser α} {sep : parser Unit} (hp : valid p) (hs : valid sep) : valid (sep_by1 sep p) := seq (map hp) (many (and_then hs hp)) theorem sep_by {α : Type} {p : parser α} {sep : parser Unit} (hp : valid p) (hs : valid sep) : valid (sep_by sep p) := orelse (sep_by1 hp hs) pure theorem fix_core {α : Type} {F : parser α → parser α} (hF : ∀ (p : parser α), valid p → valid (F p)) (max_depth : ℕ) : valid (fix_core F max_depth) := sorry theorem digit : valid digit := decorate_error (bind sat fun (_x : char) => pure) theorem nat : valid nat := decorate_error (bind (many1 digit) fun (_x : List ℕ) => pure) theorem fix {α : Type} {F : parser α → parser α} (hF : ∀ (p : parser α), valid p → valid (F p)) : valid (fix F) := fun (_x : char_buffer) (_x_1 : ℕ) => fix_core hF (buffer.size _x - _x_1 + 1) _x _x_1 end valid @[simp] theorem orelse_pure_eq_fail {α : Type} {p : parser α} {cb : char_buffer} {n : ℕ} {n' : ℕ} {err : dlist string} {a : α} : has_orelse.orelse p (pure a) cb n = parse_result.fail n' err ↔ p cb n = parse_result.fail n' err ∧ n ≠ n' := sorry theorem any_char_eq_done {cb : char_buffer} {n : ℕ} {n' : ℕ} (hn : n < buffer.size cb) {c : char} : any_char cb n = parse_result.done n' c ↔ n' = n + 1 ∧ buffer.read cb { val := n, property := hn } = c := sorry theorem sat_eq_done {cb : char_buffer} {n : ℕ} {n' : ℕ} (hn : n < buffer.size cb) {c : char} {p : char → Prop} [decidable_pred p] : sat p cb n = parse_result.done n' c ↔ p c ∧ n' = n + 1 ∧ buffer.read cb { val := n, property := hn } = c := sorry theorem eps_eq_done {cb : char_buffer} {n : ℕ} {n' : ℕ} : eps cb n = parse_result.done n' Unit.unit ↔ n = n' := sorry theorem ch_eq_done {cb : char_buffer} {n : ℕ} {n' : ℕ} (hn : n < buffer.size cb) {c : char} : ch c cb n = parse_result.done n' Unit.unit ↔ n' = n + 1 ∧ buffer.read cb { val := n, property := hn } = c := sorry -- TODO: add char_buf_eq_done, needs lemmas about matching buffers theorem one_of_eq_done {cb : char_buffer} {n : ℕ} {n' : ℕ} (hn : n < buffer.size cb) {c : char} {cs : List char} : one_of cs cb n = parse_result.done n' c ↔ c ∈ cs ∧ n' = n + 1 ∧ buffer.read cb { val := n, property := hn } = c := sorry theorem one_of'_eq_done {cb : char_buffer} {n : ℕ} {n' : ℕ} (hn : n < buffer.size cb) {cs : List char} : one_of' cs cb n = parse_result.done n' Unit.unit ↔ buffer.read cb { val := n, property := hn } ∈ cs ∧ n' = n + 1 := sorry theorem remaining_eq_done {cb : char_buffer} {n : ℕ} {n' : ℕ} {r : ℕ} : remaining cb n = parse_result.done n' r ↔ n = n' ∧ buffer.size cb - n = r := sorry theorem eof_eq_done {cb : char_buffer} {n : ℕ} {n' : ℕ} : eof cb n = parse_result.done n' Unit.unit ↔ n = n' ∧ buffer.size cb ≤ n := sorry @[simp] theorem foldr_core_zero_eq_done {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {b : β} {f : α → β → β} {p : parser α} {b' : β} : foldr_core f p b 0 cb n ≠ parse_result.done n' b' := sorry theorem foldr_core_eq_done {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {b : β} {f : α → β → β} {p : parser α} {reps : ℕ} {b' : β} : foldr_core f p b (reps + 1) cb n = parse_result.done n' b' ↔ (∃ (np : ℕ), ∃ (a : α), ∃ (xs : β), p cb n = parse_result.done np a ∧ foldr_core f p b reps cb np = parse_result.done n' xs ∧ f a xs = b') ∨ n = n' ∧ b = b' ∧ ∃ (err : dlist string), p cb n = parse_result.fail n err ∨ ∃ (np : ℕ), ∃ (a : α), p cb n = parse_result.done np a ∧ foldr_core f p b reps cb np = parse_result.fail n err := sorry @[simp] theorem foldr_core_zero_eq_fail {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {b : β} {f : α → β → β} {p : parser α} {err : dlist string} : foldr_core f p b 0 cb n = parse_result.fail n' err ↔ n = n' ∧ err = dlist.empty := sorry theorem foldr_core_succ_eq_fail {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {b : β} {f : α → β → β} {p : parser α} {reps : ℕ} {err : dlist string} : foldr_core f p b (reps + 1) cb n = parse_result.fail n' err ↔ n ≠ n' ∧ (p cb n = parse_result.fail n' err ∨ ∃ (np : ℕ), ∃ (a : α), p cb n = parse_result.done np a ∧ foldr_core f p b reps cb np = parse_result.fail n' err) := sorry theorem foldr_eq_done {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {b : β} {f : α → β → β} {p : parser α} {b' : β} : foldr f p b cb n = parse_result.done n' b' ↔ (∃ (np : ℕ), ∃ (a : α), ∃ (x : β), p cb n = parse_result.done np a ∧ foldr_core f p b (buffer.size cb - n) cb np = parse_result.done n' x ∧ f a x = b') ∨ n = n' ∧ b = b' ∧ ∃ (err : dlist string), p cb n = parse_result.fail n err ∨ ∃ (np : ℕ), ∃ (x : α), p cb n = parse_result.done np x ∧ foldr_core f p b (buffer.size cb - n) cb np = parse_result.fail n err := sorry theorem foldr_eq_fail_of_valid_at_end {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {b : β} {f : α → β → β} {p : parser α} {err : dlist string} (hp : valid p) (hc : buffer.size cb ≤ n) : foldr f p b cb n = parse_result.fail n' err ↔ n < n' ∧ (p cb n = parse_result.fail n' err ∨ ∃ (a : α), p cb n = parse_result.done n' a ∧ err = dlist.empty) := sorry theorem foldr_eq_fail {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {b : β} {f : α → β → β} {p : parser α} {err : dlist string} : foldr f p b cb n = parse_result.fail n' err ↔ n ≠ n' ∧ (p cb n = parse_result.fail n' err ∨ ∃ (np : ℕ), ∃ (a : α), p cb n = parse_result.done np a ∧ foldr_core f p b (buffer.size cb - n) cb np = parse_result.fail n' err) := sorry @[simp] theorem foldl_core_zero_eq_done {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {b : β} {f : β → α → β} {p : parser α} {b' : β} : foldl_core f b p 0 cb n = parse_result.done n' b' ↔ False := sorry theorem foldl_core_eq_done {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {b : β} {f : β → α → β} {p : parser α} {reps : ℕ} {b' : β} : foldl_core f b p (reps + 1) cb n = parse_result.done n' b' ↔ (∃ (np : ℕ), ∃ (a : α), p cb n = parse_result.done np a ∧ foldl_core f (f b a) p reps cb np = parse_result.done n' b') ∨ n = n' ∧ b = b' ∧ ∃ (err : dlist string), p cb n = parse_result.fail n err ∨ ∃ (np : ℕ), ∃ (a : α), p cb n = parse_result.done np a ∧ foldl_core f (f b a) p reps cb np = parse_result.fail n err := sorry @[simp] theorem foldl_core_zero_eq_fail {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {b : β} {f : β → α → β} {p : parser α} {err : dlist string} : foldl_core f b p 0 cb n = parse_result.fail n' err ↔ n = n' ∧ err = dlist.empty := sorry theorem foldl_core_succ_eq_fail {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {b : β} {f : β → α → β} {p : parser α} {reps : ℕ} {err : dlist string} : foldl_core f b p (reps + 1) cb n = parse_result.fail n' err ↔ n ≠ n' ∧ (p cb n = parse_result.fail n' err ∨ ∃ (np : ℕ), ∃ (a : α), p cb n = parse_result.done np a ∧ foldl_core f (f b a) p reps cb np = parse_result.fail n' err) := sorry theorem foldl_eq_done {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {b : β} {f : β → α → β} {p : parser α} {b' : β} : foldl f b p cb n = parse_result.done n' b' ↔ (∃ (np : ℕ), ∃ (a : α), p cb n = parse_result.done np a ∧ foldl_core f (f b a) p (buffer.size cb - n) cb np = parse_result.done n' b') ∨ n = n' ∧ b = b' ∧ ∃ (err : dlist string), p cb n = parse_result.fail n err ∨ ∃ (np : ℕ), ∃ (a : α), p cb n = parse_result.done np a ∧ foldl_core f (f b a) p (buffer.size cb - n) cb np = parse_result.fail n err := sorry theorem foldl_eq_fail {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {b : β} {f : β → α → β} {p : parser α} {err : dlist string} : foldl f b p cb n = parse_result.fail n' err ↔ n ≠ n' ∧ (p cb n = parse_result.fail n' err ∨ ∃ (np : ℕ), ∃ (a : α), p cb n = parse_result.done np a ∧ foldl_core f (f b a) p (buffer.size cb - n) cb np = parse_result.fail n' err) := sorry theorem many_eq_done_nil {α : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {p : parser α} : many p cb n = parse_result.done n' [] ↔ n = n' ∧ ∃ (err : dlist string), p cb n = parse_result.fail n err ∨ ∃ (np : ℕ), ∃ (a : α), p cb n = parse_result.done np a ∧ foldr_core List.cons p [] (buffer.size cb - n) cb np = parse_result.fail n err := sorry theorem many_eq_done {α : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {p : parser α} {x : α} {xs : List α} : many p cb n = parse_result.done n' (x :: xs) ↔ ∃ (np : ℕ), p cb n = parse_result.done np x ∧ foldr_core List.cons p [] (buffer.size cb - n) cb np = parse_result.done n' xs := sorry theorem many_eq_fail {α : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {p : parser α} {err : dlist string} : many p cb n = parse_result.fail n' err ↔ n ≠ n' ∧ (p cb n = parse_result.fail n' err ∨ ∃ (np : ℕ), ∃ (a : α), p cb n = parse_result.done np a ∧ foldr_core List.cons p [] (buffer.size cb - n) cb np = parse_result.fail n' err) := sorry theorem many_char_eq_done_empty {cb : char_buffer} {n : ℕ} {n' : ℕ} {p : parser char} : many_char p cb n = parse_result.done n' string.empty ↔ n = n' ∧ ∃ (err : dlist string), p cb n = parse_result.fail n err ∨ ∃ (np : ℕ), ∃ (c : char), p cb n = parse_result.done np c ∧ foldr_core List.cons p [] (buffer.size cb - n) cb np = parse_result.fail n err := sorry theorem many_char_eq_done_not_empty {cb : char_buffer} {n : ℕ} {n' : ℕ} {p : parser char} {s : string} (h : s ≠ string.empty) : many_char p cb n = parse_result.done n' s ↔ ∃ (np : ℕ), p cb n = parse_result.done np (string.head s) ∧ foldr_core List.cons p [] (buffer.size cb - n) cb np = parse_result.done n' (string.to_list (string.popn s 1)) := sorry theorem many_char_eq_many_of_to_list {cb : char_buffer} {n : ℕ} {n' : ℕ} {p : parser char} {s : string} : many_char p cb n = parse_result.done n' s ↔ many p cb n = parse_result.done n' (string.to_list s) := sorry theorem many'_eq_done {α : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {p : parser α} : many' p cb n = parse_result.done n' Unit.unit ↔ many p cb n = parse_result.done n' [] ∨ ∃ (np : ℕ), ∃ (a : α), ∃ (l : List α), many p cb n = parse_result.done n' (a :: l) ∧ p cb n = parse_result.done np a ∧ foldr_core List.cons p [] (buffer.size cb - n) cb np = parse_result.done n' l := sorry @[simp] theorem many1_ne_done_nil {α : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {p : parser α} : many1 p cb n ≠ parse_result.done n' [] := sorry theorem many1_eq_done {α : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {a : α} {p : parser α} {l : List α} : many1 p cb n = parse_result.done n' (a :: l) ↔ ∃ (np : ℕ), p cb n = parse_result.done np a ∧ many p cb np = parse_result.done n' l := sorry theorem many1_eq_fail {α : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {p : parser α} {err : dlist string} : many1 p cb n = parse_result.fail n' err ↔ p cb n = parse_result.fail n' err ∨ ∃ (np : ℕ), ∃ (a : α), p cb n = parse_result.done np a ∧ many p cb np = parse_result.fail n' err := sorry @[simp] theorem many_char1_ne_empty {cb : char_buffer} {n : ℕ} {n' : ℕ} {p : parser char} : many_char1 p cb n ≠ parse_result.done n' string.empty := sorry theorem many_char1_eq_done {cb : char_buffer} {n : ℕ} {n' : ℕ} {p : parser char} {s : string} (h : s ≠ string.empty) : many_char1 p cb n = parse_result.done n' s ↔ ∃ (np : ℕ), p cb n = parse_result.done np (string.head s) ∧ many_char p cb np = parse_result.done n' (string.popn s 1) := sorry @[simp] theorem sep_by1_ne_done_nil {α : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {sep : parser Unit} {p : parser α} : sep_by1 sep p cb n ≠ parse_result.done n' [] := sorry theorem sep_by1_eq_done {α : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {a : α} {sep : parser Unit} {p : parser α} {l : List α} : sep_by1 sep p cb n = parse_result.done n' (a :: l) ↔ ∃ (np : ℕ), p cb n = parse_result.done np a ∧ many (sep >> p) cb np = parse_result.done n' l := sorry theorem sep_by_eq_done_nil {α : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {sep : parser Unit} {p : parser α} : sep_by sep p cb n = parse_result.done n' [] ↔ n = n' ∧ ∃ (err : dlist string), sep_by1 sep p cb n = parse_result.fail n err := sorry @[simp] theorem fix_core_ne_done_zero {α : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {a : α} {F : parser α → parser α} : fix_core F 0 cb n ≠ parse_result.done n' a := sorry theorem fix_core_eq_done {α : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {a : α} {F : parser α → parser α} {max_depth : ℕ} : fix_core F (max_depth + 1) cb n = parse_result.done n' a ↔ F (fix_core F max_depth) cb n = parse_result.done n' a := sorry theorem digit_eq_done {cb : char_buffer} {n : ℕ} {n' : ℕ} (hn : n < buffer.size cb) {k : ℕ} : digit cb n = parse_result.done n' k ↔ n' = n + 1 ∧ k ≤ bit1 (bit0 (bit0 1)) ∧ char.to_nat (buffer.read cb { val := n, property := hn }) - char.to_nat (char.of_nat (bit0 (bit0 (bit0 (bit0 (bit1 1)))))) = k ∧ char.of_nat (bit0 (bit0 (bit0 (bit0 (bit1 1))))) ≤ buffer.read cb { val := n, property := hn } ∧ buffer.read cb { val := n, property := hn } ≤ char.of_nat (bit1 (bit0 (bit0 (bit1 (bit1 1))))) := sorry
0530bb6b52ffbcaf727b2e605fd90d4697f72bb9
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/mv_polynomial/invertible_auto.lean
e67209b2a5bf5e57df674c7927f9323411bfa638
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,203
lean
/- Copyright (c) 2020 Johan Commelin and Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin and Robert Y. Lewis -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.mv_polynomial.basic import Mathlib.ring_theory.algebra_tower import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # Invertible polynomials This file is a stub containing some basic facts about invertible elements in the ring of polynomials. -/ protected instance mv_polynomial.invertible_C (σ : Type u_1) {R : Type u_2} [comm_semiring R] (r : R) [invertible r] : invertible (coe_fn mv_polynomial.C r) := invertible.map (ring_hom.to_monoid_hom mv_polynomial.C) r /-- A natural number that is invertible when coerced to a commutative semiring `R` is also invertible when coerced to any polynomial ring with rational coefficients. Short-cut for typeclass resolution. -/ protected instance mv_polynomial.invertible_coe_nat (σ : Type u_1) (R : Type u_2) (p : ℕ) [comm_semiring R] [invertible ↑p] : invertible ↑p := is_scalar_tower.invertible_algebra_coe_nat R (mv_polynomial σ R) p end Mathlib
ca3cc0b5e25c0b8d3120dde5f6c4afdb154d14a1
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Init/Core.lean
5c5cc17a6c9bccc973ed4274bfc2125e312211be
[ "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
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
36,219
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura notation, basic datatypes and type classes -/ prelude import Init.Prelude import Init.SizeOf universe u v w def inline {α : Sort u} (a : α) : α := a @[inline] def flip {α : Sort u} {β : Sort v} {φ : Sort w} (f : α → β → φ) : β → α → φ := fun b a => f a b @[simp] theorem Function.const_apply {y : β} {x : α} : const α y x = y := rfl @[simp] theorem Function.comp_apply {f : β → δ} {g : α → β} {x : α} : comp f g x = f (g x) := rfl /-- Thunks are "lazy" values that are evaluated when first accessed using `Thunk.get/map/bind`. The value is then stored and not recomputed for all further accesses. -/ -- NOTE: the runtime has special support for the `Thunk` type to implement this behavior structure Thunk (α : Type u) : Type u where private fn : Unit → α attribute [extern "lean_mk_thunk"] Thunk.mk /-- Store a value in a thunk. Note that the value has already been computed, so there is no laziness. -/ @[extern "lean_thunk_pure"] protected def Thunk.pure (a : α) : Thunk α := ⟨fun _ => a⟩ -- NOTE: we use `Thunk.get` instead of `Thunk.fn` as the accessor primitive as the latter has an additional `Unit` argument @[extern "lean_thunk_get_own"] protected def Thunk.get (x : @& Thunk α) : α := x.fn () @[inline] protected def Thunk.map (f : α → β) (x : Thunk α) : Thunk β := ⟨fun _ => f x.get⟩ @[inline] protected def Thunk.bind (x : Thunk α) (f : α → Thunk β) : Thunk β := ⟨fun _ => (f x.get).get⟩ abbrev Eq.ndrecOn.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} {b : α} (h : a = b) (m : motive a) : motive b := Eq.ndrec m h structure Iff (a b : Prop) : Prop where intro :: (mp : a → b) (mpr : b → a) infix:20 " <-> " => Iff infix:20 " ↔ " => Iff inductive Sum (α : Type u) (β : Type v) where | inl (val : α) : Sum α β | inr (val : β) : Sum α β infixr:30 " ⊕ " => Sum inductive PSum (α : Sort u) (β : Sort v) where | inl (val : α) : PSum α β | inr (val : β) : PSum α β infixr:30 " ⊕' " => PSum structure Sigma {α : Type u} (β : α → Type v) where fst : α snd : β fst attribute [unbox] Sigma structure PSigma {α : Sort u} (β : α → Sort v) where fst : α snd : β fst inductive Exists {α : Sort u} (p : α → Prop) : Prop where | intro (w : α) (h : p w) : Exists p /- Auxiliary type used to compile `for x in xs` notation. -/ inductive ForInStep (α : Type u) where | done : α → ForInStep α | yield : α → ForInStep α class ForIn (m : Type u₁ → Type u₂) (ρ : Type u) (α : outParam (Type v)) where forIn {β} [Monad m] (x : ρ) (b : β) (f : α → β → m (ForInStep β)) : m β export ForIn (forIn) /- Auxiliary type used to compile `do` notation. -/ inductive DoResultPRBC (α β σ : Type u) where | «pure» : α → σ → DoResultPRBC α β σ | «return» : β → σ → DoResultPRBC α β σ | «break» : σ → DoResultPRBC α β σ | «continue» : σ → DoResultPRBC α β σ /- Auxiliary type used to compile `do` notation. -/ inductive DoResultPR (α β σ : Type u) where | «pure» : α → σ → DoResultPR α β σ | «return» : β → σ → DoResultPR α β σ /- Auxiliary type used to compile `do` notation. -/ inductive DoResultBC (σ : Type u) where | «break» : σ → DoResultBC σ | «continue» : σ → DoResultBC σ /- Auxiliary type used to compile `do` notation. -/ inductive DoResultSBC (α σ : Type u) where | «pureReturn» : α → σ → DoResultSBC α σ | «break» : σ → DoResultSBC α σ | «continue» : σ → DoResultSBC α σ class HasEquiv (α : Sort u) where Equiv : α → α → Sort v infix:50 " ≈ " => HasEquiv.Equiv class EmptyCollection (α : Type u) where emptyCollection : α notation "{" "}" => EmptyCollection.emptyCollection notation "∅" => EmptyCollection.emptyCollection /- Remark: tasks have an efficient implementation in the runtime. -/ structure Task (α : Type u) : Type u where pure :: (get : α) deriving Inhabited attribute [extern "lean_task_pure"] Task.pure attribute [extern "lean_task_get_own"] Task.get namespace Task /-- Task priority. Tasks with higher priority will always be scheduled before ones with lower priority. -/ abbrev Priority := Nat def Priority.default : Priority := 0 -- see `LEAN_MAX_PRIO` def Priority.max : Priority := 8 /-- Any priority higher than `Task.Priority.max` will result in the task being scheduled immediately on a dedicated thread. This is particularly useful for long-running and/or I/O-bound tasks since Lean will by default allocate no more non-dedicated workers than the number of cores to reduce context switches. -/ def Priority.dedicated : Priority := 9 @[noinline, extern "lean_task_spawn"] protected def spawn {α : Type u} (fn : Unit → α) (prio := Priority.default) : Task α := ⟨fn ()⟩ @[noinline, extern "lean_task_map"] protected def map {α : Type u} {β : Type v} (f : α → β) (x : Task α) (prio := Priority.default) : Task β := ⟨f x.get⟩ @[noinline, extern "lean_task_bind"] protected def bind {α : Type u} {β : Type v} (x : Task α) (f : α → Task β) (prio := Priority.default) : Task β := ⟨(f x.get).get⟩ end Task /- Some type that is not a scalar value in our runtime. -/ structure NonScalar where val : Nat /- Some type that is not a scalar value in our runtime and is universe polymorphic. -/ inductive PNonScalar : Type u where | mk (v : Nat) : PNonScalar @[simp] theorem Nat.add_zero (n : Nat) : n + 0 = n := rfl theorem optParam_eq (α : Sort u) (default : α) : optParam α default = α := rfl /- Boolean operators -/ @[extern c inline "#1 || #2"] def strictOr (b₁ b₂ : Bool) := b₁ || b₂ @[extern c inline "#1 && #2"] def strictAnd (b₁ b₂ : Bool) := b₁ && b₂ @[inline] def bne {α : Type u} [BEq α] (a b : α) : Bool := !(a == b) infix:50 " != " => bne /- Logical connectives an equality -/ def implies (a b : Prop) := a → b theorem implies.trans {p q r : Prop} (h₁ : implies p q) (h₂ : implies q r) : implies p r := fun hp => h₂ (h₁ hp) def trivial : True := ⟨⟩ theorem mt {a b : Prop} (h₁ : a → b) (h₂ : ¬b) : ¬a := fun ha => h₂ (h₁ ha) theorem not_false : ¬False := id theorem not_not_intro {p : Prop} (h : p) : ¬ ¬ p := fun hn : ¬ p => hn h -- proof irrelevance is built in theorem proofIrrel {a : Prop} (h₁ h₂ : a) : h₁ = h₂ := rfl theorem id.def {α : Sort u} (a : α) : id a = a := rfl @[macroInline] def Eq.mp {α β : Sort u} (h : α = β) (a : α) : β := h ▸ a @[macroInline] def Eq.mpr {α β : Sort u} (h : α = β) (b : β) : α := h ▸ b theorem Eq.substr {α : Sort u} {p : α → Prop} {a b : α} (h₁ : b = a) (h₂ : p a) : p b := h₁ ▸ h₂ theorem cast_eq {α : Sort u} (h : α = α) (a : α) : cast h a = a := rfl @[reducible] def Ne {α : Sort u} (a b : α) := ¬(a = b) infix:50 " ≠ " => Ne section Ne variable {α : Sort u} variable {a b : α} {p : Prop} theorem Ne.intro (h : a = b → False) : a ≠ b := h theorem Ne.elim (h : a ≠ b) : a = b → False := h theorem Ne.irrefl (h : a ≠ a) : False := h rfl theorem Ne.symm (h : a ≠ b) : b ≠ a := fun h₁ => h (h₁.symm) theorem false_of_ne : a ≠ a → False := Ne.irrefl theorem ne_false_of_self : p → p ≠ False := fun (hp : p) (h : p = False) => h ▸ hp theorem ne_true_of_not : ¬p → p ≠ True := fun (hnp : ¬p) (h : p = True) => have : ¬True := h ▸ hnp this trivial theorem true_ne_false : ¬True = False := ne_false_of_self trivial end Ne section variable {α β φ : Sort u} {a a' : α} {b b' : β} {c : φ} theorem HEq.ndrec.{u1, u2} {α : Sort u2} {a : α} {motive : {β : Sort u2} → β → Sort u1} (m : motive a) {β : Sort u2} {b : β} (h : HEq a b) : motive b := @HEq.rec α a (fun b _ => motive b) m β b h theorem HEq.ndrecOn.{u1, u2} {α : Sort u2} {a : α} {motive : {β : Sort u2} → β → Sort u1} {β : Sort u2} {b : β} (h : HEq a b) (m : motive a) : motive b := @HEq.rec α a (fun b _ => motive b) m β b h theorem HEq.elim {α : Sort u} {a : α} {p : α → Sort v} {b : α} (h₁ : HEq a b) (h₂ : p a) : p b := eq_of_heq h₁ ▸ h₂ theorem HEq.subst {p : (T : Sort u) → T → Prop} (h₁ : HEq a b) (h₂ : p α a) : p β b := HEq.ndrecOn h₁ h₂ theorem HEq.symm (h : HEq a b) : HEq b a := HEq.ndrecOn (motive := fun x => HEq x a) h (HEq.refl a) theorem heq_of_eq (h : a = a') : HEq a a' := Eq.subst h (HEq.refl a) theorem HEq.trans (h₁ : HEq a b) (h₂ : HEq b c) : HEq a c := HEq.subst h₂ h₁ theorem heq_of_heq_of_eq (h₁ : HEq a b) (h₂ : b = b') : HEq a b' := HEq.trans h₁ (heq_of_eq h₂) theorem heq_of_eq_of_heq (h₁ : a = a') (h₂ : HEq a' b) : HEq a b := HEq.trans (heq_of_eq h₁) h₂ def type_eq_of_heq (h : HEq a b) : α = β := HEq.ndrecOn (motive := @fun (x : Sort u) _ => α = x) h (Eq.refl α) end theorem eqRec_heq {α : Sort u} {φ : α → Sort v} {a a' : α} : (h : a = a') → (p : φ a) → HEq (Eq.recOn (motive := fun x _ => φ x) h p) p | rfl, p => HEq.refl p theorem heq_of_eqRec_eq {α β : Sort u} {a : α} {b : β} (h₁ : α = β) (h₂ : Eq.rec (motive := fun α _ => α) a h₁ = b) : HEq a b := by subst h₁ apply heq_of_eq exact h₂ theorem cast_heq {α β : Sort u} : (h : α = β) → (a : α) → HEq (cast h a) a | rfl, a => HEq.refl a variable {a b c d : Prop} theorem iff_iff_implies_and_implies (a b : Prop) : (a ↔ b) ↔ (a → b) ∧ (b → a) := Iff.intro (fun h => And.intro h.mp h.mpr) (fun h => Iff.intro h.left h.right) theorem Iff.refl (a : Prop) : a ↔ a := Iff.intro (fun h => h) (fun h => h) protected theorem Iff.rfl {a : Prop} : a ↔ a := Iff.refl a theorem Iff.trans (h₁ : a ↔ b) (h₂ : b ↔ c) : a ↔ c := Iff.intro (fun ha => Iff.mp h₂ (Iff.mp h₁ ha)) (fun hc => Iff.mpr h₁ (Iff.mpr h₂ hc)) theorem Iff.symm (h : a ↔ b) : b ↔ a := Iff.intro (Iff.mpr h) (Iff.mp h) theorem Iff.comm : (a ↔ b) ↔ (b ↔ a) := Iff.intro Iff.symm Iff.symm /- Exists -/ theorem Exists.elim {α : Sort u} {p : α → Prop} {b : Prop} (h₁ : Exists (fun x => p x)) (h₂ : ∀ (a : α), p a → b) : b := h₂ h₁.1 h₁.2 /- Decidable -/ theorem decide_true_eq_true (h : Decidable True) : @decide True h = true := match h with | isTrue h => rfl | isFalse h => False.elim <| h ⟨⟩ theorem decide_false_eq_false (h : Decidable False) : @decide False h = false := match h with | isFalse h => rfl | isTrue h => False.elim h /-- Similar to `decide`, but uses an explicit instance -/ @[inline] def toBoolUsing {p : Prop} (d : Decidable p) : Bool := decide p (h := d) theorem toBoolUsing_eq_true {p : Prop} (d : Decidable p) (h : p) : toBoolUsing d = true := decide_eq_true (s := d) h theorem ofBoolUsing_eq_true {p : Prop} {d : Decidable p} (h : toBoolUsing d = true) : p := of_decide_eq_true (s := d) h theorem ofBoolUsing_eq_false {p : Prop} {d : Decidable p} (h : toBoolUsing d = false) : ¬ p := of_decide_eq_false (s := d) h instance : Decidable True := isTrue trivial instance : Decidable False := isFalse not_false namespace Decidable variable {p q : Prop} @[macroInline] def byCases {q : Sort u} [dec : Decidable p] (h1 : p → q) (h2 : ¬p → q) : q := match dec with | isTrue h => h1 h | isFalse h => h2 h theorem em (p : Prop) [Decidable p] : p ∨ ¬p := byCases Or.inl Or.inr theorem byContradiction [dec : Decidable p] (h : ¬p → False) : p := byCases id (fun np => False.elim (h np)) theorem of_not_not [Decidable p] : ¬ ¬ p → p := fun hnn => byContradiction (fun hn => absurd hn hnn) theorem not_and_iff_or_not (p q : Prop) [d₁ : Decidable p] [d₂ : Decidable q] : ¬ (p ∧ q) ↔ ¬ p ∨ ¬ q := Iff.intro (fun h => match d₁, d₂ with | isTrue h₁, isTrue h₂ => absurd (And.intro h₁ h₂) h | _, isFalse h₂ => Or.inr h₂ | isFalse h₁, _ => Or.inl h₁) (fun (h) ⟨hp, hq⟩ => match h with | Or.inl h => h hp | Or.inr h => h hq) end Decidable section variable {p q : Prop} @[inline] def decidableOfDecidableOfIff (hp : Decidable p) (h : p ↔ q) : Decidable q := if hp : p then isTrue (Iff.mp h hp) else isFalse fun hq => absurd (Iff.mpr h hq) hp @[inline] def decidableOfDecidableOfEq (hp : Decidable p) (h : p = q) : Decidable q := h ▸ hp end @[macroInline] instance {p q} [Decidable p] [Decidable q] : Decidable (p → q) := if hp : p then if hq : q then isTrue (fun h => hq) else isFalse (fun h => absurd (h hp) hq) else isTrue (fun h => absurd h hp) instance {p q} [Decidable p] [Decidable q] : Decidable (p ↔ q) := if hp : p then if hq : q then isTrue ⟨fun _ => hq, fun _ => hp⟩ else isFalse fun h => hq (h.1 hp) else if hq : q then isFalse fun h => hp (h.2 hq) else isTrue ⟨fun h => absurd h hp, fun h => absurd h hq⟩ /- if-then-else expression theorems -/ theorem if_pos {c : Prop} [h : Decidable c] (hc : c) {α : Sort u} {t e : α} : (ite c t e) = t := match h with | isTrue hc => rfl | isFalse hnc => absurd hc hnc theorem if_neg {c : Prop} [h : Decidable c] (hnc : ¬c) {α : Sort u} {t e : α} : (ite c t e) = e := match h with | isTrue hc => absurd hc hnc | isFalse hnc => rfl theorem dif_pos {c : Prop} [h : Decidable c] (hc : c) {α : Sort u} {t : c → α} {e : ¬ c → α} : (dite c t e) = t hc := match h with | isTrue hc => rfl | isFalse hnc => absurd hc hnc theorem dif_neg {c : Prop} [h : Decidable c] (hnc : ¬c) {α : Sort u} {t : c → α} {e : ¬ c → α} : (dite c t e) = e hnc := match h with | isTrue hc => absurd hc hnc | isFalse hnc => rfl -- Remark: dite and ite are "defally equal" when we ignore the proofs. theorem dif_eq_if (c : Prop) [h : Decidable c] {α : Sort u} (t : α) (e : α) : dite c (fun h => t) (fun h => e) = ite c t e := match h with | isTrue hc => rfl | isFalse hnc => rfl instance {c t e : Prop} [dC : Decidable c] [dT : Decidable t] [dE : Decidable e] : Decidable (if c then t else e) := match dC with | isTrue hc => dT | isFalse hc => dE instance {c : Prop} {t : c → Prop} {e : ¬c → Prop} [dC : Decidable c] [dT : ∀ h, Decidable (t h)] [dE : ∀ h, Decidable (e h)] : Decidable (if h : c then t h else e h) := match dC with | isTrue hc => dT hc | isFalse hc => dE hc /- Auxiliary definitions for generating compact `noConfusion` for enumeration types -/ abbrev noConfusionTypeEnum {α : Sort u} {β : Sort v} [DecidableEq β] (f : α → β) (P : Sort w) (x y : α) : Sort w := if f x = f y then P → P else P abbrev noConfusionEnum {α : Sort u} {β : Sort v} [DecidableEq β] (f : α → β) {P : Sort w} {x y : α} (h : x = y) : noConfusionTypeEnum f P x y := if h' : f x = f y then cast (@if_pos _ _ h' _ (P → P) (P)).symm (fun (h : P) => h) else False.elim (h' (congrArg f h)) /- Inhabited -/ instance : Inhabited Prop where default := True deriving instance Inhabited for NonScalar, PNonScalar, True, ForInStep class inductive Nonempty (α : Sort u) : Prop where | intro (val : α) : Nonempty α protected def Nonempty.elim {α : Sort u} {p : Prop} (h₁ : Nonempty α) (h₂ : α → p) : p := h₂ h₁.1 instance {α : Sort u} [Inhabited α] : Nonempty α := ⟨arbitrary⟩ theorem nonempty_of_exists {α : Sort u} {p : α → Prop} : Exists (fun x => p x) → Nonempty α | ⟨w, h⟩ => ⟨w⟩ /- Subsingleton -/ class Subsingleton (α : Sort u) : Prop where intro :: allEq : (a b : α) → a = b protected def Subsingleton.elim {α : Sort u} [h : Subsingleton α] : (a b : α) → a = b := h.allEq protected def Subsingleton.helim {α β : Sort u} [h₁ : Subsingleton α] (h₂ : α = β) (a : α) (b : β) : HEq a b := by subst h₂ apply heq_of_eq apply Subsingleton.elim instance (p : Prop) : Subsingleton p := ⟨fun a b => proofIrrel a b⟩ instance (p : Prop) : Subsingleton (Decidable p) := Subsingleton.intro fun | isTrue t₁ => fun | isTrue t₂ => rfl | isFalse f₂ => absurd t₁ f₂ | isFalse f₁ => fun | isTrue t₂ => absurd t₂ f₁ | isFalse f₂ => rfl theorem recSubsingleton {p : Prop} [h : Decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} [h₃ : ∀ (h : p), Subsingleton (h₁ h)] [h₄ : ∀ (h : ¬p), Subsingleton (h₂ h)] : Subsingleton (Decidable.casesOn (motive := fun _ => Sort u) h h₂ h₁) := match h with | isTrue h => h₃ h | isFalse h => h₄ h structure Equivalence {α : Sort u} (r : α → α → Prop) : Prop where refl : ∀ x, r x x symm : ∀ {x y}, r x y → r y x trans : ∀ {x y z}, r x y → r y z → r x z def emptyRelation {α : Sort u} (a₁ a₂ : α) : Prop := False def Subrelation {α : Sort u} (q r : α → α → Prop) := ∀ {x y}, q x y → r x y def InvImage {α : Sort u} {β : Sort v} (r : β → β → Prop) (f : α → β) : α → α → Prop := fun a₁ a₂ => r (f a₁) (f a₂) inductive TC {α : Sort u} (r : α → α → Prop) : α → α → Prop where | base : ∀ a b, r a b → TC r a b | trans : ∀ a b c, TC r a b → TC r b c → TC r a c /- Subtype -/ namespace Subtype def existsOfSubtype {α : Type u} {p : α → Prop} : { x // p x } → Exists (fun x => p x) | ⟨a, h⟩ => ⟨a, h⟩ variable {α : Type u} {p : α → Prop} protected theorem eq : ∀ {a1 a2 : {x // p x}}, val a1 = val a2 → a1 = a2 | ⟨x, h1⟩, ⟨_, _⟩, rfl => rfl theorem eta (a : {x // p x}) (h : p (val a)) : mk (val a) h = a := by cases a exact rfl instance {α : Type u} {p : α → Prop} {a : α} (h : p a) : Inhabited {x // p x} where default := ⟨a, h⟩ instance {α : Type u} {p : α → Prop} [DecidableEq α] : DecidableEq {x : α // p x} := fun ⟨a, h₁⟩ ⟨b, h₂⟩ => if h : a = b then isTrue (by subst h; exact rfl) else isFalse (fun h' => Subtype.noConfusion h' (fun h' => absurd h' h)) end Subtype /- Sum -/ section variable {α : Type u} {β : Type v} instance Sum.inhabitedLeft [h : Inhabited α] : Inhabited (Sum α β) where default := Sum.inl arbitrary instance Sum.inhabitedRight [h : Inhabited β] : Inhabited (Sum α β) where default := Sum.inr arbitrary instance {α : Type u} {β : Type v} [DecidableEq α] [DecidableEq β] : DecidableEq (Sum α β) := fun a b => match a, b with | Sum.inl a, Sum.inl b => if h : a = b then isTrue (h ▸ rfl) else isFalse fun h' => Sum.noConfusion h' fun h' => absurd h' h | Sum.inr a, Sum.inr b => if h : a = b then isTrue (h ▸ rfl) else isFalse fun h' => Sum.noConfusion h' fun h' => absurd h' h | Sum.inr a, Sum.inl b => isFalse fun h => Sum.noConfusion h | Sum.inl a, Sum.inr b => isFalse fun h => Sum.noConfusion h end /- Product -/ instance [Inhabited α] [Inhabited β] : Inhabited (α × β) where default := (arbitrary, arbitrary) instance [DecidableEq α] [DecidableEq β] : DecidableEq (α × β) := fun (a, b) (a', b') => match decEq a a' with | isTrue e₁ => match decEq b b' with | isTrue e₂ => isTrue (e₁ ▸ e₂ ▸ rfl) | isFalse n₂ => isFalse fun h => Prod.noConfusion h fun e₁' e₂' => absurd e₂' n₂ | isFalse n₁ => isFalse fun h => Prod.noConfusion h fun e₁' e₂' => absurd e₁' n₁ instance [BEq α] [BEq β] : BEq (α × β) where beq := fun (a₁, b₁) (a₂, b₂) => a₁ == a₂ && b₁ == b₂ instance [LT α] [LT β] : LT (α × β) where lt s t := s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2) instance prodHasDecidableLt [LT α] [LT β] [DecidableEq α] [DecidableEq β] [(a b : α) → Decidable (a < b)] [(a b : β) → Decidable (a < b)] : (s t : α × β) → Decidable (s < t) := fun t s => inferInstanceAs (Decidable (_ ∨ _)) theorem Prod.lt_def [LT α] [LT β] (s t : α × β) : (s < t) = (s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2)) := rfl theorem Prod.ext (p : α × β) : (p.1, p.2) = p := by cases p; rfl def Prod.map {α₁ : Type u₁} {α₂ : Type u₂} {β₁ : Type v₁} {β₂ : Type v₂} (f : α₁ → α₂) (g : β₁ → β₂) : α₁ × β₁ → α₂ × β₂ | (a, b) => (f a, g b) /- Dependent products -/ theorem ex_of_PSigma {α : Type u} {p : α → Prop} : (PSigma (fun x => p x)) → Exists (fun x => p x) | ⟨x, hx⟩ => ⟨x, hx⟩ protected theorem PSigma.eta {α : Sort u} {β : α → Sort v} {a₁ a₂ : α} {b₁ : β a₁} {b₂ : β a₂} (h₁ : a₁ = a₂) (h₂ : Eq.ndrec b₁ h₁ = b₂) : PSigma.mk a₁ b₁ = PSigma.mk a₂ b₂ := by subst h₁ subst h₂ exact rfl /- Universe polymorphic unit -/ theorem PUnit.subsingleton (a b : PUnit) : a = b := by cases a; cases b; exact rfl theorem PUnit.eq_punit (a : PUnit) : a = ⟨⟩ := PUnit.subsingleton a ⟨⟩ instance : Subsingleton PUnit := Subsingleton.intro PUnit.subsingleton instance : Inhabited PUnit where default := ⟨⟩ instance : DecidableEq PUnit := fun a b => isTrue (PUnit.subsingleton a b) /- Setoid -/ class Setoid (α : Sort u) where r : α → α → Prop iseqv {} : Equivalence r instance {α : Sort u} [Setoid α] : HasEquiv α := ⟨Setoid.r⟩ namespace Setoid variable {α : Sort u} [Setoid α] theorem refl (a : α) : a ≈ a := (Setoid.iseqv α).refl a theorem symm {a b : α} (hab : a ≈ b) : b ≈ a := (Setoid.iseqv α).symm hab theorem trans {a b c : α} (hab : a ≈ b) (hbc : b ≈ c) : a ≈ c := (Setoid.iseqv α).trans hab hbc end Setoid /- Propositional extensionality -/ axiom propext {a b : Prop} : (a ↔ b) → a = b theorem Eq.propIntro {a b : Prop} (h₁ : a → b) (h₂ : b → a) : a = b := propext <| Iff.intro h₁ h₂ -- Eq for Prop is now decidable if the equivalent Iff is decidable instance {p q : Prop} [d : Decidable (p ↔ q)] : Decidable (p = q) := match d with | isTrue h => isTrue (propext h) | isFalse h => isFalse fun heq => h (heq ▸ Iff.rfl) gen_injective_theorems% Prod gen_injective_theorems% PProd gen_injective_theorems% MProd gen_injective_theorems% Subtype gen_injective_theorems% Fin gen_injective_theorems% Array gen_injective_theorems% Sum gen_injective_theorems% PSum gen_injective_theorems% Nat gen_injective_theorems% Option gen_injective_theorems% List gen_injective_theorems% Except gen_injective_theorems% EStateM.Result gen_injective_theorems% Lean.Name gen_injective_theorems% Lean.Syntax /- Quotients -/ -- Iff can now be used to do substitutions in a calculation theorem Iff.subst {a b : Prop} {p : Prop → Prop} (h₁ : a ↔ b) (h₂ : p a) : p b := Eq.subst (propext h₁) h₂ namespace Quot axiom sound : ∀ {α : Sort u} {r : α → α → Prop} {a b : α}, r a b → Quot.mk r a = Quot.mk r b protected theorem liftBeta {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) (c : (a b : α) → r a b → f a = f b) (a : α) : lift f c (Quot.mk r a) = f a := rfl protected theorem indBeta {α : Sort u} {r : α → α → Prop} {motive : Quot r → Prop} (p : (a : α) → motive (Quot.mk r a)) (a : α) : (ind p (Quot.mk r a) : motive (Quot.mk r a)) = p a := rfl protected abbrev liftOn {α : Sort u} {β : Sort v} {r : α → α → Prop} (q : Quot r) (f : α → β) (c : (a b : α) → r a b → f a = f b) : β := lift f c q protected theorem inductionOn {α : Sort u} {r : α → α → Prop} {motive : Quot r → Prop} (q : Quot r) (h : (a : α) → motive (Quot.mk r a)) : motive q := ind h q theorem exists_rep {α : Sort u} {r : α → α → Prop} (q : Quot r) : Exists (fun a => (Quot.mk r a) = q) := Quot.inductionOn (motive := fun q => Exists (fun a => (Quot.mk r a) = q)) q (fun a => ⟨a, rfl⟩) section variable {α : Sort u} variable {r : α → α → Prop} variable {motive : Quot r → Sort v} @[reducible, macroInline] protected def indep (f : (a : α) → motive (Quot.mk r a)) (a : α) : PSigma motive := ⟨Quot.mk r a, f a⟩ protected theorem indepCoherent (f : (a : α) → motive (Quot.mk r a)) (h : (a b : α) → (p : r a b) → Eq.ndrec (f a) (sound p) = f b) : (a b : α) → r a b → Quot.indep f a = Quot.indep f b := fun a b e => PSigma.eta (sound e) (h a b e) protected theorem liftIndepPr1 (f : (a : α) → motive (Quot.mk r a)) (h : ∀ (a b : α) (p : r a b), Eq.ndrec (f a) (sound p) = f b) (q : Quot r) : (lift (Quot.indep f) (Quot.indepCoherent f h) q).1 = q := by induction q using Quot.ind exact rfl protected abbrev rec (f : (a : α) → motive (Quot.mk r a)) (h : (a b : α) → (p : r a b) → Eq.ndrec (f a) (sound p) = f b) (q : Quot r) : motive q := Eq.ndrecOn (Quot.liftIndepPr1 f h q) ((lift (Quot.indep f) (Quot.indepCoherent f h) q).2) protected abbrev recOn (q : Quot r) (f : (a : α) → motive (Quot.mk r a)) (h : (a b : α) → (p : r a b) → Eq.ndrec (f a) (sound p) = f b) : motive q := Quot.rec f h q protected abbrev recOnSubsingleton [h : (a : α) → Subsingleton (motive (Quot.mk r a))] (q : Quot r) (f : (a : α) → motive (Quot.mk r a)) : motive q := by induction q using Quot.rec apply f apply Subsingleton.elim protected abbrev hrecOn (q : Quot r) (f : (a : α) → motive (Quot.mk r a)) (c : (a b : α) → (p : r a b) → HEq (f a) (f b)) : motive q := Quot.recOn q f fun a b p => eq_of_heq <| have p₁ : HEq (Eq.ndrec (f a) (sound p)) (f a) := eqRec_heq (sound p) (f a) HEq.trans p₁ (c a b p) end end Quot def Quotient {α : Sort u} (s : Setoid α) := @Quot α Setoid.r namespace Quotient @[inline] protected def mk {α : Sort u} [s : Setoid α] (a : α) : Quotient s := Quot.mk Setoid.r a def sound {α : Sort u} [s : Setoid α] {a b : α} : a ≈ b → Quotient.mk a = Quotient.mk b := Quot.sound protected abbrev lift {α : Sort u} {β : Sort v} [s : Setoid α] (f : α → β) : ((a b : α) → a ≈ b → f a = f b) → Quotient s → β := Quot.lift f protected theorem ind {α : Sort u} [s : Setoid α] {motive : Quotient s → Prop} : ((a : α) → motive (Quotient.mk a)) → (q : Quot Setoid.r) → motive q := Quot.ind protected abbrev liftOn {α : Sort u} {β : Sort v} [s : Setoid α] (q : Quotient s) (f : α → β) (c : (a b : α) → a ≈ b → f a = f b) : β := Quot.liftOn q f c protected theorem inductionOn {α : Sort u} [s : Setoid α] {motive : Quotient s → Prop} (q : Quotient s) (h : (a : α) → motive (Quotient.mk a)) : motive q := Quot.inductionOn q h theorem exists_rep {α : Sort u} [s : Setoid α] (q : Quotient s) : Exists (fun (a : α) => Quotient.mk a = q) := Quot.exists_rep q section variable {α : Sort u} variable [s : Setoid α] variable {motive : Quotient s → Sort v} @[inline] protected def rec (f : (a : α) → motive (Quotient.mk a)) (h : (a b : α) → (p : a ≈ b) → Eq.ndrec (f a) (Quotient.sound p) = f b) (q : Quotient s) : motive q := Quot.rec f h q protected abbrev recOn (q : Quotient s) (f : (a : α) → motive (Quotient.mk a)) (h : (a b : α) → (p : a ≈ b) → Eq.ndrec (f a) (Quotient.sound p) = f b) : motive q := Quot.recOn q f h protected abbrev recOnSubsingleton [h : (a : α) → Subsingleton (motive (Quotient.mk a))] (q : Quotient s) (f : (a : α) → motive (Quotient.mk a)) : motive q := Quot.recOnSubsingleton (h := h) q f protected abbrev hrecOn (q : Quotient s) (f : (a : α) → motive (Quotient.mk a)) (c : (a b : α) → (p : a ≈ b) → HEq (f a) (f b)) : motive q := Quot.hrecOn q f c end section universe uA uB uC variable {α : Sort uA} {β : Sort uB} {φ : Sort uC} variable [s₁ : Setoid α] [s₂ : Setoid β] protected abbrev lift₂ (f : α → β → φ) (c : (a₁ : α) → (b₁ : β) → (a₂ : α) → (b₂ : β) → a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ = f a₂ b₂) (q₁ : Quotient s₁) (q₂ : Quotient s₂) : φ := by apply Quotient.lift (fun (a₁ : α) => Quotient.lift (f a₁) (fun (a b : β) => c a₁ a a₁ b (Setoid.refl a₁)) q₂) _ q₁ intros induction q₂ using Quotient.ind apply c; assumption; apply Setoid.refl protected abbrev liftOn₂ (q₁ : Quotient s₁) (q₂ : Quotient s₂) (f : α → β → φ) (c : (a₁ : α) → (b₁ : β) → (a₂ : α) → (b₂ : β) → a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ = f a₂ b₂) : φ := Quotient.lift₂ f c q₁ q₂ protected theorem ind₂ {motive : Quotient s₁ → Quotient s₂ → Prop} (h : (a : α) → (b : β) → motive (Quotient.mk a) (Quotient.mk b)) (q₁ : Quotient s₁) (q₂ : Quotient s₂) : motive q₁ q₂ := by induction q₁ using Quotient.ind induction q₂ using Quotient.ind apply h protected theorem inductionOn₂ {motive : Quotient s₁ → Quotient s₂ → Prop} (q₁ : Quotient s₁) (q₂ : Quotient s₂) (h : (a : α) → (b : β) → motive (Quotient.mk a) (Quotient.mk b)) : motive q₁ q₂ := by induction q₁ using Quotient.ind induction q₂ using Quotient.ind apply h protected theorem inductionOn₃ [s₃ : Setoid φ] {motive : Quotient s₁ → Quotient s₂ → Quotient s₃ → Prop} (q₁ : Quotient s₁) (q₂ : Quotient s₂) (q₃ : Quotient s₃) (h : (a : α) → (b : β) → (c : φ) → motive (Quotient.mk a) (Quotient.mk b) (Quotient.mk c)) : motive q₁ q₂ q₃ := by induction q₁ using Quotient.ind induction q₂ using Quotient.ind induction q₃ using Quotient.ind apply h end section Exact variable {α : Sort u} private def rel [s : Setoid α] (q₁ q₂ : Quotient s) : Prop := Quotient.liftOn₂ q₁ q₂ (fun a₁ a₂ => a₁ ≈ a₂) (fun a₁ a₂ b₁ b₂ a₁b₁ a₂b₂ => propext (Iff.intro (fun a₁a₂ => Setoid.trans (Setoid.symm a₁b₁) (Setoid.trans a₁a₂ a₂b₂)) (fun b₁b₂ => Setoid.trans a₁b₁ (Setoid.trans b₁b₂ (Setoid.symm a₂b₂))))) private theorem rel.refl [s : Setoid α] (q : Quotient s) : rel q q := Quot.inductionOn (motive := fun q => rel q q) q (fun a => Setoid.refl a) private theorem rel_of_eq [s : Setoid α] {q₁ q₂ : Quotient s} : q₁ = q₂ → rel q₁ q₂ := fun h => Eq.ndrecOn h (rel.refl q₁) theorem exact [s : Setoid α] {a b : α} : Quotient.mk a = Quotient.mk b → a ≈ b := fun h => rel_of_eq h end Exact section universe uA uB uC variable {α : Sort uA} {β : Sort uB} variable [s₁ : Setoid α] [s₂ : Setoid β] protected abbrev recOnSubsingleton₂ {motive : Quotient s₁ → Quotient s₂ → Sort uC} [s : (a : α) → (b : β) → Subsingleton (motive (Quotient.mk a) (Quotient.mk b))] (q₁ : Quotient s₁) (q₂ : Quotient s₂) (g : (a : α) → (b : β) → motive (Quotient.mk a) (Quotient.mk b)) : motive q₁ q₂ := by induction q₁ using Quot.recOnSubsingleton induction q₂ using Quot.recOnSubsingleton apply g intro a; apply s induction q₂ using Quot.recOnSubsingleton intro a; apply s infer_instance end end Quotient section variable {α : Type u} variable (r : α → α → Prop) instance {α : Sort u} {s : Setoid α} [d : ∀ (a b : α), Decidable (a ≈ b)] : DecidableEq (Quotient s) := fun (q₁ q₂ : Quotient s) => Quotient.recOnSubsingleton₂ (motive := fun a b => Decidable (a = b)) q₁ q₂ fun a₁ a₂ => match d a₁ a₂ with | isTrue h₁ => isTrue (Quotient.sound h₁) | isFalse h₂ => isFalse fun h => absurd (Quotient.exact h) h₂ /- Function extensionality -/ namespace Function variable {α : Sort u} {β : α → Sort v} protected def Equiv (f₁ f₂ : ∀ (x : α), β x) : Prop := ∀ x, f₁ x = f₂ x protected theorem Equiv.refl (f : ∀ (x : α), β x) : Function.Equiv f f := fun x => rfl protected theorem Equiv.symm {f₁ f₂ : ∀ (x : α), β x} : Function.Equiv f₁ f₂ → Function.Equiv f₂ f₁ := fun h x => Eq.symm (h x) protected theorem Equiv.trans {f₁ f₂ f₃ : ∀ (x : α), β x} : Function.Equiv f₁ f₂ → Function.Equiv f₂ f₃ → Function.Equiv f₁ f₃ := fun h₁ h₂ x => Eq.trans (h₁ x) (h₂ x) protected theorem Equiv.isEquivalence (α : Sort u) (β : α → Sort v) : Equivalence (@Function.Equiv α β) := { refl := Equiv.refl symm := Equiv.symm trans := Equiv.trans } end Function section open Quotient variable {α : Sort u} {β : α → Sort v} @[instance] private def funSetoid (α : Sort u) (β : α → Sort v) : Setoid (∀ (x : α), β x) := Setoid.mk (@Function.Equiv α β) (Function.Equiv.isEquivalence α β) private def extfunApp (f : Quotient <| funSetoid α β) (x : α) : β x := Quot.liftOn f (fun (f : ∀ (x : α), β x) => f x) (fun f₁ f₂ h => h x) theorem funext {f₁ f₂ : ∀ (x : α), β x} (h : ∀ x, f₁ x = f₂ x) : f₁ = f₂ := by show extfunApp (Quotient.mk f₁) = extfunApp (Quotient.mk f₂) apply congrArg apply Quotient.sound exact h end instance {α : Sort u} {β : α → Sort v} [∀ a, Subsingleton (β a)] : Subsingleton (∀ a, β a) where allEq f₁ f₂ := funext (fun a => Subsingleton.elim (f₁ a) (f₂ a)) /- Squash -/ def Squash (α : Type u) := Quot (fun (a b : α) => True) def Squash.mk {α : Type u} (x : α) : Squash α := Quot.mk _ x theorem Squash.ind {α : Type u} {motive : Squash α → Prop} (h : ∀ (a : α), motive (Squash.mk a)) : ∀ (q : Squash α), motive q := Quot.ind h @[inline] def Squash.lift {α β} [Subsingleton β] (s : Squash α) (f : α → β) : β := Quot.lift f (fun a b _ => Subsingleton.elim _ _) s instance : Subsingleton (Squash α) where allEq a b := by induction a using Squash.ind induction b using Squash.ind apply Quot.sound trivial namespace Lean /- Kernel reduction hints -/ /-- When the kernel tries to reduce a term `Lean.reduceBool c`, it will invoke the Lean interpreter to evaluate `c`. The kernel will not use the interpreter if `c` is not a constant. This feature is useful for performing proofs by reflection. Remark: the Lean frontend allows terms of the from `Lean.reduceBool t` where `t` is a term not containing free variables. The frontend automatically declares a fresh auxiliary constant `c` and replaces the term with `Lean.reduceBool c`. The main motivation is that the code for `t` will be pre-compiled. Warning: by using this feature, the Lean compiler and interpreter become part of your trusted code base. This is extra 30k lines of code. More importantly, you will probably not be able to check your developement using external type checkers (e.g., Trepplein) that do not implement this feature. Keep in mind that if you are using Lean as programming language, you are already trusting the Lean compiler and interpreter. So, you are mainly losing the capability of type checking your developement using external checkers. Recall that the compiler trusts the correctness of all `[implementedBy ...]` and `[extern ...]` annotations. If an extern function is executed, then the trusted code base will also include the implementation of the associated foreign function. -/ constant reduceBool (b : Bool) : Bool := b /-- Similar to `Lean.reduceBool` for closed `Nat` terms. Remark: we do not have plans for supporting a generic `reduceValue {α} (a : α) : α := a`. The main issue is that it is non-trivial to convert an arbitrary runtime object back into a Lean expression. We believe `Lean.reduceBool` enables most interesting applications (e.g., proof by reflection). -/ constant reduceNat (n : Nat) : Nat := n axiom ofReduceBool (a b : Bool) (h : reduceBool a = b) : a = b axiom ofReduceNat (a b : Nat) (h : reduceNat a = b) : a = b end Lean
009aadd1da572a81b9b0ac0e04c60653488a6313
6dacdff2020860f2468bb8dacf344e6b043d6a78
/cap/src/demo_sander.lean
39f0062027710c099a24a8599bee7240c73f3042
[]
no_license
alexjbest/talks
514ca57af312a14cf68c30efa1c7228294edc190
84976b4329ea768c754da72cc15d5ce29332466d
refs/heads/master
1,686,993,465,308
1,686,315,975,000
1,686,315,975,000
16,347,963
2
0
null
null
null
null
UTF-8
Lean
false
false
944
lean
import tactic import data.real.basic variables {R : Type*} [comm_ring R] (x y : R) def F : R := x^3 + 2*x*y + y^3 - 1 def G : R := 2*x^2 - 3*y^2 + 2 def H : R := x^3 + 3*x*y + 7*y^2 - 1 def a : R := -568781583*x*y^2 + 1152704112*x*y + 1004446918*x + 1486171233*y^3 + 2278972316*y^2 - 8787246228*y - 7750297898 def b : R := 330260274*x^2*y^2 - 1686462745*x^2*y - 2236672062*x^2 - 189593861*x*y^3 + 53974430*x*y^2 + 4521329982*x*y + 2236672062*x + 495390411*y^4 - 1823304087*y^3 - 8168304546*y^2 - 4521329982*y + 2236672062 def c : R := -91738965*x*y^2 + 2220221378*x*y + 3468897206*x - 1106983511*y^3 - 2386921176*y^2 - 255413736*y + 3276953774 lemma sander : a x y * F x y + b x y * G x y + c x y * H x y = 8946688248 := begin simp [a, b, c, F, G, H], ring, end lemma sander2 {x y : ℝ} : ¬(F x y = 0 ∧ G x y = 0 ∧ H x y = 0) := begin rintro ⟨hF, hG, hH⟩, have := sander x y, simp [hF, hG, hH] at this, linarith, end
dff2e394b087d2de722bd6c88751c956b51f1f1f
6b45072eb2b3db3ecaace2a7a0241ce81f815787
/topology/uniform_space.lean
ad290e6bfb67a5f04f8c31471221e0568215ba23
[]
no_license
avigad/library_dev
27b47257382667b5eb7e6476c4f5b0d685dd3ddc
9d8ac7c7798ca550874e90fed585caad030bbfac
refs/heads/master
1,610,452,468,791
1,500,712,839,000
1,500,713,478,000
69,311,142
1
0
null
1,474,942,903,000
1,474,942,902,000
null
UTF-8
Lean
false
false
52,906
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 Theory of uniform spaces. -/ import algebra.lattice.filter .topological_space .continuity open set lattice filter set_option eqn_compiler.zeta true attribute [trans] subset.trans universes u v w x y section variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} {ι : Sort y} def id_rel {α : Type u} := {p : α × α | p.1 = p.2} def comp_rel {α : Type u} (r₁ r₂ : set (α×α)) := {p : α × α | ∃z:α, (p.1, z) ∈ r₁ ∧ (z, p.2) ∈ r₂} @[simp] lemma swap_id_rel : prod.swap '' id_rel = @id_rel α := set.ext $ assume ⟨a, b⟩, by simp [image_swap_eq_vimage_swap]; exact eq_comm lemma monotone_comp_rel [weak_order β] {f g : β → set (α×α)} (hf : monotone f) (hg : monotone g) : monotone (λx, comp_rel (f x) (g x)) := assume a b h p ⟨z, h₁, h₂⟩, ⟨z, hf h h₁, hg h h₂⟩ lemma prod_mk_mem_comp_rel {a b c : α} {s t : set (α×α)} (h₁ : (a, c) ∈ s) (h₂ : (c, b) ∈ t) : (a, b) ∈ comp_rel s t := ⟨c, h₁, h₂⟩ @[simp] lemma id_comp_rel {r : set (α×α)} : comp_rel id_rel r = r := set.ext $ assume ⟨a, b⟩, ⟨assume ⟨a', (heq : a = a'), ha'⟩, heq.symm ▸ ha', assume ha, ⟨a, rfl, ha⟩⟩ /- uniformity -/ class uniform_space (α : Type u) := (uniformity : filter (α × α)) (refl : principal id_rel ≤ uniformity) (symm : prod.swap <$> uniformity ≤ uniformity) (comp : uniformity^.lift' (λs, comp_rel s s) ≤ uniformity) lemma uniform_space_eq {u₁ u₂ : uniform_space α} (h : u₁.uniformity = u₂.uniformity) : u₁ = u₂ := begin cases u₁ with a, cases u₂ with b, have h' : a = b, assumption, clear h, subst h' end section uniform_space variables [uniform_space α] def uniformity : filter (α × α) := uniform_space.uniformity α lemma refl_le_uniformity : principal id_rel ≤ @uniformity α _ := uniform_space.refl α lemma refl_mem_uniformity {x : α} {s : set (α × α)} (h : s ∈ (@uniformity α _).sets) : (x, x) ∈ s := refl_le_uniformity h rfl lemma symm_le_uniformity : map (@prod.swap α α) uniformity ≤ uniformity := uniform_space.symm α lemma comp_le_uniformity : uniformity^.lift' (λs:set (α×α), comp_rel s s) ≤ uniformity := uniform_space.comp α lemma comp_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : ∃t∈(@uniformity α _).sets, comp_rel t t ⊆ s := have s ∈ (uniformity^.lift' (λt:set (α×α), comp_rel t t)).sets, from comp_le_uniformity hs, (mem_lift'_iff $ monotone_comp_rel monotone_id monotone_id).mp this lemma symm_of_uniformity {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : ∃t∈(@uniformity α _).sets, (∀a b, (a, b) ∈ t → (b, a) ∈ t) ∧ t ⊆ s := have vimage prod.swap s ∈ (@uniformity α _).sets, from symm_le_uniformity hs, ⟨s ∩ vimage prod.swap s, inter_mem_sets hs this, assume a b ⟨h₁, h₂⟩, ⟨h₂, h₁⟩, inter_subset_left _ _⟩ lemma comp_symm_of_uniformity {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : ∃t∈(@uniformity α _).sets, (∀{a b}, (a, b) ∈ t → (b, a) ∈ t) ∧ comp_rel t t ⊆ s := let ⟨t, ht₁, ht₂⟩ := comp_mem_uniformity_sets hs in let ⟨t', ht', ht'₁, ht'₂⟩ := symm_of_uniformity ht₁ in ⟨t', ht', ht'₁, subset.trans (monotone_comp_rel monotone_id monotone_id ht'₂) ht₂⟩ lemma uniformity_le_symm : uniformity ≤ map (@prod.swap α α) uniformity := calc uniformity = id <$> uniformity : (functor.id_map _)^.symm ... = (prod.swap.{u u} ∘ prod.swap) <$> uniformity : congr_arg (λf : (α×α)→(α×α), f <$> uniformity) (by apply funext; intro x; cases x; refl) ... = (map prod.swap ∘ map prod.swap) uniformity : congr map_compose rfl ... ≤ prod.swap.{u u} <$> uniformity : map_mono symm_le_uniformity lemma uniformity_eq_symm : uniformity = (@prod.swap α α) <$> uniformity := le_antisymm uniformity_le_symm symm_le_uniformity lemma uniformity_lift_le_swap {g : set (α×α) → filter β} {f : filter β} (hg : monotone g) (h : uniformity^.lift (λs, g (vimage prod.swap s)) ≤ f) : uniformity^.lift g ≤ f := le_trans (lift_mono uniformity_le_symm (le_refl _)) (by rw [map_lift_eq2 hg, image_swap_eq_vimage_swap]; exact h) lemma uniformity_lift_le_comp {f : set (α×α) → filter β} (h : monotone f): uniformity.lift (λs, f (comp_rel s s)) ≤ uniformity.lift f := calc uniformity.lift (λs, f (comp_rel s s)) = (uniformity.lift' (λs:set (α×α), comp_rel s s))^.lift f : begin rw [lift_lift'_assoc], exact monotone_comp_rel monotone_id monotone_id, exact h end ... ≤ uniformity.lift f : lift_mono comp_le_uniformity (le_refl _) lemma comp_le_uniformity3 : uniformity^.lift' (λs:set (α×α), comp_rel s (comp_rel s s)) ≤ uniformity := calc uniformity.lift' (λd, comp_rel d (comp_rel d d)) = uniformity.lift (λs, uniformity.lift' (λt:set(α×α), comp_rel s (comp_rel t t))) : begin rw [lift_lift'_same_eq_lift'], exact (assume x, monotone_comp_rel monotone_const $ monotone_comp_rel monotone_id monotone_id), exact (assume x, monotone_comp_rel monotone_id monotone_const), end ... ≤ uniformity.lift (λs, uniformity.lift' (λt:set(α×α), comp_rel s t)) : lift_mono' $ assume s hs, @uniformity_lift_le_comp α _ _ (principal ∘ comp_rel s) $ monotone_comp (monotone_comp_rel monotone_const monotone_id) monotone_principal ... = uniformity.lift' (λs:set(α×α), comp_rel s s) : lift_lift'_same_eq_lift' (assume s, monotone_comp_rel monotone_const monotone_id) (assume s, monotone_comp_rel monotone_id monotone_const) ... ≤ uniformity : comp_le_uniformity instance uniform_space.to_topological_space : topological_space α := { open' := λs, ∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ (uniformity.sets : set (set (α×α))), open_univ := by simp; intros; apply univ_mem_sets, open_inter := assume s t hs ht x ⟨xs, xt⟩, uniformity.upwards_sets (inter_mem_sets (hs x xs) (ht x xt)) $ assume p ⟨ps, pt⟩ h, ⟨ps h, pt h⟩, open_sUnion := assume s hs x ⟨t, ts, xt⟩, uniformity.upwards_sets (hs t ts x xt) $ assume p ph h, ⟨t, ts, ph h⟩ } lemma mem_nhds_uniformity_iff {x : α} {s : set α} : (s ∈ (nhds x).sets) ↔ ({p : α × α | p.1 = x → p.2 ∈ s} ∈ (@uniformity α _).sets) := ⟨ begin simp [mem_nhds_sets_iff], exact assume ⟨t, ht, ts, xt⟩, uniformity.upwards_sets (ht x xt) $ assume ⟨x', y⟩ h eq, ts $ h eq end, assume hs, mem_nhds_sets_iff.mpr $ ⟨{x | {p : α × α | p.1 = x → p.2 ∈ s} ∈ (@uniformity α _).sets}, assume x', assume hx' : {p : α × α | p.fst = x' → p.snd ∈ s} ∈ (@uniformity α _).sets, refl_mem_uniformity hx' rfl, assume x' hx', let ⟨t, ht, tr⟩ := comp_mem_uniformity_sets hx' in uniformity.upwards_sets ht $ assume ⟨a, b⟩ hp' (eq : a = x'), have hp : (x', b) ∈ t, from eq ▸ hp', show {p : α × α | p.fst = b → p.snd ∈ s} ∈ (@uniformity α _).sets, from uniformity.upwards_sets ht $ assume ⟨a, b'⟩ hp' (heq : a = b), have (b, b') ∈ t, from heq ▸ hp', have (x', b') ∈ comp_rel t t, from ⟨b, hp, this⟩, show b' ∈ s, from tr this rfl, hs⟩⟩ lemma nhds_eq_uniformity {x : α} : nhds x = uniformity^.lift' (λs:set (α×α), {y | (x, y) ∈ s}) := filter_eq $ set.ext $ assume s, begin rw [mem_lift'_iff], tactic.swap, apply monotone_vimage, simp [mem_nhds_uniformity_iff], exact ⟨assume h, ⟨_, h, assume y h, h rfl⟩, assume ⟨t, h₁, h₂⟩, uniformity.upwards_sets h₁ $ assume ⟨x', y⟩ hp (eq : x' = x), h₂ $ show (x, y) ∈ t, from eq ▸ hp⟩ end lemma mem_nhds_left {x : α} {s : set (α×α)} (h : s ∈ (uniformity.sets : set (set (α×α)))) : {y : α | (x, y) ∈ s} ∈ (nhds x)^.sets := have nhds x ≤ principal {y : α | (x, y) ∈ s}, by rw [nhds_eq_uniformity]; exact infi_le_of_le s (infi_le _ h), by simp at this; assumption lemma mem_nhds_right {y : α} {s : set (α×α)} (h : s ∈ (uniformity.sets : set (set (α×α)))) : {x : α | (x, y) ∈ s} ∈ (nhds y)^.sets := mem_nhds_left (symm_le_uniformity h) lemma lift_nhds_left {x : α} {g : set α → filter β} (hg : monotone g) : (nhds x)^.lift g = uniformity^.lift (λs:set (α×α), g {y | (x, y) ∈ s}) := eq.trans begin rw [nhds_eq_uniformity], exact (filter.lift_assoc $ monotone_comp monotone_vimage $ monotone_comp monotone_vimage monotone_principal) end (congr_arg _ $ funext $ assume s, filter.lift_principal hg) lemma lift_nhds_right {x : α} {g : set α → filter β} (hg : monotone g) : (nhds x)^.lift g = uniformity^.lift (λs:set (α×α), g {y | (y, x) ∈ s}) := calc (nhds x)^.lift g = uniformity^.lift (λs:set (α×α), g {y | (x, y) ∈ s}) : lift_nhds_left hg ... = ((@prod.swap α α) <$> uniformity)^.lift (λs:set (α×α), g {y | (x, y) ∈ s}) : by rw [←uniformity_eq_symm] ... = uniformity^.lift (λs:set (α×α), g {y | (x, y) ∈ image prod.swap s}) : map_lift_eq2 $ monotone_comp monotone_vimage hg ... = _ : by simp [image_swap_eq_vimage_swap] lemma nhds_nhds_eq_uniformity_uniformity_prod {a b : α} : filter.prod (nhds a) (nhds b) = uniformity^.lift (λs:set (α×α), uniformity^.lift' (λt:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ t})) := show (nhds a)^.lift (λs:set α, (nhds b)^.lift (λt:set α, principal (set.prod s t))) = _, begin rw [lift_nhds_right], apply congr_arg, apply funext, intro s, rw [lift_nhds_left], refl, exact monotone_comp (monotone_prod monotone_const monotone_id) monotone_principal, exact (monotone_lift' monotone_const $ monotone_lam $ assume x, monotone_prod monotone_id monotone_const) end lemma nhds_eq_uniformity_prod {a b : α} : nhds (a, b) = uniformity^.lift' (λs:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ s}) := begin rw [nhds_prod_eq, nhds_nhds_eq_uniformity_uniformity_prod, lift_lift'_same_eq_lift'], { intro s, exact monotone_prod monotone_const monotone_vimage }, { intro t, exact monotone_prod monotone_vimage monotone_const } end lemma nhdset_of_mem_uniformity {d : set (α×α)} (s : set (α×α)) (hd : d ∈ (@uniformity α _).sets) : ∃(t : set (α×α)), open' t ∧ s ⊆ t ∧ t ⊆ {p | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} := let cl_d := {p:α×α | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} in have ∀p ∈ s, ∃t ⊆ cl_d, open' t ∧ p ∈ t, from assume ⟨x, y⟩ hp, mem_nhds_sets_iff.mp $ show cl_d ∈ (nhds (x, y)).sets, begin rw [nhds_eq_uniformity_prod, mem_lift'_iff], exact ⟨d, hd, assume ⟨a, b⟩ ⟨ha, hb⟩, ⟨x, y, ha, hp, hb⟩⟩, exact monotone_prod monotone_vimage monotone_vimage end, have ∃t:(Π(p:α×α) (h:p ∈ s), set (α×α)), ∀p, ∀h:p ∈ s, t p h ⊆ cl_d ∧ open' (t p h) ∧ p ∈ t p h, by simp [classical.skolem] at this; simp; assumption, match this with | ⟨t, ht⟩ := ⟨(⋃ p:α×α, ⋃ h : p ∈ s, t p h : set (α×α)), open_Union $ assume (p:α×α), open_Union $ assume hp, (ht p hp).right.left, assume ⟨a, b⟩ hp, begin simp; exact ⟨a, b, hp, (ht (a,b) hp).right.right⟩ end, Union_subset $ assume p, Union_subset $ assume hp, (ht p hp).left⟩ end lemma closure_eq_inter_uniformity {t : set (α×α)} : closure t = (⋂ d∈(@uniformity α _).sets, comp_rel d (comp_rel t d)) := set.ext $ assume ⟨a, b⟩, calc (a, b) ∈ closure t ↔ (nhds (a, b) ⊓ principal t ≠ ⊥) : by simp [closure_eq_nhds] ... ↔ (((@prod.swap α α) <$> uniformity).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) : by rw [←uniformity_eq_symm, nhds_eq_uniformity_prod] ... ↔ ((map (@prod.swap α α) uniformity).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) : by refl ... ↔ (uniformity.lift' (λ (s : set (α × α)), set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s}) ⊓ principal t ≠ ⊥) : begin rw [map_lift'_eq2], simp [image_swap_eq_vimage_swap, function.comp], exact monotone_prod monotone_vimage monotone_vimage end ... ↔ (∀s∈(@uniformity α _).sets, ∃x, x ∈ set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s} ∩ t) : begin rw [lift'_inf_principal_eq, lift'_neq_bot_iff], apply forall_congr, intro s, rw [ne_empty_iff_exists_mem], exact monotone_inter (monotone_prod monotone_vimage monotone_vimage) monotone_const end ... ↔ (∀s∈(@uniformity α _).sets, (a, b) ∈ comp_rel s (comp_rel t s)) : forall_congr $ assume s, forall_congr $ assume hs, ⟨assume ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩, ⟨x, hx, y, hxyt, hy⟩, assume ⟨x, hx, y, hxyt, hy⟩, ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩⟩ ... ↔ _ : by simp lemma uniformity_eq_uniformity_closure : (@uniformity α _) = uniformity.lift' closure := le_antisymm (le_infi $ assume s, le_infi $ assume hs, by simp; exact uniformity.upwards_sets hs subset_closure) (calc uniformity.lift' closure ≤ uniformity.lift' (λd, comp_rel d (comp_rel d d)) : lift'_mono' (by intros s hs; rw [closure_eq_inter_uniformity]; exact bInter_subset_of_mem hs) ... ≤ uniformity : comp_le_uniformity3) lemma uniformity_eq_uniformity_interior : (@uniformity α _) = uniformity.lift' interior := le_antisymm (le_infi $ assume d, le_infi $ assume hd, let ⟨s, hs, hs_comp⟩ := (mem_lift'_iff $ monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in let ⟨t, ht, hst, ht_comp⟩ := nhdset_of_mem_uniformity s hs in have s ⊆ interior d, from calc s ⊆ t : hst ... ⊆ interior d : (subset_interior_iff_subset_of_open ht).mpr $ assume x, assume : x ∈ t, let ⟨x, y, h₁, h₂, h₃⟩ := ht_comp this in hs_comp ⟨x, h₁, y, h₂, h₃⟩, have interior d ∈ (@uniformity α _).sets, from (@uniformity α _).upwards_sets hs $ this, by simp [this]) (assume s hs, (uniformity.lift' interior).upwards_sets (mem_lift' hs) interior_subset) lemma interior_mem_uniformity {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : interior s ∈ (@uniformity α _).sets := by rw [uniformity_eq_uniformity_interior]; exact mem_lift' hs /- uniform continuity -/ definition uniform_continuous [uniform_space β] (f : α → β) := filter.map (λx:α×α, (f x.1, f x.2)) uniformity ≤ uniformity definition uniform_embedding [uniform_space β] (f : α → β) := (∀a₁ a₂, f a₁ = f a₂ → a₁ = a₂) ∧ vmap (λx:α×α, (f x.1, f x.2)) uniformity = uniformity lemma uniform_continuous_of_embedding [uniform_space β] {f : α → β} (hf : uniform_embedding f) : uniform_continuous f := by simp [uniform_continuous, hf.right.symm]; exact assume s hs, ⟨s, hs, subset.refl _⟩ lemma continuous_of_uniform [uniform_space β] {f : α → β} (hf : uniform_continuous f) : continuous f := continuous_iff_towards.mpr $ assume a, calc map f (nhds a) ≤ (map (λp:α×α, (f p.1, f p.2)) uniformity).lift' (λs:set (β×β), {y | (f a, y) ∈ s}) : begin rw [nhds_eq_uniformity, map_lift'_eq, map_lift'_eq2], exact (lift'_mono' $ assume s hs b ⟨a', (ha' : (_, a') ∈ s), a'_eq⟩, ⟨(a, a'), ha', show (f a, f a') = (f a, b), from a'_eq ▸ rfl⟩), exact monotone_vimage, exact monotone_vimage end ... ≤ nhds (f a) : by rw [nhds_eq_uniformity]; exact lift'_mono hf (le_refl _) /- cauchy filters -/ definition cauchy (f : filter α) := f ≠ ⊥ ∧ filter.prod f f ≤ uniformity lemma cauchy_downwards {f g : filter α} (h_c : cauchy f) (hg : g ≠ ⊥) (h_le : g ≤ f) : cauchy g := ⟨hg, le_trans (filter.prod_mono h_le h_le) h_c.right⟩ lemma cauchy_nhds {a : α} : cauchy (nhds a) := ⟨nhds_neq_bot, calc filter.prod (nhds a) (nhds a) = uniformity^.lift (λs:set (α×α), uniformity^.lift' (λt:set(α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (a, y) ∈ t})) : nhds_nhds_eq_uniformity_uniformity_prod ... ≤ uniformity^.lift' (λs:set (α×α), comp_rel s s) : le_infi $ assume s, le_infi $ assume hs, infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le s $ infi_le_of_le hs $ principal_mono.mpr $ assume ⟨x, y⟩ ⟨(hx : (x, a) ∈ s), (hy : (a, y) ∈ s)⟩, ⟨a, hx, hy⟩ ... ≤ uniformity : comp_le_uniformity⟩ lemma cauchy_pure {a : α} : cauchy (pure a) := cauchy_downwards cauchy_nhds (show principal {a} ≠ ⊥, by simp) (return_le_nhds a) lemma le_nhds_of_cauchy_adhp {f : filter α} {x : α} (hf : cauchy f) (adhs : f ⊓ nhds x ≠ ⊥) : f ≤ nhds x := have ∀s∈f.sets, x ∈ closure s, begin intros s hs, simp [closure_eq_nhds, inf_comm], exact assume h', adhs $ bot_unique $ h' ▸ inf_le_inf (by simp; exact hs) (le_refl _) end, calc f ≤ f.lift' (λs:set α, {y | x ∈ closure s ∧ y ∈ closure s}) : le_infi $ assume s, le_infi $ assume hs, begin rw [←forall_sets_neq_empty_iff_neq_bot] at adhs, simp [this s hs], exact f.upwards_sets hs subset_closure end ... ≤ f.lift' (λs:set α, {y | (x, y) ∈ closure (set.prod s s)}) : by simp [closure_prod_eq]; exact le_refl _ ... = (filter.prod f f).lift' (λs:set (α×α), {y | (x, y) ∈ closure s}) : begin rw [prod_same_eq], rw [lift'_lift'_assoc], exact monotone_prod monotone_id monotone_id, exact monotone_comp (assume s t h x h', closure_mono h h') monotone_vimage end ... ≤ uniformity.lift' (λs:set (α×α), {y | (x, y) ∈ closure s}) : lift'_mono hf.right (le_refl _) ... = (uniformity.lift' closure).lift' (λs:set (α×α), {y | (x, y) ∈ s}) : begin rw [lift'_lift'_assoc], exact assume s t h, closure_mono h, exact monotone_vimage end ... = uniformity.lift' (λs:set (α×α), {y | (x, y) ∈ s}) : by rw [←uniformity_eq_uniformity_closure] ... = nhds x : by rw [nhds_eq_uniformity] lemma le_nhds_iff_adhp_of_cauchy {f : filter α} {x : α} (hf : cauchy f) : f ≤ nhds x ↔ f ⊓ nhds x ≠ ⊥ := ⟨assume h, (inf_of_le_left h).symm ▸ hf.left, le_nhds_of_cauchy_adhp hf⟩ lemma cauchy_map [uniform_space β] {f : filter α} {m : α → β} (hm : uniform_continuous m) (hf : cauchy f) : cauchy (map m f) := ⟨have f ≠ ⊥, from hf.left, by simp; assumption, calc filter.prod (map m f) (map m f) = map (λp:α×α, (m p.1, m p.2)) (filter.prod f f) : filter.prod_map_map_eq ... ≤ map (λp:α×α, (m p.1, m p.2)) uniformity : map_mono hf.right ... ≤ uniformity : hm⟩ lemma cauchy_vmap [uniform_space β] {f : filter β} {m : α → β} (hm : vmap (λp:α×α, (m p.1, m p.2)) uniformity ≤ uniformity) (hf : cauchy f) (hb : vmap m f ≠ ⊥) : cauchy (vmap m f) := ⟨hb, calc filter.prod (vmap m f) (vmap m f) = vmap (λp:α×α, (m p.1, m p.2)) (filter.prod f f) : filter.prod_vmap_vmap_eq ... ≤ vmap (λp:α×α, (m p.1, m p.2)) uniformity : vmap_mono hf.right ... ≤ uniformity : hm⟩ /- separated uniformity -/ protected def separation_rel (α : Type u) [uniform_space α] := (⋂₀ (@uniformity α _).sets) lemma separated_equiv : equivalence (λx y, (x, y) ∈ separation_rel α) := ⟨assume x, assume s, refl_mem_uniformity, assume x y, assume h (s : set (α×α)) hs, have vimage prod.swap s ∈ (@uniformity α _).sets, from symm_le_uniformity hs, h _ this, assume x y z (hxy : (x, y) ∈ separation_rel α) (hyz : (y, z) ∈ separation_rel α) s (hs : s ∈ (@uniformity α _).sets), let ⟨t, ht, (h_ts : comp_rel t t ⊆ s)⟩ := comp_mem_uniformity_sets hs in h_ts $ show (x, z) ∈ comp_rel t t, from ⟨y, hxy t ht, hyz t ht⟩⟩ protected def separation_setoid (α : Type u) [uniform_space α] : setoid α := ⟨λx y, (x, y) ∈ separation_rel α, separated_equiv⟩ @[class] definition separated (α : Type u) [uniform_space α] := separation_rel α = id_rel instance separated_t2 [s : separated α] : t2_space α := ⟨assume x y, assume h : x ≠ y, have separation_rel α = id_rel, from s, have (x, y) ∉ separation_rel α, by simp [this]; exact h, let ⟨d, hd, (hxy : (x, y) ∉ d)⟩ := classical.bexists_not_of_not_bforall this in let ⟨d', hd', (hd'd' : comp_rel d' d' ⊆ d)⟩ := comp_mem_uniformity_sets hd in have {y | (x, y) ∈ d'} ∈ (nhds x).sets, from mem_nhds_left hd', let ⟨u, hu₁, hu₂, hu₃⟩ := mem_nhds_sets_iff.mp this in have {x | (x, y) ∈ d'} ∈ (nhds y).sets, from mem_nhds_right hd', let ⟨v, hv₁, hv₂, hv₃⟩ := mem_nhds_sets_iff.mp this in have u ∩ v = ∅, from eq_empty_of_subset_empty $ assume z ⟨(h₁ : z ∈ u), (h₂ : z ∈ v)⟩, have (x, y) ∈ comp_rel d' d', from ⟨z, hu₁ h₁, hv₁ h₂⟩, hxy $ hd'd' this, ⟨u, v, hu₂, hv₂, hu₃, hv₃, this⟩⟩ /- totally bounded -/ def totally_bounded (s : set α) : Prop := ∀d ∈ (@uniformity α _).sets, ∃t : set α, finite t ∧ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}) lemma cauchy_of_totally_bounded_of_ultrafilter {s : set α} {f : filter α} (hs : totally_bounded s) (hf : ultrafilter f) (h : f ≤ principal s) : cauchy f := ⟨hf.left, assume t ht, let ⟨t', ht'₁, ht'_symm, ht'_t⟩ := comp_symm_of_uniformity ht in let ⟨i, hi, hs_union⟩ := hs t' ht'₁ in have (⋃y∈i, {x | (x,y) ∈ t'}) ∈ f.sets, from f.upwards_sets (le_principal_iff.mp h) hs_union, have ∃y∈i, {x | (x,y) ∈ t'} ∈ f.sets, from mem_of_finite_Union_ultrafilter hf hi this, let ⟨y, hy, hif⟩ := this in have set.prod {x | (x,y) ∈ t'} {x | (x,y) ∈ t'} ⊆ comp_rel t' t', from assume ⟨x₁, x₂⟩ ⟨(h₁ : (x₁, y) ∈ t'), (h₂ : (x₂, y) ∈ t')⟩, ⟨y, h₁, ht'_symm h₂⟩, (filter.prod f f).upwards_sets (prod_mem_prod hif hif) (subset.trans this ht'_t)⟩ lemma totally_bounded_iff_filter {s : set α} : totally_bounded s ↔ (∀f, f ≠ ⊥ → f ≤ principal s → ∃c ≤ f, cauchy c) := ⟨assume : totally_bounded s, assume f hf hs, ⟨ultrafilter_of f, ultrafilter_of_le, cauchy_of_totally_bounded_of_ultrafilter this (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hs)⟩, assume h : ∀f, f ≠ ⊥ → f ≤ principal s → ∃c ≤ f, cauchy c, assume d hd, classical.by_contradiction $ assume hs, have hd_cover : ∀{t:set α}, finite t → ¬ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}), by simp [not_exists_iff_forall_not, classical.not_and_iff, not_or_iff_implies] at hs; assumption, let f := ⨅t:{t : set α // finite t}, principal (s - (⋃y∈t.val, {x | (x,y) ∈ d})), ⟨a, ha⟩ := @exists_mem_of_ne_empty α s (assume h, hd_cover finite.empty $ h.symm ▸ empty_subset _) in have f ≠ ⊥, from infi_neq_bot_of_directed ⟨a⟩ (assume ⟨t₁, ht₁⟩ ⟨t₂, ht₂⟩, ⟨⟨t₁ ∪ t₂, finite_union ht₁ ht₂⟩, principal_mono.mpr $ diff_right_antimono $ Union_subset_Union $ assume t, Union_subset_Union_const or.inl, principal_mono.mpr $ diff_right_antimono $ Union_subset_Union $ assume t, Union_subset_Union_const or.inr⟩) (assume ⟨t, ht⟩, by simp [diff_neq_empty]; exact hd_cover ht), have f ≤ principal s, from infi_le_of_le ⟨∅, finite.empty⟩ $ by simp; exact subset.refl s, let ⟨c, (hc₁ : c ≤ f), (hc₂ : cauchy c)⟩ := h f ‹f ≠ ⊥› this, ⟨m, hm, (hmd : set.prod m m ⊆ d)⟩ := (@mem_prod_same_iff α d c).mp $ hc₂.right hd in have c ≤ principal s, from le_trans ‹c ≤ f› this, have m ∩ s ∈ c.sets, from inter_mem_sets hm $ le_principal_iff.mp this, let ⟨y, hym, hys⟩ := inhabited_of_mem_sets hc₂.left this in let ys := (⋃y'∈({y}:set α), {x | (x, y') ∈ d}) in have m ⊆ ys, from assume y' hy', show y' ∈ (⋃y'∈({y}:set α), {x | (x, y') ∈ d}), by simp; exact @hmd (y', y) ⟨hy', hym⟩, have c ≤ principal (s - ys), from le_trans hc₁ $ infi_le_of_le ⟨{y}, finite_insert finite.empty⟩ $ le_refl _, have (s - ys) ∩ (m ∩ s) ∈ c.sets, from inter_mem_sets (le_principal_iff.mp this) ‹m ∩ s ∈ c.sets›, have ∅ ∈ c.sets, from c.upwards_sets this $ assume x ⟨⟨hxs, hxys⟩, hxm, _⟩, hxys $ ‹m ⊆ ys› hxm, hc₂.left $ empty_in_sets_eq_bot.mp this⟩ lemma totally_bounded_iff_ultrafilter {s : set α} : totally_bounded s ↔ (∀f, ultrafilter f → f ≤ principal s → cauchy f) := ⟨assume hs f, cauchy_of_totally_bounded_of_ultrafilter hs, assume h, totally_bounded_iff_filter.mpr $ assume f hf hfs, have cauchy (ultrafilter_of f), from h (ultrafilter_of f) (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hfs), ⟨ultrafilter_of f, ultrafilter_of_le, this⟩⟩ lemma compact_of_totally_bounded_complete {s : set α} (ht : totally_bounded s) (hc : ∀{f:filter α}, cauchy f → f ≤ principal s → ∃x∈s, f ≤ nhds x) : compact s := begin rw [compact_iff_ultrafilter_le_nhds], rw [totally_bounded_iff_ultrafilter] at ht, exact assume f hf hfs, hc (ht _ hf hfs) hfs end /- complete space -/ class complete_space (α : Type u) [uniform_space α] : Prop := (complete : ∀{f:filter α}, cauchy f → ∃x, f ≤ nhds x) lemma complete_of_closed [complete_space α] {s : set α} {f : filter α} (h : closed s) (hf : cauchy f) (hfs : f ≤ principal s) : ∃x∈s, f ≤ nhds x := let ⟨x, hx⟩ := complete_space.complete hf in have x ∈ s, from closed_iff_nhds.mp h x $ neq_bot_of_le_neq_bot hf.left $ le_inf hx hfs, ⟨x, this, hx⟩ lemma compact_of_totally_bounded_closed [complete_space α] {s : set α} (ht : totally_bounded s) (hc : closed s) : compact s := @compact_of_totally_bounded_complete α _ s ht $ assume f, complete_of_closed hc lemma complete_space_extension [uniform_space β] {m : β → α} (hm : uniform_embedding m) (dense : ∀x, x ∈ closure (m '' univ)) (h : ∀f:filter β, cauchy f → ∃x:α, map m f ≤ nhds x) : complete_space α := ⟨assume (f : filter α), assume hf : cauchy f, let p : set (α × α) → set α → set α := λs t, {y : α| ∃x:α, x ∈ t ∧ (x, y) ∈ s}, g := uniformity.lift (λs, f^.lift' (p s)) in have mp₀ : monotone p, from assume a b h t s ⟨x, xs, xa⟩, ⟨x, xs, h xa⟩, have mp₁ : ∀{s}, monotone (p s), from assume s a b h x ⟨y, ya, yxs⟩, ⟨y, h ya, yxs⟩, have f ≤ g, from le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht, le_principal_iff.mpr $ f.upwards_sets ht $ assume x hx, ⟨x, hx, refl_mem_uniformity hs⟩, have g ≠ ⊥, from neq_bot_of_le_neq_bot hf.left this, have vmap m g ≠ ⊥, from vmap_neq_bot $ assume t ht, let ⟨t', ht', ht_mem⟩ := (mem_lift_iff $ monotone_lift' monotone_const mp₀).mp ht in let ⟨t'', ht'', ht'_sub⟩ := (mem_lift'_iff mp₁).mp ht_mem in let ⟨x, (hx : x ∈ t'')⟩ := inhabited_of_mem_sets hf.left ht'' in have h₀ : nhds x ⊓ principal (m '' univ) ≠ ⊥, by simp [closure_eq_nhds] at dense; exact dense x, have h₁ : {y | (x, y) ∈ t'} ∈ (nhds x ⊓ principal (m '' univ)).sets, from @mem_inf_sets_of_left α (nhds x) (principal (m '' univ)) _ $ mem_nhds_left ht', have h₂ : m '' univ ∈ (nhds x ⊓ principal (m '' univ)).sets, from @mem_inf_sets_of_right α (nhds x) (principal (m '' univ)) _ $ subset.refl _, have {y | (x, y) ∈ t'} ∩ m '' univ ∈ (nhds x ⊓ principal (m '' univ)).sets, from @inter_mem_sets α (nhds x ⊓ principal (m '' univ)) _ _ h₁ h₂, let ⟨y, xyt', b, _, b_eq⟩ := inhabited_of_mem_sets h₀ this in ⟨b, b_eq.symm ▸ ht'_sub ⟨x, hx, xyt'⟩⟩, have cauchy g, from ⟨‹g ≠ ⊥›, assume s hs, let ⟨s₁, hs₁, (comp_s₁ : comp_rel s₁ s₁ ⊆ s)⟩ := comp_mem_uniformity_sets hs, ⟨s₂, hs₂, (comp_s₂ : comp_rel s₂ s₂ ⊆ s₁)⟩ := comp_mem_uniformity_sets hs₁, ⟨t, ht, (prod_t : set.prod t t ⊆ s₂)⟩ := mem_prod_same_iff.mp (hf.right hs₂) in have hg₁ : p (vimage prod.swap s₁) t ∈ g.sets, from mem_lift (symm_le_uniformity hs₁) $ @mem_lift' α α f _ t ht, have hg₂ : p s₂ t ∈ g.sets, from mem_lift hs₂ $ @mem_lift' α α f _ t ht, have hg : set.prod (p (vimage prod.swap s₁) t) (p s₂ t) ∈ (filter.prod g g).sets, from @prod_mem_prod α α _ _ g g hg₁ hg₂, (filter.prod g g).upwards_sets hg (assume ⟨a, b⟩ ⟨⟨c₁, c₁t, (hc₁ : (a, c₁) ∈ s₁)⟩, ⟨c₂, c₂t, (hc₂ : (c₂, b) ∈ s₂)⟩⟩, have (c₁, c₂) ∈ set.prod t t, from ⟨c₁t, c₂t⟩, comp_s₁ $ prod_mk_mem_comp_rel hc₁ $ comp_s₂ $ prod_mk_mem_comp_rel (prod_t this) hc₂)⟩, have cauchy (filter.vmap m g), from cauchy_vmap (le_of_eq hm.right) ‹cauchy g› (by assumption), let ⟨x, (hx : map m (filter.vmap m g) ≤ nhds x)⟩ := h _ this in have map m (filter.vmap m g) ⊓ nhds x ≠ ⊥, from (le_nhds_iff_adhp_of_cauchy (cauchy_map (uniform_continuous_of_embedding hm) this)).mp hx, have g ⊓ nhds x ≠ ⊥, from neq_bot_of_le_neq_bot this (inf_le_inf (assume s hs, ⟨s, hs, subset.refl _⟩) (le_refl _)), ⟨x, calc f ≤ g : by assumption ... ≤ nhds x : le_nhds_of_cauchy_adhp ‹cauchy g› this⟩⟩ /- separation space -/ section separation_space local attribute [instance] separation_setoid instance : uniform_space (quotient (separation_setoid α)) := { uniform_space . uniformity := map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) uniformity, refl := assume s hs ⟨a, b⟩ (h : a = b), have ∀a:α, (a, a) ∈ vimage (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) s, from assume a, refl_mem_uniformity hs, h ▸ quotient.induction_on a this, symm := have prod.swap ∘ (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) = (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ∘ prod.swap, from funext $ assume ⟨a, b⟩, rfl, calc (map prod.swap ∘ map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧))) uniformity = (map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) ∘ map prod.swap) uniformity : by simp [map_compose, this] ... ≤ map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) uniformity : map_mono symm_le_uniformity, comp := calc (map (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) uniformity).lift' (λs, comp_rel s s) = uniformity.lift' ((λs, comp_rel s s) ∘ image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧))) : map_lift'_eq2 $ monotone_comp_rel monotone_id monotone_id ... ≤ uniformity.lift' (image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ∘ (λs:set (α×α), comp_rel s (comp_rel s s))) : lift'_mono' $ assume s hs ⟨a, b⟩ ⟨c, ⟨⟨a₁, a₂⟩, ha, a_eq⟩, ⟨⟨b₁, b₂⟩, hb, b_eq⟩⟩, begin simp at a_eq, simp at b_eq, have h : ⟦a₂⟧ = ⟦b₁⟧, { rw [a_eq.right, b_eq.left] }, have h : (a₂, b₁) ∈ separation_rel α := quotient.exact h, simp [function.comp, set.image, comp_rel], exact ⟨a₁, a_eq.left, b₂, b_eq.right, a₂, ha, b₁, h s hs, hb⟩ end ... = map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) (uniformity.lift' (λs:set (α×α), comp_rel s (comp_rel s s))) : by rw [map_lift'_eq]; exact monotone_comp_rel monotone_id (monotone_comp_rel monotone_id monotone_id) ... ≤ map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) uniformity : map_mono comp_le_uniformity3 } lemma uniform_continuous_quotient_mk : uniform_continuous (quotient.mk : α → quotient (separation_setoid α)) := le_refl _ lemma vmap_quotient_le_uniformity : vmap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) uniformity ≤ uniformity := assume t' ht', let ⟨t, ht, tt_t'⟩ := comp_mem_uniformity_sets ht' in let ⟨s, hs, ss_t⟩ := comp_mem_uniformity_sets ht in ⟨(λp:α×α, (⟦p.1⟧, ⟦p.2⟧)) '' s, (@uniformity α _).upwards_sets hs $ assume x hx, ⟨x, hx, rfl⟩, assume ⟨a₁, a₂⟩ ⟨⟨b₁, b₂⟩, hb, ab_eq⟩, have ⟦b₁⟧ = ⟦a₁⟧ ∧ ⟦b₂⟧ = ⟦a₂⟧, from prod.mk.inj ab_eq, have b₁ ≈ a₁ ∧ b₂ ≈ a₂, from and.imp quotient.exact quotient.exact this, have ab₁ : (a₁, b₁) ∈ t, from (setoid.symm this.left) t ht, have ba₂ : (b₂, a₂) ∈ s, from this.right s hs, tt_t' ⟨b₁, show ((a₁, a₂).1, b₁) ∈ t, from ab₁, ss_t ⟨b₂, show ((b₁, a₂).1, b₂) ∈ s, from hb, ba₂⟩⟩⟩ lemma complete_space_separation [h : complete_space α] : complete_space (quotient (separation_setoid α)) := ⟨assume f, assume hf : cauchy f, have cauchy (vmap (λx, ⟦x⟧) f), from cauchy_vmap vmap_quotient_le_uniformity hf $ vmap_neq_bot_of_surj hf.left $ assume b, quotient.exists_rep _, let ⟨x, (hx : vmap (λx, ⟦x⟧) f ≤ nhds x)⟩ := complete_space.complete this in ⟨⟦x⟧, calc f ≤ map (λx, ⟦x⟧) (vmap (λx, ⟦x⟧) f) : le_map_vmap $ assume b, quotient.exists_rep _ ... ≤ map (λx, ⟦x⟧) (nhds x) : map_mono hx ... ≤ _ : continuous_iff_towards.mp (continuous_of_uniform uniform_continuous_quotient_mk) _⟩⟩ end separation_space noncomputable def uniformly_extend [uniform_space γ] [nonempty γ] (emb : β → α) (f : β → γ) (a : α) : γ := classical.epsilon $ λc, map f (vmap emb (nhds a)) ≤ nhds c section uniform_extension variables [uniform_space β] [uniform_space γ] {e : β → α} (h_e : uniform_embedding e) (h_dense : ∀x, x ∈ closure (e '' univ)) {f : β → γ} (h_f : uniform_continuous f) local notation `ψ` := uniformly_extend e f include h_dense h_e private lemma vmap_e_neq_empty {a : α} : vmap e (nhds a) ≠ ⊥ := forall_sets_neq_empty_iff_neq_bot.mp $ have neq_bot : nhds a ⊓ principal (e '' univ) ≠ ⊥, by simp [closure_eq_nhds] at h_dense; exact h_dense a, assume s ⟨t, ht, (hs : vimage e t ⊆ s)⟩, have h₁ : t ∈ (nhds a ⊓ principal (e '' univ)).sets, from @mem_inf_sets_of_left α (nhds a) (principal (e '' univ)) t ht, have h₂ : e '' univ ∈ (nhds a ⊓ principal (e '' univ)).sets, from @mem_inf_sets_of_right α (nhds a) (principal (e '' univ)) _ $ subset.refl _, have t ∩ e '' univ ∈ (nhds a ⊓ principal (e '' univ)).sets, from @inter_mem_sets α (nhds a ⊓ principal (e '' univ)) _ _ h₁ h₂, let ⟨x, ⟨hx₁, y, hy, y_eq⟩⟩ := inhabited_of_mem_sets neq_bot this in ne_empty_of_mem $ hs $ show e y ∈ t, from y_eq.symm ▸ hx₁ include h_f lemma uniformly_extend_spec [nonempty γ] [complete_space γ] {a : α} : map f (vmap e (nhds a)) ≤ nhds (ψ a) := have cauchy (nhds a), from cauchy_nhds, have cauchy (vmap e (nhds a)), from cauchy_vmap (le_of_eq h_e.right) this $ vmap_e_neq_empty h_e h_dense, have cauchy (map f (vmap e (nhds a))), from cauchy_map h_f this, have ∃c, map f (vmap e (nhds a)) ≤ nhds c, from complete_space.complete this, classical.epsilon_spec this lemma uniformly_extend_unique [nonempty γ] [cγ : complete_space γ] [sγ : separated γ] {a : α} {c : γ} (h : map f (vmap e (nhds a)) ≤ nhds c) : ψ a = c := have map f (vmap e (nhds a)) ≤ nhds (ψ a) ⊓ nhds c, from le_inf (@uniformly_extend_spec α β γ _ _ _ _ h_e h_dense f h_f _ cγ a) h, -- why does the elaborator not find cγ? have nhds (uniformly_extend e f a) ⊓ nhds c ≠ ⊥, from neq_bot_of_le_neq_bot (by simp [map_eq_bot_iff]; exact vmap_e_neq_empty h_e h_dense) this, @eq_of_nhds_neq_bot _ _ (@separated_t2 _ _ sγ) _ _ this lemma uniformly_extend_of_emb [nonempty γ] [cγ : complete_space γ] [sγ : separated γ] {b : β} : ψ (e b) = f b := @uniformly_extend_unique α β γ _ _ _ e h_e h_dense f h_f _ cγ sγ (e b) (f b) $ have vmap e (nhds (e b)) ≤ nhds b, begin simp [nhds_eq_uniformity], rw [vmap_lift'_eq], simp [vimage, function.comp], rw [←h_e.right], rw [vmap_lift'_eq2], exact le_refl _, exact monotone_vimage, exact monotone_vimage end, calc map f (vmap e (nhds (e b))) ≤ map f (nhds b) : map_mono this ... ≤ nhds (f b) : continuous_iff_towards.mp (continuous_of_uniform h_f) b lemma uniform_continuous_uniformly_extend [nonempty γ] [cγ : complete_space γ] [sγ : separated γ] : uniform_continuous ψ := assume d hd, let ⟨s, hs, (hs_comp : comp_rel s (comp_rel s s) ⊆ d)⟩ := (mem_lift'_iff $ monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in have vimage (λp:β×β, (f p.1, f p.2)) s ∈ (@uniformity β _).sets, from h_f hs, have vimage (λp:β×β, (f p.1, f p.2)) s ∈ (vmap (λx:β×β, (e x.1, e x.2)) uniformity).sets, by rw [h_e.right.symm] at this; assumption, let ⟨t, ht, (ts : ∀p:(β×β), (e p.1, e p.2) ∈ t → (f p.1, f p.2) ∈ s)⟩ := this in show vimage (λp:(α×α), (ψ p.1, ψ p.2)) d ∈ uniformity.sets, from (@uniformity α _).upwards_sets (interior_mem_uniformity ht) $ assume ⟨x₁, x₂⟩ hx_t, have nhds (x₁, x₂) ≤ principal (interior t), from open_iff_nhds.mp open_interior (x₁, x₂) hx_t, have interior t ∈ (filter.prod (nhds x₁) (nhds x₂)).sets, by rw [nhds_prod_eq, le_principal_iff] at this; assumption, let ⟨m₁, hm₁, m₂, hm₂, (hm : set.prod m₁ m₂ ⊆ interior t)⟩ := mem_prod_iff.mp this in have nb : ∀{x}, map f (vmap e (nhds x)) ≠ ⊥, from assume x hx, by rw [map_eq_bot_iff] at hx; exact vmap_e_neq_empty h_e h_dense hx, have (f '' vimage e m₁) ∩ {y | (ψ x₁, y) ∈ s } ∈ (map f (vmap e (nhds x₁))).sets, from inter_mem_sets (image_mem_map $ vimage_mem_vmap $ hm₁) (uniformly_extend_spec h_e h_dense h_f $ mem_nhds_left hs), let ⟨a, ha₁, ha₂⟩ := inhabited_of_mem_sets nb this in have (f '' vimage e m₂) ∩ {x | (x, ψ x₂) ∈ s } ∈ (map f (vmap e (nhds x₂))).sets, from inter_mem_sets (image_mem_map $ vimage_mem_vmap $ hm₂) (uniformly_extend_spec h_e h_dense h_f $ mem_nhds_right hs), let ⟨b, hb₁, hb₂⟩ := inhabited_of_mem_sets nb this in have set.prod (vimage e m₁) (vimage e m₂) ⊆ vimage (λp:(β×β), (f p.1, f p.2)) s, from calc vimage (λp:(β×β), (e p.1, e p.2)) (set.prod m₁ m₂) ⊆ vimage (λp:(β×β), (e p.1, e p.2)) (interior t) : vimage_mono hm ... ⊆ vimage (λp:(β×β), (e p.1, e p.2)) t : vimage_mono interior_subset ... ⊆ vimage (λp:(β×β), (f p.1, f p.2)) s : ts, have set.prod (f '' vimage e m₁) (f '' vimage e m₂) ⊆ s, from calc set.prod (f '' vimage e m₁) (f '' vimage e m₂) = (λp:(β×β), (f p.1, f p.2)) '' (set.prod (vimage e m₁) (vimage e m₂)) : prod_image_image_eq ... ⊆ (λp:(β×β), (f p.1, f p.2)) '' vimage (λp:(β×β), (f p.1, f p.2)) s : mono_image this ... ⊆ s : image_subset_iff_subset_vimage.mpr $ subset.refl _, have (a, b) ∈ s, from @this (a, b) ⟨ha₁, hb₁⟩, hs_comp $ show (ψ x₁, ψ x₂) ∈ comp_rel s (comp_rel s s), from ⟨a, ha₂, ⟨b, this, hb₂⟩⟩ end uniform_extension end uniform_space end /-- Space of Cauchy filters This is essentially the completion of a uniform space. The embeddings are the neighbourhood filters. This space is not minimal, the separated uniform space (i.e. quotiented on the intersection of all entourages) is necessary for this. -/ def Cauchy (α : Type u) [uniform_space α] : Type u := { f : filter α // cauchy f } namespace Cauchy section parameters {α : Type u} [uniform_space α] def gen (s : set (α × α)) : set (Cauchy α × Cauchy α) := {p | s ∈ (filter.prod (p.1^.val) (p.2^.val))^.sets } lemma monotone_gen : monotone gen := monotone_set_of $ assume p, @monotone_mem_sets (α×α) (filter.prod (p.1^.val) (p.2^.val)) private lemma symm_gen : map prod.swap (uniformity^.lift' gen) ≤ uniformity^.lift' gen := calc map prod.swap (uniformity^.lift' gen) = uniformity^.lift' (λs:set (α×α), {p | s ∈ (filter.prod (p.2^.val) (p.1^.val))^.sets }) : begin delta gen, simp [map_lift'_eq, monotone_set_of, monotone_mem_sets, function.comp, image_swap_eq_vimage_swap] end ... ≤ uniformity^.lift' gen : uniformity_lift_le_swap (monotone_comp (monotone_set_of $ assume p, @monotone_mem_sets (α×α) ((filter.prod ((p.2).val) ((p.1).val)))) monotone_principal) begin have h := λ(p:Cauchy α×Cauchy α), @filter.prod_comm _ _ (p.2.val) (p.1.val), simp [function.comp, h], exact le_refl _ end private lemma comp_rel_gen_gen_subset_gen_comp_rel {s t : set (α×α)} : comp_rel (gen s) (gen t) ⊆ (gen (comp_rel s t) : set (Cauchy α × Cauchy α)) := assume ⟨f, g⟩ ⟨h, h₁, h₂⟩, let ⟨t₁, (ht₁ : t₁ ∈ f.val.sets), t₂, (ht₂ : t₂ ∈ h.val.sets), (h₁ : set.prod t₁ t₂ ⊆ s)⟩ := mem_prod_iff^.mp h₁ in let ⟨t₃, (ht₃ : t₃ ∈ h.val.sets), t₄, (ht₄ : t₄ ∈ g.val.sets), (h₂ : set.prod t₃ t₄ ⊆ t)⟩ := mem_prod_iff^.mp h₂ in have t₂ ∩ t₃ ∈ h.val.sets, from inter_mem_sets ht₂ ht₃, let ⟨x, xt₂, xt₃⟩ := inhabited_of_mem_sets (h.property.left) this in (filter.prod f^.val g^.val).upwards_sets (prod_mem_prod ht₁ ht₄) (assume ⟨a, b⟩ ⟨(ha : a ∈ t₁), (hb : b ∈ t₄)⟩, ⟨x, h₁ (show (a, x) ∈ set.prod t₁ t₂, from ⟨ha, xt₂⟩), h₂ (show (x, b) ∈ set.prod t₃ t₄, from ⟨xt₃, hb⟩)⟩) private lemma comp_gen : (uniformity^.lift' gen)^.lift' (λs, comp_rel s s) ≤ uniformity^.lift' gen := calc (uniformity^.lift' gen)^.lift' (λs, comp_rel s s) = uniformity^.lift' (λs, comp_rel (gen s) (gen s)) : begin rw [lift'_lift'_assoc], exact monotone_gen, exact (monotone_comp_rel monotone_id monotone_id) end ... ≤ uniformity^.lift' (λs, gen $ comp_rel s s) : lift'_mono' $ assume s hs, comp_rel_gen_gen_subset_gen_comp_rel ... = (uniformity^.lift' $ λs:set(α×α), comp_rel s s)^.lift' gen : begin rw [lift'_lift'_assoc], exact (monotone_comp_rel monotone_id monotone_id), exact monotone_gen end ... ≤ uniformity^.lift' gen : lift'_mono comp_le_uniformity (le_refl _) instance completion_space : uniform_space (Cauchy α) := { uniformity := uniformity^.lift' gen, refl := principal_le_lift' $ assume s hs ⟨a, b⟩ (a_eq_b : a = b), a_eq_b ▸ a^.property^.right hs, symm := symm_gen, comp := comp_gen } def pure_cauchy (a : α) : Cauchy α := ⟨pure a, cauchy_pure⟩ lemma uniform_embedding_pure_cauchy : uniform_embedding (pure_cauchy : α → Cauchy α) := ⟨assume a₁ a₂ h, have (pure_cauchy a₁).val = (pure_cauchy a₂).val, from congr_arg _ h, have {a₁} = ({a₂} : set α), from principal_eq_iff_eq.mp this, by simp at this; assumption, have (vimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) = id, from funext $ assume s, set.ext $ assume ⟨a₁, a₂⟩, by simp [vimage, gen, pure_cauchy, prod_principal_principal], calc vmap (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) (uniformity^.lift' gen) = uniformity^.lift' (vimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) : vmap_lift'_eq monotone_gen ... = uniformity : by simp [this]⟩ lemma pure_cauchy_dense : ∀x, x ∈ closure (pure_cauchy '' univ) := assume f, have h_ex : ∀s∈(@uniformity (Cauchy α) _).sets, ∃y:α, (f, pure_cauchy y) ∈ s, from assume s hs, let ⟨t'', ht''₁, (ht''₂ : gen t'' ⊆ s)⟩ := (mem_lift'_iff monotone_gen).mp hs in let ⟨t', ht'₁, ht'₂⟩ := comp_mem_uniformity_sets ht''₁ in have t' ∈ (filter.prod (f.val) (f.val)).sets, from f.property.right ht'₁, let ⟨t, ht, (h : set.prod t t ⊆ t')⟩ := mem_prod_same_iff.mp this in let ⟨x, (hx : x ∈ t)⟩ := inhabited_of_mem_sets f.property.left ht in have t'' ∈ (filter.prod f.val (pure x)).sets, from mem_prod_iff.mpr ⟨t, ht, {y:α | (x, y) ∈ t'}, assume y, begin simp, intro h, simp [h], exact refl_mem_uniformity ht'₁ end, assume ⟨a, b⟩ ⟨(h₁ : a ∈ t), (h₂ : (x, b) ∈ t')⟩, ht'₂ $ prod_mk_mem_comp_rel (@h (a, x) ⟨h₁, hx⟩) h₂⟩, ⟨x, ht''₂ $ by dsimp [gen]; exact this⟩, begin simp [closure_eq_nhds, nhds_eq_uniformity, lift'_inf_principal_eq], exact (lift'_neq_bot_iff $ monotone_inter monotone_const monotone_vimage).mpr (assume s hs, let ⟨y, hy⟩ := h_ex s hs in have pure_cauchy y ∈ pure_cauchy '' univ ∩ {y : Cauchy α | (f, y) ∈ s}, from ⟨mem_image_of_mem _ $ mem_univ y, hy⟩, ne_empty_of_mem this) end instance : complete_space (Cauchy α) := complete_space_extension uniform_embedding_pure_cauchy pure_cauchy_dense $ assume f hf, let f' : Cauchy α := ⟨f, hf⟩ in have map pure_cauchy f ≤ uniformity.lift' (vimage (prod.mk f')), from le_lift' $ assume s hs, let ⟨t, ht₁, (ht₂ : gen t ⊆ s)⟩ := (mem_lift'_iff monotone_gen).mp hs in let ⟨t', ht', (h : set.prod t' t' ⊆ t)⟩ := mem_prod_same_iff.mp (hf.right ht₁) in have t' ⊆ { y : α | (f', pure_cauchy y) ∈ gen t }, from assume x hx, (filter.prod f (pure x)).upwards_sets (prod_mem_prod ht' $ mem_pure hx) h, f.upwards_sets ht' $ subset.trans this (vimage_mono ht₂), ⟨f', by simp [nhds_eq_uniformity]; assumption⟩ end end Cauchy section constructions variables {α : Type u} {β : Type v} instance : weak_order (uniform_space α) := { weak_order . le := λt s, s^.uniformity ≤ t^.uniformity, le_antisymm := assume t s h₁ h₂, uniform_space_eq $ le_antisymm h₂ h₁, le_refl := assume t, le_refl _, le_trans := assume a b c h₁ h₂, @le_trans _ _ c^.uniformity b^.uniformity a^.uniformity h₂ h₁ } instance : has_Sup (uniform_space α) := ⟨assume s, { uniformity := (⨅u∈s, @uniformity α u), refl := le_infi $ assume u, le_infi $ assume hu, u.refl, symm := le_infi $ assume u, le_infi $ assume hu, le_trans (map_mono $ infi_le_of_le _ $ infi_le _ hu) u.symm, comp := le_infi $ assume u, le_infi $ assume hu, le_trans (lift'_mono (infi_le_of_le _ $ infi_le _ hu) $ le_refl _) u.comp }⟩ private lemma le_Sup {tt : set (uniform_space α)} {t : uniform_space α} (h : t ∈ tt) : t ≤ Sup tt := show (⨅u∈tt, @uniformity α u) ≤ t.uniformity, from infi_le_of_le t $ infi_le _ h private lemma Sup_le {tt : set (uniform_space α)} {t : uniform_space α} (h : ∀t'∈tt, t' ≤ t) : Sup tt ≤ t := show t.uniformity ≤ (⨅u∈tt, @uniformity α u), from le_infi $ assume t', le_infi $ assume ht', h t' ht' instance : has_bot (uniform_space α) := ⟨{ uniformity := ⊤, refl := le_top, symm := le_top, comp := le_top }⟩ instance : has_top (uniform_space α) := ⟨{ uniformity := principal id_rel, refl := le_refl _, symm := by simp; apply subset.refl, comp := begin rw [lift'_principal], { simp, apply subset.refl }, exact monotone_comp_rel monotone_id monotone_id end}⟩ instance : complete_lattice (uniform_space α) := { uniform_space.weak_order with sup := λa b, Sup {a, b}, le_sup_left := assume a b, le_Sup $ by simp, le_sup_right := assume a b, le_Sup $ by simp, sup_le := assume a b c h₁ h₂, Sup_le $ assume t', begin simp, intro h, cases h with h h, repeat { subst h; assumption } end, inf := λa b, Sup {x | x ≤ a ∧ x ≤ b}, le_inf := assume a b c h₁ h₂, le_Sup ⟨h₁, h₂⟩, inf_le_left := assume a b, Sup_le $ assume x ⟨ha, hb⟩, ha, inf_le_right := assume a b, Sup_le $ assume x ⟨ha, hb⟩, hb, top := ⊤, le_top := assume u, u.refl, bot := ⊥, bot_le := assume a, show a.uniformity ≤ ⊤, from le_top, Sup := Sup, le_Sup := assume s u, le_Sup, Sup_le := assume s u, Sup_le, Inf := λtt, Sup {t | ∀t'∈tt, t ≤ t'}, le_Inf := assume s a hs, le_Sup hs, Inf_le := assume s a ha, Sup_le $ assume u hs, hs _ ha } instance inhabited_uniform_space : inhabited (uniform_space α) := ⟨⊤⟩ def uniform_space.vmap (f : α → β) (u : uniform_space β) : uniform_space α := { uniformity := u.uniformity.vmap (λp:α×α, (f p.1, f p.2)), refl := le_trans (by simp; exact assume ⟨a, b⟩ (h : a = b), h ▸ rfl) (vmap_mono u.refl), symm := le_trans (by simp [map_swap_vmap_swap_eq, vmap_vmap_comp, function.comp]; exact le_refl _) (vmap_mono u.symm), comp := le_trans begin rw [vmap_lift'_eq, vmap_lift'_eq2], exact (lift'_mono' $ assume s hs ⟨a₁, a₂⟩ ⟨x, h₁, h₂⟩, ⟨f x, h₁, h₂⟩), repeat { exact monotone_comp_rel monotone_id monotone_id } end (vmap_mono u.comp) } lemma uniform_continuous_vmap {f : α → β} {u : uniform_space β} : @uniform_continuous α β (uniform_space.vmap f u) u f := map_vmap_le lemma to_topological_space_vmap {f : α → β} {u : uniform_space β} : @uniform_space.to_topological_space _ (uniform_space.vmap f u) = topological_space.induced f (@uniform_space.to_topological_space β u) := eq_of_nhds_eq_nhds $ assume a, begin simp [nhds_induced_eq_vmap, nhds_eq_uniformity, nhds_eq_uniformity], change vmap f (uniformity.lift' (vimage (λb, (f a, b)))) = (u.uniformity.vmap (λp:α×α, (f p.1, f p.2))).lift' (vimage (λa', (a, a'))), rw [vmap_lift'_eq monotone_vimage, vmap_lift'_eq2 monotone_vimage], exact rfl end instance : uniform_space empty := ⊤ instance : uniform_space unit := ⊤ instance : uniform_space bool := ⊤ instance : uniform_space ℕ := ⊤ instance : uniform_space ℤ := ⊤ instance {p : α → Prop} [t : uniform_space α] : uniform_space (subtype p) := uniform_space.vmap subtype.val t instance [t₁ : uniform_space α] [t₂ : uniform_space β] : uniform_space (α × β) := uniform_space.vmap prod.fst t₁ ⊔ uniform_space.vmap prod.snd t₂ /- a similar product space is possible on the function space (uniformity of pointwise convergence), but we want to have the uniformity of uniform convergence on function spaces -/ lemma to_topological_space_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) : @uniform_space.to_topological_space _ u₁ ≤ @uniform_space.to_topological_space _ u₂ := le_of_nhds_le_nhds $ assume a, by rw [@nhds_eq_uniformity α u₁ a, @nhds_eq_uniformity α u₂ a]; exact (lift'_mono h $ le_refl _) lemma supr_uniformity {ι : Sort v} {u : ι → uniform_space α} : (supr u).uniformity = (⨅i, (u i).uniformity) := show (⨅a (h : ∃i:ι, a = u i), a.uniformity) = _, from le_antisymm (le_infi $ assume i, infi_le_of_le (u i) $ infi_le _ ⟨i, rfl⟩) (le_infi $ assume a, le_infi $ assume ⟨i, (ha : a = u i)⟩, ha.symm ▸ infi_le _ _) lemma to_topological_space_top : @uniform_space.to_topological_space α ⊤ = ⊤ := top_unique $ assume s hs x hx ⟨a₁, a₂⟩ (h₁ : a₁ = a₂) (h₂ : a₁ = x), h₁ ▸ h₂.symm ▸ hx lemma to_topological_space_bot : @uniform_space.to_topological_space α ⊥ = ⊥ := bot_unique $ assume s hs, classical.by_cases (assume : s = ∅, this.symm ▸ @open_empty _ ⊥) (assume : s ≠ ∅, let ⟨x, hx⟩ := exists_mem_of_ne_empty this in have univ ⊆ _, from hs x hx, have s = univ, from top_unique $ assume y hy, @this (x, y) ⟨⟩ rfl, this.symm ▸ @open_univ _ ⊥) lemma to_topological_space_supr {ι : Sort v} {u : ι → uniform_space α} : @uniform_space.to_topological_space α (supr u) = (⨆i, @uniform_space.to_topological_space α (u i)) := classical.by_cases (assume h : nonempty ι, eq_of_nhds_eq_nhds $ assume a, begin rw [nhds_supr, nhds_eq_uniformity], change _ = (supr u).uniformity.lift' (vimage $ prod.mk a), begin rw [supr_uniformity, lift'_infi], exact (congr_arg _ $ funext $ assume i, @nhds_eq_uniformity α (u i) a), exact h, exact assume a b, rfl end end) (assume : ¬ nonempty ι, le_antisymm (have supr u = ⊥, from bot_unique $ supr_le $ assume i, (this ⟨i⟩).elim, have @uniform_space.to_topological_space _ (supr u) = ⊥, from this.symm ▸ to_topological_space_bot, this.symm ▸ bot_le) (supr_le $ assume i, to_topological_space_mono $ le_supr _ _)) end constructions
f3e1b4e548149c1df9c7b9038b7e35b883bcf895
16af888b14ca6cb84a768588040792cda8158ab8
/src/mathematica_parser.lean
48af895f9421488c5925f330be76c33092687572
[]
no_license
robertylewis/mathematica
e67c9ad9ca2b2cdd4a26799ee8ff447a6a199cc8
5fa094b9a390a71821ba3f11aa2fd40377d6b017
refs/heads/master
1,670,299,844,147
1,668,914,224,000
1,668,914,224,000
99,119,937
26
4
null
1,553,861,645,000
1,501,680,840,000
Lean
UTF-8
Lean
false
false
6,368
lean
import data.buffer.parser system.io open parser --namespace mathematica meta def htfi : has_to_format ℤ := ⟨λ z, int.rec_on z (λ k, ↑k) (λ k, "-"++↑(k+1))⟩ local attribute [instance] htfi structure mfloat := (sign : ℕ) (mantisa : ℕ) (exponent : ℕ) local notation `float` := mfloat meta instance : has_to_format float := ⟨λ f, to_fmt "(" ++ to_fmt f.sign ++ to_fmt ", " ++ to_fmt f.mantisa ++ ", " ++ to_fmt f.exponent ++ to_fmt ")"⟩ meta instance : has_reflect float | ⟨s, m, e⟩ := ((`(λ s' m' e', mfloat.mk s' m' e').subst (nat.reflect s)).subst (nat.reflect m)).subst (nat.reflect e) /-- The type mmexpr reflects Mathematica expression syntax. -/ inductive mmexpr : Type | sym : string → mmexpr | mstr : string → mmexpr | mint : int → mmexpr | app : mmexpr → list mmexpr → mmexpr | mreal : float → mmexpr meta def mmexpr_list_to_format (f : mmexpr → format) : list mmexpr → format | [] := to_fmt "" | [h] := f h | (h :: t) := f h ++ ", " ++ mmexpr_list_to_format t open mmexpr meta def mmexpr_to_format : mmexpr → format | (sym s) := to_fmt s | (mstr s) := to_fmt "\"" ++ to_fmt s ++ "\"" | (mint i) := to_fmt i | (app e1 ls) := mmexpr_to_format e1 ++ to_fmt "[" ++ mmexpr_list_to_format mmexpr_to_format ls ++ to_fmt "]" | (mreal r) := to_fmt r meta instance : has_to_format mmexpr := ⟨mmexpr_to_format⟩ def nat_of_char : char → ℕ | '0' := 0 | '1' := 1 | '2' := 2 | '3' := 3 | '4' := 4 | '5' := 5 | '6' := 6 | '7' := 7 | '8' := 8 | '9' := 9 | _ := 0 def nat_of_string_aux : ℕ → ℕ → list char → ℕ | weight acc [] := acc | weight acc (h::t) := nat_of_string_aux (weight*10) (weight * (nat_of_char h) + acc) t def nat_of_string (s : string) : nat := nat_of_string_aux 1 0 s.to_list.reverse def parse_is_neg : parser bool := (ch '-' >> return tt) <|> return ff def parse_int : parser mmexpr := do str "I[", is_neg ← parse_is_neg, n ← (nat_of_string ∘ list.as_string) <$> many (sat char.is_alphanum), ch ']', return $ mmexpr.mint (if is_neg then -n else n) def parse_string : parser mmexpr := do str "T[\"", s ← list.as_string <$> many (sat ((≠) '\"')), ch '\"', ch ']', return $ mmexpr.mstr s def parse_symbol : parser mmexpr := do str "Y[", s ← list.as_string <$> many (sat ((≠) ']')), ch ']', return $ mmexpr.sym s def parse_app_aux (parse_expr : parser mmexpr) : parser mmexpr := do str "A", hd ← parse_expr, ch '[', args ← sep_by (ch ',') parse_expr, ch ']', return $ mmexpr.app hd args def parse_mmexpr_aux (p : parser mmexpr) : parser mmexpr := parse_int <|> parse_string <|> parse_symbol <|> (parse_app_aux p) def parse_mmexpr : parser mmexpr := fix parse_mmexpr_aux private def make_monospaced : char → char | '\n' := ' ' | '\t' := ' ' | '\x0d' := ' ' | c := c def mk_mono_cb (s : char_buffer) : char_buffer := s.map make_monospaced def buffer.back {α} [inhabited α] (b : buffer α) : α := b.read' (b.size-1) meta def strip_trailing_whitespace_cb : char_buffer → char_buffer := λ s, if s.back = '\n' ∨ s.back = ' ' then strip_trailing_whitespace_cb s.pop_back else s def escape_quotes_cb (s : char_buffer) : char_buffer := s.foldl buffer.nil (λ c s', if c = '\"' then s' ++ "\\\"".to_char_buffer else s'.push_back c) def escape_term_buffer_cb (s : char_buffer) : char_buffer := s.foldl buffer.nil (λ c s', if c = '&' then s' ++ "&&".to_char_buffer else s'.push_back c) def quote_string_cb (s : char_buffer) : char_buffer := "\'".to_char_buffer ++ s ++ "\'".to_char_buffer def mk_mono (s : string) : string := (s.to_list.map make_monospaced).as_string meta def strip_trailing_whitespace : string → string := λ s, if s.back = '\n' ∨ s.back = ' ' then strip_trailing_whitespace s.pop_back else s def strip_newline : string → string := λ s, if s.back = '\n' then s.pop_back else s def escape_quotes (s : string) : string := s.fold "" (λ s' c, if c = '\"' then s' ++ "\\\"" else s'.str c) def escape_term (s : string) : string := s.fold "" (λ s' c, if c = '&' then s' ++ "&&" else s'.str c) def escape_slash (s : string) : string := s.fold "" (λ s' c, if c = '\\' then s' ++ "\\\\" else s'.str c) def quote_string (s : string) : string := "\'" ++ s ++ "\'" meta def parse_mmexpr_tac (s : char_buffer) : tactic mmexpr := match parser.run parse_mmexpr ((strip_trailing_whitespace_cb ∘ mk_mono_cb) s) with | sum.inr mme := return mme | sum.inl error := tactic.fail error end def parse_name : parser (list string) := do l ← sep_by (ch '.') (many $ sat ((≠) '.')), return $ (l.map list.as_string).reverse def mk_name_using : list string → name | [] := name.anonymous | (s :: l) := mk_str_name (mk_name_using l) s meta def parse_name_tac (s : string) : tactic name := match parser.run_string parse_name s with | sum.inr ls := return $ mk_name_using ls | sum.inl error := tactic.fail error end /-meta def parse_mmexpr_tac (s : char_buffer) : tactic mmexpr := (do sum.inr mme ← return $ parser.run parse_mmexpr ((strip_trailing_whitespace_cb ∘ mk_mono_cb) s), return mme) -/ namespace mathematica section def write_file (fn : string) (cnts : string) (mode := io.mode.write) : io unit := do h ← io.mk_file_handle fn io.mode.write, io.fs.write h cnts.to_char_buffer, io.fs.close h def exists_file (f : string) : io bool := do ch ← io.proc.spawn { cmd := "test", args := ["-f", f] }, ev ← io.proc.wait ch, return $ ev = 0 meta def new_text_file : string → ℕ → io nat | base n := do b ← exists_file (base ++ to_string n ++ ".txt"), if b then new_text_file base (n+1) else return n end meta def temp_file_name (base : string) : tactic string := do n ← tactic.unsafe_run_io $ new_text_file base 0, return $ base ++ to_string n ++ ".txt" end mathematica def io.buffer_cmd (args : io.process.spawn_args) : io char_buffer := do child ← io.proc.spawn { args with stdout := io.process.stdio.piped }, buf ← io.fs.read_to_end child.stdout, exitv ← io.proc.wait child, when (exitv ≠ 0) $ io.fail $ "process exited with status " ++ to_string exitv, return buf
836c5d45d6eb2ede9d22b0142616bf1ac3deca30
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/group_theory/submonoid.lean
f821b967d23b11d82ce2ffa785d485eff64011ce
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
43,066
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 -/ import algebra.big_operators import data.finset import data.equiv.mul_add /-! # Submonoids This file defines multiplicative and additive submonoids, first in an unbundled form (deprecated) and then in a bundled form. We prove submonoids of a monoid form a complete lattice, and results about images and preimages of submonoids under monoid homomorphisms. For the unbundled submonoids, these theorems use unbundled monoid homomorphisms (also deprecated), and the bundled versions use bundled monoid homomorphisms. There are also theorems about the submonoids generated by an element or a subset of a monoid, defined both inductively and as the infimum of the set of submonoids containing a given element/subset. ## Implementation notes Unbundled submonoids will slowly be removed from mathlib. (Bundled) submonoid inclusion is denoted `≤` rather than `⊆`, although `∈` is defined as membership of a submonoid's underlying set. ## Tags submonoid, submonoids, is_submonoid -/ variables {M : Type*} [monoid M] {s : set M} variables {A : Type*} [add_monoid A] {t : set A} /-- `s` is an additive submonoid: a set containing 0 and closed under addition. -/ class is_add_submonoid (s : set A) : Prop := (zero_mem : (0:A) ∈ s) (add_mem {a b} : a ∈ s → b ∈ s → a + b ∈ s) /-- `s` is a submonoid: a set containing 1 and closed under multiplication. -/ @[to_additive is_add_submonoid] class is_submonoid (s : set M) : Prop := (one_mem : (1:M) ∈ s) (mul_mem {a b} : a ∈ s → b ∈ s → a * b ∈ s) lemma additive.is_add_submonoid (s : set M) : ∀ [is_submonoid s], @is_add_submonoid (additive M) _ s | ⟨h₁, h₂⟩ := ⟨h₁, @h₂⟩ theorem additive.is_add_submonoid_iff {s : set M} : @is_add_submonoid (additive M) _ s ↔ is_submonoid s := ⟨λ ⟨h₁, h₂⟩, ⟨h₁, @h₂⟩, λ h, by exactI additive.is_add_submonoid _⟩ lemma multiplicative.is_submonoid (s : set A) : ∀ [is_add_submonoid s], @is_submonoid (multiplicative A) _ s | ⟨h₁, h₂⟩ := ⟨h₁, @h₂⟩ theorem multiplicative.is_submonoid_iff {s : set A} : @is_submonoid (multiplicative A) _ s ↔ is_add_submonoid s := ⟨λ ⟨h₁, h₂⟩, ⟨h₁, @h₂⟩, λ h, by exactI multiplicative.is_submonoid _⟩ /-- The intersection of two submonoids of a monoid `M` is a submonoid of `M`. -/ @[to_additive "The intersection of two `add_submonoid`s of an `add_monoid` `M` is an `add_submonoid` of M."] instance is_submonoid.inter (s₁ s₂ : set M) [is_submonoid s₁] [is_submonoid s₂] : is_submonoid (s₁ ∩ s₂) := { one_mem := ⟨is_submonoid.one_mem _, is_submonoid.one_mem _⟩, mul_mem := λ x y hx hy, ⟨is_submonoid.mul_mem hx.1 hy.1, is_submonoid.mul_mem hx.2 hy.2⟩ } /-- The intersection of an indexed set of submonoids of a monoid `M` is a submonoid of `M`. -/ @[to_additive "The intersection of an indexed set of `add_submonoid`s of an `add_monoid` `M` is an `add_submonoid` of `M`."] instance is_submonoid.Inter {ι : Sort*} (s : ι → set M) [h : ∀ y : ι, is_submonoid (s y)] : is_submonoid (set.Inter s) := { one_mem := set.mem_Inter.2 $ λ y, is_submonoid.one_mem (s y), mul_mem := λ x₁ x₂ h₁ h₂, set.mem_Inter.2 $ λ y, is_submonoid.mul_mem (set.mem_Inter.1 h₁ y) (set.mem_Inter.1 h₂ y) } /-- The union of an indexed, directed, nonempty set of submonoids of a monoid `M` is a submonoid of `M`. -/ @[to_additive is_add_submonoid_Union_of_directed "The union of an indexed, directed, nonempty set of `add_submonoid`s of an `add_monoid` `M` is an `add_submonoid` of `M`. "] lemma is_submonoid_Union_of_directed {ι : Type*} [hι : nonempty ι] (s : ι → set M) [∀ i, is_submonoid (s i)] (directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) : is_submonoid (⋃i, s i) := { one_mem := let ⟨i⟩ := hι in set.mem_Union.2 ⟨i, is_submonoid.one_mem _⟩, mul_mem := λ a b ha hb, let ⟨i, hi⟩ := set.mem_Union.1 ha in let ⟨j, hj⟩ := set.mem_Union.1 hb in let ⟨k, hk⟩ := directed i j in set.mem_Union.2 ⟨k, is_submonoid.mul_mem (hk.1 hi) (hk.2 hj)⟩ } section powers /-- The set of natural number powers `1, x, x², ...` of an element `x` of a monoid. -/ def powers (x : M) : set M := {y | ∃ n:ℕ, x^n = y} /-- The set of natural number multiples `0, x, 2x, ...` of an element `x` of an `add_monoid`. -/ def multiples (x : A) : set A := {y | ∃ n:ℕ, add_monoid.smul n x = y} attribute [to_additive multiples] powers /-- 1 is in the set of natural number powers of an element of a monoid. -/ lemma powers.one_mem {x : M} : (1 : M) ∈ powers x := ⟨0, pow_zero _⟩ /-- 0 is in the set of natural number multiples of an element of an `add_monoid`. -/ lemma multiples.zero_mem {x : A} : (0 : A) ∈ multiples x := ⟨0, add_monoid.zero_smul _⟩ attribute [to_additive] powers.one_mem /-- An element of a monoid is in the set of that element's natural number powers. -/ lemma powers.self_mem {x : M} : x ∈ powers x := ⟨1, pow_one _⟩ /-- An element of an `add_monoid` is in the set of that element's natural number multiples. -/ lemma multiples.self_mem {x : A} : x ∈ multiples x := ⟨1, add_monoid.one_smul _⟩ attribute [to_additive] powers.self_mem /-- The set of natural number powers of an element of a monoid is closed under multiplication. -/ lemma powers.mul_mem {x y z : M} : (y ∈ powers x) → (z ∈ powers x) → (y * z ∈ powers x) := λ ⟨n₁, h₁⟩ ⟨n₂, h₂⟩, ⟨n₁ + n₂, by simp only [pow_add, *]⟩ /-- The set of natural number multiples of an element of an `add_monoid` is closed under addition. -/ lemma multiples.add_mem {x y z : A} : (y ∈ multiples x) → (z ∈ multiples x) → (y + z ∈ multiples x) := @powers.mul_mem (multiplicative A) _ _ _ _ attribute [to_additive] powers.mul_mem /-- The set of natural number powers of an element of a monoid `M` is a submonoid of `M`. -/ @[to_additive is_add_submonoid "The set of natural number multiples of an element of an `add_monoid` `M` is an `add_submonoid` of `M`."] instance powers.is_submonoid (x : M) : is_submonoid (powers x) := { one_mem := powers.one_mem, mul_mem := λ y z, powers.mul_mem } /-- A monoid is a submonoid of itself. -/ @[to_additive is_add_submonoid "An `add_monoid` is an `add_submonoid` of itself."] instance univ.is_submonoid : is_submonoid (@set.univ M) := by split; simp /-- The preimage of a submonoid under a monoid hom is a submonoid of the domain. -/ @[to_additive is_add_submonoid "The preimage of an `add_submonoid` under an `add_monoid` hom is an `add_submonoid` of the domain."] instance preimage.is_submonoid {N : Type*} [monoid N] (f : M → N) [is_monoid_hom f] (s : set N) [is_submonoid s] : is_submonoid (f ⁻¹' s) := { one_mem := show f 1 ∈ s, by rw is_monoid_hom.map_one f; exact is_submonoid.one_mem s, mul_mem := λ a b (ha : f a ∈ s) (hb : f b ∈ s), show f (a * b) ∈ s, by rw is_monoid_hom.map_mul f; exact is_submonoid.mul_mem ha hb } /-- The image of a submonoid under a monoid hom is a submonoid of the codomain. -/ @[instance, to_additive is_add_submonoid "The image of an `add_submonoid` under an `add_monoid` hom is an `add_submonoid` of the codomain."] lemma image.is_submonoid {γ : Type*} [monoid γ] (f : M → γ) [is_monoid_hom f] (s : set M) [is_submonoid s] : is_submonoid (f '' s) := { one_mem := ⟨1, is_submonoid.one_mem s, is_monoid_hom.map_one f⟩, mul_mem := λ a b ⟨x, hx⟩ ⟨y, hy⟩, ⟨x * y, is_submonoid.mul_mem hx.1 hy.1, by rw [is_monoid_hom.map_mul f, hx.2, hy.2]⟩ } /-- The image of a monoid hom is a submonoid of the codomain. -/ @[to_additive is_add_submonoid "The image of an `add_monoid` hom is an `add_submonoid` of the codomain."] instance range.is_submonoid {γ : Type*} [monoid γ] (f : M → γ) [is_monoid_hom f] : is_submonoid (set.range f) := by rw ← set.image_univ; apply_instance /-- Submonoids are closed under natural powers. -/ lemma is_submonoid.pow_mem {a : M} [is_submonoid s] (h : a ∈ s) : ∀ {n : ℕ}, a ^ n ∈ s | 0 := is_submonoid.one_mem s | (n + 1) := is_submonoid.mul_mem h is_submonoid.pow_mem /-- An `add_submonoid` is closed under multiplication by naturals. -/ lemma is_add_submonoid.smul_mem {a : A} [is_add_submonoid t] : ∀ (h : a ∈ t) {n : ℕ}, add_monoid.smul n a ∈ t := @is_submonoid.pow_mem (multiplicative A) _ _ _ (multiplicative.is_submonoid _) attribute [to_additive smul_mem] is_submonoid.pow_mem /-- The set of natural number powers of an element of a submonoid is a subset of the submonoid. -/ lemma is_submonoid.power_subset {a : M} [is_submonoid s] (h : a ∈ s) : powers a ⊆ s := assume x ⟨n, hx⟩, hx ▸ is_submonoid.pow_mem h /-- The set of natural number multiples of an element of an `add_submonoid` is a subset of the `add_submonoid`. -/ lemma is_add_submonoid.multiple_subset {a : A} [is_add_submonoid t] : a ∈ t → multiples a ⊆ t := @is_submonoid.power_subset (multiplicative A) _ _ _ (multiplicative.is_submonoid _) attribute [to_additive multiple_subset] is_submonoid.power_subset end powers namespace is_submonoid /-- The product of a list of elements of a submonoid is an element of the submonoid. -/ @[to_additive "The sum of a list of elements of an `add_submonoid` is an element of the `add_submonoid`."] lemma list_prod_mem [is_submonoid s] : ∀{l : list M}, (∀x∈l, x ∈ s) → l.prod ∈ s | [] h := one_mem s | (a::l) h := suffices a * l.prod ∈ s, by simpa, have a ∈ s ∧ (∀x∈l, x ∈ s), by simpa using h, is_submonoid.mul_mem this.1 (list_prod_mem this.2) /-- The product of a multiset of elements of a submonoid of a `comm_monoid` is an element of the submonoid. -/ @[to_additive "The sum of a multiset of elements of an `add_submonoid` of an `add_comm_monoid` is an element of the `add_submonoid`. "] lemma multiset_prod_mem {M} [comm_monoid M] (s : set M) [is_submonoid s] (m : multiset M) : (∀a∈m, a ∈ s) → m.prod ∈ s := begin refine quotient.induction_on m (assume l hl, _), rw [multiset.quot_mk_to_coe, multiset.coe_prod], exact list_prod_mem hl end /-- The product of elements of a submonoid of a `comm_monoid` indexed by a `finset` is an element of the submonoid. -/ @[to_additive "The sum of elements of an `add_submonoid` of an `add_comm_monoid` indexed by a `finset` is an element of the `add_submonoid`."] lemma finset_prod_mem {M A} [comm_monoid M] (s : set M) [is_submonoid s] (f : A → M) : ∀(t : finset A), (∀b∈t, f b ∈ s) → t.prod f ∈ s | ⟨m, hm⟩ hs := begin refine multiset_prod_mem s _ _, simp, rintros a b hb rfl, exact hs _ hb end end is_submonoid -- TODO: modify `subtype_instance` to produce this definition, then use it here -- and for `subtype.group` /-- Submonoids are themselves monoids. -/ @[to_additive add_monoid "An `add_submonoid` is itself an `add_monoid`."] instance subtype.monoid {s : set M} [is_submonoid s] : monoid s := { one := ⟨1, is_submonoid.one_mem s⟩, mul := λ x y, ⟨x * y, is_submonoid.mul_mem x.2 y.2⟩, mul_one := λ x, subtype.eq $ mul_one x.1, one_mul := λ x, subtype.eq $ one_mul x.1, mul_assoc := λ x y z, subtype.eq $ mul_assoc x.1 y.1 z.1 } /-- Submonoids of commutative monoids are themselves commutative monoids. -/ @[to_additive add_comm_monoid "An `add_submonoid` of a commutative `add_monoid` is itself a commutative `add_monoid`. "] instance subtype.comm_monoid {M} [comm_monoid M] {s : set M} [is_submonoid s] : comm_monoid s := { mul_comm := λ x y, subtype.eq $ mul_comm x.1 y.1, .. subtype.monoid } /-- Submonoids inherit the 1 of the monoid. -/ @[simp, to_additive "An `add_submonoid` inherits the 0 of the `add_monoid`. "] lemma is_submonoid.coe_one [is_submonoid s] : ((1 : s) : M) = 1 := rfl /-- Submonoids inherit the multiplication of the monoid. -/ @[simp, to_additive "An `add_submonoid` inherits the addition of the `add_monoid`. "] lemma is_submonoid.coe_mul [is_submonoid s] (a b : s) : ((a * b : s) : M) = a * b := rfl /-- Submonoids inherit the exponentiation by naturals of the monoid. -/ @[simp] lemma is_submonoid.coe_pow [is_submonoid s] (a : s) (n : ℕ) : ((a ^ n : s) : M) = a ^ n := by induction n; simp [*, pow_succ] /-- An `add_submonoid` inherits the multiplication by naturals of the `add_monoid`. -/ @[simp] lemma is_add_submonoid.smul_coe {A : Type*} [add_monoid A] {s : set A} [is_add_submonoid s] (a : s) (n : ℕ) : ((add_monoid.smul n a : s) : A) = add_monoid.smul n a := by {induction n, refl, simp [*, succ_smul]} attribute [to_additive smul_coe] is_submonoid.coe_pow /-- The natural injection from a submonoid into the monoid is a monoid hom. -/ @[to_additive is_add_monoid_hom "The natural injection from an `add_submonoid` into the `add_monoid` is an `add_monoid` hom. "] instance subtype_val.is_monoid_hom [is_submonoid s] : is_monoid_hom (subtype.val : s → M) := { map_one := rfl, map_mul := λ _ _, rfl } /-- The natural injection from a submonoid into the monoid is a monoid hom. -/ @[to_additive is_add_monoid_hom "The natural injection from an `add_submonoid` into the `add_monoid` is an `add_monoid` hom. "] instance coe.is_monoid_hom [is_submonoid s] : is_monoid_hom (coe : s → M) := subtype_val.is_monoid_hom /-- Given a monoid hom `f : γ → M` whose image is contained in a submonoid `s`, the induced map from `γ` to `s` is a monoid hom. -/ @[to_additive is_add_monoid_hom "Given an `add_monoid` hom `f : γ → M` whose image is contained in an `add_submonoid` s, the induced map from `γ` to `s` is an `add_monoid` hom."] instance subtype_mk.is_monoid_hom {γ : Type*} [monoid γ] [is_submonoid s] (f : γ → M) [is_monoid_hom f] (h : ∀ x, f x ∈ s) : is_monoid_hom (λ x, (⟨f x, h x⟩ : s)) := { map_one := subtype.eq (is_monoid_hom.map_one f), map_mul := λ x y, subtype.eq (is_monoid_hom.map_mul f x y) } /-- Given two submonoids `s` and `t` such that `s ⊆ t`, the natural injection from `s` into `t` is a monoid hom. -/ @[to_additive is_add_monoid_hom "Given two `add_submonoid`s `s` and `t` such that `s ⊆ t`, the natural injection from `s` into `t` is an `add_monoid` hom."] instance set_inclusion.is_monoid_hom (t : set M) [is_submonoid s] [is_submonoid t] (h : s ⊆ t) : is_monoid_hom (set.inclusion h) := subtype_mk.is_monoid_hom _ _ namespace add_monoid /-- The inductively defined membership predicate for the submonoid generated by a subset of a monoid. -/ inductive in_closure (s : set A) : A → Prop | basic {a : A} : a ∈ s → in_closure a | zero : in_closure 0 | add {a b : A} : in_closure a → in_closure b → in_closure (a + b) end add_monoid namespace monoid /-- The inductively defined membership predicate for the `add_submonoid` generated by a subset of an add_monoid. -/ inductive in_closure (s : set M) : M → Prop | basic {a : M} : a ∈ s → in_closure a | one : in_closure 1 | mul {a b : M} : in_closure a → in_closure b → in_closure (a * b) attribute [to_additive] monoid.in_closure attribute [to_additive] monoid.in_closure.one attribute [to_additive] monoid.in_closure.mul /-- The inductively defined submonoid generated by a subset of a monoid. -/ @[to_additive "The inductively defined `add_submonoid` genrated by a subset of an `add_monoid`."] def closure (s : set M) : set M := {a | in_closure s a } @[to_additive is_add_submonoid] instance closure.is_submonoid (s : set M) : is_submonoid (closure s) := { one_mem := in_closure.one s, mul_mem := assume a b, in_closure.mul } /-- A subset of a monoid is contained in the submonoid it generates. -/ @[to_additive "A subset of an `add_monoid` is contained in the `add_submonoid` it generates."] theorem subset_closure {s : set M} : s ⊆ closure s := assume a, in_closure.basic /-- The submonoid generated by a set is contained in any submonoid that contains the set. -/ @[to_additive "The `add_submonoid` generated by a set is contained in any `add_submonoid` that contains the set."] theorem closure_subset {s t : set M} [is_submonoid t] (h : s ⊆ t) : closure s ⊆ t := assume a ha, by induction ha; simp [h _, *, is_submonoid.one_mem, is_submonoid.mul_mem] /-- Given subsets `t` and `s` of a monoid `M`, if `s ⊆ t`, the submonoid of `M` generated by `s` is contained in the submonoid generated by `t`. -/ @[to_additive "Given subsets `t` and `s` of an `add_monoid M`, if `s ⊆ t`, the `add_submonoid` of `M` generated by `s` is contained in the `add_submonoid` generated by `t`."] theorem closure_mono {s t : set M} (h : s ⊆ t) : closure s ⊆ closure t := closure_subset $ set.subset.trans h subset_closure /-- The submonoid generated by an element of a monoid equals the set of natural number powers of the element. -/ @[to_additive "The `add_submonoid` generated by an element of an `add_monoid` equals the set of natural number multiples of the element."] theorem closure_singleton {x : M} : closure ({x} : set M) = powers x := set.eq_of_subset_of_subset (closure_subset $ set.singleton_subset_iff.2 $ powers.self_mem) $ is_submonoid.power_subset $ set.singleton_subset_iff.1 $ subset_closure /-- The image under a monoid hom of the submonoid generated by a set equals the submonoid generated by the image of the set under the monoid hom. -/ @[to_additive "The image under an `add_monoid` hom of the `add_submonoid` generated by a set equals the `add_submonoid` generated by the image of the set under the `add_monoid` hom."] lemma image_closure {A : Type*} [monoid A] (f : M → A) [is_monoid_hom f] (s : set M) : f '' closure s = closure (f '' s) := le_antisymm begin rintros _ ⟨x, hx, rfl⟩, apply in_closure.rec_on hx; intros, { solve_by_elim [subset_closure, set.mem_image_of_mem] }, { rw [is_monoid_hom.map_one f], apply is_submonoid.one_mem }, { rw [is_monoid_hom.map_mul f], solve_by_elim [is_submonoid.mul_mem] } end (closure_subset $ set.image_subset _ subset_closure) /-- Given an element `a` of the submonoid of a monoid `M` generated by a set `s`, there exists a list of elements of `s` whose product is `a`. -/ @[to_additive "Given an element `a` of the `add_submonoid` of an `add_monoid M` generated by a set `s`, there exists a list of elements of `s` whose sum is `a`."] theorem exists_list_of_mem_closure {s : set M} {a : M} (h : a ∈ closure s) : (∃l:list M, (∀x∈l, x ∈ s) ∧ l.prod = a) := begin induction h, case in_closure.basic : a ha { existsi ([a]), simp [ha] }, case in_closure.one { existsi ([]), simp }, case in_closure.mul : a b _ _ ha hb { rcases ha with ⟨la, ha, eqa⟩, rcases hb with ⟨lb, hb, eqb⟩, existsi (la ++ lb), simp [eqa.symm, eqb.symm, or_imp_distrib], exact assume a, ⟨ha a, hb a⟩ } end /-- Given sets `s, t` of a commutative monoid `M`, `x ∈ M` is in the submonoid of `M` generated by `s ∪ t` iff there exists an element of the submonoid generated by `s` and an element of the submonoid generated by `t` whose product is `x`. -/ @[to_additive "Given sets `s, t` of a commutative `add_monoid M`, `x ∈ M` is in the `add_submonoid` of `M` generated by `s ∪ t` iff there exists an element of the `add_submonoid` generated by `s` and an element of the `add_submonoid` generated by `t` whose sum is `x`."] theorem mem_closure_union_iff {M : Type*} [comm_monoid M] {s t : set M} {x : M} : x ∈ closure (s ∪ t) ↔ ∃ y ∈ closure s, ∃ z ∈ closure t, y * z = x := ⟨λ hx, let ⟨L, HL1, HL2⟩ := exists_list_of_mem_closure hx in HL2 ▸ list.rec_on L (λ _, ⟨1, is_submonoid.one_mem _, 1, is_submonoid.one_mem _, mul_one _⟩) (λ hd tl ih HL1, let ⟨y, hy, z, hz, hyzx⟩ := ih (list.forall_mem_of_forall_mem_cons HL1) in or.cases_on (HL1 hd $ list.mem_cons_self _ _) (λ hs, ⟨hd * y, is_submonoid.mul_mem (subset_closure hs) hy, z, hz, by rw [mul_assoc, list.prod_cons, ← hyzx]; refl⟩) (λ ht, ⟨y, hy, z * hd, is_submonoid.mul_mem hz (subset_closure ht), by rw [← mul_assoc, list.prod_cons, ← hyzx, mul_comm hd]; refl⟩)) HL1, λ ⟨y, hy, z, hz, hyzx⟩, hyzx ▸ is_submonoid.mul_mem (closure_mono (set.subset_union_left _ _) hy) (closure_mono (set.subset_union_right _ _) hz)⟩ end monoid -- Bundled submonoids and `add_submonoid`s /-- A submonoid of a monoid `M` is a subset containing 1 and closed under multiplication. -/ structure submonoid (M : Type*) [monoid M] := (carrier : set M) (one_mem' : (1 : M) ∈ carrier) (mul_mem' {a b} : a ∈ carrier → b ∈ carrier → a * b ∈ carrier) /-- An additive submonoid of an additive monoid `M` is a subset containing 0 and closed under addition. -/ structure add_submonoid (M : Type*) [add_monoid M] := (carrier : set M) (zero_mem' : (0 : M) ∈ carrier) (add_mem' {a b} : a ∈ carrier → b ∈ carrier → a + b ∈ carrier) attribute [to_additive add_submonoid] submonoid /-- Map from submonoids of monoid `M` to `add_submonoid`s of `additive M`. -/ def submonoid.to_add_submonoid {M : Type*} [monoid M] (S : submonoid M) : add_submonoid (additive M) := { carrier := S.carrier, zero_mem' := S.one_mem', add_mem' := S.mul_mem' } /-- Map from `add_submonoid`s of `additive M` to submonoids of `M`. -/ def submonoid.of_add_submonoid {M : Type*} [monoid M] (S : add_submonoid (additive M)) : submonoid M := { carrier := S.carrier, one_mem' := S.zero_mem', mul_mem' := S.add_mem' } /-- Map from `add_submonoid`s of `add_monoid M` to submonoids of `multiplicative M`. -/ def add_submonoid.to_submonoid {M : Type*} [add_monoid M] (S : add_submonoid M) : submonoid (multiplicative M) := { carrier := S.carrier, one_mem' := S.zero_mem', mul_mem' := S.add_mem' } /-- Map from submonoids of `multiplicative M` to `add_submonoid`s of `add_monoid M`. -/ def add_submonoid.of_submonoid {M : Type*} [add_monoid M] (S : submonoid (multiplicative M)) : add_submonoid M := { carrier := S.carrier, zero_mem' := S.one_mem', add_mem' := S.mul_mem' } /-- Submonoids of monoid `M` are isomorphic to additive submonoids of `additive M`. -/ def submonoid.add_submonoid_equiv (M : Type*) [monoid M] : submonoid M ≃ add_submonoid (additive M) := { to_fun := submonoid.to_add_submonoid, inv_fun := submonoid.of_add_submonoid, left_inv := λ x, by cases x; refl, right_inv := λ x, by cases x; refl } namespace submonoid variables (S : submonoid M) @[to_additive] instance : has_coe (submonoid M) (set M) := ⟨submonoid.carrier⟩ @[to_additive] instance : has_mem M (submonoid M) := ⟨λ m S, m ∈ S.carrier⟩ @[to_additive] instance : has_le (submonoid M) := ⟨λ S T, S.carrier ⊆ T.carrier⟩ @[simp, to_additive] lemma mem_coe {m : M} : m ∈ (S : set M) ↔ m ∈ S := iff.rfl /-- Two submonoids are equal if the underlying subsets are equal. -/ @[to_additive "Two `add_submonoid`s are equal if the underlying subsets are equal."] theorem ext' {S T : submonoid M} (h : (S : set M) = T) : S = T := by cases S; cases T; congr' /-- Two submonoids are equal if and only if the underlying subsets are equal. -/ @[to_additive "Two `add_submonoid`s are equal if and only if the underlying subsets are equal."] protected theorem ext'_iff {S T : submonoid M} : (S : set M) = T ↔ S = T := ⟨ext', λ h, h ▸ rfl⟩ /-- Two submonoids are equal if they have the same elements. -/ @[ext, to_additive "Two `add_submonoid`s are equal if they have the same elements."] theorem ext {S T : submonoid M} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := ext' $ set.ext h attribute [ext] add_submonoid.ext /-- A submonoid contains the monoid's 1. -/ @[to_additive "An `add_submonoid` contains the monoid's 0."] theorem one_mem : (1 : M) ∈ S := S.one_mem' /-- A submonoid is closed under multiplication. -/ @[to_additive "An `add_submonoid` is closed under addition."] theorem mul_mem {x y : M} : x ∈ S → y ∈ S → x * y ∈ S := submonoid.mul_mem' S /-- A finite product of elements of a submonoid of a commutative monoid is in the submonoid. -/ @[to_additive "A finite sum of elements of an `add_submonoid` of an `add_comm_monoid` is in the `add_submonoid`."] lemma prod_mem {M : Type*} [comm_monoid M] (S : submonoid M) {ι : Type*} [decidable_eq ι] {t : finset ι} {f : ι → M} : (∀c ∈ t, f c ∈ S) → t.prod f ∈ S := finset.induction_on t (by simp [S.one_mem]) (by simp [S.mul_mem] {contextual := tt}) /-- A directed union of submonoids is a submonoid. -/ @[to_additive "A directed union of `add_submonoid`s is an `add_submonoid`."] def Union_of_directed {ι : Type*} [hι : nonempty ι] (s : ι → submonoid M) (directed : ∀ i j, ∃ k, s i ≤ s k ∧ s j ≤ s k) : submonoid M := { carrier := (⋃i, s i), one_mem' := let ⟨i⟩ := hι in set.mem_Union.2 ⟨i, submonoid.one_mem _⟩, mul_mem' := λ a b ha hb, let ⟨i, hi⟩ := set.mem_Union.1 ha in let ⟨j, hj⟩ := set.mem_Union.1 hb in let ⟨k, hk⟩ := directed i j in set.mem_Union.2 ⟨k, (s k).mul_mem (hk.1 hi) (hk.2 hj)⟩ } /-- A submonoid of a monoid inherits a multiplication. -/ @[to_additive "An `add_submonoid` of an `add_monoid` inherits an addition."] instance has_mul : has_mul S := ⟨λ a b, ⟨a.1 * b.1, S.mul_mem a.2 b.2⟩⟩ /-- A submonoid of a monoid inherits a 1. -/ @[to_additive "An `add_submonoid` of an `add_monoid` inherits a zero."] instance has_one : has_one S := ⟨⟨_, S.one_mem⟩⟩ @[simp, to_additive] lemma coe_mul (x y : S) : (↑(x * y) : M) = ↑x * ↑y := rfl @[simp, to_additive] lemma coe_one : ((1 : S) : M) = 1 := rfl /-- A submonoid of a monoid inherits a monoid structure. -/ @[to_additive to_add_monoid "An `add_submonoid` of an `add_monoid` inherits an `add_monoid` structure."] instance to_monoid {M : Type*} [monoid M] {S : submonoid M} : monoid S := by refine { mul := (*), one := 1, ..}; by simp [mul_assoc] /-- A submonoid of a `comm_monoid` is a `comm_monoid`. -/ @[to_additive to_add_comm_monoid "An `add_submonoid` of an `add_comm_monoid` is an `add_comm_monoid`."] instance to_comm_monoid {M} [comm_monoid M] (S : submonoid M) : comm_monoid S := { mul_comm := λ _ _, subtype.ext.2 $ mul_comm _ _, ..submonoid.to_monoid} /-- The natural monoid hom from a submonoid of monoid `M` to `M`. -/ @[to_additive "The natural monoid hom from an `add_submonoid` of `add_monoid` `M` to `M`."] def subtype : S →* M := { to_fun := coe, map_one' := rfl, map_mul' := λ _ _, rfl } @[simp, to_additive] theorem subtype_apply (x : S) : S.subtype x = x := rfl @[to_additive] lemma subtype_eq_val : (S.subtype : S → M) = subtype.val := rfl /-- The powers `1, x, x², ...` of an element `x` of a monoid `M` are a submonoid. -/ def powers (x : M) : submonoid M := { carrier := {y | ∃ n:ℕ, x^n = y}, one_mem' := ⟨0, pow_zero x⟩, mul_mem' := by rintros x₁ x₂ ⟨n₁, rfl⟩ ⟨n₂, rfl⟩; exact ⟨n₁ + n₂, pow_add _ _ _ ⟩ } /-- An element `x` of a monoid is in the submonoid generated by `x`. -/ lemma powers.self_mem {x : M} : x ∈ powers x := ⟨1, pow_one _⟩ /-- If `a` is in a submonoid, so are all its natural number powers. -/ lemma pow_mem {a : M} (h : a ∈ S) : ∀ {n : ℕ}, a ^ n ∈ S | 0 := S.one_mem | (n + 1) := S.mul_mem h pow_mem lemma powers_subset {a : M} (h : a ∈ S) : powers a ≤ S := assume x ⟨n, hx⟩, hx ▸ S.pow_mem h @[simp] lemma coe_pow (a : S) (n : ℕ) : ((a ^ n : S) : M) = a ^ n := by induction n; simp [*, pow_succ] end submonoid namespace add_submonoid variables (S : add_submonoid A) /-- The multiples `0, x, 2x, ...` of an element `x` of an `add_monoid M` are an `add_submonoid`. -/ def multiples (x : A) : add_submonoid A := { carrier := {y | ∃ n:ℕ, add_monoid.smul n x = y}, zero_mem' := ⟨0, add_monoid.zero_smul x⟩, add_mem' := by rintros x₁ x₂ ⟨n₁, rfl⟩ ⟨n₂, rfl⟩; exact ⟨n₁ + n₂, add_monoid.add_smul _ _ _ ⟩ } /-- An element `x` of an `add_monoid` is in the `add_submonoid` generated by `x`. -/ lemma multiples.self_mem {x : A} : x ∈ multiples x := ⟨1, add_monoid.one_smul x⟩ lemma smul_mem {a : A} (h : a ∈ S) {n : ℕ} : add_monoid.smul n a ∈ S := submonoid.pow_mem (add_submonoid.to_submonoid S) h lemma multiples_subset {a : A} (h : a ∈ S) : multiples a ≤ S := submonoid.powers_subset (add_submonoid.to_submonoid S) h @[simp] lemma coe_smul (a : S) (n : ℕ) : ((add_monoid.smul n a : S) : A) = add_monoid.smul n a := submonoid.coe_pow (add_submonoid.to_submonoid S) a n end add_submonoid namespace submonoid variables (S : submonoid M) /-- The submonoid `M` of the monoid `M`. -/ @[to_additive "The `add_submonoid M` of the `add_monoid M`."] def univ : submonoid M := { carrier := set.univ, one_mem' := set.mem_univ 1, mul_mem' := λ _ _ _ _, set.mem_univ _ } /-- The trivial submonoid `{1}` of an monoid `M`. -/ @[to_additive "The trivial `add_submonoid` `{0}` of an `add_monoid` `M`."] def bot : submonoid M := { carrier := {1}, one_mem' := set.mem_singleton 1, mul_mem' := λ a b ha hb, by simp * at *} /-- Submonoids of a monoid are partially ordered (by inclusion). -/ @[to_additive "The `add_submonoid`s of an `add_monoid` are partially ordered (by inclusion)."] instance : partial_order (submonoid M) := partial_order.lift (coe : submonoid M → set M) (λ a b, ext') (by apply_instance) @[to_additive] lemma le_def (p p' : submonoid M) : p ≤ p' ↔ ∀ x ∈ p, x ∈ p' := iff.rfl @[to_additive] instance : has_bot (submonoid M) := ⟨submonoid.bot⟩ @[to_additive] instance : inhabited (submonoid M) := ⟨⊥⟩ @[simp, to_additive] lemma mem_bot {x : M} : x ∈ (⊥ : submonoid M) ↔ x = 1 := set.mem_singleton_iff @[to_additive] instance : order_bot (submonoid M) := { bot := ⊥, bot_le := λ P x hx, by simp * at *; exact P.one_mem, ..submonoid.partial_order } @[to_additive] instance : has_top (submonoid M) := ⟨univ⟩ @[simp, to_additive] lemma mem_top (x : M) : x ∈ (⊤ : submonoid M) := set.mem_univ x @[to_additive] instance : order_top (submonoid M) := { top := ⊤, le_top := λ p x _, mem_top x, ..submonoid.partial_order} /-- The inf of two submonoids is their intersection. -/ @[to_additive "The inf of two `add_submonoid`s is their intersection."] def inf (S₁ S₂ : submonoid M) : submonoid M := { carrier := S₁ ∩ S₂, one_mem' := ⟨S₁.one_mem, S₂.one_mem⟩, mul_mem' := λ _ _ ⟨hx, hx'⟩ ⟨hy, hy'⟩, ⟨S₁.mul_mem hx hy, S₂.mul_mem hx' hy'⟩ } @[to_additive] instance : has_inf (submonoid M) := ⟨inf⟩ @[to_additive] lemma mem_inf {p p' : submonoid M} {x : M} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := ⟨λ h, ⟨h.1, h.2⟩, λ h, (p ⊓ p').mem_coe.2 ⟨h.1, h.2⟩⟩ @[to_additive] instance : has_Inf (submonoid M) := ⟨λ s, { carrier := ⋂ t ∈ s, ↑t, one_mem' := set.mem_bInter $ λ i h, i.one_mem, mul_mem' := λ x y hx hy, set.mem_bInter $ λ i h, i.mul_mem (by apply set.mem_bInter_iff.1 hx i h) (by apply set.mem_bInter_iff.1 hy i h) }⟩ @[to_additive] lemma Inf_le' {S : set (submonoid M)} {p} : p ∈ S → Inf S ≤ p := set.bInter_subset_of_mem @[to_additive] lemma le_Inf' {S : set (submonoid M)} {p} : (∀p' ∈ S, p ≤ p') → p ≤ Inf S := set.subset_bInter @[to_additive] lemma mem_Inf {S : set (submonoid M)} {x : M} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff /-- Submonoids of a monoid form a lattice. -/ @[to_additive "The `add_submonoid`s of an `add_monoid` form a lattice."] instance : lattice (submonoid M) := { sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x}, le_sup_left := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, ha, le_sup_right := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, hb, sup_le := λ a b c h₁ h₂, Inf_le' ⟨h₁, h₂⟩, inf := (⊓), le_inf := λ a b c ha hb, set.subset_inter ha hb, inf_le_left := λ a b, set.inter_subset_left _ _, inf_le_right := λ a b, set.inter_subset_right _ _, ..submonoid.partial_order} /-- Submonoids of a monoid form a complete lattice. -/ @[to_additive "The `add_submonoid`s of an `add_monoid` form a complete lattice."] instance : complete_lattice (submonoid M) := { Sup := λ tt, Inf {t | ∀t'∈tt, t' ≤ t}, le_Sup := λ s p hs, le_Inf' $ λ p' hp', hp' _ hs, Sup_le := λ s p hs, Inf_le' hs, Inf := Inf, le_Inf := λ s a, le_Inf', Inf_le := λ s a, Inf_le', ..submonoid.order_top, ..submonoid.order_bot, ..submonoid.lattice} /-- Submonoids of a monoid form an `add_comm_monoid`. -/ @[to_additive "The `add_submonoid`s of an `add_monoid` form an `add_comm_monoid`."] instance complete_lattice.add_comm_monoid : add_comm_monoid (submonoid M) := { add := (⊔), add_assoc := λ _ _ _, sup_assoc, zero := ⊥, zero_add := λ _, bot_sup_eq, add_zero := λ _, sup_bot_eq, add_comm := λ _ _, sup_comm } end submonoid namespace monoid_hom variables (S : submonoid M) open submonoid /-- The preimage of a submonoid along a monoid homomorphism is a submonoid. -/ @[to_additive "The preimage of an `add_submonoid` along an `add_monoid` homomorphism is an `add_submonoid`."] def comap {N : Type*} [monoid N] (f : M →* N) (S : submonoid N) : submonoid M := { carrier := (f ⁻¹' S), one_mem' := show f 1 ∈ S, by rw f.map_one; exact S.one_mem, mul_mem' := λ a b ha hb, show f (a * b) ∈ S, by rw f.map_mul; exact S.mul_mem ha hb } /-- The image of a submonoid along a monoid homomorphism is a submonoid. -/ @[to_additive "The image of an `add_submonoid` along an `add_monoid` homomorphism is an `add_submonoid`."] def map {N : Type*} [monoid N] (f : M →* N) (S : submonoid M) : submonoid N := { carrier := (f '' S), one_mem' := ⟨1, S.one_mem, f.map_one⟩, mul_mem' := begin rintros _ _ ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩, exact ⟨x * y, S.mul_mem hx hy, by rw f.map_mul; refl⟩ end } /-- The range of a monoid homomorphism is a submonoid. -/ @[to_additive "The range of an `add_monoid_hom` is an `add_submonoid`."] def range {N : Type*} [monoid N] (f : M →* N) : submonoid N := map f univ end monoid_hom namespace submonoid variables (S : submonoid M) /-- 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}, (∀x∈l, x ∈ S) → l.prod ∈ S | [] h := S.one_mem | (a::l) h := suffices a * l.prod ∈ S, by simpa, have a ∈ S ∧ (∀ x ∈ l, x ∈ S), by simpa using h, S.mul_mem this.1 (list_prod_mem this.2) /-- 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) : (∀a ∈ m, a ∈ S) → m.prod ∈ S := begin refine quotient.induction_on m (assume l hl, _), rw [multiset.quot_mk_to_coe, multiset.coe_prod], exact S.list_prod_mem hl end /-- 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 finset_prod_mem {M ι} [comm_monoid M] (S : submonoid M) (f : ι → M) : ∀(t : finset ι), (∀b∈t, f b ∈ S) → t.prod f ∈ S | ⟨m, hm⟩ hs := begin refine S.multiset_prod_mem _ _, suffices : ∀ (a : M) (x : ι), x ∈ m → f x = a → a ∈ S, simpa using this, rintros a b hb rfl, exact hs _ hb end end submonoid namespace monoid_hom variables (S : submonoid M) /-- Restriction of a monoid hom to a submonoid of the domain. -/ @[to_additive "Restriction of an add_monoid hom to an `add_submonoid` of the domain."] def restrict {N : Type*} [monoid N] (f : M →* N) : S →* N := ⟨λ s, f s, f.map_one, λ x y, f.map_mul x y⟩ /-- Restriction of a monoid hom to a submonoid of the codomain. -/ @[to_additive "Restriction of an `add_monoid` hom to an `add_submonoid` of the codomain."] def subtype_mk {N : Type*} [monoid N] (f : N →* M) (h : ∀ x, f x ∈ S) : N →* S := { to_fun := λ n, ⟨f n, h n⟩, map_one' := subtype.eq f.map_one, map_mul' := λ x y, subtype.eq (f.map_mul x y) } /-- Restriction of a monoid hom to its range. -/ @[to_additive "Restriction of an `add_monoid` hom to its range."] def range_mk {N} [monoid N] (f : M →* N) : M →* f.range := subtype_mk f.range f $ λ x, ⟨x, submonoid.mem_top x, rfl⟩ /-- The range of a surjective monoid hom is the whole of the codomain. -/ @[to_additive "The range of a surjective `add_monoid` hom is the whole of the codomain."] lemma range_top_of_surjective {N} [monoid N] (f : M →* N) (hf : function.surjective f) : f.range = (⊤ : submonoid N) := submonoid.ext'_iff.1 $ (set.ext_iff _ _).2 $ λ x, ⟨λ h, submonoid.mem_top x, λ h, exists.elim (hf x) $ λ w hw, ⟨w, submonoid.mem_top w, hw⟩⟩ /-- The monoid hom associated to an inclusion of submonoids. -/ @[to_additive "The `add_monoid` hom associated to an inclusion of submonoids."] def set_inclusion (T : submonoid M) (h : S ≤ T) : S →* T := subtype_mk _ S.subtype (λ x, h x.2) end monoid_hom namespace monoid variables (S : submonoid M) open submonoid /-- The inductively defined submonoid generated by a set. -/ @[to_additive "The inductively defined `add_submonoid` generated by a set. "] def closure' (s : set M) : submonoid M := { carrier := in_closure s, one_mem' := in_closure.one s, mul_mem' := λ _ _, in_closure.mul} /-- The submonoid generated by a set contains the set. -/ @[to_additive "The `add_submonoid` generated by a set contains the set."] theorem le_closure' {s : set M} : s ≤ closure' s := λ a, in_closure.basic /-- The submonoid generated by a set is contained in any submonoid that contains the set. -/ @[to_additive "The `add_submonoid` generated by a set is contained in any `add_submonoid` that contains the set."] theorem closure'_le {s : set M} {T : submonoid M} (h : s ≤ T) : closure' s ≤ T := λ a ha, begin induction ha with _ hb _ _ _ _ ha hb, {exact h hb }, {exact T.one_mem }, {exact T.mul_mem ha hb } end /-- Given subsets `t` and `s` of a monoid `M`, if `s ⊆ t`, the submonoid of `M` generated by `s` is contained in the submonoid generated by `t`. -/ @[to_additive "Given subsets `t` and `s` of an `add_monoid` `M`, if `s ⊆ t`, the `add_submonoid` of `M` generated by `s` is contained in the `add_submonoid` generated by `t`."] theorem closure'_mono {s t : set M} (h : s ≤ t) : closure' s ≤ closure' t := closure'_le $ set.subset.trans h le_closure' /-- The submonoid generated by an element of a monoid equals the set of natural number powers of the element. -/ theorem closure'_singleton {x : M} : closure' ({x} : set M) = powers x := ext' $ set.eq_of_subset_of_subset (closure'_le $ set.singleton_subset_iff.2 powers.self_mem) $ submonoid.powers_subset _ $ in_closure.basic $ set.mem_singleton x /-- The image under a monoid hom of the submonoid generated by a set equals the submonoid generated by the image of the set. -/ @[to_additive "The image under an `add_monoid` hom of the `add_submonoid` generated by a set equals the `add_submonoid` generated by the image of the set."] lemma image_closure' {N : Type*} [monoid N] (f : M →* N) (s : set M) : f.map (closure' s) = closure' (f '' s) := le_antisymm begin rintros _ ⟨x, hx, rfl⟩, apply in_closure.rec_on hx; intros, { solve_by_elim [le_closure', set.mem_image_of_mem] }, { rw f.map_one, apply submonoid.one_mem }, { rw f.map_mul, solve_by_elim [submonoid.mul_mem] } end (closure'_le $ set.image_subset _ le_closure') /-- Given an element `a` of the submonoid of a monoid `M` generated by a set `s`, there exists a list of elements of `s` whose product is `a`. -/ @[to_additive "Given an element `a` of the `add_submonoid` of an `add_monoid` `M` generated by a set `s`, there exists a list of elements of `s` whose sum is `a`."] theorem exists_list_of_mem_closure' {s : set M} {a : M} (h : a ∈ closure' s) : (∃l:list M, (∀x∈l, x ∈ s) ∧ l.prod = a) := begin induction h, case in_closure.basic : a ha { existsi ([a]), simp [ha] }, case in_closure.one { existsi ([]), simp }, case in_closure.mul : a b _ _ ha hb { rcases ha with ⟨la, ha, eqa⟩, rcases hb with ⟨lb, hb, eqb⟩, existsi (la ++ lb), simp [eqa.symm, eqb.symm, or_imp_distrib], exact assume a, ⟨ha a, hb a⟩ } end /-- Given sets `s, t` of a commutative monoid `M`, `x ∈ M` is in the submonoid of `M` generated by `s ∪ t` iff there exists an element of the submonoid generated by `s` and an element of the submonoid generated by `t` whose product is `x`. -/ @[to_additive "Given sets `s, t` of a commutative `add_monoid` `M`, `x ∈ M` is in the `add_submonoid` of `M` generated by `s ∪ t` iff there exists an element of the `add_submonoid` generated by `s` and an element of the `add_submonoid` generated by `t` whose sum is `x`."] theorem mem_closure'_union_iff {M : Type*} [comm_monoid M] {s t : set M} {x : M} : x ∈ closure' (s ∪ t) ↔ ∃ y ∈ closure' s, ∃ z ∈ closure' t, y * z = x := ⟨λ hx, let ⟨L, HL1, HL2⟩ := exists_list_of_mem_closure' hx in HL2 ▸ list.rec_on L (λ _, ⟨1, submonoid.one_mem _, 1, submonoid.one_mem _, mul_one _⟩) (λ hd tl ih HL1, let ⟨y, hy, z, hz, hyzx⟩ := ih (list.forall_mem_of_forall_mem_cons HL1) in or.cases_on (HL1 hd $ list.mem_cons_self _ _) (λ hs, ⟨hd * y, submonoid.mul_mem _ (le_closure' hs) hy, z, hz, by rw [mul_assoc, list.prod_cons, ← hyzx]; refl⟩) (λ ht, ⟨y, hy, z * hd, submonoid.mul_mem _ hz (le_closure' ht), by rw [← mul_assoc, list.prod_cons, ← hyzx, mul_comm hd]; refl⟩)) HL1, λ ⟨y, hy, z, hz, hyzx⟩, hyzx ▸ submonoid.mul_mem _ ((closure_mono (set.subset_union_left s t)) hy) ((closure_mono (set.subset_union_right s t)) hz)⟩ end monoid namespace add_monoid open add_submonoid /-- The `add_submonoid` generated by an element of an `add_monoid` equals the set of natural number multiples of the element. -/ theorem closure'_singleton {x : A} : closure' ({x} : set A) = multiples x := ext' $ set.eq_of_subset_of_subset (closure'_le $ set.singleton_subset_iff.2 multiples.self_mem) $ multiples_subset _ $ in_closure.basic $ set.mem_singleton x end add_monoid namespace mul_equiv variables {S T : submonoid M} /-- Makes the identity isomorphism from a proof two submonoids of a multiplicative monoid are equal. -/ @[to_additive add_submonoid_congr "Makes the identity additive isomorphism from a proof two submonoids of an additive monoid are equal."] def submonoid_congr (h : S = T) : S ≃* T := { map_mul' := λ _ _, rfl, ..equiv.set_congr $ submonoid.ext'_iff.2 h } end mul_equiv
136e8b17bd0411be47d69e353fe63a9b514efbfd
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/limits/shapes/default.lean
157e139ed7f7386497b1cf300e21239359f672c9
[ "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
575
lean
import category_theory.limits.shapes.terminal import category_theory.limits.shapes.binary_products import category_theory.limits.shapes.products import category_theory.limits.shapes.finite_products import category_theory.limits.shapes.finite_limits import category_theory.limits.shapes.biproducts import category_theory.limits.shapes.images import category_theory.limits.shapes.zero import category_theory.limits.shapes.kernels import category_theory.limits.shapes.equalizers import category_theory.limits.shapes.wide_pullbacks import category_theory.limits.shapes.pullbacks
3ae5afdc41ef3ec0b036d45075022a7b8f4a7fc6
5fbbd711f9bfc21ee168f46a4be146603ece8835
/lean/natural_number_game/advanced_multiplication/3.lean
528b8372bfffa5c197b7ac8d794847b9ea9233d4
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
goedel-gang/maths
22596f71e3fde9c088e59931f128a3b5efb73a2c
a20a6f6a8ce800427afd595c598a5ad43da1408d
refs/heads/master
1,623,055,941,960
1,621,599,441,000
1,621,599,441,000
169,335,840
0
0
null
null
null
null
UTF-8
Lean
false
false
206
lean
theorem mul_eq_zero_iff (a b : mynat): a * b = 0 ↔ a = 0 ∨ b = 0 := begin split, exact eq_zero_or_eq_zero_of_mul_eq_zero a b, intro h, cases h with ha hb, rw ha, simp, rw hb, simp, end
854664e5f9133dd895c575152a1604a388b864dc
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/stage0/src/Init/Notation.lean
5112f5ce1c044e6dcf45add50e7edc92da05f82b
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,455
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 Notation for operators defined at Prelude.lean -/ prelude import Init.Prelude infixr:90 " ∘ " => Function.comp infixr:35 " × " => Prod infixl:65 " + " => Add.add infixl:65 " - " => Sub.sub infixl:70 " * " => Mul.mul infixl:70 " / " => Div.div infixl:70 " % " => Mod.mod infixl:70 " %ₙ " => ModN.modn infixr:80 " ^ " => Pow.pow infix:50 " ≤ " => HasLessEq.LessEq infix:50 " <= " => HasLessEq.LessEq infix:50 " < " => HasLess.Less infix:50 " ≥ " => GreaterEq infix:50 " >= " => GreaterEq infix:50 " > " => Greater infix:50 " = " => Eq infix:50 " == " => BEq.beq infix:50 " ~= " => HEq infix:50 " ≅ " => HEq infixr:35 " ∧ " => And infixr:35 " /\\ " => And infixr:30 " ∨ " => Or infixr:30 " \\/ " => Or infixl:35 " && " => and infixl:30 " || " => or infixl:65 " ++ " => Append.append infixr:67 " :: " => List.cons infixr:2 " <|> " => OrElse.orElse infixr:60 " >> " => AndThen.andThen infixl:55 " >>= " => Bind.bind infixl:60 " <*> " => Seq.seq infixl:60 " <* " => SeqLeft.seqLeft infixr:60 " *> " => SeqRight.seqRight infixr:100 " <$> " => Functor.map macro "if" h:ident ":" c:term " then " t:term " else " e:term : term => `(dite $c (fun $h => $t) (fun $h => $e)) macro "if" c:term " then " t:term " else " e:term : term => `(ite $c $t $e)
228d023600f842dc648da88704ca0b6ddf85d469
618003631150032a5676f229d13a079ac875ff77
/src/algebra/group_ring_action.lean
86ad4b4bcf8f7053e5a7b5ec859c87263405b28f
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
4,658
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Group action on rings. -/ import group_theory.group_action import data.equiv.ring import data.polynomial universes u v variables (M G : Type u) [monoid M] [group G] variables (A R S F : Type v) [add_monoid A] [semiring R] [comm_semiring S] [field F] section prio set_option default_priority 100 -- see Note [default priority] /-- Typeclass for multiplicative actions by monoids on semirings. -/ class mul_semiring_action extends distrib_mul_action M R := (smul_one : ∀ (g : M), (g • 1 : R) = 1) (smul_mul : ∀ (g : M) (x y : R), g • (x * y) = (g • x) * (g • y)) end prio export mul_semiring_action (smul_one) variables {M R} lemma smul_mul' [mul_semiring_action M R] (g : M) (x y : R) : g • (x * y) = (g • x) * (g • y) := mul_semiring_action.smul_mul g x y variables (M R) /-- Each element of the monoid defines a additive monoid homomorphism. -/ def distrib_mul_action.to_add_monoid_hom [distrib_mul_action M A] (x : M) : A →+ A := { to_fun := (•) x, map_zero' := smul_zero x, map_add' := smul_add x } /-- Each element of the group defines an additive monoid isomorphism. -/ def distrib_mul_action.to_add_equiv [distrib_mul_action G A] (x : G) : A ≃+ A := { .. distrib_mul_action.to_add_monoid_hom G A x, .. mul_action.to_perm G A x } /-- The monoid of endomorphisms. -/ def monoid.End := M →* M instance monoid.End.monoid : monoid (monoid.End M) := { mul := monoid_hom.comp, one := monoid_hom.id M, mul_assoc := λ _ _ _, monoid_hom.comp_assoc _ _ _, mul_one := monoid_hom.comp_id, one_mul := monoid_hom.id_comp } instance monoid.End.inhabited : inhabited (monoid.End M) := ⟨1⟩ /-- The monoid of endomorphisms. -/ def add_monoid.End := A →+ A instance add_monoid.End.monoid : monoid (add_monoid.End A) := { mul := add_monoid_hom.comp, one := add_monoid_hom.id A, mul_assoc := λ _ _ _, add_monoid_hom.comp_assoc _ _ _, mul_one := add_monoid_hom.comp_id, one_mul := add_monoid_hom.id_comp } instance add_monoid.End.inhabited : inhabited (add_monoid.End A) := ⟨1⟩ /-- Each element of the group defines an additive monoid homomorphism. -/ def distrib_mul_action.hom_add_monoid_hom [distrib_mul_action M A] : M →* add_monoid.End A := { to_fun := distrib_mul_action.to_add_monoid_hom M A, map_one' := add_monoid_hom.ext $ λ x, one_smul M x, map_mul' := λ x y, add_monoid_hom.ext $ λ z, mul_smul x y z } /-- Each element of the monoid defines a semiring homomorphism. -/ def mul_semiring_action.to_semiring_hom [mul_semiring_action M R] (x : M) : R →+* R := { map_one' := smul_one x, map_mul' := smul_mul' x, .. distrib_mul_action.to_add_monoid_hom M R x } /-- Each element of the group defines a semiring isomorphism. -/ def mul_semiring_action.to_semiring_equiv [mul_semiring_action G R] (x : G) : R ≃+* R := { .. distrib_mul_action.to_add_equiv G R x, .. mul_semiring_action.to_semiring_hom G R x } section simp_lemmas variables {M G A R} attribute [simp] smul_one smul_mul' smul_zero smul_add @[simp] lemma smul_inv [mul_semiring_action M F] (x : M) (m : F) : x • m⁻¹ = (x • m)⁻¹ := (mul_semiring_action.to_semiring_hom M F x).map_inv @[simp] lemma smul_pow [mul_semiring_action M R] (x : M) (m : R) (n : ℕ) : x • m ^ n = (x • m) ^ n := nat.rec_on n (smul_one x) $ λ n ih, (smul_mul' x m (m ^ n)).trans $ congr_arg _ ih end simp_lemmas variables [mul_semiring_action M S] noncomputable instance : mul_semiring_action M (polynomial S) := { smul := λ m, polynomial.map $ mul_semiring_action.to_semiring_hom M S m, one_smul := λ p, by { ext n, erw polynomial.coeff_map, exact one_smul M (p.coeff n) }, mul_smul := λ m n p, by { ext i, iterate 3 { rw polynomial.coeff_map (mul_semiring_action.to_semiring_hom M S _) }, exact mul_smul m n (p.coeff i) }, smul_add := λ m p q, polynomial.map_add (mul_semiring_action.to_semiring_hom M S m), smul_zero := λ m, polynomial.map_zero (mul_semiring_action.to_semiring_hom M S m), smul_one := λ m, polynomial.map_one (mul_semiring_action.to_semiring_hom M S m), smul_mul := λ m p q, polynomial.map_mul (mul_semiring_action.to_semiring_hom M S m), } @[simp] lemma polynomial.coeff_smul' (m : M) (p : polynomial S) (n : ℕ) : (m • p).coeff n = m • p.coeff n := polynomial.coeff_map _ _ @[simp] lemma polynomial.smul_C (m : M) (r : S) : m • polynomial.C r = polynomial.C (m • r) := polynomial.map_C _ @[simp] lemma polynomial.smul_X (m : M) : (m • polynomial.X : polynomial S) = polynomial.X := polynomial.map_X _
e8ad55436bee5692700ac9a51967e9ecd404af90
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/computability/encoding.lean
bd2004d8da9e58a478eefc6a871308abd1b54b8f
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
6,115
lean
/- Copyright (c) 2020 Pim Spelier, Daan van Gent. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Pim Spelier, Daan van Gent -/ import data.fintype.basic import data.num.lemmas import tactic.derive_fintype /-! # Encodings This file contains the definition of a (finite) encoding, a map from a type to strings in an alphabet, used in defining computability by Turing machines. It also contains several examples: ## Examples - `fin_encoding_nat_bool` : a binary encoding of ℕ in a simple alphabet. - `fin_encoding_nat_Γ'` : a binary encoding of ℕ in the alphabet used for TM's. - `unary_fin_encoding_nat` : a unary encoding of ℕ - `fin_encoding_bool_bool` : an encoding of bool. -/ namespace computability /-- An encoding of a type in a certain alphabet, together with a decoding. -/ structure encoding (α : Type) := (Γ : Type) (encode : α → list Γ) (decode : list Γ → option α) (decode_encode : ∀ x, decode (encode x) = some x) /-- An encoding plus a guarantee of finiteness of the alphabet. -/ structure fin_encoding (α : Type) extends encoding α := (Γ_fin : fintype Γ) /-- A standard Turing machine alphabet, consisting of blank,bit0,bit1,bra,ket,comma. -/ @[derive [decidable_eq,fintype]] inductive Γ' | blank | bit (b : bool) | bra | ket | comma instance inhabited_Γ' : inhabited Γ' := ⟨Γ'.blank⟩ /-- The natural inclusion of bool in Γ'. -/ def inclusion_bool_Γ' : bool → Γ' := Γ'.bit /-- An arbitrary section of the natural inclusion of bool in Γ'. -/ def section_Γ'_bool : Γ' → bool | (Γ'.bit b) := b | _ := arbitrary bool lemma left_inverse_section_inclusion : function.left_inverse section_Γ'_bool inclusion_bool_Γ' := λ x, bool.cases_on x rfl rfl lemma inclusion_bool_Γ'_injective : function.injective inclusion_bool_Γ' := function.has_left_inverse.injective (Exists.intro section_Γ'_bool left_inverse_section_inclusion) /-- An encoding function of the positive binary numbers in bool. -/ def encode_pos_num : pos_num → list bool | pos_num.one := [tt] | (pos_num.bit0 n) := ff :: encode_pos_num n | (pos_num.bit1 n) := tt :: encode_pos_num n /-- An encoding function of the binary numbers in bool. -/ def encode_num : num → list bool | num.zero := [] | (num.pos n) := encode_pos_num n /-- An encoding function of ℕ in bool. -/ def encode_nat (n : ℕ) : list bool := encode_num n /-- A decoding function from `list bool` to the positive binary numbers. -/ def decode_pos_num : list bool → pos_num | (ff :: l) := (pos_num.bit0 (decode_pos_num l)) | (tt :: l) := ite (l = []) pos_num.one (pos_num.bit1 (decode_pos_num l)) | _ := pos_num.one /-- A decoding function from `list bool` to the binary numbers. -/ def decode_num : list bool → num := λ l, ite (l = []) num.zero $ decode_pos_num l /-- A decoding function from `list bool` to ℕ. -/ def decode_nat : list bool → nat := λ l, decode_num l lemma encode_pos_num_nonempty (n : pos_num) : (encode_pos_num n) ≠ [] := pos_num.cases_on n (list.cons_ne_nil _ _) (λ m, list.cons_ne_nil _ _) (λ m, list.cons_ne_nil _ _) lemma decode_encode_pos_num : ∀ n, decode_pos_num(encode_pos_num n) = n := begin intros n, induction n with m hm m hm; unfold encode_pos_num decode_pos_num, { refl }, { rw hm, exact if_neg (encode_pos_num_nonempty m) }, { exact congr_arg pos_num.bit0 hm } end lemma decode_encode_num : ∀ n, decode_num(encode_num n) = n := begin intros n, cases n; unfold encode_num decode_num, { refl }, rw decode_encode_pos_num n, rw pos_num.cast_to_num, exact if_neg (encode_pos_num_nonempty n), end lemma decode_encode_nat : ∀ n, decode_nat(encode_nat n) = n := begin intro n, conv_rhs {rw ← num.to_of_nat n}, exact congr_arg coe (decode_encode_num ↑n), end /-- A binary encoding of ℕ in bool. -/ def encoding_nat_bool : encoding ℕ := { Γ := bool, encode := encode_nat, decode := λ n, some (decode_nat n), decode_encode := λ n, congr_arg _ (decode_encode_nat n) } /-- A binary fin_encoding of ℕ in bool. -/ def fin_encoding_nat_bool : fin_encoding ℕ := ⟨encoding_nat_bool, bool.fintype⟩ /-- A binary encoding of ℕ in Γ'. -/ def encoding_nat_Γ' : encoding ℕ := { Γ := Γ', encode := λ x, list.map inclusion_bool_Γ' (encode_nat x), decode := λ x, some (decode_nat (list.map section_Γ'_bool x)), decode_encode := λ x, congr_arg _ $ by rw [list.map_map, list.map_id' left_inverse_section_inclusion, decode_encode_nat] } /-- A binary fin_encoding of ℕ in Γ'. -/ def fin_encoding_nat_Γ' : fin_encoding ℕ := ⟨encoding_nat_Γ', Γ'.fintype⟩ /-- A unary encoding function of ℕ in bool. -/ def unary_encode_nat : nat → list bool | 0 := [] | (n+1) := tt :: (unary_encode_nat n) /-- A unary decoding function from `list bool` to ℕ. -/ def unary_decode_nat : list bool → nat := list.length lemma unary_decode_encode_nat : ∀ n, unary_decode_nat (unary_encode_nat n) = n := λ n, nat.rec rfl (λ (m : ℕ) hm, (congr_arg nat.succ hm.symm).symm) n /-- A unary fin_encoding of ℕ. -/ def unary_fin_encoding_nat : fin_encoding ℕ := { Γ := bool, encode := unary_encode_nat, decode := λ n, some (unary_decode_nat n), decode_encode := λ n, congr_arg _ (unary_decode_encode_nat n), Γ_fin := bool.fintype} /-- An encoding function of bool in bool. -/ def encode_bool : bool → list bool := list.ret /-- A decoding function from `list bool` to bool. -/ def decode_bool : list bool → bool | (b :: _) := b | _ := arbitrary bool lemma decode_encode_bool : ∀ b, decode_bool(encode_bool b) = b := λ b, bool.cases_on b rfl rfl /-- A fin_encoding of bool in bool. -/ def fin_encoding_bool_bool : fin_encoding bool := { Γ := bool, encode := encode_bool, decode := λ x, some (decode_bool x), decode_encode := λ x, congr_arg _ (decode_encode_bool x), Γ_fin := bool.fintype } instance inhabited_fin_encoding : inhabited (fin_encoding bool) := ⟨fin_encoding_bool_bool⟩ instance inhabited_encoding : inhabited (encoding bool) := ⟨fin_encoding_bool_bool.to_encoding⟩ end computability
5c6b17b2b48d8fdb86cd4db797bc4de432790a2a
6214e13b31733dc9aeb4833db6a6466005763162
/src/bindings.lean
11cfc6b258f7031b6bfb5709c12d8b2c094ccb4e
[]
no_license
joshua0pang/esverify-theory
272a250445f3aeea49a7e72d1ab58c2da6618bbe
8565b123c87b0113f83553d7732cd6696c9b5807
refs/heads/master
1,585,873,849,081
1,527,304,393,000
1,527,304,393,000
154,901,199
1
0
null
1,540,593,067,000
1,540,593,067,000
null
UTF-8
Lean
false
false
50,839
lean
-- auxiliary lemmas about translation of environments/variable bindings import .definitions3 .substitution lemma free_of_contains {P: prop} {σ: env} {x: var}: (⊩ σ : P) → x ∈ σ → x ∈ FV P := assume env_verified: ⊩ σ : P, assume x_contained: x ∈ σ, show x ∈ FV P, by begin induction env_verified, case env.dvcgen.empty { cases x_contained }, case env.dvcgen.tru σ' y Q _ _ ih { from or.elim (env.contains.inv x_contained) ( assume : x = y, have free_in_term x y, from this ▸ free_in_term.var x, have free_in_term x (y ≡ value.true), from free_in_term.binop₁ this, have free_in_prop x (y ≡ value.true), from free_in_prop.term this, show x ∈ FV (Q ⋀ y ≡ value.true), from free_in_prop.and₂ this ) ( assume : x ∈ σ', have x ∈ FV Q, from ih this, show x ∈ FV (Q ⋀ y ≡ value.true), from free_in_prop.and₁ this ) }, case env.dvcgen.fls σ' y Q _ _ ih { from or.elim (env.contains.inv x_contained) ( assume : x = y, have free_in_term x y, from this ▸ free_in_term.var x, have free_in_term x (y ≡ value.false), from free_in_term.binop₁ this, have free_in_prop x (y ≡ value.false), from free_in_prop.term this, show x ∈ FV (Q ⋀ y ≡ value.false), from free_in_prop.and₂ this ) ( assume : x ∈ σ', have x ∈ FV Q, from ih this, show x ∈ FV (Q ⋀ y ≡ value.false), from free_in_prop.and₁ this ) }, case env.dvcgen.num n σ' y Q _ _ ih { from or.elim (env.contains.inv x_contained) ( assume : x = y, have free_in_term x y, from this ▸ free_in_term.var x, have free_in_term x (y ≡ value.num n), from free_in_term.binop₁ this, have free_in_prop x (y ≡ value.num n), from free_in_prop.term this, show x ∈ FV (Q ⋀ y ≡ value.num n), from free_in_prop.and₂ this ) ( assume : x ∈ σ', have x ∈ FV Q, from ih this, show x ∈ FV (Q ⋀ y ≡ value.num n), from free_in_prop.and₁ this ) }, case env.dvcgen.func f σ₂ σ₁ g gx R S e Q₁ Q₂ Q₃ _ _ _ _ _ _ _ fv_R fv_S e_verified _ ih₁ ih₂ { from or.elim (env.contains.inv x_contained) ( assume : x = f, have free_in_term x f, from this ▸ free_in_term.var x, have free_in_term x (f ≡ value.func g gx R S e σ₂), from free_in_term.binop₁ this, have free_in_prop x (f ≡ value.func g gx R S e σ₂), from free_in_prop.term this, have x ∈ FV (prop.term (f ≡ value.func g gx R S e σ₂) ⋀ prop.subst_env (σ₂[g↦value.func g gx R S e σ₂]) (prop.func g gx R (Q₃ (term.app g gx) ⋀ S))), from free_in_prop.and₁ this, show x ∈ FV (Q₁ ⋀ f ≡ value.func g gx R S e σ₂ ⋀ prop.subst_env (σ₂[g↦value.func g gx R S e σ₂]) (prop.func g gx R (Q₃ (term.app g gx) ⋀ S))), from free_in_prop.and₂ this ) ( assume : x ∈ σ₁, have x ∈ FV Q₁, from ih₁ this, show x ∈ FV (Q₁ ⋀ f ≡ value.func g gx R S e σ₂ ⋀ prop.subst_env (σ₂[g↦value.func g gx R S e σ₂]) (prop.func g gx R (Q₃ (term.app g gx) ⋀ S))), from free_in_prop.and₁ this ) } end lemma exp.post_free {P: prop} {e: exp} {Q: propctx} {x: var}: (P ⊩ e : Q) → ∀t, x ∈ FV (Q t) → x ∈ FV t ∨ x ∈ FV P := assume e_verified: P ⊩ e : Q, begin induction e_verified, case exp.dvcgen.tru P y e' Q y_not_in_P e'_verified ih { from assume t: term, assume x_free_in_Qt: x ∈ FV ((propctx.exis y ((y ≡ value.true) ⋀ Q)) t), have x_neq_y: x ≠ y, from (free_in_propctx.exis.inv x_free_in_Qt).left, have x_not_in_yv: x ∉ FV (y ≡ value.true), from ( assume : x ∈ FV (y ≡ value.true), have free_in_term x y ∨ free_in_term x value.true, from free_in_term.binop.inv this, or.elim this ( assume : free_in_term x y, have x = y, from free_in_term.var.inv this, show «false», from x_neq_y this ) ( assume : free_in_term x value.true, show «false», from free_in_term.value.inv this ) ), have x ∈ FV ((↑(y ≡ value.true) ⋀ Q) t), from (free_in_propctx.exis.inv x_free_in_Qt).right, have x ∈ FV (propctx.term (y ≡ value.true) t) ∨ x ∈ FV (Q t), from free_in_propctx.and.inv this, or.elim this ( assume : x ∈ FV (propctx.term (y ≡ value.true) t), have x ∈ FV (((y ≡ value.true).to_termctx) t), from free_in_propctx.term.inv this, have x ∈ FV (y ≡ value.true), from free_in_termctx.term.inv this, show x ∈ FV t ∨ x ∈ FV P, from absurd this x_not_in_yv ) ( assume : x ∈ FV (Q t), have x ∈ FV t ∨ x ∈ FV (P ⋀ (y ≡ value.true)), from ih t this, or.elim this ( assume : x ∈ FV t, show x ∈ FV t ∨ x ∈ FV P, from or.inl this ) ( assume : x ∈ FV (P ⋀ (y ≡ value.true)), or.elim (free_in_prop.and.inv this) ( assume : x ∈ FV P, show x ∈ FV t ∨ x ∈ FV P, from or.inr this ) ( assume : x ∈ FV (prop.term (y ≡ value.true)), have x ∈ FV (y ≡ value.true), from free_in_prop.term.inv this, show x ∈ FV t ∨ x ∈ FV P, from absurd this x_not_in_yv ) ) ) }, case exp.dvcgen.fals P y e' Q y_not_in_P e'_verified ih { from assume t: term, assume x_free_in_Qt: x ∈ FV ((propctx.exis y ((y ≡ value.false) ⋀ Q)) t), have x_neq_y: x ≠ y, from (free_in_propctx.exis.inv x_free_in_Qt).left, have x_not_in_yv: x ∉ FV (y ≡ value.false), from ( assume : x ∈ FV (y ≡ value.false), have free_in_term x y ∨ free_in_term x value.false, from free_in_term.binop.inv this, or.elim this ( assume : free_in_term x y, have x = y, from free_in_term.var.inv this, show «false», from x_neq_y this ) ( assume : free_in_term x value.false, show «false», from free_in_term.value.inv this ) ), have x ∈ FV ((↑(y ≡ value.false) ⋀ Q) t), from (free_in_propctx.exis.inv x_free_in_Qt).right, have x ∈ FV (propctx.term (y ≡ value.false) t) ∨ x ∈ FV (Q t), from free_in_propctx.and.inv this, or.elim this ( assume : x ∈ FV (propctx.term (y ≡ value.false) t), have x ∈ FV (((y ≡ value.false).to_termctx) t), from free_in_propctx.term.inv this, have x ∈ FV (y ≡ value.false), from free_in_termctx.term.inv this, show x ∈ FV t ∨ x ∈ FV P, from absurd this x_not_in_yv ) ( assume : x ∈ FV (Q t), have x ∈ FV t ∨ x ∈ FV (P ⋀ (y ≡ value.false)), from ih t this, or.elim this ( assume : x ∈ FV t, show x ∈ FV t ∨ x ∈ FV P, from or.inl this ) ( assume : x ∈ FV (P ⋀ (y ≡ value.false)), or.elim (free_in_prop.and.inv this) ( assume : x ∈ FV P, show x ∈ FV t ∨ x ∈ FV P, from or.inr this ) ( assume : x ∈ FV (prop.term (y ≡ value.false)), have x ∈ FV (y ≡ value.false), from free_in_prop.term.inv this, show x ∈ FV t ∨ x ∈ FV P, from absurd this x_not_in_yv ) ) ) }, case exp.dvcgen.num P y n e' Q y_not_in_P e'_verified ih { from assume t: term, assume x_free_in_Qt: x ∈ FV ((propctx.exis y ((y ≡ value.num n) ⋀ Q)) t), have x_neq_y: x ≠ y, from (free_in_propctx.exis.inv x_free_in_Qt).left, have x_not_in_yv: x ∉ FV (y ≡ value.num n), from ( assume : x ∈ FV (y ≡ value.num n), have free_in_term x y ∨ free_in_term x (value.num n), from free_in_term.binop.inv this, or.elim this ( assume : free_in_term x y, have x = y, from free_in_term.var.inv this, show «false», from x_neq_y this ) ( assume : free_in_term x (value.num n), show «false», from free_in_term.value.inv this ) ), have x ∈ FV ((↑(y ≡ value.num n) ⋀ Q) t), from (free_in_propctx.exis.inv x_free_in_Qt).right, have x ∈ FV (propctx.term (y ≡ value.num n) t) ∨ x ∈ FV (Q t), from free_in_propctx.and.inv this, or.elim this ( assume : x ∈ FV (propctx.term (y ≡ value.num n) t), have x ∈ FV (((y ≡ value.num n).to_termctx) t), from free_in_propctx.term.inv this, have x ∈ FV (y ≡ value.num n), from free_in_termctx.term.inv this, show x ∈ FV t ∨ x ∈ FV P, from absurd this x_not_in_yv ) ( assume : x ∈ FV (Q t), have x ∈ FV t ∨ x ∈ FV (P ⋀ (y ≡ value.num n)), from ih t this, or.elim this ( assume : x ∈ FV t, show x ∈ FV t ∨ x ∈ FV P, from or.inl this ) ( assume : x ∈ FV (P ⋀ (y ≡ value.num n)), or.elim (free_in_prop.and.inv this) ( assume : x ∈ FV P, show x ∈ FV t ∨ x ∈ FV P, from or.inr this ) ( assume : x ∈ FV (prop.term (y ≡ value.num n)), have x ∈ FV (y ≡ value.num n), from free_in_prop.term.inv this, show x ∈ FV t ∨ x ∈ FV P, from absurd this x_not_in_yv ) ) ) }, case exp.dvcgen.func P f fx R S e₁ e₂ Q₁ Q₂ f_not_in_P _ _ _ fv_R fv_S _ _ func_vc ih₁ ih₂ { from assume t: term, assume x_free_in_Qt: x ∈ FV ((propctx.exis f ((prop.func f fx R (Q₁ (term.app f fx) ⋀ S)) ⋀ Q₂)) t), have x_neq_f: x ≠ f, from (free_in_propctx.exis.inv x_free_in_Qt).left, have x_not_in_non_rec_func: x ∈ FV (prop.func f fx R S) → x ∈ FV P, from ( assume : x ∈ FV (prop.func f fx R S), have x ∈ FV (term.var f) ∨ (x ≠ fx ∧ (x ∈ FV R.to_prop ∨ x ∈ FV S.to_prop)), from free_in_prop.func.inv this, or.elim this ( assume : x ∈ FV (term.var f), have x = f, from free_in_term.var.inv this, show x ∈ FV P, from absurd this x_neq_f ) ( assume : x ≠ fx ∧ (x ∈ FV R.to_prop ∨ x ∈ FV S.to_prop), have x_neq_fx: x ≠ fx, from this.left, or.elim this.right ( assume : x ∈ FV R.to_prop, have x ∈ FV P ∪ {f, fx}, from set.mem_of_mem_of_subset this fv_R, have x ∈ FV P ∨ x ∈ {f, fx}, from set.mem_or_mem_of_mem_union this, or.elim this id ( assume : x ∈ {f, fx}, have (x = f) ∨ (x = fx), from set.two_elems_mem this, or.elim this ( assume : x = f, show x ∈ FV P, from absurd this x_neq_f ) ( assume : x = fx, show x ∈ FV P, from absurd this x_neq_fx ) ) ) ( assume : x ∈ FV S.to_prop, have x ∈ FV P ∪ {f, fx}, from set.mem_of_mem_of_subset this fv_S, have x ∈ FV P ∨ x ∈ {f, fx}, from set.mem_or_mem_of_mem_union this, or.elim this id ( assume : x ∈ {f, fx}, have (x = f) ∨ (x = fx), from set.two_elems_mem this, or.elim this ( assume : x = f, show x ∈ FV P, from absurd this x_neq_f ) ( assume : x = fx, show x ∈ FV P, from absurd this x_neq_fx ) ) ) ) ), have x_not_in_func: x ∈ FV (prop.func f fx R (Q₁ (term.app f fx) ⋀ S)) → x ∈ FV P, from ( assume : x ∈ FV (prop.func f fx R (Q₁ (term.app f fx) ⋀ S)), have x ∈ FV (term.var f) ∨ (x ≠ fx ∧ (x ∈ FV R.to_prop ∨ x ∈ FV (Q₁ (term.app f fx) ⋀ S))), from free_in_prop.func.inv this, or.elim this ( assume : x ∈ FV (term.var f), have x = f, from free_in_term.var.inv this, show x ∈ FV P, from absurd this x_neq_f ) ( assume : x ≠ fx ∧ (x ∈ FV R.to_prop ∨ x ∈ FV (Q₁ (term.app f fx) ⋀ S)), have x_neq_fx: x ≠ fx, from this.left, have x_not_in_R: x ∈ FV R.to_prop → x ∈ FV P, from ( assume : x ∈ FV R.to_prop, have x ∈ FV P ∪ {f, fx}, from set.mem_of_mem_of_subset this fv_R, have x ∈ FV P ∨ x ∈ {f, fx}, from set.mem_or_mem_of_mem_union this, or.elim this id ( assume : x ∈ {f, fx}, have (x = f) ∨ (x = fx), from set.two_elems_mem this, or.elim this ( assume : x = f, show x ∈ FV P, from absurd this x_neq_f ) ( assume : x = fx, show x ∈ FV P, from absurd this x_neq_fx ) ) ), have x_not_in_S: x ∈ FV S.to_prop → x ∈ FV P, from ( assume : x ∈ FV S.to_prop, have x ∈ FV P ∪ {f, fx}, from set.mem_of_mem_of_subset this fv_S, have x ∈ FV P ∨ x ∈ {f, fx}, from set.mem_or_mem_of_mem_union this, or.elim this id ( assume : x ∈ {f, fx}, have (x = f) ∨ (x = fx), from set.two_elems_mem this, or.elim this ( assume : x = f, show x ∈ FV P, from absurd this x_neq_f ) ( assume : x = fx, show x ∈ FV P, from absurd this x_neq_fx ) ) ), or.elim this.right x_not_in_R ( assume : x ∈ FV (Q₁ (term.app f fx) ⋀ S), or.elim (free_in_prop.and.inv this) ( assume : x ∈ FV (Q₁ (term.app f fx)), have x ∈ FV (term.app f fx) ∨ x ∈ FV (P ⋀ (spec.func f fx R S) ⋀ R), from ih₁ (term.app f fx) this, or.elim this ( assume : x ∈ FV (term.app f fx), have free_in_term x f ∨ free_in_term x fx, from free_in_term.app.inv this, or.elim this ( assume : free_in_term x f, have x = f, from free_in_term.var.inv this, show x ∈ FV P, from absurd this x_neq_f ) ( assume : free_in_term x fx, have x = fx, from free_in_term.var.inv this, show x ∈ FV P, from absurd this x_neq_fx ) ) ( assume : x ∈ FV (P ⋀ (spec.func f fx R S) ⋀ R), or.elim (free_in_prop.and.inv this) id ( assume : free_in_prop x (spec.func f fx R S ⋀ R), have h: free_in_prop x ((spec.func f fx R S).to_prop ⋀ R.to_prop), from this, have spec.to_prop (spec.func f fx R S) = prop.func f fx R.to_prop S.to_prop, by unfold spec.to_prop, have free_in_prop x (prop.func f fx R S ⋀ R.to_prop), from this ▸ h, or.elim (free_in_prop.and.inv this).symm x_not_in_R ( assume : x ∈ FV (prop.func f fx R S), show x ∈ FV P, from x_not_in_non_rec_func this ) ) ) ) ( assume : x ∈ FV S.to_prop, have x ∈ FV P ∪ {f, fx}, from set.mem_of_mem_of_subset this fv_S, have x ∈ FV P ∨ x ∈ {f, fx}, from set.mem_or_mem_of_mem_union this, or.elim this id ( assume : x ∈ {f, fx}, have (x = f) ∨ (x = fx), from set.two_elems_mem this, or.elim this ( assume : x = f, show x ∈ FV P, from absurd this x_neq_f ) ( assume : x = fx, show x ∈ FV P, from absurd this x_neq_fx ) ) ) ) ) ), have x ∈ FV ((propctx.and (prop.func f fx R (Q₁ (term.app f fx) ⋀ S)) Q₂) t), from (free_in_propctx.exis.inv x_free_in_Qt).right, have x ∈ FV ((prop.func f fx R (Q₁ (term.app f fx) ⋀ S)) t) ∨ x ∈ FV (Q₂ t), from free_in_propctx.and.inv this, or.elim this ( assume : x ∈ FV ((prop.func f fx R (Q₁ (term.app f fx) ⋀ S)) t), have x ∈ FV (prop.func f fx R (Q₁ (term.app f fx) ⋀ S)), from free_in_propctx.prop.inv this, show x ∈ FV t ∨ x ∈ FV P, from or.inr (x_not_in_func this) ) ( assume : x ∈ FV (Q₂ t), have x ∈ FV t ∨ x ∈ FV (P ⋀ prop.func f fx R (Q₁ (term.app f fx) ⋀ S)), from ih₂ t this, or.elim this ( assume : x ∈ FV t, show x ∈ FV t ∨ x ∈ FV P, from or.inl this ) ( assume : x ∈ FV (P ⋀ prop.func f fx R (Q₁ (term.app f fx) ⋀ S)), or.elim (free_in_prop.and.inv this) ( assume : x ∈ FV P, show x ∈ FV t ∨ x ∈ FV P, from or.inr this ) ( assume : x ∈ FV (prop.func f fx R (Q₁ (term.app f fx) ⋀ S)), show x ∈ FV t ∨ x ∈ FV P, from or.inr (x_not_in_func this) ) ) ) }, case exp.dvcgen.unop op P e' x₁ y Q x_free_in_P y_not_in_P e'_verified vc_valid ih { from assume t: term, assume x_free_in_Qt: x ∈ FV ((propctx.exis y ((y ≡ term.unop op x₁) ⋀ Q)) t), have x_neq_y: x ≠ y, from (free_in_propctx.exis.inv x_free_in_Qt).left, have x_not_in_unop: x ∈ FV (y ≡ term.unop op x₁) → x ∈ FV P, from ( assume : x ∈ FV (y ≡ term.unop op x₁), have free_in_term x y ∨ free_in_term x (term.unop op x₁), from free_in_term.binop.inv this, or.elim this ( assume : free_in_term x y, have x = y, from free_in_term.var.inv this, show x ∈ FV P, from absurd this x_neq_y ) ( assume : free_in_term x (term.unop op x₁), have free_in_term x x₁, from free_in_term.unop.inv this, have x = x₁, from free_in_term.var.inv this, show x ∈ FV P, from this.symm ▸ x_free_in_P ) ), have x ∈ FV ((↑(y ≡ term.unop op x₁) ⋀ Q) t), from (free_in_propctx.exis.inv x_free_in_Qt).right, have x ∈ FV (propctx.term (y ≡ term.unop op x₁) t) ∨ x ∈ FV (Q t), from free_in_propctx.and.inv this, or.elim this ( assume : x ∈ FV (propctx.term (y ≡ term.unop op x₁) t), have x ∈ FV (((y ≡ term.unop op x₁).to_termctx) t), from free_in_propctx.term.inv this, have x ∈ FV (y ≡ term.unop op x₁), from free_in_termctx.term.inv this, show x ∈ FV t ∨ x ∈ FV P, from or.inr (x_not_in_unop this) ) ( assume : x ∈ FV (Q t), have x ∈ FV t ∨ x ∈ FV (P ⋀ (y ≡ term.unop op x₁)), from ih t this, or.elim this ( assume : x ∈ FV t, show x ∈ FV t ∨ x ∈ FV P, from or.inl this ) ( assume : x ∈ FV (P ⋀ (y ≡ term.unop op x₁)), or.elim (free_in_prop.and.inv this) ( assume : x ∈ FV P, show x ∈ FV t ∨ x ∈ FV P, from or.inr this ) ( assume : x ∈ FV (prop.term (y ≡ term.unop op x₁)), have x ∈ FV (y ≡ term.unop op x₁), from free_in_prop.term.inv this, show x ∈ FV t ∨ x ∈ FV P, from or.inr (x_not_in_unop this) ) ) ) }, case exp.dvcgen.binop op P e' x₁ x₂ y Q x₁_free_in_P x₂_free_in_P y_not_in_P e'_verified vc_valid ih { from assume t: term, assume x_free_in_Qt: x ∈ FV ((propctx.exis y ((y ≡ term.binop op x₁ x₂) ⋀ Q)) t), have x_neq_y: x ≠ y, from (free_in_propctx.exis.inv x_free_in_Qt).left, have x_not_in_binop: x ∈ FV (y ≡ term.binop op x₁ x₂) → x ∈ FV P, from ( assume : x ∈ FV (y ≡ term.binop op x₁ x₂), have free_in_term x y ∨ free_in_term x (term.binop op x₁ x₂), from free_in_term.binop.inv this, or.elim this ( assume : free_in_term x y, have x = y, from free_in_term.var.inv this, show x ∈ FV P, from absurd this x_neq_y ) ( assume : free_in_term x (term.binop op x₁ x₂), have free_in_term x x₁ ∨ free_in_term x x₂, from free_in_term.binop.inv this, or.elim this ( assume : free_in_term x x₁, have x = x₁, from free_in_term.var.inv this, show x ∈ FV P, from this.symm ▸ x₁_free_in_P ) ( assume : free_in_term x x₂, have x = x₂, from free_in_term.var.inv this, show x ∈ FV P, from this.symm ▸ x₂_free_in_P ) ) ), have x ∈ FV ((↑(y ≡ term.binop op x₁ x₂) ⋀ Q) t), from (free_in_propctx.exis.inv x_free_in_Qt).right, have x ∈ FV (propctx.term (y ≡ term.binop op x₁ x₂) t) ∨ x ∈ FV (Q t), from free_in_propctx.and.inv this, or.elim this ( assume : x ∈ FV (propctx.term (y ≡ term.binop op x₁ x₂) t), have x ∈ FV (((y ≡ term.binop op x₁ x₂).to_termctx) t), from free_in_propctx.term.inv this, have x ∈ FV (y ≡ term.binop op x₁ x₂), from free_in_termctx.term.inv this, show x ∈ FV t ∨ x ∈ FV P, from or.inr (x_not_in_binop this) ) ( assume : x ∈ FV (Q t), have x ∈ FV t ∨ x ∈ FV (P ⋀ (y ≡ term.binop op x₁ x₂)), from ih t this, or.elim this ( assume : x ∈ FV t, show x ∈ FV t ∨ x ∈ FV P, from or.inl this ) ( assume : x ∈ FV (P ⋀ (y ≡ term.binop op x₁ x₂)), or.elim (free_in_prop.and.inv this) ( assume : x ∈ FV P, show x ∈ FV t ∨ x ∈ FV P, from or.inr this ) ( assume : x ∈ FV (prop.term (y ≡ term.binop op x₁ x₂)), have x ∈ FV (y ≡ term.binop op x₁ x₂), from free_in_prop.term.inv this, show x ∈ FV t ∨ x ∈ FV P, from or.inr (x_not_in_binop this) ) ) ) }, case exp.dvcgen.app P y f e' x₁ Q f_free_in_P x₁_free_in_P y_not_in_P e'_verified vc_valid ih { from assume t: term, assume x_free_in_Qt: x ∈ FV ((propctx.exis y ((prop.call x₁) ⋀ (prop.post f x₁) ⋀ (y ≡ term.app f x₁) ⋀ Q)) t), have x_neq_y: x ≠ y, from (free_in_propctx.exis.inv x_free_in_Qt).left, have x_not_in_call: x ∈ FV (prop.call x₁) → x ∈ FV P, from ( assume : x ∈ FV (prop.call x₁), have free_in_term x x₁, from free_in_prop.call.inv this, have x = x₁, from free_in_term.var.inv this, show x ∈ FV P, from this.symm ▸ x₁_free_in_P ), have x_not_in_post: x ∈ FV (prop.post f x₁) → x ∈ FV P, from ( assume : x ∈ FV (prop.post f x₁), or.elim (free_in_prop.post.inv this) ( assume : free_in_term x f, have x = f, from free_in_term.var.inv this, show x ∈ FV P, from this.symm ▸ f_free_in_P ) ( assume : free_in_term x x₁, have x = x₁, from free_in_term.var.inv this, show x ∈ FV P, from this.symm ▸ x₁_free_in_P ) ), have x_not_in_app: x ∈ FV (y ≡ term.app f x₁) → x ∈ FV P, from ( assume : x ∈ FV (y ≡ term.app f x₁), have free_in_term x y ∨ free_in_term x (term.app f x₁), from free_in_term.binop.inv this, or.elim this ( assume : free_in_term x y, have x = y, from free_in_term.var.inv this, show x ∈ FV P, from absurd this x_neq_y ) ( assume : free_in_term x (term.app f x₁), have free_in_term x f ∨ free_in_term x x₁, from free_in_term.app.inv this, or.elim this ( assume : free_in_term x f, have x = f, from free_in_term.var.inv this, show x ∈ FV P, from this.symm ▸ f_free_in_P ) ( assume : free_in_term x x₁, have x = x₁, from free_in_term.var.inv this, show x ∈ FV P, from this.symm ▸ x₁_free_in_P ) ) ), have x ∈ FV ((↑(prop.call ↑x₁) ⋀ ↑(prop.post ↑f ↑x₁) ⋀ ↑(↑y ≡ term.app ↑f ↑x₁) ⋀ Q) t), from (free_in_propctx.exis.inv x_free_in_Qt).right, have x ∈ FV (((prop.call x₁):propctx) t) ∨ x ∈ FV ((↑(prop.post f x₁) ⋀ ↑(y ≡ term.app f x₁) ⋀ Q) t), from free_in_propctx.and.inv this, or.elim this ( assume : x ∈ FV (((prop.call x₁):propctx) t), have x ∈ FV (prop.call x₁), from free_in_propctx.prop.inv this, show x ∈ FV t ∨ x ∈ FV P, from or.inr (x_not_in_call this) ) ( assume : x ∈ FV ((↑(prop.post f x₁) ⋀ ↑(y ≡ term.app f x₁) ⋀ Q) t), have x ∈ FV (((prop.post f x₁):propctx) t) ∨ x ∈ FV ((↑(y ≡ term.app f x₁) ⋀ Q) t), from free_in_propctx.and.inv this, or.elim this ( assume : x ∈ FV (((prop.post f x₁):propctx) t), have x ∈ FV (prop.post f x₁), from free_in_propctx.prop.inv this, show x ∈ FV t ∨ x ∈ FV P, from or.inr (x_not_in_post this) ) ( assume : x ∈ FV ((↑(y ≡ term.app f x₁) ⋀ Q) t), have x ∈ FV ((↑(y ≡ term.app f x₁):propctx) t) ∨ x ∈ FV (Q t), from free_in_propctx.and.inv this, or.elim this ( assume : x ∈ FV (((y ≡ term.app f x₁):propctx) t), have x ∈ FV ((y ≡ term.app f x₁):prop), from free_in_propctx.prop.inv this, have x ∈ FV (y ≡ term.app f x₁), from free_in_prop.term.inv this, show x ∈ FV t ∨ x ∈ FV P, from or.inr (x_not_in_app this) ) ( assume : x ∈ FV (Q t), have x ∈ FV t ∨ x ∈ FV (P ⋀ prop.call x₁ ⋀ prop.post f x₁ ⋀ (y ≡ term.app f x₁)), from ih t this, or.elim this ( assume : x ∈ FV t, show x ∈ FV t ∨ x ∈ FV P, from or.inl this ) ( assume : x ∈ FV (P ⋀ prop.call x₁ ⋀ prop.post f x₁ ⋀ (y ≡ term.app f x₁)), or.elim (free_in_prop.and.inv this) ( assume : x ∈ FV P, show x ∈ FV t ∨ x ∈ FV P, from or.inr this ) ( assume : x ∈ FV (prop.call x₁ ⋀ prop.post f x₁ ⋀ (y ≡ term.app f x₁)), or.elim (free_in_prop.and.inv this) ( assume : x ∈ FV (prop.call x₁), show x ∈ FV t ∨ x ∈ FV P, from or.inr (x_not_in_call this) ) ( assume : x ∈ FV (prop.post f x₁ ⋀ (y ≡ term.app f x₁)), or.elim (free_in_prop.and.inv this) ( assume : x ∈ FV (prop.post f x₁), show x ∈ FV t ∨ x ∈ FV P, from or.inr (x_not_in_post this) ) ( assume : free_in_prop x (y ≡ term.app f x₁), have x ∈ FV (y ≡ term.app f x₁), from free_in_prop.term.inv this, show x ∈ FV t ∨ x ∈ FV P, from or.inr (x_not_in_app this) ) ) ) ) ) ) ) }, case exp.dvcgen.ite P e₁ e₂ y Q₁ Q₂ y_free_in_P _ _ vc_valid ih₁ ih₂ { from assume t: term, assume x_free_in_Qt: x ∈ FV ((propctx.implies y Q₁ ⋀ propctx.implies (prop.not y) Q₂) t), have x_not_in_y: free_in_prop x y → x ∈ FV P, from ( assume : free_in_prop x y, have free_in_term x y, from free_in_prop.term.inv this, have x = y, from free_in_term.var.inv this, show x ∈ FV P, from this.symm ▸ y_free_in_P ), have x_not_in_yn: free_in_prop x (prop.not y) → x ∈ FV P, from ( assume : free_in_prop x (prop.not y), have free_in_prop x y, from free_in_prop.not.inv this, have free_in_term x y, from free_in_prop.term.inv this, have x = y, from free_in_term.var.inv this, show x ∈ FV P, from this.symm ▸ y_free_in_P ), or.elim (free_in_propctx.and.inv x_free_in_Qt) ( assume : x ∈ FV ((propctx.implies y Q₁) t), or.elim (free_in_propctx.implies.inv this) ( assume : x ∈ FV ((prop.term y).to_propctx t), have x ∈ FV (prop.term y), from free_in_propctx.prop.inv this, show x ∈ FV t ∨ x ∈ FV P, from or.inr (x_not_in_y this) ) ( assume : x ∈ FV (Q₁ t), have x ∈ FV t ∨ x ∈ FV (P ⋀ y), from ih₁ t this, or.elim this ( assume : x ∈ FV t, show x ∈ FV t ∨ x ∈ FV P, from or.inl this ) ( assume : x ∈ FV (P ⋀ y), or.elim (free_in_prop.and.inv this) ( assume : x ∈ FV P, show x ∈ FV t ∨ x ∈ FV P, from or.inr this ) ( assume : free_in_prop x y, have x ∈ FV P, from x_not_in_y this, show x ∈ FV t ∨ x ∈ FV P, from or.inr this ) ) ) ) ( assume : x ∈ FV ((propctx.implies (prop.not y) Q₂) t), or.elim (free_in_propctx.implies.inv this) ( assume : x ∈ FV ((prop.not y).to_propctx t), have x ∈ FV (prop.not y), from free_in_propctx.prop.inv this, show x ∈ FV t ∨ x ∈ FV P, from or.inr (x_not_in_yn this) ) ( assume : x ∈ FV (Q₂ t), have x ∈ FV t ∨ x ∈ FV (P ⋀ (prop.not y)), from ih₂ t this, or.elim this ( assume : x ∈ FV t, show x ∈ FV t ∨ x ∈ FV P, from or.inl this ) ( assume : x ∈ FV (P ⋀ (prop.not y)), or.elim (free_in_prop.and.inv this) ( assume : x ∈ FV P, show x ∈ FV t ∨ x ∈ FV P, from or.inr this ) ( assume : free_in_prop x (prop.not y), have x ∈ FV P, from x_not_in_yn this, show x ∈ FV t ∨ x ∈ FV P, from or.inr this ) ) ) ) }, case exp.dvcgen.return P y y_free_in_P { from assume t: term, assume : x ∈ FV ((propctx.term (y ≣ •)) t), have x ∈ FV ((y ≣ •) t), from free_in_propctx.term.inv this, or.elim (free_in_termctx.binop.inv this) ( assume : x ∈ FV ((y:termctx) t), have free_in_term x y, from free_in_termctx.term.inv this, have x = y, from free_in_term.var.inv this, have x ∈ FV P, from this.symm ▸ y_free_in_P, show x ∈ FV t ∨ x ∈ FV P, from or.inr this ) ( assume : x ∈ FV (• t), have x ∈ FV t, from free_in_termctx.hole.inv this, show x ∈ FV t ∨ x ∈ FV P, from or.inl this ) } end lemma contains_of_free {P: prop} {σ: env} {x: var}: (⊩ σ : P) → free_in_prop x P → x ∈ σ := assume env_verified: ⊩ σ : P, assume x_free_in_P: free_in_prop x P, show x ∈ σ, by begin induction env_verified, case env.dvcgen.empty { from have free_in_term x value.true, from free_in_prop.term.inv x_free_in_P, show x ∈ env.empty, from absurd this free_in_term.value.inv }, case env.dvcgen.tru σ' y Q _ _ ih { show x ∈ (σ'[y↦value.true]), from contains_of_free_eq_value x_free_in_P ih }, case env.dvcgen.fls σ' y Q _ _ ih { from show x ∈ (σ'[y↦value.false]), from contains_of_free_eq_value x_free_in_P ih }, case env.dvcgen.num n σ' y Q _ _ ih { from show x ∈ (σ'[y↦value.num n]), from contains_of_free_eq_value x_free_in_P ih }, case env.dvcgen.func f σ₂ σ₁ g gx R S e Q₁ Q₂ Q₃ _ _ _ _ _ _ _ fv_R fv_S e_verified _ ih₁ ih₂ { from contains_of_free_in_nonempty_env ( assume : f ≠ x, have x_neq_f: x ≠ f, from this.symm, let vf := value.func g gx R S e σ₂ in have free_in_prop x Q₁ ∨ free_in_prop x ((f ≡ vf) ⋀ prop.subst_env (σ₂[g↦vf]) (prop.func g gx R (Q₃ (term.app g gx) ⋀ S))), from free_in_prop.and.inv x_free_in_P, or.elim this ( assume x_free_in_Q₁: free_in_prop x Q₁, show x ∈ σ₁, from ih₁ x_free_in_Q₁ ) ( assume : free_in_prop x ((f ≡ vf) ⋀ prop.subst_env (σ₂[g↦vf]) (prop.func g gx R (Q₃ (term.app g gx) ⋀ S))), or.elim (free_in_prop.and.inv this) ( assume x_free_in_eq_v: free_in_prop x (f ≡ vf), show x ∈ σ₁, by begin cases x_free_in_eq_v, case free_in_prop.term x_free_in_eq { cases x_free_in_eq, case free_in_term.binop₁ free_in_f { have f_is_x: (f = x), from (free_in_term.var.inv free_in_f).symm, contradiction }, case free_in_term.binop₂ free_in_vf { cases free_in_vf } } end ) ( assume x_free_in_sFunc: free_in_prop x (prop.subst_env (σ₂[g↦vf]) (prop.func g gx R (Q₃ (term.app g gx) ⋀ S))), have x ≠ g ∧ free_in_prop x (prop.subst_env σ₂ (prop.func g gx R (Q₃ (term.app g gx) ⋀ S))), from free_of_subst_env_prop x_free_in_sFunc, have x_neq_g: x ≠ g, from this.left, have x_free_in_sFunc': free_in_prop x (prop.subst_env σ₂ (prop.func g gx R (Q₃ (term.app g gx) ⋀ S))), from this.right, have x_free_in_func: free_in_prop x (prop.func g gx R (Q₃ (term.app g gx) ⋀ S)), from free_of_subst_env x_free_in_sFunc', let forallp := (prop.implies R.to_prop (prop.pre g gx) ⋀ prop.implies (prop.post g gx) (Q₃ (term.app g gx) ⋀ S.to_prop)) in have h: prop.func g gx R.to_prop (Q₃ (term.app g gx) ⋀ S.to_prop) = (term.unop unop.isFunc g ⋀ prop.forallc gx forallp), by unfold prop.func, have free_in_prop x (term.unop unop.isFunc g ⋀ prop.forallc gx forallp), from h ▸ x_free_in_func, have free_in_prop x (term.unop unop.isFunc g) ∨ free_in_prop x (prop.forallc gx forallp), from free_in_prop.and.inv this, or.elim this ( assume : free_in_prop x (term.unop unop.isFunc g), have free_in_term x (term.unop unop.isFunc g), from free_in_prop.term.inv this, have free_in_term x g, from free_in_term.unop.inv this, have x = g, from free_in_term.var.inv this, show x ∈ σ₁, from absurd this x_neq_g ) ( assume x_free_in_forallp: free_in_prop x (prop.forallc gx forallp), have x_neq_gx: x ≠ gx, from (free_in_prop.forallc.inv x_free_in_forallp).left, have x_not_in_R: x ∉ FV R.to_prop, from ( assume : free_in_prop x R.to_prop, have x ∈ FV Q₂ ∪ {g, gx}, from set.mem_of_mem_of_subset this fv_R, have x ∈ FV Q₂ ∨ x ∈ {g, gx}, from set.mem_or_mem_of_mem_union this, or.elim this ( assume : x ∈ FV Q₂, have x ∈ σ₂, from ih₂ this, have ¬ free_in_prop x (prop.subst_env σ₂ (prop.func g gx R (Q₃ (term.app g gx) ⋀ S))), from prop.not_free_of_subst_env this, show «false», from this x_free_in_sFunc' ) ( assume : x ∈ {g, gx}, have (x = g) ∨ (x = gx), from set.two_elems_mem this, or.elim this ( assume : x = g, show «false», from x_neq_g this ) ( assume : x = gx, show «false», from x_neq_gx this ) ) ), have x_not_in_S: x ∉ FV S.to_prop, from ( assume : free_in_prop x S.to_prop, have x ∈ FV Q₂ ∪ {g, gx}, from set.mem_of_mem_of_subset this fv_S, have x ∈ FV Q₂ ∨ x ∈ {g, gx}, from set.mem_or_mem_of_mem_union this, or.elim this ( assume : x ∈ FV Q₂, have x ∈ σ₂, from ih₂ this, have ¬ free_in_prop x (prop.subst_env σ₂ (prop.func g gx R (Q₃ (term.app g gx) ⋀ S))), from prop.not_free_of_subst_env this, show «false», from this x_free_in_sFunc' ) ( assume : x ∈ {g, gx}, have (x = g) ∨ (x = gx), from set.two_elems_mem this, or.elim this ( assume : x = g, show «false», from x_neq_g this ) ( assume : x = gx, show «false», from x_neq_gx this ) ) ), have x_not_in_gfunc: x ∉ FV (prop.func g gx R S), from ( assume x_free_in_gfunc: x ∈ FV (prop.func g gx R S), let forallp' := (prop.implies R.to_prop (prop.pre g gx) ⋀ prop.implies (prop.post g gx) S.to_prop) in have h: prop.func g gx R.to_prop S.to_prop = (term.unop unop.isFunc g ⋀ prop.forallc gx forallp'), by unfold prop.func, have free_in_prop x (term.unop unop.isFunc g ⋀ prop.forallc gx forallp'), from h ▸ x_free_in_gfunc, have free_in_prop x (term.unop unop.isFunc g) ∨ free_in_prop x (prop.forallc gx forallp'), from free_in_prop.and.inv this, or.elim this ( assume : free_in_prop x (term.unop unop.isFunc g), have free_in_term x (term.unop unop.isFunc g), from free_in_prop.term.inv this, have free_in_term x g, from free_in_term.unop.inv this, have x = g, from free_in_term.var.inv this, show «false», from x_neq_g this ) ( assume x_free_in_forallp': free_in_prop x (prop.forallc gx forallp'), have x_neq_gx: x ≠ gx, from (free_in_prop.forallc.inv x_free_in_forallp').left, have free_in_prop x forallp', from (free_in_prop.forallc.inv x_free_in_forallp').right, or.elim (free_in_prop.and.inv this) ( assume : free_in_prop x (prop.implies R.to_prop (prop.pre g gx)), or.elim (free_in_prop.implies.inv this) x_not_in_R ( assume : free_in_prop x (prop.pre g gx), have free_in_term x g ∨ free_in_term x gx, from free_in_prop.pre.inv this, or.elim this ( assume : free_in_term x g, have x = g, from free_in_term.var.inv this, show «false», from x_neq_g this ) ( assume : free_in_term x gx, have x = gx, from free_in_term.var.inv this, show «false», from x_neq_gx this ) ) ) ( assume : free_in_prop x (prop.implies (prop.post g gx) S.to_prop), or.elim (free_in_prop.implies.inv this).symm x_not_in_S ( assume : free_in_prop x (prop.post g gx), have free_in_term x g ∨ free_in_term x gx, from free_in_prop.post.inv this, or.elim this ( assume : free_in_term x g, have x = g, from free_in_term.var.inv this, show «false», from x_neq_g this ) ( assume : free_in_term x gx, have x = gx, from free_in_term.var.inv this, show «false», from x_neq_gx this ) ) ) ) ), have free_in_prop x forallp, from (free_in_prop.forallc.inv x_free_in_forallp).right, or.elim (free_in_prop.and.inv this) ( assume : free_in_prop x (prop.implies R.to_prop (prop.pre g gx)), or.elim (free_in_prop.implies.inv this) ( assume : x ∈ FV R.to_prop, show x ∈ σ₁, from absurd this x_not_in_R ) ( assume : free_in_prop x (prop.pre g gx), have free_in_term x g ∨ free_in_term x gx, from free_in_prop.pre.inv this, or.elim this ( assume : free_in_term x g, have x = g, from free_in_term.var.inv this, show x ∈ σ₁, from absurd this x_neq_g ) ( assume : free_in_term x gx, have x = gx, from free_in_term.var.inv this, show x ∈ σ₁, from absurd this x_neq_gx ) ) ) ( assume : free_in_prop x (prop.implies (prop.post g gx) (Q₃ (term.app g gx) ⋀ S.to_prop)), or.elim (free_in_prop.implies.inv this) ( assume : free_in_prop x (prop.post g gx), have free_in_term x g ∨ free_in_term x gx, from free_in_prop.post.inv this, or.elim this ( assume : free_in_term x g, have x = g, from free_in_term.var.inv this, show x ∈ σ₁, from absurd this x_neq_g ) ( assume : free_in_term x gx, have x = gx, from free_in_term.var.inv this, show x ∈ σ₁, from absurd this x_neq_gx ) ) ( assume : free_in_prop x (Q₃ (term.app g gx) ⋀ S.to_prop), have free_in_prop x (Q₃ (term.app g gx)) ∨ free_in_prop x S.to_prop, from free_in_prop.and.inv this, or.elim this.symm ( assume : x ∈ FV S.to_prop, show x ∈ σ₁, from absurd this x_not_in_S ) ( assume : free_in_prop x (Q₃ (term.app g gx)), have x ∈ FV (term.app g gx) ∨ x ∈ FV (Q₂ ⋀ (spec.func g gx R S) ⋀ R), from exp.post_free e_verified (term.app g gx) this, or.elim this ( assume : x ∈ FV (term.app g gx), or.elim (free_in_term.app.inv this) ( assume : free_in_term x g, have x = g, from free_in_term.var.inv this, show x ∈ σ₁, from absurd this x_neq_g ) ( assume : free_in_term x gx, have x = gx, from free_in_term.var.inv this, show x ∈ σ₁, from absurd this x_neq_gx ) ) ( assume : x ∈ FV (Q₂ ⋀ (spec.func g gx R S) ⋀ R), or.elim (free_in_prop.and.inv this) ( assume : x ∈ FV Q₂, have x ∈ σ₂, from ih₂ this, have ¬ free_in_prop x (prop.subst_env σ₂ (prop.func g gx R (Q₃ (term.app g gx) ⋀ S))), from prop.not_free_of_subst_env this, show x ∈ σ₁, from absurd x_free_in_sFunc' this ) ( assume : free_in_prop x (spec.func g gx R S ⋀ R), have h: free_in_prop x ((spec.func g gx R S).to_prop ⋀ R.to_prop), from this, have spec.to_prop (spec.func g gx R S) = prop.func g gx R.to_prop S.to_prop, by unfold spec.to_prop, have free_in_prop x (prop.func g gx R S ⋀ R.to_prop), from this ▸ h, or.elim (free_in_prop.and.inv this) ( assume : x ∈ FV (prop.func g gx R S), show x ∈ σ₁, from absurd this x_not_in_gfunc ) ( assume : x ∈ FV R.to_prop, show x ∈ σ₁, from absurd this x_not_in_R ) ) ) ) ) ) ) ) ) ) } end lemma prop_func_closed {P: prop} {Q: propctx} {σ: env} {f fx: var} {R S: spec} {e: exp}: (⊩ (σ[f↦value.func f fx R S e σ]) : (P ⋀ (f ≡ value.func f fx R S e σ) ⋀ prop.subst_env (σ[f↦value.func f fx R S e σ]) (prop.func f fx R (Q (term.app f fx) ⋀ S)))) → closed (prop.subst_env (σ[f↦value.func f fx R S e σ]) (prop.func f fx R (Q (term.app f fx) ⋀ S))) := assume env_verified: ⊩ (σ[f↦value.func f fx R S e σ]) : (P ⋀ (f ≡ value.func f fx R S e σ) ⋀ prop.subst_env (σ[f↦value.func f fx R S e σ]) (prop.func f fx R (Q (term.app f fx) ⋀ S))), assume x: var, assume h: x ∈ FV (prop.subst_env (σ[f↦value.func f fx R S e σ]) (prop.func f fx R (Q (term.app f fx) ⋀ S))), have free_in_prop x (f ≡ value.func f fx R S e σ ⋀ prop.subst_env (σ[f↦value.func f fx R S e σ]) (prop.func f fx R (Q (term.app f fx) ⋀ S))), from free_in_prop.and₂ h, have x ∈ FV (P ⋀ (f ≡ value.func f fx R S e σ) ⋀ prop.subst_env (σ[f↦value.func f fx R S e σ]) (prop.func f fx R (Q (term.app f fx) ⋀ S))), from free_in_prop.and₂ this, have x ∈ (σ[f↦value.func f fx R S e σ]), from contains_of_free env_verified this, have x ∉ FV (prop.subst_env (σ[f↦value.func f fx R S e σ]) (prop.func f fx R (Q (term.app f fx) ⋀ S))), from prop.not_free_of_subst_env this, show «false», from this h lemma free_iff_contains {P: prop} {σ: env}: (⊩ σ : P) → (σ.dom = FV P) := assume σ_verified: ⊩ σ : P, set.eq_of_subset_of_subset ( assume x: var, assume : x ∈ σ.dom, have x ∈ σ, from this, show x ∈ FV P, from free_of_contains σ_verified this ) ( assume x: var, assume : x ∈ FV P, have x ∈ σ, from contains_of_free σ_verified this, show x ∈ σ.dom, from this ) lemma env_translation_closed_subst {P: prop} {σ: env}: (⊩ σ : P) → closed_subst σ P := assume σ_verified: ⊩ σ : P, assume z: var, assume : z ∈ FV P, show z ∈ σ.dom, from (free_iff_contains σ_verified).symm ▸ this lemma env.apply_of_vcgen {σ: env} {x: var} {v: value} {P: prop}: (⊩ (σ[x↦v]) : P) → ((σ[x↦v]) x = v) := begin intro h1, have h2: (x ∉ σ), by begin cases h1, case env.dvcgen.tru P x_not_in_σ σ_verified { from x_not_in_σ }, case env.dvcgen.fls P x_not_in_σ σ_verified { from x_not_in_σ }, case env.dvcgen.num n P x_not_in_σ σ_verified { from x_not_in_σ }, case env.dvcgen.func σ₃ f fx R S e Q₃ Q₄ Q₂ x_not_in_σ₂ f_not_in_σ₃ fx_not_in_σ₃ f_neq_fx σ₂_verified σ₃_verified x_free_in_R fv_R fv_S e_verified func_vc { from x_not_in_σ₂ } end, from env.apply_of_contains h2 end lemma env.rest_verified {P: prop} {σ: env} {x: var} {v: value}: (⊩ (σ[x↦v]) : P) → ∃Q, ⊩ σ : Q := assume σ_verified: ⊩ (σ[x↦v]) : P, begin cases σ_verified, case env.dvcgen.tru Q _ σ_verified { from exists.intro Q σ_verified }, case env.dvcgen.fls Q _ σ_verified { from exists.intro Q σ_verified }, case env.dvcgen.num n Q _ σ_verified { from exists.intro Q σ_verified }, case env.dvcgen.func σ₂ f fx R S e Q Q₂ Q₃ x_not_in_σ f_not_in_σ₂ fx_not_in_σ₂ f_neq_fx σ₁_verified { from exists.intro Q σ₁_verified } end lemma env_free_rest {P: prop} {σ: env} {x: var} {v: value}: (⊩ (σ[x↦v]) : P) → (∃Q, (⊩ σ : Q) ∧ FV Q ⊆ FV P) := assume σ_verified: ⊩ (σ[x↦v]) : P, begin cases σ_verified, case env.dvcgen.tru Q _ σ_verified ih { from have FV Q ⊆ FV (prop.and Q (x ≡ value.true)), from free_in_prop.and_left_subset, show ∃(Q_1 : prop), (⊩ σ : Q_1) ∧ FV Q_1 ⊆ FV (prop.and Q (x ≡ value.true)), from exists.intro Q ⟨σ_verified, this⟩ }, case env.dvcgen.fls Q _ σ_verified { from have FV Q ⊆ FV (prop.and Q (x ≡ value.false)), from free_in_prop.and_left_subset, show ∃(Q_1 : prop), (⊩ σ : Q_1) ∧ FV Q_1 ⊆ FV (prop.and Q (x ≡ value.false)), from exists.intro Q ⟨σ_verified, this⟩ }, case env.dvcgen.num n Q _ σ_verified { from have FV Q ⊆ FV (prop.and Q (x ≡ value.num n)), from free_in_prop.and_left_subset, show ∃(Q_1 : prop), (⊩ σ : Q_1) ∧ FV Q_1 ⊆ FV (prop.and Q (x ≡ value.num n)), from exists.intro Q ⟨σ_verified, this⟩ }, case env.dvcgen.func σ₂ f fx R S e Q Q₂ Q₃ x_not_in_σ f_not_in_σ₂ fx_not_in_σ₂ f_neq_fx σ₁_verified σ₂_verified fx_in_R fv_R fv_S e_verified func_vc { from let funcp := prop.subst_env (σ₂[f↦value.func f fx R S e σ₂]) (prop.func f fx R (Q₃ (term.app f fx) ⋀ S)) in have FV Q ⊆ FV (prop.and Q (x ≡ value.func f fx R S e σ₂ ⋀ funcp)), from free_in_prop.and_left_subset, show ∃(Q_1 : prop), (⊩ σ : Q_1) ∧ FV Q_1 ⊆ FV (prop.and Q (x ≡ value.func f fx R S e σ₂ ⋀ funcp)), from exists.intro Q ⟨σ₁_verified, this⟩ } end
9cd559bea332b0ff8493cef279fc9f76436c7d4d
96338d06deb5f54f351493a71d6ecf6c546089a2
/priv/Lean/DepSet.lean
eef99e317f565a43a06e2ea54ee1524bfd48bbfd
[]
no_license
silky/exe
5f9e4eea772d74852a1a2fac57d8d20588282d2b
e81690d6e16f2a83c105cce446011af6ae905b81
refs/heads/master
1,609,385,766,412
1,472,164,223,000
1,472,164,223,000
66,610,224
1
0
null
1,472,178,919,000
1,472,178,919,000
null
UTF-8
Lean
false
false
1,148
lean
/- DepSet.lean -/ import Setoid import Cat import Functor import Over set_option pp.universes true set_option pp.metavar_args false namespace EXE -- main definition DepSetoidCat (Base : SetoidType) : CatType := (Cat.FromSet Base) ⟶ SetoidCat definition OverSetoidCat (Base : SetoidType) : CatType := OverCat SetoidCat Base -- utils definition DepId {Base: SetoidType} (P : DepSetoidCat Base) {b1 b2 : Base} (eq12 : b1 ≡_≡ b2) (eq21 : b2 ≡_≡ b1) : Setoid.Id ≡_≡ ((P $$/ eq21) ∙ (P $$/ eq12)) := SetoidType.Trans3 ((P $$ b1)⥤(P $$ b1)) (SetoidType.Sym ((P $$ b1)⥤(P $$ b1)) (FunctorType.onId P)) (P $$// (@id (⊜ ≡(Setoid.FromType (b1 ≡_≡ b1))≡ (eq12 ⊡_⊡ eq21)) true.intro)) (FunctorType.onMul P eq21 eq12) definition DepAdj {Base: SetoidType} (P : DepSetoidCat Base) {b1 b2 : Base} (eq12 : b1 ≡_≡ b2) (eq21 : b2 ≡_≡ b1) (f1 : [P $$ b1]) (f2 : [P $$ b2]) : (((P $$/ eq12) $ f1) ≡_≡ f2) → (f1 ≡_≡ ((P $$/ eq21) $ f2)) := λ eqP, SetoidType.Trans (P $$ b1) ((DepId P eq12 eq21) /$ f1) ((P $$/ eq21) $/ eqP) end EXE
437641971955f19c0bda1df775d0cca82a844ebb
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/data/nat/multiplicity.lean
f8265732dbd7dd3fd6ef2ef6c74f65c5b63ad4e1
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
9,499
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.nat.choose import ring_theory.multiplicity import data.nat.modeq import algebra.gcd_domain /-! # Natural number multiplicity This file contains lemmas about the multiplicity function (the maximum prime power divding a number). # Main results There are natural number versions of some basic lemmas about multiplicity. There are also lemmas about the multiplicity of primes in factorials and in binomial coefficients. -/ open finset nat multiplicity namespace nat /-- The multiplicity of a divisor `m` of `n`, is the cardinality of the set of positive natural numbers `i` such that `p ^ i` divides `n`. The set is expressed by filtering `Ico 1 b` where `b` is any bound at least `n` -/ lemma multiplicity_eq_card_pow_dvd {m n b : ℕ} (hm1 : m ≠ 1) (hn0 : 0 < n) (hb : n ≤ b): multiplicity m n = ↑((finset.Ico 1 b).filter (λ i, m ^ i ∣ n)).card := calc multiplicity m n = ↑(Ico 1 $ ((multiplicity m n).get (finite_nat_iff.2 ⟨hm1, hn0⟩) + 1)).card : by simp ... = ↑((finset.Ico 1 b).filter (λ i, m ^ i ∣ n)).card : congr_arg coe $ congr_arg card $ finset.ext.2 $ λ i, have hmn : ¬ m ^ n ∣ n, from if hm0 : m = 0 then λ _, by cases n; simp [*, lt_irrefl, nat.pow_succ] at * else mt (le_of_dvd hn0) (not_le_of_gt $ lt_pow_self (lt_of_le_of_ne (nat.pos_of_ne_zero hm0) hm1.symm) _), ⟨λ hi, begin simp only [Ico.mem, mem_filter, lt_succ_iff] at *, exact ⟨⟨hi.1, lt_of_le_of_lt hi.2 $ lt_of_lt_of_le (by rw [← enat.coe_lt_coe, enat.coe_get, multiplicity_lt_iff_neg_dvd, nat.pow_eq_pow]; exact hmn) hb⟩, by rw [← nat.pow_eq_pow, pow_dvd_iff_le_multiplicity]; rw [← @enat.coe_le_coe i, enat.coe_get] at hi; exact hi.2⟩ end, begin simp only [Ico.mem, mem_filter, lt_succ_iff, and_imp, true_and] { contextual := tt }, assume h1i hib hmin, rwa [← enat.coe_le_coe, enat.coe_get, ← pow_dvd_iff_le_multiplicity, nat.pow_eq_pow] end⟩ namespace prime lemma multiplicity_one {p : ℕ} (hp : p.prime) : multiplicity p 1 = 0 := by rw [multiplicity.one_right (mt nat.is_unit_iff.mp (ne_of_gt hp.one_lt))] lemma multiplicity_mul {p m n : ℕ} (hp : p.prime) : multiplicity p (m * n) = multiplicity p m + multiplicity p n := by rw [← int.coe_nat_multiplicity, ← int.coe_nat_multiplicity, ← int.coe_nat_multiplicity, int.coe_nat_mul, multiplicity.mul (nat.prime_iff_prime_int.1 hp)] lemma multiplicity_pow {p m n : ℕ} (hp : p.prime) : multiplicity p (m ^ n) = add_monoid.smul n (multiplicity p m) := by induction n; simp [nat.pow_succ, hp.multiplicity_mul, *, hp.multiplicity_one, succ_smul, add_comm] lemma multiplicity_self {p : ℕ} (hp : p.prime) : multiplicity p p = 1 := have h₁ : ¬ is_unit (p : ℤ), from mt is_unit_int.1 (ne_of_gt hp.one_lt), have h₂ : (p : ℤ) ≠ 0, from int.coe_nat_ne_zero.2 hp.ne_zero, by rw [← int.coe_nat_multiplicity, multiplicity_self h₁ h₂] lemma multiplicity_pow_self {p n : ℕ} (hp : p.prime) : multiplicity p (p ^ n) = n := by induction n; simp [hp.multiplicity_one, nat.pow_succ, hp.multiplicity_mul, *, hp.multiplicity_self, succ_eq_add_one] /-- The multiplicity of a prime in `fact n` is the sum of the quotients `n / p ^ i`. This sum is expressed over the set `Ico 1 b` where `b` is any bound at least `n` -/ lemma multiplicity_fact {p : ℕ} (hp : p.prime) : ∀ {n b : ℕ}, n ≤ b → multiplicity p n.fact = ((Ico 1 b).sum (λ i, n / p ^ i) : ℕ) | 0 b hb := by simp [Ico, hp.multiplicity_one] | (n+1) b hb := calc multiplicity p (n+1).fact = multiplicity p n.fact + multiplicity p (n+1) : by rw [fact_succ, hp.multiplicity_mul, add_comm] ... = ((Ico 1 b).sum (λ i, n / p ^ i) : ℕ) + ((finset.Ico 1 b).filter (λ i, p ^ i ∣ n+1)).card : by rw [multiplicity_fact (le_of_succ_le hb), ← multiplicity_eq_card_pow_dvd (ne_of_gt hp.one_lt) (succ_pos _) hb] ... = ((Ico 1 b).sum (λ i, n / p ^ i + if p^i ∣ n+1 then 1 else 0) : ℕ) : by rw [sum_add_distrib, sum_boole]; simp ... = ((Ico 1 b).sum (λ i, (n + 1) / p ^ i) : ℕ) : congr_arg coe $ finset.sum_congr rfl (by intros; simp [nat.succ_div]; congr) /-- A prime power divides `fact n` iff it is at most the sum of the quotients `n / p ^ i`. This sum is expressed over the set `Ico 1 b` where `b` is any bound at least `n` -/ lemma pow_dvd_fact_iff {p : ℕ} {n r b : ℕ} (hp : p.prime) (hbn : n ≤ b) : p ^ r ∣ fact n ↔ r ≤ (Ico 1 b).sum (λ i, n / p ^ i) := by rw [← enat.coe_le_coe, ← hp.multiplicity_fact hbn, ← pow_dvd_iff_le_multiplicity, nat.pow_eq_pow] lemma multiplicity_choose_aux {p n b k : ℕ} (hp : p.prime) (hkn : k ≤ n) : (finset.Ico 1 b).sum (λ i, n / p ^ i) = (finset.Ico 1 b).sum (λ i, k / p ^ i) + (finset.Ico 1 b).sum (λ i, (n - k) / p ^ i) + ((finset.Ico 1 b).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card := calc (finset.Ico 1 b).sum (λ i, n / p ^ i) = (finset.Ico 1 b).sum (λ i, (k + (n - k)) / p ^ i) : by simp only [nat.add_sub_cancel' hkn] ... = (finset.Ico 1 b).sum (λ i, k / p ^ i + (n - k) / p ^ i + if p ^ i ≤ k % p ^ i + (n - k) % p ^ i then 1 else 0) : by simp only [nat.add_div (nat.pow_pos hp.pos _)] ... = _ : begin simp only [sum_add_distrib], simp [sum_boole], end -- we have to use `sum_add_distrib` before `add_ite` fires. /-- The multiplity of `p` in `choose n k` is the number of carries when `k` and `n - k` are added in base `p`. The set is expressed by filtering `Ico 1 b` where `b` is any bound at least `n`. -/ lemma multiplicity_choose {p n k b : ℕ} (hp : p.prime) (hkn : k ≤ n) (hnb : n ≤ b) : multiplicity p (choose n k) = ((Ico 1 b).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card := have h₁ : multiplicity p (choose n k) + multiplicity p (k.fact * (n - k).fact) = ((finset.Ico 1 b).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card + multiplicity p (k.fact * (n - k).fact), begin rw [← hp.multiplicity_mul, ← mul_assoc, choose_mul_fact_mul_fact hkn, hp.multiplicity_fact hnb, hp.multiplicity_mul, hp.multiplicity_fact (le_trans hkn hnb), hp.multiplicity_fact (le_trans (nat.sub_le_self _ _) hnb), multiplicity_choose_aux hp hkn], simp [add_comm], end, (enat.add_right_cancel_iff (enat.ne_top_iff_dom.2 $ by exact finite_nat_iff.2 ⟨ne_of_gt hp.one_lt, mul_pos (fact_pos k) (fact_pos (n - k))⟩)).1 h₁ /-- A lower bound on the multiplicity of `p` in `choose n k`. -/ lemma multiplicity_le_multiplicity_choose_add {p : ℕ} (hp : p.prime) (n k : ℕ) : multiplicity p n ≤ multiplicity p (choose n k) + multiplicity p k := if hkn : n < k then by simp [choose_eq_zero_of_lt hkn] else if hk0 : k = 0 then by simp [hk0] else if hn0 : n = 0 then by cases k; simp [hn0, *] at * else begin rw [multiplicity_choose hp (le_of_not_gt hkn) (le_refl _), multiplicity_eq_card_pow_dvd (ne_of_gt hp.one_lt) (nat.pos_of_ne_zero hk0) (le_of_not_gt hkn), multiplicity_eq_card_pow_dvd (ne_of_gt hp.one_lt) (nat.pos_of_ne_zero hn0) (le_refl _), ← enat.coe_add, enat.coe_le_coe], calc ((Ico 1 n).filter (λ i, p ^ i ∣ n)).card ≤ ((Ico 1 n).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i) ∪ (Ico 1 n).filter (λ i, p ^ i ∣ k) ).card : card_le_of_subset $ λ i, begin have := @le_mod_add_mod_of_dvd_add_of_not_dvd k (n - k) (p ^ i), simp [nat.add_sub_cancel' (le_of_not_gt hkn)] at * {contextual := tt}, tauto end ... ≤ ((Ico 1 n).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card + ((Ico 1 n).filter (λ i, p ^ i ∣ k)).card : card_union_le _ _ end lemma multiplicity_choose_prime_pow {p n k : ℕ} (hp : p.prime) (hkn : k ≤ p ^ n) (hk0 : 0 < k) : multiplicity p (choose (p ^ n) k) + multiplicity p k = n := le_antisymm (have hdisj : disjoint ((Ico 1 (p ^ n)).filter (λ i, p ^ i ≤ k % p ^ i + (p ^ n - k) % p ^ i)) ((Ico 1 (p ^ n)).filter (λ i, p ^ i ∣ k)), by simp [disjoint_right, *, dvd_iff_mod_eq_zero, nat.mod_lt _ (nat.pow_pos hp.pos _)] {contextual := tt}, have filter_subset_Ico : filter (λ i, p ^ i ≤ k % p ^ i + (p ^ n - k) % p ^ i ∨ p ^ i ∣ k) (Ico 1 (p ^ n)) ⊆ Ico 1 n.succ, from begin simp only [finset.subset_iff, Ico.mem, mem_filter, and_imp, true_and] {contextual := tt}, assume i h1i hip h, refine lt_succ_of_le (le_of_not_gt (λ hin, _)), have hpik : ¬ p ^ i ∣ k, from mt (le_of_dvd hk0) (not_le_of_gt (lt_of_le_of_lt hkn (pow_right_strict_mono hp.two_le hin))), have hpn : k % p ^ i + (p ^ n - k) % p ^ i < p ^ i, from calc k % p ^ i + (p ^ n - k) % p ^ i ≤ k + (p ^ n - k) : add_le_add (mod_le _ _) (mod_le _ _) ... = p ^ n : nat.add_sub_cancel' hkn ... < p ^ i : pow_right_strict_mono hp.two_le hin, simpa [hpik, not_le_of_gt hpn] using h end, begin rw [multiplicity_choose hp hkn (le_refl _), multiplicity_eq_card_pow_dvd (ne_of_gt hp.one_lt) hk0 hkn, ← enat.coe_add, enat.coe_le_coe, ← card_disjoint_union hdisj, filter_union_right], exact le_trans (card_le_of_subset filter_subset_Ico) (by simp) end) (by rw [← hp.multiplicity_pow_self]; exact multiplicity_le_multiplicity_choose_add hp _ _) end prime end nat
6c5268645519bc177102f332c5040b0d9af2b8fd
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/order/lattice.lean
24b75bb36a09d5460746983b8ca65fc00d2834b6
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
16,590
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 Defines the inf/sup (semi)-lattice with optionally top/bot type class hierarchy. -/ import order.basic set_option old_structure_cmd true universes u v w variables {α : Type u} {β : Type v} -- TODO: move this eventually, if we decide to use them attribute [ematch] le_trans lt_of_le_of_lt lt_of_lt_of_le lt_trans section -- TODO: this seems crazy, but it also seems to work reasonably well @[ematch] theorem le_antisymm' [partial_order α] : ∀ {a b : α}, (: a ≤ b :) → b ≤ a → a = b := @le_antisymm _ _ end /- TODO: automatic construction of dual definitions / theorems -/ reserve infixl ` ⊓ `:70 reserve infixl ` ⊔ `:65 /-- Typeclass for the `⊔` (`\lub`) notation -/ class has_sup (α : Type u) := (sup : α → α → α) /-- Typeclass for the `⊓` (`\glb`) notation -/ class has_inf (α : Type u) := (inf : α → α → α) infix ⊔ := has_sup.sup infix ⊓ := has_inf.inf section prio set_option default_priority 100 -- see Note [default priority] /-- A `semilattice_sup` is a join-semilattice, that is, a partial order with a join (a.k.a. lub / least upper bound, sup / supremum) operation `⊔` which is the least element larger than both factors. -/ class semilattice_sup (α : Type u) extends has_sup α, partial_order α := (le_sup_left : ∀ a b : α, a ≤ a ⊔ b) (le_sup_right : ∀ a b : α, b ≤ a ⊔ b) (sup_le : ∀ a b c : α, a ≤ c → b ≤ c → a ⊔ b ≤ c) end prio section semilattice_sup variables [semilattice_sup α] {a b c d : α} @[simp] theorem le_sup_left : a ≤ a ⊔ b := semilattice_sup.le_sup_left a b @[ematch] theorem le_sup_left' : a ≤ (: a ⊔ b :) := semilattice_sup.le_sup_left a b @[simp] theorem le_sup_right : b ≤ a ⊔ b := semilattice_sup.le_sup_right a b @[ematch] theorem le_sup_right' : b ≤ (: a ⊔ b :) := semilattice_sup.le_sup_right a b theorem le_sup_left_of_le (h : c ≤ a) : c ≤ a ⊔ b := by finish theorem le_sup_right_of_le (h : c ≤ b) : c ≤ a ⊔ b := by finish theorem sup_le : a ≤ c → b ≤ c → a ⊔ b ≤ c := semilattice_sup.sup_le a b c @[simp] theorem sup_le_iff : a ⊔ b ≤ c ↔ a ≤ c ∧ b ≤ c := ⟨assume h : a ⊔ b ≤ c, ⟨le_trans le_sup_left h, le_trans le_sup_right h⟩, assume ⟨h₁, h₂⟩, sup_le h₁ h₂⟩ -- TODO: if we just write le_antisymm, Lean doesn't know which ≤ we want to use -- Can we do anything about that? theorem sup_of_le_left (h : b ≤ a) : a ⊔ b = a := by apply le_antisymm; finish theorem sup_of_le_right (h : a ≤ b) : a ⊔ b = b := by apply le_antisymm; finish theorem sup_le_sup (h₁ : a ≤ b) (h₂ : c ≤ d) : a ⊔ c ≤ b ⊔ d := by finish theorem sup_le_sup_left (h₁ : a ≤ b) (c) : c ⊔ a ≤ c ⊔ b := by finish theorem sup_le_sup_right (h₁ : a ≤ b) (c) : a ⊔ c ≤ b ⊔ c := by finish theorem le_of_sup_eq (h : a ⊔ b = b) : a ≤ b := by finish /-- A monotone function on a sup-semilattice is directed. -/ lemma directed_of_mono (f : α → β) {r : β → β → Prop} (H : ∀ ⦃i j⦄, i ≤ j → r (f i) (f j)) : directed r f := λ a b, ⟨a ⊔ b, H le_sup_left, H le_sup_right⟩ @[simp] lemma sup_lt_iff [is_total α (≤)] {a b c : α} : b ⊔ c < a ↔ b < a ∧ c < a := begin cases (is_total.total (≤) b c) with h, { simp [sup_of_le_right h], exact ⟨λI, ⟨lt_of_le_of_lt h I, I⟩, λH, H.2⟩ }, { simp [sup_of_le_left h], exact ⟨λI, ⟨I, lt_of_le_of_lt h I⟩, λH, H.1⟩ } end @[simp] theorem sup_idem : a ⊔ a = a := by apply le_antisymm; finish instance sup_is_idempotent : is_idempotent α (⊔) := ⟨@sup_idem _ _⟩ theorem sup_comm : a ⊔ b = b ⊔ a := by apply le_antisymm; finish instance sup_is_commutative : is_commutative α (⊔) := ⟨@sup_comm _ _⟩ theorem sup_assoc : a ⊔ b ⊔ c = a ⊔ (b ⊔ c) := by apply le_antisymm; finish instance sup_is_associative : is_associative α (⊔) := ⟨@sup_assoc _ _⟩ lemma sup_left_comm (a b c : α) : a ⊔ (b ⊔ c) = b ⊔ (a ⊔ c) := by rw [← sup_assoc, ← sup_assoc, @sup_comm α _ a] lemma forall_le_or_exists_lt_sup (a : α) : (∀b, b ≤ a) ∨ (∃b, a < b) := suffices (∃b, ¬b ≤ a) → (∃b, a < b), by rwa [classical.or_iff_not_imp_left, classical.not_forall], assume ⟨b, hb⟩, have a ≠ a ⊔ b, from assume eq, hb $ eq.symm ▸ le_sup_right, ⟨a ⊔ b, lt_of_le_of_ne le_sup_left ‹a ≠ a ⊔ b›⟩ theorem semilattice_sup.ext_sup {α} {A B : semilattice_sup α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) (x y : α) : (by haveI := A; exact (x ⊔ y)) = x ⊔ y := eq_of_forall_ge_iff $ λ c, by simp only [sup_le_iff]; rw [← H, @sup_le_iff α A, H, H] theorem semilattice_sup.ext {α} {A B : semilattice_sup α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin haveI this := partial_order.ext H, have ss := funext (λ x, funext $ semilattice_sup.ext_sup H x), cases A; cases B; injection this; congr' end lemma directed_of_sup {β : Type*} {r : β → β → Prop} {f : α → β} (hf : ∀a₁ a₂, a₁ ≤ a₂ → r (f a₁) (f a₂)) : directed r f := assume x y, ⟨x ⊔ y, hf _ _ le_sup_left, hf _ _ le_sup_right⟩ end semilattice_sup section prio set_option default_priority 100 -- see Note [default priority] /-- A `semilattice_inf` is a meet-semilattice, that is, a partial order with a meet (a.k.a. glb / greatest lower bound, inf / infimum) operation `⊓` which is the greatest element smaller than both factors. -/ class semilattice_inf (α : Type u) extends has_inf α, partial_order α := (inf_le_left : ∀ a b : α, a ⊓ b ≤ a) (inf_le_right : ∀ a b : α, a ⊓ b ≤ b) (le_inf : ∀ a b c : α, a ≤ b → a ≤ c → a ≤ b ⊓ c) end prio section semilattice_inf variables [semilattice_inf α] {a b c d : α} @[simp] theorem inf_le_left : a ⊓ b ≤ a := semilattice_inf.inf_le_left a b @[ematch] theorem inf_le_left' : (: a ⊓ b :) ≤ a := semilattice_inf.inf_le_left a b @[simp] theorem inf_le_right : a ⊓ b ≤ b := semilattice_inf.inf_le_right a b @[ematch] theorem inf_le_right' : (: a ⊓ b :) ≤ b := semilattice_inf.inf_le_right a b theorem le_inf : a ≤ b → a ≤ c → a ≤ b ⊓ c := semilattice_inf.le_inf a b c theorem inf_le_left_of_le (h : a ≤ c) : a ⊓ b ≤ c := le_trans inf_le_left h theorem inf_le_right_of_le (h : b ≤ c) : a ⊓ b ≤ c := le_trans inf_le_right h @[simp] theorem le_inf_iff : a ≤ b ⊓ c ↔ a ≤ b ∧ a ≤ c := ⟨assume h : a ≤ b ⊓ c, ⟨le_trans h inf_le_left, le_trans h inf_le_right⟩, assume ⟨h₁, h₂⟩, le_inf h₁ h₂⟩ theorem inf_of_le_left (h : a ≤ b) : a ⊓ b = a := by apply le_antisymm; finish theorem inf_of_le_right (h : b ≤ a) : a ⊓ b = b := by apply le_antisymm; finish theorem inf_le_inf (h₁ : a ≤ b) (h₂ : c ≤ d) : a ⊓ c ≤ b ⊓ d := by finish lemma inf_le_inf_left (a : α) {b c: α} (h : b ≤ c): b ⊓ a ≤ c ⊓ a := by finish lemma inf_le_inf_right (a : α) {b c: α} (h : b ≤ c): a ⊓ b ≤ a ⊓ c := by finish theorem le_of_inf_eq (h : a ⊓ b = a) : a ≤ b := by finish @[simp] lemma lt_inf_iff [is_total α (≤)] {a b c : α} : a < b ⊓ c ↔ a < b ∧ a < c := begin cases (is_total.total (≤) b c) with h, { simp [inf_of_le_left h], exact ⟨λI, ⟨I, lt_of_lt_of_le I h⟩, λH, H.1⟩ }, { simp [inf_of_le_right h], exact ⟨λI, ⟨lt_of_lt_of_le I h, I⟩, λH, H.2⟩ } end @[simp] theorem inf_idem : a ⊓ a = a := by apply le_antisymm; finish instance inf_is_idempotent : is_idempotent α (⊓) := ⟨@inf_idem _ _⟩ theorem inf_comm : a ⊓ b = b ⊓ a := by apply le_antisymm; finish instance inf_is_commutative : is_commutative α (⊓) := ⟨@inf_comm _ _⟩ theorem inf_assoc : a ⊓ b ⊓ c = a ⊓ (b ⊓ c) := by apply le_antisymm; finish instance inf_is_associative : is_associative α (⊓) := ⟨@inf_assoc _ _⟩ lemma inf_left_comm (a b c : α) : a ⊓ (b ⊓ c) = b ⊓ (a ⊓ c) := by rw [← inf_assoc, ← inf_assoc, @inf_comm α _ a] lemma forall_le_or_exists_lt_inf (a : α) : (∀b, a ≤ b) ∨ (∃b, b < a) := suffices (∃b, ¬a ≤ b) → (∃b, b < a), by rwa [classical.or_iff_not_imp_left, classical.not_forall], assume ⟨b, hb⟩, have a ⊓ b ≠ a, from assume eq, hb $ eq ▸ inf_le_right, ⟨a ⊓ b, lt_of_le_of_ne inf_le_left ‹a ⊓ b ≠ a›⟩ theorem semilattice_inf.ext_inf {α} {A B : semilattice_inf α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) (x y : α) : (by haveI := A; exact (x ⊓ y)) = x ⊓ y := eq_of_forall_le_iff $ λ c, by simp only [le_inf_iff]; rw [← H, @le_inf_iff α A, H, H] theorem semilattice_inf.ext {α} {A B : semilattice_inf α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin haveI this := partial_order.ext H, have ss := funext (λ x, funext $ semilattice_inf.ext_inf H x), cases A; cases B; injection this; congr' end /-- An antimonotone function on an inf-semilattice is directed. -/ lemma directed_of_inf {r : β → β → Prop} {f : α → β} (hf : ∀a₁ a₂, a₁ ≤ a₂ → r (f a₂) (f a₁)) : directed r f := assume x y, ⟨x ⊓ y, hf _ _ inf_le_left, hf _ _ inf_le_right⟩ end semilattice_inf /- Lattices -/ section prio set_option default_priority 100 -- see Note [default priority] /-- A lattice is a join-semilattice which is also a meet-semilattice. -/ class lattice (α : Type u) extends semilattice_sup α, semilattice_inf α end prio section lattice variables [lattice α] {a b c d : α} /- Distributivity laws -/ /- TODO: better names? -/ theorem sup_inf_le : a ⊔ (b ⊓ c) ≤ (a ⊔ b) ⊓ (a ⊔ c) := by finish theorem le_inf_sup : (a ⊓ b) ⊔ (a ⊓ c) ≤ a ⊓ (b ⊔ c) := by finish theorem inf_sup_self : a ⊓ (a ⊔ b) = a := le_antisymm (by finish) (by finish) theorem sup_inf_self : a ⊔ (a ⊓ b) = a := le_antisymm (by finish) (by finish) theorem lattice.ext {α} {A B : lattice α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have SS : @lattice.to_semilattice_sup α A = @lattice.to_semilattice_sup α B := semilattice_sup.ext H, have II := semilattice_inf.ext H, resetI, cases A; cases B; injection SS; injection II; congr' end end lattice section prio set_option default_priority 100 -- see Note [default priority] /-- A distributive lattice is a lattice that satisfies any of four equivalent distribution properties (of sup over inf or inf over sup, on the left or right). A classic example of a distributive lattice is the lattice of subsets of a set, and in fact this example is generic in the sense that every distributive lattice is realizable as a sublattice of a powerset lattice. -/ class distrib_lattice α extends lattice α := (le_sup_inf : ∀x y z : α, (x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z)) end prio section distrib_lattice variables [distrib_lattice α] {x y z : α} theorem le_sup_inf : ∀{x y z : α}, (x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z) := distrib_lattice.le_sup_inf theorem sup_inf_left : x ⊔ (y ⊓ z) = (x ⊔ y) ⊓ (x ⊔ z) := le_antisymm sup_inf_le le_sup_inf theorem sup_inf_right : (y ⊓ z) ⊔ x = (y ⊔ x) ⊓ (z ⊔ x) := by simp only [sup_inf_left, λy:α, @sup_comm α _ y x, eq_self_iff_true] theorem inf_sup_left : x ⊓ (y ⊔ z) = (x ⊓ y) ⊔ (x ⊓ z) := calc x ⊓ (y ⊔ z) = (x ⊓ (x ⊔ z)) ⊓ (y ⊔ z) : by rw [inf_sup_self] ... = x ⊓ ((x ⊓ y) ⊔ z) : by simp only [inf_assoc, sup_inf_right, eq_self_iff_true] ... = (x ⊔ (x ⊓ y)) ⊓ ((x ⊓ y) ⊔ z) : by rw [sup_inf_self] ... = ((x ⊓ y) ⊔ x) ⊓ ((x ⊓ y) ⊔ z) : by rw [sup_comm] ... = (x ⊓ y) ⊔ (x ⊓ z) : by rw [sup_inf_left] theorem inf_sup_right : (y ⊔ z) ⊓ x = (y ⊓ x) ⊔ (z ⊓ x) := by simp only [inf_sup_left, λy:α, @inf_comm α _ y x, eq_self_iff_true] lemma eq_of_sup_eq_inf_eq {α : Type u} [distrib_lattice α] {a b c : α} (h₁ : b ⊓ a = c ⊓ a) (h₂ : b ⊔ a = c ⊔ a) : b = c := le_antisymm (calc b ≤ (c ⊓ a) ⊔ b : le_sup_right ... = (c ⊔ b) ⊓ (a ⊔ b) : sup_inf_right ... = c ⊔ (c ⊓ a) : by rw [←h₁, sup_inf_left, ←h₂]; simp only [sup_comm, eq_self_iff_true] ... = c : sup_inf_self) (calc c ≤ (b ⊓ a) ⊔ c : le_sup_right ... = (b ⊔ c) ⊓ (a ⊔ c) : sup_inf_right ... = b ⊔ (b ⊓ a) : by rw [h₁, sup_inf_left, h₂]; simp only [sup_comm, eq_self_iff_true] ... = b : sup_inf_self) end distrib_lattice /- Lattices derived from linear orders -/ @[priority 100] -- see Note [lower instance priority] instance lattice_of_decidable_linear_order {α : Type u} [o : decidable_linear_order α] : lattice α := { sup := max, le_sup_left := le_max_left, le_sup_right := le_max_right, sup_le := assume a b c, max_le, inf := min, inf_le_left := min_le_left, inf_le_right := min_le_right, le_inf := assume a b c, le_min, ..o } theorem sup_eq_max [decidable_linear_order α] {x y : α} : x ⊔ y = max x y := rfl theorem inf_eq_min [decidable_linear_order α] {x y : α} : x ⊓ y = min x y := rfl @[priority 100] -- see Note [lower instance priority] instance distrib_lattice_of_decidable_linear_order {α : Type u} [o : decidable_linear_order α] : distrib_lattice α := { le_sup_inf := assume a b c, match le_total b c with | or.inl h := inf_le_left_of_le $ sup_le_sup_left (le_inf (le_refl b) h) _ | or.inr h := inf_le_right_of_le $ sup_le_sup_left (le_inf h (le_refl c)) _ end, ..lattice_of_decidable_linear_order } instance nat.distrib_lattice : distrib_lattice ℕ := by apply_instance namespace monotone lemma le_map_sup [semilattice_sup α] [semilattice_sup β] {f : α → β} (h : monotone f) (x y : α) : f x ⊔ f y ≤ f (x ⊔ y) := sup_le (h le_sup_left) (h le_sup_right) lemma map_inf_le [semilattice_inf α] [semilattice_inf β] {f : α → β} (h : monotone f) (x y : α) : f (x ⊓ y) ≤ f x ⊓ f y := le_inf (h inf_le_left) (h inf_le_right) end monotone namespace order_dual variable (α) instance [has_inf α] : has_sup (order_dual α) := ⟨((⊓) : α → α → α)⟩ instance [has_sup α] : has_inf (order_dual α) := ⟨((⊔) : α → α → α)⟩ instance [semilattice_inf α] : semilattice_sup (order_dual α) := { le_sup_left := @inf_le_left α _, le_sup_right := @inf_le_right α _, sup_le := assume a b c hca hcb, @le_inf α _ _ _ _ hca hcb, .. order_dual.partial_order α, .. order_dual.has_sup α } instance [semilattice_sup α] : semilattice_inf (order_dual α) := { inf_le_left := @le_sup_left α _, inf_le_right := @le_sup_right α _, le_inf := assume a b c hca hcb, @sup_le α _ _ _ _ hca hcb, .. order_dual.partial_order α, .. order_dual.has_inf α } instance [lattice α] : lattice (order_dual α) := { .. order_dual.semilattice_sup α, .. order_dual.semilattice_inf α } instance [distrib_lattice α] : distrib_lattice (order_dual α) := { le_sup_inf := assume x y z, le_of_eq inf_sup_left.symm, .. order_dual.lattice α } end order_dual namespace prod variables (α β) instance [has_sup α] [has_sup β] : has_sup (α × β) := ⟨λp q, ⟨p.1 ⊔ q.1, p.2 ⊔ q.2⟩⟩ instance [has_inf α] [has_inf β] : has_inf (α × β) := ⟨λp q, ⟨p.1 ⊓ q.1, p.2 ⊓ q.2⟩⟩ instance [semilattice_sup α] [semilattice_sup β] : semilattice_sup (α × β) := { sup_le := assume a b c h₁ h₂, ⟨sup_le h₁.1 h₂.1, sup_le h₁.2 h₂.2⟩, le_sup_left := assume a b, ⟨le_sup_left, le_sup_left⟩, le_sup_right := assume a b, ⟨le_sup_right, le_sup_right⟩, .. prod.partial_order α β, .. prod.has_sup α β } instance [semilattice_inf α] [semilattice_inf β] : semilattice_inf (α × β) := { le_inf := assume a b c h₁ h₂, ⟨le_inf h₁.1 h₂.1, le_inf h₁.2 h₂.2⟩, inf_le_left := assume a b, ⟨inf_le_left, inf_le_left⟩, inf_le_right := assume a b, ⟨inf_le_right, inf_le_right⟩, .. prod.partial_order α β, .. prod.has_inf α β } instance [lattice α] [lattice β] : lattice (α × β) := { .. prod.semilattice_inf α β, .. prod.semilattice_sup α β } instance [distrib_lattice α] [distrib_lattice β] : distrib_lattice (α × β) := { le_sup_inf := assume a b c, ⟨le_sup_inf, le_sup_inf⟩, .. prod.lattice α β } end prod
56d5ef6ac85cf384e460c57af5676babd7b18c3c
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/ring_theory/localization.lean
2249b1e935f68b389b5602fcbc6563c3411ee024
[ "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
60,930
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston -/ import data.equiv.ring import group_theory.monoid_localization import ring_theory.algebraic import ring_theory.integral_closure import ring_theory.non_zero_divisors /-! # Localizations of commutative rings We characterize the localization of a commutative ring `R` at a submonoid `M` up to isomorphism; that is, a commutative ring `S` is the localization of `R` at `M` iff we can find a ring homomorphism `f : R →+* S` satisfying 3 properties: 1. For all `y ∈ M`, `f y` is a unit; 2. For all `z : S`, there exists `(x, y) : R × M` such that `z * f y = f x`; 3. For all `x, y : R`, `f x = f y` iff there exists `c ∈ M` such that `x * c = y * c`. Given such a localization map `f : R →+* S`, we can define the surjection `localization_map.mk'` sending `(x, y) : R × M` to `f x * (f y)⁻¹`, and `localization_map.lift`, the homomorphism from `S` induced by a homomorphism from `R` which maps elements of `M` to invertible elements of the codomain. Similarly, given commutative rings `P, Q`, a submonoid `T` of `P` and a localization map for `T` from `P` to `Q`, then a homomorphism `g : R →+* P` such that `g(M) ⊆ T` induces a homomorphism of localizations, `localization_map.map`, from `S` to `Q`. We treat the special case of localizing away from an element in the sections `away_map` and `away`. We show the localization as a quotient type, defined in `group_theory.monoid_localization` as `submonoid.localization`, is a `comm_ring` and that the natural ring hom `of : R →+* localization M` is a localization map. We show that a localization at the complement of a prime ideal is a local ring. We prove some lemmas about the `R`-algebra structure of `S`. When `R` is an integral domain, we define `fraction_map R K` as an abbreviation for `localization (non_zero_divisors R) K`, the natural map to `R`'s field of fractions. We show that a `comm_ring` `K` which is the localization of an integral domain `R` at `R \ {0}` is a field. We use this to show the field of fractions as a quotient type, `fraction_ring`, is a field. ## Implementation notes In maths it is natural to reason up to isomorphism, but in Lean we cannot naturally `rewrite` one structure with an isomorphic one; one way around this is to isolate a predicate characterizing a structure up to isomorphism, and reason about things that satisfy the predicate. A ring localization map is defined to be a localization map of the underlying `comm_monoid` (a `submonoid.localization_map`) which is also a ring hom. To prove most lemmas about a `localization_map` `f` in this file we invoke the corresponding proof for the underlying `comm_monoid` localization map `f.to_localization_map`, which can be found in `group_theory.monoid_localization` and the namespace `submonoid.localization_map`. To apply a localization map `f` as a function, we use `f.to_map`, as coercions don't work well for this structure. To reason about the localization as a quotient type, use `mk_eq_of_mk'` and associated lemmas. These show the quotient map `mk : R → M → localization M` equals the surjection `localization_map.mk'` induced by the map `of : localization_map M (localization M)` (where `of` establishes the localization as a quotient type satisfies the characteristic predicate). The lemma `mk_eq_of_mk'` hence gives you access to the results in the rest of the file, which are about the `localization_map.mk'` induced by any localization map. We define a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that instances on `S` induced by `f` can 'know' the map needed to induce the instance. The proof that "a `comm_ring` `K` which is the localization of an integral domain `R` at `R \ {0}` is a field" is a `def` rather than an `instance`, so if you want to reason about a field of fractions `K`, assume `[field K]` instead of just `[comm_ring K]`. ## Tags localization, ring localization, commutative ring localization, characteristic predicate, commutative ring, field of fractions -/ variables {R : Type*} [comm_ring R] (M : submonoid R) (S : Type*) [comm_ring S] {P : Type*} [comm_ring P] open function set_option old_structure_cmd true /-- The type of ring homomorphisms satisfying the characteristic predicate: if `f : R →+* S` satisfies this predicate, then `S` is isomorphic to the localization of `R` at `M`. We later define an instance coercing a localization map `f` to its codomain `S` so that instances on `S` induced by `f` can 'know' the map needed to induce the instance. -/ @[nolint has_inhabited_instance] structure localization_map extends ring_hom R S, submonoid.localization_map M S /-- The ring hom underlying a `localization_map`. -/ add_decl_doc localization_map.to_ring_hom /-- The `comm_monoid` `localization_map` underlying a `comm_ring` `localization_map`. See `group_theory.monoid_localization` for its definition. -/ add_decl_doc localization_map.to_localization_map variables {M S} namespace ring_hom /-- Makes a localization map from a `comm_ring` hom satisfying the characteristic predicate. -/ def to_localization_map (f : R →+* S) (H1 : ∀ y : M, is_unit (f y)) (H2 : ∀ z, ∃ x : R × M, z * f x.2 = f x.1) (H3 : ∀ x y, f x = f y ↔ ∃ c : M, x * c = y * c) : localization_map M S := { map_units' := H1, surj' := H2, eq_iff_exists' := H3, .. f } end ring_hom /-- Makes a `comm_ring` localization map from an additive `comm_monoid` localization map of `comm_ring`s. -/ def submonoid.localization_map.to_ring_localization (f : submonoid.localization_map M S) (h : ∀ x y, f.to_map (x + y) = f.to_map x + f.to_map y) : localization_map M S := { ..ring_hom.mk' f.to_monoid_hom h, ..f } namespace localization_map variables (f : localization_map M S) /-- We define a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that instances on `S` induced by `f` can 'know` the map needed to induce the instance. -/ @[nolint unused_arguments has_inhabited_instance] def codomain (f : localization_map M S) := S instance : comm_ring f.codomain := by assumption instance {K : Type*} [field K] (f : localization_map M K) : field f.codomain := by assumption /-- Short for `to_ring_hom`; used for applying a localization map as a function. -/ abbreviation to_map := f.to_ring_hom lemma map_units (y : M) : is_unit (f.to_map y) := f.6 y lemma surj (z) : ∃ x : R × M, z * f.to_map x.2 = f.to_map x.1 := f.7 z lemma eq_iff_exists {x y} : f.to_map x = f.to_map y ↔ ∃ c : M, x * c = y * c := f.8 x y @[ext] lemma ext {f g : localization_map M S} (h : ∀ x, f.to_map x = g.to_map x) : f = g := begin cases f, cases g, simp only at *, exact funext h end lemma ext_iff {f g : localization_map M S} : f = g ↔ ∀ x, f.to_map x = g.to_map x := ⟨λ h x, h ▸ rfl, ext⟩ lemma to_map_injective : injective (@localization_map.to_map _ _ M S _) := λ _ _ h, ext $ ring_hom.ext_iff.1 h /-- Given `a : S`, `S` a localization of `R`, `is_integer a` iff `a` is in the image of the localization map from `R` to `S`. -/ def is_integer (a : S) : Prop := a ∈ set.range f.to_map variables {f} lemma is_integer_add {a b} (ha : f.is_integer a) (hb : f.is_integer b) : f.is_integer (a + b) := begin rcases ha with ⟨a', ha⟩, rcases hb with ⟨b', hb⟩, use a' + b', rw [f.to_map.map_add, ha, hb] end lemma is_integer_mul {a b} (ha : f.is_integer a) (hb : f.is_integer b) : f.is_integer (a * b) := begin rcases ha with ⟨a', ha⟩, rcases hb with ⟨b', hb⟩, use a' * b', rw [f.to_map.map_mul, ha, hb] end lemma is_integer_smul {a : R} {b} (hb : f.is_integer b) : f.is_integer (f.to_map a * b) := begin rcases hb with ⟨b', hb⟩, use a * b', rw [←hb, f.to_map.map_mul] end variables (f) /-- Each element `a : S` has an `M`-multiple which is an integer. This version multiplies `a` on the right, matching the argument order in `localization_map.surj`. -/ lemma exists_integer_multiple' (a : S) : ∃ (b : M), is_integer f (a * f.to_map b) := let ⟨⟨num, denom⟩, h⟩ := f.surj a in ⟨denom, set.mem_range.mpr ⟨num, h.symm⟩⟩ /-- Each element `a : S` has an `M`-multiple which is an integer. This version multiplies `a` on the left, matching the argument order in the `has_scalar` instance. -/ lemma exists_integer_multiple (a : S) : ∃ (b : M), is_integer f (f.to_map b * a) := by { simp_rw mul_comm _ a, apply exists_integer_multiple' } /-- Given `z : S`, `f.to_localization_map.sec z` is defined to be a pair `(x, y) : R × M` such that `z * f y = f x` (so this lemma is true by definition). -/ lemma sec_spec {f : localization_map M S} (z : S) : z * f.to_map (f.to_localization_map.sec z).2 = f.to_map (f.to_localization_map.sec z).1 := classical.some_spec $ f.surj z /-- Given `z : S`, `f.to_localization_map.sec z` is defined to be a pair `(x, y) : R × M` such that `z * f y = f x`, so this lemma is just an application of `S`'s commutativity. -/ lemma sec_spec' {f : localization_map M S} (z : S) : f.to_map (f.to_localization_map.sec z).1 = f.to_map (f.to_localization_map.sec z).2 * z := by rw [mul_comm, sec_spec] open_locale big_operators /-- We can clear the denominators of a finite set of fractions. -/ lemma exist_integer_multiples_of_finset (s : finset S) : ∃ (b : M), ∀ a ∈ s, is_integer f (f.to_map b * a) := begin haveI := classical.prop_decidable, use ∏ a in s, (f.to_localization_map.sec a).2, intros a ha, use (∏ x in s.erase a, (f.to_localization_map.sec x).2) * (f.to_localization_map.sec a).1, rw [ring_hom.map_mul, sec_spec', ←mul_assoc, ←f.to_map.map_mul], congr' 2, refine trans _ ((submonoid.subtype M).map_prod _ _).symm, rw [mul_comm, ←finset.prod_insert (s.not_mem_erase a), finset.insert_erase ha], refl, end lemma map_right_cancel {x y} {c : M} (h : f.to_map (c * x) = f.to_map (c * y)) : f.to_map x = f.to_map y := f.to_localization_map.map_right_cancel h lemma map_left_cancel {x y} {c : M} (h : f.to_map (x * c) = f.to_map (y * c)) : f.to_map x = f.to_map y := f.to_localization_map.map_left_cancel h lemma eq_zero_of_fst_eq_zero {z x} {y : M} (h : z * f.to_map y = f.to_map x) (hx : x = 0) : z = 0 := by rw [hx, f.to_map.map_zero] at h; exact (f.map_units y).mul_left_eq_zero.1 h /-- Given a localization map `f : R →+* S`, the surjection sending `(x, y) : R × M` to `f x * (f y)⁻¹`. -/ noncomputable def mk' (f : localization_map M S) (x : R) (y : M) : S := f.to_localization_map.mk' x y @[simp] lemma mk'_sec (z : S) : f.mk' (f.to_localization_map.sec z).1 (f.to_localization_map.sec z).2 = z := f.to_localization_map.mk'_sec _ lemma mk'_mul (x₁ x₂ : R) (y₁ y₂ : M) : f.mk' (x₁ * x₂) (y₁ * y₂) = f.mk' x₁ y₁ * f.mk' x₂ y₂ := f.to_localization_map.mk'_mul _ _ _ _ lemma mk'_one (x) : f.mk' x (1 : M) = f.to_map x := f.to_localization_map.mk'_one _ @[simp] lemma mk'_spec (x) (y : M) : f.mk' x y * f.to_map y = f.to_map x := f.to_localization_map.mk'_spec _ _ @[simp] lemma mk'_spec' (x) (y : M) : f.to_map y * f.mk' x y = f.to_map x := f.to_localization_map.mk'_spec' _ _ theorem eq_mk'_iff_mul_eq {x} {y : M} {z} : z = f.mk' x y ↔ z * f.to_map y = f.to_map x := f.to_localization_map.eq_mk'_iff_mul_eq theorem mk'_eq_iff_eq_mul {x} {y : M} {z} : f.mk' x y = z ↔ f.to_map x = z * f.to_map y := f.to_localization_map.mk'_eq_iff_eq_mul lemma mk'_surjective (z : S) : ∃ x (y : M), f.mk' x y = z := let ⟨r, hr⟩ := f.surj z in ⟨r.1, r.2, (f.eq_mk'_iff_mul_eq.2 hr).symm⟩ lemma mk'_eq_iff_eq {x₁ x₂} {y₁ y₂ : M} : f.mk' x₁ y₁ = f.mk' x₂ y₂ ↔ f.to_map (x₁ * y₂) = f.to_map (x₂ * y₁) := f.to_localization_map.mk'_eq_iff_eq lemma mk'_mem_iff {x} {y : M} {I : ideal S} : f.mk' x y ∈ I ↔ f.to_map x ∈ I := begin split; intro h, { rw [← mk'_spec f x y, mul_comm], exact I.smul_mem (f.to_map y) h }, { rw ← mk'_spec f x y at h, obtain ⟨b, hb⟩ := is_unit_iff_exists_inv.1 (map_units f y), have := I.smul_mem b h, rwa [smul_eq_mul, mul_comm, mul_assoc, hb, mul_one] at this } end protected lemma eq {a₁ b₁} {a₂ b₂ : M} : f.mk' a₁ a₂ = f.mk' b₁ b₂ ↔ ∃ c : M, a₁ * b₂ * c = b₁ * a₂ * c := f.to_localization_map.eq lemma eq_iff_eq (g : localization_map M P) {x y} : f.to_map x = f.to_map y ↔ g.to_map x = g.to_map y := f.to_localization_map.eq_iff_eq g.to_localization_map lemma mk'_eq_iff_mk'_eq (g : localization_map M P) {x₁ x₂} {y₁ y₂ : M} : f.mk' x₁ y₁ = f.mk' x₂ y₂ ↔ g.mk' x₁ y₁ = g.mk' x₂ y₂ := f.to_localization_map.mk'_eq_iff_mk'_eq g.to_localization_map lemma mk'_eq_of_eq {a₁ b₁ : R} {a₂ b₂ : M} (H : b₁ * a₂ = a₁ * b₂) : f.mk' a₁ a₂ = f.mk' b₁ b₂ := f.to_localization_map.mk'_eq_of_eq H @[simp] lemma mk'_self {x : R} (hx : x ∈ M) : f.mk' x ⟨x, hx⟩ = 1 := f.to_localization_map.mk'_self _ hx @[simp] lemma mk'_self' {x : M} : f.mk' x x = 1 := f.to_localization_map.mk'_self' _ lemma mk'_self'' {x : M} : f.mk' x.1 x = 1 := f.mk'_self' lemma mul_mk'_eq_mk'_of_mul (x y : R) (z : M) : f.to_map x * f.mk' y z = f.mk' (x * y) z := f.to_localization_map.mul_mk'_eq_mk'_of_mul _ _ _ lemma mk'_eq_mul_mk'_one (x : R) (y : M) : f.mk' x y = f.to_map x * f.mk' 1 y := (f.to_localization_map.mul_mk'_one_eq_mk' _ _).symm @[simp] lemma mk'_mul_cancel_left (x : R) (y : M) : f.mk' (y * x) y = f.to_map x := f.to_localization_map.mk'_mul_cancel_left _ _ lemma mk'_mul_cancel_right (x : R) (y : M) : f.mk' (x * y) y = f.to_map x := f.to_localization_map.mk'_mul_cancel_right _ _ @[simp] lemma mk'_mul_mk'_eq_one (x y : M) : f.mk' x y * f.mk' y x = 1 := by rw [←f.mk'_mul, mul_comm]; exact f.mk'_self _ lemma mk'_mul_mk'_eq_one' (x : R) (y : M) (h : x ∈ M) : f.mk' x y * f.mk' y ⟨x, h⟩ = 1 := f.mk'_mul_mk'_eq_one ⟨x, h⟩ _ lemma is_unit_comp (j : S →+* P) (y : M) : is_unit (j.comp f.to_map y) := f.to_localization_map.is_unit_comp j.to_monoid_hom _ /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s `g : R →+* P` such that `g(M) ⊆ units P`, `f x = f y → g x = g y` for all `x y : R`. -/ lemma eq_of_eq {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) {x y} (h : f.to_map x = f.to_map y) : g x = g y := @submonoid.localization_map.eq_of_eq _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom hg _ _ h lemma mk'_add (x₁ x₂ : R) (y₁ y₂ : M) : f.mk' (x₁ * y₂ + x₂ * y₁) (y₁ * y₂) = f.mk' x₁ y₁ + f.mk' x₂ y₂ := f.mk'_eq_iff_eq_mul.2 $ eq.symm begin rw [mul_comm (_ + _), mul_add, mul_mk'_eq_mk'_of_mul, ←eq_sub_iff_add_eq, mk'_eq_iff_eq_mul, mul_comm _ (f.to_map _), mul_sub, eq_sub_iff_add_eq, ←eq_sub_iff_add_eq', ←mul_assoc, ←f.to_map.map_mul, mul_mk'_eq_mk'_of_mul, mk'_eq_iff_eq_mul], simp only [f.to_map.map_add, submonoid.coe_mul, f.to_map.map_mul], ring_exp, end /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s `g : R →+* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from `S` to `P` sending `z : S` to `g x * (g y)⁻¹`, where `(x, y) : R × M` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def lift {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) : S →+* P := ring_hom.mk' (@submonoid.localization_map.lift _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom hg) $ begin intros x y, rw [f.to_localization_map.lift_spec, mul_comm, add_mul, ←sub_eq_iff_eq_add, eq_comm, f.to_localization_map.lift_spec_mul, mul_comm _ (_ - _), sub_mul, eq_sub_iff_add_eq', ←eq_sub_iff_add_eq, mul_assoc, f.to_localization_map.lift_spec_mul], show g _ * (g _ * g _) = g _ * (g _ * g _ - g _ * g _), repeat {rw ←g.map_mul}, rw [←g.map_sub, ←g.map_mul], apply f.eq_of_eq hg, erw [f.to_map.map_mul, sec_spec', mul_sub, f.to_map.map_sub], simp only [f.to_map.map_mul, sec_spec'], ring_exp, end variables {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s `g : R →* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from `S` to `P` maps `f x * (f y)⁻¹` to `g x * (g y)⁻¹` for all `x : R, y ∈ M`. -/ lemma lift_mk' (x y) : f.lift hg (f.mk' x y) = g x * ↑(is_unit.lift_right (g.to_monoid_hom.mrestrict M) hg y)⁻¹ := f.to_localization_map.lift_mk' _ _ _ lemma lift_mk'_spec (x v) (y : M) : f.lift hg (f.mk' x y) = v ↔ g x = g y * v := f.to_localization_map.lift_mk'_spec _ _ _ _ @[simp] lemma lift_eq (x : R) : f.lift hg (f.to_map x) = g x := f.to_localization_map.lift_eq _ _ lemma lift_eq_iff {x y : R × M} : f.lift hg (f.mk' x.1 x.2) = f.lift hg (f.mk' y.1 y.2) ↔ g (x.1 * y.2) = g (y.1 * x.2) := f.to_localization_map.lift_eq_iff _ @[simp] lemma lift_comp : (f.lift hg).comp f.to_map = g := ring_hom.ext $ monoid_hom.ext_iff.1 $ f.to_localization_map.lift_comp _ @[simp] lemma lift_of_comp (j : S →+* P) : f.lift (f.is_unit_comp j) = j := ring_hom.ext $ monoid_hom.ext_iff.1 $ f.to_localization_map.lift_of_comp j.to_monoid_hom lemma epic_of_localization_map {j k : S →+* P} (h : ∀ a, j.comp f.to_map a = k.comp f.to_map a) : j = k := ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.epic_of_localization_map _ _ _ _ _ _ _ f.to_localization_map j.to_monoid_hom k.to_monoid_hom h lemma lift_unique {j : S →+* P} (hj : ∀ x, j (f.to_map x) = g x) : f.lift hg = j := ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.lift_unique _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom hg j.to_monoid_hom hj @[simp] lemma lift_id (x) : f.lift f.map_units x = x := f.to_localization_map.lift_id _ /-- Given two localization maps `f : R →+* S, k : R →+* P` for a submonoid `M ⊆ R`, the hom from `P` to `S` induced by `f` is left inverse to the hom from `S` to `P` induced by `k`. -/ @[simp] lemma lift_left_inverse {k : localization_map M S} (z : S) : k.lift f.map_units (f.lift k.map_units z) = z := f.to_localization_map.lift_left_inverse _ lemma lift_surjective_iff : surjective (f.lift hg) ↔ ∀ v : P, ∃ x : R × M, v * g x.2 = g x.1 := f.to_localization_map.lift_surjective_iff hg lemma lift_injective_iff : injective (f.lift hg) ↔ ∀ x y, f.to_map x = f.to_map y ↔ g x = g y := f.to_localization_map.lift_injective_iff hg variables {T : submonoid P} (hy : ∀ y : M, g y ∈ T) {Q : Type*} [comm_ring Q] (k : localization_map T Q) /-- Given a `comm_ring` homomorphism `g : R →+* P` where for submonoids `M ⊆ R, T ⊆ P` we have `g(M) ⊆ T`, the induced ring homomorphism from the localization of `R` at `M` to the localization of `P` at `T`: if `f : R →+* S` and `k : P →+* Q` are localization maps for `M` and `T` respectively, we send `z : S` to `k (g x) * (k (g y))⁻¹`, where `(x, y) : R × M` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def map : S →+* Q := @lift _ _ _ _ _ _ _ f (k.to_map.comp g) $ λ y, k.map_units ⟨g y, hy y⟩ variables {k} lemma map_eq (x) : f.map hy k (f.to_map x) = k.to_map (g x) := f.lift_eq (λ y, k.map_units ⟨g y, hy y⟩) x @[simp] lemma map_comp : (f.map hy k).comp f.to_map = k.to_map.comp g := f.lift_comp $ λ y, k.map_units ⟨g y, hy y⟩ lemma map_mk' (x) (y : M) : f.map hy k (f.mk' x y) = k.mk' (g x) ⟨g y, hy y⟩ := @submonoid.localization_map.map_mk' _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom _ hy _ _ k.to_localization_map _ _ @[simp] lemma map_id (z : S) : f.map (λ y, show ring_hom.id R y ∈ M, from y.2) f z = z := f.lift_id _ /-- If `comm_ring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ lemma map_comp_map {A : Type*} [comm_ring A] {U : submonoid A} {W} [comm_ring W] (j : localization_map U W) {l : P →+* A} (hl : ∀ w : T, l w ∈ U) : (k.map hl j).comp (f.map hy k) = f.map (λ x, show l.comp g x ∈ U, from hl ⟨g x, hy x⟩) j := ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.map_comp_map _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom _ hy _ _ k.to_localization_map _ _ _ _ _ j.to_localization_map l.to_monoid_hom hl /-- If `comm_ring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ lemma map_map {A : Type*} [comm_ring A] {U : submonoid A} {W} [comm_ring W] (j : localization_map U W) {l : P →+* A} (hl : ∀ w : T, l w ∈ U) (x) : k.map hl j (f.map hy k x) = f.map (λ x, show l.comp g x ∈ U, from hl ⟨g x, hy x⟩) j x := by rw ←f.map_comp_map hy j hl; refl /-- Given localization maps `f : R →+* S, k : P →+* Q` for submonoids `M, T` respectively, an isomorphism `j : R ≃+* P` such that `j(M) = T` induces an isomorphism of localizations `S ≃+* Q`. -/ noncomputable def ring_equiv_of_ring_equiv (k : localization_map T Q) (h : R ≃+* P) (H : M.map h.to_monoid_hom = T) : S ≃+* Q := (f.to_localization_map.mul_equiv_of_mul_equiv k.to_localization_map H).to_ring_equiv $ (@lift _ _ _ _ _ _ _ f (k.to_map.comp h.to_ring_hom) (λ y, k.map_units ⟨(h y), H ▸ set.mem_image_of_mem h y.2⟩)).map_add @[simp] lemma ring_equiv_of_ring_equiv_eq_map_apply {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x) : f.ring_equiv_of_ring_equiv k j H x = f.map (λ y : M, show j.to_monoid_hom y ∈ T, from H ▸ set.mem_image_of_mem j y.2) k x := rfl lemma ring_equiv_of_ring_equiv_eq_map {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) : (f.ring_equiv_of_ring_equiv k j H).to_monoid_hom = f.map (λ y : M, show j.to_monoid_hom y ∈ T, from H ▸ set.mem_image_of_mem j y.2) k := rfl @[simp] lemma ring_equiv_of_ring_equiv_eq {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x) : f.ring_equiv_of_ring_equiv k j H (f.to_map x) = k.to_map (j x) := f.to_localization_map.mul_equiv_of_mul_equiv_eq H _ lemma ring_equiv_of_ring_equiv_mk' {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x y) : f.ring_equiv_of_ring_equiv k j H (f.mk' x y) = k.mk' (j x) ⟨j y, H ▸ set.mem_image_of_mem j y.2⟩ := f.to_localization_map.mul_equiv_of_mul_equiv_mk' H _ _ section away_map variables (x : R) /-- Given `x : R`, the type of homomorphisms `f : R →* S` such that `S` is isomorphic to the localization of `R` at the submonoid generated by `x`. -/ @[reducible] def away_map (S' : Type*) [comm_ring S'] := localization_map (submonoid.powers x) S' variables (F : away_map x S) /-- Given `x : R` and a localization map `F : R →+* S` away from `x`, `inv_self` is `(F x)⁻¹`. -/ noncomputable def away_map.inv_self : S := F.mk' 1 ⟨x, submonoid.mem_powers _⟩ /-- Given `x : R`, a localization map `F : R →+* S` away from `x`, and a map of `comm_ring`s `g : R →+* P` such that `g x` is invertible, the homomorphism induced from `S` to `P` sending `z : S` to `g y * (g x)⁻ⁿ`, where `y : R, n : ℕ` are such that `z = F y * (F x)⁻ⁿ`. -/ noncomputable def away_map.lift (hg : is_unit (g x)) : S →+* P := localization_map.lift F $ λ y, show is_unit (g y.1), begin obtain ⟨n, hn⟩ := y.2, rw [←hn, g.map_pow], exact is_unit.map (monoid_hom.of $ ((^ n) : P → P)) hg, end @[simp] lemma away_map.lift_eq (hg : is_unit (g x)) (a : R) : F.lift x hg (F.to_map a) = g a := lift_eq _ _ _ @[simp] lemma away_map.lift_comp (hg : is_unit (g x)) : (F.lift x hg).comp F.to_map = g := lift_comp _ _ /-- Given `x y : R` and localization maps `F : R →+* S, G : R →+* P` away from `x` and `x * y` respectively, the homomorphism induced from `S` to `P`. -/ noncomputable def away_to_away_right (y : R) (G : away_map (x * y) P) : S →* P := F.lift x $ show is_unit (G.to_map x), from is_unit_of_mul_eq_one (G.to_map x) (G.mk' y ⟨x * y, submonoid.mem_powers _⟩) $ by rw [mul_mk'_eq_mk'_of_mul, mk'_self] end away_map end localization_map namespace localization variables {M} instance : has_add (localization M) := ⟨λ z w, con.lift_on₂ z w (λ x y : R × M, mk ((x.2 : R) * y.1 + y.2 * x.1) (x.2 * y.2)) $ λ r1 r2 r3 r4 h1 h2, (con.eq _).2 begin rw r_eq_r' at h1 h2 ⊢, cases h1 with t₅ ht₅, cases h2 with t₆ ht₆, use t₆ * t₅, calc ((r1.2 : R) * r2.1 + r2.2 * r1.1) * (r3.2 * r4.2) * (t₆ * t₅) = (r2.1 * r4.2 * t₆) * (r1.2 * r3.2 * t₅) + (r1.1 * r3.2 * t₅) * (r2.2 * r4.2 * t₆) : by ring ... = (r3.2 * r4.1 + r4.2 * r3.1) * (r1.2 * r2.2) * (t₆ * t₅) : by rw [ht₆, ht₅]; ring end⟩ instance : has_neg (localization M) := ⟨λ z, con.lift_on z (λ x : R × M, mk (-x.1) x.2) $ λ r1 r2 h, (con.eq _).2 begin rw r_eq_r' at h ⊢, cases h with t ht, use t, rw [neg_mul_eq_neg_mul_symm, neg_mul_eq_neg_mul_symm, ht], ring, end⟩ instance : has_zero (localization M) := ⟨mk 0 1⟩ private meta def tac := `[{ intros, refine quotient.sound' (r_of_eq _), simp only [prod.snd_mul, prod.fst_mul, submonoid.coe_mul], ring }] instance : comm_ring (localization M) := { zero := 0, one := 1, add := (+), mul := (*), add_assoc := λ m n k, quotient.induction_on₃' m n k (by tac), zero_add := λ y, quotient.induction_on' y (by tac), add_zero := λ y, quotient.induction_on' y (by tac), neg := has_neg.neg, add_left_neg := λ y, quotient.induction_on' y (by tac), add_comm := λ y z, quotient.induction_on₂' z y (by tac), left_distrib := λ m n k, quotient.induction_on₃' m n k (by tac), right_distrib := λ m n k, quotient.induction_on₃' m n k (by tac), ..localization.comm_monoid M } variables (M) /-- Natural hom sending `x : R`, `R` a `comm_ring`, to the equivalence class of `(x, 1)` in the localization of `R` at a submonoid. -/ def of : localization_map M (localization M) := (localization.monoid_of M).to_ring_localization $ λ x y, (con.eq _).2 $ r_of_eq $ by simp [add_comm] variables {M} lemma monoid_of_eq_of (x) : (monoid_of M).to_map x = (of M).to_map x := rfl lemma mk_one_eq_of (x) : mk x 1 = (of M).to_map x := rfl lemma mk_eq_mk'_apply (x y) : mk x y = (of M).mk' x y := mk_eq_monoid_of_mk'_apply _ _ @[simp] lemma mk_eq_mk' : mk = (of M).mk' := mk_eq_monoid_of_mk' variables (f : localization_map M S) /-- Given a localization map `f : R →+* S` for a submonoid `M`, we get an isomorphism between the localization of `R` at `M` as a quotient type and `S`. -/ noncomputable def ring_equiv_of_quotient : localization M ≃+* S := (mul_equiv_of_quotient f.to_localization_map).to_ring_equiv $ ((of M).lift f.map_units).map_add variables {f} @[simp] lemma ring_equiv_of_quotient_apply (x) : ring_equiv_of_quotient f x = (of M).lift f.map_units x := rfl @[simp] lemma ring_equiv_of_quotient_mk' (x y) : ring_equiv_of_quotient f ((of M).mk' x y) = f.mk' x y := mul_equiv_of_quotient_mk' _ _ lemma ring_equiv_of_quotient_mk (x y) : ring_equiv_of_quotient f (mk x y) = f.mk' x y := mul_equiv_of_quotient_mk _ _ @[simp] lemma ring_equiv_of_quotient_of (x) : ring_equiv_of_quotient f ((of M).to_map x) = f.to_map x := mul_equiv_of_quotient_monoid_of _ @[simp] lemma ring_equiv_of_quotient_symm_mk' (x y) : (ring_equiv_of_quotient f).symm (f.mk' x y) = (of M).mk' x y := mul_equiv_of_quotient_symm_mk' _ _ lemma ring_equiv_of_quotient_symm_mk (x y) : (ring_equiv_of_quotient f).symm (f.mk' x y) = mk x y := mul_equiv_of_quotient_symm_mk _ _ @[simp] lemma ring_equiv_of_quotient_symm_of (x) : (ring_equiv_of_quotient f).symm (f.to_map x) = (of M).to_map x := mul_equiv_of_quotient_symm_monoid_of _ section away variables (x : R) /-- Given `x : R`, the natural hom sending `y : R`, `R` a `comm_ring`, to the equivalence class of `(y, 1)` in the localization of `R` at the submonoid generated by `x`. -/ @[reducible] def away.of : localization_map.away_map x (away x) := of (submonoid.powers x) @[simp] lemma away.mk_eq_mk' : mk = (away.of x).mk' := mk_eq_mk' /-- Given `x : R` and a localization map `f : R →+* S` away from `x`, we get an isomorphism between the localization of `R` at the submonoid generated by `x` as a quotient type and `S`. -/ noncomputable def away.ring_equiv_of_quotient (f : localization_map.away_map x S) : away x ≃+* S := ring_equiv_of_quotient f end away end localization variables {M} section at_prime variables (I : ideal R) [hp : I.is_prime] include hp namespace ideal /-- The complement of a prime ideal `I ⊆ R` is a submonoid of `R`. -/ def prime_compl : submonoid R := { carrier := (Iᶜ : set R), one_mem' := by convert I.ne_top_iff_one.1 hp.1; refl, mul_mem' := λ x y hnx hny hxy, or.cases_on (hp.2 hxy) hnx hny } end ideal namespace localization_map variables (S) /-- A localization map from `R` to `S` where the submonoid is the complement of a prime ideal of `R`. -/ @[reducible] def at_prime := localization_map I.prime_compl S end localization_map namespace localization /-- The localization of `R` at the complement of a prime ideal, as a quotient type. -/ @[reducible] def at_prime := localization I.prime_compl end localization namespace localization_map variables {I} /-- When `f` is a localization map from `R` at the complement of a prime ideal `I`, we use a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that the `local_ring` instance on `S` can 'know' the map needed to induce the instance. -/ instance at_prime.local_ring (f : at_prime S I) : local_ring f.codomain := local_of_nonunits_ideal (λ hze, begin rw [←f.to_map.map_one, ←f.to_map.map_zero] at hze, obtain ⟨t, ht⟩ := f.eq_iff_exists.1 hze, exact ((show (t : R) ∉ I, from t.2) (have htz : (t : R) = 0, by simpa using ht.symm, htz.symm ▸ I.zero_mem)) end) (begin intros x y hx hy hu, cases is_unit_iff_exists_inv.1 hu with z hxyz, have : ∀ {r s}, f.mk' r s ∈ nonunits S → r ∈ I, from λ r s, not_imp_comm.1 (λ nr, is_unit_iff_exists_inv.2 ⟨f.mk' s ⟨r, nr⟩, f.mk'_mul_mk'_eq_one' _ _ nr⟩), rcases f.mk'_surjective x with ⟨rx, sx, hrx⟩, rcases f.mk'_surjective y with ⟨ry, sy, hry⟩, rcases f.mk'_surjective z with ⟨rz, sz, hrz⟩, rw [←hrx, ←hry, ←hrz, ←f.mk'_add, ←f.mk'_mul, ←f.mk'_self I.prime_compl.one_mem] at hxyz, rw ←hrx at hx, rw ←hry at hy, cases f.eq.1 hxyz with t ht, simp only [mul_one, one_mul, submonoid.coe_mul, subtype.coe_mk] at ht, rw [←sub_eq_zero, ←sub_mul] at ht, have hr := (hp.mem_or_mem_of_mul_eq_zero ht).resolve_right t.2, have := I.neg_mem_iff.1 ((ideal.add_mem_iff_right _ _).1 hr), { exact not_or (mt hp.mem_or_mem (not_or sx.2 sy.2)) sz.2 (hp.mem_or_mem this)}, { exact I.mul_mem_right (I.add_mem (I.mul_mem_right (this hx)) (I.mul_mem_right (this hy)))} end) end localization_map namespace localization /-- The localization of `R` at the complement of a prime ideal is a local ring. -/ instance at_prime.local_ring : local_ring (localization I.prime_compl) := localization_map.at_prime.local_ring (of I.prime_compl) end localization end at_prime namespace localization_map variables (f : localization_map M S) section ideals /-- Explicit characterization of the ideal given by `ideal.map f.to_map I`. In practice, this ideal differs only in that the carrier set is defined explicitly. This definition is only meant to be used in proving `mem_map_to_map_iff`, and any proof that needs to refer to the explicit carrier set should use that theorem. -/ private def to_map_ideal (I : ideal R) : ideal S := { carrier := { z : S | ∃ x : I × M, z * (f.to_map x.2) = f.to_map x.1}, zero_mem' := ⟨⟨0, 1⟩, by simp⟩, add_mem' := begin rintros a b ⟨a', ha⟩ ⟨b', hb⟩, use ⟨a'.2 * b'.1 + b'.2 * a'.1, I.add_mem (I.smul_mem _ b'.1.2) (I.smul_mem _ a'.1.2)⟩, use a'.2 * b'.2, simp only [ring_hom.map_add, submodule.coe_mk, submonoid.coe_mul, ring_hom.map_mul], rw [add_mul, ← mul_assoc a, ha, mul_comm (f.to_map a'.2) (f.to_map b'.2), ← mul_assoc b, hb], ring end, smul_mem' := begin rintros c x ⟨x', hx⟩, obtain ⟨c', hc⟩ := localization_map.surj f c, use ⟨c'.1 * x'.1, I.smul_mem c'.1 x'.1.2⟩, use c'.2 * x'.2, simp only [←hx, ←hc, smul_eq_mul, submodule.coe_mk, submonoid.coe_mul, ring_hom.map_mul], ring end } theorem mem_map_to_map_iff {I : ideal R} {z} : z ∈ ideal.map f.to_map I ↔ ∃ x : I × M, z * (f.to_map x.2) = f.to_map x.1 := begin split, { show _ → z ∈ to_map_ideal f I, refine λ h, ideal.mem_Inf.1 h (λ z hz, _), obtain ⟨y, hy⟩ := hz, use ⟨⟨⟨y, hy.left⟩, 1⟩, by simp [hy.right]⟩ }, { rintros ⟨⟨a, s⟩, h⟩, rw [← ideal.unit_mul_mem_iff_mem _ (map_units f s), mul_comm], exact h.symm ▸ ideal.mem_map_of_mem a.2 } end theorem map_comap (J : ideal S) : ideal.map f.to_map (ideal.comap f.to_map J) = J := le_antisymm (ideal.map_le_iff_le_comap.2 (le_refl _)) $ λ x hJ, begin obtain ⟨r, s, hx⟩ := f.mk'_surjective x, rw ←hx at ⊢ hJ, exact ideal.mul_mem_right _ (ideal.mem_map_of_mem (show f.to_map r ∈ J, from f.mk'_spec r s ▸ @ideal.mul_mem_right _ _ J (f.mk' r s) (f.to_map s) hJ)), end theorem comap_map_of_is_prime_disjoint (I : ideal R) (hI : I.is_prime) (hM : disjoint (M : set R) I) : ideal.comap f.to_map (ideal.map f.to_map I) = I := begin refine le_antisymm (λ a ha, _) ideal.le_comap_map, rw [ideal.mem_comap, mem_map_to_map_iff] at ha, obtain ⟨⟨b, s⟩, h⟩ := ha, have : f.to_map (a * ↑s - b) = 0 := by simpa [sub_eq_zero] using h, rw [← f.to_map.map_zero, eq_iff_exists] at this, obtain ⟨c, hc⟩ := this, have : a * s ∈ I, { rw zero_mul at hc, let this : (a * ↑s - ↑b) * ↑c ∈ I := hc.symm ▸ I.zero_mem, cases hI.right this with h1 h2, { simpa using I.add_mem h1 b.2 }, { exfalso, refine hM ⟨c.2, h2⟩ } }, cases hI.right this with h1 h2, { exact h1 }, { exfalso, refine hM ⟨s.2, h2⟩ } end /-- If `S` is the localization of `R` at a submonoid, the ordering of ideals of `S` is embedded in the ordering of ideals of `R`. -/ def order_embedding : ideal S ↪o ideal R := { to_fun := λ J, ideal.comap f.to_map J, inj' := function.left_inverse.injective f.map_comap, map_rel_iff' := λ J₁ J₂, ⟨ideal.comap_mono, λ hJ, f.map_comap J₁ ▸ f.map_comap J₂ ▸ ideal.map_mono hJ⟩ } /-- If `R` is a ring, then prime ideals in the localization at `M` correspond to prime ideals in the original ring `R` that are disjoint from `M`. This lemma gives the particular case for an ideal and its comap, see `le_rel_iso_of_prime` for the more general relation isomorphism -/ lemma is_prime_iff_is_prime_disjoint (J : ideal S) : J.is_prime ↔ (ideal.comap f.to_map J).is_prime ∧ disjoint (M : set R) ↑(ideal.comap f.to_map J) := begin split, { refine λ h, ⟨⟨_, _⟩, λ m hm, h.1 (ideal.eq_top_of_is_unit_mem _ hm.2 (map_units f ⟨m, hm.left⟩))⟩, { refine λ hJ, h.left _, rw [eq_top_iff, (order_embedding f).map_rel_iff], exact le_of_eq hJ.symm }, { intros x y hxy, rw [ideal.mem_comap, ring_hom.map_mul] at hxy, exact h.right hxy } }, { refine λ h, ⟨λ hJ, h.left.left (eq_top_iff.2 _), _⟩, { rwa [eq_top_iff, (order_embedding f).map_rel_iff] at hJ }, { intros x y hxy, obtain ⟨a, s, ha⟩ := mk'_surjective f x, obtain ⟨b, t, hb⟩ := mk'_surjective f y, have : f.mk' (a * b) (s * t) ∈ J := by rwa [mk'_mul, ha, hb], rw [mk'_mem_iff, ← ideal.mem_comap] at this, replace this := h.left.right this, rw [ideal.mem_comap, ideal.mem_comap] at this, rwa [← ha, ← hb, mk'_mem_iff, mk'_mem_iff] } } end /-- If `R` is a ring, then prime ideals in the localization at `M` correspond to prime ideals in the original ring `R` that are disjoint from `M`. This lemma gives the particular case for an ideal and its map, see `le_rel_iso_of_prime` for the more general relation isomorphism, and the reverse implication -/ lemma is_prime_of_is_prime_disjoint (I : ideal R) (hp : I.is_prime) (hd : disjoint (M : set R) ↑I) : (ideal.map f.to_map I).is_prime := begin rw [is_prime_iff_is_prime_disjoint f, comap_map_of_is_prime_disjoint f I hp hd], exact ⟨hp, hd⟩ end /-- If `R` is a ring, then prime ideals in the localization at `M` correspond to prime ideals in the original ring `R` that are disjoint from `M` -/ def order_iso_of_prime (f : localization_map M S) : {p : ideal S // p.is_prime} ≃o {p : ideal R // p.is_prime ∧ disjoint (M : set R) ↑p} := { to_fun := λ p, ⟨ideal.comap f.to_map p.1, (is_prime_iff_is_prime_disjoint f p.1).1 p.2⟩, inv_fun := λ p, ⟨ideal.map f.to_map p.1, is_prime_of_is_prime_disjoint f p.1 p.2.1 p.2.2⟩, left_inv := λ J, subtype.eq (map_comap f J), right_inv := λ I, subtype.eq (comap_map_of_is_prime_disjoint f I.1 I.2.1 I.2.2), map_rel_iff' := λ I I', ⟨λ h x hx, h hx, λ h, (show I.val ≤ I'.val, from (map_comap f I.val) ▸ (map_comap f I'.val) ▸ (ideal.map_mono h))⟩ } end ideals /-! ### `algebra` section Defines the `R`-algebra instance on a copy of `S` carrying the data of the localization map `f` needed to induce the `R`-algebra structure. -/ /-- We use a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that the `R`-algebra instance on `S` can 'know' the map needed to induce the `R`-algebra structure. -/ instance : algebra R f.codomain := f.to_map.to_algebra end localization_map namespace localization instance : algebra R (localization M) := localization_map.algebra (of M) end localization namespace localization_map variables (f : localization_map M S) @[simp] lemma of_id (a : R) : (algebra.of_id R f.codomain) a = f.to_map a := rfl @[simp] lemma algebra_map_eq : algebra_map R f.codomain = f.to_map := rfl variables (f) /-- Localization map `f` from `R` to `S` as an `R`-linear map. -/ def lin_coe : R →ₗ[R] f.codomain := { to_fun := f.to_map, map_add' := f.to_map.map_add, map_smul' := f.to_map.map_mul } /-- Map from ideals of `R` to submodules of `S` induced by `f`. -/ -- This was previously a `has_coe` instance, but if `f.codomain = R` then this will loop. -- It could be a `has_coe_t` instance, but we keep it explicit here to avoid slowing down -- the rest of the library. def coe_submodule (I : ideal R) : submodule R f.codomain := submodule.map f.lin_coe I variables {f} lemma mem_coe_submodule (I : ideal R) {x : S} : x ∈ f.coe_submodule I ↔ ∃ y : R, y ∈ I ∧ f.to_map y = x := iff.rfl @[simp] lemma lin_coe_apply {x} : f.lin_coe x = f.to_map x := rfl variables {g : R →+* P} variables {T : submonoid P} (hy : ∀ y : M, g y ∈ T) {Q : Type*} [comm_ring Q] (k : localization_map T Q) lemma map_smul (x : f.codomain) (z : R) : f.map hy k (z • x : f.codomain) = @has_scalar.smul P k.codomain _ (g z) (f.map hy k x) := show f.map hy k (f.to_map z * x) = k.to_map (g z) * f.map hy k x, by rw [ring_hom.map_mul, map_eq] section integer_normalization open finsupp polynomial open_locale classical /-- `coeff_integer_normalization p` gives the coefficients of the polynomial `integer_normalization p` -/ noncomputable def coeff_integer_normalization (p : polynomial f.codomain) (i : ℕ) : R := if hi : i ∈ p.support then classical.some (classical.some_spec (f.exist_integer_multiples_of_finset (p.support.image p.coeff)) (p.coeff i) (finset.mem_image.mpr ⟨i, hi, rfl⟩)) else 0 lemma coeff_integer_normalization_mem_support (p : polynomial f.codomain) (i : ℕ) (h : coeff_integer_normalization p i ≠ 0) : i ∈ p.support := begin contrapose h, rw [ne.def, not_not, coeff_integer_normalization, dif_neg h] end /-- `integer_normalization g` normalizes `g` to have integer coefficients by clearing the denominators -/ noncomputable def integer_normalization : polynomial f.codomain → polynomial R := λ p, on_finset p.support (coeff_integer_normalization p) (coeff_integer_normalization_mem_support p) @[simp] lemma integer_normalization_coeff (p : polynomial f.codomain) (i : ℕ) : (integer_normalization p).coeff i = coeff_integer_normalization p i := rfl lemma integer_normalization_spec (p : polynomial f.codomain) : ∃ (b : M), ∀ i, f.to_map ((integer_normalization p).coeff i) = f.to_map b * p.coeff i := begin use classical.some (f.exist_integer_multiples_of_finset (p.support.image p.coeff)), intro i, rw [integer_normalization_coeff, coeff_integer_normalization], split_ifs with hi, { exact classical.some_spec (classical.some_spec (f.exist_integer_multiples_of_finset (p.support.image p.coeff)) (p.coeff i) (finset.mem_image.mpr ⟨i, hi, rfl⟩)) }, { convert (_root_.mul_zero (f.to_map _)).symm, { exact f.to_ring_hom.map_zero }, { exact finsupp.not_mem_support_iff.mp hi } } end lemma integer_normalization_map_to_map (p : polynomial f.codomain) : ∃ (b : M), (integer_normalization p).map f.to_map = f.to_map b • p := let ⟨b, hb⟩ := integer_normalization_spec p in ⟨b, polynomial.ext (λ i, by { rw coeff_map, exact hb i })⟩ variables {R' : Type*} [comm_ring R'] lemma integer_normalization_eval₂_eq_zero (g : f.codomain →+* R') (p : polynomial f.codomain) {x : R'} (hx : eval₂ g x p = 0) : eval₂ (g.comp f.to_map) x (integer_normalization p) = 0 := let ⟨b, hb⟩ := integer_normalization_map_to_map p in trans (eval₂_map f.to_map g x).symm (by rw [hb, eval₂_smul, hx, smul_zero]) lemma integer_normalization_aeval_eq_zero [algebra R R'] [algebra f.codomain R'] [is_scalar_tower R f.codomain R'] (p : polynomial f.codomain) {x : R'} (hx : aeval x p = 0) : aeval x (integer_normalization p) = 0 := by rw [aeval_def, is_scalar_tower.algebra_map_eq R f.codomain R', algebra_map_eq, integer_normalization_eval₂_eq_zero _ _ hx] end integer_normalization variables {R} {A K : Type*} [integral_domain A] lemma to_map_eq_zero_iff (f : localization_map M S) {x : R} (hM : M ≤ non_zero_divisors R) : f.to_map x = 0 ↔ x = 0 := begin rw ← f.to_map.map_zero, split; intro h, { cases f.eq_iff_exists.mp h with c hc, rw zero_mul at hc, exact hM c.2 x hc }, { rw h }, end lemma injective (f : localization_map M S) (hM : M ≤ non_zero_divisors R) : injective f.to_map := begin rw ring_hom.injective_iff f.to_map, intros a ha, rw [← f.to_map.map_zero, f.eq_iff_exists] at ha, cases ha with c hc, rw zero_mul at hc, exact hM c.2 a hc, end protected lemma to_map_ne_zero_of_mem_non_zero_divisors {M : submonoid A} (f : localization_map M S) (hM : M ≤ non_zero_divisors A) (x : non_zero_divisors A) : f.to_map x ≠ 0 := map_ne_zero_of_mem_non_zero_divisors (f.injective hM) /-- A `comm_ring` `S` which is the localization of an integral domain `R` at a subset of non-zero elements is an integral domain. -/ def integral_domain_of_le_non_zero_divisors {M : submonoid A} (f : localization_map M S) (hM : M ≤ non_zero_divisors A) : integral_domain S := { eq_zero_or_eq_zero_of_mul_eq_zero := begin intros z w h, cases f.surj z with x hx, cases f.surj w with y hy, have : z * w * f.to_map y.2 * f.to_map x.2 = f.to_map x.1 * f.to_map y.1, by rw [mul_assoc z, hy, ←hx]; ac_refl, rw [h, zero_mul, zero_mul, ← f.to_map.map_mul] at this, cases eq_zero_or_eq_zero_of_mul_eq_zero ((to_map_eq_zero_iff f hM).mp this.symm) with H H, { exact or.inl (f.eq_zero_of_fst_eq_zero hx H) }, { exact or.inr (f.eq_zero_of_fst_eq_zero hy H) }, end, exists_pair_ne := ⟨f.to_map 0, f.to_map 1, λ h, zero_ne_one (f.injective hM h)⟩, ..(infer_instance : comm_ring S) } /-- The localization at of an integral domain to a set of non-zero elements is an integral domain -/ def integral_domain_localization {M : submonoid A} (hM : M ≤ non_zero_divisors A) : integral_domain (localization M) := (localization.of M).integral_domain_of_le_non_zero_divisors hM /-- The localization of an integral domain at the complement of a prime ideal is an integral domain. -/ instance integral_domain_of_local_at_prime {P : ideal A} (hp : P.is_prime) : integral_domain (localization.at_prime P) := integral_domain_localization (le_non_zero_divisors_of_domain (by simpa only [] using P.zero_mem)) end localization_map variables (R) {A : Type*} [integral_domain A] variables (K : Type*) /-- Localization map from an integral domain `R` to its field of fractions. -/ @[reducible] def fraction_map [comm_ring K] := localization_map (non_zero_divisors R) K namespace fraction_map open localization_map variables {R K} lemma to_map_eq_zero_iff [comm_ring K] (φ : fraction_map R K) {x : R} : φ.to_map x = 0 ↔ x = 0 := φ.to_map_eq_zero_iff (le_of_eq rfl) protected theorem injective [comm_ring K] (φ : fraction_map R K) : function.injective φ.to_map := φ.injective (le_of_eq rfl) protected lemma to_map_ne_zero_of_mem_non_zero_divisors [comm_ring K] (φ : fraction_map A K) (x : non_zero_divisors A) : φ.to_map x ≠ 0 := φ.to_map_ne_zero_of_mem_non_zero_divisors (le_of_eq rfl) x /-- A `comm_ring` `K` which is the localization of an integral domain `R` at `R - {0}` is an integral domain. -/ def to_integral_domain [comm_ring K] (φ : fraction_map A K) : integral_domain K := φ.integral_domain_of_le_non_zero_divisors (le_of_eq rfl) local attribute [instance] classical.dec_eq /-- The inverse of an element in the field of fractions of an integral domain. -/ protected noncomputable def inv [comm_ring K] (φ : fraction_map A K) (z : K) : K := if h : z = 0 then 0 else φ.mk' (φ.to_localization_map.sec z).2 ⟨(φ.to_localization_map.sec z).1, mem_non_zero_divisors_iff_ne_zero.2 $ λ h0, h $ φ.eq_zero_of_fst_eq_zero (sec_spec z) h0⟩ protected lemma mul_inv_cancel [comm_ring K] (φ : fraction_map A K) (x : K) (hx : x ≠ 0) : x * φ.inv x = 1 := show x * dite _ _ _ = 1, by rw [dif_neg hx, ←is_unit.mul_left_inj (φ.map_units ⟨(φ.to_localization_map.sec x).1, mem_non_zero_divisors_iff_ne_zero.2 $ λ h0, hx $ φ.eq_zero_of_fst_eq_zero (sec_spec x) h0⟩), one_mul, mul_assoc, mk'_spec, ←eq_mk'_iff_mul_eq]; exact (φ.mk'_sec x).symm /-- A `comm_ring` `K` which is the localization of an integral domain `R` at `R - {0}` is a field. -/ noncomputable def to_field [comm_ring K] (φ : fraction_map A K) : field K := { inv := φ.inv, mul_inv_cancel := φ.mul_inv_cancel, inv_zero := dif_pos rfl, ..φ.to_integral_domain } variables {B : Type*} [integral_domain B] [field K] {L : Type*} [field L] (f : fraction_map A K) {g : A →+* L} lemma mk'_eq_div {r s} : f.mk' r s = f.to_map r / f.to_map s := f.mk'_eq_iff_eq_mul.2 $ (div_mul_cancel _ (f.to_map_ne_zero_of_mem_non_zero_divisors _)).symm lemma is_unit_map_of_injective (hg : function.injective g) (y : non_zero_divisors A) : is_unit (g y) := is_unit.mk0 (g y) $ map_ne_zero_of_mem_non_zero_divisors hg /-- Given an integral domain `A`, a localization map to its fields of fractions `f : A →+* K`, and an injective ring hom `g : A →+* L` where `L` is a field, we get a field hom sending `z : K` to `g x * (g y)⁻¹`, where `(x, y) : A × (non_zero_divisors A)` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def lift (hg : injective g) : K →+* L := f.lift $ is_unit_map_of_injective hg /-- Given an integral domain `A`, a localization map to its fields of fractions `f : A →+* K`, and an injective ring hom `g : A →+* L` where `L` is a field, field hom induced from `K` to `L` maps `f x / f y` to `g x / g y` for all `x : A, y ∈ non_zero_divisors A`. -/ @[simp] lemma lift_mk' (hg : injective g) (x y) : f.lift hg (f.mk' x y) = g x / g y := begin erw f.lift_mk' (is_unit_map_of_injective hg), erw submonoid.localization_map.mul_inv_left (λ y : non_zero_divisors A, show is_unit (g.to_monoid_hom y), from is_unit_map_of_injective hg y), exact (mul_div_cancel' _ (map_ne_zero_of_mem_non_zero_divisors hg)).symm, end /-- Given integral domains `A, B` and localization maps to their fields of fractions `f : A →+* K, g : B →+* L` and an injective ring hom `j : A →+* B`, we get a field hom sending `z : K` to `g (j x) * (g (j y))⁻¹`, where `(x, y) : A × (non_zero_divisors A)` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def map (g : fraction_map B L) {j : A →+* B} (hj : injective j) : K →+* L := f.map (λ y, mem_non_zero_divisors_iff_ne_zero.2 $ map_ne_zero_of_mem_non_zero_divisors hj) g /-- Given integral domains `A, B` and localization maps to their fields of fractions `f : A →+* K, g : B →+* L`, an isomorphism `j : A ≃+* B` induces an isomorphism of fields of fractions `K ≃+* L`. -/ noncomputable def field_equiv_of_ring_equiv (g : fraction_map B L) (h : A ≃+* B) : K ≃+* L := f.ring_equiv_of_ring_equiv g h begin ext b, show b ∈ h.to_equiv '' _ ↔ _, erw [h.to_equiv.image_eq_preimage, set.preimage, set.mem_set_of_eq, mem_non_zero_divisors_iff_ne_zero, mem_non_zero_divisors_iff_ne_zero], exact h.symm.map_ne_zero_iff end /-- The cast from `int` to `rat` as a `fraction_map`. -/ def int.fraction_map : fraction_map ℤ ℚ := { to_fun := coe, map_units' := begin rintro ⟨x, hx⟩, rw [submonoid.mem_carrier, mem_non_zero_divisors_iff_ne_zero] at hx, simpa only [is_unit_iff_ne_zero, int.cast_eq_zero, ne.def, subtype.coe_mk] using hx, end, surj' := begin rintro ⟨n, d, hd, h⟩, refine ⟨⟨n, ⟨d, _⟩⟩, rat.mul_denom_eq_num⟩, rwa [submonoid.mem_carrier, mem_non_zero_divisors_iff_ne_zero, int.coe_nat_ne_zero_iff_pos] end, eq_iff_exists' := begin intros x y, rw [int.cast_inj], refine ⟨by { rintro rfl, use 1 }, _⟩, rintro ⟨⟨c, hc⟩, h⟩, apply int.eq_of_mul_eq_mul_right _ h, rwa [submonoid.mem_carrier, mem_non_zero_divisors_iff_ne_zero] at hc, end, ..int.cast_ring_hom ℚ } lemma integer_normalization_eq_zero_iff {p : polynomial f.codomain} : integer_normalization p = 0 ↔ p = 0 := begin refine (polynomial.ext_iff.trans (polynomial.ext_iff.trans _).symm), obtain ⟨⟨b, nonzero⟩, hb⟩ := integer_normalization_spec p, split; intros h i, { apply f.to_map_eq_zero_iff.mp, rw [hb i, h i], exact _root_.mul_zero _ }, { have hi := h i, rw [polynomial.coeff_zero, ← f.to_map_eq_zero_iff, hb i] at hi, apply or.resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero hi), intro h, apply mem_non_zero_divisors_iff_ne_zero.mp nonzero, exact f.to_map_eq_zero_iff.mp h } end /-- A field is algebraic over the ring `A` iff it is algebraic over the field of fractions of `A`. -/ lemma comap_is_algebraic_iff [algebra A L] [algebra f.codomain L] [is_scalar_tower A f.codomain L] : algebra.is_algebraic A L ↔ algebra.is_algebraic f.codomain L := begin split; intros h x; obtain ⟨p, hp, px⟩ := h x, { refine ⟨p.map f.to_map, λ h, hp (polynomial.ext (λ i, _)), _⟩, { have : f.to_map (p.coeff i) = 0 := trans (polynomial.coeff_map _ _).symm (by simp [h]), exact f.to_map_eq_zero_iff.mp this }, { rwa [is_scalar_tower.aeval_apply _ f.codomain, algebra_map_eq] at px } }, { exact ⟨integer_normalization p, mt f.integer_normalization_eq_zero_iff.mp hp, integer_normalization_aeval_eq_zero p px⟩ }, end section num_denom variables [unique_factorization_domain A] (φ : fraction_map A K) lemma exists_reduced_fraction (x : φ.codomain) : ∃ (a : A) (b : non_zero_divisors A), (∀ {d}, d ∣ a → d ∣ b → is_unit d) ∧ φ.mk' a b = x := begin obtain ⟨⟨b, b_nonzero⟩, a, hab⟩ := φ.exists_integer_multiple x, obtain ⟨a', b', c', no_factor, rfl, rfl⟩ := unique_factorization_domain.exists_reduced_factors' a b (mem_non_zero_divisors_iff_ne_zero.mp b_nonzero), obtain ⟨c'_nonzero, b'_nonzero⟩ := mul_mem_non_zero_divisors.mp b_nonzero, refine ⟨a', ⟨b', b'_nonzero⟩, @no_factor, _⟩, apply mul_left_cancel' (φ.to_map_ne_zero_of_mem_non_zero_divisors ⟨c' * b', b_nonzero⟩), simp only [subtype.coe_mk, φ.to_map.map_mul] at *, erw [←hab, mul_assoc, φ.mk'_spec' a' ⟨b', b'_nonzero⟩], end /-- `f.num x` is the numerator of `x : f.codomain` as a reduced fraction. -/ noncomputable def num (x : φ.codomain) : A := classical.some (φ.exists_reduced_fraction x) /-- `f.num x` is the denominator of `x : f.codomain` as a reduced fraction. -/ noncomputable def denom (x : φ.codomain) : non_zero_divisors A := classical.some (classical.some_spec (φ.exists_reduced_fraction x)) lemma num_denom_reduced (x : φ.codomain) : ∀ {d}, d ∣ φ.num x → d ∣ φ.denom x → is_unit d := (classical.some_spec (classical.some_spec (φ.exists_reduced_fraction x))).1 @[simp] lemma mk'_num_denom (x : φ.codomain) : φ.mk' (φ.num x) (φ.denom x) = x := (classical.some_spec (classical.some_spec (φ.exists_reduced_fraction x))).2 lemma num_mul_denom_eq_num_iff_eq {x y : φ.codomain} : x * φ.to_map (φ.denom y) = φ.to_map (φ.num y) ↔ x = y := ⟨ λ h, by simpa only [mk'_num_denom] using φ.eq_mk'_iff_mul_eq.mpr h, λ h, φ.eq_mk'_iff_mul_eq.mp (by rw [h, mk'_num_denom]) ⟩ lemma num_mul_denom_eq_num_iff_eq' {x y : φ.codomain} : y * φ.to_map (φ.denom x) = φ.to_map (φ.num x) ↔ x = y := ⟨ λ h, by simpa only [eq_comm, mk'_num_denom] using φ.eq_mk'_iff_mul_eq.mpr h, λ h, φ.eq_mk'_iff_mul_eq.mp (by rw [h, mk'_num_denom]) ⟩ lemma num_mul_denom_eq_num_mul_denom_iff_eq {x y : φ.codomain} : φ.num y * φ.denom x = φ.num x * φ.denom y ↔ x = y := ⟨ λ h, by simpa only [mk'_num_denom] using φ.mk'_eq_of_eq h, λ h, by rw h ⟩ lemma eq_zero_of_num_eq_zero {x : φ.codomain} (h : φ.num x = 0) : x = 0 := φ.num_mul_denom_eq_num_iff_eq'.mp (by rw [zero_mul, h, ring_hom.map_zero]) lemma is_integer_of_is_unit_denom {x : φ.codomain} (h : is_unit (φ.denom x : A)) : φ.is_integer x := begin cases h with d hd, have d_ne_zero : φ.to_map (φ.denom x) ≠ 0 := φ.to_map_ne_zero_of_mem_non_zero_divisors (φ.denom x), use ↑d⁻¹ * φ.num x, refine trans _ (φ.mk'_num_denom x), rw [φ.to_map.map_mul, φ.to_map.map_units_inv, hd], apply mul_left_cancel' d_ne_zero, rw [←mul_assoc, mul_inv_cancel d_ne_zero, one_mul, φ.mk'_spec'] end lemma is_unit_denom_of_num_eq_zero {x : φ.codomain} (h : φ.num x = 0) : is_unit (φ.denom x : A) := φ.num_denom_reduced x (h.symm ▸ dvd_zero _) (dvd_refl _) end num_denom end fraction_map section algebra section is_integral variables {R S} {Rₘ Sₘ : Type*} [comm_ring Rₘ] [comm_ring Sₘ] [algebra R S] /-- Definition of the natural algebra induced by the localization of an algebra. Given an algebra `R → S`, a submonoid `R` of `M`, and a localizaiton `Rₘ` for `M`, let `Sₘ` be the localization of `S` to the image of `M` under `algebra_map R S`. Then this is the natural algebra structure on `Rₘ → Sₘ`, such that the entire square commutes, where `localization_map.map_comp` gives the commutativity of the underlying maps -/ noncomputable def localization_algebra (M : submonoid R) (f : localization_map M Rₘ) (g : localization_map (algebra.algebra_map_submonoid S M) Sₘ) : algebra Rₘ Sₘ := (f.map (@algebra.mem_algebra_map_submonoid_of_mem R S _ _ _ _) g).to_algebra variables (f : localization_map M Rₘ) variables (g : localization_map (algebra.algebra_map_submonoid S M) Sₘ) open polynomial /-- Given a particular witness to an element being algebraic over an algebra `R → S`, We can localize to a submonoid containing the leading coefficient to make it integral -/ theorem is_integral_localization_at_leading_coeff {x : S} (p : polynomial R) (hp : aeval x p = 0) (hM' : p.leading_coeff ∈ M) : @is_integral Rₘ _ _ _ (localization_algebra M f g) (g.to_map x) := begin by_cases triv : (1 : Rₘ) = 0, { exact ⟨0, ⟨trans leading_coeff_zero triv.symm, eval₂_zero _ _⟩⟩ }, haveI : nontrivial Rₘ := nontrivial_of_ne 1 0 triv, obtain ⟨b, hb⟩ := is_unit_iff_exists_inv.mp (localization_map.map_units f ⟨p.leading_coeff, hM'⟩), refine ⟨(p.map f.to_map) * C b, ⟨_, _⟩⟩, { refine monic_mul_C_of_leading_coeff_mul_eq_one _, rwa leading_coeff_map_of_leading_coeff_ne_zero f.to_map, refine λ hfp, zero_ne_one (trans (zero_mul b).symm (hfp ▸ hb) : (0 : Rₘ) = 1) }, { refine eval₂_mul_eq_zero_of_left _ _ _ _, erw [eval₂_map, localization_map.map_comp, ← hom_eval₂ _ (algebra_map R S) g.to_map x], exact trans (congr_arg g.to_map hp) g.to_map.map_zero } end /-- If `R → S` is an integral extension, `M` is a submonoid of `R`, `Rₘ` is the localization of `R` at `M`, and `Sₘ` is the localization of `S` at the image of `M` under the extension map, then the induced map `Rₘ → Sₘ` is also an integral extension -/ theorem is_integral_localization (H : ∀ x : S, is_integral R x) (x : Sₘ) : @is_integral Rₘ _ _ _ (localization_algebra M f g) x := begin by_cases triv : (1 : R) = 0, { have : (1 : Rₘ) = 0 := by convert congr_arg f.to_map triv; simp, exact ⟨0, ⟨trans leading_coeff_zero this.symm, eval₂_zero _ _⟩⟩ }, { haveI : nontrivial R := nontrivial_of_ne 1 0 triv, obtain ⟨⟨s, ⟨u, hu⟩⟩, hx⟩ := g.surj x, obtain ⟨v, hv⟩ := hu, obtain ⟨v', hv'⟩ := is_unit_iff_exists_inv'.1 (f.map_units ⟨v, hv.1⟩), refine @is_integral_of_is_integral_mul_unit Rₘ _ _ _ (localization_algebra M f g) x (g.to_map u) v' _ _, { replace hv' := congr_arg (@algebra_map Rₘ Sₘ _ _ (localization_algebra M f g)) hv', rw [ring_hom.map_mul, ring_hom.map_one, ← ring_hom.comp_apply _ f.to_map] at hv', erw localization_map.map_comp at hv', exact hv.2 ▸ hv' }, { obtain ⟨p, hp⟩ := H s, exact hx.symm ▸ is_integral_localization_at_leading_coeff f g p hp.2 (hp.1.symm ▸ M.one_mem) } } end end is_integral namespace integral_closure variables {L : Type*} [field K] [field L] {f : fraction_map A K} open algebra /-- If the field `L` is an algebraic extension of the integral domain `A`, the integral closure of `A` in `L` has fraction field `L`. -/ def fraction_map_of_algebraic [algebra A L] (alg : is_algebraic A L) (inj : ∀ x, algebra_map A L x = 0 → x = 0) : fraction_map (integral_closure A L) L := (algebra_map (integral_closure A L) L).to_localization_map (λ ⟨⟨y, integral⟩, nonzero⟩, have y ≠ 0 := λ h, mem_non_zero_divisors_iff_ne_zero.mp nonzero (subtype.ext_iff_val.mpr h), show is_unit y, from ⟨⟨y, y⁻¹, mul_inv_cancel this, inv_mul_cancel this⟩, rfl⟩) (λ z, let ⟨x, y, hy, hxy⟩ := exists_integral_multiple (alg z) inj in ⟨⟨x, ⟨y, mem_non_zero_divisors_iff_ne_zero.mpr hy⟩⟩, hxy⟩) (λ x y, ⟨ λ (h : x.1 = y.1), ⟨1, by simpa using subtype.ext_iff_val.mpr h⟩, λ ⟨c, hc⟩, congr_arg (algebra_map _ L) (mul_right_cancel' (mem_non_zero_divisors_iff_ne_zero.mp c.2) hc) ⟩) /-- If the field `L` is a finite extension of the fraction field of the integral domain `A`, the integral closure of `A` in `L` has fraction field `L`. -/ def fraction_map_of_finite_extension [algebra A L] [algebra f.codomain L] [is_scalar_tower A f.codomain L] [finite_dimensional f.codomain L] : fraction_map (integral_closure A L) L := fraction_map_of_algebraic (f.comap_is_algebraic_iff.mpr is_algebraic_of_finite) (λ x hx, f.to_map_eq_zero_iff.mp ((algebra_map f.codomain L).map_eq_zero.mp $ (is_scalar_tower.algebra_map_apply _ _ _ _).symm.trans hx)) end integral_closure end algebra variables (A) /-- The fraction field of an integral domain as a quotient type. -/ @[reducible] def fraction_ring := localization (non_zero_divisors A) /-- Natural hom sending `x : A`, `A` an integral domain, to the equivalence class of `(x, 1)` in the field of fractions of `A`. -/ def of : fraction_map A (localization (non_zero_divisors A)) := localization.of (non_zero_divisors A) namespace fraction_ring variables {A} noncomputable instance : field (fraction_ring A) := (of A).to_field @[simp] lemma mk_eq_div {r s} : (localization.mk r s : fraction_ring A) = ((of A).to_map r / (of A).to_map s : fraction_ring A) := by erw [localization.mk_eq_mk', (of A).mk'_eq_div] /-- Given an integral domain `A` and a localization map to a field of fractions `f : A →+* K`, we get an isomorphism between the field of fractions of `A` as a quotient type and `K`. -/ noncomputable def field_equiv_of_quotient {K : Type*} [field K] (f : fraction_map A K) : fraction_ring A ≃+* K := localization.ring_equiv_of_quotient f end fraction_ring
9b9c6f6bbf32cbd41f58ee92a12868eb556433e0
e4850d3690538c747274f940d23178380b465a23
/LeanNixStatic1/Inline.lean
685c791367c18a22cb7056d43e09f2d6dfbe0013
[]
no_license
zygi/leannixstatic1
5d81973a69c98e6f29e9283c245d10f81303155c
b10ce543ec1d990186295bfd33bc84d3a69a6fd7
refs/heads/master
1,678,438,994,937
1,614,394,028,000
1,614,394,028,000
342,754,763
0
0
null
null
null
null
UTF-8
Lean
false
false
261
lean
-- A definition with both native and Lean implementations @[extern c inline "lean_box(1)"] def ifNative1Else0(dummy: Nat): Nat := 0 -- A constant with only a native implementation @[extern c inline "#1 ^ #2"] constant xor (a: @& UInt64) (b: @& UInt64) : UInt64
ddc27dc01c567f8ae22509eef312f9cfa6e126b3
4c630d016e43ace8c5f476a5070a471130c8a411
/group_theory/free_abelian_group.lean
e7766827d28cce2f837a03f064fd7c74d57a9c6d
[ "Apache-2.0" ]
permissive
ngamt/mathlib
9a510c391694dc43eec969914e2a0e20b272d172
58909bd424209739a2214961eefaa012fb8a18d2
refs/heads/master
1,585,942,993,674
1,540,739,585,000
1,540,916,815,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,287
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 abelian groups as abelianization of free groups. -/ import algebra.pi_instances import group_theory.free_group import group_theory.abelianization universes u v variables (α : Type u) def free_abelian_group : Type u := additive $ abelianization $ free_group α instance : add_comm_group (free_abelian_group α) := @additive.add_comm_group _ $ abelianization.comm_group _ variable {α} namespace free_abelian_group def of (x : α) : free_abelian_group α := abelianization.of $ free_group.of x instance : has_coe α (free_abelian_group α) := ⟨of⟩ def lift {β : Type v} [add_comm_group β] (f : α → β) (x : free_abelian_group α) : β := @abelianization.lift _ _ (multiplicative β) _ (@free_group.to_group _ (multiplicative β) _ f) _ x namespace lift variables {β : Type v} [add_comm_group β] (f : α → β) open free_abelian_group instance is_add_group_hom : is_add_group_hom (lift f) := ⟨λ x y, @is_group_hom.mul _ (multiplicative β) _ _ _ (abelianization.lift.is_group_hom _) x y⟩ local attribute [instance] lift.is_add_group_hom @[simp] protected lemma add (x y : free_abelian_group α) : lift f (x + y) = lift f x + lift f y := is_add_group_hom.add _ _ _ @[simp] protected lemma neg (x : free_abelian_group α) : lift f (-x) = -lift f x := is_add_group_hom.neg _ _ @[simp] protected lemma sub (x y : free_abelian_group α) : lift f (x - y) = lift f x - lift f y := by simp @[simp] protected lemma zero : lift f 0 = 0 := is_add_group_hom.zero _ @[simp] protected lemma of (x : α) : lift f (of x) = f x := by unfold of; unfold lift; simp @[simp] protected lemma coe (x : α) : lift f ↑x = f x := lift.of f x protected theorem unique (g : free_abelian_group α → β) [is_add_group_hom g] (hg : ∀ x, g (of x) = f x) {x} : g x = lift f x := @abelianization.lift.unique (free_group α) _ (multiplicative β) _ _ _ g ⟨λ x y, @is_add_group_hom.add (additive $ abelianization (free_group α)) _ _ _ _ _ x y⟩ (λ x, @free_group.to_group.unique α (multiplicative β) _ _ (g ∘ abelianization.of) ⟨λ m n, is_add_group_hom.add g (abelianization.of m) (abelianization.of n)⟩ hg _) _ protected theorem ext (g h : free_abelian_group α → β) [is_add_group_hom g] [is_add_group_hom h] (H : ∀ x, g (of x) = h (of x)) {x} : g x = h x := (lift.unique (g ∘ of) g (λ _, rfl)).trans $ eq.symm $ lift.unique _ _ $ λ x, eq.symm $ H x lemma map_hom {α β γ} [add_comm_group β] [add_comm_group γ] (a : free_abelian_group α) (f : α → β) (g : β → γ) [is_add_group_hom g] : g (a.lift f) = a.lift (g ∘ f) := show (g ∘ lift f) a = a.lift (g ∘ f), begin apply @lift.unique, assume a, simp only [(∘), lift.of] end def universal : (α → β) ≃ { f : free_abelian_group α → β // is_add_group_hom f } := { to_fun := λ f, ⟨_, lift.is_add_group_hom f⟩, inv_fun := λ f, f.1 ∘ of, left_inv := λ f, funext $ λ x, lift.of f x, right_inv := λ f, subtype.eq $ funext $ λ x, eq.symm $ by letI := f.2; from lift.unique _ _ (λ _, rfl) } end lift local attribute [instance] quotient_group.left_rel normal_subgroup.to_is_subgroup @[elab_as_eliminator] protected theorem induction_on {C : free_abelian_group α → Prop} (z : free_abelian_group α) (C0 : C 0) (C1 : ∀ x, C $ of x) (Cn : ∀ x, C (of x) → C (-of x)) (Cp : ∀ x y, C x → C y → C (x + y)) : C z := quotient.induction_on z $ λ x, quot.induction_on x $ λ L, list.rec_on L C0 $ λ ⟨x, b⟩ tl ih, bool.rec_on b (Cp _ _ (Cn _ (C1 x)) ih) (Cp _ _ (C1 x) ih) instance is_add_group_hom_lift' {α} (β) [add_comm_group β] (a : free_abelian_group α) : is_add_group_hom (λf, (a.lift f : β)) := begin refine ⟨assume f g, free_abelian_group.induction_on a _ _ _ _⟩, { simp [is_add_group_hom.zero (free_abelian_group.lift f)] }, { simp [lift.of], assume x, refl }, { simp [is_add_group_hom.neg (free_abelian_group.lift f)], assume x h, show - (f x + g x) = -f x + - g x, exact neg_add _ _ }, { simp [is_add_group_hom.add (free_abelian_group.lift f)], assume x y hx hy, rw [hx, hy], ac_refl } end end free_abelian_group
28738b694ef012e643553102f72e79d4167d4f0b
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/monoidal/category.lean
0380ffb3e39e8eaf5fe0f020eb0181a05205a8da
[ "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
18,997
lean
/- Copyright (c) 2018 Michael Jendrusch. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Jendrusch, Scott Morrison, Bhavik Mehta -/ import category_theory.products.basic /-! # Monoidal categories A monoidal category is a category equipped with a tensor product, unitors, and an associator. In the definition, we provide the tensor product as a pair of functions * `tensor_obj : C → C → C` * `tensor_hom : (X₁ ⟶ Y₁) → (X₂ ⟶ Y₂) → ((X₁ ⊗ X₂) ⟶ (Y₁ ⊗ Y₂))` and allow use of the overloaded notation `⊗` for both. The unitors and associator are provided componentwise. The tensor product can be expressed as a functor via `tensor : C × C ⥤ C`. The unitors and associator are gathered together as natural isomorphisms in `left_unitor_nat_iso`, `right_unitor_nat_iso` and `associator_nat_iso`. Some consequences of the definition are proved in other files, e.g. `(λ_ (𝟙_ C)).hom = (ρ_ (𝟙_ C)).hom` in `category_theory.monoidal.unitors_equal`. ## Implementation Dealing with unitors and associators is painful, and at this stage we do not have a useful implementation of coherence for monoidal categories. In an effort to lessen the pain, we put some effort into choosing the right `simp` lemmas. Generally, the rule is that the component index of a natural transformation "weighs more" in considering the complexity of an expression than does a structural isomorphism (associator, etc). As an example when we prove Proposition 2.2.4 of <http://www-math.mit.edu/~etingof/egnobookfinal.pdf> we state it as a `@[simp]` lemma as ``` (λ_ (X ⊗ Y)).hom = (α_ (𝟙_ C) X Y).inv ≫ (λ_ X).hom ⊗ (𝟙 Y) ``` This is far from completely effective, but seems to prove a useful principle. ## References * Tensor categories, Etingof, Gelaki, Nikshych, Ostrik, http://www-math.mit.edu/~etingof/egnobookfinal.pdf * https://stacks.math.columbia.edu/tag/0FFK. -/ open category_theory universes v u open category_theory open category_theory.category open category_theory.iso namespace category_theory /-- In a monoidal category, we can take the tensor product of objects, `X ⊗ Y` and of morphisms `f ⊗ g`. Tensor product does not need to be strictly associative on objects, but there is a specified associator, `α_ X Y Z : (X ⊗ Y) ⊗ Z ≅ X ⊗ (Y ⊗ Z)`. There is a tensor unit `𝟙_ C`, with specified left and right unitor isomorphisms `λ_ X : 𝟙_ C ⊗ X ≅ X` and `ρ_ X : X ⊗ 𝟙_ C ≅ X`. These associators and unitors satisfy the pentagon and triangle equations. See https://stacks.math.columbia.edu/tag/0FFK. -/ class monoidal_category (C : Type u) [𝒞 : category.{v} C] := -- curried tensor product of objects: (tensor_obj : C → C → C) (infixr ` ⊗ `:70 := tensor_obj) -- This notation is only temporary -- curried tensor product of morphisms: (tensor_hom : Π {X₁ Y₁ X₂ Y₂ : C}, (X₁ ⟶ Y₁) → (X₂ ⟶ Y₂) → ((X₁ ⊗ X₂) ⟶ (Y₁ ⊗ Y₂))) (infixr ` ⊗' `:69 := tensor_hom) -- This notation is only temporary -- tensor product laws: (tensor_id' : ∀ (X₁ X₂ : C), (𝟙 X₁) ⊗' (𝟙 X₂) = 𝟙 (X₁ ⊗ X₂) . obviously) (tensor_comp' : ∀ {X₁ Y₁ Z₁ X₂ Y₂ Z₂ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (g₁ : Y₁ ⟶ Z₁) (g₂ : Y₂ ⟶ Z₂), (f₁ ≫ g₁) ⊗' (f₂ ≫ g₂) = (f₁ ⊗' f₂) ≫ (g₁ ⊗' g₂) . obviously) -- tensor unit: (tensor_unit [] : C) (notation `𝟙_` := tensor_unit) -- associator: (associator : Π X Y Z : C, (X ⊗ Y) ⊗ Z ≅ X ⊗ (Y ⊗ Z)) (notation `α_` := associator) (associator_naturality' : ∀ {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃), ((f₁ ⊗' f₂) ⊗' f₃) ≫ (α_ Y₁ Y₂ Y₃).hom = (α_ X₁ X₂ X₃).hom ≫ (f₁ ⊗' (f₂ ⊗' f₃)) . obviously) -- left unitor: (left_unitor : Π X : C, 𝟙_ ⊗ X ≅ X) (notation `λ_` := left_unitor) (left_unitor_naturality' : ∀ {X Y : C} (f : X ⟶ Y), ((𝟙 𝟙_) ⊗' f) ≫ (λ_ Y).hom = (λ_ X).hom ≫ f . obviously) -- right unitor: (right_unitor : Π X : C, X ⊗ 𝟙_ ≅ X) (notation `ρ_` := right_unitor) (right_unitor_naturality' : ∀ {X Y : C} (f : X ⟶ Y), (f ⊗' (𝟙 𝟙_)) ≫ (ρ_ Y).hom = (ρ_ X).hom ≫ f . obviously) -- pentagon identity: (pentagon' : ∀ W X Y Z : C, ((α_ W X Y).hom ⊗' (𝟙 Z)) ≫ (α_ W (X ⊗ Y) Z).hom ≫ ((𝟙 W) ⊗' (α_ X Y Z).hom) = (α_ (W ⊗ X) Y Z).hom ≫ (α_ W X (Y ⊗ Z)).hom . obviously) -- triangle identity: (triangle' : ∀ X Y : C, (α_ X 𝟙_ Y).hom ≫ ((𝟙 X) ⊗' (λ_ Y).hom) = (ρ_ X).hom ⊗' (𝟙 Y) . obviously) restate_axiom monoidal_category.tensor_id' attribute [simp] monoidal_category.tensor_id restate_axiom monoidal_category.tensor_comp' attribute [reassoc] monoidal_category.tensor_comp -- This would be redundant in the simp set. attribute [simp] monoidal_category.tensor_comp restate_axiom monoidal_category.associator_naturality' attribute [reassoc] monoidal_category.associator_naturality restate_axiom monoidal_category.left_unitor_naturality' attribute [reassoc] monoidal_category.left_unitor_naturality restate_axiom monoidal_category.right_unitor_naturality' attribute [reassoc] monoidal_category.right_unitor_naturality restate_axiom monoidal_category.pentagon' restate_axiom monoidal_category.triangle' attribute [reassoc] monoidal_category.pentagon attribute [simp, reassoc] monoidal_category.triangle open monoidal_category infixr ` ⊗ `:70 := tensor_obj infixr ` ⊗ `:70 := tensor_hom notation `𝟙_` := tensor_unit notation `α_` := associator notation `λ_` := left_unitor notation `ρ_` := right_unitor /-- The tensor product of two isomorphisms is an isomorphism. -/ @[simps] def tensor_iso {C : Type u} {X Y X' Y' : C} [category.{v} C] [monoidal_category.{v} C] (f : X ≅ Y) (g : X' ≅ Y') : X ⊗ X' ≅ Y ⊗ Y' := { hom := f.hom ⊗ g.hom, inv := f.inv ⊗ g.inv, hom_inv_id' := by rw [←tensor_comp, iso.hom_inv_id, iso.hom_inv_id, ←tensor_id], inv_hom_id' := by rw [←tensor_comp, iso.inv_hom_id, iso.inv_hom_id, ←tensor_id] } infixr ` ⊗ `:70 := tensor_iso namespace monoidal_category section variables {C : Type u} [category.{v} C] [monoidal_category.{v} C] instance tensor_is_iso {W X Y Z : C} (f : W ⟶ X) [is_iso f] (g : Y ⟶ Z) [is_iso g] : is_iso (f ⊗ g) := is_iso.of_iso (as_iso f ⊗ as_iso g) @[simp] lemma inv_tensor {W X Y Z : C} (f : W ⟶ X) [is_iso f] (g : Y ⟶ Z) [is_iso g] : inv (f ⊗ g) = inv f ⊗ inv g := by { ext, simp [←tensor_comp], } variables {U V W X Y Z : C} -- When `rewrite_search` lands, add @[search] attributes to -- monoidal_category.tensor_id monoidal_category.tensor_comp monoidal_category.associator_naturality -- monoidal_category.left_unitor_naturality monoidal_category.right_unitor_naturality -- monoidal_category.pentagon monoidal_category.triangle -- tensor_comp_id tensor_id_comp comp_id_tensor_tensor_id -- triangle_assoc_comp_left triangle_assoc_comp_right -- triangle_assoc_comp_left_inv triangle_assoc_comp_right_inv -- left_unitor_tensor left_unitor_tensor_inv -- right_unitor_tensor right_unitor_tensor_inv -- pentagon_inv -- associator_inv_naturality -- left_unitor_inv_naturality -- right_unitor_inv_naturality @[reassoc, simp] lemma comp_tensor_id (f : W ⟶ X) (g : X ⟶ Y) : (f ≫ g) ⊗ (𝟙 Z) = (f ⊗ (𝟙 Z)) ≫ (g ⊗ (𝟙 Z)) := by { rw ←tensor_comp, simp } @[reassoc, simp] lemma id_tensor_comp (f : W ⟶ X) (g : X ⟶ Y) : (𝟙 Z) ⊗ (f ≫ g) = (𝟙 Z ⊗ f) ≫ (𝟙 Z ⊗ g) := by { rw ←tensor_comp, simp } @[simp, reassoc] lemma id_tensor_comp_tensor_id (f : W ⟶ X) (g : Y ⟶ Z) : ((𝟙 Y) ⊗ f) ≫ (g ⊗ (𝟙 X)) = g ⊗ f := by { rw [←tensor_comp], simp } @[simp, reassoc] lemma tensor_id_comp_id_tensor (f : W ⟶ X) (g : Y ⟶ Z) : (g ⊗ (𝟙 W)) ≫ ((𝟙 Z) ⊗ f) = g ⊗ f := by { rw [←tensor_comp], simp } @[reassoc] lemma left_unitor_inv_naturality {X X' : C} (f : X ⟶ X') : f ≫ (λ_ X').inv = (λ_ X).inv ≫ (𝟙 _ ⊗ f) := begin apply (cancel_mono (λ_ X').hom).1, simp only [assoc, comp_id, iso.inv_hom_id], rw [left_unitor_naturality, ←category.assoc, iso.inv_hom_id, category.id_comp] end @[reassoc] lemma right_unitor_inv_naturality {X X' : C} (f : X ⟶ X') : f ≫ (ρ_ X').inv = (ρ_ X).inv ≫ (f ⊗ 𝟙 _) := begin apply (cancel_mono (ρ_ X').hom).1, simp only [assoc, comp_id, iso.inv_hom_id], rw [right_unitor_naturality, ←category.assoc, iso.inv_hom_id, category.id_comp] end @[simp] lemma right_unitor_conjugation {X Y : C} (f : X ⟶ Y) : (ρ_ X).inv ≫ (f ⊗ (𝟙 (𝟙_ C))) ≫ (ρ_ Y).hom = f := by rw [right_unitor_naturality, ←category.assoc, iso.inv_hom_id, category.id_comp] @[simp] lemma left_unitor_conjugation {X Y : C} (f : X ⟶ Y) : (λ_ X).inv ≫ ((𝟙 (𝟙_ C)) ⊗ f) ≫ (λ_ Y).hom = f := by rw [left_unitor_naturality, ←category.assoc, iso.inv_hom_id, category.id_comp] @[simp] lemma tensor_left_iff {X Y : C} (f g : X ⟶ Y) : ((𝟙 (𝟙_ C)) ⊗ f = (𝟙 (𝟙_ C)) ⊗ g) ↔ (f = g) := by { rw [←cancel_mono (λ_ Y).hom, left_unitor_naturality, left_unitor_naturality], simp } @[simp] lemma tensor_right_iff {X Y : C} (f g : X ⟶ Y) : (f ⊗ (𝟙 (𝟙_ C)) = g ⊗ (𝟙 (𝟙_ C))) ↔ (f = g) := by { rw [←cancel_mono (ρ_ Y).hom, right_unitor_naturality, right_unitor_naturality], simp } -- See Proposition 2.2.4 of <http://www-math.mit.edu/~etingof/egnobookfinal.pdf> @[reassoc] lemma left_unitor_tensor' (X Y : C) : ((α_ (𝟙_ C) X Y).hom) ≫ ((λ_ (X ⊗ Y)).hom) = ((λ_ X).hom ⊗ (𝟙 Y)) := by rw [←tensor_left_iff, id_tensor_comp, ←cancel_epi (α_ (𝟙_ C) (𝟙_ C ⊗ X) Y).hom, ←cancel_epi ((α_ (𝟙_ C) (𝟙_ C) X).hom ⊗ 𝟙 Y), pentagon_assoc, triangle, ←associator_naturality, ←comp_tensor_id_assoc, triangle, associator_naturality, tensor_id] @[simp] lemma left_unitor_tensor (X Y : C) : ((λ_ (X ⊗ Y)).hom) = ((α_ (𝟙_ C) X Y).inv) ≫ ((λ_ X).hom ⊗ (𝟙 Y)) := by { rw [←left_unitor_tensor'], simp } lemma left_unitor_tensor_inv' (X Y : C) : ((λ_ (X ⊗ Y)).inv) ≫ ((α_ (𝟙_ C) X Y).inv) = ((λ_ X).inv ⊗ (𝟙 Y)) := eq_of_inv_eq_inv (by simp) @[reassoc, simp] lemma left_unitor_tensor_inv (X Y : C) : (λ_ (X ⊗ Y)).inv = ((λ_ X).inv ⊗ (𝟙 Y)) ≫ (α_ (𝟙_ C) X Y).hom := by { rw [←left_unitor_tensor_inv'], simp } @[simp] lemma right_unitor_tensor (X Y : C) : (ρ_ (X ⊗ Y)).hom = (α_ X Y (𝟙_ C)).hom ≫ ((𝟙 X) ⊗ (ρ_ Y).hom) := by rw [←tensor_right_iff, comp_tensor_id, ←cancel_mono (α_ X Y (𝟙_ C)).hom, assoc, associator_naturality, ←triangle_assoc, ←triangle, id_tensor_comp, pentagon_assoc, ←associator_naturality, tensor_id] @[reassoc, simp] lemma right_unitor_tensor_inv (X Y : C) : ((ρ_ (X ⊗ Y)).inv) = ((𝟙 X) ⊗ (ρ_ Y).inv) ≫ ((α_ X Y (𝟙_ C)).inv) := eq_of_inv_eq_inv (by simp) @[reassoc] lemma associator_inv_naturality {X Y Z X' Y' Z' : C} (f : X ⟶ X') (g : Y ⟶ Y') (h : Z ⟶ Z') : (f ⊗ (g ⊗ h)) ≫ (α_ X' Y' Z').inv = (α_ X Y Z).inv ≫ ((f ⊗ g) ⊗ h) := by { rw [comp_inv_eq, assoc, associator_naturality], simp } @[reassoc] lemma id_tensor_associator_naturality {X Y Z Z' : C} (h : Z ⟶ Z') : (𝟙 (X ⊗ Y) ⊗ h) ≫ (α_ X Y Z').hom = (α_ X Y Z).hom ≫ (𝟙 X ⊗ (𝟙 Y ⊗ h)) := by { rw [←tensor_id, associator_naturality], } @[reassoc] lemma id_tensor_associator_inv_naturality {X Y Z X' : C} (f : X ⟶ X') : (f ⊗ 𝟙 (Y ⊗ Z)) ≫ (α_ X' Y Z).inv = (α_ X Y Z).inv ≫ ((f ⊗ 𝟙 Y) ⊗ 𝟙 Z) := by { rw [←tensor_id, associator_inv_naturality] } @[reassoc] lemma pentagon_inv (W X Y Z : C) : ((𝟙 W) ⊗ (α_ X Y Z).inv) ≫ (α_ W (X ⊗ Y) Z).inv ≫ ((α_ W X Y).inv ⊗ (𝟙 Z)) = (α_ W X (Y ⊗ Z)).inv ≫ (α_ (W ⊗ X) Y Z).inv := category_theory.eq_of_inv_eq_inv (by simp [pentagon]) lemma triangle_assoc_comp_left (X Y : C) : (α_ X (𝟙_ C) Y).hom ≫ ((𝟙 X) ⊗ (λ_ Y).hom) = (ρ_ X).hom ⊗ 𝟙 Y := monoidal_category.triangle X Y @[simp, reassoc] lemma triangle_assoc_comp_right (X Y : C) : (α_ X (𝟙_ C) Y).inv ≫ ((ρ_ X).hom ⊗ 𝟙 Y) = ((𝟙 X) ⊗ (λ_ Y).hom) := by rw [←triangle_assoc_comp_left, iso.inv_hom_id_assoc] @[simp, reassoc] lemma triangle_assoc_comp_right_inv (X Y : C) : ((ρ_ X).inv ⊗ 𝟙 Y) ≫ (α_ X (𝟙_ C) Y).hom = ((𝟙 X) ⊗ (λ_ Y).inv) := begin apply (cancel_mono (𝟙 X ⊗ (λ_ Y).hom)).1, simp only [assoc, triangle_assoc_comp_left], rw [←comp_tensor_id, iso.inv_hom_id, ←id_tensor_comp, iso.inv_hom_id] end @[simp, reassoc] lemma triangle_assoc_comp_left_inv (X Y : C) : ((𝟙 X) ⊗ (λ_ Y).inv) ≫ (α_ X (𝟙_ C) Y).inv = ((ρ_ X).inv ⊗ 𝟙 Y) := begin apply (cancel_mono ((ρ_ X).hom ⊗ 𝟙 Y)).1, simp only [triangle_assoc_comp_right, assoc], rw [←id_tensor_comp, iso.inv_hom_id, ←comp_tensor_id, iso.inv_hom_id] end lemma unitors_equal : (λ_ (𝟙_ C)).hom = (ρ_ (𝟙_ C)).hom := by rw [←tensor_left_iff, ←cancel_epi (α_ (𝟙_ C) (𝟙_ _) (𝟙_ _)).hom, ←cancel_mono (ρ_ (𝟙_ C)).hom, triangle, ←right_unitor_tensor, right_unitor_naturality] lemma unitors_inv_equal : (λ_ (𝟙_ C)).inv = (ρ_ (𝟙_ C)).inv := by { ext, simp [←unitors_equal], } @[simp, reassoc] lemma hom_inv_id_tensor {V W X Y Z : C} (f : V ≅ W) (g : X ⟶ Y) (h : Y ⟶ Z) : (f.hom ⊗ g) ≫ (f.inv ⊗ h) = 𝟙 V ⊗ (g ≫ h) := by rw [←tensor_comp, f.hom_inv_id] @[simp, reassoc] lemma inv_hom_id_tensor {V W X Y Z : C} (f : V ≅ W) (g : X ⟶ Y) (h : Y ⟶ Z) : (f.inv ⊗ g) ≫ (f.hom ⊗ h) = 𝟙 W ⊗ (g ≫ h) := by rw [←tensor_comp, f.inv_hom_id] @[simp, reassoc] lemma tensor_hom_inv_id {V W X Y Z : C} (f : V ≅ W) (g : X ⟶ Y) (h : Y ⟶ Z) : (g ⊗ f.hom) ≫ (h ⊗ f.inv) = (g ≫ h) ⊗ 𝟙 V := by rw [←tensor_comp, f.hom_inv_id] @[simp, reassoc] lemma tensor_inv_hom_id {V W X Y Z : C} (f : V ≅ W) (g : X ⟶ Y) (h : Y ⟶ Z) : (g ⊗ f.inv) ≫ (h ⊗ f.hom) = (g ≫ h) ⊗ 𝟙 W := by rw [←tensor_comp, f.inv_hom_id] end section variables (C : Type u) [category.{v} C] [monoidal_category.{v} C] /-- The tensor product expressed as a functor. -/ def tensor : (C × C) ⥤ C := { obj := λ X, X.1 ⊗ X.2, map := λ {X Y : C × C} (f : X ⟶ Y), f.1 ⊗ f.2 } /-- The left-associated triple tensor product as a functor. -/ def left_assoc_tensor : (C × C × C) ⥤ C := { obj := λ X, (X.1 ⊗ X.2.1) ⊗ X.2.2, map := λ {X Y : C × C × C} (f : X ⟶ Y), (f.1 ⊗ f.2.1) ⊗ f.2.2 } @[simp] lemma left_assoc_tensor_obj (X) : (left_assoc_tensor C).obj X = (X.1 ⊗ X.2.1) ⊗ X.2.2 := rfl @[simp] lemma left_assoc_tensor_map {X Y} (f : X ⟶ Y) : (left_assoc_tensor C).map f = (f.1 ⊗ f.2.1) ⊗ f.2.2 := rfl /-- The right-associated triple tensor product as a functor. -/ def right_assoc_tensor : (C × C × C) ⥤ C := { obj := λ X, X.1 ⊗ (X.2.1 ⊗ X.2.2), map := λ {X Y : C × C × C} (f : X ⟶ Y), f.1 ⊗ (f.2.1 ⊗ f.2.2) } @[simp] lemma right_assoc_tensor_obj (X) : (right_assoc_tensor C).obj X = X.1 ⊗ (X.2.1 ⊗ X.2.2) := rfl @[simp] lemma right_assoc_tensor_map {X Y} (f : X ⟶ Y) : (right_assoc_tensor C).map f = f.1 ⊗ (f.2.1 ⊗ f.2.2) := rfl /-- The functor `λ X, 𝟙_ C ⊗ X`. -/ def tensor_unit_left : C ⥤ C := { obj := λ X, 𝟙_ C ⊗ X, map := λ {X Y : C} (f : X ⟶ Y), (𝟙 (𝟙_ C)) ⊗ f } /-- The functor `λ X, X ⊗ 𝟙_ C`. -/ def tensor_unit_right : C ⥤ C := { obj := λ X, X ⊗ 𝟙_ C, map := λ {X Y : C} (f : X ⟶ Y), f ⊗ (𝟙 (𝟙_ C)) } -- We can express the associator and the unitors, given componentwise above, -- as natural isomorphisms. /-- The associator as a natural isomorphism. -/ @[simps] def associator_nat_iso : left_assoc_tensor C ≅ right_assoc_tensor C := nat_iso.of_components (by { intros, apply monoidal_category.associator }) (by { intros, apply monoidal_category.associator_naturality }) /-- The left unitor as a natural isomorphism. -/ @[simps] def left_unitor_nat_iso : tensor_unit_left C ≅ 𝟭 C := nat_iso.of_components (by { intros, apply monoidal_category.left_unitor }) (by { intros, apply monoidal_category.left_unitor_naturality }) /-- The right unitor as a natural isomorphism. -/ @[simps] def right_unitor_nat_iso : tensor_unit_right C ≅ 𝟭 C := nat_iso.of_components (by { intros, apply monoidal_category.right_unitor }) (by { intros, apply monoidal_category.right_unitor_naturality }) section variables {C} /-- Tensoring on the left with a fixed object, as a functor. -/ @[simps] def tensor_left (X : C) : C ⥤ C := { obj := λ Y, X ⊗ Y, map := λ Y Y' f, (𝟙 X) ⊗ f, } /-- Tensoring on the left with `X ⊗ Y` is naturally isomorphic to tensoring on the left with `Y`, and then again with `X`. -/ def tensor_left_tensor (X Y : C) : tensor_left (X ⊗ Y) ≅ tensor_left Y ⋙ tensor_left X := nat_iso.of_components (associator _ _) (λ Z Z' f, by { dsimp, rw[←tensor_id], apply associator_naturality }) @[simp] lemma tensor_left_tensor_hom_app (X Y Z : C) : (tensor_left_tensor X Y).hom.app Z = (associator X Y Z).hom := rfl @[simp] lemma tensor_left_tensor_inv_app (X Y Z : C) : (tensor_left_tensor X Y).inv.app Z = (associator X Y Z).inv := by { simp [tensor_left_tensor], } /-- Tensoring on the right with a fixed object, as a functor. -/ @[simps] def tensor_right (X : C) : C ⥤ C := { obj := λ Y, Y ⊗ X, map := λ Y Y' f, f ⊗ (𝟙 X), } variables (C) /-- Tensoring on the right, as a functor from `C` into endofunctors of `C`. We later show this is a monoidal functor. -/ @[simps] def tensoring_right : C ⥤ (C ⥤ C) := { obj := tensor_right, map := λ X Y f, { app := λ Z, (𝟙 Z) ⊗ f } } instance : faithful (tensoring_right C) := { map_injective' := λ X Y f g h, begin injections with h, replace h := congr_fun h (𝟙_ C), simpa using h, end } variables {C} /-- Tensoring on the right with `X ⊗ Y` is naturally isomorphic to tensoring on the right with `X`, and then again with `Y`. -/ def tensor_right_tensor (X Y : C) : tensor_right (X ⊗ Y) ≅ tensor_right X ⋙ tensor_right Y := nat_iso.of_components (λ Z, (associator Z X Y).symm) (λ Z Z' f, by { dsimp, rw[←tensor_id], apply associator_inv_naturality }) @[simp] lemma tensor_right_tensor_hom_app (X Y Z : C) : (tensor_right_tensor X Y).hom.app Z = (associator Z X Y).inv := rfl @[simp] lemma tensor_right_tensor_inv_app (X Y Z : C) : (tensor_right_tensor X Y).inv.app Z = (associator Z X Y).hom := by simp [tensor_right_tensor] end end end monoidal_category end category_theory
d4a0cca4fd10fb030f17b6e2bbd947887239a97e
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/measure_theory/covering/vitali.lean
effcc2878ea8eb67c1476c992f582686be0b3520
[ "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
29,677
lean
/- Copyright (c) 2021 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.metric_space.basic import measure_theory.constructions.borel_space import measure_theory.covering.vitali_family /-! # Vitali covering theorems The topological Vitali covering theorem, in its most classical version, states the following. Consider a family of balls `(B (x_i, r_i))_{i ∈ I}` in a metric space, with uniformly bounded radii. Then one can extract a disjoint subfamily indexed by `J ⊆ I`, such that any `B (x_i, r_i)` is included in a ball `B (x_j, 5 r_j)`. We prove this theorem in `vitali.exists_disjoint_subfamily_covering_enlargment_closed_ball`. It is deduced from a more general version, called `vitali.exists_disjoint_subfamily_covering_enlargment`, which applies to any family of sets together with a size function `δ` (think "radius" or "diameter"). We deduce the measurable Vitali covering theorem. Assume one is given a family `t` of closed sets with nonempty interior, such that each `a ∈ t` is included in a ball `B (x, r)` and covers a definite proportion of the ball `B (x, 6 r)` for a given measure `μ` (think of the situation where `μ` is a doubling measure and `t` is a family of balls). Consider a set `s` at which the family is fine, i.e., every point of `s` belongs to arbitrarily small elements of `t`. Then one can extract from `t` a disjoint subfamily that covers almost all `s`. It is proved in `vitali.exists_disjoint_covering_ae`. A way to restate this theorem is to say that the set of closed sets `a` with nonempty interior covering a fixed proportion `1/C` of the ball `closed_ball x (3 * diam a)` forms a Vitali family. This version is given in `vitali.vitali_family`. -/ variables {α : Type*} open set metric measure_theory topological_space filter open_locale nnreal classical ennreal topological_space namespace vitali /-- Vitali covering theorem: given a set `t` of subsets of a type, one may extract a disjoint subfamily `u` such that the `τ`-enlargment of this family covers all elements of `t`, where `τ > 1` is any fixed number. When `t` is a family of balls, the `τ`-enlargment of `ball x r` is `ball x ((1+2τ) r)`. In general, it is expressed in terms of a function `δ` (think "radius" or "diameter"), positive and bounded on all elements of `t`. The condition is that every element `a` of `t` should intersect an element `b` of `u` of size larger than that of `a` up to `τ`, i.e., `δ b ≥ δ a / τ`. -/ theorem exists_disjoint_subfamily_covering_enlargment (t : set (set α)) (δ : set α → ℝ) (τ : ℝ) (hτ : 1 < τ) (δnonneg : ∀ a ∈ t, 0 ≤ δ a) (R : ℝ) (δle : ∀ a ∈ t, δ a ≤ R) (hne : ∀ a ∈ t, set.nonempty a) : ∃ u ⊆ t, u.pairwise_disjoint id ∧ ∀ a ∈ t, ∃ b ∈ u, set.nonempty (a ∩ b) ∧ δ a ≤ τ * δ b := begin /- The proof could be formulated as a transfinite induction. First pick an element of `t` with `δ` as large as possible (up to a factor of `τ`). Then among the remaining elements not intersecting the already chosen one, pick another element with large `δ`. Go on forever (transfinitely) until there is nothing left. Instead, we give a direct Zorn-based argument. Consider a maximal family `u` of disjoint sets with the following property: if an element `a` of `t` intersects some element `b` of `u`, then it intersects some `b' ∈ u` with `δ b' ≥ δ a / τ`. Such a maximal family exists by Zorn. If this family did not intersect some element `a ∈ t`, then take an element `a' ∈ t` which does not intersect any element of `u`, with `δ a'` almost as large as possible. One checks easily that `u ∪ {a'}` still has this property, contradicting the maximality. Therefore, `u` intersects all elements of `t`, and by definition it satisfies all the desired properties. -/ let T : set (set (set α)) := {u | u ⊆ t ∧ u.pairwise_disjoint id ∧ ∀ a ∈ t, ∀ b ∈ u, set.nonempty (a ∩ b) → ∃ c ∈ u, (a ∩ c).nonempty ∧ δ a ≤ τ * δ c}, -- By Zorn, choose a maximal family in the good set `T` of disjoint families. obtain ⟨u, uT, hu⟩ : ∃ u ∈ T, ∀ v ∈ T, u ⊆ v → v = u, { refine zorn.zorn_subset _ (λ U UT hU, _), refine ⟨⋃₀ U, _, λ s hs, subset_sUnion_of_mem hs⟩, simp only [set.sUnion_subset_iff, and_imp, exists_prop, forall_exists_index, set.mem_set_of_eq], refine ⟨λ u hu, (UT hu).1, (pairwise_disjoint_sUnion hU.directed_on).2 (λ u hu, (UT hu).2.1), λ a hat b u uU hbu hab, _⟩, obtain ⟨c, cu, ac, hc⟩ : ∃ (c : set α) (H : c ∈ u), (a ∩ c).nonempty ∧ δ a ≤ τ * δ c := (UT uU).2.2 a hat b hbu hab, exact ⟨c, ⟨u, uU, cu⟩, ac, hc⟩ }, -- the only nontrivial bit is to check that every `a ∈ t` intersects an element `b ∈ u` with -- comparatively large `δ b`. Assume this is not the case, then we will contradict the maximality. refine ⟨u, uT.1, uT.2.1, λ a hat, _⟩, contrapose! hu, have a_disj : ∀ c ∈ u, disjoint a c, { assume c hc, by_contra, rw not_disjoint_iff_nonempty_inter at h, obtain ⟨d, du, ad, hd⟩ : ∃ (d : set α) (H : d ∈ u), (a ∩ d).nonempty ∧ δ a ≤ τ * δ d := uT.2.2 a hat c hc h, exact lt_irrefl _ ((hu d du ad).trans_le hd) }, -- Let `A` be all the elements of `t` which do not intersect the family `u`. It is nonempty as it -- contains `a`. We will pick an element `a'` of `A` with `δ a'` almost as large as possible. let A := {a' | a' ∈ t ∧ ∀ c ∈ u, disjoint a' c}, have Anonempty : A.nonempty := ⟨a, hat, a_disj⟩, let m := Sup (δ '' A), have bddA : bdd_above (δ '' A), { refine ⟨R, λ x xA, _⟩, rcases (mem_image _ _ _).1 xA with ⟨a', ha', rfl⟩, exact δle a' ha'.1 }, obtain ⟨a', a'A, ha'⟩ : ∃ a' ∈ A, m / τ ≤ δ a', { have : 0 ≤ m := (δnonneg a hat).trans (le_cSup bddA (mem_image_of_mem _ ⟨hat, a_disj⟩)), rcases eq_or_lt_of_le this with mzero|mpos, { refine ⟨a, ⟨hat, a_disj⟩, _⟩, simpa only [← mzero, zero_div] using δnonneg a hat }, { have I : m / τ < m, { rw div_lt_iff (zero_lt_one.trans hτ), conv_lhs { rw ← mul_one m }, exact (mul_lt_mul_left mpos).2 hτ }, rcases exists_lt_of_lt_cSup (nonempty_image_iff.2 Anonempty) I with ⟨x, xA, hx⟩, rcases (mem_image _ _ _).1 xA with ⟨a', ha', rfl⟩, exact ⟨a', ha', hx.le⟩, } }, clear hat hu a_disj a, have a'_ne_u : a' ∉ u := λ H, (hne _ a'A.1).ne_empty (disjoint_self.1 (a'A.2 _ H)), -- we claim that `u ∪ {a'}` still belongs to `T`, contradicting the maximality of `u`. refine ⟨insert a' u, ⟨_, _, _⟩, subset_insert _ _, (ne_insert_of_not_mem _ a'_ne_u).symm⟩, -- check that `u ∪ {a'}` is made of elements of `t`. { rw insert_subset, exact ⟨a'A.1, uT.1⟩ }, -- check that `u ∪ {a'}` is a disjoint family. This follows from the fact that `a'` does not -- intersect `u`. { exact uT.2.1.insert (λ b bu ba', a'A.2 b bu) }, -- check that every element `c` of `t` intersecting `u ∪ {a'}` intersects an element of this -- family with large `δ`. { assume c ct b ba'u hcb, -- if `c` already intersects an element of `u`, then it intersects an element of `u` with -- large `δ` by the assumption on `u`, and there is nothing left to do. by_cases H : ∃ d ∈ u, set.nonempty (c ∩ d), { rcases H with ⟨d, du, hd⟩, rcases uT.2.2 c ct d du hd with ⟨d', d'u, hd'⟩, exact ⟨d', mem_insert_of_mem _ d'u, hd'⟩ }, -- otherwise, `c` belongs to `A`. The element of `u ∪ {a'}` that it intersects has to be `a'`. -- moreover, `δ c` is smaller than the maximum `m` of `δ` over `A`, which is `≤ δ a' / τ` -- thanks to the good choice of `a'`. This is the desired inequality. { push_neg at H, simp only [← not_disjoint_iff_nonempty_inter, not_not] at H, rcases mem_insert_iff.1 ba'u with rfl|H', { refine ⟨b, mem_insert _ _, hcb, _⟩, calc δ c ≤ m : le_cSup bddA (mem_image_of_mem _ ⟨ct, H⟩) ... = τ * (m / τ) : by { field_simp [(zero_lt_one.trans hτ).ne'], ring } ... ≤ τ * δ b : mul_le_mul_of_nonneg_left ha' (zero_le_one.trans hτ.le) }, { rw ← not_disjoint_iff_nonempty_inter at hcb, exact (hcb (H _ H')).elim } } } end /-- Vitali covering theorem, closed balls version: given a family `t` of closed balls, one can extract a disjoint subfamily `u ⊆ t` so that all balls in `t` are covered by the 5-times dilations of balls in `u`. -/ theorem exists_disjoint_subfamily_covering_enlargment_closed_ball [metric_space α] (t : set (set α)) (R : ℝ) (ht : ∀ s ∈ t, ∃ x r, s = closed_ball x r ∧ r ≤ R) : ∃ u ⊆ t, u.pairwise_disjoint id ∧ ∀ a ∈ t, ∃ x r, closed_ball x r ∈ u ∧ a ⊆ closed_ball x (5 * r) := begin rcases eq_empty_or_nonempty t with rfl|tnonempty, { exact ⟨∅, subset.refl _, pairwise_disjoint_empty, by simp⟩ }, haveI : inhabited α, { choose s hst using tnonempty, choose x r hxr using ht s hst, exact ⟨x⟩ }, -- Exclude the trivial case where `t` is reduced to the empty set. rcases eq_or_ne t {∅} with rfl|t_ne_empty, { refine ⟨{∅}, subset.refl _, _⟩, simp only [true_and, closed_ball_eq_empty, mem_singleton_iff, and_true, empty_subset, forall_eq, pairwise_disjoint_singleton, exists_const], exact ⟨-1, by simp only [right.neg_neg_iff, zero_lt_one]⟩ }, -- The real proof starts now. Since the center or the radius of a ball is not uniquely defined -- in a general metric space, we just choose one for definiteness. choose! x r hxr using ht, have r_nonneg : ∀ (a : set α), a ∈ t → a.nonempty → 0 ≤ r a, { assume a hat a_nonempty, rw (hxr a hat).1 at a_nonempty, simpa only [nonempty_closed_ball] using a_nonempty }, -- The difference with the generic version is that we are not excluding empty sets in our family -- (which would correspond to `r a < 0`). To compensate for this, we apply the generic version -- to the subfamily `t'` made of nonempty sets, and we use `δ = r` there. This gives a disjointed -- subfamily `u'`. let t' := {a ∈ t | 0 ≤ r a}, obtain ⟨u', u't', u'_disj, hu'⟩ : ∃ u' ⊆ t', u'.pairwise_disjoint id ∧ ∀ a ∈ t', ∃ b ∈ u', set.nonempty (a ∩ b) ∧ r a ≤ 2 * r b, { refine exists_disjoint_subfamily_covering_enlargment t' r 2 one_lt_two (λ a ha, ha.2) R (λ a ha, (hxr a ha.1).2) (λ a ha, _), rw [(hxr a ha.1).1], simp only [ha.2, nonempty_closed_ball] }, -- this subfamily is nonempty, as we have excluded the situation `t = {∅}`. have u'_nonempty : u'.nonempty, { have : ∃ a ∈ t, a ≠ ∅, { contrapose! t_ne_empty, apply subset.antisymm, { simpa only using t_ne_empty }, { rcases tnonempty with ⟨a, hat⟩, have := t_ne_empty a hat, simpa only [this, singleton_subset_iff] using hat } }, rcases this with ⟨a, hat, a_nonempty⟩, have ranonneg : 0 ≤ r a := r_nonneg a hat (ne_empty_iff_nonempty.1 a_nonempty), rcases hu' a ⟨hat, ranonneg⟩ with ⟨b, bu', hb⟩, exact ⟨b, bu'⟩ }, -- check that the family `u'` gives the desired disjoint covering. refine ⟨u', λ a ha, (u't' ha).1, u'_disj, λ a hat, _⟩, -- it remains to check that any ball in `t` is contained in the 5-dilation of a ball -- in `u'`. This depends on whether the ball is empty of not. rcases eq_empty_or_nonempty a with rfl|a_nonempty, -- if the ball is empty, use any element of `u'` (since we know that `u'` is nonempty). { rcases u'_nonempty with ⟨b, hb⟩, refine ⟨x b, r b, _, empty_subset _⟩, rwa ← (hxr b (u't' hb).1).1 }, -- if the ball is not empty, it belongs to `t'`. Then it intersects a ball `a'` in `u'` with -- controlled radius, by definition of `u'`. It is straightforward to check that this ball -- satisfies all the desired properties. { have hat' : a ∈ t' := ⟨hat, r_nonneg a hat a_nonempty⟩, obtain ⟨a', a'u', aa', raa'⟩ : (∃ (a' : set α) (H : a' ∈ u'), (a ∩ a').nonempty ∧ r a ≤ 2 * r a') := hu' a hat', refine ⟨x a', r a', _, _⟩, { convert a'u', exact (hxr a' (u't' a'u').1).1.symm }, { rw (hxr a hat'.1).1 at aa' ⊢, rw (hxr a' (u't' a'u').1).1 at aa', have : dist (x a) (x a') ≤ r a + r a' := dist_le_add_of_nonempty_closed_ball_inter_closed_ball aa', apply closed_ball_subset_closed_ball', linarith } } end /-- The measurable Vitali covering theorem. Assume one is given a family `t` of closed sets with nonempty interior, such that each `a ∈ t` is included in a ball `B (x, r)` and covers a definite proportion of the ball `B (x, 6 r)` for a given measure `μ` (think of the situation where `μ` is a doubling measure and `t` is a family of balls). Consider a (possible non-measurable) set `s` at which the family is fine, i.e., every point of `s` belongs to arbitrarily small elements of `t`. Then one can extract from `t` a disjoint subfamily that covers almost all `s`. -/ theorem exists_disjoint_covering_ae [metric_space α] [measurable_space α] [opens_measurable_space α] [second_countable_topology α] (μ : measure α) [is_locally_finite_measure μ] (s : set α) (t : set (set α)) (hf : ∀ x ∈ s, ∀ (ε > (0 : ℝ)), ∃ a ∈ t, x ∈ a ∧ a ⊆ closed_ball x ε) (ht : ∀ a ∈ t, (interior a).nonempty) (h't : ∀ a ∈ t, is_closed a) (C : ℝ≥0) (h : ∀ a ∈ t, ∃ x ∈ a, μ (closed_ball x (3 * diam a)) ≤ C * μ a) : ∃ u ⊆ t, countable u ∧ u.pairwise_disjoint id ∧ μ (s \ ⋃ (a ∈ u), a) = 0 := begin /- The idea of the proof is the following. Assume for simplicity that `μ` is finite. Applying the abstract Vitali covering theorem with `δ = diam`, one obtains a disjoint subfamily `u`, such that any element of `t` intersects an element of `u` with comparable diameter. Fix `ε > 0`. Since the elements of `u` have summable measure, one can remove finitely elements `w_1, ..., w_n`. so that the measure of the remaining elements is `< ε`. Consider now a point `z` not in the `w_i`. There is a small ball around `z` not intersecting the `w_i` (as they are closed), an element `a ∈ t` contained in this small ball (as the family `t` is fine at `z`) and an element `b ∈ u` intersecting `a`, with comparable diameter (by definition of `u`). Then `z` belongs to the enlargement of `b`. This shows that `s \ (w_1 ∪ ... ∪ w_n)` is contained in `⋃ (b ∈ u \ {w_1, ... w_n}) (enlargement of b)`. The measure of the latter set is bounded by `∑ (b ∈ u \ {w_1, ... w_n}) C * μ b` (by the doubling property of the measure), which is at most `C ε`. Letting `ε` tend to `0` shows that `s` is almost everywhere covered by the family `u`. For the real argument, the measure is only locally finite. Therefore, we implement the same strategy, but locally restricted to balls on which the measure is finite. For this, we do not use the whole family `t`, but a subfamily `t'` supported on small balls (which is possible since the family is assumed to be fine at every point of `s`). -/ rcases eq_empty_or_nonempty s with rfl|nonempty, { refine ⟨∅, empty_subset _, countable_empty, pairwise_disjoint_empty, by simp only [measure_empty, Union_false, Union_empty, diff_self]⟩ }, haveI : inhabited α, { choose x hx using nonempty, exact ⟨x⟩ }, -- choose around each `x` a small ball on which the measure is finite have : ∀ x, ∃ r, 0 < r ∧ r ≤ 1 ∧ μ (closed_ball x (20 * r)) < ∞, { assume x, obtain ⟨R, Rpos, μR⟩ : ∃ (R : ℝ) (hR : 0 < R), μ (closed_ball x R) < ∞ := (μ.finite_at_nhds x).exists_mem_basis nhds_basis_closed_ball, refine ⟨min 1 (R/20), _, min_le_left _ _, _⟩, { simp only [true_and, lt_min_iff, zero_lt_one], linarith }, { apply lt_of_le_of_lt (measure_mono _) μR, apply closed_ball_subset_closed_ball, calc 20 * min 1 (R / 20) ≤ 20 * (R/20) : mul_le_mul_of_nonneg_left (min_le_right _ _) (by norm_num) ... = R : by ring } }, choose r hr using this, -- we restrict to a subfamily `t'` of `t`, made of elements small enough to ensure that -- they only see a finite part of the measure. let t' := {a ∈ t | ∃ x, a ⊆ closed_ball x (r x)}, -- extract a disjoint subfamily `u` of `t'` thanks to the abstract Vitali covering theorem. obtain ⟨u, ut', u_disj, hu⟩ : ∃ u ⊆ t', u.pairwise_disjoint id ∧ ∀ a ∈ t', ∃ b ∈ u, set.nonempty (a ∩ b) ∧ diam a ≤ 2 * diam b, { have A : ∀ (a : set α), a ∈ t' → diam a ≤ 2, { rintros a ⟨hat, ⟨x, hax⟩⟩, calc diam a ≤ diam (closed_ball x (r x)) : diam_mono hax bounded_closed_ball ... ≤ 2 * r x : diam_closed_ball (hr x).1.le ... ≤ 2 * 1 : mul_le_mul_of_nonneg_left (hr x).2.1 zero_le_two ... = 2 : by norm_num }, have B : ∀ (a : set α), a ∈ t' → a.nonempty := λ a hat', set.nonempty.mono interior_subset (ht a hat'.1), exact exists_disjoint_subfamily_covering_enlargment t' diam 2 one_lt_two (λ a ha, diam_nonneg) 2 A B }, have ut : u ⊆ t := λ a hau, (ut' hau).1, -- As the space is second countable, the family is countable since all its sets have nonempty -- interior. have u_count : countable u := u_disj.countable_of_nonempty_interior (λ a ha, ht a (ut ha)), -- the family `u` will be the desired family refine ⟨u, λ a hat', (ut' hat').1, u_count, u_disj, _⟩, -- it suffices to show that it covers almost all `s` locally around each point `x`. refine null_of_locally_null _ (λ x hx, _), -- let `v` be the subfamily of `u` made of those sets intersecting the small ball `ball x (r x)` let v := {a ∈ u | (a ∩ ball x (r x)).nonempty }, have vu : v ⊆ u := λ a ha, ha.1, -- they are all contained in a fixed ball of finite measure, thanks to our choice of `t'` obtain ⟨R, μR, hR⟩ : ∃ R, μ (closed_ball x R) < ∞ ∧ ∀ a ∈ u, (a ∩ ball x (r x)).nonempty → a ⊆ closed_ball x R, { have : ∀ a ∈ u, ∃ y, a ⊆ closed_ball y (r y) := λ a hau, (ut' hau).2, choose! y hy using this, have Idist_v : ∀ a ∈ v, dist (y a) x ≤ r (y a) + r x, { assume a hav, apply dist_le_add_of_nonempty_closed_ball_inter_closed_ball, exact hav.2.mono (inter_subset_inter (hy a hav.1) ball_subset_closed_ball) }, set R0 := Sup ((λ a, r (y a)) '' v) with hR0, have R0_bdd : bdd_above ((λ a, r (y a)) '' v), { refine ⟨1, λ r' hr', _⟩, rcases (mem_image _ _ _).1 hr' with ⟨b, hb, rfl⟩, exact (hr _).2.1 }, rcases le_total R0 (r x) with H|H, { refine ⟨20 * r x, (hr x).2.2, λ a au hax, _⟩, refine (hy a au).trans _, apply closed_ball_subset_closed_ball', have : r (y a) ≤ R0 := le_cSup R0_bdd (mem_image_of_mem _ ⟨au, hax⟩), linarith [(hr (y a)).1.le, (hr x).1.le, Idist_v a ⟨au, hax⟩] }, { have R0pos : 0 < R0 := (hr x).1.trans_le H, have vnonempty : v.nonempty, { by_contra, rw [← ne_empty_iff_nonempty, not_not] at h, simp only [h, real.Sup_empty, image_empty] at hR0, exact lt_irrefl _ (R0pos.trans_le (le_of_eq hR0)) }, obtain ⟨a, hav, R0a⟩ : ∃ a ∈ v, R0/2 < r (y a), { obtain ⟨r', r'mem, hr'⟩ : ∃ r' ∈ ((λ a, r (y a)) '' v), R0 / 2 < r' := exists_lt_of_lt_cSup (nonempty_image_iff.2 vnonempty) (half_lt_self R0pos), rcases (mem_image _ _ _).1 r'mem with ⟨a, hav, rfl⟩, exact ⟨a, hav, hr'⟩ }, refine ⟨8 * R0, _, _⟩, { apply lt_of_le_of_lt (measure_mono _) (hr (y a)).2.2, apply closed_ball_subset_closed_ball', rw dist_comm, linarith [Idist_v a hav] }, { assume b bu hbx, refine (hy b bu).trans _, apply closed_ball_subset_closed_ball', have : r (y b) ≤ R0 := le_cSup R0_bdd (mem_image_of_mem _ ⟨bu, hbx⟩), linarith [Idist_v b ⟨bu, hbx⟩] } } }, -- we will show that, in `ball x (r x)`, almost all `s` is covered by the family `u`. refine ⟨ball x (r x), _, le_antisymm (le_of_forall_le_of_dense (λ ε εpos, _)) bot_le⟩, { apply mem_nhds_within_of_mem_nhds (is_open_ball.mem_nhds _), simp only [(hr x).left, mem_ball, dist_self] }, -- the elements of `v` are disjoint and all contained in a finite volume ball, hence the sum -- of their measures is finite. have I : ∑' (a : v), μ a < ∞, { calc ∑' (a : v), μ a = μ (⋃ (a ∈ v), a) : begin rw measure_bUnion (u_count.mono vu) _ (λ a ha, (h't _ (vu.trans ut ha)).measurable_set), exact u_disj.subset vu end ... ≤ μ (closed_ball x R) : measure_mono (bUnion_subset (λ a ha, hR a (vu ha) ha.2)) ... < ∞ : μR }, -- we can obtain a finite subfamily of `v`, such that the measures of the remaining elements -- add up to an arbitrarily small number, say `ε / C`. obtain ⟨w, hw⟩ : ∃ (w : finset ↥v), ∑' (a : {a // a ∉ w}), μ a < ε / C, { haveI : ne_bot (at_top : filter (finset v)) := at_top_ne_bot, have : 0 < ε / C, by simp only [ennreal.div_pos_iff, εpos.ne', ennreal.coe_ne_top, ne.def, not_false_iff, and_self], exact ((tendsto_order.1 (ennreal.tendsto_tsum_compl_at_top_zero I.ne)).2 _ this).exists }, choose! y hy using h, -- main property: the points `z` of `s` which are not covered by `u` are contained in the -- enlargements of the elements not in `w`. have M : (s \ ⋃ (a : set α) (H : a ∈ u), a) ∩ ball x (r x) ⊆ ⋃ (a : {a // a ∉ w}), closed_ball (y a) (3 * diam (a : set α)), { assume z hz, set k := ⋃ (a : v) (ha : a ∈ w), (a : set α) with hk, have k_closed : is_closed k := is_closed_bUnion w.finite_to_set (λ i hi, h't _ (ut (vu i.2))), have z_notmem_k : z ∉ k, { simp only [not_exists, exists_prop, mem_Union, mem_sep_eq, forall_exists_index, set_coe.exists, not_and, exists_and_distrib_right, subtype.coe_mk], assume b hbv h'b h'z, have : z ∈ (s \ ⋃ (a : set α) (H : a ∈ u), a) ∩ (⋃ (a : set α) (H : a ∈ u), a) := mem_inter (mem_of_mem_inter_left hz) (mem_bUnion (vu hbv) h'z), simpa only [diff_inter_self] }, -- since the elements of `w` are closed and finitely many, one can find a small ball around `z` -- not intersecting them have : ball x (r x) \ k ∈ 𝓝 z, { apply is_open.mem_nhds (is_open_ball.sdiff k_closed) _, exact (mem_diff _).2 ⟨mem_of_mem_inter_right hz, z_notmem_k⟩ }, obtain ⟨d, dpos, hd⟩ : ∃ (d : ℝ) (dpos : 0 < d), closed_ball z d ⊆ ball x (r x) \ k := nhds_basis_closed_ball.mem_iff.1 this, -- choose an element `a` of the family `t` contained in this small ball obtain ⟨a, hat, za, ad⟩ : ∃ a ∈ t, z ∈ a ∧ a ⊆ closed_ball z d := hf z ((mem_diff _).1 (mem_of_mem_inter_left hz)).1 d dpos, have ax : a ⊆ ball x (r x) := ad.trans (hd.trans (diff_subset (ball x (r x)) k)), -- it intersects an element `b` of `u` with comparable diameter, by definition of `u` obtain ⟨b, bu, ab, bdiam⟩ : ∃ (b : set α) (H : b ∈ u), (a ∩ b).nonempty ∧ diam a ≤ 2 * diam b := hu a ⟨hat, ⟨x, ax.trans ball_subset_closed_ball⟩⟩, have bv : b ∈ v, { refine ⟨bu, ab.mono _⟩, rw inter_comm, exact inter_subset_inter_right _ ax }, let b' : v := ⟨b, bv⟩, -- `b` can not belong to `w`, as the elements of `w` do not intersect `closed_ball z d`, -- contrary to `b` have b'_notmem_w : b' ∉ w, { assume b'w, have b'k : (b' : set α) ⊆ k := finset.subset_set_bUnion_of_mem b'w, have : ((ball x (r x) \ k) ∩ k).nonempty := ab.mono (inter_subset_inter (ad.trans hd) b'k), simpa only [diff_inter_self, not_nonempty_empty] }, let b'' : {a // a ∉ w} := ⟨b', b'_notmem_w⟩, -- since `a` and `b` have comparable diameters, it follows that `z` belongs to the -- enlargement of `b` have zb : z ∈ closed_ball (y b) (3 * diam b), { rcases ab with ⟨e, ⟨ea, eb⟩⟩, have A : dist z e ≤ diam a := dist_le_diam_of_mem (bounded_closed_ball.mono ad) za ea, have B : dist e (y b) ≤ diam b, { rcases (ut' bu).2 with ⟨c, hc⟩, apply dist_le_diam_of_mem (bounded_closed_ball.mono hc) eb (hy b (ut bu)).1 }, simp only [mem_closed_ball], linarith [dist_triangle z e (y b)] }, suffices H : closed_ball (y (b'' : set α)) (3 * diam (b'' : set α)) ⊆ ⋃ (a : {a // a ∉ w}), closed_ball (y (a : set α)) (3 * diam (a : set α)), from H zb, exact subset_Union (λ (a : {a // a ∉ w}), closed_ball (y a) (3 * diam (a : set α))) b'' }, -- now that we have proved our main inclusion, we can use it to estimate the measure of the points -- in `ball x (r x)` not covered by `u`. haveI : encodable v := (u_count.mono vu).to_encodable, calc μ ((s \ ⋃ (a : set α) (H : a ∈ u), a) ∩ ball x (r x)) ≤ μ (⋃ (a : {a // a ∉ w}), closed_ball (y a) (3 * diam (a : set α))) : measure_mono M ... ≤ ∑' (a : {a // a ∉ w}), μ (closed_ball (y a) (3 * diam (a : set α))) : measure_Union_le _ ... ≤ ∑' (a : {a // a ∉ w}), C * μ a : ennreal.tsum_le_tsum (λ a, (hy a (ut (vu a.1.2))).2) ... = C * ∑' (a : {a // a ∉ w}), μ a : ennreal.tsum_mul_left ... ≤ C * (ε / C) : ennreal.mul_le_mul le_rfl hw.le ... ≤ ε : ennreal.mul_div_le, end /-- Assume that around every point there are arbitrarily small scales at which the measure is doubling. Then the set of closed sets `a` with nonempty interior covering a fixed proportion `1/C` of the ball `closed_ball x (3 * diam a)` forms a Vitali family. This is essentially a restatement of the measurable Vitali theorem. -/ protected def vitali_family [metric_space α] [measurable_space α] [opens_measurable_space α] [second_countable_topology α] (μ : measure α) [is_locally_finite_measure μ] (C : ℝ≥0) (h : ∀ x (ε > 0), ∃ r ∈ Ioc (0 : ℝ) ε, μ (closed_ball x (6 * r)) ≤ C * μ (closed_ball x r)) : vitali_family μ := { sets_at := λ x, {a | x ∈ a ∧ is_closed a ∧ (interior a).nonempty ∧ μ (closed_ball x (3 * diam a)) ≤ C * μ a}, measurable_set' := λ x a ha, ha.2.1.measurable_set, nonempty_interior := λ x a ha, ha.2.2.1, nontrivial := λ x ε εpos, begin obtain ⟨r, ⟨rpos, rε⟩, μr⟩ : ∃ r ∈ Ioc (0 : ℝ) ε, μ (closed_ball x (6 * r)) ≤ C * μ (closed_ball x r) := h x ε εpos, refine ⟨closed_ball x r, ⟨_, is_closed_ball, _, _⟩, closed_ball_subset_closed_ball rε⟩, { simp only [rpos.le, mem_closed_ball, dist_self] }, { exact (nonempty_ball.2 rpos).mono (ball_subset_interior_closed_ball) }, { apply le_trans (measure_mono (closed_ball_subset_closed_ball _)) μr, have : diam (closed_ball x r) ≤ 2 * r := diam_closed_ball rpos.le, linarith } end, covering := begin assume s f fsubset ffine, rcases eq_empty_or_nonempty s with rfl|H, { exact ⟨∅, λ _, ∅, by simp, by simp⟩ }, haveI : inhabited α, { choose x hx using H, exact ⟨x⟩ }, let t := ⋃ (x ∈ s), f x, have A₁ : ∀ x ∈ s, ∀ (ε : ℝ), 0 < ε → (∃ a ∈ t, x ∈ a ∧ a ⊆ closed_ball x ε), { assume x xs ε εpos, rcases ffine x xs ε εpos with ⟨a, xa, hax⟩, exact ⟨a, mem_bUnion xs xa, (fsubset x xs xa).1, hax⟩ }, have A₂ : ∀ a ∈ t, (interior a).nonempty, { rintros a ha, rcases mem_bUnion_iff.1 ha with ⟨x, xs, xa⟩, exact (fsubset x xs xa).2.2.1 }, have A₃ : ∀ a ∈ t, is_closed a, { rintros a ha, rcases mem_bUnion_iff.1 ha with ⟨x, xs, xa⟩, exact (fsubset x xs xa).2.1 }, have A₄ : ∀ a ∈ t, ∃ x ∈ a, μ (closed_ball x (3 * diam a)) ≤ C * μ a, { rintros a ha, rcases mem_bUnion_iff.1 ha with ⟨x, xs, xa⟩, exact ⟨x, (fsubset x xs xa).1, (fsubset x xs xa).2.2.2⟩ }, obtain ⟨u, ut, u_count, u_disj, μu⟩ : ∃ u ⊆ t, u.countable ∧ u.pairwise disjoint ∧ μ (s \ ⋃ a ∈ u, a) = 0 := exists_disjoint_covering_ae μ s t A₁ A₂ A₃ C A₄, have : ∀ a ∈ u, ∃ x ∈ s, a ∈ f x := λ a ha, mem_bUnion_iff.1 (ut ha), choose! x hx using this, have inj_on_x : inj_on x u, { assume a ha b hb hab, have A : (a ∩ b).nonempty, { refine ⟨x a, mem_inter ((fsubset _ (hx a ha).1 (hx a ha).2).1) _⟩, rw hab, exact (fsubset _ (hx b hb).1 (hx b hb).2).1 }, contrapose A, have : disjoint a b := u_disj a ha b hb A, simpa only [← not_disjoint_iff_nonempty_inter] }, refine ⟨x '' u, function.inv_fun_on x u, _, _, _, _⟩, { assume y hy, rcases (mem_image _ _ _).1 hy with ⟨a, au, rfl⟩, exact (hx a au).1 }, { rw [inj_on_x.pairwise_disjoint_image], assume a ha b hb hab, simp only [function.on_fun, function.inv_fun_on_eq' inj_on_x, ha, hb, (∘)], exact u_disj a ha b hb hab }, { assume y hy, rcases (mem_image _ _ _).1 hy with ⟨a, ha, rfl⟩, rw function.inv_fun_on_eq' inj_on_x ha, exact (hx a ha).2 }, { rw [bUnion_image], convert μu using 3, exact bUnion_congr (λ a ha, function.inv_fun_on_eq' inj_on_x ha) } end } end vitali
ee070ec04194da481e1ce8b72012ee4204f03446
4f643cce24b2d005aeeb5004c2316a8d6cc7f3b1
/src/o_minimal/sheaf/tactic.lean
6b8d6d24645344676eb39a2aa1ecee561d3224b9
[]
no_license
rwbarton/lean-omin
da209ed061d64db65a8f7f71f198064986f30eb9
fd733c6d95ef6f4743aae97de5e15df79877c00e
refs/heads/master
1,674,408,673,325
1,607,343,535,000
1,607,343,535,000
285,150,399
9
0
null
null
null
null
UTF-8
Lean
false
false
9,949
lean
import data.list.alist import o_minimal.sheaf.basic /- Tactics for proving goals of the form ⊢ definable S e notably including the case where `e` is a function. First we implement some ordinary `tactic.interactive` tactics with names of the form `defin_foo`. Then we wrap them in a special `defin` tactic mode. -/ namespace tactic namespace o_minimal /-- Return the local constant (hopefully) representing the definable context. -/ meta def guess_ctx_ty : tactic expr := do `(o_minimal.definable_sheaf.definable (λ (_ : ↥%%var), _)) ← target, return var /-- Return a list of the "definable" variables in the local context. -/ meta def guess_defin_vars (ctx_ty : expr) : tactic (list expr) := do l ← local_context, -- some kind of moption_map? l ← l.mmap (λ var, (do `(o_minimal.definable_sheaf.sect %%ctx_ty %%ty) ← infer_type var, return $ some var) <|> return none), return (l.filter_map id) end o_minimal namespace interactive setup_tactic_parser open tactic.o_minimal /- TODO: * more Lean-like argument parsing, e.g., `intros p q` * probably `app` should automatically try calling `var`, say * what to do about constants? need database of some kind * more tactics? -/ meta def defin_start : tactic unit := `[refine o_minimal.definable.mk (λ Γ, _)] /-- Goal should look like ⊢ definable_sheaf.definable (λ i, λ x, e) We want to "intro" `x` as a definable variable, and leave ⊢ definable_sheaf.definable (λ i, e) as the new goal. Strategy: By `definable_fun_iff` it's enough to check the new goal for an arbitrary context extension `π : Γ' ⟶ Γ` and section `x : sect Γ' α`. However, we also have to move any existing definable variables from `Γ` to `Γ'`. So, we proceed as follows: * Identify the variables `i` (`i_var`) and `Γ` (`ctx_var`) in the goal `definable_sheaf.definable (λ (i : Γ), body)`. Here `body` is expected to be a function whose argument `x` we want to intro. * Use `definable_fun_iff` but then intro only `Γ'` and `π`. * For each existing definable variable `p`, we add a let binding `p' := p.precomp π`. * Now intro the new variable `x` (`new_var`) as well, and build a new function `λ (i' : Γ'), body' (x.to_fun γ')`, by making the following replacements: - each old `p` becomes `p'`; - `i` becomes `i'`; - `Γ` becomes `Γ'`. The claim is that the new expression is well-typed and definitionally equal (in the context of the let-bound variables `p'`, ...) to the current goal. Moreover, it only mentions the new `Γ'` and `p'`. * Now we cover our tracks: - clear the bodies of the let bindings `p'`, so that we can: - clear the old definable variables, `π`, and the old `Γ`. The tactic reuses the same user-visible names for the new `Γ` and `γ`. This is nice for interactive use, but not so nice for debugging the tactic. In the latter case, add `name.append_after _ 1` when generating names. -/ meta def defin_intro (var : parse ident_) : tactic unit := let trace : Π {α : Type} [has_to_tactic_format α] (a : α), tactic unit := λ _ _ _, tactic.skip in -- comment this for debugging do `(o_minimal.definable_sheaf.definable %%f) ← target, ([i_var], body) ← open_n_lambdas f 1, -- `body` might not be a lambda yet, e.g., `function.curry`. -- Reduce it to whnf in hopes of making it a lambda. -- This won't do anything if it was a lambda already. -- It might not always succeed, e.g., in the case of `and`. body ← whnf body, ctx_var ← guess_ctx_ty, trace i_var, trace body, `[refine o_minimal.definable_sheaf.definable_fun_iff.mpr _], new_ctx_var ← tactic.intro ctx_var.local_pp_name, proj_var ← tactic.intro `π, defin_vars ← guess_defin_vars ctx_var, -- do something to them: -- * for each old variable `p`, create a new variable `p'` -- which is let-bound to `p.precomp π` defin_var_list ← defin_vars.mmap (λ dvar, do -- "let p' := p.precomp π," new_body ← to_expr ``((%%dvar).precomp %%proj_var), new_dvar ← tactic.pose dvar.local_pp_name none new_body, return (sigma.mk dvar new_dvar)), new_i_type ← to_expr ``(↥%%new_ctx_var), new_i_var ← mk_local' i_var.local_pp_name f.binding_info new_i_type, -- * replace variables `p` → `p'` in `body`, and also the γ and Γ vars let var_map := (defin_var_list.to_alist.insert i_var new_i_var).insert ctx_var new_ctx_var, let body' := body.replace (λ e _, do -- for "efficiency", first check whether we have a variable at all guard (e.is_local_constant), -- then, look up the whole expression in our map var_map.lookup e), -- do the actual intro new_var ← tactic.intro var, new_var' ← to_expr ``((%%new_var).to_fun %%new_i_var), new_f ← tactic.lambdas [new_i_var] (body'.subst new_var'), trace new_f, new_target ← to_expr ``(o_minimal.definable_sheaf.definable %%new_f), tactic.change new_target, -- for each defin var: -- * forget its let binding (so that we can do the `clear`s below) -- (using `clear_value` from mathlib's `tactic.core`) -- * clear the original variable tactic.clear_value (defin_var_list.map sigma.snd), defin_var_list.mmap (λ ⟨dvar, new_dvar⟩, do tactic.clear dvar), tactic.clear proj_var, tactic.clear ctx_var, return () /-- Goal should look like ⊢ definable_sheaf.definable (λ i, f x) and we want to produce ⊢ definable_sheaf.definable (λ i, f) ⊢ definable_sheaf.definable (λ i, x) This is just `apply definable_sheaf.definable_app`, but Lean needs help with the unification problem. -/ meta def defin_app : tactic unit := do `(o_minimal.definable_sheaf.definable %%e) ← target, ([i_var], body) ← open_n_lambdas e 1, (expr.app f x) ← pure body, f' ← tactic.lambdas [i_var] f, x' ← tactic.lambdas [i_var] x, `[refine o_minimal.definable_sheaf.definable_app %%f' %%x'], return () /-- Goal should look like ⊢ definable_sheaf.definable (λ i, p.to_fun i) where p : Γ ⊢ α. Just apply `sect.definable`. -/ meta def defin_var : tactic unit := `[refine o_minimal.definable_sheaf.sect.definable _] end interactive end tactic meta def defin := tactic meta instance : monad defin := show monad tactic, by apply_instance meta instance : interactive.executor defin := { config_type := unit, inhabited := by apply_instance, execute_with := λ _ tac, tactic.interactive.defin_start >> tac } namespace defin -- TODO: -- * tactic display not quite done (need `compact`) meta def step := @tactic.step meta def istep := @tactic.istep meta def solve1 : defin unit → defin unit := tactic.solve1 -- Tactic state display borrows liberally from -- https://github.com/unitb/temporal-logic -- file temporal_logic.tactic /-- Replace any occurrences of `p.to_fun γ` with simply `p`. This is rather crude, but these aren't expected to appear outside the execution of a defin tactic. (More sophisticated would be to process only those variables which are sections over the context variable that appears in the goal.) The resulting expression is intended to be used for display purposes. -/ meta def shorten (E : expr) : expr := E.replace $ λ e _, match e with | `(o_minimal.definable_sheaf.sect.to_fun %%p _) := some p | _ := none end section display open tactic meta structure hyp_data : Type := (crisp : bool) (var : expr) (ty : expr) (val : option expr) /-- Return information about a local hypothesis `l`. -/ meta def get_hyp_data (l : expr) : defin hyp_data := do ty ← infer_type l, val ← try_core (shorten <$> local_def_value l), match ty with | `(o_minimal.definable_sheaf.sect %%Γ %%ty') := return ⟨ff, l, shorten ty', val⟩ | _ := return ⟨tt, l, shorten ty, val⟩ end meta def decl_to_fmt (s : tactic_state) (crisp : bool) (vs : list expr) (ty : expr) (val : option expr) : format := let vs' := format.join $ (vs.map s.format_expr).intersperse " ", t := s.format_expr ty, sep := if crisp then "::" else ":" in match val with | (some val) := format! "{vs'} {sep} {t} := {s.format_expr val}" | none := format! "{vs'} {sep} {t}" end meta def goal_to_fmt (g : expr) : defin (thunk format) := do set_goals [g], s ← read, `(o_minimal.definable_sheaf.definable (λ (_ : ↥%%Γ), %%body)) ← target | pure (λ _, to_fmt s), lc ← local_context, ctx_var ← tactic.o_minimal.guess_ctx_ty, dat ← (lc.filter (λ l, l ≠ ctx_var)).mmap get_hyp_data, return $ λ _, format.intercalate format.line [format.intercalate ("," ++ format.line) $ dat.map $ λ d, decl_to_fmt s d.crisp [d.var] d.ty d.val, format! "⊢ {s.format_expr (shorten body)} def"] meta def save_info (p : pos) : defin unit := do gs ← get_goals, fmt ← gs.mmap goal_to_fmt, set_goals gs, tactic.save_info_thunk p (λ _, let header := if fmt.length > 1 then format! "{fmt.length} goals\n" else "", eval : thunk format → format := λ f, f () in if fmt.empty then "no goals" else format.join ((fmt.map eval).intersperse (format.line ++ format.line))) end display namespace interactive meta def swap := tactic.interactive.swap meta def exact := tactic.interactive.exact meta def solve1 : defin unit → defin unit := tactic.interactive.solve1 meta def intro := tactic.interactive.defin_intro meta def app := tactic.interactive.defin_app meta def var := tactic.interactive.defin_var /-- Display the actual, underlying tactic state. -/ meta def trace_state : defin unit := do s ← tactic.read, tactic.trace s.to_format end interactive end defin namespace o_minimal variables {R : Type*} [S : struc R] variables {X Y Z : Type*} [definable_sheaf S X] [definable_sheaf S Y] [definable_sheaf S Z] example : definable S (@function.curry X Y Z) := begin [defin] intro f, intro x, intro y, app, { var }, { exact ⟨x.definable, y.definable⟩ } end end o_minimal
d1137fb8e8f7f4929fc7a6ded5908d969bff437e
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/data/fintype/basic.lean
82ad9c6d8e00c87a32ffc99d050d4023369d1516
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
41,188
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Finite types. -/ import data.finset import data.array.lemmas universes u v variables {α : Type*} {β : Type*} {γ : Type*} /-- `fintype α` means that `α` is finite, i.e. there are only finitely many distinct elements of type `α`. The evidence of this is a finset `elems` (a list up to permutation without duplicates), together with a proof that everything of type `α` is in the list. -/ class fintype (α : Type*) := (elems [] : finset α) (complete : ∀ x : α, x ∈ elems) namespace finset variable [fintype α] /-- `univ` is the universal finite set of type `finset α` implied from the assumption `fintype α`. -/ def univ : finset α := fintype.elems α @[simp] theorem mem_univ (x : α) : x ∈ (univ : finset α) := fintype.complete x @[simp] theorem mem_univ_val : ∀ x, x ∈ (univ : finset α).1 := mem_univ @[simp] lemma coe_univ : ↑(univ : finset α) = (set.univ : set α) := by ext; simp theorem subset_univ (s : finset α) : s ⊆ univ := λ a _, mem_univ a theorem eq_univ_iff_forall {s : finset α} : s = univ ↔ ∀ x, x ∈ s := by simp [ext] @[simp] lemma univ_inter [decidable_eq α] (s : finset α) : univ ∩ s = s := ext' $ λ a, by simp @[simp] lemma inter_univ [decidable_eq α] (s : finset α) : s ∩ univ = s := by rw [inter_comm, univ_inter] @[simp] lemma piecewise_univ [∀i : α, decidable (i ∈ (univ : finset α))] {δ : α → Sort*} (f g : Πi, δ i) : univ.piecewise f g = f := by { ext i, simp [piecewise] } lemma univ_map_equiv_to_embedding {α β : Type*} [fintype α] [fintype β] (e : α ≃ β) : univ.map e.to_embedding = univ := begin apply eq_univ_iff_forall.mpr, intro b, rw [mem_map], use e.symm b, simp, end end finset open finset function namespace fintype instance decidable_pi_fintype {α} {β : α → Type*} [∀a, decidable_eq (β a)] [fintype α] : decidable_eq (Πa, β a) := assume f g, decidable_of_iff (∀ a ∈ fintype.elems α, f a = g a) (by simp [function.funext_iff, fintype.complete]) instance decidable_forall_fintype {p : α → Prop} [decidable_pred p] [fintype α] : decidable (∀ a, p a) := decidable_of_iff (∀ a ∈ @univ α _, p a) (by simp) instance decidable_exists_fintype {p : α → Prop} [decidable_pred p] [fintype α] : decidable (∃ a, p a) := decidable_of_iff (∃ a ∈ @univ α _, p a) (by simp) instance decidable_eq_equiv_fintype [decidable_eq β] [fintype α] : decidable_eq (α ≃ β) := λ a b, decidable_of_iff (a.1 = b.1) ⟨λ h, equiv.ext (congr_fun h), congr_arg _⟩ instance decidable_injective_fintype [decidable_eq α] [decidable_eq β] [fintype α] : decidable_pred (injective : (α → β) → Prop) := λ x, by unfold injective; apply_instance instance decidable_surjective_fintype [decidable_eq β] [fintype α] [fintype β] : decidable_pred (surjective : (α → β) → Prop) := λ x, by unfold surjective; apply_instance instance decidable_bijective_fintype [decidable_eq α] [decidable_eq β] [fintype α] [fintype β] : decidable_pred (bijective : (α → β) → Prop) := λ x, by unfold bijective; apply_instance instance decidable_left_inverse_fintype [decidable_eq α] [fintype α] (f : α → β) (g : β → α) : decidable (function.right_inverse f g) := show decidable (∀ x, g (f x) = x), by apply_instance instance decidable_right_inverse_fintype [decidable_eq β] [fintype β] (f : α → β) (g : β → α) : decidable (function.left_inverse f g) := show decidable (∀ x, f (g x) = x), by apply_instance /-- Construct a proof of `fintype α` from a universal multiset -/ def of_multiset [decidable_eq α] (s : multiset α) (H : ∀ x : α, x ∈ s) : fintype α := ⟨s.to_finset, by simpa using H⟩ /-- Construct a proof of `fintype α` from a universal list -/ def of_list [decidable_eq α] (l : list α) (H : ∀ x : α, x ∈ l) : fintype α := ⟨l.to_finset, by simpa using H⟩ theorem exists_univ_list (α) [fintype α] : ∃ l : list α, l.nodup ∧ ∀ x : α, x ∈ l := let ⟨l, e⟩ := quotient.exists_rep (@univ α _).1 in by have := and.intro univ.2 mem_univ_val; exact ⟨_, by rwa ← e at this⟩ /-- `card α` is the number of elements in `α`, defined when `α` is a fintype. -/ def card (α) [fintype α] : ℕ := (@univ α _).card /-- If `l` lists all the elements of `α` without duplicates, then `α ≃ fin (l.length)`. -/ def equiv_fin_of_forall_mem_list {α} [decidable_eq α] {l : list α} (h : ∀ x:α, x ∈ l) (nd : l.nodup) : α ≃ fin (l.length) := ⟨λ a, ⟨_, list.index_of_lt_length.2 (h a)⟩, λ i, l.nth_le i.1 i.2, λ a, by simp, λ ⟨i, h⟩, fin.eq_of_veq $ list.nodup_iff_nth_le_inj.1 nd _ _ (list.index_of_lt_length.2 (list.nth_le_mem _ _ _)) h $ by simp⟩ /-- There is (computably) a bijection between `α` and `fin n` where `n = card α`. Since it is not unique, and depends on which permutation of the universe list is used, the bijection is wrapped in `trunc` to preserve computability. -/ def equiv_fin (α) [fintype α] [decidable_eq α] : trunc (α ≃ fin (card α)) := by unfold card finset.card; exact quot.rec_on_subsingleton (@univ α _).1 (λ l (h : ∀ x:α, x ∈ l) (nd : l.nodup), trunc.mk (equiv_fin_of_forall_mem_list h nd)) mem_univ_val univ.2 theorem exists_equiv_fin (α) [fintype α] : ∃ n, nonempty (α ≃ fin n) := by haveI := classical.dec_eq α; exact ⟨card α, nonempty_of_trunc (equiv_fin α)⟩ /-- Given a linearly ordered fintype `α` of cardinal `k`, the equiv `mono_equiv_of_fin α h` is the increasing bijection between `fin k` and `α`. Here, `h` is a proof that the cardinality of `s` is `k`. We use this instead of a map `fin s.card → α` to avoid casting issues in further uses of this function. -/ noncomputable def mono_equiv_of_fin (α) [fintype α] [decidable_linear_order α] {k : ℕ} (h : fintype.card α = k) : fin k ≃ α := have A : bijective (mono_of_fin univ h) := begin apply set.bijective_iff_bij_on_univ.2, rw ← @coe_univ α _, exact mono_of_fin_bij_on (univ : finset α) h end, equiv.of_bijective A instance (α : Type*) : subsingleton (fintype α) := ⟨λ ⟨s₁, h₁⟩ ⟨s₂, h₂⟩, by congr; simp [finset.ext, h₁, h₂]⟩ protected def subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : fintype {x // p x} := ⟨⟨multiset.pmap subtype.mk s.1 (λ x, (H x).1), multiset.nodup_pmap (λ a _ b _, congr_arg subtype.val) s.2⟩, λ ⟨x, px⟩, multiset.mem_pmap.2 ⟨x, (H x).2 px, rfl⟩⟩ theorem subtype_card {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : @card {x // p x} (fintype.subtype s H) = s.card := multiset.card_pmap _ _ _ theorem card_of_subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) [fintype {x // p x}] : card {x // p x} = s.card := by rw ← subtype_card s H; congr /-- Construct a fintype from a finset with the same elements. -/ def of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : fintype p := fintype.subtype s H @[simp] theorem card_of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : @fintype.card p (of_finset s H) = s.card := fintype.subtype_card s H theorem card_of_finset' {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) [fintype p] : fintype.card p = s.card := by rw ← card_of_finset s H; congr /-- If `f : α → β` is a bijection and `α` is a fintype, then `β` is also a fintype. -/ def of_bijective [fintype α] (f : α → β) (H : function.bijective f) : fintype β := ⟨univ.map ⟨f, H.1⟩, λ b, let ⟨a, e⟩ := H.2 b in e ▸ mem_map_of_mem _ (mem_univ _)⟩ /-- If `f : α → β` is a surjection and `α` is a fintype, then `β` is also a fintype. -/ def of_surjective [fintype α] [decidable_eq β] (f : α → β) (H : function.surjective f) : fintype β := ⟨univ.image f, λ b, let ⟨a, e⟩ := H b in e ▸ mem_image_of_mem _ (mem_univ _)⟩ noncomputable def of_injective [fintype β] (f : α → β) (H : function.injective f) : fintype α := by letI := classical.dec; exact if hα : nonempty α then by letI := classical.inhabited_of_nonempty hα; exact of_surjective (inv_fun f) (inv_fun_surjective H) else ⟨∅, λ x, (hα ⟨x⟩).elim⟩ /-- If `f : α ≃ β` and `α` is a fintype, then `β` is also a fintype. -/ def of_equiv (α : Type*) [fintype α] (f : α ≃ β) : fintype β := of_bijective _ f.bijective theorem of_equiv_card [fintype α] (f : α ≃ β) : @card β (of_equiv α f) = card α := multiset.card_map _ _ theorem card_congr {α β} [fintype α] [fintype β] (f : α ≃ β) : card α = card β := by rw ← of_equiv_card f; congr theorem card_eq {α β} [F : fintype α] [G : fintype β] : card α = card β ↔ nonempty (α ≃ β) := ⟨λ h, ⟨by classical; calc α ≃ fin (card α) : trunc.out (equiv_fin α) ... ≃ fin (card β) : by rw h ... ≃ β : (trunc.out (equiv_fin β)).symm⟩, λ ⟨f⟩, card_congr f⟩ def of_subsingleton (a : α) [subsingleton α] : fintype α := ⟨{a}, λ b, finset.mem_singleton.2 (subsingleton.elim _ _)⟩ @[simp] theorem univ_of_subsingleton (a : α) [subsingleton α] : @univ _ (of_subsingleton a) = {a} := rfl @[simp] theorem card_of_subsingleton (a : α) [subsingleton α] : @fintype.card _ (of_subsingleton a) = 1 := rfl end fintype namespace set /-- Construct a finset enumerating a set `s`, given a `fintype` instance. -/ def to_finset (s : set α) [fintype s] : finset α := ⟨(@finset.univ s _).1.map subtype.val, multiset.nodup_map (λ a b, subtype.eq) finset.univ.2⟩ @[simp] theorem mem_to_finset {s : set α} [fintype s] {a : α} : a ∈ s.to_finset ↔ a ∈ s := by simp [to_finset] @[simp] theorem mem_to_finset_val {s : set α} [fintype s] {a : α} : a ∈ s.to_finset.1 ↔ a ∈ s := mem_to_finset @[simp] theorem coe_to_finset (s : set α) [fintype s] : (↑s.to_finset : set α) = s := set.ext $ λ _, mem_to_finset end set lemma finset.card_univ [fintype α] : (finset.univ : finset α).card = fintype.card α := rfl lemma finset.card_univ_diff [fintype α] [decidable_eq α] (s : finset α) : (finset.univ \ s).card = fintype.card α - s.card := finset.card_sdiff (subset_univ s) instance (n : ℕ) : fintype (fin n) := ⟨⟨list.fin_range n, list.nodup_fin_range n⟩, list.mem_fin_range⟩ @[simp] theorem fintype.card_fin (n : ℕ) : fintype.card (fin n) = n := list.length_fin_range n @[simp] lemma finset.card_fin (n : ℕ) : finset.card (finset.univ : finset (fin n)) = n := by rw [finset.card_univ, fintype.card_fin] lemma fin.univ_succ (n : ℕ) : (univ : finset (fin $ n+1)) = insert 0 (univ.image fin.succ) := begin ext m, simp only [mem_univ, mem_insert, true_iff, mem_image, exists_prop], exact fin.cases (or.inl rfl) (λ i, or.inr ⟨i, trivial, rfl⟩) m end lemma fin.univ_cast_succ (n : ℕ) : (univ : finset (fin $ n+1)) = insert (fin.last n) (univ.image fin.cast_succ) := begin ext m, simp only [mem_univ, mem_insert, true_iff, mem_image, exists_prop, true_and], by_cases h : m.val < n, { right, use fin.cast_lt m h, rw fin.cast_succ_cast_lt }, { left, exact fin.eq_last_of_not_lt h } end /-- Any increasing map between `fin k` and a finset of cardinality `k` has to coincide with the increasing bijection `mono_of_fin s h`. -/ lemma finset.mono_of_fin_unique' [decidable_linear_order α] {s : finset α} {k : ℕ} (h : s.card = k) {f : fin k → α} (fmap : set.maps_to f set.univ ↑s) (hmono : strict_mono f) : f = s.mono_of_fin h := begin have finj : set.inj_on f set.univ := hmono.injective.inj_on _, apply mono_of_fin_unique h (set.bij_on.mk fmap finj (λ y hy, _)) hmono, simp only [set.image_univ, set.mem_range], rcases surj_on_of_inj_on_of_card_le (λ i (hi : i ∈ finset.univ), f i) (λ i hi, fmap (set.mem_univ i)) (λ i j hi hj hij, finj (set.mem_univ i) (set.mem_univ j) hij) (by simp [h]) y hy with ⟨x, _, hx⟩, exact ⟨x, hx.symm⟩ end @[instance, priority 10] def unique.fintype {α : Type*} [unique α] : fintype α := fintype.of_subsingleton (default α) @[simp] lemma univ_unique {α : Type*} [unique α] [f : fintype α] : @finset.univ α _ = {default α} := by rw [subsingleton.elim f (@unique.fintype α _)]; refl instance : fintype empty := ⟨∅, empty.rec _⟩ @[simp] theorem fintype.univ_empty : @univ empty _ = ∅ := rfl @[simp] theorem fintype.card_empty : fintype.card empty = 0 := rfl instance : fintype pempty := ⟨∅, pempty.rec _⟩ @[simp] theorem fintype.univ_pempty : @univ pempty _ = ∅ := rfl @[simp] theorem fintype.card_pempty : fintype.card pempty = 0 := rfl instance : fintype unit := fintype.of_subsingleton () theorem fintype.univ_unit : @univ unit _ = {()} := rfl theorem fintype.card_unit : fintype.card unit = 1 := rfl instance : fintype punit := fintype.of_subsingleton punit.star @[simp] theorem fintype.univ_punit : @univ punit _ = {punit.star} := rfl @[simp] theorem fintype.card_punit : fintype.card punit = 1 := rfl instance : fintype bool := ⟨⟨tt::ff::0, by simp⟩, λ x, by cases x; simp⟩ @[simp] theorem fintype.univ_bool : @univ bool _ = {tt, ff} := rfl instance units_int.fintype : fintype (units ℤ) := ⟨{1, -1}, λ x, by cases int.units_eq_one_or x; simp *⟩ instance additive.fintype : Π [fintype α], fintype (additive α) := id instance multiplicative.fintype : Π [fintype α], fintype (multiplicative α) := id @[simp] theorem fintype.card_units_int : fintype.card (units ℤ) = 2 := rfl noncomputable instance [monoid α] [fintype α] : fintype (units α) := by classical; exact fintype.of_injective units.val units.ext @[simp] theorem fintype.card_bool : fintype.card bool = 2 := rfl def finset.insert_none (s : finset α) : finset (option α) := ⟨none :: s.1.map some, multiset.nodup_cons.2 ⟨by simp, multiset.nodup_map (λ a b, option.some.inj) s.2⟩⟩ @[simp] theorem finset.mem_insert_none {s : finset α} : ∀ {o : option α}, o ∈ s.insert_none ↔ ∀ a ∈ o, a ∈ s | none := iff_of_true (multiset.mem_cons_self _ _) (λ a h, by cases h) | (some a) := multiset.mem_cons.trans $ by simp; refl theorem finset.some_mem_insert_none {s : finset α} {a : α} : some a ∈ s.insert_none ↔ a ∈ s := by simp instance {α : Type*} [fintype α] : fintype (option α) := ⟨univ.insert_none, λ a, by simp⟩ @[simp] theorem fintype.card_option {α : Type*} [fintype α] : fintype.card (option α) = fintype.card α + 1 := (multiset.card_cons _ _).trans (by rw multiset.card_map; refl) instance {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype (sigma β) := ⟨univ.sigma (λ _, univ), λ ⟨a, b⟩, by simp⟩ @[simp] lemma finset.univ_sigma_univ {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] : (univ : finset α).sigma (λ a, (univ : finset (β a))) = univ := rfl instance (α β : Type*) [fintype α] [fintype β] : fintype (α × β) := ⟨univ.product univ, λ ⟨a, b⟩, by simp⟩ @[simp] theorem fintype.card_prod (α β : Type*) [fintype α] [fintype β] : fintype.card (α × β) = fintype.card α * fintype.card β := card_product _ _ def fintype.fintype_prod_left {α β} [decidable_eq α] [fintype (α × β)] [nonempty β] : fintype α := ⟨(fintype.elems (α × β)).image prod.fst, assume a, let ⟨b⟩ := ‹nonempty β› in by simp; exact ⟨b, fintype.complete _⟩⟩ def fintype.fintype_prod_right {α β} [decidable_eq β] [fintype (α × β)] [nonempty α] : fintype β := ⟨(fintype.elems (α × β)).image prod.snd, assume b, let ⟨a⟩ := ‹nonempty α› in by simp; exact ⟨a, fintype.complete _⟩⟩ instance (α : Type*) [fintype α] : fintype (ulift α) := fintype.of_equiv _ equiv.ulift.symm @[simp] theorem fintype.card_ulift (α : Type*) [fintype α] : fintype.card (ulift α) = fintype.card α := fintype.of_equiv_card _ instance (α : Type u) (β : Type v) [fintype α] [fintype β] : fintype (α ⊕ β) := @fintype.of_equiv _ _ (@sigma.fintype _ (λ b, cond b (ulift α) (ulift.{(max u v) v} β)) _ (λ b, by cases b; apply ulift.fintype)) ((equiv.sum_equiv_sigma_bool _ _).symm.trans (equiv.sum_congr equiv.ulift equiv.ulift)) lemma fintype.card_le_of_injective [fintype α] [fintype β] (f : α → β) (hf : function.injective f) : fintype.card α ≤ fintype.card β := by haveI := classical.prop_decidable; exact finset.card_le_card_of_inj_on f (λ _ _, finset.mem_univ _) (λ _ _ _ _ h, hf h) lemma fintype.card_eq_one_iff [fintype α] : fintype.card α = 1 ↔ (∃ x : α, ∀ y, y = x) := by rw [← fintype.card_unit, fintype.card_eq]; exact ⟨λ ⟨a⟩, ⟨a.symm (), λ y, a.injective (subsingleton.elim _ _)⟩, λ ⟨x, hx⟩, ⟨⟨λ _, (), λ _, x, λ _, (hx _).trans (hx _).symm, λ _, subsingleton.elim _ _⟩⟩⟩ lemma fintype.card_eq_zero_iff [fintype α] : fintype.card α = 0 ↔ (α → false) := ⟨λ h a, have e : α ≃ empty := classical.choice (fintype.card_eq.1 (by simp [h])), (e a).elim, λ h, have e : α ≃ empty := ⟨λ a, (h a).elim, λ a, a.elim, λ a, (h a).elim, λ a, a.elim⟩, by simp [fintype.card_congr e]⟩ lemma fintype.card_pos_iff [fintype α] : 0 < fintype.card α ↔ nonempty α := ⟨λ h, classical.by_contradiction (λ h₁, have fintype.card α = 0 := fintype.card_eq_zero_iff.2 (λ a, h₁ ⟨a⟩), lt_irrefl 0 $ by rwa this at h), λ ⟨a⟩, nat.pos_of_ne_zero (mt fintype.card_eq_zero_iff.1 (λ h, h a))⟩ lemma fintype.card_le_one_iff [fintype α] : fintype.card α ≤ 1 ↔ (∀ a b : α, a = b) := let n := fintype.card α in have hn : n = fintype.card α := rfl, match n, hn with | 0 := λ ha, ⟨λ h, λ a, (fintype.card_eq_zero_iff.1 ha.symm a).elim, λ _, ha ▸ nat.le_succ _⟩ | 1 := λ ha, ⟨λ h, λ a b, let ⟨x, hx⟩ := fintype.card_eq_one_iff.1 ha.symm in by rw [hx a, hx b], λ _, ha ▸ le_refl _⟩ | (n+2) := λ ha, ⟨λ h, by rw ← ha at h; exact absurd h dec_trivial, (λ h, fintype.card_unit ▸ fintype.card_le_of_injective (λ _, ()) (λ _ _ _, h _ _))⟩ end lemma fintype.exists_ne_of_one_lt_card [fintype α] (h : 1 < fintype.card α) (a : α) : ∃ b : α, b ≠ a := let ⟨b, hb⟩ := classical.not_forall.1 (mt fintype.card_le_one_iff.2 (not_le_of_gt h)) in let ⟨c, hc⟩ := classical.not_forall.1 hb in by haveI := classical.dec_eq α; exact if hba : b = a then ⟨c, by cc⟩ else ⟨b, hba⟩ lemma fintype.exists_pair_of_one_lt_card [fintype α] (h : 1 < fintype.card α) : ∃ (a b : α), b ≠ a := begin rcases fintype.card_pos_iff.1 (nat.lt_of_succ_lt h) with a, exact ⟨a, fintype.exists_ne_of_one_lt_card h a⟩, end lemma fintype.injective_iff_surjective [fintype α] {f : α → α} : injective f ↔ surjective f := by haveI := classical.prop_decidable; exact have ∀ {f : α → α}, injective f → surjective f, from λ f hinj x, have h₁ : image f univ = univ := eq_of_subset_of_card_le (subset_univ _) ((card_image_of_injective univ hinj).symm ▸ le_refl _), have h₂ : x ∈ image f univ := h₁.symm ▸ mem_univ _, exists_of_bex (mem_image.1 h₂), ⟨this, λ hsurj, has_left_inverse.injective ⟨surj_inv hsurj, left_inverse_of_surjective_of_right_inverse (this (injective_surj_inv _)) (right_inverse_surj_inv _)⟩⟩ lemma fintype.injective_iff_bijective [fintype α] {f : α → α} : injective f ↔ bijective f := by simp [bijective, fintype.injective_iff_surjective] lemma fintype.surjective_iff_bijective [fintype α] {f : α → α} : surjective f ↔ bijective f := by simp [bijective, fintype.injective_iff_surjective] lemma fintype.injective_iff_surjective_of_equiv [fintype α] {f : α → β} (e : α ≃ β) : injective f ↔ surjective f := have injective (e.symm ∘ f) ↔ surjective (e.symm ∘ f), from fintype.injective_iff_surjective, ⟨λ hinj, by simpa [function.comp] using e.surjective.comp (this.1 (e.symm.injective.comp hinj)), λ hsurj, by simpa [function.comp] using e.injective.comp (this.2 (e.symm.surjective.comp hsurj))⟩ lemma fintype.coe_image_univ [fintype α] [decidable_eq β] {f : α → β} : ↑(finset.image f finset.univ) = set.range f := by { ext x, simp } instance list.subtype.fintype [decidable_eq α] (l : list α) : fintype {x // x ∈ l} := fintype.of_list l.attach l.mem_attach instance multiset.subtype.fintype [decidable_eq α] (s : multiset α) : fintype {x // x ∈ s} := fintype.of_multiset s.attach s.mem_attach instance finset.subtype.fintype (s : finset α) : fintype {x // x ∈ s} := ⟨s.attach, s.mem_attach⟩ instance finset_coe.fintype (s : finset α) : fintype (↑s : set α) := finset.subtype.fintype s @[simp] lemma fintype.card_coe (s : finset α) : fintype.card (↑s : set α) = s.card := card_attach lemma finset.card_le_one_iff {s : finset α} : s.card ≤ 1 ↔ ∀ {x y}, x ∈ s → y ∈ s → x = y := begin let t : set α := ↑s, letI : fintype t := finset_coe.fintype s, have : fintype.card t = s.card := fintype.card_coe s, rw [← this, fintype.card_le_one_iff], split, { assume H x y hx hy, exact subtype.mk.inj (H ⟨x, hx⟩ ⟨y, hy⟩) }, { assume H x y, exact subtype.eq (H x.2 y.2) } end lemma finset.one_lt_card_iff {s : finset α} : 1 < s.card ↔ ∃ x y, (x ∈ s) ∧ (y ∈ s) ∧ x ≠ y := begin classical, rw ← not_iff_not, push_neg, simpa [classical.or_iff_not_imp_left] using finset.card_le_one_iff end instance plift.fintype (p : Prop) [decidable p] : fintype (plift p) := ⟨if h : p then {⟨h⟩} else ∅, λ ⟨h⟩, by simp [h]⟩ instance Prop.fintype : fintype Prop := ⟨⟨true::false::0, by simp [true_ne_false]⟩, classical.cases (by simp) (by simp)⟩ def set_fintype {α} [fintype α] (s : set α) [decidable_pred s] : fintype s := fintype.subtype (univ.filter (∈ s)) (by simp) namespace function.embedding /-- An embedding from a `fintype` to itself can be promoted to an equivalence. -/ noncomputable def equiv_of_fintype_self_embedding {α : Type*} [fintype α] (e : α ↪ α) : α ≃ α := equiv.of_bijective (fintype.injective_iff_bijective.1 e.2) @[simp] lemma equiv_of_fintype_self_embedding_to_embedding {α : Type*} [fintype α] (e : α ↪ α) : e.equiv_of_fintype_self_embedding.to_embedding = e := by { ext, refl, } end function.embedding @[simp] lemma finset.univ_map_embedding {α : Type*} [fintype α] (e : α ↪ α) : univ.map e = univ := by rw [← e.equiv_of_fintype_self_embedding_to_embedding, univ_map_equiv_to_embedding] namespace fintype variables [fintype α] [decidable_eq α] {δ : α → Type*} /-- Given for all `a : α` a finset `t a` of `δ a`, then one can define the finset `fintype.pi_finset t` of all functions taking values in `t a` for all `a`. This is the analogue of `finset.pi` where the base finset is `univ` (but formally they are not the same, as there is an additional condition `i ∈ finset.univ` in the `finset.pi` definition). -/ def pi_finset (t : Πa, finset (δ a)) : finset (Πa, δ a) := (finset.univ.pi t).map ⟨λ f a, f a (mem_univ a), λ _ _, by simp [function.funext_iff]⟩ @[simp] lemma mem_pi_finset {t : Πa, finset (δ a)} {f : Πa, δ a} : f ∈ pi_finset t ↔ (∀a, f a ∈ t a) := begin split, { simp only [pi_finset, mem_map, and_imp, forall_prop_of_true, exists_prop, mem_univ, exists_imp_distrib, mem_pi], assume g hg hgf a, rw ← hgf, exact hg a }, { simp only [pi_finset, mem_map, forall_prop_of_true, exists_prop, mem_univ, mem_pi], assume hf, exact ⟨λ a ha, f a, hf, rfl⟩ } end lemma pi_finset_subset (t₁ t₂ : Πa, finset (δ a)) (h : ∀ a, t₁ a ⊆ t₂ a) : pi_finset t₁ ⊆ pi_finset t₂ := λ g hg, mem_pi_finset.2 $ λ a, h a $ mem_pi_finset.1 hg a lemma pi_finset_disjoint_of_disjoint [∀ a, decidable_eq (δ a)] (t₁ t₂ : Πa, finset (δ a)) {a : α} (h : disjoint (t₁ a) (t₂ a)) : disjoint (pi_finset t₁) (pi_finset t₂) := disjoint_iff_ne.2 $ λ f₁ hf₁ f₂ hf₂ eq₁₂, disjoint_iff_ne.1 h (f₁ a) (mem_pi_finset.1 hf₁ a) (f₂ a) (mem_pi_finset.1 hf₂ a) (congr_fun eq₁₂ a) end fintype /-! ### pi -/ /-- A dependent product of fintypes, indexed by a fintype, is a fintype. -/ instance pi.fintype {α : Type*} {β : α → Type*} [decidable_eq α] [fintype α] [∀a, fintype (β a)] : fintype (Πa, β a) := ⟨fintype.pi_finset (λ _, univ), by simp⟩ @[simp] lemma fintype.pi_finset_univ {α : Type*} {β : α → Type*} [decidable_eq α] [fintype α] [∀a, fintype (β a)] : fintype.pi_finset (λ a : α, (finset.univ : finset (β a))) = (finset.univ : finset (Π a, β a)) := rfl instance d_array.fintype {n : ℕ} {α : fin n → Type*} [∀n, fintype (α n)] : fintype (d_array n α) := fintype.of_equiv _ (equiv.d_array_equiv_fin _).symm instance array.fintype {n : ℕ} {α : Type*} [fintype α] : fintype (array n α) := d_array.fintype instance vector.fintype {α : Type*} [fintype α] {n : ℕ} : fintype (vector α n) := fintype.of_equiv _ (equiv.vector_equiv_fin _ _).symm instance quotient.fintype [fintype α] (s : setoid α) [decidable_rel ((≈) : α → α → Prop)] : fintype (quotient s) := fintype.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩)) instance finset.fintype [fintype α] : fintype (finset α) := ⟨univ.powerset, λ x, finset.mem_powerset.2 (finset.subset_univ _)⟩ @[simp] lemma fintype.card_finset [fintype α] : fintype.card (finset α) = 2 ^ (fintype.card α) := finset.card_powerset finset.univ instance subtype.fintype (p : α → Prop) [decidable_pred p] [fintype α] : fintype {x // p x} := set_fintype _ @[simp] lemma set.to_finset_univ [fintype α] : (set.univ : set α).to_finset = finset.univ := by { ext, simp only [set.mem_univ, mem_univ, set.mem_to_finset] } theorem fintype.card_subtype_le [fintype α] (p : α → Prop) [decidable_pred p] : fintype.card {x // p x} ≤ fintype.card α := by rw fintype.subtype_card; exact card_le_of_subset (subset_univ _) theorem fintype.card_subtype_lt [fintype α] {p : α → Prop} [decidable_pred p] {x : α} (hx : ¬ p x) : fintype.card {x // p x} < fintype.card α := by rw [fintype.subtype_card]; exact finset.card_lt_card ⟨subset_univ _, classical.not_forall.2 ⟨x, by simp [*, set.mem_def]⟩⟩ instance psigma.fintype {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] : fintype (Σ' a, β a) := fintype.of_equiv _ (equiv.psigma_equiv_sigma _).symm instance psigma.fintype_prop_left {α : Prop} {β : α → Type*} [decidable α] [∀ a, fintype (β a)] : fintype (Σ' a, β a) := if h : α then fintype.of_equiv (β h) ⟨λ x, ⟨h, x⟩, psigma.snd, λ _, rfl, λ ⟨_, _⟩, rfl⟩ else ⟨∅, λ x, h x.1⟩ instance psigma.fintype_prop_right {α : Type*} {β : α → Prop} [∀ a, decidable (β a)] [fintype α] : fintype (Σ' a, β a) := fintype.of_equiv {a // β a} ⟨λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, rfl, λ ⟨x, y⟩, rfl⟩ instance psigma.fintype_prop_prop {α : Prop} {β : α → Prop} [decidable α] [∀ a, decidable (β a)] : fintype (Σ' a, β a) := if h : ∃ a, β a then ⟨{⟨h.fst, h.snd⟩}, λ ⟨_, _⟩, by simp⟩ else ⟨∅, λ ⟨x, y⟩, h ⟨x, y⟩⟩ instance set.fintype [fintype α] : fintype (set α) := ⟨(@finset.univ α _).powerset.map ⟨coe, coe_injective⟩, λ s, begin classical, refine mem_map.2 ⟨finset.univ.filter s, mem_powerset.2 (subset_univ _), _⟩, apply (coe_filter _).trans, rw [coe_univ, set.sep_univ], refl end⟩ instance pfun_fintype (p : Prop) [decidable p] (α : p → Type*) [Π hp, fintype (α hp)] : fintype (Π hp : p, α hp) := if hp : p then fintype.of_equiv (α hp) ⟨λ a _, a, λ f, f hp, λ _, rfl, λ _, rfl⟩ else ⟨singleton (λ h, (hp h).elim), by simp [hp, function.funext_iff]⟩ def quotient.fin_choice_aux {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι), (∀ i ∈ l, quotient (S i)) → @quotient (Π i ∈ l, α i) (by apply_instance) | [] f := ⟦λ i, false.elim⟧ | (i::l) f := begin refine quotient.lift_on₂ (f i (list.mem_cons_self _ _)) (quotient.fin_choice_aux l (λ j h, f j (list.mem_cons_of_mem _ h))) _ _, exact λ a l, ⟦λ j h, if e : j = i then by rw e; exact a else l _ (h.resolve_left e)⟧, refine λ a₁ l₁ a₂ l₂ h₁ h₂, quotient.sound (λ j h, _), by_cases e : j = i; simp [e], { subst j, exact h₁ }, { exact h₂ _ _ } end theorem quotient.fin_choice_aux_eq {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι) (f : ∀ i ∈ l, α i), quotient.fin_choice_aux l (λ i h, ⟦f i h⟧) = ⟦f⟧ | [] f := quotient.sound (λ i h, h.elim) | (i::l) f := begin simp [quotient.fin_choice_aux, quotient.fin_choice_aux_eq l], refine quotient.sound (λ j h, _), by_cases e : j = i; simp [e], subst j, refl end def quotient.fin_choice {ι : Type*} [fintype ι] [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] (f : ∀ i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) := quotient.lift_on (@quotient.rec_on _ _ (λ l : multiset ι, @quotient (Π i ∈ l, α i) (by apply_instance)) finset.univ.1 (λ l, quotient.fin_choice_aux l (λ i _, f i)) (λ a b h, begin have := λ a, quotient.fin_choice_aux_eq a (λ i h, quotient.out (f i)), simp [quotient.out_eq] at this, simp [this], let g := λ a:multiset ι, ⟦λ (i : ι) (h : i ∈ a), quotient.out (f i)⟧, refine eq_of_heq ((eq_rec_heq _ _).trans (_ : g a == g b)), congr' 1, exact quotient.sound h, end)) (λ f, ⟦λ i, f i (finset.mem_univ _)⟧) (λ a b h, quotient.sound $ λ i, h _ _) theorem quotient.fin_choice_eq {ι : Type*} [fintype ι] [decidable_eq ι] {α : ι → Type*} [∀ i, setoid (α i)] (f : ∀ i, α i) : quotient.fin_choice (λ i, ⟦f i⟧) = ⟦f⟧ := begin let q, swap, change quotient.lift_on q _ _ = _, have : q = ⟦λ i h, f i⟧, { dsimp [q], exact quotient.induction_on (@finset.univ ι _).1 (λ l, quotient.fin_choice_aux_eq _ _) }, simp [this], exact setoid.refl _ end section equiv open list equiv equiv.perm variables [decidable_eq α] [decidable_eq β] def perms_of_list : list α → list (perm α) | [] := [1] | (a :: l) := perms_of_list l ++ l.bind (λ b, (perms_of_list l).map (λ f, swap a b * f)) lemma length_perms_of_list : ∀ l : list α, length (perms_of_list l) = l.length.fact | [] := rfl | (a :: l) := begin rw [length_cons, nat.fact_succ], simp [perms_of_list, length_bind, length_perms_of_list, function.comp, nat.succ_mul], cc end lemma mem_perms_of_list_of_mem : ∀ {l : list α} {f : perm α} (h : ∀ x, f x ≠ x → x ∈ l), f ∈ perms_of_list l | [] f h := list.mem_singleton.2 $ equiv.ext $ λ x, by simp [imp_false, *] at * | (a::l) f h := if hfa : f a = a then mem_append_left _ $ mem_perms_of_list_of_mem (λ x hx, mem_of_ne_of_mem (λ h, by rw h at hx; exact hx hfa) (h x hx)) else have hfa' : f (f a) ≠ f a, from mt (λ h, f.injective h) hfa, have ∀ (x : α), (swap a (f a) * f) x ≠ x → x ∈ l, from λ x hx, have hxa : x ≠ a, from λ h, by simpa [h, mul_apply] using hx, have hfxa : f x ≠ f a, from mt (λ h, f.injective h) hxa, list.mem_of_ne_of_mem hxa (h x (λ h, by simp [h, mul_apply, swap_apply_def] at hx; split_ifs at hx; cc)), suffices f ∈ perms_of_list l ∨ ∃ (b : α), b ∈ l ∧ ∃ g : perm α, g ∈ perms_of_list l ∧ swap a b * g = f, by simpa [perms_of_list], (@or_iff_not_imp_left _ _ (classical.prop_decidable _)).2 (λ hfl, ⟨f a, if hffa : f (f a) = a then mem_of_ne_of_mem hfa (h _ (mt (λ h, f.injective h) hfa)) else this _ $ by simp [mul_apply, swap_apply_def]; split_ifs; cc, ⟨swap a (f a) * f, mem_perms_of_list_of_mem this, by rw [← mul_assoc, mul_def (swap a (f a)) (swap a (f a)), swap_swap, ← equiv.perm.one_def, one_mul]⟩⟩) lemma mem_of_mem_perms_of_list : ∀ {l : list α} {f : perm α}, f ∈ perms_of_list l → ∀ {x}, f x ≠ x → x ∈ l | [] f h := have f = 1 := by simpa [perms_of_list] using h, by rw this; simp | (a::l) f h := (mem_append.1 h).elim (λ h x hx, mem_cons_of_mem _ (mem_of_mem_perms_of_list h hx)) (λ h x hx, let ⟨y, hy, hy'⟩ := list.mem_bind.1 h in let ⟨g, hg₁, hg₂⟩ := list.mem_map.1 hy' in if hxa : x = a then by simp [hxa] else if hxy : x = y then mem_cons_of_mem _ $ by rwa hxy else mem_cons_of_mem _ $ mem_of_mem_perms_of_list hg₁ $ by rw [eq_inv_mul_iff_mul_eq.2 hg₂, mul_apply, swap_inv, swap_apply_def]; split_ifs; cc) lemma mem_perms_of_list_iff {l : list α} {f : perm α} : f ∈ perms_of_list l ↔ ∀ {x}, f x ≠ x → x ∈ l := ⟨mem_of_mem_perms_of_list, mem_perms_of_list_of_mem⟩ lemma nodup_perms_of_list : ∀ {l : list α} (hl : l.nodup), (perms_of_list l).nodup | [] hl := by simp [perms_of_list] | (a::l) hl := have hl' : l.nodup, from nodup_of_nodup_cons hl, have hln' : (perms_of_list l).nodup, from nodup_perms_of_list hl', have hmeml : ∀ {f : perm α}, f ∈ perms_of_list l → f a = a, from λ f hf, not_not.1 (mt (mem_of_mem_perms_of_list hf) (nodup_cons.1 hl).1), by rw [perms_of_list, list.nodup_append, list.nodup_bind, pairwise_iff_nth_le]; exact ⟨hln', ⟨λ _ _, nodup_map (λ _ _, (mul_right_inj _).1) hln', λ i j hj hij x hx₁ hx₂, let ⟨f, hf⟩ := list.mem_map.1 hx₁ in let ⟨g, hg⟩ := list.mem_map.1 hx₂ in have hix : x a = nth_le l i (lt_trans hij hj), by rw [← hf.2, mul_apply, hmeml hf.1, swap_apply_left], have hiy : x a = nth_le l j hj, by rw [← hg.2, mul_apply, hmeml hg.1, swap_apply_left], absurd (hf.2.trans (hg.2.symm)) $ λ h, ne_of_lt hij $ nodup_iff_nth_le_inj.1 hl' i j (lt_trans hij hj) hj $ by rw [← hix, hiy]⟩, λ f hf₁ hf₂, let ⟨x, hx, hx'⟩ := list.mem_bind.1 hf₂ in let ⟨g, hg⟩ := list.mem_map.1 hx' in have hgxa : g⁻¹ x = a, from f.injective $ by rw [hmeml hf₁, ← hg.2]; simp, have hxa : x ≠ a, from λ h, (list.nodup_cons.1 hl).1 (h ▸ hx), (list.nodup_cons.1 hl).1 $ hgxa ▸ mem_of_mem_perms_of_list hg.1 (by rwa [apply_inv_self, hgxa])⟩ def perms_of_finset (s : finset α) : finset (perm α) := quotient.hrec_on s.1 (λ l hl, ⟨perms_of_list l, nodup_perms_of_list hl⟩) (λ a b hab, hfunext (congr_arg _ (quotient.sound hab)) (λ ha hb _, heq_of_eq $ finset.ext.2 $ by simp [mem_perms_of_list_iff, hab.mem_iff])) s.2 lemma mem_perms_of_finset_iff : ∀ {s : finset α} {f : perm α}, f ∈ perms_of_finset s ↔ ∀ {x}, f x ≠ x → x ∈ s := by rintros ⟨⟨l⟩, hs⟩ f; exact mem_perms_of_list_iff lemma card_perms_of_finset : ∀ (s : finset α), (perms_of_finset s).card = s.card.fact := by rintros ⟨⟨l⟩, hs⟩; exact length_perms_of_list l def fintype_perm [fintype α] : fintype (perm α) := ⟨perms_of_finset (@finset.univ α _), by simp [mem_perms_of_finset_iff]⟩ instance [fintype α] [fintype β] : fintype (α ≃ β) := if h : fintype.card β = fintype.card α then trunc.rec_on_subsingleton (fintype.equiv_fin α) (λ eα, trunc.rec_on_subsingleton (fintype.equiv_fin β) (λ eβ, @fintype.of_equiv _ (perm α) fintype_perm (equiv_congr (equiv.refl α) (eα.trans (eq.rec_on h eβ.symm)) : (α ≃ α) ≃ (α ≃ β)))) else ⟨∅, λ x, false.elim (h (fintype.card_eq.2 ⟨x.symm⟩))⟩ lemma fintype.card_perm [fintype α] : fintype.card (perm α) = (fintype.card α).fact := subsingleton.elim (@fintype_perm α _ _) (@equiv.fintype α α _ _ _ _) ▸ card_perms_of_finset _ lemma fintype.card_equiv [fintype α] [fintype β] (e : α ≃ β) : fintype.card (α ≃ β) = (fintype.card α).fact := fintype.card_congr (equiv_congr (equiv.refl α) e) ▸ fintype.card_perm lemma univ_eq_singleton_of_card_one {α} [fintype α] (x : α) (h : fintype.card α = 1) : (univ : finset α) = {x} := begin apply symm, apply eq_of_subset_of_card_le (subset_univ ({x})), apply le_of_eq, simp [h, finset.card_univ] end end equiv namespace fintype section choose open fintype open equiv variables [fintype α] [decidable_eq α] (p : α → Prop) [decidable_pred p] def choose_x (hp : ∃! a : α, p a) : {a // p a} := ⟨finset.choose p univ (by simp; exact hp), finset.choose_property _ _ _⟩ def choose (hp : ∃! a, p a) : α := choose_x p hp lemma choose_spec (hp : ∃! a, p a) : p (choose p hp) := (choose_x p hp).property end choose section bijection_inverse open function variables [fintype α] [decidable_eq α] variables [fintype β] [decidable_eq β] variables {f : α → β} /-- ` `bij_inv f` is the unique inverse to a bijection `f`. This acts as a computable alternative to `function.inv_fun`. -/ def bij_inv (f_bij : bijective f) (b : β) : α := fintype.choose (λ a, f a = b) begin rcases f_bij.right b with ⟨a', fa_eq_b⟩, rw ← fa_eq_b, exact ⟨a', ⟨rfl, (λ a h, f_bij.left h)⟩⟩ end lemma left_inverse_bij_inv (f_bij : bijective f) : left_inverse (bij_inv f_bij) f := λ a, f_bij.left (choose_spec (λ a', f a' = f a) _) lemma right_inverse_bij_inv (f_bij : bijective f) : right_inverse (bij_inv f_bij) f := λ b, choose_spec (λ a', f a' = b) _ lemma bijective_bij_inv (f_bij : bijective f) : bijective (bij_inv f_bij) := ⟨(right_inverse_bij_inv _).injective, (left_inverse_bij_inv _).surjective⟩ end bijection_inverse lemma well_founded_of_trans_of_irrefl [fintype α] (r : α → α → Prop) [is_trans α r] [is_irrefl α r] : well_founded r := by classical; exact have ∀ x y, r x y → (univ.filter (λ z, r z x)).card < (univ.filter (λ z, r z y)).card, from λ x y hxy, finset.card_lt_card $ by simp only [finset.lt_iff_ssubset.symm, lt_iff_le_not_le, finset.le_iff_subset, finset.subset_iff, mem_filter, true_and, mem_univ, hxy]; exact ⟨λ z hzx, trans hzx hxy, not_forall_of_exists_not ⟨x, not_imp.2 ⟨hxy, irrefl x⟩⟩⟩, subrelation.wf this (measure_wf _) lemma preorder.well_founded [fintype α] [preorder α] : well_founded ((<) : α → α → Prop) := well_founded_of_trans_of_irrefl _ @[instance, priority 10] lemma linear_order.is_well_order [fintype α] [linear_order α] : is_well_order α (<) := { wf := preorder.well_founded } end fintype class infinite (α : Type*) : Prop := (not_fintype : fintype α → false) @[simp] lemma not_nonempty_fintype {α : Type*} : ¬nonempty (fintype α) ↔ infinite α := ⟨λf, ⟨λ x, f ⟨x⟩⟩, λ⟨f⟩ ⟨x⟩, f x⟩ namespace infinite lemma exists_not_mem_finset [infinite α] (s : finset α) : ∃ x, x ∉ s := classical.not_forall.1 $ λ h, not_fintype ⟨s, h⟩ @[priority 100] -- see Note [lower instance priority] instance nonempty (α : Type*) [infinite α] : nonempty α := nonempty_of_exists (exists_not_mem_finset (∅ : finset α)) lemma of_injective [infinite β] (f : β → α) (hf : injective f) : infinite α := ⟨λ I, by exactI not_fintype (fintype.of_injective f hf)⟩ lemma of_surjective [infinite β] (f : α → β) (hf : surjective f) : infinite α := ⟨λ I, by classical; exactI not_fintype (fintype.of_surjective f hf)⟩ private noncomputable def nat_embedding_aux (α : Type*) [infinite α] : ℕ → α | n := by letI := classical.dec_eq α; exact classical.some (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux m) (λ _, multiset.mem_range.1)).to_finset) private lemma nat_embedding_aux_injective (α : Type*) [infinite α] : function.injective (nat_embedding_aux α) := begin assume m n h, letI := classical.dec_eq α, wlog hmlen : m ≤ n using m n, by_contradiction hmn, have hmn : m < n, from lt_of_le_of_ne hmlen hmn, refine (classical.some_spec (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux α m) (λ _, multiset.mem_range.1)).to_finset)) _, refine multiset.mem_to_finset.2 (multiset.mem_pmap.2 ⟨m, multiset.mem_range.2 hmn, _⟩), rw [h, nat_embedding_aux] end noncomputable def nat_embedding (α : Type*) [infinite α] : ℕ ↪ α := ⟨_, nat_embedding_aux_injective α⟩ end infinite lemma not_injective_infinite_fintype [infinite α] [fintype β] (f : α → β) : ¬ injective f := assume (hf : injective f), have H : fintype α := fintype.of_injective f hf, infinite.not_fintype H lemma not_surjective_fintype_infinite [fintype α] [infinite β] (f : α → β) : ¬ surjective f := assume (hf : surjective f), have H : infinite α := infinite.of_surjective f hf, @infinite.not_fintype _ H infer_instance instance nat.infinite : infinite ℕ := ⟨λ ⟨s, hs⟩, finset.not_mem_range_self $ s.subset_range_sup_succ (hs _)⟩ instance int.infinite : infinite ℤ := infinite.of_injective int.of_nat (λ _ _, int.of_nat_inj)
2e5eb59e02fbe67c71e49c20d619fbbfbc071585
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/tests/lean/auxDeclIssue.lean
3a69df9d983b67e47fb8f019fbea8d804400ba5b
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
374
lean
theorem ex1 : False := by { assumption -- should not use the auxiliary declaration `ex1 : False` } variable (x y : Nat) in theorem ex2 : x = y := by { subst x; -- should not use the auxiliary declaration `ex2 : x = y` exact rfl } set_option pp.auxDecls true in theorem ex1 : False := by { assumption -- should not use the auxiliary declaration `ex1 : False` }
534778db7df7435cc0b684d4b80699eb8ddc63b5
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/library/init/meta/injection_tactic.lean
2ba647ea9edc98232c16ef3d84aba3d49ae4c9c0
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,988
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.tactic init.function namespace tactic open nat tactic environment expr list private meta def mk_intro_name : name → list name → name | n₁ (n₂ :: ns) := n₂ | n [] := if n = `a then `h else n -- Auxiliary function for introducing the new equalities produced by the -- injection tactic private meta def injection_intro : expr → list name → tactic unit | (pi n bi b d) ns := do hname ← return $ mk_intro_name n ns, h ← intro hname, ht ← infer_type h, -- Clear new hypothesis if it is of the form (a = a) try $ do { (lhs, rhs) ← match_eq ht, unify lhs rhs, clear h }, -- If new hypothesis is of the form (@heq A a B b) where -- A and B can be unified then convert it into (a = b) using -- the eq_of_heq lemma try $ do { (A, lhs, B, rhs) ← match_heq ht, unify A B, heq ← mk_app `eq [lhs, rhs], pr ← mk_app `eq_of_heq [h], assertv hname heq pr, clear h }, injection_intro d (tail ns) | e ns := skip meta def injection_with (h : expr) (ns : list name) : tactic unit := do ht ← infer_type h, (lhs, rhs) ← match_eq ht, env ← get_env, if is_constructor_app env lhs ∧ is_constructor_app env rhs ∧ const_name (get_app_fn lhs) = const_name (get_app_fn rhs) then do tgt ← target, I_name ← return $ name.get_prefix (const_name (get_app_fn lhs)), pr ← mk_app (I_name <.> "no_confusion") [tgt, lhs, rhs, h], pr_type ← infer_type pr, pr_type ← whnf pr_type, apply pr, injection_intro (binding_domain pr_type) ns else fail "injection tactic failed, argument must be an equality proof where lhs and rhs are of the form (c ...), where c is a constructor" meta def injection (h : expr) : tactic unit := injection_with h [] end tactic
d456d563579fb29f2a5b7c0a41834506205c4afb
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/PreDefinition/WF/PackDomain.lean
bd319a788a02922e5490cb207843556b5e8fabb9
[ "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
7,729
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Tactic.Cases import Lean.Elab.PreDefinition.Basic namespace Lean.Elab.WF open Meta /-- Given a (dependent) tuple `t` (using `PSigma`) of the given arity. Return an array containing its "elements". Example: `mkTupleElems a 4` returns `#[a.1, a.2.1, a.2.2.1, a.2.2.2]`. -/ private def mkTupleElems (t : Expr) (arity : Nat) : Array Expr := Id.run do let mut result := #[] let mut t := t for _ in [:arity - 1] do result := result.push (mkProj ``PSigma 0 t) t := mkProj ``PSigma 1 t result.push t /-- Create a unary application by packing the given arguments using `PSigma.mk` -/ partial def mkUnaryArg (type : Expr) (args : Array Expr) : MetaM Expr := do go 0 type where go (i : Nat) (type : Expr) : MetaM Expr := do if i < args.size - 1 then let arg := args[i]! assert! type.isAppOfArity ``PSigma 2 let us := type.getAppFn.constLevels! let α := type.appFn!.appArg! let β := type.appArg! assert! β.isLambda let type := β.bindingBody!.instantiate1 arg let rest ← go (i+1) type return mkApp4 (mkConst ``PSigma.mk us) α β arg rest else return args[i]! private partial def mkPSigmaCasesOn (y : Expr) (codomain : Expr) (xs : Array Expr) (value : Expr) : MetaM Expr := do let mvar ← mkFreshExprSyntheticOpaqueMVar codomain let rec go (mvarId : MVarId) (y : FVarId) (ys : Array Expr) : MetaM Unit := do if ys.size < xs.size - 1 then let xDecl ← xs[ys.size]!.fvarId!.getDecl let xDecl' ← xs[ys.size + 1]!.fvarId!.getDecl let #[s] ← mvarId.cases y #[{ varNames := [xDecl.userName, xDecl'.userName] }] | unreachable! go s.mvarId s.fields[1]!.fvarId! (ys.push s.fields[0]!) else let ys := ys.push (mkFVar y) mvarId.assign (value.replaceFVars xs ys) go mvar.mvarId! y.fvarId! #[] instantiateMVars mvar /-- Convert the given pre-definitions into unary functions. We "pack" the arguments using `PSigma`. -/ partial def packDomain (fixedPrefix : Nat) (preDefs : Array PreDefinition) : MetaM (Array PreDefinition) := do let mut preDefsNew := #[] let mut arities := #[] let mut modified := false for preDef in preDefs do let (preDefNew, arity, modifiedCurr) ← lambdaTelescope preDef.value fun xs _ => do if xs.size == fixedPrefix then throwError "well-founded recursion cannot be used, '{preDef.declName}' does not take any (non-fixed) arguments" let arity := xs.size if arity > fixedPrefix + 1 then let bodyType ← instantiateForall preDef.type xs let mut d ← inferType xs.back let ys : Array Expr := xs[:fixedPrefix] let xs : Array Expr := xs[fixedPrefix:] for x in xs.pop.reverse do d ← mkAppOptM ``PSigma #[some (← inferType x), some (← mkLambdaFVars #[x] d)] withLocalDeclD (← mkFreshUserName `_x) d fun tuple => do let elems := mkTupleElems tuple xs.size let codomain := bodyType.replaceFVars xs elems let preDefNew:= { preDef with declName := preDef.declName ++ `_unary type := (← mkForallFVars (ys.push tuple) codomain) } addAsAxiom preDefNew return (preDefNew, arity, true) else return (preDef, arity, false) modified := modified || modifiedCurr arities := arities.push arity preDefsNew := preDefsNew.push preDefNew if !modified then return preDefs -- Update values for i in [:preDefs.size] do let preDef := preDefs[i]! let preDefNew := preDefsNew[i]! let valueNew ← lambdaTelescope preDef.value fun xs body => do let ys : Array Expr := xs[:fixedPrefix] let xs : Array Expr := xs[fixedPrefix:] let type ← instantiateForall preDefNew.type ys forallBoundedTelescope type (some 1) fun z codomain => do let z := z[0]! let newBody ← mkPSigmaCasesOn z codomain xs body mkLambdaFVars (ys.push z) (← packApplications newBody arities preDefsNew) let isBad (e : Expr) : Bool := match isAppOfPreDef? e with | none => false | some i => e.getAppNumArgs > fixedPrefix + 1 || preDefsNew[i]!.declName != preDefs[i]!.declName if let some bad := valueNew.find? isBad then if let some i := isAppOfPreDef? bad then throwErrorAt preDef.ref "well-founded recursion cannot be used, function '{preDef.declName}' contains application of function '{preDefs[i]!.declName}' with #{bad.getAppNumArgs} argument(s), but function has arity {arities[i]!}" preDefsNew := preDefsNew.set! i { preDefNew with value := valueNew } return preDefsNew where /-- Return `some i` if `e` is a `preDefs[i]` application -/ isAppOfPreDef? (e : Expr) : Option Nat := do let f := e.getAppFn guard f.isConst preDefs.findIdx? (·.declName == f.constName!) packApplications (e : Expr) (arities : Array Nat) (preDefsNew : Array PreDefinition) : MetaM Expr := do let pack (e : Expr) (funIdx : Nat) : MetaM Expr := do let f := e.getAppFn let args := e.getAppArgs let fNew := mkConst preDefsNew[funIdx]!.declName f.constLevels! let fNew := mkAppN fNew args[:fixedPrefix] let Expr.forallE _ d .. ← inferType fNew | unreachable! let argNew ← mkUnaryArg d args[fixedPrefix:] return mkApp fNew argNew let rec visit (e : Expr) : MonadCacheT ExprStructEq Expr MetaM Expr := do checkCache { val := e : ExprStructEq } fun _ => Meta.withIncRecDepth do match e with | Expr.lam n d b c => withLocalDecl n c (← visit d) fun x => do mkLambdaFVars (usedLetOnly := false) #[x] (← visit (b.instantiate1 x)) | Expr.forallE n d b c => withLocalDecl n c (← visit d) fun x => do mkForallFVars (usedLetOnly := false) #[x] (← visit (b.instantiate1 x)) | Expr.letE n t v b _ => withLetDecl n (← visit t) (← visit v) fun x => do mkLambdaFVars (usedLetOnly := false) #[x] (← visit (b.instantiate1 x)) | Expr.proj n i s .. => return mkProj n i (← visit s) | Expr.mdata d b => return mkMData d (← visit b) | Expr.app .. => visitApp e | Expr.const .. => visitApp e | e => return e, visitApp (e : Expr) : MonadCacheT ExprStructEq Expr MetaM Expr := e.withApp fun f args => do let args ← args.mapM visit if let some funIdx := isAppOfPreDef? f then let numArgs := args.size let arity := arities[funIdx]! if numArgs < arity then -- Partial application let extra := arity - numArgs withDefault do forallBoundedTelescope (← inferType e) extra fun xs _ => do if xs.size != extra then return (mkAppN f args) -- It will fail later else mkLambdaFVars xs (← pack (mkAppN (mkAppN f args) xs) funIdx) else if numArgs > arity then -- Over application let r ← pack (mkAppN f args[:arity]) funIdx let rType ← inferType r -- Make sure the new auxiliary definition has only one argument. withLetDecl (← mkFreshUserName `aux) rType r fun aux => mkLetFVars #[aux] (mkAppN aux args[arity:]) else pack (mkAppN f args) funIdx else if args.isEmpty then return f else return mkAppN (← visit f) args visit e |>.run end Lean.Elab.WF
c3f11f394f378fb3567826e1d5b10495f1f262b9
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/tests/lean/run/depElim1.lean
e6dd22639b44c1166dc6c6f34c62fc8097f4f7bd
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,783
lean
import Lean.Meta.Match open Lean open Lean.Meta open Lean.Meta.Match /- Infrastructure for testing -/ universes u v def check (x : Bool) : IO Unit := do unless x do throw $ IO.userError "check failed" def inaccessible {α : Sort u} (a : α) : α := a def val {α : Sort u} (a : α) : α := a def As {α : Sort u} (v a : α) : α := a inductive Pat {α : Sort u} (a : α) : Type u | mk : Pat a inductive ArrayLit0 (α : Sort u) : Type u | mk : ArrayLit0 α inductive ArrayLit1 {α : Sort u} (a : α) : Type u | mk : ArrayLit1 a inductive ArrayLit2 {α : Sort u} (a b : α) : Type u | mk : ArrayLit2 a b inductive ArrayLit3 {α : Sort u} (a b c : α) : Type u | mk : ArrayLit3 a b c inductive ArrayLit4 {α : Sort u} (a b c d : α) : Type u | mk : ArrayLit4 a b c d private def getConstructorVal (ctorName : Name) (fn : Expr) (args : Array Expr) : MetaM (Option (ConstructorVal × Expr × Array Expr)) := do let env ← getEnv match env.find? ctorName with | some (ConstantInfo.ctorInfo v) => if args.size == v.nparams + v.nfields then return some (v, fn, args) else return none | _ => return none private def constructorApp? (e : Expr) : MetaM (Option (ConstructorVal × Expr × Array Expr)) := do let env ← getEnv match e with | Expr.lit (Literal.natVal n) _ => if n == 0 then getConstructorVal `Nat.zero (mkConst `Nat.zero) #[] else getConstructorVal `Nat.succ (mkConst `Nat.succ) #[mkNatLit (n-1)] | _ => let fn := e.getAppFn match fn with | Expr.const n _ _ => getConstructorVal n fn e.getAppArgs | _ => pure none /- Convert expression using auxiliary hints `inaccessible` and `val` into a pattern -/ partial def mkPattern : Expr → MetaM Pattern | e => do if e.isAppOfArity `val 2 then return Pattern.val e.appArg! else if e.isAppOfArity `inaccessible 2 then return Pattern.inaccessible e.appArg! else if e.isFVar then return Pattern.var e.fvarId! else if e.isAppOfArity `As 3 && (e.getArg! 1).isFVar then let v := e.getArg! 1 let p := e.getArg! 2 let p ← mkPattern p return Pattern.as v.fvarId! p else if e.isAppOfArity `ArrayLit0 1 || e.isAppOfArity `ArrayLit1 2 || e.isAppOfArity `ArrayLit2 3 || e.isAppOfArity `ArrayLit3 4 || e.isAppOfArity `ArrayLit4 5 then let args := e.getAppArgs let type := args[0] let ps := args.extract 1 args.size let ps ← ps.toList.mapM mkPattern return Pattern.arrayLit type ps else match e.arrayLit? with | some (_, es) => let pats ← es.mapM mkPattern let type ← inferType e let type ← whnfD type let elemType := type.appArg! return Pattern.arrayLit elemType pats | none => let e ← whnfD e let r? ← constructorApp? e match r? with | none => throwError "unexpected pattern" | some (cval, fn, args) => let params := args.extract 0 cval.nparams let fields := args.extract cval.nparams args.size let pats ← fields.toList.mapM mkPattern return Pattern.ctor cval.name fn.constLevels! params.toList pats partial def decodePats : Expr → MetaM (List Pattern) | e => do match e.app2? `Pat with | some (_, pat) => let pat ← mkPattern pat; return [pat] | none => match e.prod? with | none => throwError "unexpected pattern" | some (pat, pats) => let pat ← decodePats pat let pats ← decodePats pats return pat ++ pats partial def decodeAltLHS (e : Expr) : MetaM AltLHS := forallTelescopeReducing e fun args body => do let decls ← args.toList.mapM (fun arg => getLocalDecl arg.fvarId!) let pats ← decodePats body return { ref := Syntax.missing, fvarDecls := decls, patterns := pats } partial def decodeAltLHSs : Expr → MetaM (List AltLHS) | e => do match e.app2? `LHS with | some (_, lhs) => let lhs ← decodeAltLHS lhs; return [lhs] | none => match e.prod? with | none => throwError "unexpected LHS" | some (lhs, lhss) => let lhs ← decodeAltLHSs lhs let lhss ← decodeAltLHSs lhss return lhs ++ lhss def withDepElimFrom {α} (declName : Name) (numPats : Nat) (k : List FVarId → List AltLHS → MetaM α) : MetaM α := do let cinfo ← getConstInfo declName forallTelescopeReducing cinfo.type fun args body => if args.size < numPats then throwError "insufficient number of parameters" else do let xs := (args.extract (args.size - numPats) args.size).toList.map $ Expr.fvarId! let alts ← decodeAltLHSs body k xs alts inductive LHS {α : Sort u} (a : α) : Type u | mk : LHS a instance LHS.inhabited {α} (a : α) : Inhabited (LHS a) := ⟨LHS.mk⟩ -- set_option trace.Meta.debug true -- set_option trace.Meta.Tactic.cases true -- set_option trace.Meta.Tactic.subst true @[init] def register : IO Unit := registerTraceClass `Meta.mkElim /- Helper methods for testins mkElim -/ private def getUnusedLevelParam (majors : List Expr) (lhss : List AltLHS) : MetaM Level := do let mut s := {} for major in majors do let major ← instantiateMVars major let majorType ← inferType major let majorType ← instantiateMVars majorType s := collectLevelParams s major s := collectLevelParams s majorType return s.getUnusedLevelParam /- Return `Prop` if `inProf == true` and `Sort u` otherwise, where `u` is a fresh universe level parameter. -/ private def mkElimSort (majors : List Expr) (lhss : List AltLHS) (inProp : Bool) : MetaM Expr := do if inProp then return mkSort levelZero else let v ← getUnusedLevelParam majors lhss return mkSort $ v def mkTester (elimName : Name) (majors : List Expr) (lhss : List AltLHS) (inProp : Bool := false) : MetaM MatcherResult := do generalizeTelescope majors.toArray fun majors => do let resultType := if inProp then mkConst `True /- some proposition -/ else mkConst `Nat let matchType ← mkForallFVars majors resultType Match.mkMatcher elimName matchType majors.size lhss def test (ex : Name) (numPats : Nat) (elimName : Name) (inProp : Bool := false) : MetaM Unit := withDepElimFrom ex numPats fun majors alts => do let majors := majors.map mkFVar trace[Meta.debug]! msg!"majors: {majors.toArray}" let r ← mkTester elimName majors alts inProp unless r.counterExamples.isEmpty do throwError msg!"missing cases:\n{counterExamplesToMessageData r.counterExamples}" unless r.unusedAltIdxs.isEmpty do throwError ("unused alternatives: " ++ toString (r.unusedAltIdxs.map fun idx => "#" ++ toString (idx+1))) let cinfo ← getConstInfo elimName IO.println (toString cinfo.name ++ " : " ++ toString cinfo.type) pure () def testFailure (ex : Name) (numPats : Nat) (elimName : Name) (inProp : Bool := false) : MetaM Unit := do let worked ← tryCatch (do test ex numPats elimName inProp; pure true) (fun ex => pure false) if worked then throwError "unexpected success" def ex0 (x : Nat) : LHS (forall (y : Nat), Pat y) := arbitrary _ #eval test `ex0 1 `elimTest0 #print elimTest0 def ex1 (α : Type u) (β : Type v) (n : Nat) (x : List α) (y : List β) : LHS (Pat ([] : List α) × Pat ([] : List β)) × LHS (forall (a : α) (as : List α) (b : β) (bs : List β), Pat (a::as) × Pat (b::bs)) × LHS (forall (a : α) (as : List α), Pat (a::as) × Pat ([] : List β)) × LHS (forall (b : β) (bs : List β), Pat ([] : List α) × Pat (b::bs)) := arbitrary _ #eval test `ex1 2 `elimTest1 #print elimTest1 inductive Vec (α : Type u) : Nat → Type u | nil : Vec α 0 | cons {n : Nat} : α → Vec α n → Vec α (n+1) def ex2 (α : Type u) (n : Nat) (xs : Vec α n) (ys : Vec α n) : LHS (Pat (inaccessible 0) × Pat (Vec.nil : Vec α 0) × Pat (Vec.nil : Vec α 0)) × LHS (forall (n : Nat) (x : α) (xs : Vec α n) (y : α) (ys : Vec α n), Pat (inaccessible (n+1)) × Pat (Vec.cons x xs) × Pat (Vec.cons y ys)) := arbitrary _ #eval test `ex2 3 `elimTest2 #print elimTest2 def ex3 (α : Type u) (β : Type v) (n : Nat) (x : List α) (y : List β) : LHS (Pat ([] : List α) × Pat ([] : List β)) × LHS (forall (a : α) (b : β), Pat [a] × Pat [b]) × LHS (forall (a₁ a₂ : α) (as : List α) (b₁ b₂ : β) (bs : List β), Pat (a₁::a₂::as) × Pat (b₁::b₂::bs)) × LHS (forall (as : List α) (bs : List β), Pat as × Pat bs) := arbitrary _ -- set_option trace.Meta.EqnCompiler.match true -- set_option trace.Meta.EqnCompiler.matchDebug true #eval test `ex3 2 `elimTest3 #print elimTest3 def ex4 (α : Type u) (n : Nat) (xs : Vec α n) : LHS (Pat (inaccessible 0) × Pat (Vec.nil : Vec α 0)) × LHS (forall (n : Nat) (xs : Vec α (n+1)), Pat (inaccessible (n+1)) × Pat xs) := arbitrary _ #eval test `ex4 2 `elimTest4 #print elimTest4 def ex5 (α : Type u) (n : Nat) (xs : Vec α n) : LHS (Pat Nat.zero × Pat (Vec.nil : Vec α 0)) × LHS (forall (n : Nat) (xs : Vec α (n+1)), Pat (Nat.succ n) × Pat xs) := arbitrary _ #eval test `ex5 2 `elimTest5 #print elimTest5 def ex6 (α : Type u) (n : Nat) (xs : Vec α n) : LHS (Pat (inaccessible Nat.zero) × Pat (Vec.nil : Vec α 0)) × LHS (forall (N : Nat) (XS : Vec α N), Pat (inaccessible N) × Pat XS) := arbitrary _ set_option trace.Meta.Match.match true set_option trace.Meta.Match.debug true #eval test `ex6 2 `elimTest6 #print elimTest6 def ex7 (α : Type u) (n : Nat) (xs : Vec α n) : LHS (forall (a : α), Pat (inaccessible 1) × Pat (Vec.cons a Vec.nil)) × LHS (forall (N : Nat) (XS : Vec α N), Pat (inaccessible N) × Pat XS) := arbitrary _ #eval test `ex7 2 `elimTest7 #check elimTest7 def isSizeOne {n : Nat} (xs : Vec Nat n) : Bool := elimTest7 _ (fun _ _ => Bool) n xs (fun _ => true) (fun _ _ => false) #eval isSizeOne Vec.nil #eval isSizeOne (Vec.cons 1 Vec.nil) #eval isSizeOne (Vec.cons 2 (Vec.cons 1 Vec.nil)) def singleton? {n : Nat} (xs : Vec Nat n) : Option Nat := elimTest7 _ (fun _ _ => Option Nat) n xs (fun a => some a) (fun _ _ => none) #eval singleton? Vec.nil #eval singleton? (Vec.cons 10 Vec.nil) #eval singleton? (Vec.cons 20 (Vec.cons 10 Vec.nil)) def ex8 (α : Type u) (n : Nat) (xs : Vec α n) : LHS (forall (a b : α), Pat (inaccessible 2) × Pat (Vec.cons a (Vec.cons b Vec.nil))) × LHS (forall (N : Nat) (XS : Vec α N), Pat (inaccessible N) × Pat XS) := arbitrary _ #eval test `ex8 2 `elimTest8 #print elimTest8 def pair? {n : Nat} (xs : Vec Nat n) : Option (Nat × Nat) := elimTest8 _ (fun _ _ => Option (Nat × Nat)) n xs (fun a b => some (a, b)) (fun _ _ => none) #eval pair? Vec.nil #eval pair? (Vec.cons 10 Vec.nil) #eval pair? (Vec.cons 20 (Vec.cons 10 Vec.nil)) inductive Op : Nat → Nat → Type | mk : ∀ n, Op n n structure Node : Type := (id₁ id₂ : Nat) (o : Op id₁ id₂) def ex9 (xs : List Node) : LHS (forall (h : Node) (t : List Node), Pat (h :: Node.mk 1 1 (Op.mk 1) :: t)) × LHS (forall (ys : List Node), Pat ys) := arbitrary _ #eval test `ex9 1 `elimTest9 #print elimTest9 def f (xs : List Node) : Bool := elimTest9 (fun _ => Bool) xs (fun _ _ => true) (fun _ => false) #eval check (f [] == false) #eval check (f [⟨0, 0, Op.mk 0⟩] == false) #eval check (f [⟨0, 0, Op.mk 0⟩, ⟨1, 1, Op.mk 1⟩]) #eval check (f [⟨0, 0, Op.mk 0⟩, ⟨2, 2, Op.mk 2⟩] == false) inductive Foo : Bool → Prop | bar : Foo false | baz : Foo false def ex10 (x : Bool) (y : Foo x) : LHS (Pat (inaccessible false) × Pat Foo.bar) × LHS (forall (x : Bool) (y : Foo x), Pat (inaccessible x) × Pat y) := arbitrary _ #eval test `ex10 2 `elimTest10 true def ex11 (xs : List Node) : LHS (forall (h : Node) (t : List Node), Pat (h :: Node.mk 1 1 (Op.mk 1) :: t)) × LHS (Pat ([] : List Node)) := arbitrary _ #eval testFailure `ex11 1 `elimTest11 -- should produce error message def ex12 (x y z : Bool) : LHS (forall (x y : Bool), Pat x × Pat y × Pat true) × LHS (forall (x z : Bool), Pat false × Pat true × Pat z) × LHS (forall (y z : Bool), Pat true × Pat false × Pat z) := arbitrary _ #eval testFailure `ex12 3 `elimTest12 -- should produce error message def ex13 (xs : List Node) : LHS (forall (h : Node) (t : List Node), Pat (h :: Node.mk 1 1 (Op.mk 1) :: t)) × LHS (forall (ys : List Node), Pat ys) × LHS (forall (ys : List Node), Pat ys) := arbitrary _ #eval testFailure `ex13 1 `elimTest13 -- should produce error message def ex14 (x y : Nat) : LHS (Pat (val 1) × Pat (val 2)) × LHS (Pat (val 2) × Pat (val 3)) × LHS (forall (x y : Nat), Pat x × Pat y) := arbitrary _ set_option trace.Meta.Match true #eval test `ex14 2 `elimTest14 #print elimTest14 def h2 (x y : Nat) : Nat := elimTest14 (fun _ _ => Nat) x y (fun _ => 0) (fun _ => 1) (fun x y => x + y) #eval check (h2 1 2 == 0) #eval check (h2 1 4 == 5) #eval check (h2 2 3 == 1) #eval check (h2 2 4 == 6) #eval check (h2 3 4 == 7) def ex15 (xs : Array (List Nat)) : LHS (forall (a : Nat), Pat (ArrayLit1 [a])) × LHS (forall (a b : Nat), Pat (ArrayLit2 [a] [b])) × LHS (forall (ys : Array (List Nat)), Pat ys) := arbitrary _ #eval test `ex15 1 `elimTest15 #check elimTest15 def h3 (xs : Array (List Nat)) : Nat := elimTest15 (fun _ => Nat) xs (fun a => a + 1) (fun a b => a + b) (fun ys => ys.size) #eval check (h3 #[[1]] == 2) #eval check (h3 #[[3], [2]] == 5) #eval check (h3 #[[1, 2]] == 1) #eval check (h3 #[[1, 2], [2, 3], [3]] == 3) def ex16 (xs : List Nat) : LHS (forall (a : Nat) (xs : List Nat) (b : Nat) (as : List Nat), Pat (a :: As xs (b :: as))) × LHS (forall (a : Nat), Pat ([a])) × LHS (Pat ([] : List Nat)) := arbitrary _ #eval test `ex16 1 `elimTest16 #check elimTest16 #print elimTest16 def h4 (xs : List Nat) : List Nat := elimTest16 (fun _ => List Nat) xs (fun a xs b ys => xs) (fun a => []) (fun _ => [1]) #eval check (h4 [1, 2, 3] == [2, 3]) #eval check (h4 [1] == []) #eval check (h4 [] == [1])
10b0edc2d8a197d503a96416e440868f2d6197b8
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Init/Data/Nat/Bitwise.lean
d8dc69aaf1f0d7e853ad31f416010f07f6b591fe
[ "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
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
1,308
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.Nat.Basic import Init.Data.Nat.Div import Init.Coe namespace Nat partial def bitwise (f : Bool → Bool → Bool) (n m : Nat) : Nat := if n = 0 then if f false true then m else 0 else if m = 0 then if f true false then n else 0 else let n' := n / 2 let m' := m / 2 let b₁ := n % 2 = 1 let b₂ := m % 2 = 1 let r := bitwise f n' m' if f b₁ b₂ then r+r+1 else r+r @[extern "lean_nat_land"] def land : @& Nat → @& Nat → Nat := bitwise and @[extern "lean_nat_lor"] def lor : @& Nat → @& Nat → Nat := bitwise or @[extern "lean_nat_lxor"] def xor : @& Nat → @& Nat → Nat := bitwise bne @[extern "lean_nat_shiftl"] def shiftLeft : @& Nat → @& Nat → Nat | n, 0 => n | n, succ m => shiftLeft (2*n) m @[extern "lean_nat_shiftr"] def shiftRight : @& Nat → @& Nat → Nat | n, 0 => n | n, succ m => shiftRight n m / 2 instance : AndOp Nat := ⟨Nat.land⟩ instance : OrOp Nat := ⟨Nat.lor⟩ instance : Xor Nat := ⟨Nat.xor⟩ instance : ShiftLeft Nat := ⟨Nat.shiftLeft⟩ instance : ShiftRight Nat := ⟨Nat.shiftRight⟩ end Nat
3a92c57a662c2317ca0b93c9443b0d40e11187e8
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/metric_space/gluing.lean
8f35142bced4f9a4c735d8ff256f6f36c190f9a9
[ "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
32,099
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 topology.metric_space.isometry /-! # Metric space gluing > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Gluing two metric spaces along a common subset. Formally, we are given ``` Φ Z ---> X | |Ψ v Y ``` where `hΦ : isometry Φ` and `hΨ : isometry Ψ`. We want to complete the square by a space `glue_space hΦ hΨ` and two isometries `to_glue_l hΦ hΨ` and `to_glue_r hΦ hΨ` that make the square commute. We start by defining a predistance on the disjoint union `X ⊕ Y`, for which points `Φ p` and `Ψ p` are at distance 0. The (quotient) metric space associated to this predistance is the desired space. This is an instance of a more general construction, where `Φ` and `Ψ` do not have to be isometries, but the distances in the image almost coincide, up to `2ε` say. Then one can almost glue the two spaces so that the images of a point under `Φ` and `Ψ` are `ε`-close. If `ε > 0`, this yields a metric space structure on `X ⊕ Y`, without the need to take a quotient. In particular, this gives a natural metric space structure on `X ⊕ Y`, where the basepoints are at distance 1, say, and the distances between other points are obtained by going through the two basepoints. (We also register the same metric space structure on a general disjoint union `Σ i, E i`). We also define the inductive limit of metric spaces. Given ``` f 0 f 1 f 2 f 3 X 0 -----> X 1 -----> X 2 -----> X 3 -----> ... ``` where the `X n` are metric spaces and `f n` isometric embeddings, we define the inductive limit of the `X n`, also known as the increasing union of the `X n` in this context, if we identify `X n` and `X (n+1)` through `f n`. This is a metric space in which all `X n` embed isometrically and in a way compatible with `f n`. -/ noncomputable theory universes u v w open function set open_locale uniformity namespace metric section approx_gluing variables {X : Type u} {Y : Type v} {Z : Type w} variables [metric_space X] [metric_space Y] {Φ : Z → X} {Ψ : Z → Y} {ε : ℝ} open _root_.sum (inl inr) /-- Define a predistance on `X ⊕ Y`, for which `Φ p` and `Ψ p` are at distance `ε` -/ def glue_dist (Φ : Z → X) (Ψ : Z → Y) (ε : ℝ) : X ⊕ Y → X ⊕ Y → ℝ | (inl x) (inl y) := dist x y | (inr x) (inr y) := dist x y | (inl x) (inr y) := (⨅ p, dist x (Φ p) + dist y (Ψ p)) + ε | (inr x) (inl y) := (⨅ p, dist y (Φ p) + dist x (Ψ p)) + ε private lemma glue_dist_self (Φ : Z → X) (Ψ : Z → Y) (ε : ℝ) : ∀ x, glue_dist Φ Ψ ε x x = 0 | (inl x) := dist_self _ | (inr x) := dist_self _ lemma glue_dist_glued_points [nonempty Z] (Φ : Z → X) (Ψ : Z → Y) (ε : ℝ) (p : Z) : glue_dist Φ Ψ ε (inl (Φ p)) (inr (Ψ p)) = ε := begin have : (⨅ q, dist (Φ p) (Φ q) + dist (Ψ p) (Ψ q)) = 0, { have A : ∀ q, 0 ≤ dist (Φ p) (Φ q) + dist (Ψ p) (Ψ q) := λq, by rw ← add_zero (0 : ℝ); exact add_le_add dist_nonneg dist_nonneg, refine le_antisymm _ (le_cinfi A), have : 0 = dist (Φ p) (Φ p) + dist (Ψ p) (Ψ p), by simp, rw this, exact cinfi_le ⟨0, forall_range_iff.2 A⟩ p }, rw [glue_dist, this, zero_add] end private lemma glue_dist_comm (Φ : Z → X) (Ψ : Z → Y) (ε : ℝ) : ∀ x y, glue_dist Φ Ψ ε x y = glue_dist Φ Ψ ε y x | (inl x) (inl y) := dist_comm _ _ | (inr x) (inr y) := dist_comm _ _ | (inl x) (inr y) := rfl | (inr x) (inl y) := rfl variable [nonempty Z] private lemma glue_dist_triangle (Φ : Z → X) (Ψ : Z → Y) (ε : ℝ) (H : ∀ p q, |dist (Φ p) (Φ q) - dist (Ψ p) (Ψ q)| ≤ 2 * ε) : ∀ x y z, glue_dist Φ Ψ ε x z ≤ glue_dist Φ Ψ ε x y + glue_dist Φ Ψ ε y z | (inl x) (inl y) (inl z) := dist_triangle _ _ _ | (inr x) (inr y) (inr z) := dist_triangle _ _ _ | (inr x) (inl y) (inl z) := begin have B : ∀ a b, bdd_below (range (λ (p : Z), dist a (Φ p) + dist b (Ψ p))) := λa b, ⟨0, forall_range_iff.2 (λp, add_nonneg dist_nonneg dist_nonneg)⟩, unfold glue_dist, have : (⨅ p, dist z (Φ p) + dist x (Ψ p)) ≤ (⨅ p, dist y (Φ p) + dist x (Ψ p)) + dist y z, { have : (⨅ p, dist y (Φ p) + dist x (Ψ p)) + dist y z = infi ((λt, t + dist y z) ∘ (λp, dist y (Φ p) + dist x (Ψ p))), { refine monotone.map_cinfi_of_continuous_at (continuous_at_id.add continuous_at_const) _ (B _ _), intros x y hx, simpa }, rw [this, comp], refine cinfi_mono (B _ _) (λp, _), calc dist z (Φ p) + dist x (Ψ p) ≤ (dist y z + dist y (Φ p)) + dist x (Ψ p) : add_le_add (dist_triangle_left _ _ _) le_rfl ... = dist y (Φ p) + dist x (Ψ p) + dist y z : by ring }, linarith end | (inr x) (inr y) (inl z) := begin have B : ∀ a b, bdd_below (range (λ (p : Z), dist a (Φ p) + dist b (Ψ p))) := λa b, ⟨0, forall_range_iff.2 (λp, add_nonneg dist_nonneg dist_nonneg)⟩, unfold glue_dist, have : (⨅ p, dist z (Φ p) + dist x (Ψ p)) ≤ dist x y + ⨅ p, dist z (Φ p) + dist y (Ψ p), { have : dist x y + (⨅ p, dist z (Φ p) + dist y (Ψ p)) = infi ((λt, dist x y + t) ∘ (λp, dist z (Φ p) + dist y (Ψ p))), { refine monotone.map_cinfi_of_continuous_at (continuous_at_const.add continuous_at_id) _ (B _ _), intros x y hx, simpa }, rw [this, comp], refine cinfi_mono (B _ _) (λp, _), calc dist z (Φ p) + dist x (Ψ p) ≤ dist z (Φ p) + (dist x y + dist y (Ψ p)) : add_le_add le_rfl (dist_triangle _ _ _) ... = dist x y + (dist z (Φ p) + dist y (Ψ p)) : by ring }, linarith end | (inl x) (inl y) (inr z) := begin have B : ∀ a b, bdd_below (range (λ (p : Z), dist a (Φ p) + dist b (Ψ p))) := λa b, ⟨0, forall_range_iff.2 (λp, add_nonneg dist_nonneg dist_nonneg)⟩, unfold glue_dist, have : (⨅ p, dist x (Φ p) + dist z (Ψ p)) ≤ dist x y + ⨅ p, dist y (Φ p) + dist z (Ψ p), { have : dist x y + (⨅ p, dist y (Φ p) + dist z (Ψ p)) = infi ((λt, dist x y + t) ∘ (λp, dist y (Φ p) + dist z (Ψ p))), { refine monotone.map_cinfi_of_continuous_at (continuous_at_const.add continuous_at_id) _ (B _ _), intros x y hx, simpa }, rw [this, comp], refine cinfi_mono (B _ _) (λp, _), calc dist x (Φ p) + dist z (Ψ p) ≤ (dist x y + dist y (Φ p)) + dist z (Ψ p) : add_le_add (dist_triangle _ _ _) le_rfl ... = dist x y + (dist y (Φ p) + dist z (Ψ p)) : by ring }, linarith end | (inl x) (inr y) (inr z) := begin have B : ∀ a b, bdd_below (range (λ (p : Z), dist a (Φ p) + dist b (Ψ p))) := λa b, ⟨0, forall_range_iff.2 (λp, add_nonneg dist_nonneg dist_nonneg)⟩, unfold glue_dist, have : (⨅ p, dist x (Φ p) + dist z (Ψ p)) ≤ (⨅ p, dist x (Φ p) + dist y (Ψ p)) + dist y z, { have : (⨅ p, dist x (Φ p) + dist y (Ψ p)) + dist y z = infi ((λt, t + dist y z) ∘ (λp, dist x (Φ p) + dist y (Ψ p))), { refine monotone.map_cinfi_of_continuous_at (continuous_at_id.add continuous_at_const) _ (B _ _), intros x y hx, simpa }, rw [this, comp], refine cinfi_mono (B _ _) (λp, _), calc dist x (Φ p) + dist z (Ψ p) ≤ dist x (Φ p) + (dist y z + dist y (Ψ p)) : add_le_add le_rfl (dist_triangle_left _ _ _) ... = dist x (Φ p) + dist y (Ψ p) + dist y z : by ring }, linarith end | (inl x) (inr y) (inl z) := le_of_forall_pos_le_add $ λδ δpos, begin obtain ⟨p, hp⟩ : ∃ p, dist x (Φ p) + dist y (Ψ p) < (⨅ p, dist x (Φ p) + dist y (Ψ p)) + δ / 2, from exists_lt_of_cinfi_lt (by linarith), obtain ⟨q, hq⟩ : ∃ q, dist z (Φ q) + dist y (Ψ q) < (⨅ p, dist z (Φ p) + dist y (Ψ p)) + δ / 2, from exists_lt_of_cinfi_lt (by linarith), have : dist (Φ p) (Φ q) ≤ dist (Ψ p) (Ψ q) + 2 * ε, { have := le_trans (le_abs_self _) (H p q), by linarith }, calc dist x z ≤ dist x (Φ p) + dist (Φ p) (Φ q) + dist (Φ q) z : dist_triangle4 _ _ _ _ ... ≤ dist x (Φ p) + dist (Ψ p) (Ψ q) + dist z (Φ q) + 2 * ε : by rw [dist_comm z]; linarith ... ≤ dist x (Φ p) + (dist y (Ψ p) + dist y (Ψ q)) + dist z (Φ q) + 2 * ε : add_le_add (add_le_add (add_le_add le_rfl (dist_triangle_left _ _ _)) le_rfl) le_rfl ... ≤ ((⨅ p, dist x (Φ p) + dist y (Ψ p)) + ε) + ((⨅ p, dist z (Φ p) + dist y (Ψ p)) + ε) + δ : by linarith end | (inr x) (inl y) (inr z) := le_of_forall_pos_le_add $ λδ δpos, begin obtain ⟨p, hp⟩ : ∃ p, dist y (Φ p) + dist x (Ψ p) < (⨅ p, dist y (Φ p) + dist x (Ψ p)) + δ / 2, from exists_lt_of_cinfi_lt (by linarith), obtain ⟨q, hq⟩ : ∃ q, dist y (Φ q) + dist z (Ψ q) < (⨅ p, dist y (Φ p) + dist z (Ψ p)) + δ / 2, from exists_lt_of_cinfi_lt (by linarith), have : dist (Ψ p) (Ψ q) ≤ dist (Φ p) (Φ q) + 2 * ε, { have := le_trans (neg_le_abs_self _) (H p q), by linarith }, calc dist x z ≤ dist x (Ψ p) + dist (Ψ p) (Ψ q) + dist (Ψ q) z : dist_triangle4 _ _ _ _ ... ≤ dist x (Ψ p) + dist (Φ p) (Φ q) + dist z (Ψ q) + 2 * ε : by rw [dist_comm z]; linarith ... ≤ dist x (Ψ p) + (dist y (Φ p) + dist y (Φ q)) + dist z (Ψ q) + 2 * ε : add_le_add (add_le_add (add_le_add le_rfl (dist_triangle_left _ _ _)) le_rfl) le_rfl ... ≤ ((⨅ p, dist y (Φ p) + dist x (Ψ p)) + ε) + ((⨅ p, dist y (Φ p) + dist z (Ψ p)) + ε) + δ : by linarith end private lemma glue_eq_of_dist_eq_zero (Φ : Z → X) (Ψ : Z → Y) (ε : ℝ) (ε0 : 0 < ε) : ∀ p q : X ⊕ Y, glue_dist Φ Ψ ε p q = 0 → p = q | (inl x) (inl y) h := by rw eq_of_dist_eq_zero h | (inl x) (inr y) h := begin have : 0 ≤ (⨅ p, dist x (Φ p) + dist y (Ψ p)) := le_cinfi (λp, by simpa using add_le_add (@dist_nonneg _ _ x _) (@dist_nonneg _ _ y _)), have : 0 + ε ≤ glue_dist Φ Ψ ε (inl x) (inr y) := add_le_add this (le_refl ε), exfalso, linarith end | (inr x) (inl y) h := begin have : 0 ≤ ⨅ p, dist y (Φ p) + dist x (Ψ p) := le_cinfi (λp, by simpa [add_comm] using add_le_add (@dist_nonneg _ _ x _) (@dist_nonneg _ _ y _)), have : 0 + ε ≤ glue_dist Φ Ψ ε (inr x) (inl y) := add_le_add this (le_refl ε), exfalso, linarith end | (inr x) (inr y) h := by rw eq_of_dist_eq_zero h /-- Given two maps `Φ` and `Ψ` intro metric spaces `X` and `Y` such that the distances between `Φ p` and `Φ q`, and between `Ψ p` and `Ψ q`, coincide up to `2 ε` where `ε > 0`, one can almost glue the two spaces `X` and `Y` along the images of `Φ` and `Ψ`, so that `Φ p` and `Ψ p` are at distance `ε`. -/ def glue_metric_approx (Φ : Z → X) (Ψ : Z → Y) (ε : ℝ) (ε0 : 0 < ε) (H : ∀ p q, |dist (Φ p) (Φ q) - dist (Ψ p) (Ψ q)| ≤ 2 * ε) : metric_space (X ⊕ Y) := { dist := glue_dist Φ Ψ ε, dist_self := glue_dist_self Φ Ψ ε, dist_comm := glue_dist_comm Φ Ψ ε, dist_triangle := glue_dist_triangle Φ Ψ ε H, eq_of_dist_eq_zero := glue_eq_of_dist_eq_zero Φ Ψ ε ε0 } end approx_gluing section sum /- A particular case of the previous construction is when one uses basepoints in `X` and `Y` and one glues only along the basepoints, putting them at distance 1. We give a direct definition of the distance, without infi, as it is easier to use in applications, and show that it is equal to the gluing distance defined above to take advantage of the lemmas we have already proved. -/ variables {X : Type u} {Y : Type v} {Z : Type w} variables [metric_space X] [metric_space Y] open sum (inl inr) /-- Distance on a disjoint union. There are many (noncanonical) ways to put a distance compatible with each factor. If the two spaces are bounded, one can say for instance that each point in the first is at distance `diam X + diam Y + 1` of each point in the second. Instead, we choose a construction that works for unbounded spaces, but requires basepoints, chosen arbitrarily. We embed isometrically each factor, set the basepoints at distance 1, arbitrarily, and say that the distance from `a` to `b` is the sum of the distances of `a` and `b` to their respective basepoints, plus the distance 1 between the basepoints. Since there is an arbitrary choice in this construction, it is not an instance by default. -/ def sum.dist : X ⊕ Y → X ⊕ Y → ℝ | (inl a) (inl a') := dist a a' | (inr b) (inr b') := dist b b' | (inl a) (inr b) := dist a (nonempty.some ⟨a⟩) + 1 + dist (nonempty.some ⟨b⟩) b | (inr b) (inl a) := dist b (nonempty.some ⟨b⟩) + 1 + dist (nonempty.some ⟨a⟩) a lemma sum.dist_eq_glue_dist {p q : X ⊕ Y} (x : X) (y : Y) : sum.dist p q = glue_dist (λ _ : unit, nonempty.some ⟨x⟩) (λ _ : unit, nonempty.some ⟨y⟩) 1 p q := by cases p; cases q; refl <|> simp [sum.dist, glue_dist, dist_comm, add_comm, add_left_comm] private lemma sum.dist_comm (x y : X ⊕ Y) : sum.dist x y = sum.dist y x := by cases x; cases y; simp only [sum.dist, dist_comm, add_comm, add_left_comm] lemma sum.one_dist_le {x : X} {y : Y} : 1 ≤ sum.dist (inl x) (inr y) := le_trans (le_add_of_nonneg_right dist_nonneg) $ add_le_add_right (le_add_of_nonneg_left dist_nonneg) _ lemma sum.one_dist_le' {x : X} {y : Y} : 1 ≤ sum.dist (inr y) (inl x) := by rw sum.dist_comm; exact sum.one_dist_le private lemma sum.mem_uniformity (s : set ((X ⊕ Y) × (X ⊕ Y))) : s ∈ 𝓤 (X ⊕ Y) ↔ ∃ ε > 0, ∀ a b, sum.dist a b < ε → (a, b) ∈ s := begin split, { rintro ⟨hsX, hsY⟩, rcases mem_uniformity_dist.1 hsX with ⟨εX, εX0, hX⟩, rcases mem_uniformity_dist.1 hsY with ⟨εY, εY0, hY⟩, refine ⟨min (min εX εY) 1, lt_min (lt_min εX0 εY0) zero_lt_one, _⟩, rintro (a|a) (b|b) h, { exact hX (lt_of_lt_of_le h (le_trans (min_le_left _ _) (min_le_left _ _))) }, { cases not_le_of_lt (lt_of_lt_of_le h (min_le_right _ _)) sum.one_dist_le }, { cases not_le_of_lt (lt_of_lt_of_le h (min_le_right _ _)) sum.one_dist_le' }, { exact hY (lt_of_lt_of_le h (le_trans (min_le_left _ _) (min_le_right _ _))) } }, { rintro ⟨ε, ε0, H⟩, split; rw [filter.mem_sets, filter.mem_map, mem_uniformity_dist]; exact ⟨ε, ε0, λ x y h, H _ _ (by exact h)⟩ } end /-- The distance on the disjoint union indeed defines a metric space. All the distance properties follow from our choice of the distance. The harder work is to show that the uniform structure defined by the distance coincides with the disjoint union uniform structure. -/ def metric_space_sum : metric_space (X ⊕ Y) := { dist := sum.dist, dist_self := λx, by cases x; simp only [sum.dist, dist_self], dist_comm := sum.dist_comm, dist_triangle := λ p q r, begin cases p; cases q; cases r, { exact dist_triangle _ _ _ }, { simp only [dist, sum.dist_eq_glue_dist p r], exact glue_dist_triangle _ _ _ (by norm_num) _ _ _ }, { simp only [dist, sum.dist_eq_glue_dist p q], exact glue_dist_triangle _ _ _ (by norm_num) _ _ _ }, { simp only [dist, sum.dist_eq_glue_dist p q], exact glue_dist_triangle _ _ _ (by norm_num) _ _ _ }, { simp only [dist, sum.dist_eq_glue_dist q p], exact glue_dist_triangle _ _ _ (by norm_num) _ _ _ }, { simp only [dist, sum.dist_eq_glue_dist q p], exact glue_dist_triangle _ _ _ (by norm_num) _ _ _ }, { simp only [dist, sum.dist_eq_glue_dist r p], exact glue_dist_triangle _ _ _ (by norm_num) _ _ _ }, { exact dist_triangle _ _ _ }, end, eq_of_dist_eq_zero := λ p q, begin cases p; cases q, { simp only [sum.dist, dist_eq_zero, imp_self] }, { assume h, simp only [dist, sum.dist_eq_glue_dist p q] at h, exact glue_eq_of_dist_eq_zero _ _ _ zero_lt_one _ _ h }, { assume h, simp only [dist, sum.dist_eq_glue_dist q p] at h, exact glue_eq_of_dist_eq_zero _ _ _ zero_lt_one _ _ h }, { simp only [sum.dist, dist_eq_zero, imp_self] }, end, to_uniform_space := sum.uniform_space, uniformity_dist := uniformity_dist_of_mem_uniformity _ _ sum.mem_uniformity } local attribute [instance] metric_space_sum lemma sum.dist_eq {x y : X ⊕ Y} : dist x y = sum.dist x y := rfl /-- The left injection of a space in a disjoint union is an isometry -/ lemma isometry_inl : isometry (sum.inl : X → (X ⊕ Y)) := isometry.of_dist_eq $ λ x y, rfl /-- The right injection of a space in a disjoint union is an isometry -/ lemma isometry_inr : isometry (sum.inr : Y → (X ⊕ Y)) := isometry.of_dist_eq $ λ x y, rfl end sum namespace sigma /- Copy of the previous paragraph, but for arbitrary disjoint unions instead of the disjoint union of two spaces. I.e., work with sigma types instead of sum types. -/ variables {ι : Type*} {E : ι → Type*} [∀ i, metric_space (E i)] open_locale classical /-- Distance on a disjoint union. There are many (noncanonical) ways to put a distance compatible with each factor. We choose a construction that works for unbounded spaces, but requires basepoints, chosen arbitrarily. We embed isometrically each factor, set the basepoints at distance 1, arbitrarily, and say that the distance from `a` to `b` is the sum of the distances of `a` and `b` to their respective basepoints, plus the distance 1 between the basepoints. Since there is an arbitrary choice in this construction, it is not an instance by default. -/ protected def dist : (Σ i, E i) → (Σ i, E i) → ℝ | ⟨i, x⟩ ⟨j, y⟩ := if h : i = j then by { have : E j = E i, by rw h, exact has_dist.dist x (cast this y) } else has_dist.dist x (nonempty.some ⟨x⟩) + 1 + has_dist.dist (nonempty.some ⟨y⟩) y /-- A `has_dist` instance on the disjoint union `Σ i, E i`. We embed isometrically each factor, set the basepoints at distance 1, arbitrarily, and say that the distance from `a` to `b` is the sum of the distances of `a` and `b` to their respective basepoints, plus the distance 1 between the basepoints. Since there is an arbitrary choice in this construction, it is not an instance by default. -/ def has_dist : has_dist (Σ i, E i) := ⟨sigma.dist⟩ local attribute [instance] sigma.has_dist @[simp] lemma dist_same (i : ι) (x : E i) (y : E i) : dist (⟨i, x⟩ : Σ j, E j) ⟨i, y⟩ = dist x y := by simp [has_dist.dist, sigma.dist] @[simp] lemma dist_ne {i j : ι} (h : i ≠ j) (x : E i) (y : E j) : dist (⟨i, x⟩ : Σ k, E k) ⟨j, y⟩ = dist x (nonempty.some ⟨x⟩) + 1 + dist (nonempty.some ⟨y⟩) y := by simp [has_dist.dist, sigma.dist, h] lemma one_le_dist_of_ne {i j : ι} (h : i ≠ j) (x : E i) (y : E j) : 1 ≤ dist (⟨i, x⟩ : Σ k, E k) ⟨j, y⟩ := begin rw sigma.dist_ne h x y, linarith [@dist_nonneg _ _ x (nonempty.some ⟨x⟩), @dist_nonneg _ _ (nonempty.some ⟨y⟩) y] end lemma fst_eq_of_dist_lt_one (x y : Σ i, E i) (h : dist x y < 1) : x.1 = y.1 := begin cases x, cases y, contrapose! h, apply one_le_dist_of_ne h, end protected lemma dist_triangle (x y z : Σ i, E i) : dist x z ≤ dist x y + dist y z := begin rcases x with ⟨i, x⟩, rcases y with ⟨j, y⟩, rcases z with ⟨k, z⟩, rcases eq_or_ne i k with rfl|hik, { rcases eq_or_ne i j with rfl|hij, { simpa using dist_triangle x y z }, { simp only [hij, hij.symm, sigma.dist_same, sigma.dist_ne, ne.def, not_false_iff], calc dist x z ≤ dist x (nonempty.some ⟨x⟩) + 0 + 0 + (0 + 0 + dist (nonempty.some ⟨z⟩) z) : by simpa only [zero_add, add_zero] using dist_triangle _ _ _ ... ≤ _ : by apply_rules [add_le_add, le_rfl, dist_nonneg, zero_le_one] } }, { rcases eq_or_ne i j with rfl|hij, { simp only [hik, sigma.dist_ne, ne.def, not_false_iff, sigma.dist_same], calc dist x (nonempty.some ⟨x⟩) + 1 + dist (nonempty.some ⟨z⟩) z ≤ (dist x y + dist y (nonempty.some ⟨y⟩) + 1 + dist (nonempty.some ⟨z⟩) z) : by apply_rules [add_le_add, le_rfl, dist_triangle] ... = _ : by abel }, { rcases eq_or_ne j k with rfl|hjk, { simp only [hij, sigma.dist_ne, ne.def, not_false_iff, sigma.dist_same], calc dist x (nonempty.some ⟨x⟩) + 1 + dist (nonempty.some ⟨z⟩) z ≤ dist x (nonempty.some ⟨x⟩) + 1 + (dist (nonempty.some ⟨z⟩) y + dist y z) : by apply_rules [add_le_add, le_rfl, dist_triangle] ... = _ : by abel }, { simp only [hik, hij, hjk, sigma.dist_ne, ne.def, not_false_iff], calc dist x (nonempty.some ⟨x⟩) + 1 + dist (nonempty.some ⟨z⟩) z = dist x (nonempty.some ⟨x⟩) + 1 + 0 + (0 + 0 + dist (nonempty.some ⟨z⟩) z) : by simp only [add_zero, zero_add] ... ≤ _ : by apply_rules [add_le_add, zero_le_one, dist_nonneg, le_rfl] } } } end protected lemma is_open_iff (s : set (Σ i, E i)) : is_open s ↔ ∀ x ∈ s, ∃ ε > 0, ∀ y, dist x y < ε → y ∈ s := begin split, { rintros hs ⟨i, x⟩ hx, obtain ⟨ε, εpos, hε⟩ : ∃ (ε : ℝ) (H : ε > 0), ball x ε ⊆ sigma.mk i ⁻¹' s := metric.is_open_iff.1 (is_open_sigma_iff.1 hs i) x hx, refine ⟨min ε 1, lt_min εpos zero_lt_one, _⟩, rintros ⟨j, y⟩ hy, rcases eq_or_ne i j with rfl|hij, { simp only [sigma.dist_same, lt_min_iff] at hy, exact hε (mem_ball'.2 hy.1) }, { apply (lt_irrefl (1 : ℝ) _).elim, calc 1 ≤ sigma.dist ⟨i, x⟩ ⟨j, y⟩ : sigma.one_le_dist_of_ne hij _ _ ... < 1 : hy.trans_le (min_le_right _ _) } }, { assume H, apply is_open_sigma_iff.2 (λ i, _), apply metric.is_open_iff.2 (λ x hx, _), obtain ⟨ε, εpos, hε⟩ : ∃ (ε : ℝ) (H : ε > 0), ∀ y, dist (⟨i, x⟩ : Σ j, E j) y < ε → y ∈ s := H ⟨i, x⟩ hx, refine ⟨ε, εpos, λ y hy, _⟩, apply hε ⟨i, y⟩, rw sigma.dist_same, exact mem_ball'.1 hy } end /-- A metric space structure on the disjoint union `Σ i, E i`. We embed isometrically each factor, set the basepoints at distance 1, arbitrarily, and say that the distance from `a` to `b` is the sum of the distances of `a` and `b` to their respective basepoints, plus the distance 1 between the basepoints. Since there is an arbitrary choice in this construction, it is not an instance by default. -/ protected def metric_space : metric_space (Σ i, E i) := begin refine metric_space.of_dist_topology sigma.dist _ _ sigma.dist_triangle sigma.is_open_iff _, { rintros ⟨i, x⟩, simp [sigma.dist] }, { rintros ⟨i, x⟩ ⟨j, y⟩, rcases eq_or_ne i j with rfl|h, { simp [sigma.dist, dist_comm] }, { simp only [sigma.dist, dist_comm, h, h.symm, not_false_iff, dif_neg], abel } }, { rintros ⟨i, x⟩ ⟨j, y⟩, rcases eq_or_ne i j with rfl|hij, { simp [sigma.dist] }, { assume h, apply (lt_irrefl (1 : ℝ) _).elim, calc 1 ≤ sigma.dist (⟨i, x⟩ : Σ k, E k) ⟨j, y⟩ : sigma.one_le_dist_of_ne hij _ _ ... < 1 : by { rw h, exact zero_lt_one } } } end local attribute [instance] sigma.metric_space open_locale topology open filter /-- The injection of a space in a disjoint union is an isometry -/ lemma isometry_mk (i : ι) : isometry (sigma.mk i : E i → Σ k, E k) := isometry.of_dist_eq (λ x y, by simp) /-- A disjoint union of complete metric spaces is complete. -/ protected lemma complete_space [∀ i, complete_space (E i)] : complete_space (Σ i, E i) := begin set s : ι → set (Σ i, E i) := λ i, (sigma.fst ⁻¹' {i}), set U := {p : (Σ k, E k) × (Σ k, E k) | dist p.1 p.2 < 1}, have hc : ∀ i, is_complete (s i), { intro i, simp only [s, ← range_sigma_mk], exact (isometry_mk i).uniform_inducing.is_complete_range }, have hd : ∀ i j (x ∈ s i) (y ∈ s j), (x, y) ∈ U → i = j, from λ i j x hx y hy hxy, (eq.symm hx).trans ((fst_eq_of_dist_lt_one _ _ hxy).trans hy), refine complete_space_of_is_complete_univ _, convert is_complete_Union_separated hc (dist_mem_uniformity zero_lt_one) hd, simp [s, ← preimage_Union] end end sigma section gluing /- Exact gluing of two metric spaces along isometric subsets. -/ variables {X : Type u} {Y : Type v} {Z : Type w} variables [nonempty Z] [metric_space Z] [metric_space X] [metric_space Y] {Φ : Z → X} {Ψ : Z → Y} {ε : ℝ} open _root_.sum (inl inr) local attribute [instance] uniform_space.separation_setoid /-- Given two isometric embeddings `Φ : Z → X` and `Ψ : Z → Y`, we define a pseudo metric space structure on `X ⊕ Y` by declaring that `Φ x` and `Ψ x` are at distance `0`. -/ def glue_premetric (hΦ : isometry Φ) (hΨ : isometry Ψ) : pseudo_metric_space (X ⊕ Y) := { dist := glue_dist Φ Ψ 0, dist_self := glue_dist_self Φ Ψ 0, dist_comm := glue_dist_comm Φ Ψ 0, dist_triangle := glue_dist_triangle Φ Ψ 0 $ λp q, by rw [hΦ.dist_eq, hΨ.dist_eq]; simp } /-- Given two isometric embeddings `Φ : Z → X` and `Ψ : Z → Y`, we define a space `glue_space hΦ hΨ` by identifying in `X ⊕ Y` the points `Φ x` and `Ψ x`. -/ @[derive metric_space] def glue_space (hΦ : isometry Φ) (hΨ : isometry Ψ) : Type* := @uniform_space.separation_quotient _ (glue_premetric hΦ hΨ).to_uniform_space /-- The canonical map from `X` to the space obtained by gluing isometric subsets in `X` and `Y`. -/ def to_glue_l (hΦ : isometry Φ) (hΨ : isometry Ψ) (x : X) : glue_space hΦ hΨ := quotient.mk' (inl x) /-- The canonical map from `Y` to the space obtained by gluing isometric subsets in `X` and `Y`. -/ def to_glue_r (hΦ : isometry Φ) (hΨ : isometry Ψ) (y : Y) : glue_space hΦ hΨ := quotient.mk' (inr y) instance inhabited_left (hΦ : isometry Φ) (hΨ : isometry Ψ) [inhabited X] : inhabited (glue_space hΦ hΨ) := ⟨to_glue_l _ _ default⟩ instance inhabited_right (hΦ : isometry Φ) (hΨ : isometry Ψ) [inhabited Y] : inhabited (glue_space hΦ hΨ) := ⟨to_glue_r _ _ default⟩ lemma to_glue_commute (hΦ : isometry Φ) (hΨ : isometry Ψ) : (to_glue_l hΦ hΨ) ∘ Φ = (to_glue_r hΦ hΨ) ∘ Ψ := begin letI i : pseudo_metric_space (X ⊕ Y) := glue_premetric hΦ hΨ, letI := i.to_uniform_space, funext, simp only [comp, to_glue_l, to_glue_r], refine uniform_space.separation_quotient.mk_eq_mk.2 (metric.inseparable_iff.2 _), exact glue_dist_glued_points Φ Ψ 0 x end lemma to_glue_l_isometry (hΦ : isometry Φ) (hΨ : isometry Ψ) : isometry (to_glue_l hΦ hΨ) := isometry.of_dist_eq $ λ_ _, rfl lemma to_glue_r_isometry (hΦ : isometry Φ) (hΨ : isometry Ψ) : isometry (to_glue_r hΦ hΨ) := isometry.of_dist_eq $ λ_ _, rfl end gluing --section section inductive_limit /- In this section, we define the inductive limit of f 0 f 1 f 2 f 3 X 0 -----> X 1 -----> X 2 -----> X 3 -----> ... where the X n are metric spaces and f n isometric embeddings. We do it by defining a premetric space structure on Σ n, X n, where the predistance dist x y is obtained by pushing x and y in a common X k using composition by the f n, and taking the distance there. This does not depend on the choice of k as the f n are isometries. The metric space associated to this premetric space is the desired inductive limit.-/ open nat variables {X : ℕ → Type u} [∀ n, metric_space (X n)] {f : Π n, X n → X (n+1)} /-- Predistance on the disjoint union `Σ n, X n`. -/ def inductive_limit_dist (f : Π n, X n → X (n+1)) (x y : Σ n, X n) : ℝ := dist (le_rec_on (le_max_left x.1 y.1) f x.2 : X (max x.1 y.1)) (le_rec_on (le_max_right x.1 y.1) f y.2 : X (max x.1 y.1)) /-- The predistance on the disjoint union `Σ n, X n` can be computed in any `X k` for large enough `k`. -/ lemma inductive_limit_dist_eq_dist (I : ∀ n, isometry (f n)) (x y : Σ n, X n) (m : ℕ) : ∀ hx : x.1 ≤ m, ∀ hy : y.1 ≤ m, inductive_limit_dist f x y = dist (le_rec_on hx f x.2 : X m) (le_rec_on hy f y.2 : X m) := begin induction m with m hm, { assume hx hy, have A : max x.1 y.1 = 0, { rw [nonpos_iff_eq_zero.1 hx, nonpos_iff_eq_zero.1 hy], simp }, unfold inductive_limit_dist, congr; simp only [A] }, { assume hx hy, by_cases h : max x.1 y.1 = m.succ, { unfold inductive_limit_dist, congr; simp only [h] }, { have : max x.1 y.1 ≤ succ m := by simp [hx, hy], have : max x.1 y.1 ≤ m := by simpa [h] using of_le_succ this, have xm : x.1 ≤ m := le_trans (le_max_left _ _) this, have ym : y.1 ≤ m := le_trans (le_max_right _ _) this, rw [le_rec_on_succ xm, le_rec_on_succ ym, (I m).dist_eq], exact hm xm ym }} end /-- Premetric space structure on `Σ n, X n`.-/ def inductive_premetric (I : ∀ n, isometry (f n)) : pseudo_metric_space (Σ n, X n) := { dist := inductive_limit_dist f, dist_self := λx, by simp [dist, inductive_limit_dist], dist_comm := λx y, begin let m := max x.1 y.1, have hx : x.1 ≤ m := le_max_left _ _, have hy : y.1 ≤ m := le_max_right _ _, unfold dist, rw [inductive_limit_dist_eq_dist I x y m hx hy, inductive_limit_dist_eq_dist I y x m hy hx, dist_comm] end, dist_triangle := λx y z, begin let m := max (max x.1 y.1) z.1, have hx : x.1 ≤ m := le_trans (le_max_left _ _) (le_max_left _ _), have hy : y.1 ≤ m := le_trans (le_max_right _ _) (le_max_left _ _), have hz : z.1 ≤ m := le_max_right _ _, calc inductive_limit_dist f x z = dist (le_rec_on hx f x.2 : X m) (le_rec_on hz f z.2 : X m) : inductive_limit_dist_eq_dist I x z m hx hz ... ≤ dist (le_rec_on hx f x.2 : X m) (le_rec_on hy f y.2 : X m) + dist (le_rec_on hy f y.2 : X m) (le_rec_on hz f z.2 : X m) : dist_triangle _ _ _ ... = inductive_limit_dist f x y + inductive_limit_dist f y z : by rw [inductive_limit_dist_eq_dist I x y m hx hy, inductive_limit_dist_eq_dist I y z m hy hz] end } local attribute [instance] inductive_premetric uniform_space.separation_setoid /-- The type giving the inductive limit in a metric space context. -/ @[derive metric_space] def inductive_limit (I : ∀ n, isometry (f n)) : Type* := @uniform_space.separation_quotient _ (inductive_premetric I).to_uniform_space /-- Mapping each `X n` to the inductive limit. -/ def to_inductive_limit (I : ∀ n, isometry (f n)) (n : ℕ) (x : X n) : metric.inductive_limit I := quotient.mk' (sigma.mk n x) instance (I : ∀ n, isometry (f n)) [inhabited (X 0)] : inhabited (inductive_limit I) := ⟨to_inductive_limit _ 0 default⟩ /-- The map `to_inductive_limit n` mapping `X n` to the inductive limit is an isometry. -/ lemma to_inductive_limit_isometry (I : ∀ n, isometry (f n)) (n : ℕ) : isometry (to_inductive_limit I n) := isometry.of_dist_eq $ λ x y, begin change inductive_limit_dist f ⟨n, x⟩ ⟨n, y⟩ = dist x y, rw [inductive_limit_dist_eq_dist I ⟨n, x⟩ ⟨n, y⟩ n (le_refl n) (le_refl n), le_rec_on_self, le_rec_on_self] end /-- The maps `to_inductive_limit n` are compatible with the maps `f n`. -/ lemma to_inductive_limit_commute (I : ∀ n, isometry (f n)) (n : ℕ) : (to_inductive_limit I n.succ) ∘ (f n) = to_inductive_limit I n := begin letI := inductive_premetric I, funext, simp only [comp, to_inductive_limit], refine uniform_space.separation_quotient.mk_eq_mk.2 (metric.inseparable_iff.2 _), show inductive_limit_dist f ⟨n.succ, f n x⟩ ⟨n, x⟩ = 0, { rw [inductive_limit_dist_eq_dist I ⟨n.succ, f n x⟩ ⟨n, x⟩ n.succ, le_rec_on_self, le_rec_on_succ, le_rec_on_self, dist_self], exact le_rfl, exact le_rfl, exact le_succ _ } end end inductive_limit --section end metric --namespace
63afc5069319faf3d0966eb589aa0951a02c3e5a
5fbbd711f9bfc21ee168f46a4be146603ece8835
/lean/natural_number_game/advanced_addition/01.lean
90d6857334e1cd1b11db60682b21101c171566ce
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
goedel-gang/maths
22596f71e3fde9c088e59931f128a3b5efb73a2c
a20a6f6a8ce800427afd595c598a5ad43da1408d
refs/heads/master
1,623,055,941,960
1,621,599,441,000
1,621,599,441,000
169,335,840
0
0
null
null
null
null
UTF-8
Lean
false
false
100
lean
theorem succ_inj' {a b : mynat} (hs : succ(a) = succ(b)) : a = b := begin exact succ_inj hs, end
2cf4156e6f678ed8c7413912a1569f24e57e18f1
453dcd7c0d1ef170b0843a81d7d8caedc9741dce
/analysis/metric_space.lean
f25180c1f1c1686aaae7d95ce6a63480bf5a7797
[ "Apache-2.0" ]
permissive
amswerdlow/mathlib
9af77a1f08486d8fa059448ae2d97795bd12ec0c
27f96e30b9c9bf518341705c99d641c38638dfd0
refs/heads/master
1,585,200,953,598
1,534,275,532,000
1,534,275,532,000
144,564,700
0
0
null
1,534,156,197,000
1,534,156,197,000
null
UTF-8
Lean
false
false
18,422
lean
/- Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Metric spaces. Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro Many definitions and theorems expected on metric spaces are already introduced on uniform spaces and topological spaces. For example: open and closed sets, compactness, completeness, continuity and uniform continuity -/ import data.real.basic analysis.topology.topological_structures open lattice set filter classical noncomputable theory universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- Construct a metric space from a distance function and metric space axioms -/ def metric_space.uniform_space_of_dist (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) : uniform_space α := uniform_space.of_core { uniformity := (⨅ ε>0, principal {p:α×α | dist p.1 p.2 < ε}), refl := le_infi $ assume ε, le_infi $ by simp [set.subset_def, id_rel, dist_self, (>)] {contextual := tt}, comp := le_infi $ assume ε, le_infi $ assume h, lift'_le (mem_infi_sets (ε / 2) $ mem_infi_sets (div_pos_of_pos_of_pos h two_pos) (subset.refl _)) $ have ∀ (a b c : α), dist a c < ε / 2 → dist c b < ε / 2 → dist a b < ε, from assume a b c hac hcb, calc dist a b ≤ dist a c + dist c b : dist_triangle _ _ _ ... < ε / 2 + ε / 2 : add_lt_add hac hcb ... = ε : by rw [div_add_div_same, add_self_div_two], by simpa [comp_rel], symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h, tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [dist_comm] } /-- Metric space Each metric space induces a canonical `uniform_space` and hence a canonical `topological_space`. This is enforced in the type class definition, by extending the `uniform_space` structure. When instantiating a `metric_space` structure, the uniformity fields are not necessary, they will be filled in by default. -/ class metric_space (α : Type u) : Type u := (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (eq_of_dist_eq_zero : ∀ {x y : α}, dist x y = 0 → x = y) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) (to_uniform_space : uniform_space α := metric_space.uniform_space_of_dist dist dist_self dist_comm dist_triangle) (uniformity_dist : uniformity = ⨅ ε>0, principal {p:α×α | dist p.1 p.2 < ε} . control_laws_tac) theorem uniformity_dist_of_mem_uniformity {U : filter (α × α)} (D : α → α → ℝ) (H : ∀ s, s ∈ U.sets ↔ ∃ε>0, ∀{a b:α}, D a b < ε → (a, b) ∈ s) : U = ⨅ ε>0, principal {p:α×α | D p.1 p.2 < ε} := le_antisymm (le_infi $ λ ε, le_infi $ λ ε0, le_principal_iff.2 $ (H _).2 ⟨ε, ε0, λ a b, id⟩) (λ r ur, let ⟨ε, ε0, h⟩ := (H _).1 ur in mem_infi_sets ε $ mem_infi_sets ε0 $ mem_principal_sets.2 $ λ ⟨a, b⟩, h) variables [metric_space α] instance metric_space.to_uniform_space' : uniform_space α := metric_space.to_uniform_space α /-- The distance function (given an ambient metric space on `α`), which returns a nonnegative real number `dist x y` given `x y : α`. -/ def dist : α → α → ℝ := metric_space.dist @[simp] theorem dist_self (x : α) : dist x x = 0 := metric_space.dist_self x theorem eq_of_dist_eq_zero {x y : α} : dist x y = 0 → x = y := metric_space.eq_of_dist_eq_zero theorem dist_comm (x y : α) : dist x y = dist y x := metric_space.dist_comm x y @[simp] theorem dist_eq_zero {x y : α} : dist x y = 0 ↔ x = y := iff.intro eq_of_dist_eq_zero (assume : x = y, this ▸ dist_self _) @[simp] theorem zero_eq_dist {x y : α} : 0 = dist x y ↔ x = y := by rw [eq_comm, dist_eq_zero] theorem dist_triangle (x y z : α) : dist x z ≤ dist x y + dist y z := metric_space.dist_triangle x y z theorem dist_triangle_left (x y z : α) : dist x y ≤ dist z x + dist z y := by rw dist_comm z; apply dist_triangle theorem dist_triangle_right (x y z : α) : dist x y ≤ dist x z + dist y z := by rw dist_comm y; apply dist_triangle theorem swap_dist : function.swap (@dist α _) = dist := by funext x y; exact dist_comm _ _ theorem abs_dist_sub_le (x y z : α) : abs (dist x z - dist y z) ≤ dist x y := abs_sub_le_iff.2 ⟨sub_le_iff_le_add.2 (dist_triangle _ _ _), sub_le_iff_le_add.2 (dist_triangle_left _ _ _)⟩ theorem dist_nonneg {x y : α} : 0 ≤ dist x y := have 2 * dist x y ≥ 0, from calc 2 * dist x y = dist x y + dist y x : by rw [dist_comm x y, two_mul] ... ≥ 0 : by rw ← dist_self x; apply dist_triangle, nonneg_of_mul_nonneg_left this two_pos @[simp] theorem dist_le_zero {x y : α} : dist x y ≤ 0 ↔ x = y := by simpa [le_antisymm_iff, dist_nonneg] using @dist_eq_zero _ _ x y @[simp] theorem dist_pos {x y : α} : 0 < dist x y ↔ x ≠ y := by simpa [-dist_le_zero] using not_congr (@dist_le_zero _ _ x y) /- instantiate metric space as a topology -/ variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α} /-- `ball x ε` is the set of all points `y` with `dist y x < ε` -/ def ball (x : α) (ε : ℝ) : set α := {y | dist y x < ε} @[simp] theorem mem_ball : y ∈ ball x ε ↔ dist y x < ε := iff.rfl theorem mem_ball' : y ∈ ball x ε ↔ dist x y < ε := by rw dist_comm; refl /-- `closed_ball x ε` is the set of all points `y` with `dist y x ≤ ε` -/ def closed_ball (x : α) (ε : ℝ) := {y | dist y x ≤ ε} @[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ dist y x ≤ ε := iff.rfl theorem pos_of_mem_ball (hy : y ∈ ball x ε) : ε > 0 := lt_of_le_of_lt dist_nonneg hy theorem mem_ball_self (h : ε > 0) : x ∈ ball x ε := show dist x x < ε, by rw dist_self; assumption theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε := by simp [dist_comm] theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ := λ y (yx : _ < ε₁), lt_of_lt_of_le yx h theorem ball_disjoint (h : ε₁ + ε₂ ≤ dist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ := eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩, not_lt_of_le (dist_triangle_left x y z) (lt_of_lt_of_le (add_lt_add h₁ h₂) h) theorem ball_disjoint_same (h : ε ≤ dist x y / 2) : ball x ε ∩ ball y ε = ∅ := ball_disjoint $ by rwa [← two_mul, ← le_div_iff' two_pos] theorem ball_subset (h : dist x y ≤ ε₂ - ε₁) : ball x ε₁ ⊆ ball y ε₂ := λ z zx, by rw ← add_sub_cancel'_right ε₁ ε₂; exact lt_of_le_of_lt (dist_triangle z x y) (add_lt_add_of_lt_of_le zx h) theorem ball_half_subset (y) (h : y ∈ ball x (ε / 2)) : ball y (ε / 2) ⊆ ball x ε := ball_subset $ by rw sub_self_div_two; exact le_of_lt h theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε := ⟨_, sub_pos.2 h, ball_subset $ by rw sub_sub_self⟩ theorem ball_eq_empty_iff_nonpos : ε ≤ 0 ↔ ball x ε = ∅ := (eq_empty_iff_forall_not_mem.trans ⟨λ h, le_of_not_gt $ λ ε0, h _ $ mem_ball_self ε0, λ ε0 y h, not_lt_of_le ε0 $ pos_of_mem_ball h⟩).symm theorem uniformity_dist : uniformity = (⨅ ε>0, principal {p:α×α | dist p.1 p.2 < ε}) := metric_space.uniformity_dist _ theorem uniformity_dist' : uniformity = (⨅ε:{ε:ℝ // ε>0}, principal {p:α×α | dist p.1 p.2 < ε.val}) := by simp [infi_subtype]; exact uniformity_dist theorem mem_uniformity_dist {s : set (α×α)} : s ∈ (@uniformity α _).sets ↔ (∃ε>0, ∀{a b:α}, dist a b < ε → (a, b) ∈ s) := begin rw [uniformity_dist', infi_sets_eq], simp [subset_def], exact assume ⟨r, hr⟩ ⟨p, hp⟩, ⟨⟨min r p, lt_min hr hp⟩, by simp [lt_min_iff] {contextual := tt}⟩, exact ⟨⟨1, zero_lt_one⟩⟩ end theorem dist_mem_uniformity {ε:ℝ} (ε0 : 0 < ε) : {p:α×α | dist p.1 p.2 < ε} ∈ (@uniformity α _).sets := mem_uniformity_dist.2 ⟨ε, ε0, λ a b, id⟩ theorem uniform_continuous_of_metric [metric_space β] {f : α → β} : uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b:α}, dist a b < δ → dist (f a) (f b) < ε := uniform_continuous_def.trans ⟨λ H ε ε0, mem_uniformity_dist.1 $ H _ $ dist_mem_uniformity ε0, λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru, ⟨δ, δ0, hδ⟩ := H _ ε0 in mem_uniformity_dist.2 ⟨δ, δ0, λ a b h, hε (hδ h)⟩⟩ theorem uniform_embedding_of_metric [metric_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ := uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl ⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (dist_mem_uniformity δ0), ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 tu in ⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩, λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in ⟨_, dist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩ theorem totally_bounded_of_metric {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, H _ (dist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru, ⟨t, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ lemma cauchy_of_metric {f : filter α} : cauchy f ↔ f ≠ ⊥ ∧ ∀ ε > 0, ∃ t ∈ f.sets, ∀ x y ∈ t, dist x y < ε := cauchy_iff.trans $ and_congr iff.rfl ⟨λ H ε ε0, let ⟨t, tf, ts⟩ := H _ (dist_mem_uniformity ε0) in ⟨t, tf, λ x y xt yt, @ts (x, y) ⟨xt, yt⟩⟩, λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru, ⟨t, tf, h⟩ := H ε ε0 in ⟨t, tf, λ ⟨x, y⟩ ⟨hx, hy⟩, hε (h x y hx hy)⟩⟩ theorem nhds_eq_metric : nhds x = (⨅ε:{ε:ℝ // ε>0}, principal (ball x ε.val)) := begin rw [nhds_eq_uniformity, uniformity_dist', lift'_infi], { apply congr_arg, funext ε, rw [lift'_principal], { simp [ball, dist_comm] }, { exact monotone_preimage } }, { exact ⟨⟨1, zero_lt_one⟩⟩ }, { intros, refl } end theorem mem_nhds_iff_metric : s ∈ (nhds x).sets ↔ ∃ε>0, ball x ε ⊆ s := begin rw [nhds_eq_metric, infi_sets_eq], { simp }, { intros y z, cases y with y hy, cases z with z hz, refine ⟨⟨min y z, lt_min hy hz⟩, _⟩, simp [ball_subset_ball, min_le_left, min_le_right] }, { exact ⟨⟨1, zero_lt_one⟩⟩ } end theorem is_open_metric : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s := by simp [is_open_iff_nhds, mem_nhds_iff_metric] theorem is_open_ball : is_open (ball x ε) := is_open_metric.2 $ λ y, exists_ball_subset_ball theorem ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : ball x ε ∈ (nhds x).sets := mem_nhds_sets is_open_ball (mem_ball_self ε0) theorem tendsto_nhds_of_metric [metric_space β] {f : α → β} {a b} : tendsto f (nhds a) (nhds b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) b < ε := ⟨λ H ε ε0, mem_nhds_iff_metric.1 (H (ball_mem_nhds _ ε0)), λ H s hs, let ⟨ε, ε0, hε⟩ := mem_nhds_iff_metric.1 hs, ⟨δ, δ0, hδ⟩ := H _ ε0 in mem_nhds_iff_metric.2 ⟨δ, δ0, λ x h, hε (hδ h)⟩⟩ theorem continuous_of_metric [metric_space β] {f : α → β} : continuous f ↔ ∀ {b} (ε > 0), ∃ δ > 0, ∀{a}, dist a b < δ → dist (f a) (f b) < ε := continuous_iff_tendsto.trans $ forall_congr $ λ b, tendsto_nhds_of_metric theorem eq_of_forall_dist_le {x y : α} (h : ∀ε, ε > 0 → dist x y ≤ ε) : x = y := eq_of_dist_eq_zero (eq_of_le_of_forall_le_of_dense dist_nonneg h) instance metric_space.to_separated : separated α := separated_def.2 $ λ x y h, eq_of_forall_dist_le $ λ ε ε0, le_of_lt (h _ (dist_mem_uniformity ε0)) /-- Instantiate the reals as a metric space. -/ instance : metric_space ℝ := { dist := λx y, abs (x - y), dist_self := by simp [abs_zero], eq_of_dist_eq_zero := by simp [add_neg_eq_zero], dist_comm := assume x y, by rw [abs_sub], dist_triangle := assume x y z, abs_sub_le _ _ _ } theorem real.dist_eq (x y : ℝ) : dist x y = abs (x - y) := rfl theorem real.dist_0_eq_abs (x : ℝ) : dist x 0 = abs x := by simp [real.dist_eq] @[simp] theorem abs_dist {a b : α} : abs (dist a b) = dist a b := abs_of_nonneg dist_nonneg instance : orderable_topology ℝ := orderable_topology_of_nhds_abs $ λ x, begin simp only [show ∀ r, {b : ℝ | abs (x - b) < r} = ball x r, by simp [-sub_eq_add_neg, abs_sub, ball, real.dist_eq]], apply le_antisymm, { simp [le_infi_iff], exact λ ε ε0, mem_nhds_sets (is_open_ball) (mem_ball_self ε0) }, { intros s h, rcases mem_nhds_iff_metric.1 h with ⟨ε, ε0, ss⟩, exact mem_infi_sets _ (mem_infi_sets ε0 (mem_principal_sets.2 ss)) }, end def metric_space.replace_uniformity {α} [U : uniform_space α] (m : metric_space α) (H : @uniformity _ U = @uniformity _ (metric_space.to_uniform_space α)) : metric_space α := { dist := @dist _ m, dist_self := dist_self, eq_of_dist_eq_zero := @eq_of_dist_eq_zero _ _, dist_comm := dist_comm, dist_triangle := dist_triangle, to_uniform_space := U, uniformity_dist := H.trans (@uniformity_dist α _) } def metric_space.induced {α β} (f : α → β) (hf : function.injective f) (m : metric_space β) : metric_space α := { dist := λ x y, dist (f x) (f y), dist_self := λ x, dist_self _, eq_of_dist_eq_zero := λ x y h, hf (dist_eq_zero.1 h), dist_comm := λ x y, dist_comm _ _, dist_triangle := λ x y z, dist_triangle _ _ _, to_uniform_space := uniform_space.vmap f m.to_uniform_space, uniformity_dist := begin apply @uniformity_dist_of_mem_uniformity _ _ (λ x y, dist (f x) (f y)), refine λ s, mem_vmap_sets.trans _, split; intro H, { rcases H with ⟨r, ru, rs⟩, rcases mem_uniformity_dist.1 ru with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h }, { rcases H with ⟨ε, ε0, hε⟩, exact ⟨_, dist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ } end } theorem metric_space.induced_uniform_embedding {α β} (f : α → β) (hf : function.injective f) (m : metric_space β) : by haveI := metric_space.induced f hf m; exact uniform_embedding f := by let := metric_space.induced f hf m; exactI uniform_embedding_of_metric.2 ⟨hf, uniform_continuous_vmap, λ ε ε0, ⟨ε, ε0, λ a b, id⟩⟩ instance {p : α → Prop} [t : metric_space α] : metric_space (subtype p) := metric_space.induced subtype.val (λ x y, subtype.eq) t theorem subtype.dist_eq {p : α → Prop} [t : metric_space α] (x y : subtype p) : dist x y = dist x.1 y.1 := rfl instance prod.metric_space_max [metric_space β] : metric_space (α × β) := { dist := λ x y, max (dist x.1 y.1) (dist x.2 y.2), dist_self := λ x, by simp, eq_of_dist_eq_zero := λ x y h, begin cases max_le_iff.1 (le_of_eq h) with h₁ h₂, exact prod.ext_iff.2 ⟨dist_le_zero.1 h₁, dist_le_zero.1 h₂⟩ end, dist_comm := λ x y, by simp [dist_comm], dist_triangle := λ x y z, max_le (le_trans (dist_triangle _ _ _) (add_le_add (le_max_left _ _) (le_max_left _ _))) (le_trans (dist_triangle _ _ _) (add_le_add (le_max_right _ _) (le_max_right _ _))), uniformity_dist := begin refine uniformity_prod.trans _, simp [uniformity_dist, vmap_infi], rw ← infi_inf_eq, congr, funext, rw ← infi_inf_eq, congr, funext, simp [inf_principal, ext_iff, max_lt_iff] end, to_uniform_space := prod.uniform_space } theorem uniform_continuous_dist' : uniform_continuous (λp:α×α, dist p.1 p.2) := uniform_continuous_of_metric.2 (λ ε ε0, ⟨ε/2, half_pos ε0, begin suffices, { intros p q h, cases p with p₁ p₂, cases q with q₁ q₂, cases max_lt_iff.1 h with h₁ h₂, clear h, dsimp at h₁ h₂ ⊢, rw real.dist_eq, refine abs_sub_lt_iff.2 ⟨_, _⟩, { revert p₁ p₂ q₁ q₂ h₁ h₂, exact this }, { apply this; rwa dist_comm } }, intros p₁ p₂ q₁ q₂ h₁ h₂, have := add_lt_add (abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₁ q₁ p₂) h₁)).1 (abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₂ q₂ q₁) h₂)).1, rwa [add_halves, dist_comm p₂, sub_add_sub_cancel, dist_comm q₂] at this end⟩) theorem uniform_continuous_dist [uniform_space β] {f g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λb, dist (f b) (g b)) := (hf.prod_mk hg).comp uniform_continuous_dist' theorem continuous_dist' : continuous (λp:α×α, dist p.1 p.2) := uniform_continuous_dist'.continuous theorem continuous_dist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, dist (f b) (g b)) := (hf.prod_mk hg).comp continuous_dist' theorem tendsto_dist {f g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (nhds a)) (hg : tendsto g x (nhds b)) : tendsto (λx, dist (f x) (g x)) x (nhds (dist a b)) := have tendsto (λp:α×α, dist p.1 p.2) (nhds (a, b)) (nhds (dist a b)), from continuous_iff_tendsto.mp continuous_dist' (a, b), (hf.prod_mk hg).comp (by rw [nhds_prod_eq] at this; exact this) lemma nhds_vmap_dist (a : α) : (nhds (0 : ℝ)).vmap (λa', dist a' a) = nhds a := have h₁ : ∀ε, (λa', dist a' a) ⁻¹' ball 0 ε ⊆ ball a ε, by simp [subset_def, real.dist_0_eq_abs], have h₂ : tendsto (λa', dist a' a) (nhds a) (nhds (dist a a)), from tendsto_dist tendsto_id tendsto_const_nhds, le_antisymm (by simp [h₁, nhds_eq_metric, infi_le_infi, principal_mono, -le_principal_iff, -le_infi_iff]) (by simpa [map_le_iff_le_vmap.symm, tendsto] using h₂) lemma tendsto_iff_dist_tendsto_zero {f : β → α} {x : filter β} {a : α} : (tendsto f x (nhds a)) ↔ (tendsto (λb, dist (f b) a) x (nhds 0)) := by rw [← nhds_vmap_dist a, tendsto_vmap_iff] theorem is_closed_ball : is_closed (closed_ball x ε) := is_closed_le (continuous_dist continuous_id continuous_const) continuous_const