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
09e36d8505e70dc5d3fd566c7778ea636b6b5581
1437b3495ef9020d5413178aa33c0a625f15f15f
/category_theory/yoneda.lean
a5da4e750c805063e161ccf91443b9c9a83fa548
[ "Apache-2.0" ]
permissive
jean002/mathlib
c66bbb2d9fdc9c03ae07f869acac7ddbfce67a30
dc6c38a765799c99c4d9c8d5207d9e6c9e0e2cfd
refs/heads/master
1,587,027,806,375
1,547,306,358,000
1,547,306,358,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,371
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison /- The Yoneda embedding, as a functor `yoneda : C ⥤ ((Cᵒᵖ) ⥤ (Type v₁))`, along with an instance that it is `fully_faithful`. Also the Yoneda lemma, `yoneda_lemma : (yoneda_pairing C) ≅ (yoneda_evaluation C)`. -/ import category_theory.natural_transformation import category_theory.opposites import category_theory.types import category_theory.fully_faithful import category_theory.natural_isomorphism namespace category_theory universes v₁ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u₁} [𝒞 : category.{v₁} C] include 𝒞 def yoneda : C ⥤ (Cᵒᵖ ⥤ Type v₁) := { obj := λ X, { obj := λ Y : C, Y ⟶ X, map := λ Y Y' f g, f ≫ g, map_comp' := begin intros X_1 Y Z f g, ext1, dsimp at *, erw [category.assoc] end, map_id' := begin intros X_1, ext1, dsimp at *, erw [category.id_comp] end }, map := λ X X' f, { app := λ Y g, g ≫ f } } def coyoneda : Cᵒᵖ ⥤ (C ⥤ Type v₁) := { obj := λ X : C, { obj := λ Y, X ⟶ Y, map := λ Y Y' f g, g ≫ f, map_comp' := begin intros X_1 Y Z f g, ext1, dsimp at *, erw [category.assoc] end, map_id' := begin intros X_1, ext1, dsimp at *, erw [category.comp_id] end }, map := λ X X' f, { app := λ Y g, f ≫ g }, map_comp' := begin intros X Y Z f g, ext1, ext1, dsimp at *, erw [category.assoc] end, map_id' := begin intros X, ext1, ext1, dsimp at *, erw [category.id_comp] end } namespace yoneda @[simp] lemma obj_obj (X Y : C) : (yoneda.obj X).obj Y = (Y ⟶ X) := rfl @[simp] lemma obj_map (X : C) {Y Y' : C} (f : Y ⟶ Y') : (yoneda.obj X).map f = λ g, f ≫ g := rfl @[simp] lemma map_app {X X' : C} (f : X ⟶ X') (Y : C) : (yoneda.map f).app Y = λ g, g ≫ f := rfl lemma obj_map_id {X Y : Cᵒᵖ} (f : X ⟶ Y) : ((@yoneda C _).obj X).map f (𝟙 X) = ((@yoneda C _).map f).app Y (𝟙 Y) := by obviously @[simp] lemma naturality {X Y : C} (α : yoneda.obj X ⟶ yoneda.obj Y) {Z Z' : C} (f : Z ⟶ Z') (h : Z' ⟶ X) : f ≫ α.app Z' h = α.app Z (f ≫ h) := begin erw [functor_to_types.naturality], refl end instance yoneda_fully_faithful : fully_faithful (@yoneda C _) := { preimage := λ X Y f, (f.app X) (𝟙 X), injectivity' := λ X Y f g p, begin injection p with h, convert (congr_fun (congr_fun h X) (𝟙 X)) ; simp end } /-- Extensionality via Yoneda. The typical usage would be ``` -- Goal is `X ≅ Y` apply yoneda.ext, -- Goals are now functions `(Z ⟶ X) → (Z ⟶ Y)`, `(Z ⟶ Y) → (Z ⟶ X)`, and the fact that these functions are inverses and natural in `Z`. ``` -/ def ext (X Y : C) (p : Π {Z : C}, (Z ⟶ X) → (Z ⟶ Y)) (q : Π {Z : C}, (Z ⟶ Y) → (Z ⟶ X)) (h₁ : Π {Z : C} (f : Z ⟶ X), q (p f) = f) (h₂ : Π {Z : C} (f : Z ⟶ Y), p (q f) = f) (n : Π {Z Z' : C} (f : Z' ⟶ Z) (g : Z ⟶ X), p (f ≫ g) = f ≫ p g) : X ≅ Y := @preimage_iso _ _ _ _ yoneda _ _ _ _ (nat_iso.of_components (λ Z, { hom := p, inv := q, }) (by tidy)) -- We need to help typeclass inference with some awkward universe levels here. instance prod_category_instance_1 : category (((Cᵒᵖ) ⥤ Type v₁) × (Cᵒᵖ)) := category_theory.prod.{(max u₁ v₁) v₁} (Cᵒᵖ ⥤ Type v₁) (Cᵒᵖ) instance prod_category_instance_2 : category ((Cᵒᵖ) × ((Cᵒᵖ) ⥤ Type v₁)) := category_theory.prod.{v₁ (max u₁ v₁)} (Cᵒᵖ) (Cᵒᵖ ⥤ Type v₁) end yoneda namespace coyoneda @[simp] lemma obj_obj (X Y : C) : (coyoneda.obj X).obj Y = (X ⟶ Y) := rfl @[simp] lemma obj_map {X' X : C} (f : X' ⟶ X) (Y : C) : (coyoneda.obj Y).map f = λ g, g ≫ f := rfl @[simp] lemma map_app (X : C) {Y Y' : C} (f : Y ⟶ Y') : (coyoneda.map f).app X = λ g, f ≫ g := rfl end coyoneda class representable (F : Cᵒᵖ ⥤ Type v₁) := (X : C) (w : yoneda.obj X ≅ F) variables (C) open yoneda def yoneda_evaluation : (Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) ⥤ Type (max u₁ v₁) := (evaluation_uncurried (Cᵒᵖ) (Type v₁)) ⋙ ulift_functor.{u₁} @[simp] lemma yoneda_evaluation_map_down (P Q : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) (α : P ⟶ Q) (x : (yoneda_evaluation C).obj P) : ((yoneda_evaluation C).map α x).down = α.2.app Q.1 (P.2.map α.1 x.down) := rfl def yoneda_pairing : (Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) ⥤ Type (max u₁ v₁) := (functor.prod yoneda.op (functor.id (Cᵒᵖ ⥤ Type v₁))) ⋙ functor.hom (Cᵒᵖ ⥤ Type v₁) @[simp] lemma yoneda_pairing_map (P Q : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) (α : P ⟶ Q) (β : (yoneda_pairing C).obj P) : (yoneda_pairing C).map α β = yoneda.map α.1 ≫ β ≫ α.2 := rfl def yoneda_lemma : yoneda_pairing C ≅ yoneda_evaluation C := { hom := { app := λ F x, ulift.up ((x.app F.1) (𝟙 F.1)), naturality' := begin intros X Y f, ext1, ext1, cases f, cases Y, cases X, dsimp at *, simp at *, erw [←functor_to_types.naturality, obj_map_id, functor_to_types.naturality, functor_to_types.map_id] end }, inv := { app := λ F x, { app := λ X a, (F.2.map a) x.down, naturality' := begin intros X Y f, ext1, cases x, cases F, dsimp at *, erw [functor_to_types.map_comp] end }, naturality' := begin intros X Y f, ext1, ext1, ext1, cases x, cases f, cases Y, cases X, dsimp at *, erw [←functor_to_types.naturality, functor_to_types.map_comp] end }, hom_inv_id' := begin ext1, ext1, ext1, ext1, cases X, dsimp at *, erw [←functor_to_types.naturality, obj_map_id, functor_to_types.naturality, functor_to_types.map_id] end, inv_hom_id' := begin ext1, ext1, ext1, cases x, cases X, dsimp at *, erw [functor_to_types.map_id] end }. variables {C} @[simp] def yoneda_sections (X : C) (F : Cᵒᵖ ⥤ Type v₁) : (yoneda.obj X ⟹ F) ≅ ulift.{u₁} (F.obj X) := nat_iso.app (yoneda_lemma C) (X, F) omit 𝒞 @[simp] def yoneda_sections_small {C : Type u₁} [small_category C] (X : C) (F : Cᵒᵖ ⥤ Type u₁) : (yoneda.obj X ⟹ F) ≅ F.obj X := yoneda_sections X F ≪≫ ulift_trivial _ end category_theory
dd0a1749ede44bf6e17cdfcb110d851e3979bdc4
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/number_theory/padics/padic_numbers.lean
b77c4f65eae3fdc4facba6c1e04eed27c75f93ca
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
38,556
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import analysis.normed_space.basic import number_theory.padics.padic_norm /-! # p-adic numbers This file defines the p-adic numbers (rationals) `ℚ_p` as the completion of `ℚ` with respect to the p-adic norm. We show that the p-adic norm on ℚ extends to `ℚ_p`, that `ℚ` is embedded in `ℚ_p`, and that `ℚ_p` is Cauchy complete. ## Important definitions * `padic` : the type of p-adic numbers * `padic_norm_e` : the rational valued p-adic norm on `ℚ_p` ## Notation We introduce the notation `ℚ_[p]` for the p-adic numbers. ## Implementation notes Much, but not all, of this file assumes that `p` is prime. This assumption is inferred automatically by taking `[fact (prime p)]` as a type class argument. We use the same concrete Cauchy sequence construction that is used to construct ℝ. `ℚ_p` inherits a field structure from this construction. The extension of the norm on ℚ to `ℚ_p` is *not* analogous to extending the absolute value to ℝ, and hence the proof that `ℚ_p` is complete is different from the proof that ℝ is complete. A small special-purpose simplification tactic, `padic_index_simp`, is used to manipulate sequence indices in the proof that the norm extends. `padic_norm_e` is the rational-valued p-adic norm on `ℚ_p`. To instantiate `ℚ_p` as a normed field, we must cast this into a ℝ-valued norm. The `ℝ`-valued norm, using notation `∥ ∥` from normed spaces, is the canonical representation of this norm. `simp` prefers `padic_norm` to `padic_norm_e` when possible. Since `padic_norm_e` and `∥ ∥` have different types, `simp` does not rewrite one to the other. Coercions from `ℚ` to `ℚ_p` are set up to work with the `norm_cast` tactic. ## References * [F. Q. Gouêva, *p-adic numbers*][gouvea1997] * [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019] * <https://en.wikipedia.org/wiki/P-adic_number> ## Tags p-adic, p adic, padic, norm, valuation, cauchy, completion, p-adic completion -/ noncomputable theory open_locale classical open nat multiplicity padic_norm cau_seq cau_seq.completion metric /-- The type of Cauchy sequences of rationals with respect to the p-adic norm. -/ @[reducible] def padic_seq (p : ℕ) := cau_seq _ (padic_norm p) namespace padic_seq section variables {p : ℕ} [fact p.prime] /-- The p-adic norm of the entries of a nonzero Cauchy sequence of rationals is eventually constant. -/ lemma stationary {f : cau_seq ℚ (padic_norm p)} (hf : ¬ f ≈ 0) : ∃ N, ∀ m n, N ≤ m → N ≤ n → padic_norm p (f n) = padic_norm p (f m) := have ∃ ε > 0, ∃ N1, ∀ j ≥ N1, ε ≤ padic_norm p (f j), from cau_seq.abv_pos_of_not_lim_zero $ not_lim_zero_of_not_congr_zero hf, let ⟨ε, hε, N1, hN1⟩ := this, ⟨N2, hN2⟩ := cau_seq.cauchy₂ f hε in ⟨ max N1 N2, λ n m hn hm, have padic_norm p (f n - f m) < ε, from hN2 _ _ (max_le_iff.1 hn).2 (max_le_iff.1 hm).2, have padic_norm p (f n - f m) < padic_norm p (f n), from lt_of_lt_of_le this $ hN1 _ (max_le_iff.1 hn).1, have padic_norm p (f n - f m) < max (padic_norm p (f n)) (padic_norm p (f m)), from lt_max_iff.2 (or.inl this), begin by_contradiction hne, rw ←padic_norm.neg p (f m) at hne, have hnam := add_eq_max_of_ne p hne, rw [padic_norm.neg, max_comm] at hnam, rw [←hnam, sub_eq_add_neg, add_comm] at this, apply _root_.lt_irrefl _ this end ⟩ /-- For all n ≥ stationary_point f hf, the p-adic norm of f n is the same. -/ def stationary_point {f : padic_seq p} (hf : ¬ f ≈ 0) : ℕ := classical.some $ stationary hf lemma stationary_point_spec {f : padic_seq p} (hf : ¬ f ≈ 0) : ∀ {m n}, stationary_point hf ≤ m → stationary_point hf ≤ n → padic_norm p (f n) = padic_norm p (f m) := classical.some_spec $ stationary hf /-- Since the norm of the entries of a Cauchy sequence is eventually stationary, we can lift the norm to sequences. -/ def norm (f : padic_seq p) : ℚ := if hf : f ≈ 0 then 0 else padic_norm p (f (stationary_point hf)) lemma norm_zero_iff (f : padic_seq p) : f.norm = 0 ↔ f ≈ 0 := begin constructor, { intro h, by_contradiction hf, unfold norm at h, split_ifs at h, apply hf, intros ε hε, existsi stationary_point hf, intros j hj, have heq := stationary_point_spec hf (le_refl _) hj, simpa [h, heq] }, { intro h, simp [norm, h] } end end section embedding open cau_seq variables {p : ℕ} [fact p.prime] lemma equiv_zero_of_val_eq_of_equiv_zero {f g : padic_seq p} (h : ∀ k, padic_norm p (f k) = padic_norm p (g k)) (hf : f ≈ 0) : g ≈ 0 := λ ε hε, let ⟨i, hi⟩ := hf _ hε in ⟨i, λ j hj, by simpa [h] using hi _ hj⟩ lemma norm_nonzero_of_not_equiv_zero {f : padic_seq p} (hf : ¬ f ≈ 0) : f.norm ≠ 0 := hf ∘ f.norm_zero_iff.1 lemma norm_eq_norm_app_of_nonzero {f : padic_seq p} (hf : ¬ f ≈ 0) : ∃ k, f.norm = padic_norm p k ∧ k ≠ 0 := have heq : f.norm = padic_norm p (f $ stationary_point hf), by simp [norm, hf], ⟨f $ stationary_point hf, heq, λ h, norm_nonzero_of_not_equiv_zero hf (by simpa [h] using heq)⟩ lemma not_lim_zero_const_of_nonzero {q : ℚ} (hq : q ≠ 0) : ¬ lim_zero (const (padic_norm p) q) := λ h', hq $ const_lim_zero.1 h' lemma not_equiv_zero_const_of_nonzero {q : ℚ} (hq : q ≠ 0) : ¬ (const (padic_norm p) q) ≈ 0 := λ h : lim_zero (const (padic_norm p) q - 0), not_lim_zero_const_of_nonzero hq $ by simpa using h lemma norm_nonneg (f : padic_seq p) : 0 ≤ f.norm := if hf : f ≈ 0 then by simp [hf, norm] else by simp [norm, hf, padic_norm.nonneg] /-- An auxiliary lemma for manipulating sequence indices. -/ lemma lift_index_left_left {f : padic_seq p} (hf : ¬ f ≈ 0) (v2 v3 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max (stationary_point hf) (max v2 v3))) := begin apply stationary_point_spec hf, { apply le_max_left }, { apply le_refl } end /-- An auxiliary lemma for manipulating sequence indices. -/ lemma lift_index_left {f : padic_seq p} (hf : ¬ f ≈ 0) (v1 v3 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max v1 (max (stationary_point hf) v3))) := begin apply stationary_point_spec hf, { apply le_trans, { apply le_max_left _ v3 }, { apply le_max_right } }, { apply le_refl } end /-- An auxiliary lemma for manipulating sequence indices. -/ lemma lift_index_right {f : padic_seq p} (hf : ¬ f ≈ 0) (v1 v2 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max v1 (max v2 (stationary_point hf)))) := begin apply stationary_point_spec hf, { apply le_trans, { apply le_max_right v2 }, { apply le_max_right } }, { apply le_refl } end end embedding section valuation open cau_seq variables {p : ℕ} [fact p.prime] /-! ### Valuation on `padic_seq` -/ /-- The `p`-adic valuation on `ℚ` lifts to `padic_seq p`. `valuation f` is defined to be the valuation of the (`ℚ`-valued) stationary point of `f`. -/ def valuation (f : padic_seq p) : ℤ := if hf : f ≈ 0 then 0 else padic_val_rat p (f (stationary_point hf)) lemma norm_eq_pow_val {f : padic_seq p} (hf : ¬ f ≈ 0) : f.norm = p^(-f.valuation : ℤ) := begin rw [norm, valuation, dif_neg hf, dif_neg hf, padic_norm, if_neg], intro H, apply cau_seq.not_lim_zero_of_not_congr_zero hf, intros ε hε, use (stationary_point hf), intros n hn, rw stationary_point_spec hf (le_refl _) hn, simpa [H] using hε, end lemma val_eq_iff_norm_eq {f g : padic_seq p} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) : f.valuation = g.valuation ↔ f.norm = g.norm := begin rw [norm_eq_pow_val hf, norm_eq_pow_val hg, ← neg_inj, fpow_inj], { exact_mod_cast (fact.out p.prime).pos }, { exact_mod_cast (fact.out p.prime).ne_one }, end end valuation end padic_seq section open padic_seq private meta def index_simp_core (hh hf hg : expr) (at_ : interactive.loc := interactive.loc.ns [none]) : tactic unit := do [v1, v2, v3] ← [hh, hf, hg].mmap (λ n, tactic.mk_app ``stationary_point [n] <|> return n), e1 ← tactic.mk_app ``lift_index_left_left [hh, v2, v3] <|> return `(true), e2 ← tactic.mk_app ``lift_index_left [hf, v1, v3] <|> return `(true), e3 ← tactic.mk_app ``lift_index_right [hg, v1, v2] <|> return `(true), sl ← [e1, e2, e3].mfoldl (λ s e, simp_lemmas.add s e) simp_lemmas.mk, when at_.include_goal (tactic.simp_target sl >> tactic.skip), hs ← at_.get_locals, hs.mmap' (tactic.simp_hyp sl []) /-- This is a special-purpose tactic that lifts padic_norm (f (stationary_point f)) to padic_norm (f (max _ _ _)). -/ meta def tactic.interactive.padic_index_simp (l : interactive.parse interactive.types.pexpr_list) (at_ : interactive.parse interactive.types.location) : tactic unit := do [h, f, g] ← l.mmap tactic.i_to_expr, index_simp_core h f g at_ end namespace padic_seq section embedding open cau_seq variables {p : ℕ} [hp : fact p.prime] include hp lemma norm_mul (f g : padic_seq p) : (f * g).norm = f.norm * g.norm := if hf : f ≈ 0 then have hg : f * g ≈ 0, from mul_equiv_zero' _ hf, by simp only [hf, hg, norm, dif_pos, zero_mul] else if hg : g ≈ 0 then have hf : f * g ≈ 0, from mul_equiv_zero _ hg, by simp only [hf, hg, norm, dif_pos, mul_zero] else have hfg : ¬ f * g ≈ 0, by apply mul_not_equiv_zero; assumption, begin unfold norm, split_ifs, padic_index_simp [hfg, hf, hg], apply padic_norm.mul end lemma eq_zero_iff_equiv_zero (f : padic_seq p) : mk f = 0 ↔ f ≈ 0 := mk_eq lemma ne_zero_iff_nequiv_zero (f : padic_seq p) : mk f ≠ 0 ↔ ¬ f ≈ 0 := not_iff_not.2 (eq_zero_iff_equiv_zero _) lemma norm_const (q : ℚ) : norm (const (padic_norm p) q) = padic_norm p q := if hq : q = 0 then have (const (padic_norm p) q) ≈ 0, by simp [hq]; apply setoid.refl (const (padic_norm p) 0), by subst hq; simp [norm, this] else have ¬ (const (padic_norm p) q) ≈ 0, from not_equiv_zero_const_of_nonzero hq, by simp [norm, this] lemma norm_values_discrete (a : padic_seq p) (ha : ¬ a ≈ 0) : (∃ (z : ℤ), a.norm = ↑p ^ (-z)) := let ⟨k, hk, hk'⟩ := norm_eq_norm_app_of_nonzero ha in by simpa [hk] using padic_norm.values_discrete p hk' lemma norm_one : norm (1 : padic_seq p) = 1 := have h1 : ¬ (1 : padic_seq p) ≈ 0, from one_not_equiv_zero _, by simp [h1, norm, hp.1.one_lt] private lemma norm_eq_of_equiv_aux {f g : padic_seq p} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) (hfg : f ≈ g) (h : padic_norm p (f (stationary_point hf)) ≠ padic_norm p (g (stationary_point hg))) (hlt : padic_norm p (g (stationary_point hg)) < padic_norm p (f (stationary_point hf))) : false := begin have hpn : 0 < padic_norm p (f (stationary_point hf)) - padic_norm p (g (stationary_point hg)), from sub_pos_of_lt hlt, cases hfg _ hpn with N hN, let i := max N (max (stationary_point hf) (stationary_point hg)), have hi : N ≤ i, from le_max_left _ _, have hN' := hN _ hi, padic_index_simp [N, hf, hg] at hN' h hlt, have hpne : padic_norm p (f i) ≠ padic_norm p (-(g i)), by rwa [ ←padic_norm.neg p (g i)] at h, let hpnem := add_eq_max_of_ne p hpne, have hpeq : padic_norm p ((f - g) i) = max (padic_norm p (f i)) (padic_norm p (g i)), { rwa padic_norm.neg at hpnem }, rw [hpeq, max_eq_left_of_lt hlt] at hN', have : padic_norm p (f i) < padic_norm p (f i), { apply lt_of_lt_of_le hN', apply sub_le_self, apply padic_norm.nonneg }, exact lt_irrefl _ this end private lemma norm_eq_of_equiv {f g : padic_seq p} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) (hfg : f ≈ g) : padic_norm p (f (stationary_point hf)) = padic_norm p (g (stationary_point hg)) := begin by_contradiction h, cases (decidable.em (padic_norm p (g (stationary_point hg)) < padic_norm p (f (stationary_point hf)))) with hlt hnlt, { exact norm_eq_of_equiv_aux hf hg hfg h hlt }, { apply norm_eq_of_equiv_aux hg hf (setoid.symm hfg) (ne.symm h), apply lt_of_le_of_ne, apply le_of_not_gt hnlt, apply h } end theorem norm_equiv {f g : padic_seq p} (hfg : f ≈ g) : f.norm = g.norm := if hf : f ≈ 0 then have hg : g ≈ 0, from setoid.trans (setoid.symm hfg) hf, by simp [norm, hf, hg] else have hg : ¬ g ≈ 0, from hf ∘ setoid.trans hfg, by unfold norm; split_ifs; exact norm_eq_of_equiv hf hg hfg private lemma norm_nonarchimedean_aux {f g : padic_seq p} (hfg : ¬ f + g ≈ 0) (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) : (f + g).norm ≤ max (f.norm) (g.norm) := begin unfold norm, split_ifs, padic_index_simp [hfg, hf, hg], apply padic_norm.nonarchimedean end theorem norm_nonarchimedean (f g : padic_seq p) : (f + g).norm ≤ max (f.norm) (g.norm) := if hfg : f + g ≈ 0 then have 0 ≤ max (f.norm) (g.norm), from le_max_of_le_left (norm_nonneg _), by simpa only [hfg, norm, ne.def, le_max_iff, cau_seq.add_apply, not_true, dif_pos] else if hf : f ≈ 0 then have hfg' : f + g ≈ g, { change lim_zero (f - 0) at hf, show lim_zero (f + g - g), by simpa only [sub_zero, add_sub_cancel] using hf }, have hcfg : (f + g).norm = g.norm, from norm_equiv hfg', have hcl : f.norm = 0, from (norm_zero_iff f).2 hf, have max (f.norm) (g.norm) = g.norm, by rw hcl; exact max_eq_right (norm_nonneg _), by rw [this, hcfg] else if hg : g ≈ 0 then have hfg' : f + g ≈ f, { change lim_zero (g - 0) at hg, show lim_zero (f + g - f), by simpa only [add_sub_cancel', sub_zero] using hg }, have hcfg : (f + g).norm = f.norm, from norm_equiv hfg', have hcl : g.norm = 0, from (norm_zero_iff g).2 hg, have max (f.norm) (g.norm) = f.norm, by rw hcl; exact max_eq_left (norm_nonneg _), by rw [this, hcfg] else norm_nonarchimedean_aux hfg hf hg lemma norm_eq {f g : padic_seq p} (h : ∀ k, padic_norm p (f k) = padic_norm p (g k)) : f.norm = g.norm := if hf : f ≈ 0 then have hg : g ≈ 0, from equiv_zero_of_val_eq_of_equiv_zero h hf, by simp only [hf, hg, norm, dif_pos] else have hg : ¬ g ≈ 0, from λ hg, hf $ equiv_zero_of_val_eq_of_equiv_zero (by simp only [h, forall_const, eq_self_iff_true]) hg, begin simp only [hg, hf, norm, dif_neg, not_false_iff], let i := max (stationary_point hf) (stationary_point hg), have hpf : padic_norm p (f (stationary_point hf)) = padic_norm p (f i), { apply stationary_point_spec, apply le_max_left, apply le_refl }, have hpg : padic_norm p (g (stationary_point hg)) = padic_norm p (g i), { apply stationary_point_spec, apply le_max_right, apply le_refl }, rw [hpf, hpg, h] end lemma norm_neg (a : padic_seq p) : (-a).norm = a.norm := norm_eq $ by simp lemma norm_eq_of_add_equiv_zero {f g : padic_seq p} (h : f + g ≈ 0) : f.norm = g.norm := have lim_zero (f + g - 0), from h, have f ≈ -g, from show lim_zero (f - (-g)), by simpa only [sub_zero, sub_neg_eq_add], have f.norm = (-g).norm, from norm_equiv this, by simpa only [norm_neg] using this lemma add_eq_max_of_ne {f g : padic_seq p} (hfgne : f.norm ≠ g.norm) : (f + g).norm = max f.norm g.norm := have hfg : ¬f + g ≈ 0, from mt norm_eq_of_add_equiv_zero hfgne, if hf : f ≈ 0 then have lim_zero (f - 0), from hf, have f + g ≈ g, from show lim_zero ((f + g) - g), by simpa only [sub_zero, add_sub_cancel], have h1 : (f+g).norm = g.norm, from norm_equiv this, have h2 : f.norm = 0, from (norm_zero_iff _).2 hf, by rw [h1, h2]; rw max_eq_right (norm_nonneg _) else if hg : g ≈ 0 then have lim_zero (g - 0), from hg, have f + g ≈ f, from show lim_zero ((f + g) - f), by rw [add_sub_cancel']; simpa only [sub_zero], have h1 : (f+g).norm = f.norm, from norm_equiv this, have h2 : g.norm = 0, from (norm_zero_iff _).2 hg, by rw [h1, h2]; rw max_eq_left (norm_nonneg _) else begin unfold norm at ⊢ hfgne, split_ifs at ⊢ hfgne, padic_index_simp [hfg, hf, hg] at ⊢ hfgne, exact padic_norm.add_eq_max_of_ne p hfgne end end embedding end padic_seq /-- The p-adic numbers `Q_[p]` are the Cauchy completion of `ℚ` with respect to the p-adic norm. -/ def padic (p : ℕ) [fact p.prime] := @cau_seq.completion.Cauchy _ _ _ _ (padic_norm p) _ notation `ℚ_[` p `]` := padic p namespace padic section completion variables {p : ℕ} [fact p.prime] /-- The discrete field structure on `ℚ_p` is inherited from the Cauchy completion construction. -/ instance field : field (ℚ_[p]) := cau_seq.completion.field instance : inhabited ℚ_[p] := ⟨0⟩ -- short circuits instance : has_zero ℚ_[p] := by apply_instance instance : has_one ℚ_[p] := by apply_instance instance : has_add ℚ_[p] := by apply_instance instance : has_mul ℚ_[p] := by apply_instance instance : has_sub ℚ_[p] := by apply_instance instance : has_neg ℚ_[p] := by apply_instance instance : has_div ℚ_[p] := by apply_instance instance : add_comm_group ℚ_[p] := by apply_instance instance : comm_ring ℚ_[p] := by apply_instance /-- Builds the equivalence class of a Cauchy sequence of rationals. -/ def mk : padic_seq p → ℚ_[p] := quotient.mk end completion section completion variables (p : ℕ) [fact p.prime] lemma mk_eq {f g : padic_seq p} : mk f = mk g ↔ f ≈ g := quotient.eq /-- Embeds the rational numbers in the p-adic numbers. -/ def of_rat : ℚ → ℚ_[p] := cau_seq.completion.of_rat @[simp] lemma of_rat_add : ∀ (x y : ℚ), of_rat p (x + y) = of_rat p x + of_rat p y := cau_seq.completion.of_rat_add @[simp] lemma of_rat_neg : ∀ (x : ℚ), of_rat p (-x) = -of_rat p x := cau_seq.completion.of_rat_neg @[simp] lemma of_rat_mul : ∀ (x y : ℚ), of_rat p (x * y) = of_rat p x * of_rat p y := cau_seq.completion.of_rat_mul @[simp] lemma of_rat_sub : ∀ (x y : ℚ), of_rat p (x - y) = of_rat p x - of_rat p y := cau_seq.completion.of_rat_sub @[simp] lemma of_rat_div : ∀ (x y : ℚ), of_rat p (x / y) = of_rat p x / of_rat p y := cau_seq.completion.of_rat_div @[simp] lemma of_rat_one : of_rat p 1 = 1 := rfl @[simp] lemma of_rat_zero : of_rat p 0 = 0 := rfl lemma cast_eq_of_rat_of_nat (n : ℕ) : (↑n : ℚ_[p]) = of_rat p n := begin induction n with n ih, { refl }, { simpa using ih } end lemma cast_eq_of_rat_of_int (n : ℤ) : ↑n = of_rat p n := by induction n; simp [cast_eq_of_rat_of_nat] lemma cast_eq_of_rat : ∀ (q : ℚ), (↑q : ℚ_[p]) = of_rat p q | ⟨n, d, h1, h2⟩ := show ↑n / ↑d = _, from have (⟨n, d, h1, h2⟩ : ℚ) = rat.mk n d, from rat.num_denom', by simp [this, rat.mk_eq_div, of_rat_div, cast_eq_of_rat_of_int, cast_eq_of_rat_of_nat] @[norm_cast] lemma coe_add : ∀ {x y : ℚ}, (↑(x + y) : ℚ_[p]) = ↑x + ↑y := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_neg : ∀ {x : ℚ}, (↑(-x) : ℚ_[p]) = -↑x := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_mul : ∀ {x y : ℚ}, (↑(x * y) : ℚ_[p]) = ↑x * ↑y := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_sub : ∀ {x y : ℚ}, (↑(x - y) : ℚ_[p]) = ↑x - ↑y := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_div : ∀ {x y : ℚ}, (↑(x / y) : ℚ_[p]) = ↑x / ↑y := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_one : (↑1 : ℚ_[p]) = 1 := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_zero : (↑0 : ℚ_[p]) = 0 := rfl lemma const_equiv {q r : ℚ} : const (padic_norm p) q ≈ const (padic_norm p) r ↔ q = r := ⟨ λ heq : lim_zero (const (padic_norm p) (q - r)), eq_of_sub_eq_zero $ const_lim_zero.1 heq, λ heq, by rw heq; apply setoid.refl _ ⟩ lemma of_rat_eq {q r : ℚ} : of_rat p q = of_rat p r ↔ q = r := ⟨(const_equiv p).1 ∘ quotient.eq.1, λ h, by rw h⟩ @[norm_cast] lemma coe_inj {q r : ℚ} : (↑q : ℚ_[p]) = ↑r ↔ q = r := by simp [cast_eq_of_rat, of_rat_eq] instance : char_zero ℚ_[p] := ⟨λ m n, by { rw ← rat.cast_coe_nat, norm_cast, exact id }⟩ end completion end padic /-- The rational-valued p-adic norm on `ℚ_p` is lifted from the norm on Cauchy sequences. The canonical form of this function is the normed space instance, with notation `∥ ∥`. -/ def padic_norm_e {p : ℕ} [hp : fact p.prime] : ℚ_[p] → ℚ := quotient.lift padic_seq.norm $ @padic_seq.norm_equiv _ _ namespace padic_norm_e section embedding open padic_seq variables {p : ℕ} [fact p.prime] lemma defn (f : padic_seq p) {ε : ℚ} (hε : 0 < ε) : ∃ N, ∀ i ≥ N, padic_norm_e (⟦f⟧ - f i) < ε := begin simp only [padic.cast_eq_of_rat], change ∃ N, ∀ i ≥ N, (f - const _ (f i)).norm < ε, by_contradiction h, cases cauchy₂ f hε with N hN, have : ∀ N, ∃ i ≥ N, ε ≤ (f - const _ (f i)).norm, by simpa only [not_forall, not_exists, not_lt] using h, rcases this N with ⟨i, hi, hge⟩, have hne : ¬ (f - const (padic_norm p) (f i)) ≈ 0, { intro h, unfold padic_seq.norm at hge; split_ifs at hge, exact not_lt_of_ge hge hε }, unfold padic_seq.norm at hge; split_ifs at hge, apply not_le_of_gt _ hge, cases decidable.em (N ≤ stationary_point hne) with hgen hngen, { apply hN; assumption }, { have := stationary_point_spec hne (le_refl _) (le_of_not_le hngen), rw ←this, apply hN, apply le_refl, assumption } end protected lemma nonneg (q : ℚ_[p]) : 0 ≤ padic_norm_e q := quotient.induction_on q $ norm_nonneg lemma zero_def : (0 : ℚ_[p]) = ⟦0⟧ := rfl lemma zero_iff (q : ℚ_[p]) : padic_norm_e q = 0 ↔ q = 0 := quotient.induction_on q $ by simpa only [zero_def, quotient.eq] using norm_zero_iff @[simp] protected lemma zero : padic_norm_e (0 : ℚ_[p]) = 0 := (zero_iff _).2 rfl /-- Theorems about `padic_norm_e` are named with a `'` so the names do not conflict with the equivalent theorems about `norm` (`∥ ∥`). -/ @[simp] protected lemma one' : padic_norm_e (1 : ℚ_[p]) = 1 := norm_one @[simp] protected lemma neg (q : ℚ_[p]) : padic_norm_e (-q) = padic_norm_e q := quotient.induction_on q $ norm_neg /-- Theorems about `padic_norm_e` are named with a `'` so the names do not conflict with the equivalent theorems about `norm` (`∥ ∥`). -/ theorem nonarchimedean' (q r : ℚ_[p]) : padic_norm_e (q + r) ≤ max (padic_norm_e q) (padic_norm_e r) := quotient.induction_on₂ q r $ norm_nonarchimedean /-- Theorems about `padic_norm_e` are named with a `'` so the names do not conflict with the equivalent theorems about `norm` (`∥ ∥`). -/ theorem add_eq_max_of_ne' {q r : ℚ_[p]} : padic_norm_e q ≠ padic_norm_e r → padic_norm_e (q + r) = max (padic_norm_e q) (padic_norm_e r) := quotient.induction_on₂ q r $ λ _ _, padic_seq.add_eq_max_of_ne lemma triangle_ineq (x y z : ℚ_[p]) : padic_norm_e (x - z) ≤ padic_norm_e (x - y) + padic_norm_e (y - z) := calc padic_norm_e (x - z) = padic_norm_e ((x - y) + (y - z)) : by rw sub_add_sub_cancel ... ≤ max (padic_norm_e (x - y)) (padic_norm_e (y - z)) : padic_norm_e.nonarchimedean' _ _ ... ≤ padic_norm_e (x - y) + padic_norm_e (y - z) : max_le_add_of_nonneg (padic_norm_e.nonneg _) (padic_norm_e.nonneg _) protected lemma add (q r : ℚ_[p]) : padic_norm_e (q + r) ≤ (padic_norm_e q) + (padic_norm_e r) := calc padic_norm_e (q + r) ≤ max (padic_norm_e q) (padic_norm_e r) : nonarchimedean' _ _ ... ≤ (padic_norm_e q) + (padic_norm_e r) : max_le_add_of_nonneg (padic_norm_e.nonneg _) (padic_norm_e.nonneg _) protected lemma mul' (q r : ℚ_[p]) : padic_norm_e (q * r) = (padic_norm_e q) * (padic_norm_e r) := quotient.induction_on₂ q r $ norm_mul instance : is_absolute_value (@padic_norm_e p _) := { abv_nonneg := padic_norm_e.nonneg, abv_eq_zero := zero_iff, abv_add := padic_norm_e.add, abv_mul := padic_norm_e.mul' } @[simp] lemma eq_padic_norm' (q : ℚ) : padic_norm_e (padic.of_rat p q) = padic_norm p q := norm_const _ protected theorem image' {q : ℚ_[p]} : q ≠ 0 → ∃ n : ℤ, padic_norm_e q = p ^ (-n) := quotient.induction_on q $ λ f hf, have ¬ f ≈ 0, from (ne_zero_iff_nequiv_zero f).1 hf, norm_values_discrete f this lemma sub_rev (q r : ℚ_[p]) : padic_norm_e (q - r) = padic_norm_e (r - q) := by rw ←(padic_norm_e.neg); simp end embedding end padic_norm_e namespace padic section complete open padic_seq padic theorem rat_dense' {p : ℕ} [fact p.prime] (q : ℚ_[p]) {ε : ℚ} (hε : 0 < ε) : ∃ r : ℚ, padic_norm_e (q - r) < ε := quotient.induction_on q $ λ q', have ∃ N, ∀ m n ≥ N, padic_norm p (q' m - q' n) < ε, from cauchy₂ _ hε, let ⟨N, hN⟩ := this in ⟨q' N, begin simp only [padic.cast_eq_of_rat], change padic_seq.norm (q' - const _ (q' N)) < ε, cases decidable.em ((q' - const (padic_norm p) (q' N)) ≈ 0) with heq hne', { simpa only [heq, padic_seq.norm, dif_pos] }, { simp only [padic_seq.norm, dif_neg hne'], change padic_norm p (q' _ - q' _) < ε, have := stationary_point_spec hne', cases decidable.em (stationary_point hne' ≤ N) with hle hle, { have := eq.symm (this (le_refl _) hle), simp only [const_apply, sub_apply, padic_norm.zero, sub_self] at this, simpa only [this] }, { apply hN, apply le_of_lt, apply lt_of_not_ge, apply hle, apply le_refl }} end⟩ variables {p : ℕ} [fact p.prime] (f : cau_seq _ (@padic_norm_e p _)) open classical private lemma div_nat_pos (n : ℕ) : 0 < (1 / ((n + 1): ℚ)) := div_pos zero_lt_one (by exact_mod_cast succ_pos _) /-- `lim_seq f`, for `f` a Cauchy sequence of `p`-adic numbers, is a sequence of rationals with the same limit point as `f`. -/ def lim_seq : ℕ → ℚ := λ n, classical.some (rat_dense' (f n) (div_nat_pos n)) lemma exi_rat_seq_conv {ε : ℚ} (hε : 0 < ε) : ∃ N, ∀ i ≥ N, padic_norm_e (f i - ((lim_seq f) i : ℚ_[p])) < ε := begin refine (exists_nat_gt (1/ε)).imp (λ N hN i hi, _), have h := classical.some_spec (rat_dense' (f i) (div_nat_pos i)), refine lt_of_lt_of_le h ((div_le_iff' $ by exact_mod_cast succ_pos _).mpr _), rw right_distrib, apply le_add_of_le_of_nonneg, { exact (div_le_iff hε).mp (le_trans (le_of_lt hN) (by exact_mod_cast hi)) }, { apply le_of_lt, simpa } end lemma exi_rat_seq_conv_cauchy : is_cau_seq (padic_norm p) (lim_seq f) := assume ε hε, have hε3 : 0 < ε / 3, from div_pos hε (by norm_num), let ⟨N, hN⟩ := exi_rat_seq_conv f hε3, ⟨N2, hN2⟩ := f.cauchy₂ hε3 in begin existsi max N N2, intros j hj, suffices : padic_norm_e ((↑(lim_seq f j) - f (max N N2)) + (f (max N N2) - lim_seq f (max N N2))) < ε, { ring_nf at this ⊢, rw [← padic_norm_e.eq_padic_norm', ← padic.cast_eq_of_rat], exact_mod_cast this }, { apply lt_of_le_of_lt, { apply padic_norm_e.add }, { have : (3 : ℚ) ≠ 0, by norm_num, have : ε = ε / 3 + ε / 3 + ε / 3, { field_simp [this], simp only [bit0, bit1, mul_add, mul_one] }, rw this, apply add_lt_add, { suffices : padic_norm_e ((↑(lim_seq f j) - f j) + (f j - f (max N N2))) < ε / 3 + ε / 3, by simpa only [sub_add_sub_cancel], apply lt_of_le_of_lt, { apply padic_norm_e.add }, { apply add_lt_add, { rw [padic_norm_e.sub_rev], apply_mod_cast hN, exact le_of_max_le_left hj }, { apply hN2, exact le_of_max_le_right hj, apply le_max_right }}}, { apply_mod_cast hN, apply le_max_left }}} end private def lim' : padic_seq p := ⟨_, exi_rat_seq_conv_cauchy f⟩ private def lim : ℚ_[p] := ⟦lim' f⟧ theorem complete' : ∃ q : ℚ_[p], ∀ ε > 0, ∃ N, ∀ i ≥ N, padic_norm_e (q - f i) < ε := ⟨ lim f, λ ε hε, let ⟨N, hN⟩ := exi_rat_seq_conv f (show 0 < ε / 2, from div_pos hε (by norm_num)), ⟨N2, hN2⟩ := padic_norm_e.defn (lim' f) (show 0 < ε / 2, from div_pos hε (by norm_num)) in begin existsi max N N2, intros i hi, suffices : padic_norm_e ((lim f - lim' f i) + (lim' f i - f i)) < ε, { ring_nf at this; exact this }, { apply lt_of_le_of_lt, { apply padic_norm_e.add }, { have : ε = ε / 2 + ε / 2, by rw ←(add_self_div_two ε); simp, rw this, apply add_lt_add, { apply hN2, exact le_of_max_le_right hi }, { rw_mod_cast [padic_norm_e.sub_rev], apply hN, exact le_of_max_le_left hi }}} end ⟩ end complete section normed_space variables (p : ℕ) [fact p.prime] instance : has_dist ℚ_[p] := ⟨λ x y, padic_norm_e (x - y)⟩ instance : metric_space ℚ_[p] := { dist_self := by simp [dist], dist_comm := λ x y, by unfold dist; rw ←padic_norm_e.neg (x - y); simp, dist_triangle := begin intros, unfold dist, exact_mod_cast padic_norm_e.triangle_ineq _ _ _, end, eq_of_dist_eq_zero := begin unfold dist, intros _ _ h, apply eq_of_sub_eq_zero, apply (padic_norm_e.zero_iff _).1, exact_mod_cast h end } instance : has_norm ℚ_[p] := ⟨λ x, padic_norm_e x⟩ instance : normed_field ℚ_[p] := { dist_eq := λ _ _, rfl, norm_mul' := by simp [has_norm.norm, padic_norm_e.mul'] } instance is_absolute_value : is_absolute_value (λ a : ℚ_[p], ∥a∥) := { abv_nonneg := norm_nonneg, abv_eq_zero := λ _, norm_eq_zero, abv_add := norm_add_le, abv_mul := by simp [has_norm.norm, padic_norm_e.mul'] } theorem rat_dense {p : ℕ} {hp : fact p.prime} (q : ℚ_[p]) {ε : ℝ} (hε : 0 < ε) : ∃ r : ℚ, ∥q - r∥ < ε := let ⟨ε', hε'l, hε'r⟩ := exists_rat_btwn hε, ⟨r, hr⟩ := rat_dense' q (by simpa using hε'l) in ⟨r, lt_trans (by simpa [has_norm.norm] using hr) hε'r⟩ end normed_space end padic namespace padic_norm_e section normed_space variables {p : ℕ} [hp : fact p.prime] include hp @[simp] protected lemma mul (q r : ℚ_[p]) : ∥q * r∥ = ∥q∥ * ∥r∥ := by simp [has_norm.norm, padic_norm_e.mul'] protected lemma is_norm (q : ℚ_[p]) : ↑(padic_norm_e q) = ∥q∥ := rfl theorem nonarchimedean (q r : ℚ_[p]) : ∥q + r∥ ≤ max (∥q∥) (∥r∥) := begin unfold has_norm.norm, exact_mod_cast nonarchimedean' _ _ end theorem add_eq_max_of_ne {q r : ℚ_[p]} (h : ∥q∥ ≠ ∥r∥) : ∥q+r∥ = max (∥q∥) (∥r∥) := begin unfold has_norm.norm, apply_mod_cast add_eq_max_of_ne', intro h', apply h, unfold has_norm.norm, exact_mod_cast h' end @[simp] lemma eq_padic_norm (q : ℚ) : ∥(↑q : ℚ_[p])∥ = padic_norm p q := begin unfold has_norm.norm, rw [← padic_norm_e.eq_padic_norm', ← padic.cast_eq_of_rat] end @[simp] lemma norm_p : ∥(p : ℚ_[p])∥ = p⁻¹ := begin have p₀ : p ≠ 0 := hp.1.ne_zero, have p₁ : p ≠ 1 := hp.1.ne_one, simp [p₀, p₁, norm, padic_norm, padic_val_rat, fpow_neg, padic.cast_eq_of_rat_of_nat], end lemma norm_p_lt_one : ∥(p : ℚ_[p])∥ < 1 := begin rw norm_p, apply inv_lt_one, exact_mod_cast hp.1.one_lt end @[simp] lemma norm_p_pow (n : ℤ) : ∥(p^n : ℚ_[p])∥ = p^-n := by rw [normed_field.norm_fpow, norm_p]; field_simp instance : nondiscrete_normed_field ℚ_[p] := { non_trivial := ⟨p⁻¹, begin rw [normed_field.norm_inv, norm_p, inv_inv₀], exact_mod_cast hp.1.one_lt end⟩ } protected theorem image {q : ℚ_[p]} : q ≠ 0 → ∃ n : ℤ, ∥q∥ = ↑((↑p : ℚ) ^ (-n)) := quotient.induction_on q $ λ f hf, have ¬ f ≈ 0, from (padic_seq.ne_zero_iff_nequiv_zero f).1 hf, let ⟨n, hn⟩ := padic_seq.norm_values_discrete f this in ⟨n, congr_arg coe hn⟩ protected lemma is_rat (q : ℚ_[p]) : ∃ q' : ℚ, ∥q∥ = ↑q' := if h : q = 0 then ⟨0, by simp [h]⟩ else let ⟨n, hn⟩ := padic_norm_e.image h in ⟨_, hn⟩ /--`rat_norm q`, for a `p`-adic number `q` is the `p`-adic norm of `q`, as rational number. The lemma `padic_norm_e.eq_rat_norm` asserts `∥q∥ = rat_norm q`. -/ def rat_norm (q : ℚ_[p]) : ℚ := classical.some (padic_norm_e.is_rat q) lemma eq_rat_norm (q : ℚ_[p]) : ∥q∥ = rat_norm q := classical.some_spec (padic_norm_e.is_rat q) theorem norm_rat_le_one : ∀ {q : ℚ} (hq : ¬ p ∣ q.denom), ∥(q : ℚ_[p])∥ ≤ 1 | ⟨n, d, hn, hd⟩ := λ hq : ¬ p ∣ d, if hnz : n = 0 then have (⟨n, d, hn, hd⟩ : ℚ) = 0, from rat.zero_iff_num_zero.mpr hnz, by norm_num [this] else begin have hnz' : { rat . num := n, denom := d, pos := hn, cop := hd } ≠ 0, from mt rat.zero_iff_num_zero.1 hnz, rw [padic_norm_e.eq_padic_norm], norm_cast, rw [padic_norm.eq_fpow_of_nonzero p hnz', padic_val_rat_def p hnz'], have h : (multiplicity p d).get _ = 0, by simp [multiplicity_eq_zero_of_not_dvd, hq], simp only, norm_cast, rw_mod_cast [h, sub_zero], apply fpow_le_one_of_nonpos, { exact_mod_cast le_of_lt hp.1.one_lt, }, { apply neg_nonpos_of_nonneg, norm_cast, simp, } end theorem norm_int_le_one (z : ℤ) : ∥(z : ℚ_[p])∥ ≤ 1 := suffices ∥((z : ℚ) : ℚ_[p])∥ ≤ 1, by simpa, norm_rat_le_one $ by simp [hp.1.ne_one] lemma norm_int_lt_one_iff_dvd (k : ℤ) : ∥(k : ℚ_[p])∥ < 1 ↔ ↑p ∣ k := begin split, { intro h, contrapose! h, apply le_of_eq, rw eq_comm, calc ∥(k : ℚ_[p])∥ = ∥((k : ℚ) : ℚ_[p])∥ : by { norm_cast } ... = padic_norm p k : padic_norm_e.eq_padic_norm _ ... = 1 : _, rw padic_norm, split_ifs with H, { exfalso, apply h, norm_cast at H, rw H, apply dvd_zero }, { norm_cast at H ⊢, convert gpow_zero _, simp only [neg_eq_zero], rw padic_val_rat.padic_val_rat_of_int _ hp.1.ne_one H, norm_cast, rw [← enat.coe_inj, enat.coe_get, nat.cast_zero], apply multiplicity.multiplicity_eq_zero_of_not_dvd h } }, { rintro ⟨x, rfl⟩, push_cast, rw padic_norm_e.mul, calc _ ≤ ∥(p : ℚ_[p])∥ * 1 : mul_le_mul (le_refl _) (by simpa using norm_int_le_one _) (norm_nonneg _) (norm_nonneg _) ... < 1 : _, { rw [mul_one, padic_norm_e.norm_p], apply inv_lt_one, exact_mod_cast hp.1.one_lt }, }, end lemma norm_int_le_pow_iff_dvd (k : ℤ) (n : ℕ) : ∥(k : ℚ_[p])∥ ≤ ((↑p)^(-n : ℤ)) ↔ ↑(p^n) ∣ k := begin have : (p : ℝ) ^ (-n : ℤ) = ↑((p ^ (-n : ℤ) : ℚ)), {simp}, rw [show (k : ℚ_[p]) = ((k : ℚ) : ℚ_[p]), by norm_cast, eq_padic_norm, this], norm_cast, rw padic_norm.dvd_iff_norm_le, end lemma eq_of_norm_add_lt_right {p : ℕ} {hp : fact p.prime} {z1 z2 : ℚ_[p]} (h : ∥z1 + z2∥ < ∥z2∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw padic_norm_e.add_eq_max_of_ne hne; apply le_max_right) h lemma eq_of_norm_add_lt_left {p : ℕ} {hp : fact p.prime} {z1 z2 : ℚ_[p]} (h : ∥z1 + z2∥ < ∥z1∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw padic_norm_e.add_eq_max_of_ne hne; apply le_max_left) h end normed_space end padic_norm_e namespace padic variables {p : ℕ} [hp_prime : fact p.prime] include hp_prime set_option eqn_compiler.zeta true instance complete : cau_seq.is_complete ℚ_[p] norm := begin split, intro f, have cau_seq_norm_e : is_cau_seq padic_norm_e f, { intros ε hε, let h := is_cau f ε (by exact_mod_cast hε), unfold norm at h, apply_mod_cast h }, cases padic.complete' ⟨f, cau_seq_norm_e⟩ with q hq, existsi q, intros ε hε, cases exists_rat_btwn hε with ε' hε', norm_cast at hε', cases hq ε' hε'.1 with N hN, existsi N, intros i hi, let h := hN i hi, unfold norm, rw_mod_cast [cau_seq.sub_apply, padic_norm_e.sub_rev], refine lt_trans _ hε'.2, exact_mod_cast hN i hi end lemma padic_norm_e_lim_le {f : cau_seq ℚ_[p] norm} {a : ℝ} (ha : 0 < a) (hf : ∀ i, ∥f i∥ ≤ a) : ∥f.lim∥ ≤ a := let ⟨N, hN⟩ := setoid.symm (cau_seq.equiv_lim f) _ ha in calc ∥f.lim∥ = ∥f.lim - f N + f N∥ : by simp ... ≤ max (∥f.lim - f N∥) (∥f N∥) : padic_norm_e.nonarchimedean _ _ ... ≤ a : max_le (le_of_lt (hN _ (le_refl _))) (hf _) /-! ### Valuation on `ℚ_[p]` -/ /-- `padic.valuation` lifts the p-adic valuation on rationals to `ℚ_[p]`. -/ def valuation : ℚ_[p] → ℤ := quotient.lift (@padic_seq.valuation p _) (λ f g h, begin by_cases hf : f ≈ 0, { have hg : g ≈ 0, from setoid.trans (setoid.symm h) hf, simp [hf, hg, padic_seq.valuation] }, { have hg : ¬ g ≈ 0, from (λ hg, hf (setoid.trans h hg)), rw padic_seq.val_eq_iff_norm_eq hf hg, exact padic_seq.norm_equiv h }, end) @[simp] lemma valuation_zero : valuation (0 : ℚ_[p]) = 0 := dif_pos ((const_equiv p).2 rfl) @[simp] lemma valuation_one : valuation (1 : ℚ_[p]) = 0 := begin change dite (cau_seq.const (padic_norm p) 1 ≈ _) _ _ = _, have h : ¬ cau_seq.const (padic_norm p) 1 ≈ 0, { assume H, erw const_equiv p at H, exact one_ne_zero H }, rw dif_neg h, simp, end lemma norm_eq_pow_val {x : ℚ_[p]} : x ≠ 0 → ∥x∥ = p^(-x.valuation) := begin apply quotient.induction_on' x, clear x, intros f hf, change (padic_seq.norm _ : ℝ) = (p : ℝ) ^ -padic_seq.valuation _, rw padic_seq.norm_eq_pow_val, change ↑((p : ℚ) ^ -padic_seq.valuation f) = (p : ℝ) ^ -padic_seq.valuation f, { rw rat.cast_fpow, congr' 1, norm_cast }, { apply cau_seq.not_lim_zero_of_not_congr_zero, contrapose! hf, apply quotient.sound, simpa using hf, } end @[simp] lemma valuation_p : valuation (p : ℚ_[p]) = 1 := begin have h : (1 : ℝ) < p := by exact_mod_cast (fact.out p.prime).one_lt, rw ← neg_inj, apply (fpow_strict_mono h).injective, dsimp only, rw ← norm_eq_pow_val, { simp }, { exact_mod_cast (fact.out p.prime).ne_zero } end section norm_le_iff /-! ### Various characterizations of open unit balls -/ lemma norm_le_pow_iff_norm_lt_pow_add_one (x : ℚ_[p]) (n : ℤ) : ∥x∥ ≤ p ^ n ↔ ∥x∥ < p ^ (n + 1) := begin have aux : ∀ n : ℤ, 0 < (p ^ n : ℝ), { apply nat.fpow_pos_of_pos, exact hp_prime.1.pos }, by_cases hx0 : x = 0, { simp [hx0, norm_zero, aux, le_of_lt (aux _)], }, rw norm_eq_pow_val hx0, have h1p : 1 < (p : ℝ), { exact_mod_cast hp_prime.1.one_lt }, have H := fpow_strict_mono h1p, rw [H.le_iff_le, H.lt_iff_lt, int.lt_add_one_iff], end lemma norm_lt_pow_iff_norm_le_pow_sub_one (x : ℚ_[p]) (n : ℤ) : ∥x∥ < p ^ n ↔ ∥x∥ ≤ p ^ (n - 1) := by rw [norm_le_pow_iff_norm_lt_pow_add_one, sub_add_cancel] end norm_le_iff end padic
eff924c6bc84e651de68f4b6ab976203f48befed
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/order/interval.lean
aa63d9e1d7b84f46d4567a95b2477e171bde4fdd
[ "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
15,169
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import algebra.big_operators.order import algebra.group.prod import data.option.n_ary import data.set.pointwise.basic import order.interval import tactic.positivity /-! # Interval arithmetic This file defines arithmetic operations on intervals and prove their correctness. Note that this is full precision operations. The essentials of float operations can be found in `data.fp.basic`. We hsve not yet integrated these with the rest of the library. -/ open function set open_locale big_operators pointwise universe u variables {ι α : Type*} /-! ### One/zero -/ section one section preorder variables [preorder α] [has_one α] @[to_additive] instance : has_one (nonempty_interval α) := ⟨nonempty_interval.pure 1⟩ @[to_additive] instance : has_one (interval α) := ⟨interval.pure 1⟩ namespace nonempty_interval @[simp, to_additive to_prod_zero] lemma to_prod_one : (1 : nonempty_interval α).to_prod = 1 := rfl @[to_additive] lemma fst_one : (1 : nonempty_interval α).fst = 1 := rfl @[to_additive] lemma snd_one : (1 : nonempty_interval α).snd = 1 := rfl @[simp, norm_cast, to_additive] lemma coe_one_interval : ((1 : nonempty_interval α) : interval α) = 1 := rfl @[simp, to_additive] lemma pure_one : pure (1 : α) = 1 := rfl end nonempty_interval namespace interval @[simp, to_additive] lemma pure_one : pure (1 : α) = 1 := rfl @[simp, to_additive] lemma one_ne_bot : (1 : interval α) ≠ ⊥ := pure_ne_bot @[simp, to_additive] lemma bot_ne_one : (⊥ : interval α) ≠ 1 := bot_ne_pure end interval end preorder section partial_order variables [partial_order α] [has_one α] namespace nonempty_interval @[simp, to_additive] lemma coe_one : ((1 : nonempty_interval α) : set α) = 1 := coe_pure _ @[to_additive] lemma one_mem_one : (1 : α) ∈ (1 : nonempty_interval α) := ⟨le_rfl, le_rfl⟩ end nonempty_interval namespace interval @[simp, to_additive] lemma coe_one : ((1 : interval α) : set α) = 1 := Icc_self _ @[to_additive] lemma one_mem_one : (1 : α) ∈ (1 : interval α) := ⟨le_rfl, le_rfl⟩ end interval end partial_order end one /-! ### Addition/multiplication Note that this multiplication does not apply to `ℚ` or `ℝ`. -/ section mul variables [preorder α] [has_mul α] [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (≤)] @[to_additive] instance : has_mul (nonempty_interval α) := ⟨λ s t, ⟨s.to_prod * t.to_prod, mul_le_mul' s.fst_le_snd t.fst_le_snd⟩⟩ @[to_additive] instance : has_mul (interval α) := ⟨option.map₂ (*)⟩ namespace nonempty_interval variables (s t : nonempty_interval α) (a b : α) @[simp, to_additive to_prod_add] lemma to_prod_mul : (s * t).to_prod = s.to_prod * t.to_prod := rfl @[to_additive] lemma fst_mul : (s * t).fst = s.fst * t.fst := rfl @[to_additive] lemma snd_mul : (s * t).snd = s.snd * t.snd := rfl @[simp, to_additive] lemma coe_mul_interval : (↑(s * t) : interval α) = s * t := rfl @[simp, to_additive] lemma pure_mul_pure : pure a * pure b = pure (a * b) := rfl end nonempty_interval namespace interval variables (s t : interval α) @[simp, to_additive] lemma bot_mul : ⊥ * t = ⊥ := rfl @[simp, to_additive] lemma mul_bot : s * ⊥ = ⊥ := option.map₂_none_right _ _ end interval end mul /-! ### Powers -/ -- TODO: if `to_additive` gets improved sufficiently, derive this from `has_pow` instance nonempty_interval.has_nsmul [add_monoid α] [preorder α] [covariant_class α α (+) (≤)] [covariant_class α α (swap (+)) (≤)] : has_smul ℕ (nonempty_interval α) := ⟨λ n s, ⟨(n • s.fst, n • s.snd), nsmul_le_nsmul_of_le_right s.fst_le_snd _⟩⟩ section pow variables [monoid α] [preorder α] [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (≤)] @[to_additive nonempty_interval.has_nsmul] instance nonempty_interval.has_pow : has_pow (nonempty_interval α) ℕ := ⟨λ s n, ⟨s.to_prod ^ n, pow_le_pow_of_le_left' s.fst_le_snd _⟩⟩ namespace nonempty_interval variables (s : nonempty_interval α) (a : α) (n : ℕ) @[simp, to_additive to_prod_nsmul] lemma to_prod_pow : (s ^ n).to_prod = s.to_prod ^ n := rfl @[to_additive] lemma fst_pow : (s ^ n).fst = s.fst ^ n := rfl @[to_additive] lemma snd_pow : (s ^ n).snd = s.snd ^ n := rfl @[simp, to_additive] lemma pure_pow : pure a ^ n = pure (a ^ n) := rfl end nonempty_interval end pow namespace nonempty_interval @[to_additive] instance [ordered_comm_monoid α] : comm_monoid (nonempty_interval α) := nonempty_interval.to_prod_injective.comm_monoid _ to_prod_one to_prod_mul to_prod_pow end nonempty_interval @[to_additive] instance [ordered_comm_monoid α] : mul_one_class (interval α) := { mul := (*), one := 1, one_mul := λ s, (option.map₂_coe_left _ _ _).trans $ by simp only [nonempty_interval.pure_one, one_mul, ←id_def, option.map_id, id], mul_one := λ s, (option.map₂_coe_right _ _ _).trans $ by simp only [nonempty_interval.pure_one, mul_one, ←id_def, option.map_id, id] } @[to_additive] instance [ordered_comm_monoid α] : comm_monoid (interval α) := { mul_comm := λ _ _, option.map₂_comm mul_comm, mul_assoc := λ _ _ _, option.map₂_assoc mul_assoc, ..interval.mul_one_class } namespace nonempty_interval @[simp, to_additive] lemma coe_pow_interval [ordered_comm_monoid α] (s : nonempty_interval α) (n : ℕ) : (↑(s ^ n) : interval α) = s ^ n := map_pow (⟨coe, coe_one_interval, coe_mul_interval⟩ : nonempty_interval α →* interval α) _ _ end nonempty_interval namespace interval variables [ordered_comm_monoid α] (s : interval α) {n : ℕ} @[to_additive] lemma bot_pow : ∀ {n : ℕ} (hn : n ≠ 0), (⊥ : interval α) ^ n = ⊥ | 0 h := (h rfl).elim | (nat.succ n) _ := bot_mul (⊥ ^ n) end interval /-! ### Subtraction Subtraction is defined more generally than division so that it applies to `ℕ` (and `has_ordered_div` is not a thing and probably should not become one). -/ section sub variables [preorder α] [add_comm_semigroup α] [has_sub α] [has_ordered_sub α] [covariant_class α α (+) (≤)] instance : has_sub (nonempty_interval α) := ⟨λ s t, ⟨(s.fst - t.snd, s.snd - t.fst), tsub_le_tsub s.fst_le_snd t.fst_le_snd⟩⟩ instance : has_sub (interval α) := ⟨option.map₂ has_sub.sub⟩ namespace nonempty_interval variables (s t : nonempty_interval α) {a b : α} @[simp] lemma fst_sub : (s - t).fst = s.fst - t.snd := rfl @[simp] lemma snd_sub : (s - t).snd = s.snd - t.fst := rfl @[simp] lemma coe_sub_interval : (↑(s - t) : interval α) = s - t := rfl lemma sub_mem_sub (ha : a ∈ s) (hb : b ∈ t) : a - b ∈ s - t := ⟨tsub_le_tsub ha.1 hb.2, tsub_le_tsub ha.2 hb.1⟩ @[simp] lemma pure_sub_pure (a b : α) : pure a - pure b = pure (a - b) := rfl end nonempty_interval namespace interval variables (s t : interval α) @[simp] lemma bot_sub : ⊥ - t = ⊥ := rfl @[simp] lemma sub_bot : s - ⊥ = ⊥ := option.map₂_none_right _ _ end interval end sub /-! ### Division in ordered groups Note that this division does not apply to `ℚ` or `ℝ`. -/ section div variables [preorder α] [comm_group α] [covariant_class α α (*) (≤)] @[to_additive] instance : has_div (nonempty_interval α) := ⟨λ s t, ⟨(s.fst / t.snd, s.snd / t.fst), div_le_div'' s.fst_le_snd t.fst_le_snd⟩⟩ @[to_additive] instance : has_div (interval α) := ⟨option.map₂ (/)⟩ namespace nonempty_interval variables (s t : nonempty_interval α) (a b : α) @[simp, to_additive] lemma fst_div : (s / t).fst = s.fst / t.snd := rfl @[simp, to_additive] lemma snd_div : (s / t).snd = s.snd / t.fst := rfl @[simp, to_additive] lemma coe_div_interval : (↑(s / t) : interval α) = s / t := rfl @[to_additive] lemma div_mem_div (ha : a ∈ s) (hb : b ∈ t) : a / b ∈ s / t := ⟨div_le_div'' ha.1 hb.2, div_le_div'' ha.2 hb.1⟩ @[simp, to_additive] lemma pure_div_pure : pure a / pure b = pure (a / b) := rfl end nonempty_interval namespace interval variables (s t : interval α) @[simp, to_additive] lemma bot_div : ⊥ / t = ⊥ := rfl @[simp, to_additive] lemma div_bot : s / ⊥ = ⊥ := option.map₂_none_right _ _ end interval end div /-! ### Negation/inversion -/ section inv variables [ordered_comm_group α] @[to_additive] instance : has_inv (nonempty_interval α) := ⟨λ s, ⟨(s.snd⁻¹, s.fst⁻¹), inv_le_inv' s.fst_le_snd⟩⟩ @[to_additive] instance : has_inv (interval α) := ⟨option.map has_inv.inv⟩ namespace nonempty_interval variables (s t : nonempty_interval α) (a : α) @[simp, to_additive] lemma fst_inv : s⁻¹.fst = s.snd⁻¹ := rfl @[simp, to_additive] lemma snd_inv : s⁻¹.snd = s.fst⁻¹ := rfl @[simp, to_additive] lemma coe_inv_interval : (↑(s⁻¹) : interval α) = s⁻¹ := rfl @[to_additive] lemma inv_mem_inv (ha : a ∈ s) : a⁻¹ ∈ s⁻¹ := ⟨inv_le_inv' ha.2, inv_le_inv' ha.1⟩ @[simp, to_additive] lemma inv_pure : (pure a)⁻¹ = pure a⁻¹ := rfl end nonempty_interval @[simp, to_additive] lemma interval.inv_bot : (⊥ : interval α)⁻¹ = ⊥ := rfl end inv namespace nonempty_interval variables [ordered_comm_group α] {s t : nonempty_interval α} @[to_additive] protected lemma mul_eq_one_iff : s * t = 1 ↔ ∃ a b, s = pure a ∧ t = pure b ∧ a * b = 1 := begin refine ⟨λ h, _, _⟩, { rw [ext_iff, prod.ext_iff] at h, have := (mul_le_mul_iff_of_ge s.fst_le_snd t.fst_le_snd).1 (h.2.trans h.1.symm).le, refine ⟨s.fst, t.fst, _, _, h.1⟩; ext; try { refl }, exacts [this.1.symm, this.2.symm] }, { rintro ⟨b, c, rfl, rfl, h⟩, rw [pure_mul_pure, h, pure_one] } end instance {α : Type u} [ordered_add_comm_group α] : subtraction_comm_monoid (nonempty_interval α) := { neg := has_neg.neg, sub := has_sub.sub, sub_eq_add_neg := λ s t, by ext; exact sub_eq_add_neg _ _, neg_neg := λ s, by ext; exact neg_neg _, neg_add_rev := λ s t, by ext; exact neg_add_rev _ _, neg_eq_of_add := λ s t h, begin obtain ⟨a, b, rfl, rfl, hab⟩ := nonempty_interval.add_eq_zero_iff.1 h, rw [neg_pure, neg_eq_of_add_eq_zero_right hab], end, ..nonempty_interval.add_comm_monoid } @[to_additive nonempty_interval.subtraction_comm_monoid] instance : division_comm_monoid (nonempty_interval α) := { inv := has_inv.inv, div := (/), div_eq_mul_inv := λ s t, by ext; exact div_eq_mul_inv _ _, inv_inv := λ s, by ext; exact inv_inv _, mul_inv_rev := λ s t, by ext; exact mul_inv_rev _ _, inv_eq_of_mul := λ s t h, begin obtain ⟨a, b, rfl, rfl, hab⟩ := nonempty_interval.mul_eq_one_iff.1 h, rw [inv_pure, inv_eq_of_mul_eq_one_right hab], end, ..nonempty_interval.comm_monoid } end nonempty_interval namespace interval variables [ordered_comm_group α] {s t : interval α} @[to_additive] protected lemma mul_eq_one_iff : s * t = 1 ↔ ∃ a b, s = pure a ∧ t = pure b ∧ a * b = 1 := begin cases s, { simp [with_bot.none_eq_bot] }, cases t, { simp [with_bot.none_eq_bot] }, { simp [with_bot.some_eq_coe, ←nonempty_interval.coe_mul_interval, nonempty_interval.mul_eq_one_iff] } end instance {α : Type u} [ordered_add_comm_group α] : subtraction_comm_monoid (interval α) := { neg := has_neg.neg, sub := has_sub.sub, sub_eq_add_neg := by rintro (_ | s) (_ | t); refl <|> exact congr_arg some (sub_eq_add_neg _ _), neg_neg := by rintro (_ | s); refl <|> exact congr_arg some (neg_neg _), neg_add_rev := by rintro (_ | s) (_ | t); refl <|> exact congr_arg some (neg_add_rev _ _), neg_eq_of_add := by rintro (_ | s) (_ | t) h; cases h <|> exact congr_arg some (neg_eq_of_add_eq_zero_right $ option.some_injective _ h), ..interval.add_comm_monoid } @[to_additive interval.subtraction_comm_monoid] instance : division_comm_monoid (interval α) := { inv := has_inv.inv, div := (/), div_eq_mul_inv := by rintro (_ | s) (_ | t); refl <|> exact congr_arg some (div_eq_mul_inv _ _), inv_inv := by rintro (_ | s); refl <|> exact congr_arg some (inv_inv _), mul_inv_rev := by rintro (_ | s) (_ | t); refl <|> exact congr_arg some (mul_inv_rev _ _), inv_eq_of_mul := by rintro (_ | s) (_ | t) h; cases h <|> exact congr_arg some (inv_eq_of_mul_eq_one_right $ option.some_injective _ h), ..interval.comm_monoid } end interval section length variables [ordered_add_comm_group α] namespace nonempty_interval variables (s t : nonempty_interval α) (a : α) /-- The length of an interval is its first component minus its second component. This measures the accuracy of the approximation by an interval. -/ def length : α := s.snd - s.fst @[simp] lemma length_nonneg : 0 ≤ s.length := sub_nonneg_of_le s.fst_le_snd @[simp] lemma length_pure : (pure a).length = 0 := sub_self _ @[simp] lemma length_zero : (0 : nonempty_interval α).length = 0 := length_pure _ @[simp] lemma length_neg : (-s).length = s.length := neg_sub_neg _ _ @[simp] lemma length_add : (s + t).length = s.length + t.length := add_sub_add_comm _ _ _ _ @[simp] lemma length_sub : (s - t).length = s.length + t.length := by simp [sub_eq_add_neg] @[simp] lemma length_sum (f : ι → nonempty_interval α) (s : finset ι) : (∑ i in s, f i).length = ∑ i in s, (f i).length := map_sum (⟨length, length_zero, length_add⟩ : nonempty_interval α →+ α) _ _ end nonempty_interval namespace interval variables (s t : interval α) (a : α) /-- The length of an interval is its first component minus its second component. This measures the accuracy of the approximation by an interval. -/ def length : interval α → α | ⊥ := 0 | (s : nonempty_interval α) := s.length @[simp] lemma length_nonneg : ∀ s : interval α, 0 ≤ s.length | ⊥ := le_rfl | (s : nonempty_interval α) := s.length_nonneg @[simp] lemma length_pure : (pure a).length = 0 := nonempty_interval.length_pure _ @[simp] lemma length_zero : (0 : interval α).length = 0 := length_pure _ @[simp] lemma length_neg : ∀ s : interval α, (-s).length = s.length | ⊥ := rfl | (s : nonempty_interval α) := s.length_neg lemma length_add_le : ∀ s t : interval α, (s + t).length ≤ s.length + t.length | ⊥ _ := by simp | _ ⊥ := by simp | (s : nonempty_interval α) (t : nonempty_interval α) := (s.length_add t).le lemma length_sub_le : (s - t).length ≤ s.length + t.length := by simpa [sub_eq_add_neg] using length_add_le s (-t) lemma length_sum_le (f : ι → interval α) (s : finset ι) : (∑ i in s, f i).length ≤ ∑ i in s, (f i).length := finset.le_sum_of_subadditive _ length_zero length_add_le _ _ end interval end length namespace tactic open positivity /-- Extension for the `positivity` tactic: The length of an interval is always nonnegative. -/ @[positivity] meta def positivity_interval_length : expr → tactic strictness | `(nonempty_interval.length %%s) := nonnegative <$> mk_app `nonempty_interval.length_nonneg [s] | `(interval.length %%s) := nonnegative <$> mk_app `interval.length_nonneg [s] | e := pp e >>= fail ∘ format.bracket "The expression `" "` isn't of the form `nonempty_interval.length s` or `interval.length s`" end tactic
253b976d331885074b68aa6a1360a867bc1fd960
fecda8e6b848337561d6467a1e30cf23176d6ad0
/src/algebra/gcd_monoid.lean
c56e146d27e7f07b7e5ec49e5a4d9c001776f1b4
[ "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
31,132
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, Jens Wagemaker TODO: Provide a GCD monoid instance for `ℕ`, port GCD facts about nats TODO: Generalize normalization monoids commutative (cancellative) monoids with or without zero TODO: Generalize GCD monoid to not require normalization in all cases -/ import algebra.associated import data.nat.basic import data.int.gcd /-! # Monoids with normalization functions, `gcd`, and `lcm` This file defines extra structures on `comm_cancel_monoid_with_zero`s, including `integral_domain`s. ## Main Definitions * `normalization_monoid` * `gcd_monoid` ## Implementation Notes * `normalization_monoid` is defined by assigning to each element a `norm_unit` such that multiplying by that unit normalizes the monoid, and `normalize` is an idempotent monoid homomorphism. This definition as currently implemented does casework on `0`. * `gcd_monoid` extends `normalization_monoid`, so the `gcd` and `lcm` are always normalized. This makes `gcd`s of polynomials easier to work with, but excludes Euclidean domains, and monoids without zero. ## TODO * Provide a GCD monoid instance for `ℕ`, port GCD facts about nats, definition of coprime * Generalize normalization monoids to commutative (cancellative) monoids with or without zero * Generalize GCD monoid to not require normalization in all cases ## Tags divisibility, gcd, lcm, normalize -/ variables {α : Type*} set_option old_structure_cmd true /-- Normalization monoid: multiplying with `norm_unit` gives a normal form for associated elements. -/ @[protect_proj] class normalization_monoid (α : Type*) [nontrivial α] [comm_cancel_monoid_with_zero α] := (norm_unit : α → units α) (norm_unit_zero : norm_unit 0 = 1) (norm_unit_mul : ∀{a b}, a ≠ 0 → b ≠ 0 → norm_unit (a * b) = norm_unit a * norm_unit b) (norm_unit_coe_units : ∀(u : units α), norm_unit u = u⁻¹) export normalization_monoid (norm_unit norm_unit_zero norm_unit_mul norm_unit_coe_units) attribute [simp] norm_unit_coe_units norm_unit_zero norm_unit_mul section normalization_monoid variables [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] @[simp] theorem norm_unit_one : norm_unit (1:α) = 1 := norm_unit_coe_units 1 /-- Chooses an element of each associate class, by multiplying by `norm_unit` -/ def normalize : α →* α := { to_fun := λ x, x * norm_unit x, map_one' := by rw [norm_unit_one, units.coe_one, mul_one], map_mul' := λ x y, classical.by_cases (λ hx : x = 0, by rw [hx, zero_mul, zero_mul, zero_mul]) $ λ hx, classical.by_cases (λ hy : y = 0, by rw [hy, mul_zero, zero_mul, mul_zero]) $ λ hy, by simp only [norm_unit_mul hx hy, units.coe_mul]; simp only [mul_assoc, mul_left_comm y], } @[simp] lemma normalize_apply {x : α} : normalize x = x * norm_unit x := rfl theorem associated_normalize {x : α} : associated x (normalize x) := ⟨_, rfl⟩ theorem normalize_associated {x : α} : associated (normalize x) x := associated_normalize.symm @[simp] lemma normalize_zero : normalize (0 : α) = 0 := by simp @[simp] lemma normalize_one : normalize (1 : α) = 1 := normalize.map_one lemma normalize_coe_units (u : units α) : normalize (u : α) = 1 := by simp lemma normalize_eq_zero {x : α} : normalize x = 0 ↔ x = 0 := ⟨λ hx, (associated_zero_iff_eq_zero x).1 $ hx ▸ associated_normalize, by rintro rfl; exact normalize_zero⟩ lemma normalize_eq_one {x : α} : normalize x = 1 ↔ is_unit x := ⟨λ hx, is_unit_iff_exists_inv.2 ⟨_, hx⟩, λ ⟨u, hu⟩, hu ▸ normalize_coe_units u⟩ @[simp] theorem norm_unit_mul_norm_unit (a : α) : norm_unit (a * norm_unit a) = 1 := classical.by_cases (assume : a = 0, by simp only [this, norm_unit_zero, zero_mul]) $ assume h, by rw [norm_unit_mul h (units.ne_zero _), norm_unit_coe_units, mul_inv_eq_one] theorem normalize_idem (x : α) : normalize (normalize x) = normalize x := by simp theorem normalize_eq_normalize {a b : α} (hab : a ∣ b) (hba : b ∣ a) : normalize a = normalize b := begin rcases associated_of_dvd_dvd hab hba with ⟨u, rfl⟩, refine classical.by_cases (by rintro rfl; simp only [zero_mul]) (assume ha : a ≠ 0, _), suffices : a * ↑(norm_unit a) = a * ↑u * ↑(norm_unit a) * ↑u⁻¹, by simpa only [normalize_apply, mul_assoc, norm_unit_mul ha u.ne_zero, norm_unit_coe_units], calc a * ↑(norm_unit a) = a * ↑(norm_unit a) * ↑u * ↑u⁻¹: (units.mul_inv_cancel_right _ _).symm ... = a * ↑u * ↑(norm_unit a) * ↑u⁻¹ : by rw mul_right_comm a end lemma normalize_eq_normalize_iff {x y : α} : normalize x = normalize y ↔ x ∣ y ∧ y ∣ x := ⟨λ h, ⟨units.dvd_mul_right.1 ⟨_, h.symm⟩, units.dvd_mul_right.1 ⟨_, h⟩⟩, λ ⟨hxy, hyx⟩, normalize_eq_normalize hxy hyx⟩ theorem dvd_antisymm_of_normalize_eq {a b : α} (ha : normalize a = a) (hb : normalize b = b) (hab : a ∣ b) (hba : b ∣ a) : a = b := ha ▸ hb ▸ normalize_eq_normalize hab hba --can be proven by simp lemma dvd_normalize_iff {a b : α} : a ∣ normalize b ↔ a ∣ b := units.dvd_mul_right --can be proven by simp lemma normalize_dvd_iff {a b : α} : normalize a ∣ b ↔ a ∣ b := units.mul_right_dvd end normalization_monoid namespace associates variables [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] local attribute [instance] associated.setoid /-- Maps an element of `associates` back to the normalized element of its associate class -/ protected def out : associates α → α := quotient.lift (normalize : α → α) $ λ a b ⟨u, hu⟩, hu ▸ normalize_eq_normalize ⟨_, rfl⟩ (units.mul_right_dvd.2 $ dvd_refl a) lemma out_mk (a : α) : (associates.mk a).out = normalize a := rfl @[simp] lemma out_one : (1 : associates α).out = 1 := normalize_one lemma out_mul (a b : associates α) : (a * b).out = a.out * b.out := quotient.induction_on₂ a b $ assume a b, by simp only [associates.quotient_mk_eq_mk, out_mk, mk_mul_mk, normalize.map_mul] lemma dvd_out_iff (a : α) (b : associates α) : a ∣ b.out ↔ associates.mk a ≤ b := quotient.induction_on b $ by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff] lemma out_dvd_iff (a : α) (b : associates α) : b.out ∣ a ↔ b ≤ associates.mk a := quotient.induction_on b $ by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff] @[simp] lemma out_top : (⊤ : associates α).out = 0 := normalize_zero @[simp] lemma normalize_out (a : associates α) : normalize a.out = a.out := quotient.induction_on a normalize_idem end associates /-- GCD monoid: a `comm_cancel_monoid_with_zero` with normalization and `gcd` (greatest common divisor) and `lcm` (least common multiple) operations. In this setting `gcd` and `lcm` form a bounded lattice on the associated elements where `gcd` is the infimum, `lcm` is the supremum, `1` is bottom, and `0` is top. The type class focuses on `gcd` and we derive the corresponding `lcm` facts from `gcd`. -/ @[protect_proj] class gcd_monoid (α : Type*) [comm_cancel_monoid_with_zero α] [nontrivial α] extends normalization_monoid α := (gcd : α → α → α) (lcm : α → α → α) (gcd_dvd_left : ∀a b, gcd a b ∣ a) (gcd_dvd_right : ∀a b, gcd a b ∣ b) (dvd_gcd : ∀{a b c}, a ∣ c → a ∣ b → a ∣ gcd c b) (normalize_gcd : ∀a b, normalize (gcd a b) = gcd a b) (gcd_mul_lcm : ∀a b, gcd a b * lcm a b = normalize (a * b)) (lcm_zero_left : ∀a, lcm 0 a = 0) (lcm_zero_right : ∀a, lcm a 0 = 0) export gcd_monoid (gcd lcm gcd_dvd_left gcd_dvd_right dvd_gcd lcm_zero_left lcm_zero_right) attribute [simp] lcm_zero_left lcm_zero_right section gcd_monoid variables [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] @[simp] theorem normalize_gcd : ∀a b:α, normalize (gcd a b) = gcd a b := gcd_monoid.normalize_gcd @[simp] theorem gcd_mul_lcm : ∀a b:α, gcd a b * lcm a b = normalize (a * b) := gcd_monoid.gcd_mul_lcm section gcd theorem dvd_gcd_iff (a b c : α) : a ∣ gcd b c ↔ (a ∣ b ∧ a ∣ c) := iff.intro (assume h, ⟨dvd_trans h (gcd_dvd_left _ _), dvd_trans h (gcd_dvd_right _ _)⟩) (assume ⟨hab, hac⟩, dvd_gcd hab hac) theorem gcd_comm (a b : α) : gcd a b = gcd b a := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _) (dvd_gcd (gcd_dvd_right _ _) (gcd_dvd_left _ _)) (dvd_gcd (gcd_dvd_right _ _) (gcd_dvd_left _ _)) theorem gcd_assoc (m n k : α) : gcd (gcd m n) k = gcd m (gcd n k) := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _) (dvd_gcd (dvd.trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_left m n)) (dvd_gcd (dvd.trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_right m n)) (gcd_dvd_right (gcd m n) k))) (dvd_gcd (dvd_gcd (gcd_dvd_left m (gcd n k)) (dvd.trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_left n k))) (dvd.trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_right n k))) instance : is_commutative α gcd := ⟨gcd_comm⟩ instance : is_associative α gcd := ⟨gcd_assoc⟩ theorem gcd_eq_normalize {a b c : α} (habc : gcd a b ∣ c) (hcab : c ∣ gcd a b) : gcd a b = normalize c := normalize_gcd a b ▸ normalize_eq_normalize habc hcab @[simp] theorem gcd_zero_left (a : α) : gcd 0 a = normalize a := gcd_eq_normalize (gcd_dvd_right 0 a) (dvd_gcd (dvd_zero _) (dvd_refl a)) @[simp] theorem gcd_zero_right (a : α) : gcd a 0 = normalize a := gcd_eq_normalize (gcd_dvd_left a 0) (dvd_gcd (dvd_refl a) (dvd_zero _)) @[simp] theorem gcd_eq_zero_iff (a b : α) : gcd a b = 0 ↔ a = 0 ∧ b = 0 := iff.intro (assume h, let ⟨ca, ha⟩ := gcd_dvd_left a b, ⟨cb, hb⟩ := gcd_dvd_right a b in by rw [h, zero_mul] at ha hb; exact ⟨ha, hb⟩) (assume ⟨ha, hb⟩, by rw [ha, hb, gcd_zero_left, normalize_zero]) @[simp] theorem gcd_one_left (a : α) : gcd 1 a = 1 := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) normalize_one (gcd_dvd_left _ _) (one_dvd _) @[simp] theorem gcd_one_right (a : α) : gcd a 1 = 1 := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) normalize_one (gcd_dvd_right _ _) (one_dvd _) theorem gcd_dvd_gcd {a b c d: α} (hab : a ∣ b) (hcd : c ∣ d) : gcd a c ∣ gcd b d := dvd_gcd (dvd.trans (gcd_dvd_left _ _) hab) (dvd.trans (gcd_dvd_right _ _) hcd) @[simp] theorem gcd_same (a : α) : gcd a a = normalize a := gcd_eq_normalize (gcd_dvd_left _ _) (dvd_gcd (dvd_refl a) (dvd_refl a)) @[simp] theorem gcd_mul_left (a b c : α) : gcd (a * b) (a * c) = normalize a * gcd b c := classical.by_cases (by rintro rfl; simp only [zero_mul, gcd_zero_left, normalize_zero]) $ assume ha : a ≠ 0, suffices gcd (a * b) (a * c) = normalize (a * gcd b c), by simpa only [normalize.map_mul, normalize_gcd], let ⟨d, eq⟩ := dvd_gcd (dvd_mul_right a b) (dvd_mul_right a c) in gcd_eq_normalize (eq.symm ▸ mul_dvd_mul_left a $ show d ∣ gcd b c, from dvd_gcd ((mul_dvd_mul_iff_left ha).1 $ eq ▸ gcd_dvd_left _ _) ((mul_dvd_mul_iff_left ha).1 $ eq ▸ gcd_dvd_right _ _)) (dvd_gcd (mul_dvd_mul_left a $ gcd_dvd_left _ _) (mul_dvd_mul_left a $ gcd_dvd_right _ _)) @[simp] theorem gcd_mul_right (a b c : α) : gcd (b * a) (c * a) = gcd b c * normalize a := by simp only [mul_comm, gcd_mul_left] theorem gcd_eq_left_iff (a b : α) (h : normalize a = a) : gcd a b = a ↔ a ∣ b := iff.intro (assume eq, eq ▸ gcd_dvd_right _ _) $ assume hab, dvd_antisymm_of_normalize_eq (normalize_gcd _ _) h (gcd_dvd_left _ _) (dvd_gcd (dvd_refl a) hab) theorem gcd_eq_right_iff (a b : α) (h : normalize b = b) : gcd a b = b ↔ b ∣ a := by simpa only [gcd_comm a b] using gcd_eq_left_iff b a h theorem gcd_dvd_gcd_mul_left (m n k : α) : gcd m n ∣ gcd (k * m) n := gcd_dvd_gcd (dvd_mul_left _ _) (dvd_refl _) theorem gcd_dvd_gcd_mul_right (m n k : α) : gcd m n ∣ gcd (m * k) n := gcd_dvd_gcd (dvd_mul_right _ _) (dvd_refl _) theorem gcd_dvd_gcd_mul_left_right (m n k : α) : gcd m n ∣ gcd m (k * n) := gcd_dvd_gcd (dvd_refl _) (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right_right (m n k : α) : gcd m n ∣ gcd m (n * k) := gcd_dvd_gcd (dvd_refl _) (dvd_mul_right _ _) end gcd section lcm lemma lcm_dvd_iff {a b c : α} : lcm a b ∣ c ↔ a ∣ c ∧ b ∣ c := classical.by_cases (assume : a = 0 ∨ b = 0, by rcases this with rfl | rfl; simp only [iff_def, lcm_zero_left, lcm_zero_right, zero_dvd_iff, dvd_zero, eq_self_iff_true, and_true, imp_true_iff] {contextual:=tt}) (assume this : ¬ (a = 0 ∨ b = 0), let ⟨h1, h2⟩ := not_or_distrib.1 this in have h : gcd a b ≠ 0, from λ H, h1 ((gcd_eq_zero_iff _ _).1 H).1, by rw [← mul_dvd_mul_iff_left h, gcd_mul_lcm, normalize_dvd_iff, ← dvd_normalize_iff, normalize.map_mul, normalize_gcd, ← gcd_mul_right, dvd_gcd_iff, mul_comm b c, mul_dvd_mul_iff_left h1, mul_dvd_mul_iff_right h2, and_comm]) lemma dvd_lcm_left (a b : α) : a ∣ lcm a b := (lcm_dvd_iff.1 (dvd_refl _)).1 lemma dvd_lcm_right (a b : α) : b ∣ lcm a b := (lcm_dvd_iff.1 (dvd_refl _)).2 lemma lcm_dvd {a b c : α} (hab : a ∣ b) (hcb : c ∣ b) : lcm a c ∣ b := lcm_dvd_iff.2 ⟨hab, hcb⟩ @[simp] theorem lcm_eq_zero_iff (a b : α) : lcm a b = 0 ↔ a = 0 ∨ b = 0 := iff.intro (assume h : lcm a b = 0, have normalize (a * b) = 0, by rw [← gcd_mul_lcm _ _, h, mul_zero], by simpa only [normalize_eq_zero, mul_eq_zero, units.ne_zero, or_false]) (by rintro (rfl | rfl); [apply lcm_zero_left, apply lcm_zero_right]) @[simp] lemma normalize_lcm (a b : α) : normalize (lcm a b) = lcm a b := classical.by_cases (assume : lcm a b = 0, by rw [this, normalize_zero]) $ assume h_lcm : lcm a b ≠ 0, have h1 : gcd a b ≠ 0, from mt (by rw [gcd_eq_zero_iff, lcm_eq_zero_iff]; rintros ⟨rfl, rfl⟩; left; refl) h_lcm, have h2 : normalize (gcd a b * lcm a b) = gcd a b * lcm a b, by rw [gcd_mul_lcm, normalize_idem], by simpa only [normalize.map_mul, normalize_gcd, one_mul, mul_right_inj' h1] using h2 theorem lcm_comm (a b : α) : lcm a b = lcm b a := dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _) (lcm_dvd (dvd_lcm_right _ _) (dvd_lcm_left _ _)) (lcm_dvd (dvd_lcm_right _ _) (dvd_lcm_left _ _)) theorem lcm_assoc (m n k : α) : lcm (lcm m n) k = lcm m (lcm n k) := dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _) (lcm_dvd (lcm_dvd (dvd_lcm_left _ _) (dvd.trans (dvd_lcm_left _ _) (dvd_lcm_right _ _))) (dvd.trans (dvd_lcm_right _ _) (dvd_lcm_right _ _))) (lcm_dvd (dvd.trans (dvd_lcm_left _ _) (dvd_lcm_left _ _)) (lcm_dvd (dvd.trans (dvd_lcm_right _ _) (dvd_lcm_left _ _)) (dvd_lcm_right _ _))) instance : is_commutative α lcm := ⟨lcm_comm⟩ instance : is_associative α lcm := ⟨lcm_assoc⟩ lemma lcm_eq_normalize {a b c : α} (habc : lcm a b ∣ c) (hcab : c ∣ lcm a b) : lcm a b = normalize c := normalize_lcm a b ▸ normalize_eq_normalize habc hcab theorem lcm_dvd_lcm {a b c d : α} (hab : a ∣ b) (hcd : c ∣ d) : lcm a c ∣ lcm b d := lcm_dvd (dvd.trans hab (dvd_lcm_left _ _)) (dvd.trans hcd (dvd_lcm_right _ _)) @[simp] theorem lcm_units_coe_left (u : units α) (a : α) : lcm ↑u a = normalize a := lcm_eq_normalize (lcm_dvd units.coe_dvd (dvd_refl _)) (dvd_lcm_right _ _) @[simp] theorem lcm_units_coe_right (a : α) (u : units α) : lcm a ↑u = normalize a := (lcm_comm a u).trans $ lcm_units_coe_left _ _ @[simp] theorem lcm_one_left (a : α) : lcm 1 a = normalize a := lcm_units_coe_left 1 a @[simp] theorem lcm_one_right (a : α) : lcm a 1 = normalize a := lcm_units_coe_right a 1 @[simp] theorem lcm_same (a : α) : lcm a a = normalize a := lcm_eq_normalize (lcm_dvd (dvd_refl _) (dvd_refl _)) (dvd_lcm_left _ _) @[simp] theorem lcm_eq_one_iff (a b : α) : lcm a b = 1 ↔ a ∣ 1 ∧ b ∣ 1 := iff.intro (assume eq, eq ▸ ⟨dvd_lcm_left _ _, dvd_lcm_right _ _⟩) (assume ⟨⟨c, hc⟩, ⟨d, hd⟩⟩, show lcm (units.mk_of_mul_eq_one a c hc.symm : α) (units.mk_of_mul_eq_one b d hd.symm) = 1, by rw [lcm_units_coe_left, normalize_coe_units]) @[simp] theorem lcm_mul_left (a b c : α) : lcm (a * b) (a * c) = normalize a * lcm b c := classical.by_cases (by rintro rfl; simp only [zero_mul, lcm_zero_left, normalize_zero]) $ assume ha : a ≠ 0, suffices lcm (a * b) (a * c) = normalize (a * lcm b c), by simpa only [normalize.map_mul, normalize_lcm], have a ∣ lcm (a * b) (a * c), from dvd.trans (dvd_mul_right _ _) (dvd_lcm_left _ _), let ⟨d, eq⟩ := this in lcm_eq_normalize (lcm_dvd (mul_dvd_mul_left a (dvd_lcm_left _ _)) (mul_dvd_mul_left a (dvd_lcm_right _ _))) (eq.symm ▸ (mul_dvd_mul_left a $ lcm_dvd ((mul_dvd_mul_iff_left ha).1 $ eq ▸ dvd_lcm_left _ _) ((mul_dvd_mul_iff_left ha).1 $ eq ▸ dvd_lcm_right _ _))) @[simp] theorem lcm_mul_right (a b c : α) : lcm (b * a) (c * a) = lcm b c * normalize a := by simp only [mul_comm, lcm_mul_left] theorem lcm_eq_left_iff (a b : α) (h : normalize a = a) : lcm a b = a ↔ b ∣ a := iff.intro (assume eq, eq ▸ dvd_lcm_right _ _) $ assume hab, dvd_antisymm_of_normalize_eq (normalize_lcm _ _) h (lcm_dvd (dvd_refl a) hab) (dvd_lcm_left _ _) theorem lcm_eq_right_iff (a b : α) (h : normalize b = b) : lcm a b = b ↔ a ∣ b := by simpa only [lcm_comm b a] using lcm_eq_left_iff b a h theorem lcm_dvd_lcm_mul_left (m n k : α) : lcm m n ∣ lcm (k * m) n := lcm_dvd_lcm (dvd_mul_left _ _) (dvd_refl _) theorem lcm_dvd_lcm_mul_right (m n k : α) : lcm m n ∣ lcm (m * k) n := lcm_dvd_lcm (dvd_mul_right _ _) (dvd_refl _) theorem lcm_dvd_lcm_mul_left_right (m n k : α) : lcm m n ∣ lcm m (k * n) := lcm_dvd_lcm (dvd_refl _) (dvd_mul_left _ _) theorem lcm_dvd_lcm_mul_right_right (m n k : α) : lcm m n ∣ lcm m (n * k) := lcm_dvd_lcm (dvd_refl _) (dvd_mul_right _ _) end lcm namespace gcd_monoid theorem prime_of_irreducible {x : α} (hi: irreducible x) : prime x := ⟨hi.ne_zero, ⟨hi.1, λ a b h, begin cases gcd_dvd_left x a with y hy, cases hi.2 _ _ hy with hu hu; cases hu with u hu, { right, transitivity (gcd (x * b) (a * b)), apply dvd_gcd (dvd_mul_right x b) h, rw gcd_mul_right, rw ← hu, apply dvd_of_associated, transitivity (normalize b), symmetry, use u, apply mul_comm, apply normalize_associated, }, { left, rw [hy, ← hu], transitivity, {apply dvd_of_associated, symmetry, use u}, apply gcd_dvd_right, } end ⟩⟩ theorem irreducible_iff_prime {p : α} : irreducible p ↔ prime p := ⟨prime_of_irreducible, irreducible_of_prime⟩ end gcd_monoid end gcd_monoid namespace int section normalization_monoid instance : normalization_monoid ℤ := { norm_unit := λa:ℤ, if 0 ≤ a then 1 else -1, norm_unit_zero := if_pos (le_refl _), norm_unit_mul := assume a b hna hnb, begin by_cases ha : 0 ≤ a; by_cases hb : 0 ≤ b; simp [ha, hb], exact if_pos (mul_nonneg ha hb), exact if_neg (assume h, hb $ nonneg_of_mul_nonneg_left h $ lt_of_le_of_ne ha hna.symm), exact if_neg (assume h, ha $ nonneg_of_mul_nonneg_right h $ lt_of_le_of_ne hb hnb.symm), exact if_pos (mul_nonneg_of_nonpos_of_nonpos (le_of_not_ge ha) (le_of_not_ge hb)) end, norm_unit_coe_units := assume u, (units_eq_one_or u).elim (assume eq, eq.symm ▸ if_pos zero_le_one) (assume eq, eq.symm ▸ if_neg (not_le_of_gt $ show (-1:ℤ) < 0, by simp [@neg_lt ℤ _ 1 0])), } lemma normalize_of_nonneg {z : ℤ} (h : 0 ≤ z) : normalize z = z := show z * ↑(ite _ _ _) = z, by rw [if_pos h, units.coe_one, mul_one] lemma normalize_of_neg {z : ℤ} (h : z < 0) : normalize z = -z := show z * ↑(ite _ _ _) = -z, by rw [if_neg (not_le_of_gt h), units.coe_neg, units.coe_one, mul_neg_one] lemma normalize_coe_nat (n : ℕ) : normalize (n : ℤ) = n := normalize_of_nonneg (coe_nat_le_coe_nat_of_le $ nat.zero_le n) theorem coe_nat_abs_eq_normalize (z : ℤ) : (z.nat_abs : ℤ) = normalize z := begin by_cases 0 ≤ z, { simp [nat_abs_of_nonneg h, normalize_of_nonneg h] }, { simp [of_nat_nat_abs_of_nonpos (le_of_not_ge h), normalize_of_neg (lt_of_not_ge h)] } end end normalization_monoid /-- ℤ specific version of least common multiple. -/ def lcm (i j : ℤ) : ℕ := nat.lcm (nat_abs i) (nat_abs j) theorem lcm_def (i j : ℤ) : lcm i j = nat.lcm (nat_abs i) (nat_abs j) := rfl section gcd_monoid theorem gcd_dvd_left (i j : ℤ) : (gcd i j : ℤ) ∣ i := dvd_nat_abs.mp $ coe_nat_dvd.mpr $ nat.gcd_dvd_left _ _ theorem gcd_dvd_right (i j : ℤ) : (gcd i j : ℤ) ∣ j := dvd_nat_abs.mp $ coe_nat_dvd.mpr $ nat.gcd_dvd_right _ _ theorem dvd_gcd {i j k : ℤ} (h1 : k ∣ i) (h2 : k ∣ j) : k ∣ gcd i j := nat_abs_dvd.1 $ coe_nat_dvd.2 $ nat.dvd_gcd (nat_abs_dvd_abs_iff.2 h1) (nat_abs_dvd_abs_iff.2 h2) theorem gcd_mul_lcm (i j : ℤ) : gcd i j * lcm i j = nat_abs (i * j) := by rw [int.gcd, int.lcm, nat.gcd_mul_lcm, nat_abs_mul] instance : gcd_monoid ℤ := { gcd := λa b, int.gcd a b, lcm := λa b, int.lcm a b, gcd_dvd_left := assume a b, int.gcd_dvd_left _ _, gcd_dvd_right := assume a b, int.gcd_dvd_right _ _, dvd_gcd := assume a b c, dvd_gcd, normalize_gcd := assume a b, normalize_coe_nat _, gcd_mul_lcm := by intros; rw [← int.coe_nat_mul, gcd_mul_lcm, coe_nat_abs_eq_normalize], lcm_zero_left := assume a, coe_nat_eq_zero.2 $ nat.lcm_zero_left _, lcm_zero_right := assume a, coe_nat_eq_zero.2 $ nat.lcm_zero_right _, .. int.normalization_monoid } lemma coe_gcd (i j : ℤ) : ↑(int.gcd i j) = gcd_monoid.gcd i j := rfl lemma coe_lcm (i j : ℤ) : ↑(int.lcm i j) = gcd_monoid.lcm i j := rfl lemma nat_abs_gcd (i j : ℤ) : nat_abs (gcd_monoid.gcd i j) = int.gcd i j := rfl lemma nat_abs_lcm (i j : ℤ) : nat_abs (gcd_monoid.lcm i j) = int.lcm i j := rfl end gcd_monoid theorem gcd_comm (i j : ℤ) : gcd i j = gcd j i := nat.gcd_comm _ _ theorem gcd_assoc (i j k : ℤ) : gcd (gcd i j) k = gcd i (gcd j k) := nat.gcd_assoc _ _ _ @[simp] theorem gcd_self (i : ℤ) : gcd i i = nat_abs i := by simp [gcd] @[simp] theorem gcd_zero_left (i : ℤ) : gcd 0 i = nat_abs i := by simp [gcd] @[simp] theorem gcd_zero_right (i : ℤ) : gcd i 0 = nat_abs i := by simp [gcd] @[simp] theorem gcd_one_left (i : ℤ) : gcd 1 i = 1 := nat.gcd_one_left _ @[simp] theorem gcd_one_right (i : ℤ) : gcd i 1 = 1 := nat.gcd_one_right _ theorem gcd_mul_left (i j k : ℤ) : gcd (i * j) (i * k) = nat_abs i * gcd j k := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_gcd, coe_nat_abs_eq_normalize] theorem gcd_mul_right (i j k : ℤ) : gcd (i * j) (k * j) = gcd i k * nat_abs j := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_gcd, coe_nat_abs_eq_normalize] theorem gcd_pos_of_non_zero_left {i : ℤ} (j : ℤ) (i_non_zero : i ≠ 0) : 0 < gcd i j := nat.gcd_pos_of_pos_left (nat_abs j) (nat_abs_pos_of_ne_zero i_non_zero) theorem gcd_pos_of_non_zero_right (i : ℤ) {j : ℤ} (j_non_zero : j ≠ 0) : 0 < gcd i j := nat.gcd_pos_of_pos_right (nat_abs i) (nat_abs_pos_of_ne_zero j_non_zero) theorem gcd_eq_zero_iff {i j : ℤ} : gcd i j = 0 ↔ i = 0 ∧ j = 0 := by rw [← int.coe_nat_eq_coe_nat_iff, int.coe_nat_zero, coe_gcd, gcd_eq_zero_iff] theorem gcd_div {i j k : ℤ} (H1 : k ∣ i) (H2 : k ∣ j) : gcd (i / k) (j / k) = gcd i j / nat_abs k := by rw [gcd, nat_abs_div i k H1, nat_abs_div j k H2]; exact nat.gcd_div (nat_abs_dvd_abs_iff.mpr H1) (nat_abs_dvd_abs_iff.mpr H2) theorem gcd_div_gcd_div_gcd {i j : ℤ} (H : 0 < gcd i j) : gcd (i / gcd i j) (j / gcd i j) = 1 := begin rw [gcd_div (gcd_dvd_left i j) (gcd_dvd_right i j)], rw [nat_abs_of_nat, nat.div_self H] end theorem gcd_dvd_gcd_of_dvd_left {i k : ℤ} (j : ℤ) (H : i ∣ k) : gcd i j ∣ gcd k j := int.coe_nat_dvd.1 $ dvd_gcd (dvd.trans (gcd_dvd_left i j) H) (gcd_dvd_right i j) theorem gcd_dvd_gcd_of_dvd_right {i k : ℤ} (j : ℤ) (H : i ∣ k) : gcd j i ∣ gcd j k := int.coe_nat_dvd.1 $ dvd_gcd (gcd_dvd_left j i) (dvd.trans (gcd_dvd_right j i) H) theorem gcd_dvd_gcd_mul_left (i j k : ℤ) : gcd i j ∣ gcd (k * i) j := gcd_dvd_gcd_of_dvd_left _ (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right (i j k : ℤ) : gcd i j ∣ gcd (i * k) j := gcd_dvd_gcd_of_dvd_left _ (dvd_mul_right _ _) theorem gcd_dvd_gcd_mul_left_right (i j k : ℤ) : gcd i j ∣ gcd i (k * j) := gcd_dvd_gcd_of_dvd_right _ (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right_right (i j k : ℤ) : gcd i j ∣ gcd i (j * k) := gcd_dvd_gcd_of_dvd_right _ (dvd_mul_right _ _) theorem gcd_eq_left {i j : ℤ} (H : i ∣ j) : gcd i j = nat_abs i := nat.dvd_antisymm (by unfold gcd; exact nat.gcd_dvd_left _ _) (by unfold gcd; exact nat.dvd_gcd (dvd_refl _) (nat_abs_dvd_abs_iff.mpr H)) theorem gcd_eq_right {i j : ℤ} (H : j ∣ i) : gcd i j = nat_abs j := by rw [gcd_comm, gcd_eq_left H] theorem ne_zero_of_gcd {x y : ℤ} (hc : gcd x y ≠ 0) : x ≠ 0 ∨ y ≠ 0 := begin contrapose! hc, rw [hc.left, hc.right, gcd_zero_right, nat_abs_zero] end theorem exists_gcd_one {m n : ℤ} (H : 0 < gcd m n) : ∃ (m' n' : ℤ), gcd m' n' = 1 ∧ m = m' * gcd m n ∧ n = n' * gcd m n := ⟨_, _, gcd_div_gcd_div_gcd H, (int.div_mul_cancel (gcd_dvd_left m n)).symm, (int.div_mul_cancel (gcd_dvd_right m n)).symm⟩ theorem exists_gcd_one' {m n : ℤ} (H : 0 < gcd m n) : ∃ (g : ℕ) (m' n' : ℤ), 0 < g ∧ gcd m' n' = 1 ∧ m = m' * g ∧ n = n' * g := let ⟨m', n', h⟩ := exists_gcd_one H in ⟨_, m', n', H, h⟩ theorem pow_dvd_pow_iff {m n : ℤ} {k : ℕ} (k0 : 0 < k) : m ^ k ∣ n ^ k ↔ m ∣ n := begin refine ⟨λ h, _, λ h, pow_dvd_pow_of_dvd h _⟩, apply int.nat_abs_dvd_abs_iff.mp, apply (nat.pow_dvd_pow_iff k0).mp, rw [← int.nat_abs_pow, ← int.nat_abs_pow], exact int.nat_abs_dvd_abs_iff.mpr h end /- lcm -/ theorem lcm_comm (i j : ℤ) : lcm i j = lcm j i := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, lcm_comm] theorem lcm_assoc (i j k : ℤ) : lcm (lcm i j) k = lcm i (lcm j k) := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, lcm_assoc] @[simp] theorem lcm_zero_left (i : ℤ) : lcm 0 i = 0 := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm] @[simp] theorem lcm_zero_right (i : ℤ) : lcm i 0 = 0 := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm] @[simp] theorem lcm_one_left (i : ℤ) : lcm 1 i = nat_abs i := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, coe_nat_abs_eq_normalize] @[simp] theorem lcm_one_right (i : ℤ) : lcm i 1 = nat_abs i := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, coe_nat_abs_eq_normalize] @[simp] theorem lcm_self (i : ℤ) : lcm i i = nat_abs i := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, coe_nat_abs_eq_normalize] theorem dvd_lcm_left (i j : ℤ) : i ∣ lcm i j := by rw [coe_lcm]; exact dvd_lcm_left _ _ theorem dvd_lcm_right (i j : ℤ) : j ∣ lcm i j := by rw [coe_lcm]; exact dvd_lcm_right _ _ theorem lcm_dvd {i j k : ℤ} : i ∣ k → j ∣ k → (lcm i j : ℤ) ∣ k := by rw [coe_lcm]; exact lcm_dvd end int theorem irreducible_iff_nat_prime : ∀(a : ℕ), irreducible a ↔ nat.prime a | 0 := by simp [nat.not_prime_zero] | 1 := by simp [nat.prime, one_lt_two] | (n + 2) := have h₁ : ¬n + 2 = 1, from dec_trivial, begin simp [h₁, nat.prime, irreducible, (≥), nat.le_add_left 2 n, (∣)], refine forall_congr (assume a, forall_congr $ assume b, forall_congr $ assume hab, _), by_cases a = 1; simp [h], split, { assume hb, simpa [hb] using hab.symm }, { assume ha, subst ha, have : n + 2 > 0, from dec_trivial, refine nat.eq_of_mul_eq_mul_left this _, rw [← hab, mul_one] } end lemma nat.prime_iff_prime {p : ℕ} : p.prime ↔ _root_.prime (p : ℕ) := ⟨λ hp, ⟨nat.pos_iff_ne_zero.1 hp.pos, mt is_unit_iff_dvd_one.1 hp.not_dvd_one, λ a b, hp.dvd_mul.1⟩, λ hp, ⟨nat.one_lt_iff_ne_zero_and_ne_one.2 ⟨hp.1, λ h1, hp.2.1 $ h1.symm ▸ is_unit_one⟩, λ a h, let ⟨b, hab⟩ := h in (hp.2.2 a b (hab ▸ dvd_refl _)).elim (λ ha, or.inr (nat.dvd_antisymm h ha)) (λ hb, or.inl (have hpb : p = b, from nat.dvd_antisymm hb (hab.symm ▸ dvd_mul_left _ _), (nat.mul_right_inj (show 0 < p, from nat.pos_of_ne_zero hp.1)).1 $ by rw [hpb, mul_comm, ← hab, hpb, mul_one]))⟩⟩ lemma nat.prime_iff_prime_int {p : ℕ} : p.prime ↔ _root_.prime (p : ℤ) := ⟨λ hp, ⟨int.coe_nat_ne_zero_iff_pos.2 hp.pos, mt is_unit_int.1 hp.ne_one, λ a b h, by rw [← int.dvd_nat_abs, int.coe_nat_dvd, int.nat_abs_mul, hp.dvd_mul] at h; rwa [← int.dvd_nat_abs, int.coe_nat_dvd, ← int.dvd_nat_abs, int.coe_nat_dvd]⟩, λ hp, nat.prime_iff_prime.2 ⟨int.coe_nat_ne_zero.1 hp.1, mt nat.is_unit_iff.1 $ λ h, by simpa [h, not_prime_one] using hp, λ a b, by simpa only [int.coe_nat_dvd, (int.coe_nat_mul _ _).symm] using hp.2.2 a b⟩⟩ /-- Maps an associate class of integers consisting of `-n, n` to `n : ℕ` -/ def associates_int_equiv_nat : associates ℤ ≃ ℕ := begin refine ⟨λz, z.out.nat_abs, λn, associates.mk n, _, _⟩, { refine (assume a, quotient.induction_on' a $ assume a, associates.mk_eq_mk_iff_associated.2 $ associated.symm $ ⟨norm_unit a, _⟩), show normalize a = int.nat_abs (normalize a), rw [int.coe_nat_abs_eq_normalize, normalize_idem] }, { intro n, dsimp, rw [associates.out_mk ↑n, ← int.coe_nat_abs_eq_normalize, int.nat_abs_of_nat, int.nat_abs_of_nat] } end lemma int.prime.dvd_mul {m n : ℤ} {p : ℕ} (hp : nat.prime p) (h : (p : ℤ) ∣ m * n) : p ∣ m.nat_abs ∨ p ∣ n.nat_abs := begin apply (nat.prime.dvd_mul hp).mp, rw ← int.nat_abs_mul, exact int.coe_nat_dvd_left.mp h end lemma int.prime.dvd_mul' {m n : ℤ} {p : ℕ} (hp : nat.prime p) (h : (p : ℤ) ∣ m * n) : (p : ℤ) ∣ m ∨ (p : ℤ) ∣ n := begin rw [int.coe_nat_dvd_left, int.coe_nat_dvd_left], exact int.prime.dvd_mul hp h end lemma prime_two_or_dvd_of_dvd_two_mul_pow_self_two {m : ℤ} {p : ℕ} (hp : nat.prime p) (h : (p : ℤ) ∣ 2 * m ^ 2) : p = 2 ∨ p ∣ int.nat_abs m := begin cases int.prime.dvd_mul hp h with hp2 hpp, { apply or.intro_left, exact le_antisymm (nat.le_of_dvd two_pos hp2) (nat.prime.two_le hp) }, { apply or.intro_right, rw [pow_two, int.nat_abs_mul] at hpp, exact (or_self _).mp ((nat.prime.dvd_mul hp).mp hpp)} end section unique_unit instance nat.unique_units : unique (units ℕ) := { default := 1, uniq := nat.units_eq_one } variables [comm_cancel_monoid_with_zero α] [unique (units α)] lemma units_eq_one (u : units α) : u = 1 := subsingleton.elim u 1 variable [nontrivial α] @[priority 100] -- see Note [lower instance priority] instance normalization_monoid_of_unique_units : normalization_monoid α := { norm_unit := λ x, 1, norm_unit_zero := rfl, norm_unit_mul := λ x y hx hy, (mul_one 1).symm, norm_unit_coe_units := λ u, subsingleton.elim _ _ } @[simp] lemma norm_unit_eq_one (x : α) : norm_unit x = 1 := rfl @[simp] lemma normalize_eq (x : α) : normalize x = x := mul_one x end unique_unit
68d3d31e644c1921e1800b4f0ad56bfb19ecf142
4727251e0cd73359b15b664c3170e5d754078599
/src/order/complete_lattice_intervals.lean
1c894dafe4afef90b5dcb7dbd41a12c52bce289e
[ "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
5,898
lean
/- Copyright (c) 2022 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth -/ import order.conditionally_complete_lattice import data.set.intervals.ord_connected /-! # Subtypes of conditionally complete linear orders In this file we give conditions on a subset of a conditionally complete linear order, to ensure that the subtype is itself conditionally complete. We check that an `ord_connected` set satisfies these conditions. ## TODO Add appropriate instances for all `set.Ixx`. This requires a refactor that will allow different default values for `Sup` and `Inf`. -/ open_locale classical open set variables {α : Type*} (s : set α) section has_Sup variables [has_Sup α] /-- `has_Sup` structure on a nonempty subset `s` of an object with `has_Sup`. This definition is non-canonical (it uses `default s`); it should be used only as here, as an auxiliary instance in the construction of the `conditionally_complete_linear_order` structure. -/ noncomputable def subset_has_Sup [inhabited s] : has_Sup s := {Sup := λ t, if ht : Sup (coe '' t : set α) ∈ s then ⟨Sup (coe '' t : set α), ht⟩ else default} local attribute [instance] subset_has_Sup @[simp] lemma subset_Sup_def [inhabited s] : @Sup s _ = λ t, if ht : Sup (coe '' t : set α) ∈ s then ⟨Sup (coe '' t : set α), ht⟩ else default := rfl lemma subset_Sup_of_within [inhabited s] {t : set s} (h : Sup (coe '' t : set α) ∈ s) : Sup (coe '' t : set α) = (@Sup s _ t : α) := by simp [dif_pos h] end has_Sup section has_Inf variables [has_Inf α] /-- `has_Inf` structure on a nonempty subset `s` of an object with `has_Inf`. This definition is non-canonical (it uses `default s`); it should be used only as here, as an auxiliary instance in the construction of the `conditionally_complete_linear_order` structure. -/ noncomputable def subset_has_Inf [inhabited s] : has_Inf s := {Inf := λ t, if ht : Inf (coe '' t : set α) ∈ s then ⟨Inf (coe '' t : set α), ht⟩ else default} local attribute [instance] subset_has_Inf @[simp] lemma subset_Inf_def [inhabited s] : @Inf s _ = λ t, if ht : Inf (coe '' t : set α) ∈ s then ⟨Inf (coe '' t : set α), ht⟩ else default := rfl lemma subset_Inf_of_within [inhabited s] {t : set s} (h : Inf (coe '' t : set α) ∈ s) : Inf (coe '' t : set α) = (@Inf s _ t : α) := by simp [dif_pos h] end has_Inf variables [conditionally_complete_linear_order α] local attribute [instance] subset_has_Sup local attribute [instance] subset_has_Inf /-- For a nonempty subset of a conditionally complete linear order to be a conditionally complete linear order, it suffices that it contain the `Sup` of all its nonempty bounded-above subsets, and the `Inf` of all its nonempty bounded-below subsets. See note [reducible non-instances]. -/ @[reducible] noncomputable def subset_conditionally_complete_linear_order [inhabited s] (h_Sup : ∀ {t : set s} (ht : t.nonempty) (h_bdd : bdd_above t), Sup (coe '' t : set α) ∈ s) (h_Inf : ∀ {t : set s} (ht : t.nonempty) (h_bdd : bdd_below t), Inf (coe '' t : set α) ∈ s) : conditionally_complete_linear_order s := { le_cSup := begin rintros t c h_bdd hct, -- The following would be a more natural way to finish, but gives a "deep recursion" error: -- simpa [subset_Sup_of_within (h_Sup t)] using -- (strict_mono_coe s).monotone.le_cSup_image hct h_bdd, have := (subtype.mono_coe s).le_cSup_image hct h_bdd, rwa subset_Sup_of_within s (h_Sup ⟨c, hct⟩ h_bdd) at this, end, cSup_le := begin rintros t B ht hB, have := (subtype.mono_coe s).cSup_image_le ht hB, rwa subset_Sup_of_within s (h_Sup ht ⟨B, hB⟩) at this, end, le_cInf := begin intros t B ht hB, have := (subtype.mono_coe s).le_cInf_image ht hB, rwa subset_Inf_of_within s (h_Inf ht ⟨B, hB⟩) at this, end, cInf_le := begin rintros t c h_bdd hct, have := (subtype.mono_coe s).cInf_image_le hct h_bdd, rwa subset_Inf_of_within s (h_Inf ⟨c, hct⟩ h_bdd) at this, end, ..subset_has_Sup s, ..subset_has_Inf s, ..distrib_lattice.to_lattice s, ..(infer_instance : linear_order s) } section ord_connected /-- The `Sup` function on a nonempty `ord_connected` set `s` in a conditionally complete linear order takes values within `s`, for all nonempty bounded-above subsets of `s`. -/ lemma Sup_within_of_ord_connected {s : set α} [hs : ord_connected s] ⦃t : set s⦄ (ht : t.nonempty) (h_bdd : bdd_above t) : Sup (coe '' t : set α) ∈ s := begin obtain ⟨c, hct⟩ : ∃ c, c ∈ t := ht, obtain ⟨B, hB⟩ : ∃ B, B ∈ upper_bounds t := h_bdd, refine hs.out c.2 B.2 ⟨_, _⟩, { exact (subtype.mono_coe s).le_cSup_image hct ⟨B, hB⟩ }, { exact (subtype.mono_coe s).cSup_image_le ⟨c, hct⟩ hB }, end /-- The `Inf` function on a nonempty `ord_connected` set `s` in a conditionally complete linear order takes values within `s`, for all nonempty bounded-below subsets of `s`. -/ lemma Inf_within_of_ord_connected {s : set α} [hs : ord_connected s] ⦃t : set s⦄ (ht : t.nonempty) (h_bdd : bdd_below t) : Inf (coe '' t : set α) ∈ s := begin obtain ⟨c, hct⟩ : ∃ c, c ∈ t := ht, obtain ⟨B, hB⟩ : ∃ B, B ∈ lower_bounds t := h_bdd, refine hs.out B.2 c.2 ⟨_, _⟩, { exact (subtype.mono_coe s).le_cInf_image ⟨c, hct⟩ hB }, { exact (subtype.mono_coe s).cInf_image_le hct ⟨B, hB⟩ }, end /-- A nonempty `ord_connected` set in a conditionally complete linear order is naturally a conditionally complete linear order. -/ noncomputable instance ord_connected_subset_conditionally_complete_linear_order [inhabited s] [ord_connected s] : conditionally_complete_linear_order s := subset_conditionally_complete_linear_order s Sup_within_of_ord_connected Inf_within_of_ord_connected end ord_connected
da679c4d6347fcd8b9c7fd9c2651a04a6e570e7a
130c49f47783503e462c16b2eff31933442be6ff
/stage0/src/Lean/Meta/WHNF.lean
96d02a6a13c3f106fa8d63b7e74bd18755f6a156
[ "Apache-2.0" ]
permissive
Hazel-Brown/lean4
8aa5860e282435ffc30dcdfccd34006c59d1d39c
79e6732fc6bbf5af831b76f310f9c488d44e7a16
refs/heads/master
1,689,218,208,951
1,629,736,869,000
1,629,736,896,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,063
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.ToExpr import Lean.AuxRecursor import Lean.ProjFns import Lean.Meta.Basic import Lean.Meta.LevelDefEq import Lean.Meta.GetConst import Lean.Meta.Match.MatcherInfo namespace Lean.Meta /- =========================== Smart unfolding support =========================== -/ def smartUnfoldingSuffix := "_sunfold" @[inline] def mkSmartUnfoldingNameFor (declName : Name) : Name := Name.mkStr declName smartUnfoldingSuffix register_builtin_option smartUnfolding : Bool := { defValue := true descr := "when computing weak head normal form, use auxiliary definition created for functions defined by structural recursion" } /- =========================== Helper methods =========================== -/ def isAuxDef (constName : Name) : MetaM Bool := do let env ← getEnv return isAuxRecursor env constName || isNoConfusion env constName @[inline] private def matchConstAux {α} (e : Expr) (failK : Unit → MetaM α) (k : ConstantInfo → List Level → MetaM α) : MetaM α := match e with | Expr.const name lvls _ => do let (some cinfo) ← getConst? name | failK () k cinfo lvls | _ => failK () /- =========================== Helper functions for reducing recursors =========================== -/ private def getFirstCtor (d : Name) : MetaM (Option Name) := do let some (ConstantInfo.inductInfo { ctors := ctor::_, ..}) ← getConstNoEx? d | pure none return some ctor private def mkNullaryCtor (type : Expr) (nparams : Nat) : MetaM (Option Expr) := do match type.getAppFn with | Expr.const d lvls _ => let (some ctor) ← getFirstCtor d | pure none return mkAppN (mkConst ctor lvls) (type.getAppArgs.shrink nparams) | _ => return none def toCtorIfLit : Expr → Expr | Expr.lit (Literal.natVal v) _ => if v == 0 then mkConst `Nat.zero else mkApp (mkConst `Nat.succ) (mkRawNatLit (v-1)) | Expr.lit (Literal.strVal v) _ => mkApp (mkConst `String.mk) (toExpr v.toList) | e => e private def getRecRuleFor (recVal : RecursorVal) (major : Expr) : Option RecursorRule := match major.getAppFn with | Expr.const fn _ _ => recVal.rules.find? fun r => r.ctor == fn | _ => none private def toCtorWhenK (recVal : RecursorVal) (major : Expr) : MetaM (Option Expr) := do let majorType ← inferType major let majorType ← instantiateMVars (← whnf majorType) let majorTypeI := majorType.getAppFn if !majorTypeI.isConstOf recVal.getInduct then return none else if majorType.hasExprMVar && majorType.getAppArgs[recVal.numParams:].any Expr.hasExprMVar then return none else do let (some newCtorApp) ← mkNullaryCtor majorType recVal.numParams | pure none let newType ← inferType newCtorApp if (← isDefEq majorType newType) then return newCtorApp else return none /-- Auxiliary function for reducing recursor applications. -/ private def reduceRec (recVal : RecursorVal) (recLvls : List Level) (recArgs : Array Expr) (failK : Unit → MetaM α) (successK : Expr → MetaM α) : MetaM α := let majorIdx := recVal.getMajorIdx if h : majorIdx < recArgs.size then do let major := recArgs.get ⟨majorIdx, h⟩ let mut major ← whnf major if recVal.k then let newMajor ← toCtorWhenK recVal major major := newMajor.getD major major := toCtorIfLit major match getRecRuleFor recVal major with | some rule => let majorArgs := major.getAppArgs if recLvls.length != recVal.levelParams.length then failK () else let rhs := rule.rhs.instantiateLevelParams recVal.levelParams recLvls -- Apply parameters, motives and minor premises from recursor application. let rhs := mkAppRange rhs 0 (recVal.numParams+recVal.numMotives+recVal.numMinors) recArgs /- The number of parameters in the constructor is not necessarily equal to the number of parameters in the recursor when we have nested inductive types. -/ let nparams := majorArgs.size - rule.nfields let rhs := mkAppRange rhs nparams majorArgs.size majorArgs let rhs := mkAppRange rhs (majorIdx + 1) recArgs.size recArgs successK rhs | none => failK () else failK () /- =========================== Helper functions for reducing Quot.lift and Quot.ind =========================== -/ /-- Auxiliary function for reducing `Quot.lift` and `Quot.ind` applications. -/ private def reduceQuotRec (recVal : QuotVal) (recLvls : List Level) (recArgs : Array Expr) (failK : Unit → MetaM α) (successK : Expr → MetaM α) : MetaM α := let process (majorPos argPos : Nat) : MetaM α := if h : majorPos < recArgs.size then do let major := recArgs.get ⟨majorPos, h⟩ let major ← whnf major match major with | Expr.app (Expr.app (Expr.app (Expr.const majorFn _ _) _ _) _ _) majorArg _ => do let some (ConstantInfo.quotInfo { kind := QuotKind.ctor, .. }) ← getConstNoEx? majorFn | failK () let f := recArgs[argPos] let r := mkApp f majorArg let recArity := majorPos + 1 successK $ mkAppRange r recArity recArgs.size recArgs | _ => failK () else failK () match recVal.kind with | QuotKind.lift => process 5 3 | QuotKind.ind => process 4 3 | _ => failK () /- =========================== Helper function for extracting "stuck term" =========================== -/ mutual private partial def isRecStuck? (recVal : RecursorVal) (recLvls : List Level) (recArgs : Array Expr) : MetaM (Option MVarId) := if recVal.k then -- TODO: improve this case return none else do let majorIdx := recVal.getMajorIdx if h : majorIdx < recArgs.size then do let major := recArgs.get ⟨majorIdx, h⟩ let major ← whnf major getStuckMVar? major else return none private partial def isQuotRecStuck? (recVal : QuotVal) (recLvls : List Level) (recArgs : Array Expr) : MetaM (Option MVarId) := let process? (majorPos : Nat) : MetaM (Option MVarId) := if h : majorPos < recArgs.size then do let major := recArgs.get ⟨majorPos, h⟩ let major ← whnf major getStuckMVar? major else return none match recVal.kind with | QuotKind.lift => process? 5 | QuotKind.ind => process? 4 | _ => return none /-- Return `some (Expr.mvar mvarId)` if metavariable `mvarId` is blocking reduction. -/ partial def getStuckMVar? : Expr → MetaM (Option MVarId) | Expr.mdata _ e _ => getStuckMVar? e | Expr.proj _ _ e _ => do getStuckMVar? (← whnf e) | e@(Expr.mvar ..) => do let e ← instantiateMVars e match e with | Expr.mvar mvarId _ => pure (some mvarId) | _ => getStuckMVar? e | e@(Expr.app f _ _) => let f := f.getAppFn match f with | Expr.mvar mvarId _ => return some mvarId | Expr.const fName fLvls _ => do let cinfo? ← getConstNoEx? fName match cinfo? with | some $ ConstantInfo.recInfo recVal => isRecStuck? recVal fLvls e.getAppArgs | some $ ConstantInfo.quotInfo recVal => isQuotRecStuck? recVal fLvls e.getAppArgs | _ => return none | _ => return none | _ => return none end /- =========================== Weak Head Normal Form auxiliary combinators =========================== -/ /-- Auxiliary combinator for handling easy WHNF cases. It takes a function for handling the "hard" cases as an argument -/ @[specialize] partial def whnfEasyCases (e : Expr) (k : Expr → MetaM Expr) : MetaM Expr := do match e with | Expr.forallE .. => return e | Expr.lam .. => return e | Expr.sort .. => return e | Expr.lit .. => return e | Expr.bvar .. => unreachable! | Expr.letE .. => k e | Expr.const .. => k e | Expr.app .. => k e | Expr.proj .. => k e | Expr.mdata _ e _ => whnfEasyCases e k | Expr.fvar fvarId _ => let decl ← getLocalDecl fvarId match decl with | LocalDecl.cdecl .. => return e | LocalDecl.ldecl (value := v) (nonDep := nonDep) .. => let cfg ← getConfig if nonDep && !cfg.zetaNonDep then return e else if cfg.trackZeta then modify fun s => { s with zetaFVarIds := s.zetaFVarIds.insert fvarId } whnfEasyCases v k | Expr.mvar mvarId _ => match (← getExprMVarAssignment? mvarId) with | some v => whnfEasyCases v k | none => return e /-- Return true iff term is of the form `idRhs ...` -/ private def isIdRhsApp (e : Expr) : Bool := e.isAppOf `idRhs /-- (@idRhs T f a_1 ... a_n) ==> (f a_1 ... a_n) -/ private def extractIdRhs (e : Expr) : Expr := if !isIdRhsApp e then e else let args := e.getAppArgs if args.size < 2 then e else mkAppRange args[1] 2 args.size args @[specialize] private def deltaDefinition (c : ConstantInfo) (lvls : List Level) (failK : Unit → α) (successK : Expr → α) : α := if c.levelParams.length != lvls.length then failK () else let val := c.instantiateValueLevelParams lvls successK (extractIdRhs val) @[specialize] private def deltaBetaDefinition (c : ConstantInfo) (lvls : List Level) (revArgs : Array Expr) (failK : Unit → α) (successK : Expr → α) : α := if c.levelParams.length != lvls.length then failK () else let val := c.instantiateValueLevelParams lvls let val := val.betaRev revArgs successK (extractIdRhs val) inductive ReduceMatcherResult where | reduced (val : Expr) | stuck (val : Expr) | notMatcher | partialApp def reduceMatcher? (e : Expr) : MetaM ReduceMatcherResult := do match e.getAppFn with | Expr.const declName declLevels _ => let some info ← getMatcherInfo? declName | return ReduceMatcherResult.notMatcher let args := e.getAppArgs let prefixSz := info.numParams + 1 + info.numDiscrs if args.size < prefixSz + info.numAlts then return ReduceMatcherResult.partialApp else let constInfo ← getConstInfo declName let f := constInfo.instantiateValueLevelParams declLevels let auxApp := mkAppN f args[0:prefixSz] let auxAppType ← inferType auxApp forallBoundedTelescope auxAppType info.numAlts fun hs _ => do let auxApp := mkAppN auxApp hs let auxApp ← whnf auxApp let auxAppFn := auxApp.getAppFn let mut i := prefixSz for h in hs do if auxAppFn == h then let result := mkAppN args[i] auxApp.getAppArgs let result := mkAppN result args[prefixSz + info.numAlts:args.size] return ReduceMatcherResult.reduced result.headBeta i := i + 1 return ReduceMatcherResult.stuck auxApp | _ => pure ReduceMatcherResult.notMatcher /- Given an expression `e`, compute its WHNF and if the result is a constructor, return field #i. -/ def project? (e : Expr) (i : Nat) : MetaM (Option Expr) := do let e ← whnf e let e := toCtorIfLit e matchConstCtor e.getAppFn (fun _ => pure none) fun ctorVal _ => let numArgs := e.getAppNumArgs let idx := ctorVal.numParams + i if idx < numArgs then return some (e.getArg! idx) else return none /-- Reduce kernel projection `Expr.proj ..` expression. -/ def reduceProj? (e : Expr) : MetaM (Option Expr) := do match e with | Expr.proj _ i c _ => project? c i | _ => return none /- Auxiliary method for reducing terms of the form `?m t_1 ... t_n` where `?m` is delayed assigned. Recall that we can only expand a delayed assignment when all holes/metavariables in the assigned value have been "filled". -/ private def whnfDelayedAssigned? (f' : Expr) (e : Expr) : MetaM (Option Expr) := do if f'.isMVar then match (← getDelayedAssignment? f'.mvarId!) with | none => return none | some { fvars := fvars, val := val, .. } => let args := e.getAppArgs if fvars.size > args.size then -- Insufficient number of argument to expand delayed assignment return none else let newVal ← instantiateMVars val if newVal.hasExprMVar then -- Delayed assignment still contains metavariables return none else let newVal := newVal.abstract fvars let result := newVal.instantiateRevRange 0 fvars.size args return mkAppRange result fvars.size args.size args else return none /-- Apply beta-reduction, zeta-reduction (i.e., unfold let local-decls), iota-reduction, expand let-expressions, expand assigned meta-variables. -/ partial def whnfCore (e : Expr) : MetaM Expr := whnfEasyCases e fun e => do trace[Meta.whnf] e match e with | Expr.const .. => pure e | Expr.letE _ _ v b _ => whnfCore $ b.instantiate1 v | Expr.app f .. => let f := f.getAppFn let f' ← whnfCore f if f'.isLambda then let revArgs := e.getAppRevArgs whnfCore <| f'.betaRev revArgs else if let some eNew ← whnfDelayedAssigned? f' e then whnfCore eNew else let e := if f == f' then e else e.updateFn f' match (← reduceMatcher? e) with | ReduceMatcherResult.reduced eNew => whnfCore eNew | ReduceMatcherResult.partialApp => pure e | ReduceMatcherResult.stuck _ => pure e | ReduceMatcherResult.notMatcher => matchConstAux f' (fun _ => return e) fun cinfo lvls => match cinfo with | ConstantInfo.recInfo rec => reduceRec rec lvls e.getAppArgs (fun _ => return e) whnfCore | ConstantInfo.quotInfo rec => reduceQuotRec rec lvls e.getAppArgs (fun _ => return e) whnfCore | c@(ConstantInfo.defnInfo _) => do if (← isAuxDef c.name) then deltaBetaDefinition c lvls e.getAppRevArgs (fun _ => return e) whnfCore else return e | _ => return e | Expr.proj .. => match (← reduceProj? e) with | some e => whnfCore e | none => return e | _ => unreachable! mutual /-- Reduce `e` until `idRhs` application is exposed or it gets stuck. This is a helper method for implementing smart unfolding. -/ private partial def whnfUntilIdRhs (e : Expr) : MetaM Expr := do let e ← whnfCore e match (← getStuckMVar? e) with | some mvarId => /- Try to "unstuck" by resolving pending TC problems -/ if (← Meta.synthPending mvarId) then whnfUntilIdRhs e else return e -- failed because metavariable is blocking reduction | _ => if isIdRhsApp e then return e -- done else match (← unfoldDefinition? e) with | some e => whnfUntilIdRhs e | none => pure e -- failed because of symbolic argument /-- Auxiliary method for unfolding a class projection when transparency is set to `TransparencyMode.instances`. Recall that class instance projections are not marked with `[reducible]` because we want them to be in "reducible canonical form". -/ private partial def unfoldProjInst (e : Expr) : MetaM (Option Expr) := do if (← getTransparency) != TransparencyMode.instances then return none else match e.getAppFn with | Expr.const declName .. => match (← getProjectionFnInfo? declName) with | some { fromClass := true, .. } => match (← withDefault <| unfoldDefinition? e) with | none => return none | some e => match (← reduceProj? e.getAppFn) with | none => return none | some r => return mkAppN r e.getAppArgs |>.headBeta | _ => return none | _ => return none /-- Unfold definition using "smart unfolding" if possible. -/ partial def unfoldDefinition? (e : Expr) : MetaM (Option Expr) := match e with | Expr.app f _ _ => matchConstAux f.getAppFn (fun _ => unfoldProjInst e) fun fInfo fLvls => do if fInfo.levelParams.length != fLvls.length then return none else let unfoldDefault (_ : Unit) : MetaM (Option Expr) := if fInfo.hasValue then deltaBetaDefinition fInfo fLvls e.getAppRevArgs (fun _ => pure none) (fun e => pure (some e)) else return none if smartUnfolding.get (← getOptions) then match (← getConstNoEx? (mkSmartUnfoldingNameFor fInfo.name)) with | some fAuxInfo@(ConstantInfo.defnInfo _) => deltaBetaDefinition fAuxInfo fLvls e.getAppRevArgs (fun _ => pure none) fun e₁ => do let e₂ ← whnfUntilIdRhs e₁ if isIdRhsApp e₂ then return some (extractIdRhs e₂) else return none | _ => if (← getMatcherInfo? fInfo.name).isSome then -- Recall that `whnfCore` tries to reduce "matcher" applications. return none else unfoldDefault () else unfoldDefault () | Expr.const declName lvls _ => do if smartUnfolding.get (← getOptions) && (← getEnv).contains (mkSmartUnfoldingNameFor declName) then return none else let (some (cinfo@(ConstantInfo.defnInfo _))) ← getConstNoEx? declName | pure none deltaDefinition cinfo lvls (fun _ => pure none) (fun e => pure (some e)) | _ => return none end def unfoldDefinition (e : Expr) : MetaM Expr := do let some e ← unfoldDefinition? e | throwError "failed to unfold definition{indentExpr e}" return e @[specialize] partial def whnfHeadPred (e : Expr) (pred : Expr → MetaM Bool) : MetaM Expr := whnfEasyCases e fun e => do let e ← whnfCore e if (← pred e) then match (← unfoldDefinition? e) with | some e => whnfHeadPred e pred | none => return e else return e def whnfUntil (e : Expr) (declName : Name) : MetaM (Option Expr) := do let e ← whnfHeadPred e (fun e => return !e.isAppOf declName) if e.isAppOf declName then return e else return none /-- Try to reduce matcher/recursor/quot applications. We say they are all "morally" recursor applications. -/ def reduceRecMatcher? (e : Expr) : MetaM (Option Expr) := do if !e.isApp then return none else match (← reduceMatcher? e) with | ReduceMatcherResult.reduced e => return e | _ => matchConstAux e.getAppFn (fun _ => pure none) fun cinfo lvls => do match cinfo with | ConstantInfo.recInfo «rec» => reduceRec «rec» lvls e.getAppArgs (fun _ => pure none) (fun e => pure (some e)) | ConstantInfo.quotInfo «rec» => reduceQuotRec «rec» lvls e.getAppArgs (fun _ => pure none) (fun e => pure (some e)) | c@(ConstantInfo.defnInfo _) => if (← isAuxDef c.name) then deltaBetaDefinition c lvls e.getAppRevArgs (fun _ => pure none) (fun e => pure (some e)) else return none | _ => return none unsafe def reduceBoolNativeUnsafe (constName : Name) : MetaM Bool := evalConstCheck Bool `Bool constName unsafe def reduceNatNativeUnsafe (constName : Name) : MetaM Nat := evalConstCheck Nat `Nat constName @[implementedBy reduceBoolNativeUnsafe] constant reduceBoolNative (constName : Name) : MetaM Bool @[implementedBy reduceNatNativeUnsafe] constant reduceNatNative (constName : Name) : MetaM Nat def reduceNative? (e : Expr) : MetaM (Option Expr) := match e with | Expr.app (Expr.const fName _ _) (Expr.const argName _ _) _ => if fName == `Lean.reduceBool then do return toExpr (← reduceBoolNative argName) else if fName == `Lean.reduceNat then do return toExpr (← reduceNatNative argName) else return none | _ => return none @[inline] def withNatValue {α} (a : Expr) (k : Nat → MetaM (Option α)) : MetaM (Option α) := do let a ← whnf a match a with | Expr.const `Nat.zero _ _ => k 0 | Expr.lit (Literal.natVal v) _ => k v | _ => return none def reduceUnaryNatOp (f : Nat → Nat) (a : Expr) : MetaM (Option Expr) := withNatValue a fun a => return mkRawNatLit <| f a def reduceBinNatOp (f : Nat → Nat → Nat) (a b : Expr) : MetaM (Option Expr) := withNatValue a fun a => withNatValue b fun b => do trace[Meta.isDefEq.whnf.reduceBinOp] "{a} op {b}" return mkRawNatLit <| f a b def reduceBinNatPred (f : Nat → Nat → Bool) (a b : Expr) : MetaM (Option Expr) := do withNatValue a fun a => withNatValue b fun b => return toExpr <| f a b def reduceNat? (e : Expr) : MetaM (Option Expr) := if e.hasFVar || e.hasMVar then return none else match e with | Expr.app (Expr.const fn _ _) a _ => if fn == `Nat.succ then reduceUnaryNatOp Nat.succ a else return none | Expr.app (Expr.app (Expr.const fn _ _) a1 _) a2 _ => if fn == `Nat.add then reduceBinNatOp Nat.add a1 a2 else if fn == `Nat.sub then reduceBinNatOp Nat.sub a1 a2 else if fn == `Nat.mul then reduceBinNatOp Nat.mul a1 a2 else if fn == `Nat.div then reduceBinNatOp Nat.div a1 a2 else if fn == `Nat.mod then reduceBinNatOp Nat.mod a1 a2 else if fn == `Nat.beq then reduceBinNatPred Nat.beq a1 a2 else if fn == `Nat.ble then reduceBinNatPred Nat.ble a1 a2 else return none | _ => return none @[inline] private def useWHNFCache (e : Expr) : MetaM Bool := do -- We cache only closed terms without expr metavars. -- Potential refinement: cache if `e` is not stuck at a metavariable if e.hasFVar || e.hasExprMVar then return false else match (← getConfig).transparency with | TransparencyMode.default => true | TransparencyMode.all => true | _ => false @[inline] private def cached? (useCache : Bool) (e : Expr) : MetaM (Option Expr) := do if useCache then match (← getConfig).transparency with | TransparencyMode.default => return (← get).cache.whnfDefault.find? e | TransparencyMode.all => return (← get).cache.whnfAll.find? e | _ => unreachable! else return none private def cache (useCache : Bool) (e r : Expr) : MetaM Expr := do if useCache then match (← getConfig).transparency with | TransparencyMode.default => modify fun s => { s with cache.whnfDefault := s.cache.whnfDefault.insert e r } | TransparencyMode.all => modify fun s => { s with cache.whnfAll := s.cache.whnfAll.insert e r } | _ => unreachable! return r @[export lean_whnf] partial def whnfImp (e : Expr) : MetaM Expr := withIncRecDepth <| whnfEasyCases e fun e => do checkMaxHeartbeats "whnf" let useCache ← useWHNFCache e match (← cached? useCache e) with | some e' => pure e' | none => let e' ← whnfCore e match (← reduceNat? e') with | some v => cache useCache e v | none => match (← reduceNative? e') with | some v => cache useCache e v | none => match (← unfoldDefinition? e') with | some e => whnfImp e | none => cache useCache e e' /-- If `e` is a projection function that satisfies `p`, then reduce it -/ def reduceProjOf? (e : Expr) (p : Name → Bool) : MetaM (Option Expr) := do if !e.isApp then pure none else match e.getAppFn with | Expr.const name .. => do let env ← getEnv match env.getProjectionStructureName? name with | some structName => if p structName then Meta.unfoldDefinition? e else pure none | none => pure none | _ => pure none builtin_initialize registerTraceClass `Meta.whnf end Lean.Meta
c5bb3a2dc1c8f757393703dd6a8fb8d9ade151f9
f7315930643edc12e76c229a742d5446dad77097
/tests/lean/run/tactic28.lean
31663a239b162d849b663f7a91018ceb7ec20c6b
[ "Apache-2.0" ]
permissive
bmalehorn/lean
8f77b762a76c59afff7b7403f9eb5fc2c3ce70c1
53653c352643751c4b62ff63ec5e555f11dae8eb
refs/heads/master
1,610,945,684,489
1,429,681,220,000
1,429,681,449,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
817
lean
import logic data.num open tactic inhabited namespace foo inductive sum (A : Type) (B : Type) : Type := | inl : A → sum A B | inr : B → sum A B theorem inl_inhabited {A : Type} (B : Type) (H : inhabited A) : inhabited (sum A B) := inhabited.destruct H (λ a, inhabited.mk (sum.inl B a)) theorem inr_inhabited (A : Type) {B : Type} (H : inhabited B) : inhabited (sum A B) := inhabited.destruct H (λ b, inhabited.mk (sum.inr A b)) infixl `..`:10 := append definition my_tac := repeat (trace "iteration"; state; ( apply @inl_inhabited; trace "used inl" .. apply @inr_inhabited; trace "used inr" .. apply @num.is_inhabited; trace "used num")) ; now tactic_hint my_tac theorem T : inhabited (sum false num) end foo
831f45232e0a56ecfb0e41f5c8c2f67c8de8dd8d
618003631150032a5676f229d13a079ac875ff77
/test/norm_cast_cardinal.lean
e25d1dca97bcf2170711bf6f17831d619331ce48
[ "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
1,002
lean
import tactic.norm_cast constant cardinal : Type @[instance] constant cardinal.has_zero : has_zero cardinal @[instance] constant cardinal.has_one : has_one cardinal @[instance] constant cardinal.has_add : has_add cardinal constant cardinal.succ : cardinal → cardinal @[instance] constant cardinal.has_coe_from_nat : has_coe ℕ cardinal @[norm_cast] axiom coe_zero : ((0 : ℕ) : cardinal) = 0 @[norm_cast] axiom coe_one : ((1 : ℕ) : cardinal) = 1 @[norm_cast] axiom coe_add {a b : ℕ} : ((a + b : ℕ) : cardinal) = a + b @[norm_cast] lemma coe_bit0 {a : ℕ} : ((bit0 a : ℕ) : cardinal) = bit0 a := coe_add @[norm_cast] lemma coe_bit1 {a : ℕ} : ((bit1 a : ℕ) : cardinal) = bit1 a := by unfold bit1; norm_cast @[norm_cast, priority 900] axiom coe_succ {n : ℕ} : (n.succ : cardinal) = cardinal.succ n example : cardinal.succ 0 = 1 := by norm_cast example : cardinal.succ 1 = 2 := by norm_cast example : cardinal.succ 2 = 3 := by norm_cast example : cardinal.succ 3 = 4 := by norm_cast
19ae53bfa1a4dcbb1f68eac008ccea29bb7f305e
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/rw_set3.lean
1d6cda167f869e795a1f9efaf18083d5e32e2def
[ "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
218
lean
open tactic nat constant f : nat → nat constant g : nat → nat axiom foo : ∀ x, f x = 1 axiom bla : ∀ x, f x = 2 attribute [simp] foo attribute [simp] bla #print [simp] default example : f 5 = 2 := by simp
0a678a6ab7e9515bb85621a8212e4e9c1ebc439c
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/analysis/normed_space/inner_product.lean
bf7d0c77d0bb45dd065ada2d0b445d6be0af49a4
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
130,604
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Sébastien Gouëzel, Frédéric Dupuis, Heather Macbeth -/ import analysis.complex.basic import analysis.normed_space.bounded_linear_maps import analysis.special_functions.sqrt import linear_algebra.bilinear_form import linear_algebra.sesquilinear_form /-! # Inner Product Space This file defines inner product spaces and proves its basic properties. An inner product space is a vector space endowed with an inner product. It generalizes the notion of dot product in `ℝ^n` and provides the means of defining the length of a vector and the angle between two vectors. In particular vectors `x` and `y` are orthogonal if their inner product equals zero. We define both the real and complex cases at the same time using the `is_R_or_C` typeclass. This file proves general results on inner product spaces. For the specific construction of an inner product structure on `n → 𝕜` for `𝕜 = ℝ` or `ℂ`, see `euclidean_space` in `analysis.pi_Lp`. ## Main results - We define the class `inner_product_space 𝕜 E` extending `normed_space 𝕜 E` with a number of basic properties, most notably the Cauchy-Schwarz inequality. Here `𝕜` is understood to be either `ℝ` or `ℂ`, through the `is_R_or_C` typeclass. - We show that if `f i` is an inner product space for each `i`, then so is `Π i, f i` - Existence of orthogonal projection onto nonempty complete subspace: Let `u` be a point in an inner product space, and let `K` be a nonempty complete subspace. Then there exists a unique `v` in `K` that minimizes the distance `∥u - v∥` to `u`. The point `v` is usually called the orthogonal projection of `u` onto `K`. - We define `orthonormal`, a predicate on a function `v : ι → E`. We prove the existence of a maximal orthonormal set, `exists_maximal_orthonormal`, and also prove that a maximal orthonormal set is a basis (`maximal_orthonormal_iff_basis_of_finite_dimensional`), if `E` is finite- dimensional, or in general (`maximal_orthonormal_iff_dense_span`) a set whose span is dense (i.e., a Hilbert basis, although we do not make that definition). ## Notation We globally denote the real and complex inner products by `⟪·, ·⟫_ℝ` and `⟪·, ·⟫_ℂ` respectively. We also provide two notation namespaces: `real_inner_product_space`, `complex_inner_product_space`, which respectively introduce the plain notation `⟪·, ·⟫` for the the real and complex inner product. The orthogonal complement of a submodule `K` is denoted by `Kᗮ`. ## Implementation notes We choose the convention that inner products are conjugate linear in the first argument and linear in the second. ## Tags inner product space, norm ## References * [Clément & Martin, *The Lax-Milgram Theorem. A detailed proof to be formalized in Coq*] * [Clément & Martin, *A Coq formal proof of the Lax–Milgram theorem*] The Coq code is available at the following address: <http://www.lri.fr/~sboldo/elfic/index.html> -/ noncomputable theory open is_R_or_C real filter open_locale big_operators classical topological_space variables {𝕜 E F : Type*} [is_R_or_C 𝕜] /-- Syntactic typeclass for types endowed with an inner product -/ class has_inner (𝕜 E : Type*) := (inner : E → E → 𝕜) export has_inner (inner) notation `⟪`x`, `y`⟫_ℝ` := @inner ℝ _ _ x y notation `⟪`x`, `y`⟫_ℂ` := @inner ℂ _ _ x y section notations localized "notation `⟪`x`, `y`⟫` := @inner ℝ _ _ x y" in real_inner_product_space localized "notation `⟪`x`, `y`⟫` := @inner ℂ _ _ x y" in complex_inner_product_space end notations /-- An inner product space is a vector space with an additional operation called inner product. The norm could be derived from the inner product, instead we require the existence of a norm and the fact that `∥x∥^2 = re ⟪x, x⟫` to be able to put instances on `𝕂` or product spaces. To construct a norm from an inner product, see `inner_product_space.of_core`. -/ class inner_product_space (𝕜 : Type*) (E : Type*) [is_R_or_C 𝕜] extends normed_group E, normed_space 𝕜 E, has_inner 𝕜 E := (norm_sq_eq_inner : ∀ (x : E), ∥x∥^2 = re (inner x x)) (conj_sym : ∀ x y, conj (inner y x) = inner x y) (add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z) (smul_left : ∀ x y r, inner (r • x) y = (conj r) * inner x y) attribute [nolint dangerous_instance] inner_product_space.to_normed_group -- note [is_R_or_C instance] /-! ### Constructing a normed space structure from an inner product In the definition of an inner product space, we require the existence of a norm, which is equal (but maybe not defeq) to the square root of the scalar product. This makes it possible to put an inner product space structure on spaces with a preexisting norm (for instance `ℝ`), with good properties. However, sometimes, one would like to define the norm starting only from a well-behaved scalar product. This is what we implement in this paragraph, starting from a structure `inner_product_space.core` stating that we have a nice scalar product. Our goal here is not to develop a whole theory with all the supporting API, as this will be done below for `inner_product_space`. Instead, we implement the bare minimum to go as directly as possible to the construction of the norm and the proof of the triangular inequality. Warning: Do not use this `core` structure if the space you are interested in already has a norm instance defined on it, otherwise this will create a second non-defeq norm instance! -/ /-- A structure requiring that a scalar product is positive definite and symmetric, from which one can construct an `inner_product_space` instance in `inner_product_space.of_core`. -/ @[nolint has_inhabited_instance] structure inner_product_space.core (𝕜 : Type*) (F : Type*) [is_R_or_C 𝕜] [add_comm_group F] [module 𝕜 F] := (inner : F → F → 𝕜) (conj_sym : ∀ x y, conj (inner y x) = inner x y) (nonneg_re : ∀ x, 0 ≤ re (inner x x)) (definite : ∀ x, inner x x = 0 → x = 0) (add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z) (smul_left : ∀ x y r, inner (r • x) y = (conj r) * inner x y) /- We set `inner_product_space.core` to be a class as we will use it as such in the construction of the normed space structure that it produces. However, all the instances we will use will be local to this proof. -/ attribute [class] inner_product_space.core namespace inner_product_space.of_core variables [add_comm_group F] [module 𝕜 F] [c : inner_product_space.core 𝕜 F] include c local notation `⟪`x`, `y`⟫` := @inner 𝕜 F _ x y local notation `norm_sqK` := @is_R_or_C.norm_sq 𝕜 _ local notation `reK` := @is_R_or_C.re 𝕜 _ local notation `absK` := @is_R_or_C.abs 𝕜 _ local notation `ext_iff` := @is_R_or_C.ext_iff 𝕜 _ local postfix `†`:90 := @is_R_or_C.conj 𝕜 _ /-- Inner product defined by the `inner_product_space.core` structure. -/ def to_has_inner : has_inner 𝕜 F := { inner := c.inner } local attribute [instance] to_has_inner /-- The norm squared function for `inner_product_space.core` structure. -/ def norm_sq (x : F) := reK ⟪x, x⟫ local notation `norm_sqF` := @norm_sq 𝕜 F _ _ _ _ lemma inner_conj_sym (x y : F) : ⟪y, x⟫† = ⟪x, y⟫ := c.conj_sym x y lemma inner_self_nonneg {x : F} : 0 ≤ re ⟪x, x⟫ := c.nonneg_re _ lemma inner_self_nonneg_im {x : F} : im ⟪x, x⟫ = 0 := by rw [← @of_real_inj 𝕜, im_eq_conj_sub]; simp [inner_conj_sym] lemma inner_self_im_zero {x : F} : im ⟪x, x⟫ = 0 := inner_self_nonneg_im lemma inner_add_left {x y z : F} : ⟪x + y, z⟫ = ⟪x, z⟫ + ⟪y, z⟫ := c.add_left _ _ _ lemma inner_add_right {x y z : F} : ⟪x, y + z⟫ = ⟪x, y⟫ + ⟪x, z⟫ := by rw [←inner_conj_sym, inner_add_left, ring_hom.map_add]; simp only [inner_conj_sym] lemma inner_norm_sq_eq_inner_self (x : F) : (norm_sqF x : 𝕜) = ⟪x, x⟫ := begin rw ext_iff, exact ⟨by simp only [of_real_re]; refl, by simp only [inner_self_nonneg_im, of_real_im]⟩ end lemma inner_re_symm {x y : F} : re ⟪x, y⟫ = re ⟪y, x⟫ := by rw [←inner_conj_sym, conj_re] lemma inner_im_symm {x y : F} : im ⟪x, y⟫ = -im ⟪y, x⟫ := by rw [←inner_conj_sym, conj_im] lemma inner_smul_left {x y : F} {r : 𝕜} : ⟪r • x, y⟫ = r† * ⟪x, y⟫ := c.smul_left _ _ _ lemma inner_smul_right {x y : F} {r : 𝕜} : ⟪x, r • y⟫ = r * ⟪x, y⟫ := by rw [←inner_conj_sym, inner_smul_left]; simp only [conj_conj, inner_conj_sym, ring_hom.map_mul] lemma inner_zero_left {x : F} : ⟪0, x⟫ = 0 := by rw [←zero_smul 𝕜 (0 : F), inner_smul_left]; simp only [zero_mul, ring_hom.map_zero] lemma inner_zero_right {x : F} : ⟪x, 0⟫ = 0 := by rw [←inner_conj_sym, inner_zero_left]; simp only [ring_hom.map_zero] lemma inner_self_eq_zero {x : F} : ⟪x, x⟫ = 0 ↔ x = 0 := iff.intro (c.definite _) (by { rintro rfl, exact inner_zero_left }) lemma inner_self_re_to_K {x : F} : (re ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ := by norm_num [ext_iff, inner_self_nonneg_im] lemma inner_abs_conj_sym {x y : F} : abs ⟪x, y⟫ = abs ⟪y, x⟫ := by rw [←inner_conj_sym, abs_conj] lemma inner_neg_left {x y : F} : ⟪-x, y⟫ = -⟪x, y⟫ := by { rw [← neg_one_smul 𝕜 x, inner_smul_left], simp } lemma inner_neg_right {x y : F} : ⟪x, -y⟫ = -⟪x, y⟫ := by rw [←inner_conj_sym, inner_neg_left]; simp only [ring_hom.map_neg, inner_conj_sym] lemma inner_sub_left {x y z : F} : ⟪x - y, z⟫ = ⟪x, z⟫ - ⟪y, z⟫ := by { simp [sub_eq_add_neg, inner_add_left, inner_neg_left] } lemma inner_sub_right {x y z : F} : ⟪x, y - z⟫ = ⟪x, y⟫ - ⟪x, z⟫ := by { simp [sub_eq_add_neg, inner_add_right, inner_neg_right] } lemma inner_mul_conj_re_abs {x y : F} : re (⟪x, y⟫ * ⟪y, x⟫) = abs (⟪x, y⟫ * ⟪y, x⟫) := by { rw[←inner_conj_sym, mul_comm], exact re_eq_abs_of_mul_conj (inner y x), } /-- Expand `inner (x + y) (x + y)` -/ lemma inner_add_add_self {x y : F} : ⟪x + y, x + y⟫ = ⟪x, x⟫ + ⟪x, y⟫ + ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_add_left, inner_add_right]; ring /- Expand `inner (x - y) (x - y)` -/ lemma inner_sub_sub_self {x y : F} : ⟪x - y, x - y⟫ = ⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_sub_left, inner_sub_right]; ring /-- **Cauchy–Schwarz inequality**. This proof follows "Proof 2" on Wikipedia. We need this for the `core` structure to prove the triangle inequality below when showing the core is a normed group. -/ lemma inner_mul_inner_self_le (x y : F) : abs ⟪x, y⟫ * abs ⟪y, x⟫ ≤ re ⟪x, x⟫ * re ⟪y, y⟫ := begin by_cases hy : y = 0, { rw [hy], simp only [is_R_or_C.abs_zero, inner_zero_left, mul_zero, add_monoid_hom.map_zero] }, { change y ≠ 0 at hy, have hy' : ⟪y, y⟫ ≠ 0 := λ h, by rw [inner_self_eq_zero] at h; exact hy h, set T := ⟪y, x⟫ / ⟪y, y⟫ with hT, have h₁ : re ⟪y, x⟫ = re ⟪x, y⟫ := inner_re_symm, have h₂ : im ⟪y, x⟫ = -im ⟪x, y⟫ := inner_im_symm, have h₃ : ⟪y, x⟫ * ⟪x, y⟫ * ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = ⟪y, x⟫ * ⟪x, y⟫ / ⟪y, y⟫, { rw [mul_div_assoc], have : ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = 1 / ⟪y, y⟫ := by rw [div_mul_eq_div_mul_one_div, div_self hy', one_mul], rw [this, div_eq_mul_inv, one_mul, ←div_eq_mul_inv] }, have h₄ : ⟪y, y⟫ = re ⟪y, y⟫ := by simp only [inner_self_re_to_K], have h₅ : re ⟪y, y⟫ > 0, { refine lt_of_le_of_ne inner_self_nonneg _, intro H, apply hy', rw ext_iff, exact ⟨by simp only [H, zero_re'], by simp only [inner_self_nonneg_im, add_monoid_hom.map_zero]⟩ }, have h₆ : re ⟪y, y⟫ ≠ 0 := ne_of_gt h₅, have hmain := calc 0 ≤ re ⟪x - T • y, x - T • y⟫ : inner_self_nonneg ... = re ⟪x, x⟫ - re ⟪T • y, x⟫ - re ⟪x, T • y⟫ + re ⟪T • y, T • y⟫ : by simp only [inner_sub_sub_self, inner_smul_left, inner_smul_right, h₁, h₂, neg_mul_eq_neg_mul_symm, add_monoid_hom.map_add, mul_re, conj_im, add_monoid_hom.map_sub, mul_neg_eq_neg_mul_symm, conj_re, neg_neg] ... = re ⟪x, x⟫ - re (T† * ⟪y, x⟫) - re (T * ⟪x, y⟫) + re (T * T† * ⟪y, y⟫) : by simp only [inner_smul_left, inner_smul_right, mul_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ / ⟪y, y⟫ * ⟪y, x⟫) : by field_simp [-mul_re, inner_conj_sym, hT, conj_div, h₁, h₃] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / ⟪y, y⟫) : by rw [div_mul_eq_mul_div_comm, ←mul_div_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / re ⟪y, y⟫) : by conv_lhs { rw [h₄] } ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [div_re_of_real] ... = re ⟪x, x⟫ - abs (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [inner_mul_conj_re_abs] ... = re ⟪x, x⟫ - abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ : by rw is_R_or_C.abs_mul, have hmain' : abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ ≤ re ⟪x, x⟫ := by linarith, have := (mul_le_mul_right h₅).mpr hmain', rwa [div_mul_cancel (abs ⟪x, y⟫ * abs ⟪y, x⟫) h₆] at this } end /-- Norm constructed from a `inner_product_space.core` structure, defined to be the square root of the scalar product. -/ def to_has_norm : has_norm F := { norm := λ x, sqrt (re ⟪x, x⟫) } local attribute [instance] to_has_norm lemma norm_eq_sqrt_inner (x : F) : ∥x∥ = sqrt (re ⟪x, x⟫) := rfl lemma inner_self_eq_norm_sq (x : F) : re ⟪x, x⟫ = ∥x∥ * ∥x∥ := by rw[norm_eq_sqrt_inner, ←sqrt_mul inner_self_nonneg (re ⟪x, x⟫), sqrt_mul_self inner_self_nonneg] lemma sqrt_norm_sq_eq_norm {x : F} : sqrt (norm_sqF x) = ∥x∥ := rfl /-- Cauchy–Schwarz inequality with norm -/ lemma abs_inner_le_norm (x y : F) : abs ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := nonneg_le_nonneg_of_sq_le_sq (mul_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) begin have H : ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥) = re ⟪y, y⟫ * re ⟪x, x⟫, { simp only [inner_self_eq_norm_sq], ring, }, rw H, conv begin to_lhs, congr, rw[inner_abs_conj_sym], end, exact inner_mul_inner_self_le y x, end /-- Normed group structure constructed from an `inner_product_space.core` structure -/ def to_normed_group : normed_group F := normed_group.of_core F { norm_eq_zero_iff := assume x, begin split, { intro H, change sqrt (re ⟪x, x⟫) = 0 at H, rw [sqrt_eq_zero inner_self_nonneg] at H, apply (inner_self_eq_zero : ⟪x, x⟫ = 0 ↔ x = 0).mp, rw ext_iff, exact ⟨by simp [H], by simp [inner_self_im_zero]⟩ }, { rintro rfl, change sqrt (re ⟪0, 0⟫) = 0, simp only [sqrt_zero, inner_zero_right, add_monoid_hom.map_zero] } end, triangle := assume x y, begin have h₁ : abs ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := abs_inner_le_norm _ _, have h₂ : re ⟪x, y⟫ ≤ abs ⟪x, y⟫ := re_le_abs _, have h₃ : re ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := by linarith, have h₄ : re ⟪y, x⟫ ≤ ∥x∥ * ∥y∥ := by rwa [←inner_conj_sym, conj_re], have : ∥x + y∥ * ∥x + y∥ ≤ (∥x∥ + ∥y∥) * (∥x∥ + ∥y∥), { simp [←inner_self_eq_norm_sq, inner_add_add_self, add_mul, mul_add, mul_comm], linarith }, exact nonneg_le_nonneg_of_sq_le_sq (add_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) this end, norm_neg := λ x, by simp only [norm, inner_neg_left, neg_neg, inner_neg_right] } local attribute [instance] to_normed_group /-- Normed space structure constructed from a `inner_product_space.core` structure -/ def to_normed_space : normed_space 𝕜 F := { norm_smul_le := assume r x, begin rw [norm_eq_sqrt_inner, inner_smul_left, inner_smul_right, ←mul_assoc], rw [conj_mul_eq_norm_sq_left, of_real_mul_re, sqrt_mul, ←inner_norm_sq_eq_inner_self, of_real_re], { simp [sqrt_norm_sq_eq_norm, is_R_or_C.sqrt_norm_sq_eq_norm] }, { exact norm_sq_nonneg r } end } end inner_product_space.of_core /-- Given a `inner_product_space.core` structure on a space, one can use it to turn the space into an inner product space, constructing the norm out of the inner product -/ def inner_product_space.of_core [add_comm_group F] [module 𝕜 F] (c : inner_product_space.core 𝕜 F) : inner_product_space 𝕜 F := begin letI : normed_group F := @inner_product_space.of_core.to_normed_group 𝕜 F _ _ _ c, letI : normed_space 𝕜 F := @inner_product_space.of_core.to_normed_space 𝕜 F _ _ _ c, exact { norm_sq_eq_inner := λ x, begin have h₁ : ∥x∥^2 = (sqrt (re (c.inner x x))) ^ 2 := rfl, have h₂ : 0 ≤ re (c.inner x x) := inner_product_space.of_core.inner_self_nonneg, simp [h₁, sq_sqrt, h₂], end, ..c } end /-! ### Properties of inner product spaces -/ variables [inner_product_space 𝕜 E] [inner_product_space ℝ F] local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y local notation `IK` := @is_R_or_C.I 𝕜 _ local notation `absR` := _root_.abs local notation `absK` := @is_R_or_C.abs 𝕜 _ local postfix `†`:90 := @is_R_or_C.conj 𝕜 _ local postfix `⋆`:90 := complex.conj export inner_product_space (norm_sq_eq_inner) section basic_properties @[simp] lemma inner_conj_sym (x y : E) : ⟪y, x⟫† = ⟪x, y⟫ := inner_product_space.conj_sym _ _ lemma real_inner_comm (x y : F) : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := inner_conj_sym x y lemma inner_eq_zero_sym {x y : E} : ⟪x, y⟫ = 0 ↔ ⟪y, x⟫ = 0 := ⟨λ h, by simp [←inner_conj_sym, h], λ h, by simp [←inner_conj_sym, h]⟩ @[simp] lemma inner_self_nonneg_im {x : E} : im ⟪x, x⟫ = 0 := by rw [← @of_real_inj 𝕜, im_eq_conj_sub]; simp lemma inner_self_im_zero {x : E} : im ⟪x, x⟫ = 0 := inner_self_nonneg_im lemma inner_add_left {x y z : E} : ⟪x + y, z⟫ = ⟪x, z⟫ + ⟪y, z⟫ := inner_product_space.add_left _ _ _ lemma inner_add_right {x y z : E} : ⟪x, y + z⟫ = ⟪x, y⟫ + ⟪x, z⟫ := by { rw [←inner_conj_sym, inner_add_left, ring_hom.map_add], simp only [inner_conj_sym] } lemma inner_re_symm {x y : E} : re ⟪x, y⟫ = re ⟪y, x⟫ := by rw [←inner_conj_sym, conj_re] lemma inner_im_symm {x y : E} : im ⟪x, y⟫ = -im ⟪y, x⟫ := by rw [←inner_conj_sym, conj_im] lemma inner_smul_left {x y : E} {r : 𝕜} : ⟪r • x, y⟫ = r† * ⟪x, y⟫ := inner_product_space.smul_left _ _ _ lemma real_inner_smul_left {x y : F} {r : ℝ} : ⟪r • x, y⟫_ℝ = r * ⟪x, y⟫_ℝ := inner_smul_left lemma inner_smul_real_left {x y : E} {r : ℝ} : ⟪(r : 𝕜) • x, y⟫ = r • ⟪x, y⟫ := by { rw [inner_smul_left, conj_of_real, algebra.smul_def], refl } lemma inner_smul_right {x y : E} {r : 𝕜} : ⟪x, r • y⟫ = r * ⟪x, y⟫ := by rw [←inner_conj_sym, inner_smul_left, ring_hom.map_mul, conj_conj, inner_conj_sym] lemma real_inner_smul_right {x y : F} {r : ℝ} : ⟪x, r • y⟫_ℝ = r * ⟪x, y⟫_ℝ := inner_smul_right lemma inner_smul_real_right {x y : E} {r : ℝ} : ⟪x, (r : 𝕜) • y⟫ = r • ⟪x, y⟫ := by { rw [inner_smul_right, algebra.smul_def], refl } /-- The inner product as a sesquilinear form. -/ @[simps] def sesq_form_of_inner : sesq_form 𝕜 E (conj_to_ring_equiv 𝕜) := { sesq := λ x y, ⟪y, x⟫, -- Note that sesquilinear forms are linear in the first argument sesq_add_left := λ x y z, inner_add_right, sesq_add_right := λ x y z, inner_add_left, sesq_smul_left := λ r x y, inner_smul_right, sesq_smul_right := λ r x y, inner_smul_left } /-- The real inner product as a bilinear form. -/ @[simps] def bilin_form_of_real_inner : bilin_form ℝ F := { bilin := inner, bilin_add_left := λ x y z, inner_add_left, bilin_smul_left := λ a x y, inner_smul_left, bilin_add_right := λ x y z, inner_add_right, bilin_smul_right := λ a x y, inner_smul_right } /-- An inner product with a sum on the left. -/ lemma sum_inner {ι : Type*} (s : finset ι) (f : ι → E) (x : E) : ⟪∑ i in s, f i, x⟫ = ∑ i in s, ⟪f i, x⟫ := sesq_form.sum_right (sesq_form_of_inner) _ _ _ /-- An inner product with a sum on the right. -/ lemma inner_sum {ι : Type*} (s : finset ι) (f : ι → E) (x : E) : ⟪x, ∑ i in s, f i⟫ = ∑ i in s, ⟪x, f i⟫ := sesq_form.sum_left (sesq_form_of_inner) _ _ _ /-- An inner product with a sum on the left, `finsupp` version. -/ lemma finsupp.sum_inner {ι : Type*} (l : ι →₀ 𝕜) (v : ι → E) (x : E) : ⟪l.sum (λ (i : ι) (a : 𝕜), a • v i), x⟫ = l.sum (λ (i : ι) (a : 𝕜), (is_R_or_C.conj a) • ⟪v i, x⟫) := by { convert sum_inner l.support (λ a, l a • v a) x, simp [inner_smul_left, finsupp.sum] } /-- An inner product with a sum on the right, `finsupp` version. -/ lemma finsupp.inner_sum {ι : Type*} (l : ι →₀ 𝕜) (v : ι → E) (x : E) : ⟪x, l.sum (λ (i : ι) (a : 𝕜), a • v i)⟫ = l.sum (λ (i : ι) (a : 𝕜), a • ⟪x, v i⟫) := by { convert inner_sum l.support (λ a, l a • v a) x, simp [inner_smul_right, finsupp.sum] } @[simp] lemma inner_zero_left {x : E} : ⟪0, x⟫ = 0 := by rw [← zero_smul 𝕜 (0:E), inner_smul_left, ring_hom.map_zero, zero_mul] lemma inner_re_zero_left {x : E} : re ⟪0, x⟫ = 0 := by simp only [inner_zero_left, add_monoid_hom.map_zero] @[simp] lemma inner_zero_right {x : E} : ⟪x, 0⟫ = 0 := by rw [←inner_conj_sym, inner_zero_left, ring_hom.map_zero] lemma inner_re_zero_right {x : E} : re ⟪x, 0⟫ = 0 := by simp only [inner_zero_right, add_monoid_hom.map_zero] lemma inner_self_nonneg {x : E} : 0 ≤ re ⟪x, x⟫ := by rw [←norm_sq_eq_inner]; exact pow_nonneg (norm_nonneg x) 2 lemma real_inner_self_nonneg {x : F} : 0 ≤ ⟪x, x⟫_ℝ := @inner_self_nonneg ℝ F _ _ x @[simp] lemma inner_self_eq_zero {x : E} : ⟪x, x⟫ = 0 ↔ x = 0 := begin split, { intro h, have h₁ : re ⟪x, x⟫ = 0 := by rw is_R_or_C.ext_iff at h; simp [h.1], rw [←norm_sq_eq_inner x] at h₁, rw [←norm_eq_zero], exact pow_eq_zero h₁ }, { rintro rfl, exact inner_zero_left } end @[simp] lemma inner_self_nonpos {x : E} : re ⟪x, x⟫ ≤ 0 ↔ x = 0 := begin split, { intro h, rw ←inner_self_eq_zero, have H₁ : re ⟪x, x⟫ ≥ 0, exact inner_self_nonneg, have H₂ : re ⟪x, x⟫ = 0, exact le_antisymm h H₁, rw is_R_or_C.ext_iff, exact ⟨by simp [H₂], by simp [inner_self_nonneg_im]⟩ }, { rintro rfl, simp only [inner_zero_left, add_monoid_hom.map_zero] } end lemma real_inner_self_nonpos {x : F} : ⟪x, x⟫_ℝ ≤ 0 ↔ x = 0 := by { have h := @inner_self_nonpos ℝ F _ _ x, simpa using h } @[simp] lemma inner_self_re_to_K {x : E} : (re ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ := by rw is_R_or_C.ext_iff; exact ⟨by simp, by simp [inner_self_nonneg_im]⟩ lemma inner_self_eq_norm_sq_to_K (x : E) : ⟪x, x⟫ = (∥x∥ ^ 2 : 𝕜) := begin suffices : (is_R_or_C.re ⟪x, x⟫ : 𝕜) = ∥x∥ ^ 2, { simpa [inner_self_re_to_K] using this }, exact_mod_cast (norm_sq_eq_inner x).symm end lemma inner_self_re_abs {x : E} : re ⟪x, x⟫ = abs ⟪x, x⟫ := begin conv_rhs { rw [←inner_self_re_to_K] }, symmetry, exact is_R_or_C.abs_of_nonneg inner_self_nonneg, end lemma inner_self_abs_to_K {x : E} : (absK ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ := by { rw[←inner_self_re_abs], exact inner_self_re_to_K } lemma real_inner_self_abs {x : F} : absR ⟪x, x⟫_ℝ = ⟪x, x⟫_ℝ := by { have h := @inner_self_abs_to_K ℝ F _ _ x, simpa using h } lemma inner_abs_conj_sym {x y : E} : abs ⟪x, y⟫ = abs ⟪y, x⟫ := by rw [←inner_conj_sym, abs_conj] @[simp] lemma inner_neg_left {x y : E} : ⟪-x, y⟫ = -⟪x, y⟫ := by { rw [← neg_one_smul 𝕜 x, inner_smul_left], simp } @[simp] lemma inner_neg_right {x y : E} : ⟪x, -y⟫ = -⟪x, y⟫ := by rw [←inner_conj_sym, inner_neg_left]; simp only [ring_hom.map_neg, inner_conj_sym] lemma inner_neg_neg {x y : E} : ⟪-x, -y⟫ = ⟪x, y⟫ := by simp @[simp] lemma inner_self_conj {x : E} : ⟪x, x⟫† = ⟪x, x⟫ := by rw [is_R_or_C.ext_iff]; exact ⟨by rw [conj_re], by rw [conj_im, inner_self_im_zero, neg_zero]⟩ lemma inner_sub_left {x y z : E} : ⟪x - y, z⟫ = ⟪x, z⟫ - ⟪y, z⟫ := by { simp [sub_eq_add_neg, inner_add_left] } lemma inner_sub_right {x y z : E} : ⟪x, y - z⟫ = ⟪x, y⟫ - ⟪x, z⟫ := by { simp [sub_eq_add_neg, inner_add_right] } lemma inner_mul_conj_re_abs {x y : E} : re (⟪x, y⟫ * ⟪y, x⟫) = abs (⟪x, y⟫ * ⟪y, x⟫) := by { rw[←inner_conj_sym, mul_comm], exact re_eq_abs_of_mul_conj (inner y x), } /-- Expand `⟪x + y, x + y⟫` -/ lemma inner_add_add_self {x y : E} : ⟪x + y, x + y⟫ = ⟪x, x⟫ + ⟪x, y⟫ + ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_add_left, inner_add_right]; ring /-- Expand `⟪x + y, x + y⟫_ℝ` -/ lemma real_inner_add_add_self {x y : F} : ⟪x + y, x + y⟫_ℝ = ⟪x, x⟫_ℝ + 2 * ⟪x, y⟫_ℝ + ⟪y, y⟫_ℝ := begin have : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl, simp [inner_add_add_self, this], ring, end /- Expand `⟪x - y, x - y⟫` -/ lemma inner_sub_sub_self {x y : E} : ⟪x - y, x - y⟫ = ⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_sub_left, inner_sub_right]; ring /-- Expand `⟪x - y, x - y⟫_ℝ` -/ lemma real_inner_sub_sub_self {x y : F} : ⟪x - y, x - y⟫_ℝ = ⟪x, x⟫_ℝ - 2 * ⟪x, y⟫_ℝ + ⟪y, y⟫_ℝ := begin have : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl, simp [inner_sub_sub_self, this], ring, end /-- Parallelogram law -/ lemma parallelogram_law {x y : E} : ⟪x + y, x + y⟫ + ⟪x - y, x - y⟫ = 2 * (⟪x, x⟫ + ⟪y, y⟫) := by simp [inner_add_add_self, inner_sub_sub_self, two_mul, sub_eq_add_neg, add_comm, add_left_comm] /-- Cauchy–Schwarz inequality. This proof follows "Proof 2" on Wikipedia. -/ lemma inner_mul_inner_self_le (x y : E) : abs ⟪x, y⟫ * abs ⟪y, x⟫ ≤ re ⟪x, x⟫ * re ⟪y, y⟫ := begin by_cases hy : y = 0, { rw [hy], simp only [is_R_or_C.abs_zero, inner_zero_left, mul_zero, add_monoid_hom.map_zero] }, { change y ≠ 0 at hy, have hy' : ⟪y, y⟫ ≠ 0 := λ h, by rw [inner_self_eq_zero] at h; exact hy h, set T := ⟪y, x⟫ / ⟪y, y⟫ with hT, have h₁ : re ⟪y, x⟫ = re ⟪x, y⟫ := inner_re_symm, have h₂ : im ⟪y, x⟫ = -im ⟪x, y⟫ := inner_im_symm, have h₃ : ⟪y, x⟫ * ⟪x, y⟫ * ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = ⟪y, x⟫ * ⟪x, y⟫ / ⟪y, y⟫, { rw [mul_div_assoc], have : ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = 1 / ⟪y, y⟫ := by rw [div_mul_eq_div_mul_one_div, div_self hy', one_mul], rw [this, div_eq_mul_inv, one_mul, ←div_eq_mul_inv] }, have h₄ : ⟪y, y⟫ = re ⟪y, y⟫ := by simp, have h₅ : re ⟪y, y⟫ > 0, { refine lt_of_le_of_ne inner_self_nonneg _, intro H, apply hy', rw is_R_or_C.ext_iff, exact ⟨by simp only [H, zero_re'], by simp only [inner_self_nonneg_im, add_monoid_hom.map_zero]⟩ }, have h₆ : re ⟪y, y⟫ ≠ 0 := ne_of_gt h₅, have hmain := calc 0 ≤ re ⟪x - T • y, x - T • y⟫ : inner_self_nonneg ... = re ⟪x, x⟫ - re ⟪T • y, x⟫ - re ⟪x, T • y⟫ + re ⟪T • y, T • y⟫ : by simp only [inner_sub_sub_self, inner_smul_left, inner_smul_right, h₁, h₂, neg_mul_eq_neg_mul_symm, add_monoid_hom.map_add, conj_im, add_monoid_hom.map_sub, mul_neg_eq_neg_mul_symm, conj_re, neg_neg, mul_re] ... = re ⟪x, x⟫ - re (T† * ⟪y, x⟫) - re (T * ⟪x, y⟫) + re (T * T† * ⟪y, y⟫) : by simp only [inner_smul_left, inner_smul_right, mul_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ / ⟪y, y⟫ * ⟪y, x⟫) : by field_simp [-mul_re, hT, conj_div, h₁, h₃, inner_conj_sym] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / ⟪y, y⟫) : by rw [div_mul_eq_mul_div_comm, ←mul_div_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / re ⟪y, y⟫) : by conv_lhs { rw [h₄] } ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [div_re_of_real] ... = re ⟪x, x⟫ - abs (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [inner_mul_conj_re_abs] ... = re ⟪x, x⟫ - abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ : by rw is_R_or_C.abs_mul, have hmain' : abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ ≤ re ⟪x, x⟫ := by linarith, have := (mul_le_mul_right h₅).mpr hmain', rwa [div_mul_cancel (abs ⟪x, y⟫ * abs ⟪y, x⟫) h₆] at this } end /-- Cauchy–Schwarz inequality for real inner products. -/ lemma real_inner_mul_inner_self_le (x y : F) : ⟪x, y⟫_ℝ * ⟪x, y⟫_ℝ ≤ ⟪x, x⟫_ℝ * ⟪y, y⟫_ℝ := begin have h₁ : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl, have h₂ := @inner_mul_inner_self_le ℝ F _ _ x y, dsimp at h₂, have h₃ := abs_mul_abs_self ⟪x, y⟫_ℝ, rw [h₁] at h₂, simpa [h₃] using h₂, end /-- A family of vectors is linearly independent if they are nonzero and orthogonal. -/ lemma linear_independent_of_ne_zero_of_inner_eq_zero {ι : Type*} {v : ι → E} (hz : ∀ i, v i ≠ 0) (ho : ∀ i j, i ≠ j → ⟪v i, v j⟫ = 0) : linear_independent 𝕜 v := begin rw linear_independent_iff', intros s g hg i hi, have h' : g i * inner (v i) (v i) = inner (v i) (∑ j in s, g j • v j), { rw inner_sum, symmetry, convert finset.sum_eq_single i _ _, { rw inner_smul_right }, { intros j hj hji, rw [inner_smul_right, ho i j hji.symm, mul_zero] }, { exact λ h, false.elim (h hi) } }, simpa [hg, hz] using h' end end basic_properties section orthonormal_sets variables {ι : Type*} (𝕜) include 𝕜 /-- An orthonormal set of vectors in an `inner_product_space` -/ def orthonormal (v : ι → E) : Prop := (∀ i, ∥v i∥ = 1) ∧ (∀ {i j}, i ≠ j → ⟪v i, v j⟫ = 0) omit 𝕜 variables {𝕜} /-- `if ... then ... else` characterization of an indexed set of vectors being orthonormal. (Inner product equals Kronecker delta.) -/ lemma orthonormal_iff_ite {v : ι → E} : orthonormal 𝕜 v ↔ ∀ i j, ⟪v i, v j⟫ = if i = j then (1:𝕜) else (0:𝕜) := begin split, { intros hv i j, split_ifs, { simp [h, inner_self_eq_norm_sq_to_K, hv.1] }, { exact hv.2 h } }, { intros h, split, { intros i, have h' : ∥v i∥ ^ 2 = 1 ^ 2 := by simp [norm_sq_eq_inner, h i i], have h₁ : 0 ≤ ∥v i∥ := norm_nonneg _, have h₂ : (0:ℝ) ≤ 1 := zero_le_one, rwa sq_eq_sq h₁ h₂ at h' }, { intros i j hij, simpa [hij] using h i j } } end /-- `if ... then ... else` characterization of a set of vectors being orthonormal. (Inner product equals Kronecker delta.) -/ theorem orthonormal_subtype_iff_ite {s : set E} : orthonormal 𝕜 (coe : s → E) ↔ (∀ v ∈ s, ∀ w ∈ s, ⟪v, w⟫ = if v = w then 1 else 0) := begin rw orthonormal_iff_ite, split, { intros h v hv w hw, convert h ⟨v, hv⟩ ⟨w, hw⟩ using 1, simp }, { rintros h ⟨v, hv⟩ ⟨w, hw⟩, convert h v hv w hw using 1, simp } end /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_right_finsupp {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι →₀ 𝕜) (i : ι) : ⟪v i, finsupp.total ι E 𝕜 v l⟫ = l i := by simp [finsupp.total_apply, finsupp.inner_sum, orthonormal_iff_ite.mp hv] /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_right_fintype [fintype ι] {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι → 𝕜) (i : ι) : ⟪v i, ∑ i : ι, (l i) • (v i)⟫ = l i := by simp [inner_sum, inner_smul_right, orthonormal_iff_ite.mp hv] /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_left_finsupp {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι →₀ 𝕜) (i : ι) : ⟪finsupp.total ι E 𝕜 v l, v i⟫ = conj (l i) := by rw [← inner_conj_sym, hv.inner_right_finsupp] /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_left_fintype [fintype ι] {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι → 𝕜) (i : ι) : ⟪∑ i : ι, (l i) • (v i), v i⟫ = conj (l i) := by simp [sum_inner, inner_smul_left, orthonormal_iff_ite.mp hv] /-- The double sum of weighted inner products of pairs of vectors from an orthonormal sequence is the sum of the weights. -/ lemma orthonormal.inner_left_right_finset {s : finset ι} {v : ι → E} (hv : orthonormal 𝕜 v) {a : ι → ι → 𝕜} : ∑ i in s, ∑ j in s, (a i j) • ⟪v j, v i⟫ = ∑ k in s, a k k := by simp [orthonormal_iff_ite.mp hv, finset.sum_ite_of_true] /-- An orthonormal set is linearly independent. -/ lemma orthonormal.linear_independent {v : ι → E} (hv : orthonormal 𝕜 v) : linear_independent 𝕜 v := begin rw linear_independent_iff, intros l hl, ext i, have key : ⟪v i, finsupp.total ι E 𝕜 v l⟫ = ⟪v i, 0⟫ := by rw hl, simpa [hv.inner_right_finsupp] using key end /-- A subfamily of an orthonormal family (i.e., a composition with an injective map) is an orthonormal family. -/ lemma orthonormal.comp {ι' : Type*} {v : ι → E} (hv : orthonormal 𝕜 v) (f : ι' → ι) (hf : function.injective f) : orthonormal 𝕜 (v ∘ f) := begin rw orthonormal_iff_ite at ⊢ hv, intros i j, convert hv (f i) (f j) using 1, simp [hf.eq_iff] end /-- A linear combination of some subset of an orthonormal set is orthogonal to other members of the set. -/ lemma orthonormal.inner_finsupp_eq_zero {v : ι → E} (hv : orthonormal 𝕜 v) {s : set ι} {i : ι} (hi : i ∉ s) {l : ι →₀ 𝕜} (hl : l ∈ finsupp.supported 𝕜 𝕜 s) : ⟪finsupp.total ι E 𝕜 v l, v i⟫ = 0 := begin rw finsupp.mem_supported' at hl, simp [hv.inner_left_finsupp, hl i hi], end /- The material that follows, culminating in the existence of a maximal orthonormal subset, is adapted from the corresponding development of the theory of linearly independents sets. See `exists_linear_independent` in particular. -/ variables (𝕜 E) lemma orthonormal_empty : orthonormal 𝕜 (λ x, x : (∅ : set E) → E) := by simp [orthonormal_subtype_iff_ite] variables {𝕜 E} lemma orthonormal_Union_of_directed {η : Type*} {s : η → set E} (hs : directed (⊆) s) (h : ∀ i, orthonormal 𝕜 (λ x, x : s i → E)) : orthonormal 𝕜 (λ x, x : (⋃ i, s i) → E) := begin rw orthonormal_subtype_iff_ite, rintros x ⟨_, ⟨i, rfl⟩, hxi⟩ y ⟨_, ⟨j, rfl⟩, hyj⟩, obtain ⟨k, hik, hjk⟩ := hs i j, have h_orth : orthonormal 𝕜 (λ x, x : (s k) → E) := h k, rw orthonormal_subtype_iff_ite at h_orth, exact h_orth x (hik hxi) y (hjk hyj) end lemma orthonormal_sUnion_of_directed {s : set (set E)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, orthonormal 𝕜 (λ x, x : (a : set E) → E)) : orthonormal 𝕜 (λ x, x : (⋃₀ s) → E) := by rw set.sUnion_eq_Union; exact orthonormal_Union_of_directed hs.directed_coe (by simpa using h) /-- Given an orthonormal set `v` of vectors in `E`, there exists a maximal orthonormal set containing it. -/ lemma exists_maximal_orthonormal {s : set E} (hs : orthonormal 𝕜 (coe : s → E)) : ∃ w ⊇ s, orthonormal 𝕜 (coe : w → E) ∧ ∀ u ⊇ w, orthonormal 𝕜 (coe : u → E) → u = w := begin rcases zorn.zorn_subset_nonempty {b | orthonormal 𝕜 (coe : b → E)} _ _ hs with ⟨b, bi, sb, h⟩, { refine ⟨b, sb, bi, _⟩, exact λ u hus hu, h u hu hus }, { refine λ c hc cc c0, ⟨⋃₀ c, _, _⟩, { exact orthonormal_sUnion_of_directed cc.directed_on (λ x xc, hc xc) }, { exact λ _, set.subset_sUnion_of_mem } } end lemma orthonormal.ne_zero {v : ι → E} (hv : orthonormal 𝕜 v) (i : ι) : v i ≠ 0 := begin have : ∥v i∥ ≠ 0, { rw hv.1 i, norm_num }, simpa using this end open finite_dimensional /-- A family of orthonormal vectors with the correct cardinality forms a basis. -/ def basis_of_orthonormal_of_card_eq_finrank [fintype ι] [nonempty ι] {v : ι → E} (hv : orthonormal 𝕜 v) (card_eq : fintype.card ι = finrank 𝕜 E) : basis ι 𝕜 E := basis_of_linear_independent_of_card_eq_finrank hv.linear_independent card_eq @[simp] lemma coe_basis_of_orthonormal_of_card_eq_finrank [fintype ι] [nonempty ι] {v : ι → E} (hv : orthonormal 𝕜 v) (card_eq : fintype.card ι = finrank 𝕜 E) : (basis_of_orthonormal_of_card_eq_finrank hv card_eq : ι → E) = v := coe_basis_of_linear_independent_of_card_eq_finrank _ _ end orthonormal_sets section norm lemma norm_eq_sqrt_inner (x : E) : ∥x∥ = sqrt (re ⟪x, x⟫) := begin have h₁ : ∥x∥^2 = re ⟪x, x⟫ := norm_sq_eq_inner x, have h₂ := congr_arg sqrt h₁, simpa using h₂, end lemma norm_eq_sqrt_real_inner (x : F) : ∥x∥ = sqrt ⟪x, x⟫_ℝ := by { have h := @norm_eq_sqrt_inner ℝ F _ _ x, simpa using h } lemma inner_self_eq_norm_sq (x : E) : re ⟪x, x⟫ = ∥x∥ * ∥x∥ := by rw[norm_eq_sqrt_inner, ←sqrt_mul inner_self_nonneg (re ⟪x, x⟫), sqrt_mul_self inner_self_nonneg] lemma real_inner_self_eq_norm_sq (x : F) : ⟪x, x⟫_ℝ = ∥x∥ * ∥x∥ := by { have h := @inner_self_eq_norm_sq ℝ F _ _ x, simpa using h } /-- Expand the square -/ lemma norm_add_sq {x y : E} : ∥x + y∥^2 = ∥x∥^2 + 2 * (re ⟪x, y⟫) + ∥y∥^2 := begin repeat {rw [sq, ←inner_self_eq_norm_sq]}, rw[inner_add_add_self, two_mul], simp only [add_assoc, add_left_inj, add_right_inj, add_monoid_hom.map_add], rw [←inner_conj_sym, conj_re], end alias norm_add_sq ← norm_add_pow_two /-- Expand the square -/ lemma norm_add_sq_real {x y : F} : ∥x + y∥^2 = ∥x∥^2 + 2 * ⟪x, y⟫_ℝ + ∥y∥^2 := by { have h := @norm_add_sq ℝ F _ _, simpa using h } alias norm_add_sq_real ← norm_add_pow_two_real /-- Expand the square -/ lemma norm_add_mul_self {x y : E} : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + 2 * (re ⟪x, y⟫) + ∥y∥ * ∥y∥ := by { repeat {rw [← sq]}, exact norm_add_sq } /-- Expand the square -/ lemma norm_add_mul_self_real {x y : F} : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + 2 * ⟪x, y⟫_ℝ + ∥y∥ * ∥y∥ := by { have h := @norm_add_mul_self ℝ F _ _, simpa using h } /-- Expand the square -/ lemma norm_sub_sq {x y : E} : ∥x - y∥^2 = ∥x∥^2 - 2 * (re ⟪x, y⟫) + ∥y∥^2 := begin repeat {rw [sq, ←inner_self_eq_norm_sq]}, rw[inner_sub_sub_self], calc re (⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫) = re ⟪x, x⟫ - re ⟪x, y⟫ - re ⟪y, x⟫ + re ⟪y, y⟫ : by simp ... = -re ⟪y, x⟫ - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by ring ... = -re (⟪x, y⟫†) - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by rw[inner_conj_sym] ... = -re ⟪x, y⟫ - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by rw[conj_re] ... = re ⟪x, x⟫ - 2*re ⟪x, y⟫ + re ⟪y, y⟫ : by ring end alias norm_sub_sq ← norm_sub_pow_two /-- Expand the square -/ lemma norm_sub_sq_real {x y : F} : ∥x - y∥^2 = ∥x∥^2 - 2 * ⟪x, y⟫_ℝ + ∥y∥^2 := norm_sub_sq alias norm_sub_sq_real ← norm_sub_pow_two_real /-- Expand the square -/ lemma norm_sub_mul_self {x y : E} : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ - 2 * re ⟪x, y⟫ + ∥y∥ * ∥y∥ := by { repeat {rw [← sq]}, exact norm_sub_sq } /-- Expand the square -/ lemma norm_sub_mul_self_real {x y : F} : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ - 2 * ⟪x, y⟫_ℝ + ∥y∥ * ∥y∥ := by { have h := @norm_sub_mul_self ℝ F _ _, simpa using h } /-- Cauchy–Schwarz inequality with norm -/ lemma abs_inner_le_norm (x y : E) : abs ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := nonneg_le_nonneg_of_sq_le_sq (mul_nonneg (norm_nonneg _) (norm_nonneg _)) begin have : ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥) = (re ⟪x, x⟫) * (re ⟪y, y⟫), simp only [inner_self_eq_norm_sq], ring, rw this, conv_lhs { congr, skip, rw [inner_abs_conj_sym] }, exact inner_mul_inner_self_le _ _ end lemma norm_inner_le_norm (x y : E) : ∥⟪x, y⟫∥ ≤ ∥x∥ * ∥y∥ := (is_R_or_C.norm_eq_abs _).le.trans (abs_inner_le_norm x y) /-- Cauchy–Schwarz inequality with norm -/ lemma abs_real_inner_le_norm (x y : F) : absR ⟪x, y⟫_ℝ ≤ ∥x∥ * ∥y∥ := by { have h := @abs_inner_le_norm ℝ F _ _ x y, simpa using h } /-- Cauchy–Schwarz inequality with norm -/ lemma real_inner_le_norm (x y : F) : ⟪x, y⟫_ℝ ≤ ∥x∥ * ∥y∥ := le_trans (le_abs_self _) (abs_real_inner_le_norm _ _) include 𝕜 lemma parallelogram_law_with_norm {x y : E} : ∥x + y∥ * ∥x + y∥ + ∥x - y∥ * ∥x - y∥ = 2 * (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥) := begin simp only [← inner_self_eq_norm_sq], rw[← re.map_add, parallelogram_law, two_mul, two_mul], simp only [re.map_add], end omit 𝕜 lemma parallelogram_law_with_norm_real {x y : F} : ∥x + y∥ * ∥x + y∥ + ∥x - y∥ * ∥x - y∥ = 2 * (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥) := by { have h := @parallelogram_law_with_norm ℝ F _ _ x y, simpa using h } /-- Polarization identity: The real part of the inner product, in terms of the norm. -/ lemma re_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two (x y : E) : re ⟪x, y⟫ = (∥x + y∥ * ∥x + y∥ - ∥x∥ * ∥x∥ - ∥y∥ * ∥y∥) / 2 := by { rw norm_add_mul_self, ring } /-- Polarization identity: The real part of the inner product, in terms of the norm. -/ lemma re_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two (x y : E) : re ⟪x, y⟫ = (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ - ∥x - y∥ * ∥x - y∥) / 2 := by { rw [norm_sub_mul_self], ring } /-- Polarization identity: The real part of the inner product, in terms of the norm. -/ lemma re_inner_eq_norm_add_mul_self_sub_norm_sub_mul_self_div_four (x y : E) : re ⟪x, y⟫ = (∥x + y∥ * ∥x + y∥ - ∥x - y∥ * ∥x - y∥) / 4 := by { rw [norm_add_mul_self, norm_sub_mul_self], ring } /-- Polarization identity: The imaginary part of the inner product, in terms of the norm. -/ lemma im_inner_eq_norm_sub_I_smul_mul_self_sub_norm_add_I_smul_mul_self_div_four (x y : E) : im ⟪x, y⟫ = (∥x - IK • y∥ * ∥x - IK • y∥ - ∥x + IK • y∥ * ∥x + IK • y∥) / 4 := by { simp only [norm_add_mul_self, norm_sub_mul_self, inner_smul_right, I_mul_re], ring } /-- Polarization identity: The inner product, in terms of the norm. -/ lemma inner_eq_sum_norm_sq_div_four (x y : E) : ⟪x, y⟫ = (∥x + y∥ ^ 2 - ∥x - y∥ ^ 2 + (∥x - IK • y∥ ^ 2 - ∥x + IK • y∥ ^ 2) * IK) / 4 := begin rw [← re_add_im ⟪x, y⟫, re_inner_eq_norm_add_mul_self_sub_norm_sub_mul_self_div_four, im_inner_eq_norm_sub_I_smul_mul_self_sub_norm_add_I_smul_mul_self_div_four], push_cast, simp only [sq, ← mul_div_right_comm, ← add_div] end section variables {E' : Type*} [inner_product_space 𝕜 E'] /-- A linear isometry preserves the inner product. -/ @[simp] lemma linear_isometry.inner_map_map (f : E →ₗᵢ[𝕜] E') (x y : E) : ⟪f x, f y⟫ = ⟪x, y⟫ := by simp [inner_eq_sum_norm_sq_div_four, ← f.norm_map] /-- A linear isometric equivalence preserves the inner product. -/ @[simp] lemma linear_isometry_equiv.inner_map_map (f : E ≃ₗᵢ[𝕜] E') (x y : E) : ⟪f x, f y⟫ = ⟪x, y⟫ := f.to_linear_isometry.inner_map_map x y /-- A linear map that preserves the inner product is a linear isometry. -/ def linear_map.isometry_of_inner (f : E →ₗ[𝕜] E') (h : ∀ x y, ⟪f x, f y⟫ = ⟪x, y⟫) : E →ₗᵢ[𝕜] E' := ⟨f, λ x, by simp only [norm_eq_sqrt_inner, h]⟩ @[simp] lemma linear_map.coe_isometry_of_inner (f : E →ₗ[𝕜] E') (h) : ⇑(f.isometry_of_inner h) = f := rfl @[simp] lemma linear_map.isometry_of_inner_to_linear_map (f : E →ₗ[𝕜] E') (h) : (f.isometry_of_inner h).to_linear_map = f := rfl /-- A linear equivalence that preserves the inner product is a linear isometric equivalence. -/ def linear_equiv.isometry_of_inner (f : E ≃ₗ[𝕜] E') (h : ∀ x y, ⟪f x, f y⟫ = ⟪x, y⟫) : E ≃ₗᵢ[𝕜] E' := ⟨f, ((f : E →ₗ[𝕜] E').isometry_of_inner h).norm_map⟩ @[simp] lemma linear_equiv.coe_isometry_of_inner (f : E ≃ₗ[𝕜] E') (h) : ⇑(f.isometry_of_inner h) = f := rfl @[simp] lemma linear_equiv.isometry_of_inner_to_linear_equiv (f : E ≃ₗ[𝕜] E') (h) : (f.isometry_of_inner h).to_linear_equiv = f := rfl end /-- Polarization identity: The real inner product, in terms of the norm. -/ lemma real_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two (x y : F) : ⟪x, y⟫_ℝ = (∥x + y∥ * ∥x + y∥ - ∥x∥ * ∥x∥ - ∥y∥ * ∥y∥) / 2 := re_to_real.symm.trans $ re_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two x y /-- Polarization identity: The real inner product, in terms of the norm. -/ lemma real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two (x y : F) : ⟪x, y⟫_ℝ = (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ - ∥x - y∥ * ∥x - y∥) / 2 := re_to_real.symm.trans $ re_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two x y /-- Pythagorean theorem, if-and-only-if vector inner product form. -/ lemma norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero (x y : F) : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ ↔ ⟪x, y⟫_ℝ = 0 := begin rw [norm_add_mul_self, add_right_cancel_iff, add_right_eq_self, mul_eq_zero], norm_num end /-- Pythagorean theorem, vector inner product form. -/ lemma norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero (x y : E) (h : ⟪x, y⟫ = 0) : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ := begin rw [norm_add_mul_self, add_right_cancel_iff, add_right_eq_self, mul_eq_zero], apply or.inr, simp only [h, zero_re'], end /-- Pythagorean theorem, vector inner product form. -/ lemma norm_add_sq_eq_norm_sq_add_norm_sq_real {x y : F} (h : ⟪x, y⟫_ℝ = 0) : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ := (norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero x y).2 h /-- Pythagorean theorem, subtracting vectors, if-and-only-if vector inner product form. -/ lemma norm_sub_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero (x y : F) : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ ↔ ⟪x, y⟫_ℝ = 0 := begin rw [norm_sub_mul_self, add_right_cancel_iff, sub_eq_add_neg, add_right_eq_self, neg_eq_zero, mul_eq_zero], norm_num end /-- Pythagorean theorem, subtracting vectors, vector inner product form. -/ lemma norm_sub_sq_eq_norm_sq_add_norm_sq_real {x y : F} (h : ⟪x, y⟫_ℝ = 0) : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ := (norm_sub_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero x y).2 h /-- The sum and difference of two vectors are orthogonal if and only if they have the same norm. -/ lemma real_inner_add_sub_eq_zero_iff (x y : F) : ⟪x + y, x - y⟫_ℝ = 0 ↔ ∥x∥ = ∥y∥ := begin conv_rhs { rw ←mul_self_inj_of_nonneg (norm_nonneg _) (norm_nonneg _) }, simp only [←inner_self_eq_norm_sq, inner_add_left, inner_sub_right, real_inner_comm y x, sub_eq_zero, re_to_real], split, { intro h, rw [add_comm] at h, linarith }, { intro h, linarith } end /-- Given two orthogonal vectors, their sum and difference have equal norms. -/ lemma norm_sub_eq_norm_add {v w : E} (h : ⟪v, w⟫ = 0) : ∥w - v∥ = ∥w + v∥ := begin rw ←mul_self_inj_of_nonneg (norm_nonneg _) (norm_nonneg _), simp [h, ←inner_self_eq_norm_sq, inner_add_left, inner_add_right, inner_sub_left, inner_sub_right, inner_re_symm] end /-- The real inner product of two vectors, divided by the product of their norms, has absolute value at most 1. -/ lemma abs_real_inner_div_norm_mul_norm_le_one (x y : F) : absR (⟪x, y⟫_ℝ / (∥x∥ * ∥y∥)) ≤ 1 := begin rw _root_.abs_div, by_cases h : 0 = absR (∥x∥ * ∥y∥), { rw [←h, div_zero], norm_num }, { change 0 ≠ absR (∥x∥ * ∥y∥) at h, rw div_le_iff' (lt_of_le_of_ne (ge_iff_le.mp (_root_.abs_nonneg (∥x∥ * ∥y∥))) h), convert abs_real_inner_le_norm x y using 1, rw [_root_.abs_mul, _root_.abs_of_nonneg (norm_nonneg x), _root_.abs_of_nonneg (norm_nonneg y), mul_one] } end /-- The inner product of a vector with a multiple of itself. -/ lemma real_inner_smul_self_left (x : F) (r : ℝ) : ⟪r • x, x⟫_ℝ = r * (∥x∥ * ∥x∥) := by rw [real_inner_smul_left, ←real_inner_self_eq_norm_sq] /-- The inner product of a vector with a multiple of itself. -/ lemma real_inner_smul_self_right (x : F) (r : ℝ) : ⟪x, r • x⟫_ℝ = r * (∥x∥ * ∥x∥) := by rw [inner_smul_right, ←real_inner_self_eq_norm_sq] /-- The inner product of a nonzero vector with a nonzero multiple of itself, divided by the product of their norms, has absolute value 1. -/ lemma abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul {x : E} {r : 𝕜} (hx : x ≠ 0) (hr : r ≠ 0) : abs ⟪x, r • x⟫ / (∥x∥ * ∥r • x∥) = 1 := begin have hx' : ∥x∥ ≠ 0 := by simp [norm_eq_zero, hx], have hr' : abs r ≠ 0 := by simp [is_R_or_C.abs_eq_zero, hr], rw [inner_smul_right, is_R_or_C.abs_mul, ←inner_self_re_abs, inner_self_eq_norm_sq, norm_smul], rw [is_R_or_C.norm_eq_abs, ←mul_assoc, ←div_div_eq_div_mul, mul_div_cancel _ hx', ←div_div_eq_div_mul, mul_comm, mul_div_cancel _ hr', div_self hx'], end /-- The inner product of a nonzero vector with a nonzero multiple of itself, divided by the product of their norms, has absolute value 1. -/ lemma abs_real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : r ≠ 0) : absR ⟪x, r • x⟫_ℝ / (∥x∥ * ∥r • x∥) = 1 := begin rw ← abs_to_real, exact abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul hx hr end /-- The inner product of a nonzero vector with a positive multiple of itself, divided by the product of their norms, has value 1. -/ lemma real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : 0 < r) : ⟪x, r • x⟫_ℝ / (∥x∥ * ∥r • x∥) = 1 := begin rw [real_inner_smul_self_right, norm_smul, real.norm_eq_abs, ←mul_assoc ∥x∥, mul_comm _ (absR r), mul_assoc, _root_.abs_of_nonneg (le_of_lt hr), div_self], exact mul_ne_zero (ne_of_gt hr) (λ h, hx (norm_eq_zero.1 (eq_zero_of_mul_self_eq_zero h))) end /-- The inner product of a nonzero vector with a negative multiple of itself, divided by the product of their norms, has value -1. -/ lemma real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : r < 0) : ⟪x, r • x⟫_ℝ / (∥x∥ * ∥r • x∥) = -1 := begin rw [real_inner_smul_self_right, norm_smul, real.norm_eq_abs, ←mul_assoc ∥x∥, mul_comm _ (absR r), mul_assoc, abs_of_neg hr, ←neg_mul_eq_neg_mul, div_neg_eq_neg_div, div_self], exact mul_ne_zero (ne_of_lt hr) (λ h, hx (norm_eq_zero.1 (eq_zero_of_mul_self_eq_zero h))) end /-- The inner product of two vectors, divided by the product of their norms, has absolute value 1 if and only if they are nonzero and one is a multiple of the other. One form of equality case for Cauchy-Schwarz. -/ lemma abs_inner_div_norm_mul_norm_eq_one_iff (x y : E) : abs (⟪x, y⟫ / (∥x∥ * ∥y∥)) = 1 ↔ (x ≠ 0 ∧ ∃ (r : 𝕜), r ≠ 0 ∧ y = r • x) := begin split, { intro h, have hx0 : x ≠ 0, { intro hx0, rw [hx0, inner_zero_left, zero_div] at h, norm_num at h, }, refine and.intro hx0 _, set r := ⟪x, y⟫ / (∥x∥ * ∥x∥) with hr, use r, set t := y - r • x with ht, have ht0 : ⟪x, t⟫ = 0, { rw [ht, inner_sub_right, inner_smul_right, hr], norm_cast, rw [←inner_self_eq_norm_sq, inner_self_re_to_K, div_mul_cancel _ (λ h, hx0 (inner_self_eq_zero.1 h)), sub_self] }, replace h : ∥r • x∥ / ∥t + r • x∥ = 1, { rw [←sub_add_cancel y (r • x), ←ht, inner_add_right, ht0, zero_add, inner_smul_right, is_R_or_C.abs_div, is_R_or_C.abs_mul, ←inner_self_re_abs, inner_self_eq_norm_sq] at h, norm_cast at h, rwa [_root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm, ←mul_assoc, mul_comm, mul_div_mul_left _ _ (λ h, hx0 (norm_eq_zero.1 h)), ←is_R_or_C.norm_eq_abs, ←norm_smul] at h }, have hr0 : r ≠ 0, { intro hr0, rw [hr0, zero_smul, norm_zero, zero_div] at h, norm_num at h }, refine and.intro hr0 _, have h2 : ∥r • x∥ ^ 2 = ∥t + r • x∥ ^ 2, { rw [eq_of_div_eq_one h] }, replace h2 : ⟪r • x, r • x⟫ = ⟪t, t⟫ + ⟪t, r • x⟫ + ⟪r • x, t⟫ + ⟪r • x, r • x⟫, { rw [sq, sq, ←inner_self_eq_norm_sq, ←inner_self_eq_norm_sq ] at h2, have h2' := congr_arg (λ z : ℝ, (z : 𝕜)) h2, simp_rw [inner_self_re_to_K, inner_add_add_self] at h2', exact h2' }, conv at h2 in ⟪r • x, t⟫ { rw [inner_smul_left, ht0, mul_zero] }, symmetry' at h2, have h₁ : ⟪t, r • x⟫ = 0 := by { rw [inner_smul_right, ←inner_conj_sym, ht0], simp }, rw [add_zero, h₁, add_left_eq_self, add_zero, inner_self_eq_zero] at h2, rw h2 at ht, exact eq_of_sub_eq_zero ht.symm }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw [hy, is_R_or_C.abs_div], norm_cast, rw [_root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm], exact abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul hx hr } end /-- The inner product of two vectors, divided by the product of their norms, has absolute value 1 if and only if they are nonzero and one is a multiple of the other. One form of equality case for Cauchy-Schwarz. -/ lemma abs_real_inner_div_norm_mul_norm_eq_one_iff (x y : F) : absR (⟪x, y⟫_ℝ / (∥x∥ * ∥y∥)) = 1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r ≠ 0 ∧ y = r • x) := begin have := @abs_inner_div_norm_mul_norm_eq_one_iff ℝ F _ _ x y, simpa [coe_real_eq_id] using this, end /-- If the inner product of two vectors is equal to the product of their norms, then the two vectors are multiples of each other. One form of the equality case for Cauchy-Schwarz. Compare `inner_eq_norm_mul_iff`, which takes the stronger hypothesis `⟪x, y⟫ = ∥x∥ * ∥y∥`. -/ lemma abs_inner_eq_norm_iff (x y : E) (hx0 : x ≠ 0) (hy0 : y ≠ 0): abs ⟪x, y⟫ = ∥x∥ * ∥y∥ ↔ ∃ (r : 𝕜), r ≠ 0 ∧ y = r • x := begin have hx0' : ∥x∥ ≠ 0 := by simp [norm_eq_zero, hx0], have hy0' : ∥y∥ ≠ 0 := by simp [norm_eq_zero, hy0], have hxy0 : ∥x∥ * ∥y∥ ≠ 0 := by simp [hx0', hy0'], have h₁ : abs ⟪x, y⟫ = ∥x∥ * ∥y∥ ↔ abs (⟪x, y⟫ / (∥x∥ * ∥y∥)) = 1, { refine ⟨_ ,_⟩, { intro h, norm_cast, rw [is_R_or_C.abs_div, h, abs_of_real, _root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm], exact div_self hxy0 }, { intro h, norm_cast at h, rwa [is_R_or_C.abs_div, abs_of_real, _root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm, div_eq_one_iff_eq hxy0] at h } }, rw [h₁, abs_inner_div_norm_mul_norm_eq_one_iff x y], have : x ≠ 0 := λ h, (hx0' $ norm_eq_zero.mpr h), simp [this] end /-- The inner product of two vectors, divided by the product of their norms, has value 1 if and only if they are nonzero and one is a positive multiple of the other. -/ lemma real_inner_div_norm_mul_norm_eq_one_iff (x y : F) : ⟪x, y⟫_ℝ / (∥x∥ * ∥y∥) = 1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), 0 < r ∧ y = r • x) := begin split, { intro h, have ha := h, apply_fun absR at ha, norm_num at ha, rcases (abs_real_inner_div_norm_mul_norm_eq_one_iff x y).1 ha with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, use [hx, r], refine and.intro _ hy, by_contradiction hrneg, rw hy at h, rw real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul hx (lt_of_le_of_ne (le_of_not_lt hrneg) hr) at h, norm_num at h }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw hy, exact real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul hx hr } end /-- The inner product of two vectors, divided by the product of their norms, has value -1 if and only if they are nonzero and one is a negative multiple of the other. -/ lemma real_inner_div_norm_mul_norm_eq_neg_one_iff (x y : F) : ⟪x, y⟫_ℝ / (∥x∥ * ∥y∥) = -1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r < 0 ∧ y = r • x) := begin split, { intro h, have ha := h, apply_fun absR at ha, norm_num at ha, rcases (abs_real_inner_div_norm_mul_norm_eq_one_iff x y).1 ha with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, use [hx, r], refine and.intro _ hy, by_contradiction hrpos, rw hy at h, rw real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul hx (lt_of_le_of_ne (le_of_not_lt hrpos) hr.symm) at h, norm_num at h }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw hy, exact real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul hx hr } end /-- If the inner product of two vectors is equal to the product of their norms (i.e., `⟪x, y⟫ = ∥x∥ * ∥y∥`), then the two vectors are nonnegative real multiples of each other. One form of the equality case for Cauchy-Schwarz. Compare `abs_inner_eq_norm_iff`, which takes the weaker hypothesis `abs ⟪x, y⟫ = ∥x∥ * ∥y∥`. -/ lemma inner_eq_norm_mul_iff {x y : E} : ⟪x, y⟫ = (∥x∥ : 𝕜) * ∥y∥ ↔ (∥y∥ : 𝕜) • x = (∥x∥ : 𝕜) • y := begin by_cases h : (x = 0 ∨ y = 0), -- WLOG `x` and `y` are nonzero { cases h; simp [h] }, calc ⟪x, y⟫ = (∥x∥ : 𝕜) * ∥y∥ ↔ ∥x∥ * ∥y∥ = re ⟪x, y⟫ : begin norm_cast, split, { intros h', simp [h'] }, { have cauchy_schwarz := abs_inner_le_norm x y, intros h', rw h' at ⊢ cauchy_schwarz, rwa re_eq_self_of_le } end ... ↔ 2 * ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥ - re ⟪x, y⟫) = 0 : by simp [h, show (2:ℝ) ≠ 0, by norm_num, sub_eq_zero] ... ↔ ∥(∥y∥:𝕜) • x - (∥x∥:𝕜) • y∥ * ∥(∥y∥:𝕜) • x - (∥x∥:𝕜) • y∥ = 0 : begin simp only [norm_sub_mul_self, inner_smul_left, inner_smul_right, norm_smul, conj_of_real, is_R_or_C.norm_eq_abs, abs_of_real, of_real_im, of_real_re, mul_re, abs_norm_eq_norm], refine eq.congr _ rfl, ring end ... ↔ (∥y∥ : 𝕜) • x = (∥x∥ : 𝕜) • y : by simp [norm_sub_eq_zero_iff] end /-- If the inner product of two vectors is equal to the product of their norms (i.e., `⟪x, y⟫ = ∥x∥ * ∥y∥`), then the two vectors are nonnegative real multiples of each other. One form of the equality case for Cauchy-Schwarz. Compare `abs_inner_eq_norm_iff`, which takes the weaker hypothesis `abs ⟪x, y⟫ = ∥x∥ * ∥y∥`. -/ lemma inner_eq_norm_mul_iff_real {x y : F} : ⟪x, y⟫_ℝ = ∥x∥ * ∥y∥ ↔ ∥y∥ • x = ∥x∥ • y := inner_eq_norm_mul_iff /-- If the inner product of two unit vectors is `1`, then the two vectors are equal. One form of the equality case for Cauchy-Schwarz. -/ lemma inner_eq_norm_mul_iff_of_norm_one {x y : E} (hx : ∥x∥ = 1) (hy : ∥y∥ = 1) : ⟪x, y⟫ = 1 ↔ x = y := by { convert inner_eq_norm_mul_iff using 2; simp [hx, hy] } lemma inner_lt_norm_mul_iff_real {x y : F} : ⟪x, y⟫_ℝ < ∥x∥ * ∥y∥ ↔ ∥y∥ • x ≠ ∥x∥ • y := calc ⟪x, y⟫_ℝ < ∥x∥ * ∥y∥ ↔ ⟪x, y⟫_ℝ ≠ ∥x∥ * ∥y∥ : ⟨ne_of_lt, lt_of_le_of_ne (real_inner_le_norm _ _)⟩ ... ↔ ∥y∥ • x ≠ ∥x∥ • y : not_congr inner_eq_norm_mul_iff_real /-- If the inner product of two unit vectors is strictly less than `1`, then the two vectors are distinct. One form of the equality case for Cauchy-Schwarz. -/ lemma inner_lt_one_iff_real_of_norm_one {x y : F} (hx : ∥x∥ = 1) (hy : ∥y∥ = 1) : ⟪x, y⟫_ℝ < 1 ↔ x ≠ y := by { convert inner_lt_norm_mul_iff_real; simp [hx, hy] } /-- The inner product of two weighted sums, where the weights in each sum add to 0, in terms of the norms of pairwise differences. -/ lemma inner_sum_smul_sum_smul_of_sum_eq_zero {ι₁ : Type*} {s₁ : finset ι₁} {w₁ : ι₁ → ℝ} (v₁ : ι₁ → F) (h₁ : ∑ i in s₁, w₁ i = 0) {ι₂ : Type*} {s₂ : finset ι₂} {w₂ : ι₂ → ℝ} (v₂ : ι₂ → F) (h₂ : ∑ i in s₂, w₂ i = 0) : ⟪(∑ i₁ in s₁, w₁ i₁ • v₁ i₁), (∑ i₂ in s₂, w₂ i₂ • v₂ i₂)⟫_ℝ = (-∑ i₁ in s₁, ∑ i₂ in s₂, w₁ i₁ * w₂ i₂ * (∥v₁ i₁ - v₂ i₂∥ * ∥v₁ i₁ - v₂ i₂∥)) / 2 := by simp_rw [sum_inner, inner_sum, real_inner_smul_left, real_inner_smul_right, real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two, ←div_sub_div_same, ←div_add_div_same, mul_sub_left_distrib, left_distrib, finset.sum_sub_distrib, finset.sum_add_distrib, ←finset.mul_sum, ←finset.sum_mul, h₁, h₂, zero_mul, mul_zero, finset.sum_const_zero, zero_add, zero_sub, finset.mul_sum, neg_div, finset.sum_div, mul_div_assoc, mul_assoc] /-- The inner product with a fixed left element, as a continuous linear map. This can be upgraded to a continuous map which is jointly conjugate-linear in the left argument and linear in the right argument, once (TODO) conjugate-linear maps have been defined. -/ def inner_right (v : E) : E →L[𝕜] 𝕜 := linear_map.mk_continuous { to_fun := λ w, ⟪v, w⟫, map_add' := λ x y, inner_add_right, map_smul' := λ c x, inner_smul_right } ∥v∥ (by simpa using norm_inner_le_norm v) @[simp] lemma inner_right_coe (v : E) : (inner_right v : E → 𝕜) = λ w, ⟪v, w⟫ := rfl @[simp] lemma inner_right_apply (v w : E) : inner_right v w = ⟪v, w⟫ := rfl end norm section bessels_inequality variables {ι: Type*} (x : E) {v : ι → E} /-- Bessel's inequality for finite sums. -/ lemma orthonormal.sum_inner_products_le {s : finset ι} (hv : orthonormal 𝕜 v) : ∑ i in s, ∥⟪v i, x⟫∥ ^ 2 ≤ ∥x∥ ^ 2 := begin have h₂ : ∑ i in s, ∑ j in s, ⟪v i, x⟫ * ⟪x, v j⟫ * ⟪v j, v i⟫ = (∑ k in s, (⟪v k, x⟫ * ⟪x, v k⟫) : 𝕜), { exact hv.inner_left_right_finset }, have h₃ : ∀ z : 𝕜, re (z * conj (z)) = ∥z∥ ^ 2, { intro z, simp only [mul_conj, norm_sq_eq_def'], norm_cast, }, suffices hbf: ∥x - ∑ i in s, ⟪v i, x⟫ • (v i)∥ ^ 2 = ∥x∥ ^ 2 - ∑ i in s, ∥⟪v i, x⟫∥ ^ 2, { rw [←sub_nonneg, ←hbf], simp only [norm_nonneg, pow_nonneg], }, rw [norm_sub_sq, sub_add], simp only [inner_product_space.norm_sq_eq_inner, inner_sum], simp only [sum_inner, two_mul, inner_smul_right, inner_conj_sym, ←mul_assoc, h₂, ←h₃, inner_conj_sym, add_monoid_hom.map_sum, finset.mul_sum, ←finset.sum_sub_distrib, inner_smul_left, add_sub_cancel'], end /-- Bessel's inequality. -/ lemma orthonormal.tsum_inner_products_le (hv : orthonormal 𝕜 v) : ∑' i, ∥⟪v i, x⟫∥ ^ 2 ≤ ∥x∥ ^ 2 := begin refine tsum_le_of_sum_le' _ (λ s, hv.sum_inner_products_le x), simp only [norm_nonneg, pow_nonneg] end /-- The sum defined in Bessel's inequality is summable. -/ lemma orthonormal.inner_products_summable (hv : orthonormal 𝕜 v) : summable (λ i, ∥⟪v i, x⟫∥ ^ 2) := begin use ⨆ s : finset ι, ∑ i in s, ∥⟪v i, x⟫∥ ^ 2, apply has_sum_of_is_lub_of_nonneg, { intro b, simp only [norm_nonneg, pow_nonneg], }, { refine is_lub_csupr _, use ∥x∥ ^ 2, rintro y ⟨s, rfl⟩, exact hv.sum_inner_products_le x } end end bessels_inequality /-- A field `𝕜` satisfying `is_R_or_C` is itself a `𝕜`-inner product space. -/ instance is_R_or_C.inner_product_space : inner_product_space 𝕜 𝕜 := { inner := (λ x y, (conj x) * y), norm_sq_eq_inner := λ x, by { unfold inner, rw [mul_comm, mul_conj, of_real_re, norm_sq_eq_def'] }, conj_sym := λ x y, by simp [mul_comm], add_left := λ x y z, by simp [inner, add_mul], smul_left := λ x y z, by simp [inner, mul_assoc] } @[simp] lemma is_R_or_C.inner_apply (x y : 𝕜) : ⟪x, y⟫ = (conj x) * y := rfl /-! ### Inner product space structure on subspaces -/ /-- Induced inner product on a submodule. -/ instance submodule.inner_product_space (W : submodule 𝕜 E) : inner_product_space 𝕜 W := { inner := λ x y, ⟪(x:E), (y:E)⟫, conj_sym := λ _ _, inner_conj_sym _ _ , norm_sq_eq_inner := λ _, norm_sq_eq_inner _, add_left := λ _ _ _ , inner_add_left, smul_left := λ _ _ _, inner_smul_left, ..submodule.normed_space W } /-- The inner product on submodules is the same as on the ambient space. -/ @[simp] lemma submodule.coe_inner (W : submodule 𝕜 E) (x y : W) : ⟪x, y⟫ = ⟪(x:E), ↑y⟫ := rfl section is_R_or_C_to_real variables {G : Type*} variables (𝕜 E) include 𝕜 /-- A general inner product implies a real inner product. This is not registered as an instance since it creates problems with the case `𝕜 = ℝ`. -/ def has_inner.is_R_or_C_to_real : has_inner ℝ E := { inner := λ x y, re ⟪x, y⟫ } /-- A general inner product space structure implies a real inner product structure. This is not registered as an instance since it creates problems with the case `𝕜 = ℝ`, but in can be used in a proof to obtain a real inner product space structure from a given `𝕜`-inner product space structure. -/ def inner_product_space.is_R_or_C_to_real : inner_product_space ℝ E := { norm_sq_eq_inner := norm_sq_eq_inner, conj_sym := λ x y, inner_re_symm, add_left := λ x y z, by { change re ⟪x + y, z⟫ = re ⟪x, z⟫ + re ⟪y, z⟫, simp [inner_add_left] }, smul_left := λ x y r, by { change re ⟪(r : 𝕜) • x, y⟫ = r * re ⟪x, y⟫, simp [inner_smul_left] }, ..has_inner.is_R_or_C_to_real 𝕜 E, ..normed_space.restrict_scalars ℝ 𝕜 E } variable {E} lemma real_inner_eq_re_inner (x y : E) : @has_inner.inner ℝ E (has_inner.is_R_or_C_to_real 𝕜 E) x y = re ⟪x, y⟫ := rfl lemma real_inner_I_smul_self (x : E) : @has_inner.inner ℝ E (has_inner.is_R_or_C_to_real 𝕜 E) x ((I : 𝕜) • x) = 0 := by simp [real_inner_eq_re_inner, inner_smul_right] omit 𝕜 /-- A complex inner product implies a real inner product -/ instance inner_product_space.complex_to_real [inner_product_space ℂ G] : inner_product_space ℝ G := inner_product_space.is_R_or_C_to_real ℂ G end is_R_or_C_to_real section deriv /-! ### Derivative of the inner product In this section we prove that the inner product and square of the norm in an inner space are infinitely `ℝ`-smooth. In order to state these results, we need a `normed_space ℝ E` instance. Though we can deduce this structure from `inner_product_space 𝕜 E`, this instance may be not definitionally equal to some other “natural” instance. So, we assume `[normed_space ℝ E]` and `[is_scalar_tower ℝ 𝕜 E]`. In both interesting cases `𝕜 = ℝ` and `𝕜 = ℂ` we have these instances. -/ variables [normed_space ℝ E] [is_scalar_tower ℝ 𝕜 E] lemma is_bounded_bilinear_map_inner : is_bounded_bilinear_map ℝ (λ p : E × E, ⟪p.1, p.2⟫) := { add_left := λ _ _ _, inner_add_left, smul_left := λ r x y, by simp only [← algebra_map_smul 𝕜 r x, algebra_map_eq_of_real, inner_smul_real_left], add_right := λ _ _ _, inner_add_right, smul_right := λ r x y, by simp only [← algebra_map_smul 𝕜 r y, algebra_map_eq_of_real, inner_smul_real_right], bound := ⟨1, zero_lt_one, λ x y, by { rw [one_mul], exact norm_inner_le_norm x y, }⟩ } /-- Derivative of the inner product. -/ def fderiv_inner_clm (p : E × E) : E × E →L[ℝ] 𝕜 := is_bounded_bilinear_map_inner.deriv p @[simp] lemma fderiv_inner_clm_apply (p x : E × E) : fderiv_inner_clm p x = ⟪p.1, x.2⟫ + ⟪x.1, p.2⟫ := rfl lemma times_cont_diff_inner {n} : times_cont_diff ℝ n (λ p : E × E, ⟪p.1, p.2⟫) := is_bounded_bilinear_map_inner.times_cont_diff lemma times_cont_diff_at_inner {p : E × E} {n} : times_cont_diff_at ℝ n (λ p : E × E, ⟪p.1, p.2⟫) p := times_cont_diff_inner.times_cont_diff_at lemma differentiable_inner : differentiable ℝ (λ p : E × E, ⟪p.1, p.2⟫) := is_bounded_bilinear_map_inner.differentiable_at variables {G : Type*} [normed_group G] [normed_space ℝ G] {f g : G → E} {f' g' : G →L[ℝ] E} {s : set G} {x : G} {n : with_top ℕ} include 𝕜 lemma times_cont_diff_within_at.inner (hf : times_cont_diff_within_at ℝ n f s x) (hg : times_cont_diff_within_at ℝ n g s x) : times_cont_diff_within_at ℝ n (λ x, ⟪f x, g x⟫) s x := times_cont_diff_at_inner.comp_times_cont_diff_within_at x (hf.prod hg) lemma times_cont_diff_at.inner (hf : times_cont_diff_at ℝ n f x) (hg : times_cont_diff_at ℝ n g x) : times_cont_diff_at ℝ n (λ x, ⟪f x, g x⟫) x := hf.inner hg lemma times_cont_diff_on.inner (hf : times_cont_diff_on ℝ n f s) (hg : times_cont_diff_on ℝ n g s) : times_cont_diff_on ℝ n (λ x, ⟪f x, g x⟫) s := λ x hx, (hf x hx).inner (hg x hx) lemma times_cont_diff.inner (hf : times_cont_diff ℝ n f) (hg : times_cont_diff ℝ n g) : times_cont_diff ℝ n (λ x, ⟪f x, g x⟫) := times_cont_diff_inner.comp (hf.prod hg) lemma has_fderiv_within_at.inner (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ t, ⟪f t, g t⟫) ((fderiv_inner_clm (f x, g x)).comp $ f'.prod g') s x := (is_bounded_bilinear_map_inner.has_fderiv_at (f x, g x)).comp_has_fderiv_within_at x (hf.prod hg) lemma has_fderiv_at.inner (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ t, ⟪f t, g t⟫) ((fderiv_inner_clm (f x, g x)).comp $ f'.prod g') x := (is_bounded_bilinear_map_inner.has_fderiv_at (f x, g x)).comp x (hf.prod hg) lemma has_deriv_within_at.inner {f g : ℝ → E} {f' g' : E} {s : set ℝ} {x : ℝ} (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) : has_deriv_within_at (λ t, ⟪f t, g t⟫) (⟪f x, g'⟫ + ⟪f', g x⟫) s x := by simpa using (hf.has_fderiv_within_at.inner hg.has_fderiv_within_at).has_deriv_within_at lemma has_deriv_at.inner {f g : ℝ → E} {f' g' : E} {x : ℝ} : has_deriv_at f f' x → has_deriv_at g g' x → has_deriv_at (λ t, ⟪f t, g t⟫) (⟪f x, g'⟫ + ⟪f', g x⟫) x := by simpa only [← has_deriv_within_at_univ] using has_deriv_within_at.inner lemma differentiable_within_at.inner (hf : differentiable_within_at ℝ f s x) (hg : differentiable_within_at ℝ g s x) : differentiable_within_at ℝ (λ x, ⟪f x, g x⟫) s x := ((differentiable_inner _).has_fderiv_at.comp_has_fderiv_within_at x (hf.prod hg).has_fderiv_within_at).differentiable_within_at lemma differentiable_at.inner (hf : differentiable_at ℝ f x) (hg : differentiable_at ℝ g x) : differentiable_at ℝ (λ x, ⟪f x, g x⟫) x := (differentiable_inner _).comp x (hf.prod hg) lemma differentiable_on.inner (hf : differentiable_on ℝ f s) (hg : differentiable_on ℝ g s) : differentiable_on ℝ (λ x, ⟪f x, g x⟫) s := λ x hx, (hf x hx).inner (hg x hx) lemma differentiable.inner (hf : differentiable ℝ f) (hg : differentiable ℝ g) : differentiable ℝ (λ x, ⟪f x, g x⟫) := λ x, (hf x).inner (hg x) lemma fderiv_inner_apply (hf : differentiable_at ℝ f x) (hg : differentiable_at ℝ g x) (y : G) : fderiv ℝ (λ t, ⟪f t, g t⟫) x y = ⟪f x, fderiv ℝ g x y⟫ + ⟪fderiv ℝ f x y, g x⟫ := by { rw [(hf.has_fderiv_at.inner hg.has_fderiv_at).fderiv], refl } lemma deriv_inner_apply {f g : ℝ → E} {x : ℝ} (hf : differentiable_at ℝ f x) (hg : differentiable_at ℝ g x) : deriv (λ t, ⟪f t, g t⟫) x = ⟪f x, deriv g x⟫ + ⟪deriv f x, g x⟫ := (hf.has_deriv_at.inner hg.has_deriv_at).deriv lemma times_cont_diff_norm_sq : times_cont_diff ℝ n (λ x : E, ∥x∥ ^ 2) := begin simp only [sq, ← inner_self_eq_norm_sq], exact (re_clm : 𝕜 →L[ℝ] ℝ).times_cont_diff.comp (times_cont_diff_id.inner times_cont_diff_id) end lemma times_cont_diff.norm_sq (hf : times_cont_diff ℝ n f) : times_cont_diff ℝ n (λ x, ∥f x∥ ^ 2) := times_cont_diff_norm_sq.comp hf lemma times_cont_diff_within_at.norm_sq (hf : times_cont_diff_within_at ℝ n f s x) : times_cont_diff_within_at ℝ n (λ y, ∥f y∥ ^ 2) s x := times_cont_diff_norm_sq.times_cont_diff_at.comp_times_cont_diff_within_at x hf lemma times_cont_diff_at.norm_sq (hf : times_cont_diff_at ℝ n f x) : times_cont_diff_at ℝ n (λ y, ∥f y∥ ^ 2) x := hf.norm_sq lemma times_cont_diff_at_norm {x : E} (hx : x ≠ 0) : times_cont_diff_at ℝ n norm x := have ∥id x∥ ^ 2 ≠ 0, from pow_ne_zero _ (norm_pos_iff.2 hx).ne', by simpa only [id, sqrt_sq, norm_nonneg] using times_cont_diff_at_id.norm_sq.sqrt this lemma times_cont_diff_at.norm (hf : times_cont_diff_at ℝ n f x) (h0 : f x ≠ 0) : times_cont_diff_at ℝ n (λ y, ∥f y∥) x := (times_cont_diff_at_norm h0).comp x hf lemma times_cont_diff_at.dist (hf : times_cont_diff_at ℝ n f x) (hg : times_cont_diff_at ℝ n g x) (hne : f x ≠ g x) : times_cont_diff_at ℝ n (λ y, dist (f y) (g y)) x := by { simp only [dist_eq_norm], exact (hf.sub hg).norm (sub_ne_zero.2 hne) } lemma times_cont_diff_within_at.norm (hf : times_cont_diff_within_at ℝ n f s x) (h0 : f x ≠ 0) : times_cont_diff_within_at ℝ n (λ y, ∥f y∥) s x := (times_cont_diff_at_norm h0).comp_times_cont_diff_within_at x hf lemma times_cont_diff_within_at.dist (hf : times_cont_diff_within_at ℝ n f s x) (hg : times_cont_diff_within_at ℝ n g s x) (hne : f x ≠ g x) : times_cont_diff_within_at ℝ n (λ y, dist (f y) (g y)) s x := by { simp only [dist_eq_norm], exact (hf.sub hg).norm (sub_ne_zero.2 hne) } lemma times_cont_diff_on.norm_sq (hf : times_cont_diff_on ℝ n f s) : times_cont_diff_on ℝ n (λ y, ∥f y∥ ^ 2) s := (λ x hx, (hf x hx).norm_sq) lemma times_cont_diff_on.norm (hf : times_cont_diff_on ℝ n f s) (h0 : ∀ x ∈ s, f x ≠ 0) : times_cont_diff_on ℝ n (λ y, ∥f y∥) s := λ x hx, (hf x hx).norm (h0 x hx) lemma times_cont_diff_on.dist (hf : times_cont_diff_on ℝ n f s) (hg : times_cont_diff_on ℝ n g s) (hne : ∀ x ∈ s, f x ≠ g x) : times_cont_diff_on ℝ n (λ y, dist (f y) (g y)) s := λ x hx, (hf x hx).dist (hg x hx) (hne x hx) lemma times_cont_diff.norm (hf : times_cont_diff ℝ n f) (h0 : ∀ x, f x ≠ 0) : times_cont_diff ℝ n (λ y, ∥f y∥) := times_cont_diff_iff_times_cont_diff_at.2 $ λ x, hf.times_cont_diff_at.norm (h0 x) lemma times_cont_diff.dist (hf : times_cont_diff ℝ n f) (hg : times_cont_diff ℝ n g) (hne : ∀ x, f x ≠ g x) : times_cont_diff ℝ n (λ y, dist (f y) (g y)) := times_cont_diff_iff_times_cont_diff_at.2 $ λ x, hf.times_cont_diff_at.dist hg.times_cont_diff_at (hne x) lemma differentiable_at.norm_sq (hf : differentiable_at ℝ f x) : differentiable_at ℝ (λ y, ∥f y∥ ^ 2) x := (times_cont_diff_at_id.norm_sq.differentiable_at le_rfl).comp x hf lemma differentiable_at.norm (hf : differentiable_at ℝ f x) (h0 : f x ≠ 0) : differentiable_at ℝ (λ y, ∥f y∥) x := ((times_cont_diff_at_norm h0).differentiable_at le_rfl).comp x hf lemma differentiable_at.dist (hf : differentiable_at ℝ f x) (hg : differentiable_at ℝ g x) (hne : f x ≠ g x) : differentiable_at ℝ (λ y, dist (f y) (g y)) x := by { simp only [dist_eq_norm], exact (hf.sub hg).norm (sub_ne_zero.2 hne) } lemma differentiable.norm_sq (hf : differentiable ℝ f) : differentiable ℝ (λ y, ∥f y∥ ^ 2) := λ x, (hf x).norm_sq lemma differentiable.norm (hf : differentiable ℝ f) (h0 : ∀ x, f x ≠ 0) : differentiable ℝ (λ y, ∥f y∥) := λ x, (hf x).norm (h0 x) lemma differentiable.dist (hf : differentiable ℝ f) (hg : differentiable ℝ g) (hne : ∀ x, f x ≠ g x) : differentiable ℝ (λ y, dist (f y) (g y)) := λ x, (hf x).dist (hg x) (hne x) lemma differentiable_within_at.norm_sq (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ y, ∥f y∥ ^ 2) s x := (times_cont_diff_at_id.norm_sq.differentiable_at le_rfl).comp_differentiable_within_at x hf lemma differentiable_within_at.norm (hf : differentiable_within_at ℝ f s x) (h0 : f x ≠ 0) : differentiable_within_at ℝ (λ y, ∥f y∥) s x := ((times_cont_diff_at_id.norm h0).differentiable_at le_rfl).comp_differentiable_within_at x hf lemma differentiable_within_at.dist (hf : differentiable_within_at ℝ f s x) (hg : differentiable_within_at ℝ g s x) (hne : f x ≠ g x) : differentiable_within_at ℝ (λ y, dist (f y) (g y)) s x := by { simp only [dist_eq_norm], exact (hf.sub hg).norm (sub_ne_zero.2 hne) } lemma differentiable_on.norm_sq (hf : differentiable_on ℝ f s) : differentiable_on ℝ (λ y, ∥f y∥ ^ 2) s := λ x hx, (hf x hx).norm_sq lemma differentiable_on.norm (hf : differentiable_on ℝ f s) (h0 : ∀ x ∈ s, f x ≠ 0) : differentiable_on ℝ (λ y, ∥f y∥) s := λ x hx, (hf x hx).norm (h0 x hx) lemma differentiable_on.dist (hf : differentiable_on ℝ f s) (hg : differentiable_on ℝ g s) (hne : ∀ x ∈ s, f x ≠ g x) : differentiable_on ℝ (λ y, dist (f y) (g y)) s := λ x hx, (hf x hx).dist (hg x hx) (hne x hx) end deriv section continuous /-! ### Continuity of the inner product Since the inner product is `ℝ`-smooth, it is continuous. We do not need a `[normed_space ℝ E]` structure to *state* this fact and its corollaries, so we introduce them in the proof instead. -/ lemma continuous_inner : continuous (λ p : E × E, ⟪p.1, p.2⟫) := begin letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜 E, letI : is_scalar_tower ℝ 𝕜 E := restrict_scalars.is_scalar_tower _ _ _, exact differentiable_inner.continuous end variables {α : Type*} lemma filter.tendsto.inner {f g : α → E} {l : filter α} {x y : E} (hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) : tendsto (λ t, ⟪f t, g t⟫) l (𝓝 ⟪x, y⟫) := (continuous_inner.tendsto _).comp (hf.prod_mk_nhds hg) variables [topological_space α] {f g : α → E} {x : α} {s : set α} include 𝕜 lemma continuous_within_at.inner (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (λ t, ⟪f t, g t⟫) s x := hf.inner hg lemma continuous_at.inner (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λ t, ⟪f t, g t⟫) x := hf.inner hg lemma continuous_on.inner (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λ t, ⟪f t, g t⟫) s := λ x hx, (hf x hx).inner (hg x hx) lemma continuous.inner (hf : continuous f) (hg : continuous g) : continuous (λ t, ⟪f t, g t⟫) := continuous_iff_continuous_at.2 $ λ x, hf.continuous_at.inner hg.continuous_at end continuous /-! ### Orthogonal projection in inner product spaces -/ section orthogonal open filter /-- Existence of minimizers Let `u` be a point in a real inner product space, and let `K` be a nonempty complete convex subset. Then there exists a (unique) `v` in `K` that minimizes the distance `∥u - v∥` to `u`. -/ -- FIXME this monolithic proof causes a deterministic timeout with `-T50000` -- It should be broken in a sequence of more manageable pieces, -- perhaps with individual statements for the three steps below. theorem exists_norm_eq_infi_of_complete_convex {K : set F} (ne : K.nonempty) (h₁ : is_complete K) (h₂ : convex K) : ∀ u : F, ∃ v ∈ K, ∥u - v∥ = ⨅ w : K, ∥u - w∥ := assume u, begin let δ := ⨅ w : K, ∥u - w∥, letI : nonempty K := ne.to_subtype, have zero_le_δ : 0 ≤ δ := le_cinfi (λ _, norm_nonneg _), have δ_le : ∀ w : K, δ ≤ ∥u - w∥, from cinfi_le ⟨0, set.forall_range_iff.2 $ λ _, norm_nonneg _⟩, have δ_le' : ∀ w ∈ K, δ ≤ ∥u - w∥ := assume w hw, δ_le ⟨w, hw⟩, -- Step 1: since `δ` is the infimum, can find a sequence `w : ℕ → K` in `K` -- such that `∥u - w n∥ < δ + 1 / (n + 1)` (which implies `∥u - w n∥ --> δ`); -- maybe this should be a separate lemma have exists_seq : ∃ w : ℕ → K, ∀ n, ∥u - w n∥ < δ + 1 / (n + 1), { have hδ : ∀n:ℕ, δ < δ + 1 / (n + 1), from λ n, lt_add_of_le_of_pos (le_refl _) nat.one_div_pos_of_nat, have h := λ n, exists_lt_of_cinfi_lt (hδ n), let w : ℕ → K := λ n, classical.some (h n), exact ⟨w, λ n, classical.some_spec (h n)⟩ }, rcases exists_seq with ⟨w, hw⟩, have norm_tendsto : tendsto (λ n, ∥u - w n∥) at_top (nhds δ), { have h : tendsto (λ n:ℕ, δ) at_top (nhds δ) := tendsto_const_nhds, have h' : tendsto (λ n:ℕ, δ + 1 / (n + 1)) at_top (nhds δ), { convert h.add tendsto_one_div_add_at_top_nhds_0_nat, simp only [add_zero] }, exact tendsto_of_tendsto_of_tendsto_of_le_of_le h h' (λ x, δ_le _) (λ x, le_of_lt (hw _)) }, -- Step 2: Prove that the sequence `w : ℕ → K` is a Cauchy sequence have seq_is_cauchy : cauchy_seq (λ n, ((w n):F)), { rw cauchy_seq_iff_le_tendsto_0, -- splits into three goals let b := λ n:ℕ, (8 * δ * (1/(n+1)) + 4 * (1/(n+1)) * (1/(n+1))), use (λn, sqrt (b n)), split, -- first goal : `∀ (n : ℕ), 0 ≤ sqrt (b n)` assume n, exact sqrt_nonneg _, split, -- second goal : `∀ (n m N : ℕ), N ≤ n → N ≤ m → dist ↑(w n) ↑(w m) ≤ sqrt (b N)` assume p q N hp hq, let wp := ((w p):F), let wq := ((w q):F), let a := u - wq, let b := u - wp, let half := 1 / (2:ℝ), let div := 1 / ((N:ℝ) + 1), have : 4 * ∥u - half • (wq + wp)∥ * ∥u - half • (wq + wp)∥ + ∥wp - wq∥ * ∥wp - wq∥ = 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) := calc 4 * ∥u - half•(wq + wp)∥ * ∥u - half•(wq + wp)∥ + ∥wp - wq∥ * ∥wp - wq∥ = (2*∥u - half•(wq + wp)∥) * (2 * ∥u - half•(wq + wp)∥) + ∥wp-wq∥*∥wp-wq∥ : by ring ... = (absR ((2:ℝ)) * ∥u - half•(wq + wp)∥) * (absR ((2:ℝ)) * ∥u - half•(wq+wp)∥) + ∥wp-wq∥*∥wp-wq∥ : by { rw _root_.abs_of_nonneg, exact zero_le_two } ... = ∥(2:ℝ) • (u - half • (wq + wp))∥ * ∥(2:ℝ) • (u - half • (wq + wp))∥ + ∥wp-wq∥ * ∥wp-wq∥ : by simp [norm_smul] ... = ∥a + b∥ * ∥a + b∥ + ∥a - b∥ * ∥a - b∥ : begin rw [smul_sub, smul_smul, mul_one_div_cancel (_root_.two_ne_zero : (2 : ℝ) ≠ 0), ← one_add_one_eq_two, add_smul], simp only [one_smul], have eq₁ : wp - wq = a - b, from (sub_sub_sub_cancel_left _ _ _).symm, have eq₂ : u + u - (wq + wp) = a + b, show u + u - (wq + wp) = (u - wq) + (u - wp), abel, rw [eq₁, eq₂], end ... = 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) : parallelogram_law_with_norm, have eq : δ ≤ ∥u - half • (wq + wp)∥, { rw smul_add, apply δ_le', apply h₂, repeat {exact subtype.mem _}, repeat {exact le_of_lt one_half_pos}, exact add_halves 1 }, have eq₁ : 4 * δ * δ ≤ 4 * ∥u - half • (wq + wp)∥ * ∥u - half • (wq + wp)∥, { mono, mono, norm_num, apply mul_nonneg, norm_num, exact norm_nonneg _ }, have eq₂ : ∥a∥ * ∥a∥ ≤ (δ + div) * (δ + div) := mul_self_le_mul_self (norm_nonneg _) (le_trans (le_of_lt $ hw q) (add_le_add_left (nat.one_div_le_one_div hq) _)), have eq₂' : ∥b∥ * ∥b∥ ≤ (δ + div) * (δ + div) := mul_self_le_mul_self (norm_nonneg _) (le_trans (le_of_lt $ hw p) (add_le_add_left (nat.one_div_le_one_div hp) _)), rw dist_eq_norm, apply nonneg_le_nonneg_of_sq_le_sq, { exact sqrt_nonneg _ }, rw mul_self_sqrt, exact calc ∥wp - wq∥ * ∥wp - wq∥ = 2 * (∥a∥*∥a∥ + ∥b∥*∥b∥) - 4 * ∥u - half • (wq+wp)∥ * ∥u - half • (wq+wp)∥ : by { rw ← this, simp } ... ≤ 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) - 4 * δ * δ : sub_le_sub_left eq₁ _ ... ≤ 2 * ((δ + div) * (δ + div) + (δ + div) * (δ + div)) - 4 * δ * δ : sub_le_sub_right (mul_le_mul_of_nonneg_left (add_le_add eq₂ eq₂') (by norm_num)) _ ... = 8 * δ * div + 4 * div * div : by ring, exact add_nonneg (mul_nonneg (mul_nonneg (by norm_num) zero_le_δ) (le_of_lt nat.one_div_pos_of_nat)) (mul_nonneg (mul_nonneg (by norm_num) nat.one_div_pos_of_nat.le) nat.one_div_pos_of_nat.le), -- third goal : `tendsto (λ (n : ℕ), sqrt (b n)) at_top (𝓝 0)` apply tendsto.comp, { convert continuous_sqrt.continuous_at, exact sqrt_zero.symm }, have eq₁ : tendsto (λ (n : ℕ), 8 * δ * (1 / (n + 1))) at_top (nhds (0:ℝ)), { convert (@tendsto_const_nhds _ _ _ (8 * δ) _).mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, have : tendsto (λ (n : ℕ), (4:ℝ) * (1 / (n + 1))) at_top (nhds (0:ℝ)), { convert (@tendsto_const_nhds _ _ _ (4:ℝ) _).mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, have eq₂ : tendsto (λ (n : ℕ), (4:ℝ) * (1 / (n + 1)) * (1 / (n + 1))) at_top (nhds (0:ℝ)), { convert this.mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, convert eq₁.add eq₂, simp only [add_zero] }, -- Step 3: By completeness of `K`, let `w : ℕ → K` converge to some `v : K`. -- Prove that it satisfies all requirements. rcases cauchy_seq_tendsto_of_is_complete h₁ (λ n, _) seq_is_cauchy with ⟨v, hv, w_tendsto⟩, use v, use hv, have h_cont : continuous (λ v, ∥u - v∥) := continuous.comp continuous_norm (continuous.sub continuous_const continuous_id), have : tendsto (λ n, ∥u - w n∥) at_top (nhds ∥u - v∥), convert (tendsto.comp h_cont.continuous_at w_tendsto), exact tendsto_nhds_unique this norm_tendsto, exact subtype.mem _ end /-- Characterization of minimizers for the projection on a convex set in a real inner product space. -/ theorem norm_eq_infi_iff_real_inner_le_zero {K : set F} (h : convex K) {u : F} {v : F} (hv : v ∈ K) : ∥u - v∥ = (⨅ w : K, ∥u - w∥) ↔ ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0 := iff.intro begin assume eq w hw, let δ := ⨅ w : K, ∥u - w∥, let p := ⟪u - v, w - v⟫_ℝ, let q := ∥w - v∥^2, letI : nonempty K := ⟨⟨v, hv⟩⟩, have zero_le_δ : 0 ≤ δ, apply le_cinfi, intro, exact norm_nonneg _, have δ_le : ∀ w : K, δ ≤ ∥u - w∥, assume w, apply cinfi_le, use (0:ℝ), rintros _ ⟨_, rfl⟩, exact norm_nonneg _, have δ_le' : ∀ w ∈ K, δ ≤ ∥u - w∥ := assume w hw, δ_le ⟨w, hw⟩, have : ∀θ:ℝ, 0 < θ → θ ≤ 1 → 2 * p ≤ θ * q, assume θ hθ₁ hθ₂, have : ∥u - v∥^2 ≤ ∥u - v∥^2 - 2 * θ * ⟪u - v, w - v⟫_ℝ + θ*θ*∥w - v∥^2 := calc ∥u - v∥^2 ≤ ∥u - (θ•w + (1-θ)•v)∥^2 : begin simp only [sq], apply mul_self_le_mul_self (norm_nonneg _), rw [eq], apply δ_le', apply h hw hv, exacts [le_of_lt hθ₁, sub_nonneg.2 hθ₂, add_sub_cancel'_right _ _], end ... = ∥(u - v) - θ • (w - v)∥^2 : begin have : u - (θ•w + (1-θ)•v) = (u - v) - θ • (w - v), { rw [smul_sub, sub_smul, one_smul], simp only [sub_eq_add_neg, add_comm, add_left_comm, add_assoc, neg_add_rev] }, rw this end ... = ∥u - v∥^2 - 2 * θ * inner (u - v) (w - v) + θ*θ*∥w - v∥^2 : begin rw [norm_sub_sq, inner_smul_right, norm_smul], simp only [sq], show ∥u-v∥*∥u-v∥-2*(θ*inner(u-v)(w-v))+absR (θ)*∥w-v∥*(absR (θ)*∥w-v∥)= ∥u-v∥*∥u-v∥-2*θ*inner(u-v)(w-v)+θ*θ*(∥w-v∥*∥w-v∥), rw abs_of_pos hθ₁, ring end, have eq₁ : ∥u-v∥^2-2*θ*inner(u-v)(w-v)+θ*θ*∥w-v∥^2=∥u-v∥^2+(θ*θ*∥w-v∥^2-2*θ*inner(u-v)(w-v)), by abel, rw [eq₁, le_add_iff_nonneg_right] at this, have eq₂ : θ*θ*∥w-v∥^2-2*θ*inner(u-v)(w-v)=θ*(θ*∥w-v∥^2-2*inner(u-v)(w-v)), ring, rw eq₂ at this, have := le_of_sub_nonneg (nonneg_of_mul_nonneg_left this hθ₁), exact this, by_cases hq : q = 0, { rw hq at this, have : p ≤ 0, have := this (1:ℝ) (by norm_num) (by norm_num), linarith, exact this }, { have q_pos : 0 < q, apply lt_of_le_of_ne, exact sq_nonneg _, intro h, exact hq h.symm, by_contradiction hp, rw not_le at hp, let θ := min (1:ℝ) (p / q), have eq₁ : θ*q ≤ p := calc θ*q ≤ (p/q) * q : mul_le_mul_of_nonneg_right (min_le_right _ _) (sq_nonneg _) ... = p : div_mul_cancel _ hq, have : 2 * p ≤ p := calc 2 * p ≤ θ*q : by { refine this θ (lt_min (by norm_num) (div_pos hp q_pos)) (by norm_num) } ... ≤ p : eq₁, linarith } end begin assume h, letI : nonempty K := ⟨⟨v, hv⟩⟩, apply le_antisymm, { apply le_cinfi, assume w, apply nonneg_le_nonneg_of_sq_le_sq (norm_nonneg _), have := h w w.2, exact calc ∥u - v∥ * ∥u - v∥ ≤ ∥u - v∥ * ∥u - v∥ - 2 * inner (u - v) ((w:F) - v) : by linarith ... ≤ ∥u - v∥^2 - 2 * inner (u - v) ((w:F) - v) + ∥(w:F) - v∥^2 : by { rw sq, refine le_add_of_nonneg_right _, exact sq_nonneg _ } ... = ∥(u - v) - (w - v)∥^2 : norm_sub_sq.symm ... = ∥u - w∥ * ∥u - w∥ : by { have : (u - v) - (w - v) = u - w, abel, rw [this, sq] } }, { show (⨅ (w : K), ∥u - w∥) ≤ (λw:K, ∥u - w∥) ⟨v, hv⟩, apply cinfi_le, use 0, rintros y ⟨z, rfl⟩, exact norm_nonneg _ } end variables (K : submodule 𝕜 E) /-- Existence of projections on complete subspaces. Let `u` be a point in an inner product space, and let `K` be a nonempty complete subspace. Then there exists a (unique) `v` in `K` that minimizes the distance `∥u - v∥` to `u`. This point `v` is usually called the orthogonal projection of `u` onto `K`. -/ theorem exists_norm_eq_infi_of_complete_subspace (h : is_complete (↑K : set E)) : ∀ u : E, ∃ v ∈ K, ∥u - v∥ = ⨅ w : (K : set E), ∥u - w∥ := begin letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜 E, letI : module ℝ E := restrict_scalars.module ℝ 𝕜 E, letI : is_scalar_tower ℝ 𝕜 E := restrict_scalars.is_scalar_tower _ _ _, let K' : submodule ℝ E := submodule.restrict_scalars ℝ K, exact exists_norm_eq_infi_of_complete_convex ⟨0, K'.zero_mem⟩ h K'.convex end /-- Characterization of minimizers in the projection on a subspace, in the real case. Let `u` be a point in a real inner product space, and let `K` be a nonempty subspace. Then point `v` minimizes the distance `∥u - v∥` over points in `K` if and only if for all `w ∈ K`, `⟪u - v, w⟫ = 0` (i.e., `u - v` is orthogonal to the subspace `K`). This is superceded by `norm_eq_infi_iff_inner_eq_zero` that gives the same conclusion over any `is_R_or_C` field. -/ theorem norm_eq_infi_iff_real_inner_eq_zero (K : submodule ℝ F) {u : F} {v : F} (hv : v ∈ K) : ∥u - v∥ = (⨅ w : (↑K : set F), ∥u - w∥) ↔ ∀ w ∈ K, ⟪u - v, w⟫_ℝ = 0 := iff.intro begin assume h, have h : ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0, { rwa [norm_eq_infi_iff_real_inner_le_zero] at h, exacts [K.convex, hv] }, assume w hw, have le : ⟪u - v, w⟫_ℝ ≤ 0, let w' := w + v, have : w' ∈ K := submodule.add_mem _ hw hv, have h₁ := h w' this, have h₂ : w' - v = w, simp only [add_neg_cancel_right, sub_eq_add_neg], rw h₂ at h₁, exact h₁, have ge : ⟪u - v, w⟫_ℝ ≥ 0, let w'' := -w + v, have : w'' ∈ K := submodule.add_mem _ (submodule.neg_mem _ hw) hv, have h₁ := h w'' this, have h₂ : w'' - v = -w, simp only [neg_inj, add_neg_cancel_right, sub_eq_add_neg], rw [h₂, inner_neg_right] at h₁, linarith, exact le_antisymm le ge end begin assume h, have : ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0, assume w hw, let w' := w - v, have : w' ∈ K := submodule.sub_mem _ hw hv, have h₁ := h w' this, exact le_of_eq h₁, rwa norm_eq_infi_iff_real_inner_le_zero, exacts [submodule.convex _, hv] end /-- Characterization of minimizers in the projection on a subspace. Let `u` be a point in an inner product space, and let `K` be a nonempty subspace. Then point `v` minimizes the distance `∥u - v∥` over points in `K` if and only if for all `w ∈ K`, `⟪u - v, w⟫ = 0` (i.e., `u - v` is orthogonal to the subspace `K`) -/ theorem norm_eq_infi_iff_inner_eq_zero {u : E} {v : E} (hv : v ∈ K) : ∥u - v∥ = (⨅ w : (↑K : set E), ∥u - w∥) ↔ ∀ w ∈ K, ⟪u - v, w⟫ = 0 := begin letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜 E, letI : module ℝ E := restrict_scalars.module ℝ 𝕜 E, letI : is_scalar_tower ℝ 𝕜 E := restrict_scalars.is_scalar_tower _ _ _, let K' : submodule ℝ E := K.restrict_scalars ℝ, split, { assume H, have A : ∀ w ∈ K, re ⟪u - v, w⟫ = 0 := (norm_eq_infi_iff_real_inner_eq_zero K' hv).1 H, assume w hw, apply ext, { simp [A w hw] }, { symmetry, calc im (0 : 𝕜) = 0 : im.map_zero ... = re ⟪u - v, (-I) • w⟫ : (A _ (K.smul_mem (-I) hw)).symm ... = re ((-I) * ⟪u - v, w⟫) : by rw inner_smul_right ... = im ⟪u - v, w⟫ : by simp } }, { assume H, have : ∀ w ∈ K', ⟪u - v, w⟫_ℝ = 0, { assume w hw, rw [real_inner_eq_re_inner, H w hw], exact zero_re' }, exact (norm_eq_infi_iff_real_inner_eq_zero K' hv).2 this } end section orthogonal_projection variables [complete_space K] /-- The orthogonal projection onto a complete subspace, as an unbundled function. This definition is only intended for use in setting up the bundled version `orthogonal_projection` and should not be used once that is defined. -/ def orthogonal_projection_fn (v : E) := (exists_norm_eq_infi_of_complete_subspace K (complete_space_coe_iff_is_complete.mp ‹_›) v).some variables {K} /-- The unbundled orthogonal projection is in the given subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_mem (v : E) : orthogonal_projection_fn K v ∈ K := (exists_norm_eq_infi_of_complete_subspace K (complete_space_coe_iff_is_complete.mp ‹_›) v).some_spec.some /-- The characterization of the unbundled orthogonal projection. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_inner_eq_zero (v : E) : ∀ w ∈ K, ⟪v - orthogonal_projection_fn K v, w⟫ = 0 := begin rw ←norm_eq_infi_iff_inner_eq_zero K (orthogonal_projection_fn_mem v), exact (exists_norm_eq_infi_of_complete_subspace K (complete_space_coe_iff_is_complete.mp ‹_›) v).some_spec.some_spec end /-- The unbundled orthogonal projection is the unique point in `K` with the orthogonality property. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero {u v : E} (hvm : v ∈ K) (hvo : ∀ w ∈ K, ⟪u - v, w⟫ = 0) : orthogonal_projection_fn K u = v := begin rw [←sub_eq_zero, ←inner_self_eq_zero], have hvs : orthogonal_projection_fn K u - v ∈ K := submodule.sub_mem K (orthogonal_projection_fn_mem u) hvm, have huo : ⟪u - orthogonal_projection_fn K u, orthogonal_projection_fn K u - v⟫ = 0 := orthogonal_projection_fn_inner_eq_zero u _ hvs, have huv : ⟪u - v, orthogonal_projection_fn K u - v⟫ = 0 := hvo _ hvs, have houv : ⟪(u - v) - (u - orthogonal_projection_fn K u), orthogonal_projection_fn K u - v⟫ = 0, { rw [inner_sub_left, huo, huv, sub_zero] }, rwa sub_sub_sub_cancel_left at houv end variables (K) lemma orthogonal_projection_fn_norm_sq (v : E) : ∥v∥ * ∥v∥ = ∥v - (orthogonal_projection_fn K v)∥ * ∥v - (orthogonal_projection_fn K v)∥ + ∥orthogonal_projection_fn K v∥ * ∥orthogonal_projection_fn K v∥ := begin set p := orthogonal_projection_fn K v, have h' : ⟪v - p, p⟫ = 0, { exact orthogonal_projection_fn_inner_eq_zero _ _ (orthogonal_projection_fn_mem v) }, convert norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero (v - p) p h' using 2; simp, end /-- The orthogonal projection onto a complete subspace. -/ def orthogonal_projection : E →L[𝕜] K := linear_map.mk_continuous { to_fun := λ v, ⟨orthogonal_projection_fn K v, orthogonal_projection_fn_mem v⟩, map_add' := λ x y, begin have hm : orthogonal_projection_fn K x + orthogonal_projection_fn K y ∈ K := submodule.add_mem K (orthogonal_projection_fn_mem x) (orthogonal_projection_fn_mem y), have ho : ∀ w ∈ K, ⟪x + y - (orthogonal_projection_fn K x + orthogonal_projection_fn K y), w⟫ = 0, { intros w hw, rw [add_sub_comm, inner_add_left, orthogonal_projection_fn_inner_eq_zero _ w hw, orthogonal_projection_fn_inner_eq_zero _ w hw, add_zero] }, ext, simp [eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hm ho] end, map_smul' := λ c x, begin have hm : c • orthogonal_projection_fn K x ∈ K := submodule.smul_mem K _ (orthogonal_projection_fn_mem x), have ho : ∀ w ∈ K, ⟪c • x - c • orthogonal_projection_fn K x, w⟫ = 0, { intros w hw, rw [←smul_sub, inner_smul_left, orthogonal_projection_fn_inner_eq_zero _ w hw, mul_zero] }, ext, simp [eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hm ho] end } 1 (λ x, begin simp only [one_mul, linear_map.coe_mk], refine le_of_pow_le_pow 2 (norm_nonneg _) (by norm_num) _, change ∥orthogonal_projection_fn K x∥ ^ 2 ≤ ∥x∥ ^ 2, nlinarith [orthogonal_projection_fn_norm_sq K x] end) variables {K} @[simp] lemma orthogonal_projection_fn_eq (v : E) : orthogonal_projection_fn K v = (orthogonal_projection K v : E) := rfl /-- The characterization of the orthogonal projection. -/ @[simp] lemma orthogonal_projection_inner_eq_zero (v : E) : ∀ w ∈ K, ⟪v - orthogonal_projection K v, w⟫ = 0 := orthogonal_projection_fn_inner_eq_zero v /-- The orthogonal projection is the unique point in `K` with the orthogonality property. -/ lemma eq_orthogonal_projection_of_mem_of_inner_eq_zero {u v : E} (hvm : v ∈ K) (hvo : ∀ w ∈ K, ⟪u - v, w⟫ = 0) : (orthogonal_projection K u : E) = v := eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hvm hvo /-- The orthogonal projections onto equal subspaces are coerced back to the same point in `E`. -/ lemma eq_orthogonal_projection_of_eq_submodule {K' : submodule 𝕜 E} [complete_space K'] (h : K = K') (u : E) : (orthogonal_projection K u : E) = (orthogonal_projection K' u : E) := begin change orthogonal_projection_fn K u = orthogonal_projection_fn K' u, congr, exact h end /-- The orthogonal projection sends elements of `K` to themselves. -/ @[simp] lemma orthogonal_projection_mem_subspace_eq_self (v : K) : orthogonal_projection K v = v := by { ext, apply eq_orthogonal_projection_of_mem_of_inner_eq_zero; simp } /-- A point equals its orthogonal projection if and only if it lies in the subspace. -/ lemma orthogonal_projection_eq_self_iff {v : E} : (orthogonal_projection K v : E) = v ↔ v ∈ K := begin refine ⟨λ h, _, λ h, eq_orthogonal_projection_of_mem_of_inner_eq_zero h _⟩, { rw ← h, simp }, { simp } end /-- Orthogonal projection onto the `submodule.map` of a subspace. -/ lemma orthogonal_projection_map_apply {E E' : Type*} [inner_product_space 𝕜 E] [inner_product_space 𝕜 E'] (f : E ≃ₗᵢ[𝕜] E') (p : submodule 𝕜 E) [finite_dimensional 𝕜 p] (x : E') : (orthogonal_projection (p.map (f.to_linear_equiv : E →ₗ[𝕜] E')) x : E') = f (orthogonal_projection p (f.symm x)) := begin apply eq_orthogonal_projection_of_mem_of_inner_eq_zero, { exact ⟨orthogonal_projection p (f.symm x), submodule.coe_mem _, by simp⟩, }, rintros w ⟨a, ha, rfl⟩, suffices : inner (f (f.symm x - orthogonal_projection p (f.symm x))) (f a) = (0:𝕜), { simpa using this }, rw f.inner_map_map, exact orthogonal_projection_inner_eq_zero _ _ ha, end /-- The orthogonal projection onto the trivial submodule is the zero map. -/ @[simp] lemma orthogonal_projection_bot : orthogonal_projection (⊥ : submodule 𝕜 E) = 0 := by ext variables (K) /-- The orthogonal projection has norm `≤ 1`. -/ lemma orthogonal_projection_norm_le : ∥orthogonal_projection K∥ ≤ 1 := linear_map.mk_continuous_norm_le _ (by norm_num) _ variables (𝕜) lemma smul_orthogonal_projection_singleton {v : E} (w : E) : (∥v∥ ^ 2 : 𝕜) • (orthogonal_projection (𝕜 ∙ v) w : E) = ⟪v, w⟫ • v := begin suffices : ↑(orthogonal_projection (𝕜 ∙ v) ((∥v∥ ^ 2 : 𝕜) • w)) = ⟪v, w⟫ • v, { simpa using this }, apply eq_orthogonal_projection_of_mem_of_inner_eq_zero, { rw submodule.mem_span_singleton, use ⟪v, w⟫ }, { intros x hx, obtain ⟨c, rfl⟩ := submodule.mem_span_singleton.mp hx, have hv : ↑∥v∥ ^ 2 = ⟪v, v⟫ := by { norm_cast, simp [norm_sq_eq_inner] }, simp [inner_sub_left, inner_smul_left, inner_smul_right, is_R_or_C.conj_div, mul_comm, hv, inner_product_space.conj_sym, hv] } end /-- Formula for orthogonal projection onto a single vector. -/ lemma orthogonal_projection_singleton {v : E} (w : E) : (orthogonal_projection (𝕜 ∙ v) w : E) = (⟪v, w⟫ / ∥v∥ ^ 2) • v := begin by_cases hv : v = 0, { rw [hv, eq_orthogonal_projection_of_eq_submodule submodule.span_zero_singleton], { simp }, { apply_instance } }, have hv' : ∥v∥ ≠ 0 := ne_of_gt (norm_pos_iff.mpr hv), have key : ((∥v∥ ^ 2 : 𝕜)⁻¹ * ∥v∥ ^ 2) • ↑(orthogonal_projection (𝕜 ∙ v) w) = ((∥v∥ ^ 2 : 𝕜)⁻¹ * ⟪v, w⟫) • v, { simp [mul_smul, smul_orthogonal_projection_singleton 𝕜 w] }, convert key; field_simp [hv'] end /-- Formula for orthogonal projection onto a single unit vector. -/ lemma orthogonal_projection_unit_singleton {v : E} (hv : ∥v∥ = 1) (w : E) : (orthogonal_projection (𝕜 ∙ v) w : E) = ⟪v, w⟫ • v := by { rw ← smul_orthogonal_projection_singleton 𝕜 w, simp [hv] } end orthogonal_projection section reflection variables {𝕜} (K) [complete_space K] /-- Reflection in a complete subspace of an inner product space. The word "reflection" is sometimes understood to mean specifically reflection in a codimension-one subspace, and sometimes more generally to cover operations such as reflection in a point. The definition here, of reflection in a subspace, is a more general sense of the word that includes both those common cases. -/ def reflection : E ≃ₗᵢ[𝕜] E := { norm_map' := begin intros x, let w : K := orthogonal_projection K x, let v := x - w, have : ⟪v, w⟫ = 0 := orthogonal_projection_inner_eq_zero x w w.2, convert norm_sub_eq_norm_add this using 2, { simp [bit0], dsimp [w, v], abel }, { simp [bit0] } end, ..linear_equiv.of_involutive (bit0 (K.subtype.comp (orthogonal_projection K).to_linear_map) - linear_map.id) (λ x, by simp [bit0]) } variables {K} /-- The result of reflecting. -/ lemma reflection_apply (p : E) : reflection K p = bit0 ↑(orthogonal_projection K p) - p := rfl /-- Reflection is its own inverse. -/ @[simp] lemma reflection_symm : (reflection K).symm = reflection K := rfl variables (K) /-- Reflecting twice in the same subspace. -/ @[simp] lemma reflection_reflection (p : E) : reflection K (reflection K p) = p := (reflection K).left_inv p /-- Reflection is involutive. -/ lemma reflection_involutive : function.involutive (reflection K) := reflection_reflection K variables {K} /-- A point is its own reflection if and only if it is in the subspace. -/ lemma reflection_eq_self_iff (x : E) : reflection K x = x ↔ x ∈ K := begin rw [←orthogonal_projection_eq_self_iff, reflection_apply, sub_eq_iff_eq_add', ← two_smul 𝕜, ← two_smul' 𝕜], refine (smul_right_injective E _).eq_iff, exact two_ne_zero end lemma reflection_mem_subspace_eq_self {x : E} (hx : x ∈ K) : reflection K x = x := (reflection_eq_self_iff x).mpr hx /-- Reflection in the `submodule.map` of a subspace. -/ lemma reflection_map_apply {E E' : Type*} [inner_product_space 𝕜 E] [inner_product_space 𝕜 E'] (f : E ≃ₗᵢ[𝕜] E') (K : submodule 𝕜 E) [finite_dimensional 𝕜 K] (x : E') : reflection (K.map (f.to_linear_equiv : E →ₗ[𝕜] E')) x = f (reflection K (f.symm x)) := by simp [bit0, reflection_apply, orthogonal_projection_map_apply f K x] /-- Reflection in the `submodule.map` of a subspace. -/ lemma reflection_map {E E' : Type*} [inner_product_space 𝕜 E] [inner_product_space 𝕜 E'] (f : E ≃ₗᵢ[𝕜] E') (K : submodule 𝕜 E) [finite_dimensional 𝕜 K] : reflection (K.map (f.to_linear_equiv : E →ₗ[𝕜] E')) = f.symm.trans ((reflection K).trans f) := linear_isometry_equiv.ext $ reflection_map_apply f K /-- Reflection through the trivial subspace {0} is just negation. -/ @[simp] lemma reflection_bot : reflection (⊥ : submodule 𝕜 E) = linear_isometry_equiv.neg 𝕜 := by ext; simp [reflection_apply] end reflection /-- The subspace of vectors orthogonal to a given subspace. -/ def submodule.orthogonal : submodule 𝕜 E := { carrier := {v | ∀ u ∈ K, ⟪u, v⟫ = 0}, zero_mem' := λ _ _, inner_zero_right, add_mem' := λ x y hx hy u hu, by rw [inner_add_right, hx u hu, hy u hu, add_zero], smul_mem' := λ c x hx u hu, by rw [inner_smul_right, hx u hu, mul_zero] } notation K`ᗮ`:1200 := submodule.orthogonal K /-- When a vector is in `Kᗮ`. -/ lemma submodule.mem_orthogonal (v : E) : v ∈ Kᗮ ↔ ∀ u ∈ K, ⟪u, v⟫ = 0 := iff.rfl /-- When a vector is in `Kᗮ`, with the inner product the other way round. -/ lemma submodule.mem_orthogonal' (v : E) : v ∈ Kᗮ ↔ ∀ u ∈ K, ⟪v, u⟫ = 0 := by simp_rw [submodule.mem_orthogonal, inner_eq_zero_sym] variables {K} /-- A vector in `K` is orthogonal to one in `Kᗮ`. -/ lemma submodule.inner_right_of_mem_orthogonal {u v : E} (hu : u ∈ K) (hv : v ∈ Kᗮ) : ⟪u, v⟫ = 0 := (K.mem_orthogonal v).1 hv u hu /-- A vector in `Kᗮ` is orthogonal to one in `K`. -/ lemma submodule.inner_left_of_mem_orthogonal {u v : E} (hu : u ∈ K) (hv : v ∈ Kᗮ) : ⟪v, u⟫ = 0 := by rw [inner_eq_zero_sym]; exact submodule.inner_right_of_mem_orthogonal hu hv /-- A vector in `(𝕜 ∙ u)ᗮ` is orthogonal to `u`. -/ lemma inner_right_of_mem_orthogonal_singleton (u : E) {v : E} (hv : v ∈ (𝕜 ∙ u)ᗮ) : ⟪u, v⟫ = 0 := submodule.inner_right_of_mem_orthogonal (submodule.mem_span_singleton_self u) hv /-- A vector in `(𝕜 ∙ u)ᗮ` is orthogonal to `u`. -/ lemma inner_left_of_mem_orthogonal_singleton (u : E) {v : E} (hv : v ∈ (𝕜 ∙ u)ᗮ) : ⟪v, u⟫ = 0 := submodule.inner_left_of_mem_orthogonal (submodule.mem_span_singleton_self u) hv variables (K) /-- `K` and `Kᗮ` have trivial intersection. -/ lemma submodule.inf_orthogonal_eq_bot : K ⊓ Kᗮ = ⊥ := begin rw submodule.eq_bot_iff, intros x, rw submodule.mem_inf, exact λ ⟨hx, ho⟩, inner_self_eq_zero.1 (ho x hx) end /-- `K` and `Kᗮ` have trivial intersection. -/ lemma submodule.orthogonal_disjoint : disjoint K Kᗮ := by simp [disjoint_iff, K.inf_orthogonal_eq_bot] /-- `Kᗮ` can be characterized as the intersection of the kernels of the operations of inner product with each of the elements of `K`. -/ lemma orthogonal_eq_inter : Kᗮ = ⨅ v : K, (inner_right (v:E)).ker := begin apply le_antisymm, { rw le_infi_iff, rintros ⟨v, hv⟩ w hw, simpa using hw _ hv }, { intros v hv w hw, simp only [submodule.mem_infi] at hv, exact hv ⟨w, hw⟩ } end /-- The orthogonal complement of any submodule `K` is closed. -/ lemma submodule.is_closed_orthogonal : is_closed (Kᗮ : set E) := begin rw orthogonal_eq_inter K, convert is_closed_Inter (λ v : K, (inner_right (v:E)).is_closed_ker), simp end /-- In a complete space, the orthogonal complement of any submodule `K` is complete. -/ instance [complete_space E] : complete_space Kᗮ := K.is_closed_orthogonal.complete_space_coe variables (𝕜 E) /-- `submodule.orthogonal` gives a `galois_connection` between `submodule 𝕜 E` and its `order_dual`. -/ lemma submodule.orthogonal_gc : @galois_connection (submodule 𝕜 E) (order_dual $ submodule 𝕜 E) _ _ submodule.orthogonal submodule.orthogonal := λ K₁ K₂, ⟨λ h v hv u hu, submodule.inner_left_of_mem_orthogonal hv (h hu), λ h v hv u hu, submodule.inner_left_of_mem_orthogonal hv (h hu)⟩ variables {𝕜 E} /-- `submodule.orthogonal` reverses the `≤` ordering of two subspaces. -/ lemma submodule.orthogonal_le {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂) : K₂ᗮ ≤ K₁ᗮ := (submodule.orthogonal_gc 𝕜 E).monotone_l h /-- `submodule.orthogonal.orthogonal` preserves the `≤` ordering of two subspaces. -/ lemma submodule.orthogonal_orthogonal_monotone {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂) : K₁ᗮᗮ ≤ K₂ᗮᗮ := submodule.orthogonal_le (submodule.orthogonal_le h) /-- `K` is contained in `Kᗮᗮ`. -/ lemma submodule.le_orthogonal_orthogonal : K ≤ Kᗮᗮ := (submodule.orthogonal_gc 𝕜 E).le_u_l _ /-- The inf of two orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.inf_orthogonal (K₁ K₂ : submodule 𝕜 E) : K₁ᗮ ⊓ K₂ᗮ = (K₁ ⊔ K₂)ᗮ := (submodule.orthogonal_gc 𝕜 E).l_sup.symm /-- The inf of an indexed family of orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.infi_orthogonal {ι : Type*} (K : ι → submodule 𝕜 E) : (⨅ i, (K i)ᗮ) = (supr K)ᗮ := (submodule.orthogonal_gc 𝕜 E).l_supr.symm /-- The inf of a set of orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.Inf_orthogonal (s : set $ submodule 𝕜 E) : (⨅ K ∈ s, Kᗮ) = (Sup s)ᗮ := (submodule.orthogonal_gc 𝕜 E).l_Sup.symm /-- If `K₁` is complete and contained in `K₂`, `K₁` and `K₁ᗮ ⊓ K₂` span `K₂`. -/ lemma submodule.sup_orthogonal_inf_of_is_complete {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂) (hc : is_complete (K₁ : set E)) : K₁ ⊔ (K₁ᗮ ⊓ K₂) = K₂ := begin ext x, rw submodule.mem_sup, rcases exists_norm_eq_infi_of_complete_subspace K₁ hc x with ⟨v, hv, hvm⟩, rw norm_eq_infi_iff_inner_eq_zero K₁ hv at hvm, split, { rintro ⟨y, hy, z, hz, rfl⟩, exact K₂.add_mem (h hy) hz.2 }, { exact λ hx, ⟨v, hv, x - v, ⟨(K₁.mem_orthogonal' _).2 hvm, K₂.sub_mem hx (h hv)⟩, add_sub_cancel'_right _ _⟩ } end variables {K} /-- If `K` is complete, `K` and `Kᗮ` span the whole space. -/ lemma submodule.sup_orthogonal_of_is_complete (h : is_complete (K : set E)) : K ⊔ Kᗮ = ⊤ := begin convert submodule.sup_orthogonal_inf_of_is_complete (le_top : K ≤ ⊤) h, simp end /-- If `K` is complete, `K` and `Kᗮ` span the whole space. Version using `complete_space`. -/ lemma submodule.sup_orthogonal_of_complete_space [complete_space K] : K ⊔ Kᗮ = ⊤ := submodule.sup_orthogonal_of_is_complete (complete_space_coe_iff_is_complete.mp ‹_›) variables (K) /-- If `K` is complete, any `v` in `E` can be expressed as a sum of elements of `K` and `Kᗮ`. -/ lemma submodule.exists_sum_mem_mem_orthogonal [complete_space K] (v : E) : ∃ (y ∈ K) (z ∈ Kᗮ), v = y + z := begin have h_mem : v ∈ K ⊔ Kᗮ := by simp [submodule.sup_orthogonal_of_complete_space], obtain ⟨y, hy, z, hz, hyz⟩ := submodule.mem_sup.mp h_mem, exact ⟨y, hy, z, hz, hyz.symm⟩ end /-- If `K` is complete, then the orthogonal complement of its orthogonal complement is itself. -/ @[simp] lemma submodule.orthogonal_orthogonal [complete_space K] : Kᗮᗮ = K := begin ext v, split, { obtain ⟨y, hy, z, hz, rfl⟩ := K.exists_sum_mem_mem_orthogonal v, intros hv, have hz' : z = 0, { have hyz : ⟪z, y⟫ = 0 := by simp [hz y hy, inner_eq_zero_sym], simpa [inner_add_right, hyz] using hv z hz }, simp [hy, hz'] }, { intros hv w hw, rw inner_eq_zero_sym, exact hw v hv } end lemma submodule.orthogonal_orthogonal_eq_closure [complete_space E] : Kᗮᗮ = K.topological_closure := begin refine le_antisymm _ _, { convert submodule.orthogonal_orthogonal_monotone K.submodule_topological_closure, haveI : complete_space K.topological_closure := K.is_closed_topological_closure.complete_space_coe, rw K.topological_closure.orthogonal_orthogonal }, { exact K.topological_closure_minimal K.le_orthogonal_orthogonal Kᗮ.is_closed_orthogonal } end variables {K} /-- If `K` is complete, `K` and `Kᗮ` are complements of each other. -/ lemma submodule.is_compl_orthogonal_of_is_complete (h : is_complete (K : set E)) : is_compl K Kᗮ := ⟨K.orthogonal_disjoint, le_of_eq (submodule.sup_orthogonal_of_is_complete h).symm⟩ @[simp] lemma submodule.top_orthogonal_eq_bot : (⊤ : submodule 𝕜 E)ᗮ = ⊥ := begin ext, rw [submodule.mem_bot, submodule.mem_orthogonal], exact ⟨λ h, inner_self_eq_zero.mp (h x submodule.mem_top), by { rintro rfl, simp }⟩ end @[simp] lemma submodule.bot_orthogonal_eq_top : (⊥ : submodule 𝕜 E)ᗮ = ⊤ := begin rw [← submodule.top_orthogonal_eq_bot, eq_top_iff], exact submodule.le_orthogonal_orthogonal ⊤ end @[simp] lemma submodule.orthogonal_eq_bot_iff (hK : is_complete (K : set E)) : Kᗮ = ⊥ ↔ K = ⊤ := begin refine ⟨_, by { rintro rfl, exact submodule.top_orthogonal_eq_bot }⟩, intro h, have : K ⊔ Kᗮ = ⊤ := submodule.sup_orthogonal_of_is_complete hK, rwa [h, sup_comm, bot_sup_eq] at this, end @[simp] lemma submodule.orthogonal_eq_top_iff : Kᗮ = ⊤ ↔ K = ⊥ := begin refine ⟨_, by { rintro rfl, exact submodule.bot_orthogonal_eq_top }⟩, intro h, have : K ⊓ Kᗮ = ⊥ := K.orthogonal_disjoint.eq_bot, rwa [h, inf_comm, top_inf_eq] at this end /-- A point in `K` with the orthogonality property (here characterized in terms of `Kᗮ`) must be the orthogonal projection. -/ lemma eq_orthogonal_projection_of_mem_orthogonal [complete_space K] {u v : E} (hv : v ∈ K) (hvo : u - v ∈ Kᗮ) : (orthogonal_projection K u : E) = v := eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hv (λ w, inner_eq_zero_sym.mp ∘ (hvo w)) /-- A point in `K` with the orthogonality property (here characterized in terms of `Kᗮ`) must be the orthogonal projection. -/ lemma eq_orthogonal_projection_of_mem_orthogonal' [complete_space K] {u v z : E} (hv : v ∈ K) (hz : z ∈ Kᗮ) (hu : u = v + z) : (orthogonal_projection K u : E) = v := eq_orthogonal_projection_of_mem_orthogonal hv (by simpa [hu]) /-- The orthogonal projection onto `K` of an element of `Kᗮ` is zero. -/ lemma orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero [complete_space K] {v : E} (hv : v ∈ Kᗮ) : orthogonal_projection K v = 0 := by { ext, convert eq_orthogonal_projection_of_mem_orthogonal _ _; simp [hv] } /-- The reflection in `K` of an element of `Kᗮ` is its negation. -/ lemma reflection_mem_subspace_orthogonal_complement_eq_neg [complete_space K] {v : E} (hv : v ∈ Kᗮ) : reflection K v = - v := by simp [reflection_apply, orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero hv] /-- The orthogonal projection onto `Kᗮ` of an element of `K` is zero. -/ lemma orthogonal_projection_mem_subspace_orthogonal_precomplement_eq_zero [complete_space E] {v : E} (hv : v ∈ K) : orthogonal_projection Kᗮ v = 0 := orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero (K.le_orthogonal_orthogonal hv) /-- The reflection in `Kᗮ` of an element of `K` is its negation. -/ lemma reflection_mem_subspace_orthogonal_precomplement_eq_neg [complete_space E] {v : E} (hv : v ∈ K) : reflection Kᗮ v = -v := reflection_mem_subspace_orthogonal_complement_eq_neg (K.le_orthogonal_orthogonal hv) /-- The orthogonal projection onto `(𝕜 ∙ v)ᗮ` of `v` is zero. -/ lemma orthogonal_projection_orthogonal_complement_singleton_eq_zero [complete_space E] (v : E) : orthogonal_projection (𝕜 ∙ v)ᗮ v = 0 := orthogonal_projection_mem_subspace_orthogonal_precomplement_eq_zero (submodule.mem_span_singleton_self v) /-- The reflection in `(𝕜 ∙ v)ᗮ` of `v` is `-v`. -/ lemma reflection_orthogonal_complement_singleton_eq_neg [complete_space E] (v : E) : reflection (𝕜 ∙ v)ᗮ v = -v := reflection_mem_subspace_orthogonal_precomplement_eq_neg (submodule.mem_span_singleton_self v) variables (K) /-- In a complete space `E`, a vector splits as the sum of its orthogonal projections onto a complete submodule `K` and onto the orthogonal complement of `K`.-/ lemma eq_sum_orthogonal_projection_self_orthogonal_complement [complete_space E] [complete_space K] (w : E) : w = (orthogonal_projection K w : E) + (orthogonal_projection Kᗮ w : E) := begin obtain ⟨y, hy, z, hz, hwyz⟩ := K.exists_sum_mem_mem_orthogonal w, convert hwyz, { exact eq_orthogonal_projection_of_mem_orthogonal' hy hz hwyz }, { rw add_comm at hwyz, refine eq_orthogonal_projection_of_mem_orthogonal' hz _ hwyz, simp [hy] } end /-- In a complete space `E`, the projection maps onto a complete subspace `K` and its orthogonal complement sum to the identity. -/ lemma id_eq_sum_orthogonal_projection_self_orthogonal_complement [complete_space E] [complete_space K] : continuous_linear_map.id 𝕜 E = K.subtypeL.comp (orthogonal_projection K) + Kᗮ.subtypeL.comp (orthogonal_projection Kᗮ) := by { ext w, exact eq_sum_orthogonal_projection_self_orthogonal_complement K w } /-- The orthogonal projection is self-adjoint. -/ lemma inner_orthogonal_projection_left_eq_right [complete_space E] [complete_space K] (u v : E) : ⟪↑(orthogonal_projection K u), v⟫ = ⟪u, orthogonal_projection K v⟫ := begin nth_rewrite 0 eq_sum_orthogonal_projection_self_orthogonal_complement K v, nth_rewrite 1 eq_sum_orthogonal_projection_self_orthogonal_complement K u, rw [inner_add_left, inner_add_right, submodule.inner_right_of_mem_orthogonal (submodule.coe_mem (orthogonal_projection K u)) (submodule.coe_mem (orthogonal_projection Kᗮ v)), submodule.inner_left_of_mem_orthogonal (submodule.coe_mem (orthogonal_projection K v)) (submodule.coe_mem (orthogonal_projection Kᗮ u))], end open finite_dimensional /-- Given a finite-dimensional subspace `K₂`, and a subspace `K₁` containined in it, the dimensions of `K₁` and the intersection of its orthogonal subspace with `K₂` add to that of `K₂`. -/ lemma submodule.finrank_add_inf_finrank_orthogonal {K₁ K₂ : submodule 𝕜 E} [finite_dimensional 𝕜 K₂] (h : K₁ ≤ K₂) : finrank 𝕜 K₁ + finrank 𝕜 (K₁ᗮ ⊓ K₂ : submodule 𝕜 E) = finrank 𝕜 K₂ := begin haveI := submodule.finite_dimensional_of_le h, have hd := submodule.dim_sup_add_dim_inf_eq K₁ (K₁ᗮ ⊓ K₂), rw [←inf_assoc, (submodule.orthogonal_disjoint K₁).eq_bot, bot_inf_eq, finrank_bot, submodule.sup_orthogonal_inf_of_is_complete h (submodule.complete_of_finite_dimensional _)] at hd, rw add_zero at hd, exact hd.symm end /-- Given a finite-dimensional subspace `K₂`, and a subspace `K₁` containined in it, the dimensions of `K₁` and the intersection of its orthogonal subspace with `K₂` add to that of `K₂`. -/ lemma submodule.finrank_add_inf_finrank_orthogonal' {K₁ K₂ : submodule 𝕜 E} [finite_dimensional 𝕜 K₂] (h : K₁ ≤ K₂) {n : ℕ} (h_dim : finrank 𝕜 K₁ + n = finrank 𝕜 K₂) : finrank 𝕜 (K₁ᗮ ⊓ K₂ : submodule 𝕜 E) = n := by { rw ← add_right_inj (finrank 𝕜 K₁), simp [submodule.finrank_add_inf_finrank_orthogonal h, h_dim] } /-- Given a finite-dimensional space `E` and subspace `K`, the dimensions of `K` and `Kᗮ` add to that of `E`. -/ lemma submodule.finrank_add_finrank_orthogonal [finite_dimensional 𝕜 E] {K : submodule 𝕜 E} : finrank 𝕜 K + finrank 𝕜 Kᗮ = finrank 𝕜 E := begin convert submodule.finrank_add_inf_finrank_orthogonal (le_top : K ≤ ⊤) using 1, { rw inf_top_eq }, { simp } end /-- Given a finite-dimensional space `E` and subspace `K`, the dimensions of `K` and `Kᗮ` add to that of `E`. -/ lemma submodule.finrank_add_finrank_orthogonal' [finite_dimensional 𝕜 E] {K : submodule 𝕜 E} {n : ℕ} (h_dim : finrank 𝕜 K + n = finrank 𝕜 E) : finrank 𝕜 Kᗮ = n := by { rw ← add_right_inj (finrank 𝕜 K), simp [submodule.finrank_add_finrank_orthogonal, h_dim] } local attribute [instance] fact_finite_dimensional_of_finrank_eq_succ /-- In a finite-dimensional inner product space, the dimension of the orthogonal complement of the span of a nonzero vector is one less than the dimension of the space. -/ lemma finrank_orthogonal_span_singleton {n : ℕ} [_i : fact (finrank 𝕜 E = n + 1)] {v : E} (hv : v ≠ 0) : finrank 𝕜 (𝕜 ∙ v)ᗮ = n := submodule.finrank_add_finrank_orthogonal' $ by simp [finrank_span_singleton hv, _i.elim, add_comm] end orthogonal section orthonormal_basis /-! ### Existence of Hilbert basis, orthonormal basis, etc. -/ variables {𝕜 E} {v : set E} open finite_dimensional submodule set /-- An orthonormal set in an `inner_product_space` is maximal, if and only if the orthogonal complement of its span is empty. -/ lemma maximal_orthonormal_iff_orthogonal_complement_eq_bot (hv : orthonormal 𝕜 (coe : v → E)) : (∀ u ⊇ v, orthonormal 𝕜 (coe : u → E) → u = v) ↔ (span 𝕜 v)ᗮ = ⊥ := begin rw submodule.eq_bot_iff, split, { contrapose!, -- ** direction 1: nonempty orthogonal complement implies nonmaximal rintros ⟨x, hx', hx⟩, -- take a nonzero vector and normalize it let e := (∥x∥⁻¹ : 𝕜) • x, have he : ∥e∥ = 1 := by simp [e, norm_smul_inv_norm hx], have he' : e ∈ (span 𝕜 v)ᗮ := smul_mem' _ _ hx', have he'' : e ∉ v, { intros hev, have : e = 0, { have : e ∈ (span 𝕜 v) ⊓ (span 𝕜 v)ᗮ := ⟨subset_span hev, he'⟩, simpa [(span 𝕜 v).inf_orthogonal_eq_bot] using this }, have : e ≠ 0 := hv.ne_zero ⟨e, hev⟩, contradiction }, -- put this together with `v` to provide a candidate orthonormal basis for the whole space refine ⟨v.insert e, v.subset_insert e, ⟨_, _⟩, (v.ne_insert_of_not_mem he'').symm⟩, { -- show that the elements of `v.insert e` have unit length rintros ⟨a, ha'⟩, cases eq_or_mem_of_mem_insert ha' with ha ha, { simp [ha, he] }, { exact hv.1 ⟨a, ha⟩ } }, { -- show that the elements of `v.insert e` are orthogonal have h_end : ∀ a ∈ v, ⟪a, e⟫ = 0, { intros a ha, exact he' a (submodule.subset_span ha) }, rintros ⟨a, ha'⟩, cases eq_or_mem_of_mem_insert ha' with ha ha, { rintros ⟨b, hb'⟩ hab', have hb : b ∈ v, { refine mem_of_mem_insert_of_ne hb' _, intros hbe', apply hab', simp [ha, hbe'] }, rw inner_eq_zero_sym, simpa [ha] using h_end b hb }, rintros ⟨b, hb'⟩ hab', cases eq_or_mem_of_mem_insert hb' with hb hb, { simpa [hb] using h_end a ha }, have : (⟨a, ha⟩ : v) ≠ ⟨b, hb⟩, { intros hab'', apply hab', simpa using hab'' }, exact hv.2 this } }, { -- ** direction 2: empty orthogonal complement implies maximal simp only [subset.antisymm_iff], rintros h u (huv : v ⊆ u) hu, refine ⟨_, huv⟩, intros x hxu, refine ((mt (h x)) (hu.ne_zero ⟨x, hxu⟩)).imp_symm _, intros hxv y hy, have hxv' : (⟨x, hxu⟩ : u) ∉ (coe ⁻¹' v : set u) := by simp [huv, hxv], obtain ⟨l, hl, rfl⟩ : ∃ l ∈ finsupp.supported 𝕜 𝕜 (coe ⁻¹' v : set u), (finsupp.total ↥u E 𝕜 coe) l = y, { rw ← finsupp.mem_span_image_iff_total, simp [huv, inter_eq_self_of_subset_left, hy] }, exact hu.inner_finsupp_eq_zero hxv' hl } end /-- An orthonormal set in an `inner_product_space` is maximal, if and only if the closure of its span is the whole space. -/ lemma maximal_orthonormal_iff_dense_span [complete_space E] (hv : orthonormal 𝕜 (coe : v → E)) : (∀ u ⊇ v, orthonormal 𝕜 (coe : u → E) → u = v) ↔ (span 𝕜 v).topological_closure = ⊤ := by rw [maximal_orthonormal_iff_orthogonal_complement_eq_bot hv, ← submodule.orthogonal_eq_top_iff, (span 𝕜 v).orthogonal_orthogonal_eq_closure] /-- Any orthonormal subset can be extended to an orthonormal set whose span is dense. -/ lemma exists_subset_is_orthonormal_dense_span [complete_space E] (hv : orthonormal 𝕜 (coe : v → E)) : ∃ u ⊇ v, orthonormal 𝕜 (coe : u → E) ∧ (span 𝕜 u).topological_closure = ⊤ := begin obtain ⟨u, hus, hu, hu_max⟩ := exists_maximal_orthonormal hv, rw maximal_orthonormal_iff_dense_span hu at hu_max, exact ⟨u, hus, hu, hu_max⟩ end variables (𝕜 E) /-- An inner product space admits an orthonormal set whose span is dense. -/ lemma exists_is_orthonormal_dense_span [complete_space E] : ∃ u : set E, orthonormal 𝕜 (coe : u → E) ∧ (span 𝕜 u).topological_closure = ⊤ := let ⟨u, hus, hu, hu_max⟩ := exists_subset_is_orthonormal_dense_span (orthonormal_empty 𝕜 E) in ⟨u, hu, hu_max⟩ variables {𝕜 E} /-- An orthonormal set in a finite-dimensional `inner_product_space` is maximal, if and only if it is a basis. -/ lemma maximal_orthonormal_iff_basis_of_finite_dimensional [finite_dimensional 𝕜 E] (hv : orthonormal 𝕜 (coe : v → E)) : (∀ u ⊇ v, orthonormal 𝕜 (coe : u → E) → u = v) ↔ ∃ b : basis v 𝕜 E, ⇑b = coe := begin rw maximal_orthonormal_iff_orthogonal_complement_eq_bot hv, have hv_compl : is_complete (span 𝕜 v : set E) := (span 𝕜 v).complete_of_finite_dimensional, rw submodule.orthogonal_eq_bot_iff hv_compl, have hv_coe : range (coe : v → E) = v := by simp, split, { refine λ h, ⟨basis.mk hv.linear_independent _, basis.coe_mk _ _⟩, convert h }, { rintros ⟨h, coe_h⟩, rw [← h.span_eq, coe_h, hv_coe] } end /-- In a finite-dimensional `inner_product_space`, any orthonormal subset can be extended to an orthonormal basis. -/ lemma exists_subset_is_orthonormal_basis [finite_dimensional 𝕜 E] (hv : orthonormal 𝕜 (coe : v → E)) : ∃ (u ⊇ v) (b : basis u 𝕜 E), orthonormal 𝕜 b ∧ ⇑b = coe := begin obtain ⟨u, hus, hu, hu_max⟩ := exists_maximal_orthonormal hv, obtain ⟨b, hb⟩ := (maximal_orthonormal_iff_basis_of_finite_dimensional hu).mp hu_max, exact ⟨u, hus, b, by rwa hb, hb⟩ end variables (𝕜 E) /-- Index for an arbitrary orthonormal basis on a finite-dimensional `inner_product_space`. -/ def orthonormal_basis_index [finite_dimensional 𝕜 E] : set E := classical.some (exists_subset_is_orthonormal_basis (orthonormal_empty 𝕜 E)) /-- A finite-dimensional `inner_product_space` has an orthonormal basis. -/ def orthonormal_basis [finite_dimensional 𝕜 E] : basis (orthonormal_basis_index 𝕜 E) 𝕜 E := (exists_subset_is_orthonormal_basis (orthonormal_empty 𝕜 E)).some_spec.some_spec.some lemma orthonormal_basis_orthonormal [finite_dimensional 𝕜 E] : orthonormal 𝕜 (orthonormal_basis 𝕜 E) := (exists_subset_is_orthonormal_basis (orthonormal_empty 𝕜 E)).some_spec.some_spec.some_spec.1 @[simp] lemma coe_orthonormal_basis [finite_dimensional 𝕜 E] : ⇑(orthonormal_basis 𝕜 E) = coe := (exists_subset_is_orthonormal_basis (orthonormal_empty 𝕜 E)).some_spec.some_spec.some_spec.2 instance [finite_dimensional 𝕜 E] : fintype (orthonormal_basis_index 𝕜 E) := is_noetherian.fintype_basis_index (orthonormal_basis 𝕜 E) variables {𝕜 E} /-- An `n`-dimensional `inner_product_space` has an orthonormal basis indexed by `fin n`. -/ def fin_orthonormal_basis [finite_dimensional 𝕜 E] {n : ℕ} (hn : finrank 𝕜 E = n) : basis (fin n) 𝕜 E := have h : fintype.card (orthonormal_basis_index 𝕜 E) = n, by rw [← finrank_eq_card_basis (orthonormal_basis 𝕜 E), hn], (orthonormal_basis 𝕜 E).reindex (fintype.equiv_fin_of_card_eq h) lemma fin_orthonormal_basis_orthonormal [finite_dimensional 𝕜 E] {n : ℕ} (hn : finrank 𝕜 E = n) : orthonormal 𝕜 (fin_orthonormal_basis hn) := suffices orthonormal 𝕜 (orthonormal_basis _ _ ∘ equiv.symm _), by { simp only [fin_orthonormal_basis, basis.coe_reindex], assumption }, -- why doesn't simpa work? (orthonormal_basis_orthonormal 𝕜 E).comp _ (equiv.injective _) end orthonormal_basis
77cadf721b71cc6d4f87ec593393004dc07d034c
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/polynomial/induction.lean
83e663f4e1b10d1bef24f2d35a058e4a84117a8a
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
4,293
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.coeff /-! # Theory of univariate polynomials The main results are `induction_on` and `as_sum`. -/ noncomputable theory open finsupp finset namespace polynomial universes u v w x y z variables {R : Type u} {S : Type v} {T : Type w} {ι : Type x} {k : Type y} {A : Type z} {a b : R} {m n : ℕ} section semiring variables [semiring R] {p q r : polynomial R} lemma sum_C_mul_X_eq (p : polynomial R) : p.sum (λn a, C a * X^n) = p := begin ext n, simp only [polynomial.sum, X_pow_eq_monomial, coeff_monomial, mul_one, finset_sum_coeff, C_mul_monomial, not_not, mem_support_iff, finset.sum_ite_eq', ite_eq_left_iff], exact λ h, h.symm end lemma sum_monomial_eq (p : polynomial R) : p.sum (λn a, monomial n a) = p := by simp only [monomial_eq_C_mul_X, sum_C_mul_X_eq] @[elab_as_eliminator] protected lemma induction_on {M : polynomial R → Prop} (p : polynomial R) (h_C : ∀a, M (C a)) (h_add : ∀p q, M p → M q → M (p + q)) (h_monomial : ∀(n : ℕ) (a : R), M (C a * X^n) → M (C a * X^(n+1))) : M p := begin have A : ∀{n:ℕ} {a}, M (C a * X^n), { assume n a, induction n with n ih, { simp only [pow_zero, mul_one, h_C] }, { exact h_monomial _ _ ih } }, have B : ∀ (s : finset ℕ), M (s.sum (λ (n : ℕ), C (p.coeff n) * X ^ n)), { apply finset.induction, { convert h_C 0, exact C_0.symm }, { assume n s ns ih, rw sum_insert ns, exact h_add _ _ A ih, } }, rw [← sum_C_mul_X_eq p, polynomial.sum], exact B _ end /-- To prove something about polynomials, it suffices to show the condition is closed under taking sums, and it holds for monomials. -/ @[elab_as_eliminator] protected lemma induction_on' {M : polynomial R → Prop} (p : polynomial R) (h_add : ∀p q, M p → M q → M (p + q)) (h_monomial : ∀(n : ℕ) (a : R), M (monomial n a)) : M p := polynomial.induction_on p (h_monomial 0) h_add (λ n a h, by { rw ← monomial_eq_C_mul_X at ⊢, exact h_monomial _ _ }) section coeff theorem coeff_mul_monomial (p : polynomial R) (n d : ℕ) (r : R) : coeff (p * monomial n r) (d + n) = coeff p d * r := by rw [monomial_eq_C_mul_X, ←X_pow_mul, ←mul_assoc, coeff_mul_C, coeff_mul_X_pow] theorem coeff_monomial_mul (p : polynomial R) (n d : ℕ) (r : R) : coeff (monomial n r * p) (d + n) = r * coeff p d := by rw [monomial_eq_C_mul_X, mul_assoc, coeff_C_mul, X_pow_mul, coeff_mul_X_pow] -- This can already be proved by `simp`. theorem coeff_mul_monomial_zero (p : polynomial R) (d : ℕ) (r : R) : coeff (p * monomial 0 r) d = coeff p d * r := coeff_mul_monomial p 0 d r -- This can already be proved by `simp`. theorem coeff_monomial_zero_mul (p : polynomial R) (d : ℕ) (r : R) : coeff (monomial 0 r * p) d = r * coeff p d := coeff_monomial_mul p 0 d r end coeff open submodule polynomial set variables {f : polynomial R} {I : submodule (polynomial R) (polynomial R)} /-- If the coefficients of a polynomial belong to n ideal contains the submodule span of the coefficients of a polynomial. -/ lemma span_le_of_coeff_mem_C_inverse (cf : ∀ (i : ℕ), f.coeff i ∈ (C ⁻¹' I.carrier)) : (span (polynomial R) {g | ∃ i, g = C (f.coeff i)}) ≤ I := begin refine bInter_subset_of_mem _, rintros _ ⟨i, rfl⟩, exact set_like.mem_coe.mpr (cf i), end lemma mem_span_C_coeff : f ∈ span (polynomial R) {g : polynomial R | ∃ i : ℕ, g = (C (coeff f i))} := begin let p := span (polynomial R) {g : polynomial R | ∃ i : ℕ, g = (C (coeff f i))}, nth_rewrite 0 (sum_C_mul_X_eq f).symm, refine submodule.sum_mem _ (λ n hn, _), dsimp, have : C (coeff f n) ∈ p, by { apply subset_span, simp }, have : (monomial n (1 : R)) • C (coeff f n) ∈ p := p.smul_mem _ this, convert this using 1, simp only [monomial_mul_C, one_mul, smul_eq_mul], rw monomial_eq_C_mul_X, end lemma exists_coeff_not_mem_C_inverse : f ∉ I → ∃ i : ℕ , coeff f i ∉ (C ⁻¹' I.carrier) := imp_of_not_imp_not _ _ (λ cf, not_not.mpr ((span_le_of_coeff_mem_C_inverse (not_exists_not.mp cf)) mem_span_C_coeff)) end semiring end polynomial
b2f808400cb12f59620fdd7d31c2083b3d9ed273
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/meta/widget/replace_save_info.lean
c9ac27643c7994afcb5f5472aa750d2a8e832a6e
[ "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
463
lean
/- Copyright (c) E.W.Ayers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: E.W.Ayers -/ prelude import init.meta.widget.interactive_expr meta def tactic.save_info_with_widgets (p : pos) : tactic unit := do s ← tactic.read, tactic.save_info_thunk p (λ _, tactic_state.to_format s), tactic.save_widget p widget.tactic_state_widget attribute [vm_override tactic.save_info_with_widgets] tactic.save_info
e36b7128deda5cc6153f6052efeb8e475b50873c
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Meta/AbstractMVars.lean
6813105b7896b3c035431c15efb41a98b15855a7
[ "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
5,611
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Basic namespace Lean.Meta structure AbstractMVarsResult where paramNames : Array Name numMVars : Nat expr : Expr deriving Inhabited, BEq namespace AbstractMVars open Std (HashMap) structure State where ngen : NameGenerator lctx : LocalContext mctx : MetavarContext nextParamIdx : Nat := 0 paramNames : Array Name := #[] fvars : Array Expr := #[] lmap : HashMap MVarId Level := {} emap : HashMap MVarId Expr := {} abbrev M := StateM State def mkFreshId : M Name := do let s ← get let fresh := s.ngen.curr modify fun s => { s with ngen := s.ngen.next } pure fresh def mkFreshFVarId : M FVarId := return { name := (← mkFreshId) } private partial def abstractLevelMVars (u : Level) : M Level := do if !u.hasMVar then return u else match u with | Level.zero _ => return u | Level.param _ _ => return u | Level.succ v _ => return u.updateSucc! (← abstractLevelMVars v) | Level.max v w _ => return u.updateMax! (← abstractLevelMVars v) (← abstractLevelMVars w) | Level.imax v w _ => return u.updateIMax! (← abstractLevelMVars v) (← abstractLevelMVars w) | Level.mvar mvarId _ => let s ← get let depth := s.mctx.getLevelDepth mvarId; if depth != s.mctx.depth then return u -- metavariables from lower depths are treated as constants else match s.lmap.find? mvarId with | some u => pure u | none => let paramId := Name.mkNum `_abstMVar s.nextParamIdx let u := mkLevelParam paramId modify fun s => { s with nextParamIdx := s.nextParamIdx + 1, lmap := s.lmap.insert mvarId u, paramNames := s.paramNames.push paramId } return u partial def abstractExprMVars (e : Expr) : M Expr := do if !e.hasMVar then return e else match e with | e@(Expr.lit _ _) => return e | e@(Expr.bvar _ _) => return e | e@(Expr.fvar _ _) => return e | e@(Expr.sort u _) => return e.updateSort! (← abstractLevelMVars u) | e@(Expr.const _ us _) => return e.updateConst! (← us.mapM abstractLevelMVars) | e@(Expr.proj _ _ s _) => return e.updateProj! (← abstractExprMVars s) | e@(Expr.app f a _) => return e.updateApp! (← abstractExprMVars f) (← abstractExprMVars a) | e@(Expr.mdata _ b _) => return e.updateMData! (← abstractExprMVars b) | e@(Expr.lam _ d b _) => return e.updateLambdaE! (← abstractExprMVars d) (← abstractExprMVars b) | e@(Expr.forallE _ d b _) => return e.updateForallE! (← abstractExprMVars d) (← abstractExprMVars b) | e@(Expr.letE _ t v b _) => return e.updateLet! (← abstractExprMVars t) (← abstractExprMVars v) (← abstractExprMVars b) | e@(Expr.mvar mvarId _) => let s ← get let decl := s.mctx.getDecl mvarId if decl.depth != s.mctx.depth then return e else let (eNew, mctxNew) ← s.mctx.instantiateMVars e if e != eNew then modify fun s => { s with mctx := mctxNew } abstractExprMVars eNew else match s.emap.find? mvarId with | some e => return e | none => let type ← abstractExprMVars decl.type let fvarId ← mkFreshFVarId let fvar := mkFVar fvarId; let userName := if decl.userName.isAnonymous then (`x).appendIndexAfter s.fvars.size else decl.userName modify fun s => { s with emap := s.emap.insert mvarId fvar, fvars := s.fvars.push fvar, lctx := s.lctx.mkLocalDecl fvarId userName type } return fvar end AbstractMVars /-- Abstract (current depth) metavariables occurring in `e`. The result contains - An array of universe level parameters that replaced universe metavariables occurring in `e`. - The number of (expr) metavariables abstracted. - And an expression of the form `fun (m_1 : A_1) ... (m_k : A_k) => e'`, where `k` equal to the number of (expr) metavariables abstracted, and `e'` is `e` after we replace the metavariables. Example: given `f.{?u} ?m1` where `?m1 : ?m2 Nat`, `?m2 : Type -> Type`. This function returns `{ levels := #[u], size := 2, expr := (fun (m2 : Type -> Type) (m1 : m2 Nat) => f.{u} m1) }` This API can be used to "transport" to a different metavariable context. Given a new metavariable context, we replace the `AbstractMVarsResult.levels` with new fresh universe metavariables, and instantiate the `(m_i : A_i)` in the lambda-expression with new fresh metavariables. Application: we use this method to cache the results of type class resolution. -/ def abstractMVars (e : Expr) : MetaM AbstractMVarsResult := do let e ← instantiateMVars e let (e, s) := AbstractMVars.abstractExprMVars e { mctx := (← getMCtx), lctx := (← getLCtx), ngen := (← getNGen) } setNGen s.ngen setMCtx s.mctx let e := s.lctx.mkLambda s.fvars e pure { paramNames := s.paramNames, numMVars := s.fvars.size, expr := e } def openAbstractMVarsResult (a : AbstractMVarsResult) : MetaM (Array Expr × Array BinderInfo × Expr) := do let us ← a.paramNames.mapM fun _ => mkFreshLevelMVar let e := a.expr.instantiateLevelParamsArray a.paramNames us lambdaMetaTelescope e (some a.numMVars) end Lean.Meta
e7b6d1d99d00d389fdb099296d6fa70ba277d1e7
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/linear_algebra/matrix.lean
66f2d863ffcf95c341a93834e665375077f6f714
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
39,896
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl, Patrick Massot, Casper Putz -/ import linear_algebra.finite_dimensional import linear_algebra.nonsingular_inverse import linear_algebra.multilinear import linear_algebra.dual /-! # Linear maps and matrices This file defines the maps to send matrices to a linear map, and to send linear maps between modules with a finite bases to matrices. This defines a linear equivalence between linear maps between finite-dimensional vector spaces and matrices indexed by the respective bases. It also defines the trace of an endomorphism, and the determinant of a family of vectors with respect to some basis. Some results are proved about the linear map corresponding to a diagonal matrix (`range`, `ker` and `rank`). ## Main definitions In the list below, and in all this file, `R` is a commutative ring (semiring is sometimes enough), `M` and its variations are `R`-modules, `ι`, `κ`, `n` and `m` are finite types used for indexing. * `linear_map.to_matrix`: given bases `v₁ : ι → M₁` and `v₂ : κ → M₂`, the `R`-linear equivalence from `M₁ →ₗ[R] M₂` to `matrix κ ι R` * `matrix.to_lin`: the inverse of `linear_map.to_matrix` * `linear_map.to_matrix'`: the `R`-linear equivalence from `(n → R) →ₗ[R] (m → R)` to `matrix n m R` (with the standard basis on `n → R` and `m → R`) * `matrix.to_lin'`: the inverse of `linear_map.to_matrix'` * `alg_equiv_matrix`: given a basis indexed by `n`, the `R`-algebra equivalence between `R`-endomorphisms of `M` and `matrix n n R` * `matrix.trace`: the trace of a square matrix * `linear_map.trace`: the trace of an endomorphism * `is_basis.to_matrix`: the matrix whose columns are a given family of vectors in a given basis * `is_basis.to_matrix_equiv`: given a basis, the linear equivalence between families of vectors and matrices arising from `is_basis.to_matrix` * `is_basis.det`: the determinant of a family of vectors with respect to a basis, as a multilinear map ## Tags linear_map, matrix, linear_equiv, diagonal, det, trace -/ noncomputable theory open linear_map matrix set submodule open_locale big_operators open_locale matrix universes u v w section to_matrix' variables {R : Type*} [comm_ring R] variables {l m n : Type*} [fintype l] [fintype m] [fintype n] instance [decidable_eq m] [decidable_eq n] (R) [fintype R] : fintype (matrix m n R) := by unfold matrix; apply_instance /-- `matrix.mul_vec M` is a linear map. -/ def matrix.mul_vec_lin (M : matrix m n R) : (n → R) →ₗ[R] (m → R) := { to_fun := M.mul_vec, map_add' := λ v w, funext (λ i, dot_product_add _ _ _), map_smul' := λ c v, funext (λ i, dot_product_smul _ _ _) } @[simp] lemma matrix.mul_vec_lin_apply (M : matrix m n R) (v : n → R) : matrix.mul_vec_lin M v = M.mul_vec v := rfl variables [decidable_eq n] @[simp] lemma matrix.mul_vec_std_basis (M : matrix m n R) (i j) : M.mul_vec (std_basis R (λ _, R) j 1) i = M i j := begin have : (∑ j', M i j' * if j = j' then 1 else 0) = M i j, { simp_rw [mul_boole, finset.sum_ite_eq, finset.mem_univ, if_true] }, convert this, ext, split_ifs with h; simp only [std_basis_apply], { rw [h, function.update_same] }, { rw [function.update_noteq (ne.symm h), pi.zero_apply] } end /-- Linear maps `(n → R) →ₗ[R] (m → R)` are linearly equivalent to `matrix m n R`. -/ def linear_map.to_matrix' : ((n → R) →ₗ[R] (m → R)) ≃ₗ[R] matrix m n R := { to_fun := λ f i j, f (std_basis R (λ _, R) j 1) i, inv_fun := matrix.mul_vec_lin, right_inv := λ M, by { ext i j, simp only [matrix.mul_vec_std_basis, matrix.mul_vec_lin_apply] }, left_inv := λ f, begin apply (pi.is_basis_fun R n).ext, intro j, ext i, simp only [matrix.mul_vec_std_basis, matrix.mul_vec_lin_apply] end, map_add' := λ f g, by { ext i j, simp only [pi.add_apply, linear_map.add_apply] }, map_smul' := λ c f, by { ext i j, simp only [pi.smul_apply, linear_map.smul_apply] } } /-- A `matrix m n R` is linearly equivalent to a linear map `(n → R) →ₗ[R] (m → R)`. -/ def matrix.to_lin' : matrix m n R ≃ₗ[R] ((n → R) →ₗ[R] (m → R)) := linear_map.to_matrix'.symm @[simp] lemma linear_map.to_matrix'_symm : (linear_map.to_matrix'.symm : matrix m n R ≃ₗ[R] _) = matrix.to_lin' := rfl @[simp] lemma matrix.to_lin'_symm : (matrix.to_lin'.symm : ((n → R) →ₗ[R] (m → R)) ≃ₗ[R] _) = linear_map.to_matrix' := rfl @[simp] lemma linear_map.to_matrix'_to_lin' (M : matrix m n R) : linear_map.to_matrix' (matrix.to_lin' M) = M := linear_map.to_matrix'.apply_symm_apply M @[simp] lemma matrix.to_lin'_to_matrix' (f : (n → R) →ₗ[R] (m → R)) : matrix.to_lin' (linear_map.to_matrix' f) = f := matrix.to_lin'.apply_symm_apply f @[simp] lemma linear_map.to_matrix'_apply (f : (n → R) →ₗ[R] (m → R)) (i j) : linear_map.to_matrix' f i j = f (λ j', if j' = j then 1 else 0) i := begin simp only [linear_map.to_matrix', linear_equiv.mk_apply], congr, ext j', split_ifs with h, { rw [h, std_basis_same] }, apply std_basis_ne _ _ _ _ h end @[simp] lemma matrix.to_lin'_apply (M : matrix m n R) (v : n → R) : matrix.to_lin' M v = M.mul_vec v := rfl @[simp] lemma matrix.to_lin'_one : matrix.to_lin' (1 : matrix n n R) = id := by { ext, simp } @[simp] lemma linear_map.to_matrix'_id : (linear_map.to_matrix' (linear_map.id : (n → R) →ₗ[R] (n → R))) = 1 := by { ext, rw [matrix.one_apply, linear_map.to_matrix'_apply, id_apply] } @[simp] lemma matrix.to_lin'_mul [decidable_eq m] (M : matrix l m R) (N : matrix m n R) : matrix.to_lin' (M ⬝ N) = (matrix.to_lin' M).comp (matrix.to_lin' N) := by { ext, simp } lemma linear_map.to_matrix'_comp [decidable_eq l] (f : (n → R) →ₗ[R] (m → R)) (g : (l → R) →ₗ[R] (n → R)) : (f.comp g).to_matrix' = f.to_matrix' ⬝ g.to_matrix' := suffices (f.comp g) = (f.to_matrix' ⬝ g.to_matrix').to_lin', by rw [this, linear_map.to_matrix'_to_lin'], by rw [matrix.to_lin'_mul, matrix.to_lin'_to_matrix', matrix.to_lin'_to_matrix'] lemma linear_map.to_matrix'_mul [decidable_eq m] (f g : (m → R) →ₗ[R] (m → R)) : (f * g).to_matrix' = f.to_matrix' ⬝ g.to_matrix' := linear_map.to_matrix'_comp f g end to_matrix' section to_matrix variables {R : Type*} [comm_ring R] variables {l m n : Type*} [fintype l] [fintype m] [fintype n] [decidable_eq n] variables {M₁ M₂ : Type*} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] variables {v₁ : n → M₁} (hv₁ : is_basis R v₁) {v₂ : m → M₂} (hv₂ : is_basis R v₂) /-- Given bases of two modules `M₁` and `M₂` over a commutative ring `R`, we get a linear equivalence between linear maps `M₁ →ₗ M₂` and matrices over `R` indexed by the bases. -/ def linear_map.to_matrix : (M₁ →ₗ[R] M₂) ≃ₗ[R] matrix m n R := linear_equiv.trans (linear_equiv.arrow_congr hv₁.equiv_fun hv₂.equiv_fun) linear_map.to_matrix' /-- Given bases of two modules `M₁` and `M₂` over a commutative ring `R`, we get a linear equivalence between matrices over `R` indexed by the bases and linear maps `M₁ →ₗ M₂`. -/ def matrix.to_lin : matrix m n R ≃ₗ[R] (M₁ →ₗ[R] M₂) := (linear_map.to_matrix hv₁ hv₂).symm @[simp] lemma linear_map.to_matrix_symm : (linear_map.to_matrix hv₁ hv₂).symm = matrix.to_lin hv₁ hv₂ := rfl @[simp] lemma matrix.to_lin_symm : (matrix.to_lin hv₁ hv₂).symm = linear_map.to_matrix hv₁ hv₂ := rfl @[simp] lemma matrix.to_lin_to_matrix (f : M₁ →ₗ[R] M₂) : matrix.to_lin hv₁ hv₂ (linear_map.to_matrix hv₁ hv₂ f) = f := by rw [← matrix.to_lin_symm, linear_equiv.apply_symm_apply] @[simp] lemma linear_map.to_matrix_to_lin (M : matrix m n R) : linear_map.to_matrix hv₁ hv₂ (matrix.to_lin hv₁ hv₂ M) = M := by rw [← matrix.to_lin_symm, linear_equiv.symm_apply_apply] lemma linear_map.to_matrix_apply (f : M₁ →ₗ[R] M₂) (i : m) (j : n) : linear_map.to_matrix hv₁ hv₂ f i j = hv₂.equiv_fun (f (v₁ j)) i := begin rw [linear_map.to_matrix, linear_equiv.trans_apply, linear_map.to_matrix'_apply, linear_equiv.arrow_congr_apply, is_basis.equiv_fun_symm_apply, finset.sum_eq_single j, if_pos rfl, one_smul], { intros j' _ hj', rw [if_neg hj', zero_smul] }, { intro hj, have := finset.mem_univ j, contradiction } end lemma linear_map.to_matrix_transpose_apply (f : M₁ →ₗ[R] M₂) (j : n) : (linear_map.to_matrix hv₁ hv₂ f)ᵀ j = hv₂.equiv_fun (f (v₁ j)) := funext $ λ i, f.to_matrix_apply _ _ i j lemma linear_map.to_matrix_apply' (f : M₁ →ₗ[R] M₂) (i : m) (j : n) : linear_map.to_matrix hv₁ hv₂ f i j = hv₂.repr (f (v₁ j)) i := linear_map.to_matrix_apply hv₁ hv₂ f i j lemma linear_map.to_matrix_transpose_apply' (f : M₁ →ₗ[R] M₂) (j : n) : (linear_map.to_matrix hv₁ hv₂ f)ᵀ j = hv₂.repr (f (v₁ j)) := linear_map.to_matrix_transpose_apply hv₁ hv₂ f j lemma matrix.to_lin_apply (M : matrix m n R) (v : M₁) : matrix.to_lin hv₁ hv₂ M v = ∑ j, M.mul_vec (hv₁.equiv_fun v) j • v₂ j := show hv₂.equiv_fun.symm (matrix.to_lin' M (hv₁.equiv_fun v)) = _, by rw [matrix.to_lin'_apply, hv₂.equiv_fun_symm_apply] @[simp] lemma matrix.to_lin_self (M : matrix m n R) (i : n) : matrix.to_lin hv₁ hv₂ M (v₁ i) = ∑ j, M j i • v₂ j := by simp only [matrix.to_lin_apply, matrix.mul_vec, dot_product, hv₁.equiv_fun_self, mul_boole, finset.sum_ite_eq, finset.mem_univ, if_true] @[simp] lemma linear_map.to_matrix_id : linear_map.to_matrix hv₁ hv₁ id = 1 := begin ext i j, simp [linear_map.to_matrix_apply, is_basis.equiv_fun, matrix.one_apply, finsupp.single, eq_comm] end @[simp] lemma matrix.to_lin_one : matrix.to_lin hv₁ hv₁ 1 = id := by rw [← linear_map.to_matrix_id hv₁, matrix.to_lin_to_matrix] theorem linear_map.to_matrix_range [decidable_eq M₁] [decidable_eq M₂] (f : M₁ →ₗ[R] M₂) (k : m) (i : n) : linear_map.to_matrix hv₁.range hv₂.range f ⟨v₂ k, mem_range_self k⟩ ⟨v₁ i, mem_range_self i⟩ = linear_map.to_matrix hv₁ hv₂ f k i := by simp_rw [linear_map.to_matrix_apply, subtype.coe_mk, is_basis.equiv_fun_apply, hv₂.range_repr] variables {M₃ : Type*} [add_comm_group M₃] [module R M₃] {v₃ : l → M₃} (hv₃ : is_basis R v₃) lemma linear_map.to_matrix_comp [decidable_eq m] (f : M₂ →ₗ[R] M₃) (g : M₁ →ₗ[R] M₂) : linear_map.to_matrix hv₁ hv₃ (f.comp g) = linear_map.to_matrix hv₂ hv₃ f ⬝ linear_map.to_matrix hv₁ hv₂ g := by simp_rw [linear_map.to_matrix, linear_equiv.trans_apply, linear_equiv.arrow_congr_comp _ hv₂.equiv_fun, linear_map.to_matrix'_comp] lemma linear_map.to_matrix_mul (f g : M₁ →ₗ[R] M₁) : linear_map.to_matrix hv₁ hv₁ (f * g) = linear_map.to_matrix hv₁ hv₁ f ⬝ linear_map.to_matrix hv₁ hv₁ g := by { rw [show (@has_mul.mul (M₁ →ₗ[R] M₁) _) = linear_map.comp, from rfl, linear_map.to_matrix_comp hv₁ hv₁ hv₁ f g] } lemma matrix.to_lin_mul [decidable_eq m] (A : matrix l m R) (B : matrix m n R) : matrix.to_lin hv₁ hv₃ (A ⬝ B) = (matrix.to_lin hv₂ hv₃ A).comp (matrix.to_lin hv₁ hv₂ B) := begin apply (linear_map.to_matrix hv₁ hv₃).injective, haveI : decidable_eq l := λ _ _, classical.prop_decidable _, rw linear_map.to_matrix_comp hv₁ hv₂ hv₃, repeat { rw linear_map.to_matrix_to_lin }, end end to_matrix section is_basis_to_matrix variables {ι ι' : Type*} [fintype ι] [fintype ι'] variables {R M : Type*} [comm_ring R] [add_comm_group M] [module R M] open function matrix /-- From a basis `e : ι → M` and a family of vectors `v : ι' → M`, make the matrix whose columns are the vectors `v i` written in the basis `e`. -/ def is_basis.to_matrix {e : ι → M} (he : is_basis R e) (v : ι' → M) : matrix ι ι' R := λ i j, he.equiv_fun (v j) i variables {e : ι → M} (he : is_basis R e) (v : ι' → M) (i : ι) (j : ι') namespace is_basis lemma to_matrix_apply : he.to_matrix v i j = he.equiv_fun (v j) i := rfl lemma to_matrix_transpose_apply : (he.to_matrix v)ᵀ j = he.repr (v j) := funext $ (λ _, rfl) lemma to_matrix_eq_to_matrix_constr [decidable_eq ι] (v : ι → M) : he.to_matrix v = linear_map.to_matrix he he (he.constr v) := by { ext, simp [is_basis.to_matrix_apply, linear_map.to_matrix_apply] } @[simp] lemma to_matrix_self [decidable_eq ι] : he.to_matrix e = 1 := begin rw is_basis.to_matrix, ext i j, simp [is_basis.equiv_fun, matrix.one_apply, finsupp.single, eq_comm] end lemma to_matrix_update [decidable_eq ι'] (x : M) : he.to_matrix (function.update v j x) = matrix.update_column (he.to_matrix v) j (he.repr x) := begin ext i' k, rw [is_basis.to_matrix, matrix.update_column_apply, he.to_matrix_apply], split_ifs, { rw [h, update_same j x v, he.equiv_fun_apply] }, { rw update_noteq h }, end @[simp] lemma sum_to_matrix_smul_self : ∑ (i : ι), he.to_matrix v i j • e i = v j := begin conv_rhs { rw ← he.total_repr (v j) }, rw [finsupp.total_apply, finsupp.sum_fintype], { refl }, simp end @[simp] lemma to_lin_to_matrix [decidable_eq ι'] (hv : is_basis R v) : matrix.to_lin hv he (he.to_matrix v) = id := hv.ext (λ i, by rw [to_lin_self, id_apply, he.sum_to_matrix_smul_self]) /-- From a basis `e : ι → M`, build a linear equivalence between families of vectors `v : ι → M`, and matrices, making the matrix whose columns are the vectors `v i` written in the basis `e`. -/ def to_matrix_equiv {e : ι → M} (he : is_basis R e) : (ι → M) ≃ₗ[R] matrix ι ι R := { to_fun := he.to_matrix, map_add' := λ v w, begin ext i j, change _ = _ + _, simp [he.to_matrix_apply] end, map_smul' := begin intros c v, ext i j, simp [he.to_matrix_apply] end, inv_fun := λ m j, ∑ i, (m i j) • e i, left_inv := begin intro v, ext j, simp [he.to_matrix_apply, he.equiv_fun_total (v j)] end, right_inv := begin intros x, ext k l, simp [he.to_matrix_apply, he.equiv_fun.map_sum, he.equiv_fun.map_smul, fintype.sum_apply k (λ i, x i l • he.equiv_fun (e i)), he.equiv_fun_self] end } end is_basis section mul_linear_map_to_matrix variables {N : Type*} [add_comm_group N] [module R N] variables {b : ι → M} {b' : ι' → M} {c : ι → N} {c' : ι' → N} variables (hb : is_basis R b) (hb' : is_basis R b') (hc : is_basis R c) (hc' : is_basis R c') variables (f : M →ₗ[R] N) @[simp] lemma is_basis_to_matrix_mul_linear_map_to_matrix [decidable_eq ι'] : hc.to_matrix c' ⬝ linear_map.to_matrix hb' hc' f = linear_map.to_matrix hb' hc f := (matrix.to_lin hb' hc).injective (by rw [to_lin_to_matrix, to_lin_mul hb' hc' hc, to_lin_to_matrix, hc.to_lin_to_matrix, id_comp]) @[simp] lemma linear_map_to_matrix_mul_is_basis_to_matrix [decidable_eq ι] [decidable_eq ι'] : linear_map.to_matrix hb' hc' f ⬝ hb'.to_matrix b = linear_map.to_matrix hb hc' f := (matrix.to_lin hb hc').injective (by rw [to_lin_to_matrix, to_lin_mul hb hb' hc', to_lin_to_matrix, hb'.to_lin_to_matrix, comp_id]) end mul_linear_map_to_matrix end is_basis_to_matrix open_locale matrix section det open linear_map matrix variables {R : Type} [comm_ring R] variables {M : Type*} [add_comm_group M] [module R M] variables {M' : Type*} [add_comm_group M'] [module R M'] variables {ι : Type*} [decidable_eq ι] [fintype ι] {v : ι → M} {v' : ι → M'} lemma linear_equiv.is_unit_det (f : M ≃ₗ[R] M') (hv : is_basis R v) (hv' : is_basis R v') : is_unit (linear_map.to_matrix hv hv' f).det := begin apply is_unit_det_of_left_inverse, simpa using (linear_map.to_matrix_comp hv hv' hv f.symm f).symm end /-- Builds a linear equivalence from a linear map whose determinant in some bases is a unit. -/ def linear_equiv.of_is_unit_det {f : M →ₗ[R] M'} {hv : is_basis R v} {hv' : is_basis R v'} (h : is_unit (linear_map.to_matrix hv hv' f).det) : M ≃ₗ[R] M' := { to_fun := f, map_add' := f.map_add, map_smul' := f.map_smul, inv_fun := to_lin hv' hv (to_matrix hv hv' f)⁻¹, left_inv := λ x, calc to_lin hv' hv (to_matrix hv hv' f)⁻¹ (f x) = to_lin hv hv ((to_matrix hv hv' f)⁻¹ ⬝ to_matrix hv hv' f) x : by { rw [to_lin_mul hv hv' hv, to_lin_to_matrix, linear_map.comp_apply] } ... = x : by simp [h], right_inv := λ x, calc f (to_lin hv' hv (to_matrix hv hv' f)⁻¹ x) = to_lin hv' hv' (to_matrix hv hv' f ⬝ (to_matrix hv hv' f)⁻¹) x : by { rw [to_lin_mul hv' hv hv', linear_map.comp_apply, to_lin_to_matrix hv hv'] } ... = x : by simp [h], } variables {e : ι → M} (he : is_basis R e) /-- The determinant of a family of vectors with respect to some basis, as an alternating multilinear map. -/ def is_basis.det : alternating_map R M R ι := { to_fun := λ v, det (he.to_matrix v), map_add' := begin intros v i x y, simp only [he.to_matrix_update, linear_map.map_add], apply det_update_column_add end, map_smul' := begin intros u i c x, simp only [he.to_matrix_update, algebra.id.smul_eq_mul, map_smul_of_tower], apply det_update_column_smul end, map_eq_zero_of_eq' := begin intros v i j h hij, rw [←function.update_eq_self i v, h, ←det_transpose, he.to_matrix_update, ←update_row_transpose, ←he.to_matrix_transpose_apply], apply det_zero_of_row_eq hij, rw [update_row_ne hij.symm, update_row_self], end } lemma is_basis.det_apply (v : ι → M) : he.det v = det (he.to_matrix v) := rfl lemma is_basis.det_self : he.det e = 1 := by simp [he.det_apply] lemma is_basis.iff_det {v : ι → M} : is_basis R v ↔ is_unit (he.det v) := begin split, { intro hv, suffices : is_unit (linear_map.to_matrix he he (linear_equiv_of_is_basis he hv $ equiv.refl ι)).det, { rw [is_basis.det_apply, is_basis.to_matrix_eq_to_matrix_constr], exact this }, apply linear_equiv.is_unit_det }, { intro h, rw [is_basis.det_apply, is_basis.to_matrix_eq_to_matrix_constr] at h, convert linear_equiv.is_basis he (linear_equiv.of_is_unit_det h), ext i, exact (constr_basis he).symm }, end end det section transpose variables {K V₁ V₂ ι₁ ι₂ : Type*} [field K] [add_comm_group V₁] [vector_space K V₁] [add_comm_group V₂] [vector_space K V₂] [fintype ι₁] [fintype ι₂] [decidable_eq ι₁] [decidable_eq ι₂] {B₁ : ι₁ → V₁} (h₁ : is_basis K B₁) {B₂ : ι₂ → V₂} (h₂ : is_basis K B₂) @[simp] lemma linear_map.to_matrix_transpose (u : V₁ →ₗ[K] V₂) : linear_map.to_matrix h₂.dual_basis_is_basis h₁.dual_basis_is_basis (module.dual.transpose u) = (linear_map.to_matrix h₁ h₂ u)ᵀ := begin ext i j, simp only [linear_map.to_matrix_apply, module.dual.transpose_apply, h₁.dual_basis_equiv_fun, h₂.dual_basis_apply, matrix.transpose_apply, linear_map.comp_apply] end lemma linear_map.to_matrix_symm_transpose (M : matrix ι₁ ι₂ K) : (linear_map.to_matrix h₁.dual_basis_is_basis h₂.dual_basis_is_basis).symm Mᵀ = module.dual.transpose (matrix.to_lin h₂ h₁ M) := begin apply (linear_map.to_matrix h₁.dual_basis_is_basis h₂.dual_basis_is_basis).injective, rw [linear_equiv.apply_symm_apply], ext i j, simp only [linear_map.to_matrix_apply, module.dual.transpose_apply, h₂.dual_basis_equiv_fun, h₁.dual_basis_apply, matrix.transpose_apply, linear_map.comp_apply, if_true, matrix.to_lin_apply, linear_equiv.map_smul, mul_boole, algebra.id.smul_eq_mul, linear_equiv.map_sum, is_basis.equiv_fun_self, fintype.sum_apply, finset.sum_ite_eq', finset.sum_ite_eq, is_basis.equiv_fun_symm_apply, pi.smul_apply, matrix.to_lin_apply, matrix.mul_vec, matrix.dot_product, is_basis.equiv_fun_self, finset.mem_univ] end end transpose namespace matrix section trace variables {m : Type*} [fintype m] (n : Type*) [fintype n] variables (R : Type v) (M : Type w) [semiring R] [add_comm_monoid M] [semimodule R M] /-- The diagonal of a square matrix. -/ def diag : (matrix n n M) →ₗ[R] n → M := { to_fun := λ A i, A i i, map_add' := by { intros, ext, refl, }, map_smul' := by { intros, ext, refl, } } variables {n} {R} {M} @[simp] lemma diag_apply (A : matrix n n M) (i : n) : diag n R M A i = A i i := rfl @[simp] lemma diag_one [decidable_eq n] : diag n R R 1 = λ i, 1 := by { dunfold diag, ext, simp [one_apply_eq] } @[simp] lemma diag_transpose (A : matrix n n M) : diag n R M Aᵀ = diag n R M A := rfl variables (n) (R) (M) /-- The trace of a square matrix. -/ def trace : (matrix n n M) →ₗ[R] M := { to_fun := λ A, ∑ i, diag n R M A i, map_add' := by { intros, apply finset.sum_add_distrib, }, map_smul' := by { intros, simp [finset.smul_sum], } } variables {n} {R} {M} @[simp] lemma trace_diag (A : matrix n n M) : trace n R M A = ∑ i, diag n R M A i := rfl @[simp] lemma trace_one [decidable_eq n] : trace n R R 1 = fintype.card n := have h : trace n R R 1 = ∑ i, diag n R R 1 i := rfl, by simp_rw [h, diag_one, finset.sum_const, nsmul_one]; refl @[simp] lemma trace_transpose (A : matrix n n M) : trace n R M Aᵀ = trace n R M A := rfl @[simp] lemma trace_transpose_mul (A : matrix m n R) (B : matrix n m R) : trace n R R (Aᵀ ⬝ Bᵀ) = trace m R R (A ⬝ B) := finset.sum_comm lemma trace_mul_comm {S : Type v} [comm_ring S] (A : matrix m n S) (B : matrix n m S) : trace n S S (B ⬝ A) = trace m S S (A ⬝ B) := by rw [←trace_transpose, ←trace_transpose_mul, transpose_mul] end trace section ring variables {n : Type*} [fintype n] [decidable_eq n] {R : Type v} [comm_ring R] open linear_map matrix lemma proj_diagonal (i : n) (w : n → R) : (proj i).comp (to_lin' (diagonal w)) = (w i) • proj i := by ext j; simp [mul_vec_diagonal] lemma diagonal_comp_std_basis (w : n → R) (i : n) : (diagonal w).to_lin'.comp (std_basis R (λ_:n, R) i) = (w i) • std_basis R (λ_:n, R) i := begin ext j, simp_rw [linear_map.comp_apply, to_lin'_apply, mul_vec_diagonal, linear_map.smul_apply, pi.smul_apply, algebra.id.smul_eq_mul], by_cases i = j, { subst h }, { rw [std_basis_ne R (λ_:n, R) _ _ (ne.symm h), _root_.mul_zero, _root_.mul_zero] } end lemma diagonal_to_lin' (w : n → R) : (diagonal w).to_lin' = linear_map.pi (λi, w i • linear_map.proj i) := by ext v j; simp [mul_vec_diagonal] /-- An invertible matrix yields a linear equivalence from the free module to itself. -/ def to_linear_equiv (P : matrix n n R) (h : is_unit P) : (n → R) ≃ₗ[R] (n → R) := have h' : is_unit P.det := P.is_unit_iff_is_unit_det.mp h, { inv_fun := P⁻¹.to_lin', left_inv := λ v, show (P⁻¹.to_lin'.comp P.to_lin') v = v, by rw [← matrix.to_lin'_mul, P.nonsing_inv_mul h', matrix.to_lin'_one, linear_map.id_apply], right_inv := λ v, show (P.to_lin'.comp P⁻¹.to_lin') v = v, by rw [← matrix.to_lin'_mul, P.mul_nonsing_inv h', matrix.to_lin'_one, linear_map.id_apply], ..P.to_lin' } @[simp] lemma to_linear_equiv_apply (P : matrix n n R) (h : is_unit P) : (↑(P.to_linear_equiv h) : module.End R (n → R)) = P.to_lin' := rfl @[simp] lemma to_linear_equiv_symm_apply (P : matrix n n R) (h : is_unit P) : (↑(P.to_linear_equiv h).symm : module.End R (n → R)) = P⁻¹.to_lin' := rfl end ring section vector_space variables {m n : Type*} [fintype m] [fintype n] variables {K : Type u} [field K] -- maybe try to relax the universe constraint open linear_map matrix lemma rank_vec_mul_vec {m n : Type u} [fintype m] [fintype n] [decidable_eq n] (w : m → K) (v : n → K) : rank (vec_mul_vec w v).to_lin' ≤ 1 := begin rw [vec_mul_vec_eq, to_lin'_mul], refine le_trans (rank_comp_le1 _ _) _, refine le_trans (rank_le_domain _) _, rw [dim_fun', ← cardinal.lift_eq_nat_iff.mpr (cardinal.fintype_card unit), cardinal.mk_unit], exact le_of_eq (cardinal.lift_one) end lemma ker_diagonal_to_lin' [decidable_eq m] (w : m → K) : ker (diagonal w).to_lin' = (⨆i∈{i | w i = 0 }, range (std_basis K (λi, K) i)) := begin rw [← comap_bot, ← infi_ker_proj], simp only [comap_infi, (ker_comp _ _).symm, proj_diagonal, ker_smul'], have : univ ⊆ {i : m | w i = 0} ∪ {i : m | w i = 0}ᶜ, { rw set.union_compl_self }, exact (supr_range_std_basis_eq_infi_ker_proj K (λi:m, K) disjoint_compl_right this (finite.of_fintype _)).symm end lemma range_diagonal [decidable_eq m] (w : m → K) : (diagonal w).to_lin'.range = (⨆ i ∈ {i | w i ≠ 0}, (std_basis K (λi, K) i).range) := begin dsimp only [mem_set_of_eq], rw [← map_top, ← supr_range_std_basis, map_supr], congr, funext i, rw [← linear_map.range_comp, diagonal_comp_std_basis, ← range_smul'] end lemma rank_diagonal [decidable_eq m] [decidable_eq K] (w : m → K) : rank (diagonal w).to_lin' = fintype.card { i // w i ≠ 0 } := begin have hu : univ ⊆ {i : m | w i = 0}ᶜ ∪ {i : m | w i = 0}, { rw set.compl_union_self }, have hd : disjoint {i : m | w i ≠ 0} {i : m | w i = 0} := disjoint_compl_left, have h₁ := supr_range_std_basis_eq_infi_ker_proj K (λi:m, K) hd hu (finite.of_fintype _), have h₂ := @infi_ker_proj_equiv K _ _ (λi:m, K) _ _ _ _ (by simp; apply_instance) hd hu, rw [rank, range_diagonal, h₁, ←@dim_fun' K], apply linear_equiv.dim_eq, apply h₂, end end vector_space section finite_dimensional variables {m n : Type*} [fintype m] [fintype n] variables {R : Type v} [field R] instance : finite_dimensional R (matrix m n R) := linear_equiv.finite_dimensional (linear_equiv.uncurry R m n).symm /-- The dimension of the space of finite dimensional matrices is the product of the number of rows and columns. -/ @[simp] lemma findim_matrix : finite_dimensional.findim R (matrix m n R) = fintype.card m * fintype.card n := by rw [@linear_equiv.findim_eq R (matrix m n R) _ _ _ _ _ _ (linear_equiv.uncurry R m n), finite_dimensional.findim_fintype_fun_eq_card, fintype.card_prod] end finite_dimensional section reindexing variables {l m n : Type*} [fintype l] [fintype m] [fintype n] variables {l' m' n' : Type*} [fintype l'] [fintype m'] [fintype n'] variables {R : Type v} /-- The natural map that reindexes a matrix's rows and columns with equivalent types is an equivalence. -/ def reindex (eₘ : m ≃ m') (eₙ : n ≃ n') : matrix m n R ≃ matrix m' n' R := { to_fun := λ M i j, M (eₘ.symm i) (eₙ.symm j), inv_fun := λ M i j, M (eₘ i) (eₙ j), left_inv := λ M, by simp, right_inv := λ M, by simp, } @[simp] lemma reindex_apply (eₘ : m ≃ m') (eₙ : n ≃ n') (M : matrix m n R) : reindex eₘ eₙ M = λ i j, M (eₘ.symm i) (eₙ.symm j) := rfl @[simp] lemma reindex_symm_apply (eₘ : m ≃ m') (eₙ : n ≃ n') (M : matrix m' n' R) : (reindex eₘ eₙ).symm M = λ i j, M (eₘ i) (eₙ j) := rfl /-- The natural map that reindexes a matrix's rows and columns with equivalent types is a linear equivalence. -/ def reindex_linear_equiv [semiring R] (eₘ : m ≃ m') (eₙ : n ≃ n') : matrix m n R ≃ₗ[R] matrix m' n' R := { map_add' := λ M N, rfl, map_smul' := λ M N, rfl, ..(reindex eₘ eₙ)} @[simp] lemma reindex_linear_equiv_apply [semiring R] (eₘ : m ≃ m') (eₙ : n ≃ n') (M : matrix m n R) : reindex_linear_equiv eₘ eₙ M = λ i j, M (eₘ.symm i) (eₙ.symm j) := rfl @[simp] lemma reindex_linear_equiv_symm_apply [semiring R] (eₘ : m ≃ m') (eₙ : n ≃ n') (M : matrix m' n' R) : (reindex_linear_equiv eₘ eₙ).symm M = λ i j, M (eₘ i) (eₙ j) := rfl lemma reindex_mul [semiring R] (eₘ : m ≃ m') (eₙ : n ≃ n') (eₗ : l ≃ l') (M : matrix m n R) (N : matrix n l R) : (reindex_linear_equiv eₘ eₙ M) ⬝ (reindex_linear_equiv eₙ eₗ N) = reindex_linear_equiv eₘ eₗ (M ⬝ N) := begin ext i j, dsimp only [matrix.mul, matrix.dot_product], rw [←finset.univ_map_equiv_to_embedding eₙ, finset.sum_map finset.univ eₙ.to_embedding], simp, end /-- For square matrices, the natural map that reindexes a matrix's rows and columns with equivalent types is an equivalence of algebras. -/ def reindex_alg_equiv [comm_semiring R] [decidable_eq m] [decidable_eq n] (e : m ≃ n) : matrix m m R ≃ₐ[R] matrix n n R := { map_mul' := λ M N, by simp only [reindex_mul, linear_equiv.to_fun_apply, mul_eq_mul], commutes' := λ r, by { ext, simp [algebra_map, algebra.to_ring_hom], by_cases h : i = j; simp [h], }, ..(reindex_linear_equiv e e) } @[simp] lemma reindex_alg_equiv_apply [comm_semiring R] [decidable_eq m] [decidable_eq n] (e : m ≃ n) (M : matrix m m R) : reindex_alg_equiv e M = λ i j, M (e.symm i) (e.symm j) := rfl @[simp] lemma reindex_alg_equiv_symm_apply [comm_semiring R] [decidable_eq m] [decidable_eq n] (e : m ≃ n) (M : matrix n n R) : (reindex_alg_equiv e).symm M = λ i j, M (e i) (e j) := rfl lemma reindex_transpose (eₘ : m ≃ m') (eₙ : n ≃ n') (M : matrix m n R) : (reindex eₘ eₙ M)ᵀ = (reindex eₙ eₘ Mᵀ) := rfl /-- `simp` version of `det_reindex_self` `det_reindex_self` is not a good simp lemma because `reindex_apply` fires before. So we have this lemma to continue from there. -/ @[simp] lemma det_reindex_self' [decidable_eq m] [decidable_eq n] [comm_ring R] (e : m ≃ n) (A : matrix m m R) : det (λ i j, A (e.symm i) (e.symm j)) = det A := begin unfold det, apply finset.sum_bij' (λ σ _, equiv.perm_congr e.symm σ) _ _ (λ σ _, equiv.perm_congr e σ), { intros σ _, ext, simp only [equiv.symm_symm, equiv.perm_congr_apply, equiv.apply_symm_apply] }, { intros σ _, ext, simp only [equiv.symm_symm, equiv.perm_congr_apply, equiv.symm_apply_apply] }, { intros σ _, apply finset.mem_univ }, { intros σ _, apply finset.mem_univ }, intros σ _, simp_rw [equiv.perm_congr_apply, equiv.symm_symm], congr, { convert (equiv.perm.sign_perm_congr e.symm σ).symm }, apply finset.prod_bij' (λ i _, e.symm i) _ _ (λ i _, e i), { intros, simp_rw equiv.apply_symm_apply }, { intros, simp_rw equiv.symm_apply_apply }, { intros, apply finset.mem_univ }, { intros, apply finset.mem_univ }, { intros, simp_rw equiv.apply_symm_apply }, end /-- Reindexing both indices along the same equivalence preserves the determinant. For the `simp` version of this lemma, see `det_reindex_self'`. -/ lemma det_reindex_self [decidable_eq m] [decidable_eq n] [comm_ring R] (e : m ≃ n) (A : matrix m m R) : det (reindex e e A) = det A := det_reindex_self' e A /-- Reindexing both indices along the same equivalence preserves the determinant. For the `simp` version of this lemma, see `det_reindex_self'`. -/ lemma det_reindex_linear_equiv_self [decidable_eq m] [decidable_eq n] [comm_ring R] (e : m ≃ n) (A : matrix m m R) : det (reindex_linear_equiv e e A) = det A := det_reindex_self' e A /-- Reindexing both indices along the same equivalence preserves the determinant. For the `simp` version of this lemma, see `det_reindex_self'`. -/ lemma det_reindex_alg_equiv [decidable_eq m] [decidable_eq n] [comm_ring R] (e : m ≃ n) (A : matrix m m R) : det (reindex_alg_equiv e A) = det A := det_reindex_self' e A end reindexing end matrix namespace linear_map open_locale matrix /-- The trace of an endomorphism given a basis. -/ def trace_aux (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M] {ι : Type w} [decidable_eq ι] [fintype ι] {b : ι → M} (hb : is_basis R b) : (M →ₗ[R] M) →ₗ[R] R := (matrix.trace ι R R).comp $ linear_map.to_matrix hb hb @[simp] lemma trace_aux_def (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M] {ι : Type w} [decidable_eq ι] [fintype ι] {b : ι → M} (hb : is_basis R b) (f : M →ₗ[R] M) : trace_aux R hb f = matrix.trace ι R R (linear_map.to_matrix hb hb f) := rfl theorem trace_aux_eq' (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M] {ι : Type w} [decidable_eq ι] [fintype ι] {b : ι → M} (hb : is_basis R b) {κ : Type w} [decidable_eq κ] [fintype κ] {c : κ → M} (hc : is_basis R c) : trace_aux R hb = trace_aux R hc := linear_map.ext $ λ f, calc matrix.trace ι R R (linear_map.to_matrix hb hb f) = matrix.trace ι R R (linear_map.to_matrix hb hb ((linear_map.id.comp f).comp linear_map.id)) : by rw [linear_map.id_comp, linear_map.comp_id] ... = matrix.trace ι R R (linear_map.to_matrix hc hb linear_map.id ⬝ linear_map.to_matrix hc hc f ⬝ linear_map.to_matrix hb hc linear_map.id) : by rw [linear_map.to_matrix_comp _ hc, linear_map.to_matrix_comp _ hc] ... = matrix.trace κ R R (linear_map.to_matrix hc hc f ⬝ linear_map.to_matrix hb hc linear_map.id ⬝ linear_map.to_matrix hc hb linear_map.id) : by rw [matrix.mul_assoc, matrix.trace_mul_comm] ... = matrix.trace κ R R (linear_map.to_matrix hc hc ((f.comp linear_map.id).comp linear_map.id)) : by rw [linear_map.to_matrix_comp _ hb, linear_map.to_matrix_comp _ hc] ... = matrix.trace κ R R (linear_map.to_matrix hc hc f) : by rw [linear_map.comp_id, linear_map.comp_id] open_locale classical theorem trace_aux_range (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M] {ι : Type w} [decidable_eq ι] [fintype ι] {b : ι → M} (hb : is_basis R b) : trace_aux R hb.range = trace_aux R hb := linear_map.ext $ λ f, if H : 0 = 1 then eq_of_zero_eq_one H _ _ else begin haveI : nontrivial R := ⟨⟨0, 1, H⟩⟩, change ∑ i : set.range b, _ = ∑ i : ι, _, simp_rw [matrix.diag_apply], symmetry, convert (equiv.of_injective _ hb.injective).sum_comp _, ext i, exact (linear_map.to_matrix_range hb hb f i i).symm end /-- where `ι` and `κ` can reside in different universes -/ theorem trace_aux_eq (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M] {ι : Type*} [decidable_eq ι] [fintype ι] {b : ι → M} (hb : is_basis R b) {κ : Type*} [decidable_eq κ] [fintype κ] {c : κ → M} (hc : is_basis R c) : trace_aux R hb = trace_aux R hc := calc trace_aux R hb = trace_aux R hb.range : by rw trace_aux_range R hb ... = trace_aux R hc.range : trace_aux_eq' _ _ _ ... = trace_aux R hc : by rw trace_aux_range R hc /-- Trace of an endomorphism independent of basis. -/ def trace (R : Type u) [comm_ring R] (M : Type v) [add_comm_group M] [module R M] : (M →ₗ[R] M) →ₗ[R] R := if H : ∃ s : finset M, is_basis R (λ x, x : (↑s : set M) → M) then trace_aux R (classical.some_spec H) else 0 theorem trace_eq_matrix_trace (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M] {ι : Type w} [fintype ι] [decidable_eq ι] {b : ι → M} (hb : is_basis R b) (f : M →ₗ[R] M) : trace R M f = matrix.trace ι R R (linear_map.to_matrix hb hb f) := have ∃ s : finset M, is_basis R (λ x, x : (↑s : set M) → M), from ⟨finset.univ.image b, by { rw [finset.coe_image, finset.coe_univ, set.image_univ], exact hb.range }⟩, by { rw [trace, dif_pos this, ← trace_aux_def], congr' 1, apply trace_aux_eq } theorem trace_mul_comm (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M] (f g : M →ₗ[R] M) : trace R M (f * g) = trace R M (g * f) := if H : ∃ s : finset M, is_basis R (λ x, x : (↑s : set M) → M) then let ⟨s, hb⟩ := H in by { simp_rw [trace_eq_matrix_trace R hb, linear_map.to_matrix_mul], apply matrix.trace_mul_comm } else by rw [trace, dif_neg H, linear_map.zero_apply, linear_map.zero_apply] section finite_dimensional variables {K : Type*} [field K] variables {V : Type*} [add_comm_group V] [vector_space K V] [finite_dimensional K V] variables {W : Type*} [add_comm_group W] [vector_space K W] [finite_dimensional K W] instance : finite_dimensional K (V →ₗ[K] W) := begin classical, cases finite_dimensional.exists_is_basis_finset K V with bV hbV, cases finite_dimensional.exists_is_basis_finset K W with bW hbW, apply linear_equiv.finite_dimensional (linear_map.to_matrix hbV hbW).symm, end /-- The dimension of the space of linear transformations is the product of the dimensions of the domain and codomain. -/ @[simp] lemma findim_linear_map : finite_dimensional.findim K (V →ₗ[K] W) = (finite_dimensional.findim K V) * (finite_dimensional.findim K W) := begin classical, cases finite_dimensional.exists_is_basis_finset K V with bV hbV, cases finite_dimensional.exists_is_basis_finset K W with bW hbW, rw [linear_equiv.findim_eq (linear_map.to_matrix hbV hbW), matrix.findim_matrix, finite_dimensional.findim_eq_card_basis hbV, finite_dimensional.findim_eq_card_basis hbW, mul_comm], end end finite_dimensional end linear_map /-- The natural equivalence between linear endomorphisms of finite free modules and square matrices is compatible with the algebra structures. -/ def alg_equiv_matrix' {R : Type v} [comm_ring R] {n : Type*} [fintype n] [decidable_eq n] : module.End R (n → R) ≃ₐ[R] matrix n n R := { map_mul' := linear_map.to_matrix'_comp, map_add' := linear_map.to_matrix'.map_add, commutes' := λ r, by { change (r • (linear_map.id : module.End R _)).to_matrix' = r • 1, rw ←linear_map.to_matrix'_id, refl, }, ..linear_map.to_matrix' } /-- A linear equivalence of two modules induces an equivalence of algebras of their endomorphisms. -/ def linear_equiv.alg_conj {R : Type v} [comm_ring R] {M₁ M₂ : Type*} [add_comm_group M₁] [module R M₁] [add_comm_group M₂] [module R M₂] (e : M₁ ≃ₗ[R] M₂) : module.End R M₁ ≃ₐ[R] module.End R M₂ := { map_mul' := λ f g, by apply e.arrow_congr_comp, map_add' := e.conj.map_add, commutes' := λ r, by { change e.conj (r • linear_map.id) = r • linear_map.id, rw [linear_equiv.map_smul, linear_equiv.conj_id], }, ..e.conj } /-- A basis of a module induces an equivalence of algebras from the endomorphisms of the module to square matrices. -/ def alg_equiv_matrix {R : Type v} {M : Type w} {n : Type*} [fintype n] [comm_ring R] [add_comm_group M] [module R M] [decidable_eq n] {b : n → M} (h : is_basis R b) : module.End R M ≃ₐ[R] matrix n n R := h.equiv_fun.alg_conj.trans alg_equiv_matrix' section variables {R : Type v} [semiring R] {n : Type w} [fintype n] @[simp] lemma matrix.dot_product_std_basis_eq_mul [decidable_eq n] (v : n → R) (c : R) (i : n) : matrix.dot_product v (linear_map.std_basis R (λ _, R) i c) = v i * c := begin rw [matrix.dot_product, finset.sum_eq_single i, linear_map.std_basis_same], exact λ _ _ hb, by rw [linear_map.std_basis_ne _ _ _ _ hb, mul_zero], exact λ hi, false.elim (hi $ finset.mem_univ _) end @[simp] lemma matrix.dot_product_std_basis_one [decidable_eq n] (v : n → R) (i : n) : matrix.dot_product v (linear_map.std_basis R (λ _, R) i 1) = v i := by rw [matrix.dot_product_std_basis_eq_mul, mul_one] lemma matrix.dot_product_eq (v w : n → R) (h : ∀ u, matrix.dot_product v u = matrix.dot_product w u) : v = w := begin funext x, classical, rw [← matrix.dot_product_std_basis_one v x, ← matrix.dot_product_std_basis_one w x, h], end lemma matrix.dot_product_eq_iff {v w : n → R} : (∀ u, matrix.dot_product v u = matrix.dot_product w u) ↔ v = w := ⟨λ h, matrix.dot_product_eq v w h, λ h _, h ▸ rfl⟩ lemma matrix.dot_product_eq_zero (v : n → R) (h : ∀ w, matrix.dot_product v w = 0) : v = 0 := matrix.dot_product_eq _ _ $ λ u, (h u).symm ▸ (zero_dot_product u).symm lemma matrix.dot_product_eq_zero_iff {v : n → R} : (∀ w, matrix.dot_product v w = 0) ↔ v = 0 := ⟨λ h, matrix.dot_product_eq_zero v h, λ h w, h.symm ▸ zero_dot_product w⟩ end
2a0dd75641294ca3792962ff5449e08e35ea629d
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/key_eqv1.lean
141c05217d0cf375fe64c761c7ffa940dbcb7239
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
124
lean
add_key_equivalence add nat.add add_key_equivalence nat.add nat.succ add_key_equivalence mul nat.mul print key_equivalences
d455840e153b4980de747471b9ad9005dc2e5cfa
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/geometry/manifold/mfderiv.lean
a685f0d3659e71e4592587e5fb7f0a31348324e3
[ "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
71,159
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import geometry.manifold.basic_smooth_bundle /-! # The derivative of functions between smooth manifolds Let `M` and `M'` be two smooth manifolds with corners over a field `𝕜` (with respective models with corners `I` on `(E, H)` and `I'` on `(E', H')`), and let `f : M → M'`. We define the derivative of the function at a point, within a set or along the whole space, mimicking the API for (Fréchet) derivatives. It is denoted by `mfderiv I I' f x`, where "m" stands for "manifold" and "f" for "Fréchet" (as in the usual derivative `fderiv 𝕜 f x`). ## Main definitions * `unique_mdiff_on I s` : predicate saying that, at each point of the set `s`, a function can have at most one derivative. This technical condition is important when we define `mfderiv_within` below, as otherwise there is an arbitrary choice in the derivative, and many properties will fail (for instance the chain rule). This is analogous to `unique_diff_on 𝕜 s` in a vector space. Let `f` be a map between smooth manifolds. The following definitions follow the `fderiv` API. * `mfderiv I I' f x` : the derivative of `f` at `x`, as a continuous linear map from the tangent space at `x` to the tangent space at `f x`. If the map is not differentiable, this is `0`. * `mfderiv_within I I' f s x` : the derivative of `f` at `x` within `s`, as a continuous linear map from the tangent space at `x` to the tangent space at `f x`. If the map is not differentiable within `s`, this is `0`. * `mdifferentiable_at I I' f x` : Prop expressing whether `f` is differentiable at `x`. * `mdifferentiable_within_at 𝕜 f s x` : Prop expressing whether `f` is differentiable within `s` at `x`. * `has_mfderiv_at I I' f s x f'` : Prop expressing whether `f` has `f'` as a derivative at `x`. * `has_mfderiv_within_at I I' f s x f'` : Prop expressing whether `f` has `f'` as a derivative within `s` at `x`. * `mdifferentiable_on I I' f s` : Prop expressing that `f` is differentiable on the set `s`. * `mdifferentiable I I' f` : Prop expressing that `f` is differentiable everywhere. * `tangent_map I I' f` : the derivative of `f`, as a map from the tangent bundle of `M` to the tangent bundle of `M'`. We also establish results on the differential of the identity, constant functions, charts, extended charts. For functions between vector spaces, we show that the usual notions and the manifold notions coincide. ## Implementation notes The tangent bundle is constructed using the machinery of topological fiber bundles, for which one can define bundled morphisms and construct canonically maps from the total space of one bundle to the total space of another one. One could use this mechanism to construct directly the derivative of a smooth map. However, we want to define the derivative of any map (and let it be zero if the map is not differentiable) to avoid proof arguments everywhere. This means we have to go back to the details of the definition of the total space of a fiber bundle constructed from core, to cook up a suitable definition of the derivative. It is the following: at each point, we have a preferred chart (used to identify the fiber above the point with the model vector space in fiber bundles). Then one should read the function using these preferred charts at `x` and `f x`, and take the derivative of `f` in these charts. Due to the fact that we are working in a model with corners, with an additional embedding `I` of the model space `H` in the model vector space `E`, the charts taking values in `E` are not the original charts of the manifold, but those ones composed with `I`, called extended charts. We define `written_in_ext_chart I I' x f` for the function `f` written in the preferred extended charts. Then the manifold derivative of `f`, at `x`, is just the usual derivative of `written_in_ext_chart I I' x f`, at the point `(ext_chart_at I x) x`. There is a subtelty with respect to continuity: if the function is not continuous, then the image of a small open set around `x` will not be contained in the source of the preferred chart around `f x`, which means that when reading `f` in the chart one is losing some information. To avoid this, we include continuity in the definition of differentiablity (which is reasonable since with any definition, differentiability implies continuity). *Warning*: the derivative (even within a subset) is a linear map on the whole tangent space. Suppose that one is given a smooth submanifold `N`, and a function which is smooth on `N` (i.e., its restriction to the subtype `N` is smooth). Then, in the whole manifold `M`, the property `mdifferentiable_on I I' f N` holds. However, `mfderiv_within I I' f N` is not uniquely defined (what values would one choose for vectors that are transverse to `N`?), which can create issues down the road. The problem here is that knowing the value of `f` along `N` does not determine the differential of `f` in all directions. This is in contrast to the case where `N` would be an open subset, or a submanifold with boundary of maximal dimension, where this issue does not appear. The predicate `unique_mdiff_on I N` indicates that the derivative along `N` is unique if it exists, and is an assumption in most statements requiring a form of uniqueness. On a vector space, the manifold derivative and the usual derivative are equal. This means in particular that they live on the same space, i.e., the tangent space is defeq to the original vector space. To get this property is a motivation for our definition of the tangent space as a single copy of the vector space, instead of more usual definitions such as the space of derivations, or the space of equivalence classes of smooth curves in the manifold. ## Tags Derivative, manifold -/ noncomputable theory open_locale classical topological_space manifold open set universe u section derivatives_definitions /-! ### Derivative of maps between manifolds The derivative of a smooth map `f` between smooth manifold `M` and `M'` at `x` is a bounded linear map from the tangent space to `M` at `x`, to the tangent space to `M'` at `f x`. Since we defined the tangent space using one specific chart, the formula for the derivative is written in terms of this specific chart. We use the names `mdifferentiable` and `mfderiv`, where the prefix letter `m` means "manifold". -/ variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) {M : Type*} [topological_space M] [charted_space H M] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] (I' : model_with_corners 𝕜 E' H') {M' : Type*} [topological_space M'] [charted_space H' M'] /-- Predicate ensuring that, at a point and within a set, a function can have at most one derivative. This is expressed using the preferred chart at the considered point. -/ def unique_mdiff_within_at (s : set M) (x : M) := unique_diff_within_at 𝕜 ((ext_chart_at I x).symm ⁻¹' s ∩ range I) ((ext_chart_at I x) x) /-- Predicate ensuring that, at all points of a set, a function can have at most one derivative. -/ def unique_mdiff_on (s : set M) := ∀x∈s, unique_mdiff_within_at I s x /-- Conjugating a function to write it in the preferred charts around `x`. The manifold derivative of `f` will just be the derivative of this conjugated function. -/ @[simp, mfld_simps] def written_in_ext_chart_at (x : M) (f : M → M') : E → E' := (ext_chart_at I' (f x)) ∘ f ∘ (ext_chart_at I x).symm /-- `mdifferentiable_within_at I I' f s x` indicates that the function `f` between manifolds has a derivative at the point `x` within the set `s`. This is a generalization of `differentiable_within_at` to manifolds. We require continuity in the definition, as otherwise points close to `x` in `s` could be sent by `f` outside of the chart domain around `f x`. Then the chart could do anything to the image points, and in particular by coincidence `written_in_ext_chart_at I I' x f` could be differentiable, while this would not mean anything relevant. -/ def mdifferentiable_within_at (f : M → M') (s : set M) (x : M) := continuous_within_at f s x ∧ differentiable_within_at 𝕜 (written_in_ext_chart_at I I' x f) ((ext_chart_at I x).symm ⁻¹' s ∩ range I) ((ext_chart_at I x) x) /-- `mdifferentiable_at I I' f x` indicates that the function `f` between manifolds has a derivative at the point `x`. This is a generalization of `differentiable_at` to manifolds. We require continuity in the definition, as otherwise points close to `x` could be sent by `f` outside of the chart domain around `f x`. Then the chart could do anything to the image points, and in particular by coincidence `written_in_ext_chart_at I I' x f` could be differentiable, while this would not mean anything relevant. -/ def mdifferentiable_at (f : M → M') (x : M) := continuous_at f x ∧ differentiable_within_at 𝕜 (written_in_ext_chart_at I I' x f) (range I) ((ext_chart_at I x) x) /-- `mdifferentiable_on I I' f s` indicates that the function `f` between manifolds has a derivative within `s` at all points of `s`. This is a generalization of `differentiable_on` to manifolds. -/ def mdifferentiable_on (f : M → M') (s : set M) := ∀x ∈ s, mdifferentiable_within_at I I' f s x /-- `mdifferentiable I I' f` indicates that the function `f` between manifolds has a derivative everywhere. This is a generalization of `differentiable` to manifolds. -/ def mdifferentiable (f : M → M') := ∀x, mdifferentiable_at I I' f x /-- Prop registering if a local homeomorphism is a local diffeomorphism on its source -/ def local_homeomorph.mdifferentiable (f : local_homeomorph M M') := (mdifferentiable_on I I' f f.source) ∧ (mdifferentiable_on I' I f.symm f.target) variables [smooth_manifold_with_corners I M] [smooth_manifold_with_corners I' M'] /-- `has_mfderiv_within_at I I' f s x f'` indicates that the function `f` between manifolds has, at the point `x` and within the set `s`, the derivative `f'`. Here, `f'` is a continuous linear map from the tangent space at `x` to the tangent space at `f x`. This is a generalization of `has_fderiv_within_at` to manifolds (as indicated by the prefix `m`). The order of arguments is changed as the type of the derivative `f'` depends on the choice of `x`. We require continuity in the definition, as otherwise points close to `x` in `s` could be sent by `f` outside of the chart domain around `f x`. Then the chart could do anything to the image points, and in particular by coincidence `written_in_ext_chart_at I I' x f` could be differentiable, while this would not mean anything relevant. -/ def has_mfderiv_within_at (f : M → M') (s : set M) (x : M) (f' : tangent_space I x →L[𝕜] tangent_space I' (f x)) := continuous_within_at f s x ∧ has_fderiv_within_at (written_in_ext_chart_at I I' x f : E → E') f' ((ext_chart_at I x).symm ⁻¹' s ∩ range I) ((ext_chart_at I x) x) /-- `has_mfderiv_at I I' f x f'` indicates that the function `f` between manifolds has, at the point `x`, the derivative `f'`. Here, `f'` is a continuous linear map from the tangent space at `x` to the tangent space at `f x`. We require continuity in the definition, as otherwise points close to `x` `s` could be sent by `f` outside of the chart domain around `f x`. Then the chart could do anything to the image points, and in particular by coincidence `written_in_ext_chart_at I I' x f` could be differentiable, while this would not mean anything relevant. -/ def has_mfderiv_at (f : M → M') (x : M) (f' : tangent_space I x →L[𝕜] tangent_space I' (f x)) := continuous_at f x ∧ has_fderiv_within_at (written_in_ext_chart_at I I' x f : E → E') f' (range I) ((ext_chart_at I x) x) /-- Let `f` be a function between two smooth manifolds. Then `mfderiv_within I I' f s x` is the derivative of `f` at `x` within `s`, as a continuous linear map from the tangent space at `x` to the tangent space at `f x`. -/ def mfderiv_within (f : M → M') (s : set M) (x : M) : tangent_space I x →L[𝕜] tangent_space I' (f x) := if h : mdifferentiable_within_at I I' f s x then (fderiv_within 𝕜 (written_in_ext_chart_at I I' x f) ((ext_chart_at I x).symm ⁻¹' s ∩ range I) ((ext_chart_at I x) x) : _) else 0 /-- Let `f` be a function between two smooth manifolds. Then `mfderiv I I' f x` is the derivative of `f` at `x`, as a continuous linear map from the tangent space at `x` to the tangent space at `f x`. -/ def mfderiv (f : M → M') (x : M) : tangent_space I x →L[𝕜] tangent_space I' (f x) := if h : mdifferentiable_at I I' f x then (fderiv_within 𝕜 (written_in_ext_chart_at I I' x f : E → E') (range I) ((ext_chart_at I x) x) : _) else 0 /-- The derivative within a set, as a map between the tangent bundles -/ def tangent_map_within (f : M → M') (s : set M) : tangent_bundle I M → tangent_bundle I' M' := λp, ⟨f p.1, (mfderiv_within I I' f s p.1 : tangent_space I p.1 → tangent_space I' (f p.1)) p.2⟩ /-- The derivative, as a map between the tangent bundles -/ def tangent_map (f : M → M') : tangent_bundle I M → tangent_bundle I' M' := λp, ⟨f p.1, (mfderiv I I' f p.1 : tangent_space I p.1 → tangent_space I' (f p.1)) p.2⟩ end derivatives_definitions section derivatives_properties /-! ### Unique differentiability sets in manifolds -/ variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) {M : Type*} [topological_space M] [charted_space H M] -- {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} {M' : Type*} [topological_space M'] [charted_space H' M'] {E'' : Type*} [normed_group E''] [normed_space 𝕜 E''] {H'' : Type*} [topological_space H''] {I'' : model_with_corners 𝕜 E'' H''} {M'' : Type*} [topological_space M''] [charted_space H'' M''] {f f₀ f₁ : M → M'} {x : M} {s t : set M} {g : M' → M''} {u : set M'} lemma unique_mdiff_within_at_univ : unique_mdiff_within_at I univ x := begin unfold unique_mdiff_within_at, simp only [preimage_univ, univ_inter], exact I.unique_diff _ (mem_range_self _) end variable {I} lemma unique_mdiff_within_at_iff {s : set M} {x : M} : unique_mdiff_within_at I s x ↔ unique_diff_within_at 𝕜 ((ext_chart_at I x).symm ⁻¹' s ∩ (ext_chart_at I x).target) ((ext_chart_at I x) x) := begin apply unique_diff_within_at_congr, rw [nhds_within_inter, nhds_within_inter, nhds_within_ext_chart_target_eq] end lemma unique_mdiff_within_at.mono (h : unique_mdiff_within_at I s x) (st : s ⊆ t) : unique_mdiff_within_at I t x := unique_diff_within_at.mono h $ inter_subset_inter (preimage_mono st) (subset.refl _) lemma unique_mdiff_within_at.inter' (hs : unique_mdiff_within_at I s x) (ht : t ∈ 𝓝[s] x) : unique_mdiff_within_at I (s ∩ t) x := begin rw [unique_mdiff_within_at, ext_chart_preimage_inter_eq], exact unique_diff_within_at.inter' hs (ext_chart_preimage_mem_nhds_within I x ht) end lemma unique_mdiff_within_at.inter (hs : unique_mdiff_within_at I s x) (ht : t ∈ 𝓝 x) : unique_mdiff_within_at I (s ∩ t) x := begin rw [unique_mdiff_within_at, ext_chart_preimage_inter_eq], exact unique_diff_within_at.inter hs (ext_chart_preimage_mem_nhds I x ht) end lemma is_open.unique_mdiff_within_at (xs : x ∈ s) (hs : is_open s) : unique_mdiff_within_at I s x := begin have := unique_mdiff_within_at.inter (unique_mdiff_within_at_univ I) (is_open.mem_nhds hs xs), rwa univ_inter at this end lemma unique_mdiff_on.inter (hs : unique_mdiff_on I s) (ht : is_open t) : unique_mdiff_on I (s ∩ t) := λx hx, unique_mdiff_within_at.inter (hs _ hx.1) (is_open.mem_nhds ht hx.2) lemma is_open.unique_mdiff_on (hs : is_open s) : unique_mdiff_on I s := λx hx, is_open.unique_mdiff_within_at hx hs lemma unique_mdiff_on_univ : unique_mdiff_on I (univ : set M) := is_open_univ.unique_mdiff_on /- We name the typeclass variables related to `smooth_manifold_with_corners` structure as they are necessary in lemmas mentioning the derivative, but not in lemmas about differentiability, so we want to include them or omit them when necessary. -/ variables [Is : smooth_manifold_with_corners I M] [I's : smooth_manifold_with_corners I' M'] [I''s : smooth_manifold_with_corners I'' M''] {f' f₀' f₁' : tangent_space I x →L[𝕜] tangent_space I' (f x)} {g' : tangent_space I' (f x) →L[𝕜] tangent_space I'' (g (f x))} /-- `unique_mdiff_within_at` achieves its goal: it implies the uniqueness of the derivative. -/ theorem unique_mdiff_within_at.eq (U : unique_mdiff_within_at I s x) (h : has_mfderiv_within_at I I' f s x f') (h₁ : has_mfderiv_within_at I I' f s x f₁') : f' = f₁' := U.eq h.2 h₁.2 theorem unique_mdiff_on.eq (U : unique_mdiff_on I s) (hx : x ∈ s) (h : has_mfderiv_within_at I I' f s x f') (h₁ : has_mfderiv_within_at I I' f s x f₁') : f' = f₁' := unique_mdiff_within_at.eq (U _ hx) h h₁ /-! ### General lemmas on derivatives of functions between manifolds We mimick the API for functions between vector spaces -/ lemma mdifferentiable_within_at_iff {f : M → M'} {s : set M} {x : M} : mdifferentiable_within_at I I' f s x ↔ continuous_within_at f s x ∧ differentiable_within_at 𝕜 (written_in_ext_chart_at I I' x f) ((ext_chart_at I x).target ∩ (ext_chart_at I x).symm ⁻¹' s) ((ext_chart_at I x) x) := begin refine and_congr iff.rfl (exists_congr $ λ f', _), rw [inter_comm], simp only [has_fderiv_within_at, nhds_within_inter, nhds_within_ext_chart_target_eq] end include Is I's lemma mfderiv_within_zero_of_not_mdifferentiable_within_at (h : ¬ mdifferentiable_within_at I I' f s x) : mfderiv_within I I' f s x = 0 := by simp only [mfderiv_within, h, dif_neg, not_false_iff] lemma mfderiv_zero_of_not_mdifferentiable_at (h : ¬ mdifferentiable_at I I' f x) : mfderiv I I' f x = 0 := by simp only [mfderiv, h, dif_neg, not_false_iff] theorem has_mfderiv_within_at.mono (h : has_mfderiv_within_at I I' f t x f') (hst : s ⊆ t) : has_mfderiv_within_at I I' f s x f' := ⟨ continuous_within_at.mono h.1 hst, has_fderiv_within_at.mono h.2 (inter_subset_inter (preimage_mono hst) (subset.refl _)) ⟩ theorem has_mfderiv_at.has_mfderiv_within_at (h : has_mfderiv_at I I' f x f') : has_mfderiv_within_at I I' f s x f' := ⟨ continuous_at.continuous_within_at h.1, has_fderiv_within_at.mono h.2 (inter_subset_right _ _) ⟩ lemma has_mfderiv_within_at.mdifferentiable_within_at (h : has_mfderiv_within_at I I' f s x f') : mdifferentiable_within_at I I' f s x := ⟨h.1, ⟨f', h.2⟩⟩ lemma has_mfderiv_at.mdifferentiable_at (h : has_mfderiv_at I I' f x f') : mdifferentiable_at I I' f x := ⟨h.1, ⟨f', h.2⟩⟩ @[simp, mfld_simps] lemma has_mfderiv_within_at_univ : has_mfderiv_within_at I I' f univ x f' ↔ has_mfderiv_at I I' f x f' := by simp only [has_mfderiv_within_at, has_mfderiv_at, continuous_within_at_univ] with mfld_simps theorem has_mfderiv_at_unique (h₀ : has_mfderiv_at I I' f x f₀') (h₁ : has_mfderiv_at I I' f x f₁') : f₀' = f₁' := begin rw ← has_mfderiv_within_at_univ at h₀ h₁, exact (unique_mdiff_within_at_univ I).eq h₀ h₁ end lemma has_mfderiv_within_at_inter' (h : t ∈ 𝓝[s] x) : has_mfderiv_within_at I I' f (s ∩ t) x f' ↔ has_mfderiv_within_at I I' f s x f' := begin rw [has_mfderiv_within_at, has_mfderiv_within_at, ext_chart_preimage_inter_eq, has_fderiv_within_at_inter', continuous_within_at_inter' h], exact ext_chart_preimage_mem_nhds_within I x h, end lemma has_mfderiv_within_at_inter (h : t ∈ 𝓝 x) : has_mfderiv_within_at I I' f (s ∩ t) x f' ↔ has_mfderiv_within_at I I' f s x f' := begin rw [has_mfderiv_within_at, has_mfderiv_within_at, ext_chart_preimage_inter_eq, has_fderiv_within_at_inter, continuous_within_at_inter h], exact ext_chart_preimage_mem_nhds I x h, end lemma has_mfderiv_within_at.union (hs : has_mfderiv_within_at I I' f s x f') (ht : has_mfderiv_within_at I I' f t x f') : has_mfderiv_within_at I I' f (s ∪ t) x f' := begin split, { exact continuous_within_at.union hs.1 ht.1 }, { convert has_fderiv_within_at.union hs.2 ht.2, simp only [union_inter_distrib_right, preimage_union] } end lemma has_mfderiv_within_at.nhds_within (h : has_mfderiv_within_at I I' f s x f') (ht : s ∈ 𝓝[t] x) : has_mfderiv_within_at I I' f t x f' := (has_mfderiv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _)) lemma has_mfderiv_within_at.has_mfderiv_at (h : has_mfderiv_within_at I I' f s x f') (hs : s ∈ 𝓝 x) : has_mfderiv_at I I' f x f' := by rwa [← univ_inter s, has_mfderiv_within_at_inter hs, has_mfderiv_within_at_univ] at h lemma mdifferentiable_within_at.has_mfderiv_within_at (h : mdifferentiable_within_at I I' f s x) : has_mfderiv_within_at I I' f s x (mfderiv_within I I' f s x) := begin refine ⟨h.1, _⟩, simp only [mfderiv_within, h, dif_pos] with mfld_simps, exact differentiable_within_at.has_fderiv_within_at h.2 end lemma mdifferentiable_within_at.mfderiv_within (h : mdifferentiable_within_at I I' f s x) : (mfderiv_within I I' f s x) = fderiv_within 𝕜 (written_in_ext_chart_at I I' x f : _) ((ext_chart_at I x).symm ⁻¹' s ∩ range I) ((ext_chart_at I x) x) := by simp only [mfderiv_within, h, dif_pos] lemma mdifferentiable_at.has_mfderiv_at (h : mdifferentiable_at I I' f x) : has_mfderiv_at I I' f x (mfderiv I I' f x) := begin refine ⟨h.1, _⟩, simp only [mfderiv, h, dif_pos] with mfld_simps, exact differentiable_within_at.has_fderiv_within_at h.2 end lemma mdifferentiable_at.mfderiv (h : mdifferentiable_at I I' f x) : (mfderiv I I' f x) = fderiv_within 𝕜 (written_in_ext_chart_at I I' x f : _) (range I) ((ext_chart_at I x) x) := by simp only [mfderiv, h, dif_pos] lemma has_mfderiv_at.mfderiv (h : has_mfderiv_at I I' f x f') : mfderiv I I' f x = f' := (has_mfderiv_at_unique h h.mdifferentiable_at.has_mfderiv_at).symm lemma has_mfderiv_within_at.mfderiv_within (h : has_mfderiv_within_at I I' f s x f') (hxs : unique_mdiff_within_at I s x) : mfderiv_within I I' f s x = f' := by { ext, rw hxs.eq h h.mdifferentiable_within_at.has_mfderiv_within_at } lemma mdifferentiable.mfderiv_within (h : mdifferentiable_at I I' f x) (hxs : unique_mdiff_within_at I s x) : mfderiv_within I I' f s x = mfderiv I I' f x := begin apply has_mfderiv_within_at.mfderiv_within _ hxs, exact h.has_mfderiv_at.has_mfderiv_within_at end lemma mfderiv_within_subset (st : s ⊆ t) (hs : unique_mdiff_within_at I s x) (h : mdifferentiable_within_at I I' f t x) : mfderiv_within I I' f s x = mfderiv_within I I' f t x := ((mdifferentiable_within_at.has_mfderiv_within_at h).mono st).mfderiv_within hs omit Is I's lemma mdifferentiable_within_at.mono (hst : s ⊆ t) (h : mdifferentiable_within_at I I' f t x) : mdifferentiable_within_at I I' f s x := ⟨ continuous_within_at.mono h.1 hst, differentiable_within_at.mono h.2 (inter_subset_inter (preimage_mono hst) (subset.refl _)) ⟩ lemma mdifferentiable_within_at_univ : mdifferentiable_within_at I I' f univ x ↔ mdifferentiable_at I I' f x := by simp only [mdifferentiable_within_at, mdifferentiable_at, continuous_within_at_univ] with mfld_simps lemma mdifferentiable_within_at_inter (ht : t ∈ 𝓝 x) : mdifferentiable_within_at I I' f (s ∩ t) x ↔ mdifferentiable_within_at I I' f s x := begin rw [mdifferentiable_within_at, mdifferentiable_within_at, ext_chart_preimage_inter_eq, differentiable_within_at_inter, continuous_within_at_inter ht], exact ext_chart_preimage_mem_nhds I x ht end lemma mdifferentiable_within_at_inter' (ht : t ∈ 𝓝[s] x) : mdifferentiable_within_at I I' f (s ∩ t) x ↔ mdifferentiable_within_at I I' f s x := begin rw [mdifferentiable_within_at, mdifferentiable_within_at, ext_chart_preimage_inter_eq, differentiable_within_at_inter', continuous_within_at_inter' ht], exact ext_chart_preimage_mem_nhds_within I x ht end lemma mdifferentiable_at.mdifferentiable_within_at (h : mdifferentiable_at I I' f x) : mdifferentiable_within_at I I' f s x := mdifferentiable_within_at.mono (subset_univ _) (mdifferentiable_within_at_univ.2 h) lemma mdifferentiable_within_at.mdifferentiable_at (h : mdifferentiable_within_at I I' f s x) (hs : s ∈ 𝓝 x) : mdifferentiable_at I I' f x := begin have : s = univ ∩ s, by rw univ_inter, rwa [this, mdifferentiable_within_at_inter hs, mdifferentiable_within_at_univ] at h, end lemma mdifferentiable_on.mono (h : mdifferentiable_on I I' f t) (st : s ⊆ t) : mdifferentiable_on I I' f s := λx hx, (h x (st hx)).mono st lemma mdifferentiable_on_univ : mdifferentiable_on I I' f univ ↔ mdifferentiable I I' f := by { simp only [mdifferentiable_on, mdifferentiable_within_at_univ] with mfld_simps, refl } lemma mdifferentiable.mdifferentiable_on (h : mdifferentiable I I' f) : mdifferentiable_on I I' f s := (mdifferentiable_on_univ.2 h).mono (subset_univ _) lemma mdifferentiable_on_of_locally_mdifferentiable_on (h : ∀x∈s, ∃u, is_open u ∧ x ∈ u ∧ mdifferentiable_on I I' f (s ∩ u)) : mdifferentiable_on I I' f s := begin assume x xs, rcases h x xs with ⟨t, t_open, xt, ht⟩, exact (mdifferentiable_within_at_inter (is_open.mem_nhds t_open xt)).1 (ht x ⟨xs, xt⟩) end include Is I's @[simp, mfld_simps] lemma mfderiv_within_univ : mfderiv_within I I' f univ = mfderiv I I' f := begin ext x : 1, simp only [mfderiv_within, mfderiv] with mfld_simps, rw mdifferentiable_within_at_univ end lemma mfderiv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_mdiff_within_at I s x) : mfderiv_within I I' f (s ∩ t) x = mfderiv_within I I' f s x := by rw [mfderiv_within, mfderiv_within, ext_chart_preimage_inter_eq, mdifferentiable_within_at_inter ht, fderiv_within_inter (ext_chart_preimage_mem_nhds I x ht) hs] omit Is I's /-! ### Deriving continuity from differentiability on manifolds -/ theorem has_mfderiv_within_at.continuous_within_at (h : has_mfderiv_within_at I I' f s x f') : continuous_within_at f s x := h.1 theorem has_mfderiv_at.continuous_at (h : has_mfderiv_at I I' f x f') : continuous_at f x := h.1 lemma mdifferentiable_within_at.continuous_within_at (h : mdifferentiable_within_at I I' f s x) : continuous_within_at f s x := h.1 lemma mdifferentiable_at.continuous_at (h : mdifferentiable_at I I' f x) : continuous_at f x := h.1 lemma mdifferentiable_on.continuous_on (h : mdifferentiable_on I I' f s) : continuous_on f s := λx hx, (h x hx).continuous_within_at lemma mdifferentiable.continuous (h : mdifferentiable I I' f) : continuous f := continuous_iff_continuous_at.2 $ λx, (h x).continuous_at include Is I's lemma tangent_map_within_subset {p : tangent_bundle I M} (st : s ⊆ t) (hs : unique_mdiff_within_at I s p.1) (h : mdifferentiable_within_at I I' f t p.1) : tangent_map_within I I' f s p = tangent_map_within I I' f t p := begin simp only [tangent_map_within] with mfld_simps, rw mfderiv_within_subset st hs h, end lemma tangent_map_within_univ : tangent_map_within I I' f univ = tangent_map I I' f := by { ext p : 1, simp only [tangent_map_within, tangent_map] with mfld_simps } lemma tangent_map_within_eq_tangent_map {p : tangent_bundle I M} (hs : unique_mdiff_within_at I s p.1) (h : mdifferentiable_at I I' f p.1) : tangent_map_within I I' f s p = tangent_map I I' f p := begin rw ← mdifferentiable_within_at_univ at h, rw ← tangent_map_within_univ, exact tangent_map_within_subset (subset_univ _) hs h, end @[simp, mfld_simps] lemma tangent_map_within_tangent_bundle_proj {p : tangent_bundle I M} : tangent_bundle.proj I' M' (tangent_map_within I I' f s p) = f (tangent_bundle.proj I M p) := rfl @[simp, mfld_simps] lemma tangent_map_within_proj {p : tangent_bundle I M} : (tangent_map_within I I' f s p).1 = f p.1 := rfl @[simp, mfld_simps] lemma tangent_map_tangent_bundle_proj {p : tangent_bundle I M} : tangent_bundle.proj I' M' (tangent_map I I' f p) = f (tangent_bundle.proj I M p) := rfl @[simp, mfld_simps] lemma tangent_map_proj {p : tangent_bundle I M} : (tangent_map I I' f p).1 = f p.1 := rfl omit Is I's /-! ### Congruence lemmas for derivatives on manifolds -/ lemma has_mfderiv_within_at.congr_of_eventually_eq (h : has_mfderiv_within_at I I' f s x f') (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : has_mfderiv_within_at I I' f₁ s x f' := begin refine ⟨continuous_within_at.congr_of_eventually_eq h.1 h₁ hx, _⟩, apply has_fderiv_within_at.congr_of_eventually_eq h.2, { have : (ext_chart_at I x).symm ⁻¹' {y | f₁ y = f y} ∈ 𝓝[(ext_chart_at I x).symm ⁻¹' s ∩ range I] ((ext_chart_at I x) x) := ext_chart_preimage_mem_nhds_within I x h₁, apply filter.mem_of_superset this (λy, _), simp only [hx] with mfld_simps {contextual := tt} }, { simp only [hx] with mfld_simps }, end lemma has_mfderiv_within_at.congr_mono (h : has_mfderiv_within_at I I' f s x f') (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : has_mfderiv_within_at I I' f₁ t x f' := (h.mono h₁).congr_of_eventually_eq (filter.mem_inf_of_right ht) hx lemma has_mfderiv_at.congr_of_eventually_eq (h : has_mfderiv_at I I' f x f') (h₁ : f₁ =ᶠ[𝓝 x] f) : has_mfderiv_at I I' f₁ x f' := begin rw ← has_mfderiv_within_at_univ at ⊢ h, apply h.congr_of_eventually_eq _ (mem_of_mem_nhds h₁ : _), rwa nhds_within_univ end include Is I's lemma mdifferentiable_within_at.congr_of_eventually_eq (h : mdifferentiable_within_at I I' f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : mdifferentiable_within_at I I' f₁ s x := (h.has_mfderiv_within_at.congr_of_eventually_eq h₁ hx).mdifferentiable_within_at variables (I I') lemma filter.eventually_eq.mdifferentiable_within_at_iff (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : mdifferentiable_within_at I I' f s x ↔ mdifferentiable_within_at I I' f₁ s x := begin split, { assume h, apply h.congr_of_eventually_eq h₁ hx }, { assume h, apply h.congr_of_eventually_eq _ hx.symm, apply h₁.mono, intro y, apply eq.symm } end variables {I I'} lemma mdifferentiable_within_at.congr_mono (h : mdifferentiable_within_at I I' f s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : mdifferentiable_within_at I I' f₁ t x := (has_mfderiv_within_at.congr_mono h.has_mfderiv_within_at ht hx h₁).mdifferentiable_within_at lemma mdifferentiable_within_at.congr (h : mdifferentiable_within_at I I' f s x) (ht : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : mdifferentiable_within_at I I' f₁ s x := (has_mfderiv_within_at.congr_mono h.has_mfderiv_within_at ht hx (subset.refl _)).mdifferentiable_within_at lemma mdifferentiable_on.congr_mono (h : mdifferentiable_on I I' f s) (h' : ∀x ∈ t, f₁ x = f x) (h₁ : t ⊆ s) : mdifferentiable_on I I' f₁ t := λ x hx, (h x (h₁ hx)).congr_mono h' (h' x hx) h₁ lemma mdifferentiable_at.congr_of_eventually_eq (h : mdifferentiable_at I I' f x) (hL : f₁ =ᶠ[𝓝 x] f) : mdifferentiable_at I I' f₁ x := ((h.has_mfderiv_at).congr_of_eventually_eq hL).mdifferentiable_at lemma mdifferentiable_within_at.mfderiv_within_congr_mono (h : mdifferentiable_within_at I I' f s x) (hs : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (hxt : unique_mdiff_within_at I t x) (h₁ : t ⊆ s) : mfderiv_within I I' f₁ t x = (mfderiv_within I I' f s x : _) := (has_mfderiv_within_at.congr_mono h.has_mfderiv_within_at hs hx h₁).mfderiv_within hxt lemma filter.eventually_eq.mfderiv_within_eq (hs : unique_mdiff_within_at I s x) (hL : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : mfderiv_within I I' f₁ s x = (mfderiv_within I I' f s x : _) := begin by_cases h : mdifferentiable_within_at I I' f s x, { exact ((h.has_mfderiv_within_at).congr_of_eventually_eq hL hx).mfderiv_within hs }, { unfold mfderiv_within, rw [dif_neg h, dif_neg], rwa ← hL.mdifferentiable_within_at_iff I I' hx } end lemma mfderiv_within_congr (hs : unique_mdiff_within_at I s x) (hL : ∀ x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : mfderiv_within I I' f₁ s x = (mfderiv_within I I' f s x : _) := filter.eventually_eq.mfderiv_within_eq hs (filter.eventually_eq_of_mem (self_mem_nhds_within) hL) hx lemma tangent_map_within_congr (h : ∀ x ∈ s, f x = f₁ x) (p : tangent_bundle I M) (hp : p.1 ∈ s) (hs : unique_mdiff_within_at I s p.1) : tangent_map_within I I' f s p = tangent_map_within I I' f₁ s p := begin simp only [tangent_map_within, h p.fst hp, true_and, eq_self_iff_true, heq_iff_eq, sigma.mk.inj_iff], congr' 1, exact mfderiv_within_congr hs h (h _ hp) end lemma filter.eventually_eq.mfderiv_eq (hL : f₁ =ᶠ[𝓝 x] f) : mfderiv I I' f₁ x = (mfderiv I I' f x : _) := begin have A : f₁ x = f x := (mem_of_mem_nhds hL : _), rw [← mfderiv_within_univ, ← mfderiv_within_univ], rw ← nhds_within_univ at hL, exact hL.mfderiv_within_eq (unique_mdiff_within_at_univ I) A end /-! ### Composition lemmas -/ omit Is I's lemma written_in_ext_chart_comp (h : continuous_within_at f s x) : {y | written_in_ext_chart_at I I'' x (g ∘ f) y = ((written_in_ext_chart_at I' I'' (f x) g) ∘ (written_in_ext_chart_at I I' x f)) y} ∈ 𝓝[(ext_chart_at I x).symm ⁻¹' s ∩ range I] ((ext_chart_at I x) x) := begin apply @filter.mem_of_superset _ _ ((f ∘ (ext_chart_at I x).symm)⁻¹' (ext_chart_at I' (f x)).source) _ (ext_chart_preimage_mem_nhds_within I x (h.preimage_mem_nhds_within (ext_chart_at_source_mem_nhds _ _))), mfld_set_tac, end variable (x) include Is I's I''s theorem has_mfderiv_within_at.comp (hg : has_mfderiv_within_at I' I'' g u (f x) g') (hf : has_mfderiv_within_at I I' f s x f') (hst : s ⊆ f ⁻¹' u) : has_mfderiv_within_at I I'' (g ∘ f) s x (g'.comp f') := begin refine ⟨continuous_within_at.comp hg.1 hf.1 hst, _⟩, have A : has_fderiv_within_at ((written_in_ext_chart_at I' I'' (f x) g) ∘ (written_in_ext_chart_at I I' x f)) (continuous_linear_map.comp g' f' : E →L[𝕜] E'') ((ext_chart_at I x).symm ⁻¹' s ∩ range (I)) ((ext_chart_at I x) x), { have : (ext_chart_at I x).symm ⁻¹' (f ⁻¹' (ext_chart_at I' (f x)).source) ∈ 𝓝[(ext_chart_at I x).symm ⁻¹' s ∩ range I] ((ext_chart_at I x) x) := (ext_chart_preimage_mem_nhds_within I x (hf.1.preimage_mem_nhds_within (ext_chart_at_source_mem_nhds _ _))), unfold has_mfderiv_within_at at *, rw [← has_fderiv_within_at_inter' this, ← ext_chart_preimage_inter_eq] at hf ⊢, have : written_in_ext_chart_at I I' x f ((ext_chart_at I x) x) = (ext_chart_at I' (f x)) (f x), by simp only with mfld_simps, rw ← this at hg, apply has_fderiv_within_at.comp ((ext_chart_at I x) x) hg.2 hf.2 _, assume y hy, simp only with mfld_simps at hy, have : f (((chart_at H x).symm : H → M) (I.symm y)) ∈ u := hst hy.1.1, simp only [hy, this] with mfld_simps }, apply A.congr_of_eventually_eq (written_in_ext_chart_comp hf.1), simp only with mfld_simps end /-- The chain rule. -/ theorem has_mfderiv_at.comp (hg : has_mfderiv_at I' I'' g (f x) g') (hf : has_mfderiv_at I I' f x f') : has_mfderiv_at I I'' (g ∘ f) x (g'.comp f') := begin rw ← has_mfderiv_within_at_univ at *, exact has_mfderiv_within_at.comp x (hg.mono (subset_univ _)) hf subset_preimage_univ end theorem has_mfderiv_at.comp_has_mfderiv_within_at (hg : has_mfderiv_at I' I'' g (f x) g') (hf : has_mfderiv_within_at I I' f s x f') : has_mfderiv_within_at I I'' (g ∘ f) s x (g'.comp f') := begin rw ← has_mfderiv_within_at_univ at *, exact has_mfderiv_within_at.comp x (hg.mono (subset_univ _)) hf subset_preimage_univ end lemma mdifferentiable_within_at.comp (hg : mdifferentiable_within_at I' I'' g u (f x)) (hf : mdifferentiable_within_at I I' f s x) (h : s ⊆ f ⁻¹' u) : mdifferentiable_within_at I I'' (g ∘ f) s x := begin rcases hf.2 with ⟨f', hf'⟩, have F : has_mfderiv_within_at I I' f s x f' := ⟨hf.1, hf'⟩, rcases hg.2 with ⟨g', hg'⟩, have G : has_mfderiv_within_at I' I'' g u (f x) g' := ⟨hg.1, hg'⟩, exact (has_mfderiv_within_at.comp x G F h).mdifferentiable_within_at end lemma mdifferentiable_at.comp (hg : mdifferentiable_at I' I'' g (f x)) (hf : mdifferentiable_at I I' f x) : mdifferentiable_at I I'' (g ∘ f) x := (hg.has_mfderiv_at.comp x hf.has_mfderiv_at).mdifferentiable_at lemma mfderiv_within_comp (hg : mdifferentiable_within_at I' I'' g u (f x)) (hf : mdifferentiable_within_at I I' f s x) (h : s ⊆ f ⁻¹' u) (hxs : unique_mdiff_within_at I s x) : mfderiv_within I I'' (g ∘ f) s x = (mfderiv_within I' I'' g u (f x)).comp (mfderiv_within I I' f s x) := begin apply has_mfderiv_within_at.mfderiv_within _ hxs, exact has_mfderiv_within_at.comp x hg.has_mfderiv_within_at hf.has_mfderiv_within_at h end lemma mfderiv_comp (hg : mdifferentiable_at I' I'' g (f x)) (hf : mdifferentiable_at I I' f x) : mfderiv I I'' (g ∘ f) x = (mfderiv I' I'' g (f x)).comp (mfderiv I I' f x) := begin apply has_mfderiv_at.mfderiv, exact has_mfderiv_at.comp x hg.has_mfderiv_at hf.has_mfderiv_at end lemma mdifferentiable_on.comp (hg : mdifferentiable_on I' I'' g u) (hf : mdifferentiable_on I I' f s) (st : s ⊆ f ⁻¹' u) : mdifferentiable_on I I'' (g ∘ f) s := λx hx, mdifferentiable_within_at.comp x (hg (f x) (st hx)) (hf x hx) st lemma mdifferentiable.comp (hg : mdifferentiable I' I'' g) (hf : mdifferentiable I I' f) : mdifferentiable I I'' (g ∘ f) := λx, mdifferentiable_at.comp x (hg (f x)) (hf x) lemma tangent_map_within_comp_at (p : tangent_bundle I M) (hg : mdifferentiable_within_at I' I'' g u (f p.1)) (hf : mdifferentiable_within_at I I' f s p.1) (h : s ⊆ f ⁻¹' u) (hps : unique_mdiff_within_at I s p.1) : tangent_map_within I I'' (g ∘ f) s p = tangent_map_within I' I'' g u (tangent_map_within I I' f s p) := begin simp only [tangent_map_within] with mfld_simps, rw mfderiv_within_comp p.1 hg hf h hps, refl end lemma tangent_map_comp_at (p : tangent_bundle I M) (hg : mdifferentiable_at I' I'' g (f p.1)) (hf : mdifferentiable_at I I' f p.1) : tangent_map I I'' (g ∘ f) p = tangent_map I' I'' g (tangent_map I I' f p) := begin simp only [tangent_map] with mfld_simps, rw mfderiv_comp p.1 hg hf, refl end lemma tangent_map_comp (hg : mdifferentiable I' I'' g) (hf : mdifferentiable I I' f) : tangent_map I I'' (g ∘ f) = (tangent_map I' I'' g) ∘ (tangent_map I I' f) := by { ext p : 1, exact tangent_map_comp_at _ (hg _) (hf _) } end derivatives_properties section mfderiv_fderiv /-! ### Relations between vector space derivative and manifold derivative The manifold derivative `mfderiv`, when considered on the model vector space with its trivial manifold structure, coincides with the usual Frechet derivative `fderiv`. In this section, we prove this and related statements. -/ variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {f : E → E'} {s : set E} {x : E} lemma unique_mdiff_within_at_iff_unique_diff_within_at : unique_mdiff_within_at (𝓘(𝕜, E)) s x ↔ unique_diff_within_at 𝕜 s x := by simp only [unique_mdiff_within_at] with mfld_simps alias unique_mdiff_within_at_iff_unique_diff_within_at ↔ unique_mdiff_within_at.unique_diff_within_at unique_diff_within_at.unique_mdiff_within_at lemma unique_mdiff_on_iff_unique_diff_on : unique_mdiff_on (𝓘(𝕜, E)) s ↔ unique_diff_on 𝕜 s := by simp [unique_mdiff_on, unique_diff_on, unique_mdiff_within_at_iff_unique_diff_within_at] alias unique_mdiff_on_iff_unique_diff_on ↔ unique_mdiff_on.unique_diff_on unique_diff_on.unique_mdiff_on @[simp, mfld_simps] lemma written_in_ext_chart_model_space : written_in_ext_chart_at (𝓘(𝕜, E)) (𝓘(𝕜, E')) x f = f := rfl lemma has_mfderiv_within_at_iff_has_fderiv_within_at {f'} : has_mfderiv_within_at 𝓘(𝕜, E) 𝓘(𝕜, E') f s x f' ↔ has_fderiv_within_at f f' s x := by simpa only [has_mfderiv_within_at, and_iff_right_iff_imp] with mfld_simps using has_fderiv_within_at.continuous_within_at alias has_mfderiv_within_at_iff_has_fderiv_within_at ↔ has_mfderiv_within_at.has_fderiv_within_at has_fderiv_within_at.has_mfderiv_within_at lemma has_mfderiv_at_iff_has_fderiv_at {f'} : has_mfderiv_at 𝓘(𝕜, E) 𝓘(𝕜, E') f x f' ↔ has_fderiv_at f f' x := by rw [← has_mfderiv_within_at_univ, has_mfderiv_within_at_iff_has_fderiv_within_at, has_fderiv_within_at_univ] alias has_mfderiv_at_iff_has_fderiv_at ↔ has_mfderiv_at.has_fderiv_at has_fderiv_at.has_mfderiv_at /-- For maps between vector spaces, `mdifferentiable_within_at` and `fdifferentiable_within_at` coincide -/ theorem mdifferentiable_within_at_iff_differentiable_within_at : mdifferentiable_within_at (𝓘(𝕜, E)) (𝓘(𝕜, E')) f s x ↔ differentiable_within_at 𝕜 f s x := begin simp only [mdifferentiable_within_at] with mfld_simps, exact ⟨λH, H.2, λH, ⟨H.continuous_within_at, H⟩⟩ end alias mdifferentiable_within_at_iff_differentiable_within_at ↔ mdifferentiable_within_at.differentiable_within_at differentiable_within_at.mdifferentiable_within_at /-- For maps between vector spaces, `mdifferentiable_at` and `differentiable_at` coincide -/ theorem mdifferentiable_at_iff_differentiable_at : mdifferentiable_at (𝓘(𝕜, E)) (𝓘(𝕜, E')) f x ↔ differentiable_at 𝕜 f x := begin simp only [mdifferentiable_at, differentiable_within_at_univ] with mfld_simps, exact ⟨λH, H.2, λH, ⟨H.continuous_at, H⟩⟩ end alias mdifferentiable_at_iff_differentiable_at ↔ mdifferentiable_at.differentiable_at differentiable_at.mdifferentiable_at /-- For maps between vector spaces, `mdifferentiable_on` and `differentiable_on` coincide -/ theorem mdifferentiable_on_iff_differentiable_on : mdifferentiable_on (𝓘(𝕜, E)) (𝓘(𝕜, E')) f s ↔ differentiable_on 𝕜 f s := by simp only [mdifferentiable_on, differentiable_on, mdifferentiable_within_at_iff_differentiable_within_at] alias mdifferentiable_on_iff_differentiable_on ↔ mdifferentiable_on.differentiable_on differentiable_on.mdifferentiable_on /-- For maps between vector spaces, `mdifferentiable` and `differentiable` coincide -/ theorem mdifferentiable_iff_differentiable : mdifferentiable (𝓘(𝕜, E)) (𝓘(𝕜, E')) f ↔ differentiable 𝕜 f := by simp only [mdifferentiable, differentiable, mdifferentiable_at_iff_differentiable_at] alias mdifferentiable_iff_differentiable ↔ mdifferentiable.differentiable differentiable.mdifferentiable /-- For maps between vector spaces, `mfderiv_within` and `fderiv_within` coincide -/ @[simp] theorem mfderiv_within_eq_fderiv_within : mfderiv_within (𝓘(𝕜, E)) (𝓘(𝕜, E')) f s x = fderiv_within 𝕜 f s x := begin by_cases h : mdifferentiable_within_at (𝓘(𝕜, E)) (𝓘(𝕜, E')) f s x, { simp only [mfderiv_within, h, dif_pos] with mfld_simps }, { simp only [mfderiv_within, h, dif_neg, not_false_iff], rw [mdifferentiable_within_at_iff_differentiable_within_at] at h, exact (fderiv_within_zero_of_not_differentiable_within_at h).symm } end /-- For maps between vector spaces, `mfderiv` and `fderiv` coincide -/ @[simp] theorem mfderiv_eq_fderiv : mfderiv (𝓘(𝕜, E)) (𝓘(𝕜, E')) f x = fderiv 𝕜 f x := begin rw [← mfderiv_within_univ, ← fderiv_within_univ], exact mfderiv_within_eq_fderiv_within end end mfderiv_fderiv section specific_functions /-! ### Differentiability of specific functions -/ variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) {M : Type*} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] (I' : model_with_corners 𝕜 E' H') {M' : Type*} [topological_space M'] [charted_space H' M'] [smooth_manifold_with_corners I' M'] namespace continuous_linear_map variables (f : E →L[𝕜] E') {s : set E} {x : E} protected lemma has_mfderiv_within_at : has_mfderiv_within_at 𝓘(𝕜, E) 𝓘(𝕜, E') f s x f := f.has_fderiv_within_at.has_mfderiv_within_at protected lemma has_mfderiv_at : has_mfderiv_at 𝓘(𝕜, E) 𝓘(𝕜, E') f x f := f.has_fderiv_at.has_mfderiv_at protected lemma mdifferentiable_within_at : mdifferentiable_within_at 𝓘(𝕜, E) 𝓘(𝕜, E') f s x := f.differentiable_within_at.mdifferentiable_within_at protected lemma mdifferentiable_on : mdifferentiable_on 𝓘(𝕜, E) 𝓘(𝕜, E') f s := f.differentiable_on.mdifferentiable_on protected lemma mdifferentiable_at : mdifferentiable_at 𝓘(𝕜, E) 𝓘(𝕜, E') f x := f.differentiable_at.mdifferentiable_at protected lemma mdifferentiable : mdifferentiable 𝓘(𝕜, E) 𝓘(𝕜, E') f := f.differentiable.mdifferentiable lemma mfderiv_eq : mfderiv 𝓘(𝕜, E) 𝓘(𝕜, E') f x = f := f.has_mfderiv_at.mfderiv lemma mfderiv_within_eq (hs : unique_mdiff_within_at 𝓘(𝕜, E) s x) : mfderiv_within 𝓘(𝕜, E) 𝓘(𝕜, E') f s x = f := f.has_mfderiv_within_at.mfderiv_within hs end continuous_linear_map namespace continuous_linear_equiv variables (f : E ≃L[𝕜] E') {s : set E} {x : E} protected lemma has_mfderiv_within_at : has_mfderiv_within_at 𝓘(𝕜, E) 𝓘(𝕜, E') f s x (f : E →L[𝕜] E') := f.has_fderiv_within_at.has_mfderiv_within_at protected lemma has_mfderiv_at : has_mfderiv_at 𝓘(𝕜, E) 𝓘(𝕜, E') f x (f : E →L[𝕜] E') := f.has_fderiv_at.has_mfderiv_at protected lemma mdifferentiable_within_at : mdifferentiable_within_at 𝓘(𝕜, E) 𝓘(𝕜, E') f s x := f.differentiable_within_at.mdifferentiable_within_at protected lemma mdifferentiable_on : mdifferentiable_on 𝓘(𝕜, E) 𝓘(𝕜, E') f s := f.differentiable_on.mdifferentiable_on protected lemma mdifferentiable_at : mdifferentiable_at 𝓘(𝕜, E) 𝓘(𝕜, E') f x := f.differentiable_at.mdifferentiable_at protected lemma mdifferentiable : mdifferentiable 𝓘(𝕜, E) 𝓘(𝕜, E') f := f.differentiable.mdifferentiable lemma mfderiv_eq : mfderiv 𝓘(𝕜, E) 𝓘(𝕜, E') f x = (f : E →L[𝕜] E') := f.has_mfderiv_at.mfderiv lemma mfderiv_within_eq (hs : unique_mdiff_within_at 𝓘(𝕜, E) s x) : mfderiv_within 𝓘(𝕜, E) 𝓘(𝕜, E') f s x = (f : E →L[𝕜] E') := f.has_mfderiv_within_at.mfderiv_within hs end continuous_linear_equiv variables {s : set M} {x : M} section id /-! #### Identity -/ lemma has_mfderiv_at_id (x : M) : has_mfderiv_at I I (@_root_.id M) x (continuous_linear_map.id 𝕜 (tangent_space I x)) := begin refine ⟨continuous_id.continuous_at, _⟩, have : ∀ᶠ y in 𝓝[range I] ((ext_chart_at I x) x), ((ext_chart_at I x) ∘ (ext_chart_at I x).symm) y = id y, { apply filter.mem_of_superset (ext_chart_at_target_mem_nhds_within I x), mfld_set_tac }, apply has_fderiv_within_at.congr_of_eventually_eq (has_fderiv_within_at_id _ _) this, simp only with mfld_simps end theorem has_mfderiv_within_at_id (s : set M) (x : M) : has_mfderiv_within_at I I (@_root_.id M) s x (continuous_linear_map.id 𝕜 (tangent_space I x)) := (has_mfderiv_at_id I x).has_mfderiv_within_at lemma mdifferentiable_at_id : mdifferentiable_at I I (@_root_.id M) x := (has_mfderiv_at_id I x).mdifferentiable_at lemma mdifferentiable_within_at_id : mdifferentiable_within_at I I (@_root_.id M) s x := (mdifferentiable_at_id I).mdifferentiable_within_at lemma mdifferentiable_id : mdifferentiable I I (@_root_.id M) := λx, mdifferentiable_at_id I lemma mdifferentiable_on_id : mdifferentiable_on I I (@_root_.id M) s := (mdifferentiable_id I).mdifferentiable_on @[simp, mfld_simps] lemma mfderiv_id : mfderiv I I (@_root_.id M) x = (continuous_linear_map.id 𝕜 (tangent_space I x)) := has_mfderiv_at.mfderiv (has_mfderiv_at_id I x) lemma mfderiv_within_id (hxs : unique_mdiff_within_at I s x) : mfderiv_within I I (@_root_.id M) s x = (continuous_linear_map.id 𝕜 (tangent_space I x)) := begin rw mdifferentiable.mfderiv_within (mdifferentiable_at_id I) hxs, exact mfderiv_id I end @[simp, mfld_simps] lemma tangent_map_id : tangent_map I I (id : M → M) = id := by { ext1 ⟨x, v⟩, simp [tangent_map] } lemma tangent_map_within_id {p : tangent_bundle I M} (hs : unique_mdiff_within_at I s (tangent_bundle.proj I M p)) : tangent_map_within I I (id : M → M) s p = p := begin simp only [tangent_map_within, id.def], rw mfderiv_within_id, { rcases p, refl }, { exact hs } end end id section const /-! #### Constants -/ variables {c : M'} lemma has_mfderiv_at_const (c : M') (x : M) : has_mfderiv_at I I' (λy : M, c) x (0 : tangent_space I x →L[𝕜] tangent_space I' c) := begin refine ⟨continuous_const.continuous_at, _⟩, simp only [written_in_ext_chart_at, (∘), has_fderiv_within_at_const] end theorem has_mfderiv_within_at_const (c : M') (s : set M) (x : M) : has_mfderiv_within_at I I' (λy : M, c) s x (0 : tangent_space I x →L[𝕜] tangent_space I' c) := (has_mfderiv_at_const I I' c x).has_mfderiv_within_at lemma mdifferentiable_at_const : mdifferentiable_at I I' (λy : M, c) x := (has_mfderiv_at_const I I' c x).mdifferentiable_at lemma mdifferentiable_within_at_const : mdifferentiable_within_at I I' (λy : M, c) s x := (mdifferentiable_at_const I I').mdifferentiable_within_at lemma mdifferentiable_const : mdifferentiable I I' (λy : M, c) := λx, mdifferentiable_at_const I I' lemma mdifferentiable_on_const : mdifferentiable_on I I' (λy : M, c) s := (mdifferentiable_const I I').mdifferentiable_on @[simp, mfld_simps] lemma mfderiv_const : mfderiv I I' (λy : M, c) x = (0 : tangent_space I x →L[𝕜] tangent_space I' c) := has_mfderiv_at.mfderiv (has_mfderiv_at_const I I' c x) lemma mfderiv_within_const (hxs : unique_mdiff_within_at I s x) : mfderiv_within I I' (λy : M, c) s x = (0 : tangent_space I x →L[𝕜] tangent_space I' c) := (has_mfderiv_within_at_const _ _ _ _ _).mfderiv_within hxs end const namespace model_with_corners /-! #### Model with corners -/ protected lemma has_mfderiv_at {x} : has_mfderiv_at I 𝓘(𝕜, E) I x (continuous_linear_map.id _ _) := ⟨I.continuous_at, (has_fderiv_within_at_id _ _).congr' I.right_inv_on (mem_range_self _)⟩ protected lemma has_mfderiv_within_at {s x} : has_mfderiv_within_at I 𝓘(𝕜, E) I s x (continuous_linear_map.id _ _) := I.has_mfderiv_at.has_mfderiv_within_at protected lemma mdifferentiable_within_at {s x} : mdifferentiable_within_at I 𝓘(𝕜, E) I s x := I.has_mfderiv_within_at.mdifferentiable_within_at protected lemma mdifferentiable_at {x} : mdifferentiable_at I 𝓘(𝕜, E) I x := I.has_mfderiv_at.mdifferentiable_at protected lemma mdifferentiable_on {s} : mdifferentiable_on I 𝓘(𝕜, E) I s := λ x hx, I.mdifferentiable_within_at protected lemma mdifferentiable : mdifferentiable I (𝓘(𝕜, E)) I := λ x, I.mdifferentiable_at lemma has_mfderiv_within_at_symm {x} (hx : x ∈ range I) : has_mfderiv_within_at 𝓘(𝕜, E) I I.symm (range I) x (continuous_linear_map.id _ _) := ⟨I.continuous_within_at_symm, (has_fderiv_within_at_id _ _).congr' (λ y hy, I.right_inv_on hy.1) ⟨hx, mem_range_self _⟩⟩ lemma mdifferentiable_on_symm : mdifferentiable_on (𝓘(𝕜, E)) I I.symm (range I) := λ x hx, (I.has_mfderiv_within_at_symm hx).mdifferentiable_within_at end model_with_corners section charts variable {e : local_homeomorph M H} lemma mdifferentiable_at_atlas (h : e ∈ atlas H M) {x : M} (hx : x ∈ e.source) : mdifferentiable_at I I e x := begin refine ⟨(e.continuous_on x hx).continuous_at (is_open.mem_nhds e.open_source hx), _⟩, have mem : I ((chart_at H x : M → H) x) ∈ I.symm ⁻¹' ((chart_at H x).symm ≫ₕ e).source ∩ range I, by simp only [hx] with mfld_simps, have : (chart_at H x).symm.trans e ∈ times_cont_diff_groupoid ∞ I := has_groupoid.compatible _ (chart_mem_atlas H x) h, have A : times_cont_diff_on 𝕜 ∞ (I ∘ ((chart_at H x).symm.trans e) ∘ I.symm) (I.symm ⁻¹' ((chart_at H x).symm.trans e).source ∩ range I) := this.1, have B := A.differentiable_on le_top (I ((chart_at H x : M → H) x)) mem, simp only with mfld_simps at B, rw [inter_comm, differentiable_within_at_inter] at B, { simpa only with mfld_simps }, { apply is_open.mem_nhds ((local_homeomorph.open_source _).preimage I.continuous_symm) mem.1 } end lemma mdifferentiable_on_atlas (h : e ∈ atlas H M) : mdifferentiable_on I I e e.source := λx hx, (mdifferentiable_at_atlas I h hx).mdifferentiable_within_at lemma mdifferentiable_at_atlas_symm (h : e ∈ atlas H M) {x : H} (hx : x ∈ e.target) : mdifferentiable_at I I e.symm x := begin refine ⟨(e.continuous_on_symm x hx).continuous_at (is_open.mem_nhds e.open_target hx), _⟩, have mem : I x ∈ I.symm ⁻¹' (e.symm ≫ₕ chart_at H (e.symm x)).source ∩ range (I), by simp only [hx] with mfld_simps, have : e.symm.trans (chart_at H (e.symm x)) ∈ times_cont_diff_groupoid ∞ I := has_groupoid.compatible _ h (chart_mem_atlas H _), have A : times_cont_diff_on 𝕜 ∞ (I ∘ (e.symm.trans (chart_at H (e.symm x))) ∘ I.symm) (I.symm ⁻¹' (e.symm.trans (chart_at H (e.symm x))).source ∩ range I) := this.1, have B := A.differentiable_on le_top (I x) mem, simp only with mfld_simps at B, rw [inter_comm, differentiable_within_at_inter] at B, { simpa only with mfld_simps }, { apply (is_open.mem_nhds ((local_homeomorph.open_source _).preimage I.continuous_symm) mem.1) } end lemma mdifferentiable_on_atlas_symm (h : e ∈ atlas H M) : mdifferentiable_on I I e.symm e.target := λx hx, (mdifferentiable_at_atlas_symm I h hx).mdifferentiable_within_at lemma mdifferentiable_of_mem_atlas (h : e ∈ atlas H M) : e.mdifferentiable I I := ⟨mdifferentiable_on_atlas I h, mdifferentiable_on_atlas_symm I h⟩ lemma mdifferentiable_chart (x : M) : (chart_at H x).mdifferentiable I I := mdifferentiable_of_mem_atlas _ (chart_mem_atlas _ _) /-- The derivative of the chart at a base point is the chart of the tangent bundle, composed with the identification between the tangent bundle of the model space and the product space. -/ lemma tangent_map_chart {p q : tangent_bundle I M} (h : q.1 ∈ (chart_at H p.1).source) : tangent_map I I (chart_at H p.1) q = (equiv.sigma_equiv_prod _ _).symm ((chart_at (model_prod H E) p : tangent_bundle I M → model_prod H E) q) := begin dsimp [tangent_map], rw mdifferentiable_at.mfderiv, { refl }, { exact mdifferentiable_at_atlas _ (chart_mem_atlas _ _) h } end /-- The derivative of the inverse of the chart at a base point is the inverse of the chart of the tangent bundle, composed with the identification between the tangent bundle of the model space and the product space. -/ lemma tangent_map_chart_symm {p : tangent_bundle I M} {q : tangent_bundle I H} (h : q.1 ∈ (chart_at H p.1).target) : tangent_map I I (chart_at H p.1).symm q = ((chart_at (model_prod H E) p).symm : model_prod H E → tangent_bundle I M) ((equiv.sigma_equiv_prod H E) q) := begin dsimp only [tangent_map], rw mdifferentiable_at.mfderiv (mdifferentiable_at_atlas_symm _ (chart_mem_atlas _ _) h), -- a trivial instance is needed after the rewrite, handle it right now. rotate, { apply_instance }, simp only [chart_at, basic_smooth_bundle_core.chart, subtype.coe_mk, tangent_bundle_core, h, basic_smooth_bundle_core.to_topological_fiber_bundle_core, equiv.sigma_equiv_prod_apply] with mfld_simps, end end charts end specific_functions /-! ### Differentiable local homeomorphisms -/ namespace local_homeomorph.mdifferentiable variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] {I : model_with_corners 𝕜 E H} {M : Type*} [topological_space M] [charted_space H M] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} {M' : Type*} [topological_space M'] [charted_space H' M'] {E'' : Type*} [normed_group E''] [normed_space 𝕜 E''] {H'' : Type*} [topological_space H''] {I'' : model_with_corners 𝕜 E'' H''} {M'' : Type*} [topological_space M''] [charted_space H'' M''] {e : local_homeomorph M M'} (he : e.mdifferentiable I I') {e' : local_homeomorph M' M''} include he lemma symm : e.symm.mdifferentiable I' I := ⟨he.2, he.1⟩ protected lemma mdifferentiable_at {x : M} (hx : x ∈ e.source) : mdifferentiable_at I I' e x := (he.1 x hx).mdifferentiable_at (is_open.mem_nhds e.open_source hx) lemma mdifferentiable_at_symm {x : M'} (hx : x ∈ e.target) : mdifferentiable_at I' I e.symm x := (he.2 x hx).mdifferentiable_at (is_open.mem_nhds e.open_target hx) variables [smooth_manifold_with_corners I M] [smooth_manifold_with_corners I' M'] [smooth_manifold_with_corners I'' M''] lemma symm_comp_deriv {x : M} (hx : x ∈ e.source) : (mfderiv I' I e.symm (e x)).comp (mfderiv I I' e x) = continuous_linear_map.id 𝕜 (tangent_space I x) := begin have : (mfderiv I I (e.symm ∘ e) x) = (mfderiv I' I e.symm (e x)).comp (mfderiv I I' e x) := mfderiv_comp x (he.mdifferentiable_at_symm (e.map_source hx)) (he.mdifferentiable_at hx), rw ← this, have : mfderiv I I (_root_.id : M → M) x = continuous_linear_map.id _ _ := mfderiv_id I, rw ← this, apply filter.eventually_eq.mfderiv_eq, have : e.source ∈ 𝓝 x := is_open.mem_nhds e.open_source hx, exact filter.mem_of_superset this (by mfld_set_tac) end lemma comp_symm_deriv {x : M'} (hx : x ∈ e.target) : (mfderiv I I' e (e.symm x)).comp (mfderiv I' I e.symm x) = continuous_linear_map.id 𝕜 (tangent_space I' x) := he.symm.symm_comp_deriv hx /-- The derivative of a differentiable local homeomorphism, as a continuous linear equivalence between the tangent spaces at `x` and `e x`. -/ protected def mfderiv {x : M} (hx : x ∈ e.source) : tangent_space I x ≃L[𝕜] tangent_space I' (e x) := { inv_fun := (mfderiv I' I e.symm (e x)), continuous_to_fun := (mfderiv I I' e x).cont, continuous_inv_fun := (mfderiv I' I e.symm (e x)).cont, left_inv := λy, begin have : (continuous_linear_map.id _ _ : tangent_space I x →L[𝕜] tangent_space I x) y = y := rfl, conv_rhs { rw [← this, ← he.symm_comp_deriv hx] }, refl end, right_inv := λy, begin have : (continuous_linear_map.id 𝕜 _ : tangent_space I' (e x) →L[𝕜] tangent_space I' (e x)) y = y := rfl, conv_rhs { rw [← this, ← he.comp_symm_deriv (e.map_source hx)] }, rw e.left_inv hx, refl end, .. mfderiv I I' e x } lemma mfderiv_bijective {x : M} (hx : x ∈ e.source) : function.bijective (mfderiv I I' e x) := (he.mfderiv hx).bijective lemma mfderiv_injective {x : M} (hx : x ∈ e.source) : function.injective (mfderiv I I' e x) := (he.mfderiv hx).injective lemma mfderiv_surjective {x : M} (hx : x ∈ e.source) : function.surjective (mfderiv I I' e x) := (he.mfderiv hx).surjective lemma ker_mfderiv_eq_bot {x : M} (hx : x ∈ e.source) : (mfderiv I I' e x).ker = ⊥ := (he.mfderiv hx).to_linear_equiv.ker lemma range_mfderiv_eq_top {x : M} (hx : x ∈ e.source) : (mfderiv I I' e x).range = ⊤ := (he.mfderiv hx).to_linear_equiv.range lemma range_mfderiv_eq_univ {x : M} (hx : x ∈ e.source) : range (mfderiv I I' e x) = univ := (he.mfderiv_surjective hx).range_eq lemma trans (he': e'.mdifferentiable I' I'') : (e.trans e').mdifferentiable I I'' := begin split, { assume x hx, simp only with mfld_simps at hx, exact ((he'.mdifferentiable_at hx.2).comp _ (he.mdifferentiable_at hx.1)).mdifferentiable_within_at }, { assume x hx, simp only with mfld_simps at hx, exact ((he.symm.mdifferentiable_at hx.2).comp _ (he'.symm.mdifferentiable_at hx.1)).mdifferentiable_within_at } end end local_homeomorph.mdifferentiable /-! ### Differentiability of `ext_chart_at` -/ section ext_chart_at variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) {M : Type*} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] {s : set M} {x y : M} lemma has_mfderiv_at_ext_chart_at (h : y ∈ (chart_at H x).source) : has_mfderiv_at I 𝓘(𝕜, E) (ext_chart_at I x) y (mfderiv I I (chart_at H x) y : _) := I.has_mfderiv_at.comp y ((mdifferentiable_chart I x).mdifferentiable_at h).has_mfderiv_at lemma has_mfderiv_within_at_ext_chart_at (h : y ∈ (chart_at H x).source) : has_mfderiv_within_at I 𝓘(𝕜, E) (ext_chart_at I x) s y (mfderiv I I (chart_at H x) y : _) := (has_mfderiv_at_ext_chart_at I h).has_mfderiv_within_at lemma mdifferentiable_at_ext_chart_at (h : y ∈ (chart_at H x).source) : mdifferentiable_at I 𝓘(𝕜, E) (ext_chart_at I x) y := (has_mfderiv_at_ext_chart_at I h).mdifferentiable_at lemma mdifferentiable_on_ext_chart_at : mdifferentiable_on I 𝓘(𝕜, E) (ext_chart_at I x) (chart_at H x).source := λ y hy, (has_mfderiv_within_at_ext_chart_at I hy).mdifferentiable_within_at end ext_chart_at /-! ### Unique derivative sets in manifolds -/ section unique_mdiff variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] {I : model_with_corners 𝕜 E H} {M : Type*} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} {M' : Type*} [topological_space M'] [charted_space H' M'] {s : set M} /-- If a set has the unique differential property, then its image under a local diffeomorphism also has the unique differential property. -/ lemma unique_mdiff_on.unique_mdiff_on_preimage [smooth_manifold_with_corners I' M'] (hs : unique_mdiff_on I s) {e : local_homeomorph M M'} (he : e.mdifferentiable I I') : unique_mdiff_on I' (e.target ∩ e.symm ⁻¹' s) := begin /- Start from a point `x` in the image, and let `z` be its preimage. Then the unique derivative property at `x` is expressed through `ext_chart_at I' x`, and the unique derivative property at `z` is expressed through `ext_chart_at I z`. We will argue that the composition of these two charts with `e` is a local diffeomorphism in vector spaces, and therefore preserves the unique differential property thanks to lemma `has_fderiv_within_at.unique_diff_within_at`, saying that a differentiable function with onto derivative preserves the unique derivative property.-/ assume x hx, let z := e.symm x, have z_source : z ∈ e.source, by simp only [hx.1] with mfld_simps, have zx : e z = x, by simp only [z, hx.1] with mfld_simps, let F := ext_chart_at I z, -- the unique derivative property at `z` is expressed through its preferred chart, -- that we call `F`. have B : unique_diff_within_at 𝕜 (F.symm ⁻¹' (s ∩ (e.source ∩ e ⁻¹' ((ext_chart_at I' x).source))) ∩ F.target) (F z), { have : unique_mdiff_within_at I s z := hs _ hx.2, have S : e.source ∩ e ⁻¹' ((ext_chart_at I' x).source) ∈ 𝓝 z, { apply is_open.mem_nhds, apply e.continuous_on.preimage_open_of_open e.open_source (ext_chart_at_open_source I' x), simp only [z_source, zx] with mfld_simps }, have := this.inter S, rw [unique_mdiff_within_at_iff] at this, exact this }, -- denote by `G` the change of coordinate, i.e., the composition of the two extended charts and -- of `e` let G := F.symm ≫ e.to_local_equiv ≫ (ext_chart_at I' x), -- `G` is differentiable have Diff : ((chart_at H z).symm ≫ₕ e ≫ₕ (chart_at H' x)).mdifferentiable I I', { have A := mdifferentiable_of_mem_atlas I (chart_mem_atlas H z), have B := mdifferentiable_of_mem_atlas I' (chart_mem_atlas H' x), exact A.symm.trans (he.trans B) }, have Mmem : (chart_at H z : M → H) z ∈ ((chart_at H z).symm ≫ₕ e ≫ₕ (chart_at H' x)).source, by simp only [z_source, zx] with mfld_simps, have A : differentiable_within_at 𝕜 G (range I) (F z), { refine (Diff.mdifferentiable_at Mmem).2.congr (λp hp, _) _; simp only [G, F] with mfld_simps }, -- let `G'` be its derivative let G' := fderiv_within 𝕜 G (range I) (F z), have D₁ : has_fderiv_within_at G G' (range I) (F z) := A.has_fderiv_within_at, have D₂ : has_fderiv_within_at G G' (F.symm ⁻¹' (s ∩ (e.source ∩ e ⁻¹' ((ext_chart_at I' x).source))) ∩ F.target) (F z) := D₁.mono (by mfld_set_tac), -- The derivative `G'` is onto, as it is the derivative of a local diffeomorphism, the composition -- of the two charts and of `e`. have C : dense_range (G' : E → E'), { have : G' = mfderiv I I' ((chart_at H z).symm ≫ₕ e ≫ₕ (chart_at H' x)) ((chart_at H z : M → H) z), by { rw (Diff.mdifferentiable_at Mmem).mfderiv, refl }, rw this, exact (Diff.mfderiv_surjective Mmem).dense_range }, -- key step: thanks to what we have proved about it, `G` preserves the unique derivative property have key : unique_diff_within_at 𝕜 (G '' (F.symm ⁻¹' (s ∩ (e.source ∩ e ⁻¹' ((ext_chart_at I' x).source))) ∩ F.target)) (G (F z)) := D₂.unique_diff_within_at B C, have : G (F z) = (ext_chart_at I' x) x, by { dsimp [G, F], simp only [hx.1] with mfld_simps }, rw this at key, apply key.mono, show G '' (F.symm ⁻¹' (s ∩ (e.source ∩ e ⁻¹' ((ext_chart_at I' x).source))) ∩ F.target) ⊆ (ext_chart_at I' x).symm ⁻¹' e.target ∩ (ext_chart_at I' x).symm ⁻¹' (e.symm ⁻¹' s) ∩ range (I'), rw image_subset_iff, mfld_set_tac end /-- If a set in a manifold has the unique derivative property, then its pullback by any extended chart, in the vector space, also has the unique derivative property. -/ lemma unique_mdiff_on.unique_diff_on_target_inter (hs : unique_mdiff_on I s) (x : M) : unique_diff_on 𝕜 ((ext_chart_at I x).target ∩ ((ext_chart_at I x).symm ⁻¹' s)) := begin -- this is just a reformulation of `unique_mdiff_on.unique_mdiff_on_preimage`, using as `e` -- the local chart at `x`. assume z hz, simp only with mfld_simps at hz, have : (chart_at H x).mdifferentiable I I := mdifferentiable_chart _ _, have T := (hs.unique_mdiff_on_preimage this) (I.symm z), simp only [hz.left.left, hz.left.right, hz.right, unique_mdiff_within_at] with mfld_simps at ⊢ T, convert T using 1, rw @preimage_comp _ _ _ _ (chart_at H x).symm, mfld_set_tac end /-- When considering functions between manifolds, this statement shows up often. It entails the unique differential of the pullback in extended charts of the set where the function can be read in the charts. -/ lemma unique_mdiff_on.unique_diff_on_inter_preimage (hs : unique_mdiff_on I s) (x : M) (y : M') {f : M → M'} (hf : continuous_on f s) : unique_diff_on 𝕜 ((ext_chart_at I x).target ∩ ((ext_chart_at I x).symm ⁻¹' (s ∩ f⁻¹' (ext_chart_at I' y).source))) := begin have : unique_mdiff_on I (s ∩ f ⁻¹' (ext_chart_at I' y).source), { assume z hz, apply (hs z hz.1).inter', apply (hf z hz.1).preimage_mem_nhds_within, exact is_open.mem_nhds (ext_chart_at_open_source I' y) hz.2 }, exact this.unique_diff_on_target_inter _ end variables {F : Type*} [normed_group F] [normed_space 𝕜 F] (Z : basic_smooth_bundle_core I M F) /-- In a smooth fiber bundle constructed from core, the preimage under the projection of a set with unique differential in the basis also has unique differential. -/ lemma unique_mdiff_on.smooth_bundle_preimage (hs : unique_mdiff_on I s) : unique_mdiff_on (I.prod (𝓘(𝕜, F))) (Z.to_topological_fiber_bundle_core.proj ⁻¹' s) := begin /- Using a chart (and the fact that unique differentiability is invariant under charts), we reduce the situation to the model space, where we can use the fact that products respect unique differentiability. -/ assume p hp, replace hp : p.fst ∈ s, by simpa only with mfld_simps using hp, let e₀ := chart_at H p.1, let e := chart_at (model_prod H F) p, -- It suffices to prove unique differentiability in a chart suffices h : unique_mdiff_on (I.prod (𝓘(𝕜, F))) (e.target ∩ e.symm⁻¹' (Z.to_topological_fiber_bundle_core.proj ⁻¹' s)), { have A : unique_mdiff_on (I.prod (𝓘(𝕜, F))) (e.symm.target ∩ e.symm.symm ⁻¹' (e.target ∩ e.symm⁻¹' (Z.to_topological_fiber_bundle_core.proj ⁻¹' s))), { apply h.unique_mdiff_on_preimage, exact (mdifferentiable_of_mem_atlas _ (chart_mem_atlas _ _)).symm, apply_instance }, have : p ∈ e.symm.target ∩ e.symm.symm ⁻¹' (e.target ∩ e.symm⁻¹' (Z.to_topological_fiber_bundle_core.proj ⁻¹' s)), by simp only [e, hp] with mfld_simps, apply (A _ this).mono, assume q hq, simp only [e, local_homeomorph.left_inv _ hq.1] with mfld_simps at hq, simp only [hq] with mfld_simps }, -- rewrite the relevant set in the chart as a direct product have : (λ (p : E × F), (I.symm p.1, p.snd)) ⁻¹' e.target ∩ (λ (p : E × F), (I.symm p.1, p.snd)) ⁻¹' (e.symm ⁻¹' (sigma.fst ⁻¹' s)) ∩ (range I ×ˢ (univ : set F)) = (I.symm ⁻¹' (e₀.target ∩ e₀.symm⁻¹' s) ∩ range I) ×ˢ (univ : set F), by mfld_set_tac, assume q hq, replace hq : q.1 ∈ (chart_at H p.1).target ∧ ((chart_at H p.1).symm : H → M) q.1 ∈ s, by simpa only with mfld_simps using hq, simp only [unique_mdiff_within_at, model_with_corners.prod, preimage_inter, this] with mfld_simps, -- apply unique differentiability of products to conclude apply unique_diff_on.prod _ unique_diff_on_univ, { simp only [hq] with mfld_simps }, { assume x hx, have A : unique_mdiff_on I (e₀.target ∩ e₀.symm⁻¹' s), { apply hs.unique_mdiff_on_preimage, exact (mdifferentiable_of_mem_atlas _ (chart_mem_atlas _ _)), apply_instance }, simp only [unique_mdiff_on, unique_mdiff_within_at, preimage_inter] with mfld_simps at A, have B := A (I.symm x) hx.1.1 hx.1.2, rwa [← preimage_inter, model_with_corners.right_inv _ hx.2] at B } end lemma unique_mdiff_on.tangent_bundle_proj_preimage (hs : unique_mdiff_on I s): unique_mdiff_on I.tangent ((tangent_bundle.proj I M) ⁻¹' s) := hs.smooth_bundle_preimage _ end unique_mdiff
cd06ad3a2e05b967c581952277ec75a6f8f082cb
8e31b9e0d8cec76b5aa1e60a240bbd557d01047c
/scratch/analytics.lean
574189e2dfe1103086eb8d143c3cc7f9a9b264fe
[]
no_license
ChrisHughes24/LP
7bdd62cb648461c67246457f3ddcb9518226dd49
e3ed64c2d1f642696104584e74ae7226d8e916de
refs/heads/master
1,685,642,642,858
1,578,070,602,000
1,578,070,602,000
195,268,102
4
3
null
1,569,229,518,000
1,562,255,287,000
Lean
UTF-8
Lean
false
false
5,602
lean
import linear_algebra.finite_dimensional open declaration tactic meta def list_constant (e : expr) : tactic (list name) := e.fold (return []) $ λ e _ cs, do env ← get_env, cs ← cs, let n := e.const_name in match (@option.none ℕ) with | none := if e.is_constant ∧ n ∉ cs then return (n :: cs) else return cs | _ := return cs end meta def const_in_def (n : name) : tactic (list name) := do d ← get_decl n, match d with | thm _ _ t v := do lv ← list_constant v.get, lt ← list_constant t, return (lv ∪ lt) | defn _ _ t v _ _ := do lv ← list_constant v, lt ← list_constant t, return (lv ∪ lt) | cnst _ _ t _ := list_constant t | ax _ _ t := list_constant t end meta def const_in_def_trans_aux₁ : list name × list (name × list name) → tactic (list name × list (name × list name)) | ([], l₂) := pure ([], l₂) | (l₁, l₂) := do l' ← l₁.mmap (λ n, do l ← const_in_def n, return (n, l)), let l2 := l' ++ l₂, const_in_def_trans_aux₁ ((l'.map prod.snd).join.erase_dup.diff (l2.map prod.fst), l2) meta def const_in_def_trans_aux₂ : list name × list name → tactic (list name × list name) | ([], l₂) := pure ([], l₂) | (l₁, l₂) := do l' ← l₁.mmap const_in_def, let l2 := l₁ ∪ l₂, const_in_def_trans_aux₂ (l'.join.erase_dup.diff l2, l2) meta def const_in_def_trans (n : name) : tactic unit := do l ← const_in_def_trans_aux₂ ([n], []), trace l.2.length, trace (list.insertion_sort (≤) (l.2.map to_string)), return () set_option profiler true #eval const_in_def_trans `linear_map.mul_eq_one_comm #print environment.is_projection -- #eval const_in_def_trans `zmodp.is_square_iff_is_square_of_mod_four_eq_one #print int.le.dest meta def list_all_consts : tactic (list name) := do e ← get_env, let l : list name := environment.fold e [] (λ d l, match d with | thm n _ _ _ := n :: l | defn n _ _ _ _ _ := n :: l | cnst n _ _ _ := n :: l | ax n _ _ := n :: l end), return l #print unsigned_sz meta def list_namespace : tactic unit := do l ← list_all_consts, let m := l.filter (λ n, n.get_prefix = `polynomial), trace m.length, trace m, return () #eval (name.get_prefix `nat.prime.mod_add_div).to_string #eval (name.get_prefix (`nat.mod_add_div) = `polynomial : bool) #eval list_namespace -- meta def trans_def_all_aux : list name → rbmap name (rbtree name) -- → rbmap name (rbtree name) → option (rbmap name (rbtree name)) -- | [] m₁ m₂ := pure m₂ -- | (n::l₁) m₁ m₂ := -- do l₁ ← m₁.find n, -- l₂ ← l₁.mmap m₁.find, -- let l₃ := l₂.join, -- if l₃ = l₁ then trans_def_all_aux l₁ (m₁.erase n) -- else sorry -- meta def trans_def_list (l : list name) : tactic unit := -- do -- map ← l.mmap (λ n, do l' ← const_in_def n, return (n, l)), -- m ← trans_def_all_aux [`prod.swap] (pure (rbmap.from_list map)), -- let result := m.to_list, -- trace (result.map (λ n, (n.1, n.2.length))), -- return () -- meta def trans_def_list_all : tactic unit := -- do l ← list_all_consts, -- trans_def_list l, -- return () #print if_ctx_simp_congr -- #eval const_in_def_trans `zmodp.quadratic_reciprocity #print algebra.sub -- #eval trans_def_list_all #exit #print list.union meta def const_in_def_trans_aux : Π (n : name), tactic (list name) | n := do d ← get_decl n, match d with | thm _ _ t v := do let v := v.get, let l := list_constant v, -- do m ← l.mmap const_in_def_trans_aux, return (l).erase_dup | defn _ _ t v _ _ := do let l := list_constant v, do m ← l.mmap const_in_def_trans_aux, return (l).erase_dup | d := pure [] end meta def const_in_def_depth_aux : ℕ → name → list name → tactic (list name) | 0 n p := pure [] | (m+1) n p := do d ← get_decl n, match d with | thm _ _ t v := do let v := v.get, let l := (list_constant v).diff p, let q := p ++ l, l' ← l.mmap (λ n, const_in_def_depth_aux m n q), return (l ++ l'.bind id).erase_dup | defn _ _ t v _ _ := do let l := (list_constant v).diff p, let q := p ++ l, l' ← l.mmap (λ n, const_in_def_depth_aux m n q), return (l ++ l'.bind id).erase_dup | d := pure [] end meta def const_in_def_depth_aux' : ℕ → Π n : name, tactic (list name) | 0 n := pure [] | (m+1) n := do d ← get_decl n, match d with | thm _ _ t v := do let v := v.get, let l := list_constant v, l' ← l.mmap (const_in_def_depth_aux' m), return (l'.bind id ++ l).erase_dup | defn _ _ t v _ _ := do let l := list_constant v, l' ← l.mmap (const_in_def_depth_aux' m), return (l'.bind id ++ l).erase_dup | d := pure [] end meta def const_in_def_depth (m : ℕ) (n : name) : tactic unit := do l ← const_in_def_depth_aux m n [], trace l.length, trace l, return () meta def const_in_def_depth' (m : ℕ) (n : name) : tactic unit := do l ← const_in_def_depth_aux' m n, trace l.length, trace l, return () meta def const_in_def_trans (n : name) : tactic unit := do l ← const_in_def_trans_aux n, trace l.length, trace l, return () set_option profiler true -- #eval const_in_def_depth' 3 `polynomial.euclidean_domain -- #eval const_in_def_depth 5 `polynomial.euclidean_domain -- meta def const_in_def₂ (n : name) : tactic (list name) := -- do l ← const_in_def n, -- m ← l.mmap const_in_def, -- trace m, -- return l #print simp_config #exit data.zmod.basic data.polynomial tactic.norm_num data.rat instance h {p : ℕ} (hp : nat.prime p) : has_repr (zmodp p hp) := fin.has_repr _ open polynomial #eval (11 * X ^ 20 + 7 * X ^ 9 + 12 * X + 11 : polynomial ℚ) / (22 * X ^ 2 - 1)
e140720e1846349a0c48a7a9243589e50a94154d
b7b549d2cf38ac9d4e49372b7ad4d37f70449409
/src/LeanLLVM/simple.lean
aceede2a16d03c746f5d42490f8e9bcaa5ad814f
[ "Apache-2.0" ]
permissive
GaloisInc/lean-llvm
7cc196172fe02ff3554edba6cc82f333c30fdc2b
36e2ec604ae22d8ec1b1b66eca0f8887880db6c6
refs/heads/master
1,637,359,020,356
1,629,332,114,000
1,629,402,464,000
146,700,234
29
1
Apache-2.0
1,631,225,695,000
1,535,607,191,000
Lean
UTF-8
Lean
false
false
5,264
lean
import init.data.rbmap import init.io import .ast import .pp open llvm def simple_module := module.mk (some "simple.c") [layout_spec.little_endian, (layout_spec.mangling mangling.mach_o), (layout_spec.align_size align_type.integer 64 64 none), (layout_spec.align_size align_type.float 80 128 none), (layout_spec.native_int_size [8, 16, 32, 64]), (layout_spec.stack_align 128)] [] [(named_md.mk "llvm.dbg.cu" [0]), (named_md.mk "llvm.ident" [7]), (named_md.mk "llvm.module.flags" [3, 4, 5, 6])] [(unnamed_md.mk 0 val_md.debug_info true), (unnamed_md.mk 1 val_md.debug_info false), (unnamed_md.mk 2 (val_md.node []) false), (unnamed_md.mk 3 (val_md.node [(some (val_md.value (typed.mk (llvm_type.prim_type (prim_type.integer 32)) (value.integer 2)))), (some (val_md.string "Dwarf Version")), (some (val_md.value (typed.mk (llvm_type.prim_type (prim_type.integer 32)) (value.integer 4))))]) false), (unnamed_md.mk 4 (val_md.node [(some (val_md.value (typed.mk (llvm_type.prim_type (prim_type.integer 32)) (value.integer 2)))), (some (val_md.string "Debug Info Version")), (some (val_md.value (typed.mk (llvm_type.prim_type (prim_type.integer 32)) (value.integer 3))))]) false), (unnamed_md.mk 5 (val_md.node [(some (val_md.value (typed.mk (llvm_type.prim_type (prim_type.integer 32)) (value.integer 1)))), (some (val_md.string "wchar_size")), (some (val_md.value (typed.mk (llvm_type.prim_type (prim_type.integer 32)) (value.integer 4))))]) false), (unnamed_md.mk 6 (val_md.node [(some (val_md.value (typed.mk (llvm_type.prim_type (prim_type.integer 32)) (value.integer 7)))), (some (val_md.string "PIC Level")), (some (val_md.value (typed.mk (llvm_type.prim_type (prim_type.integer 32)) (value.integer 2))))]) false), (unnamed_md.mk 7 (val_md.node [(some (val_md.string "Apple LLVM version 10.0.0 (clang-1000.10.44.4)"))]) false), (unnamed_md.mk 8 val_md.debug_info true), (unnamed_md.mk 9 val_md.debug_info false), (unnamed_md.mk 10 val_md.debug_info false), (unnamed_md.mk 11 val_md.debug_info false), (unnamed_md.mk 12 (val_md.node [(some (val_md.ref 11)), (some (val_md.ref 11)), (some (val_md.ref 11))]) false), (unnamed_md.mk 13 val_md.debug_info true), (unnamed_md.mk 14 val_md.debug_info false), (unnamed_md.mk 15 val_md.debug_info false), (unnamed_md.mk 16 (val_md.node [(some (val_md.ref 14)), (some (val_md.ref 15))]) false), (unnamed_md.mk 17 val_md.debug_info true)] (strmap_empty selection_kind) [] [(declare.mk (llvm_type.prim_type prim_type.void) (symbol.mk "llvm.dbg.value") [(llvm_type.prim_type prim_type.metadata), (llvm_type.prim_type prim_type.metadata), (llvm_type.prim_type prim_type.metadata)] false [] none)] [(define.mk none (llvm_type.prim_type (prim_type.integer 32)) (symbol.mk "add") [(typed.mk (llvm_type.prim_type (prim_type.integer 32)) (ident.mk "0")), (typed.mk (llvm_type.prim_type (prim_type.integer 32)) (ident.mk "1"))] false [] none none [ (basic_block.mk (some (block_label.anon 2)) [ (stmt.mk none (instruction.call false (llvm_type.ptr_to (llvm_type.fun_ty (llvm_type.prim_type prim_type.void) [(llvm_type.prim_type prim_type.metadata), (llvm_type.prim_type prim_type.metadata), (llvm_type.prim_type prim_type.metadata)] false)) (value.symbol (symbol.mk "llvm.dbg.value")) [(typed.mk (llvm_type.prim_type prim_type.metadata) (value.md (val_md.value (typed.mk (llvm_type.prim_type (prim_type.integer 32)) (value.ident (ident.mk "0")))))), (typed.mk (llvm_type.prim_type prim_type.metadata) (value.md val_md.debug_info)), (typed.mk (llvm_type.prim_type prim_type.metadata) (value.md val_md.debug_info))]) [("dbg", (val_md.loc (debug_loc.debug_loc 3 24 (val_md.ref 8) none)))]) , (stmt.mk none (instruction.call false (llvm_type.ptr_to (llvm_type.fun_ty (llvm_type.prim_type prim_type.void) [(llvm_type.prim_type prim_type.metadata), (llvm_type.prim_type prim_type.metadata), (llvm_type.prim_type prim_type.metadata)] false)) (value.symbol (symbol.mk "llvm.dbg.value")) [(typed.mk (llvm_type.prim_type prim_type.metadata) (value.md (val_md.value (typed.mk (llvm_type.prim_type (prim_type.integer 32)) (value.ident (ident.mk "1")))))), (typed.mk (llvm_type.prim_type prim_type.metadata) (value.md val_md.debug_info)), (typed.mk (llvm_type.prim_type prim_type.metadata) (value.md val_md.debug_info))]) [("dbg", (val_md.loc (debug_loc.debug_loc 3 36 (val_md.ref 8) none)))]) , (stmt.mk (some (ident.mk "3")) (instruction.bit (bit_op.shl false false) (typed.mk (llvm_type.prim_type (prim_type.integer 32)) (value.ident (ident.mk "1"))) (value.integer 1)) [("dbg", (val_md.loc (debug_loc.debug_loc 4 17 (val_md.ref 8) none)))]) , (stmt.mk (some (ident.mk "4")) (instruction.arith (arith_op.add false false) (typed.mk (llvm_type.prim_type (prim_type.integer 32)) (value.ident (ident.mk "3"))) (value.ident (ident.mk "0"))) [("dbg", (val_md.loc (debug_loc.debug_loc 4 13 (val_md.ref 8) none)))]) , (stmt.mk none (instruction.ret (typed.mk (llvm_type.prim_type (prim_type.integer 32)) (value.ident (ident.mk "4")))) [("dbg", (val_md.loc (debug_loc.debug_loc 4 3 (val_md.ref 8) none)))]) ]) ] (strmap_empty val_md) none)] [] [] def main : IO Unit := IO.println (pp.render (pp_module simple_module))
ff4ba883e7b99ee786a8d7981112d37be0049078
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/meta/injection_tactic.lean
e43dddb8e7f55fef6c990afe7c2030ccc27fbe21
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
4,753
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, Jannis Limperg -/ prelude import init.meta.tactic namespace tactic open expr /-- Given a local constant `H : C x₁ ... xₙ = D y₁ ... yₘ`, where `C` and `D` are fully applied constructors, `injection_with H ns base offset` does the following: - If `C ≠ D`, it solves the goal (using the no-confusion rule). - If `C = D` (and thus `n = m`), it adds hypotheses `h₁ : x₁ = y₁, ..., hₙ : xₙ = yₙ` to the local context. Names for the `hᵢ` are taken from `ns`. If `ns` does not contain enough names, then the names are derived from `base` and `offset` (by default `h_1`, `h_2` etc.; see `intro_fresh`). - Special case: if `C = D` and `n = 0` (i.e. the constructors have no arguments), the hypothesis `h : true` is added to the context. `injection_with` returns the new hypotheses and the leftover names from `ns` (i.e. those names that were not used to name the new hypotheses). If (and only if) the goal was solved, the list of new hypotheses is empty. -/ meta def injection_with (h : expr) (ns : list name) (base := `h) (offset := some 1) : tactic (list expr × list name) := do H ← infer_type h, (lhs, rhs, constructor_left, constructor_right, inj_name) ← do { (lhs, rhs) ← match_eq H, lhs ← whnf_ginductive lhs, rhs ← whnf_ginductive rhs, env ← get_env, (const constructor_left _) ← pure $ get_app_fn lhs, (const constructor_right _) ← pure $ get_app_fn rhs, inj_name ← resolve_constant $ constructor_left ++ "inj_arrow", pure (lhs, rhs, constructor_left, constructor_right, inj_name) } <|> fail "injection tactic failed, argument must be an equality proof where lhs and rhs are of the form (c ...), where c is a constructor", if constructor_left = constructor_right then do -- C.inj_arrow, for a given constructor C of datatype D, has type -- -- ∀ (A₁ ... Aₙ) (x₁ ... xₘ) (y₁ ... yₘ), C x₁ ... xₘ = C y₁ ... yₘ -- → ∀ ⦃P : Sort u⦄, (x₁ = y₁ → ... → yₖ = yₖ → P) → P -- -- where the Aᵢ are parameters of D and the xᵢ/yᵢ are arguments of C. -- Note that if xᵢ/yᵢ are propositions, no equation is generated, so the -- number of equations is not necessarily the constructor arity. -- First, we find out how many equations we need to intro later. inj ← mk_const inj_name, inj_type ← infer_type inj, inj_arity ← get_pi_arity inj_type, let num_equations := (inj_type.nth_binding_body (inj_arity - 1)).binding_domain.pi_arity, -- Now we generate the actual proof of the target. tgt ← target, proof ← mk_mapp inj_name (list.repeat none (inj_arity - 3) ++ [some h, some tgt]), eapply proof, intron_with num_equations ns base offset else do tgt ← target, let inductive_name := constructor_left.get_prefix, pr ← mk_app (inductive_name <.> "no_confusion") [tgt, lhs, rhs, h], exact pr, return ([], ns) /-- Simplify the equation `h` using injectivity of constructors. See `injection_with`. Returns the hypotheses that were added to the context, or an empty list if the goal was solved by contradiction. -/ meta def injection (h : expr) (base := `h) (offset := some 1) : tactic (list expr) := prod.fst <$> injection_with h [] base offset private meta def injections_with_inner (base : name) (offset : option ℕ) : ℕ → list expr → list name → tactic unit | 0 lc ns := fail "recursion depth exceeded" | (n+1) [] ns := skip | (n+1) (h :: lc) ns := do o ← try_core (injection_with h ns base offset), match o with | none := injections_with_inner (n+1) lc ns | some ([], _) := skip -- This means that the contradiction part was triggered and the goal is done | some (t, ns') := injections_with_inner n (t ++ lc) ns' end /-- Simplifies equations in the context using injectivity of constructors. For each equation `h : C x₁ ... xₙ = D y₁ ... yₘ` in the context, where `C` and `D` are constructors of the same data type, `injections_with` does the following: - If `C = D`, it adds equations `x₁ = y₁`, ..., `xₙ = yₙ`. - If `C ≠ D`, it solves the goal by contradiction. See `injection_with` for details, including information about `base` and `offset`. `injections_with` also recurses into the new equations `xᵢ = yᵢ`. If it has to recurse more than five times, it fails. -/ meta def injections_with (ns : list name) (base := `h) (offset := some 1) : tactic unit := do lc ← local_context, injections_with_inner base offset 5 lc ns end tactic
037df052a65a7df41fac4bd233228d9a56fae3ab
4950bf76e5ae40ba9f8491647d0b6f228ddce173
/src/order/bounds.lean
54641e63f53e7e19365ccaf877671112473159d8
[ "Apache-2.0" ]
permissive
ntzwq/mathlib
ca50b21079b0a7c6781c34b62199a396dd00cee2
36eec1a98f22df82eaccd354a758ef8576af2a7f
refs/heads/master
1,675,193,391,478
1,607,822,996,000
1,607,822,996,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
29,484
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, Yury Kudryashov -/ import data.set.intervals.basic import algebra.ordered_group /-! # Upper / lower bounds In this file we define: * `upper_bounds`, `lower_bounds` : the set of upper bounds (resp., lower bounds) of a set; * `bdd_above s`, `bdd_below s` : the set `s` is bounded above (resp., below), i.e., the set of upper (resp., lower) bounds of `s` is nonempty; * `is_least s a`, `is_greatest s a` : `a` is a least (resp., greatest) element of `s`; for a partial order, it is unique if exists; * `is_lub s a`, `is_glb s a` : `a` is a least upper bound (resp., a greatest lower bound) of `s`; for a partial order, it is unique if exists. We also prove various lemmas about monotonicity, behaviour under `∪`, `∩`, `insert`, and provide formulas for `∅`, `univ`, and intervals. -/ open set universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} section variables [preorder α] [preorder β] {s t : set α} {a b : α} /-! ### Definitions -/ /-- The set of upper bounds of a set. -/ def upper_bounds (s : set α) : set α := { x | ∀ ⦃a⦄, a ∈ s → a ≤ x } /-- The set of lower bounds of a set. -/ def lower_bounds (s : set α) : set α := { x | ∀ ⦃a⦄, a ∈ s → x ≤ a } /-- A set is bounded above if there exists an upper bound. -/ def bdd_above (s : set α) := (upper_bounds s).nonempty /-- A set is bounded below if there exists a lower bound. -/ def bdd_below (s : set α) := (lower_bounds s).nonempty /-- `a` is a least element of a set `s`; for a partial order, it is unique if exists. -/ def is_least (s : set α) (a : α) : Prop := a ∈ s ∧ a ∈ lower_bounds s /-- `a` is a greatest element of a set `s`; for a partial order, it is unique if exists -/ def is_greatest (s : set α) (a : α) : Prop := a ∈ s ∧ a ∈ upper_bounds s /-- `a` is a least upper bound of a set `s`; for a partial order, it is unique if exists. -/ def is_lub (s : set α) : α → Prop := is_least (upper_bounds s) /-- `a` is a greatest lower bound of a set `s`; for a partial order, it is unique if exists. -/ def is_glb (s : set α) : α → Prop := is_greatest (lower_bounds s) lemma mem_upper_bounds : a ∈ upper_bounds s ↔ ∀ x ∈ s, x ≤ a := iff.rfl lemma mem_lower_bounds : a ∈ lower_bounds s ↔ ∀ x ∈ s, a ≤ x := iff.rfl /-- A set `s` is not bounded above if and only if for each `x` there exists `y ∈ s` such that `x` is not greater than or equal to `y`. This version only assumes `preorder` structure and uses `¬(y ≤ x)`. A version for linear orders is called `not_bdd_above_iff`. -/ lemma not_bdd_above_iff' : ¬bdd_above s ↔ ∀ x, ∃ y ∈ s, ¬(y ≤ x) := by simp [bdd_above, upper_bounds, set.nonempty] /-- A set `s` is not bounded below if and only if for each `x` there exists `y ∈ s` such that `x` is not less than or equal to `y`. This version only assumes `preorder` structure and uses `¬(x ≤ y)`. A version for linear orders is called `not_bdd_below_iff`. -/ lemma not_bdd_below_iff' : ¬bdd_below s ↔ ∀ x, ∃ y ∈ s, ¬(x ≤ y) := @not_bdd_above_iff' (order_dual α) _ _ /-- A set `s` is not bounded above if and only if for each `x` there exists `y ∈ s` that is greater than `x`. A version for preorders is called `not_bdd_above_iff'`. -/ lemma not_bdd_above_iff {α : Type*} [linear_order α] {s : set α} : ¬bdd_above s ↔ ∀ x, ∃ y ∈ s, x < y := by simp only [not_bdd_above_iff', not_le] /-- A set `s` is not bounded below if and only if for each `x` there exists `y ∈ s` that is less than `x`. A version for preorders is called `not_bdd_below_iff'`. -/ lemma not_bdd_below_iff {α : Type*} [linear_order α] {s : set α} : ¬bdd_below s ↔ ∀ x, ∃ y ∈ s, y < x := @not_bdd_above_iff (order_dual α) _ _ /-! ### Monotonicity -/ lemma upper_bounds_mono_set ⦃s t : set α⦄ (hst : s ⊆ t) : upper_bounds t ⊆ upper_bounds s := λ b hb x h, hb $ hst h lemma lower_bounds_mono_set ⦃s t : set α⦄ (hst : s ⊆ t) : lower_bounds t ⊆ lower_bounds s := λ b hb x h, hb $ hst h lemma upper_bounds_mono_mem ⦃a b⦄ (hab : a ≤ b) : a ∈ upper_bounds s → b ∈ upper_bounds s := λ ha x h, le_trans (ha h) hab lemma lower_bounds_mono_mem ⦃a b⦄ (hab : a ≤ b) : b ∈ lower_bounds s → a ∈ lower_bounds s := λ hb x h, le_trans hab (hb h) lemma upper_bounds_mono ⦃s t : set α⦄ (hst : s ⊆ t) ⦃a b⦄ (hab : a ≤ b) : a ∈ upper_bounds t → b ∈ upper_bounds s := λ ha, upper_bounds_mono_set hst $ upper_bounds_mono_mem hab ha lemma lower_bounds_mono ⦃s t : set α⦄ (hst : s ⊆ t) ⦃a b⦄ (hab : a ≤ b) : b ∈ lower_bounds t → a ∈ lower_bounds s := λ hb, lower_bounds_mono_set hst $ lower_bounds_mono_mem hab hb /-- If `s ⊆ t` and `t` is bounded above, then so is `s`. -/ lemma bdd_above.mono ⦃s t : set α⦄ (h : s ⊆ t) : bdd_above t → bdd_above s := nonempty.mono $ upper_bounds_mono_set h /-- If `s ⊆ t` and `t` is bounded below, then so is `s`. -/ lemma bdd_below.mono ⦃s t : set α⦄ (h : s ⊆ t) : bdd_below t → bdd_below s := nonempty.mono $ lower_bounds_mono_set h /-- If `a` is a least upper bound for sets `s` and `p`, then it is a least upper bound for any set `t`, `s ⊆ t ⊆ p`. -/ lemma is_lub.of_subset_of_superset {s t p : set α} (hs : is_lub s a) (hp : is_lub p a) (hst : s ⊆ t) (htp : t ⊆ p) : is_lub t a := ⟨upper_bounds_mono_set htp hp.1, lower_bounds_mono_set (upper_bounds_mono_set hst) hs.2⟩ /-- If `a` is a greatest lower bound for sets `s` and `p`, then it is a greater lower bound for any set `t`, `s ⊆ t ⊆ p`. -/ lemma is_glb.of_subset_of_superset {s t p : set α} (hs : is_glb s a) (hp : is_glb p a) (hst : s ⊆ t) (htp : t ⊆ p) : is_glb t a := @is_lub.of_subset_of_superset (order_dual α) _ a s t p hs hp hst htp lemma is_least.mono (ha : is_least s a) (hb : is_least t b) (hst : s ⊆ t) : b ≤ a := hb.2 (hst ha.1) lemma is_greatest.mono (ha : is_greatest s a) (hb : is_greatest t b) (hst : s ⊆ t) : a ≤ b := hb.2 (hst ha.1) lemma is_lub.mono (ha : is_lub s a) (hb : is_lub t b) (hst : s ⊆ t) : a ≤ b := hb.mono ha $ upper_bounds_mono_set hst lemma is_glb.mono (ha : is_glb s a) (hb : is_glb t b) (hst : s ⊆ t) : b ≤ a := hb.mono ha $ lower_bounds_mono_set hst /-! ### Conversions -/ lemma is_least.is_glb (h : is_least s a) : is_glb s a := ⟨h.2, λ b hb, hb h.1⟩ lemma is_greatest.is_lub (h : is_greatest s a) : is_lub s a := ⟨h.2, λ b hb, hb h.1⟩ lemma is_lub.upper_bounds_eq (h : is_lub s a) : upper_bounds s = Ici a := set.ext $ λ b, ⟨λ hb, h.2 hb, λ hb, upper_bounds_mono_mem hb h.1⟩ lemma is_glb.lower_bounds_eq (h : is_glb s a) : lower_bounds s = Iic a := @is_lub.upper_bounds_eq (order_dual α) _ _ _ h lemma is_least.lower_bounds_eq (h : is_least s a) : lower_bounds s = Iic a := h.is_glb.lower_bounds_eq lemma is_greatest.upper_bounds_eq (h : is_greatest s a) : upper_bounds s = Ici a := h.is_lub.upper_bounds_eq lemma is_lub_le_iff (h : is_lub s a) : a ≤ b ↔ b ∈ upper_bounds s := by { rw h.upper_bounds_eq, refl } lemma le_is_glb_iff (h : is_glb s a) : b ≤ a ↔ b ∈ lower_bounds s := by { rw h.lower_bounds_eq, refl } /-- If `s` has a least upper bound, then it is bounded above. -/ lemma is_lub.bdd_above (h : is_lub s a) : bdd_above s := ⟨a, h.1⟩ /-- If `s` has a greatest lower bound, then it is bounded below. -/ lemma is_glb.bdd_below (h : is_glb s a) : bdd_below s := ⟨a, h.1⟩ /-- If `s` has a greatest element, then it is bounded above. -/ lemma is_greatest.bdd_above (h : is_greatest s a) : bdd_above s := ⟨a, h.2⟩ /-- If `s` has a least element, then it is bounded below. -/ lemma is_least.bdd_below (h : is_least s a) : bdd_below s := ⟨a, h.2⟩ lemma is_least.nonempty (h : is_least s a) : s.nonempty := ⟨a, h.1⟩ lemma is_greatest.nonempty (h : is_greatest s a) : s.nonempty := ⟨a, h.1⟩ /-! ### Union and intersection -/ @[simp] lemma upper_bounds_union : upper_bounds (s ∪ t) = upper_bounds s ∩ upper_bounds t := subset.antisymm (λ b hb, ⟨λ x hx, hb (or.inl hx), λ x hx, hb (or.inr hx)⟩) (λ b hb x hx, hx.elim (λ hs, hb.1 hs) (λ ht, hb.2 ht)) @[simp] lemma lower_bounds_union : lower_bounds (s ∪ t) = lower_bounds s ∩ lower_bounds t := @upper_bounds_union (order_dual α) _ s t lemma union_upper_bounds_subset_upper_bounds_inter : upper_bounds s ∪ upper_bounds t ⊆ upper_bounds (s ∩ t) := union_subset (upper_bounds_mono_set $ inter_subset_left _ _) (upper_bounds_mono_set $ inter_subset_right _ _) lemma union_lower_bounds_subset_lower_bounds_inter : lower_bounds s ∪ lower_bounds t ⊆ lower_bounds (s ∩ t) := @union_upper_bounds_subset_upper_bounds_inter (order_dual α) _ s t lemma is_least_union_iff {a : α} {s t : set α} : is_least (s ∪ t) a ↔ (is_least s a ∧ a ∈ lower_bounds t ∨ a ∈ lower_bounds s ∧ is_least t a) := by simp [is_least, lower_bounds_union, or_and_distrib_right, and_comm (a ∈ t), and_assoc] lemma is_greatest_union_iff : is_greatest (s ∪ t) a ↔ (is_greatest s a ∧ a ∈ upper_bounds t ∨ a ∈ upper_bounds s ∧ is_greatest t a) := @is_least_union_iff (order_dual α) _ a s t /-- If `s` is bounded, then so is `s ∩ t` -/ lemma bdd_above.inter_of_left (h : bdd_above s) : bdd_above (s ∩ t) := h.mono $ inter_subset_left s t /-- If `t` is bounded, then so is `s ∩ t` -/ lemma bdd_above.inter_of_right (h : bdd_above t) : bdd_above (s ∩ t) := h.mono $ inter_subset_right s t /-- If `s` is bounded, then so is `s ∩ t` -/ lemma bdd_below.inter_of_left (h : bdd_below s) : bdd_below (s ∩ t) := h.mono $ inter_subset_left s t /-- If `t` is bounded, then so is `s ∩ t` -/ lemma bdd_below.inter_of_right (h : bdd_below t) : bdd_below (s ∩ t) := h.mono $ inter_subset_right s t /-- If `s` and `t` are bounded above sets in a `semilattice_sup`, then so is `s ∪ t`. -/ lemma bdd_above.union [semilattice_sup γ] {s t : set γ} : bdd_above s → bdd_above t → bdd_above (s ∪ t) := begin rintros ⟨bs, hs⟩ ⟨bt, ht⟩, use bs ⊔ bt, rw upper_bounds_union, exact ⟨upper_bounds_mono_mem le_sup_left hs, upper_bounds_mono_mem le_sup_right ht⟩ end /-- The union of two sets is bounded above if and only if each of the sets is. -/ lemma bdd_above_union [semilattice_sup γ] {s t : set γ} : bdd_above (s ∪ t) ↔ bdd_above s ∧ bdd_above t := ⟨λ h, ⟨h.mono $ subset_union_left s t, h.mono $ subset_union_right s t⟩, λ h, h.1.union h.2⟩ lemma bdd_below.union [semilattice_inf γ] {s t : set γ} : bdd_below s → bdd_below t → bdd_below (s ∪ t) := @bdd_above.union (order_dual γ) _ s t /--The union of two sets is bounded above if and only if each of the sets is.-/ lemma bdd_below_union [semilattice_inf γ] {s t : set γ} : bdd_below (s ∪ t) ↔ bdd_below s ∧ bdd_below t := @bdd_above_union (order_dual γ) _ s t /-- If `a` is the least upper bound of `s` and `b` is the least upper bound of `t`, then `a ⊔ b` is the least upper bound of `s ∪ t`. -/ lemma is_lub.union [semilattice_sup γ] {a b : γ} {s t : set γ} (hs : is_lub s a) (ht : is_lub t b) : is_lub (s ∪ t) (a ⊔ b) := ⟨assume c h, h.cases_on (λ h, le_sup_left_of_le $ hs.left h) (λ h, le_sup_right_of_le $ ht.left h), assume c hc, sup_le (hs.right $ assume d hd, hc $ or.inl hd) (ht.right $ assume d hd, hc $ or.inr hd)⟩ /-- If `a` is the greatest lower bound of `s` and `b` is the greatest lower bound of `t`, then `a ⊓ b` is the greatest lower bound of `s ∪ t`. -/ lemma is_glb.union [semilattice_inf γ] {a₁ a₂ : γ} {s t : set γ} (hs : is_glb s a₁) (ht : is_glb t a₂) : is_glb (s ∪ t) (a₁ ⊓ a₂) := @is_lub.union (order_dual γ) _ _ _ _ _ hs ht /-- If `a` is the least element of `s` and `b` is the least element of `t`, then `min a b` is the least element of `s ∪ t`. -/ lemma is_least.union [linear_order γ] {a b : γ} {s t : set γ} (ha : is_least s a) (hb : is_least t b) : is_least (s ∪ t) (min a b) := ⟨by cases (le_total a b) with h h; simp [h, ha.1, hb.1], (ha.is_glb.union hb.is_glb).1⟩ /-- If `a` is the greatest element of `s` and `b` is the greatest element of `t`, then `max a b` is the greatest element of `s ∪ t`. -/ lemma is_greatest.union [linear_order γ] {a b : γ} {s t : set γ} (ha : is_greatest s a) (hb : is_greatest t b) : is_greatest (s ∪ t) (max a b) := ⟨by cases (le_total a b) with h h; simp [h, ha.1, hb.1], (ha.is_lub.union hb.is_lub).1⟩ /-! ### Specific sets #### Unbounded intervals -/ lemma is_least_Ici : is_least (Ici a) a := ⟨left_mem_Ici, λ x, id⟩ lemma is_greatest_Iic : is_greatest (Iic a) a := ⟨right_mem_Iic, λ x, id⟩ lemma is_lub_Iic : is_lub (Iic a) a := is_greatest_Iic.is_lub lemma is_glb_Ici : is_glb (Ici a) a := is_least_Ici.is_glb lemma upper_bounds_Iic : upper_bounds (Iic a) = Ici a := is_lub_Iic.upper_bounds_eq lemma lower_bounds_Ici : lower_bounds (Ici a) = Iic a := is_glb_Ici.lower_bounds_eq lemma bdd_above_Iic : bdd_above (Iic a) := is_lub_Iic.bdd_above lemma bdd_below_Ici : bdd_below (Ici a) := is_glb_Ici.bdd_below lemma bdd_above_Iio : bdd_above (Iio a) := ⟨a, λ x hx, le_of_lt hx⟩ lemma bdd_below_Ioi : bdd_below (Ioi a) := ⟨a, λ x hx, le_of_lt hx⟩ section variables [linear_order γ] [densely_ordered γ] lemma is_lub_Iio {a : γ} : is_lub (Iio a) a := ⟨λ x hx, le_of_lt hx, λ y hy, le_of_forall_ge_of_dense hy⟩ lemma is_glb_Ioi {a : γ} : is_glb (Ioi a) a := @is_lub_Iio (order_dual γ) _ _ a lemma upper_bounds_Iio {a : γ} : upper_bounds (Iio a) = Ici a := is_lub_Iio.upper_bounds_eq lemma lower_bounds_Ioi {a : γ} : lower_bounds (Ioi a) = Iic a := is_glb_Ioi.lower_bounds_eq end /-! #### Singleton -/ lemma is_greatest_singleton : is_greatest {a} a := ⟨mem_singleton a, λ x hx, le_of_eq $ eq_of_mem_singleton hx⟩ lemma is_least_singleton : is_least {a} a := @is_greatest_singleton (order_dual α) _ a lemma is_lub_singleton : is_lub {a} a := is_greatest_singleton.is_lub lemma is_glb_singleton : is_glb {a} a := is_least_singleton.is_glb lemma bdd_above_singleton : bdd_above ({a} : set α) := is_lub_singleton.bdd_above lemma bdd_below_singleton : bdd_below ({a} : set α) := is_glb_singleton.bdd_below @[simp] lemma upper_bounds_singleton : upper_bounds {a} = Ici a := is_lub_singleton.upper_bounds_eq @[simp] lemma lower_bounds_singleton : lower_bounds {a} = Iic a := is_glb_singleton.lower_bounds_eq /-! #### Bounded intervals -/ lemma bdd_above_Icc : bdd_above (Icc a b) := ⟨b, λ _, and.right⟩ lemma bdd_below_Icc : bdd_below (Icc a b) := ⟨a, λ _, and.left⟩ lemma bdd_above_Ico : bdd_above (Ico a b) := bdd_above_Icc.mono Ico_subset_Icc_self lemma bdd_below_Ico : bdd_below (Ico a b) := bdd_below_Icc.mono Ico_subset_Icc_self lemma bdd_above_Ioc : bdd_above (Ioc a b) := bdd_above_Icc.mono Ioc_subset_Icc_self lemma bdd_below_Ioc : bdd_below (Ioc a b) := bdd_below_Icc.mono Ioc_subset_Icc_self lemma bdd_above_Ioo : bdd_above (Ioo a b) := bdd_above_Icc.mono Ioo_subset_Icc_self lemma bdd_below_Ioo : bdd_below (Ioo a b) := bdd_below_Icc.mono Ioo_subset_Icc_self lemma is_greatest_Icc (h : a ≤ b) : is_greatest (Icc a b) b := ⟨right_mem_Icc.2 h, λ x, and.right⟩ lemma is_lub_Icc (h : a ≤ b) : is_lub (Icc a b) b := (is_greatest_Icc h).is_lub lemma upper_bounds_Icc (h : a ≤ b) : upper_bounds (Icc a b) = Ici b := (is_lub_Icc h).upper_bounds_eq lemma is_least_Icc (h : a ≤ b) : is_least (Icc a b) a := ⟨left_mem_Icc.2 h, λ x, and.left⟩ lemma is_glb_Icc (h : a ≤ b) : is_glb (Icc a b) a := (is_least_Icc h).is_glb lemma lower_bounds_Icc (h : a ≤ b) : lower_bounds (Icc a b) = Iic a := (is_glb_Icc h).lower_bounds_eq lemma is_greatest_Ioc (h : a < b) : is_greatest (Ioc a b) b := ⟨right_mem_Ioc.2 h, λ x, and.right⟩ lemma is_lub_Ioc (h : a < b) : is_lub (Ioc a b) b := (is_greatest_Ioc h).is_lub lemma upper_bounds_Ioc (h : a < b) : upper_bounds (Ioc a b) = Ici b := (is_lub_Ioc h).upper_bounds_eq lemma is_least_Ico (h : a < b) : is_least (Ico a b) a := ⟨left_mem_Ico.2 h, λ x, and.left⟩ lemma is_glb_Ico (h : a < b) : is_glb (Ico a b) a := (is_least_Ico h).is_glb lemma lower_bounds_Ico (h : a < b) : lower_bounds (Ico a b) = Iic a := (is_glb_Ico h).lower_bounds_eq section variables [linear_order γ] [densely_ordered γ] lemma is_glb_Ioo {a b : γ} (hab : a < b) : is_glb (Ioo a b) a := begin refine ⟨λx hx, le_of_lt hx.1, λy hy, le_of_not_lt $ λ h, _⟩, have : a < min b y, by { rw lt_min_iff, exact ⟨hab, h⟩ }, rcases exists_between this with ⟨z, az, zy⟩, rw lt_min_iff at zy, exact lt_irrefl _ (lt_of_le_of_lt (hy ⟨az, zy.1⟩) zy.2) end lemma lower_bounds_Ioo {a b : γ} (hab : a < b) : lower_bounds (Ioo a b) = Iic a := (is_glb_Ioo hab).lower_bounds_eq lemma is_glb_Ioc {a b : γ} (hab : a < b) : is_glb (Ioc a b) a := (is_glb_Ioo hab).of_subset_of_superset (is_glb_Icc $ le_of_lt hab) Ioo_subset_Ioc_self Ioc_subset_Icc_self lemma lower_bound_Ioc {a b : γ} (hab : a < b) : lower_bounds (Ioc a b) = Iic a := (is_glb_Ioc hab).lower_bounds_eq lemma is_lub_Ioo {a b : γ} (hab : a < b) : is_lub (Ioo a b) b := by simpa only [dual_Ioo] using @is_glb_Ioo (order_dual γ) _ _ b a hab lemma upper_bounds_Ioo {a b : γ} (hab : a < b) : upper_bounds (Ioo a b) = Ici b := (is_lub_Ioo hab).upper_bounds_eq lemma is_lub_Ico {a b : γ} (hab : a < b) : is_lub (Ico a b) b := by simpa only [dual_Ioc] using @is_glb_Ioc (order_dual γ) _ _ b a hab lemma upper_bounds_Ico {a b : γ} (hab : a < b) : upper_bounds (Ico a b) = Ici b := (is_lub_Ico hab).upper_bounds_eq end lemma bdd_below_iff_subset_Ici : bdd_below s ↔ ∃ a, s ⊆ Ici a := iff.rfl lemma bdd_above_iff_subset_Iic : bdd_above s ↔ ∃ a, s ⊆ Iic a := iff.rfl lemma bdd_below_bdd_above_iff_subset_Icc : bdd_below s ∧ bdd_above s ↔ ∃ a b, s ⊆ Icc a b := by simp only [Ici_inter_Iic.symm, subset_inter_iff, bdd_below_iff_subset_Ici, bdd_above_iff_subset_Iic, exists_and_distrib_left, exists_and_distrib_right] /-! ### Univ -/ lemma order_top.upper_bounds_univ [order_top γ] : upper_bounds (univ : set γ) = {⊤} := set.ext $ λ b, iff.trans ⟨λ hb, top_unique $ hb trivial, λ hb x hx, hb.symm ▸ le_top⟩ mem_singleton_iff.symm lemma is_greatest_univ [order_top γ] : is_greatest (univ : set γ) ⊤ := by simp only [is_greatest, order_top.upper_bounds_univ, mem_univ, mem_singleton, true_and] lemma is_lub_univ [order_top γ] : is_lub (univ : set γ) ⊤ := is_greatest_univ.is_lub lemma order_bot.lower_bounds_univ [order_bot γ] : lower_bounds (univ : set γ) = {⊥} := @order_top.upper_bounds_univ (order_dual γ) _ lemma is_least_univ [order_bot γ] : is_least (univ : set γ) ⊥ := @is_greatest_univ (order_dual γ) _ lemma is_glb_univ [order_bot γ] : is_glb (univ : set γ) ⊥ := is_least_univ.is_glb lemma no_top_order.upper_bounds_univ [no_top_order α] : upper_bounds (univ : set α) = ∅ := eq_empty_of_subset_empty $ λ b hb, let ⟨x, hx⟩ := no_top b in not_le_of_lt hx (hb trivial) lemma no_bot_order.lower_bounds_univ [no_bot_order α] : lower_bounds (univ : set α) = ∅ := @no_top_order.upper_bounds_univ (order_dual α) _ _ /-! ### Empty set -/ @[simp] lemma upper_bounds_empty : upper_bounds (∅ : set α) = univ := by simp only [upper_bounds, eq_univ_iff_forall, mem_set_of_eq, ball_empty_iff, forall_true_iff] @[simp] lemma lower_bounds_empty : lower_bounds (∅ : set α) = univ := @upper_bounds_empty (order_dual α) _ @[simp] lemma bdd_above_empty [nonempty α] : bdd_above (∅ : set α) := by simp only [bdd_above, upper_bounds_empty, univ_nonempty] @[simp] lemma bdd_below_empty [nonempty α] : bdd_below (∅ : set α) := by simp only [bdd_below, lower_bounds_empty, univ_nonempty] lemma is_glb_empty [order_top γ] : is_glb ∅ (⊤:γ) := by simp only [is_glb, lower_bounds_empty, is_greatest_univ] lemma is_lub_empty [order_bot γ] : is_lub ∅ (⊥:γ) := @is_glb_empty (order_dual γ) _ lemma is_lub.nonempty [no_bot_order α] (hs : is_lub s a) : s.nonempty := let ⟨a', ha'⟩ := no_bot a in ne_empty_iff_nonempty.1 $ assume h, have a ≤ a', from hs.right $ by simp only [h, upper_bounds_empty], not_le_of_lt ha' this lemma is_glb.nonempty [no_top_order α] (hs : is_glb s a) : s.nonempty := @is_lub.nonempty (order_dual α) _ _ _ _ hs lemma nonempty_of_not_bdd_above [ha : nonempty α] (h : ¬bdd_above s) : s.nonempty := nonempty.elim ha $ λ x, (not_bdd_above_iff'.1 h x).imp $ λ a ha, ha.fst lemma nonempty_of_not_bdd_below [ha : nonempty α] (h : ¬bdd_below s) : s.nonempty := @nonempty_of_not_bdd_above (order_dual α) _ _ _ h /-! ### insert -/ /-- Adding a point to a set preserves its boundedness above. -/ @[simp] lemma bdd_above_insert [semilattice_sup γ] (a : γ) {s : set γ} : bdd_above (insert a s) ↔ bdd_above s := by simp only [insert_eq, bdd_above_union, bdd_above_singleton, true_and] lemma bdd_above.insert [semilattice_sup γ] (a : γ) {s : set γ} (hs : bdd_above s) : bdd_above (insert a s) := (bdd_above_insert a).2 hs /--Adding a point to a set preserves its boundedness below.-/ @[simp] lemma bdd_below_insert [semilattice_inf γ] (a : γ) {s : set γ} : bdd_below (insert a s) ↔ bdd_below s := by simp only [insert_eq, bdd_below_union, bdd_below_singleton, true_and] lemma bdd_below.insert [semilattice_inf γ] (a : γ) {s : set γ} (hs : bdd_below s) : bdd_below (insert a s) := (bdd_below_insert a).2 hs lemma is_lub.insert [semilattice_sup γ] (a) {b} {s : set γ} (hs : is_lub s b) : is_lub (insert a s) (a ⊔ b) := by { rw insert_eq, exact is_lub_singleton.union hs } lemma is_glb.insert [semilattice_inf γ] (a) {b} {s : set γ} (hs : is_glb s b) : is_glb (insert a s) (a ⊓ b) := by { rw insert_eq, exact is_glb_singleton.union hs } lemma is_greatest.insert [linear_order γ] (a) {b} {s : set γ} (hs : is_greatest s b) : is_greatest (insert a s) (max a b) := by { rw insert_eq, exact is_greatest_singleton.union hs } lemma is_least.insert [linear_order γ] (a) {b} {s : set γ} (hs : is_least s b) : is_least (insert a s) (min a b) := by { rw insert_eq, exact is_least_singleton.union hs } @[simp] lemma upper_bounds_insert (a : α) (s : set α) : upper_bounds (insert a s) = Ici a ∩ upper_bounds s := by rw [insert_eq, upper_bounds_union, upper_bounds_singleton] @[simp] lemma lower_bounds_insert (a : α) (s : set α) : lower_bounds (insert a s) = Iic a ∩ lower_bounds s := by rw [insert_eq, lower_bounds_union, lower_bounds_singleton] /-- When there is a global maximum, every set is bounded above. -/ @[simp] protected lemma order_top.bdd_above [order_top γ] (s : set γ) : bdd_above s := ⟨⊤, assume a ha, order_top.le_top a⟩ /-- When there is a global minimum, every set is bounded below. -/ @[simp] protected lemma order_bot.bdd_below [order_bot γ] (s : set γ) : bdd_below s := ⟨⊥, assume a ha, order_bot.bot_le a⟩ /-! ### Pair -/ lemma is_lub_pair [semilattice_sup γ] {a b : γ} : is_lub {a, b} (a ⊔ b) := is_lub_singleton.insert _ lemma is_glb_pair [semilattice_inf γ] {a b : γ} : is_glb {a, b} (a ⊓ b) := is_glb_singleton.insert _ lemma is_least_pair [linear_order γ] {a b : γ} : is_least {a, b} (min a b) := is_least_singleton.insert _ lemma is_greatest_pair [linear_order γ] {a b : γ} : is_greatest {a, b} (max a b) := is_greatest_singleton.insert _ end /-! ### (In)equalities with the least upper bound and the greatest lower bound -/ section preorder variables [preorder α] {s : set α} {a b : α} lemma lower_bounds_le_upper_bounds (ha : a ∈ lower_bounds s) (hb : b ∈ upper_bounds s) : s.nonempty → a ≤ b | ⟨c, hc⟩ := le_trans (ha hc) (hb hc) lemma is_glb_le_is_lub (ha : is_glb s a) (hb : is_lub s b) (hs : s.nonempty) : a ≤ b := lower_bounds_le_upper_bounds ha.1 hb.1 hs lemma is_lub_lt_iff (ha : is_lub s a) : a < b ↔ ∃ c ∈ upper_bounds s, c < b := ⟨λ hb, ⟨a, ha.1, hb⟩, λ ⟨c, hcs, hcb⟩, lt_of_le_of_lt (ha.2 hcs) hcb⟩ lemma lt_is_glb_iff (ha : is_glb s a) : b < a ↔ ∃ c ∈ lower_bounds s, b < c := @is_lub_lt_iff (order_dual α) _ s _ _ ha end preorder section partial_order variables [partial_order α] {s : set α} {a b : α} lemma is_least.unique (Ha : is_least s a) (Hb : is_least s b) : a = b := le_antisymm (Ha.right Hb.left) (Hb.right Ha.left) lemma is_least.is_least_iff_eq (Ha : is_least s a) : is_least s b ↔ a = b := iff.intro Ha.unique (assume h, h ▸ Ha) lemma is_greatest.unique (Ha : is_greatest s a) (Hb : is_greatest s b) : a = b := le_antisymm (Hb.right Ha.left) (Ha.right Hb.left) lemma is_greatest.is_greatest_iff_eq (Ha : is_greatest s a) : is_greatest s b ↔ a = b := iff.intro Ha.unique (assume h, h ▸ Ha) lemma is_lub.unique (Ha : is_lub s a) (Hb : is_lub s b) : a = b := Ha.unique Hb lemma is_glb.unique (Ha : is_glb s a) (Hb : is_glb s b) : a = b := Ha.unique Hb end partial_order section linear_order variables [linear_order α] {s : set α} {a b : α} lemma lt_is_lub_iff (h : is_lub s a) : b < a ↔ ∃ c ∈ s, b < c := by haveI := classical.dec; simpa [upper_bounds, not_ball] using not_congr (@is_lub_le_iff _ _ _ _ b h) lemma is_glb_lt_iff (h : is_glb s a) : a < b ↔ ∃ c ∈ s, c < b := @lt_is_lub_iff (order_dual α) _ _ _ _ h end linear_order /-! ### Least upper bound and the greatest lower bound in linear ordered additive commutative groups -/ section linear_ordered_add_comm_group variables [linear_ordered_add_comm_group α] {s : set α} {a ε : α} (h₃ : 0 < ε) include h₃ lemma is_glb.exists_between_self_add (h₁ : is_glb s a) : ∃ b, b ∈ s ∧ a ≤ b ∧ b < a + ε := begin have h' : a + ε ∉ lower_bounds s, { set A := a + ε, have : a < A := by { simp [A, h₃] }, intros hA, exact lt_irrefl a (lt_of_lt_of_le this (h₁.2 hA)) }, obtain ⟨b, hb, hb'⟩ : ∃ b ∈ s, b < a + ε, by simpa [lower_bounds] using h', exact ⟨b, hb, h₁.1 hb, hb'⟩ end lemma is_glb.exists_between_self_add' (h₁ : is_glb s a) (h₂ : a ∉ s) : ∃ b, b ∈ s ∧ a < b ∧ b < a + ε := begin rcases h₁.exists_between_self_add h₃ with ⟨b, b_in, hb₁, hb₂⟩, have h₅ : a ≠ b, { intros contra, apply h₂, rwa ← contra at b_in }, exact ⟨b, b_in, lt_of_le_of_ne (h₁.1 b_in) h₅, hb₂⟩ end lemma is_lub.exists_between_sub_self (h₁ : is_lub s a) : ∃ b, b ∈ s ∧ a - ε < b ∧ b ≤ a := begin have h' : a - ε ∉ upper_bounds s, { set A := a - ε, have : A < a := sub_lt_self a h₃, intros hA, exact lt_irrefl a (lt_of_le_of_lt (h₁.2 hA) this) }, obtain ⟨b, hb, hb'⟩ : ∃ (x : α), x ∈ s ∧ a - ε < x, by simpa [upper_bounds] using h', exact ⟨b, hb, hb', h₁.1 hb⟩ end lemma is_lub.exists_between_sub_self' (h₁ : is_lub s a) (h₂ : a ∉ s) : ∃ b, b ∈ s ∧ a - ε < b ∧ b < a := begin rcases h₁.exists_between_sub_self h₃ with ⟨b, b_in, hb₁, hb₂⟩, have h₅ : a ≠ b, { intros contra, apply h₂, rwa ← contra at b_in }, exact ⟨b, b_in, hb₁, lt_of_le_of_ne (h₁.1 b_in) h₅.symm⟩ end end linear_ordered_add_comm_group /-! ### Images of upper/lower bounds under monotone functions -/ namespace monotone variables [preorder α] [preorder β] {f : α → β} (Hf : monotone f) {a : α} {s : set α} lemma mem_upper_bounds_image (Ha : a ∈ upper_bounds s) : f a ∈ upper_bounds (f '' s) := ball_image_of_ball (assume x H, Hf (Ha ‹x ∈ s›)) lemma mem_lower_bounds_image (Ha : a ∈ lower_bounds s) : f a ∈ lower_bounds (f '' s) := ball_image_of_ball (assume x H, Hf (Ha ‹x ∈ s›)) /-- The image under a monotone function of a set which is bounded above is bounded above. -/ lemma map_bdd_above (hf : monotone f) : bdd_above s → bdd_above (f '' s) | ⟨C, hC⟩ := ⟨f C, hf.mem_upper_bounds_image hC⟩ /-- The image under a monotone function of a set which is bounded below is bounded below. -/ lemma map_bdd_below (hf : monotone f) : bdd_below s → bdd_below (f '' s) | ⟨C, hC⟩ := ⟨f C, hf.mem_lower_bounds_image hC⟩ /-- A monotone map sends a least element of a set to a least element of its image. -/ lemma map_is_least (Ha : is_least s a) : is_least (f '' s) (f a) := ⟨mem_image_of_mem _ Ha.1, Hf.mem_lower_bounds_image Ha.2⟩ /-- A monotone map sends a greatest element of a set to a greatest element of its image. -/ lemma map_is_greatest (Ha : is_greatest s a) : is_greatest (f '' s) (f a) := ⟨mem_image_of_mem _ Ha.1, Hf.mem_upper_bounds_image Ha.2⟩ lemma is_lub_image_le (Ha : is_lub s a) {b : β} (Hb : is_lub (f '' s) b) : b ≤ f a := Hb.2 (Hf.mem_upper_bounds_image Ha.1) lemma le_is_glb_image (Ha : is_glb s a) {b : β} (Hb : is_glb (f '' s) b) : f a ≤ b := Hb.2 (Hf.mem_lower_bounds_image Ha.1) end monotone lemma is_glb.of_image [preorder α] [preorder β] {f : α → β} (hf : ∀ {x y}, f x ≤ f y ↔ x ≤ y) {s : set α} {x : α} (hx : is_glb (f '' s) (f x)) : is_glb s x := ⟨λ y hy, hf.1 $ hx.1 $ mem_image_of_mem _ hy, λ y hy, hf.1 $ hx.2 $ monotone.mem_lower_bounds_image (λ x y, hf.2) hy⟩ lemma is_lub.of_image [preorder α] [preorder β] {f : α → β} (hf : ∀ {x y}, f x ≤ f y ↔ x ≤ y) {s : set α} {x : α} (hx : is_lub (f '' s) (f x)) : is_lub s x := @is_glb.of_image (order_dual α) (order_dual β) _ _ f (λ x y, hf) _ _ hx
560b2b44f95994e1397821f7280b5849e2fbb123
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/lcnf2.lean
d0846b5c2407bf9734cdf51fde51167aefff3acb
[ "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
678
lean
import Lean open Lean def f (x : Nat) : Nat := let y := match x with | 0 => 1 | x + 1 => 2 * x match y with | 0 => 2 | z+1 => z + y + 2 set_option trace.Compiler true def g (x : Nat) : Bool := let pred? := match x with | 0 => none | y+1 => some y match pred? with | none => true | some _ => false abbrev TupleNTyp : Nat → Type 1 | 0 => Type | n + 1 => Type → (TupleNTyp n) noncomputable abbrev TupleN : (n : Fin 1) → TupleNTyp n.val | 0 => Unit × Unit set_option pp.proofs true #eval Compiler.compile #[``TupleN] def userControlled (a b : Nat) := let f := fun _ => a f () + b #eval Compiler.compile #[``userControlled]
9ea427d64e2ab0e4b330f27bb9a7cf4bc989940f
217bb195841a8be2d1b4edd2084d6b69ccd62f50
/library/init/lean/format.lean
bda986c33c9c297f3d612c548d0c388d651866ed
[ "Apache-2.0" ]
permissive
frank-lesser/lean4
717f56c9bacd5bf3a67542d2f5cea721d4743a30
79e2abe33f73162f773ea731265e456dbfe822f9
refs/heads/master
1,589,741,267,933
1,556,424,200,000
1,556,424,281,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,980
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 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 instance : HasAppend Format := ⟨compose false⟩ instance : HasCoe String Format := ⟨text⟩ instance : Inhabited Format := ⟨nil⟩ def join (xs : List Format) : Format := xs.foldl (++) "" 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₂) 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 in if y.exceeded || y.found then y else let newSpace := r₁.space + y.space in { 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) in 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" } def pretty (f : Format) (o : Options := {}) : String := let w := getWidth o in be w 0 "" [(0, f)] end Format open Lean.Format class HasToFormat (α : Type u) := (toFormat : α → Format) export Lean.HasToFormat (toFormat) def toFmt {α : Type u} [HasToFormat α] : α → Format := toFormat instance toStringToFormat {α : Type u} [HasToString α] : HasToFormat α := ⟨text ∘ toString⟩ -- note: must take precendence over the above instance to avoid premature formatting instance formatHasToFormat : HasToFormat Format := ⟨id⟩ instance stringHasToFormat : HasToFormat String := ⟨Format.text⟩ def Format.joinSep {α : Type u} [HasToFormat α] : List α → Format → Format | [] sep := nil | [a] sep := toFmt a | (a::as) sep := toFmt a ++ sep ++ Format.joinSep as sep def Format.prefixJoin {α : Type u} [HasToFormat α] (pre : Format) : List α → Format | [] := nil | (a::as) := pre ++ toFmt a ++ Format.prefixJoin as def Format.joinSuffix {α : Type u} [HasToFormat α] : List α → Format → Format | [] suffix := nil | (a::as) suffix := toFmt a ++ suffix ++ Format.joinSuffix as suffix def List.toFormat {α : Type u} [HasToFormat α] : List α → Format | [] := "[]" | xs := sbracket $ Format.joinSep xs ("," ++ line) instance listHasToFormat {α : Type u} [HasToFormat α] : HasToFormat (List α) := ⟨List.toFormat⟩ instance prodHasToFormat {α : Type u} {β : Type v} [HasToFormat α] [HasToFormat β] : HasToFormat (Prod α β) := ⟨λ ⟨a, b⟩, paren $ toFormat a ++ "," ++ line ++ toFormat b⟩ instance natHasToFormat : HasToFormat Nat := ⟨λ n, toString n⟩ instance uint16HasToFormat : HasToFormat UInt16 := ⟨λ n, toString n⟩ instance uint32HasToFormat : HasToFormat UInt32 := ⟨λ n, toString n⟩ instance uint64HasToFormat : HasToFormat UInt64 := ⟨λ n, toString n⟩ instance usizeHasToFormat : HasToFormat USize := ⟨λ n, toString n⟩ instance nameHasToFormat : HasToFormat Name := ⟨λ 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) := toFormat (repr v) | (DataValue.ofBool v) := toFormat v | (DataValue.ofName v) := "`" ++ toFormat v | (DataValue.ofNat v) := toFormat v | (DataValue.ofInt v) := toFormat v instance dataValueHasToFormat : HasToFormat DataValue := ⟨formatDataValue⟩ def formatEntry : Name × DataValue → Format | (n, v) := toFormat n ++ " := " ++ toFormat v instance entryHasToFormat : HasToFormat (Name × DataValue) := ⟨formatEntry⟩ def formatKVMap (m : KVMap) : Format := sbracket (Format.joinSep m.entries ", ") instance kvMapHasToFormat : HasToFormat KVMap := ⟨formatKVMap⟩ end Lean
c36afc27d39a9d675c470fcbff800408c94d71f3
1dd482be3f611941db7801003235dc84147ec60a
/src/order/basic.lean
46c7462d34b2e8ed5f79ae52efca97bfd9fb47fb
[ "Apache-2.0" ]
permissive
sanderdahmen/mathlib
479039302bd66434bb5672c2a4cecf8d69981458
8f0eae75cd2d8b7a083cf935666fcce4565df076
refs/heads/master
1,587,491,322,775
1,549,672,060,000
1,549,672,060,000
169,748,224
0
0
Apache-2.0
1,549,636,694,000
1,549,636,694,000
null
UTF-8
Lean
false
false
22,113
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Mario Carneiro -/ import tactic.interactive logic.basic data.sum data.set.basic algebra.order open function /- TODO: automatic construction of dual definitions / theorems -/ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} {r : α → α → Prop} theorem ge_of_eq [preorder α] {a b : α} : a = b → a ≥ b := λ h, h ▸ le_refl a theorem is_refl.swap (r) [is_refl α r] : is_refl α (swap r) := ⟨refl_of r⟩ theorem is_irrefl.swap (r) [is_irrefl α r] : is_irrefl α (swap r) := ⟨irrefl_of r⟩ theorem is_trans.swap (r) [is_trans α r] : is_trans α (swap r) := ⟨λ a b c h₁ h₂, trans_of r h₂ h₁⟩ theorem is_antisymm.swap (r) [is_antisymm α r] : is_antisymm α (swap r) := ⟨λ a b h₁ h₂, antisymm h₂ h₁⟩ theorem is_asymm.swap (r) [is_asymm α r] : is_asymm α (swap r) := ⟨λ a b h₁ h₂, asymm_of r h₂ h₁⟩ theorem is_total.swap (r) [is_total α r] : is_total α (swap r) := ⟨λ a b, (total_of r a b).swap⟩ theorem is_trichotomous.swap (r) [is_trichotomous α r] : is_trichotomous α (swap r) := ⟨λ a b, by simpa [swap, or.comm, or.left_comm] using trichotomous_of r a b⟩ theorem is_preorder.swap (r) [is_preorder α r] : is_preorder α (swap r) := {..@is_refl.swap α r _, ..@is_trans.swap α r _} theorem is_strict_order.swap (r) [is_strict_order α r] : is_strict_order α (swap r) := {..@is_irrefl.swap α r _, ..@is_trans.swap α r _} theorem is_partial_order.swap (r) [is_partial_order α r] : is_partial_order α (swap r) := {..@is_preorder.swap α r _, ..@is_antisymm.swap α r _} theorem is_total_preorder.swap (r) [is_total_preorder α r] : is_total_preorder α (swap r) := {..@is_preorder.swap α r _, ..@is_total.swap α r _} theorem is_linear_order.swap (r) [is_linear_order α r] : is_linear_order α (swap r) := {..@is_partial_order.swap α r _, ..@is_total.swap α r _} def antisymm_of_asymm (r) [is_asymm α r] : is_antisymm α r := ⟨λ x y h₁ h₂, (asymm h₁ h₂).elim⟩ /- Convert algebraic structure style to explicit relation style typeclasses -/ instance [preorder α] : is_refl α (≤) := ⟨le_refl⟩ instance [preorder α] : is_refl α (≥) := is_refl.swap _ instance [preorder α] : is_trans α (≤) := ⟨@le_trans _ _⟩ instance [preorder α] : is_trans α (≥) := is_trans.swap _ instance [preorder α] : is_preorder α (≤) := {} instance [preorder α] : is_preorder α (≥) := {} instance [preorder α] : is_irrefl α (<) := ⟨lt_irrefl⟩ instance [preorder α] : is_irrefl α (>) := is_irrefl.swap _ instance [preorder α] : is_trans α (<) := ⟨@lt_trans _ _⟩ instance [preorder α] : is_trans α (>) := is_trans.swap _ instance [preorder α] : is_asymm α (<) := ⟨@lt_asymm _ _⟩ instance [preorder α] : is_asymm α (>) := is_asymm.swap _ instance [preorder α] : is_antisymm α (<) := antisymm_of_asymm _ instance [preorder α] : is_antisymm α (>) := antisymm_of_asymm _ instance [preorder α] : is_strict_order α (<) := {} instance [preorder α] : is_strict_order α (>) := {} instance preorder.is_total_preorder [preorder α] [is_total α (≤)] : is_total_preorder α (≤) := {} instance [partial_order α] : is_antisymm α (≤) := ⟨@le_antisymm _ _⟩ instance [partial_order α] : is_antisymm α (≥) := is_antisymm.swap _ instance [partial_order α] : is_partial_order α (≤) := {} instance [partial_order α] : is_partial_order α (≥) := {} instance [linear_order α] : is_total α (≤) := ⟨le_total⟩ instance [linear_order α] : is_total α (≥) := is_total.swap _ instance linear_order.is_total_preorder [linear_order α] : is_total_preorder α (≤) := by apply_instance instance [linear_order α] : is_total_preorder α (≥) := {} instance [linear_order α] : is_linear_order α (≤) := {} instance [linear_order α] : is_linear_order α (≥) := {} instance [linear_order α] : is_trichotomous α (<) := ⟨lt_trichotomy⟩ instance [linear_order α] : is_trichotomous α (>) := is_trichotomous.swap _ theorem preorder.ext {α} {A B : preorder α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin resetI, cases A, cases B, congr, { funext x y, exact propext (H x y) }, { funext x y, dsimp [(≤)] at A_lt_iff_le_not_le B_lt_iff_le_not_le H, simp [A_lt_iff_le_not_le, B_lt_iff_le_not_le, H] }, end theorem partial_order.ext {α} {A B : partial_order α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := by haveI this := preorder.ext H; cases A; cases B; injection this; congr' theorem linear_order.ext {α} {A B : linear_order α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := by haveI this := partial_order.ext H; cases A; cases B; injection this; congr' /-- Given an order `R` on `β` and a function `f : α → β`, the preimage order on `α` is defined by `x ≤ y ↔ f x ≤ f y`. It is the unique order on `α` making `f` an order embedding (assuming `f` is injective). -/ @[simp] def order.preimage {α β} (f : α → β) (s : β → β → Prop) (x y : α) := s (f x) (f y) infix ` ⁻¹'o `:80 := order.preimage section monotone variables [preorder α] [preorder β] [preorder γ] /-- A function between preorders is monotone if `a ≤ b` implies `f a ≤ f b`. -/ def monotone (f : α → β) := ∀⦃a b⦄, a ≤ b → f a ≤ f b theorem monotone_id : @monotone α α _ _ id := assume x y h, h theorem monotone_const {b : β} : monotone (λ(a:α), b) := assume x y h, le_refl b theorem monotone_comp {f : α → β} {g : β → γ} (m_f : monotone f) (m_g : monotone g) : monotone (g ∘ f) := assume a b h, m_g (m_f h) lemma monotone_of_monotone_nat {f : ℕ → α} (hf : ∀n, f n ≤ f (n + 1)) : monotone f | n m h := begin induction h, { refl }, { transitivity, assumption, exact hf _ } end end monotone def order_dual (α : Type*) := α namespace order_dual instance (α : Type*) [has_le α] : has_le (order_dual α) := ⟨λx y:α, y ≤ x⟩ instance (α : Type*) [preorder α] : preorder (order_dual α) := { le_refl := le_refl, le_trans := assume a b c hab hbc, le_trans hbc hab, .. order_dual.has_le α } instance (α : Type*) [partial_order α] : partial_order (order_dual α) := { le_antisymm := assume a b hab hba, @le_antisymm α _ a b hba hab, .. order_dual.preorder α } instance (α : Type*) [linear_order α] : linear_order (order_dual α) := { le_total := assume a b:α, le_total b a, .. order_dual.partial_order α } instance (α : Type*) [decidable_linear_order α] : decidable_linear_order (order_dual α) := { decidable_le := show decidable_rel (λa b:α, b ≤ a), by apply_instance, .. order_dual.linear_order α } end order_dual /- order instances on the function space -/ instance pi.preorder {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] : preorder (Πi, α i) := { le := λx y, ∀i, x i ≤ y i, le_refl := assume a i, le_refl (a i), le_trans := assume a b c h₁ h₂ i, le_trans (h₁ i) (h₂ i) } instance pi.partial_order {ι : Type u} {α : ι → Type v} [∀i, partial_order (α i)] : partial_order (Πi, α i) := { le_antisymm := λf g h1 h2, funext (λb, le_antisymm (h1 b) (h2 b)), ..pi.preorder } theorem comp_le_comp_left_of_monotone [preorder α] [preorder β] [preorder γ] {f : β → α} {g h : γ → β} (m_f : monotone f) (le_gh : g ≤ h) : has_le.le.{max w u} (f ∘ g) (f ∘ h) := assume x, m_f (le_gh x) section monotone variables [preorder α] [preorder γ] theorem monotone_lam {f : α → β → γ} (m : ∀b, monotone (λa, f a b)) : monotone f := assume a a' h b, m b h theorem monotone_app (f : β → α → γ) (b : β) (m : monotone (λa b, f b a)) : monotone (f b) := assume a a' h, m h b end monotone def preorder.lift {α β} [preorder β] (f : α → β) : preorder α := { le := λx y, f x ≤ f y, le_refl := λ a, le_refl _, le_trans := λ a b c, le_trans, lt := λx y, f x < f y, lt_iff_le_not_le := λ a b, lt_iff_le_not_le } def partial_order.lift {α β} [partial_order β] (f : α → β) (inj : injective f) : partial_order α := { le_antisymm := λ a b h₁ h₂, inj (le_antisymm h₁ h₂), .. preorder.lift f } def linear_order.lift {α β} [linear_order β] (f : α → β) (inj : injective f) : linear_order α := { le_total := λx y, le_total (f x) (f y), .. partial_order.lift f inj } def decidable_linear_order.lift {α β} [decidable_linear_order β] (f : α → β) (inj : injective f) : decidable_linear_order α := { decidable_le := λ x y, show decidable (f x ≤ f y), by apply_instance, decidable_lt := λ x y, show decidable (f x < f y), by apply_instance, decidable_eq := λ x y, decidable_of_iff _ ⟨@inj x y, congr_arg f⟩, .. linear_order.lift f inj } instance subtype.preorder {α} [preorder α] (p : α → Prop) : preorder (subtype p) := preorder.lift subtype.val instance subtype.partial_order {α} [partial_order α] (p : α → Prop) : partial_order (subtype p) := partial_order.lift subtype.val $ λ x y, subtype.eq' instance subtype.linear_order {α} [linear_order α] (p : α → Prop) : linear_order (subtype p) := linear_order.lift subtype.val $ λ x y, subtype.eq' instance subtype.decidable_linear_order {α} [decidable_linear_order α] (p : α → Prop) : decidable_linear_order (subtype p) := decidable_linear_order.lift subtype.val $ λ x y, subtype.eq' instance prod.has_le (α : Type u) (β : Type v) [has_le α] [has_le β] : has_le (α × β) := ⟨λp q, p.1 ≤ q.1 ∧ p.2 ≤ q.2⟩ instance prod.preorder (α : Type u) (β : Type v) [preorder α] [preorder β] : preorder (α × β) := { le_refl := assume ⟨a, b⟩, ⟨le_refl a, le_refl b⟩, le_trans := assume ⟨a, b⟩ ⟨c, d⟩ ⟨e, f⟩ ⟨hac, hbd⟩ ⟨hce, hdf⟩, ⟨le_trans hac hce, le_trans hbd hdf⟩, .. prod.has_le α β } instance prod.partial_order (α : Type u) (β : Type v) [partial_order α] [partial_order β] : partial_order (α × β) := { le_antisymm := assume ⟨a, b⟩ ⟨c, d⟩ ⟨hac, hbd⟩ ⟨hca, hdb⟩, prod.ext (le_antisymm hac hca) (le_antisymm hbd hdb), .. prod.preorder α β } /- additional order classes -/ /-- order without a top element; somtimes called cofinal -/ class no_top_order (α : Type u) [preorder α] : Prop := (no_top : ∀a:α, ∃a', a < a') lemma no_top [preorder α] [no_top_order α] : ∀a:α, ∃a', a < a' := no_top_order.no_top /-- order without a bottom element; somtimes called coinitial or dense -/ class no_bot_order (α : Type u) [preorder α] : Prop := (no_bot : ∀a:α, ∃a', a' < a) lemma no_bot [preorder α] [no_bot_order α] : ∀a:α, ∃a', a' < a := no_bot_order.no_bot /-- An order is dense if there is an element between any pair of distinct elements. -/ class densely_ordered (α : Type u) [preorder α] : Prop := (dense : ∀a₁ a₂:α, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂) lemma dense [preorder α] [densely_ordered α] : ∀{a₁ a₂:α}, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂ := densely_ordered.dense lemma le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h : ∀a₃>a₂, a₁ ≤ a₃) : a₁ ≤ a₂ := le_of_not_gt $ assume ha, let ⟨a, ha₁, ha₂⟩ := dense ha in lt_irrefl a $ lt_of_lt_of_le ‹a < a₁› (h _ ‹a₂ < a›) lemma eq_of_le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h₁ : a₂ ≤ a₁) (h₂ : ∀a₃>a₂, a₁ ≤ a₃) : a₁ = a₂ := le_antisymm (le_of_forall_le_of_dense h₂) h₁ lemma le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α}(h : ∀a₃<a₁, a₂ ≥ a₃) : a₁ ≤ a₂ := le_of_not_gt $ assume ha, let ⟨a, ha₁, ha₂⟩ := dense ha in lt_irrefl a $ lt_of_le_of_lt (h _ ‹a < a₁›) ‹a₂ < a› lemma eq_of_le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h₁ : a₂ ≤ a₁) (h₂ : ∀a₃<a₁, a₂ ≥ a₃) : a₁ = a₂ := le_antisymm (le_of_forall_ge_of_dense h₂) h₁ lemma dense_or_discrete [linear_order α] {a₁ a₂ : α} (h : a₁ < a₂) : (∃a, a₁ < a ∧ a < a₂) ∨ ((∀a>a₁, a ≥ a₂) ∧ (∀a<a₂, a ≤ a₁)) := classical.or_iff_not_imp_left.2 $ assume h, ⟨assume a ha₁, le_of_not_gt $ assume ha₂, h ⟨a, ha₁, ha₂⟩, assume a ha₂, le_of_not_gt $ assume ha₁, h ⟨a, ha₁, ha₂⟩⟩ section variables {s : β → β → Prop} {t : γ → γ → Prop} theorem is_irrefl_of_is_asymm [is_asymm α r] : is_irrefl α r := ⟨λ a h, asymm h h⟩ /-- Construct a partial order from a `is_strict_order` relation -/ def partial_order_of_SO (r) [is_strict_order α r] : partial_order α := { le := λ x y, x = y ∨ r x y, lt := r, le_refl := λ x, or.inl rfl, le_trans := λ x y z h₁ h₂, match y, z, h₁, h₂ with | _, _, or.inl rfl, h₂ := h₂ | _, _, h₁, or.inl rfl := h₁ | _, _, or.inr h₁, or.inr h₂ := or.inr (trans h₁ h₂) end, le_antisymm := λ x y h₁ h₂, match y, h₁, h₂ with | _, or.inl rfl, h₂ := rfl | _, h₁, or.inl rfl := rfl | _, or.inr h₁, or.inr h₂ := (asymm h₁ h₂).elim end, lt_iff_le_not_le := λ x y, ⟨λ h, ⟨or.inr h, not_or (λ e, by rw e at h; exact irrefl _ h) (asymm h)⟩, λ ⟨h₁, h₂⟩, h₁.resolve_left (λ e, h₂ $ e ▸ or.inl rfl)⟩ } /-- This is basically the same as `is_strict_total_order`, but that definition is in Type (probably by mistake) and also has redundant assumptions. -/ @[algebra] class is_strict_total_order' (α : Type u) (lt : α → α → Prop) extends is_trichotomous α lt, is_strict_order α lt : Prop. /-- Construct a linear order from a `is_strict_total_order'` relation -/ def linear_order_of_STO' (r) [is_strict_total_order' α r] : linear_order α := { le_total := λ x y, match y, trichotomous_of r x y with | y, or.inl h := or.inl (or.inr h) | _, or.inr (or.inl rfl) := or.inl (or.inl rfl) | _, or.inr (or.inr h) := or.inr (or.inr h) end, ..partial_order_of_SO r } /-- Construct a decidable linear order from a `is_strict_total_order'` relation -/ def decidable_linear_order_of_STO' (r) [is_strict_total_order' α r] [decidable_rel r] : decidable_linear_order α := by letI LO := linear_order_of_STO' r; exact { decidable_le := λ x y, decidable_of_iff (¬ r y x) (@not_lt _ _ y x), ..LO } noncomputable def classical.DLO (α) [LO : linear_order α] : decidable_linear_order α := { decidable_le := classical.dec_rel _, ..LO } theorem is_strict_total_order'.swap (r) [is_strict_total_order' α r] : is_strict_total_order' α (swap r) := {..is_trichotomous.swap r, ..is_strict_order.swap r} instance [linear_order α] : is_strict_total_order' α (<) := {} /-- A connected order is one satisfying the condition `a < c → a < b ∨ b < c`. This is recognizable as an intuitionistic substitute for `a ≤ b ∨ b ≤ a` on the constructive reals, and is also known as negative transitivity, since the contrapositive asserts transitivity of the relation `¬ a < b`. -/ @[algebra] class is_order_connected (α : Type u) (lt : α → α → Prop) : Prop := (conn : ∀ a b c, lt a c → lt a b ∨ lt b c) theorem is_order_connected.neg_trans {r : α → α → Prop} [is_order_connected α r] {a b c} (h₁ : ¬ r a b) (h₂ : ¬ r b c) : ¬ r a c := mt (is_order_connected.conn a b c) $ by simp [h₁, h₂] theorem is_strict_weak_order_of_is_order_connected [is_asymm α r] [is_order_connected α r] : is_strict_weak_order α r := { trans := λ a b c h₁ h₂, (is_order_connected.conn _ c _ h₁).resolve_right (asymm h₂), incomp_trans := λ a b c ⟨h₁, h₂⟩ ⟨h₃, h₄⟩, ⟨is_order_connected.neg_trans h₁ h₃, is_order_connected.neg_trans h₄ h₂⟩, ..@is_irrefl_of_is_asymm α r _ } instance is_order_connected_of_is_strict_total_order' [is_strict_total_order' α r] : is_order_connected α r := ⟨λ a b c h, (trichotomous _ _).imp_right (λ o, o.elim (λ e, e ▸ h) (λ h', trans h' h))⟩ instance is_strict_total_order_of_is_strict_total_order' [is_strict_total_order' α r] : is_strict_total_order α r := {..is_strict_weak_order_of_is_order_connected} instance [linear_order α] : is_strict_total_order α (<) := by apply_instance instance [linear_order α] : is_order_connected α (<) := by apply_instance instance [linear_order α] : is_incomp_trans α (<) := by apply_instance instance [linear_order α] : is_strict_weak_order α (<) := by apply_instance /-- An extensional relation is one in which an element is determined by its set of predecessors. It is named for the `x ∈ y` relation in set theory, whose extensionality is one of the first axioms of ZFC. -/ @[algebra] class is_extensional (α : Type u) (r : α → α → Prop) : Prop := (ext : ∀ a b, (∀ x, r x a ↔ r x b) → a = b) instance is_extensional_of_is_strict_total_order' [is_strict_total_order' α r] : is_extensional α r := ⟨λ a b H, ((@trichotomous _ r _ a b) .resolve_left $ mt (H _).2 (irrefl a)) .resolve_right $ mt (H _).1 (irrefl b)⟩ /-- A well order is a well-founded linear order. -/ @[algebra] class is_well_order (α : Type u) (r : α → α → Prop) extends is_strict_total_order' α r : Prop := (wf : well_founded r) instance is_well_order.is_strict_total_order {α} (r : α → α → Prop) [is_well_order α r] : is_strict_total_order α r := by apply_instance instance is_well_order.is_extensional {α} (r : α → α → Prop) [is_well_order α r] : is_extensional α r := by apply_instance instance is_well_order.is_trichotomous {α} (r : α → α → Prop) [is_well_order α r] : is_trichotomous α r := by apply_instance instance is_well_order.is_trans {α} (r : α → α → Prop) [is_well_order α r] : is_trans α r := by apply_instance instance is_well_order.is_irrefl {α} (r : α → α → Prop) [is_well_order α r] : is_irrefl α r := by apply_instance instance is_well_order.is_asymm {α} (r : α → α → Prop) [is_well_order α r] : is_asymm α r := by apply_instance instance empty_relation.is_well_order [subsingleton α] : is_well_order α empty_relation := { trichotomous := λ a b, or.inr $ or.inl $ subsingleton.elim _ _, irrefl := λ a, id, trans := λ a b c, false.elim, wf := ⟨λ a, ⟨_, λ y, false.elim⟩⟩ } instance nat.lt.is_well_order : is_well_order ℕ (<) := ⟨nat.lt_wf⟩ instance sum.lex.is_well_order [is_well_order α r] [is_well_order β s] : is_well_order (α ⊕ β) (sum.lex r s) := { trichotomous := λ a b, by cases a; cases b; simp; apply trichotomous, irrefl := λ a, by cases a; simp; apply irrefl, trans := λ a b c, by cases a; cases b; simp; cases c; simp; apply trans, wf := sum.lex_wf (is_well_order.wf r) (is_well_order.wf s) } instance prod.lex.is_well_order [is_well_order α r] [is_well_order β s] : is_well_order (α × β) (prod.lex r s) := { trichotomous := λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩, match @trichotomous _ r _ a₁ b₁ with | or.inl h₁ := or.inl $ prod.lex.left _ _ _ h₁ | or.inr (or.inr h₁) := or.inr $ or.inr $ prod.lex.left _ _ _ h₁ | or.inr (or.inl e) := e ▸ match @trichotomous _ s _ a₂ b₂ with | or.inl h := or.inl $ prod.lex.right _ _ h | or.inr (or.inr h) := or.inr $ or.inr $ prod.lex.right _ _ h | or.inr (or.inl e) := e ▸ or.inr $ or.inl rfl end end, irrefl := λ ⟨a₁, a₂⟩ h, by cases h with _ _ _ _ h _ _ _ h; [exact irrefl _ h, exact irrefl _ h], trans := λ a b c h₁ h₂, begin cases h₁ with a₁ a₂ b₁ b₂ ab a₁ b₁ b₂ ab; cases h₂ with _ _ c₁ c₂ bc _ _ c₂ bc, { exact prod.lex.left _ _ _ (trans ab bc) }, { exact prod.lex.left _ _ _ ab }, { exact prod.lex.left _ _ _ bc }, { exact prod.lex.right _ _ (trans ab bc) } end, wf := prod.lex_wf (is_well_order.wf r) (is_well_order.wf s) } theorem well_founded.has_min {α} {r : α → α → Prop} (H : well_founded r) (p : set α) : p ≠ ∅ → ∃ a ∈ p, ∀ x ∈ p, ¬ r x a := by haveI := classical.prop_decidable; exact not_imp_comm.1 (λ he, set.eq_empty_iff_forall_not_mem.2 $ λ a, acc.rec_on (H.apply a) $ λ a H IH h, he ⟨_, h, λ y, imp_not_comm.1 (IH y)⟩) /-- The minimum element of a nonempty set in a well-founded order -/ noncomputable def well_founded.min {α} {r : α → α → Prop} (H : well_founded r) (p : set α) (h : p ≠ ∅) : α := classical.some (H.has_min p h) theorem well_founded.min_mem {α} {r : α → α → Prop} (H : well_founded r) (p : set α) (h : p ≠ ∅) : H.min p h ∈ p := let ⟨h, _⟩ := classical.some_spec (H.has_min p h) in h theorem well_founded.not_lt_min {α} {r : α → α → Prop} (H : well_founded r) (p : set α) (h : p ≠ ∅) {x} (xp : x ∈ p) : ¬ r x (H.min p h) := let ⟨_, h'⟩ := classical.some_spec (H.has_min p h) in h' _ xp variable (r) local infix `≼` : 50 := r /-- A family of elements of α is directed (with respect to a relation `≼` on α) if there is a member of the family `≼`-above any pair in the family. -/ def directed {ι : Sort v} (f : ι → α) := ∀x y, ∃z, f x ≼ f z ∧ f y ≼ f z /-- A subset of α is directed if there is an element of the set `≼`-above any pair of elements in the set. -/ def directed_on (s : set α) := ∀ (x ∈ s) (y ∈ s), ∃z ∈ s, x ≼ z ∧ y ≼ z theorem directed_on_iff_directed {s} : @directed_on α r s ↔ directed r (coe : s → α) := by simp [directed, directed_on]; refine ball_congr (λ x hx, by simp; refl) theorem directed_comp {ι} (f : ι → β) (g : β → α) : directed r (g ∘ f) ↔ directed (g ⁻¹'o r) f := iff.rfl theorem directed_mono {s : α → α → Prop} {ι} (f : ι → α) (H : ∀ a b, r a b → s a b) (h : directed r f) : directed s f := λ a b, let ⟨c, h₁, h₂⟩ := h a b in ⟨c, H _ _ h₁, H _ _ h₂⟩ end
24a0394ef272c674d8d1ba9f77159a5aaed62834
82e44445c70db0f03e30d7be725775f122d72f3e
/src/ring_theory/adjoin/basic.lean
a0176702dcb549bb200de516a5af067ca92305d9
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
16,846
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import ring_theory.polynomial.basic import algebra.algebra.subalgebra /-! # Adjoining elements to form subalgebras This file develops the basic theory of subalgebras of an R-algebra generated by a set of elements. A basic interface for `adjoin` is set up, and various results about finitely-generated subalgebras and submodules are proved. ## Definitions * `fg (S : subalgebra R A)` : A predicate saying that the subalgebra is finitely-generated as an A-algebra ## Tags adjoin, algebra, finitely-generated algebra -/ universes u v w open submodule namespace algebra variables {R : Type u} {A : Type v} {B : Type w} section semiring variables [comm_semiring R] [semiring A] [semiring B] variables [algebra R A] [algebra R B] {s t : set A} open subsemiring theorem subset_adjoin : s ⊆ adjoin R s := algebra.gc.le_u_l s theorem adjoin_le {S : subalgebra R A} (H : s ⊆ S) : adjoin R s ≤ S := algebra.gc.l_le H theorem adjoin_le_iff {S : subalgebra R A} : adjoin R s ≤ S ↔ s ⊆ S:= algebra.gc _ _ theorem adjoin_mono (H : s ⊆ t) : adjoin R s ≤ adjoin R t := algebra.gc.monotone_l H theorem adjoin_eq_of_le (S : subalgebra R A) (h₁ : s ⊆ S) (h₂ : S ≤ adjoin R s) : adjoin R s = S := le_antisymm (adjoin_le h₁) h₂ theorem adjoin_eq (S : subalgebra R A) : adjoin R ↑S = S := adjoin_eq_of_le _ (set.subset.refl _) subset_adjoin theorem adjoin_induction {p : A → Prop} {x : A} (h : x ∈ adjoin R s) (Hs : ∀ x ∈ s, p x) (Halg : ∀ r, p (algebra_map R A r)) (Hadd : ∀ x y, p x → p y → p (x + y)) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := let S : subalgebra R A := { carrier := p, mul_mem' := Hmul, add_mem' := Hadd, algebra_map_mem' := Halg } in adjoin_le (show s ≤ S, from Hs) h lemma adjoin_union (s t : set A) : adjoin R (s ∪ t) = adjoin R s ⊔ adjoin R t := (algebra.gc : galois_connection _ (coe : subalgebra R A → set A)).l_sup variables (R A) @[simp] theorem adjoin_empty : adjoin R (∅ : set A) = ⊥ := show adjoin R ⊥ = ⊥, by { apply galois_connection.l_bot, exact algebra.gc } variables (R) {A} (s) theorem adjoin_eq_span : (adjoin R s).to_submodule = span R (submonoid.closure s) := begin apply le_antisymm, { intros r hr, rcases subsemiring.mem_closure_iff_exists_list.1 hr with ⟨L, HL, rfl⟩, clear hr, induction L with hd tl ih, { exact zero_mem _ }, rw list.forall_mem_cons at HL, rw [list.map_cons, list.sum_cons], refine submodule.add_mem _ _ (ih HL.2), replace HL := HL.1, clear ih tl, suffices : ∃ z r (hr : r ∈ submonoid.closure s), has_scalar.smul z r = list.prod hd, { rcases this with ⟨z, r, hr, hzr⟩, rw ← hzr, exact smul_mem _ _ (subset_span hr) }, induction hd with hd tl ih, { exact ⟨1, 1, (submonoid.closure s).one_mem', one_smul _ _⟩ }, rw list.forall_mem_cons at HL, rcases (ih HL.2) with ⟨z, r, hr, hzr⟩, rw [list.prod_cons, ← hzr], rcases HL.1 with ⟨hd, rfl⟩ | hs, { refine ⟨hd * z, r, hr, _⟩, rw [algebra.smul_def, algebra.smul_def, (algebra_map _ _).map_mul, _root_.mul_assoc] }, { exact ⟨z, hd * r, submonoid.mul_mem _ (submonoid.subset_closure hs) hr, (mul_smul_comm _ _ _).symm⟩ } }, refine span_le.2 _, change submonoid.closure s ≤ (adjoin R s).to_subsemiring.to_submonoid, exact submonoid.closure_le.2 subset_adjoin end lemma span_le_adjoin (s : set A) : span R s ≤ (adjoin R s).to_submodule := span_le.mpr subset_adjoin lemma adjoin_to_submodule_le {s : set A} {t : submodule R A} : (adjoin R s).to_submodule ≤ t ↔ ↑(submonoid.closure s) ⊆ (t : set A) := by rw [adjoin_eq_span, span_le] lemma adjoin_eq_span_of_subset {s : set A} (hs : ↑(submonoid.closure s) ⊆ (span R s : set A)) : (adjoin R s).to_submodule = span R s := le_antisymm ((adjoin_to_submodule_le R).mpr hs) (span_le_adjoin R s) lemma adjoin_image (f : A →ₐ[R] B) (s : set A) : adjoin R (f '' s) = (adjoin R s).map f := le_antisymm (adjoin_le $ set.image_subset _ subset_adjoin) $ subalgebra.map_le.2 $ adjoin_le $ set.image_subset_iff.1 subset_adjoin @[simp] lemma adjoin_insert_adjoin (x : A) : adjoin R (insert x ↑(adjoin R s)) = adjoin R (insert x s) := le_antisymm (adjoin_le (set.insert_subset.mpr ⟨subset_adjoin (set.mem_insert _ _), adjoin_mono (set.subset_insert _ _)⟩)) (algebra.adjoin_mono (set.insert_subset_insert algebra.subset_adjoin)) lemma adjoint_prod_le (s : set A) (t : set B) : adjoin R (set.prod s t) ≤ (adjoin R s).prod (adjoin R t) := adjoin_le $ set.prod_mono subset_adjoin subset_adjoin lemma adjoin_inl_union_inr_le_prod (s) (t) : adjoin R (linear_map.inl R A B '' (s ∪ {1}) ∪ linear_map.inr R A B '' (t ∪ {1})) ≤ (adjoin R s).prod (adjoin R t) := begin rw [set.image_union, set.image_union], refine adjoin_le (λ x hx, subalgebra.mem_prod.2 _), rcases hx with (⟨x₁, ⟨hx₁, rfl⟩⟩ | ⟨x₂, ⟨hx₂, rfl⟩⟩) | (⟨x₃, ⟨hx₃, rfl⟩⟩ | ⟨x₄, ⟨hx₄, rfl⟩⟩), { exact ⟨subset_adjoin hx₁, subalgebra.zero_mem _⟩ }, { rw set.mem_singleton_iff.1 hx₂, exact ⟨subalgebra.one_mem _, subalgebra.zero_mem _⟩ }, { exact ⟨subalgebra.zero_mem _, subset_adjoin hx₃⟩ }, { rw set.mem_singleton_iff.1 hx₄, exact ⟨subalgebra.zero_mem _, subalgebra.one_mem _⟩ } end lemma mem_adjoin_of_map_mul {s} {x : A} {f : A →ₗ[R] B} (hf : ∀ a₁ a₂, f(a₁ * a₂) = f a₁ * f a₂) (h : x ∈ adjoin R s) : f x ∈ adjoin R (f '' (s ∪ {1})) := begin refine @adjoin_induction R A _ _ _ _ (λ a, f a ∈ adjoin R (f '' (s ∪ {1}))) x h (λ a ha, subset_adjoin ⟨a, ⟨set.subset_union_left _ _ ha, rfl⟩⟩) (λ r, _) (λ y z hy hz, by simpa [hy, hz] using subalgebra.add_mem _ hy hz) (λ y z hy hz, by simpa [hy, hz, hf y z] using subalgebra.mul_mem _ hy hz), have : f 1 ∈ adjoin R (f '' (s ∪ {1})) := subset_adjoin ⟨1, ⟨set.subset_union_right _ _ $ set.mem_singleton 1, rfl⟩⟩, replace this := subalgebra.smul_mem (adjoin R (f '' (s ∪ {1}))) this r, convert this, rw algebra_map_eq_smul_one, exact f.map_smul _ _ end lemma adjoin_inl_union_inr_eq_prod (s) (t) : adjoin R (linear_map.inl R A B '' (s ∪ {1}) ∪ linear_map.inr R A B '' (t ∪ {1})) = (adjoin R s).prod (adjoin R t) := begin let P := adjoin R (linear_map.inl R A B '' (s ∪ {1}) ∪ linear_map.inr R A B '' (t ∪ {1})), refine le_antisymm (adjoin_inl_union_inr_le_prod R s t) _, rintro ⟨a, b⟩ ⟨ha, hb⟩, have Ha : (a, (0 : B)) ∈ adjoin R ((linear_map.inl R A B) '' (s ∪ {1})) := mem_adjoin_of_map_mul R (linear_map.inl_map_mul) ha, have Hb : ((0 : A), b) ∈ adjoin R ((linear_map.inr R A B) '' (t ∪ {1})) := mem_adjoin_of_map_mul R (linear_map.inr_map_mul) hb, replace Ha : (a, (0 : B)) ∈ P := adjoin_mono (set.subset_union_of_subset_left (set.subset.refl _) _) Ha, replace Hb : ((0 : A), b) ∈ P := adjoin_mono (set.subset_union_of_subset_right (set.subset.refl _) _) Hb, simpa using subalgebra.add_mem _ Ha Hb end end semiring section comm_semiring variables [comm_semiring R] [comm_semiring A] variables [algebra R A] {s t : set A} open subsemiring variables (R s t) theorem adjoin_union_eq_under : adjoin R (s ∪ t) = (adjoin R s).under (adjoin (adjoin R s) t) := le_antisymm (closure_mono $ set.union_subset (set.range_subset_iff.2 $ λ r, or.inl ⟨algebra_map R (adjoin R s) r, rfl⟩) (set.union_subset_union_left _ $ λ x hxs, ⟨⟨_, subset_adjoin hxs⟩, rfl⟩)) (closure_le.2 $ set.union_subset (set.range_subset_iff.2 $ λ x, adjoin_mono (set.subset_union_left _ _) x.2) (set.subset.trans (set.subset_union_right _ _) subset_adjoin)) theorem adjoin_eq_range : adjoin R s = (mv_polynomial.aeval (coe : s → A)).range := le_antisymm (adjoin_le $ λ x hx, ⟨mv_polynomial.X ⟨x, hx⟩, mv_polynomial.eval₂_X _ _ _⟩) (λ x ⟨p, (hp : mv_polynomial.aeval coe p = x)⟩, hp ▸ mv_polynomial.induction_on p (λ r, by { rw [mv_polynomial.aeval_def, mv_polynomial.eval₂_C], exact (adjoin R s).algebra_map_mem r }) (λ p q hp hq, by rw alg_hom.map_add; exact subalgebra.add_mem _ hp hq) (λ p ⟨n, hn⟩ hp, by rw [alg_hom.map_mul, mv_polynomial.aeval_def _ (mv_polynomial.X _), mv_polynomial.eval₂_X]; exact subalgebra.mul_mem _ hp (subset_adjoin hn))) theorem adjoin_singleton_eq_range (x : A) : adjoin R {x} = (polynomial.aeval x).range := le_antisymm (adjoin_le $ set.singleton_subset_iff.2 ⟨polynomial.X, polynomial.eval₂_X _ _⟩) (λ y ⟨p, (hp : polynomial.aeval x p = y)⟩, hp ▸ polynomial.induction_on p (λ r, by { rw [polynomial.aeval_def, polynomial.eval₂_C], exact (adjoin R _).algebra_map_mem r }) (λ p q hp hq, by rw alg_hom.map_add; exact subalgebra.add_mem _ hp hq) (λ n r ih, by { rw [pow_succ', ← mul_assoc, alg_hom.map_mul, polynomial.aeval_def _ polynomial.X, polynomial.eval₂_X], exact subalgebra.mul_mem _ ih (subset_adjoin rfl) })) lemma adjoin_singleton_one : adjoin R ({1} : set A) = ⊥ := eq_bot_iff.2 $ adjoin_le $ set.singleton_subset_iff.2 $ set_like.mem_coe.2 $ one_mem _ theorem adjoin_union_coe_submodule : (adjoin R (s ∪ t)).to_submodule = (adjoin R s).to_submodule * (adjoin R t).to_submodule := begin rw [adjoin_eq_span, adjoin_eq_span, adjoin_eq_span, span_mul_span], congr' 1 with z, simp [submonoid.closure_union, submonoid.mem_sup, set.mem_mul] end end comm_semiring section ring variables [comm_ring R] [ring A] variables [algebra R A] {s t : set A} variables {R s t} open ring theorem adjoin_int (s : set R) : adjoin ℤ s = subalgebra_of_subring (subring.closure s) := le_antisymm (adjoin_le subring.subset_closure) (subring.closure_le.2 subset_adjoin : subring.closure s ≤ (adjoin ℤ s).to_subring) theorem mem_adjoin_iff {s : set A} {x : A} : x ∈ adjoin R s ↔ x ∈ subring.closure (set.range (algebra_map R A) ∪ s) := ⟨λ hx, subsemiring.closure_induction hx subring.subset_closure (subring.zero_mem _) (subring.one_mem _) (λ _ _, subring.add_mem _) ( λ _ _, subring.mul_mem _), suffices subring.closure (set.range ⇑(algebra_map R A) ∪ s) ≤ (adjoin R s).to_subring, from @this x, subring.closure_le.2 subsemiring.subset_closure⟩ theorem adjoin_eq_ring_closure (s : set A) : (adjoin R s).to_subring = subring.closure (set.range (algebra_map R A) ∪ s) := subring.ext $ λ x, mem_adjoin_iff end ring section comm_ring variables [comm_ring R] [comm_ring A] variables [algebra R A] {s t : set A} variables {R s t} open ring theorem fg_trans (h1 : (adjoin R s).to_submodule.fg) (h2 : (adjoin (adjoin R s) t).to_submodule.fg) : (adjoin R (s ∪ t)).to_submodule.fg := begin rcases fg_def.1 h1 with ⟨p, hp, hp'⟩, rcases fg_def.1 h2 with ⟨q, hq, hq'⟩, refine fg_def.2 ⟨p * q, hp.mul hq, le_antisymm _ _⟩, { rw [span_le], rintros _ ⟨x, y, hx, hy, rfl⟩, change x * y ∈ _, refine subalgebra.mul_mem _ _ _, { have : x ∈ (adjoin R s).to_submodule, { rw ← hp', exact subset_span hx }, exact adjoin_mono (set.subset_union_left _ _) this }, have : y ∈ (adjoin (adjoin R s) t).to_submodule, { rw ← hq', exact subset_span hy }, change y ∈ adjoin R (s ∪ t), rwa adjoin_union_eq_under }, { intros r hr, change r ∈ adjoin R (s ∪ t) at hr, rw adjoin_union_eq_under at hr, change r ∈ (adjoin (adjoin R s) t).to_submodule at hr, haveI := classical.dec_eq A, haveI := classical.dec_eq R, rw [← hq', ← set.image_id q, finsupp.mem_span_image_iff_total (adjoin R s)] at hr, rcases hr with ⟨l, hlq, rfl⟩, have := @finsupp.total_apply A A (adjoin R s), rw [this, finsupp.sum], refine sum_mem _ _, intros z hz, change (l z).1 * _ ∈ _, have : (l z).1 ∈ (adjoin R s).to_submodule := (l z).2, rw [← hp', ← set.image_id p, finsupp.mem_span_image_iff_total R] at this, rcases this with ⟨l2, hlp, hl⟩, have := @finsupp.total_apply A A R, rw this at hl, rw [←hl, finsupp.sum_mul], refine sum_mem _ _, intros t ht, change _ * _ ∈ _, rw smul_mul_assoc, refine smul_mem _ _ _, exact subset_span ⟨t, z, hlp ht, hlq hz, rfl⟩ } end end comm_ring end algebra namespace subalgebra variables {R : Type u} {A : Type v} {B : Type w} variables [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B] /-- A subalgebra `S` is finitely generated if there exists `t : finset A` such that `algebra.adjoin R t = S`. -/ def fg (S : subalgebra R A) : Prop := ∃ t : finset A, algebra.adjoin R ↑t = S lemma fg_adjoin_finset (s : finset A) : (algebra.adjoin R (↑s : set A)).fg := ⟨s, rfl⟩ theorem fg_def {S : subalgebra R A} : S.fg ↔ ∃ t : set A, set.finite t ∧ algebra.adjoin R t = S := ⟨λ ⟨t, ht⟩, ⟨↑t, set.finite_mem_finset t, ht⟩, λ ⟨t, ht1, ht2⟩, ⟨ht1.to_finset, by rwa set.finite.coe_to_finset⟩⟩ theorem fg_bot : (⊥ : subalgebra R A).fg := ⟨∅, algebra.adjoin_empty R A⟩ theorem fg_of_fg_to_submodule {S : subalgebra R A} : S.to_submodule.fg → S.fg := λ ⟨t, ht⟩, ⟨t, le_antisymm (algebra.adjoin_le (λ x hx, show x ∈ S.to_submodule, from ht ▸ subset_span hx)) $ show S.to_submodule ≤ (algebra.adjoin R ↑t).to_submodule, from (λ x hx, span_le.mpr (λ x hx, algebra.subset_adjoin hx) (show x ∈ span R ↑t, by { rw ht, exact hx }))⟩ theorem fg_of_noetherian [is_noetherian R A] (S : subalgebra R A) : S.fg := fg_of_fg_to_submodule (is_noetherian.noetherian S.to_submodule) lemma fg_of_submodule_fg (h : (⊤ : submodule R A).fg) : (⊤ : subalgebra R A).fg := let ⟨s, hs⟩ := h in ⟨s, to_submodule_injective $ by { rw [algebra.top_to_submodule, eq_top_iff, ← hs, span_le], exact algebra.subset_adjoin }⟩ lemma fg_prod {S : subalgebra R A} {T : subalgebra R B} (hS : S.fg) (hT : T.fg) : (S.prod T).fg := begin obtain ⟨s, hs⟩ := fg_def.1 hS, obtain ⟨t, ht⟩ := fg_def.1 hT, rw [← hs.2, ← ht.2], exact fg_def.2 ⟨(linear_map.inl R A B '' (s ∪ {1})) ∪ (linear_map.inr R A B '' (t ∪ {1})), set.finite.union (set.finite.image _ (set.finite.union hs.1 (set.finite_singleton _))) (set.finite.image _ (set.finite.union ht.1 (set.finite_singleton _))), algebra.adjoin_inl_union_inr_eq_prod R s t⟩ end section open_locale classical lemma fg_map (S : subalgebra R A) (f : A →ₐ[R] B) (hs : S.fg) : (S.map f).fg := let ⟨s, hs⟩ := hs in ⟨s.image f, by rw [finset.coe_image, algebra.adjoin_image, hs]⟩ end lemma fg_of_fg_map (S : subalgebra R A) (f : A →ₐ[R] B) (hf : function.injective f) (hs : (S.map f).fg) : S.fg := let ⟨s, hs⟩ := hs in ⟨s.preimage f $ λ _ _ _ _ h, hf h, map_injective f hf $ by { rw [← algebra.adjoin_image, finset.coe_preimage, set.image_preimage_eq_of_subset, hs], rw [← alg_hom.coe_range, ← algebra.adjoin_le_iff, hs, ← algebra.map_top], exact map_mono le_top }⟩ lemma fg_top (S : subalgebra R A) : (⊤ : subalgebra R S).fg ↔ S.fg := ⟨λ h, by { rw [← S.range_val, ← algebra.map_top], exact fg_map _ _ h }, λ h, fg_of_fg_map _ S.val subtype.val_injective $ by { rw [algebra.map_top, range_val], exact h }⟩ lemma induction_on_adjoin [is_noetherian R A] (P : subalgebra R A → Prop) (base : P ⊥) (ih : ∀ (S : subalgebra R A) (x : A), P S → P (algebra.adjoin R (insert x S))) (S : subalgebra R A) : P S := begin classical, obtain ⟨t, rfl⟩ := S.fg_of_noetherian, refine finset.induction_on t _ _, { simpa using base }, intros x t hxt h, convert ih _ x h using 1, rw [finset.coe_insert, algebra.adjoin_insert_adjoin] end end subalgebra variables {R : Type u} {A : Type v} {B : Type w} variables [comm_ring R] [comm_ring A] [comm_ring B] [algebra R A] [algebra R B] /-- The image of a Noetherian R-algebra under an R-algebra map is a Noetherian ring. -/ instance alg_hom.is_noetherian_ring_range (f : A →ₐ[R] B) [is_noetherian_ring A] : is_noetherian_ring f.range := is_noetherian_ring_range f.to_ring_hom theorem is_noetherian_ring_of_fg {S : subalgebra R A} (HS : S.fg) [is_noetherian_ring R] : is_noetherian_ring S := let ⟨t, ht⟩ := HS in ht ▸ (algebra.adjoin_eq_range R (↑t : set A)).symm ▸ by haveI : is_noetherian_ring (mv_polynomial (↑t : set A) R) := mv_polynomial.is_noetherian_ring; convert alg_hom.is_noetherian_ring_range _; apply_instance theorem is_noetherian_subring_closure (s : set R) (hs : s.finite) : is_noetherian_ring (subring.closure s) := show is_noetherian_ring (subalgebra_of_subring (subring.closure s)), from algebra.adjoin_int s ▸ is_noetherian_ring_of_fg (subalgebra.fg_def.2 ⟨s, hs, rfl⟩)
b800b4a4fabf4e7d65a07aba74f131a346114a5b
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/run/congr_imp_bug.lean
f5f9cf7aa28951c2c30655e6e524ea68d3506903
[ "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
2,163
lean
---------------------------------------------------------------------------------------------------- --- Copyright (c) 2014 Microsoft Corporation. All rights reserved. --- Released under Apache 2.0 license as described in the file LICENSE. --- Author: Jeremy Avigad ---------------------------------------------------------------------------------------------------- import logic.connectives.basic logic.connectives.function using function namespace congr inductive struc {T1 : Type} {T2 : Type} (R1 : T1 → T1 → Prop) (R2 : T2 → T2 → Prop) (f : T1 → T2) : Prop := | mk : (∀x y : T1, R1 x y → R2 (f x) (f y)) → struc R1 R2 f abbreviation app {T1 : Type} {T2 : Type} {R1 : T1 → T1 → Prop} {R2 : T2 → T2 → Prop} {f : T1 → T2} (C : struc R1 R2 f) {x y : T1} : R1 x y → R2 (f x) (f y) := struc_rec id C x y inductive struc2 {T1 : Type} {T2 : Type} {T3 : Type} (R1 : T1 → T1 → Prop) (R2 : T2 → T2 → Prop) (R3 : T3 → T3 → Prop) (f : T1 → T2 → T3) : Prop := | mk2 : (∀(x1 y1 : T1) (x2 y2 : T2), R1 x1 y1 → R2 x2 y2 → R3 (f x1 x2) (f y1 y2)) → struc2 R1 R2 R3 f abbreviation app2 {T1 : Type} {T2 : Type} {T3 : Type} {R1 : T1 → T1 → Prop} {R2 : T2 → T2 → Prop} {R3 : T3 → T3 → Prop} {f : T1 → T2 → T3} (C : struc2 R1 R2 R3 f) {x1 y1 : T1} {x2 y2 : T2} : R1 x1 y1 → R2 x2 y2 → R3 (f x1 x2) (f y1 y2) := struc2_rec id C x1 y1 x2 y2 theorem compose21 {T2 : Type} {R2 : T2 → T2 → Prop} {T3 : Type} {R3 : T3 → T3 → Prop} {T4 : Type} {R4 : T4 → T4 → Prop} {g : T2 → T3 → T4} (C3 : congr.struc2 R2 R3 R4 g) ⦃T1 : Type⦄ -- nice! {R1 : T1 → T1 → Prop} {f1 : T1 → T2} (C1 : congr.struc R1 R2 f1) {f2 : T1 → T3} (C2 : congr.struc R1 R3 f2) : congr.struc R1 R4 (λx, g (f1 x) (f2 x)) := mk (take x1 x2 H, app2 C3 (app C1 H) (app C2 H)) theorem congr_and : congr.struc2 iff iff iff and := sorry theorem congr_and_comp [instance] {T : Type} {R : T → T → Prop} {f1 f2 : T → Prop} (C1 : struc R iff f1) (C2 : struc R iff f2) : congr.struc R iff (λx, f1 x ∧ f2 x) := congr.compose21 congr_and C1 C2 end
57080c7e3ad086f15efd283392e86b697814fd2f
9028d228ac200bbefe3a711342514dd4e4458bff
/src/data/matrix/basic.lean
f6d6bd58b90dfed06d760160502efa8989d45cca
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
38,984
lean
/- Copyright (c) 2018 Ellen Arlt. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ellen Arlt, Blair Shi, Sean Leather, Mario Carneiro, Johan Commelin -/ import algebra.big_operators.pi import algebra.module.pi import algebra.big_operators.ring import data.fintype.card /-! # Matrices -/ universes u u' v w open_locale big_operators /-- `matrix m n` is the type of matrices whose rows are indexed by the fintype `m` and whose columns are indexed by the fintype `n`. -/ @[nolint unused_arguments] def matrix (m : Type u) (n : Type u') [fintype m] [fintype n] (α : Type v) : Type (max u u' v) := m → n → α variables {l m n o : Type*} [fintype l] [fintype m] [fintype n] [fintype o] variables {α : Type v} namespace matrix section ext variables {M N : matrix m n α} theorem ext_iff : (∀ i j, M i j = N i j) ↔ M = N := ⟨λ h, funext $ λ i, funext $ h i, λ h, by simp [h]⟩ @[ext] theorem ext : (∀ i j, M i j = N i j) → M = N := ext_iff.mp end ext /-- `M.map f` is the matrix obtained by applying `f` to each entry of the matrix `M`. -/ def map (M : matrix m n α) {β : Type w} (f : α → β) : matrix m n β := λ i j, f (M i j) @[simp] lemma map_apply {M : matrix m n α} {β : Type w} {f : α → β} {i : m} {j : n} : M.map f i j = f (M i j) := rfl /-- The transpose of a matrix. -/ def transpose (M : matrix m n α) : matrix n m α | x y := M y x localized "postfix `ᵀ`:1500 := matrix.transpose" in matrix /-- `matrix.col u` is the column matrix whose entries are given by `u`. -/ def col (w : m → α) : matrix m unit α | x y := w x /-- `matrix.row u` is the row matrix whose entries are given by `u`. -/ def row (v : n → α) : matrix unit n α | x y := v y instance [inhabited α] : inhabited (matrix m n α) := pi.inhabited _ instance [has_add α] : has_add (matrix m n α) := pi.has_add instance [add_semigroup α] : add_semigroup (matrix m n α) := pi.add_semigroup instance [add_comm_semigroup α] : add_comm_semigroup (matrix m n α) := pi.add_comm_semigroup instance [has_zero α] : has_zero (matrix m n α) := pi.has_zero instance [add_monoid α] : add_monoid (matrix m n α) := pi.add_monoid instance [add_comm_monoid α] : add_comm_monoid (matrix m n α) := pi.add_comm_monoid instance [has_neg α] : has_neg (matrix m n α) := pi.has_neg instance [add_group α] : add_group (matrix m n α) := pi.add_group instance [add_comm_group α] : add_comm_group (matrix m n α) := pi.add_comm_group @[simp] theorem zero_apply [has_zero α] (i j) : (0 : matrix m n α) i j = 0 := rfl @[simp] theorem neg_apply [has_neg α] (M : matrix m n α) (i j) : (- M) i j = - M i j := rfl @[simp] theorem add_apply [has_add α] (M N : matrix m n α) (i j) : (M + N) i j = M i j + N i j := rfl @[simp] lemma map_zero [has_zero α] {β : Type w} [has_zero β] {f : α → β} (h : f 0 = 0) : (0 : matrix m n α).map f = 0 := by { ext, simp [h], } lemma map_add [add_monoid α] {β : Type w} [add_monoid β] (f : α →+ β) (M N : matrix m n α) : (M + N).map f = M.map f + N.map f := by { ext, simp, } lemma map_sub [add_group α] {β : Type w} [add_group β] (f : α →+ β) (M N : matrix m n α) : (M - N).map f = M.map f - N.map f := by { ext, simp } lemma subsingleton_of_empty_left (hm : ¬ nonempty m) : subsingleton (matrix m n α) := ⟨λ M N, by { ext, contrapose! hm, use i }⟩ lemma subsingleton_of_empty_right (hn : ¬ nonempty n) : subsingleton (matrix m n α) := ⟨λ M N, by { ext, contrapose! hn, use j }⟩ end matrix /-- The `add_monoid_hom` between spaces of matrices induced by an `add_monoid_hom` between their coefficients. -/ def add_monoid_hom.map_matrix [add_monoid α] {β : Type w} [add_monoid β] (f : α →+ β) : matrix m n α →+ matrix m n β := { to_fun := λ M, M.map f, map_zero' := by simp, map_add' := matrix.map_add f, } @[simp] lemma add_monoid_hom.map_matrix_apply [add_monoid α] {β : Type w} [add_monoid β] (f : α →+ β) (M : matrix m n α) : f.map_matrix M = M.map f := rfl open_locale matrix namespace matrix section diagonal variables [decidable_eq n] /-- `diagonal d` is the square matrix such that `(diagonal d) i i = d i` and `(diagonal d) i j = 0` if `i ≠ j`. -/ def diagonal [has_zero α] (d : n → α) : matrix n n α := λ i j, if i = j then d i else 0 @[simp] theorem diagonal_apply_eq [has_zero α] {d : n → α} (i : n) : (diagonal d) i i = d i := by simp [diagonal] @[simp] theorem diagonal_apply_ne [has_zero α] {d : n → α} {i j : n} (h : i ≠ j) : (diagonal d) i j = 0 := by simp [diagonal, h] theorem diagonal_apply_ne' [has_zero α] {d : n → α} {i j : n} (h : j ≠ i) : (diagonal d) i j = 0 := diagonal_apply_ne h.symm @[simp] theorem diagonal_zero [has_zero α] : (diagonal (λ _, 0) : matrix n n α) = 0 := by simp [diagonal]; refl @[simp] lemma diagonal_transpose [has_zero α] (v : n → α) : (diagonal v)ᵀ = diagonal v := begin ext i j, by_cases h : i = j, { simp [h, transpose] }, { simp [h, transpose, diagonal_apply_ne' h] } end @[simp] theorem diagonal_add [add_monoid α] (d₁ d₂ : n → α) : diagonal d₁ + diagonal d₂ = diagonal (λ i, d₁ i + d₂ i) := by ext i j; by_cases h : i = j; simp [h] @[simp] lemma diagonal_map {β : Type w} [has_zero α] [has_zero β] {f : α → β} (h : f 0 = 0) {d : n → α} : (diagonal d).map f = diagonal (λ m, f (d m)) := by { ext, simp only [diagonal, map_apply], split_ifs; simp [h], } section one variables [has_zero α] [has_one α] instance : has_one (matrix n n α) := ⟨diagonal (λ _, 1)⟩ @[simp] theorem diagonal_one : (diagonal (λ _, 1) : matrix n n α) = 1 := rfl theorem one_apply {i j} : (1 : matrix n n α) i j = if i = j then 1 else 0 := rfl @[simp] theorem one_apply_eq (i) : (1 : matrix n n α) i i = 1 := diagonal_apply_eq i @[simp] theorem one_apply_ne {i j} : i ≠ j → (1 : matrix n n α) i j = 0 := diagonal_apply_ne theorem one_apply_ne' {i j} : j ≠ i → (1 : matrix n n α) i j = 0 := diagonal_apply_ne' @[simp] lemma one_map {β : Type w} [has_zero β] [has_one β] {f : α → β} (h₀ : f 0 = 0) (h₁ : f 1 = 1) : (1 : matrix n n α).map f = (1 : matrix n n β) := by { ext, simp only [one_apply, map_apply], split_ifs; simp [h₀, h₁], } end one section numeral @[simp] lemma bit0_apply [has_add α] (M : matrix m m α) (i : m) (j : m) : (bit0 M) i j = bit0 (M i j) := rfl variables [add_monoid α] [has_one α] lemma bit1_apply (M : matrix n n α) (i : n) (j : n) : (bit1 M) i j = if i = j then bit1 (M i j) else bit0 (M i j) := by dsimp [bit1]; by_cases h : i = j; simp [h] @[simp] lemma bit1_apply_eq (M : matrix n n α) (i : n) : (bit1 M) i i = bit1 (M i i) := by simp [bit1_apply] @[simp] lemma bit1_apply_ne (M : matrix n n α) {i j : n} (h : i ≠ j) : (bit1 M) i j = bit0 (M i j) := by simp [bit1_apply, h] end numeral end diagonal section dot_product /-- `dot_product v w` is the sum of the entrywise products `v i * w i` -/ def dot_product [has_mul α] [add_comm_monoid α] (v w : m → α) : α := ∑ i, v i * w i lemma dot_product_assoc [semiring α] (u : m → α) (v : m → n → α) (w : n → α) : dot_product (λ j, dot_product u (λ i, v i j)) w = dot_product u (λ i, dot_product (v i) w) := by simpa [dot_product, finset.mul_sum, finset.sum_mul, mul_assoc] using finset.sum_comm lemma dot_product_comm [comm_semiring α] (v w : m → α) : dot_product v w = dot_product w v := by simp_rw [dot_product, mul_comm] @[simp] lemma dot_product_punit [add_comm_monoid α] [has_mul α] (v w : punit → α) : dot_product v w = v ⟨⟩ * w ⟨⟩ := by simp [dot_product] @[simp] lemma dot_product_zero [semiring α] (v : m → α) : dot_product v 0 = 0 := by simp [dot_product] @[simp] lemma dot_product_zero' [semiring α] (v : m → α) : dot_product v (λ _, 0) = 0 := dot_product_zero v @[simp] lemma zero_dot_product [semiring α] (v : m → α) : dot_product 0 v = 0 := by simp [dot_product] @[simp] lemma zero_dot_product' [semiring α] (v : m → α) : dot_product (λ _, (0 : α)) v = 0 := zero_dot_product v @[simp] lemma add_dot_product [semiring α] (u v w : m → α) : dot_product (u + v) w = dot_product u w + dot_product v w := by simp [dot_product, add_mul, finset.sum_add_distrib] @[simp] lemma dot_product_add [semiring α] (u v w : m → α) : dot_product u (v + w) = dot_product u v + dot_product u w := by simp [dot_product, mul_add, finset.sum_add_distrib] @[simp] lemma diagonal_dot_product [decidable_eq m] [semiring α] (v w : m → α) (i : m) : dot_product (diagonal v i) w = v i * w i := have ∀ j ≠ i, diagonal v i j * w j = 0 := λ j hij, by simp [diagonal_apply_ne' hij], by convert finset.sum_eq_single i (λ j _, this j) _; simp @[simp] lemma dot_product_diagonal [decidable_eq m] [semiring α] (v w : m → α) (i : m) : dot_product v (diagonal w i) = v i * w i := have ∀ j ≠ i, v j * diagonal w i j = 0 := λ j hij, by simp [diagonal_apply_ne' hij], by convert finset.sum_eq_single i (λ j _, this j) _; simp @[simp] lemma dot_product_diagonal' [decidable_eq m] [semiring α] (v w : m → α) (i : m) : dot_product v (λ j, diagonal w j i) = v i * w i := have ∀ j ≠ i, v j * diagonal w j i = 0 := λ j hij, by simp [diagonal_apply_ne hij], by convert finset.sum_eq_single i (λ j _, this j) _; simp @[simp] lemma neg_dot_product [ring α] (v w : m → α) : dot_product (-v) w = - dot_product v w := by simp [dot_product] @[simp] lemma dot_product_neg [ring α] (v w : m → α) : dot_product v (-w) = - dot_product v w := by simp [dot_product] @[simp] lemma smul_dot_product [semiring α] (x : α) (v w : m → α) : dot_product (x • v) w = x * dot_product v w := by simp [dot_product, finset.mul_sum, mul_assoc] @[simp] lemma dot_product_smul [comm_semiring α] (x : α) (v w : m → α) : dot_product v (x • w) = x * dot_product v w := by simp [dot_product, finset.mul_sum, mul_assoc, mul_comm, mul_left_comm] end dot_product /-- `M ⬝ N` is the usual product of matrices `M` and `N`, i.e. we have that `(M ⬝ N) i k` is the dot product of the `i`-th row of `M` by the `k`-th column of `Ǹ`. -/ protected def mul [has_mul α] [add_comm_monoid α] (M : matrix l m α) (N : matrix m n α) : matrix l n α := λ i k, dot_product (λ j, M i j) (λ j, N j k) localized "infixl ` ⬝ `:75 := matrix.mul" in matrix theorem mul_apply [has_mul α] [add_comm_monoid α] {M : matrix l m α} {N : matrix m n α} {i k} : (M ⬝ N) i k = ∑ j, M i j * N j k := rfl instance [has_mul α] [add_comm_monoid α] : has_mul (matrix n n α) := ⟨matrix.mul⟩ @[simp] theorem mul_eq_mul [has_mul α] [add_comm_monoid α] (M N : matrix n n α) : M * N = M ⬝ N := rfl theorem mul_apply' [has_mul α] [add_comm_monoid α] {M N : matrix n n α} {i k} : (M ⬝ N) i k = dot_product (λ j, M i j) (λ j, N j k) := rfl section semigroup variables [semiring α] protected theorem mul_assoc (L : matrix l m α) (M : matrix m n α) (N : matrix n o α) : (L ⬝ M) ⬝ N = L ⬝ (M ⬝ N) := by { ext, apply dot_product_assoc } instance : semigroup (matrix n n α) := { mul_assoc := matrix.mul_assoc, ..matrix.has_mul } end semigroup @[simp] theorem diagonal_neg [decidable_eq n] [add_group α] (d : n → α) : -diagonal d = diagonal (λ i, -d i) := by ext i j; by_cases i = j; simp [h] section semiring variables [semiring α] @[simp] protected theorem mul_zero (M : matrix m n α) : M ⬝ (0 : matrix n o α) = 0 := by { ext i j, apply dot_product_zero } @[simp] protected theorem zero_mul (M : matrix m n α) : (0 : matrix l m α) ⬝ M = 0 := by { ext i j, apply zero_dot_product } protected theorem mul_add (L : matrix m n α) (M N : matrix n o α) : L ⬝ (M + N) = L ⬝ M + L ⬝ N := by { ext i j, apply dot_product_add } protected theorem add_mul (L M : matrix l m α) (N : matrix m n α) : (L + M) ⬝ N = L ⬝ N + M ⬝ N := by { ext i j, apply add_dot_product } @[simp] theorem diagonal_mul [decidable_eq m] (d : m → α) (M : matrix m n α) (i j) : (diagonal d).mul M i j = d i * M i j := diagonal_dot_product _ _ _ @[simp] theorem mul_diagonal [decidable_eq n] (d : n → α) (M : matrix m n α) (i j) : (M ⬝ diagonal d) i j = M i j * d j := by { rw ← diagonal_transpose, apply dot_product_diagonal } @[simp] protected theorem one_mul [decidable_eq m] (M : matrix m n α) : (1 : matrix m m α) ⬝ M = M := by ext i j; rw [← diagonal_one, diagonal_mul, one_mul] @[simp] protected theorem mul_one [decidable_eq n] (M : matrix m n α) : M ⬝ (1 : matrix n n α) = M := by ext i j; rw [← diagonal_one, mul_diagonal, mul_one] instance [decidable_eq n] : monoid (matrix n n α) := { one_mul := matrix.one_mul, mul_one := matrix.mul_one, ..matrix.has_one, ..matrix.semigroup } instance [decidable_eq n] : semiring (matrix n n α) := { mul_zero := matrix.mul_zero, zero_mul := matrix.zero_mul, left_distrib := matrix.mul_add, right_distrib := matrix.add_mul, ..matrix.add_comm_monoid, ..matrix.monoid } @[simp] theorem diagonal_mul_diagonal [decidable_eq n] (d₁ d₂ : n → α) : (diagonal d₁) ⬝ (diagonal d₂) = diagonal (λ i, d₁ i * d₂ i) := by ext i j; by_cases i = j; simp [h] theorem diagonal_mul_diagonal' [decidable_eq n] (d₁ d₂ : n → α) : diagonal d₁ * diagonal d₂ = diagonal (λ i, d₁ i * d₂ i) := diagonal_mul_diagonal _ _ lemma map_mul {L : matrix m n α} {M : matrix n o α} {β : Type w} [semiring β] {f : α →+* β} : (L ⬝ M).map f = L.map f ⬝ M.map f := by { ext, simp [mul_apply, ring_hom.map_sum], } lemma is_add_monoid_hom_mul_left (M : matrix l m α) : is_add_monoid_hom (λ x : matrix m n α, M ⬝ x) := { to_is_add_hom := ⟨matrix.mul_add _⟩, map_zero := matrix.mul_zero _ } lemma is_add_monoid_hom_mul_right (M : matrix m n α) : is_add_monoid_hom (λ x : matrix l m α, x ⬝ M) := { to_is_add_hom := ⟨λ _ _, matrix.add_mul _ _ _⟩, map_zero := matrix.zero_mul _ } protected lemma sum_mul {β : Type*} (s : finset β) (f : β → matrix l m α) (M : matrix m n α) : (∑ a in s, f a) ⬝ M = ∑ a in s, f a ⬝ M := (@finset.sum_hom _ _ _ _ _ s f (λ x, x ⬝ M) /- This line does not type-check without `id` and `: _`. Lean did not recognize that two different `add_monoid` instances were def-eq -/ (id (@is_add_monoid_hom_mul_right l _ _ _ _ _ _ _ M) : _)).symm protected lemma mul_sum {β : Type*} (s : finset β) (f : β → matrix m n α) (M : matrix l m α) : M ⬝ ∑ a in s, f a = ∑ a in s, M ⬝ f a := (@finset.sum_hom _ _ _ _ _ s f (λ x, M ⬝ x) /- This line does not type-check without `id` and `: _`. Lean did not recognize that two different `add_monoid` instances were def-eq -/ (id (@is_add_monoid_hom_mul_left _ _ n _ _ _ _ _ M) : _)).symm @[simp] lemma row_mul_col_apply (v w : m → α) (i j) : (row v ⬝ col w) i j = dot_product v w := rfl end semiring end matrix /-- The `ring_hom` between spaces of square matrices induced by a `ring_hom` between their coefficients. -/ def ring_hom.map_matrix [decidable_eq m] [semiring α] {β : Type w} [semiring β] (f : α →+* β) : matrix m m α →+* matrix m m β := { to_fun := λ M, M.map f, map_one' := by simp, map_mul' := λ L M, matrix.map_mul, ..(f.to_add_monoid_hom).map_matrix } @[simp] lemma ring_hom.map_matrix_apply [decidable_eq m] [semiring α] {β : Type w} [semiring β] (f : α →+* β) (M : matrix m m α) : f.map_matrix M = M.map f := rfl open_locale matrix namespace matrix section ring variables [ring α] @[simp] theorem neg_mul (M : matrix m n α) (N : matrix n o α) : (-M) ⬝ N = -(M ⬝ N) := by { ext, apply neg_dot_product } @[simp] theorem mul_neg (M : matrix m n α) (N : matrix n o α) : M ⬝ (-N) = -(M ⬝ N) := by { ext, apply dot_product_neg } protected theorem sub_mul (M M' : matrix m n α) (N : matrix n o α) : (M - M') ⬝ N = M ⬝ N - M' ⬝ N := by rw [sub_eq_add_neg, matrix.add_mul, neg_mul, sub_eq_add_neg] protected theorem mul_sub (M : matrix m n α) (N N' : matrix n o α) : M ⬝ (N - N') = M ⬝ N - M ⬝ N' := by rw [sub_eq_add_neg, matrix.mul_add, mul_neg, sub_eq_add_neg] end ring instance [decidable_eq n] [ring α] : ring (matrix n n α) := { ..matrix.semiring, ..matrix.add_comm_group } instance [semiring α] : has_scalar α (matrix m n α) := pi.has_scalar instance {β : Type w} [semiring α] [add_comm_monoid β] [semimodule α β] : semimodule α (matrix m n β) := pi.semimodule _ _ _ @[simp] lemma smul_apply [semiring α] (a : α) (A : matrix m n α) (i : m) (j : n) : (a • A) i j = a * A i j := rfl section semiring variables [semiring α] lemma smul_eq_diagonal_mul [decidable_eq m] (M : matrix m n α) (a : α) : a • M = diagonal (λ _, a) ⬝ M := by { ext, simp } @[simp] lemma smul_mul (M : matrix m n α) (a : α) (N : matrix n l α) : (a • M) ⬝ N = a • M ⬝ N := by { ext, apply smul_dot_product } @[simp] lemma mul_mul_left (M : matrix m n α) (N : matrix n o α) (a : α) : (λ i j, a * M i j) ⬝ N = a • (M ⬝ N) := begin simp only [←smul_apply], simp, end /-- The ring homomorphism `α →+* matrix n n α` sending `a` to the diagonal matrix with `a` on the diagonal. -/ def scalar (n : Type u) [decidable_eq n] [fintype n] : α →+* matrix n n α := { to_fun := λ a, a • 1, map_zero' := by simp, map_add' := by { intros, ext, simp [add_mul], }, map_one' := by simp, map_mul' := by { intros, ext, simp [mul_assoc], }, } section scalar variable [decidable_eq n] @[simp] lemma coe_scalar : (scalar n : α → matrix n n α) = λ a, a • 1 := rfl lemma scalar_apply_eq (a : α) (i : n) : scalar n a i i = a := by simp only [coe_scalar, mul_one, one_apply_eq, smul_apply] lemma scalar_apply_ne (a : α) (i j : n) (h : i ≠ j) : scalar n a i j = 0 := by simp only [h, coe_scalar, one_apply_ne, ne.def, not_false_iff, smul_apply, mul_zero] lemma scalar_inj [nonempty n] {r s : α} : scalar n r = scalar n s ↔ r = s := begin split, { intro h, inhabit n, rw [← scalar_apply_eq r (arbitrary n), ← scalar_apply_eq s (arbitrary n), h] }, { rintro rfl, refl } end end scalar end semiring section comm_semiring variables [comm_semiring α] lemma smul_eq_mul_diagonal [decidable_eq n] (M : matrix m n α) (a : α) : a • M = M ⬝ diagonal (λ _, a) := by { ext, simp [mul_comm] } @[simp] lemma mul_smul (M : matrix m n α) (a : α) (N : matrix n l α) : M ⬝ (a • N) = a • M ⬝ N := by { ext, apply dot_product_smul } @[simp] lemma mul_mul_right (M : matrix m n α) (N : matrix n o α) (a : α) : M ⬝ (λ i j, a * N i j) = a • (M ⬝ N) := begin simp only [←smul_apply], simp, end lemma scalar.commute [decidable_eq n] (r : α) (M : matrix n n α) : commute (scalar n r) M := by simp [commute, semiconj_by] end comm_semiring section semiring variables [semiring α] /-- For two vectors `w` and `v`, `vec_mul_vec w v i j` is defined to be `w i * v j`. Put another way, `vec_mul_vec w v` is exactly `col w ⬝ row v`. -/ def vec_mul_vec (w : m → α) (v : n → α) : matrix m n α | x y := w x * v y /-- `mul_vec M v` is the matrix-vector product of `M` and `v`, where `v` is seen as a column matrix. Put another way, `mul_vec M v` is the vector whose entries are those of `M ⬝ col v` (see `col_mul_vec`). -/ def mul_vec (M : matrix m n α) (v : n → α) : m → α | i := dot_product (λ j, M i j) v /-- `vec_mul v M` is the vector-matrix product of `v` and `M`, where `v` is seen as a row matrix. Put another way, `vec_mul v M` is the vector whose entries are those of `row v ⬝ M` (see `row_vec_mul`). -/ def vec_mul (v : m → α) (M : matrix m n α) : n → α | j := dot_product v (λ i, M i j) instance mul_vec.is_add_monoid_hom_left (v : n → α) : is_add_monoid_hom (λM:matrix m n α, mul_vec M v) := { map_zero := by ext; simp [mul_vec]; refl, map_add := begin intros x y, ext m, apply add_dot_product end } lemma mul_vec_diagonal [decidable_eq m] (v w : m → α) (x : m) : mul_vec (diagonal v) w x = v x * w x := diagonal_dot_product v w x lemma vec_mul_diagonal [decidable_eq m] (v w : m → α) (x : m) : vec_mul v (diagonal w) x = v x * w x := dot_product_diagonal' v w x @[simp] lemma mul_vec_one [decidable_eq m] (v : m → α) : mul_vec 1 v = v := by { ext, rw [←diagonal_one, mul_vec_diagonal, one_mul] } @[simp] lemma vec_mul_one [decidable_eq m] (v : m → α) : vec_mul v 1 = v := by { ext, rw [←diagonal_one, vec_mul_diagonal, mul_one] } @[simp] lemma mul_vec_zero (A : matrix m n α) : mul_vec A 0 = 0 := by { ext, simp [mul_vec] } @[simp] lemma vec_mul_zero (A : matrix m n α) : vec_mul 0 A = 0 := by { ext, simp [vec_mul] } @[simp] lemma vec_mul_vec_mul (v : m → α) (M : matrix m n α) (N : matrix n o α) : vec_mul (vec_mul v M) N = vec_mul v (M ⬝ N) := by { ext, apply dot_product_assoc } @[simp] lemma mul_vec_mul_vec (v : o → α) (M : matrix m n α) (N : matrix n o α) : mul_vec M (mul_vec N v) = mul_vec (M ⬝ N) v := by { ext, symmetry, apply dot_product_assoc } lemma vec_mul_vec_eq (w : m → α) (v : n → α) : vec_mul_vec w v = (col w) ⬝ (row v) := by { ext i j, simp [vec_mul_vec, mul_apply], refl } variables [decidable_eq m] [decidable_eq n] /-- `std_basis_matrix i j a` is the matrix with `a` in the `i`-th row, `j`-th column, and zeroes elsewhere. -/ def std_basis_matrix (i : m) (j : n) (a : α) : matrix m n α := (λ i' j', if i' = i ∧ j' = j then a else 0) @[simp] lemma smul_std_basis_matrix (i : m) (j : n) (a b : α) : b • std_basis_matrix i j a = std_basis_matrix i j (b • a) := by { unfold std_basis_matrix, ext, simp } @[simp] lemma std_basis_matrix_zero (i : m) (j : n) : std_basis_matrix i j (0 : α) = 0 := by { unfold std_basis_matrix, ext, simp } lemma std_basis_matrix_add (i : m) (j : n) (a b : α) : std_basis_matrix i j (a + b) = std_basis_matrix i j a + std_basis_matrix i j b := begin unfold std_basis_matrix, ext, split_ifs with h; simp [h], end lemma matrix_eq_sum_std_basis (x : matrix n m α) : x = ∑ (i : n) (j : m), std_basis_matrix i j (x i j) := begin ext, iterate 2 {rw finset.sum_apply}, rw ← finset.sum_subset, swap 4, exact {i}, { norm_num [std_basis_matrix] }, { simp }, intros, norm_num at a, norm_num, convert finset.sum_const_zero, ext, norm_num [std_basis_matrix], rw if_neg, tauto!, end -- TODO: tie this up with the `basis` machinery of linear algebra -- this is not completely trivial because we are indexing by two types, instead of one -- TODO: add `std_basis_vec` lemma std_basis_eq_basis_mul_basis (i : m) (j : n) : std_basis_matrix i j 1 = vec_mul_vec (λ i', ite (i = i') 1 0) (λ j', ite (j = j') 1 0) := begin ext, norm_num [std_basis_matrix, vec_mul_vec], split_ifs; tauto, end @[elab_as_eliminator] protected lemma induction_on' {X : Type*} [semiring X] {M : matrix n n X → Prop} (m : matrix n n X) (h_zero : M 0) (h_add : ∀p q, M p → M q → M (p + q)) (h_std_basis : ∀ i j x, M (std_basis_matrix i j x)) : M m := begin rw [matrix_eq_sum_std_basis m, ← finset.sum_product'], apply finset.sum_induction _ _ h_add h_zero, { intros, apply h_std_basis, } end @[elab_as_eliminator] protected lemma induction_on [nonempty n] {X : Type*} [semiring X] {M : matrix n n X → Prop} (m : matrix n n X) (h_add : ∀p q, M p → M q → M (p + q)) (h_std_basis : ∀ i j x, M (std_basis_matrix i j x)) : M m := matrix.induction_on' m begin have i : n := classical.choice (by assumption), simpa using h_std_basis i i 0, end h_add h_std_basis end semiring section ring variables [ring α] lemma neg_vec_mul (v : m → α) (A : matrix m n α) : vec_mul (-v) A = - vec_mul v A := by { ext, apply neg_dot_product } lemma vec_mul_neg (v : m → α) (A : matrix m n α) : vec_mul v (-A) = - vec_mul v A := by { ext, apply dot_product_neg } lemma neg_mul_vec (v : n → α) (A : matrix m n α) : mul_vec (-A) v = - mul_vec A v := by { ext, apply neg_dot_product } lemma mul_vec_neg (v : n → α) (A : matrix m n α) : mul_vec A (-v) = - mul_vec A v := by { ext, apply dot_product_neg } end ring section transpose open_locale matrix /-- Tell `simp` what the entries are in a transposed matrix. Compare with `mul_apply`, `diagonal_apply_eq`, etc. -/ @[simp] lemma transpose_apply (M : matrix m n α) (i j) : M.transpose j i = M i j := rfl @[simp] lemma transpose_transpose (M : matrix m n α) : Mᵀᵀ = M := by ext; refl @[simp] lemma transpose_zero [has_zero α] : (0 : matrix m n α)ᵀ = 0 := by ext i j; refl @[simp] lemma transpose_one [decidable_eq n] [has_zero α] [has_one α] : (1 : matrix n n α)ᵀ = 1 := begin ext i j, unfold has_one.one transpose, by_cases i = j, { simp only [h, diagonal_apply_eq] }, { simp only [diagonal_apply_ne h, diagonal_apply_ne (λ p, h (symm p))] } end @[simp] lemma transpose_add [has_add α] (M : matrix m n α) (N : matrix m n α) : (M + N)ᵀ = Mᵀ + Nᵀ := by { ext i j, simp } @[simp] lemma transpose_sub [add_group α] (M : matrix m n α) (N : matrix m n α) : (M - N)ᵀ = Mᵀ - Nᵀ := by { ext i j, simp } @[simp] lemma transpose_mul [comm_semiring α] (M : matrix m n α) (N : matrix n l α) : (M ⬝ N)ᵀ = Nᵀ ⬝ Mᵀ := begin ext i j, apply dot_product_comm end @[simp] lemma transpose_smul [semiring α] (c : α) (M : matrix m n α) : (c • M)ᵀ = c • Mᵀ := by { ext i j, refl } @[simp] lemma transpose_neg [has_neg α] (M : matrix m n α) : (- M)ᵀ = - Mᵀ := by ext i j; refl lemma transpose_map {β : Type w} {f : α → β} {M : matrix m n α} : Mᵀ.map f = (M.map f)ᵀ := by { ext, refl } end transpose /-- `M.minor row col` is the matrix obtained by reindexing the rows and the lines of `M`, such that `M.minor row col i j = M (row i) (col j)`. Note that the total number of row/colums doesn't have to be preserved. -/ def minor (A : matrix m n α) (row : l → m) (col : o → n) : matrix l o α := λ i j, A (row i) (col j) /-- The left `n × l` part of a `n × (l+r)` matrix. -/ @[reducible] def sub_left {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin l) α := minor A id (fin.cast_add r) /-- The right `n × r` part of a `n × (l+r)` matrix. -/ @[reducible] def sub_right {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin r) α := minor A id (fin.nat_add l) /-- The top `u × n` part of a `(u+d) × n` matrix. -/ @[reducible] def sub_up {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin u) (fin n) α := minor A (fin.cast_add d) id /-- The bottom `d × n` part of a `(u+d) × n` matrix. -/ @[reducible] def sub_down {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin d) (fin n) α := minor A (fin.nat_add u) id /-- The top-right `u × r` part of a `(u+d) × (l+r)` matrix. -/ @[reducible] def sub_up_right {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin u) (fin r) α := sub_up (sub_right A) /-- The bottom-right `d × r` part of a `(u+d) × (l+r)` matrix. -/ @[reducible] def sub_down_right {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin d) (fin r) α := sub_down (sub_right A) /-- The top-left `u × l` part of a `(u+d) × (l+r)` matrix. -/ @[reducible] def sub_up_left {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin u) (fin (l)) α := sub_up (sub_left A) /-- The bottom-left `d × l` part of a `(u+d) × (l+r)` matrix. -/ @[reducible] def sub_down_left {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin d) (fin (l)) α := sub_down (sub_left A) section row_col /-! ### `row_col` section Simplification lemmas for `matrix.row` and `matrix.col`. -/ open_locale matrix @[simp] lemma col_add [semiring α] (v w : m → α) : col (v + w) = col v + col w := by { ext, refl } @[simp] lemma col_smul [semiring α] (x : α) (v : m → α) : col (x • v) = x • col v := by { ext, refl } @[simp] lemma row_add [semiring α] (v w : m → α) : row (v + w) = row v + row w := by { ext, refl } @[simp] lemma row_smul [semiring α] (x : α) (v : m → α) : row (x • v) = x • row v := by { ext, refl } @[simp] lemma col_apply (v : m → α) (i j) : matrix.col v i j = v i := rfl @[simp] lemma row_apply (v : m → α) (i j) : matrix.row v i j = v j := rfl @[simp] lemma transpose_col (v : m → α) : (matrix.col v).transpose = matrix.row v := by {ext, refl} @[simp] lemma transpose_row (v : m → α) : (matrix.row v).transpose = matrix.col v := by {ext, refl} lemma row_vec_mul [semiring α] (M : matrix m n α) (v : m → α) : matrix.row (matrix.vec_mul v M) = matrix.row v ⬝ M := by {ext, refl} lemma col_vec_mul [semiring α] (M : matrix m n α) (v : m → α) : matrix.col (matrix.vec_mul v M) = (matrix.row v ⬝ M)ᵀ := by {ext, refl} lemma col_mul_vec [semiring α] (M : matrix m n α) (v : n → α) : matrix.col (matrix.mul_vec M v) = M ⬝ matrix.col v := by {ext, refl} lemma row_mul_vec [semiring α] (M : matrix m n α) (v : n → α) : matrix.row (matrix.mul_vec M v) = (M ⬝ matrix.col v)ᵀ := by {ext, refl} end row_col section update /-- Update, i.e. replace the `i`th row of matrix `A` with the values in `b`. -/ def update_row [decidable_eq n] (M : matrix n m α) (i : n) (b : m → α) : matrix n m α := function.update M i b /-- Update, i.e. replace the `i`th column of matrix `A` with the values in `b`. -/ def update_column [decidable_eq m] (M : matrix n m α) (j : m) (b : n → α) : matrix n m α := λ i, function.update (M i) j (b i) variables {M : matrix n m α} {i : n} {j : m} {b : m → α} {c : n → α} @[simp] lemma update_row_self [decidable_eq n] : update_row M i b i = b := function.update_same i b M @[simp] lemma update_column_self [decidable_eq m] : update_column M j c i j = c i := function.update_same j (c i) (M i) @[simp] lemma update_row_ne [decidable_eq n] {i' : n} (i_ne : i' ≠ i) : update_row M i b i' = M i' := function.update_noteq i_ne b M @[simp] lemma update_column_ne [decidable_eq m] {j' : m} (j_ne : j' ≠ j) : update_column M j c i j' = M i j' := function.update_noteq j_ne (c i) (M i) lemma update_row_apply [decidable_eq n] {i' : n} : update_row M i b i' j = if i' = i then b j else M i' j := begin by_cases i' = i, { rw [h, update_row_self, if_pos rfl] }, { rwa [update_row_ne h, if_neg h] } end lemma update_column_apply [decidable_eq m] {j' : m} : update_column M j c i j' = if j' = j then c i else M i j' := begin by_cases j' = j, { rw [h, update_column_self, if_pos rfl] }, { rwa [update_column_ne h, if_neg h] } end lemma update_row_transpose [decidable_eq m] : update_row Mᵀ j c = (update_column M j c)ᵀ := begin ext i' j, rw [transpose_apply, update_row_apply, update_column_apply], refl end lemma update_column_transpose [decidable_eq n] : update_column Mᵀ i b = (update_row M i b)ᵀ := begin ext i' j, rw [transpose_apply, update_row_apply, update_column_apply], refl end end update section block_matrices /-- We can form a single large matrix by flattening smaller 'block' matrices of compatible dimensions. -/ def from_blocks (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : matrix (n ⊕ o) (l ⊕ m) α := sum.elim (λ i, sum.elim (A i) (B i)) (λ i, sum.elim (C i) (D i)) @[simp] lemma from_blocks_apply₁₁ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) (i : n) (j : l) : from_blocks A B C D (sum.inl i) (sum.inl j) = A i j := rfl @[simp] lemma from_blocks_apply₁₂ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) (i : n) (j : m) : from_blocks A B C D (sum.inl i) (sum.inr j) = B i j := rfl @[simp] lemma from_blocks_apply₂₁ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) (i : o) (j : l) : from_blocks A B C D (sum.inr i) (sum.inl j) = C i j := rfl @[simp] lemma from_blocks_apply₂₂ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) (i : o) (j : m) : from_blocks A B C D (sum.inr i) (sum.inr j) = D i j := rfl /-- Given a matrix whose row and column indexes are sum types, we can extract the correspnding "top left" submatrix. -/ def to_blocks₁₁ (M : matrix (n ⊕ o) (l ⊕ m) α) : matrix n l α := λ i j, M (sum.inl i) (sum.inl j) /-- Given a matrix whose row and column indexes are sum types, we can extract the correspnding "top right" submatrix. -/ def to_blocks₁₂ (M : matrix (n ⊕ o) (l ⊕ m) α) : matrix n m α := λ i j, M (sum.inl i) (sum.inr j) /-- Given a matrix whose row and column indexes are sum types, we can extract the correspnding "bottom left" submatrix. -/ def to_blocks₂₁ (M : matrix (n ⊕ o) (l ⊕ m) α) : matrix o l α := λ i j, M (sum.inr i) (sum.inl j) /-- Given a matrix whose row and column indexes are sum types, we can extract the correspnding "bottom right" submatrix. -/ def to_blocks₂₂ (M : matrix (n ⊕ o) (l ⊕ m) α) : matrix o m α := λ i j, M (sum.inr i) (sum.inr j) lemma from_blocks_to_blocks (M : matrix (n ⊕ o) (l ⊕ m) α) : from_blocks M.to_blocks₁₁ M.to_blocks₁₂ M.to_blocks₂₁ M.to_blocks₂₂ = M := begin ext i j, rcases i; rcases j; refl, end @[simp] lemma to_blocks_from_blocks₁₁ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : (from_blocks A B C D).to_blocks₁₁ = A := rfl @[simp] lemma to_blocks_from_blocks₁₂ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : (from_blocks A B C D).to_blocks₁₂ = B := rfl @[simp] lemma to_blocks_from_blocks₂₁ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : (from_blocks A B C D).to_blocks₂₁ = C := rfl @[simp] lemma to_blocks_from_blocks₂₂ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : (from_blocks A B C D).to_blocks₂₂ = D := rfl lemma from_blocks_transpose (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : (from_blocks A B C D)ᵀ = from_blocks Aᵀ Cᵀ Bᵀ Dᵀ := begin ext i j, rcases i; rcases j; simp [from_blocks], end variables [semiring α] lemma from_blocks_smul (x : α) (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : x • (from_blocks A B C D) = from_blocks (x • A) (x • B) (x • C) (x • D) := begin ext i j, rcases i; rcases j; simp [from_blocks], end lemma from_blocks_add (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) (A' : matrix n l α) (B' : matrix n m α) (C' : matrix o l α) (D' : matrix o m α) : (from_blocks A B C D) + (from_blocks A' B' C' D') = from_blocks (A + A') (B + B') (C + C') (D + D') := begin ext i j, rcases i; rcases j; refl, end lemma from_blocks_multiply {p q : Type*} [fintype p] [fintype q] (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) (A' : matrix l p α) (B' : matrix l q α) (C' : matrix m p α) (D' : matrix m q α) : (from_blocks A B C D) ⬝ (from_blocks A' B' C' D') = from_blocks (A ⬝ A' + B ⬝ C') (A ⬝ B' + B ⬝ D') (C ⬝ A' + D ⬝ C') (C ⬝ B' + D ⬝ D') := begin ext i j, rcases i; rcases j; simp only [from_blocks, mul_apply, fintype.sum_sum_type, sum.elim_inl, sum.elim_inr, pi.add_apply], end variables [decidable_eq l] [decidable_eq m] @[simp] lemma from_blocks_diagonal (d₁ : l → α) (d₂ : m → α) : from_blocks (diagonal d₁) 0 0 (diagonal d₂) = diagonal (sum.elim d₁ d₂) := begin ext i j, rcases i; rcases j; simp [diagonal], end @[simp] lemma from_blocks_one : from_blocks (1 : matrix l l α) 0 0 (1 : matrix m m α) = 1 := by { ext i j, rcases i; rcases j; simp [one_apply] } end block_matrices section block_diagonal variables (M N : o → matrix m n α) [decidable_eq o] section has_zero variables [has_zero α] /-- `matrix.block_diagonal M` turns `M : o → matrix m n α'` into a `m × o`-by`n × o` block matrix which has the entries of `M` along the diagonal and zero elsewhere. -/ def block_diagonal : matrix (m × o) (n × o) α | ⟨i, k⟩ ⟨j, k'⟩ := if k = k' then M k i j else 0 lemma block_diagonal_apply (ik jk) : block_diagonal M ik jk = if ik.2 = jk.2 then M ik.2 ik.1 jk.1 else 0 := by { cases ik, cases jk, refl } @[simp] lemma block_diagonal_apply_eq (i j k) : block_diagonal M (i, k) (j, k) = M k i j := if_pos rfl lemma block_diagonal_apply_ne (i j) {k k'} (h : k ≠ k') : block_diagonal M (i, k) (j, k') = 0 := if_neg h @[simp] lemma block_diagonal_transpose : (block_diagonal M)ᵀ = (block_diagonal (λ k, (M k)ᵀ)) := begin ext, simp only [transpose_apply, block_diagonal_apply, eq_comm], split_ifs with h, { rw h }, { refl } end @[simp] lemma block_diagonal_zero : block_diagonal (0 : o → matrix m n α) = 0 := by { ext, simp [block_diagonal_apply] } @[simp] lemma block_diagonal_diagonal [decidable_eq m] (d : o → m → α) : (block_diagonal (λ k, diagonal (d k))) = diagonal (λ ik, d ik.2 ik.1) := begin ext ⟨i, k⟩ ⟨j, k'⟩, simp only [block_diagonal_apply, diagonal], split_ifs; finish end @[simp] lemma block_diagonal_one [decidable_eq m] [has_one α] : (block_diagonal (1 : o → matrix m m α)) = 1 := show (block_diagonal (λ (_ : o), diagonal (λ (_ : m), (1 : α)))) = diagonal (λ _, 1), by rw [block_diagonal_diagonal] end has_zero @[simp] lemma block_diagonal_add [add_monoid α] : block_diagonal (M + N) = block_diagonal M + block_diagonal N := begin ext, simp only [block_diagonal_apply, add_apply], split_ifs; simp end @[simp] lemma block_diagonal_neg [add_group α] : block_diagonal (-M) = - block_diagonal M := begin ext, simp only [block_diagonal_apply, neg_apply], split_ifs; simp end @[simp] lemma block_diagonal_sub [add_group α] : block_diagonal (M - N) = block_diagonal M - block_diagonal N := by simp [sub_eq_add_neg] @[simp] lemma block_diagonal_mul {p : Type*} [fintype p] [semiring α] (N : o → matrix n p α) : block_diagonal (λ k, M k ⬝ N k) = block_diagonal M ⬝ block_diagonal N := begin ext ⟨i, k⟩ ⟨j, k'⟩, simp only [block_diagonal_apply, mul_apply, ← finset.univ_product_univ, finset.sum_product], split_ifs with h; simp [h] end @[simp] lemma block_diagonal_smul {R : Type*} [semiring R] [add_comm_monoid α] [semimodule R α] (x : R) : block_diagonal (x • M) = x • block_diagonal M := by { ext, simp only [block_diagonal_apply, pi.smul_apply, smul_apply], split_ifs; simp } end block_diagonal end matrix namespace ring_hom variables {β : Type*} [semiring α] [semiring β] lemma map_matrix_mul (M : matrix m n α) (N : matrix n o α) (i : m) (j : o) (f : α →+* β) : f (matrix.mul M N i j) = matrix.mul (λ i j, f (M i j)) (λ i j, f (N i j)) i j := by simp [matrix.mul_apply, ring_hom.map_sum] end ring_hom
260a9fcd401b9a4410302c33ebbd01626dd0f4fa
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/topology/metric_space/gromov_hausdorff_realized.lean
d6e39096a3aec82516ba9f23ac4e5ffe7602c7e1
[ "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
26,258
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sébastien Gouëzel Construction of a good coupling between nonempty compact metric spaces, minimizing their Hausdorff distance. This construction is instrumental to study the Gromov-Hausdorff distance between nonempty compact metric spaces -/ import topology.metric_space.gluing import topology.metric_space.hausdorff_distance noncomputable theory open_locale classical open_locale topological_space universes u v w open classical set function topological_space filter metric quotient open bounded_continuous_function open sum (inl inr) local attribute [instance] metric_space_sum namespace Gromov_Hausdorff section Gromov_Hausdorff_realized /- This section shows that the Gromov-Hausdorff distance is realized. For this, we consider candidate distances on the disjoint union α ⊕ β of two compact nonempty metric spaces, almost realizing the Gromov-Hausdorff distance, and show that they form a compact family by applying Arzela-Ascoli theorem. The existence of a minimizer follows. -/ section definitions variables (α : Type u) (β : Type v) [metric_space α] [compact_space α] [nonempty α] [metric_space β] [compact_space β] [nonempty β] @[reducible] private def prod_space_fun : Type* := ((α ⊕ β) × (α ⊕ β)) → ℝ @[reducible] private def Cb : Type* := bounded_continuous_function ((α ⊕ β) × (α ⊕ β)) ℝ private def max_var : nnreal := 2 * ⟨diam (univ : set α), diam_nonneg⟩ + 1 + 2 * ⟨diam (univ : set β), diam_nonneg⟩ private lemma one_le_max_var : 1 ≤ max_var α β := calc (1 : real) = 2 * 0 + 1 + 2 * 0 : by simp ... ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : by apply_rules [add_le_add, mul_le_mul_of_nonneg_left, diam_nonneg]; norm_num /-- The set of functions on α ⊕ β that are candidates distances to realize the minimum of the Hausdorff distances between α and β in a coupling -/ def candidates : set (prod_space_fun α β) := {f | (((((∀x y : α, f (sum.inl x, sum.inl y) = dist x y) ∧ (∀x y : β, f (sum.inr x, sum.inr y) = dist x y)) ∧ (∀x y, f (x, y) = f (y, x))) ∧ (∀x y z, f (x, z) ≤ f (x, y) + f (y, z))) ∧ (∀x, f (x, x) = 0)) ∧ (∀x y, f (x, y) ≤ max_var α β) } /-- Version of the set of candidates in bounded_continuous_functions, to apply Arzela-Ascoli -/ private def candidates_b : set (Cb α β) := {f : Cb α β | f.val ∈ candidates α β} end definitions --section section constructions variables {α : Type u} {β : Type v} [metric_space α] [compact_space α] [nonempty α] [metric_space β] [compact_space β] [nonempty β] {f : prod_space_fun α β} {x y z t : α ⊕ β} local attribute [instance, priority 10] inhabited_of_nonempty' private lemma max_var_bound : dist x y ≤ max_var α β := calc dist x y ≤ diam (univ : set (α ⊕ β)) : dist_le_diam_of_mem (bounded_of_compact compact_univ) (mem_univ _) (mem_univ _) ... = diam (inl '' (univ : set α) ∪ inr '' (univ : set β)) : by apply congr_arg; ext x y z; cases x; simp [mem_univ, mem_range_self] ... ≤ diam (inl '' (univ : set α)) + dist (inl (default α)) (inr (default β)) + diam (inr '' (univ : set β)) : diam_union (mem_image_of_mem _ (mem_univ _)) (mem_image_of_mem _ (mem_univ _)) ... = diam (univ : set α) + (dist (default α) (default α) + 1 + dist (default β) (default β)) + diam (univ : set β) : by { rw [isometry_on_inl.diam_image, isometry_on_inr.diam_image], refl } ... = 1 * diam (univ : set α) + 1 + 1 * diam (univ : set β) : by simp ... ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : begin apply_rules [add_le_add, mul_le_mul_of_nonneg_right, diam_nonneg, le_refl], norm_num, norm_num end private lemma candidates_symm (fA : f ∈ candidates α β) : f (x, y) = f (y ,x) := fA.1.1.1.2 x y private lemma candidates_triangle (fA : f ∈ candidates α β) : f (x, z) ≤ f (x, y) + f (y, z) := fA.1.1.2 x y z private lemma candidates_refl (fA : f ∈ candidates α β) : f (x, x) = 0 := fA.1.2 x private lemma candidates_nonneg (fA : f ∈ candidates α β) : 0 ≤ f (x, y) := begin have : 0 ≤ 2 * f (x, y) := calc 0 = f (x, x) : (candidates_refl fA).symm ... ≤ f (x, y) + f (y, x) : candidates_triangle fA ... = f (x, y) + f (x, y) : by rw [candidates_symm fA] ... = 2 * f (x, y) : by ring, by linarith end private lemma candidates_dist_inl (fA : f ∈ candidates α β) (x y: α) : f (inl x, inl y) = dist x y := fA.1.1.1.1.1 x y private lemma candidates_dist_inr (fA : f ∈ candidates α β) (x y : β) : f (inr x, inr y) = dist x y := fA.1.1.1.1.2 x y private lemma candidates_le_max_var (fA : f ∈ candidates α β) : f (x, y) ≤ max_var α β := fA.2 x y /-- candidates are bounded by max_var α β -/ private lemma candidates_dist_bound (fA : f ∈ candidates α β) : ∀ {x y : α ⊕ β}, f (x, y) ≤ max_var α β * dist x y | (inl x) (inl y) := calc f (inl x, inl y) = dist x y : candidates_dist_inl fA x y ... = dist (inl x) (inl y) : by { rw @sum.dist_eq α β, refl } ... = 1 * dist (inl x) (inl y) : by simp ... ≤ max_var α β * dist (inl x) (inl y) : mul_le_mul_of_nonneg_right (one_le_max_var α β) dist_nonneg | (inl x) (inr y) := calc f (inl x, inr y) ≤ max_var α β : candidates_le_max_var fA ... = max_var α β * 1 : by simp ... ≤ max_var α β * dist (inl x) (inr y) : mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var α β)) | (inr x) (inl y) := calc f (inr x, inl y) ≤ max_var α β : candidates_le_max_var fA ... = max_var α β * 1 : by simp ... ≤ max_var α β * dist (inl x) (inr y) : mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var α β)) | (inr x) (inr y) := calc f (inr x, inr y) = dist x y : candidates_dist_inr fA x y ... = dist (inr x) (inr y) : by { rw @sum.dist_eq α β, refl } ... = 1 * dist (inr x) (inr y) : by simp ... ≤ max_var α β * dist (inr x) (inr y) : mul_le_mul_of_nonneg_right (one_le_max_var α β) dist_nonneg /-- Technical lemma to prove that candidates are Lipschitz -/ private lemma candidates_lipschitz_aux (fA : f ∈ candidates α β) : f (x, y) - f (z, t) ≤ 2 * max_var α β * dist (x, y) (z, t) := calc f (x, y) - f(z, t) ≤ f (x, t) + f (t, y) - f (z, t) : add_le_add_right (candidates_triangle fA) _ ... ≤ (f (x, z) + f (z, t) + f(t, y)) - f (z, t) : add_le_add_right (add_le_add_right (candidates_triangle fA) _ ) _ ... = f (x, z) + f (t, y) : by simp [sub_eq_add_neg, add_assoc] ... ≤ max_var α β * dist x z + max_var α β * dist t y : add_le_add (candidates_dist_bound fA) (candidates_dist_bound fA) ... ≤ max_var α β * max (dist x z) (dist t y) + max_var α β * max (dist x z) (dist t y) : begin apply add_le_add, apply mul_le_mul_of_nonneg_left (le_max_left (dist x z) (dist t y)) (le_trans zero_le_one (one_le_max_var α β)), apply mul_le_mul_of_nonneg_left (le_max_right (dist x z) (dist t y)) (le_trans zero_le_one (one_le_max_var α β)), end ... = 2 * max_var α β * max (dist x z) (dist y t) : by { simp [dist_comm], ring } ... = 2 * max_var α β * dist (x, y) (z, t) : by refl /-- Candidates are Lipschitz -/ private lemma candidates_lipschitz (fA : f ∈ candidates α β) : lipschitz_with (2 * max_var α β) f := begin apply lipschitz_with.of_dist_le_mul, rintros ⟨x, y⟩ ⟨z, t⟩, rw real.dist_eq, apply abs_le_of_le_of_neg_le, { exact candidates_lipschitz_aux fA }, { have : -(f (x, y) - f (z, t)) = f (z, t) - f (x, y), by ring, rw [this, dist_comm], exact candidates_lipschitz_aux fA } end /-- candidates give rise to elements of bounded_continuous_functions -/ def candidates_b_of_candidates (f : prod_space_fun α β) (fA : f ∈ candidates α β) : Cb α β := bounded_continuous_function.mk_of_compact f (candidates_lipschitz fA).continuous lemma candidates_b_of_candidates_mem (f : prod_space_fun α β) (fA : f ∈ candidates α β) : candidates_b_of_candidates f fA ∈ candidates_b α β := fA /-- The distance on α ⊕ β is a candidate -/ private lemma dist_mem_candidates : (λp : (α ⊕ β) × (α ⊕ β), dist p.1 p.2) ∈ candidates α β := begin simp only [candidates, dist_comm, forall_const, and_true, add_comm, eq_self_iff_true, and_self, sum.forall, set.mem_set_of_eq, dist_self], repeat { split <|> exact (λa y z, dist_triangle_left _ _ _) <|> exact (λx y, by refl) <|> exact (λx y, max_var_bound) } end def candidates_b_dist (α : Type u) (β : Type v) [metric_space α] [compact_space α] [inhabited α] [metric_space β] [compact_space β] [inhabited β] : Cb α β := candidates_b_of_candidates _ dist_mem_candidates lemma candidates_b_dist_mem_candidates_b : candidates_b_dist α β ∈ candidates_b α β := candidates_b_of_candidates_mem _ _ private lemma candidates_b_nonempty : (candidates_b α β).nonempty := ⟨_, candidates_b_dist_mem_candidates_b⟩ /-- To apply Arzela-Ascoli, we need to check that the set of candidates is closed and equicontinuous. Equicontinuity follows from the Lipschitz control, we check closedness -/ private lemma closed_candidates_b : is_closed (candidates_b α β) := begin have I1 : ∀x y, is_closed {f : Cb α β | f (inl x, inl y) = dist x y} := λx y, is_closed_eq continuous_evalx continuous_const, have I2 : ∀x y, is_closed {f : Cb α β | f (inr x, inr y) = dist x y } := λx y, is_closed_eq continuous_evalx continuous_const, have I3 : ∀x y, is_closed {f : Cb α β | f (x, y) = f (y, x)} := λx y, is_closed_eq continuous_evalx continuous_evalx, have I4 : ∀x y z, is_closed {f : Cb α β | f (x, z) ≤ f (x, y) + f (y, z)} := λx y z, is_closed_le continuous_evalx (continuous_evalx.add continuous_evalx), have I5 : ∀x, is_closed {f : Cb α β | f (x, x) = 0} := λx, is_closed_eq continuous_evalx continuous_const, have I6 : ∀x y, is_closed {f : Cb α β | f (x, y) ≤ max_var α β} := λx y, is_closed_le continuous_evalx continuous_const, have : candidates_b α β = (⋂x y, {f : Cb α β | f ((@inl α β x), (@inl α β y)) = dist x y}) ∩ (⋂x y, {f : Cb α β | f ((@inr α β x), (@inr α β y)) = dist x y}) ∩ (⋂x y, {f : Cb α β | f (x, y) = f (y, x)}) ∩ (⋂x y z, {f : Cb α β | f (x, z) ≤ f (x, y) + f (y, z)}) ∩ (⋂x, {f : Cb α β | f (x, x) = 0}) ∩ (⋂x y, {f : Cb α β | f (x, y) ≤ max_var α β}) := begin ext, unfold candidates_b, unfold candidates, simp [-sum.forall], refl end, rw this, repeat { apply is_closed_inter _ _ <|> apply is_closed_Inter _ <|> apply I1 _ _ <|> apply I2 _ _ <|> apply I3 _ _ <|> apply I4 _ _ _ <|> apply I5 _ <|> apply I6 _ _ <|> assume x }, end /-- Compactness of candidates (in bounded_continuous_functions) follows -/ private lemma compact_candidates_b : is_compact (candidates_b α β) := begin refine arzela_ascoli₂ (Icc 0 (max_var α β)) compact_Icc (candidates_b α β) closed_candidates_b _ _, { rintros f ⟨x1, x2⟩ hf, simp only [set.mem_Icc], exact ⟨candidates_nonneg hf, candidates_le_max_var hf⟩ }, { refine equicontinuous_of_continuity_modulus (λt, 2 * max_var α β * t) _ _ _, { have : tendsto (λ (t : ℝ), 2 * (max_var α β : ℝ) * t) (𝓝 0) (𝓝 (2 * max_var α β * 0)) := tendsto_const_nhds.mul tendsto_id, simpa using this }, { assume x y f hf, exact (candidates_lipschitz hf).dist_le_mul _ _ } } end /-- We will then choose the candidate minimizing the Hausdorff distance. Except that we are not in a metric space setting, so we need to define our custom version of Hausdorff distance, called HD, and prove its basic properties. -/ def HD (f : Cb α β) := max (⨆ x, ⨅ y, f (inl x, inr y)) (⨆ y, ⨅ x, f (inl x, inr y)) /- We will show that HD is continuous on bounded_continuous_functions, to deduce that its minimum on the compact set candidates_b is attained. Since it is defined in terms of infimum and supremum on ℝ, which is only conditionnally complete, we will need all the time to check that the defining sets are bounded below or above. This is done in the next few technical lemmas -/ lemma HD_below_aux1 {f : Cb α β} (C : ℝ) {x : α} : bdd_below (range (λ (y : β), f (inl x, inr y) + C)) := let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 in ⟨cf + C, forall_range_iff.2 (λi, add_le_add_right ((λx, hcf (mem_range_self x)) _) _)⟩ private lemma HD_bound_aux1 (f : Cb α β) (C : ℝ) : bdd_above (range (λ (x : α), ⨅ y, f (inl x, inr y) + C)) := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).2 with ⟨Cf, hCf⟩, refine ⟨Cf + C, forall_range_iff.2 (λx, _)⟩, calc (⨅ y, f (inl x, inr y) + C) ≤ f (inl x, inr (default β)) + C : cinfi_le (HD_below_aux1 C) (default β) ... ≤ Cf + C : add_le_add ((λx, hCf (mem_range_self x)) _) (le_refl _) end lemma HD_below_aux2 {f : Cb α β} (C : ℝ) {y : β} : bdd_below (range (λ (x : α), f (inl x, inr y) + C)) := let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 in ⟨cf + C, forall_range_iff.2 (λi, add_le_add_right ((λx, hcf (mem_range_self x)) _) _)⟩ private lemma HD_bound_aux2 (f : Cb α β) (C : ℝ) : bdd_above (range (λ (y : β), ⨅ x, f (inl x, inr y) + C)) := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).2 with ⟨Cf, hCf⟩, refine ⟨Cf + C, forall_range_iff.2 (λy, _)⟩, calc (⨅ x, f (inl x, inr y) + C) ≤ f (inl (default α), inr y) + C : cinfi_le (HD_below_aux2 C) (default α) ... ≤ Cf + C : add_le_add ((λx, hCf (mem_range_self x)) _) (le_refl _) end /-- Explicit bound on HD (dist). This means that when looking for minimizers it will be sufficient to look for functions with HD(f) bounded by this bound. -/ lemma HD_candidates_b_dist_le : HD (candidates_b_dist α β) ≤ diam (univ : set α) + 1 + diam (univ : set β) := begin refine max_le (csupr_le (λx, _)) (csupr_le (λy, _)), { have A : (⨅ y, candidates_b_dist α β (inl x, inr y)) ≤ candidates_b_dist α β (inl x, inr (default β)) := cinfi_le (by simpa using HD_below_aux1 0) (default β), have B : dist (inl x) (inr (default β)) ≤ diam (univ : set α) + 1 + diam (univ : set β) := calc dist (inl x) (inr (default β)) = dist x (default α) + 1 + dist (default β) (default β) : rfl ... ≤ diam (univ : set α) + 1 + diam (univ : set β) : begin apply add_le_add (add_le_add _ (le_refl _)), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _) end, exact le_trans A B }, { have A : (⨅ x, candidates_b_dist α β (inl x, inr y)) ≤ candidates_b_dist α β (inl (default α), inr y) := cinfi_le (by simpa using HD_below_aux2 0) (default α), have B : dist (inl (default α)) (inr y) ≤ diam (univ : set α) + 1 + diam (univ : set β) := calc dist (inl (default α)) (inr y) = dist (default α) (default α) + 1 + dist (default β) y : rfl ... ≤ diam (univ : set α) + 1 + diam (univ : set β) : begin apply add_le_add (add_le_add _ (le_refl _)), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _) end, exact le_trans A B }, end /- To check that HD is continuous, we check that it is Lipschitz. As HD is a max, we prove separately inequalities controlling the two terms (relying too heavily on copy-paste...) -/ private lemma HD_lipschitz_aux1 (f g : Cb α β) : (⨆ x, ⨅ y, f (inl x, inr y)) ≤ (⨆ x, ⨅ y, g (inl x, inr y)) + dist f g := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cg, hcg⟩, have Hcg : ∀x, cg ≤ g x := λx, hcg (mem_range_self x), rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cf, hcf⟩, have Hcf : ∀x, cf ≤ f x := λx, hcf (mem_range_self x), -- prove the inequality but with `dist f g` inside, by using inequalities comparing -- supr to supr and infi to infi have Z : (⨆ x, ⨅ y, f (inl x, inr y)) ≤ ⨆ x, ⨅ y, g (inl x, inr y) + dist f g := csupr_le_csupr (HD_bound_aux1 _ (dist f g)) (λx, cinfi_le_cinfi ⟨cf, forall_range_iff.2(λi, Hcf _)⟩ (λy, coe_le_coe_add_dist)), -- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps -- (here the addition of `dist f g`) preserve infimum and supremum have E1 : ∀x, (⨅ y, g (inl x, inr y)) + dist f g = ⨅ y, g (inl x, inr y) + dist f g, { assume x, refine map_cinfi_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { show bdd_below (range (λ (y : β), g (inl x, inr y))), from ⟨cg, forall_range_iff.2(λi, Hcg _)⟩ } }, have E2 : (⨆ x, ⨅ y, g (inl x, inr y)) + dist f g = ⨆ x, (⨅ y, g (inl x, inr y)) + dist f g, { refine map_csupr_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { by simpa using HD_bound_aux1 _ 0 } }, -- deduce the result from the above two steps simpa [E2, E1, function.comp] end private lemma HD_lipschitz_aux2 (f g : Cb α β) : (⨆ y, ⨅ x, f (inl x, inr y)) ≤ (⨆ y, ⨅ x, g (inl x, inr y)) + dist f g := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cg, hcg⟩, have Hcg : ∀x, cg ≤ g x := λx, hcg (mem_range_self x), rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cf, hcf⟩, have Hcf : ∀x, cf ≤ f x := λx, hcf (mem_range_self x), -- prove the inequality but with `dist f g` inside, by using inequalities comparing -- supr to supr and infi to infi have Z : (⨆ y, ⨅ x, f (inl x, inr y)) ≤ ⨆ y, ⨅ x, g (inl x, inr y) + dist f g := csupr_le_csupr (HD_bound_aux2 _ (dist f g)) (λy, cinfi_le_cinfi ⟨cf, forall_range_iff.2(λi, Hcf _)⟩ (λy, coe_le_coe_add_dist)), -- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps -- (here the addition of `dist f g`) preserve infimum and supremum have E1 : ∀y, (⨅ x, g (inl x, inr y)) + dist f g = ⨅ x, g (inl x, inr y) + dist f g, { assume y, refine map_cinfi_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { show bdd_below (range (λx:α, g (inl x, inr y))), from ⟨cg, forall_range_iff.2 (λi, Hcg _)⟩ } }, have E2 : (⨆ y, ⨅ x, g (inl x, inr y)) + dist f g = ⨆ y, (⨅ x, g (inl x, inr y)) + dist f g, { refine map_csupr_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { by simpa using HD_bound_aux2 _ 0 } }, -- deduce the result from the above two steps simpa [E2, E1] end private lemma HD_lipschitz_aux3 (f g : Cb α β) : HD f ≤ HD g + dist f g := max_le (le_trans (HD_lipschitz_aux1 f g) (add_le_add_right (le_max_left _ _) _)) (le_trans (HD_lipschitz_aux2 f g) (add_le_add_right (le_max_right _ _) _)) /-- Conclude that HD, being Lipschitz, is continuous -/ private lemma HD_continuous : continuous (HD : Cb α β → ℝ) := lipschitz_with.continuous (lipschitz_with.of_le_add HD_lipschitz_aux3) end constructions --section section consequences variables (α : Type u) (β : Type v) [metric_space α] [compact_space α] [nonempty α] [metric_space β] [compact_space β] [nonempty β] /- Now that we have proved that the set of candidates is compact, and that HD is continuous, we can finally select a candidate minimizing HD. This will be the candidate realizing the optimal coupling. -/ private lemma exists_minimizer : ∃f ∈ candidates_b α β, ∀g ∈ candidates_b α β, HD f ≤ HD g := compact_candidates_b.exists_forall_le candidates_b_nonempty HD_continuous.continuous_on private definition optimal_GH_dist : Cb α β := classical.some (exists_minimizer α β) private lemma optimal_GH_dist_mem_candidates_b : optimal_GH_dist α β ∈ candidates_b α β := by cases (classical.some_spec (exists_minimizer α β)); assumption private lemma HD_optimal_GH_dist_le (g : Cb α β) (hg : g ∈ candidates_b α β) : HD (optimal_GH_dist α β) ≤ HD g := let ⟨Z1, Z2⟩ := classical.some_spec (exists_minimizer α β) in Z2 g hg /-- With the optimal candidate, construct a premetric space structure on α ⊕ β, on which the predistance is given by the candidate. Then, we will identify points at 0 predistance to obtain a genuine metric space -/ def premetric_optimal_GH_dist : premetric_space (α ⊕ β) := { dist := λp q, optimal_GH_dist α β (p, q), dist_self := λx, candidates_refl (optimal_GH_dist_mem_candidates_b α β), dist_comm := λx y, candidates_symm (optimal_GH_dist_mem_candidates_b α β), dist_triangle := λx y z, candidates_triangle (optimal_GH_dist_mem_candidates_b α β) } local attribute [instance] premetric_optimal_GH_dist premetric.dist_setoid /-- A metric space which realizes the optimal coupling between α and β -/ @[derive [metric_space]] definition optimal_GH_coupling : Type* := premetric.metric_quot (α ⊕ β) /-- Injection of α in the optimal coupling between α and β -/ def optimal_GH_injl (x : α) : optimal_GH_coupling α β := ⟦inl x⟧ /-- The injection of α in the optimal coupling between α and β is an isometry. -/ lemma isometry_optimal_GH_injl : isometry (optimal_GH_injl α β) := begin refine isometry_emetric_iff_metric.2 (λx y, _), change dist ⟦inl x⟧ ⟦inl y⟧ = dist x y, exact candidates_dist_inl (optimal_GH_dist_mem_candidates_b α β) _ _, end /-- Injection of β in the optimal coupling between α and β -/ def optimal_GH_injr (y : β) : optimal_GH_coupling α β := ⟦inr y⟧ /-- The injection of β in the optimal coupling between α and β is an isometry. -/ lemma isometry_optimal_GH_injr : isometry (optimal_GH_injr α β) := begin refine isometry_emetric_iff_metric.2 (λx y, _), change dist ⟦inr x⟧ ⟦inr y⟧ = dist x y, exact candidates_dist_inr (optimal_GH_dist_mem_candidates_b α β) _ _, end /-- The optimal coupling between two compact spaces α and β is still a compact space -/ instance compact_space_optimal_GH_coupling : compact_space (optimal_GH_coupling α β) := ⟨begin have : (univ : set (optimal_GH_coupling α β)) = (optimal_GH_injl α β '' univ) ∪ (optimal_GH_injr α β '' univ), { refine subset.antisymm (λxc hxc, _) (subset_univ _), rcases quotient.exists_rep xc with ⟨x, hx⟩, cases x; rw ← hx, { have : ⟦inl x⟧ = optimal_GH_injl α β x := rfl, rw this, exact mem_union_left _ (mem_image_of_mem _ (mem_univ _)) }, { have : ⟦inr x⟧ = optimal_GH_injr α β x := rfl, rw this, exact mem_union_right _ (mem_image_of_mem _ (mem_univ _)) } }, rw this, exact (compact_univ.image (isometry_optimal_GH_injl α β).continuous).union (compact_univ.image (isometry_optimal_GH_injr α β).continuous) end⟩ /-- For any candidate f, HD(f) is larger than or equal to the Hausdorff distance in the optimal coupling. This follows from the fact that HD of the optimal candidate is exactly the Hausdorff distance in the optimal coupling, although we only prove here the inequality we need. -/ lemma Hausdorff_dist_optimal_le_HD {f} (h : f ∈ candidates_b α β) : Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ HD f := begin refine le_trans (le_of_forall_le_of_dense (λr hr, _)) (HD_optimal_GH_dist_le α β f h), have A : ∀ x ∈ range (optimal_GH_injl α β), ∃ y ∈ range (optimal_GH_injr α β), dist x y ≤ r, { assume x hx, rcases mem_range.1 hx with ⟨z, hz⟩, rw ← hz, have I1 : (⨆ x, ⨅ y, optimal_GH_dist α β (inl x, inr y)) < r := lt_of_le_of_lt (le_max_left _ _) hr, have I2 : (⨅ y, optimal_GH_dist α β (inl z, inr y)) ≤ ⨆ x, ⨅ y, optimal_GH_dist α β (inl x, inr y) := le_cSup (by simpa using HD_bound_aux1 _ 0) (mem_range_self _), have I : (⨅ y, optimal_GH_dist α β (inl z, inr y)) < r := lt_of_le_of_lt I2 I1, rcases exists_lt_of_cInf_lt (range_nonempty _) I with ⟨r', r'range, hr'⟩, rcases mem_range.1 r'range with ⟨z', hz'⟩, existsi [optimal_GH_injr α β z', mem_range_self _], have : (optimal_GH_dist α β) (inl z, inr z') ≤ r := begin rw hz', exact le_of_lt hr' end, exact this }, refine Hausdorff_dist_le_of_mem_dist _ A _, { rcases exists_mem_of_nonempty α with ⟨xα, _⟩, have : optimal_GH_injl α β xα ∈ range (optimal_GH_injl α β) := mem_range_self _, rcases A _ this with ⟨y, yrange, hy⟩, exact le_trans dist_nonneg hy }, { assume y hy, rcases mem_range.1 hy with ⟨z, hz⟩, rw ← hz, have I1 : (⨆ y, ⨅ x, optimal_GH_dist α β (inl x, inr y)) < r := lt_of_le_of_lt (le_max_right _ _) hr, have I2 : (⨅ x, optimal_GH_dist α β (inl x, inr z)) ≤ ⨆ y, ⨅ x, optimal_GH_dist α β (inl x, inr y) := le_cSup (by simpa using HD_bound_aux2 _ 0) (mem_range_self _), have I : (⨅ x, optimal_GH_dist α β (inl x, inr z)) < r := lt_of_le_of_lt I2 I1, rcases exists_lt_of_cInf_lt (range_nonempty _) I with ⟨r', r'range, hr'⟩, rcases mem_range.1 r'range with ⟨z', hz'⟩, existsi [optimal_GH_injl α β z', mem_range_self _], have : (optimal_GH_dist α β) (inl z', inr z) ≤ r := begin rw hz', exact le_of_lt hr' end, rw dist_comm, exact this } end end consequences /- We are done with the construction of the optimal coupling -/ end Gromov_Hausdorff_realized end Gromov_Hausdorff
8cff4e1fa434adb973e44bd71101c3e637742869
36938939954e91f23dec66a02728db08a7acfcf9
/lean/deps/typed_smt2/src/galois/smt2/semantics.lean
b92caf90558ed2299f2b284d26a63e2bb6777c6c
[ "Apache-2.0" ]
permissive
pnwamk/reopt-vcg
f8b56dd0279392a5e1c6aee721be8138e6b558d3
c9f9f185fbefc25c36c4b506bbc85fd1a03c3b6d
refs/heads/master
1,631,145,017,772
1,593,549,019,000
1,593,549,143,000
254,191,418
0
0
null
1,586,377,077,000
1,586,377,077,000
null
UTF-8
Lean
false
false
4,297
lean
import galois.category.combinators import galois.category.except import galois.data.list import galois.data.rbmap import .interface ------------------------------------------------------------------------ -- Semantics namespace smt2 namespace semantics inductive binding : Type | declare_fun {} (nm:symbol) (args:list sort) (res:sort) : binding | define_fun (nm:symbol) (args:list (symbol × sort)) (res:sort) (rhs : term res) : binding /-- State built up so far in generating an SMT file -/ structure context : Type := -- Map of symbols created so far. TODO: (defined_symbols : rbmap symbol unit) -- List of bindings (bindings : list binding) -- Conjunction of all asserted propositions (asserted : list (term Bool)) -- List of propositions we called check_sat with; most recent first. (checked : list Prop) namespace context def initial : context := { defined_symbols := mk_rbmap _ _ , bindings := [] , asserted := [] , checked := [] } /-- Low-level utility that adds a binding. -/ def add_binding (b:binding) (s:context) : context := { s with bindings := b::s.bindings } end context end semantics def semantics : Type → Type := state_t semantics.context (except string) namespace semantics section local attribute [reducible] semantics instance : monad semantics := by apply_instance instance : monad_except string semantics := by apply_instance instance : monad_state context semantics := by apply_instance end universe u /-- Given a proposition @p@ that expects a model with the symbol in the binding @b@ defined, this calls p by adding the symbol to it. -/ def quantify_binding : interpretation → binding → (interpretation → Prop) → Prop | mdl (binding.declare_fun sym arg_sorts return_sort) p := do ∃(x : (rank.mk arg_sorts return_sort).domain), p (mdl.bind sym _ x) | mdl (binding.define_fun sym args tp rhs) p := do p (mdl.bind sym _ (function_def mdl args rhs)) /-- Generate a model from a list of bindings and obtain a proposition. -/ def quantify_bindings : list binding → (interpretation → Prop) → Prop | [] p := p ∅ | (b::r) p := do quantify_bindings r (λmdl, quantify_binding mdl b p) /-- Registers that a symbol is defined. -/ def register_symbol (nm:symbol) : semantics punit := do -- Check symbol is not already defined s ← get, pwhen (nm ∈ s.defined_symbols) (throw ("Already defined: " ++ repr nm)), -- Insert symbol into defined_symbols put $ { s with defined_symbols := s.defined_symbols.insert nm () } --protected --def interp_bool (m:interpretation) (p:term Bool) : Prop := p.interp m /-- Assert a term is true. -/ protected def assert (p:term Bool) : semantics punit := do modify $ λctx, { ctx with asserted := p :: ctx.asserted } /-- Declare a function -/ protected def declare_fun (nm:symbol) (args:list sort) (res:sort) : semantics punit := do register_symbol nm, modify $ context.add_binding (binding.declare_fun nm args res) /-- Define a function in terms of inputs -/ protected def define_fun (nm:symbol) (args:list (symbol × sort)) {res:sort} (rhs : term res) : semantics punit := do register_symbol nm, modify $ context.add_binding (binding.define_fun nm args res rhs) /-- Invoke check-sat-assuming command -/ protected def check_sat_assuming (preds : list (term Bool)) : semantics punit := do modify $ λctx, -- Build list containing previous assertions plus current predicates let all_preds := list.reverse_core ctx.asserted preds in let p := quantify_bindings ctx.bindings (λ(m:interpretation), all_band (λ(t:term Bool), t.interp m) all_preds) in { ctx with checked := p :: ctx.checked } /-- Invoke check-sat command -/ protected def check_sat : semantics punit := semantics.check_sat_assuming [] instance : is_generator semantics := { assert := semantics.assert , declare_fun := semantics.declare_fun , define_fun := semantics.define_fun , check_sat := semantics.check_sat } /-- This runs the semantics monad and either returns an error due to API misuse or the proposition that was asserted. -/ protected def run_and_collect_unsat (m:semantics punit) : except string Prop := let f (r:punit × context) : Prop := (r.snd.checked.map (λp, not p)).forall_prop in (m.run context.initial).map_poly f end semantics end smt2
367e2ed274552428de0212f22be3f60c41ebfa8c
a4673261e60b025e2c8c825dfa4ab9108246c32e
/tests/lean/run/subst1.lean
393f2d8dcd2dd0bd95ce90e28d5f69a8da1ee213
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
619
lean
set_option trace.Meta.Tactic.subst true theorem tst1 (x y z : Nat) : y = z → x = x → x = y → x = z := by intros h1 h2 h3 subst x assumption theorem tst2 (x y z : Nat) : y = z → x = z + y → x = z + z := by intros h1 h2 subst h1 subst h2 exact rfl def BV (n : Nat) : Type := Unit theorem tst3 (n m : Nat) (v : BV n) (w : BV m) (h1 : n = m) (h2 : forall (v1 v2 : BV n), v1 = v2) : v = cast (congrArg BV h1) w := by subst h1 apply h2 theorem tst4 (n m : Nat) (v : BV n) (w : BV m) (h1 : n = m) (h2 : forall (v1 v2 : BV n), v1 = v2) : v = cast (congrArg BV h1.symm) w := by subst n apply h2
5f5b3a4cfb96ebeb77a1855f7e28a6fca8580c01
ea5678cc400c34ff95b661fa26d15024e27ea8cd
/sylow_2.lean
523382ba8a9626bf8ebd751a426ebb24e3f8fa94
[]
no_license
ChrisHughes24/leanstuff
dca0b5349c3ed893e8792ffbd98cbcadaff20411
9efa85f72efaccd1d540385952a6acc18fce8687
refs/heads/master
1,654,883,241,759
1,652,873,885,000
1,652,873,885,000
134,599,537
1
0
null
null
null
null
UTF-8
Lean
false
false
41,527
lean
import group_theory.order_of_element .zmod_as_fin2 algebra.pi_instances group_theory.group_action open equiv fintype finset is_group_action is_monoid_action universes u v w variables {G : Type u} {α : Type v} {β : Type w} [group G] #check le_antisymm' namespace finset lemma filter_insert_of_pos [decidable_eq α] (s : finset α) {P : α → Prop} [decidable_pred P] (a : α) (h : P a) : (insert a s).filter P = insert a (s.filter P) := ext.2 (λ x, by rw [mem_filter, mem_insert, mem_insert, mem_filter, eq_comm]; exact ⟨λ h₁, by cases h₁.1; simp * at *, λ h₁, by cases h₁; simp * at *⟩) lemma filter_insert_of_neg [decidable_eq α] (s : finset α) {P : α → Prop} [decidable_pred P] (a : α) (h : ¬P a) : (insert a s).filter P = s.filter P := ext.2 (λ x, by rw [mem_filter, mem_insert, mem_filter, eq_comm]; exact ⟨λ h₁, by cases h₁.1; simp * at *, by finish⟩) end finset lemma nat.sum_mod [decidable_eq α] (s : finset α) (f : α → ℕ) (n : ℕ) : s.sum f ≡ (s.filter (λ x, f x % n ≠ 0)).sum f [MOD n] := finset.induction_on s rfl begin assume a s has ih, by_cases ha : f a % n ≠ 0, { rw [finset.sum_insert has, finset.filter_insert_of_pos s a ha, finset.sum_insert], exact nat.modeq.modeq_add rfl ih, { finish [finset.mem_filter] } }, { rw [finset.sum_insert has, finset.filter_insert_of_neg s a ha, ← zero_add (finset.sum (finset.filter _ _) _)], rw [ne.def, ← nat.zero_mod n] at ha, exact nat.modeq.modeq_add (not_not.1 ha) ih } end namespace set lemma card_eq_of_eq {s t : set α} [fintype s] [fintype t] (h : s = t) : card s = card t := by congr; assumption lemma card_image_of_inj_on {s : set α} [fintype s] {f : α → β} [fintype (f '' s)] (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : fintype.card (f '' s) = fintype.card s := by haveI := classical.prop_decidable; exact calc fintype.card (f '' s) = (s.to_finset.image f).card : card_fintype_of_finset' _ (by simp) ... = s.to_finset.card : card_image_of_inj_on (λ x hx y hy hxy, H x (mem_to_finset.1 hx) y (mem_to_finset.1 hy) hxy) ... = card s : (card_fintype_of_finset' _ (λ a, mem_to_finset)).symm lemma card_image_of_injective (s : set α) [fintype s] {f : α → β} [fintype (f '' s)] (H : function.injective f) : fintype.card (f '' s) = fintype.card s := card_image_of_inj_on $ λ _ _ _ _ h, H h lemma coe_to_finset [decidable_eq α] (s : set α) [fintype s] : (↑s.to_finset : set α) = s := set.ext (by simp) lemma ssubset_iff_subset_not_subset {s t : set α} : s ⊂ t ↔ s ⊆ t ∧ ¬ t ⊆ s := by split; simp [set.ssubset_def, ne.def, set.subset.antisymm_iff] {contextual := tt} lemma coe_ssubset [decidable_eq α] {s t : finset α} : (↑s : set α) ⊂ ↑t ↔ s ⊂ t := show (↑s : set α) ⊂ ↑t ↔ s ⊆ t ∧ ¬t ⊆ s, by simp [ssubset_iff_subset_not_subset] {contextual := tt} #print coe_ssubset lemma card_lt_card {s t : set α} [fintype s] [fintype t] (h : s ⊂ t) : card s < card t := begin haveI := classical.prop_decidable, rw [card_fintype_of_finset' _ (λ x, mem_to_finset), card_fintype_of_finset' _ (λ x, mem_to_finset)], rw [← coe_to_finset s, ← coe_to_finset t, coe_ssubset] at h, exact finset.card_lt_card h, end def equiv_univ (α : Type u) : α ≃ (set.univ : set α) := { to_fun := λ a, ⟨a, mem_univ _⟩, inv_fun := λ a, a.1, left_inv := λ a, rfl, right_inv := λ ⟨a, ha⟩, rfl } @[simp] lemma card_univ (α : Type u) [fintype α] [fintype.{u} (set.univ : set α)] : fintype.card (set.univ : set α) = fintype.card α := eq.symm (card_congr (equiv_univ α)) lemma eq_of_card_eq_of_subset {s t : set α} [fintype s] [fintype t] (hcard : card s = card t) (hsub : s ⊆ t) : s = t := classical.by_contradiction (λ h, lt_irrefl (card t) (have card s < card t := set.card_lt_card ⟨hsub, h⟩, by rwa hcard at this)) end set local attribute [instance, priority 0] subtype.fintype set_fintype classical.prop_decidable section should_be_in_group_theory noncomputable instance [fintype G] (H : set G) [is_subgroup H] : fintype (left_cosets H) := quotient.fintype (left_rel H) lemma card_eq_card_cosets_mul_card_subgroup [fintype G] (H : set G) [is_subgroup H] : card G = card (left_cosets H) * card H := by rw ← card_prod; exact card_congr (is_subgroup.group_equiv_left_cosets_times_subgroup _) lemma order_of_dvd_of_pow_eq_one [fintype G] {a : G} {n : ℕ} (h : a ^ n = 1) : order_of a ∣ n := by_contradiction (λ h₁, nat.find_min _ (show n % order_of a < order_of a, from nat.mod_lt _ (nat.pos_of_ne_zero (order_of_ne_zero _))) ⟨mt nat.dvd_of_mod_eq_zero h₁, by rwa ← pow_eq_mod_order_of⟩) lemma eq_one_of_order_of_eq_one [fintype G] {a : G} (h : order_of a = 1) : a = 1 := by conv { to_lhs, rw [← pow_one a, ← h, pow_order_of_eq_one] } lemma order_eq_card_gpowers [fintype G] {a : G} : order_of a = card (gpowers a) := begin refine (finset.card_eq_of_bijective _ _ _ _).symm, { exact λn hn, ⟨gpow a n, ⟨n, rfl⟩⟩ }, { exact assume ⟨_, i, rfl⟩ _, have pos: (0:int) < order_of a, from int.coe_nat_lt.mpr $ nat.pos_iff_ne_zero.mpr $ order_of_ne_zero a, have 0 ≤ i % (order_of a), from int.mod_nonneg _ $ ne_of_gt pos, ⟨int.to_nat (i % order_of a), by rw [← int.coe_nat_lt, int.to_nat_of_nonneg this]; exact ⟨int.mod_lt_of_pos _ pos, subtype.eq gpow_eq_mod_order_of.symm⟩⟩ }, { intros, exact finset.mem_univ _ }, { exact assume i j hi hj eq, pow_injective_of_lt_order_of a hi hj $ by simpa using eq } end @[simp] lemma card_trivial [fintype (is_subgroup.trivial G)] : fintype.card (is_subgroup.trivial G) = 1 := fintype.card_eq_one_iff.2 ⟨⟨(1 : G), by simp⟩, λ ⟨y, hy⟩, subtype.eq $ is_subgroup.mem_trivial.1 hy⟩ local attribute [instance] left_rel normal_subgroup.to_is_subgroup instance quotient.mk.is_group_hom (H : set G) [normal_subgroup H] : @is_group_hom G (left_cosets H) _ _ quotient.mk := ⟨λ _ _, rfl⟩ instance subtype.val.is_group_hom (H : set G) [is_subgroup H] : is_group_hom (subtype.val : H → G) := ⟨λ _ _, rfl⟩ def normalizer (H : set G) : set G := { g : G | ∀ n, n ∈ H ↔ g * n * g⁻¹ ∈ H } instance (H : set G) [is_subgroup H] : is_subgroup (normalizer H) := { one_mem := by simp [normalizer], mul_mem := λ a b (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) (hb : ∀ n, n ∈ H ↔ b * n * b⁻¹ ∈ H) n, by rw [mul_inv_rev, ← mul_assoc, mul_assoc a, mul_assoc a, ← ha, ← hb], inv_mem := λ a (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) n, by rw [ha (a⁻¹ * n * a⁻¹⁻¹)]; simp [mul_assoc] } lemma subset_normalizer (H : set G) [is_subgroup H] : H ⊆ normalizer H := λ g hg n, by rw [is_subgroup.mul_mem_cancel_left _ ((is_subgroup.inv_mem_iff _).2 hg), is_subgroup.mul_mem_cancel_right _ hg] instance (H : set G) [is_subgroup H] : normal_subgroup { x : normalizer H | ↑x ∈ H } := { one_mem := show (1 : G) ∈ H, from is_submonoid.one_mem _, mul_mem := λ a b ha hb, show (a * b : G) ∈ H, from is_submonoid.mul_mem ha hb, inv_mem := λ a ha, show (a⁻¹ : G) ∈ H, from is_subgroup.inv_mem ha, normal := λ a ha ⟨m, hm⟩, (hm a).1 ha } lemma conj_inj_left {x : G} : function.injective (λ (n : G), x * n * x⁻¹) := λ a b h, (mul_left_inj x).1 $ (mul_right_inj (x⁻¹)).1 h lemma mem_normalizer_fintype {H : set G} [fintype H] {x : G} : (∀ n, n ∈ H → x * n * x⁻¹ ∈ H) → x ∈ normalizer H := λ h n, ⟨h n, λ h₁, have heq : (λ n, x * n * x⁻¹) '' H = H := set.eq_of_card_eq_of_subset (set.card_image_of_injective _ conj_inj_left) (λ n ⟨y, hy⟩, hy.2 ▸ h y hy.1), have x * n * x⁻¹ ∈ (λ n, x * n * x⁻¹) '' H := heq.symm ▸ h₁, let ⟨y, hy⟩ := this in conj_inj_left hy.2 ▸ hy.1⟩ noncomputable lemma preimage_quotient_mk_equiv_subgroup_times_set (H : set G) [is_subgroup H] (s : set (left_cosets H)) : quotient.mk ⁻¹' s ≃ (H × s) := have h : ∀ {x : left_cosets H} {a : G}, x ∈ s → a ∈ H → ⟦quotient.out x * a⟧ = ⟦quotient.out x⟧ := λ x a hx ha, quotient.sound (show (quotient.out x * a)⁻¹ * quotient.out x ∈ H, from (is_subgroup.inv_mem_iff _).1 $ by rwa [mul_inv_rev, inv_inv, ← mul_assoc, inv_mul_self, one_mul]), { to_fun := λ ⟨a, ha⟩, ⟨⟨(quotient.out ⟦a⟧)⁻¹ * a, @quotient.exact _ (left_rel H) _ _ $ by simp⟩, ⟨⟦a⟧, ha⟩⟩, inv_fun := λ ⟨⟨a, ha⟩, ⟨x, hx⟩⟩, ⟨(quotient.out x) * a, show _ ∈ s, by simpa [h hx ha]⟩, left_inv := λ ⟨a, ha⟩, by simp, right_inv := λ ⟨⟨a, ha⟩, ⟨x, hx⟩⟩, by simp [h hx ha] } end should_be_in_group_theory section group_action variables (f : G → α → α) [is_group_action f] lemma card_orbit_of_mem_fixed_points {f : G → α → α} [is_group_action f] {a : α} [fintype (orbit f a)] : a ∈ fixed_points f ↔ card (orbit f a) = 1 := begin rw [fintype.card_eq_one_iff, mem_fixed_points], split, { exact λ h, ⟨⟨a, mem_orbit_self _ _⟩, λ ⟨b, ⟨x, hx⟩⟩, subtype.eq $ by simp [h x, hx.symm]⟩ }, { assume h x, rcases h with ⟨⟨z, hz⟩, hz₁⟩, exact calc f x a = z : subtype.mk.inj (hz₁ ⟨f x a, mem_orbit _ _ _⟩) ... = a : (subtype.mk.inj (hz₁ ⟨a, mem_orbit_self _ _⟩)).symm } end lemma card_modeq_card_fixed_points [fintype α] [fintype G] [fintype (fixed_points f)] {p n : ℕ} (hp : nat.prime p) (h : card G = p ^ n) : card α ≡ card (fixed_points f) [MOD p] := have hcard : ∀ s : set α, card ↥{x : α | orbit f x = s} % p ≠ 0 ↔ card ↥{x : α | orbit f x = s} = 1 := λ s, ⟨λ hs, begin have h : ∃ y, orbit f y = s := by_contradiction (λ h, begin rw not_exists at h, have : {x | orbit f x = s} = ∅ := set.eq_empty_iff_forall_not_mem.2 h, rw [set.card_eq_of_eq this, set.empty_card', nat.zero_mod] at hs, contradiction end), cases h with y hy, have hseq : {x | orbit f x = s} = orbit f y := set.ext (λ z, ⟨λ h : orbit f z = s, hy.symm ▸ h ▸ mem_orbit_self _ _, λ h, show orbit f z = s, by rwa orbit_eq_iff.2 h⟩), rw [card_eq_card_cosets_mul_card_subgroup (stabilizer f y), ← card_congr (orbit_equiv_left_cosets f y)] at h, have : ∃ k ≤ n, card (orbit f y) = p ^ k := (nat.dvd_prime_pow hp).1 (h ▸ dvd_mul_right _ _), rcases this with ⟨k, hk₁, hk₂⟩, rw [set.card_eq_of_eq hseq, hk₂] at hs ⊢, have : ¬p ∣ p ^ k := mt nat.mod_eq_zero_of_dvd hs, cases k, { refl }, { simpa [nat.pow_succ] using this } end, λ hs, hs.symm ▸ (nat.mod_eq_of_lt hp.gt_one).symm ▸ λ h, nat.no_confusion h⟩, have h : (finset.univ.filter (λ a, card {x | orbit f x = a} % p ≠ 0)).sum (λ a : set α, card {x | orbit f x = a}) = card (fixed_points f), from calc _ = (finset.univ.filter (λ a, card {x | orbit f x = a} % p ≠ 0)).sum (λ a : set α, 1) : finset.sum_congr rfl (λ s hs, (hcard s).1 (finset.mem_filter.1 hs).2) ... = card {a : set α | card ↥{x : α | orbit f x = a} % p ≠ 0} : begin rw [finset.sum_const, nat.smul_eq_mul, mul_one], refine eq.symm (set.card_fintype_of_finset' _ _), simp [finset.mem_filter], end ... = card (fixed_points f) : fintype.card_congr (@equiv.of_bijective _ _ (show fixed_points f → {a : set α // card ↥{x : α | orbit f x = a} % p ≠ 0}, from λ x, ⟨orbit f x.1, begin rw [hcard, fintype.card_eq_one_iff], exact ⟨⟨x, rfl⟩, λ ⟨y, hy⟩, have hy : y ∈ orbit f x := (show orbit f y = orbit f x, from hy) ▸ mem_orbit_self _ _, subtype.eq (mem_fixed_points'.1 x.2 _ hy)⟩ end⟩) ⟨λ x y hxy, have hxy : orbit f x.1 = orbit f y.1 := subtype.mk.inj hxy, have hxo : x.1 ∈ orbit f y.1 := hxy ▸ mem_orbit_self _ _, subtype.eq (mem_fixed_points'.1 y.2 _ hxo), λ ⟨s, hs⟩, begin rw [hcard, fintype.card_eq_one_iff] at hs, rcases hs with ⟨⟨x, hx₁⟩, hx₂⟩, exact ⟨⟨x, mem_fixed_points'.2 (λ y hy, subtype.mk.inj (hx₂ ⟨y, by have := orbit_eq_iff.2 hy; simpa [this, hx₁] using hx₁⟩))⟩, by simpa using hx₁⟩ end⟩).symm, calc card α % p = finset.sum finset.univ (λ a : set α, card {x // orbit f x = a}) % p : by rw [card_congr (equiv_fib (orbit f)), fintype.card_sigma] ... = _ : nat.sum_mod _ _ _ ... = fintype.card ↥(fixed_points f) % p : by rw ← h; congr end group_action namespace sylow open is_group_action def mk_vector_prod_eq_one (n : ℕ) [pos_nat n] (v : Zmod n → G) : Zmod (n+1) → G := λ m, if h : m.1 < n then v m.1 else ((list.range n).map (λ m : ℕ, v (m : Zmod n))).prod⁻¹ lemma mk_vector_prod_eq_one_injective {p : ℕ} [h0 : pos_nat p] : function.injective (@mk_vector_prod_eq_one G _ p _) := λ x y hxy, funext (λ ⟨a, ha⟩, begin have : dite _ _ _ = dite _ _ _ := congr_fun hxy a, rw [Zmod.cast_val_nat, nat.mod_eq_of_lt (nat.lt_succ_of_lt ha), dif_pos ha, dif_pos ha] at this, rwa Zmod.mk_eq_cast end) /-- set of elements of G^n such that the product of the list of elements of the vector is one -/ def vectors_prod_eq_one (G : Type*) [group G] (n : ℕ) [pos_nat n] : set (Zmod n → G) := {v | ((list.range n).map (λ m : ℕ, v (↑m : Zmod n))).prod = 1 } lemma mem_vectors_prod_eq_one_iff {n : ℕ} [pos_nat n] (v : Zmod (n + 1) → G) : v ∈ vectors_prod_eq_one G (n + 1) ↔ v ∈ mk_vector_prod_eq_one n '' (set.univ : set (Zmod n → G)) := have prod_lemma : ((list.range (n + 1)).map (λ m : ℕ, v (m : Zmod (n + 1)))).prod = list.prod (list.map (λ (m : ℕ), v ↑m) (list.range n)) * v ↑n := by rw [list.range_concat, list.map_append, list.prod_append, list.map_singleton, list.prod_cons, list.prod_nil, mul_one], ⟨λ h : list.prod (list.map (λ (m : ℕ), v ↑m) (list.range (n + 1))) = 1, have h₁ : list.map (λ (m : ℕ), v ((m : Zmod n).val : Zmod (n+1))) (list.range n) = list.map (λ (m : ℕ), v m) (list.range n) := list.map_congr (λ m hm, have hm' : m < n := list.mem_range.1 hm, by simp [Zmod.cast_val_nat, nat.mod_eq_of_lt hm']), ⟨λ m, v m.val, set.mem_univ _, funext (λ i, show dite _ _ _ = _, begin split_ifs, { refine congr_arg _ (fin.eq_of_veq _), simp [Zmod.cast_val_nat, nat.mod_eq_of_lt h_1, nat.mod_eq_of_lt (nat.lt_succ_of_lt h_1)] }, { have hi : i = n := fin.eq_of_veq begin rw [Zmod.cast_val_nat, nat.mod_eq_of_lt (nat.lt_succ_self _)], exact le_antisymm (nat.le_of_lt_succ i.2) (le_of_not_gt h_1), end, rw [h₁, hi, inv_eq_iff_mul_eq_one, ← prod_lemma, h] } end)⟩, λ ⟨w, hw⟩, have h : list.map (λ m : ℕ, w m) (list.range n) = list.map (λ m : ℕ, v m) (list.range n) := list.map_congr (λ k hk, have hk' : k < n := list.mem_range.1 hk, hw.2 ▸ (show _ = dite _ _ _, by rw [Zmod.cast_val_nat, nat.mod_eq_of_lt (nat.lt_succ_of_lt hk'), dif_pos hk'])), begin show list.prod (list.map (λ (m : ℕ), v ↑m) (list.range (n + 1))) = 1, rw [prod_lemma, ← h, ← hw.2], show _ * dite _ _ _ = (1 : G), rw [Zmod.cast_val_nat, nat.mod_eq_of_lt (nat.lt_succ_self _), dif_neg (lt_irrefl _), mul_inv_self], end⟩ def rotate (α : Type v) (n : ℕ) (i : multiplicative (Zmod n)) (v : multiplicative (Zmod n) → α) (m : multiplicative (Zmod n)) := v (m * i) instance rotate.is_group_action (n : ℕ) [pos_nat n] : is_group_action (rotate α n) := { mul := λ x y v, funext (λ i, show v (i * (x * y)) = v (i * x * y), by rw mul_assoc), one := λ v, funext (λ i, show v (i * 1) = v i, by rw mul_one) } lemma fixed_points_rotate_eq_const {n : ℕ} [h0 : pos_nat n] {v : multiplicative (Zmod n) → G} (h : v ∈ fixed_points (rotate G n)) (i j : multiplicative (Zmod n)) : v i = v j := calc v i = v (j * i) : mul_comm i j ▸ (congr_fun ((mem_fixed_points'.1 h _) (mem_orbit (rotate G n) v j)) i).symm ... = v j : congr_fun ((mem_fixed_points'.1 h _) (mem_orbit (rotate G n) v i)) j lemma map_succ_range : ∀ n : ℕ, list.range (nat.succ n) = 0 :: (list.range n).map nat.succ | 0 := rfl | (n+1) := by rw [list.range_concat, list.range_concat, list.map_append, ← list.cons_append, ← map_succ_range, list.range_concat, list.map_singleton] open nat lemma list.prod_const [monoid α] : ∀ {l : list α} {a : α}, (∀ b ∈ l, b = a) → l.prod = a ^ l.length | [] := λ _ _, rfl | (b::l) := λ a ha, have h : ∀ b ∈ l, b = a := λ b hb, ha b (list.mem_cons_of_mem _ hb), have hb : b = a := ha b (list.mem_cons_self _ _), by simp [_root_.pow_add, list.prod_const h, hb] lemma rotate_on_vectors_prod_eq_one {n : ℕ} [h0 : pos_nat n] {v : Zmod n → G} (hv : v ∈ vectors_prod_eq_one G n) (i : Zmod n) : (rotate G n) (i : Zmod n) v ∈ vectors_prod_eq_one G n := begin cases i with i hi, rw Zmod.mk_eq_cast, clear hi, induction i with i ih, { show list.prod (list.map (λ (m : ℕ), v (m + 0)) (list.range n)) = 1, simpa }, { show list.prod (list.map (λ (m : ℕ), v (m + (i + 1))) (list.range n)) = 1, replace ih : list.prod (list.map (λ (m : ℕ), v (m + i)) (list.range n)) = 1 := ih, resetI, cases n, { simp [list.range, list.range_core] }, { rw [list.range_concat, list.map_append, list.prod_append, list.map_singleton, list.prod_cons, list.prod_nil, mul_one] at ⊢ ih, have h : list.map (λ m : ℕ, v (↑m + (i + 1))) (list.range n) = list.map (λ m : ℕ, v (m + i)) (list.map (λ m : ℕ, m + 1) (list.range n)), { simp [list.map_map, function.comp] }, resetI, cases n, { rw ← ih, congr }, { have h : list.map (λ m : ℕ, v (↑m + (i + 1))) (list.range n) = list.map (λ m : ℕ, v (m + i)) (list.map succ (list.range n)), { simp [list.map_map, function.comp] }, have h₁ : (succ n : Zmod (succ (succ n))) + (↑i + 1) = i, { rw [add_left_comm, ← nat.cast_one, ← nat.cast_add, Zmod.cast_self_eq_zero, add_zero] }, have h₂ : (n : Zmod (succ (succ n))) + i + 1 = succ n + i := by simp [succ_eq_add_one], rw [map_succ_range, list.map_cons, list.prod_cons, ← h, nat.cast_zero, zero_add] at ih, have := eq_inv_mul_of_mul_eq ih, rw [list.range_concat, list.map_append, list.map_singleton, list.prod_append, list.prod_cons, list.prod_nil, mul_one, ← add_assoc, h₁, h₂, this], simp } } } end def rotate_vectors_prod_eq_one (G : Type u) [group G] (n : ℕ) [pos_nat n] (i : multiplicative (Zmod n)) (v : vectors_prod_eq_one G n) : vectors_prod_eq_one G n := ⟨rotate _ n i v.1, rotate_on_vectors_prod_eq_one v.2 _⟩ instance (n : ℕ) [pos_nat n] : is_group_action (rotate_vectors_prod_eq_one G n) := { one := λ ⟨a, ha⟩, subtype.eq (is_monoid_action.one (rotate G n) _), mul := λ x y ⟨a, ha⟩, subtype.eq (is_monoid_action.mul (rotate G n) _ _ _) } lemma mem_fixed_points_rotate_vectors_prod_eq_one {n : ℕ} [pos_nat n] : ∀ {v : vectors_prod_eq_one G n}, v ∈ fixed_points (rotate_vectors_prod_eq_one G n) ↔ (v : Zmod n → G) ∈ fixed_points (rotate G n) := λ ⟨v, hv⟩, ⟨λ h x, subtype.mk.inj (h x), λ h x, subtype.eq (h x)⟩ lemma fixed_points_rotate_pow_n [fintype G] {n : ℕ} (hn : nat.prime (succ n)) [h0 : pos_nat n] : ∀ {v : vectors_prod_eq_one G (succ n)} (hv : v ∈ fixed_points (rotate_vectors_prod_eq_one G (succ n))), (v : Zmod (succ n) → G) 0 ^ (n + 1) = 1 := λ ⟨v, hv₁⟩ hv, let ⟨w, hw⟩ := (mem_vectors_prod_eq_one_iff _).1 hv₁ in have hv' : (v : Zmod (succ n) → G) ∈ fixed_points (rotate G (succ n)) := λ i, subtype.mk.inj (mem_stabilizer_iff.1 (hv i)), begin have h₁ : dite _ _ _ = (v : Zmod (succ n) → G) _ := congr_fun hw.2 ⟨n, nat.lt_succ_self n⟩, rw dif_neg (lt_irrefl _) at h₁, have h₂ : ∀ b, b < n → w b = (v : Zmod (succ n) → G) b := λ b hb, begin have : dite _ _ _ = _ := congr_fun hw.2 b, rwa [Zmod.cast_val_of_lt (lt_succ_of_lt hb), dif_pos hb] at this, end, have hb : ∀ (b : G), b ∈ list.map (λ (m : ℕ), w ↑m) (list.range n) → b = w 0 := λ b hb, let ⟨i, hi⟩ := list.mem_map.1 hb in by rw [← hi.2, h₂ _ (list.mem_range.1 hi.1), fixed_points_rotate_eq_const hv' _ 1]; exact (h₂ 0 h0.pos).symm, refine (@mul_left_inj _ _ (w 0 ^ (-n : ℤ)) _ _).1 _, rw [@list.prod_const _ _ _ (w 0) hb, list.length_map, list.length_range, ← gpow_coe_nat, ← gpow_neg] at h₁, conv { to_rhs, rw [h₁, fixed_points_rotate_eq_const hv' _ 1] }, rw [← nat.cast_zero, h₂ 0 h0.pos, nat.cast_zero, subtype.coe_mk, ← gpow_coe_nat, ← _root_.gpow_add, int.coe_nat_add], simp, refl, end lemma one_mem_fixed_points_rotate [fintype G] {n : ℕ} [h0 : pos_nat n] : (1 : Zmod n → G) ∈ fixed_points (rotate G n) := mem_fixed_points'.2 (λ y hy, funext (λ j, let ⟨i, hi⟩ := mem_orbit_iff.1 hy in have hj : (1 : G) = y j := congr_fun hi j, hj ▸ rfl)) lemma one_mem_vectors_prod_eq_one (n : ℕ) [pos_nat n] : (1 : Zmod n → G) ∈ vectors_prod_eq_one G n := show list.prod (list.map (λ (m : ℕ), (1 : G)) (list.range n)) = 1, from have h : ∀ b : G, b ∈ list.map (λ (m : ℕ), (1 : G)) (list.range n) → b = 1 := λ b hb, let ⟨_, h⟩ := list.mem_map.1 hb in h.2.symm, by simp [list.prod_const h] attribute [trans] dvd.trans lemma exists_prime_order_of_dvd_card [fintype G] {p : ℕ} (hp : nat.prime p) (hdvd : p ∣ card G) : ∃ x : G, order_of x = p := let n := p - 1 in have hn : p = n + 1 := nat.succ_sub hp.pos, have hnp : nat.prime (n + 1) := hn ▸ hp, have hn0 : pos_nat n := ⟨nat.lt_of_succ_lt_succ hnp.gt_one⟩, have hlt : ¬(n : Zmod (n + 1)).val < n := not_lt_of_ge (by rw [Zmod.cast_val_nat, nat.mod_eq_of_lt (nat.lt_succ_self _)]; exact le_refl _), have hcard1 : card (vectors_prod_eq_one G (n + 1)) = card (Zmod n → G) := by rw [← set.card_univ (Zmod n → G), set.ext (@mem_vectors_prod_eq_one_iff _ _ _ hn0), set.card_image_of_injective _ mk_vector_prod_eq_one_injective], have hcard : card (vectors_prod_eq_one G (n + 1)) = card G ^ n := by conv { rw hcard1, to_rhs, rw ← card_fin n }; exact fintype.card_fun, have fintype (multiplicative (Zmod (succ n))) := fin.fintype _, have pos_nat (succ n) := ⟨succ_pos _⟩, have hZmod : @fintype.card (multiplicative (Zmod (succ n))) (fin.fintype _) = (n+1) ^ 1 := (nat.pow_one (n + 1)).symm ▸ card_fin _, by exactI have hmodeq : _ = _ := @card_modeq_card_fixed_points _ _ _ (rotate_vectors_prod_eq_one G (succ n)) _ _ _ _ _ 1 hnp hZmod, have hdvdcard : (n + 1) ∣ card (vectors_prod_eq_one G (n + 1)) := calc (n + 1) = p : hn.symm ... ∣ card G ^ 1 : by rwa nat.pow_one ... ∣ card G ^ n : nat.pow_dvd_pow _ hn0.pos ... = card (vectors_prod_eq_one G (n + 1)) : hcard.symm, have hdvdcard₂ : (n + 1) ∣ card (fixed_points (rotate_vectors_prod_eq_one G (succ n))) := nat.dvd_of_mod_eq_zero (hmodeq ▸ (nat.mod_eq_zero_of_dvd hdvdcard)), have hcard_pos : 0 < card (fixed_points (rotate_vectors_prod_eq_one G (succ n))) := fintype.card_pos_iff.2 ⟨⟨⟨(1 : Zmod (succ n) → G), one_mem_vectors_prod_eq_one _⟩, λ x, subtype.eq (one_mem_fixed_points_rotate x)⟩⟩, have hle : 1 < card (fixed_points (rotate_vectors_prod_eq_one G (succ n))) := calc 1 < n + 1 : hnp.gt_one ... ≤ _ : nat.le_of_dvd hcard_pos hdvdcard₂, let ⟨⟨x, hx₁⟩, hx₂⟩ := classical.not_forall.1 (mt fintype.card_le_one_iff.2 (not_le_of_gt hle)) in let ⟨⟨y, hy₁⟩, hy₂⟩ := classical.not_forall.1 hx₂ in have hxy : (x : Zmod (succ n) → G) 0 ≠ 1 ∨ (y : Zmod (succ n) → G) 0 ≠ 1 := or_iff_not_imp_left.2 (λ hx1 hy1, hy₂ $ subtype.eq $ subtype.eq $ funext $ λ i, show (x : Zmod (succ n) → G) i = (y : Zmod (succ n) → G) i, by rw [fixed_points_rotate_eq_const ((mem_fixed_points_rotate_vectors_prod_eq_one).1 hx₁) _ (0 : Zmod (succ n)), fixed_points_rotate_eq_const ((mem_fixed_points_rotate_vectors_prod_eq_one).1 hy₁) _ (0 : Zmod (succ n)), not_not.1 hx1, hy1]), have hxp : (x : Zmod (succ n) → G) 0 ^ (n + 1) = 1 := @fixed_points_rotate_pow_n _ _ _ _ hnp hn0 _ hx₁, have hyp : (y : Zmod (succ n) → G) 0 ^ (n + 1) = 1 := @fixed_points_rotate_pow_n _ _ _ _ hnp hn0 _ hy₁, begin rw hn, cases hxy with hx hy, { existsi (x : Zmod (succ n) → G) 0, exact or.resolve_left (hnp.2 _ (order_of_dvd_of_pow_eq_one hxp)) (λ h, hx (eq_one_of_order_of_eq_one h)) }, { existsi (y : Zmod (succ n) → G) 0, exact or.resolve_left (hnp.2 _ (order_of_dvd_of_pow_eq_one hyp)) (λ h, hy (eq_one_of_order_of_eq_one h)) } end local attribute [instance] left_rel set_fintype open is_subgroup is_submonoid is_group_hom def mul_left_cosets (L₁ L₂ : set G) [is_subgroup L₂] [is_subgroup L₁] (x : L₂) (y : left_cosets L₁) : left_cosets L₁ := quotient.lift_on y (λ y, ⟦(x : G) * y⟧) (λ a b (hab : _ ∈ L₁), quotient.sound (show _ ∈ L₁, by rwa [mul_inv_rev, ← mul_assoc, mul_assoc (a⁻¹), inv_mul_self, mul_one])) instance mul_left_cosets.is_group_action (L₁ L₂ : set G) [is_subgroup L₂] [is_subgroup L₁] : is_group_action (mul_left_cosets L₁ L₂) := { one := λ a, quotient.induction_on a (λ a, quotient.sound (show (1 : G) * a ≈ a, by simp)), mul := λ x y a, quotient.induction_on a (λ a, quotient.sound (by rw ← mul_assoc; refl)) } lemma mem_fixed_points_mul_left_cosets_iff_mem_normalizer {H : set G} [is_subgroup H] [fintype H] {x : G} : ⟦x⟧ ∈ fixed_points (mul_left_cosets H H) ↔ x ∈ normalizer H := ⟨λ hx, have ha : ∀ {y : left_cosets H}, y ∈ orbit (mul_left_cosets H H) ⟦x⟧ → y = ⟦x⟧ := λ _, (mem_fixed_points'.1 hx _), (inv_mem_iff _).1 (mem_normalizer_fintype (λ n hn, have (n⁻¹ * x)⁻¹ * x ∈ H := quotient.exact (ha (mem_orbit (mul_left_cosets H H) _ ⟨n⁻¹, inv_mem hn⟩)), by simpa only [mul_inv_rev, inv_inv] using this)), λ (hx : ∀ (n : G), n ∈ H ↔ x * n * x⁻¹ ∈ H), mem_fixed_points'.2 $ λ y, quotient.induction_on y $ λ y hy, quotient.sound (let ⟨⟨b, hb₁⟩, hb₂⟩ := hy in have hb₂ : (b * x)⁻¹ * y ∈ H := quotient.exact hb₂, (inv_mem_iff H).1 $ (hx _).2 $ (mul_mem_cancel_right H (inv_mem hb₁)).1 $ by rw hx at hb₂; simpa [mul_inv_rev, mul_assoc] using hb₂)⟩ lemma fixed_points_mul_left_cosets_equiv_cosets (H : set G) [is_subgroup H] [fintype H] : fixed_points (mul_left_cosets H H) ≃ left_cosets {x : normalizer H | ↑x ∈ H} := { to_fun := λ a, quotient.hrec_on a.1 (λ a ha, @quotient.mk _ (left_rel {x : normalizer H | ↑x ∈ H}) ⟨a, mem_fixed_points_mul_left_cosets_iff_mem_normalizer.1 ha⟩) (λ x y hxy, function.hfunext (by rw quotient.sound hxy) (λ hx hy _, heq_of_eq (@quotient.sound _ (left_rel {x : normalizer H | ↑x ∈ H}) _ _ (by exact hxy)))) a.2, inv_fun := λ x, ⟨@quotient.lift_on _ _ (left_rel {x : normalizer H | ↑x ∈ H}) x (λ x, show (↥(fixed_points (mul_left_cosets H H)) : Type u), from ⟨⟦x⟧, mem_fixed_points_mul_left_cosets_iff_mem_normalizer.2 x.2⟩) (λ ⟨x, hx⟩ ⟨y, hy⟩ (hxy : x⁻¹ * y ∈ H), subtype.eq (quotient.sound hxy)), (@quotient.induction_on _ (left_rel {x : normalizer H | ↑x ∈ H}) _ x (by intro x; cases x with x hx; exact mem_fixed_points_mul_left_cosets_iff_mem_normalizer.2 hx))⟩, left_inv := λ ⟨x, hx⟩, by revert hx; exact quotient.induction_on x (by intros; refl), right_inv := λ x, @quotient.induction_on _ (left_rel {x : normalizer H | ↑x ∈ H}) _ x (by intro x; cases x; refl) } lemma exists_subgroup_card_pow_prime [fintype G] {p : ℕ} : ∀ {n : ℕ} (hp : nat.prime p) (hdvd : p ^ n ∣ card G), ∃ H : set G, is_subgroup H ∧ card H = p ^ n | 0 := λ _ _, ⟨trivial G, by apply_instance, by simp [-set.set_coe_eq_subtype]⟩ | (n+1) := λ hp hdvd, let ⟨H, ⟨hH1, hH2⟩⟩ := exists_subgroup_card_pow_prime hp (dvd.trans (pow_dvd_pow _ (le_succ _)) hdvd) in let ⟨s, hs⟩ := exists_eq_mul_left_of_dvd hdvd in by exactI have hcard : card (left_cosets H) = s * p := (nat.mul_right_inj (show card H > 0, from fintype.card_pos_iff.2 ⟨⟨1, is_submonoid.one_mem H⟩⟩)).1 (by rwa [← card_eq_card_cosets_mul_card_subgroup, hH2, hs, nat.pow_succ, mul_assoc, mul_comm p]), have hm : s * p % p = card (left_cosets {x : normalizer H | ↑x ∈ H}) % p := card_congr (fixed_points_mul_left_cosets_equiv_cosets H) ▸ hcard ▸ card_modeq_card_fixed_points _ hp hH2, have hm' : p ∣ card (left_cosets {x : normalizer H | ↑x ∈ H}) := nat.dvd_of_mod_eq_zero (by rwa [nat.mod_eq_zero_of_dvd (dvd_mul_left _ _), eq_comm] at hm), let ⟨x, hx⟩ := exists_prime_order_of_dvd_card hp hm' in have hxcard : card (gpowers x) = p := by rwa ← order_eq_card_gpowers, let S : set ↥(normalizer H) := set.preimage (@quotient.mk _ (left_rel {x : ↥(normalizer H) | ↑x ∈ H})) (@gpowers (left_cosets {x : ↥(normalizer H) | ↑x ∈ H}) _ x) in have is_subgroup S := @is_group_hom.preimage _ (left_cosets {x : ↥(normalizer H) | ↑x ∈ H}) _ _ _ _ _ _, have fS : fintype S := by apply_instance, let hequiv : {x : ↥(normalizer H) | ↑x ∈ H} ≃ H := { to_fun := λ ⟨x, hx⟩, ⟨x, hx⟩, inv_fun := λ ⟨x, hx⟩, ⟨⟨x, subset_normalizer _ hx⟩, hx⟩, left_inv := λ ⟨⟨_, _⟩, _⟩, rfl, right_inv := λ ⟨_, _⟩, rfl } in ⟨subtype.val '' S, by apply_instance, by dsimp only [S]; rw [set.card_image_of_injective _ subtype.val_injective, nat.pow_succ, @card_congr _ _ fS _ (preimage_quotient_mk_equiv_subgroup_times_set _ _), card_prod, hxcard, ← hH2, card_congr hequiv]⟩ def conjugate_set (x : G) (H : set G) : set G := (λ n, x⁻¹ * n * x) ⁻¹' H lemma conjugate_set_eq_image (H : set G) (x : G) : conjugate_set x H = (λ n, x * n * x⁻¹) '' H := eq.symm (congr_fun (set.image_eq_preimage_of_inverse (λ _, by simp [mul_assoc]) (λ _, by simp [mul_assoc])) _) lemma conjugate_set_eq_preimage (H : set G) (x : G) : conjugate_set x H = (λ n, x⁻¹ * n * x) ⁻¹' H := rfl instance conjugate_set.is_group_action : is_group_action (@conjugate_set G _) := { one := λ H, by simp [conjugate_set_eq_image, set.image], mul := λ x y H, by simp [mul_inv_rev, mul_assoc, function.comp, conjugate_set_eq_preimage, set.preimage] } @[simp] lemma conjugate_set_normal_subgroup (H : set G) [normal_subgroup H] (x : G) : conjugate_set x H = H := set.ext (λ n, ⟨λ h : _ ∈ H, by have := normal_subgroup.normal _ h x; simpa [mul_assoc] using this, λ h, show _ ∈ H, by have := normal_subgroup.normal _ h (x⁻¹); by simpa using this⟩) instance is_group_action.subgroup (H : set G) [is_subgroup H] (f : G → α → α) [is_group_action f] : is_group_action (λ x : H, f x) := { one := λ a, is_monoid_action.one f a, mul := λ ⟨x, hx⟩ ⟨y, hy⟩ a, is_monoid_action.mul f x y a } instance is_group_hom_conj (x : G) : is_group_hom (λ (n : G), x * n * x⁻¹) := ⟨by simp [mul_assoc]⟩ instance is_subgroup_conj (x : G) (H : set G) [is_subgroup H] : is_subgroup (conjugate_set x H) := by rw conjugate_set_eq_image; apply_instance /-- `dlogn p a` gives the maximum value of `n` such that `p ^ n ∣ a` -/ def dlogn (p : ℕ) : ℕ → ℕ | 0 := 0 | (a+1) := if h : p > 1 then have (a + 1) / p < a + 1, from div_lt_self dec_trivial h, if p ∣ (a + 1) then dlogn ((a + 1) / p) + 1 else 0 else 0 lemma dlogn_dvd {p : ℕ} : ∀ a, p > 1 → p ^ dlogn p a ∣ a | 0 := λ _, dvd_zero _ | (a+1) := λ h, have (a + 1) / p < a + 1, from div_lt_self dec_trivial h, begin rw [dlogn, if_pos h], split_ifs with hd, { rw nat.pow_succ, conv { to_rhs, rw ← nat.div_mul_cancel hd }, exact mul_dvd_mul (dlogn_dvd _ h) (dvd_refl _) }, { simp } end lemma not_dvd_of_gt_dlogn {p : ℕ} : ∀ {a m}, a > 0 → p > 1 → m > dlogn p a → ¬p ^ m ∣ a | 0 := λ m h, (lt_irrefl _ h).elim | (a+1) := λ m h hp hm , have (a + 1) / p < a + 1, from div_lt_self dec_trivial hp, begin rw [dlogn, if_pos hp] at hm, split_ifs at hm with hd, { have hmsub : succ (m - 1) = m := succ_sub (show 1 ≤ m, from (lt_of_le_of_lt (nat.zero_le _) hm)) ▸ (succ_sub_one m).symm, have := @not_dvd_of_gt_dlogn ((a + 1) / p) (m - 1) (pos_of_mul_pos_left (by rw nat.mul_div_cancel' hd; exact nat.succ_pos _) (nat.zero_le p)) hp (lt_of_succ_lt_succ (hmsub.symm ▸ hm)), rwa [← nat.mul_dvd_mul_iff_right (lt_trans dec_trivial hp), nat.div_mul_cancel hd, ← nat.pow_succ, hmsub] at this }, { assume h, exact hd (calc p = p ^ 1 : (nat.pow_one _).symm ... ∣ p ^ m : nat.pow_dvd_pow p hm ... ∣ a + 1 : h) } end lemma pow_dvd_of_dvd_mul {p : ℕ} : ∀ {m n k : ℕ} (hp : prime p) (hd : p ^ m ∣ n * k) (hk : ¬p ∣ k), p ^ m ∣ n | 0 := by simp | (m+1) := λ n k hp hd hk, have hpnk : p ∣ n * k := calc p = p ^ 1 : by rw nat.pow_one ... ∣ p ^ (m + 1) : nat.pow_dvd_pow _ (succ_pos _) ... ∣ n * k : by assumption, have hpn : p ∣ n := or.resolve_right (hp.dvd_mul.1 hpnk) hk, have p ^ m ∣ (n / p) * k := dvd_of_mul_dvd_mul_right hp.pos $ by rwa [mul_right_comm, nat.div_mul_cancel hpn, ← nat.pow_succ], by rw [nat.pow_succ, ← nat.div_mul_cancel hpn]; exact mul_dvd_mul_right (pow_dvd_of_dvd_mul hp this hk) _ lemma eq_dlogn_of_dvd_of_succ_not_dvd {a p n : ℕ} (hp : 1 < p) (h₁ : p ^ n ∣ a) (h₂ : ¬p ^ succ n ∣ a) : n = dlogn p a := have ha : 0 < a := nat.pos_of_ne_zero (λ h, by simpa [h] using h₂), le_antisymm (le_of_not_gt $ λ h, not_dvd_of_gt_dlogn ha hp h h₁) (le_of_not_gt $ λ h, h₂ $ calc p ^ succ n ∣ p ^ dlogn p a : nat.pow_dvd_pow _ h ... ∣ _ : dlogn_dvd _ hp) lemma dlogn_eq_of_not_dvd {a b p : ℕ} (hp : prime p) (hpb : ¬p ∣ b) : dlogn p a = dlogn p (a * b) := if ha : a = 0 then by simp [ha, dlogn] else eq_dlogn_of_dvd_of_succ_not_dvd hp.gt_one (dvd.trans (dlogn_dvd _ hp.gt_one) (dvd_mul_right _ _)) (λ h, not_dvd_of_gt_dlogn (nat.pos_of_ne_zero ha) hp.gt_one (lt_succ_self _) (pow_dvd_of_dvd_mul hp h hpb)) lemma not_dvd_div_dlogn {p a : ℕ} (ha : a > 0) (hp : p > 1) : ¬p ∣ a / (p ^ dlogn p a) := by rw [← nat.mul_dvd_mul_iff_left (nat.pos_pow_of_pos (dlogn p a) (lt_trans dec_trivial hp)), nat.mul_div_cancel' (dlogn_dvd _ hp), ← nat.pow_succ]; exact not_dvd_of_gt_dlogn ha hp (lt_succ_self _) class is_sylow [fintype G] (H : set G) {p : ℕ} (hp : prime p) extends is_subgroup H : Prop := (card_eq : card H = p ^ dlogn p (card G)) instance is_subgroup_in_subgroup (H K : set G) [is_subgroup H] [is_subgroup K] : is_subgroup {x : K | (x : G) ∈ H} := { one_mem := show _ ∈ H, from one_mem _, mul_mem := λ x y hx hy, show x.1 * y.1 ∈ H, from mul_mem hx hy, inv_mem := λ x hx, show x.1⁻¹ ∈ H, from inv_mem hx } lemma exists_sylow_subgroup (G : Type u) [group G] [fintype G] {p : ℕ} (hp : prime p) : ∃ H : set G, is_sylow H hp := let ⟨H, ⟨hH₁, hH₂⟩⟩ := exists_subgroup_card_pow_prime hp (dlogn_dvd (card G) hp.gt_one) in by exactI ⟨H, by split; assumption⟩ lemma card_sylow [fintype G] (H : set G) [f : fintype H] {p : ℕ} (hp : prime p) [is_sylow H hp] : card H = p ^ dlogn p (card G) := by rw ← is_sylow.card_eq H hp; congr lemma is_sylow_in_subgroup [fintype G] (H K : set G) {p : ℕ} (hp : prime p) [is_sylow H hp] (hsub : H ⊆ K) [is_subgroup K] : is_sylow {x : K | (x : G) ∈ H} hp := { card_eq := have h₁ : H = subtype.val '' {x : K | (x : G) ∈ H}, from set.ext $ λ x, ⟨λ h, ⟨⟨x, hsub h⟩, ⟨h, rfl⟩⟩, λ ⟨y, hy⟩, hy.2 ▸ hy.1⟩, have h₂ : card K * (card G / card K) = card G := nat.mul_div_cancel' ((card_eq_card_cosets_mul_card_subgroup K).symm ▸ dvd_mul_left _ _), have h₃ : ∀ {f : fintype {x : K | (x : G) ∈ H}}, @fintype.card {x : K | (x : G) ∈ H} f = card H := λ f, by exactI calc @fintype.card {x : K | (x : G) ∈ H} f = card (subtype.val '' {x : K | (x : G) ∈ H}) : by exact (set.card_image_of_injective _ subtype.val_injective).symm ... = card H : set.card_eq_of_eq h₁.symm, calc _ = _ : h₃ ... = p ^ dlogn p (card G) : card_sylow H hp ... = p ^ dlogn p (card K) : congr_arg _ (h₂ ▸ eq.symm begin refine dlogn_eq_of_not_dvd hp (λ h, _), have h₄ := mul_dvd_mul_left (card K) h, rw [h₂, card_eq_card_cosets_mul_card_subgroup {x : K | (x : G) ∈ H}, h₃, card_sylow H hp, mul_assoc, ← nat.pow_succ] at h₄, exact not_dvd_of_gt_dlogn (fintype.card_pos_iff.2 ⟨(1 : G)⟩) hp.gt_one (lt_succ_self _) (dvd_of_mul_left_dvd h₄), end), ..sylow.is_subgroup_in_subgroup H K } lemma sylow_conjugate [fintype G] {p : ℕ} (hp : prime p) (H K : set G) [is_sylow H hp] [is_sylow K hp] : ∃ g : G, H = conjugate_set g K := have hs : card (left_cosets K) = card G / (p ^ dlogn p (card G)) := (nat.mul_right_inj (pos_pow_of_pos (dlogn p (card G)) hp.pos)).1 $ by rw [← card_sylow K hp, ← card_eq_card_cosets_mul_card_subgroup, card_sylow K hp, nat.div_mul_cancel (dlogn_dvd _ hp.gt_one)], have hmodeq : card G / (p ^ dlogn p (card G)) ≡ card (fixed_points (mul_left_cosets K H)) [MOD p] := hs ▸ card_modeq_card_fixed_points (mul_left_cosets K H) hp (card_sylow H hp), have hfixed : 0 < card (fixed_points (mul_left_cosets K H)) := nat.pos_of_ne_zero (λ h, (not_dvd_div_dlogn (fintype.card_pos_iff.2 ⟨(1 : G)⟩) hp.gt_one) $ by rwa [h, nat.modeq.modeq_zero_iff] at hmodeq), let ⟨⟨x, hx⟩⟩ := fintype.card_pos_iff.1 hfixed in begin haveI : is_subgroup K := by apply_instance, revert hx, refine quotient.induction_on x (λ x hx, ⟨x, set.eq_of_card_eq_of_subset _ _⟩), { rw [conjugate_set_eq_image, set.card_image_of_injective _ conj_inj_left, card_sylow K hp, card_sylow H hp] }, { assume y hy, have : (y⁻¹ * x)⁻¹ * x ∈ K := quotient.exact (mem_fixed_points'.1 hx ⟦y⁻¹ * x⟧ ⟨⟨y⁻¹, inv_mem hy⟩, rfl⟩), simp [conjugate_set_eq_preimage, set.preimage, mul_inv_rev, *, mul_assoc] at * } end def conj_on_sylow [fintype G] {p : ℕ} (hp : nat.prime p) : Π (x : G) (H : {H : set G // is_sylow H hp}), {H : set G // is_sylow H hp} := λ x ⟨H, hH⟩, ⟨conjugate_set x H, by exactI have h : is_subgroup (conjugate_set x H) := @sylow.is_subgroup_conj _ _ _ _ _, { card_eq := by exactI by rw [← card_sylow H hp, conjugate_set_eq_image, set.card_image_of_injective _ conj_inj_left], ..h }⟩ instance conj_on_sylow.is_group_action [fintype G] {p : ℕ} (hp : prime p) : is_group_action (@conj_on_sylow G _ _ _ hp) := { one := λ ⟨H, hH⟩, by simp [conj_on_sylow, conjugate_set_eq_preimage, set.preimage], mul := λ x y ⟨H, hH⟩, by simp! [mul_inv_rev, mul_assoc, function.comp, conjugate_set_eq_image, (set.image_comp _ _ _).symm, conj_on_sylow] } lemma card_sylow_dvd [fintype G] {p : ℕ} (hp : prime p) : card {H : set G // is_sylow H hp} ∣ card G := let ⟨H, hH⟩ := exists_sylow_subgroup G hp in have h : orbit (conj_on_sylow hp) ⟨H, hH⟩ = set.univ := set.eq_univ_iff_forall.2 (λ S, mem_orbit_iff.2 $ let ⟨x, (hx : S.val = _)⟩ := @sylow_conjugate _ _ _ _ hp S.1 H S.2 hH in ⟨x, subtype.eq (hx.symm ▸ rfl)⟩), have is_subgroup (stabilizer (conj_on_sylow hp) ⟨H, hH⟩) := by apply_instance, by exactI have orbit_equiv : card (orbit (conj_on_sylow hp) ⟨H, hH⟩) = fintype.card (left_cosets (stabilizer (conj_on_sylow hp) ⟨H, hH⟩)) := card_congr (orbit_equiv_left_cosets (conj_on_sylow hp) (⟨H, hH⟩ : {H : set G // is_sylow H hp})), by exactI begin rw [h, ← card_congr (set.equiv_univ _)] at orbit_equiv, rw [orbit_equiv, card_congr (@group_equiv_left_cosets_times_subgroup _ _ (stabilizer (conj_on_sylow hp) ⟨H, hH⟩) (by apply_instance)), card_prod], exact dvd_mul_right _ _ end lemma card_sylow_modeq_one [fintype G] {p : ℕ} (hp : prime p) : card {H : set G // is_sylow H hp} ≡ 1 [MOD p] := let ⟨H, hH⟩ := exists_sylow_subgroup G hp in by exactI eq.trans (card_modeq_card_fixed_points (λ x : H, conj_on_sylow hp (x : G)) hp (card_sylow H hp)) begin refine congr_fun (show (%) _ = (%) 1, from congr_arg _ (fintype.card_eq_one_iff.2 _)) p, refine ⟨(⟨(⟨H, hH⟩ : {H // is_sylow H hp}), λ ⟨x, hx⟩, subtype.eq $ set.ext (λ i, by simp [conj_on_sylow, conjugate_set_eq_preimage, mul_mem_cancel_left _ hx, mul_mem_cancel_right _ (inv_mem hx)])⟩ : subtype (fixed_points (λ (x : ↥H), conj_on_sylow hp ↑x))), _⟩, refine λ L, subtype.eq (subtype.eq _), rcases L with ⟨⟨L, hL₁⟩, hL₂⟩, have Hsub : H ⊆ normalizer L, { assume x hx n, conv {to_rhs, rw ← subtype.mk.inj (hL₂ ⟨x, hx⟩)}, simp [conjugate_set, mul_assoc] }, suffices : ∀ x, x ∈ {x : normalizer L | (x : G) ∈ L} ↔ x ∈ {x : normalizer L | (x : G) ∈ H}, { exact set.ext (λ x, ⟨λ h, (this ⟨x, subset_normalizer _ h⟩).1 h, λ h, (this ⟨x, Hsub h⟩).2 h⟩) }, assume x, haveI := is_sylow_in_subgroup L (normalizer L) hp (subset_normalizer L), haveI := is_sylow_in_subgroup H (normalizer L) hp Hsub, cases sylow_conjugate hp {x : normalizer L | (x : G) ∈ H} {x | (x : G) ∈ L} with x hx, simp [hx] end end sylow
86508e5c2a92ca6477934958178d8be646401cc2
453dcd7c0d1ef170b0843a81d7d8caedc9741dce
/group_theory/quotient_group.lean
e8aca2e90fa453baf4457397ef4bb61a2c932d56
[ "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
2,310
lean
/- Copyright (c) 2018 Kevin Buzzard and Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Patrick Massot. This file is to a certain extent based on `quotient_module.lean` by Johannes Hölzl. -/ import group_theory.coset universes u v variables {G : Type u} [group G] (N : set G) [normal_subgroup N] {H : Type v} [group H] local attribute [instance] left_rel normal_subgroup.to_is_subgroup definition quotient_group := left_cosets N local notation ` Q ` := quotient_group N instance : group Q := left_cosets.group N namespace group.quotient instance inhabited : inhabited Q := ⟨1⟩ def mk : G → Q := λ g, ⟦g⟧ instance is_group_hom_quotient_mk : is_group_hom (mk N) := by refine {..}; intros; refl def lift (φ : G → H) [is_group_hom φ] (HN : ∀x∈N, φ x = 1) (q : Q) : H := q.lift_on φ $ assume a b (hab : a⁻¹ * b ∈ N), (calc φ a = φ a * 1 : by simp ... = φ a * φ (a⁻¹ * b) : by rw HN (a⁻¹ * b) hab ... = φ (a * (a⁻¹ * b)) : by rw is_group_hom.mul φ a (a⁻¹ * b) ... = φ b : by simp) @[simp] lemma lift_mk {φ : G → H} [is_group_hom φ] (HN : ∀x∈N, φ x = 1) (g : G) : lift N φ HN ⟦g⟧ = φ g := rfl @[simp] lemma lift_mk' {φ : G → H} [is_group_hom φ] (HN : ∀x∈N, φ x = 1) (g : G) : lift N φ HN (mk N g) = φ g := rfl variables (φ : G → H) [is_group_hom φ] (HN : ∀x∈N, φ x = 1) instance is_group_hom_quotient_lift : is_group_hom (lift N φ HN) := ⟨λ q r, quotient.induction_on₂ q r $ λ a b, show φ (a * b) = φ a * φ b, from is_group_hom.mul φ a b⟩ open function is_group_hom lemma injective_ker_lift : injective (lift (ker φ) φ $ λ x h, (mem_ker φ).1 h) := assume a b, quotient.induction_on₂ a b $ assume a b (h : φ a = φ b), quotient.sound $ show a⁻¹ * b ∈ ker φ, by rw [mem_ker φ, is_group_hom.mul φ, ← h, is_group_hom.inv φ, inv_mul_self] end group.quotient namespace group variables {cG : Type u} [comm_group cG] (cN : set cG) [normal_subgroup cN] instance : comm_group (quotient_group cN) := { mul_comm := λ a b, quotient.induction_on₂ a b $ λ g h, show ⟦g * h⟧ = ⟦h * g⟧, by rw [mul_comm g h], ..left_cosets.group cN } end group
1fb9db677e3bb1cf45a57906411e273681a4be97
88892181780ff536a81e794003fe058062f06758
/src/projecteuler/all.lean
a4520c1abccb8c93f8cf07e41ffc010d237d71fd
[]
no_license
AtnNn/lean-sandbox
fe2c44280444e8bb8146ab8ac391c82b480c0a2e
8c68afbdc09213173aef1be195da7a9a86060a97
refs/heads/master
1,623,004,395,876
1,579,969,507,000
1,579,969,507,000
146,666,368
0
0
null
null
null
null
UTF-8
Lean
false
false
17
lean
import .problem1
0be617465f78dd7affb7b8621e0a33ebcb9b4ce1
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/compiler/t1.lean
f5b115b451d951a27c97cbbedfaf51b56cc85f33
[ "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
78
lean
def main (xs : List String) : IO UInt32 := IO.println "hello world" *> pure 0
38287a091fc44a7c742e4cf7a40e39b819f78b91
c465bc191b95d7a9e7544551279b09708d373f58
/standards/time_std.lean
be86b35c6bdb597f1c2071d7e2055018bda418d0
[]
no_license
kevinsullivan/physvm_develop
b7a4149c72a10b3a87894c5db5af9b2ce5885c80
a57e9c87d4d3fb7548dc6dfae3b932a51fc25b67
refs/heads/main
1,692,010,146,359
1,633,989,164,000
1,633,989,164,000
397,360,532
0
1
null
null
null
null
UTF-8
Lean
false
false
330
lean
import ..phys.time.time /- Units are in seconds. Seconds are the smallest non-variable unit in UTC. -/ noncomputable def coordinated_universal_time_in_seconds : time_space _ := let origin := mk_time time_std_space (1970*365*24*60*60) in let basis := mk_duration time_std_space 1 in mk_space (mk_time_frame origin basis)
c2665852616fd31504479887c2aceff4d7222d5e
491068d2ad28831e7dade8d6dff871c3e49d9431
/library/data/real/division.lean
ec1b9820ee965867e460de0fec29d9d521c6deb0
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,736
lean
/- Copyright (c) 2015 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis The real numbers, constructed as equivalence classes of Cauchy sequences of rationals. This construction follows Bishop and Bridges (1985). At this point, we no longer proceed constructively: this file makes heavy use of decidability and excluded middle. -/ import data.real.basic data.real.order data.rat data.nat open -[coercions] rat open -[coercions] nat open eq.ops pnat classical local notation 0 := rat.of_num 0 local notation 1 := rat.of_num 1 local notation 2 := subtype.tag (nat.of_num 2) dec_trivial namespace rat_seq ----------------------------- -- Facts about absolute values of sequences, to define inverse definition s_abs (s : seq) : seq := λ n, abs (s n) theorem abs_reg_of_reg {s : seq} (Hs : regular s) : regular (s_abs s) := begin intros, apply rat.le.trans, apply abs_abs_sub_abs_le_abs_sub, apply Hs end theorem abs_pos_of_nonzero {s : seq} (Hs : regular s) (Hnz : sep s zero) : ∃ N : ℕ+, ∀ m : ℕ+, m ≥ N → abs (s m) ≥ N⁻¹ := begin rewrite [↑sep at Hnz, ↑s_lt at Hnz], apply or.elim Hnz, intro Hnz1, have H' : pos (sneg s), begin apply pos_of_pos_equiv, rotate 2, apply Hnz1, rotate 1, apply s_zero_add, repeat (assumption | apply reg_add_reg | apply reg_neg_reg | apply zero_is_reg) end, cases bdd_away_of_pos (reg_neg_reg Hs) H' with [N, HN], existsi N, intro m Hm, apply rat.le.trans, apply HN m Hm, rewrite ↑sneg, apply neg_le_abs_self, intro Hnz2, let H' := pos_of_pos_equiv (reg_add_reg Hs (reg_neg_reg zero_is_reg)) (s_add_zero s Hs) Hnz2, let H'' := bdd_away_of_pos Hs H', cases H'' with [N, HN], existsi N, intro m Hm, apply rat.le.trans, apply HN m Hm, apply le_abs_self end theorem abs_well_defined {s t : seq} (Hs : regular s) (Ht : regular t) (Heq : s ≡ t) : s_abs s ≡ s_abs t := begin rewrite [↑equiv at *], intro n, rewrite ↑s_abs, apply rat.le.trans, apply abs_abs_sub_abs_le_abs_sub, apply Heq end theorem sep_zero_of_pos {s : seq} (Hs : regular s) (Hpos : pos s) : sep s zero := begin apply or.inr, apply pos_of_pos_equiv, rotate 2, apply Hpos, apply Hs, apply equiv.symm, apply s_sub_zero Hs end ------------------------ -- This section could be cleaned up. private noncomputable definition pb {s : seq} (Hs : regular s) (Hpos : pos s) := some (abs_pos_of_nonzero Hs (sep_zero_of_pos Hs Hpos)) private noncomputable definition ps {s : seq} (Hs : regular s) (Hsep : sep s zero) := some (abs_pos_of_nonzero Hs Hsep) private theorem pb_spec {s : seq} (Hs : regular s) (Hpos : pos s) : ∀ m : ℕ+, m ≥ (pb Hs Hpos) → abs (s m) ≥ (pb Hs Hpos)⁻¹ := some_spec (abs_pos_of_nonzero Hs (sep_zero_of_pos Hs Hpos)) private theorem ps_spec {s : seq} (Hs : regular s) (Hsep : sep s zero) : ∀ m : ℕ+, m ≥ (ps Hs Hsep) → abs (s m) ≥ (ps Hs Hsep)⁻¹ := some_spec (abs_pos_of_nonzero Hs Hsep) noncomputable definition s_inv {s : seq} (Hs : regular s) (n : ℕ+) : ℚ := if H : sep s zero then (if n < (ps Hs H) then 1 / (s ((ps Hs H) * (ps Hs H) * (ps Hs H))) else 1 / (s ((ps Hs H) * (ps Hs H) * n))) else 0 private theorem peq {s : seq} (Hsep : sep s zero) (Hpos : pos s) (Hs : regular s) : pb Hs Hpos = ps Hs Hsep := rfl private theorem s_inv_of_sep_lt_p {s : seq} (Hs : regular s) (Hsep : sep s zero) {n : ℕ+} (Hn : n < (ps Hs Hsep)) : s_inv Hs n = 1 / s ((ps Hs Hsep) * (ps Hs Hsep) * (ps Hs Hsep)) := begin apply eq.trans, apply dif_pos Hsep, apply dif_pos Hn end private theorem s_inv_of_sep_gt_p {s : seq} (Hs : regular s) (Hsep : sep s zero) {n : ℕ+} (Hn : n ≥ (ps Hs Hsep)) : s_inv Hs n = 1 / s ((ps Hs Hsep) * (ps Hs Hsep) * n) := begin apply eq.trans, apply dif_pos Hsep, apply dif_neg (pnat.not_lt_of_ge Hn) end private theorem s_inv_of_pos_lt_p {s : seq} (Hs : regular s) (Hpos : pos s) {n : ℕ+} (Hn : n < (pb Hs Hpos)) : s_inv Hs n = 1 / s ((pb Hs Hpos) * (pb Hs Hpos) * (pb Hs Hpos)) := s_inv_of_sep_lt_p Hs (sep_zero_of_pos Hs Hpos) Hn private theorem s_inv_of_pos_gt_p {s : seq} (Hs : regular s) (Hpos : pos s) {n : ℕ+} (Hn : n ≥ (pb Hs Hpos)) : s_inv Hs n = 1 / s ((pb Hs Hpos) * (pb Hs Hpos) * n) := s_inv_of_sep_gt_p Hs (sep_zero_of_pos Hs Hpos) Hn private theorem le_ps {s : seq} (Hs : regular s) (Hsep : sep s zero) (n : ℕ+) : abs (s_inv Hs n) ≤ (rat_of_pnat (ps Hs Hsep)) := if Hn : n < ps Hs Hsep then (begin rewrite [(s_inv_of_sep_lt_p Hs Hsep Hn), abs_one_div], apply div_le_pnat, apply ps_spec, apply pnat.mul_le_mul_left end) else (begin rewrite [(s_inv_of_sep_gt_p Hs Hsep (le_of_not_gt Hn)), abs_one_div], apply div_le_pnat, apply ps_spec, rewrite pnat.mul.assoc, apply pnat.mul_le_mul_right end) theorem s_inv_zero : s_inv zero_is_reg = zero := funext (λ n, dif_neg (!not_sep_self)) private theorem s_inv_of_zero' {s : seq} (Hs : regular s) (Hz : ¬ sep s zero) (n : ℕ+) : s_inv Hs n = 0 := dif_neg Hz theorem s_inv_of_zero {s : seq} (Hs : regular s) (Hz : ¬ sep s zero) : s_inv Hs = zero := begin apply funext, intro n, apply s_inv_of_zero' Hs Hz n end private theorem s_ne_zero_of_ge_p {s : seq} (Hs : regular s) (Hsep : sep s zero) {n : ℕ+} (Hn : n ≥ (ps Hs Hsep)) : s n ≠ 0 := begin let Hps := ps_spec Hs Hsep, apply ne_zero_of_abs_ne_zero, apply ne_of_gt, apply gt_of_ge_of_gt, apply Hps, apply Hn, apply inv_pos end theorem reg_inv_reg {s : seq} (Hs : regular s) (Hsep : sep s zero) : regular (s_inv Hs) := begin rewrite ↑regular, intros, have Hsp : s ((ps Hs Hsep) * (ps Hs Hsep) * (ps Hs Hsep)) ≠ 0, from s_ne_zero_of_ge_p Hs Hsep !mul_le_mul_left, have Hspn : s ((ps Hs Hsep) * (ps Hs Hsep) * n) ≠ 0, from s_ne_zero_of_ge_p Hs Hsep (show (ps Hs Hsep) * (ps Hs Hsep) * n ≥ ps Hs Hsep, by rewrite pnat.mul.assoc; apply pnat.mul_le_mul_right), have Hspm : s ((ps Hs Hsep) * (ps Hs Hsep) * m) ≠ 0, from s_ne_zero_of_ge_p Hs Hsep (show (ps Hs Hsep) * (ps Hs Hsep) * m ≥ ps Hs Hsep, by rewrite pnat.mul.assoc; apply pnat.mul_le_mul_right), cases em (m < ps Hs Hsep) with [Hmlt, Hmlt], cases em (n < ps Hs Hsep) with [Hnlt, Hnlt], rewrite [(s_inv_of_sep_lt_p Hs Hsep Hmlt), (s_inv_of_sep_lt_p Hs Hsep Hnlt)], rewrite [sub_self, abs_zero], apply add_invs_nonneg, rewrite [(s_inv_of_sep_lt_p Hs Hsep Hmlt), (s_inv_of_sep_gt_p Hs Hsep (le_of_not_gt Hnlt))], rewrite [(!div_sub_div Hsp Hspn), div_eq_mul_one_div, *abs_mul, *mul_one, *one_mul], apply rat.le.trans, apply rat.mul_le_mul, apply Hs, rewrite [-(mul_one 1), -(!field.div_mul_div Hsp Hspn), abs_mul], apply rat.mul_le_mul, rewrite -(s_inv_of_sep_lt_p Hs Hsep Hmlt), apply le_ps Hs Hsep, rewrite -(s_inv_of_sep_gt_p Hs Hsep (le_of_not_gt Hnlt)), apply le_ps Hs Hsep, apply abs_nonneg, apply le_of_lt !rat_of_pnat_is_pos, apply abs_nonneg, apply add_invs_nonneg, rewrite [right_distrib, *pnat_cancel', rat.add.comm], apply rat.add_le_add_right, apply inv_ge_of_le, apply pnat.le_of_lt, apply Hmlt, cases em (n < ps Hs Hsep) with [Hnlt, Hnlt], rewrite [(s_inv_of_sep_lt_p Hs Hsep Hnlt), (s_inv_of_sep_gt_p Hs Hsep (le_of_not_gt Hmlt))], rewrite [(!div_sub_div Hspm Hsp), div_eq_mul_one_div, *abs_mul, *mul_one, *one_mul], apply rat.le.trans, apply rat.mul_le_mul, apply Hs, rewrite [-(mul_one 1), -(!field.div_mul_div Hspm Hsp), abs_mul], apply rat.mul_le_mul, rewrite -(s_inv_of_sep_gt_p Hs Hsep (le_of_not_gt Hmlt)), apply le_ps Hs Hsep, rewrite -(s_inv_of_sep_lt_p Hs Hsep Hnlt), apply le_ps Hs Hsep, apply abs_nonneg, apply le_of_lt !rat_of_pnat_is_pos, apply abs_nonneg, apply add_invs_nonneg, rewrite [right_distrib, *pnat_cancel', rat.add.comm], apply rat.add_le_add_left, apply inv_ge_of_le, apply pnat.le_of_lt, apply Hnlt, rewrite [(s_inv_of_sep_gt_p Hs Hsep (le_of_not_gt Hnlt)), (s_inv_of_sep_gt_p Hs Hsep (le_of_not_gt Hmlt))], rewrite [(!div_sub_div Hspm Hspn), div_eq_mul_one_div, abs_mul, *one_mul, *mul_one], apply rat.le.trans, apply rat.mul_le_mul, apply Hs, rewrite [-(mul_one 1), -(!field.div_mul_div Hspm Hspn), abs_mul], apply rat.mul_le_mul, rewrite -(s_inv_of_sep_gt_p Hs Hsep (le_of_not_gt Hmlt)), apply le_ps Hs Hsep, rewrite -(s_inv_of_sep_gt_p Hs Hsep (le_of_not_gt Hnlt)), apply le_ps Hs Hsep, apply abs_nonneg, apply le_of_lt !rat_of_pnat_is_pos, apply abs_nonneg, apply add_invs_nonneg, rewrite [right_distrib, *pnat_cancel', rat.add.comm], apply rat.le.refl end theorem s_inv_ne_zero {s : seq} (Hs : regular s) (Hsep : sep s zero) (n : ℕ+) : s_inv Hs n ≠ 0 := if H : n ≥ ps Hs Hsep then (begin rewrite (s_inv_of_sep_gt_p Hs Hsep H), apply one_div_ne_zero, apply s_ne_zero_of_ge_p, apply pnat.le.trans, apply H, apply pnat.mul_le_mul_left end) else (begin rewrite (s_inv_of_sep_lt_p Hs Hsep (lt_of_not_ge H)), apply one_div_ne_zero, apply s_ne_zero_of_ge_p, apply pnat.mul_le_mul_left end) theorem mul_inv {s : seq} (Hs : regular s) (Hsep : sep s zero) : smul s (s_inv Hs) ≡ one := begin let Rsi := reg_inv_reg Hs Hsep, let Rssi := reg_mul_reg Hs Rsi, apply eq_of_bdd Rssi one_is_reg, intros, existsi max (ps Hs Hsep) j, intro n Hn, have Hnz : s_inv Hs ((K₂ s (s_inv Hs)) * 2 * n) ≠ 0, from s_inv_ne_zero Hs Hsep _, rewrite [↑smul, ↑one, rat.mul.comm, -(mul_one_div_cancel Hnz), -rat.mul_sub_left_distrib, abs_mul], apply rat.le.trans, apply rat.mul_le_mul_of_nonneg_right, apply canon_2_bound_right s, apply Rsi, apply abs_nonneg, have Hp : (K₂ s (s_inv Hs)) * 2 * n ≥ ps Hs Hsep, begin apply pnat.le.trans, apply max_left, rotate 1, apply pnat.le.trans, apply Hn, apply pnat.mul_le_mul_left end, have Hnz' : s (((ps Hs Hsep) * (ps Hs Hsep)) * ((K₂ s (s_inv Hs)) * 2 * n)) ≠ 0, from s_ne_zero_of_ge_p Hs Hsep (show ps Hs Hsep ≤ ((ps Hs Hsep) * (ps Hs Hsep)) * ((K₂ s (s_inv Hs)) * 2 * n), by rewrite *pnat.mul.assoc; apply pnat.mul_le_mul_right), rewrite [(s_inv_of_sep_gt_p Hs Hsep Hp), (division_ring.one_div_one_div Hnz')], apply rat.le.trans, apply rat.mul_le_mul_of_nonneg_left, apply Hs, apply le_of_lt, apply rat_of_pnat_is_pos, rewrite [rat.mul.left_distrib, mul.comm ((ps Hs Hsep) * (ps Hs Hsep)), *pnat.mul.assoc, *(@inv_mul_eq_mul_inv (K₂ s (s_inv Hs))), -*rat.mul.assoc, *inv_cancel_left, *one_mul, -(add_halves j)], apply rat.add_le_add, apply inv_ge_of_le, apply pnat_mul_le_mul_left', apply pnat.le.trans, rotate 1, apply Hn, rotate_right 1, apply max_right, apply inv_ge_of_le, apply pnat_mul_le_mul_left', apply pnat.le.trans, apply max_right, rotate 1, apply pnat.le.trans, apply Hn, apply pnat.mul_le_mul_right end theorem inv_mul {s : seq} (Hs : regular s) (Hsep : sep s zero) : smul (s_inv Hs) s ≡ one := begin apply equiv.trans, rotate 3, apply s_mul_comm, apply mul_inv, repeat (assumption | apply reg_mul_reg | apply reg_inv_reg | apply zero_is_reg) end theorem sep_of_equiv_sep {s t : seq} (Hs : regular s) (Ht : regular t) (Heq : s ≡ t) (Hsep : sep s zero) : sep t zero := begin apply or.elim Hsep, intro Hslt, apply or.inl, rewrite ↑s_lt at *, apply pos_of_pos_equiv, rotate 2, apply Hslt, rotate_right 1, apply add_well_defined, rotate 4, apply equiv.refl, apply neg_well_defined, apply Heq, intro Hslt, apply or.inr, rewrite ↑s_lt at *, apply pos_of_pos_equiv, rotate 2, apply Hslt, rotate_right 1, apply add_well_defined, rotate 5, apply equiv.refl, repeat (assumption | apply reg_neg_reg | apply reg_add_reg | apply zero_is_reg) end theorem inv_unique {s t : seq} (Hs : regular s) (Ht : regular t) (Hsep : sep s zero) (Heq : smul s t ≡ one) : s_inv Hs ≡ t := begin apply equiv.trans, rotate 3, apply equiv.symm, apply s_mul_one, rotate 1, apply equiv.trans, rotate 3, apply mul_well_defined, rotate 4, apply equiv.refl, apply equiv.symm, apply Heq, apply equiv.trans, rotate 3, apply equiv.symm, apply s_mul_assoc, rotate 3, apply equiv.trans, rotate 3, apply mul_well_defined, rotate 4, apply inv_mul, rotate 1, apply equiv.refl, apply s_one_mul, repeat (assumption | apply reg_inv_reg | apply reg_mul_reg | apply one_is_reg) end theorem inv_well_defined {s t : seq} (Hs : regular s) (Ht : regular t) (Heq : s ≡ t) : s_inv Hs ≡ s_inv Ht := if Hsep : sep s zero then (begin let Hsept := sep_of_equiv_sep Hs Ht Heq Hsep, have Hm : smul t (s_inv Hs) ≡ smul s (s_inv Hs), begin apply mul_well_defined, repeat (assumption | apply reg_inv_reg), apply equiv.symm s t Heq, apply equiv.refl end, apply equiv.symm, apply inv_unique, rotate 2, apply equiv.trans, rotate 3, apply Hm, apply mul_inv, repeat (assumption | apply reg_inv_reg | apply reg_mul_reg), apply one_is_reg end) else (have H : s_inv Hs = zero, from funext (λ n, dif_neg Hsep), have Hsept : ¬ sep t zero, from assume H', Hsep (sep_of_equiv_sep Ht Hs (equiv.symm _ _ Heq) H'), have H' : s_inv Ht = zero, from funext (λ n, dif_neg Hsept), H'⁻¹ ▸ (H⁻¹ ▸ equiv.refl zero)) theorem s_neg_neg {s : seq} : sneg (sneg s) ≡ s := begin rewrite [↑equiv, ↑sneg], intro n, rewrite [neg_neg, sub_self, abs_zero], apply add_invs_nonneg end theorem s_neg_sub {s t : seq} (Hs : regular s) (Ht : regular t) : sneg (sadd s (sneg t)) ≡ sadd t (sneg s) := begin apply equiv.trans, rotate 3, apply s_neg_add_eq_s_add_neg, apply equiv.trans, rotate 3, apply add_well_defined, rotate 4, apply equiv.refl, apply s_neg_neg, apply s_add_comm, repeat (assumption | apply reg_add_reg | apply reg_neg_reg) end theorem s_le_total {s t : seq} (Hs : regular s) (Ht : regular t) : s_le s t ∨ s_le t s := if H : s_le s t then or.inl H else or.inr begin rewrite [↑s_le at *], have H' : ∃ n : ℕ+, -n⁻¹ > sadd t (sneg s) n, begin apply by_contradiction, intro Hex, have Hex' : ∀ n : ℕ+, -n⁻¹ ≤ sadd t (sneg s) n, begin intro m, apply by_contradiction, intro Hm, let Hm' := rat.lt_of_not_ge Hm, let Hex'' := exists.intro m Hm', apply Hex Hex'' end, apply H Hex' end, eapply exists.elim H', intro m Hm, let Hm' := neg_lt_neg Hm, rewrite neg_neg at Hm', apply s_nonneg_of_pos, rotate 1, apply pos_of_pos_equiv, rotate 1, apply s_neg_sub, rotate 2, rewrite [↑pos, ↑sneg], existsi m, apply Hm', repeat (assumption | apply reg_add_reg | apply reg_neg_reg) end theorem s_le_of_not_lt {s t : seq} (Hle : ¬ s_lt s t) : s_le t s := begin rewrite [↑s_le, ↑nonneg, ↑s_lt at Hle, ↑pos at Hle], let Hle' := iff.mp forall_iff_not_exists Hle, intro n, let Hn := neg_le_neg (rat.le_of_not_gt (Hle' n)), rewrite [↑sadd, ↑sneg, add_neg_eq_neg_add_rev], apply Hn end theorem sep_of_nequiv {s t : seq} (Hs : regular s) (Ht : regular t) (Hneq : ¬ equiv s t) : sep s t := begin rewrite ↑sep, apply by_contradiction, intro Hnor, let Hand := iff.mp !not_or_iff_not_and_not Hnor, let Hle1 := s_le_of_not_lt (and.left Hand), let Hle2 := s_le_of_not_lt (and.right Hand), apply Hneq (equiv_of_le_of_ge Hs Ht Hle2 Hle1) end theorem s_zero_inv_equiv_zero : s_inv zero_is_reg ≡ zero := by rewrite s_inv_zero; apply equiv.refl theorem lt_or_equiv_of_le {s t : seq} (Hs : regular s) (Ht : regular t) (Hle : s_le s t) : s_lt s t ∨ s ≡ t := if H : s ≡ t then or.inr H else or.inl (lt_of_le_and_sep Hs Ht (and.intro Hle (sep_of_nequiv Hs Ht H))) theorem s_le_of_equiv_le_left {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (Heq : s ≡ t) (Hle : s_le s u) : s_le t u := begin rewrite ↑s_le at *, apply nonneg_of_nonneg_equiv, rotate 2, apply add_well_defined, rotate 4, apply equiv.refl, apply neg_well_defined, apply Heq, repeat (assumption | apply reg_add_reg | apply reg_neg_reg) end theorem s_le_of_equiv_le_right {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (Heq : t ≡ u) (Hle : s_le s t) : s_le s u := begin rewrite ↑s_le at *, apply nonneg_of_nonneg_equiv, rotate 2, apply add_well_defined, rotate 4, apply Heq, apply equiv.refl, repeat (assumption | apply reg_add_reg | apply reg_neg_reg) end ----------------------------- noncomputable definition r_inv (s : reg_seq) : reg_seq := reg_seq.mk (s_inv (reg_seq.is_reg s)) (if H : sep (reg_seq.sq s) zero then reg_inv_reg (reg_seq.is_reg s) H else have Hz : s_inv (reg_seq.is_reg s) = zero, from funext (λ n, dif_neg H), Hz⁻¹ ▸ zero_is_reg) theorem r_inv_zero : requiv (r_inv r_zero) r_zero := s_zero_inv_equiv_zero theorem r_inv_well_defined {s t : reg_seq} (H : requiv s t) : requiv (r_inv s) (r_inv t) := inv_well_defined (reg_seq.is_reg s) (reg_seq.is_reg t) H theorem r_le_total (s t : reg_seq) : r_le s t ∨ r_le t s := s_le_total (reg_seq.is_reg s) (reg_seq.is_reg t) theorem r_mul_inv (s : reg_seq) (Hsep : r_sep s r_zero) : requiv (s * (r_inv s)) r_one := mul_inv (reg_seq.is_reg s) Hsep theorem r_sep_of_nequiv (s t : reg_seq) (Hneq : ¬ requiv s t) : r_sep s t := sep_of_nequiv (reg_seq.is_reg s) (reg_seq.is_reg t) Hneq theorem r_lt_or_equiv_of_le (s t : reg_seq) (Hle : r_le s t) : r_lt s t ∨ requiv s t := lt_or_equiv_of_le (reg_seq.is_reg s) (reg_seq.is_reg t) Hle theorem r_le_of_equiv_le_left {s t u : reg_seq} (Heq : requiv s t) (Hle : r_le s u) : r_le t u := s_le_of_equiv_le_left (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) Heq Hle theorem r_le_of_equiv_le_right {s t u : reg_seq} (Heq : requiv t u) (Hle : r_le s t) : r_le s u := s_le_of_equiv_le_right (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) Heq Hle definition r_abs (s : reg_seq) : reg_seq := reg_seq.mk (s_abs (reg_seq.sq s)) (abs_reg_of_reg (reg_seq.is_reg s)) theorem r_abs_well_defined {s t : reg_seq} (H : requiv s t) : requiv (r_abs s) (r_abs t) := abs_well_defined (reg_seq.is_reg s) (reg_seq.is_reg t) H end rat_seq namespace real open [classes] rat_seq noncomputable definition inv (x : ℝ) : ℝ := quot.lift_on x (λ a, quot.mk (rat_seq.r_inv a)) (λ a b H, quot.sound (rat_seq.r_inv_well_defined H)) postfix [priority real.prio] `⁻¹` := inv theorem le_total (x y : ℝ) : x ≤ y ∨ y ≤ x := quot.induction_on₂ x y (λ s t, rat_seq.r_le_total s t) theorem mul_inv' (x : ℝ) : x ≢ 0 → x * x⁻¹ = 1 := quot.induction_on x (λ s H, quot.sound (rat_seq.r_mul_inv s H)) theorem inv_mul' (x : ℝ) : x ≢ 0 → x⁻¹ * x = 1 := by rewrite real.mul_comm; apply mul_inv' theorem neq_of_sep {x y : ℝ} (H : x ≢ y) : ¬ x = y := assume Heq, !not_sep_self (Heq ▸ H) theorem sep_of_neq {x y : ℝ} : ¬ x = y → x ≢ y := quot.induction_on₂ x y (λ s t H, rat_seq.r_sep_of_nequiv s t (assume Heq, H (quot.sound Heq))) theorem sep_is_neq (x y : ℝ) : (x ≢ y) = (¬ x = y) := propext (iff.intro neq_of_sep sep_of_neq) theorem mul_inv (x : ℝ) : x ≠ 0 → x * x⁻¹ = 1 := !sep_is_neq ▸ !mul_inv' theorem inv_mul (x : ℝ) : x ≠ 0 → x⁻¹ * x = 1 := !sep_is_neq ▸ !inv_mul' theorem inv_zero : (0 : ℝ)⁻¹ = 0 := quot.sound (rat_seq.r_inv_zero) theorem lt_or_eq_of_le (x y : ℝ) : x ≤ y → x < y ∨ x = y := quot.induction_on₂ x y (λ s t H, or.elim (rat_seq.r_lt_or_equiv_of_le s t H) (assume H1, or.inl H1) (assume H2, or.inr (quot.sound H2))) theorem le_iff_lt_or_eq (x y : ℝ) : x ≤ y ↔ x < y ∨ x = y := iff.intro (lt_or_eq_of_le x y) (le_of_lt_or_eq x y) noncomputable definition dec_lt : decidable_rel lt := begin rewrite ↑decidable_rel, intros, apply prop_decidable end section migrate_algebra open [classes] algebra protected noncomputable definition discrete_linear_ordered_field [reducible] : algebra.discrete_linear_ordered_field ℝ := ⦃ algebra.discrete_linear_ordered_field, real.comm_ring, real.ordered_ring, le_total := le_total, mul_inv_cancel := mul_inv, inv_mul_cancel := inv_mul, zero_lt_one := zero_lt_one, inv_zero := inv_zero, le_iff_lt_or_eq := le_iff_lt_or_eq, decidable_lt := dec_lt ⦄ local attribute real.discrete_linear_ordered_field [trans-instance] local attribute real.comm_ring [instance] local attribute real.ordered_ring [instance] noncomputable definition abs (n : ℝ) : ℝ := algebra.abs n noncomputable definition sign (n : ℝ) : ℝ := algebra.sign n noncomputable definition max (a b : ℝ) : ℝ := algebra.max a b noncomputable definition min (a b : ℝ) : ℝ := algebra.min a b noncomputable definition divide (a b : ℝ): ℝ := algebra.divide a b migrate from algebra with real hiding dvd, dvd.elim, dvd.elim_left, dvd.intro, dvd.intro_left, dvd.refl, dvd.trans, dvd_mul_left, dvd_mul_of_dvd_left, dvd_mul_of_dvd_right, dvd_mul_right, dvd_neg_iff_dvd, dvd_neg_of_dvd, dvd_of_dvd_neg, dvd_of_mul_left_dvd, dvd_of_mul_left_eq, dvd_of_mul_right_dvd, dvd_of_mul_right_eq, dvd_of_neg_dvd, dvd_sub, dvd_zero replacing has_le.ge → ge, has_lt.gt → gt, sub → sub, abs → abs, sign → sign, divide → divide, max → max, min → min, pow → pow, nmul → nmul, imul → imul end migrate_algebra infix / := divide theorem of_rat_divide (x y : ℚ) : of_rat (x / y) = of_rat x / of_rat y := by_cases (assume yz : y = 0, by rewrite [yz, rat.div_zero, real.div_zero]) (assume ynz : y ≠ 0, have ynz' : of_rat y ≠ 0, from assume yz', ynz (of_rat.inj yz'), !eq_div_of_mul_eq ynz' (by rewrite [-of_rat_mul, !rat.div_mul_cancel ynz])) theorem of_int_div (x y : ℤ) (H : (#int y ∣ x)) : of_int (#int x div y) = of_int x / of_int y := by rewrite [of_int_eq, rat.of_int_div H, of_rat_divide] theorem of_nat_div (x y : ℕ) (H : (#nat y ∣ x)) : of_nat (#nat x div y) = of_nat x / of_nat y := by rewrite [of_nat_eq, rat.of_nat_div H, of_rat_divide] /- useful for proving equalities -/ theorem eq_zero_of_nonneg_of_forall_lt {x : ℝ} (xnonneg : x ≥ 0) (H : ∀ ε : ℝ, ε > 0 → x < ε) : x = 0 := decidable.by_contradiction (suppose x ≠ 0, have x > 0, from real.lt_of_le_of_ne xnonneg (ne.symm this), have x < x, from H x this, show false, from !lt.irrefl this) theorem eq_zero_of_nonneg_of_forall_le {x : ℝ} (xnonneg : x ≥ 0) (H : ∀ ε : ℝ, ε > 0 → x ≤ ε) : x = 0 := have ∀ ε : ℝ, ε > 0 → x < ε, from take ε, suppose ε > 0, have e2pos : ε / 2 > 0, from div_pos_of_pos_of_pos `ε > 0` two_pos, have ε / 2 < ε, from div_two_lt_of_pos `ε > 0`, calc x ≤ ε / 2 : H _ e2pos ... < ε : div_two_lt_of_pos (by assumption), eq_zero_of_nonneg_of_forall_lt xnonneg this theorem eq_zero_of_forall_abs_le {x : ℝ} (H : ∀ ε : ℝ, ε > 0 → abs x ≤ ε) : x = 0 := by_contradiction (suppose x ≠ 0, have abs x = 0, from eq_zero_of_nonneg_of_forall_le !abs_nonneg H, show false, from `x ≠ 0` (eq_zero_of_abs_eq_zero this)) theorem eq_of_forall_abs_sub_le {x y : ℝ} (H : ∀ ε : ℝ, ε > 0 → abs (x - y) ≤ ε) : x = y := have x - y = 0, from eq_zero_of_forall_abs_le H, eq_of_sub_eq_zero this end real
33d69c850a38378cb4e3355098c37474717e8dc0
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/number_theory/legendre_symbol/gauss_eisenstein_lemmas.lean
171dcc9523d6fbb679b5dd8974f371c69630f6fd
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
13,342
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 number_theory.legendre_symbol.quadratic_reciprocity /-! # Lemmas of Gauss and Eisenstein > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains the Lemmas of Gauss and Eisenstein on the Legendre symbol. The main results are `zmod.gauss_lemma` and `zmod.eisenstein_lemma`. -/ open finset nat open_locale big_operators nat section gauss_eisenstein namespace zmod /-- The image of the map sending a non zero natural number `x ≤ p / 2` to the absolute value of the element of interger in the interval `(-p/2, p/2]` congruent to `a * x` mod p is the set of non zero natural numbers `x` such that `x ≤ p / 2` -/ lemma Ico_map_val_min_abs_nat_abs_eq_Ico_map_id (p : ℕ) [hp : fact p.prime] (a : zmod p) (hap : a ≠ 0) : (Ico 1 (p / 2).succ).1.map (λ x, (a * x).val_min_abs.nat_abs) = (Ico 1 (p / 2).succ).1.map (λ a, a) := begin have he : ∀ {x}, x ∈ Ico 1 (p / 2).succ → x ≠ 0 ∧ x ≤ p / 2, by simp [nat.lt_succ_iff, nat.succ_le_iff, pos_iff_ne_zero] {contextual := tt}, have hep : ∀ {x}, x ∈ Ico 1 (p / 2).succ → x < p, from λ x hx, lt_of_le_of_lt (he hx).2 (nat.div_lt_self hp.1.pos dec_trivial), have hpe : ∀ {x}, x ∈ Ico 1 (p / 2).succ → ¬ p ∣ x, from λ x hx hpx, not_lt_of_ge (le_of_dvd (nat.pos_of_ne_zero (he hx).1) hpx) (hep hx), have hmem : ∀ (x : ℕ) (hx : x ∈ Ico 1 (p / 2).succ), (a * x : zmod p).val_min_abs.nat_abs ∈ Ico 1 (p / 2).succ, { assume x hx, simp [hap, char_p.cast_eq_zero_iff (zmod p) p, hpe hx, lt_succ_iff, succ_le_iff, pos_iff_ne_zero, nat_abs_val_min_abs_le _], }, have hsurj : ∀ (b : ℕ) (hb : b ∈ Ico 1 (p / 2).succ), ∃ x ∈ Ico 1 (p / 2).succ, b = (a * x : zmod p).val_min_abs.nat_abs, { assume b hb, refine ⟨(b / a : zmod p).val_min_abs.nat_abs, mem_Ico.mpr ⟨_, _⟩, _⟩, { apply nat.pos_of_ne_zero, simp only [div_eq_mul_inv, hap, char_p.cast_eq_zero_iff (zmod p) p, hpe hb, not_false_iff, val_min_abs_eq_zero, inv_eq_zero, int.nat_abs_eq_zero, ne.def, mul_eq_zero, or_self] }, { apply lt_succ_of_le, apply nat_abs_val_min_abs_le }, { rw nat_cast_nat_abs_val_min_abs, split_ifs, { erw [mul_div_cancel' _ hap, val_min_abs_def_pos, val_cast_of_lt (hep hb), if_pos (le_of_lt_succ (mem_Ico.1 hb).2), int.nat_abs_of_nat], }, { erw [mul_neg, mul_div_cancel' _ hap, nat_abs_val_min_abs_neg, val_min_abs_def_pos, val_cast_of_lt (hep hb), if_pos (le_of_lt_succ (mem_Ico.1 hb).2), int.nat_abs_of_nat] } } }, exact multiset.map_eq_map_of_bij_of_nodup _ _ (finset.nodup _) (finset.nodup _) (λ x _, (a * x : zmod p).val_min_abs.nat_abs) hmem (λ _ _, rfl) (inj_on_of_surj_on_of_card_le _ hmem hsurj le_rfl) hsurj end private lemma gauss_lemma_aux₁ (p : ℕ) [fact p.prime] [fact (p % 2 = 1)] {a : ℤ} (hap : (a : zmod p) ≠ 0) : (a^(p / 2) * (p / 2)! : zmod p) = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2)).card * (p / 2)! := calc (a ^ (p / 2) * (p / 2)! : zmod p) = (∏ x in Ico 1 (p / 2).succ, a * x) : by rw [prod_mul_distrib, ← prod_nat_cast, prod_Ico_id_eq_factorial, prod_const, card_Ico, succ_sub_one]; simp ... = (∏ x in Ico 1 (p / 2).succ, (a * x : zmod p).val) : by simp ... = (∏ x in Ico 1 (p / 2).succ, (if (a * x : zmod p).val ≤ p / 2 then 1 else -1) * (a * x : zmod p).val_min_abs.nat_abs) : prod_congr rfl $ λ _ _, begin simp only [nat_cast_nat_abs_val_min_abs], split_ifs; simp end ... = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2)).card * (∏ x in Ico 1 (p / 2).succ, (a * x : zmod p).val_min_abs.nat_abs) : have (∏ x in Ico 1 (p / 2).succ, if (a * x : zmod p).val ≤ p / 2 then (1 : zmod p) else -1) = (∏ x in (Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2), -1), from prod_bij_ne_one (λ x _ _, x) (λ x, by split_ifs; simp * at * {contextual := tt}) (λ _ _ _ _ _ _, id) (λ b h _, ⟨b, by simp [-not_le, *] at *⟩) (by intros; split_ifs at *; simp * at *), by rw [prod_mul_distrib, this, prod_const] ... = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2)).card * (p / 2)! : by rw [← prod_nat_cast, finset.prod_eq_multiset_prod, Ico_map_val_min_abs_nat_abs_eq_Ico_map_id p a hap, ← finset.prod_eq_multiset_prod, prod_Ico_id_eq_factorial] lemma gauss_lemma_aux (p : ℕ) [hp : fact p.prime] [fact (p % 2 = 1)] {a : ℤ} (hap : (a : zmod p) ≠ 0) : (a^(p / 2) : zmod p) = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card := (mul_left_inj' (show ((p / 2)! : zmod p) ≠ 0, by rw [ne.def, char_p.cast_eq_zero_iff (zmod p) p, hp.1.dvd_factorial, not_le]; exact nat.div_lt_self hp.1.pos dec_trivial)).1 $ by simpa using gauss_lemma_aux₁ p hap /-- Gauss' lemma. The legendre symbol can be computed by considering the number of naturals less than `p/2` such that `(a * x) % p > p / 2` -/ lemma gauss_lemma {p : ℕ} [fact p.prime] {a : ℤ} (hp : p ≠ 2) (ha0 : (a : zmod p) ≠ 0) : legendre_sym p a = (-1) ^ ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card := begin haveI hp' : fact (p % 2 = 1) := ⟨nat.prime.mod_two_eq_one_iff_ne_two.mpr hp⟩, have : (legendre_sym p a : zmod p) = (((-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card : ℤ) : zmod p) := by { rw [legendre_sym.eq_pow, gauss_lemma_aux p ha0]; simp }, cases legendre_sym.eq_one_or_neg_one p ha0; cases neg_one_pow_eq_or ℤ ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card; simp [*, ne_neg_self p one_ne_zero, (ne_neg_self p one_ne_zero).symm] at * end private lemma eisenstein_lemma_aux₁ (p : ℕ) [fact p.prime] [hp2 : fact (p % 2 = 1)] {a : ℕ} (hap : (a : zmod p) ≠ 0) : ((∑ x in Ico 1 (p / 2).succ, a * x : ℕ) : zmod 2) = ((Ico 1 (p / 2).succ).filter ((λ x : ℕ, p / 2 < (a * x : zmod p).val))).card + ∑ x in Ico 1 (p / 2).succ, x + (∑ x in Ico 1 (p / 2).succ, (a * x) / p : ℕ) := have hp2 : (p : zmod 2) = (1 : ℕ), from (eq_iff_modeq_nat _).2 hp2.1, calc ((∑ x in Ico 1 (p / 2).succ, a * x : ℕ) : zmod 2) = ((∑ x in Ico 1 (p / 2).succ, ((a * x) % p + p * ((a * x) / p)) : ℕ) : zmod 2) : by simp only [mod_add_div] ... = (∑ x in Ico 1 (p / 2).succ, ((a * x : ℕ) : zmod p).val : ℕ) + (∑ x in Ico 1 (p / 2).succ, (a * x) / p : ℕ) : by simp only [val_nat_cast]; simp [sum_add_distrib, mul_sum.symm, nat.cast_add, nat.cast_mul, nat.cast_sum, hp2] ... = _ : congr_arg2 (+) (calc ((∑ x in Ico 1 (p / 2).succ, ((a * x : ℕ) : zmod p).val : ℕ) : zmod 2) = ∑ x in Ico 1 (p / 2).succ, ((((a * x : zmod p).val_min_abs + (if (a * x : zmod p).val ≤ p / 2 then 0 else p)) : ℤ) : zmod 2) : by simp only [(val_eq_ite_val_min_abs _).symm]; simp [nat.cast_sum] ... = ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card + ((∑ x in Ico 1 (p / 2).succ, (a * x : zmod p).val_min_abs.nat_abs) : ℕ) : by { simp [ite_cast, add_comm, sum_add_distrib, finset.sum_ite, hp2, nat.cast_sum], } ... = _ : by rw [finset.sum_eq_multiset_sum, Ico_map_val_min_abs_nat_abs_eq_Ico_map_id p a hap, ← finset.sum_eq_multiset_sum]; simp [nat.cast_sum]) rfl lemma eisenstein_lemma_aux (p : ℕ) [fact p.prime] [fact (p % 2 = 1)] {a : ℕ} (ha2 : a % 2 = 1) (hap : (a : zmod p) ≠ 0) : ((Ico 1 (p / 2).succ).filter ((λ x : ℕ, p / 2 < (a * x : zmod p).val))).card ≡ ∑ x in Ico 1 (p / 2).succ, (x * a) / p [MOD 2] := have ha2 : (a : zmod 2) = (1 : ℕ), from (eq_iff_modeq_nat _).2 ha2, (eq_iff_modeq_nat 2).1 $ sub_eq_zero.1 $ by simpa [add_left_comm, sub_eq_add_neg, finset.mul_sum.symm, mul_comm, ha2, nat.cast_sum, add_neg_eq_iff_eq_add.symm, neg_eq_self_mod_two, add_assoc] using eq.symm (eisenstein_lemma_aux₁ p hap) lemma div_eq_filter_card {a b c : ℕ} (hb0 : 0 < b) (hc : a / b ≤ c) : a / b = ((Ico 1 c.succ).filter (λ x, x * b ≤ a)).card := calc a / b = (Ico 1 (a / b).succ).card : by simp ... = ((Ico 1 c.succ).filter (λ x, x * b ≤ a)).card : congr_arg _ $ finset.ext $ λ x, have x * b ≤ a → x ≤ c, from λ h, le_trans (by rwa [le_div_iff_mul_le hb0]) hc, by simp [lt_succ_iff, le_div_iff_mul_le hb0]; tauto /-- The given sum is the number of integer points in the triangle formed by the diagonal of the rectangle `(0, p/2) × (0, q/2)` -/ private lemma sum_Ico_eq_card_lt {p q : ℕ} : ∑ a in Ico 1 (p / 2).succ, (a * q) / p = ((Ico 1 (p / 2).succ ×ˢ Ico 1 (q / 2).succ).filter $ λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q).card := if hp0 : p = 0 then by simp [hp0, finset.ext_iff] else calc ∑ a in Ico 1 (p / 2).succ, (a * q) / p = ∑ a in Ico 1 (p / 2).succ, ((Ico 1 (q / 2).succ).filter (λ x, x * p ≤ a * q)).card : finset.sum_congr rfl $ λ x hx, div_eq_filter_card (nat.pos_of_ne_zero hp0) (calc x * q / p ≤ (p / 2) * q / p : nat.div_le_div_right (mul_le_mul_of_nonneg_right (le_of_lt_succ $ (mem_Ico.mp hx).2) (nat.zero_le _)) ... ≤ _ : nat.div_mul_div_le_div _ _ _) ... = _ : by rw [← card_sigma]; exact card_congr (λ a _, ⟨a.1, a.2⟩) (by simp only [mem_filter, mem_sigma, and_self, forall_true_iff, mem_product] {contextual := tt}) (λ ⟨_, _⟩ ⟨_, _⟩, by simp only [prod.mk.inj_iff, eq_self_iff_true, and_self, heq_iff_eq, forall_true_iff] {contextual := tt}) (λ ⟨b₁, b₂⟩ h, ⟨⟨b₁, b₂⟩, by revert h; simp only [mem_filter, eq_self_iff_true, exists_prop_of_true, mem_sigma, and_self, forall_true_iff, mem_product] {contextual := tt}⟩) /-- Each of the sums in this lemma is the cardinality of the set integer points in each of the two triangles formed by the diagonal of the rectangle `(0, p/2) × (0, q/2)`. Adding them gives the number of points in the rectangle. -/ lemma sum_mul_div_add_sum_mul_div_eq_mul (p q : ℕ) [hp : fact p.prime] (hq0 : (q : zmod p) ≠ 0) : ∑ a in Ico 1 (p / 2).succ, (a * q) / p + ∑ a in Ico 1 (q / 2).succ, (a * p) / q = (p / 2) * (q / 2) := begin have hswap : ((Ico 1 (q / 2).succ ×ˢ Ico 1 (p / 2).succ).filter (λ x : ℕ × ℕ, x.2 * q ≤ x.1 * p)).card = ((Ico 1 (p / 2).succ ×ˢ Ico 1 (q / 2).succ).filter (λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p)).card := card_congr (λ x _, prod.swap x) (λ ⟨_, _⟩, by simp only [mem_filter, and_self, prod.swap_prod_mk, forall_true_iff, mem_product] {contextual := tt}) (λ ⟨_, _⟩ ⟨_, _⟩, by simp only [prod.mk.inj_iff, eq_self_iff_true, and_self, prod.swap_prod_mk, forall_true_iff] {contextual := tt}) (λ ⟨x₁, x₂⟩ h, ⟨⟨x₂, x₁⟩, by revert h; simp only [mem_filter, eq_self_iff_true, and_self, exists_prop_of_true, prod.swap_prod_mk, forall_true_iff, mem_product] {contextual := tt}⟩), have hdisj : disjoint ((Ico 1 (p / 2).succ ×ˢ Ico 1 (q / 2).succ).filter (λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q)) ((Ico 1 (p / 2).succ ×ˢ Ico 1 (q / 2).succ).filter (λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p)), { apply disjoint_filter.2 (λ x hx hpq hqp, _), have hxp : x.1 < p, from lt_of_le_of_lt (show x.1 ≤ p / 2, by simp only [*, lt_succ_iff, mem_Ico, mem_product] at *; tauto) (nat.div_lt_self hp.1.pos dec_trivial), have : (x.1 : zmod p) = 0, { simpa [hq0] using congr_arg (coe : ℕ → zmod p) (le_antisymm hpq hqp) }, apply_fun zmod.val at this, rw [val_cast_of_lt hxp, val_zero] at this, simpa only [this, nonpos_iff_eq_zero, mem_Ico, one_ne_zero, false_and, mem_product] using hx }, have hunion : (Ico 1 (p / 2).succ ×ˢ Ico 1 (q / 2).succ).filter (λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q) ∪ (Ico 1 (p / 2).succ ×ˢ Ico 1 (q / 2).succ).filter (λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p) = (Ico 1 (p / 2).succ ×ˢ Ico 1 (q / 2).succ), from finset.ext (λ x, by have := le_total (x.2 * p) (x.1 * q); simp only [mem_union, mem_filter, mem_Ico, mem_product]; tauto), rw [sum_Ico_eq_card_lt, sum_Ico_eq_card_lt, hswap, ← card_disjoint_union hdisj, hunion, card_product], simp only [card_Ico, tsub_zero, succ_sub_succ_eq_sub] end lemma eisenstein_lemma {p : ℕ} [fact p.prime] (hp : p ≠ 2) {a : ℕ} (ha1 : a % 2 = 1) (ha0 : (a : zmod p) ≠ 0) : legendre_sym p a = (-1)^∑ x in Ico 1 (p / 2).succ, (x * a) / p := begin haveI hp' : fact (p % 2 = 1) := ⟨nat.prime.mod_two_eq_one_iff_ne_two.mpr hp⟩, have ha0' : ((a : ℤ) : zmod p) ≠ 0 := by { norm_cast, exact ha0 }, rw [neg_one_pow_eq_pow_mod_two, gauss_lemma hp ha0', neg_one_pow_eq_pow_mod_two, (by norm_cast : ((a : ℤ) : zmod p) = (a : zmod p)), show _ = _, from eisenstein_lemma_aux p ha1 ha0] end end zmod end gauss_eisenstein
934eee58ac08f909ba66d844615d75609d3ffc25
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/constructions/borel_space/metrizable.lean
36478e37f5677eb0f6966e2bb9131e16d121fda3
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
8,494
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import measure_theory.constructions.borel_space.basic import topology.metric_space.metrizable /-! # Measurable functions in (pseudo-)metrizable Borel spaces > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ open filter measure_theory topological_space open_locale classical topology nnreal ennreal measure_theory variables {α β : Type*} [measurable_space α] section limits variables [topological_space β] [pseudo_metrizable_space β] [measurable_space β] [borel_space β] open metric /-- A limit (over a general filter) of measurable `ℝ≥0∞` valued functions is measurable. -/ lemma measurable_of_tendsto_ennreal' {ι} {f : ι → α → ℝ≥0∞} {g : α → ℝ≥0∞} (u : filter ι) [ne_bot u] [is_countably_generated u] (hf : ∀ i, measurable (f i)) (lim : tendsto f u (𝓝 g)) : measurable g := begin rcases u.exists_seq_tendsto with ⟨x, hx⟩, rw [tendsto_pi_nhds] at lim, have : (λ y, liminf (λ n, (f (x n) y : ℝ≥0∞)) at_top) = g := by { ext1 y, exact ((lim y).comp hx).liminf_eq, }, rw ← this, show measurable (λ y, liminf (λ n, (f (x n) y : ℝ≥0∞)) at_top), exact measurable_liminf (λ n, hf (x n)), end /-- A sequential limit of measurable `ℝ≥0∞` valued functions is measurable. -/ lemma measurable_of_tendsto_ennreal {f : ℕ → α → ℝ≥0∞} {g : α → ℝ≥0∞} (hf : ∀ i, measurable (f i)) (lim : tendsto f at_top (𝓝 g)) : measurable g := measurable_of_tendsto_ennreal' at_top hf lim /-- A limit (over a general filter) of measurable `ℝ≥0` valued functions is measurable. -/ lemma measurable_of_tendsto_nnreal' {ι} {f : ι → α → ℝ≥0} {g : α → ℝ≥0} (u : filter ι) [ne_bot u] [is_countably_generated u] (hf : ∀ i, measurable (f i)) (lim : tendsto f u (𝓝 g)) : measurable g := begin simp_rw [← measurable_coe_nnreal_ennreal_iff] at hf ⊢, refine measurable_of_tendsto_ennreal' u hf _, rw tendsto_pi_nhds at lim ⊢, exact λ x, (ennreal.continuous_coe.tendsto (g x)).comp (lim x), end /-- A sequential limit of measurable `ℝ≥0` valued functions is measurable. -/ lemma measurable_of_tendsto_nnreal {f : ℕ → α → ℝ≥0} {g : α → ℝ≥0} (hf : ∀ i, measurable (f i)) (lim : tendsto f at_top (𝓝 g)) : measurable g := measurable_of_tendsto_nnreal' at_top hf lim /-- A limit (over a general filter) of measurable functions valued in a (pseudo) metrizable space is measurable. -/ lemma measurable_of_tendsto_metrizable' {ι} {f : ι → α → β} {g : α → β} (u : filter ι) [ne_bot u] [is_countably_generated u] (hf : ∀ i, measurable (f i)) (lim : tendsto f u (𝓝 g)) : measurable g := begin letI : pseudo_metric_space β := pseudo_metrizable_space_pseudo_metric β, apply measurable_of_is_closed', intros s h1s h2s h3s, have : measurable (λ x, inf_nndist (g x) s), { suffices : tendsto (λ i x, inf_nndist (f i x) s) u (𝓝 (λ x, inf_nndist (g x) s)), from measurable_of_tendsto_nnreal' u (λ i, (hf i).inf_nndist) this, rw [tendsto_pi_nhds] at lim ⊢, intro x, exact ((continuous_inf_nndist_pt s).tendsto (g x)).comp (lim x) }, have h4s : g ⁻¹' s = (λ x, inf_nndist (g x) s) ⁻¹' {0}, { ext x, simp [h1s, ← h1s.mem_iff_inf_dist_zero h2s, ← nnreal.coe_eq_zero] }, rw [h4s], exact this (measurable_set_singleton 0), end /-- A sequential limit of measurable functions valued in a (pseudo) metrizable space is measurable. -/ lemma measurable_of_tendsto_metrizable {f : ℕ → α → β} {g : α → β} (hf : ∀ i, measurable (f i)) (lim : tendsto f at_top (𝓝 g)) : measurable g := measurable_of_tendsto_metrizable' at_top hf lim lemma ae_measurable_of_tendsto_metrizable_ae {ι} {μ : measure α} {f : ι → α → β} {g : α → β} (u : filter ι) [hu : ne_bot u] [is_countably_generated u] (hf : ∀ n, ae_measurable (f n) μ) (h_tendsto : ∀ᵐ x ∂μ, tendsto (λ n, f n x) u (𝓝 (g x))) : ae_measurable g μ := begin rcases u.exists_seq_tendsto with ⟨v, hv⟩, have h'f : ∀ n, ae_measurable (f (v n)) μ := λ n, hf (v n), set p : α → (ℕ → β) → Prop := λ x f', tendsto (λ n, f' n) at_top (𝓝 (g x)), have hp : ∀ᵐ x ∂μ, p x (λ n, f (v n) x), by filter_upwards [h_tendsto] with x hx using hx.comp hv, set ae_seq_lim := λ x, ite (x ∈ ae_seq_set h'f p) (g x) (⟨f (v 0) x⟩ : nonempty β).some with hs, refine ⟨ae_seq_lim, measurable_of_tendsto_metrizable' at_top (ae_seq.measurable h'f p) (tendsto_pi_nhds.mpr (λ x, _)), _⟩, { simp_rw [ae_seq, ae_seq_lim], split_ifs with hx, { simp_rw ae_seq.mk_eq_fun_of_mem_ae_seq_set h'f hx, exact @ae_seq.fun_prop_of_mem_ae_seq_set _ α β _ _ _ _ _ h'f x hx, }, { exact tendsto_const_nhds } }, { exact (ite_ae_eq_of_measure_compl_zero g (λ x, (⟨f (v 0) x⟩ : nonempty β).some) (ae_seq_set h'f p) (ae_seq.measure_compl_ae_seq_set_eq_zero h'f hp)).symm }, end lemma ae_measurable_of_tendsto_metrizable_ae' {μ : measure α} {f : ℕ → α → β} {g : α → β} (hf : ∀ n, ae_measurable (f n) μ) (h_ae_tendsto : ∀ᵐ x ∂μ, tendsto (λ n, f n x) at_top (𝓝 (g x))) : ae_measurable g μ := ae_measurable_of_tendsto_metrizable_ae at_top hf h_ae_tendsto lemma ae_measurable_of_unif_approx {β} [measurable_space β] [pseudo_metric_space β] [borel_space β] {μ : measure α} {g : α → β} (hf : ∀ ε > (0 : ℝ), ∃ (f : α → β), ae_measurable f μ ∧ ∀ᵐ x ∂μ, dist (f x) (g x) ≤ ε) : ae_measurable g μ := begin obtain ⟨u, u_anti, u_pos, u_lim⟩ : ∃ (u : ℕ → ℝ), strict_anti u ∧ (∀ (n : ℕ), 0 < u n) ∧ tendsto u at_top (𝓝 0) := exists_seq_strict_anti_tendsto (0 : ℝ), choose f Hf using λ (n : ℕ), hf (u n) (u_pos n), have : ∀ᵐ x ∂μ, tendsto (λ n, f n x) at_top (𝓝 (g x)), { have : ∀ᵐ x ∂ μ, ∀ n, dist (f n x) (g x) ≤ u n := ae_all_iff.2 (λ n, (Hf n).2), filter_upwards [this], assume x hx, rw tendsto_iff_dist_tendsto_zero, exact squeeze_zero (λ n, dist_nonneg) hx u_lim }, exact ae_measurable_of_tendsto_metrizable_ae' (λ n, (Hf n).1) this, end lemma measurable_of_tendsto_metrizable_ae {μ : measure α} [μ.is_complete] {f : ℕ → α → β} {g : α → β} (hf : ∀ n, measurable (f n)) (h_ae_tendsto : ∀ᵐ x ∂μ, tendsto (λ n, f n x) at_top (𝓝 (g x))) : measurable g := ae_measurable_iff_measurable.mp (ae_measurable_of_tendsto_metrizable_ae' (λ i, (hf i).ae_measurable) h_ae_tendsto) lemma measurable_limit_of_tendsto_metrizable_ae {ι} [countable ι] [nonempty ι] {μ : measure α} {f : ι → α → β} {L : filter ι} [L.is_countably_generated] (hf : ∀ n, ae_measurable (f n) μ) (h_ae_tendsto : ∀ᵐ x ∂μ, ∃ l : β, tendsto (λ n, f n x) L (𝓝 l)) : ∃ (f_lim : α → β) (hf_lim_meas : measurable f_lim), ∀ᵐ x ∂μ, tendsto (λ n, f n x) L (𝓝 (f_lim x)) := begin inhabit ι, unfreezingI { rcases eq_or_ne L ⊥ with rfl | hL }, { exact ⟨(hf default).mk _, (hf default).measurable_mk, eventually_of_forall $ λ x, tendsto_bot⟩ }, haveI : ne_bot L := ⟨hL⟩, let p : α → (ι → β) → Prop := λ x f', ∃ l : β, tendsto (λ n, f' n) L (𝓝 l), have hp_mem : ∀ x ∈ ae_seq_set hf p, p x (λ n, f n x), from λ x hx, ae_seq.fun_prop_of_mem_ae_seq_set hf hx, have h_ae_eq : ∀ᵐ x ∂μ, ∀ n, ae_seq hf p n x = f n x, from ae_seq.ae_seq_eq_fun_ae hf h_ae_tendsto, let f_lim : α → β := λ x, dite (x ∈ ae_seq_set hf p) (λ h, (hp_mem x h).some) (λ h, (⟨f default x⟩ : nonempty β).some), have hf_lim : ∀ x, tendsto (λ n, ae_seq hf p n x) L (𝓝 (f_lim x)), { intros x, simp only [f_lim, ae_seq], split_ifs, { refine (hp_mem x h).some_spec.congr (λ n, _), exact (ae_seq.mk_eq_fun_of_mem_ae_seq_set hf h n).symm }, { exact tendsto_const_nhds, }, }, have h_ae_tendsto_f_lim : ∀ᵐ x ∂μ, tendsto (λ n, f n x) L (𝓝 (f_lim x)), from h_ae_eq.mono (λ x hx, (hf_lim x).congr hx), have h_f_lim_meas : measurable f_lim, from measurable_of_tendsto_metrizable' L (ae_seq.measurable hf p) (tendsto_pi_nhds.mpr (λ x, hf_lim x)), exact ⟨f_lim, h_f_lim_meas, h_ae_tendsto_f_lim⟩, end end limits
672fab78c1fb34ad8ba25988844d256cd05088a0
c777c32c8e484e195053731103c5e52af26a25d1
/src/number_theory/fermat_psp.lean
a1860ef1866ea85f7b258ad90e08a152bcc5ae07
[ "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,641
lean
/- Copyright (c) 2022 Niels Voss. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Niels Voss -/ import data.nat.prime import field_theory.finite.basic import order.filter.cofinite /-! # Fermat Pseudoprimes In this file we define Fermat pseudoprimes: composite numbers that pass the Fermat primality test. A natural number `n` passes the Fermat primality test to base `b` (and is therefore deemed a "probable prime") if `n` divides `b ^ (n - 1) - 1`. `n` is a Fermat pseudoprime to base `b` if `n` is a composite number that passes the Fermat primality test to base `b` and is coprime with `b`. Fermat pseudoprimes can also be seen as composite numbers for which Fermat's little theorem holds true. Numbers which are Fermat pseudoprimes to all bases are known as Carmichael numbers (not yet defined in this file). ## Main Results The main definitions for this file are - `fermat_psp.probable_prime`: A number `n` is a probable prime to base `b` if it passes the Fermat primality test; that is, if `n` divides `b ^ (n - 1) - 1` - `fermat_psp`: A number `n` is a pseudoprime to base `b` if it is a probable prime to base `b`, is composite, and is coprime with `b` (this last condition is automatically true if `n` divides `b ^ (n - 1) - 1`, but some sources include it in the definition). Note that all composite numbers are pseudoprimes to base 0 and 1, and that the definiton of `probable_prime` in this file implies that all numbers are probable primes to bases 0 and 1, and that 0 and 1 are probable primes to any base. The main theorems are - `fermat_psp.exists_infinite_pseudoprimes`: there are infinite pseudoprimes to any base `b ≥ 1` -/ /-- `n` is a probable prime to base `b` if `n` passes the Fermat primality test; that is, `n` divides `b ^ (n - 1) - 1`. This definition implies that all numbers are probable primes to base 0 or 1, and that 0 and 1 are probable primes to any base. -/ def fermat_psp.probable_prime (n b : ℕ) : Prop := n ∣ b ^ (n - 1) - 1 /-- `n` is a Fermat pseudoprime to base `b` if `n` is a probable prime to base `b` and is composite. By this definition, all composite natural numbers are pseudoprimes to base 0 and 1. This definition also permits `n` to be less than `b`, so that 4 is a pseudoprime to base 5, for example. -/ def fermat_psp (n b : ℕ) : Prop := fermat_psp.probable_prime n b ∧ ¬n.prime ∧ 1 < n namespace fermat_psp instance decidable_probable_prime (n b : ℕ) : decidable (probable_prime n b) := nat.decidable_dvd _ _ instance decidable_psp (n b : ℕ) : decidable (fermat_psp n b) := and.decidable /-- If `n` passes the Fermat primality test to base `b`, then `n` is coprime with `b`, assuming that `n` and `b` are both positive. -/ lemma coprime_of_probable_prime {n b : ℕ} (h : probable_prime n b) (h₁ : 1 ≤ n) (h₂ : 1 ≤ b) : nat.coprime n b := begin by_cases h₃ : 2 ≤ n, { -- To prove that `n` is coprime with `b`, we we need to show that for all prime factors of `n`, -- we can derive a contradiction if `n` divides `b`. apply nat.coprime_of_dvd, -- If `k` is a prime number that divides both `n` and `b`, then we know that `n = m * k` and -- `b = j * k` for some natural numbers `m` and `j`. We substitute these into the hypothesis. rintros k hk ⟨m, rfl⟩ ⟨j, rfl⟩, -- Because prime numbers do not divide 1, it suffices to show that `k ∣ 1` to prove a -- contradiction apply nat.prime.not_dvd_one hk, -- Since `n` divides `b ^ (n - 1) - 1`, `k` also divides `b ^ (n - 1) - 1` replace h := dvd_of_mul_right_dvd h, -- Because `k` divides `b ^ (n - 1) - 1`, if we can show that `k` also divides `b ^ (n - 1)`, -- then we know `k` divides 1. rw [nat.dvd_add_iff_right h, nat.sub_add_cancel (nat.one_le_pow _ _ h₂)], -- Since `k` divides `b`, `k` also divides any power of `b` except `b ^ 0`. Therefore, it -- suffices to show that `n - 1` isn't zero. However, we know that `n - 1` isn't zero because we -- assumed `2 ≤ n` when doing `by_cases`. refine dvd_of_mul_right_dvd (dvd_pow_self (k * j) _), linarith }, -- If `n = 1`, then it follows trivially that `n` is coprime with `b`. { rw (show n = 1, by linarith), norm_num } end lemma probable_prime_iff_modeq (n : ℕ) {b : ℕ} (h : 1 ≤ b) : probable_prime n b ↔ b ^ (n - 1) ≡ 1 [MOD n] := begin have : 1 ≤ b ^ (n - 1) := one_le_pow_of_one_le h (n - 1), -- For exact_mod_cast rw nat.modeq.comm, split, { intro h₁, apply nat.modeq_of_dvd, exact_mod_cast h₁, }, { intro h₁, exact_mod_cast nat.modeq.dvd h₁, }, end /-- If `n` is a Fermat pseudoprime to base `b`, then `n` is coprime with `b`, assuming that `b` is positive. This lemma is a small wrapper based on `coprime_of_probable_prime` -/ lemma coprime_of_fermat_psp {n b : ℕ} (h : fermat_psp n b) (h₁ : 1 ≤ b) : nat.coprime n b := begin rcases h with ⟨hp, hn₁, hn₂⟩, exact coprime_of_probable_prime hp (by linarith) h₁, end /-- All composite numbers are Fermat pseudoprimes to base 1. -/ lemma base_one {n : ℕ} (h₁ : 1 < n) (h₂ : ¬n.prime) : fermat_psp n 1 := begin refine ⟨show n ∣ 1 ^ (n - 1) - 1, from _, h₂, h₁⟩, exact (show 0 = 1 ^ (n - 1) - 1, by norm_num) ▸ dvd_zero n, end -- Lemmas that are needed to prove statements in this file, but aren't directly related to Fermat -- pseudoprimes section helper_lemmas private lemma pow_gt_exponent {a : ℕ} (b : ℕ) (h : 2 ≤ a) : b < a ^ b := lt_of_lt_of_le (nat.lt_two_pow b) $ nat.pow_le_pow_of_le_left h _ private lemma a_id_helper {a b : ℕ} (ha : 2 ≤ a) (hb : 2 ≤ b) : 2 ≤ (a ^ b - 1) / (a - 1) := begin change 1 < _, have h₁ : a - 1 ∣ a ^ b - 1 := by simpa only [one_pow] using nat_sub_dvd_pow_sub_pow a 1 b, rw [nat.lt_div_iff_mul_lt h₁, mul_one, tsub_lt_tsub_iff_right (nat.le_of_succ_le ha)], convert pow_lt_pow (nat.lt_of_succ_le ha) hb, rw pow_one end private lemma b_id_helper {a b : ℕ} (ha : 2 ≤ a) (hb : 2 < b) : 2 ≤ (a ^ b + 1) / (a + 1) := begin rw nat.le_div_iff_mul_le (nat.zero_lt_succ _), apply nat.succ_le_succ, calc 2 * a + 1 ≤ a ^ 2 * a : by nlinarith ... = a ^ 3 : by rw pow_succ' a 2 ... ≤ a ^ b : pow_le_pow (nat.le_of_succ_le ha) hb end private lemma AB_id_helper (b p : ℕ) (hb : 2 ≤ b) (hp : odd p) : (b ^ p - 1) / (b - 1) * ((b ^ p + 1) / (b + 1)) = (b ^ (2 * p) - 1) / (b ^ 2 - 1) := begin have q₁ : b - 1 ∣ b ^ p - 1 := by simpa only [one_pow] using nat_sub_dvd_pow_sub_pow b 1 p, have q₂ : b + 1 ∣ b ^ p + 1 := by simpa only [one_pow] using hp.nat_add_dvd_pow_add_pow b 1, convert nat.div_mul_div_comm q₁ q₂; rw [mul_comm (_ - 1), ←nat.sq_sub_sq], { ring_exp }, { simp } end /-- Used in the proof of `psp_from_prime_psp` -/ private lemma bp_helper {b p : ℕ} (hb : 0 < b) (hp : 1 ≤ p) : b ^ (2 * p) - 1 - (b ^ 2 - 1) = b * (b ^ (p - 1) - 1) * (b ^ p + b) := have hi_bsquared : 1 ≤ b ^ 2 := nat.one_le_pow _ _ hb, calc b ^ (2 * p) - 1 - (b ^ 2 - 1) = b ^ (2 * p) - (1 + (b ^ 2 - 1)) : by rw nat.sub_sub ... = b ^ (2 * p) - (1 + b ^ 2 - 1) : by rw nat.add_sub_assoc hi_bsquared ... = b ^ (2 * p) - (b ^ 2) : by rw nat.add_sub_cancel_left ... = b ^ (p * 2) - (b ^ 2) : by rw mul_comm ... = (b ^ p) ^ 2 - (b ^ 2) : by rw pow_mul ... = (b ^ p + b) * (b ^ p - b) : by rw nat.sq_sub_sq ... = (b ^ p - b) * (b ^ p + b) : by rw mul_comm ... = (b ^ (p - 1 + 1) - b) * (b ^ p + b) : by rw nat.sub_add_cancel hp ... = (b * b ^ (p - 1) - b) * (b ^ p + b) : by rw pow_succ ... = (b * b ^ (p - 1) - b * 1) * (b ^ p + b) : by rw mul_one ... = b * (b ^ (p - 1) - 1) * (b ^ p + b) : by rw nat.mul_sub_left_distrib end helper_lemmas /-- Given a prime `p` which does not divide `b * (b ^ 2 - 1)`, we can produce a number `n` which is larger than `p` and pseudoprime to base `b`. We do this by defining `n = ((b ^ p - 1) / (b - 1)) * ((b ^ p + 1) / (b + 1))` The primary purpose of this definition is to help prove `exists_infinite_pseudoprimes`. For a proof that `n` is actually pseudoprime to base `b`, see `psp_from_prime_psp`, and for a proof that `n` is greater than `p`, see `psp_from_prime_gt_p`. This lemma is intended to be used when `2 ≤ b`, `2 < p`, `p` is prime, and `¬p ∣ b * (b ^ 2 - 1)`, because those are the hypotheses for `psp_from_prime_psp`. -/ private def psp_from_prime (b : ℕ) (p : ℕ) : ℕ := (b ^ p - 1) / (b - 1) * ((b ^ p + 1) / (b + 1)) /-- This is a proof that the number produced using `psp_from_prime` is actually pseudoprime to base `b`. The primary purpose of this lemma is to help prove `exists_infinite_pseudoprimes`. We use <https://primes.utm.edu/notes/proofs/a_pseudoprimes.html> as a rough outline of the proof. -/ private lemma psp_from_prime_psp {b : ℕ} (b_ge_two : 2 ≤ b) {p : ℕ} (p_prime : p.prime) (p_gt_two : 2 < p) (not_dvd : ¬p ∣ b * (b ^ 2 - 1)) : fermat_psp (psp_from_prime b p) b := begin unfold psp_from_prime, set A := (b ^ p - 1) / (b - 1), set B := (b ^ p + 1) / (b + 1), -- Inequalities have hi_A : 1 < A := a_id_helper (nat.succ_le_iff.mp b_ge_two) (nat.prime.one_lt p_prime), have hi_B : 1 < B := b_id_helper (nat.succ_le_iff.mp b_ge_two) p_gt_two, have hi_AB : 1 < A * B := one_lt_mul'' hi_A hi_B, have hi_b : 0 < b := by linarith, have hi_p : 1 ≤ p := nat.one_le_of_lt p_gt_two, have hi_bsquared : 0 < b ^ 2 - 1 := by nlinarith [nat.one_le_pow 2 b hi_b], have hi_bpowtwop : 1 ≤ b ^ (2 * p) := nat.one_le_pow (2 * p) b hi_b, have hi_bpowpsubone : 1 ≤ b ^ (p - 1) := nat.one_le_pow (p - 1) b hi_b, -- Other useful facts have p_odd : odd p := p_prime.odd_of_ne_two p_gt_two.ne.symm, have AB_not_prime : ¬nat.prime (A * B) := nat.not_prime_mul hi_A hi_B, have AB_id : A * B = (b ^ (2 * p) - 1) / (b ^ 2 - 1) := AB_id_helper _ _ b_ge_two p_odd, have hd : b ^ 2 - 1 ∣ b ^ (2 * p) - 1, { simpa only [one_pow, pow_mul] using nat_sub_dvd_pow_sub_pow _ 1 p }, -- We know that `A * B` is not prime, and that `1 < A * B`. Since two conditions of being -- pseudoprime are satisfied, we only need to show that `A * B` is probable prime to base `b` refine ⟨_, AB_not_prime, hi_AB⟩, -- Used to prove that `2 * p * (b ^ 2 - 1) ∣ (b ^ 2 - 1) * (A * B - 1)`. have ha₁ : (b ^ 2 - 1) * (A * B - 1) = b * (b ^ (p - 1) - 1) * (b ^ p + b), { apply_fun (λ x, x * (b ^ 2 - 1)) at AB_id, rw nat.div_mul_cancel hd at AB_id, apply_fun (λ x, x - (b ^ 2 - 1)) at AB_id, nth_rewrite 1 ←one_mul (b ^ 2 - 1) at AB_id, rw [←nat.mul_sub_right_distrib, mul_comm] at AB_id, rw AB_id, exact bp_helper hi_b hi_p }, -- If `b` is even, then `b^p` is also even, so `2 ∣ b^p + b` -- If `b` is odd, then `b^p` is also odd, so `2 ∣ b^p + b` have ha₂ : 2 ∣ b ^ p + b, { by_cases h : even b, { replace h : 2 ∣ b := even_iff_two_dvd.mp h, have : p ≠ 0 := by linarith, have : 2 ∣ b^p := dvd_pow h this, exact dvd_add this h }, { have h : odd b := nat.odd_iff_not_even.mpr h, have : odd (b ^ p) := odd.pow h, have : even (b ^ p + b) := odd.add_odd this h, exact even_iff_two_dvd.mp this } }, -- Since `b` isn't divisible by `p`, `b` is coprime with `p`. we can use Fermat's Little Theorem -- to prove this. have ha₃ : p ∣ b ^ (p - 1) - 1, { have : ¬p ∣ b := mt (assume h : p ∣ b, dvd_mul_of_dvd_left h _) not_dvd, have : p.coprime b := or.resolve_right (nat.coprime_or_dvd_of_prime p_prime b) this, have : is_coprime (b : ℤ) ↑p := this.symm.is_coprime, have : ↑b ^ (p - 1) ≡ 1 [ZMOD ↑p] := int.modeq.pow_card_sub_one_eq_one p_prime this, have : ↑p ∣ ↑b ^ (p - 1) - ↑1 := int.modeq.dvd (int.modeq.symm this), exact_mod_cast this }, -- Because `p - 1` is even, there is a `c` such that `2 * c = p - 1`. `nat_sub_dvd_pow_sub_pow` -- implies that `b ^ c - 1 ∣ (b ^ c) ^ 2 - 1`, and `(b ^ c) ^ 2 = b ^ (p - 1)`. have ha₄ : b ^ 2 - 1 ∣ b ^ (p - 1) - 1, { cases p_odd with k hk, have : 2 ∣ p - 1 := ⟨k, by simp [hk]⟩, cases this with c hc, have : b ^ 2 - 1 ∣ (b ^ 2) ^ c - 1 := by simpa only [one_pow] using nat_sub_dvd_pow_sub_pow _ 1 c, have : b ^ 2 - 1 ∣ b ^ (2 * c) - 1 := by rwa ←pow_mul at this, rwa ←hc at this }, -- Used to prove that `2 * p` divides `A * B - 1` have ha₅ : 2 * p * (b ^ 2 - 1) ∣ (b ^ 2 - 1) * (A * B - 1), { suffices q : 2 * p * (b ^ 2 - 1) ∣ b * (b ^ (p - 1) - 1) * (b ^ p + b), { rwa ha₁ }, -- We already proved that `b ^ 2 - 1 ∣ b ^ (p - 1) - 1`. -- Since `2 ∣ b ^ p + b` and `p ∣ b ^ p + b`, if we show that 2 and p are coprime, then we -- know that `2 * p ∣ b ^ p + b` have q₁ : nat.coprime p (b ^ 2 - 1), { have q₂ : ¬p ∣ b ^ 2 - 1, { rw mul_comm at not_dvd, exact mt (assume h : p ∣ b ^ 2 - 1, dvd_mul_of_dvd_left h _) not_dvd }, exact (nat.prime.coprime_iff_not_dvd p_prime).mpr q₂ }, have q₂ : p * (b ^ 2 - 1) ∣ b ^ (p - 1) - 1 := nat.coprime.mul_dvd_of_dvd_of_dvd q₁ ha₃ ha₄, have q₃ : p * (b ^ 2 - 1) * 2 ∣ (b ^ (p - 1) - 1) * (b ^ p + b) := mul_dvd_mul q₂ ha₂, have q₄ : p * (b ^ 2 - 1) * 2 ∣ b * ((b ^ (p - 1) - 1) * (b ^ p + b)), from dvd_mul_of_dvd_right q₃ _, rwa [mul_assoc, mul_comm, mul_assoc b] }, have ha₆ : 2 * p ∣ A * B - 1, { rw mul_comm at ha₅, exact nat.dvd_of_mul_dvd_mul_left hi_bsquared ha₅ }, -- `A * B` divides `b ^ (2 * p) - 1` because `A * B * (b ^ 2 - 1) = b ^ (2 * p) - 1`. -- This can be proven by multiplying both sides of `AB_id` by `b ^ 2 - 1`. have ha₇ : A * B ∣ b ^ (2 * p) - 1, { use b ^ 2 - 1, have : A * B * (b ^ 2 - 1) = (b ^ (2 * p) - 1) / (b ^ 2 - 1) * (b ^ 2 - 1), from congr_arg (λ x : ℕ, x * (b ^ 2 - 1)) AB_id, simpa only [add_comm, nat.div_mul_cancel hd, nat.sub_add_cancel hi_bpowtwop] using this.symm }, -- Since `2 * p ∣ A * B - 1`, there is a number `q` such that `2 * p * q = A * B - 1`. -- By `nat_sub_dvd_pow_sub_pow`, we know that `b ^ (2 * p) - 1 ∣ b ^ (2 * p * q) - 1`. -- This means that `b ^ (2 * p) - 1 ∣ b ^ (A * B - 1) - 1`. cases ha₆ with q hq, have ha₈ : b ^ (2 * p) - 1 ∣ b ^ (A * B - 1) - 1 := by simpa only [one_pow, pow_mul, hq] using nat_sub_dvd_pow_sub_pow _ 1 q, -- We have proved that `A * B ∣ b ^ (2 * p) - 1` and `b ^ (2 * p) - 1 ∣ b ^ (A * B - 1) - 1`. -- Therefore, `A * B ∣ b ^ (A * B - 1) - 1`. exact dvd_trans ha₇ ha₈ end /-- This is a proof that the number produced using `psp_from_prime` is greater than the prime `p` used to create it. The primary purpose of this lemma is to help prove `exists_infinite_pseudoprimes`. -/ private lemma psp_from_prime_gt_p {b : ℕ} (b_ge_two : 2 ≤ b) {p : ℕ} (p_prime : p.prime) (p_gt_two : 2 < p) : p < psp_from_prime b p := begin unfold psp_from_prime, set A := (b ^ p - 1) / (b - 1), set B := (b ^ p + 1) / (b + 1), rw show A * B = (b ^ (2 * p) - 1) / (b ^ 2 - 1), from AB_id_helper _ _ b_ge_two (p_prime.odd_of_ne_two p_gt_two.ne.symm), have AB_dvd : b ^ 2 - 1 ∣ b ^ (2 * p) - 1, by simpa only [one_pow, pow_mul] using nat_sub_dvd_pow_sub_pow _ 1 p, suffices h : p * (b ^ 2 - 1) < b ^ (2 * p) - 1, { have h₁ : (p * (b ^ 2 - 1)) / (b ^ 2 - 1) < (b ^ (2 * p) - 1) / (b ^ 2 - 1), from nat.div_lt_div_of_lt_of_dvd AB_dvd h, have h₂ : 0 < b ^ 2 - 1, by linarith [show 3 ≤ b ^ 2 - 1, from le_tsub_of_add_le_left (show 4 ≤ b ^ 2, by nlinarith)], rwa nat.mul_div_cancel _ h₂ at h₁ }, rw [nat.mul_sub_left_distrib, mul_one, pow_mul], nth_rewrite_rhs 0 ←nat.sub_add_cancel (show 1 ≤ p, by linarith), rw pow_succ (b ^ 2), suffices h : p * b ^ 2 < b ^ 2 * (b ^ 2) ^ (p - 1), { apply gt_of_ge_of_gt, { exact tsub_le_tsub_left (show 1 ≤ p, by linarith) (b ^ 2 * (b ^ 2) ^ (p - 1)) }, { have : p ≤ p * b ^ 2 := nat.le_mul_of_pos_right (show 0 < b ^ 2, by nlinarith), exact tsub_lt_tsub_right_of_le this h } }, suffices h : p < (b ^ 2) ^ (p - 1), { rw mul_comm (b ^ 2), have : 4 ≤ b ^ 2 := by nlinarith, have : 0 < b ^ 2 := by linarith, exact mul_lt_mul_of_pos_right h this }, rw [←pow_mul, nat.mul_sub_left_distrib, mul_one], have : 2 ≤ 2 * p - 2 := le_tsub_of_add_le_left (show 4 ≤ 2 * p, by linarith), have : 2 + p ≤ 2 * p := by linarith, have : p ≤ 2 * p - 2 := le_tsub_of_add_le_left this, exact nat.lt_of_le_of_lt this (pow_gt_exponent _ b_ge_two) end /-- For all positive bases, there exist Fermat infinite pseudoprimes to that base. Given in this form: for all numbers `b ≥ 1` and `m`, there exists a pseudoprime `n` to base `b` such that `m ≤ n`. This form is similar to `nat.exists_infinite_primes`. -/ theorem exists_infinite_pseudoprimes {b : ℕ} (h : 1 ≤ b) (m : ℕ) : ∃ n : ℕ, fermat_psp n b ∧ m ≤ n := begin by_cases b_ge_two : 2 ≤ b, -- If `2 ≤ b`, then because there exist infinite prime numbers, there is a prime number p such -- `m ≤ p` and `¬p ∣ b*(b^2 - 1)`. We pick a prime number `b*(b^2 - 1) + 1 + m ≤ p` because we -- automatically know that `p` is greater than m and that it does not divide `b*(b^2 - 1)` -- (because `p` can't divide a number less than `p`). -- From `p`, we can use the lemmas we proved earlier to show that -- `((b^p - 1)/(b - 1)) * ((b^p + 1)/(b + 1))` is a pseudoprime to base `b`. { have h := nat.exists_infinite_primes (b * (b ^ 2 - 1) + 1 + m), cases h with p hp, cases hp with hp₁ hp₂, have h₁ : 0 < b := pos_of_gt (nat.succ_le_iff.mp b_ge_two), have h₂ : 4 ≤ b ^ 2 := pow_le_pow_of_le_left' b_ge_two 2, have h₃ : 0 < b ^ 2 - 1 := tsub_pos_of_lt (gt_of_ge_of_gt h₂ (by norm_num)), have h₄ : 0 < b * (b ^ 2 - 1) := mul_pos h₁ h₃, have h₅ : b * (b ^ 2 - 1) < p := by linarith, have h₆ : ¬p ∣ b * (b ^ 2 - 1) := nat.not_dvd_of_pos_of_lt h₄ h₅, have h₇ : b ≤ b * (b ^ 2 - 1) := nat.le_mul_of_pos_right h₃, have h₈ : 2 ≤ b * (b ^ 2 - 1) := le_trans b_ge_two h₇, have h₉ : 2 < p := gt_of_gt_of_ge h₅ h₈, have h₁₀ := psp_from_prime_gt_p b_ge_two hp₂ h₉, use psp_from_prime b p, split, { exact psp_from_prime_psp b_ge_two hp₂ h₉ h₆ }, { exact le_trans (show m ≤ p, by linarith) (le_of_lt h₁₀) } }, -- If `¬2 ≤ b`, then `b = 1`. Since all composite numbers are pseudoprimes to base 1, we can pick -- any composite number greater than m. We choose `2 * (m + 2)` because it is greater than `m` and -- is composite for all natural numbers `m`. { have h₁ : b = 1 := by linarith, rw h₁, use 2 * (m + 2), have : ¬nat.prime (2 * (m + 2)) := nat.not_prime_mul (by norm_num) (by norm_num), exact ⟨base_one (by linarith) this, by linarith⟩ } end theorem frequently_at_top_fermat_psp {b : ℕ} (h : 1 ≤ b) : ∃ᶠ n in filter.at_top, fermat_psp n b := begin -- Based on the proof of `nat.frequently_at_top_modeq_one` refine filter.frequently_at_top.2 (λ n, _), obtain ⟨p, hp⟩ := exists_infinite_pseudoprimes h n, exact ⟨p, hp.2, hp.1⟩ end /-- Infinite set variant of `exists_infinite_pseudoprimes` -/ theorem infinite_set_of_prime_modeq_one {b : ℕ} (h : 1 ≤ b) : set.infinite {n : ℕ | fermat_psp n b} := nat.frequently_at_top_iff_infinite.mp (frequently_at_top_fermat_psp h) end fermat_psp
4b0e375640db3e2e86e032155349e0746b98db58
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/data/multiset/erase_dup.lean
1e4366302133fd71fa997acd547e243c8ce87f9d
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,607
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.multiset.nodup /-! # Erasing duplicates in a multiset. -/ namespace multiset open list variables {α β : Type*} [decidable_eq α] /-! ### erase_dup -/ /-- `erase_dup s` removes duplicates from `s`, yielding a `nodup` multiset. -/ def erase_dup (s : multiset α) : multiset α := quot.lift_on s (λ l, (l.erase_dup : multiset α)) (λ s t p, quot.sound p.erase_dup) @[simp] theorem coe_erase_dup (l : list α) : @erase_dup α _ l = l.erase_dup := rfl @[simp] theorem erase_dup_zero : @erase_dup α _ 0 = 0 := rfl @[simp] theorem mem_erase_dup {a : α} {s : multiset α} : a ∈ erase_dup s ↔ a ∈ s := quot.induction_on s $ λ l, mem_erase_dup @[simp] theorem erase_dup_cons_of_mem {a : α} {s : multiset α} : a ∈ s → erase_dup (a ::ₘ s) = erase_dup s := quot.induction_on s $ λ l m, @congr_arg _ _ _ _ coe $ erase_dup_cons_of_mem m @[simp] theorem erase_dup_cons_of_not_mem {a : α} {s : multiset α} : a ∉ s → erase_dup (a ::ₘ s) = a ::ₘ erase_dup s := quot.induction_on s $ λ l m, congr_arg coe $ erase_dup_cons_of_not_mem m theorem erase_dup_le (s : multiset α) : erase_dup s ≤ s := quot.induction_on s $ λ l, (erase_dup_sublist _).subperm theorem erase_dup_subset (s : multiset α) : erase_dup s ⊆ s := subset_of_le $ erase_dup_le _ theorem subset_erase_dup (s : multiset α) : s ⊆ erase_dup s := λ a, mem_erase_dup.2 @[simp] theorem erase_dup_subset' {s t : multiset α} : erase_dup s ⊆ t ↔ s ⊆ t := ⟨subset.trans (subset_erase_dup _), subset.trans (erase_dup_subset _)⟩ @[simp] theorem subset_erase_dup' {s t : multiset α} : s ⊆ erase_dup t ↔ s ⊆ t := ⟨λ h, subset.trans h (erase_dup_subset _), λ h, subset.trans h (subset_erase_dup _)⟩ @[simp] theorem nodup_erase_dup (s : multiset α) : nodup (erase_dup s) := quot.induction_on s nodup_erase_dup theorem erase_dup_eq_self {s : multiset α} : erase_dup s = s ↔ nodup s := ⟨λ e, e ▸ nodup_erase_dup s, quot.induction_on s $ λ l h, congr_arg coe $ erase_dup_eq_self.2 h⟩ theorem erase_dup_eq_zero {s : multiset α} : erase_dup s = 0 ↔ s = 0 := ⟨λ h, eq_zero_of_subset_zero $ h ▸ subset_erase_dup _, λ h, h.symm ▸ erase_dup_zero⟩ @[simp] theorem erase_dup_singleton {a : α} : erase_dup ({a} : multiset α) = {a} := erase_dup_eq_self.2 $ nodup_singleton _ theorem le_erase_dup {s t : multiset α} : s ≤ erase_dup t ↔ s ≤ t ∧ nodup s := ⟨λ h, ⟨le_trans h (erase_dup_le _), nodup_of_le h (nodup_erase_dup _)⟩, λ ⟨l, d⟩, (le_iff_subset d).2 $ subset.trans (subset_of_le l) (subset_erase_dup _)⟩ theorem erase_dup_ext {s t : multiset α} : erase_dup s = erase_dup t ↔ ∀ a, a ∈ s ↔ a ∈ t := by simp [nodup_ext] theorem erase_dup_map_erase_dup_eq [decidable_eq β] (f : α → β) (s : multiset α) : erase_dup (map f (erase_dup s)) = erase_dup (map f s) := by simp [erase_dup_ext] @[simp] lemma erase_dup_nsmul {s : multiset α} {n : ℕ} (h0 : n ≠ 0) : (n • s).erase_dup = s.erase_dup := begin ext a, by_cases h : a ∈ s; simp [h,h0] end lemma nodup.le_erase_dup_iff_le {s t : multiset α} (hno : s.nodup) : s ≤ t.erase_dup ↔ s ≤ t := by simp [le_erase_dup, hno] end multiset lemma multiset.nodup.le_nsmul_iff_le {α : Type*} {s t : multiset α} {n : ℕ} (h : s.nodup) (hn : n ≠ 0) : s ≤ n • t ↔ s ≤ t := begin classical, rw [← h.le_erase_dup_iff_le, iff.comm, ← h.le_erase_dup_iff_le], simp [hn] end
df6e53c9d6adf775dff188bc69b70603bedd1266
cbb1957fc3e28e502582c54cbce826d666350eda
/fabstract/Bauer_A_InjBaireNat/fabstract.lean
fec29c3e40ea67eb7ccfa2d521f4f8878bcfde6f
[ "CC-BY-4.0" ]
permissive
andrejbauer/formalabstracts
9040b172da080406448ad1b0260d550122dcad74
a3b84fd90901ccf4b63eb9f95d4286a8775864d0
refs/heads/master
1,609,476,417,918
1,501,541,742,000
1,501,541,760,000
97,241,872
1
0
null
1,500,042,191,000
1,500,042,191,000
null
UTF-8
Lean
false
false
1,661
lean
import meta_data .toposes .realizability namespace Bauer_A_InjBaireNat noncomputable theory -- we construct a partial combinatory algebra based on -- infinite-time Turing machines unfinished J : PCA := { description := "a partial-combinatory algebra constructured from infinite time turing machine", references := [cite.Item cite.Ibidem "Section 3", cite.DOI "10.1023/A:1021180801870", cite.Arxiv "math/9808093"] } definition RT_J := RT J definition N := RT_J.nno.underlying_object definition Baire := (RT_J.exponent N N).underlying_object unfinished Baire_to_N : RT_J.underlying_category.hom Baire N := { description := "A morphism from N^N to N", references := [cite.Item cite.Ibidem "Section 4"] } unfinished Baire_to_N_is_mono : monomorphism Baire_to_N := { description := "The morphism Baire_to_N from N^Nto N is mono", references := [cite.Item cite.Ibidem "Section 4"] } def fabstract : meta_data := { description := "We construct a realizability topos in which the reals are embedded in the natural numbers. The topos is based on infinite-time Turing machines of Joel Hamkins.", authors := [{name := "Andrej Bauer", homepage := "http://www.andrej.com"}], primary := cite.DOI "10.1017/S0960129513000406", secondary := [ cite.URL "http://math.andrej.com/2011/06/15/constructive-gem-an-injection-from-baire-space-to-natural-numbers/", -- blog cite.URL "https://vimeo.com/30368682" -- video of a talk about the paper ], results := [result.Construction J, result.Construction Baire_to_N, result.Proof Baire_to_N_is_mono] } end Bauer_A_InjBaireNat
a2ac4300098c241f3d99ce3d606f7a7ebcdc0b4d
274261f7150b4ed5f1962f172c9357591be8a2b5
/src/module_trivialities.lean
9655c43fe2272513133fbd340480a0b9685b0e58
[]
no_license
rspencer01/lean_representation_theory
219ea1edf4b9897b2997226b54473e44e1538b50
2eef2b4b39d99d7ce71bec7bbc3dcc2f7586fcb5
refs/heads/master
1,588,133,157,029
1,571,689,957,000
1,571,689,957,000
175,835,785
0
0
null
null
null
null
UTF-8
Lean
false
false
1,654
lean
import algebra.category.Module.basic import logic.unique import data.set.basic variables {R : Type} [ring R] (M : Module R) def is_trivial (R : Type) [ring R] (M : Module R) := nonempty (M ≅ 0) @[simp] lemma eq_zero_of_zero_module (a : (0 : Module R)) : a = 0 := punit.unique.uniq a lemma eq_zero_of_elts_of_trivial_module (f : M ≅ 0) (a : M) : a = 0 := calc a = ((𝟙 M) : M → M) a : by simp ... = (f.hom ≫ f.inv) a : by rw f.hom_inv_id ... = f.inv (f.hom a) : rfl ... = f.inv 0 : by rw (eq_zero_of_zero_module (f.hom a)) ... = 0 : by simp lemma bot_isom_trivial (M : Module R) : ((⊥ : submodule R M) : Module R) ≅ 0 := { hom := 0, inv := 0, hom_inv_id' := begin apply Module.hom_ext', rw Module.module_hom_comp, apply function.funext_iff.2, intros, simp[*], exact eq.symm (submodule.eq_zero_of_bot_submodule a) end, inv_hom_id' := begin apply Module.hom_ext', rw Module.module_hom_comp, simp, apply function.funext_iff.2, intros, simp[*], exact eq.symm (eq_zero_of_zero_module a) end, } lemma bot_is_trivial (M : Module R) : is_trivial R (⊥ : submodule R M) := ⟨ bot_isom_trivial M ⟩ lemma isom_trivial_is_bot (M : Module R) (N : submodule R M) : is_trivial R N → N = ⊥ := begin intros, apply nonempty.elim a, intro f, have h : ∀ x: N, x = 0 := eq_zero_of_elts_of_trivial_module _ f, apply submodule.ext, intro, split, swap, intro, have i : x = 0 := set.eq_of_mem_singleton a_1, finish, intro, have q := h ⟨ x, a_1 ⟩ , apply set.mem_singleton_of_eq, exact subtype.ext.elim_left q end
9c68844a897a1d84607ad462539bbfd31ec4f6a9
367134ba5a65885e863bdc4507601606690974c1
/src/analysis/normed_space/add_torsor.lean
b6d7f4dae75a902d4337c5fad410dfe7262717e4
[ "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
14,447
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers, Yury Kudryashov. -/ import linear_algebra.affine_space.midpoint import topology.metric_space.isometry import topology.instances.real_vector_space /-! # Torsors of additive normed group actions. This file defines torsors of additive normed group actions, with a metric space structure. The motivating case is Euclidean affine spaces. -/ noncomputable theory open_locale nnreal topological_space open filter /-- A `normed_add_torsor V P` is a torsor of an additive normed group action by a `normed_group V` on points `P`. We bundle the metric space structure and require the distance to be the same as results from the norm (which in fact implies the distance yields a metric space, but bundling just the distance and using an instance for the metric space results in type class problems). -/ class normed_add_torsor (V : out_param $ Type*) (P : Type*) [out_param $ normed_group V] [metric_space P] extends add_torsor V P := (dist_eq_norm' : ∀ (x y : P), dist x y = ∥(x -ᵥ y : V)∥) variables {α V P : Type*} [normed_group V] [metric_space P] [normed_add_torsor V P] include V section variable (V) /-- The distance equals the norm of subtracting two points. In this lemma, it is necessary to have `V` as an explicit argument; otherwise `rw dist_eq_norm_vsub` sometimes doesn't work. -/ lemma dist_eq_norm_vsub (x y : P) : dist x y = ∥(x -ᵥ y)∥ := normed_add_torsor.dist_eq_norm' x y /-- A `normed_group` is a `normed_add_torsor` over itself. -/ @[priority 100] instance normed_group.normed_add_torsor : normed_add_torsor V V := { dist_eq_norm' := dist_eq_norm } end @[simp] lemma dist_vadd_cancel_left (v : V) (x y : P) : dist (v +ᵥ x) (v +ᵥ y) = dist x y := by rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, vadd_vsub_vadd_cancel_left] @[simp] lemma dist_vadd_cancel_right (v₁ v₂ : V) (x : P) : dist (v₁ +ᵥ x) (v₂ +ᵥ x) = dist v₁ v₂ := by rw [dist_eq_norm_vsub V, dist_eq_norm, vadd_vsub_vadd_cancel_right] @[simp] lemma dist_vadd_left (v : V) (x : P) : dist (v +ᵥ x) x = ∥v∥ := by simp [dist_eq_norm_vsub V _ x] @[simp] lemma dist_vadd_right (v : V) (x : P) : dist x (v +ᵥ x) = ∥v∥ := by rw [dist_comm, dist_vadd_left] @[simp] lemma dist_vsub_cancel_left (x y z : P) : dist (x -ᵥ y) (x -ᵥ z) = dist y z := by rw [dist_eq_norm, vsub_sub_vsub_cancel_left, dist_comm, dist_eq_norm_vsub V] @[simp] lemma dist_vsub_cancel_right (x y z : P) : dist (x -ᵥ z) (y -ᵥ z) = dist x y := by rw [dist_eq_norm, vsub_sub_vsub_cancel_right, dist_eq_norm_vsub V] lemma dist_vadd_vadd_le (v v' : V) (p p' : P) : dist (v +ᵥ p) (v' +ᵥ p') ≤ dist v v' + dist p p' := by simpa using dist_triangle (v +ᵥ p) (v' +ᵥ p) (v' +ᵥ p') lemma dist_vsub_vsub_le (p₁ p₂ p₃ p₄ : P) : dist (p₁ -ᵥ p₂) (p₃ -ᵥ p₄) ≤ dist p₁ p₃ + dist p₂ p₄ := by { rw [dist_eq_norm, vsub_sub_vsub_comm, dist_eq_norm_vsub V, dist_eq_norm_vsub V], exact norm_sub_le _ _ } lemma nndist_vadd_vadd_le (v v' : V) (p p' : P) : nndist (v +ᵥ p) (v' +ᵥ p') ≤ nndist v v' + nndist p p' := by simp only [← nnreal.coe_le_coe, nnreal.coe_add, ← dist_nndist, dist_vadd_vadd_le] lemma nndist_vsub_vsub_le (p₁ p₂ p₃ p₄ : P) : nndist (p₁ -ᵥ p₂) (p₃ -ᵥ p₄) ≤ nndist p₁ p₃ + nndist p₂ p₄ := by simp only [← nnreal.coe_le_coe, nnreal.coe_add, ← dist_nndist, dist_vsub_vsub_le] lemma edist_vadd_vadd_le (v v' : V) (p p' : P) : edist (v +ᵥ p) (v' +ᵥ p') ≤ edist v v' + edist p p' := by { simp only [edist_nndist], apply_mod_cast nndist_vadd_vadd_le } lemma edist_vsub_vsub_le (p₁ p₂ p₃ p₄ : P) : edist (p₁ -ᵥ p₂) (p₃ -ᵥ p₄) ≤ edist p₁ p₃ + edist p₂ p₄ := by { simp only [edist_nndist], apply_mod_cast nndist_vsub_vsub_le } omit V /-- The distance defines a metric space structure on the torsor. This is not an instance because it depends on `V` to define a `metric_space P`. -/ def metric_space_of_normed_group_of_add_torsor (V P : Type*) [normed_group V] [add_torsor V P] : metric_space P := { dist := λ x y, ∥(x -ᵥ y : V)∥, dist_self := λ x, by simp, eq_of_dist_eq_zero := λ x y h, by simpa using h, dist_comm := λ x y, by simp only [←neg_vsub_eq_vsub_rev y x, norm_neg], dist_triangle := begin intros x y z, change ∥x -ᵥ z∥ ≤ ∥x -ᵥ y∥ + ∥y -ᵥ z∥, rw ←vsub_add_vsub_cancel, apply norm_add_le end } include V namespace isometric /-- The map `v ↦ v +ᵥ p` as an isometric equivalence between `V` and `P`. -/ def vadd_const (p : P) : V ≃ᵢ P := ⟨equiv.vadd_const p, isometry_emetric_iff_metric.2 $ λ x₁ x₂, dist_vadd_cancel_right x₁ x₂ p⟩ @[simp] lemma coe_vadd_const (p : P) : ⇑(vadd_const p) = λ v, v +ᵥ p := rfl @[simp] lemma coe_vadd_const_symm (p : P) : ⇑(vadd_const p).symm = λ p', p' -ᵥ p := rfl @[simp] lemma vadd_const_to_equiv (p : P) : (vadd_const p).to_equiv = equiv.vadd_const p := rfl /-- `p' ↦ p -ᵥ p'` as an equivalence. -/ def const_vsub (p : P) : P ≃ᵢ V := ⟨equiv.const_vsub p, isometry_emetric_iff_metric.2 $ λ p₁ p₂, dist_vsub_cancel_left _ _ _⟩ @[simp] lemma coe_const_vsub (p : P) : ⇑(const_vsub p) = (-ᵥ) p := rfl @[simp] lemma coe_const_vsub_symm (p : P) : ⇑(const_vsub p).symm = λ v, -v +ᵥ p := rfl variables (P) /-- The map `p ↦ v +ᵥ p` as an isometric automorphism of `P`. -/ def const_vadd (v : V) : P ≃ᵢ P := ⟨equiv.const_vadd P v, isometry_emetric_iff_metric.2 $ dist_vadd_cancel_left v⟩ @[simp] lemma coe_const_vadd (v : V) : ⇑(const_vadd P v) = (+ᵥ) v := rfl variable (V) @[simp] lemma const_vadd_zero : const_vadd P (0:V) = isometric.refl P := isometric.to_equiv_inj $ equiv.const_vadd_zero V P variables {P V} /-- Point reflection in `x` as an `isometric` homeomorphism. -/ def point_reflection (x : P) : P ≃ᵢ P := (const_vsub x).trans (vadd_const x) lemma point_reflection_apply (x y : P) : point_reflection x y = x -ᵥ y +ᵥ x := rfl @[simp] lemma point_reflection_to_equiv (x : P) : (point_reflection x).to_equiv = equiv.point_reflection x := rfl @[simp] lemma point_reflection_self (x : P) : point_reflection x x = x := equiv.point_reflection_self x lemma point_reflection_involutive (x : P) : function.involutive (point_reflection x : P → P) := equiv.point_reflection_involutive x @[simp] lemma point_reflection_symm (x : P) : (point_reflection x).symm = point_reflection x := to_equiv_inj $ equiv.point_reflection_symm x @[simp] lemma dist_point_reflection_fixed (x y : P) : dist (point_reflection x y) x = dist y x := by rw [← (point_reflection x).dist_eq y x, point_reflection_self] lemma dist_point_reflection_self' (x y : P) : dist (point_reflection x y) y = ∥bit0 (x -ᵥ y)∥ := by rw [point_reflection_apply, dist_eq_norm_vsub V, vadd_vsub_assoc, bit0] lemma dist_point_reflection_self (𝕜 : Type*) [normed_field 𝕜] [normed_space 𝕜 V] (x y : P) : dist (point_reflection x y) y = ∥(2:𝕜)∥ * dist x y := by rw [dist_point_reflection_self', ← two_smul' 𝕜 (x -ᵥ y), norm_smul, ← dist_eq_norm_vsub V] lemma point_reflection_fixed_iff (𝕜 : Type*) [normed_field 𝕜] [normed_space 𝕜 V] [invertible (2:𝕜)] {x y : P} : point_reflection x y = y ↔ y = x := affine_equiv.point_reflection_fixed_iff_of_module 𝕜 variables [normed_space ℝ V] lemma dist_point_reflection_self_real (x y : P) : dist (point_reflection x y) y = 2 * dist x y := by { rw [dist_point_reflection_self ℝ, real.norm_two], apply_instance } @[simp] lemma point_reflection_midpoint_left (x y : P) : point_reflection (midpoint ℝ x y) x = y := affine_equiv.point_reflection_midpoint_left x y @[simp] lemma point_reflection_midpoint_right (x y : P) : point_reflection (midpoint ℝ x y) y = x := affine_equiv.point_reflection_midpoint_right x y end isometric lemma lipschitz_with.vadd [emetric_space α] {f : α → V} {g : α → P} {Kf Kg : ℝ≥0} (hf : lipschitz_with Kf f) (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) (f +ᵥ g) := λ x y, calc edist (f x +ᵥ g x) (f y +ᵥ g y) ≤ edist (f x) (f y) + edist (g x) (g y) : edist_vadd_vadd_le _ _ _ _ ... ≤ Kf * edist x y + Kg * edist x y : add_le_add (hf x y) (hg x y) ... = (Kf + Kg) * edist x y : (add_mul _ _ _).symm lemma lipschitz_with.vsub [emetric_space α] {f g : α → P} {Kf Kg : ℝ≥0} (hf : lipschitz_with Kf f) (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) (f -ᵥ g) := λ x y, calc edist (f x -ᵥ g x) (f y -ᵥ g y) ≤ edist (f x) (f y) + edist (g x) (g y) : edist_vsub_vsub_le _ _ _ _ ... ≤ Kf * edist x y + Kg * edist x y : add_le_add (hf x y) (hg x y) ... = (Kf + Kg) * edist x y : (add_mul _ _ _).symm lemma uniform_continuous_vadd : uniform_continuous (λ x : V × P, x.1 +ᵥ x.2) := (lipschitz_with.prod_fst.vadd lipschitz_with.prod_snd).uniform_continuous lemma uniform_continuous_vsub : uniform_continuous (λ x : P × P, x.1 -ᵥ x.2) := (lipschitz_with.prod_fst.vsub lipschitz_with.prod_snd).uniform_continuous lemma continuous_vadd : continuous (λ x : V × P, x.1 +ᵥ x.2) := uniform_continuous_vadd.continuous lemma continuous_vsub : continuous (λ x : P × P, x.1 -ᵥ x.2) := uniform_continuous_vsub.continuous lemma filter.tendsto.vadd {l : filter α} {f : α → V} {g : α → P} {v : V} {p : P} (hf : tendsto f l (𝓝 v)) (hg : tendsto g l (𝓝 p)) : tendsto (f +ᵥ g) l (𝓝 (v +ᵥ p)) := (continuous_vadd.tendsto (v, p)).comp (hf.prod_mk_nhds hg) lemma filter.tendsto.vsub {l : filter α} {f g : α → P} {x y : P} (hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) : tendsto (f -ᵥ g) l (𝓝 (x -ᵥ y)) := (continuous_vsub.tendsto (x, y)).comp (hf.prod_mk_nhds hg) section variables [topological_space α] lemma continuous.vadd {f : α → V} {g : α → P} (hf : continuous f) (hg : continuous g) : continuous (f +ᵥ g) := continuous_vadd.comp (hf.prod_mk hg) lemma continuous.vsub {f g : α → P} (hf : continuous f) (hg : continuous g) : continuous (f -ᵥ g) := continuous_vsub.comp (hf.prod_mk hg : _) lemma continuous_at.vadd {f : α → V} {g : α → P} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (f +ᵥ g) x := hf.vadd hg lemma continuous_at.vsub {f g : α → P} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (f -ᵥ g) x := hf.vsub hg lemma continuous_within_at.vadd {f : α → V} {g : α → P} {x : α} {s : set α} (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (f +ᵥ g) s x := hf.vadd hg lemma continuous_within_at.vsub {f g : α → P} {x : α} {s : set α} (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (f -ᵥ g) s x := hf.vsub hg end variables {V' : Type*} {P' : Type*} [normed_group V'] [metric_space P'] [normed_add_torsor V' P'] /-- The map `g` from `V1` to `V2` corresponding to a map `f` from `P1` to `P2`, at a base point `p`, is an isometry if `f` is one. -/ lemma isometry.vadd_vsub {f : P → P'} (hf : isometry f) {p : P} {g : V → V'} (hg : ∀ v, g v = f (v +ᵥ p) -ᵥ f p) : isometry g := begin convert (isometric.vadd_const (f p)).symm.isometry.comp (hf.comp (isometric.vadd_const p).isometry), exact funext hg end section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 V] open affine_map /-- If `f` is an affine map, then its linear part is continuous iff `f` is continuous. -/ lemma affine_map.continuous_linear_iff [normed_space 𝕜 V'] {f : P →ᵃ[𝕜] P'} : continuous f.linear ↔ continuous f := begin inhabit P, have : (f.linear : V → V') = (isometric.vadd_const $ f $ default P).to_homeomorph.symm ∘ f ∘ (isometric.vadd_const $ default P).to_homeomorph, { ext v, simp }, rw this, simp only [homeomorph.comp_continuous_iff, homeomorph.comp_continuous_iff'], end @[simp] lemma dist_center_homothety (p₁ p₂ : P) (c : 𝕜) : dist p₁ (homothety p₁ c p₂) = ∥c∥ * dist p₁ p₂ := by simp [homothety_def, norm_smul, ← dist_eq_norm_vsub, dist_comm] @[simp] lemma dist_homothety_center (p₁ p₂ : P) (c : 𝕜) : dist (homothety p₁ c p₂) p₁ = ∥c∥ * dist p₁ p₂ := by rw [dist_comm, dist_center_homothety] @[simp] lemma dist_homothety_self (p₁ p₂ : P) (c : 𝕜) : dist (homothety p₁ c p₂) p₂ = ∥1 - c∥ * dist p₁ p₂ := by rw [homothety_eq_line_map, ← line_map_apply_one_sub, ← homothety_eq_line_map, dist_homothety_center, dist_comm] @[simp] lemma dist_self_homothety (p₁ p₂ : P) (c : 𝕜) : dist p₂ (homothety p₁ c p₂) = ∥1 - c∥ * dist p₁ p₂ := by rw [dist_comm, dist_homothety_self] variables [invertible (2:𝕜)] @[simp] lemma dist_left_midpoint (p₁ p₂ : P) : dist p₁ (midpoint 𝕜 p₁ p₂) = ∥(2:𝕜)∥⁻¹ * dist p₁ p₂ := by rw [midpoint, ← homothety_eq_line_map, dist_center_homothety, inv_of_eq_inv, ← normed_field.norm_inv] @[simp] lemma dist_midpoint_left (p₁ p₂ : P) : dist (midpoint 𝕜 p₁ p₂) p₁ = ∥(2:𝕜)∥⁻¹ * dist p₁ p₂ := by rw [dist_comm, dist_left_midpoint] @[simp] lemma dist_midpoint_right (p₁ p₂ : P) : dist (midpoint 𝕜 p₁ p₂) p₂ = ∥(2:𝕜)∥⁻¹ * dist p₁ p₂ := by rw [midpoint_comm, dist_midpoint_left, dist_comm] @[simp] lemma dist_right_midpoint (p₁ p₂ : P) : dist p₂ (midpoint 𝕜 p₁ p₂) = ∥(2:𝕜)∥⁻¹ * dist p₁ p₂ := by rw [dist_comm, dist_midpoint_right] end normed_space variables [normed_space ℝ V] [normed_space ℝ V'] include V' /-- A continuous map between two normed affine spaces is an affine map provided that it sends midpoints to midpoints. -/ def affine_map.of_map_midpoint (f : P → P') (h : ∀ x y, f (midpoint ℝ x y) = midpoint ℝ (f x) (f y)) (hfc : continuous f) : P →ᵃ[ℝ] P' := affine_map.mk' f ↑((add_monoid_hom.of_map_midpoint ℝ ℝ ((affine_equiv.vadd_const ℝ (f $ classical.arbitrary P)).symm ∘ f ∘ (affine_equiv.vadd_const ℝ (classical.arbitrary P))) (by simp) (λ x y, by simp [h])).to_real_linear_map $ by apply_rules [continuous.vadd, continuous.vsub, continuous_const, hfc.comp, continuous_id]) (classical.arbitrary P) (λ p, by simp)
500a6f64a6af285acb29cdd0b401386e4d44b45e
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/probability/kernel/invariance.lean
478deaee8768a56f9748371d31a89de1f6dd409b
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
3,174
lean
/- Copyright (c) 2023 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import probability.kernel.composition /-! # Invariance of measures along a kernel > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We say that a measure `μ` is invariant with respect to a kernel `κ` if its push-forward along the kernel `μ.bind κ` is the same measure. ## Main definitions * `probability_theory.kernel.invariant`: invariance of a given measure with respect to a kernel. ## Useful lemmas * `probability_theory.kernel.const_bind_eq_comp_const`, and `probability_theory.kernel.comp_const_apply_eq_bind` established the relationship between the push-forward measure and the composition of kernels. -/ open measure_theory open_locale measure_theory ennreal probability_theory namespace probability_theory variables {α β γ : Type*} {mα : measurable_space α} {mβ : measurable_space β} {mγ : measurable_space γ} include mα mβ namespace kernel /-! ### Push-forward of measures along a kernel -/ @[simp] lemma bind_add (μ ν : measure α) (κ : kernel α β) : (μ + ν).bind κ = μ.bind κ + ν.bind κ := begin ext1 s hs, rw [measure.bind_apply hs (kernel.measurable _), lintegral_add_measure, measure.coe_add, pi.add_apply, measure.bind_apply hs (kernel.measurable _), measure.bind_apply hs (kernel.measurable _)], end @[simp] lemma bind_smul (κ : kernel α β) (μ : measure α) (r : ℝ≥0∞) : (r • μ).bind κ = r • μ.bind κ := begin ext1 s hs, rw [measure.bind_apply hs (kernel.measurable _), lintegral_smul_measure, measure.coe_smul, pi.smul_apply, measure.bind_apply hs (kernel.measurable _), smul_eq_mul], end lemma const_bind_eq_comp_const (κ : kernel α β) (μ : measure α) : const α (μ.bind κ) = κ ∘ₖ const α μ := begin ext a s hs : 2, simp_rw [comp_apply' _ _ _ hs, const_apply, measure.bind_apply hs (kernel.measurable _)], end lemma comp_const_apply_eq_bind (κ : kernel α β) (μ : measure α) (a : α) : (κ ∘ₖ const α μ) a = μ.bind κ := by rw [← const_apply (μ.bind κ) a, const_bind_eq_comp_const κ μ] omit mβ /-! ### Invariant measures of kernels -/ /-- A measure `μ` is invariant with respect to the kernel `κ` if the push-forward measure of `μ` along `κ` equals `μ`. -/ def invariant (κ : kernel α α) (μ : measure α) : Prop := μ.bind κ = μ variables {κ η : kernel α α} {μ : measure α} lemma invariant.def (hκ : invariant κ μ) : μ.bind κ = μ := hκ lemma invariant.comp_const (hκ : invariant κ μ) : κ ∘ₖ const α μ = const α μ := by rw [← const_bind_eq_comp_const κ μ, hκ.def] lemma invariant.comp [is_s_finite_kernel κ] (hκ : invariant κ μ) (hη : invariant η μ) : invariant (κ ∘ₖ η) μ := begin casesI is_empty_or_nonempty α with _ hα, { exact subsingleton.elim _ _ }, { simp_rw [invariant, ← comp_const_apply_eq_bind (κ ∘ₖ η) μ hα.some, comp_assoc, hη.comp_const, hκ.comp_const, const_apply] }, end end kernel end probability_theory
0733b37fa48c2e68536c30d6de88959af8a1ea0f
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/src/Init/Lean/Util/Sorry.lean
2cb9764e3fdf375d4217780ae62ea8e211e2e2a5
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
2,400
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.Lean.Message namespace Lean def Expr.isSorry : Expr → Bool | Expr.app (Expr.app (Expr.const `sorryAx _ _) _ _) _ _ => true | _ => false def Expr.isSyntheticSorry : Expr → Bool | Expr.app (Expr.app (Expr.const `sorryAx _ _) _ _) (Expr.const `Bool.true _ _) _ => true | _ => false def Expr.hasSorry : Expr → Bool | Expr.const c _ _ => c == `sorryAx | Expr.app f a _ => f.hasSorry || a.hasSorry | Expr.letE _ t v b _ => t.hasSorry || v.hasSorry || b.hasSorry | Expr.forallE _ d b _ => d.hasSorry || b.hasSorry | Expr.lam _ d b _ => d.hasSorry || b.hasSorry | Expr.mdata _ e _ => e.hasSorry | Expr.proj _ _ e _ => e.hasSorry | _ => false def Expr.hasSyntheticSorry : Expr → Bool | e@(Expr.app f a _) => e.isSyntheticSorry || f.hasSyntheticSorry || a.hasSyntheticSorry | Expr.letE _ t v b _ => t.hasSyntheticSorry || v.hasSyntheticSorry || b.hasSyntheticSorry | Expr.forallE _ d b _ => d.hasSyntheticSorry || b.hasSyntheticSorry | Expr.lam _ d b _ => d.hasSyntheticSorry || b.hasSyntheticSorry | Expr.mdata _ e _ => e.hasSyntheticSorry | Expr.proj _ _ e _ => e.hasSyntheticSorry | _ => false partial def MessageData.hasSorry : MessageData → Bool | MessageData.ofExpr e => e.hasSorry | MessageData.withContext _ msg => msg.hasSorry | MessageData.nest _ msg => msg.hasSorry | MessageData.group msg => msg.hasSorry | MessageData.compose msg₁ msg₂ => msg₁.hasSorry || msg₂.hasSorry | MessageData.tagged _ msg => msg.hasSorry | MessageData.node msgs => msgs.any MessageData.hasSorry | _ => false partial def MessageData.hasSyntheticSorry : MessageData → Bool | MessageData.ofExpr e => e.hasSyntheticSorry | MessageData.withContext _ msg => msg.hasSyntheticSorry | MessageData.nest _ msg => msg.hasSyntheticSorry | MessageData.group msg => msg.hasSyntheticSorry | MessageData.compose msg₁ msg₂ => msg₁.hasSyntheticSorry || msg₂.hasSyntheticSorry | MessageData.tagged _ msg => msg.hasSyntheticSorry | MessageData.node msgs => msgs.any MessageData.hasSyntheticSorry | _ => false end Lean
6517641a99eb07476ae407a5daea9ed624a69d2a
94e33a31faa76775069b071adea97e86e218a8ee
/src/linear_algebra/finite_dimensional.lean
59d27263a2ca85413f64763a5fbb2105c4205fe2
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
75,164
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 algebra.algebra.subalgebra.basic import field_theory.finiteness /-! # Finite dimensional vector spaces Definition and basic properties of finite dimensional vector spaces, of their dimensions, and of linear maps on such spaces. ## Main definitions Assume `V` is a vector space over a field `K`. There are (at least) three equivalent definitions of finite-dimensionality of `V`: - it admits a finite basis. - it is finitely generated. - it is noetherian, i.e., every subspace is finitely generated. We introduce a typeclass `finite_dimensional K V` capturing this property. For ease of transfer of proof, it is defined using the second point of view, i.e., as `finite`. However, we prove that all these points of view are equivalent, with the following lemmas (in the namespace `finite_dimensional`): - `fintype_basis_index` states that a finite-dimensional vector space has a finite basis - `finite_dimensional.fin_basis` and `finite_dimensional.fin_basis_of_finrank_eq` are bases for finite dimensional vector spaces, where the index type is `fin` - `of_fintype_basis` states that the existence of a basis indexed by a finite type implies finite-dimensionality - `of_finset_basis` states that the existence of a basis indexed by a `finset` implies finite-dimensionality - `of_finite_basis` states that the existence of a basis indexed by a finite set implies finite-dimensionality - `is_noetherian.iff_fg` states that the space is finite-dimensional if and only if it is noetherian Also defined is `finrank`, the dimension of a finite dimensional space, returning a `nat`, as opposed to `module.rank`, which returns a `cardinal`. When the space has infinite dimension, its `finrank` is by convention set to `0`. Preservation of finite-dimensionality and formulas for the dimension are given for - submodules - quotients (for the dimension of a quotient, see `finrank_quotient_add_finrank`) - linear equivs, in `linear_equiv.finite_dimensional` and `linear_equiv.finrank_eq` - image under a linear map (the rank-nullity formula is in `finrank_range_add_finrank_ker`) Basic properties of linear maps of a finite-dimensional vector space are given. Notably, the equivalence of injectivity and surjectivity is proved in `linear_map.injective_iff_surjective`, and the equivalence between left-inverse and right-inverse in `linear_map.mul_eq_one_comm` and `linear_map.comp_eq_id_comm`. ## Implementation notes Most results are deduced from the corresponding results for the general dimension (as a cardinal), in `dimension.lean`. Not all results have been ported yet. Much of this file could be generalised away from fields or division rings. You should not assume that there has been any effort to state lemmas as generally as possible. One of the characterizations of finite-dimensionality is in terms of finite generation. This property is currently defined only for submodules, so we express it through the fact that the maximal submodule (which, as a set, coincides with the whole space) is finitely generated. This is not very convenient to use, although there are some helper functions. However, this becomes very convenient when speaking of submodules which are finite-dimensional, as this notion coincides with the fact that the submodule is finitely generated (as a submodule of the whole space). This equivalence is proved in `submodule.fg_iff_finite_dimensional`. -/ universes u v v' w open_locale classical cardinal open cardinal submodule module function /-- `finite_dimensional` vector spaces are defined to be finite modules. Use `finite_dimensional.of_fintype_basis` to prove finite dimension from another definition. -/ @[reducible] def finite_dimensional (K V : Type*) [division_ring K] [add_comm_group V] [module K V] := module.finite K V variables {K : Type u} {V : Type v} namespace finite_dimensional open is_noetherian section division_ring variables [division_ring K] [add_comm_group V] [module K V] {V₂ : Type v'} [add_comm_group V₂] [module K V₂] /-- If the codomain of an injective linear map is finite dimensional, the domain must be as well. -/ lemma of_injective (f : V →ₗ[K] V₂) (w : function.injective f) [finite_dimensional K V₂] : finite_dimensional K V := have is_noetherian K V₂ := is_noetherian.iff_fg.mpr ‹_›, by exactI module.finite.of_injective f w /-- If the domain of a surjective linear map is finite dimensional, the codomain must be as well. -/ lemma of_surjective (f : V →ₗ[K] V₂) (w : function.surjective f) [finite_dimensional K V] : finite_dimensional K V₂ := module.finite.of_surjective f w variables (K V) instance finite_dimensional_pi {ι} [fintype ι] : finite_dimensional K (ι → K) := iff_fg.1 is_noetherian_pi instance finite_dimensional_pi' {ι} [fintype ι] (M : ι → Type*) [∀ i, add_comm_group (M i)] [∀ i, module K (M i)] [I : ∀ i, finite_dimensional K (M i)] : finite_dimensional K (Π i, M i) := begin haveI : ∀ i : ι, is_noetherian K (M i) := λ i, iff_fg.2 (I i), exact iff_fg.1 is_noetherian_pi end /-- A finite dimensional vector space over a finite field is finite -/ noncomputable def fintype_of_fintype [fintype K] [finite_dimensional K V] : fintype V := module.fintype_of_fintype (@finset_basis K V _ _ _ (iff_fg.2 infer_instance)) variables {K V} /-- If a vector space has a finite basis, then it is finite-dimensional. -/ lemma of_fintype_basis {ι : Type w} [fintype ι] (h : basis ι K V) : finite_dimensional K V := ⟨⟨finset.univ.image h, by { convert h.span_eq, simp } ⟩⟩ /-- If a vector space is `finite_dimensional`, all bases are indexed by a finite type -/ noncomputable def fintype_basis_index {ι : Type*} [finite_dimensional K V] (b : basis ι K V) : fintype ι := begin letI : is_noetherian K V := is_noetherian.iff_fg.2 infer_instance, exact is_noetherian.fintype_basis_index b, end /-- If a vector space is `finite_dimensional`, `basis.of_vector_space` is indexed by a finite type.-/ noncomputable instance [finite_dimensional K V] : fintype (basis.of_vector_space_index K V) := begin letI : is_noetherian K V := is_noetherian.iff_fg.2 infer_instance, apply_instance end /-- If a vector space has a basis indexed by elements of a finite set, then it is finite-dimensional. -/ lemma of_finite_basis {ι : Type w} {s : set ι} (h : basis s K V) (hs : set.finite s) : finite_dimensional K V := by haveI := hs.fintype; exact of_fintype_basis h /-- If a vector space has a finite basis, then it is finite-dimensional, finset style. -/ lemma of_finset_basis {ι : Type w} {s : finset ι} (h : basis s K V) : finite_dimensional K V := of_finite_basis h s.finite_to_set /-- A subspace of a finite-dimensional space is also finite-dimensional. -/ instance finite_dimensional_submodule [finite_dimensional K V] (S : submodule K V) : finite_dimensional K S := begin letI : is_noetherian K V := iff_fg.2 _, exact iff_fg.1 (is_noetherian.iff_dim_lt_aleph_0.2 (lt_of_le_of_lt (dim_submodule_le _) (dim_lt_aleph_0 K V))), apply_instance, end /-- A quotient of a finite-dimensional space is also finite-dimensional. -/ instance finite_dimensional_quotient [finite_dimensional K V] (S : submodule K V) : finite_dimensional K (V ⧸ S) := module.finite.of_surjective (submodule.mkq S) $ surjective_quot_mk _ /-- The rank of a module as a natural number. Defined by convention to be `0` if the space has infinite rank. For a vector space `V` over a field `K`, this is the same as the finite dimension of `V` over `K`. -/ noncomputable def finrank (R V : Type*) [semiring R] [add_comm_group V] [module R V] : ℕ := (module.rank R V).to_nat /-- In a finite-dimensional space, its dimension (seen as a cardinal) coincides with its `finrank`. -/ lemma finrank_eq_dim (K : Type u) (V : Type v) [division_ring K] [add_comm_group V] [module K V] [finite_dimensional K V] : (finrank K V : cardinal.{v}) = module.rank K V := begin letI : is_noetherian K V := iff_fg.2 infer_instance, rw [finrank, cast_to_nat_of_lt_aleph_0 (dim_lt_aleph_0 K V)] end lemma finrank_eq_of_dim_eq {n : ℕ} (h : module.rank K V = ↑ n) : finrank K V = n := begin apply_fun to_nat at h, rw to_nat_cast at h, exact_mod_cast h, end lemma finrank_of_infinite_dimensional {K V : Type*} [division_ring K] [add_comm_group V] [module K V] (h : ¬finite_dimensional K V) : finrank K V = 0 := dif_neg $ mt is_noetherian.iff_dim_lt_aleph_0.2 $ (not_iff_not.2 iff_fg).2 h lemma finite_dimensional_of_finrank {K V : Type*} [division_ring K] [add_comm_group V] [module K V] (h : 0 < finrank K V) : finite_dimensional K V := by { contrapose h, simp [finrank_of_infinite_dimensional h] } lemma finite_dimensional_of_finrank_eq_succ {K V : Type*} [field K] [add_comm_group V] [module K V] {n : ℕ} (hn : finrank K V = n.succ) : finite_dimensional K V := finite_dimensional_of_finrank $ by rw hn; exact n.succ_pos /-- We can infer `finite_dimensional K V` in the presence of `[fact (finrank K V = n + 1)]`. Declare this as a local instance where needed. -/ lemma fact_finite_dimensional_of_finrank_eq_succ {K V : Type*} [field K] [add_comm_group V] [module K V] (n : ℕ) [fact (finrank K V = n + 1)] : finite_dimensional K V := finite_dimensional_of_finrank $ by convert nat.succ_pos n; apply fact.out lemma finite_dimensional_iff_of_rank_eq_nsmul {K V W : Type*} [field K] [add_comm_group V] [add_comm_group W] [module K V] [module K W] {n : ℕ} (hn : n ≠ 0) (hVW : module.rank K V = n • module.rank K W) : finite_dimensional K V ↔ finite_dimensional K W := by simp only [finite_dimensional, ← is_noetherian.iff_fg, is_noetherian.iff_dim_lt_aleph_0, hVW, cardinal.nsmul_lt_aleph_0_iff_of_ne_zero hn] /-- If a vector space has a finite basis, then its dimension is equal to the cardinality of the basis. -/ lemma finrank_eq_card_basis {ι : Type w} [fintype ι] (h : basis ι K V) : finrank K V = fintype.card ι := begin haveI : finite_dimensional K V := of_fintype_basis h, have := dim_eq_card_basis h, rw ← finrank_eq_dim at this, exact_mod_cast this end /-- If a vector space is finite-dimensional, then the cardinality of any basis is equal to its `finrank`. -/ lemma finrank_eq_card_basis' [finite_dimensional K V] {ι : Type w} (h : basis ι K V) : (finrank K V : cardinal.{w}) = #ι := begin haveI : is_noetherian K V := iff_fg.2 infer_instance, haveI : fintype ι := fintype_basis_index h, rw [cardinal.mk_fintype, finrank_eq_card_basis h] end /-- If a vector space has a finite basis, then its dimension is equal to the cardinality of the basis. This lemma uses a `finset` instead of indexed types. -/ lemma finrank_eq_card_finset_basis {ι : Type w} {b : finset ι} (h : basis.{w} b K V) : finrank K V = finset.card b := by rw [finrank_eq_card_basis h, fintype.card_coe] variables (K V) /-- A finite dimensional vector space has a basis indexed by `fin (finrank K V)`. -/ noncomputable def fin_basis [finite_dimensional K V] : basis (fin (finrank K V)) K V := have h : fintype.card (@finset_basis_index K V _ _ _ (iff_fg.2 infer_instance)) = finrank K V, from (finrank_eq_card_basis (@finset_basis K V _ _ _ (iff_fg.2 infer_instance))).symm, (@finset_basis K V _ _ _ (iff_fg.2 infer_instance)).reindex (fintype.equiv_fin_of_card_eq h) /-- An `n`-dimensional vector space has a basis indexed by `fin n`. -/ noncomputable def fin_basis_of_finrank_eq [finite_dimensional K V] {n : ℕ} (hn : finrank K V = n) : basis (fin n) K V := (fin_basis K V).reindex (fin.cast hn).to_equiv variables {K V} /-- A module with dimension 1 has a basis with one element. -/ noncomputable def basis_unique (ι : Type*) [unique ι] (h : finrank K V = 1) : basis ι K V := begin haveI := finite_dimensional_of_finrank (_root_.zero_lt_one.trans_le h.symm.le), exact (fin_basis_of_finrank_eq K V h).reindex (equiv.equiv_of_unique _ _) end @[simp] lemma basis_unique.repr_eq_zero_iff {ι : Type*} [unique ι] {h : finrank K V = 1} {v : V} {i : ι} : (basis_unique ι h).repr v i = 0 ↔ v = 0 := ⟨λ hv, (basis_unique ι h).repr.map_eq_zero_iff.mp (finsupp.ext $ λ j, subsingleton.elim i j ▸ hv), λ hv, by rw [hv, linear_equiv.map_zero, finsupp.zero_apply]⟩ lemma cardinal_mk_le_finrank_of_linear_independent [finite_dimensional K V] {ι : Type w} {b : ι → V} (h : linear_independent K b) : #ι ≤ finrank K V := begin rw ← lift_le.{_ (max v w)}, simpa [← finrank_eq_dim K V] using cardinal_lift_le_dim_of_linear_independent.{_ _ _ (max v w)} h end lemma fintype_card_le_finrank_of_linear_independent [finite_dimensional K V] {ι : Type*} [fintype ι] {b : ι → V} (h : linear_independent K b) : fintype.card ι ≤ finrank K V := by simpa using cardinal_mk_le_finrank_of_linear_independent h lemma finset_card_le_finrank_of_linear_independent [finite_dimensional K V] {b : finset V} (h : linear_independent K (λ x, x : b → V)) : b.card ≤ finrank K V := begin rw ←fintype.card_coe, exact fintype_card_le_finrank_of_linear_independent h, end lemma lt_aleph_0_of_linear_independent {ι : Type w} [finite_dimensional K V] {v : ι → V} (h : linear_independent K v) : #ι < ℵ₀ := begin apply cardinal.lift_lt.1, apply lt_of_le_of_lt, apply cardinal_lift_le_dim_of_linear_independent h, rw [←finrank_eq_dim, cardinal.lift_aleph_0, cardinal.lift_nat_cast], apply cardinal.nat_lt_aleph_0, end lemma not_linear_independent_of_infinite {ι : Type w} [inf : infinite ι] [finite_dimensional K V] (v : ι → V) : ¬ linear_independent K v := begin intro h_lin_indep, have : ¬ ℵ₀ ≤ #ι := not_le.mpr (lt_aleph_0_of_linear_independent h_lin_indep), have : ℵ₀ ≤ #ι := infinite_iff.mp inf, contradiction end /-- A finite dimensional space has positive `finrank` iff it has a nonzero element. -/ lemma finrank_pos_iff_exists_ne_zero [finite_dimensional K V] : 0 < finrank K V ↔ ∃ x : V, x ≠ 0 := iff.trans (by { rw ← finrank_eq_dim, norm_cast }) (@dim_pos_iff_exists_ne_zero K V _ _ _ _ _) /-- A finite dimensional space has positive `finrank` iff it is nontrivial. -/ lemma finrank_pos_iff [finite_dimensional K V] : 0 < finrank K V ↔ nontrivial V := iff.trans (by { rw ← finrank_eq_dim, norm_cast }) (@dim_pos_iff_nontrivial K V _ _ _ _ _) /-- A finite dimensional space is nontrivial if it has positive `finrank`. -/ lemma nontrivial_of_finrank_pos (h : 0 < finrank K V) : nontrivial V := begin haveI : finite_dimensional K V := finite_dimensional_of_finrank h, rwa finrank_pos_iff at h end /-- A finite dimensional space is nontrivial if it has `finrank` equal to the successor of a natural number. -/ lemma nontrivial_of_finrank_eq_succ {n : ℕ} (hn : finrank K V = n.succ) : nontrivial V := nontrivial_of_finrank_pos (by rw hn; exact n.succ_pos) /-- A nontrivial finite dimensional space has positive `finrank`. -/ lemma finrank_pos [finite_dimensional K V] [h : nontrivial V] : 0 < finrank K V := finrank_pos_iff.mpr h /-- A finite dimensional space has zero `finrank` iff it is a subsingleton. This is the `finrank` version of `dim_zero_iff`. -/ lemma finrank_zero_iff [finite_dimensional K V] : finrank K V = 0 ↔ subsingleton V := iff.trans (by { rw ← finrank_eq_dim, norm_cast }) (@dim_zero_iff K V _ _ _ _ _) /-- A finite dimensional space that is a subsingleton has zero `finrank`. -/ lemma finrank_zero_of_subsingleton [h : subsingleton V] : finrank K V = 0 := finrank_zero_iff.2 h lemma basis.subset_extend {s : set V} (hs : linear_independent K (coe : s → V)) : s ⊆ hs.extend (set.subset_univ _) := hs.subset_extend _ /-- If a submodule has maximal dimension in a finite dimensional space, then it is equal to the whole space. -/ lemma eq_top_of_finrank_eq [finite_dimensional K V] {S : submodule K V} (h : finrank K S = finrank K V) : S = ⊤ := begin haveI : is_noetherian K V := iff_fg.2 infer_instance, set bS := basis.of_vector_space K S with bS_eq, have : linear_independent K (coe : (coe '' basis.of_vector_space_index K S : set V) → V), from @linear_independent.image_subtype _ _ _ _ _ _ _ _ _ (submodule.subtype S) (by simpa using bS.linear_independent) (by simp), set b := basis.extend this with b_eq, letI : fintype (this.extend _) := (finite_of_linear_independent (by simpa using b.linear_independent)).fintype, letI : fintype (coe '' basis.of_vector_space_index K S) := (finite_of_linear_independent this).fintype, letI : fintype (basis.of_vector_space_index K S) := (finite_of_linear_independent (by simpa using bS.linear_independent)).fintype, have : coe '' (basis.of_vector_space_index K S) = this.extend (set.subset_univ _), from set.eq_of_subset_of_card_le (this.subset_extend _) (by rw [set.card_image_of_injective _ subtype.coe_injective, ← finrank_eq_card_basis bS, ← finrank_eq_card_basis b, h]; apply_instance), rw [← b.span_eq, b_eq, basis.coe_extend, subtype.range_coe, ← this, ← submodule.coe_subtype, span_image], have := bS.span_eq, rw [bS_eq, basis.coe_of_vector_space, subtype.range_coe] at this, rw [this, map_top (submodule.subtype S), range_subtype], end variable (K) /-- A division_ring is one-dimensional as a vector space over itself. -/ @[simp] lemma finrank_self : finrank K K = 1 := begin have := dim_self K, rw [←finrank_eq_dim] at this, exact_mod_cast this end instance finite_dimensional_self : finite_dimensional K K := by apply_instance /-- The vector space of functions on a fintype ι has finrank equal to the cardinality of ι. -/ @[simp] lemma finrank_fintype_fun_eq_card {ι : Type v} [fintype ι] : finrank K (ι → K) = fintype.card ι := begin have : module.rank K (ι → K) = fintype.card ι := dim_fun', rwa [← finrank_eq_dim, nat_cast_inj] at this, end /-- The vector space of functions on `fin n` has finrank equal to `n`. -/ @[simp] lemma finrank_fin_fun {n : ℕ} : finrank K (fin n → K) = n := by simp /-- The submodule generated by a finite set is finite-dimensional. -/ theorem span_of_finite {A : set V} (hA : set.finite A) : finite_dimensional K (submodule.span K A) := iff_fg.1 $ is_noetherian_span_of_finite K hA /-- The submodule generated by a single element is finite-dimensional. -/ instance span_singleton (x : V) : finite_dimensional K (K ∙ x) := span_of_finite K $ set.finite_singleton _ /-- The submodule generated by a finset is finite-dimensional. -/ instance span_finset (s : finset V) : finite_dimensional K (span K (s : set V)) := span_of_finite K $ s.finite_to_set /-- Pushforwards of finite-dimensional submodules are finite-dimensional. -/ instance (f : V →ₗ[K] V₂) (p : submodule K V) [h : finite_dimensional K p] : finite_dimensional K (p.map f) := begin unfreezingI { rw [finite_dimensional, ← iff_fg, is_noetherian.iff_dim_lt_aleph_0] at h ⊢ }, rw [← cardinal.lift_lt.{v' v}], rw [← cardinal.lift_lt.{v v'}] at h, rw [cardinal.lift_aleph_0] at h ⊢, exact (lift_dim_map_le f p).trans_lt h end /-- Pushforwards of finite-dimensional submodules have a smaller finrank. -/ lemma finrank_map_le (f : V →ₗ[K] V₂) (p : submodule K V) [finite_dimensional K p] : finrank K (p.map f) ≤ finrank K p := by simpa [← finrank_eq_dim] using lift_dim_map_le f p variable {K} lemma _root_.complete_lattice.independent.subtype_ne_bot_le_finrank_aux [finite_dimensional K V] {ι : Type w} {p : ι → submodule K V} (hp : complete_lattice.independent p) : #{i // p i ≠ ⊥} ≤ (finrank K V : cardinal.{w}) := begin suffices : cardinal.lift.{v} (#{i // p i ≠ ⊥}) ≤ cardinal.lift.{v} (finrank K V : cardinal.{w}), { rwa cardinal.lift_le at this }, calc cardinal.lift.{v} (# {i // p i ≠ ⊥}) ≤ cardinal.lift.{w} (module.rank K V) : hp.subtype_ne_bot_le_rank ... = cardinal.lift.{w} (finrank K V : cardinal.{v}) : by rw finrank_eq_dim ... = cardinal.lift.{v} (finrank K V : cardinal.{w}) : by simp end /-- If `p` is an independent family of subspaces of a finite-dimensional space `V`, then the number of nontrivial subspaces in the family `p` is finite. -/ noncomputable def _root_.complete_lattice.independent.fintype_ne_bot_of_finite_dimensional [finite_dimensional K V] {ι : Type w} {p : ι → submodule K V} (hp : complete_lattice.independent p) : fintype {i : ι // p i ≠ ⊥} := begin suffices : #{i // p i ≠ ⊥} < (ℵ₀ : cardinal.{w}), { rw cardinal.lt_aleph_0_iff_fintype at this, exact this.some }, refine lt_of_le_of_lt hp.subtype_ne_bot_le_finrank_aux _, simp [cardinal.nat_lt_aleph_0], end /-- If `p` is an independent family of subspaces of a finite-dimensional space `V`, then the number of nontrivial subspaces in the family `p` is bounded above by the dimension of `V`. Note that the `fintype` hypothesis required here can be provided by `complete_lattice.independent.fintype_ne_bot_of_finite_dimensional`. -/ lemma _root_.complete_lattice.independent.subtype_ne_bot_le_finrank [finite_dimensional K V] {ι : Type w} {p : ι → submodule K V} (hp : complete_lattice.independent p) [fintype {i // p i ≠ ⊥}] : fintype.card {i // p i ≠ ⊥} ≤ finrank K V := by simpa using hp.subtype_ne_bot_le_finrank_aux section open_locale big_operators open finset /-- If a finset has cardinality larger than the dimension of the space, then there is a nontrivial linear relation amongst its elements. -/ lemma exists_nontrivial_relation_of_dim_lt_card [finite_dimensional K V] {t : finset V} (h : finrank K V < t.card) : ∃ f : V → K, ∑ e in t, f e • e = 0 ∧ ∃ x ∈ t, f x ≠ 0 := begin have := mt finset_card_le_finrank_of_linear_independent (by { simpa using h }), rw not_linear_independent_iff at this, obtain ⟨s, g, sum, z, zm, nonzero⟩ := this, -- Now we have to extend `g` to all of `t`, then to all of `V`. let f : V → K := λ x, if h : x ∈ t then if (⟨x, h⟩ : t) ∈ s then g ⟨x, h⟩ else 0 else 0, -- and finally clean up the mess caused by the extension. refine ⟨f, _, _⟩, { dsimp [f], rw ← sum, fapply sum_bij_ne_zero (λ v hvt _, (⟨v, hvt⟩ : {v // v ∈ t})), { intros v hvt H, dsimp, rw [dif_pos hvt] at H, contrapose! H, rw [if_neg H, zero_smul], }, { intros _ _ _ _ _ _, exact subtype.mk.inj, }, { intros b hbs hb, use b, simpa only [hbs, exists_prop, dif_pos, finset.mk_coe, and_true, if_true, finset.coe_mem, eq_self_iff_true, exists_prop_of_true, ne.def] using hb, }, { intros a h₁, dsimp, rw [dif_pos h₁], intro h₂, rw [if_pos], contrapose! h₂, rw [if_neg h₂, zero_smul], }, }, { refine ⟨z, z.2, _⟩, dsimp only [f], erw [dif_pos z.2, if_pos]; rwa [subtype.coe_eta] }, end /-- If a finset has cardinality larger than `finrank + 1`, then there is a nontrivial linear relation amongst its elements, such that the coefficients of the relation sum to zero. -/ lemma exists_nontrivial_relation_sum_zero_of_dim_succ_lt_card [finite_dimensional K V] {t : finset V} (h : finrank K V + 1 < t.card) : ∃ f : V → K, ∑ e in t, f e • e = 0 ∧ ∑ e in t, f e = 0 ∧ ∃ x ∈ t, f x ≠ 0 := begin -- Pick an element x₀ ∈ t, have card_pos : 0 < t.card := lt_trans (nat.succ_pos _) h, obtain ⟨x₀, m⟩ := (finset.card_pos.1 card_pos).bex, -- and apply the previous lemma to the {xᵢ - x₀} let shift : V ↪ V := ⟨λ x, x - x₀, sub_left_injective⟩, let t' := (t.erase x₀).map shift, have h' : finrank K V < t'.card, { simp only [t', card_map, finset.card_erase_of_mem m], exact nat.lt_pred_iff.mpr h, }, -- to obtain a function `g`. obtain ⟨g, gsum, x₁, x₁_mem, nz⟩ := exists_nontrivial_relation_of_dim_lt_card h', -- Then obtain `f` by translating back by `x₀`, -- and setting the value of `f` at `x₀` to ensure `∑ e in t, f e = 0`. let f : V → K := λ z, if z = x₀ then - ∑ z in (t.erase x₀), g (z - x₀) else g (z - x₀), refine ⟨f, _ ,_ ,_⟩, -- After this, it's a matter of verifiying the properties, -- based on the corresponding properties for `g`. { show ∑ (e : V) in t, f e • e = 0, -- We prove this by splitting off the `x₀` term of the sum, -- which is itself a sum over `t.erase x₀`, -- combining the two sums, and -- observing that after reindexing we have exactly -- ∑ (x : V) in t', g x • x = 0. simp only [f], conv_lhs { apply_congr, skip, rw [ite_smul], }, rw [finset.sum_ite], conv { congr, congr, apply_congr, simp [filter_eq', m], }, conv { congr, congr, skip, apply_congr, simp [filter_ne'], }, rw [sum_singleton, neg_smul, add_comm, ←sub_eq_add_neg, sum_smul, ←sum_sub_distrib], simp only [←smul_sub], -- At the end we have to reindex the sum, so we use `change` to -- express the summand using `shift`. change (∑ (x : V) in t.erase x₀, (λ e, g e • e) (shift x)) = 0, rw ←sum_map _ shift, exact gsum, }, { show ∑ (e : V) in t, f e = 0, -- Again we split off the `x₀` term, -- observing that it exactly cancels the other terms. rw [← insert_erase m, sum_insert (not_mem_erase x₀ t)], dsimp [f], rw [if_pos rfl], conv_lhs { congr, skip, apply_congr, skip, rw if_neg (show x ≠ x₀, from (mem_erase.mp H).1), }, exact neg_add_self _, }, { show ∃ (x : V) (H : x ∈ t), f x ≠ 0, -- We can use x₁ + x₀. refine ⟨x₁ + x₀, _, _⟩, { rw finset.mem_map at x₁_mem, rcases x₁_mem with ⟨x₁, x₁_mem, rfl⟩, rw mem_erase at x₁_mem, simp only [x₁_mem, sub_add_cancel, function.embedding.coe_fn_mk], }, { dsimp only [f], rwa [if_neg, add_sub_cancel], rw [add_left_eq_self], rintro rfl, simpa only [sub_eq_zero, exists_prop, finset.mem_map, embedding.coe_fn_mk, eq_self_iff_true, mem_erase, not_true, exists_eq_right, ne.def, false_and] using x₁_mem, } }, end section variables {L : Type*} [linear_ordered_field L] variables {W : Type v} [add_comm_group W] [module L W] /-- A slight strengthening of `exists_nontrivial_relation_sum_zero_of_dim_succ_lt_card` available when working over an ordered field: we can ensure a positive coefficient, not just a nonzero coefficient. -/ lemma exists_relation_sum_zero_pos_coefficient_of_dim_succ_lt_card [finite_dimensional L W] {t : finset W} (h : finrank L W + 1 < t.card) : ∃ f : W → L, ∑ e in t, f e • e = 0 ∧ ∑ e in t, f e = 0 ∧ ∃ x ∈ t, 0 < f x := begin obtain ⟨f, sum, total, nonzero⟩ := exists_nontrivial_relation_sum_zero_of_dim_succ_lt_card h, exact ⟨f, sum, total, exists_pos_of_sum_zero_of_exists_nonzero f total nonzero⟩, end end end /-- In a vector space with dimension 1, each set {v} is a basis for `v ≠ 0`. -/ @[simps] noncomputable def basis_singleton (ι : Type*) [unique ι] (h : finrank K V = 1) (v : V) (hv : v ≠ 0) : basis ι K V := let b := basis_unique ι h in let h : b.repr v default ≠ 0 := mt basis_unique.repr_eq_zero_iff.mp hv in basis.of_repr { to_fun := λ w, finsupp.single default (b.repr w default / b.repr v default), inv_fun := λ f, f default • v, map_add' := by simp [add_div], map_smul' := by simp [mul_div], left_inv := λ w, begin apply_fun b.repr using b.repr.to_equiv.injective, apply_fun equiv.finsupp_unique, simp only [linear_equiv.map_smulₛₗ, finsupp.coe_smul, finsupp.single_eq_same, ring_hom.id_apply, smul_eq_mul, pi.smul_apply, equiv.finsupp_unique_apply], exact div_mul_cancel _ h, end , right_inv := λ f, begin ext, simp only [linear_equiv.map_smulₛₗ, finsupp.coe_smul, finsupp.single_eq_same, ring_hom.id_apply, smul_eq_mul, pi.smul_apply], exact mul_div_cancel _ h, end, } @[simp] lemma basis_singleton_apply (ι : Type*) [unique ι] (h : finrank K V = 1) (v : V) (hv : v ≠ 0) (i : ι) : basis_singleton ι h v hv i = v := by { cases unique.uniq ‹unique ι› i, simp [basis_singleton], } @[simp] lemma range_basis_singleton (ι : Type*) [unique ι] (h : finrank K V = 1) (v : V) (hv : v ≠ 0) : set.range (basis_singleton ι h v hv) = {v} := by rw [set.range_unique, basis_singleton_apply] end division_ring end finite_dimensional variables {K V} section zero_dim variables [division_ring K] [add_comm_group V] [module K V] open finite_dimensional lemma finite_dimensional_of_dim_eq_zero (h : module.rank K V = 0) : finite_dimensional K V := begin dsimp [finite_dimensional], rw [← is_noetherian.iff_fg, is_noetherian.iff_dim_lt_aleph_0, h], exact cardinal.aleph_0_pos end lemma finite_dimensional_of_dim_eq_one (h : module.rank K V = 1) : finite_dimensional K V := begin dsimp [finite_dimensional], rw [← is_noetherian.iff_fg, is_noetherian.iff_dim_lt_aleph_0, h], exact one_lt_aleph_0 end lemma finrank_eq_zero_of_dim_eq_zero [finite_dimensional K V] (h : module.rank K V = 0) : finrank K V = 0 := begin convert finrank_eq_dim K V, rw h, norm_cast end lemma finrank_eq_zero_of_basis_imp_not_finite (h : ∀ s : set V, basis.{v} (s : set V) K V → ¬ s.finite) : finrank K V = 0 := dif_neg (λ dim_lt, h _ (basis.of_vector_space K V) ((basis.of_vector_space K V).finite_index_of_dim_lt_aleph_0 dim_lt)) lemma finrank_eq_zero_of_basis_imp_false (h : ∀ s : finset V, basis.{v} (s : set V) K V → false) : finrank K V = 0 := finrank_eq_zero_of_basis_imp_not_finite (λ s b hs, h hs.to_finset (by { convert b, simp })) lemma finrank_eq_zero_of_not_exists_basis (h : ¬ (∃ s : finset V, nonempty (basis (s : set V) K V))) : finrank K V = 0 := finrank_eq_zero_of_basis_imp_false (λ s b, h ⟨s, ⟨b⟩⟩) lemma finrank_eq_zero_of_not_exists_basis_finite (h : ¬ ∃ (s : set V) (b : basis.{v} (s : set V) K V), s.finite) : finrank K V = 0 := finrank_eq_zero_of_basis_imp_not_finite (λ s b hs, h ⟨s, b, hs⟩) lemma finrank_eq_zero_of_not_exists_basis_finset (h : ¬ ∃ (s : finset V), nonempty (basis s K V)) : finrank K V = 0 := finrank_eq_zero_of_basis_imp_false (λ s b, h ⟨s, ⟨b⟩⟩) variables (K V) instance finite_dimensional_bot : finite_dimensional K (⊥ : submodule K V) := finite_dimensional_of_dim_eq_zero $ by simp @[simp] lemma finrank_bot : finrank K (⊥ : submodule K V) = 0 := begin convert finrank_eq_dim K (⊥ : submodule K V), rw dim_bot, norm_cast end variables {K V} lemma bot_eq_top_of_dim_eq_zero (h : module.rank K V = 0) : (⊥ : submodule K V) = ⊤ := begin haveI := finite_dimensional_of_dim_eq_zero h, apply eq_top_of_finrank_eq, rw [finrank_bot, finrank_eq_zero_of_dim_eq_zero h] end @[simp] theorem dim_eq_zero {S : submodule K V} : module.rank K S = 0 ↔ S = ⊥ := ⟨λ h, (submodule.eq_bot_iff _).2 $ λ x hx, congr_arg subtype.val $ ((submodule.eq_bot_iff _).1 $ eq.symm $ bot_eq_top_of_dim_eq_zero h) ⟨x, hx⟩ submodule.mem_top, λ h, by rw [h, dim_bot]⟩ @[simp] theorem finrank_eq_zero {S : submodule K V} [finite_dimensional K S] : finrank K S = 0 ↔ S = ⊥ := by rw [← dim_eq_zero, ← finrank_eq_dim, ← @nat.cast_zero cardinal, cardinal.nat_cast_inj] end zero_dim namespace submodule open is_noetherian finite_dimensional section division_ring variables [division_ring K] [add_comm_group V] [module K V] /-- A submodule is finitely generated if and only if it is finite-dimensional -/ theorem fg_iff_finite_dimensional (s : submodule K V) : s.fg ↔ finite_dimensional K s := ⟨λ h, module.finite_def.2 $ (fg_top s).2 h, λ h, (fg_top s).1 $ module.finite_def.1 h⟩ /-- A submodule contained in a finite-dimensional submodule is finite-dimensional. -/ lemma finite_dimensional_of_le {S₁ S₂ : submodule K V} [finite_dimensional K S₂] (h : S₁ ≤ S₂) : finite_dimensional K S₁ := begin haveI : is_noetherian K S₂ := iff_fg.2 infer_instance, exact iff_fg.1 (is_noetherian.iff_dim_lt_aleph_0.2 (lt_of_le_of_lt (dim_le_of_submodule _ _ h) (dim_lt_aleph_0 K S₂))), end /-- The inf of two submodules, the first finite-dimensional, is finite-dimensional. -/ instance finite_dimensional_inf_left (S₁ S₂ : submodule K V) [finite_dimensional K S₁] : finite_dimensional K (S₁ ⊓ S₂ : submodule K V) := finite_dimensional_of_le inf_le_left /-- The inf of two submodules, the second finite-dimensional, is finite-dimensional. -/ instance finite_dimensional_inf_right (S₁ S₂ : submodule K V) [finite_dimensional K S₂] : finite_dimensional K (S₁ ⊓ S₂ : submodule K V) := finite_dimensional_of_le inf_le_right /-- The sup of two finite-dimensional submodules is finite-dimensional. -/ instance finite_dimensional_sup (S₁ S₂ : submodule K V) [h₁ : finite_dimensional K S₁] [h₂ : finite_dimensional K S₂] : finite_dimensional K (S₁ ⊔ S₂ : submodule K V) := begin unfold finite_dimensional at *, rw [finite_def] at *, exact (fg_top _).2 (((fg_top S₁).1 h₁).sup ((fg_top S₂).1 h₂)), end /-- The submodule generated by a finite supremum of finite dimensional submodules is finite-dimensional. Note that strictly this only needs `∀ i ∈ s, finite_dimensional K (S i)`, but that doesn't work well with typeclass search. -/ instance finite_dimensional_finset_sup {ι : Type*} (s : finset ι) (S : ι → submodule K V) [Π i, finite_dimensional K (S i)] : finite_dimensional K (s.sup S : submodule K V) := begin refine @finset.sup_induction _ _ _ _ s S (λ i, finite_dimensional K ↥i) (finite_dimensional_bot K V) _ (λ i hi, by apply_instance), { introsI S₁ hS₁ S₂ hS₂, exact submodule.finite_dimensional_sup S₁ S₂ }, end /-- The submodule generated by a supremum of finite dimensional submodules, indexed by a finite type is finite-dimensional. -/ instance finite_dimensional_supr {ι : Type*} [fintype ι] (S : ι → submodule K V) [Π i, finite_dimensional K (S i)] : finite_dimensional K ↥(⨆ i, S i) := begin rw ←finset.sup_univ_eq_supr, exact submodule.finite_dimensional_finset_sup _ _, end /-- The submodule generated by a supremum indexed by a proposition is finite-dimensional if the submodule is. -/ instance finite_dimensional_supr_prop {P : Prop} (S : P → submodule K V) [Π h, finite_dimensional K (S h)] : finite_dimensional K ↥(⨆ h, S h) := begin by_cases hp : P, { rw supr_pos hp, apply_instance }, { rw supr_neg hp, apply_instance }, end /-- The dimension of a submodule is bounded by the dimension of the ambient space. -/ lemma finrank_le [finite_dimensional K V] (s : submodule K V) : finrank K s ≤ finrank K V := by simpa only [cardinal.nat_cast_le, ←finrank_eq_dim] using s.subtype.dim_le_of_injective (injective_subtype s) /-- The dimension of a quotient is bounded by the dimension of the ambient space. -/ lemma finrank_quotient_le [finite_dimensional K V] (s : submodule K V) : finrank K (V ⧸ s) ≤ finrank K V := by simpa only [cardinal.nat_cast_le, ←finrank_eq_dim] using (mkq s).dim_le_of_surjective (surjective_quot_mk _) end division_ring section field variables [field K] [add_comm_group V] [module K V] /-- In a finite-dimensional vector space, the dimensions of a submodule and of the corresponding quotient add up to the dimension of the space. -/ theorem finrank_quotient_add_finrank [finite_dimensional K V] (s : submodule K V) : finrank K (V ⧸ s) + finrank K s = finrank K V := begin have := dim_quotient_add_dim s, rw [← finrank_eq_dim, ← finrank_eq_dim, ← finrank_eq_dim] at this, exact_mod_cast this end /-- The dimension of a strict submodule is strictly bounded by the dimension of the ambient space. -/ lemma finrank_lt [finite_dimensional K V] {s : submodule K V} (h : s < ⊤) : finrank K s < finrank K V := begin rw [← s.finrank_quotient_add_finrank, add_comm], exact nat.lt_add_of_zero_lt_left _ _ (finrank_pos_iff.mpr (quotient.nontrivial_of_lt_top _ h)) end /-- The sum of the dimensions of s + t and s ∩ t is the sum of the dimensions of s and t -/ theorem dim_sup_add_dim_inf_eq (s t : submodule K V) [finite_dimensional K s] [finite_dimensional K t] : finrank K ↥(s ⊔ t) + finrank K ↥(s ⊓ t) = finrank K ↥s + finrank K ↥t := begin have key : module.rank K ↥(s ⊔ t) + module.rank K ↥(s ⊓ t) = module.rank K s + module.rank K t := dim_sup_add_dim_inf_eq s t, repeat { rw ←finrank_eq_dim at key }, norm_cast at key, exact key end lemma eq_top_of_disjoint [finite_dimensional K V] (s t : submodule K V) (hdim : finrank K s + finrank K t = finrank K V) (hdisjoint : disjoint s t) : s ⊔ t = ⊤ := begin have h_finrank_inf : finrank K ↥(s ⊓ t) = 0, { rw [disjoint, le_bot_iff] at hdisjoint, rw [hdisjoint, finrank_bot] }, apply eq_top_of_finrank_eq, rw ←hdim, convert s.dim_sup_add_dim_inf_eq t, rw h_finrank_inf, refl, end end field end submodule namespace linear_equiv open finite_dimensional variables [division_ring K] [add_comm_group V] [module K V] {V₂ : Type v'} [add_comm_group V₂] [module K V₂] /-- Finite dimensionality is preserved under linear equivalence. -/ protected theorem finite_dimensional (f : V ≃ₗ[K] V₂) [finite_dimensional K V] : finite_dimensional K V₂ := module.finite.equiv f variables {R M M₂ : Type*} [ring R] [add_comm_group M] [add_comm_group M₂] variables [module R M] [module R M₂] /-- The dimension of a finite dimensional space is preserved under linear equivalence. -/ theorem finrank_eq (f : M ≃ₗ[R] M₂) : finrank R M = finrank R M₂ := by { unfold finrank, rw [← cardinal.to_nat_lift, f.lift_dim_eq, cardinal.to_nat_lift] } /-- Pushforwards of finite-dimensional submodules along a `linear_equiv` have the same finrank. -/ lemma finrank_map_eq (f : M ≃ₗ[R] M₂) (p : submodule R M) : finrank R (p.map (f : M →ₗ[R] M₂)) = finrank R p := (f.submodule_map p).finrank_eq.symm end linear_equiv section variables [division_ring K] [add_comm_group V] [module K V] instance finite_dimensional_finsupp {ι : Type*} [fintype ι] [h : finite_dimensional K V] : finite_dimensional K (ι →₀ V) := begin letI : is_noetherian K V := is_noetherian.iff_fg.2 infer_instance, exact (finsupp.linear_equiv_fun_on_fintype K V ι).symm.finite_dimensional end end namespace finite_dimensional section division_ring variables [division_ring K] [add_comm_group V] [module K V] {V₂ : Type v'} [add_comm_group V₂] [module K V₂] /-- Two finite-dimensional vector spaces are isomorphic if they have the same (finite) dimension. -/ theorem nonempty_linear_equiv_of_finrank_eq [finite_dimensional K V] [finite_dimensional K V₂] (cond : finrank K V = finrank K V₂) : nonempty (V ≃ₗ[K] V₂) := nonempty_linear_equiv_of_lift_dim_eq $ by simp only [← finrank_eq_dim, cond, lift_nat_cast] /-- Two finite-dimensional vector spaces are isomorphic if and only if they have the same (finite) dimension. -/ theorem nonempty_linear_equiv_iff_finrank_eq [finite_dimensional K V] [finite_dimensional K V₂] : nonempty (V ≃ₗ[K] V₂) ↔ finrank K V = finrank K V₂ := ⟨λ ⟨h⟩, h.finrank_eq, λ h, nonempty_linear_equiv_of_finrank_eq h⟩ variables (V V₂) /-- Two finite-dimensional vector spaces are isomorphic if they have the same (finite) dimension. -/ noncomputable def linear_equiv.of_finrank_eq [finite_dimensional K V] [finite_dimensional K V₂] (cond : finrank K V = finrank K V₂) : V ≃ₗ[K] V₂ := classical.choice $ nonempty_linear_equiv_of_finrank_eq cond variables {V} lemma eq_of_le_of_finrank_le {S₁ S₂ : submodule K V} [finite_dimensional K S₂] (hle : S₁ ≤ S₂) (hd : finrank K S₂ ≤ finrank K S₁) : S₁ = S₂ := begin rw ←linear_equiv.finrank_eq (submodule.comap_subtype_equiv_of_le hle) at hd, exact le_antisymm hle (submodule.comap_subtype_eq_top.1 (eq_top_of_finrank_eq (le_antisymm (comap (submodule.subtype S₂) S₁).finrank_le hd))), end /-- If a submodule is less than or equal to a finite-dimensional submodule with the same dimension, they are equal. -/ lemma eq_of_le_of_finrank_eq {S₁ S₂ : submodule K V} [finite_dimensional K S₂] (hle : S₁ ≤ S₂) (hd : finrank K S₁ = finrank K S₂) : S₁ = S₂ := eq_of_le_of_finrank_le hle hd.ge @[simp] lemma finrank_map_subtype_eq (p : submodule K V) (q : submodule K p) : finite_dimensional.finrank K (q.map p.subtype) = finite_dimensional.finrank K q := (submodule.equiv_subtype_map p q).symm.finrank_eq end division_ring section field variables [field K] [add_comm_group V] [module K V] {V₂ : Type v'} [add_comm_group V₂] [module K V₂] variables [finite_dimensional K V] [finite_dimensional K V₂] /-- Given isomorphic subspaces `p q` of vector spaces `V` and `V₁` respectively, `p.quotient` is isomorphic to `q.quotient`. -/ noncomputable def linear_equiv.quot_equiv_of_equiv {p : subspace K V} {q : subspace K V₂} (f₁ : p ≃ₗ[K] q) (f₂ : V ≃ₗ[K] V₂) : (V ⧸ p) ≃ₗ[K] (V₂ ⧸ q) := linear_equiv.of_finrank_eq _ _ begin rw [← @add_right_cancel_iff _ _ (finrank K p), submodule.finrank_quotient_add_finrank, linear_equiv.finrank_eq f₁, submodule.finrank_quotient_add_finrank, linear_equiv.finrank_eq f₂], end /-- Given the subspaces `p q`, if `p.quotient ≃ₗ[K] q`, then `q.quotient ≃ₗ[K] p` -/ noncomputable def linear_equiv.quot_equiv_of_quot_equiv {p q : subspace K V} (f : (V ⧸ p) ≃ₗ[K] q) : (V ⧸ q) ≃ₗ[K] p := linear_equiv.of_finrank_eq _ _ begin rw [← @add_right_cancel_iff _ _ (finrank K q), submodule.finrank_quotient_add_finrank, ← linear_equiv.finrank_eq f, add_comm, submodule.finrank_quotient_add_finrank] end end field end finite_dimensional namespace linear_map open finite_dimensional section division_ring variables [division_ring K] [add_comm_group V] [module K V] {V₂ : Type v'} [add_comm_group V₂] [module K V₂] /-- On a finite-dimensional space, an injective linear map is surjective. -/ lemma surjective_of_injective [finite_dimensional K V] {f : V →ₗ[K] V} (hinj : injective f) : surjective f := begin have h := dim_eq_of_injective _ hinj, rw [← finrank_eq_dim, ← finrank_eq_dim, nat_cast_inj] at h, exact range_eq_top.1 (eq_top_of_finrank_eq h.symm) end /-- The image under an onto linear map of a finite-dimensional space is also finite-dimensional. -/ lemma finite_dimensional_of_surjective [h : finite_dimensional K V] (f : V →ₗ[K] V₂) (hf : f.range = ⊤) : finite_dimensional K V₂ := module.finite.of_surjective f $ range_eq_top.1 hf /-- The range of a linear map defined on a finite-dimensional space is also finite-dimensional. -/ instance finite_dimensional_range [h : finite_dimensional K V] (f : V →ₗ[K] V₂) : finite_dimensional K f.range := f.quot_ker_equiv_range.finite_dimensional /-- The dimensions of the domain and range of an injective linear map are equal. -/ lemma finrank_range_of_inj {f : V →ₗ[K] V₂} (hf : function.injective f) : finrank K f.range = finrank K V := by rw (linear_equiv.of_injective f hf).finrank_eq end division_ring section field variables [field K] [add_comm_group V] [module K V] {V₂ : Type v'} [add_comm_group V₂] [module K V₂] /-- On a finite-dimensional space, a linear map is injective if and only if it is surjective. -/ lemma injective_iff_surjective [finite_dimensional K V] {f : V →ₗ[K] V} : injective f ↔ surjective f := ⟨surjective_of_injective, λ hsurj, let ⟨g, hg⟩ := f.exists_right_inverse_of_surjective (range_eq_top.2 hsurj) in have function.right_inverse g f, from linear_map.ext_iff.1 hg, (left_inverse_of_surjective_of_right_inverse (surjective_of_injective this.injective) this).injective⟩ lemma ker_eq_bot_iff_range_eq_top [finite_dimensional K V] {f : V →ₗ[K] V} : f.ker = ⊥ ↔ f.range = ⊤ := by rw [range_eq_top, ker_eq_bot, injective_iff_surjective] /-- In a finite-dimensional space, if linear maps are inverse to each other on one side then they are also inverse to each other on the other side. -/ lemma mul_eq_one_of_mul_eq_one [finite_dimensional K V] {f g : V →ₗ[K] V} (hfg : f * g = 1) : g * f = 1 := have ginj : injective g, from has_left_inverse.injective ⟨f, (λ x, show (f * g) x = (1 : V →ₗ[K] V) x, by rw hfg; refl)⟩, let ⟨i, hi⟩ := g.exists_right_inverse_of_surjective (range_eq_top.2 (injective_iff_surjective.1 ginj)) in have f * (g * i) = f * 1, from congr_arg _ hi, by rw [← mul_assoc, hfg, one_mul, mul_one] at this; rwa ← this /-- In a finite-dimensional space, linear maps are inverse to each other on one side if and only if they are inverse to each other on the other side. -/ lemma mul_eq_one_comm [finite_dimensional K V] {f g : V →ₗ[K] V} : f * g = 1 ↔ g * f = 1 := ⟨mul_eq_one_of_mul_eq_one, mul_eq_one_of_mul_eq_one⟩ /-- In a finite-dimensional space, linear maps are inverse to each other on one side if and only if they are inverse to each other on the other side. -/ lemma comp_eq_id_comm [finite_dimensional K V] {f g : V →ₗ[K] V} : f.comp g = id ↔ g.comp f = id := mul_eq_one_comm /-- rank-nullity theorem : the dimensions of the kernel and the range of a linear map add up to the dimension of the source space. -/ theorem finrank_range_add_finrank_ker [finite_dimensional K V] (f : V →ₗ[K] V₂) : finrank K f.range + finrank K f.ker = finrank K V := by { rw [← f.quot_ker_equiv_range.finrank_eq], exact submodule.finrank_quotient_add_finrank _ } end field end linear_map namespace linear_equiv open finite_dimensional variables [field K] [add_comm_group V] [module K V] variables [finite_dimensional K V] /-- The linear equivalence corresponging to an injective endomorphism. -/ noncomputable def of_injective_endo (f : V →ₗ[K] V) (h_inj : injective f) : V ≃ₗ[K] V := linear_equiv.of_bijective f h_inj $ linear_map.injective_iff_surjective.mp h_inj @[simp] lemma coe_of_injective_endo (f : V →ₗ[K] V) (h_inj : injective f) : ⇑(of_injective_endo f h_inj) = f := rfl @[simp] lemma of_injective_endo_right_inv (f : V →ₗ[K] V) (h_inj : injective f) : f * (of_injective_endo f h_inj).symm = 1 := linear_map.ext $ (of_injective_endo f h_inj).apply_symm_apply @[simp] lemma of_injective_endo_left_inv (f : V →ₗ[K] V) (h_inj : injective f) : ((of_injective_endo f h_inj).symm : V →ₗ[K] V) * f = 1 := linear_map.ext $ (of_injective_endo f h_inj).symm_apply_apply end linear_equiv namespace linear_map variables [field K] [add_comm_group V] [module K V] lemma is_unit_iff_ker_eq_bot [finite_dimensional K V] (f : V →ₗ[K] V): is_unit f ↔ f.ker = ⊥ := begin split, { rintro ⟨u, rfl⟩, exact linear_map.ker_eq_bot_of_inverse u.inv_mul }, { intro h_inj, rw ker_eq_bot at h_inj, exact ⟨⟨f, (linear_equiv.of_injective_endo f h_inj).symm.to_linear_map, linear_equiv.of_injective_endo_right_inv f h_inj, linear_equiv.of_injective_endo_left_inv f h_inj⟩, rfl⟩ } end lemma is_unit_iff_range_eq_top [finite_dimensional K V] (f : V →ₗ[K] V): is_unit f ↔ f.range = ⊤ := by rw [is_unit_iff_ker_eq_bot, ker_eq_bot_iff_range_eq_top] end linear_map open module finite_dimensional section variables [division_ring K] [add_comm_group V] [module K V] section top @[simp] theorem finrank_top : finrank K (⊤ : submodule K V) = finrank K V := by { unfold finrank, simp [dim_top] } end top lemma finrank_zero_iff_forall_zero [finite_dimensional K V] : finrank K V = 0 ↔ ∀ x : V, x = 0 := finrank_zero_iff.trans (subsingleton_iff_forall_eq 0) /-- If `ι` is an empty type and `V` is zero-dimensional, there is a unique `ι`-indexed basis. -/ noncomputable def basis_of_finrank_zero [finite_dimensional K V] {ι : Type*} [is_empty ι] (hV : finrank K V = 0) : basis ι K V := begin haveI : subsingleton V := finrank_zero_iff.1 hV, exact basis.empty _ end end namespace linear_map variables [field K] [add_comm_group V] [module K V] {V₂ : Type v'} [add_comm_group V₂] [module K V₂] theorem injective_iff_surjective_of_finrank_eq_finrank [finite_dimensional K V] [finite_dimensional K V₂] (H : finrank K V = finrank K V₂) {f : V →ₗ[K] V₂} : function.injective f ↔ function.surjective f := begin have := finrank_range_add_finrank_ker f, rw [← ker_eq_bot, ← range_eq_top], refine ⟨λ h, _, λ h, _⟩, { rw [h, finrank_bot, add_zero, H] at this, exact eq_top_of_finrank_eq this }, { rw [h, finrank_top, H] at this, exact finrank_eq_zero.1 (add_right_injective _ this) } end lemma ker_eq_bot_iff_range_eq_top_of_finrank_eq_finrank [finite_dimensional K V] [finite_dimensional K V₂] (H : finrank K V = finrank K V₂) {f : V →ₗ[K] V₂} : f.ker = ⊥ ↔ f.range = ⊤ := by rw [range_eq_top, ker_eq_bot, injective_iff_surjective_of_finrank_eq_finrank H] theorem finrank_le_finrank_of_injective [finite_dimensional K V] [finite_dimensional K V₂] {f : V →ₗ[K] V₂} (hf : function.injective f) : finrank K V ≤ finrank K V₂ := calc finrank K V = finrank K f.range + finrank K f.ker : (finrank_range_add_finrank_ker f).symm ... = finrank K f.range : by rw [ker_eq_bot.2 hf, finrank_bot, add_zero] ... ≤ finrank K V₂ : submodule.finrank_le _ /-- Given a linear map `f` between two vector spaces with the same dimension, if `ker f = ⊥` then `linear_equiv_of_injective` is the induced isomorphism between the two vector spaces. -/ noncomputable def linear_equiv_of_injective [finite_dimensional K V] [finite_dimensional K V₂] (f : V →ₗ[K] V₂) (hf : injective f) (hdim : finrank K V = finrank K V₂) : V ≃ₗ[K] V₂ := linear_equiv.of_bijective f hf $ (linear_map.injective_iff_surjective_of_finrank_eq_finrank hdim).mp hf @[simp] lemma linear_equiv_of_injective_apply [finite_dimensional K V] [finite_dimensional K V₂] {f : V →ₗ[K] V₂} (hf : injective f) (hdim : finrank K V = finrank K V₂) (x : V) : f.linear_equiv_of_injective hf hdim x = f x := rfl end linear_map namespace alg_hom lemma bijective {F : Type*} [field F] {E : Type*} [field E] [algebra F E] [finite_dimensional F E] (ϕ : E →ₐ[F] E) : function.bijective ϕ := have inj : function.injective ϕ.to_linear_map := ϕ.to_ring_hom.injective, ⟨inj, (linear_map.injective_iff_surjective_of_finrank_eq_finrank rfl).mp inj⟩ end alg_hom /-- Bijection between algebra equivalences and algebra homomorphisms -/ noncomputable def alg_equiv_equiv_alg_hom (F : Type u) [field F] (E : Type v) [field E] [algebra F E] [finite_dimensional F E] : (E ≃ₐ[F] E) ≃ (E →ₐ[F] E) := { to_fun := λ ϕ, ϕ.to_alg_hom, inv_fun := λ ϕ, alg_equiv.of_bijective ϕ ϕ.bijective, left_inv := λ _, by {ext, refl}, right_inv := λ _, by {ext, refl} } section /-- A domain that is module-finite as an algebra over a field is a division ring. -/ noncomputable def division_ring_of_finite_dimensional (F K : Type*) [field F] [ring K] [is_domain K] [algebra F K] [finite_dimensional F K] : division_ring K := { inv := λ x, if H : x = 0 then 0 else classical.some $ (show function.surjective (algebra.lmul_left F x), from linear_map.injective_iff_surjective.1 $ λ _ _, (mul_right_inj' H).1) 1, mul_inv_cancel := λ x hx, show x * dite _ _ _ = _, by { rw dif_neg hx, exact classical.some_spec ((show function.surjective (algebra.lmul_left F x), from linear_map.injective_iff_surjective.1 $ λ _ _, (mul_right_inj' hx).1) 1) }, inv_zero := dif_pos rfl, .. ‹is_domain K›, .. ‹ring K› } /-- An integral domain that is module-finite as an algebra over a field is a field. -/ noncomputable def field_of_finite_dimensional (F K : Type*) [field F] [comm_ring K] [is_domain K] [algebra F K] [finite_dimensional F K] : field K := { .. division_ring_of_finite_dimensional F K, .. ‹comm_ring K› } end namespace submodule section division_ring variables [division_ring K] [add_comm_group V] [module K V] {V₂ : Type v'} [add_comm_group V₂] [module K V₂] lemma lt_of_le_of_finrank_lt_finrank {s t : submodule K V} (le : s ≤ t) (lt : finrank K s < finrank K t) : s < t := lt_of_le_of_ne le (λ h, ne_of_lt lt (by rw h)) lemma lt_top_of_finrank_lt_finrank {s : submodule K V} (lt : finrank K s < finrank K V) : s < ⊤ := begin rw ← @finrank_top K V at lt, exact lt_of_le_of_finrank_lt_finrank le_top lt end lemma finrank_mono [finite_dimensional K V] : monotone (λ (s : submodule K V), finrank K s) := λ s t hst, calc finrank K s = finrank K (comap t.subtype s) : linear_equiv.finrank_eq (comap_subtype_equiv_of_le hst).symm ... ≤ finrank K t : submodule.finrank_le _ end division_ring section field variables [field K] [add_comm_group V] [module K V] {V₂ : Type v'} [add_comm_group V₂] [module K V₂] lemma finrank_lt_finrank_of_lt [finite_dimensional K V] {s t : submodule K V} (hst : s < t) : finrank K s < finrank K t := begin rw linear_equiv.finrank_eq (comap_subtype_equiv_of_le (le_of_lt hst)).symm, refine finrank_lt (lt_of_le_of_ne le_top _), intro h_eq_top, rw comap_subtype_eq_top at h_eq_top, apply not_le_of_lt hst h_eq_top, end lemma finrank_add_eq_of_is_compl [finite_dimensional K V] {U W : submodule K V} (h : is_compl U W) : finrank K U + finrank K W = finrank K V := begin rw [← submodule.dim_sup_add_dim_inf_eq, top_le_iff.1 h.2, le_bot_iff.1 h.1, finrank_bot, add_zero], exact finrank_top end end field end submodule section span open submodule section division_ring variables [division_ring K] [add_comm_group V] [module K V] variable (K) /-- The rank of a set of vectors as a natural number. -/ protected noncomputable def set.finrank (s : set V) : ℕ := finrank K (span K s) variable {K} lemma finrank_span_le_card (s : set V) [fintype s] : finrank K (span K s) ≤ s.to_finset.card := begin haveI := span_of_finite K s.to_finite, have : module.rank K (span K s) ≤ #s := dim_span_le s, rw [←finrank_eq_dim, cardinal.mk_fintype, ←set.to_finset_card] at this, exact_mod_cast this, end lemma finrank_span_finset_le_card (s : finset V) : (s : set V).finrank K ≤ s.card := calc (s : set V).finrank K ≤ (s : set V).to_finset.card : finrank_span_le_card s ... = s.card : by simp lemma finrank_span_eq_card {ι : Type*} [fintype ι] {b : ι → V} (hb : linear_independent K b) : finrank K (span K (set.range b)) = fintype.card ι := begin haveI : finite_dimensional K (span K (set.range b)) := span_of_finite K (set.finite_range b), have : module.rank K (span K (set.range b)) = #(set.range b) := dim_span hb, rwa [←finrank_eq_dim, ←lift_inj, mk_range_eq_of_injective hb.injective, cardinal.mk_fintype, lift_nat_cast, lift_nat_cast, nat_cast_inj] at this, end lemma finrank_span_set_eq_card (s : set V) [fintype s] (hs : linear_independent K (coe : s → V)) : finrank K (span K s) = s.to_finset.card := begin haveI := span_of_finite K s.to_finite, have : module.rank K (span K s) = #s := dim_span_set hs, rw [←finrank_eq_dim, cardinal.mk_fintype, ←set.to_finset_card] at this, exact_mod_cast this, end lemma finrank_span_finset_eq_card (s : finset V) (hs : linear_independent K (coe : s → V)) : finrank K (span K (s : set V)) = s.card := begin convert finrank_span_set_eq_card ↑s hs, ext, simp, end lemma span_lt_of_subset_of_card_lt_finrank {s : set V} [fintype s] {t : submodule K V} (subset : s ⊆ t) (card_lt : s.to_finset.card < finrank K t) : span K s < t := lt_of_le_of_finrank_lt_finrank (span_le.mpr subset) (lt_of_le_of_lt (finrank_span_le_card _) card_lt) lemma span_lt_top_of_card_lt_finrank {s : set V} [fintype s] (card_lt : s.to_finset.card < finrank K V) : span K s < ⊤ := lt_top_of_finrank_lt_finrank (lt_of_le_of_lt (finrank_span_le_card _) card_lt) lemma finrank_span_singleton {v : V} (hv : v ≠ 0) : finrank K (K ∙ v) = 1 := begin apply le_antisymm, { exact finrank_span_le_card ({v} : set V) }, { rw [nat.succ_le_iff, finrank_pos_iff], use [⟨v, mem_span_singleton_self v⟩, 0], simp [hv] } end end division_ring section field variables [field K] [add_comm_group V] [module K V] lemma set.finrank_mono [finite_dimensional K V] {s t : set V} (h : s ⊆ t) : s.finrank K ≤ t.finrank K := finrank_mono (span_mono h) end field end span section basis section division_ring variables [division_ring K] [add_comm_group V] [module K V] lemma linear_independent_of_span_eq_top_of_card_eq_finrank {ι : Type*} [fintype ι] {b : ι → V} (span_eq : span K (set.range b) = ⊤) (card_eq : fintype.card ι = finrank K V) : linear_independent K b := linear_independent_iff'.mpr $ λ s g dependent i i_mem_s, begin by_contra gx_ne_zero, -- We'll derive a contradiction by showing `b '' (univ \ {i})` of cardinality `n - 1` -- spans a vector space of dimension `n`. refine ne_of_lt (span_lt_top_of_card_lt_finrank (show (b '' (set.univ \ {i})).to_finset.card < finrank K V, from _)) _, { calc (b '' (set.univ \ {i})).to_finset.card = ((set.univ \ {i}).to_finset.image b).card : by rw [set.to_finset_card, fintype.card_of_finset] ... ≤ (set.univ \ {i}).to_finset.card : finset.card_image_le ... = (finset.univ.erase i).card : congr_arg finset.card (finset.ext (by simp [and_comm])) ... < finset.univ.card : finset.card_erase_lt_of_mem (finset.mem_univ i) ... = finrank K V : card_eq }, -- We already have that `b '' univ` spans the whole space, -- so we only need to show that the span of `b '' (univ \ {i})` contains each `b j`. refine trans (le_antisymm (span_mono (set.image_subset_range _ _)) (span_le.mpr _)) span_eq, rintros _ ⟨j, rfl, rfl⟩, -- The case that `j ≠ i` is easy because `b j ∈ b '' (univ \ {i})`. by_cases j_eq : j = i, swap, { refine subset_span ⟨j, (set.mem_diff _).mpr ⟨set.mem_univ _, _⟩, rfl⟩, exact mt set.mem_singleton_iff.mp j_eq }, -- To show `b i ∈ span (b '' (univ \ {i}))`, we use that it's a weighted sum -- of the other `b j`s. rw [j_eq, set_like.mem_coe, show b i = -((g i)⁻¹ • (s.erase i).sum (λ j, g j • b j)), from _], { refine neg_mem (smul_mem _ _ (sum_mem (λ k hk, _))), obtain ⟨k_ne_i, k_mem⟩ := finset.mem_erase.mp hk, refine smul_mem _ _ (subset_span ⟨k, _, rfl⟩), simpa using k_mem }, -- To show `b i` is a weighted sum of the other `b j`s, we'll rewrite this sum -- to have the form of the assumption `dependent`. apply eq_neg_of_add_eq_zero_left, calc b i + (g i)⁻¹ • (s.erase i).sum (λ j, g j • b j) = (g i)⁻¹ • (g i • b i + (s.erase i).sum (λ j, g j • b j)) : by rw [smul_add, ←mul_smul, inv_mul_cancel gx_ne_zero, one_smul] ... = (g i)⁻¹ • 0 : congr_arg _ _ ... = 0 : smul_zero _, -- And then it's just a bit of manipulation with finite sums. rwa [← finset.insert_erase i_mem_s, finset.sum_insert (finset.not_mem_erase _ _)] at dependent end /-- A finite family of vectors is linearly independent if and only if its cardinality equals the dimension of its span. -/ lemma linear_independent_iff_card_eq_finrank_span {ι : Type*} [fintype ι] {b : ι → V} : linear_independent K b ↔ fintype.card ι = (set.range b).finrank K := begin split, { intro h, exact (finrank_span_eq_card h).symm }, { intro hc, let f := (submodule.subtype (span K (set.range b))), let b' : ι → span K (set.range b) := λ i, ⟨b i, mem_span.2 (λ p hp, hp (set.mem_range_self _))⟩, have hs : span K (set.range b') = ⊤, { rw eq_top_iff', intro x, have h : span K (f '' (set.range b')) = map f (span K (set.range b')) := span_image f, have hf : f '' (set.range b') = set.range b, { ext x, simp [set.mem_image, set.mem_range] }, rw hf at h, have hx : (x : V) ∈ span K (set.range b) := x.property, conv at hx { congr, skip, rw h }, simpa [mem_map] using hx }, have hi : f.ker = ⊥ := ker_subtype _, convert (linear_independent_of_span_eq_top_of_card_eq_finrank hs hc).map' _ hi } end /-- A family of `finrank K V` vectors forms a basis if they span the whole space. -/ noncomputable def basis_of_span_eq_top_of_card_eq_finrank {ι : Type*} [fintype ι] (b : ι → V) (span_eq : span K (set.range b) = ⊤) (card_eq : fintype.card ι = finrank K V) : basis ι K V := basis.mk (linear_independent_of_span_eq_top_of_card_eq_finrank span_eq card_eq) span_eq @[simp] lemma coe_basis_of_span_eq_top_of_card_eq_finrank {ι : Type*} [fintype ι] (b : ι → V) (span_eq : span K (set.range b) = ⊤) (card_eq : fintype.card ι = finrank K V) : ⇑(basis_of_span_eq_top_of_card_eq_finrank b span_eq card_eq) = b := basis.coe_mk _ _ /-- A finset of `finrank K V` vectors forms a basis if they span the whole space. -/ @[simps] noncomputable def finset_basis_of_span_eq_top_of_card_eq_finrank {s : finset V} (span_eq : span K (s : set V) = ⊤) (card_eq : s.card = finrank K V) : basis (s : set V) K V := basis_of_span_eq_top_of_card_eq_finrank (coe : (s : set V) → V) ((@subtype.range_coe_subtype _ (λ x, x ∈ s)).symm ▸ span_eq) (trans (fintype.card_coe _) card_eq) /-- A set of `finrank K V` vectors forms a basis if they span the whole space. -/ @[simps] noncomputable def set_basis_of_span_eq_top_of_card_eq_finrank {s : set V} [fintype s] (span_eq : span K s = ⊤) (card_eq : s.to_finset.card = finrank K V) : basis s K V := basis_of_span_eq_top_of_card_eq_finrank (coe : s → V) ((@subtype.range_coe_subtype _ s).symm ▸ span_eq) (trans s.to_finset_card.symm card_eq) end division_ring section field variables [field K] [add_comm_group V] [module K V] lemma span_eq_top_of_linear_independent_of_card_eq_finrank {ι : Type*} [hι : nonempty ι] [fintype ι] {b : ι → V} (lin_ind : linear_independent K b) (card_eq : fintype.card ι = finrank K V) : span K (set.range b) = ⊤ := begin by_cases fin : (finite_dimensional K V), { haveI := fin, by_contra ne_top, have lt_top : span K (set.range b) < ⊤ := lt_of_le_of_ne le_top ne_top, exact ne_of_lt (submodule.finrank_lt lt_top) (trans (finrank_span_eq_card lin_ind) card_eq) }, { exfalso, apply ne_of_lt (fintype.card_pos_iff.mpr hι), symmetry, replace fin := (not_iff_not.2 is_noetherian.iff_fg).2 fin, calc fintype.card ι = finrank K V : card_eq ... = 0 : dif_neg (mt is_noetherian.iff_dim_lt_aleph_0.mpr fin) } end /-- A linear independent family of `finrank K V` vectors forms a basis. -/ @[simps] noncomputable def basis_of_linear_independent_of_card_eq_finrank {ι : Type*} [nonempty ι] [fintype ι] {b : ι → V} (lin_ind : linear_independent K b) (card_eq : fintype.card ι = finrank K V) : basis ι K V := basis.mk lin_ind $ span_eq_top_of_linear_independent_of_card_eq_finrank lin_ind card_eq @[simp] lemma coe_basis_of_linear_independent_of_card_eq_finrank {ι : Type*} [nonempty ι] [fintype ι] {b : ι → V} (lin_ind : linear_independent K b) (card_eq : fintype.card ι = finrank K V) : ⇑(basis_of_linear_independent_of_card_eq_finrank lin_ind card_eq) = b := basis.coe_mk _ _ /-- A linear independent finset of `finrank K V` vectors forms a basis. -/ @[simps] noncomputable def finset_basis_of_linear_independent_of_card_eq_finrank {s : finset V} (hs : s.nonempty) (lin_ind : linear_independent K (coe : s → V)) (card_eq : s.card = finrank K V) : basis s K V := @basis_of_linear_independent_of_card_eq_finrank _ _ _ _ _ _ ⟨(⟨hs.some, hs.some_spec⟩ : s)⟩ _ _ lin_ind (trans (fintype.card_coe _) card_eq) @[simp] lemma coe_finset_basis_of_linear_independent_of_card_eq_finrank {s : finset V} (hs : s.nonempty) (lin_ind : linear_independent K (coe : s → V)) (card_eq : s.card = finrank K V) : ⇑(finset_basis_of_linear_independent_of_card_eq_finrank hs lin_ind card_eq) = coe := basis.coe_mk _ _ /-- A linear independent set of `finrank K V` vectors forms a basis. -/ @[simps] noncomputable def set_basis_of_linear_independent_of_card_eq_finrank {s : set V} [nonempty s] [fintype s] (lin_ind : linear_independent K (coe : s → V)) (card_eq : s.to_finset.card = finrank K V) : basis s K V := basis_of_linear_independent_of_card_eq_finrank lin_ind (trans s.to_finset_card.symm card_eq) @[simp] lemma coe_set_basis_of_linear_independent_of_card_eq_finrank {s : set V} [nonempty s] [fintype s] (lin_ind : linear_independent K (coe : s → V)) (card_eq : s.to_finset.card = finrank K V) : ⇑(set_basis_of_linear_independent_of_card_eq_finrank lin_ind card_eq) = coe := basis.coe_mk _ _ end field end basis /-! We now give characterisations of `finrank K V = 1` and `finrank K V ≤ 1`. -/ section finrank_eq_one variables [division_ring K] [add_comm_group V] [module K V] /-- If there is a nonzero vector and every other vector is a multiple of it, then the module has dimension one. -/ lemma finrank_eq_one (v : V) (n : v ≠ 0) (h : ∀ w : V, ∃ c : K, c • v = w) : finrank K V = 1 := begin obtain ⟨b⟩ := (basis.basis_singleton_iff punit).mpr ⟨v, n, h⟩, rw [finrank_eq_card_basis b, fintype.card_punit] end /-- If every vector is a multiple of some `v : V`, then `V` has dimension at most one. -/ lemma finrank_le_one (v : V) (h : ∀ w : V, ∃ c : K, c • v = w) : finrank K V ≤ 1 := begin rcases eq_or_ne v 0 with rfl | hn, { haveI := subsingleton_of_forall_eq (0 : V) (λ w, by { obtain ⟨c, rfl⟩ := h w, simp }), rw finrank_zero_of_subsingleton, exact zero_le_one }, { exact (finrank_eq_one v hn h).le } end /-- A vector space with a nonzero vector `v` has dimension 1 iff `v` spans. -/ lemma finrank_eq_one_iff_of_nonzero (v : V) (nz : v ≠ 0) : finrank K V = 1 ↔ span K ({v} : set V) = ⊤ := ⟨λ h, by simpa using (basis_singleton punit h v nz).span_eq, λ s, finrank_eq_card_basis (basis.mk (linear_independent_singleton nz) (by { convert s, simp }))⟩ /-- A module with a nonzero vector `v` has dimension 1 iff every vector is a multiple of `v`. -/ lemma finrank_eq_one_iff_of_nonzero' (v : V) (nz : v ≠ 0) : finrank K V = 1 ↔ ∀ w : V, ∃ c : K, c • v = w := begin rw finrank_eq_one_iff_of_nonzero v nz, apply span_singleton_eq_top_iff, end /-- A module has dimension 1 iff there is some `v : V` so `{v}` is a basis. -/ lemma finrank_eq_one_iff (ι : Type*) [unique ι] : finrank K V = 1 ↔ nonempty (basis ι K V) := begin fsplit, { intro h, haveI := finite_dimensional_of_finrank (_root_.zero_lt_one.trans_le h.symm.le), exact ⟨basis_unique ι h⟩ }, { rintro ⟨b⟩, simpa using finrank_eq_card_basis b } end /-- A module has dimension 1 iff there is some nonzero `v : V` so every vector is a multiple of `v`. -/ lemma finrank_eq_one_iff' : finrank K V = 1 ↔ ∃ (v : V) (n : v ≠ 0), ∀ w : V, ∃ c : K, c • v = w := begin convert finrank_eq_one_iff punit, simp only [exists_prop, eq_iff_iff, ne.def], convert (basis.basis_singleton_iff punit).symm, funext v, simp, apply_instance, apply_instance, -- Not sure why this aren't found automatically. end /-- A finite dimensional module has dimension at most 1 iff there is some `v : V` so every vector is a multiple of `v`. -/ lemma finrank_le_one_iff [finite_dimensional K V] : finrank K V ≤ 1 ↔ ∃ (v : V), ∀ w : V, ∃ c : K, c • v = w := begin fsplit, { intro h, by_cases h' : finrank K V = 0, { use 0, intro w, use 0, haveI := finrank_zero_iff.mp h', apply subsingleton.elim, }, { replace h' := zero_lt_iff.mpr h', have : finrank K V = 1, { linarith }, obtain ⟨v, -, p⟩ := finrank_eq_one_iff'.mp this, use ⟨v, p⟩, }, }, { rintro ⟨v, p⟩, exact finrank_le_one v p, } end -- We use the `linear_map.compatible_smul` typeclass here, to encompass two situations: -- * `A = K` -- * `[field K] [algebra K A] [is_scalar_tower K A V] [is_scalar_tower K A W]` lemma surjective_of_nonzero_of_finrank_eq_one {K : Type*} [division_ring K] {A : Type*} [semiring A] [module K V] [module A V] {W : Type*} [add_comm_group W] [module K W] [module A W] [linear_map.compatible_smul V W K A] (h : finrank K W = 1) {f : V →ₗ[A] W} (w : f ≠ 0) : surjective f := begin change surjective (f.restrict_scalars K), obtain ⟨v, n⟩ := fun_like.ne_iff.mp w, intro z, obtain ⟨c, rfl⟩ := (finrank_eq_one_iff_of_nonzero' (f v) n).mp h z, exact ⟨c • v, by simp⟩, end end finrank_eq_one section subalgebra_dim open module variables {F E : Type*} [field F] [field E] [algebra F E] lemma subalgebra.dim_eq_one_of_eq_bot {S : subalgebra F E} (h : S = ⊥) : module.rank F S = 1 := begin rw [← S.to_submodule_equiv.dim_eq, h, (linear_equiv.of_eq (⊥ : subalgebra F E).to_submodule _ algebra.to_submodule_bot).dim_eq, dim_span_set], exacts [mk_singleton _, linear_independent_singleton one_ne_zero] end @[simp] lemma subalgebra.dim_bot : module.rank F (⊥ : subalgebra F E) = 1 := subalgebra.dim_eq_one_of_eq_bot rfl lemma subalgebra_top_dim_eq_submodule_top_dim : module.rank F (⊤ : subalgebra F E) = module.rank F (⊤ : submodule F E) := by { rw ← algebra.top_to_submodule, refl } lemma subalgebra_top_finrank_eq_submodule_top_finrank : finrank F (⊤ : subalgebra F E) = finrank F (⊤ : submodule F E) := by { rw ← algebra.top_to_submodule, refl } lemma subalgebra.dim_top : module.rank F (⊤ : subalgebra F E) = module.rank F E := by { rw subalgebra_top_dim_eq_submodule_top_dim, exact dim_top F E } instance subalgebra.finite_dimensional_bot : finite_dimensional F (⊥ : subalgebra F E) := finite_dimensional_of_dim_eq_one subalgebra.dim_bot @[simp] lemma subalgebra.finrank_bot : finrank F (⊥ : subalgebra F E) = 1 := begin have : module.rank F (⊥ : subalgebra F E) = 1 := subalgebra.dim_bot, rw ← finrank_eq_dim at this, norm_cast at *, simp *, end lemma subalgebra.finrank_eq_one_of_eq_bot {S : subalgebra F E} (h : S = ⊥) : finrank F S = 1 := by { rw h, exact subalgebra.finrank_bot } lemma subalgebra.eq_bot_of_finrank_one {S : subalgebra F E} (h : finrank F S = 1) : S = ⊥ := begin rw eq_bot_iff, let b : set S := {1}, have : fintype b := unique.fintype, have b_lin_ind : linear_independent F (coe : b → S) := linear_independent_singleton one_ne_zero, have b_card : fintype.card b = 1 := fintype.card_of_subsingleton _, let hb := set_basis_of_linear_independent_of_card_eq_finrank b_lin_ind (by simp only [*, set.to_finset_card]), have b_spans := hb.span_eq, intros x hx, rw [algebra.mem_bot], have x_in_span_b : (⟨x, hx⟩ : S) ∈ submodule.span F b, { rw [coe_set_basis_of_linear_independent_of_card_eq_finrank, subtype.range_coe] at b_spans, rw b_spans, exact submodule.mem_top, }, obtain ⟨a, ha⟩ := submodule.mem_span_singleton.mp x_in_span_b, replace ha : a • 1 = x := by injections with ha, exact ⟨a, by rw [← ha, algebra.smul_def, mul_one]⟩, end lemma subalgebra.eq_bot_of_dim_one {S : subalgebra F E} (h : module.rank F S = 1) : S = ⊥ := begin haveI : finite_dimensional F S := finite_dimensional_of_dim_eq_one h, rw ← finrank_eq_dim at h, norm_cast at h, exact subalgebra.eq_bot_of_finrank_one h, end @[simp] lemma subalgebra.bot_eq_top_of_dim_eq_one (h : module.rank F E = 1) : (⊥ : subalgebra F E) = ⊤ := begin rw [← dim_top, ← subalgebra_top_dim_eq_submodule_top_dim] at h, exact eq.symm (subalgebra.eq_bot_of_dim_one h), end @[simp] lemma subalgebra.bot_eq_top_of_finrank_eq_one (h : finrank F E = 1) : (⊥ : subalgebra F E) = ⊤ := begin rw [← finrank_top, ← subalgebra_top_finrank_eq_submodule_top_finrank] at h, exact eq.symm (subalgebra.eq_bot_of_finrank_one h), end @[simp] theorem subalgebra.dim_eq_one_iff {S : subalgebra F E} : module.rank F S = 1 ↔ S = ⊥ := ⟨subalgebra.eq_bot_of_dim_one, subalgebra.dim_eq_one_of_eq_bot⟩ @[simp] theorem subalgebra.finrank_eq_one_iff {S : subalgebra F E} : finrank F S = 1 ↔ S = ⊥ := ⟨subalgebra.eq_bot_of_finrank_one, subalgebra.finrank_eq_one_of_eq_bot⟩ end subalgebra_dim namespace module namespace End variables [field K] [add_comm_group V] [module K V] lemma exists_ker_pow_eq_ker_pow_succ [finite_dimensional K V] (f : End K V) : ∃ (k : ℕ), k ≤ finrank K V ∧ (f ^ k).ker = (f ^ k.succ).ker := begin classical, by_contradiction h_contra, simp_rw [not_exists, not_and] at h_contra, have h_le_ker_pow : ∀ (n : ℕ), n ≤ (finrank K V).succ → n ≤ finrank K (f ^ n).ker, { intros n hn, induction n with n ih, { exact zero_le (finrank _ _) }, { have h_ker_lt_ker : (f ^ n).ker < (f ^ n.succ).ker, { refine lt_of_le_of_ne _ (h_contra n (nat.le_of_succ_le_succ hn)), rw pow_succ, apply linear_map.ker_le_ker_comp }, have h_finrank_lt_finrank : finrank K (f ^ n).ker < finrank K (f ^ n.succ).ker, { apply submodule.finrank_lt_finrank_of_lt h_ker_lt_ker }, calc n.succ ≤ (finrank K ↥(linear_map.ker (f ^ n))).succ : nat.succ_le_succ (ih (nat.le_of_succ_le hn)) ... ≤ finrank K ↥(linear_map.ker (f ^ n.succ)) : nat.succ_le_of_lt h_finrank_lt_finrank } }, have h_le_finrank_V : ∀ n, finrank K (f ^ n).ker ≤ finrank K V := λ n, submodule.finrank_le _, have h_any_n_lt: ∀ n, n ≤ (finrank K V).succ → n ≤ finrank K V := λ n hn, (h_le_ker_pow n hn).trans (h_le_finrank_V n), show false, from nat.not_succ_le_self _ (h_any_n_lt (finrank K V).succ (finrank K V).succ.le_refl), end lemma ker_pow_constant {f : End K V} {k : ℕ} (h : (f ^ k).ker = (f ^ k.succ).ker) : ∀ m, (f ^ k).ker = (f ^ (k + m)).ker | 0 := by simp | (m + 1) := begin apply le_antisymm, { rw [add_comm, pow_add], apply linear_map.ker_le_ker_comp }, { rw [ker_pow_constant m, add_comm m 1, ←add_assoc, pow_add, pow_add f k m], change linear_map.ker ((f ^ (k + 1)).comp (f ^ m)) ≤ linear_map.ker ((f ^ k).comp (f ^ m)), rw [linear_map.ker_comp, linear_map.ker_comp, h, nat.add_one], exact le_rfl, } end lemma ker_pow_eq_ker_pow_finrank_of_le [finite_dimensional K V] {f : End K V} {m : ℕ} (hm : finrank K V ≤ m) : (f ^ m).ker = (f ^ finrank K V).ker := begin obtain ⟨k, h_k_le, hk⟩ : ∃ k, k ≤ finrank K V ∧ linear_map.ker (f ^ k) = linear_map.ker (f ^ k.succ) := exists_ker_pow_eq_ker_pow_succ f, calc (f ^ m).ker = (f ^ (k + (m - k))).ker : by rw add_tsub_cancel_of_le (h_k_le.trans hm) ... = (f ^ k).ker : by rw ker_pow_constant hk _ ... = (f ^ (k + (finrank K V - k))).ker : ker_pow_constant hk (finrank K V - k) ... = (f ^ finrank K V).ker : by rw add_tsub_cancel_of_le h_k_le end lemma ker_pow_le_ker_pow_finrank [finite_dimensional K V] (f : End K V) (m : ℕ) : (f ^ m).ker ≤ (f ^ finrank K V).ker := begin by_cases h_cases: m < finrank K V, { rw [←add_tsub_cancel_of_le (nat.le_of_lt h_cases), add_comm, pow_add], apply linear_map.ker_le_ker_comp }, { rw [ker_pow_eq_ker_pow_finrank_of_le (le_of_not_lt h_cases)], exact le_rfl } end end End end module
cf4df6e61ccf6c88cf3f8abbbd7ac5fb7fd9487a
4727251e0cd73359b15b664c3170e5d754078599
/archive/100-theorems-list/45_partition.lean
1470aa2598d5892ad3f297879024a3b14ec0c3be
[ "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
21,358
lean
/- Copyright (c) 2020 Bhavik Mehta, Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Aaron Anderson -/ import ring_theory.power_series.basic import combinatorics.partition import data.nat.parity import data.finset.nat_antidiagonal import data.fin.tuple.nat_antidiagonal import tactic.interval_cases import tactic.apply_fun /-! # Euler's Partition Theorem This file proves Theorem 45 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/). The theorem concerns the counting of integer partitions -- ways of writing a positive integer `n` as a sum of positive integer parts. Specifically, Euler proved that the number of integer partitions of `n` into *distinct* parts equals the number of partitions of `n` into *odd* parts. ## Proof outline The proof is based on the generating functions for odd and distinct partitions, which turn out to be equal: $$\prod_{i=0}^\infty \frac {1}{1-X^{2i+1}} = \prod_{i=0}^\infty (1+X^{i+1})$$ In fact, we do not take a limit: it turns out that comparing the `n`'th coefficients of the partial products up to `m := n + 1` is sufficient. In particular, we 1. define the partial product for the generating function for odd partitions `partial_odd_gf m` := $$\prod_{i=0}^m \frac {1}{1-X^{2i+1}}$$; 2. prove `odd_gf_prop`: if `m` is big enough (`m * 2 > n`), the partial product's coefficient counts the number of odd partitions; 3. define the partial product for the generating function for distinct partitions `partial_distinct_gf m` := $$\prod_{i=0}^m (1+X^{i+1})$$; 4. prove `distinct_gf_prop`: if `m` is big enough (`m + 1 > n`), the `n`th coefficient of the partial product counts the number of distinct partitions of `n`; 5. prove `same_coeffs`: if m is big enough (`m ≥ n`), the `n`th coefficient of the partial products are equal; 6. combine the above in `partition_theorem`. ## References https://en.wikipedia.org/wiki/Partition_(number_theory)#Odd_parts_and_distinct_parts -/ open power_series noncomputable theory variables {α : Type*} open finset open_locale big_operators open_locale classical /-- The partial product for the generating function for odd partitions. TODO: As `m` tends to infinity, this converges (in the `X`-adic topology). If `m` is sufficiently large, the `i`th coefficient gives the number of odd partitions of the natural number `i`: proved in `odd_gf_prop`. It is stated for an arbitrary field `α`, though it usually suffices to use `ℚ` or `ℝ`. -/ def partial_odd_gf (m : ℕ) [field α] := ∏ i in range m, (1 - (X : power_series α)^(2*i+1))⁻¹ /-- The partial product for the generating function for distinct partitions. TODO: As `m` tends to infinity, this converges (in the `X`-adic topology). If `m` is sufficiently large, the `i`th coefficient gives the number of distinct partitions of the natural number `i`: proved in `distinct_gf_prop`. It is stated for an arbitrary commutative semiring `α`, though it usually suffices to use `ℕ`, `ℚ` or `ℝ`. -/ def partial_distinct_gf (m : ℕ) [comm_semiring α] := ∏ i in range m, (1 + (X : power_series α)^(i+1)) /-- Functions defined only on `s`, which sum to `n`. In other words, a partition of `n` indexed by `s`. Every function in here is finitely supported, and the support is a subset of `s`. This should be thought of as a generalisation of `finset.nat.antidiagonal_tuple` where `antidiagonal_tuple k n` is the same thing as `cut (s : finset.univ (fin k)) n`. -/ def cut {ι : Type*} (s : finset ι) (n : ℕ) : finset (ι → ℕ) := finset.filter (λ f, s.sum f = n) ((s.pi (λ _, range (n+1))).map ⟨λ f i, if h : i ∈ s then f i h else 0, λ f g h, by { ext i hi, simpa [dif_pos hi] using congr_fun h i }⟩) lemma mem_cut {ι : Type*} (s : finset ι) (n : ℕ) (f : ι → ℕ) : f ∈ cut s n ↔ s.sum f = n ∧ ∀ i ∉ s, f i = 0 := begin rw [cut, mem_filter, and_comm, and_congr_right], intro h, simp only [mem_map, exists_prop, function.embedding.coe_fn_mk, mem_pi], split, { rintro ⟨_, _, rfl⟩ _ _, simp [dif_neg H] }, { intro hf, refine ⟨λ i hi, f i, λ i hi, _, _⟩, { rw [mem_range, nat.lt_succ_iff, ← h], apply single_le_sum _ hi, simp }, { ext, rw [dite_eq_ite, ite_eq_left_iff, eq_comm], exact hf x } } end lemma cut_equiv_antidiag (n : ℕ) : equiv.finset_congr (equiv.bool_arrow_equiv_prod _) (cut univ n) = nat.antidiagonal n := begin ext ⟨x₁, x₂⟩, simp_rw [equiv.finset_congr_apply, mem_map, equiv.to_embedding, function.embedding.coe_fn_mk, ←equiv.eq_symm_apply], simp [mem_cut, add_comm], end lemma cut_univ_fin_eq_antidiagonal_tuple (n : ℕ) (k : ℕ) : cut univ n = nat.antidiagonal_tuple k n := by { ext, simp [nat.mem_antidiagonal_tuple, mem_cut] } /-- There is only one `cut` of 0. -/ @[simp] lemma cut_zero {ι : Type*} (s : finset ι) : cut s 0 = {0} := begin -- In general it's nice to prove things using `mem_cut` but in this case it's easier to just -- use the definition. rw [cut, range_one, pi_const_singleton, map_singleton, function.embedding.coe_fn_mk, filter_singleton, if_pos, singleton_inj], { ext, split_ifs; refl }, rw sum_eq_zero_iff, intros x hx, apply dif_pos hx, end @[simp] lemma cut_empty_succ {ι : Type*} (n : ℕ) : cut (∅ : finset ι) (n+1) = ∅ := begin apply eq_empty_of_forall_not_mem, intros x hx, rw [mem_cut, sum_empty] at hx, cases hx.1, end lemma cut_insert {ι : Type*} (n : ℕ) (a : ι) (s : finset ι) (h : a ∉ s) : cut (insert a s) n = (nat.antidiagonal n).bUnion (λ (p : ℕ × ℕ), (cut s p.snd).map ⟨λ f, f + λ t, if t = a then p.fst else 0, add_left_injective _⟩) := begin ext f, rw [mem_cut, mem_bUnion, sum_insert h], split, { rintro ⟨rfl, h₁⟩, simp only [exists_prop, function.embedding.coe_fn_mk, mem_map, nat.mem_antidiagonal, prod.exists], refine ⟨f a, s.sum f, rfl, λ i, if i = a then 0 else f i, _, _⟩, { rw [mem_cut], refine ⟨_, _⟩, { rw [sum_ite], have : (filter (λ x, x ≠ a) s) = s, { apply filter_true_of_mem, rintro i hi rfl, apply h hi }, simp [this] }, { intros i hi, rw ite_eq_left_iff, intro hne, apply h₁, simp [not_or_distrib, hne, hi] } }, { ext, obtain rfl|h := eq_or_ne x a, { simp }, { simp [if_neg h] } } }, { simp only [mem_insert, function.embedding.coe_fn_mk, mem_map, nat.mem_antidiagonal, prod.exists, exists_prop, mem_cut, not_or_distrib], rintro ⟨p, q, rfl, g, ⟨rfl, hg₂⟩, rfl⟩, refine ⟨_, _⟩, { simp [sum_add_distrib, if_neg h, hg₂ _ h, add_comm] }, { rintro i ⟨h₁, h₂⟩, simp [if_neg h₁, hg₂ _ h₂] } } end lemma coeff_prod_range [comm_semiring α] {ι : Type*} (s : finset ι) (f : ι → power_series α) (n : ℕ) : coeff α n (∏ j in s, f j) = ∑ l in cut s n, ∏ i in s, coeff α (l i) (f i) := begin revert n, apply finset.induction_on s, { rintro ⟨_ | n⟩, { simp }, simp [cut_empty_succ, if_neg (nat.succ_ne_zero _)] }, intros a s hi ih n, rw [cut_insert _ _ _ hi, prod_insert hi, coeff_mul, sum_bUnion], { apply sum_congr rfl _, simp only [prod.forall, sum_map, pi.add_apply, function.embedding.coe_fn_mk, nat.mem_antidiagonal], rintro i j rfl, simp only [prod_insert hi, if_pos rfl, ih, mul_sum], apply sum_congr rfl _, intros x hx, rw mem_cut at hx, rw [hx.2 a hi, zero_add], congr' 1, apply prod_congr rfl, intros k hk, rw [if_neg, add_zero], exact ne_of_mem_of_not_mem hk hi }, { simp only [set.pairwise_disjoint, set.pairwise, prod.forall, not_and, ne.def, nat.mem_antidiagonal, disjoint_left, mem_map, exists_prop, function.embedding.coe_fn_mk, exists_imp_distrib, not_exists, finset.mem_coe], rintro p₁ q₁ rfl p₂ q₂ h t x hx, simp only [finset.inf_eq_inter, finset.mem_map, finset.mem_inter, mem_cut, exists_prop, function.embedding.coe_fn_mk] at hx, rcases hx with ⟨⟨p, ⟨hp, hp2⟩, hp3⟩, ⟨q, ⟨hq, hq2⟩, hq3⟩⟩, have z := hp3.trans hq3.symm, have := sum_congr (eq.refl s) (λ x _, function.funext_iff.1 z x), obtain rfl : q₁ = q₂, { simpa [sum_add_distrib, hp, hq, if_neg hi] using this }, obtain rfl : p₂ = p₁, { simpa using h }, exact (t rfl).elim } end /-- A convenience constructor for the power series whose coefficients indicate a subset. -/ def indicator_series (α : Type*) [semiring α] (s : set ℕ) : power_series α := power_series.mk (λ n, if n ∈ s then 1 else 0) lemma coeff_indicator (s : set ℕ) [semiring α] (n : ℕ) : coeff α n (indicator_series _ s) = if n ∈ s then 1 else 0 := coeff_mk _ _ lemma coeff_indicator_pos (s : set ℕ) [semiring α] (n : ℕ) (h : n ∈ s): coeff α n (indicator_series _ s) = 1 := by rw [coeff_indicator, if_pos h] lemma coeff_indicator_neg (s : set ℕ) [semiring α] (n : ℕ) (h : n ∉ s): coeff α n (indicator_series _ s) = 0 := by rw [coeff_indicator, if_neg h] lemma constant_coeff_indicator (s : set ℕ) [semiring α] : constant_coeff α (indicator_series _ s) = if 0 ∈ s then 1 else 0 := rfl lemma two_series (i : ℕ) [semiring α] : (1 + (X : power_series α)^i.succ) = indicator_series α {0, i.succ} := begin ext, simp only [coeff_indicator, coeff_one, coeff_X_pow, set.mem_insert_iff, set.mem_singleton_iff, map_add], cases n with d, { simp [(nat.succ_ne_zero i).symm] }, { simp [nat.succ_ne_zero d], }, end lemma num_series' [field α] (i : ℕ) : (1 - (X : power_series α)^(i+1))⁻¹ = indicator_series α { k | i + 1 ∣ k } := begin rw power_series.inv_eq_iff_mul_eq_one, { ext, cases n, { simp [mul_sub, zero_pow, constant_coeff_indicator] }, { simp only [coeff_one, if_neg n.succ_ne_zero, mul_sub, mul_one, coeff_indicator, linear_map.map_sub], simp_rw [coeff_mul, coeff_X_pow, coeff_indicator, boole_mul, sum_ite, filter_filter, sum_const_zero, add_zero, sum_const, nsmul_eq_mul, mul_one, sub_eq_iff_eq_add, zero_add, filter_congr_decidable], symmetry, split_ifs, { suffices : ((nat.antidiagonal n.succ).filter (λ (a : ℕ × ℕ), i + 1 ∣ a.fst ∧ a.snd = i + 1)).card = 1, { simp only [set.mem_set_of_eq], rw this, norm_cast }, rw card_eq_one, cases h with p hp, refine ⟨((i+1) * (p-1), i+1), _⟩, ext ⟨a₁, a₂⟩, simp only [mem_filter, prod.mk.inj_iff, nat.mem_antidiagonal, mem_singleton], split, { rintro ⟨a_left, ⟨a, rfl⟩, rfl⟩, refine ⟨_, rfl⟩, rw [nat.mul_sub_left_distrib, ← hp, ← a_left, mul_one, nat.add_sub_cancel] }, { rintro ⟨rfl, rfl⟩, cases p, { rw mul_zero at hp, cases hp }, rw hp, simp [nat.succ_eq_add_one, mul_add] } }, { suffices : (filter (λ (a : ℕ × ℕ), i + 1 ∣ a.fst ∧ a.snd = i + 1) (nat.antidiagonal n.succ)).card = 0, { simp only [set.mem_set_of_eq], rw this, norm_cast }, rw card_eq_zero, apply eq_empty_of_forall_not_mem, simp only [prod.forall, mem_filter, not_and, nat.mem_antidiagonal], rintro _ h₁ h₂ ⟨a, rfl⟩ rfl, apply h, simp [← h₂] } } }, { simp [zero_pow] }, end def mk_odd : ℕ ↪ ℕ := ⟨λ i, 2 * i + 1, λ x y h, by linarith⟩ -- The main workhorse of the partition theorem proof. lemma partial_gf_prop (α : Type*) [comm_semiring α] (n : ℕ) (s : finset ℕ) (hs : ∀ i ∈ s, 0 < i) (c : ℕ → set ℕ) (hc : ∀ i ∉ s, 0 ∈ c i) : (finset.card ((univ : finset (nat.partition n)).filter (λ p, (∀ j, p.parts.count j ∈ c j) ∧ ∀ j ∈ p.parts, j ∈ s)) : α) = (coeff α n) (∏ (i : ℕ) in s, indicator_series α ((* i) '' c i)) := begin simp_rw [coeff_prod_range, coeff_indicator, prod_boole, sum_boole], congr' 1, refine finset.card_congr (λ p _ i, multiset.count i p.parts • i) _ _ _, { simp only [mem_filter, mem_cut, mem_univ, true_and, exists_prop, and_assoc, and_imp, smul_eq_zero, function.embedding.coe_fn_mk, exists_imp_distrib], rintro ⟨p, hp₁, hp₂⟩ hp₃ hp₄, dsimp only at *, refine ⟨_, _, _⟩, { rw [←hp₂, ←sum_multiset_count_of_subset p s (λ x hx, hp₄ _ (multiset.mem_to_finset.mp hx))] }, { intros i hi, left, exact multiset.count_eq_zero_of_not_mem (mt (hp₄ i) hi) }, { exact λ i hi, ⟨_, hp₃ i, rfl⟩ } }, { intros p₁ p₂ hp₁ hp₂ h, apply nat.partition.ext, simp only [true_and, mem_univ, mem_filter] at hp₁ hp₂, ext i, rw function.funext_iff at h, specialize h i, cases i, { rw multiset.count_eq_zero_of_not_mem, rw multiset.count_eq_zero_of_not_mem, intro a, exact nat.lt_irrefl 0 (hs 0 (hp₂.2 0 a)), intro a, exact nat.lt_irrefl 0 (hs 0 (hp₁.2 0 a)) }, { rwa [nat.nsmul_eq_mul, nat.nsmul_eq_mul, nat.mul_left_inj i.succ_pos] at h } }, { simp only [mem_filter, mem_cut, mem_univ, exists_prop, true_and, and_assoc], rintros f ⟨hf₁, hf₂, hf₃⟩, refine ⟨⟨∑ i in s, multiset.repeat i (f i / i), _, _⟩, _, _, _⟩, { intros i hi, simp only [exists_prop, mem_sum, mem_map, function.embedding.coe_fn_mk] at hi, rcases hi with ⟨t, ht, z⟩, apply hs, rwa multiset.eq_of_mem_repeat z }, { simp_rw [multiset.sum_sum, multiset.sum_repeat, nat.nsmul_eq_mul, ←hf₁], refine sum_congr rfl (λ i hi, nat.div_mul_cancel _), rcases hf₃ i hi with ⟨w, hw, hw₂⟩, rw ← hw₂, exact dvd_mul_left _ _ }, { intro i, simp_rw [multiset.count_sum', multiset.count_repeat, sum_ite_eq], split_ifs with h h, { rcases hf₃ i h with ⟨w, hw₁, hw₂⟩, rwa [← hw₂, nat.mul_div_cancel _ (hs i h)] }, { exact hc _ h } }, { intros i hi, rw mem_sum at hi, rcases hi with ⟨j, hj₁, hj₂⟩, rwa multiset.eq_of_mem_repeat hj₂ }, { ext i, simp_rw [multiset.count_sum', multiset.count_repeat, sum_ite_eq], split_ifs, { apply nat.div_mul_cancel, rcases hf₃ i h with ⟨w, hw, hw₂⟩, apply dvd.intro_left _ hw₂ }, { rw [zero_smul, hf₂ i h] } } }, end lemma partial_odd_gf_prop [field α] (n m : ℕ) : (finset.card ((univ : finset (nat.partition n)).filter (λ p, ∀ j ∈ p.parts, j ∈ (range m).map mk_odd)) : α) = coeff α n (partial_odd_gf m) := begin rw partial_odd_gf, convert partial_gf_prop α n ((range m).map mk_odd) _ (λ _, set.univ) (λ _ _, trivial) using 2, { congr' 2, simp only [true_and, forall_const, set.mem_univ] }, { rw finset.prod_map, simp_rw num_series', apply prod_congr rfl, intros, congr' 1, ext k, split, { rintro ⟨p, rfl⟩, refine ⟨p, ⟨⟩, _⟩, apply mul_comm }, rintro ⟨a_w, -, rfl⟩, apply dvd.intro_left a_w rfl }, { intro i, rw mem_map, rintro ⟨a, -, rfl⟩, exact nat.succ_pos _ }, end /-- If m is big enough, the partial product's coefficient counts the number of odd partitions -/ theorem odd_gf_prop [field α] (n m : ℕ) (h : n < m * 2) : (finset.card (nat.partition.odds n) : α) = coeff α n (partial_odd_gf m) := begin rw [← partial_odd_gf_prop], congr' 2, apply filter_congr, intros p hp, apply ball_congr, intros i hi, have hin : i ≤ n, { simpa [p.parts_sum] using multiset.single_le_sum (λ _ _, nat.zero_le _) _ hi }, simp only [mk_odd, exists_prop, mem_range, function.embedding.coe_fn_mk, mem_map], split, { intro hi₂, have := nat.mod_add_div i 2, rw nat.not_even_iff at hi₂, rw [hi₂, add_comm] at this, refine ⟨i / 2, _, this⟩, rw nat.div_lt_iff_lt_mul _ _ zero_lt_two, exact lt_of_le_of_lt hin h }, { rintro ⟨a, -, rfl⟩, rw even_iff_two_dvd, apply nat.two_not_dvd_two_mul_add_one }, end lemma partial_distinct_gf_prop [comm_semiring α] (n m : ℕ) : (finset.card ((univ : finset (nat.partition n)).filter (λ p, p.parts.nodup ∧ ∀ j ∈ p.parts, j ∈ (range m).map ⟨nat.succ, nat.succ_injective⟩)) : α) = coeff α n (partial_distinct_gf m) := begin rw partial_distinct_gf, convert partial_gf_prop α n ((range m).map ⟨nat.succ, nat.succ_injective⟩) _ (λ _, {0, 1}) (λ _ _, or.inl rfl) using 2, { congr' 2, ext p, congr' 2, apply propext, rw multiset.nodup_iff_count_le_one, apply forall_congr, intro i, rw [set.mem_insert_iff, set.mem_singleton_iff], split, { intro hi, interval_cases (multiset.count i p.parts), { left, assumption }, { right, assumption } }, { rintro (h | h), { rw h, norm_num }, { rw h } } }, { rw finset.prod_map, apply prod_congr rfl, intros, rw two_series, congr' 1, simp [set.image_pair] }, { simp only [mem_map, function.embedding.coe_fn_mk], rintro i ⟨_, _, rfl⟩, apply nat.succ_pos } end /-- If m is big enough, the partial product's coefficient counts the number of distinct partitions -/ theorem distinct_gf_prop [comm_semiring α] (n m : ℕ) (h : n < m + 1) : ((nat.partition.distincts n).card : α) = coeff α n (partial_distinct_gf m) := begin erw [← partial_distinct_gf_prop], congr' 2, apply filter_congr, intros p hp, apply (and_iff_left _).symm, intros i hi, have : i ≤ n, { simpa [p.parts_sum] using multiset.single_le_sum (λ _ _, nat.zero_le _) _ hi }, simp only [mk_odd, exists_prop, mem_range, function.embedding.coe_fn_mk, mem_map], refine ⟨i-1, _, nat.succ_pred_eq_of_pos (p.parts_pos hi)⟩, rw tsub_lt_iff_right (nat.one_le_iff_ne_zero.mpr (p.parts_pos hi).ne'), exact lt_of_le_of_lt this h, end /-- The key proof idea for the partition theorem, showing that the generating functions for both sequences are ultimately the same (since the factor converges to 0 as m tends to infinity). It's enough to not take the limit though, and just consider large enough `m`. -/ lemma same_gf [field α] (m : ℕ) : partial_odd_gf m * (range m).prod (λ i, (1 - (X : power_series α)^(m+i+1))) = partial_distinct_gf m := begin rw [partial_odd_gf, partial_distinct_gf], induction m with m ih, { simp }, rw nat.succ_eq_add_one, set π₀ : power_series α := ∏ i in range m, (1 - X ^ (m + 1 + i + 1)) with hπ₀, set π₁ : power_series α := ∏ i in range m, (1 - X ^ (2 * i + 1))⁻¹ with hπ₁, set π₂ : power_series α := ∏ i in range m, (1 - X ^ (m + i + 1)) with hπ₂, set π₃ : power_series α := ∏ i in range m, (1 + X ^ (i + 1)) with hπ₃, rw ←hπ₃ at ih, have h : constant_coeff α (1 - X ^ (2 * m + 1)) ≠ 0, { rw [ring_hom.map_sub, ring_hom.map_pow, constant_coeff_one, constant_coeff_X, zero_pow (2 * m).succ_pos, sub_zero], exact one_ne_zero }, calc (∏ i in range (m + 1), (1 - X ^ (2 * i + 1))⁻¹) * ∏ i in range (m + 1), (1 - X ^ (m + 1 + i + 1)) = π₁ * (1 - X ^ (2 * m + 1))⁻¹ * (π₀ * (1 - X ^ (m + 1 + m + 1))) : by rw [prod_range_succ _ m, ←hπ₁, prod_range_succ _ m, ←hπ₀] ... = π₁ * (1 - X ^ (2 * m + 1))⁻¹ * (π₀ * ((1 + X ^ (m + 1)) * (1 - X ^ (m + 1)))) : by rw [←sq_sub_sq, one_pow, add_assoc _ m 1, ←two_mul (m + 1), pow_mul'] ... = π₀ * (1 - X ^ (m + 1)) * (1 - X ^ (2 * m + 1))⁻¹ * (π₁ * (1 + X ^ (m + 1))) : by ring ... = (∏ i in range (m + 1), (1 - X ^ (m + 1 + i))) * (1 - X ^ (2 * m + 1))⁻¹ * (π₁ * (1 + X ^ (m + 1))) : by { rw [prod_range_succ', add_zero, hπ₀], simp_rw ←add_assoc } ... = π₂ * (1 - X ^ (m + 1 + m)) * (1 - X ^ (2 * m + 1))⁻¹ * (π₁ * (1 + X ^ (m + 1))) : by { rw [add_right_comm, hπ₂, ←prod_range_succ], simp_rw [add_right_comm] } ... = π₂ * (1 - X ^ (2 * m + 1)) * (1 - X ^ (2 * m + 1))⁻¹ * (π₁ * (1 + X ^ (m + 1))) : by rw [two_mul, add_right_comm _ m 1] ... = (1 - X ^ (2 * m + 1)) * (1 - X ^ (2 * m + 1))⁻¹ * π₂ * (π₁ * (1 + X ^ (m + 1))) : by ring ... = π₂ * (π₁ * (1 + X ^ (m + 1))) : by rw [power_series.mul_inv_cancel _ h, one_mul] ... = π₁ * π₂ * (1 + X ^ (m + 1)) : by ring ... = π₃ * (1 + X ^ (m + 1)) : by rw ih ... = _ : by rw prod_range_succ, end lemma same_coeffs [field α] (m n : ℕ) (h : n ≤ m) : coeff α n (partial_odd_gf m) = coeff α n (partial_distinct_gf m) := begin rw [← same_gf, coeff_mul_prod_one_sub_of_lt_order], rintros i -, rw order_X_pow, exact_mod_cast nat.lt_succ_of_le (le_add_right h), end theorem partition_theorem (n : ℕ) : (nat.partition.odds n).card = (nat.partition.distincts n).card := begin -- We need the counts to live in some field (which contains ℕ), so let's just use ℚ suffices : ((nat.partition.odds n).card : ℚ) = (nat.partition.distincts n).card, { exact_mod_cast this }, rw distinct_gf_prop n (n+1) (by linarith), rw odd_gf_prop n (n+1) (by linarith), apply same_coeffs (n+1) n n.le_succ, end
c88b1db76e4314bfb344f6e86966b4f18eccb3ef
7cef822f3b952965621309e88eadf618da0c8ae9
/src/algebra/direct_sum.lean
1a909e83d51a9eed4027e319a46c93a5e5a20e03
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
6,126
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Direct sum of abelian groups, indexed by a discrete type. -/ import data.dfinsupp universes u v w u₁ variables (ι : Type v) [decidable_eq ι] (β : ι → Type w) [Π i, add_comm_group (β i)] def direct_sum : Type* := Π₀ i, β i namespace direct_sum variables {ι β} instance : add_comm_group (direct_sum ι β) := dfinsupp.add_comm_group variables β def mk : Π s : finset ι, (Π i : (↑s : set ι), β i.1) → direct_sum ι β := dfinsupp.mk def of : Π i : ι, β i → direct_sum ι β := dfinsupp.single variables {β} instance mk.is_add_group_hom (s : finset ι) : is_add_group_hom (mk β s) := { map_add := λ _ _, dfinsupp.mk_add } @[simp] lemma mk_zero (s : finset ι) : mk β s 0 = 0 := is_add_group_hom.map_zero _ @[simp] lemma mk_add (s : finset ι) (x y) : mk β s (x + y) = mk β s x + mk β s y := is_add_hom.map_add _ x y @[simp] lemma mk_neg (s : finset ι) (x) : mk β s (-x) = -mk β s x := is_add_group_hom.map_neg _ x @[simp] lemma mk_sub (s : finset ι) (x y) : mk β s (x - y) = mk β s x - mk β s y := is_add_group_hom.map_sub _ x y instance of.is_add_group_hom (i : ι) : is_add_group_hom (of β i) := { map_add := λ _ _, dfinsupp.single_add } @[simp] lemma of_zero (i : ι) : of β i 0 = 0 := is_add_group_hom.map_zero _ @[simp] lemma of_add (i : ι) (x y) : of β i (x + y) = of β i x + of β i y := is_add_hom.map_add _ x y @[simp] lemma of_neg (i : ι) (x) : of β i (-x) = -of β i x := is_add_group_hom.map_neg _ x @[simp] lemma of_sub (i : ι) (x y) : of β i (x - y) = of β i x - of β i y := is_add_group_hom.map_sub _ x y theorem mk_inj (s : finset ι) : function.injective (mk β s) := dfinsupp.mk_inj s theorem of_inj (i : ι) : function.injective (of β i) := λ x y H, congr_fun (mk_inj _ H) ⟨i, by simp [finset.to_set]⟩ @[elab_as_eliminator] protected theorem induction_on {C : direct_sum ι β → Prop} (x : direct_sum ι β) (H_zero : C 0) (H_basic : ∀ (i : ι) (x : β i), C (of β i x)) (H_plus : ∀ x y, C x → C y → C (x + y)) : C x := begin apply dfinsupp.induction x H_zero, intros i b f h1 h2 ih, solve_by_elim end variables {γ : Type u₁} [add_comm_group γ] variables (φ : Π i, β i → γ) [Π i, is_add_group_hom (φ i)] variables (φ) def to_group (f : direct_sum ι β) : γ := quotient.lift_on f (λ x, x.2.to_finset.sum $ λ i, φ i (x.1 i)) $ λ x y H, begin have H1 : x.2.to_finset ∩ y.2.to_finset ⊆ x.2.to_finset, from finset.inter_subset_left _ _, have H2 : x.2.to_finset ∩ y.2.to_finset ⊆ y.2.to_finset, from finset.inter_subset_right _ _, refine (finset.sum_subset H1 _).symm.trans ((finset.sum_congr rfl _).trans (finset.sum_subset H2 _)), { intros i H1 H2, rw finset.mem_inter at H2, rw H i, simp only [multiset.mem_to_finset] at H1 H2, rw [(y.3 i).resolve_left (mt (and.intro H1) H2), is_add_group_hom.map_zero (φ i)] }, { intros i H1, rw H i }, { intros i H1 H2, rw finset.mem_inter at H2, rw ← H i, simp only [multiset.mem_to_finset] at H1 H2, rw [(x.3 i).resolve_left (mt (λ H3, and.intro H3 H1) H2), is_add_group_hom.map_zero (φ i)] } end variables {φ} instance to_group.is_add_group_hom : is_add_group_hom (to_group φ) := { map_add := assume f g, begin refine quotient.induction_on f (λ x, _), refine quotient.induction_on g (λ y, _), change finset.sum _ _ = finset.sum _ _ + finset.sum _ _, simp only, conv { to_lhs, congr, skip, funext, rw is_add_hom.map_add (φ i) }, simp only [finset.sum_add_distrib], congr' 1, { refine (finset.sum_subset _ _).symm, { intro i, simp only [multiset.mem_to_finset, multiset.mem_add], exact or.inl }, { intros i H1 H2, simp only [multiset.mem_to_finset, multiset.mem_add] at H2, rw [(x.3 i).resolve_left H2, is_add_group_hom.map_zero (φ i)] } }, { refine (finset.sum_subset _ _).symm, { intro i, simp only [multiset.mem_to_finset, multiset.mem_add], exact or.inr }, { intros i H1 H2, simp only [multiset.mem_to_finset, multiset.mem_add] at H2, rw [(y.3 i).resolve_left H2, is_add_group_hom.map_zero (φ i)] } } end } variables (φ) @[simp] lemma to_group_zero : to_group φ 0 = 0 := is_add_group_hom.map_zero _ @[simp] lemma to_group_add (x y) : to_group φ (x + y) = to_group φ x + to_group φ y := is_add_hom.map_add _ x y @[simp] lemma to_group_neg (x) : to_group φ (-x) = -to_group φ x := is_add_group_hom.map_neg _ x @[simp] lemma to_group_sub (x y) : to_group φ (x - y) = to_group φ x - to_group φ y := is_add_group_hom.map_sub _ x y @[simp] lemma to_group_of (i) (x : β i) : to_group φ (of β i x) = φ i x := (add_zero _).trans $ congr_arg (φ i) $ show (if H : i ∈ finset.singleton i then x else 0) = x, from dif_pos $ finset.mem_singleton_self i variables (ψ : direct_sum ι β → γ) [is_add_group_hom ψ] theorem to_group.unique (f : direct_sum ι β) : ψ f = to_group (λ i, ψ ∘ of β i) f := direct_sum.induction_on f (by rw [is_add_group_hom.map_zero ψ, is_add_group_hom.map_zero (to_group (λ i, ψ ∘ of β i))]) (λ i x, by rw [to_group_of]) (λ x y ihx ihy, by rw [is_add_hom.map_add ψ, is_add_hom.map_add (to_group (λ i, ψ ∘ of β i)), ihx, ihy]) variables (β) def set_to_set (S T : set ι) (H : S ⊆ T) : direct_sum S (β ∘ subtype.val) → direct_sum T (β ∘ subtype.val) := to_group $ λ i, of (β ∘ @subtype.val _ T) ⟨i.1, H i.2⟩ variables {β} instance (S T : set ι) (H : S ⊆ T) : is_add_group_hom (set_to_set β S T H) := to_group.is_add_group_hom protected def id (M : Type v) [add_comm_group M] : direct_sum punit (λ _, M) ≃ M := { to_fun := direct_sum.to_group (λ _, id), inv_fun := of (λ _, M) punit.star, left_inv := λ x, direct_sum.induction_on x (by rw [to_group_zero, of_zero]) (λ ⟨⟩ x, by rw [to_group_of]; refl) (λ x y ihx ihy, by rw [to_group_add, of_add, ihx, ihy]), right_inv := λ x, to_group_of _ _ _ } instance : has_coe_to_fun (direct_sum ι β) := dfinsupp.has_coe_to_fun end direct_sum
b94d14e91862a9b5f167d2ad775950f7853c1c27
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/polynomial/lifts.lean
1446c0412e21da80ea878b8bf2d64b0aa4138aa5
[ "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
10,934
lean
/- Copyright (c) 2020 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import data.polynomial.algebra_map import data.polynomial.div /-! # Polynomials that lift Given semirings `R` and `S` with a morphism `f : R →+* S`, we define a subsemiring `lifts` of `polynomial S` by the image of `ring_hom.of (map f)`. Then, we prove that a polynomial that lifts can always be lifted to a polynomial of the same degree and that a monic polynomial that lifts can be lifted to a monic polynomial (of the same degree). ## Main definition * `lifts (f : R →+* S)` : the subsemiring of polynomials that lift. ## Main results * `lifts_and_degree_eq` : A polynomial lifts if and only if it can be lifted to a polynomial of the same degree. * `lifts_and_degree_eq_and_monic` : A monic polynomial lifts if and only if it can be lifted to a monic polynomial of the same degree. * `lifts_iff_alg` : if `R` is commutative, a polynomial lifts if and only if it is in the image of `map_alg`, where `map_alg : polynomial R →ₐ[R] polynomial S` is the only `R`-algebra map that sends `X` to `X`. ## Implementation details In general `R` and `S` are semiring, so `lifts` is a semiring. In the case of rings, see `lifts_iff_lifts_ring`. Since we do not assume `R` to be commutative, we cannot say in general that the set of polynomials that lift is a subalgebra. (By `lift_iff` this is true if `R` is commutative.) -/ open_locale classical big_operators noncomputable theory namespace polynomial universes u v w section semiring variables {R : Type u} [semiring R] {S : Type v} [semiring S] {f : R →+* S} /-- We define the subsemiring of polynomials that lifts as the image of `ring_hom.of (map f)`. -/ def lifts (f : R →+* S) : subsemiring (polynomial S) := ring_hom.srange (map_ring_hom f) lemma mem_lifts (p : polynomial S) : p ∈ lifts f ↔ ∃ (q : polynomial R), map f q = p := by simp only [coe_map_ring_hom, lifts, ring_hom.mem_srange] lemma lifts_iff_set_range (p : polynomial S) : p ∈ lifts f ↔ p ∈ set.range (map f) := by simp only [coe_map_ring_hom, lifts, set.mem_range, ring_hom.mem_srange] lemma lifts_iff_ring_hom_srange (p : polynomial S) : p ∈ lifts f ↔ p ∈ (map_ring_hom f).srange := by simp only [coe_map_ring_hom, lifts, set.mem_range, ring_hom.mem_srange] lemma lifts_iff_coeff_lifts (p : polynomial S) : p ∈ lifts f ↔ ∀ (n : ℕ), p.coeff n ∈ set.range f := by { rw [lifts_iff_ring_hom_srange, mem_map_srange f], refl } /--If `(r : R)`, then `C (f r)` lifts. -/ lemma C_mem_lifts (f : R →+* S) (r : R) : (C (f r)) ∈ lifts f := ⟨C r, by simp only [coe_map_ring_hom, map_C, set.mem_univ, subsemiring.coe_top, eq_self_iff_true, and_self]⟩ /-- If `(s : S)` is in the image of `f`, then `C s` lifts. -/ lemma C'_mem_lifts {f : R →+* S} {s : S} (h : s ∈ set.range f) : (C s) ∈ lifts f := begin obtain ⟨r, rfl⟩ := set.mem_range.1 h, use C r, simp only [coe_map_ring_hom, map_C, set.mem_univ, subsemiring.coe_top, eq_self_iff_true, and_self] end /-- The polynomial `X` lifts. -/ lemma X_mem_lifts (f : R →+* S) : (X : polynomial S) ∈ lifts f := ⟨X, by simp only [coe_map_ring_hom, set.mem_univ, subsemiring.coe_top, eq_self_iff_true, map_X, and_self]⟩ /-- The polynomial `X ^ n` lifts. -/ lemma X_pow_mem_lifts (f : R →+* S) (n : ℕ) : (X ^ n : polynomial S) ∈ lifts f := ⟨X ^ n, by simp only [coe_map_ring_hom, map_pow, set.mem_univ, subsemiring.coe_top, eq_self_iff_true, map_X, and_self]⟩ /-- If `p` lifts and `(r : R)` then `r * p` lifts. -/ lemma base_mul_mem_lifts {p : polynomial S} (r : R) (hp : p ∈ lifts f) : C (f r) * p ∈ lifts f := begin simp only [lifts, ring_hom.mem_srange] at hp ⊢, obtain ⟨p₁, rfl⟩ := hp, use C r * p₁, simp only [coe_map_ring_hom, map_C, map_mul] end /-- If `(s : S)` is in the image of `f`, then `monomial n s` lifts. -/ lemma monomial_mem_lifts {s : S} (n : ℕ) (h : s ∈ set.range f) : (monomial n s) ∈ lifts f := begin obtain ⟨r, rfl⟩ := set.mem_range.1 h, use monomial n r, simp only [coe_map_ring_hom, set.mem_univ, map_monomial, subsemiring.coe_top, eq_self_iff_true, and_self], end /-- If `p` lifts then `p.erase n` lifts. -/ lemma erase_mem_lifts {p : polynomial S} (n : ℕ) (h : p ∈ lifts f) : p.erase n ∈ lifts f := begin rw [lifts_iff_ring_hom_srange, mem_map_srange] at h ⊢, intros k, by_cases hk : k = n, { use 0, simp only [hk, ring_hom.map_zero, erase_same] }, obtain ⟨i, hi⟩ := h k, use i, simp only [hi, hk, erase_ne, ne.def, not_false_iff], end section lift_deg lemma monomial_mem_lifts_and_degree_eq {s : S} {n : ℕ} (hl : monomial n s ∈ lifts f) : ∃ (q : polynomial R), map f q = (monomial n s) ∧ q.degree = (monomial n s).degree := begin by_cases hzero : s = 0, { use 0, simp only [hzero, degree_zero, eq_self_iff_true, and_self, monomial_zero_right, map_zero] }, rw lifts_iff_set_range at hl, obtain ⟨q, hq⟩ := hl, replace hq := (ext_iff.1 hq) n, have hcoeff : f (q.coeff n) = s, { simp [coeff_monomial] at hq, exact hq }, use (monomial n (q.coeff n)), split, { simp only [hcoeff, map_monomial] }, have hqzero : q.coeff n ≠ 0, { intro habs, simp only [habs, ring_hom.map_zero] at hcoeff, exact hzero hcoeff.symm }, repeat {rw monomial_eq_C_mul_X}, simp only [hzero, hqzero, ne.def, not_false_iff, degree_C_mul_X_pow], end /-- A polynomial lifts if and only if it can be lifted to a polynomial of the same degree. -/ lemma mem_lifts_and_degree_eq {p : polynomial S} (hlifts : p ∈ lifts f) : ∃ (q : polynomial R), map f q = p ∧ q.degree = p.degree := begin generalize' hd : p.nat_degree = d, revert hd p, apply nat.strong_induction_on d, intros n hn p hlifts hdeg, by_cases erase_zero : p.erase_lead = 0, { rw [← erase_lead_add_monomial_nat_degree_leading_coeff p, erase_zero, zero_add, leading_coeff], exact monomial_mem_lifts_and_degree_eq (monomial_mem_lifts p.nat_degree ((lifts_iff_coeff_lifts p).1 hlifts p.nat_degree)) }, have deg_erase := or.resolve_right (erase_lead_nat_degree_lt_or_erase_lead_eq_zero p) erase_zero, have pzero : p ≠ 0, { intro habs, exfalso, rw [habs, erase_lead_zero, eq_self_iff_true, not_true] at erase_zero, exact erase_zero }, have lead_zero : p.coeff p.nat_degree ≠ 0, { rw [← leading_coeff, ne.def, leading_coeff_eq_zero]; exact pzero }, obtain ⟨lead, hlead⟩ := monomial_mem_lifts_and_degree_eq (monomial_mem_lifts p.nat_degree ((lifts_iff_coeff_lifts p).1 hlifts p.nat_degree)), have deg_lead : lead.degree = p.nat_degree, { rw [hlead.2, monomial_eq_C_mul_X, degree_C_mul_X_pow p.nat_degree lead_zero] }, rw hdeg at deg_erase, obtain ⟨erase, herase⟩ := hn p.erase_lead.nat_degree deg_erase (erase_mem_lifts p.nat_degree hlifts) (refl p.erase_lead.nat_degree), use erase + lead, split, { simp only [hlead, herase, map_add], nth_rewrite 0 erase_lead_add_monomial_nat_degree_leading_coeff p }, rw [←hdeg, erase_lead] at deg_erase, replace deg_erase := lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 deg_erase), rw [← deg_lead, ← herase.2] at deg_erase, rw [degree_add_eq_right_of_degree_lt deg_erase, deg_lead, degree_eq_nat_degree pzero] end end lift_deg section monic /-- A monic polynomial lifts if and only if it can be lifted to a monic polynomial of the same degree. -/ lemma lifts_and_degree_eq_and_monic [nontrivial S] {p : polynomial S} (hlifts :p ∈ lifts f) (hmonic : p.monic) : ∃ (q : polynomial R), map f q = p ∧ q.degree = p.degree ∧ q.monic := begin by_cases Rtrivial : nontrivial R, swap, { rw not_nontrivial_iff_subsingleton at Rtrivial, obtain ⟨q, hq⟩ := mem_lifts_and_degree_eq hlifts, use q, exact ⟨hq.1, hq.2, @monic_of_subsingleton _ _ Rtrivial q⟩ }, by_cases er_zero : p.erase_lead = 0, { rw [← erase_lead_add_C_mul_X_pow p, er_zero, zero_add, monic.def.1 hmonic, C_1, one_mul], use X ^ p.nat_degree, repeat {split}, { simp only [map_pow, map_X] }, { rw [@degree_X_pow R _ Rtrivial, degree_X_pow] }, {exact monic_pow monic_X p.nat_degree } }, obtain ⟨q, hq⟩ := mem_lifts_and_degree_eq (erase_mem_lifts p.nat_degree hlifts), have deg_er : p.erase_lead.nat_degree < p.nat_degree := or.resolve_right (erase_lead_nat_degree_lt_or_erase_lead_eq_zero p) er_zero, replace deg_er := with_bot.coe_lt_coe.2 deg_er, rw [← degree_eq_nat_degree er_zero, erase_lead, ← hq.2, ← @degree_X_pow R _ Rtrivial p.nat_degree] at deg_er, use q + X ^ p.nat_degree, repeat {split}, { simp only [hq, map_add, map_pow, map_X], nth_rewrite 3 [← erase_lead_add_C_mul_X_pow p], rw [erase_lead, monic.leading_coeff hmonic, C_1, one_mul] }, { rw [degree_add_eq_right_of_degree_lt deg_er, @degree_X_pow R _ Rtrivial p.nat_degree, degree_eq_nat_degree (monic.ne_zero hmonic)] }, { rw [monic.def, leading_coeff_add_of_degree_lt deg_er], exact monic_pow monic_X p.nat_degree } end end monic end semiring section ring variables {R : Type u} [ring R] {S : Type v} [ring S] (f : R →+* S) /-- The subring of polynomials that lift. -/ def lifts_ring (f : R →+* S) : subring (polynomial S) := ring_hom.range (map_ring_hom f) /-- If `R` and `S` are rings, `p` is in the subring of polynomials that lift if and only if it is in the subsemiring of polynomials that lift. -/ lemma lifts_iff_lifts_ring (p : polynomial S) : p ∈ lifts f ↔ p ∈ lifts_ring f := by simp only [lifts, lifts_ring, ring_hom.mem_range, ring_hom.mem_srange] end ring section algebra variables {R : Type u} [comm_semiring R] {S : Type v} [semiring S] [algebra R S] /-- The map `polynomial R → polynomial S` as an algebra homomorphism. -/ def map_alg (R : Type u) [comm_semiring R] (S : Type v) [semiring S] [algebra R S] : polynomial R →ₐ[R] polynomial S := @aeval _ (polynomial S) _ _ _ (X : polynomial S) /-- `map_alg` is the morphism induced by `R → S`. -/ lemma map_alg_eq_map (p : polynomial R) : map_alg R S p = map (algebra_map R S) p := by simp only [map_alg, aeval_def, eval₂, map, algebra_map_apply, ring_hom.coe_comp] /-- A polynomial `p` lifts if and only if it is in the image of `map_alg`. -/ lemma mem_lifts_iff_mem_alg (R : Type u) [comm_semiring R] {S : Type v} [semiring S] [algebra R S] (p : polynomial S) :p ∈ lifts (algebra_map R S) ↔ p ∈ (alg_hom.range (@map_alg R _ S _ _)) := by simp only [coe_map_ring_hom, lifts, map_alg_eq_map, alg_hom.mem_range, ring_hom.mem_srange] /-- If `p` lifts and `(r : R)` then `r • p` lifts. -/ lemma smul_mem_lifts {p : polynomial S} (r : R) (hp : p ∈ lifts (algebra_map R S)) : r • p ∈ lifts (algebra_map R S) := by { rw mem_lifts_iff_mem_alg at hp ⊢, exact subalgebra.smul_mem (map_alg R S).range hp r } end algebra end polynomial
f2b272933508e588714beeb23dbdb7097bb75b1e
f09e92753b1d3d2eb3ce2cfb5288a7f5d1d4bd89
/src/power_bounded.lean
e393ea1ae00e8626dae1bdce31e0f690f24db50d
[ "Apache-2.0" ]
permissive
PatrickMassot/lean-perfectoid-spaces
7f63c581db26461b5a92d968e7563247e96a5597
5f70b2020b3c6d508431192b18457fa988afa50d
refs/heads/master
1,625,797,721,782
1,547,308,357,000
1,547,309,364,000
136,658,414
0
1
Apache-2.0
1,528,486,100,000
1,528,486,100,000
null
UTF-8
Lean
false
false
2,927
lean
import tactic.ring import analysis.topology.topological_space import analysis.topology.topological_structures import algebra.group_power import ring_theory.subring universe u variables {R : Type u} [comm_ring R] [topological_space R] [topological_ring R] /-- Wedhorn Definition 5.27 page 36 -/ definition is_bounded (B : set R) : Prop := ∀ U ∈ (nhds (0 : R)).sets, ∃ V ∈ (nhds (0 : R)).sets, ∀ v ∈ V, ∀ b ∈ B, v*b ∈ U definition is_power_bounded (r : R) : Prop := is_bounded (powers r) variable (R) definition power_bounded_subring := {r : R | is_power_bounded r} namespace power_bounded instance : has_coe (power_bounded_subring R) R := ⟨subtype.val⟩ lemma zero_mem : (0 : R) ∈ power_bounded_subring R := λ U hU, ⟨U, begin split, {exact hU}, intros v hv b H, cases H with n H, induction n ; { simp [H.symm, pow_succ, mem_of_nhds hU], try {assumption} } end⟩ lemma one_mem : (1 : R) ∈ power_bounded_subring R := λ U hU, ⟨U, begin split, {exact hU}, intros v hv b H, cases H with n H, simpa [H.symm] end⟩ lemma mul_mem : ∀ {a b : R}, a ∈ power_bounded_subring R → b ∈ power_bounded_subring R → a * b ∈ power_bounded_subring R := λ a b ha hb U U_nhd, begin rcases hb U U_nhd with ⟨Vb, ⟨Vb_nhd, hVb⟩⟩, rcases ha Vb Vb_nhd with ⟨Va, ⟨Va_nhd, hVa⟩⟩, clear ha hb, existsi Va, split, {exact Va_nhd}, { intros v hv x H, cases H with n hx, rw [← hx, mul_pow, ← mul_assoc], apply hVb (v * a^n) _ _ _, apply hVa v hv _ _, repeat { dsimp [powers], existsi n, refl } } end lemma neg_mem : ∀ {a : R}, a ∈ power_bounded_subring R → -a ∈ power_bounded_subring R := λ a ha U hU, begin let Usymm := U ∩ {u | -u ∈ U}, let hUsymm : Usymm ∈ (nhds (0 : R)).sets := begin apply filter.inter_mem_sets hU, apply continuous.tendsto (topological_add_group.continuous_neg R) 0, simpa end, rcases ha Usymm hUsymm with ⟨V, ⟨V_nhd, hV⟩⟩, clear hUsymm, existsi V, split, {exact V_nhd}, intros v hv b H, cases H with n hb, rw ← hb, rw show v * (-a)^n = ((-1)^n * v) * a^n, begin rw [neg_eq_neg_one_mul, mul_pow], ring, end, have H := hV v hv (a^n) _, suffices : (-1)^n * v * a^n ∈ Usymm, { exact this.1 }, { simp, cases (@neg_one_pow_eq_or R _ n) with h h; { dsimp [Usymm] at H, simp [h, H.1, H.2] } }, { dsimp [powers], existsi n, refl } end instance : is_submonoid (power_bounded_subring R) := { one_mem := power_bounded.one_mem R, mul_mem := λ a b, power_bounded.mul_mem R } instance : is_subring (power_bounded_subring R) := sorry instance nat.power_bounded: has_coe ℕ (power_bounded_subring R) := ⟨nat.cast⟩ instance int.power_bounded: has_coe ℤ (power_bounded_subring R) := ⟨int.cast⟩ definition is_uniform : Prop := is_bounded (power_bounded_subring R) end power_bounded
68a47d8b1c8d06563ee066a451a785f42bac1550
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/parserAliasShadow.lean
03d0c2c0d050d55b9ae185f5bbbd2aceff878f8d
[ "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
638
lean
namespace Foo -- The following declaration shadows the builtin parser alias `letDecl` syntax letDecl := term ">==>" term syntax "foo!" letDecl : term macro_rules | `(foo! $x:term >==> $y) => `($x + $y) end Foo -- The following declaration shadows the builtin parser alias `letDecl` syntax letDecl := term ">=>=>" term syntax "bla!" letDecl : term macro_rules | `(bla! $x:term >=>=> $y) => `($x * $y) syntax "boo!" Foo.letDecl : term macro_rules | `(boo! $x:term >==> $y) => `($x - $y) theorem ex1 : (foo! 10 >==> 20) = 30 := rfl theorem ex2 : (bla! 10 >=>=> 20) = 200 := rfl theorem ex3 : (boo! 30 >==> 20) = 10 := rfl
2ba6d4a985d14842e5e73c7fd0e0d034f325eb36
82e44445c70db0f03e30d7be725775f122d72f3e
/src/algebra/star/pi.lean
63373e3236abfeba28910248d5acc6ffa73387b7
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
1,293
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import algebra.star.basic import algebra.ring.pi /-! # `star` on pi types We put a `has_star` structure on pi types that operates elementwise, such that it describes the complex conjugation of vectors. Note that `pi.star_algebra` is in a different file to avoid pulling in everything from `algebra/algebra/basic`. -/ universes u v w variable {I : Type u} -- The indexing type variable {f : I → Type v} -- The family of types already equipped with instances namespace pi instance [Π i, has_star (f i)] : has_star (Π i, f i) := { star := λ x i, star (x i) } @[simp] lemma star_apply [Π i, has_star (f i)] (x : Π i, f i) (i : I) : star x i = star (x i) := rfl instance [Π i, has_involutive_star (f i)] : has_involutive_star (Π i, f i) := { star_involutive := λ _, funext $ λ _, star_star _ } instance [Π i, monoid (f i)] [Π i, star_monoid (f i)] : star_monoid (Π i, f i) := { star_mul := λ _ _, funext $ λ _, star_mul _ _ } instance [Π i, semiring (f i)] [Π i, star_ring (f i)] : star_ring (Π i, f i) := { star_add := λ _ _, funext $ λ _, star_add _ _, ..(by apply_instance : star_monoid (Π i, f i)) } end pi
628632497a71f18ce015cdbbdba86911c8b03492
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/library/theories/group_theory/subgroup.lean
c4cc018a48d7c52a7bad34f969e99eaf369ee287
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
16,956
lean
/- Copyright (c) 2015 Haitao Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author : Haitao Zhang -/ import data algebra.group data open function eq.ops open set namespace coset -- semigroup coset definition section variable {A : Type} variable [s : semigroup A] include s definition lmul (a : A) := λ x, a * x definition rmul (a : A) := λ x, x * a definition l a (S : set A) := (lmul a) ' S definition r a (S : set A) := (rmul a) ' S lemma lmul_compose : ∀ (a b : A), (lmul a) ∘ (lmul b) = lmul (a*b) := take a, take b, funext (assume x, by rewrite [↑function.compose, ↑lmul, mul.assoc]) lemma rmul_compose : ∀ (a b : A), (rmul a) ∘ (rmul b) = rmul (b*a) := take a, take b, funext (assume x, by rewrite [↑function.compose, ↑rmul, mul.assoc]) lemma lcompose a b (S : set A) : l a (l b S) = l (a*b) S := calc (lmul a) ' ((lmul b) ' S) = ((lmul a) ∘ (lmul b)) ' S : image_compose ... = lmul (a*b) ' S : lmul_compose lemma rcompose a b (S : set A) : r a (r b S) = r (b*a) S := calc (rmul a) ' ((rmul b) ' S) = ((rmul a) ∘ (rmul b)) ' S : image_compose ... = rmul (b*a) ' S : rmul_compose lemma l_sub a (S H : set A) : S ⊆ H → (l a S) ⊆ (l a H) := image_subset (lmul a) definition l_same S (a b : A) := l a S = l b S definition r_same S (a b : A) := r a S = r b S lemma l_same.refl S (a : A) : l_same S a a := rfl lemma l_same.symm S (a b : A) : l_same S a b → l_same S b a := eq.symm lemma l_same.trans S (a b c : A) : l_same S a b → l_same S b c → l_same S a c := eq.trans example (S : set A) : equivalence (l_same S) := mk_equivalence (l_same S) (l_same.refl S) (l_same.symm S) (l_same.trans S) end end coset section variable {A : Type} variable [s : group A] include s definition lmul_by (a : A) := λ x, a * x definition rmul_by (a : A) := λ x, x * a definition glcoset a (H : set A) : set A := λ x, H (a⁻¹ * x) definition grcoset H (a : A) : set A := λ x, H (x * a⁻¹) end namespace group_theory namespace ops infixr `∘>`:55 := glcoset -- stronger than = (50), weaker than * (70) infixl `<∘`:55 := grcoset infixr `∘c`:55 := conj_by end ops end group_theory open group_theory.ops section variable {A : Type} variable [s : group A] include s lemma conj_inj (g : A) : injective (conj_by g) := injective_of_has_left_inverse (exists.intro (conj_by g⁻¹) take a, !conj_inv_cancel) lemma lmul_inj (a : A) : injective (lmul_by a) := take x₁ x₂ Peq, by esimp [lmul_by] at Peq; rewrite [-(inv_mul_cancel_left a x₁), -(inv_mul_cancel_left a x₂), Peq] lemma lmul_inv_on (a : A) (H : set A) : left_inv_on (lmul_by a⁻¹) (lmul_by a) H := take x Px, show a⁻¹*(a*x) = x, by rewrite inv_mul_cancel_left lemma lmul_inj_on (a : A) (H : set A) : inj_on (lmul_by a) H := inj_on_of_left_inv_on (lmul_inv_on a H) lemma glcoset_eq_lcoset a (H : set A) : a ∘> H = coset.l a H := ext begin intro x, rewrite [↑glcoset, ↑coset.l, ↑image, ↑set_of, ↑mem, ↑coset.lmul], apply iff.intro, intro P1, apply (exists.intro (a⁻¹ * x)), apply and.intro, exact P1, exact (mul_inv_cancel_left a x), show (∃ (x_1 : A), H x_1 ∧ a * x_1 = x) → H (a⁻¹ * x), from assume P2, obtain x_1 P3, from P2, have P4 : a * x_1 = x, from and.right P3, have P5 : x_1 = a⁻¹ * x, from eq_inv_mul_of_mul_eq P4, eq.subst P5 (and.left P3) end lemma grcoset_eq_rcoset a (H : set A) : H <∘ a = coset.r a H := begin rewrite [↑grcoset, ↑coset.r, ↑image, ↑coset.rmul, ↑set_of], apply ext, rewrite ↑mem, intro x, apply iff.intro, show H (x * a⁻¹) → (∃ (x_1 : A), H x_1 ∧ x_1 * a = x), from assume PH, exists.intro (x * a⁻¹) (and.intro PH (inv_mul_cancel_right x a)), show (∃ (x_1 : A), H x_1 ∧ x_1 * a = x) → H (x * a⁻¹), from assume Pex, obtain x_1 Pand, from Pex, eq.subst (eq_mul_inv_of_mul_eq (and.right Pand)) (and.left Pand) end lemma glcoset_sub a (S H : set A) : S ⊆ H → (a ∘> S) ⊆ (a ∘> H) := assume Psub, assert P : _, from coset.l_sub a S H Psub, eq.symm (glcoset_eq_lcoset a S) ▸ eq.symm (glcoset_eq_lcoset a H) ▸ P lemma glcoset_compose (a b : A) (H : set A) : a ∘> b ∘> H = a*b ∘> H := begin rewrite [*glcoset_eq_lcoset], exact (coset.lcompose a b H) end lemma grcoset_compose (a b : A) (H : set A) : H <∘ a <∘ b = H <∘ a*b := begin rewrite [*grcoset_eq_rcoset], exact (coset.rcompose b a H) end lemma glcoset_id (H : set A) : 1 ∘> H = H := funext (assume x, calc (1 ∘> H) x = H (1⁻¹*x) : rfl ... = H (1*x) : {one_inv} ... = H x : {one_mul x}) lemma grcoset_id (H : set A) : H <∘ 1 = H := funext (assume x, calc H (x*1⁻¹) = H (x*1) : {one_inv} ... = H x : {mul_one x}) --lemma glcoset_inv a (H : set A) : a⁻¹ ∘> a ∘> H = H := -- funext (assume x, -- calc glcoset a⁻¹ (glcoset a H) x = H x : {mul_inv_cancel_left a⁻¹ x}) lemma glcoset_inv a (H : set A) : a⁻¹ ∘> a ∘> H = H := calc a⁻¹ ∘> a ∘> H = (a⁻¹*a) ∘> H : glcoset_compose ... = 1 ∘> H : mul.left_inv ... = H : glcoset_id lemma grcoset_inv H (a : A) : (H <∘ a) <∘ a⁻¹ = H := funext (assume x, calc grcoset (grcoset H a) a⁻¹ x = H x : {inv_mul_cancel_right x a⁻¹}) lemma glcoset_cancel a b (H : set A) : (b*a⁻¹) ∘> a ∘> H = b ∘> H := calc (b*a⁻¹) ∘> a ∘> H = b*a⁻¹*a ∘> H : glcoset_compose ... = b ∘> H : {inv_mul_cancel_right b a} lemma grcoset_cancel a b (H : set A) : H <∘ a <∘ a⁻¹*b = H <∘ b := calc H <∘ a <∘ a⁻¹*b = H <∘ a*(a⁻¹*b) : grcoset_compose ... = H <∘ b : {mul_inv_cancel_left a b} -- test how precedence breaks tie: infixr takes hold since its encountered first example a b (H : set A) : a ∘> H <∘ b = a ∘> (H <∘ b) := rfl -- should be true for semigroup as well but irrelevant lemma lcoset_rcoset_assoc a b (H : set A) : a ∘> H <∘ b = (a ∘> H) <∘ b := funext (assume x, begin esimp [glcoset, grcoset], rewrite mul.assoc end) definition mul_closed_on H := ∀ (x y : A), x ∈ H → y ∈ H → x * y ∈ H lemma closed_lcontract a (H : set A) : mul_closed_on H → a ∈ H → a ∘> H ⊆ H := begin rewrite [↑mul_closed_on, ↑glcoset, ↑subset, ↑mem], intro Pclosed, intro PHa, intro x, intro PHainvx, exact (eq.subst (mul_inv_cancel_left a x) (Pclosed a (a⁻¹*x) PHa PHainvx)) end lemma closed_rcontract a (H : set A) : mul_closed_on H → a ∈ H → H <∘ a ⊆ H := assume P1 : mul_closed_on H, assume P2 : H a, begin rewrite ↑subset, intro x, rewrite [↑grcoset, ↑mem], intro P3, exact (eq.subst (inv_mul_cancel_right x a) (P1 (x * a⁻¹) a P3 P2)) end lemma closed_lcontract_set a (H G : set A) : mul_closed_on G → H ⊆ G → a∈G → a∘>H ⊆ G := assume Pclosed, assume PHsubG, assume PainG, assert PaGsubG : a ∘> G ⊆ G, from closed_lcontract a G Pclosed PainG, assert PaHsubaG : a ∘> H ⊆ a ∘> G, from eq.symm (glcoset_eq_lcoset a H) ▸ eq.symm (glcoset_eq_lcoset a G) ▸ (coset.l_sub a H G PHsubG), subset.trans PaHsubaG PaGsubG definition subgroup.has_inv H := ∀ (a : A), a ∈ H → a⁻¹ ∈ H -- two ways to define the same equivalence relatiohship for subgroups definition in_lcoset [reducible] H (a b : A) := a ∈ b ∘> H definition in_rcoset [reducible] H (a b : A) := a ∈ H <∘ b definition same_lcoset [reducible] H (a b : A) := a ∘> H = b ∘> H definition same_rcoset [reducible] H (a b : A) := H <∘ a = H <∘ b definition same_left_right_coset (N : set A) := ∀ x, x ∘> N = N <∘ x structure is_subgroup [class] (H : set A) : Type := (has_one : H 1) (mul_closed : mul_closed_on H) (has_inv : subgroup.has_inv H) structure is_normal_subgroup [class] (N : set A) extends is_subgroup N := (normal : same_left_right_coset N) end section subgroup variable {A : Type} variable [s : group A] include s variable {H : set A} variable [is_subg : is_subgroup H] include is_subg section set_reducible local attribute set [reducible] lemma subg_has_one : H (1 : A) := @is_subgroup.has_one A s H is_subg lemma subg_mul_closed : mul_closed_on H := @is_subgroup.mul_closed A s H is_subg lemma subg_has_inv : subgroup.has_inv H := @is_subgroup.has_inv A s H is_subg lemma subgroup_coset_id : ∀ a, a ∈ H → (a ∘> H = H ∧ H <∘ a = H) := take a, assume PHa : H a, assert Pl : a ∘> H ⊆ H, from closed_lcontract a H subg_mul_closed PHa, assert Pr : H <∘ a ⊆ H, from closed_rcontract a H subg_mul_closed PHa, assert PHainv : H a⁻¹, from subg_has_inv a PHa, and.intro (ext (assume x, begin esimp [glcoset, mem], apply iff.intro, apply Pl, intro PHx, exact (subg_mul_closed a⁻¹ x PHainv PHx) end)) (ext (assume x, begin esimp [grcoset, mem], apply iff.intro, apply Pr, intro PHx, exact (subg_mul_closed x a⁻¹ PHx PHainv) end)) lemma subgroup_lcoset_id : ∀ a, a ∈ H → a ∘> H = H := take a, assume PHa : H a, and.left (subgroup_coset_id a PHa) lemma subgroup_rcoset_id : ∀ a, a ∈ H → H <∘ a = H := take a, assume PHa : H a, and.right (subgroup_coset_id a PHa) lemma subg_in_coset_refl (a : A) : a ∈ a ∘> H ∧ a ∈ H <∘ a := assert PH1 : H 1, from subg_has_one, assert PHinvaa : H (a⁻¹*a), from (eq.symm (mul.left_inv a)) ▸ PH1, assert PHainva : H (a*a⁻¹), from (eq.symm (mul.right_inv a)) ▸ PH1, and.intro PHinvaa PHainva end set_reducible lemma subg_in_lcoset_same_lcoset (a b : A) : in_lcoset H a b → same_lcoset H a b := assume Pa_in_b : H (b⁻¹*a), have Pbinva : b⁻¹*a ∘> H = H, from subgroup_lcoset_id (b⁻¹*a) Pa_in_b, have Pb_binva : b ∘> b⁻¹*a ∘> H = b ∘> H, from Pbinva ▸ rfl, have Pbbinva : b*(b⁻¹*a)∘>H = b∘>H, from glcoset_compose b (b⁻¹*a) H ▸ Pb_binva, mul_inv_cancel_left b a ▸ Pbbinva lemma subg_same_lcoset_in_lcoset (a b : A) : same_lcoset H a b → in_lcoset H a b := assume Psame : a∘>H = b∘>H, assert Pa : a ∈ a∘>H, from and.left (subg_in_coset_refl a), by exact (Psame ▸ Pa) lemma subg_lcoset_same (a b : A) : in_lcoset H a b = (a∘>H = b∘>H) := propext(iff.intro (subg_in_lcoset_same_lcoset a b) (subg_same_lcoset_in_lcoset a b)) lemma subg_rcoset_same (a b : A) : in_rcoset H a b = (H<∘a = H<∘b) := propext(iff.intro (assume Pa_in_b : H (a*b⁻¹), have Pabinv : H<∘a*b⁻¹ = H, from subgroup_rcoset_id (a*b⁻¹) Pa_in_b, have Pabinv_b : H <∘ a*b⁻¹ <∘ b = H <∘ b, from Pabinv ▸ rfl, have Pabinvb : H <∘ a*b⁻¹*b = H <∘ b, from grcoset_compose (a*b⁻¹) b H ▸ Pabinv_b, inv_mul_cancel_right a b ▸ Pabinvb) (assume Psame, assert Pa : a ∈ H<∘a, from and.right (subg_in_coset_refl a), by exact (Psame ▸ Pa))) lemma subg_same_lcoset.refl (a : A) : same_lcoset H a a := rfl lemma subg_same_rcoset.refl (a : A) : same_rcoset H a a := rfl lemma subg_same_lcoset.symm (a b : A) : same_lcoset H a b → same_lcoset H b a := eq.symm lemma subg_same_rcoset.symm (a b : A) : same_rcoset H a b → same_rcoset H b a := eq.symm lemma subg_same_lcoset.trans (a b c : A) : same_lcoset H a b → same_lcoset H b c → same_lcoset H a c := eq.trans lemma subg_same_rcoset.trans (a b c : A) : same_rcoset H a b → same_rcoset H b c → same_rcoset H a c := eq.trans variable {S : set A} lemma subg_lcoset_subset_subg (Psub : S ⊆ H) (a : A) : a ∈ H → a ∘> S ⊆ H := assume Pin, have P : a ∘> S ⊆ a ∘> H, from glcoset_sub a S H Psub, subgroup_lcoset_id a Pin ▸ P end subgroup section normal_subg open quot variable {A : Type} variable [s : group A] include s variable (N : set A) variable [is_nsubg : is_normal_subgroup N] include is_nsubg local notation a `~` b := same_lcoset N a b -- note : does not bind as strong as → lemma nsubg_normal : same_left_right_coset N := @is_normal_subgroup.normal A s N is_nsubg lemma nsubg_same_lcoset_product : ∀ a1 a2 b1 b2, (a1 ~ b1) → (a2 ~ b2) → ((a1*a2) ~ (b1*b2)) := take a1, take a2, take b1, take b2, assume Psame1 : a1 ∘> N = b1 ∘> N, assume Psame2 : a2 ∘> N = b2 ∘> N, calc a1*a2 ∘> N = a1 ∘> a2 ∘> N : glcoset_compose ... = a1 ∘> b2 ∘> N : by rewrite Psame2 ... = a1 ∘> (N <∘ b2) : by rewrite (nsubg_normal N) ... = (a1 ∘> N) <∘ b2 : by rewrite lcoset_rcoset_assoc ... = (b1 ∘> N) <∘ b2 : by rewrite Psame1 ... = N <∘ b1 <∘ b2 : by rewrite (nsubg_normal N) ... = N <∘ (b1*b2) : by rewrite grcoset_compose ... = (b1*b2) ∘> N : by rewrite (nsubg_normal N) example (a b : A) : (a⁻¹ ~ b⁻¹) = (a⁻¹ ∘> N = b⁻¹ ∘> N) := rfl lemma nsubg_same_lcoset_inv : ∀ a b, (a ~ b) → (a⁻¹ ~ b⁻¹) := take a b, assume Psame : a ∘> N = b ∘> N, calc a⁻¹ ∘> N = a⁻¹*b*b⁻¹ ∘> N : by rewrite mul_inv_cancel_right ... = a⁻¹*b ∘> b⁻¹ ∘> N : by rewrite glcoset_compose ... = a⁻¹*b ∘> (N <∘ b⁻¹) : by rewrite nsubg_normal ... = (a⁻¹*b ∘> N) <∘ b⁻¹ : by rewrite lcoset_rcoset_assoc ... = (a⁻¹ ∘> b ∘> N) <∘ b⁻¹ : by rewrite glcoset_compose ... = (a⁻¹ ∘> a ∘> N) <∘ b⁻¹ : by rewrite Psame ... = N <∘ b⁻¹ : by rewrite glcoset_inv ... = b⁻¹ ∘> N : by rewrite nsubg_normal definition nsubg_setoid [instance] : setoid A := setoid.mk (same_lcoset N) (mk_equivalence (same_lcoset N) (subg_same_lcoset.refl) (subg_same_lcoset.symm) (subg_same_lcoset.trans)) definition coset_of : Type := quot (nsubg_setoid N) definition coset_inv_base (a : A) : coset_of N := ⟦a⁻¹⟧ definition coset_product (a b : A) : coset_of N := ⟦a*b⟧ lemma coset_product_well_defined : ∀ a1 a2 b1 b2, (a1 ~ b1) → (a2 ~ b2) → ⟦a1*a2⟧ = ⟦b1*b2⟧ := take a1 a2 b1 b2, assume P1 P2, quot.sound (nsubg_same_lcoset_product N a1 a2 b1 b2 P1 P2) definition coset_mul (aN bN : coset_of N) : coset_of N := quot.lift_on₂ aN bN (coset_product N) (coset_product_well_defined N) lemma coset_inv_well_defined : ∀ a b, (a ~ b) → ⟦a⁻¹⟧ = ⟦b⁻¹⟧ := take a b, assume P, quot.sound (nsubg_same_lcoset_inv N a b P) definition coset_inv (aN : coset_of N) : coset_of N := quot.lift_on aN (coset_inv_base N) (coset_inv_well_defined N) definition coset_one : coset_of N := ⟦1⟧ local infixl `cx`:70 := coset_mul N example (a b c : A) : ⟦a⟧ cx ⟦b*c⟧ = ⟦a*(b*c)⟧ := rfl lemma coset_product_assoc (a b c : A) : ⟦a⟧ cx ⟦b⟧ cx ⟦c⟧ = ⟦a⟧ cx (⟦b⟧ cx ⟦c⟧) := calc ⟦a*b*c⟧ = ⟦a*(b*c)⟧ : {mul.assoc a b c} ... = ⟦a⟧ cx ⟦b*c⟧ : rfl lemma coset_product_left_id (a : A) : ⟦1⟧ cx ⟦a⟧ = ⟦a⟧ := calc ⟦1*a⟧ = ⟦a⟧ : {one_mul a} lemma coset_product_right_id (a : A) : ⟦a⟧ cx ⟦1⟧ = ⟦a⟧ := calc ⟦a*1⟧ = ⟦a⟧ : {mul_one a} lemma coset_product_left_inv (a : A) : ⟦a⁻¹⟧ cx ⟦a⟧ = ⟦1⟧ := calc ⟦a⁻¹*a⟧ = ⟦1⟧ : {mul.left_inv a} lemma coset_mul.assoc (aN bN cN : coset_of N) : aN cx bN cx cN = aN cx (bN cx cN) := quot.ind (λ a, quot.ind (λ b, quot.ind (λ c, coset_product_assoc N a b c) cN) bN) aN lemma coset_mul.one_mul (aN : coset_of N) : coset_one N cx aN = aN := quot.ind (coset_product_left_id N) aN lemma coset_mul.mul_one (aN : coset_of N) : aN cx (coset_one N) = aN := quot.ind (coset_product_right_id N) aN lemma coset_mul.left_inv (aN : coset_of N) : (coset_inv N aN) cx aN = (coset_one N) := quot.ind (coset_product_left_inv N) aN definition mk_quotient_group : group (coset_of N):= group.mk (coset_mul N) (coset_mul.assoc N) (coset_one N) (coset_mul.one_mul N) (coset_mul.mul_one N) (coset_inv N) (coset_mul.left_inv N) end normal_subg namespace group_theory namespace quotient section open quot variable {A : Type} variable [s : group A] include s variable {N : set A} variable [is_nsubg : is_normal_subgroup N] include is_nsubg definition quotient_group [instance] : group (coset_of N) := mk_quotient_group N example (aN : coset_of N) : aN * aN⁻¹ = 1 := mul.right_inv aN definition natural (a : A) : coset_of N := ⟦a⟧ end end quotient end group_theory
e3f904f8b463a6f0c8503ae493fe88da0e67e832
b561a44b48979a98df50ade0789a21c79ee31288
/tests/lean/run/printDecls.lean
b6b4ddf41d9e09e6ce2921999b5e6ae6f9e98f16
[ "Apache-2.0" ]
permissive
3401ijk/lean4
97659c475ebd33a034fed515cb83a85f75ccfb06
a5b1b8de4f4b038ff752b9e607b721f15a9a4351
refs/heads/master
1,693,933,007,651
1,636,424,845,000
1,636,424,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
839
lean
import Lean open Lean open Lean.Meta -- Return true if `declName` should be ignored def shouldIgnore (declName : Name) : Bool := declName.isInternal || match declName with | Name.str _ s _ => "match_".isPrefixOf s || "proof_".isPrefixOf s || "eq_".isPrefixOf s | _ => true -- Print declarations that have the given prefix. def printDecls (pre : Name) : MetaM Unit := do let cs := (← getEnv).constants cs.forM fun declName info => do if pre.isPrefixOf declName && !shouldIgnore declName then if let some docString := findDocString? (← getEnv) declName then IO.println s!"/-- {docString} -/\n{declName} : {← ppExpr info.type}" else IO.println s!"{declName} : {← ppExpr info.type}" #eval printDecls `Array #eval printDecls `List #eval printDecls `Bool #eval printDecls `Lean.Elab
43cf11bf3a5b3b5052e4e44ddb846f2ef5bf33b2
82e44445c70db0f03e30d7be725775f122d72f3e
/src/linear_algebra/prod.lean
2eb5f22480906b5d960b83b4ff7158cb9d2613ed
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
24,501
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Kevin Buzzard, Yury Kudryashov, Eric Wieser -/ import linear_algebra.basic import order.partial_sups /-! ### Products of modules This file defines constructors for linear maps whose domains or codomains are products. It contains theorems relating these to each other, as well as to `submodule.prod`, `submodule.map`, `submodule.comap`, `linear_map.range`, and `linear_map.ker`. ## Main definitions - products in the domain: - `linear_map.fst` - `linear_map.snd` - `linear_map.coprod` - `linear_map.prod_ext` - products in the codomain: - `linear_map.inl` - `linear_map.inr` - `linear_map.prod` - products in both domain and codomain: - `linear_map.prod_map` - `linear_equiv.prod_map` - `linear_equiv.skew_prod` -/ universes u v w x y z u' v' w' y' variables {R : Type u} {K : Type u'} {M : Type v} {V : Type v'} {M₂ : Type w} {V₂ : Type w'} variables {M₃ : Type y} {V₃ : Type y'} {M₄ : Type z} {ι : Type x} section prod namespace linear_map variables (S : Type*) [semiring R] [semiring S] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] variables [module R M] [module R M₂] [module R M₃] [module R M₄] variables (f : M →ₗ[R] M₂) section variables (R M M₂) /-- The first projection of a product is a linear map. -/ def fst : M × M₂ →ₗ[R] M := { to_fun := prod.fst, map_add' := λ x y, rfl, map_smul' := λ x y, rfl } /-- The second projection of a product is a linear map. -/ def snd : M × M₂ →ₗ[R] M₂ := { to_fun := prod.snd, map_add' := λ x y, rfl, map_smul' := λ x y, rfl } end @[simp] theorem fst_apply (x : M × M₂) : fst R M M₂ x = x.1 := rfl @[simp] theorem snd_apply (x : M × M₂) : snd R M M₂ x = x.2 := rfl /-- The prod of two linear maps is a linear map. -/ @[simps] def prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (M →ₗ[R] M₂ × M₃) := { to_fun := λ x, (f x, g x), map_add' := λ x y, by simp only [prod.mk_add_mk, map_add], map_smul' := λ c x, by simp only [prod.smul_mk, map_smul] } @[simp] theorem fst_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (fst R M₂ M₃).comp (prod f g) = f := by ext; refl @[simp] theorem snd_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (snd R M₂ M₃).comp (prod f g) = g := by ext; refl @[simp] theorem pair_fst_snd : prod (fst R M M₂) (snd R M M₂) = linear_map.id := by ext; refl /-- Taking the product of two maps with the same domain is equivalent to taking the product of their codomains. See note [bundled maps over different rings] for why separate `R` and `S` semirings are used. -/ @[simps] def prod_equiv [module S M₂] [module S M₃] [smul_comm_class R S M₂] [smul_comm_class R S M₃] : ((M →ₗ[R] M₂) × (M →ₗ[R] M₃)) ≃ₗ[S] (M →ₗ[R] M₂ × M₃) := { to_fun := λ f, f.1.prod f.2, inv_fun := λ f, ((fst _ _ _).comp f, (snd _ _ _).comp f), left_inv := λ f, by ext; refl, right_inv := λ f, by ext; refl, map_add' := λ a b, rfl, map_smul' := λ r a, rfl } section variables (R M M₂) /-- The left injection into a product is a linear map. -/ def inl : M →ₗ[R] M × M₂ := prod linear_map.id 0 /-- The right injection into a product is a linear map. -/ def inr : M₂ →ₗ[R] M × M₂ := prod 0 linear_map.id end @[simp] theorem inl_apply (x : M) : inl R M M₂ x = (x, 0) := rfl @[simp] theorem inr_apply (x : M₂) : inr R M M₂ x = (0, x) := rfl theorem inl_eq_prod : inl R M M₂ = prod linear_map.id 0 := rfl theorem inr_eq_prod : inr R M M₂ = prod 0 linear_map.id := rfl theorem inl_injective : function.injective (inl R M M₂) := λ _, by simp theorem inr_injective : function.injective (inr R M M₂) := λ _, by simp /-- The coprod function `λ x : M × M₂, f.1 x.1 + f.2 x.2` is a linear map. -/ def coprod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : M × M₂ →ₗ[R] M₃ := f.comp (fst _ _ _) + g.comp (snd _ _ _) @[simp] theorem coprod_apply (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (x : M × M₂) : coprod f g x = f x.1 + g x.2 := rfl @[simp] theorem coprod_inl (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (coprod f g).comp (inl R M M₂) = f := by ext; simp only [map_zero, add_zero, coprod_apply, inl_apply, comp_apply] @[simp] theorem coprod_inr (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (coprod f g).comp (inr R M M₂) = g := by ext; simp only [map_zero, coprod_apply, inr_apply, zero_add, comp_apply] @[simp] theorem coprod_inl_inr : coprod (inl R M M₂) (inr R M M₂) = linear_map.id := by ext; simp only [prod.mk_add_mk, add_zero, id_apply, coprod_apply, inl_apply, inr_apply, zero_add] theorem comp_coprod (f : M₃ →ₗ[R] M₄) (g₁ : M →ₗ[R] M₃) (g₂ : M₂ →ₗ[R] M₃) : f.comp (g₁.coprod g₂) = (f.comp g₁).coprod (f.comp g₂) := ext $ λ x, f.map_add (g₁ x.1) (g₂ x.2) theorem fst_eq_coprod : fst R M M₂ = coprod linear_map.id 0 := by ext; simp theorem snd_eq_coprod : snd R M M₂ = coprod 0 linear_map.id := by ext; simp @[simp] theorem coprod_comp_prod (f : M₂ →ₗ[R] M₄) (g : M₃ →ₗ[R] M₄) (f' : M →ₗ[R] M₂) (g' : M →ₗ[R] M₃) : (f.coprod g).comp (f'.prod g') = f.comp f' + g.comp g' := rfl @[simp] lemma coprod_map_prod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (S : submodule R M) (S' : submodule R M₂) : (submodule.prod S S').map (linear_map.coprod f g) = S.map f ⊔ S'.map g := set_like.coe_injective $ begin simp only [linear_map.coprod_apply, submodule.coe_sup, submodule.map_coe], rw [←set.image2_add, set.image2_image_left, set.image2_image_right], exact set.image_prod (λ m m₂, f m + g m₂), end /-- Taking the product of two maps with the same codomain is equivalent to taking the product of their domains. See note [bundled maps over different rings] for why separate `R` and `S` semirings are used. -/ @[simps] def coprod_equiv [module S M₃] [smul_comm_class R S M₃] : ((M →ₗ[R] M₃) × (M₂ →ₗ[R] M₃)) ≃ₗ[S] (M × M₂ →ₗ[R] M₃) := { to_fun := λ f, f.1.coprod f.2, inv_fun := λ f, (f.comp (inl _ _ _), f.comp (inr _ _ _)), left_inv := λ f, by simp only [prod.mk.eta, coprod_inl, coprod_inr], right_inv := λ f, by simp only [←comp_coprod, comp_id, coprod_inl_inr], map_add' := λ a b, by { ext, simp only [prod.snd_add, add_apply, coprod_apply, prod.fst_add], ac_refl }, map_smul' := λ r a, by { ext, simp only [smul_add, smul_apply, prod.smul_snd, prod.smul_fst, coprod_apply] } } theorem prod_ext_iff {f g : M × M₂ →ₗ[R] M₃} : f = g ↔ f.comp (inl _ _ _) = g.comp (inl _ _ _) ∧ f.comp (inr _ _ _) = g.comp (inr _ _ _) := (coprod_equiv ℕ).symm.injective.eq_iff.symm.trans prod.ext_iff /-- Split equality of linear maps from a product into linear maps over each component, to allow `ext` to apply lemmas specific to `M →ₗ M₃` and `M₂ →ₗ M₃`. See note [partially-applied ext lemmas]. -/ @[ext] theorem prod_ext {f g : M × M₂ →ₗ[R] M₃} (hl : f.comp (inl _ _ _) = g.comp (inl _ _ _)) (hr : f.comp (inr _ _ _) = g.comp (inr _ _ _)) : f = g := prod_ext_iff.2 ⟨hl, hr⟩ /-- `prod.map` of two linear maps. -/ def prod_map (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₄) : (M × M₂) →ₗ[R] (M₃ × M₄) := (f.comp (fst R M M₂)).prod (g.comp (snd R M M₂)) @[simp] theorem prod_map_apply (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₄) (x) : f.prod_map g x = (f x.1, g x.2) := rfl lemma prod_map_comap_prod (f : M →ₗ[R] M₂) (g : M₃ →ₗ[R] M₄) (S : submodule R M₂) (S' : submodule R M₄) : (submodule.prod S S').comap (linear_map.prod_map f g) = (S.comap f).prod (S'.comap g) := set_like.coe_injective $ set.preimage_prod_map_prod f g _ _ lemma ker_prod_map (f : M →ₗ[R] M₂) (g : M₃ →ₗ[R] M₄) : (linear_map.prod_map f g).ker = submodule.prod f.ker g.ker := begin dsimp only [ker], rw [←prod_map_comap_prod, submodule.prod_bot], end section map_mul variables {A : Type*} [non_unital_non_assoc_semiring A] [module R A] variables {B : Type*} [non_unital_non_assoc_semiring B] [module R B] lemma inl_map_mul (a₁ a₂ : A) : linear_map.inl R A B (a₁ * a₂) = linear_map.inl R A B a₁ * linear_map.inl R A B a₂ := prod.ext rfl (by simp) lemma inr_map_mul (b₁ b₂ : B) : linear_map.inr R A B (b₁ * b₂) = linear_map.inr R A B b₁ * linear_map.inr R A B b₂ := prod.ext (by simp) rfl end map_mul end linear_map end prod namespace linear_map open submodule variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] [module R M] [module R M₂] [module R M₃] [module R M₄] lemma range_coprod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (f.coprod g).range = f.range ⊔ g.range := submodule.ext $ λ x, by simp [mem_sup] lemma is_compl_range_inl_inr : is_compl (inl R M M₂).range (inr R M M₂).range := begin split, { rintros ⟨_, _⟩ ⟨⟨x, hx⟩, ⟨y, hy⟩⟩, simp only [prod.ext_iff, inl_apply, inr_apply, mem_bot] at hx hy ⊢, exact ⟨hy.1.symm, hx.2.symm⟩ }, { rintros ⟨x, y⟩ -, simp only [mem_sup, mem_range, exists_prop], refine ⟨(x, 0), ⟨x, rfl⟩, (0, y), ⟨y, rfl⟩, _⟩, simp } end lemma sup_range_inl_inr : (inl R M M₂).range ⊔ (inr R M M₂).range = ⊤ := is_compl_range_inl_inr.sup_eq_top lemma disjoint_inl_inr : disjoint (inl R M M₂).range (inr R M M₂).range := by simp [disjoint_def, @eq_comm M 0, @eq_comm M₂ 0] {contextual := tt}; intros; refl theorem map_coprod_prod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (p : submodule R M) (q : submodule R M₂) : map (coprod f g) (p.prod q) = map f p ⊔ map g q := begin refine le_antisymm _ (sup_le (map_le_iff_le_comap.2 _) (map_le_iff_le_comap.2 _)), { rw set_like.le_def, rintro _ ⟨x, ⟨h₁, h₂⟩, rfl⟩, exact mem_sup.2 ⟨_, ⟨_, h₁, rfl⟩, _, ⟨_, h₂, rfl⟩, rfl⟩ }, { exact λ x hx, ⟨(x, 0), by simp [hx]⟩ }, { exact λ x hx, ⟨(0, x), by simp [hx]⟩ } end theorem comap_prod_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) (p : submodule R M₂) (q : submodule R M₃) : comap (prod f g) (p.prod q) = comap f p ⊓ comap g q := submodule.ext $ λ x, iff.rfl theorem prod_eq_inf_comap (p : submodule R M) (q : submodule R M₂) : p.prod q = p.comap (linear_map.fst R M M₂) ⊓ q.comap (linear_map.snd R M M₂) := submodule.ext $ λ x, iff.rfl theorem prod_eq_sup_map (p : submodule R M) (q : submodule R M₂) : p.prod q = p.map (linear_map.inl R M M₂) ⊔ q.map (linear_map.inr R M M₂) := by rw [← map_coprod_prod, coprod_inl_inr, map_id] lemma span_inl_union_inr {s : set M} {t : set M₂} : span R (inl R M M₂ '' s ∪ inr R M M₂ '' t) = (span R s).prod (span R t) := by rw [span_union, prod_eq_sup_map, ← span_image, ← span_image] @[simp] lemma ker_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : ker (prod f g) = ker f ⊓ ker g := by rw [ker, ← prod_bot, comap_prod_prod]; refl lemma range_prod_le (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : range (prod f g) ≤ (range f).prod (range g) := begin simp only [set_like.le_def, prod_apply, mem_range, set_like.mem_coe, mem_prod, exists_imp_distrib], rintro _ x rfl, exact ⟨⟨x, rfl⟩, ⟨x, rfl⟩⟩ end lemma ker_prod_ker_le_ker_coprod {M₂ : Type*} [add_comm_group M₂] [module R M₂] {M₃ : Type*} [add_comm_group M₃] [module R M₃] (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (ker f).prod (ker g) ≤ ker (f.coprod g) := by { rintros ⟨y, z⟩, simp {contextual := tt} } lemma ker_coprod_of_disjoint_range {M₂ : Type*} [add_comm_group M₂] [module R M₂] {M₃ : Type*} [add_comm_group M₃] [module R M₃] (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (hd : disjoint f.range g.range) : ker (f.coprod g) = (ker f).prod (ker g) := begin apply le_antisymm _ (ker_prod_ker_le_ker_coprod f g), rintros ⟨y, z⟩ h, simp only [mem_ker, mem_prod, coprod_apply] at h ⊢, have : f y ∈ f.range ⊓ g.range, { simp only [true_and, mem_range, mem_inf, exists_apply_eq_apply], use -z, rwa [eq_comm, map_neg, ← sub_eq_zero, sub_neg_eq_add] }, rw [hd.eq_bot, mem_bot] at this, rw [this] at h, simpa [this] using h, end end linear_map namespace submodule open linear_map variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] variables [module R M] [module R M₂] lemma sup_eq_range (p q : submodule R M) : p ⊔ q = (p.subtype.coprod q.subtype).range := submodule.ext $ λ x, by simp [submodule.mem_sup, set_like.exists] variables (p : submodule R M) (q : submodule R M₂) @[simp] theorem map_inl : p.map (inl R M M₂) = prod p ⊥ := by { ext ⟨x, y⟩, simp only [and.left_comm, eq_comm, mem_map, prod.mk.inj_iff, inl_apply, mem_bot, exists_eq_left', mem_prod] } @[simp] theorem map_inr : q.map (inr R M M₂) = prod ⊥ q := by ext ⟨x, y⟩; simp [and.left_comm, eq_comm] @[simp] theorem comap_fst : p.comap (fst R M M₂) = prod p ⊤ := by ext ⟨x, y⟩; simp @[simp] theorem comap_snd : q.comap (snd R M M₂) = prod ⊤ q := by ext ⟨x, y⟩; simp @[simp] theorem prod_comap_inl : (prod p q).comap (inl R M M₂) = p := by ext; simp @[simp] theorem prod_comap_inr : (prod p q).comap (inr R M M₂) = q := by ext; simp @[simp] theorem prod_map_fst : (prod p q).map (fst R M M₂) = p := by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ q)] @[simp] theorem prod_map_snd : (prod p q).map (snd R M M₂) = q := by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ p)] @[simp] theorem ker_inl : (inl R M M₂).ker = ⊥ := by rw [ker, ← prod_bot, prod_comap_inl] @[simp] theorem ker_inr : (inr R M M₂).ker = ⊥ := by rw [ker, ← prod_bot, prod_comap_inr] @[simp] theorem range_fst : (fst R M M₂).range = ⊤ := by rw [range_eq_map, ← prod_top, prod_map_fst] @[simp] theorem range_snd : (snd R M M₂).range = ⊤ := by rw [range_eq_map, ← prod_top, prod_map_snd] variables (R M M₂) /-- `M` as a submodule of `M × N`. -/ def fst : submodule R (M × M₂) := (⊥ : submodule R M₂).comap (linear_map.snd R M M₂) /-- `M` as a submodule of `M × N` is isomorphic to `M`. -/ @[simps] def fst_equiv : submodule.fst R M M₂ ≃ₗ[R] M := { to_fun := λ x, x.1.1, inv_fun := λ m, ⟨⟨m, 0⟩, by tidy⟩, map_add' := by simp, map_smul' := by simp, left_inv := by tidy, right_inv := by tidy, } lemma fst_map_fst : (submodule.fst R M M₂).map (linear_map.fst R M M₂) = ⊤ := by tidy lemma fst_map_snd : (submodule.fst R M M₂).map (linear_map.snd R M M₂) = ⊥ := by { tidy, exact 0, } /-- `N` as a submodule of `M × N`. -/ def snd : submodule R (M × M₂) := (⊥ : submodule R M).comap (linear_map.fst R M M₂) /-- `N` as a submodule of `M × N` is isomorphic to `N`. -/ @[simps] def snd_equiv : submodule.snd R M M₂ ≃ₗ[R] M₂ := { to_fun := λ x, x.1.2, inv_fun := λ n, ⟨⟨0, n⟩, by tidy⟩, map_add' := by simp, map_smul' := by simp, left_inv := by tidy, right_inv := by tidy, } lemma snd_map_fst : (submodule.snd R M M₂).map (linear_map.fst R M M₂) = ⊥ := by { tidy, exact 0, } lemma snd_map_snd : (submodule.snd R M M₂).map (linear_map.snd R M M₂) = ⊤ := by tidy lemma fst_sup_snd : submodule.fst R M M₂ ⊔ submodule.snd R M M₂ = ⊤ := begin rw eq_top_iff, rintro ⟨m, n⟩ -, rw [show (m, n) = (m, 0) + (0, n), by simp], apply submodule.add_mem (submodule.fst R M M₂ ⊔ submodule.snd R M M₂), { exact submodule.mem_sup_left (submodule.mem_comap.mpr (by simp)), }, { exact submodule.mem_sup_right (submodule.mem_comap.mpr (by simp)), }, end lemma fst_inf_snd : submodule.fst R M M₂ ⊓ submodule.snd R M M₂ = ⊥ := by tidy end submodule namespace linear_equiv section variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] variables {module_M : module R M} {module_M₂ : module R M₂} variables {module_M₃ : module R M₃} {module_M₄ : module R M₄} variables (e₁ : M ≃ₗ[R] M₂) (e₂ : M₃ ≃ₗ[R] M₄) /-- Product of linear equivalences; the maps come from `equiv.prod_congr`. -/ protected def prod : (M × M₃) ≃ₗ[R] (M₂ × M₄) := { map_add' := λ x y, prod.ext (e₁.map_add _ _) (e₂.map_add _ _), map_smul' := λ c x, prod.ext (e₁.map_smul c _) (e₂.map_smul c _), .. equiv.prod_congr e₁.to_equiv e₂.to_equiv } lemma prod_symm : (e₁.prod e₂).symm = e₁.symm.prod e₂.symm := rfl @[simp] lemma prod_apply (p) : e₁.prod e₂ p = (e₁ p.1, e₂ p.2) := rfl @[simp, norm_cast] lemma coe_prod : (e₁.prod e₂ : (M × M₃) →ₗ[R] (M₂ × M₄)) = (e₁ : M →ₗ[R] M₂).prod_map (e₂ : M₃ →ₗ[R] M₄) := rfl end section variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_group M₄] variables {module_M : module R M} {module_M₂ : module R M₂} variables {module_M₃ : module R M₃} {module_M₄ : module R M₄} variables (e₁ : M ≃ₗ[R] M₂) (e₂ : M₃ ≃ₗ[R] M₄) /-- Equivalence given by a block lower diagonal matrix. `e₁` and `e₂` are diagonal square blocks, and `f` is a rectangular block below the diagonal. -/ protected def skew_prod (f : M →ₗ[R] M₄) : (M × M₃) ≃ₗ[R] M₂ × M₄ := { inv_fun := λ p : M₂ × M₄, (e₁.symm p.1, e₂.symm (p.2 - f (e₁.symm p.1))), left_inv := λ p, by simp, right_inv := λ p, by simp, .. ((e₁ : M →ₗ[R] M₂).comp (linear_map.fst R M M₃)).prod ((e₂ : M₃ →ₗ[R] M₄).comp (linear_map.snd R M M₃) + f.comp (linear_map.fst R M M₃)) } @[simp] lemma skew_prod_apply (f : M →ₗ[R] M₄) (x) : e₁.skew_prod e₂ f x = (e₁ x.1, e₂ x.2 + f x.1) := rfl @[simp] lemma skew_prod_symm_apply (f : M →ₗ[R] M₄) (x) : (e₁.skew_prod e₂ f).symm x = (e₁.symm x.1, e₂.symm (x.2 - f (e₁.symm x.1))) := rfl end end linear_equiv namespace linear_map open submodule variables [ring R] variables [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] /-- If the union of the kernels `ker f` and `ker g` spans the domain, then the range of `prod f g` is equal to the product of `range f` and `range g`. -/ lemma range_prod_eq {f : M →ₗ[R] M₂} {g : M →ₗ[R] M₃} (h : ker f ⊔ ker g = ⊤) : range (prod f g) = (range f).prod (range g) := begin refine le_antisymm (f.range_prod_le g) _, simp only [set_like.le_def, prod_apply, mem_range, set_like.mem_coe, mem_prod, exists_imp_distrib, and_imp, prod.forall], rintros _ _ x rfl y rfl, simp only [prod.mk.inj_iff, ← sub_mem_ker_iff], have : y - x ∈ ker f ⊔ ker g, { simp only [h, mem_top] }, rcases mem_sup.1 this with ⟨x', hx', y', hy', H⟩, refine ⟨x' + x, _, _⟩, { rwa add_sub_cancel }, { rwa [← eq_sub_iff_add_eq.1 H, add_sub_add_right_eq_sub, ← neg_mem_iff, neg_sub, add_sub_cancel'] } end end linear_map namespace linear_map /-! ## Tunnels and tailings Some preliminary work for establishing the strong rank condition for noetherian rings. Given a morphism `f : M × N →ₗ[R] M` which is `i : injective f`, we can find an infinite decreasing `tunnel f i n` of copies of `M` inside `M`, and sitting beside these, an infinite sequence of copies of `N`. We picturesquely name these as `tailing f i n` for each individual copy of `N`, and `tailings f i n` for the supremum of the first `n+1` copies: they are the pieces left behind, sitting inside the tunnel. By construction, each `tailing f i (n+1)` is disjoint from `tailings f i n`; later, when we assume `M` is noetherian, this implies that `N` must be trivial, and establishes the strong rank condition for any left-noetherian ring. -/ section tunnel -- (This doesn't work over a semiring: we need to use that `submodule R M` is a modular lattice, -- which requires cancellation.) variables [ring R] variables {N : Type*} [add_comm_group M] [module R M] [add_comm_group N] [module R N] open function /-- An auxiliary construction for `tunnel`. The composition of `f`, followed by the isomorphism back to `K`, followed by the inclusion of this submodule back into `M`. -/ def tunnel_aux (f : M × N →ₗ[R] M) (Kφ : Σ K : submodule R M, K ≃ₗ[R] M) : M × N →ₗ[R] M := (Kφ.1.subtype.comp Kφ.2.symm.to_linear_map).comp f lemma tunnel_aux_injective (f : M × N →ₗ[R] M) (i : injective f) (Kφ : Σ K : submodule R M, K ≃ₗ[R] M) : injective (tunnel_aux f Kφ) := (subtype.val_injective.comp Kφ.2.symm.injective).comp i noncomputable theory /-- Auxiliary definition for `tunnel`. -/ -- Even though we have `noncomputable theory`, -- we get an error without another `noncomputable` here. noncomputable def tunnel' (f : M × N →ₗ[R] M) (i : injective f) : ℕ → Σ (K : submodule R M), K ≃ₗ[R] M | 0 := ⟨⊤, linear_equiv.of_top ⊤ rfl⟩ | (n+1) := ⟨(submodule.fst R M N).map (tunnel_aux f (tunnel' n)), ((submodule.fst R M N).equiv_map_of_injective _ (tunnel_aux_injective f i (tunnel' n))).symm.trans (submodule.fst_equiv R M N)⟩ /-- Give an injective map `f : M × N →ₗ[R] M` we can find a nested sequence of submodules all isomorphic to `M`. -/ def tunnel (f : M × N →ₗ[R] M) (i : injective f) : ℕ →ₘ order_dual (submodule R M) := ⟨λ n, (tunnel' f i n).1, monotone_of_monotone_nat (λ n, begin dsimp [tunnel', tunnel_aux], rw [submodule.map_comp, submodule.map_comp], apply submodule.map_subtype_le, end)⟩ /-- Give an injective map `f : M × N →ₗ[R] M` we can find a sequence of submodules all isomorphic to `N`. -/ def tailing (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : submodule R M := (submodule.snd R M N).map (tunnel_aux f (tunnel' f i n)) /-- Each `tailing f i n` is a copy of `N`. -/ def tailing_linear_equiv (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : tailing f i n ≃ₗ[R] N := ((submodule.snd R M N).equiv_map_of_injective _ (tunnel_aux_injective f i (tunnel' f i n))).symm.trans (submodule.snd_equiv R M N) lemma tailing_le_tunnel (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : tailing f i n ≤ tunnel f i n := begin dsimp [tailing, tunnel_aux], rw [submodule.map_comp, submodule.map_comp], apply submodule.map_subtype_le, end lemma tailing_disjoint_tunnel_succ (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : disjoint (tailing f i n) (tunnel f i (n+1)) := begin rw disjoint_iff, dsimp [tailing, tunnel, tunnel'], rw [submodule.map_inf_eq_map_inf_comap, submodule.comap_map_eq_of_injective (tunnel_aux_injective _ i _), inf_comm, submodule.fst_inf_snd, submodule.map_bot], end lemma tailing_sup_tunnel_succ_le_tunnel (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : tailing f i n ⊔ tunnel f i (n+1) ≤ tunnel f i n := begin dsimp [tailing, tunnel, tunnel', tunnel_aux], rw [←submodule.map_sup, sup_comm, submodule.fst_sup_snd, submodule.map_comp, submodule.map_comp], apply submodule.map_subtype_le, end /-- The supremum of all the copies of `N` found inside the tunnel. -/ def tailings (f : M × N →ₗ[R] M) (i : injective f) : ℕ → submodule R M := partial_sups (tailing f i) @[simp] lemma tailings_zero (f : M × N →ₗ[R] M) (i : injective f) : tailings f i 0 = tailing f i 0 := by simp [tailings] @[simp] lemma tailings_succ (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : tailings f i (n+1) = tailings f i n ⊔ tailing f i (n+1) := by simp [tailings] lemma tailings_disjoint_tunnel (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : disjoint (tailings f i n) (tunnel f i (n+1)) := begin induction n with n ih, { simp only [tailings_zero], apply tailing_disjoint_tunnel_succ, }, { simp only [tailings_succ], refine disjoint.disjoint_sup_left_of_disjoint_sup_right _ _, apply tailing_disjoint_tunnel_succ, apply disjoint.mono_right _ ih, apply tailing_sup_tunnel_succ_le_tunnel, }, end lemma tailings_disjoint_tailing (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : disjoint (tailings f i n) (tailing f i (n+1)) := disjoint.mono_right (tailing_le_tunnel f i _) (tailings_disjoint_tunnel f i _) end tunnel end linear_map
d89375531e11233302fa3d53a5b689a2c9b4d29e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/category/Mon/basic.lean
e83789a6b8d17978588a74846f59572747881aa6
[ "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
8,116
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.concrete_category.bundled_hom import algebra.punit_instances import category_theory.functor.reflects_isomorphisms /-! # Category instances for monoid, add_monoid, comm_monoid, and add_comm_monoid. We introduce the bundled categories: * `Mon` * `AddMon` * `CommMon` * `AddCommMon` along with the relevant forgetful functors between them. -/ universes u v open category_theory /-- The category of monoids and monoid morphisms. -/ @[to_additive AddMon] def Mon : Type (u+1) := bundled monoid /-- The category of additive monoids and monoid morphisms. -/ add_decl_doc AddMon namespace Mon /-- `monoid_hom` doesn't actually assume associativity. This alias is needed to make the category theory machinery work. -/ @[to_additive "`add_monoid_hom` doesn't actually assume associativity. This alias is needed to make the category theory machinery work."] abbreviation assoc_monoid_hom (M N : Type*) [monoid M] [monoid N] := monoid_hom M N @[to_additive] instance bundled_hom : bundled_hom assoc_monoid_hom := ⟨λ M N [monoid M] [monoid N], by exactI @monoid_hom.to_fun M N _ _, λ M [monoid M], by exactI @monoid_hom.id M _, λ M N P [monoid M] [monoid N] [monoid P], by exactI @monoid_hom.comp M N P _ _ _, λ M N [monoid M] [monoid N], by exactI @monoid_hom.coe_inj M N _ _⟩ attribute [derive [large_category, concrete_category]] Mon attribute [to_additive] Mon.large_category Mon.concrete_category @[to_additive] instance : has_coe_to_sort Mon Type* := bundled.has_coe_to_sort /-- Construct a bundled `Mon` from the underlying type and typeclass. -/ @[to_additive] def of (M : Type u) [monoid M] : Mon := bundled.of M /-- Construct a bundled `Mon` from the underlying type and typeclass. -/ add_decl_doc AddMon.of /-- Typecheck a `monoid_hom` as a morphism in `Mon`. -/ @[to_additive] def of_hom {X Y : Type u} [monoid X] [monoid Y] (f : X →* Y) : of X ⟶ of Y := f /-- Typecheck a `add_monoid_hom` as a morphism in `AddMon`. -/ add_decl_doc AddMon.of_hom @[simp] lemma of_hom_apply {X Y : Type u} [monoid X] [monoid Y] (f : X →* Y) (x : X) : of_hom f x = f x := rfl @[to_additive] instance : inhabited Mon := -- The default instance for `monoid punit` is derived via `punit.comm_ring`, -- which breaks to_additive. ⟨@of punit $ @group.to_monoid _ $ @comm_group.to_group _ punit.comm_group⟩ @[to_additive] instance (M : Mon) : monoid M := M.str @[simp, to_additive] lemma coe_of (R : Type u) [monoid R] : (Mon.of R : Type u) = R := rfl end Mon /-- The category of commutative monoids and monoid morphisms. -/ @[to_additive AddCommMon] def CommMon : Type (u+1) := bundled comm_monoid /-- The category of additive commutative monoids and monoid morphisms. -/ add_decl_doc AddCommMon namespace CommMon @[to_additive] instance : bundled_hom.parent_projection comm_monoid.to_monoid := ⟨⟩ attribute [derive [large_category, concrete_category]] CommMon attribute [to_additive] CommMon.large_category CommMon.concrete_category @[to_additive] instance : has_coe_to_sort CommMon Type* := bundled.has_coe_to_sort /-- Construct a bundled `CommMon` from the underlying type and typeclass. -/ @[to_additive] def of (M : Type u) [comm_monoid M] : CommMon := bundled.of M /-- Construct a bundled `AddCommMon` from the underlying type and typeclass. -/ add_decl_doc AddCommMon.of @[to_additive] instance : inhabited CommMon := -- The default instance for `comm_monoid punit` is derived via `punit.comm_ring`, -- which breaks to_additive. ⟨@of punit $ @comm_group.to_comm_monoid _ punit.comm_group⟩ @[to_additive] instance (M : CommMon) : comm_monoid M := M.str @[simp, to_additive] lemma coe_of (R : Type u) [comm_monoid R] : (CommMon.of R : Type u) = R := rfl @[to_additive has_forget_to_AddMon] instance has_forget_to_Mon : has_forget₂ CommMon Mon := bundled_hom.forget₂ _ _ @[to_additive] instance : has_coe CommMon.{u} Mon.{u} := { coe := (forget₂ CommMon Mon).obj, } end CommMon -- We verify that the coercions of morphisms to functions work correctly: example {R S : Mon} (f : R ⟶ S) : (R : Type) → (S : Type) := f example {R S : CommMon} (f : R ⟶ S) : (R : Type) → (S : Type) := f -- We verify that when constructing a morphism in `CommMon`, -- when we construct the `to_fun` field, the types are presented as `↥R`, -- rather than `R.α` or (as we used to have) `↥(bundled.map comm_monoid.to_monoid R)`. example (R : CommMon.{u}) : R ⟶ R := { to_fun := λ x, begin match_target (R : Type u), match_hyp x : (R : Type u), exact x * x end , map_one' := by simp, map_mul' := λ x y, begin rw [mul_assoc x y (x * y), ←mul_assoc y x y, mul_comm y x, mul_assoc, mul_assoc], end, } variables {X Y : Type u} section variables [monoid X] [monoid Y] /-- Build an isomorphism in the category `Mon` from a `mul_equiv` between `monoid`s. -/ @[to_additive add_equiv.to_AddMon_iso "Build an isomorphism in the category `AddMon` from an `add_equiv` between `add_monoid`s.", simps] def mul_equiv.to_Mon_iso (e : X ≃* Y) : Mon.of X ≅ Mon.of Y := { hom := e.to_monoid_hom, inv := e.symm.to_monoid_hom } end section variables [comm_monoid X] [comm_monoid Y] /-- Build an isomorphism in the category `CommMon` from a `mul_equiv` between `comm_monoid`s. -/ @[to_additive add_equiv.to_AddCommMon_iso "Build an isomorphism in the category `AddCommMon` from an `add_equiv` between `add_comm_monoid`s.", simps] def mul_equiv.to_CommMon_iso (e : X ≃* Y) : CommMon.of X ≅ CommMon.of Y := { hom := e.to_monoid_hom, inv := e.symm.to_monoid_hom } end namespace category_theory.iso /-- Build a `mul_equiv` from an isomorphism in the category `Mon`. -/ @[to_additive AddMon_iso_to_add_equiv "Build an `add_equiv` from an isomorphism in the category `AddMon`."] def Mon_iso_to_mul_equiv {X Y : Mon} (i : X ≅ Y) : X ≃* Y := i.hom.to_mul_equiv i.inv i.hom_inv_id i.inv_hom_id /-- Build a `mul_equiv` from an isomorphism in the category `CommMon`. -/ @[to_additive "Build an `add_equiv` from an isomorphism in the category `AddCommMon`."] def CommMon_iso_to_mul_equiv {X Y : CommMon} (i : X ≅ Y) : X ≃* Y := i.hom.to_mul_equiv i.inv i.hom_inv_id i.inv_hom_id end category_theory.iso /-- multiplicative equivalences between `monoid`s are the same as (isomorphic to) isomorphisms in `Mon` -/ @[to_additive add_equiv_iso_AddMon_iso "additive equivalences between `add_monoid`s are the same as (isomorphic to) isomorphisms in `AddMon`"] def mul_equiv_iso_Mon_iso {X Y : Type u} [monoid X] [monoid Y] : (X ≃* Y) ≅ (Mon.of X ≅ Mon.of Y) := { hom := λ e, e.to_Mon_iso, inv := λ i, i.Mon_iso_to_mul_equiv, } /-- multiplicative equivalences between `comm_monoid`s are the same as (isomorphic to) isomorphisms in `CommMon` -/ @[to_additive add_equiv_iso_AddCommMon_iso "additive equivalences between `add_comm_monoid`s are the same as (isomorphic to) isomorphisms in `AddCommMon`"] def mul_equiv_iso_CommMon_iso {X Y : Type u} [comm_monoid X] [comm_monoid Y] : (X ≃* Y) ≅ (CommMon.of X ≅ CommMon.of Y) := { hom := λ e, e.to_CommMon_iso, inv := λ i, i.CommMon_iso_to_mul_equiv, } @[to_additive] instance Mon.forget_reflects_isos : reflects_isomorphisms (forget Mon.{u}) := { reflects := λ X Y f _, begin resetI, let i := as_iso ((forget Mon).map f), let e : X ≃* Y := { ..f, ..i.to_equiv }, exact ⟨(is_iso.of_iso e.to_Mon_iso).1⟩, end } @[to_additive] instance CommMon.forget_reflects_isos : reflects_isomorphisms (forget CommMon.{u}) := { reflects := λ X Y f _, begin resetI, let i := as_iso ((forget CommMon).map f), let e : X ≃* Y := { ..f, ..i.to_equiv }, exact ⟨(is_iso.of_iso e.to_CommMon_iso).1⟩, end } /-! Once we've shown that the forgetful functors to type reflect isomorphisms, we automatically obtain that the `forget₂` functors between our concrete categories reflect isomorphisms. -/ example : reflects_isomorphisms (forget₂ CommMon Mon) := by apply_instance
d86fe98489c293eb5a6a5beb1ef7729ddd77206b
0c1546a496eccfb56620165cad015f88d56190c5
/tests/lean/run/cc_ac3.lean
92ca32f0e41dcdb86dc7220f295e4d3060335a27
[ "Apache-2.0" ]
permissive
Solertis/lean
491e0939957486f664498fbfb02546e042699958
84188c5aa1673fdf37a082b2de8562dddf53df3f
refs/heads/master
1,610,174,257,606
1,486,263,620,000
1,486,263,620,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,130
lean
open tactic example (a b c d e : nat) (f : nat → nat → nat) : b + a = d → b + c = e → f (a + b + c) (a + b + c) = f (c + d) (a + e) := by cc example (a b c d e : nat) (f : nat → nat → nat) : b + a = d + d → b + c = e + e → f (a + b + c) (a + b + c) = f (c + d + d) (e + a + e) := by cc section universe variable u variables {α : Type u} variable [comm_semiring α] example (a b c d e : α) (f : α → α → α) : b + a = d + d → b + c = e + e → f (a + b + c) (a + b + c) = f (c + d + d) (e + a + e) := by cc end section universe variable u variables {α : Type u} variable [comm_ring α] example (a b c d e : α) (f : α → α → α) : b + a = d + d → b + c = e + e → f (a + b + c) (a + b + c) = f (c + d + d) (e + a + e) := by cc end section universe variable u variables {α : Type u} variables op : α → α → α variables [is_associative α op] variables [is_commutative α op] def ex (a b c d e : α) (f : α → α → α) : op b a = op d d → op b c = op e e → f (op a (op b c)) (op (op a b) c) = f (op (op c d) d) (op e (op a e)) := by cc end
eaa1fb30ee85fd55d9855ab273cb170ad51a7347
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/order/category/omega_complete_partial_order.lean
30da47bdd12b95344e9568d103e16198089ca18c
[ "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,286
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 order.omega_complete_partial_order import order.category.Preorder /-! # Category of types with a omega complete partial order In this file, we bundle the class `omega_complete_partial_order` into a concrete category and prove that continuous functions also form a `omega_complete_partial_order`. ## Main definitions * `ωCPO` * an instance of `category` and `concrete_category` -/ open category_theory universes u v /-- The category of types with a omega complete partial order. -/ def ωCPO := bundled omega_complete_partial_order namespace ωCPO open omega_complete_partial_order instance : bundled_hom @continuous_hom := { to_fun := @continuous_hom.to_fun, id := @continuous_hom.id, comp := @continuous_hom.comp, hom_ext := @continuous_hom.coe_inj } attribute [derive [has_coe_to_sort, large_category, concrete_category]] ωCPO /-- Construct a bundled ωCPO from the underlying type and typeclass. -/ def of (α : Type*) [omega_complete_partial_order α] : ωCPO := bundled.of α instance : inhabited ωCPO := ⟨of punit⟩ instance (α : ωCPO) : omega_complete_partial_order α := α.str end ωCPO
1d39a27351c73203248c3fc79ca5ce2ff132fd9a
5ee26964f602030578ef0159d46145dd2e357ba5
/src/valuation_spectrum.lean
f8c4fd9d77a7eff82edbaa1c54f494b2d28b30ae
[ "Apache-2.0" ]
permissive
fpvandoorn/lean-perfectoid-spaces
569b4006fdfe491ca8b58dd817bb56138ada761f
06cec51438b168837fc6e9268945735037fd1db6
refs/heads/master
1,590,154,571,918
1,557,685,392,000
1,557,685,392,000
186,363,547
0
0
Apache-2.0
1,557,730,933,000
1,557,730,933,000
null
UTF-8
Lean
false
false
6,177
lean
import topology.order import group_theory.quotient_group import valuation.canonical /- Valuation Spectrum (Spv) The API for the valuation spectrum of a commutative ring. Normally defined as "the equivalence classes of valuations", there are set-theoretic issues. These issues are easily solved by noting that two valuations are equivalent if and only if they induce the same preorder on R, where the preorder attacted to a valuation sends (r,s) to v r ≤ v s. Our definition of Spv is currently the predicates which come from a valuation. There is another approach though: Prop 2.20 (p16) of https://homepages.uni-regensburg.de/~maf55605/contin_valuation.pdf classifies the relations which come from valuations as those satisfying some axioms. See also Wedhorn 4.7. TODO(jmc): This observation is also somewhere in Huber. But I currently don't have the paper at hand. Here's why such a theorem must exist: given a relation coming from a valuation, we can reconstruct the support of the valuation (v r ≤ v 0), the relation on R / support coming from `on_quot v`, the relation on Frac(R/supp) coming from `on_frac v`, the things of valuation 1 in this field, and hence the value group of the valuation. The induced canonical valuation is a valuation we seek. This argument only uses a finite number of facts about the inequality, and so the theorem is that an inequality comes from a valuation if and only if these facts are satisfied. -/ universes u u₀ u₁ u₂ u₃ /-- Valuation spectrum of a ring. -/ -- Note that the valuation takes values in a group in the same universe as R. -- This is to avoid "set-theoretic issues". definition Spv (R : Type u₀) [comm_ring R] := {ineq : R → R → Prop // ∃ {Γ₀ : Type u₀} [linear_ordered_comm_group Γ₀], by exactI ∃ (v : valuation R Γ₀), ∀ r s : R, v r ≤ v s ↔ ineq r s} variables {R : Type u₀} [comm_ring R] {v : Spv R} local notation r `≤[`v`]` s := v.1 r s /- Spv R is morally a quotient, so we start by giving it a quotient-like interface -/ namespace Spv open valuation variables {Γ : Type u} [linear_ordered_comm_group Γ] variables {Γ₁ : Type u₁} [linear_ordered_comm_group Γ₁] variables {Γ₂ : Type u₂} [linear_ordered_comm_group Γ₂] -- The work is embedded here with `canonical_valuation_is_equiv v` etc. -- The canonical valuation attached to v lives in R's universe. /-- The constructor for a term of type Spv R given an arbitrary valuation -/ definition mk (v : valuation R Γ) : Spv R := ⟨λ r s, v r ≤ v s, ⟨value_group v, by apply_instance, canonical_valuation v, canonical_valuation_is_equiv v⟩⟩ @[simp] lemma mk_val (v : valuation R Γ) : (mk v).val = λ r s, v r ≤ v s := rfl /-- The value group attached to a term of type Spv R -/ definition out_Γ (v : Spv R) : Type u₀ := classical.some v.2 noncomputable instance (v : Spv R) : linear_ordered_comm_group (out_Γ v) := classical.some $ classical.some_spec v.2 /-- An explicit valuation attached to a term of type Spv R -/ noncomputable definition out (v : Spv R) : valuation R (out_Γ v) := classical.some $ classical.some_spec $ classical.some_spec v.2 @[simp] lemma mk_out {v : Spv R} : mk (out v) = v := begin rcases v with ⟨ineq, hv⟩, rw subtype.ext, ext, exact classical.some_spec (classical.some_spec (classical.some_spec hv)) _ _, end lemma out_mk (v : valuation R Γ) : (out (mk v)).is_equiv v := classical.some_spec (classical.some_spec (classical.some_spec (mk v).2)) noncomputable def lift {X} (f : Π ⦃Γ₀ : Type u₀⦄ [linear_ordered_comm_group Γ₀], valuation R Γ₀ → X) (v : Spv R) : X := f (out v) /-- The computation principle for Spv -/ theorem lift_eq {X} (f₀ : Π ⦃Γ₀ : Type u₀⦄ [linear_ordered_comm_group Γ₀], valuation R Γ₀ → X) (f : Π ⦃Γ : Type u⦄ [linear_ordered_comm_group Γ], valuation R Γ → X) (v : valuation R Γ) (h : ∀ ⦃Γ₀ : Type u₀⦄ [linear_ordered_comm_group Γ₀] (v₀ : valuation R Γ₀), v₀.is_equiv v → f₀ v₀ = f v) : lift f₀ (mk v) = f v := h _ (out_mk v) /-- Prop-valued version of computation principle for Spv -/ theorem lift_eq' (f₀ : Π ⦃Γ₀ : Type u₀⦄ [linear_ordered_comm_group Γ₀], valuation R Γ₀ → Prop) (f : Π ⦃Γ : Type u⦄ [linear_ordered_comm_group Γ], valuation R Γ → Prop) (v : valuation R Γ) (h : ∀ ⦃Γ₀ : Type u₀⦄ [linear_ordered_comm_group Γ₀] (v₀ : valuation R Γ₀), v₀.is_equiv v → (f₀ v₀ ↔ f v)) : lift f₀ (mk v) ↔ f v := h _ (out_mk v) lemma exists_rep (v : Spv R) : ∃ {Γ₀ : Type u₀} [linear_ordered_comm_group Γ₀], by exactI ∃ (v₀ : valuation R Γ₀), mk v₀ = v := ⟨out_Γ v, infer_instance, out v, mk_out⟩ lemma sound {v₁ : valuation R Γ₁} {v₂ : valuation R Γ₂} (h : v₁.is_equiv v₂) : mk v₁ = mk v₂ := begin apply subtype.val_injective, ext r s, apply h, end lemma is_equiv_of_eq_mk {v₁ : valuation R Γ₁} {v₂ : valuation R Γ₂} (h : mk v₁ = mk v₂) : v₁.is_equiv v₂ := begin intros r s, have := congr_arg subtype.val h, replace := congr this (rfl : r = r), replace := congr this (rfl : s = s), simp at this, simp [this], end noncomputable instance : has_coe_to_fun (Spv R) := { F := λ v, R → with_zero (out_Γ v), coe := λ v, ((out v) : R → with_zero (out_Γ v)) } section @[simp] lemma map_zero : v 0 = 0 := valuation.map_zero _ @[simp] lemma map_one : v 1 = 1 := valuation.map_one _ @[simp] lemma map_mul : ∀ x y, v (x * y) = v x * v y := valuation.map_mul _ @[simp] lemma map_add : ∀ x y, v (x + y) ≤ v x ∨ v (x + y) ≤ v y := valuation.map_add _ end /-- The open sets generating the topology of Spv R, see Wedhorn 4.1.-/ definition basic_open (r s : R) : set (Spv R) := {v | v r ≤ v s ∧ v s ≠ 0} instance : topological_space (Spv R) := topological_space.generate_from {U : set (Spv R) | ∃ r s : R, U = basic_open r s} lemma mk_mem_basic_open {r s : R} (v : valuation R Γ) : mk v ∈ basic_open r s ↔ v r ≤ v s ∧ v s ≠ 0 := begin apply and_congr, { apply out_mk, }, { apply (out_mk v).ne_zero, }, end end Spv
d617a012d02249042dc0f4d693e70e9aabba9f55
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/src/Lean/Parser/Command.lean
cae90eecf85c8e5e875420f84ca1cf98744f0db5
[ "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
7,160
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, Sebastian Ullrich -/ import Lean.Parser.Term import Lean.Parser.Do namespace Lean namespace Parser /-- Syntax quotation for terms and (lists of) commands. We prefer terms, so ambiguous quotations like `($x $y) will be parsed as an application, not two commands. Use `($x:command $y:command) instead. Multiple command will be put in a `null node, but a single command will not (so that you can directly match against a quotation in a command kind's elaborator). -/ -- TODO: use two separate quotation parsers with parser priorities instead @[builtinTermParser] def Term.quot := parser! "`(" >> toggleInsideQuot (termParser <|> many1Unbox commandParser) >> ")" namespace Command def commentBody : Parser := { fn := rawFn (finishCommentBlock 1) true } @[combinatorParenthesizer Lean.Parser.Command.commentBody] def commentBody.parenthesizer := PrettyPrinter.Parenthesizer.visitToken @[combinatorFormatter Lean.Parser.Command.commentBody] def commentBody.formatter := PrettyPrinter.Formatter.visitAtom Name.anonymous def docComment := parser! ppDedent $ "/--" >> commentBody >> ppLine def «private» := parser! "private " def «protected» := parser! "protected " def visibility := «private» <|> «protected» def «noncomputable» := parser! "noncomputable " def «unsafe» := parser! "unsafe " def «partial» := parser! "partial " def declModifiers (inline : Bool) := parser! optional docComment >> optional (Term.«attributes» >> if inline then skip else ppDedent ppLine) >> optional visibility >> optional «noncomputable» >> optional «unsafe» >> optional «partial» def declId := parser! ident >> optional (".{" >> sepBy1 ident ", " >> "}") def declSig := parser! many (ppSpace >> Term.bracketedBinder) >> Term.typeSpec def optDeclSig := parser! many (ppSpace >> Term.bracketedBinder) >> Term.optType def declValSimple := parser! " :=\n" >> termParser def declValEqns := parser! Term.matchAlts false def declVal := declValSimple <|> declValEqns def «abbrev» := parser! "abbrev " >> declId >> optDeclSig >> declVal def «def» := parser! "def " >> declId >> optDeclSig >> declVal def «theorem» := parser! "theorem " >> declId >> declSig >> declVal def «constant» := parser! "constant " >> declId >> declSig >> optional declValSimple def «instance» := parser! "instance " >> optional declId >> declSig >> declVal def «axiom» := parser! "axiom " >> declId >> declSig def «example» := parser! "example " >> declSig >> declVal def inferMod := parser! «try» ("{" >> "}") def ctor := parser! "\n| " >> declModifiers true >> ident >> optional inferMod >> optDeclSig def «inductive» := parser! "inductive " >> declId >> optDeclSig >> many ctor def classInductive := parser! «try» ("class " >> "inductive ") >> declId >> optDeclSig >> many ctor def structExplicitBinder := parser! «try» (declModifiers true >> "(") >> many1 ident >> optional inferMod >> optDeclSig >> optional Term.binderDefault >> ")" def structImplicitBinder := parser! «try» (declModifiers true >> "{") >> many1 ident >> optional inferMod >> declSig >> "}" def structInstBinder := parser! «try» (declModifiers true >> "[") >> many1 ident >> optional inferMod >> declSig >> "]" def structFields := parser! many (ppLine >> (structExplicitBinder <|> structImplicitBinder <|> structInstBinder)) def structCtor := parser! «try» (declModifiers true >> ident >> optional inferMod >> " :: ") def structureTk := parser! "structure " def classTk := parser! "class " def «extends» := parser! " extends " >> sepBy1 termParser ", " def «structure» := parser! (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional «extends» >> Term.optType >> optional (" := " >> optional structCtor >> structFields) @[builtinCommandParser] def declaration := parser! declModifiers false >> («abbrev» <|> «def» <|> «theorem» <|> «constant» <|> «instance» <|> «axiom» <|> «example» <|> «inductive» <|> classInductive <|> «structure») @[builtinCommandParser] def «section» := parser! "section " >> optional ident @[builtinCommandParser] def «namespace» := parser! "namespace " >> ident @[builtinCommandParser] def «end» := parser! "end " >> optional ident @[builtinCommandParser] def «variable» := parser! "variable" >> Term.bracketedBinder @[builtinCommandParser] def «variables» := parser! "variables" >> many1 Term.bracketedBinder @[builtinCommandParser] def «universe» := parser! "universe " >> ident @[builtinCommandParser] def «universes» := parser! "universes " >> many1 ident @[builtinCommandParser] def check := parser! "#check " >> termParser @[builtinCommandParser] def check_failure := parser! "#check_failure " >> termParser -- Like `#check`, but succeeds only if term does not type check @[builtinCommandParser] def eval := parser! "#eval " >> termParser @[builtinCommandParser] def synth := parser! "#synth " >> termParser @[builtinCommandParser] def exit := parser! "#exit" @[builtinCommandParser] def print := parser! "#print " >> (ident <|> strLit) @[builtinCommandParser] def printAxioms := parser! "#print " >> nonReservedSymbol "axioms " >> ident @[builtinCommandParser] def «resolve_name» := parser! "#resolve_name " >> ident @[builtinCommandParser] def «init_quot» := parser! "init_quot" @[builtinCommandParser] def «set_option» := parser! "set_option " >> ident >> (nonReservedSymbol "true" <|> nonReservedSymbol "false" <|> strLit <|> numLit) @[builtinCommandParser] def «attribute» := parser! optional "local " >> "attribute " >> "[" >> sepBy1 Term.attrInstance ", " >> "] " >> many1 ident @[builtinCommandParser] def «export» := parser! "export " >> ident >> "(" >> many1 ident >> ")" def openHiding := parser! «try» (ident >> "hiding") >> many1 ident def openRenamingItem := parser! ident >> unicodeSymbol "→" "->" >> ident def openRenaming := parser! «try» (ident >> "renaming") >> sepBy1 openRenamingItem ", " def openOnly := parser! «try» (ident >> "(") >> many1 ident >> ")" def openSimple := parser! many1 ident @[builtinCommandParser] def «open» := parser! "open " >> (openHiding <|> openRenaming <|> openOnly <|> openSimple) @[builtinCommandParser] def «mutual» := parser! "mutual " >> many1 (notSymbol "end" >> commandParser) >> "end" @[builtinCommandParser] def «initialize» := parser! "initialize " >> optional («try» (ident >> Term.typeSpec >> Term.leftArrow)) >> Term.doSeq @[builtinCommandParser] def «builtin_initialize» := parser! "builtin_initialize " >> optional («try» (ident >> Term.typeSpec >> Term.leftArrow)) >> Term.doSeq @[builtinCommandParser] def «in» := tparser! " in " >> commandParser end Command end Parser end Lean
3f3cadc500b44cd1d2cc2f27ed56cacd86208db0
82e44445c70db0f03e30d7be725775f122d72f3e
/src/algebra/group/units.lean
b4f1829170d4065c2b9a1ab18bd3cd6c03aa72ce
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
14,569
lean
/- Copyright (c) 2017 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johannes Hölzl, Chris Hughes, Jens Wagemaker -/ import algebra.group.basic import logic.nontrivial /-! # Units (i.e., invertible elements) of a multiplicative monoid -/ universe u variable {α : Type u} /-- Units of a monoid, bundled version. An element of a `monoid` is a unit if it has a two-sided inverse. This version bundles the inverse element so that it can be computed. For a predicate see `is_unit`. -/ structure units (α : Type u) [monoid α] := (val : α) (inv : α) (val_inv : val * inv = 1) (inv_val : inv * val = 1) /-- Units of an add_monoid, bundled version. An element of an add_monoid is a unit if it has a two-sided additive inverse. This version bundles the inverse element so that it can be computed. For a predicate see `is_add_unit`. -/ structure add_units (α : Type u) [add_monoid α] := (val : α) (neg : α) (val_neg : val + neg = 0) (neg_val : neg + val = 0) attribute [to_additive add_units] units namespace units variables [monoid α] @[to_additive] instance : has_coe (units α) α := ⟨val⟩ @[to_additive] instance : has_inv (units α) := ⟨λ u, ⟨u.2, u.1, u.4, u.3⟩⟩ /-- See Note [custom simps projection] -/ @[to_additive /-" See Note [custom simps projection] "-/] def simps.coe (u : units α) : α := u /-- See Note [custom simps projection] -/ @[to_additive /-" See Note [custom simps projection] "-/] def simps.coe_inv (u : units α) : α := ↑(u⁻¹) initialize_simps_projections units (val → coe as_prefix, inv → coe_inv as_prefix) initialize_simps_projections add_units (val → coe as_prefix, neg → coe_neg as_prefix) @[simp, to_additive] lemma coe_mk (a : α) (b h₁ h₂) : ↑(units.mk a b h₁ h₂) = a := rfl @[ext, to_additive] theorem ext : function.injective (coe : units α → α) | ⟨v, i₁, vi₁, iv₁⟩ ⟨v', i₂, vi₂, iv₂⟩ e := by change v = v' at e; subst v'; congr; simpa only [iv₂, vi₁, one_mul, mul_one] using mul_assoc i₂ v i₁ @[norm_cast, to_additive] theorem eq_iff {a b : units α} : (a : α) = b ↔ a = b := ext.eq_iff @[to_additive] theorem ext_iff {a b : units α} : a = b ↔ (a : α) = b := eq_iff.symm @[to_additive] instance [decidable_eq α] : decidable_eq (units α) := λ a b, decidable_of_iff' _ ext_iff @[simp, to_additive] theorem mk_coe (u : units α) (y h₁ h₂) : mk (u : α) y h₁ h₂ = u := ext rfl /-- Copy a unit, adjusting definition equalities. -/ @[to_additive /-"Copy an `add_unit`, adjusting definitional equalities."-/, simps] def copy (u : units α) (val : α) (hv : val = u) (inv : α) (hi : inv = ↑(u⁻¹)) : units α := { val := val, inv := inv, inv_val := hv.symm ▸ hi.symm ▸ u.inv_val, val_inv := hv.symm ▸ hi.symm ▸ u.val_inv } @[to_additive] lemma copy_eq (u : units α) (val hv inv hi) : u.copy val hv inv hi = u := ext hv /-- Units of a monoid form a group. -/ @[to_additive] instance : group (units α) := { mul := λ u₁ u₂, ⟨u₁.val * u₂.val, u₂.inv * u₁.inv, by rw [mul_assoc, ← mul_assoc u₂.val, val_inv, one_mul, val_inv], by rw [mul_assoc, ← mul_assoc u₁.inv, inv_val, one_mul, inv_val]⟩, one := ⟨1, 1, one_mul 1, one_mul 1⟩, mul_one := λ u, ext $ mul_one u, one_mul := λ u, ext $ one_mul u, mul_assoc := λ u₁ u₂ u₃, ext $ mul_assoc u₁ u₂ u₃, inv := has_inv.inv, mul_left_inv := λ u, ext u.inv_val } variables (a b : units α) {c : units α} @[simp, norm_cast, to_additive] lemma coe_mul : (↑(a * b) : α) = a * b := rfl attribute [norm_cast] add_units.coe_add @[simp, norm_cast, to_additive] lemma coe_one : ((1 : units α) : α) = 1 := rfl attribute [norm_cast] add_units.coe_zero @[simp, norm_cast, to_additive] lemma coe_eq_one {a : units α} : (a : α) = 1 ↔ a = 1 := by rw [←units.coe_one, eq_iff] @[simp, to_additive] lemma inv_mk (x y : α) (h₁ h₂) : (mk x y h₁ h₂)⁻¹ = mk y x h₂ h₁ := rfl @[to_additive] lemma val_coe : (↑a : α) = a.val := rfl @[norm_cast, to_additive] lemma coe_inv'' : ((a⁻¹ : units α) : α) = a.inv := rfl attribute [norm_cast] add_units.coe_neg'' @[simp, to_additive] lemma inv_mul : (↑a⁻¹ * a : α) = 1 := inv_val _ @[simp, to_additive] lemma mul_inv : (a * ↑a⁻¹ : α) = 1 := val_inv _ @[to_additive] lemma inv_mul_of_eq {u : units α} {a : α} (h : ↑u = a) : ↑u⁻¹ * a = 1 := by { rw [←h, u.inv_mul], } @[to_additive] lemma mul_inv_of_eq {u : units α} {a : α} (h : ↑u = a) : a * ↑u⁻¹ = 1 := by { rw [←h, u.mul_inv], } @[simp, to_additive] lemma mul_inv_cancel_left (a : units α) (b : α) : (a:α) * (↑a⁻¹ * b) = b := by rw [← mul_assoc, mul_inv, one_mul] @[simp, to_additive] lemma inv_mul_cancel_left (a : units α) (b : α) : (↑a⁻¹:α) * (a * b) = b := by rw [← mul_assoc, inv_mul, one_mul] @[simp, to_additive] lemma mul_inv_cancel_right (a : α) (b : units α) : a * b * ↑b⁻¹ = a := by rw [mul_assoc, mul_inv, mul_one] @[simp, to_additive] lemma inv_mul_cancel_right (a : α) (b : units α) : a * ↑b⁻¹ * b = a := by rw [mul_assoc, inv_mul, mul_one] @[to_additive] instance : inhabited (units α) := ⟨1⟩ @[to_additive] instance {α} [comm_monoid α] : comm_group (units α) := { mul_comm := λ u₁ u₂, ext $ mul_comm _ _, ..units.group } @[to_additive] instance [has_repr α] : has_repr (units α) := ⟨repr ∘ val⟩ @[simp, to_additive] theorem mul_right_inj (a : units α) {b c : α} : (a:α) * b = a * c ↔ b = c := ⟨λ h, by simpa only [inv_mul_cancel_left] using congr_arg ((*) ↑(a⁻¹ : units α)) h, congr_arg _⟩ @[simp, to_additive] theorem mul_left_inj (a : units α) {b c : α} : b * a = c * a ↔ b = c := ⟨λ h, by simpa only [mul_inv_cancel_right] using congr_arg (* ↑(a⁻¹ : units α)) h, congr_arg _⟩ @[to_additive] theorem eq_mul_inv_iff_mul_eq {a b : α} : a = b * ↑c⁻¹ ↔ a * c = b := ⟨λ h, by rw [h, inv_mul_cancel_right], λ h, by rw [← h, mul_inv_cancel_right]⟩ @[to_additive] theorem eq_inv_mul_iff_mul_eq {a c : α} : a = ↑b⁻¹ * c ↔ ↑b * a = c := ⟨λ h, by rw [h, mul_inv_cancel_left], λ h, by rw [← h, inv_mul_cancel_left]⟩ @[to_additive] theorem inv_mul_eq_iff_eq_mul {b c : α} : ↑a⁻¹ * b = c ↔ b = a * c := ⟨λ h, by rw [← h, mul_inv_cancel_left], λ h, by rw [h, inv_mul_cancel_left]⟩ @[to_additive] theorem mul_inv_eq_iff_eq_mul {a c : α} : a * ↑b⁻¹ = c ↔ a = c * b := ⟨λ h, by rw [← h, inv_mul_cancel_right], λ h, by rw [h, mul_inv_cancel_right]⟩ lemma inv_eq_of_mul_eq_one {u : units α} {a : α} (h : ↑u * a = 1) : ↑u⁻¹ = a := calc ↑u⁻¹ = ↑u⁻¹ * 1 : by rw mul_one ... = ↑u⁻¹ * ↑u * a : by rw [←h, ←mul_assoc] ... = a : by rw [u.inv_mul, one_mul] lemma inv_unique {u₁ u₂ : units α} (h : (↑u₁ : α) = ↑u₂) : (↑u₁⁻¹ : α) = ↑u₂⁻¹ := inv_eq_of_mul_eq_one $ by rw [h, u₂.mul_inv] end units /-- For `a, b` in a `comm_monoid` such that `a * b = 1`, makes a unit out of `a`. -/ @[to_additive "For `a, b` in an `add_comm_monoid` such that `a + b = 0`, makes an add_unit out of `a`."] def units.mk_of_mul_eq_one [comm_monoid α] (a b : α) (hab : a * b = 1) : units α := ⟨a, b, hab, (mul_comm b a).trans hab⟩ @[simp, to_additive] lemma units.coe_mk_of_mul_eq_one [comm_monoid α] {a b : α} (h : a * b = 1) : (units.mk_of_mul_eq_one a b h : α) = a := rfl section monoid variables [monoid α] {a b c : α} /-- Partial division. It is defined when the second argument is invertible, and unlike the division operator in `division_ring` it is not totalized at zero. -/ def divp (a : α) (u) : α := a * (u⁻¹ : units α) infix ` /ₚ `:70 := divp @[simp] theorem divp_self (u : units α) : (u : α) /ₚ u = 1 := units.mul_inv _ @[simp] theorem divp_one (a : α) : a /ₚ 1 = a := mul_one _ theorem divp_assoc (a b : α) (u : units α) : a * b /ₚ u = a * (b /ₚ u) := mul_assoc _ _ _ @[simp] theorem divp_inv (u : units α) : a /ₚ u⁻¹ = a * u := rfl @[simp] theorem divp_mul_cancel (a : α) (u : units α) : a /ₚ u * u = a := (mul_assoc _ _ _).trans $ by rw [units.inv_mul, mul_one] @[simp] theorem mul_divp_cancel (a : α) (u : units α) : (a * u) /ₚ u = a := (mul_assoc _ _ _).trans $ by rw [units.mul_inv, mul_one] @[simp] theorem divp_left_inj (u : units α) {a b : α} : a /ₚ u = b /ₚ u ↔ a = b := units.mul_left_inj _ theorem divp_divp_eq_divp_mul (x : α) (u₁ u₂ : units α) : (x /ₚ u₁) /ₚ u₂ = x /ₚ (u₂ * u₁) := by simp only [divp, mul_inv_rev, units.coe_mul, mul_assoc] theorem divp_eq_iff_mul_eq {x : α} {u : units α} {y : α} : x /ₚ u = y ↔ y * u = x := u.mul_left_inj.symm.trans $ by rw [divp_mul_cancel]; exact ⟨eq.symm, eq.symm⟩ theorem divp_eq_one_iff_eq {a : α} {u : units α} : a /ₚ u = 1 ↔ a = u := (units.mul_left_inj u).symm.trans $ by rw [divp_mul_cancel, one_mul] @[simp] theorem one_divp (u : units α) : 1 /ₚ u = ↑u⁻¹ := one_mul _ end monoid section comm_monoid variables [comm_monoid α] theorem divp_eq_divp_iff {x y : α} {ux uy : units α} : x /ₚ ux = y /ₚ uy ↔ x * uy = y * ux := by rw [divp_eq_iff_mul_eq, mul_comm, ← divp_assoc, divp_eq_iff_mul_eq, mul_comm y ux] theorem divp_mul_divp (x y : α) (ux uy : units α) : (x /ₚ ux) * (y /ₚ uy) = (x * y) /ₚ (ux * uy) := by rw [← divp_divp_eq_divp_mul, divp_assoc, mul_comm x, divp_assoc, mul_comm] end comm_monoid /-! # `is_unit` predicate In this file we define the `is_unit` predicate on a `monoid`, and prove a few basic properties. For the bundled version see `units`. See also `prime`, `associated`, and `irreducible` in `algebra/associated`. -/ section is_unit variables {M : Type*} {N : Type*} /-- An element `a : M` of a monoid is a unit if it has a two-sided inverse. The actual definition says that `a` is equal to some `u : units M`, where `units M` is a bundled version of `is_unit`. -/ @[to_additive is_add_unit "An element `a : M` of an add_monoid is an `add_unit` if it has a two-sided additive inverse. The actual definition says that `a` is equal to some `u : add_units M`, where `add_units M` is a bundled version of `is_add_unit`."] def is_unit [monoid M] (a : M) : Prop := ∃ u : units M, (u : M) = a @[nontriviality] lemma is_unit_of_subsingleton [monoid M] [subsingleton M] (a : M) : is_unit a := ⟨⟨a, a, subsingleton.elim _ _, subsingleton.elim _ _⟩, rfl⟩ @[simp, to_additive is_add_unit_add_unit] protected lemma units.is_unit [monoid M] (u : units M) : is_unit (u : M) := ⟨u, rfl⟩ @[simp, to_additive is_add_unit_zero] theorem is_unit_one [monoid M] : is_unit (1:M) := ⟨1, rfl⟩ @[to_additive is_add_unit_of_add_eq_zero] theorem is_unit_of_mul_eq_one [comm_monoid M] (a b : M) (h : a * b = 1) : is_unit a := ⟨units.mk_of_mul_eq_one a b h, rfl⟩ @[to_additive is_add_unit.exists_neg] theorem is_unit.exists_right_inv [monoid M] {a : M} (h : is_unit a) : ∃ b, a * b = 1 := by { rcases h with ⟨⟨a, b, hab, _⟩, rfl⟩, exact ⟨b, hab⟩ } @[to_additive is_add_unit.exists_neg'] theorem is_unit.exists_left_inv [monoid M] {a : M} (h : is_unit a) : ∃ b, b * a = 1 := by { rcases h with ⟨⟨a, b, _, hba⟩, rfl⟩, exact ⟨b, hba⟩ } @[to_additive is_add_unit_iff_exists_neg] theorem is_unit_iff_exists_inv [comm_monoid M] {a : M} : is_unit a ↔ ∃ b, a * b = 1 := ⟨λ h, h.exists_right_inv, λ ⟨b, hab⟩, is_unit_of_mul_eq_one _ b hab⟩ @[to_additive is_add_unit_iff_exists_neg'] theorem is_unit_iff_exists_inv' [comm_monoid M] {a : M} : is_unit a ↔ ∃ b, b * a = 1 := by simp [is_unit_iff_exists_inv, mul_comm] /-- Multiplication by a `u : units M` doesn't affect `is_unit`. -/ @[simp, to_additive is_add_unit_add_add_units "Addition of a `u : add_units M` doesn't affect `is_add_unit`."] theorem units.is_unit_mul_units [monoid M] (a : M) (u : units M) : is_unit (a * u) ↔ is_unit a := iff.intro (assume ⟨v, hv⟩, have is_unit (a * ↑u * ↑u⁻¹), by existsi v * u⁻¹; rw [←hv, units.coe_mul], by rwa [mul_assoc, units.mul_inv, mul_one] at this) (assume ⟨v, hv⟩, hv ▸ ⟨v * u, (units.coe_mul v u).symm⟩) @[to_additive] lemma is_unit.mul [monoid M] {x y : M} : is_unit x → is_unit y → is_unit (x * y) := by { rintros ⟨x, rfl⟩ ⟨y, rfl⟩, exact ⟨x * y, units.coe_mul _ _⟩ } @[to_additive is_add_unit_of_add_is_add_unit_left] theorem is_unit_of_mul_is_unit_left [comm_monoid M] {x y : M} (hu : is_unit (x * y)) : is_unit x := let ⟨z, hz⟩ := is_unit_iff_exists_inv.1 hu in is_unit_iff_exists_inv.2 ⟨y * z, by rwa ← mul_assoc⟩ @[to_additive] theorem is_unit_of_mul_is_unit_right [comm_monoid M] {x y : M} (hu : is_unit (x * y)) : is_unit y := @is_unit_of_mul_is_unit_left _ _ y x $ by rwa mul_comm @[simp] lemma is_unit.mul_iff [comm_monoid M] {x y : M} : is_unit (x * y) ↔ is_unit x ∧ is_unit y := ⟨λ h, ⟨is_unit_of_mul_is_unit_left h, is_unit_of_mul_is_unit_right h⟩, λ h, is_unit.mul h.1 h.2⟩ @[to_additive] theorem is_unit.mul_right_inj [monoid M] {a b c : M} (ha : is_unit a) : a * b = a * c ↔ b = c := by cases ha with a ha; rw [←ha, units.mul_right_inj] @[to_additive] theorem is_unit.mul_left_inj [monoid M] {a b c : M} (ha : is_unit a) : b * a = c * a ↔ b = c := by cases ha with a ha; rw [←ha, units.mul_left_inj] /-- The element of the group of units, corresponding to an element of a monoid which is a unit. -/ noncomputable def is_unit.unit [monoid M] {a : M} (h : is_unit a) : units M := classical.some h lemma is_unit.unit_spec [monoid M] {a : M} (h : is_unit a) : ↑h.unit = a := classical.some_spec h end is_unit section noncomputable_defs variables {M : Type*} /-- Constructs a `group` structure on a `monoid` consisting only of units. -/ noncomputable def group_of_is_unit [hM : monoid M] (h : ∀ (a : M), is_unit a) : group M := { inv := λ a, ↑((h a).unit)⁻¹, mul_left_inv := λ a, by { change ↑((h a).unit)⁻¹ * a = 1, rw [units.inv_mul_eq_iff_eq_mul, (h a).unit_spec, mul_one] }, .. hM } /-- Constructs a `comm_group` structure on a `comm_monoid` consisting only of units. -/ noncomputable def comm_group_of_is_unit [hM : comm_monoid M] (h : ∀ (a : M), is_unit a) : comm_group M := { inv := λ a, ↑((h a).unit)⁻¹, mul_left_inv := λ a, by { change ↑((h a).unit)⁻¹ * a = 1, rw [units.inv_mul_eq_iff_eq_mul, (h a).unit_spec, mul_one] }, .. hM } end noncomputable_defs
043835fb3c51e4290a78a7ea3e946d8e5171e901
0c1546a496eccfb56620165cad015f88d56190c5
/tests/lean/run/cases_tac1.lean
8150cc1bd60e03d408b63b0e66b8d138ac676a0c
[ "Apache-2.0" ]
permissive
Solertis/lean
491e0939957486f664498fbfb02546e042699958
84188c5aa1673fdf37a082b2de8562dddf53df3f
refs/heads/master
1,610,174,257,606
1,486,263,620,000
1,486,263,620,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,039
lean
inductive {u} vec (A : Type u) : nat → Type u | nil : vec 0 | cons : ∀ {n}, A → vec n → vec (n+1) open tactic nat vec def head {A : Type*} : ∀ {n : nat}, vec A (n+1) → A | n (cons h t) := h def tail {A : Type*} : ∀ {n : nat}, vec A (n+1) → vec A n | n (cons h t) := t @[simp] lemma head_cons {A : Type*} {n : nat} (a : A) (v : vec A n) : head (cons a v) = a := rfl @[simp] lemma tail_cons {A : Type*} {n : nat} (a : A) (v : vec A n) : tail (cons a v) = v := rfl example {A : Type*} {n : nat} (v w : vec A (n+1)) : head v = head w → tail v = tail w → v = w := by do v ← get_local `v, cases_using v [`n', `hv, `tv], trace_state, w ← get_local `w, cases_using w [`n', `hw, `tw], trace_state, dsimp, trace_state, Heq1 ← intro1, Heq2 ← intro1, subst Heq1, subst Heq2, reflexivity print "-------" example (n : nat) : n ≠ 0 → succ (pred n) = n := by do H ← intro `H, n ← get_local `n, cases_using n [`n'], trace_state, contradiction, reflexivity print "---------"
eae109c5fbbf27a91f6b070ad0d3e1579d342c4e
07c6143268cfb72beccd1cc35735d424ebcb187b
/src/ring_theory/multiplicity.lean
d83fd93c2e0a6a2dd93c19fe4cd43c0471757ab7
[ "Apache-2.0" ]
permissive
khoek/mathlib
bc49a842910af13a3c372748310e86467d1dc766
aa55f8b50354b3e11ba64792dcb06cccb2d8ee28
refs/heads/master
1,588,232,063,837
1,587,304,803,000
1,587,304,803,000
176,688,517
0
0
Apache-2.0
1,553,070,585,000
1,553,070,585,000
null
UTF-8
Lean
false
false
17,375
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis, Chris Hughes -/ import algebra.associated data.int.gcd algebra.big_operators import tactic.converter.interactive variables {α : Type*} open nat roption theorem nat.find_le {p q : ℕ → Prop} [decidable_pred p] [decidable_pred q] (h : ∀ n, q n → p n) (hp : ∃ n, p n) (hq : ∃ n, q n) : nat.find hp ≤ nat.find hq := nat.find_min' _ ((h _) (nat.find_spec hq)) /-- `multiplicity a b` returns the largest natural number `n` such that `a ^ n ∣ b`, as an `enat` or natural with infinity. If `∀ n, a ^ n ∣ b`, then it returns `⊤`-/ def multiplicity [comm_semiring α] [decidable_rel ((∣) : α → α → Prop)] (a b : α) : enat := ⟨∃ n : ℕ, ¬a ^ (n + 1) ∣ b, λ h, nat.find h⟩ namespace multiplicity section comm_semiring variables [comm_semiring α] @[reducible] def finite (a b : α) : Prop := ∃ n : ℕ, ¬a ^ (n + 1) ∣ b lemma finite_iff_dom [decidable_rel ((∣) : α → α → Prop)] {a b : α} : finite a b ↔ (multiplicity a b).dom := iff.rfl lemma finite_def {a b : α} : finite a b ↔ ∃ n : ℕ, ¬a ^ (n + 1) ∣ b := iff.rfl @[norm_cast] theorem int.coe_nat_multiplicity (a b : ℕ) : multiplicity (a : ℤ) (b : ℤ) = multiplicity a b := begin apply roption.ext', { repeat {rw [← finite_iff_dom, finite_def]}, norm_cast, simp }, { intros h1 h2, apply _root_.le_antisymm; { apply nat.find_le, norm_cast, simp }} end lemma not_finite_iff_forall {a b : α} : (¬ finite a b) ↔ ∀ n : ℕ, a ^ n ∣ b := ⟨λ h n, nat.cases_on n (one_dvd _) (by simpa [finite, classical.not_not] using h), by simp [finite, multiplicity, classical.not_not]; tauto⟩ lemma not_unit_of_finite {a b : α} (h : finite a b) : ¬is_unit a := let ⟨n, hn⟩ := h in mt (is_unit_iff_forall_dvd.1 ∘ is_unit_pow (n + 1)) $ λ h, hn (h b) lemma ne_zero_of_finite {a b : α} (h : finite a b) : b ≠ 0 := let ⟨n, hn⟩ := h in λ hb, by simpa [hb] using hn lemma finite_of_finite_mul_left {a b c : α} : finite a (b * c) → finite a c := λ ⟨n, hn⟩, ⟨n, λ h, hn (dvd.trans h (by simp [_root_.mul_pow]))⟩ lemma finite_of_finite_mul_right {a b c : α} : finite a (b * c) → finite a b := by rw mul_comm; exact finite_of_finite_mul_left variable [decidable_rel ((∣) : α → α → Prop)] lemma pow_dvd_of_le_multiplicity {a b : α} {k : ℕ} : (k : enat) ≤ multiplicity a b → a ^ k ∣ b := nat.cases_on k (λ _, one_dvd _) (λ k ⟨h₁, h₂⟩, by_contradiction (λ hk, (nat.find_min _ (lt_of_succ_le (h₂ ⟨k, hk⟩)) hk))) lemma pow_multiplicity_dvd {a b : α} (h : finite a b) : a ^ get (multiplicity a b) h ∣ b := pow_dvd_of_le_multiplicity (by rw enat.coe_get) lemma is_greatest {a b : α} {m : ℕ} (hm : multiplicity a b < m) : ¬a ^ m ∣ b := λ h, have finite a b, from enat.dom_of_le_some (le_of_lt hm), by rw [← enat.coe_get (finite_iff_dom.1 this), enat.coe_lt_coe] at hm; exact nat.find_spec this (dvd.trans (pow_dvd_pow _ hm) h) lemma is_greatest' {a b : α} {m : ℕ} (h : finite a b) (hm : get (multiplicity a b) h < m) : ¬a ^ m ∣ b := is_greatest (by rwa [← enat.coe_lt_coe, enat.coe_get] at hm) lemma unique {a b : α} {k : ℕ} (hk : a ^ k ∣ b) (hsucc : ¬a ^ (k + 1) ∣ b) : (k : enat) = multiplicity a b := le_antisymm (le_of_not_gt (λ hk', is_greatest hk' hk)) $ have finite a b, from ⟨k, hsucc⟩, by rw [← enat.coe_get (finite_iff_dom.1 this), enat.coe_le_coe]; exact nat.find_min' _ hsucc lemma unique' {a b : α} {k : ℕ} (hk : a ^ k ∣ b) (hsucc : ¬ a ^ (k + 1) ∣ b) : k = get (multiplicity a b) ⟨k, hsucc⟩ := by rw [← enat.coe_inj, enat.coe_get, unique hk hsucc] lemma le_multiplicity_of_pow_dvd {a b : α} {k : ℕ} (hk : a ^ k ∣ b) : (k : enat) ≤ multiplicity a b := le_of_not_gt $ λ hk', is_greatest hk' hk lemma pow_dvd_iff_le_multiplicity {a b : α} {k : ℕ} : a ^ k ∣ b ↔ (k : enat) ≤ multiplicity a b := ⟨le_multiplicity_of_pow_dvd, pow_dvd_of_le_multiplicity⟩ lemma multiplicity_lt_iff_neg_dvd {a b : α} {k : ℕ} : multiplicity a b < (k : enat) ↔ ¬ a ^ k ∣ b := by { rw [pow_dvd_iff_le_multiplicity, not_le] } lemma eq_some_iff {a b : α} {n : ℕ} : multiplicity a b = (n : enat) ↔ a ^ n ∣ b ∧ ¬a ^ (n + 1) ∣ b := ⟨λ h, let ⟨h₁, h₂⟩ := eq_some_iff.1 h in h₂ ▸ ⟨pow_multiplicity_dvd _, is_greatest (by conv_lhs {rw ← enat.coe_get h₁ }; rw [enat.coe_lt_coe]; exact lt_succ_self _)⟩, λ h, eq_some_iff.2 ⟨⟨n, h.2⟩, eq.symm $ unique' h.1 h.2⟩⟩ lemma eq_top_iff {a b : α} : multiplicity a b = ⊤ ↔ ∀ n : ℕ, a ^ n ∣ b := ⟨λ h n, nat.cases_on n (one_dvd _) (λ n, by_contradiction (not_exists.1 (eq_none_iff'.1 h) n : _)), λ h, eq_none_iff.2 (λ n ⟨⟨_, h₁⟩, _⟩, h₁ (h _))⟩ @[simp] protected lemma zero (a : α) : multiplicity a 0 = ⊤ := roption.eq_none_iff.2 (λ n ⟨⟨k, hk⟩, _⟩, hk (dvd_zero _)) lemma one_right {a : α} (ha : ¬is_unit a) : multiplicity a 1 = 0 := eq_some_iff.2 ⟨dvd_refl _, mt is_unit_iff_dvd_one.2 $ by simpa⟩ @[simp] lemma get_one_right {a : α} (ha : finite a 1) : get (multiplicity a 1) ha = 0 := get_eq_iff_eq_some.2 (eq_some_iff.2 ⟨dvd_refl _, by simpa [is_unit_iff_dvd_one.symm] using not_unit_of_finite ha⟩) @[simp] lemma multiplicity_unit {a : α} (b : α) (ha : is_unit a) : multiplicity a b = ⊤ := eq_top_iff.2 (λ _, is_unit_iff_forall_dvd.1 (is_unit_pow _ ha) _) @[simp] lemma one_left (b : α) : multiplicity 1 b = ⊤ := by simp [eq_top_iff] lemma multiplicity_eq_zero_of_not_dvd {a b : α} (ha : ¬a ∣ b) : multiplicity a b = 0 := eq_some_iff.2 (by simpa) lemma eq_top_iff_not_finite {a b : α} : multiplicity a b = ⊤ ↔ ¬ finite a b := roption.eq_none_iff' open_locale classical lemma multiplicity_le_multiplicity_iff {a b c d : α} : multiplicity a b ≤ multiplicity c d ↔ (∀ n : ℕ, a ^ n ∣ b → c ^ n ∣ d) := ⟨λ h n hab, (pow_dvd_of_le_multiplicity (le_trans (le_multiplicity_of_pow_dvd hab) h)), λ h, if hab : finite a b then by rw [← enat.coe_get (finite_iff_dom.1 hab)]; exact le_multiplicity_of_pow_dvd (h _ (pow_multiplicity_dvd _)) else have ∀ n : ℕ, c ^ n ∣ d, from λ n, h n (not_finite_iff_forall.1 hab _), by rw [eq_top_iff_not_finite.2 hab, eq_top_iff_not_finite.2 (not_finite_iff_forall.2 this)]⟩ lemma min_le_multiplicity_add {p a b : α} : min (multiplicity p a) (multiplicity p b) ≤ multiplicity p (a + b) := (le_total (multiplicity p a) (multiplicity p b)).elim (λ h, by rw [min_eq_left h, multiplicity_le_multiplicity_iff]; exact λ n hn, dvd_add hn (multiplicity_le_multiplicity_iff.1 h n hn)) (λ h, by rw [min_eq_right h, multiplicity_le_multiplicity_iff]; exact λ n hn, dvd_add (multiplicity_le_multiplicity_iff.1 h n hn) hn) lemma dvd_of_multiplicity_pos {a b : α} (h : (0 : enat) < multiplicity a b) : a ∣ b := by rw [← _root_.pow_one a]; exact pow_dvd_of_le_multiplicity (enat.pos_iff_one_le.1 h) lemma finite_nat_iff {a b : ℕ} : finite a b ↔ (a ≠ 1 ∧ 0 < b) := begin rw [← not_iff_not, not_finite_iff_forall, not_and_distrib, ne.def, not_not, not_lt, nat.le_zero_iff], exact ⟨λ h, or_iff_not_imp_right.2 (λ hb, have ha : a ≠ 0, from λ ha, by simpa [ha] using h 1, by_contradiction (λ ha1 : a ≠ 1, have ha_gt_one : 1 < a, from have ∀ a : ℕ, a ≤ 1 → a ≠ 0 → a ≠ 1 → false, from dec_trivial, lt_of_not_ge (λ ha', this a ha' ha ha1), not_lt_of_ge (le_of_dvd (nat.pos_of_ne_zero hb) (h b)) (by simp only [nat.pow_eq_pow]; exact lt_pow_self ha_gt_one b))), λ h, by cases h; simp *⟩ end lemma finite_int_iff_nat_abs_finite {a b : ℤ} : finite a b ↔ finite a.nat_abs b.nat_abs := begin rw [finite_def, finite_def], conv in (a ^ _ ∣ b) { rw [← int.nat_abs_dvd_abs_iff, int.nat_abs_pow, ← pow_eq_pow] } end lemma finite_int_iff {a b : ℤ} : finite a b ↔ (a.nat_abs ≠ 1 ∧ b ≠ 0) := begin have := int.nat_abs_eq a, have := @int.nat_abs_ne_zero_of_ne_zero b, rw [finite_int_iff_nat_abs_finite, finite_nat_iff, nat.pos_iff_ne_zero], split; finish end instance decidable_nat : decidable_rel (λ a b : ℕ, (multiplicity a b).dom) := λ a b, decidable_of_iff _ finite_nat_iff.symm instance decidable_int : decidable_rel (λ a b : ℤ, (multiplicity a b).dom) := λ a b, decidable_of_iff _ finite_int_iff.symm end comm_semiring section comm_ring variables [comm_ring α] [decidable_rel ((∣) : α → α → Prop)] open_locale classical @[simp] protected lemma neg (a b : α) : multiplicity a (-b) = multiplicity a b := roption.ext' (by simp only [multiplicity]; conv in (_ ∣ - _) {rw dvd_neg}) (λ h₁ h₂, enat.coe_inj.1 (by rw [enat.coe_get]; exact eq.symm (unique ((dvd_neg _ _).2 (pow_multiplicity_dvd _)) (mt (dvd_neg _ _).1 (is_greatest' _ (lt_succ_self _)))))) lemma multiplicity_add_of_gt {p a b : α} (h : multiplicity p b < multiplicity p a) : multiplicity p (a + b) = multiplicity p b := begin apply le_antisymm, { apply enat.le_of_lt_add_one, cases enat.ne_top_iff.mp (enat.ne_top_of_lt h) with k hk, rw [hk], rw_mod_cast [multiplicity_lt_iff_neg_dvd], intro h_dvd, rw [← dvd_add_iff_right] at h_dvd, apply multiplicity.is_greatest _ h_dvd, rw [hk], apply_mod_cast nat.lt_succ_self, rw [pow_dvd_iff_le_multiplicity, enat.coe_add, ← hk], exact enat.add_one_le_of_lt h }, { convert min_le_multiplicity_add, rw [min_eq_right (le_of_lt h)] } end lemma multiplicity_sub_of_gt {p a b : α} (h : multiplicity p b < multiplicity p a) : multiplicity p (a - b) = multiplicity p b := by { rw [sub_eq_add_neg, multiplicity_add_of_gt]; rwa [multiplicity.neg] } lemma multiplicity_add_eq_min {p a b : α} (h : multiplicity p a ≠ multiplicity p b) : multiplicity p (a + b) = min (multiplicity p a) (multiplicity p b) := begin rcases lt_trichotomy (multiplicity p a) (multiplicity p b) with hab|hab|hab, { rw [add_comm, multiplicity_add_of_gt hab, min_eq_left], exact le_of_lt hab }, { contradiction }, { rw [multiplicity_add_of_gt hab, min_eq_right], exact le_of_lt hab}, end end comm_ring section integral_domain variables [integral_domain α] lemma finite_mul_aux {p : α} (hp : prime p) : ∀ {n m : ℕ} {a b : α}, ¬p ^ (n + 1) ∣ a → ¬p ^ (m + 1) ∣ b → ¬p ^ (n + m + 1) ∣ a * b | n m := λ a b ha hb ⟨s, hs⟩, have p ∣ a * b, from ⟨p ^ (n + m) * s, by simp [hs, _root_.pow_add, mul_comm, mul_assoc, mul_left_comm]⟩, (hp.2.2 a b this).elim (λ ⟨x, hx⟩, have hn0 : 0 < n, from nat.pos_of_ne_zero (λ hn0, by clear _fun_match _fun_match; simpa [hx, hn0] using ha), have wf : (n - 1) < n, from nat.sub_lt_self hn0 dec_trivial, have hpx : ¬ p ^ (n - 1 + 1) ∣ x, from λ ⟨y, hy⟩, ha (hx.symm ▸ ⟨y, (domain.mul_left_inj hp.1).1 $ by rw [nat.sub_add_cancel hn0] at hy; simp [hy, _root_.pow_add, mul_comm, mul_assoc, mul_left_comm]⟩), have 1 ≤ n + m, from le_trans hn0 (le_add_right n m), finite_mul_aux hpx hb ⟨s, (domain.mul_left_inj hp.1).1 begin rw [← nat.sub_add_comm hn0, nat.sub_add_cancel this], clear _fun_match _fun_match finite_mul_aux, simp [*, mul_comm, mul_assoc, mul_left_comm, _root_.pow_add] at * end⟩) (λ ⟨x, hx⟩, have hm0 : 0 < m, from nat.pos_of_ne_zero (λ hm0, by clear _fun_match _fun_match; simpa [hx, hm0] using hb), have wf : (m - 1) < m, from nat.sub_lt_self hm0 dec_trivial, have hpx : ¬ p ^ (m - 1 + 1) ∣ x, from λ ⟨y, hy⟩, hb (hx.symm ▸ ⟨y, (domain.mul_left_inj hp.1).1 $ by rw [nat.sub_add_cancel hm0] at hy; simp [hy, _root_.pow_add, mul_comm, mul_assoc, mul_left_comm]⟩), finite_mul_aux ha hpx ⟨s, (domain.mul_left_inj hp.1).1 begin rw [add_assoc, nat.sub_add_cancel hm0], clear _fun_match _fun_match finite_mul_aux, simp [*, mul_comm, mul_assoc, mul_left_comm, _root_.pow_add] at * end⟩) lemma finite_mul {p a b : α} (hp : prime p) : finite p a → finite p b → finite p (a * b) := λ ⟨n, hn⟩ ⟨m, hm⟩, ⟨n + m, finite_mul_aux hp hn hm⟩ lemma finite_mul_iff {p a b : α} (hp : prime p) : finite p (a * b) ↔ finite p a ∧ finite p b := ⟨λ h, ⟨finite_of_finite_mul_right h, finite_of_finite_mul_left h⟩, λ h, finite_mul hp h.1 h.2⟩ lemma finite_pow {p a : α} (hp : prime p) : Π {k : ℕ} (ha : finite p a), finite p (a ^ k) | 0 ha := ⟨0, by simp [mt is_unit_iff_dvd_one.2 hp.2.1]⟩ | (k+1) ha := by rw [_root_.pow_succ]; exact finite_mul hp ha (finite_pow ha) variable [decidable_rel ((∣) : α → α → Prop)] @[simp] lemma multiplicity_self {a : α} (ha : ¬is_unit a) (ha0 : a ≠ 0) : multiplicity a a = 1 := eq_some_iff.2 ⟨by simp, λ ⟨b, hb⟩, ha (is_unit_iff_dvd_one.2 ⟨b, (domain.mul_left_inj ha0).1 $ by clear _fun_match; simpa [_root_.pow_succ, mul_assoc] using hb⟩)⟩ @[simp] lemma get_multiplicity_self {a : α} (ha : finite a a) : get (multiplicity a a) ha = 1 := roption.get_eq_iff_eq_some.2 (eq_some_iff.2 ⟨by simp, λ ⟨b, hb⟩, by rw [← mul_one a, _root_.pow_add, _root_.pow_one, mul_assoc, mul_assoc, domain.mul_left_inj (ne_zero_of_finite ha)] at hb; exact mt is_unit_iff_dvd_one.2 (not_unit_of_finite ha) ⟨b, by clear _fun_match; simp * at *⟩⟩) protected lemma mul' {p a b : α} (hp : prime p) (h : (multiplicity p (a * b)).dom) : get (multiplicity p (a * b)) h = get (multiplicity p a) ((finite_mul_iff hp).1 h).1 + get (multiplicity p b) ((finite_mul_iff hp).1 h).2 := have hdiva : p ^ get (multiplicity p a) ((finite_mul_iff hp).1 h).1 ∣ a, from pow_multiplicity_dvd _, have hdivb : p ^ get (multiplicity p b) ((finite_mul_iff hp).1 h).2 ∣ b, from pow_multiplicity_dvd _, have hpoweq : p ^ (get (multiplicity p a) ((finite_mul_iff hp).1 h).1 + get (multiplicity p b) ((finite_mul_iff hp).1 h).2) = p ^ get (multiplicity p a) ((finite_mul_iff hp).1 h).1 * p ^ get (multiplicity p b) ((finite_mul_iff hp).1 h).2, by simp [_root_.pow_add], have hdiv : p ^ (get (multiplicity p a) ((finite_mul_iff hp).1 h).1 + get (multiplicity p b) ((finite_mul_iff hp).1 h).2) ∣ a * b, by rw [hpoweq]; apply mul_dvd_mul; assumption, have hsucc : ¬p ^ ((get (multiplicity p a) ((finite_mul_iff hp).1 h).1 + get (multiplicity p b) ((finite_mul_iff hp).1 h).2) + 1) ∣ a * b, from λ h, not_or (is_greatest' _ (lt_succ_self _)) (is_greatest' _ (lt_succ_self _)) (succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul hp (by convert hdiva) (by convert hdivb) h), by rw [← enat.coe_inj, enat.coe_get, eq_some_iff]; exact ⟨hdiv, hsucc⟩ open_locale classical protected lemma mul {p a b : α} (hp : prime p) : multiplicity p (a * b) = multiplicity p a + multiplicity p b := if h : finite p a ∧ finite p b then by rw [← enat.coe_get (finite_iff_dom.1 h.1), ← enat.coe_get (finite_iff_dom.1 h.2), ← enat.coe_get (finite_iff_dom.1 (finite_mul hp h.1 h.2)), ← enat.coe_add, enat.coe_inj, multiplicity.mul' hp]; refl else begin rw [eq_top_iff_not_finite.2 (mt (finite_mul_iff hp).1 h)], cases not_and_distrib.1 h with h h; simp [eq_top_iff_not_finite.2 h] end lemma finset.prod {β : Type*} {p : α} (hp : prime p) (s : finset β) (f : β → α) : multiplicity p (s.prod f) = s.sum (λ x, multiplicity p (f x)) := begin classical, induction s using finset.induction with a s has ih h, { simp only [finset.sum_empty, finset.prod_empty], convert one_right hp.not_unit }, { simp [has, ← ih], convert multiplicity.mul hp } end protected lemma pow' {p a : α} (hp : prime p) (ha : finite p a) : ∀ {k : ℕ}, get (multiplicity p (a ^ k)) (finite_pow hp ha) = k * get (multiplicity p a) ha | 0 := by dsimp [_root_.pow_zero]; simp [one_right hp.not_unit]; refl | (k+1) := by dsimp only [_root_.pow_succ]; erw [multiplicity.mul' hp, pow', add_mul, one_mul, add_comm] lemma pow {p a : α} (hp : prime p) : ∀ {k : ℕ}, multiplicity p (a ^ k) = add_monoid.smul k (multiplicity p a) | 0 := by simp [one_right hp.not_unit] | (succ k) := by simp [_root_.pow_succ, succ_smul, pow, multiplicity.mul hp] lemma multiplicity_pow_self {p : α} (h0 : p ≠ 0) (hu : ¬ is_unit p) (n : ℕ) : multiplicity p (p ^ n) = n := by { rw [eq_some_iff], use dvd_refl _, rw [pow_dvd_pow_iff h0 hu], apply nat.not_succ_le_self } lemma multiplicity_pow_self_of_prime {p : α} (hp : prime p) (n : ℕ) : multiplicity p (p ^ n) = n := multiplicity_pow_self hp.ne_zero hp.not_unit n end integral_domain end multiplicity section nat open multiplicity lemma multiplicity_eq_zero_of_coprime {p a b : ℕ} (hp : p ≠ 1) (hle : multiplicity p a ≤ multiplicity p b) (hab : nat.coprime a b) : multiplicity p a = 0 := begin rw [multiplicity_le_multiplicity_iff] at hle, rw [← le_zero_iff_eq, ← not_lt, enat.pos_iff_one_le, ← enat.coe_one, ← pow_dvd_iff_le_multiplicity], assume h, have := nat.dvd_gcd h (hle _ h), rw [coprime.gcd_eq_one hab, nat.dvd_one, _root_.pow_one] at this, exact hp this end end nat
dd7f3a98281be72750e4d1950c30dc280dfdbcc9
5d166a16ae129621cb54ca9dde86c275d7d2b483
/library/init/meta/vm.lean
2a8a8b485fba0b4fc6ef0d5af0d0ec611d4153c9
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
6,517
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.data.option_t import init.meta.mk_dec_eq_instance meta constant vm_obj : Type inductive vm_obj_kind | simple | constructor | closure | native_closure | mpz | name | level | expr | declaration | environment | tactic_state | format | options | other instance vm_obj_kind_dec_eq : decidable_eq vm_obj_kind := by tactic.mk_dec_eq_instance namespace vm_obj meta constant kind : vm_obj → vm_obj_kind /- For simple and constructor vm_obj's, it returns the constructor tag/index. Return 0 otherwise. -/ meta constant cidx : vm_obj → nat /- For closure vm_obj's, it returns the internal function index. -/ meta constant fn_idx : vm_obj → nat /- For constructor vm_obj's, it returns the data stored in the object. For closure vm_obj's, it returns the local arguments captured by the closure. -/ meta constant fields : vm_obj → list vm_obj /- For simple and mpz vm_obj's -/ meta constant to_nat : vm_obj → nat /- For name vm_obj's, it returns the name wrapped by the vm_obj. -/ meta constant to_name : vm_obj → name /- For level vm_obj's, it returns the universe level wrapped by the vm_obj. -/ meta constant to_level : vm_obj → level /- For expr vm_obj's, it returns the expression wrapped by the vm_obj. -/ meta constant to_expr : vm_obj → expr /- For declaration vm_obj's, it returns the declaration wrapped by the vm_obj. -/ meta constant to_declaration : vm_obj → declaration /- For environment vm_obj's, it returns the environment wrapped by the vm_obj. -/ meta constant to_environment : vm_obj → environment /- For tactic_state vm_obj's, it returns the tactic_state object wrapped by the vm_obj. -/ meta constant to_tactic_state : vm_obj → tactic_state /- For format vm_obj's, it returns the format object wrapped by the vm_obj. -/ meta constant to_format : vm_obj → format end vm_obj meta constant vm_decl : Type inductive vm_decl_kind | bytecode | builtin | cfun /- Information for local variables and arguments on the VM stack. Remark: type is only available if it is a closed term at compilation time. -/ meta structure vm_local_info := (id : name) (type : option expr) namespace vm_decl meta constant kind : vm_decl → vm_decl_kind meta constant to_name : vm_decl → name /- Internal function index associated with the given VM declaration. -/ meta constant idx : vm_decl → nat /- Number of arguments needed to execute the given VM declaration. -/ meta constant arity : vm_decl → nat /- Return source position if available -/ meta constant pos : vm_decl → option pos /- Return .olean file where the given VM declaration was imported from. -/ meta constant olean : vm_decl → option string /- Return names .olean file where the given VM declaration was imported from. -/ meta constant args_info : vm_decl → list vm_local_info end vm_decl meta constant vm_core : Type → Type meta constant vm_core.map {α β : Type} : (α → β) → vm_core α → vm_core β meta constant vm_core.ret {α : Type} : α → vm_core α meta constant vm_core.bind {α β : Type} : vm_core α → (α → vm_core β) → vm_core β meta instance : monad vm_core := {map := @vm_core.map, pure := @vm_core.ret, bind := @vm_core.bind, id_map := undefined, pure_bind := undefined, bind_assoc := undefined, bind_pure_comp_eq_map := undefined, bind_map_eq_seq := undefined} @[reducible] meta def vm (α : Type) : Type := option_t vm_core α namespace vm meta constant get_env : vm environment meta constant get_decl : name → vm vm_decl meta constant get_options : vm options meta constant stack_size : vm nat /- Return the vm_obj stored at the given position on the execution stack. It fails if position >= vm.stack_size -/ meta constant stack_obj : nat → vm vm_obj /- Return (name, type) for the object at the given position on the execution stack. It fails if position >= vm.stack_size. The name is anonymous if vm_obj is a transient value created by the compiler. Type information is only recorded if the type is a closed term at compilation time. -/ meta constant stack_obj_info : nat → vm (name × option expr) /- Pretty print the vm_obj at the given position on the execution stack. -/ meta constant pp_stack_obj : nat → vm format /- Pretty print the given expression. -/ meta constant pp_expr : expr → vm format /- Number of frames on the call stack. -/ meta constant call_stack_size : vm nat /- Return the function name at the given stack frame. Action fails if position >= vm.call_stack_size. -/ meta constant call_stack_fn : nat → vm name /- Return the range [start, end) for the given stack frame. Action fails if position >= vm.call_stack_size. The values start and end correspond to positions at the execution stack. We have that 0 <= start < end <= vm.stack_size -/ meta constant call_stack_var_range : nat → vm (nat × nat) /- Return the name of the function on top of the call stack. -/ meta constant curr_fn : vm name /- Return the base stack pointer for the frame on top of the call stack. -/ meta constant bp : vm nat /- Return the program counter. -/ meta constant pc : vm nat /- Convert the given vm_obj into a string -/ meta constant obj_to_string : vm_obj → vm string meta constant put_str : string → vm unit meta constant get_line : vm string /- Return tt if end of the input stream has been reached. For example, this can happen if the user presses Ctrl-D -/ meta constant eof : vm bool /- Return the list of declarations tagged with the given attribute. -/ meta constant get_attribute : name → vm (list name) meta def trace {α : Type} [has_to_format α] (a : α) : vm unit := do fmt ← return $ to_fmt a, return $ _root_.trace_fmt fmt (λ u, ()) end vm /-- A Lean VM monitor. Monitors are registered using the [vm_monitor] attribute. If option 'debugger' is true, then the VM will initialize the vm_monitor state using the 'init' field, and will invoke the function 'step' before each instruction is invoked. -/ meta structure vm_monitor (α : Type) := (init : α) (step : α → vm α)
31de61e5f292646cf39a84d9dab83b8dfae552a6
ff5230333a701471f46c57e8c115a073ebaaa448
/library/data/rbtree/main.lean
67438db05c6d14b9de36a8bd5e8ca0cbeb1794a9
[ "Apache-2.0" ]
permissive
stanford-cs242/lean
f81721d2b5d00bc175f2e58c57b710d465e6c858
7bd861261f4a37326dcf8d7a17f1f1f330e4548c
refs/heads/master
1,600,957,431,849
1,576,465,093,000
1,576,465,093,000
225,779,423
0
3
Apache-2.0
1,575,433,936,000
1,575,433,935,000
null
UTF-8
Lean
false
false
8,280
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 data.rbtree.insert data.rbtree.min_max universes u namespace rbnode variables {α : Type u} {lt : α → α → Prop} lemma is_searchable_of_well_formed {t : rbnode α} [is_strict_weak_order α lt] : t.well_formed lt → is_searchable lt t none none := begin intro h, induction h, { constructor, simp [lift] }, { subst h_n', apply is_searchable_insert, assumption } end open color lemma is_red_black_of_well_formed {t : rbnode α} : t.well_formed lt → ∃ c n, is_red_black t c n := begin intro h, induction h, { existsi black, existsi 0, constructor }, { cases h_ih with c ih, cases ih with n ih, subst h_n', apply insert_is_red_black, assumption } end end rbnode namespace rbtree variables {α : Type u} {lt : α → α → Prop} lemma balanced (t : rbtree α lt) : 2 * t.depth min + 1 ≥ t.depth max := begin cases t with n p, simp only [depth], have := rbnode.is_red_black_of_well_formed p, cases this with _ this, cases this with _ this, apply rbnode.balanced, assumption end lemma not_mem_mk_rbtree : ∀ (a : α), a ∉ mk_rbtree α lt := by simp [has_mem.mem, rbtree.mem, rbnode.mem, mk_rbtree] lemma not_mem_of_empty {t : rbtree α lt} (a : α) : t.empty = tt → a ∉ t := by cases t with n p; cases n; simp [empty, has_mem.mem, rbtree.mem, rbnode.mem] lemma mem_of_mem_of_eqv [is_strict_weak_order α lt] {t : rbtree α lt} {a b : α} : a ∈ t → a ≈[lt] b → b ∈ t := begin cases t with n p; simp [has_mem.mem, rbtree.mem]; clear p; induction n; simp [rbnode.mem, strict_weak_order.equiv]; intros h₁ h₂; blast_disjs, iterate 2 { { have : rbnode.mem lt b n_lchild := n_ih_lchild h₁ h₂, simp [this] }, { simp [incomp_trans_of lt h₂.swap h₁] }, { have : rbnode.mem lt b n_rchild := n_ih_rchild h₁ h₂, simp [this] } } end variables [decidable_rel lt] lemma insert_ne_mk_rbtree (t : rbtree α lt) (a : α) : t.insert a ≠ mk_rbtree α lt := begin cases t with n p, simp [insert, mk_rbtree], intro h, injection h with h', apply rbnode.insert_ne_leaf lt n a h' end lemma find_correct [is_strict_weak_order α lt] (a : α) (t : rbtree α lt) : a ∈ t ↔ (∃ b, t.find a = some b ∧ a ≈[lt] b) := begin cases t, apply rbnode.find_correct, apply rbnode.is_searchable_of_well_formed, assumption end lemma find_correct_of_total [is_strict_total_order α lt] (a : α) (t : rbtree α lt) : a ∈ t ↔ t.find a = some a := iff.intro (λ h, match iff.mp (find_correct a t) h with | ⟨b, heq, heqv⟩ := by simp [heq, (eq_of_eqv_lt heqv).symm] end) (λ h, iff.mpr (find_correct a t) ⟨a, ⟨h, refl a⟩⟩) lemma find_correct_exact [is_strict_total_order α lt] (a : α) (t : rbtree α lt) : mem_exact a t ↔ t.find a = some a := begin cases t, apply rbnode.find_correct_exact, apply rbnode.is_searchable_of_well_formed, assumption end lemma find_insert_of_eqv [is_strict_weak_order α lt] (t : rbtree α lt) {x y} : x ≈[lt] y → (t.insert x).find y = some x := begin cases t, intro h, apply rbnode.find_insert_of_eqv lt h, apply rbnode.is_searchable_of_well_formed, assumption end lemma find_insert [is_strict_weak_order α lt] (t : rbtree α lt) (x) : (t.insert x).find x = some x := find_insert_of_eqv t (refl x) lemma find_insert_of_disj [is_strict_weak_order α lt] {x y : α} (t : rbtree α lt) : lt x y ∨ lt y x → (t.insert x).find y = t.find y := begin cases t, intro h, apply rbnode.find_insert_of_disj lt h, apply rbnode.is_searchable_of_well_formed, assumption end lemma find_insert_of_not_eqv [is_strict_weak_order α lt] {x y : α} (t : rbtree α lt) : ¬ x ≈[lt] y → (t.insert x).find y = t.find y := begin cases t, intro h, apply rbnode.find_insert_of_not_eqv lt h, apply rbnode.is_searchable_of_well_formed, assumption end lemma find_insert_of_ne [is_strict_total_order α lt] {x y : α} (t : rbtree α lt) : x ≠ y → (t.insert x).find y = t.find y := begin cases t, intro h, have : ¬ x ≈[lt] y := λ h', h (eq_of_eqv_lt h'), apply rbnode.find_insert_of_not_eqv lt this, apply rbnode.is_searchable_of_well_formed, assumption end lemma not_mem_of_find_none [is_strict_weak_order α lt] {a : α} {t : rbtree α lt} : t.find a = none → a ∉ t := λ h, iff.mpr (not_iff_not_of_iff (find_correct a t)) $ begin intro h, cases h with _ h, cases h with h₁ h₂, rw [h] at h₁, contradiction end lemma eqv_of_find_some [is_strict_weak_order α lt] {a b : α} {t : rbtree α lt} : t.find a = some b → a ≈[lt] b := begin cases t, apply rbnode.eqv_of_find_some, apply rbnode.is_searchable_of_well_formed, assumption end lemma eq_of_find_some [is_strict_total_order α lt] {a b : α} {t : rbtree α lt} : t.find a = some b → a = b := λ h, suffices a ≈[lt] b, from eq_of_eqv_lt this, eqv_of_find_some h lemma mem_of_find_some [is_strict_weak_order α lt] {a b : α} {t : rbtree α lt} : t.find a = some b → a ∈ t := λ h, iff.mpr (find_correct a t) ⟨b, ⟨h, eqv_of_find_some h⟩⟩ lemma find_eq_find_of_eqv [is_strict_weak_order α lt] {a b : α} (t : rbtree α lt) : a ≈[lt] b → t.find a = t.find b := begin cases t, apply rbnode.find_eq_find_of_eqv, apply rbnode.is_searchable_of_well_formed, assumption end lemma contains_correct [is_strict_weak_order α lt] (a : α) (t : rbtree α lt) : a ∈ t ↔ (t.contains a = tt) := begin have h := find_correct a t, simp [h, contains], apply iff.intro, { intro h', cases h' with _ h', cases h', simp [*], simp [option.is_some] }, { intro h', cases heq : find t a with v, simp [heq, option.is_some] at h', contradiction, existsi v, simp, apply eqv_of_find_some heq } end lemma mem_insert_of_incomp {a b : α} (t : rbtree α lt) : (¬ lt a b ∧ ¬ lt b a) → a ∈ t.insert b := begin cases t, apply rbnode.mem_insert_of_incomp end lemma mem_insert [is_irrefl α lt] : ∀ (a : α) (t : rbtree α lt), a ∈ t.insert a := begin intros, apply mem_insert_of_incomp, split; apply irrefl_of lt end lemma mem_insert_of_equiv {a b : α} (t : rbtree α lt) : a ≈[lt] b → a ∈ t.insert b := begin cases t, apply rbnode.mem_insert_of_incomp end lemma mem_insert_of_mem [is_strict_weak_order α lt] {a : α} {t : rbtree α lt} (b : α) : a ∈ t → a ∈ t.insert b := begin cases t, apply rbnode.mem_insert_of_mem end lemma equiv_or_mem_of_mem_insert [is_strict_weak_order α lt] {a b : α} {t : rbtree α lt} : a ∈ t.insert b → a ≈[lt] b ∨ a ∈ t := begin cases t, apply rbnode.equiv_or_mem_of_mem_insert end lemma incomp_or_mem_of_mem_ins [is_strict_weak_order α lt] {a b : α} {t : rbtree α lt} : a ∈ t.insert b → (¬ lt a b ∧ ¬ lt b a) ∨ a ∈ t := equiv_or_mem_of_mem_insert lemma eq_or_mem_of_mem_ins [is_strict_total_order α lt] {a b : α} {t : rbtree α lt} : a ∈ t.insert b → a = b ∨ a ∈ t := λ h, suffices a ≈[lt] b ∨ a ∈ t, by simp [eqv_lt_iff_eq] at this; assumption, incomp_or_mem_of_mem_ins h lemma mem_of_min_eq [is_irrefl α lt] {a : α} {t : rbtree α lt} : t.min = some a → a ∈ t := begin cases t, apply rbnode.mem_of_min_eq end lemma mem_of_max_eq [is_irrefl α lt] {a : α} {t : rbtree α lt} : t.max = some a → a ∈ t := begin cases t, apply rbnode.mem_of_max_eq end lemma eq_leaf_of_min_eq_none [is_strict_weak_order α lt] {t : rbtree α lt} : t.min = none → t = mk_rbtree α lt := begin cases t, intro h, congr, apply rbnode.eq_leaf_of_min_eq_none h end lemma eq_leaf_of_max_eq_none [is_strict_weak_order α lt] {t : rbtree α lt} : t.max = none → t = mk_rbtree α lt := begin cases t, intro h, congr, apply rbnode.eq_leaf_of_max_eq_none h end lemma min_is_minimal [is_strict_weak_order α lt] {a : α} {t : rbtree α lt} : t.min = some a → ∀ {b}, b ∈ t → a ≈[lt] b ∨ lt a b := begin cases t, apply rbnode.min_is_minimal, apply rbnode.is_searchable_of_well_formed, assumption end lemma max_is_maximal [is_strict_weak_order α lt] {a : α} {t : rbtree α lt} : t.max = some a → ∀ {b}, b ∈ t → a ≈[lt] b ∨ lt b a := begin cases t, apply rbnode.max_is_maximal, apply rbnode.is_searchable_of_well_formed, assumption end end rbtree
4665081ebbfaf980c189b95575d3a0ffc846a7ea
d7189ea2ef694124821b033e533f18905b5e87ef
/galois/nat/lemmas.lean
14fd4a8bcfc8210fde66dfc9cac3a5571050964d
[ "Apache-2.0" ]
permissive
digama0/lean-protocol-support
eaa7e6f8b8e0d5bbfff1f7f52bfb79a3b11b0f59
cabfa3abedbdd6fdca6e2da6fbbf91a13ed48dda
refs/heads/master
1,625,421,450,627
1,506,035,462,000
1,506,035,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,887
lean
import galois.tactic galois.list.take_drop_lemmas namespace nat lemma lt_succ_ne_lt (a b : ℕ) : a < nat.succ b → a ≠ b → a < b := begin intros lt ne, cases lt with x succ_lt, { contradiction, }, { exact succ_lt, } end lemma pos_subtract (n k : ℕ) (Hn : 0 < n) (Hk : 0 < k) : (n - k) < n := begin cases n, exfalso, apply (@@lt_irrefl _ _), apply Hn, cases k, exfalso, apply (@@lt_irrefl _ _), apply Hk, rename a n, rename a_1 k, clear Hn Hk, rw nat.succ_sub_succ, apply lt_of_le_of_lt, apply nat.sub_le_sub_left, apply nat.zero_le, rw nat.sub_zero, apply nat.lt_succ_self end lemma le_of_div_succ {n k p : ℕ} (H : n / k = nat.succ p) : k ≤ n := begin rw nat.div_def at H, by_cases ((0 < k ∧ k ≤ n)) with h; simp [h] at H, { cases h, assumption, }, { contradiction, } end lemma drop_drops_one : forall index drop_size, drop_size ≠ 0 → drop_size ≤ index -> index / drop_size = ((index - drop_size) / drop_size) + 1 := begin intros, rw nat.div_def, by_cases (0 < drop_size ∧ drop_size ≤ index) with h; simp [h], { exfalso, apply h, split, { destruct drop_size; intros; subst drop_size, { contradiction, }, { simp [nat.lt_is_succ_le], have e : (nat.succ a_2) = 1 + a_2, simp, rw e, apply nat.le_add_right } }, { assumption, } } end lemma drops_decreases : forall drop_size index, drop_size ≠ 0 → drop_size ≤ index -> ((index - drop_size) / drop_size) < index /drop_size := begin intros, rw (drop_drops_one index); try {assumption}, apply nat.lt.base, end lemma lt_of_div_succ_2 {n k p : ℕ} (H : n / k = p.succ) : (n - k) / k = p := begin cases k with k, simp at *, contradiction, have dps := drop_drops_one n (nat.succ k), have neO : nat.succ k ≠ 0, {contradiction}, specialize dps neO, clear neO, specialize dps (nat.le_of_div_succ H), rw dps at H, rw <- nat.succ_eq_add_one at H, injection H end lemma sub_le_le (m n k : ℕ) (Hmn : m ≤ n) (H : m ≤ k) : m + (n - k) ≤ n := begin induction H, apply le_of_eq, apply nat.add_sub_of_le, assumption, rw nat.sub_succ, apply le_trans, tactic.swap, apply ih_1, apply nat.add_le_add_left, apply nat.pred_le, end lemma sub_pos_le (n k : ℕ) (Hk : 0 < k) (Hn : 0 < n) : n - k + 1 ≤ n := begin cases k, exfalso, apply nat.lt_irrefl, assumption, rw nat.sub_succ, rw nat.add_comm, rw nat.one_add, cases n, exfalso, apply nat.lt_irrefl, assumption, rename a k, rename a_1 n, apply nat.succ_le_succ, clear Hk Hn, apply le_trans, apply nat.pred_le_pred, apply nat.sub_le, apply le_refl, end lemma sub_1_succ : forall (n b : ℕ), n - 1 - b = n - nat.succ b := begin intros n, induction n; intros, { dsimp, cases b, {refl}, { simp } }, { simp, } end lemma lt_succ_both : forall a b, nat.succ a < nat.succ b -> a < b := begin intros, simp [nat.lt_is_succ_le, nat.succ_le_succ_iff] at *, apply a_1, end lemma max_subtract : forall (a b : nat), (max a b) - b = a - b := begin intros a b, unfold max, apply (if H : a ≤ b then _ else _), { rw (if_pos H), rw nat.sub_eq_zero_of_le, rw nat.sub_eq_zero_of_le, assumption, apply le_refl, }, { rw (if_neg H), } end lemma mul_2_add {n : nat} : n * 2 = n + n := begin induction n, simp, dsimp [has_mul.mul, nat.mul], simp, end lemma le_add_r {x y : nat} : x ≤ x + y := begin induction y, simp, apply le_trans, assumption, apply nat.add_le_add_left, constructor, constructor, end lemma le_add_compat {x y x' y' : nat} (Hx : x ≤ x') (Hy : y ≤ y') : x + y ≤ x' + y' := begin induction Hx, apply nat.add_le_add_left, assumption, apply le_trans, apply ih_1, simp, apply nat.add_le_add_left, constructor, constructor, end lemma max_same (n : ℕ) : max n n = n := begin unfold max, rw (if_pos (le_refl n)), end lemma max_add {m n k : ℕ} : max (m + k) (n + k) = max m n + k := begin unfold max, apply (if H : m ≤ n then _ else _), rw (if_pos H), rw if_pos, apply nat.add_le_add_right, assumption, rw (if_neg H), rw if_neg, intros contra, apply H, rw ← nat.add_le_add_iff_le_right, assumption, end lemma neg_le_le (x y : ℕ) (H : ¬ x ≤ y) : y ≤ x := begin apply (if H' : y ≤ x then _ else _), assumption, exfalso, have H1 := @nat.le_total x y, induction H1; contradiction, end lemma max_mono {x y x' y' : ℕ} (Hx : x ≤ x') (Hy : y ≤ y') : max x y ≤ max x' y' := begin unfold max, apply (if H : x ≤ y then _ else _), { rw (if_pos H), apply (if H' : x' ≤ y' then _ else _), rw (if_pos H'), assumption, rw (if_neg H'), apply le_trans, assumption, apply nat.neg_le_le, assumption, }, { rw (if_neg H), apply (if H' : x' ≤ y' then _ else _), rw (if_pos H'), apply le_trans; assumption, rw (if_neg H'), assumption, } end lemma max_0_r (x : ℕ) : max x 0 = x := begin unfold max, apply (if H : x ≤ 0 then _ else _), rw (if_pos H), symmetry, rw ← nat.le_zero_iff, assumption, rw if_neg, assumption, end end nat
a6e7e138420192925e08f6b61a8101b27a1e4fbd
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/src/Init/Data/String/Basic.lean
71bbce7ae2a2a5cdb23668af0f1997a90c91b5a0
[ "Apache-2.0" ]
permissive
gebner/lean4-old
a4129a041af2d4d12afb3a8d4deedabde727719b
ee51cdfaf63ee313c914d83264f91f414a0e3b6e
refs/heads/master
1,683,628,606,745
1,622,651,300,000
1,622,654,405,000
142,608,821
1
0
null
null
null
null
UTF-8
Lean
false
false
17,099
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import Init.Data.List.Basic import Init.Data.Char.Basic import Init.Data.Option.Basic universes u def List.asString (s : List Char) : String := ⟨s⟩ namespace String instance : LT String := ⟨fun s₁ s₂ => s₁.data < s₂.data⟩ @[extern "lean_string_dec_lt"] instance decLt (s₁ s₂ : @& String) : Decidable (s₁ < s₂) := List.hasDecidableLt s₁.data s₂.data @[extern "lean_string_length"] def length : (@& String) → Nat | ⟨s⟩ => s.length /-- The internal implementation uses dynamic arrays and will perform destructive updates if the String is not shared. -/ @[extern "lean_string_push"] def push : String → Char → String | ⟨s⟩, c => ⟨s ++ [c]⟩ /-- The internal implementation uses dynamic arrays and will perform destructive updates if the String is not shared. -/ @[extern "lean_string_append"] def append : String → (@& String) → String | ⟨a⟩, ⟨b⟩ => ⟨a ++ b⟩ /-- O(n) in the runtime, where n is the length of the String -/ def toList (s : String) : List Char := s.data private def utf8GetAux : List Char → Pos → Pos → Char | [], i, p => arbitrary | c::cs, i, p => if i = p then c else utf8GetAux cs (i + csize c) p @[extern "lean_string_utf8_get"] def get : (@& String) → (@& Pos) → Char | ⟨s⟩, p => utf8GetAux s 0 p def getOp (self : String) (idx : Pos) : Char := self.get idx private def utf8SetAux (c' : Char) : List Char → Pos → Pos → List Char | [], i, p => [] | c::cs, i, p => if i = p then (c'::cs) else c::(utf8SetAux c' cs (i + csize c) p) @[extern "lean_string_utf8_set"] def set : String → (@& Pos) → Char → String | ⟨s⟩, i, c => ⟨utf8SetAux c s 0 i⟩ def modify (s : String) (i : Pos) (f : Char → Char) : String := s.set i <| f <| s.get i @[extern "lean_string_utf8_next"] def next (s : @& String) (p : @& Pos) : Pos := let c := get s p p + csize c private def utf8PrevAux : List Char → Pos → Pos → Pos | [], i, p => 0 | c::cs, i, p => let cz := csize c let i' := i + cz if i' = p then i else utf8PrevAux cs i' p @[extern "lean_string_utf8_prev"] def prev : (@& String) → (@& Pos) → Pos | ⟨s⟩, p => if p = 0 then 0 else utf8PrevAux s 0 p def front (s : String) : Char := get s 0 def back (s : String) : Char := get s (prev s (bsize s)) @[extern "lean_string_utf8_at_end"] def atEnd : (@& String) → (@& Pos) → Bool | s, p => p ≥ utf8ByteSize s /- TODO: remove `partial` keywords after we restore the tactic framework and wellfounded recursion support -/ partial def posOfAux (s : String) (c : Char) (stopPos : Pos) (pos : Pos) : Pos := if pos == stopPos then pos else if s.get pos == c then pos else posOfAux s c stopPos (s.next pos) @[inline] def posOf (s : String) (c : Char) : Pos := posOfAux s c s.bsize 0 partial def revPosOfAux (s : String) (c : Char) (pos : Pos) : Option Pos := if s.get pos == c then some pos else if pos == 0 then none else revPosOfAux s c (s.prev pos) def revPosOf (s : String) (c : Char) : Option Pos := if s.bsize == 0 then none else revPosOfAux s c (s.prev s.bsize) partial def findAux (s : String) (p : Char → Bool) (stopPos : Pos) (pos : Pos) : Pos := if pos == stopPos then pos else if p (s.get pos) then pos else findAux s p stopPos (s.next pos) @[inline] def find (s : String) (p : Char → Bool) : Pos := findAux s p s.bsize 0 partial def revFindAux (s : String) (p : Char → Bool) (pos : Pos) : Option Pos := if p (s.get pos) then some pos else if pos == 0 then none else revFindAux s p (s.prev pos) def revFind (s : String) (p : Char → Bool) : Option Pos := if s.bsize == 0 then none else revFindAux s p (s.prev s.bsize) private def utf8ExtractAux₂ : List Char → Pos → Pos → List Char | [], _, _ => [] | c::cs, i, e => if i = e then [] else c :: utf8ExtractAux₂ cs (i + csize c) e private def utf8ExtractAux₁ : List Char → Pos → Pos → Pos → List Char | [], _, _, _ => [] | s@(c::cs), i, b, e => if i = b then utf8ExtractAux₂ s i e else utf8ExtractAux₁ cs (i + csize c) b e @[extern "lean_string_utf8_extract"] def extract : (@& String) → (@& Pos) → (@& Pos) → String | ⟨s⟩, b, e => if b ≥ e then ⟨[]⟩ else ⟨utf8ExtractAux₁ s 0 b e⟩ @[specialize] partial def splitAux (s : String) (p : Char → Bool) (b : Pos) (i : Pos) (r : List String) : List String := if s.atEnd i then let r := (s.extract b i)::r r.reverse else if p (s.get i) then let i := s.next i splitAux s p i i (s.extract b (i-1)::r) else splitAux s p b (s.next i) r @[specialize] def split (s : String) (p : Char → Bool) : List String := splitAux s p 0 0 [] partial def splitOnAux (s sep : String) (b : Pos) (i : Pos) (j : Pos) (r : List String) : List String := if s.atEnd i then let r := if sep.atEnd j then ""::(s.extract b (i-j))::r else (s.extract b i)::r r.reverse else if s.get i == sep.get j then let i := s.next i let j := sep.next j if sep.atEnd j then splitOnAux s sep i i 0 (s.extract b (i-j)::r) else splitOnAux s sep b i j r else splitOnAux s sep b (s.next i) 0 r def splitOn (s : String) (sep : String := " ") : List String := if sep == "" then [s] else splitOnAux s sep 0 0 0 [] instance : Inhabited String := ⟨""⟩ instance : Append String := ⟨String.append⟩ def str : String → Char → String := push def pushn (s : String) (c : Char) (n : Nat) : String := n.repeat (fun s => s.push c) s def isEmpty (s : String) : Bool := s.bsize == 0 def join (l : List String) : String := l.foldl (fun r s => r ++ s) "" def singleton (c : Char) : String := "".push c def intercalate (s : String) (ss : List String) : String := (List.intercalate s.toList (ss.map toList)).asString structure Iterator where s : String i : Pos def mkIterator (s : String) : Iterator := ⟨s, 0⟩ namespace Iterator def toString : Iterator → String | ⟨s, _⟩ => s def remainingBytes : Iterator → Nat | ⟨s, i⟩ => s.bsize - i def pos : Iterator → Pos | ⟨s, i⟩ => i def curr : Iterator → Char | ⟨s, i⟩ => get s i def next : Iterator → Iterator | ⟨s, i⟩ => ⟨s, s.next i⟩ def prev : Iterator → Iterator | ⟨s, i⟩ => ⟨s, s.prev i⟩ def hasNext : Iterator → Bool | ⟨s, i⟩ => i < utf8ByteSize s def hasPrev : Iterator → Bool | ⟨s, i⟩ => i > 0 def setCurr : Iterator → Char → Iterator | ⟨s, i⟩, c => ⟨s.set i c, i⟩ def toEnd : Iterator → Iterator | ⟨s, _⟩ => ⟨s, s.bsize⟩ def extract : Iterator → Iterator → String | ⟨s₁, b⟩, ⟨s₂, e⟩ => if s₁ ≠ s₂ || b > e then "" else s₁.extract b e def forward : Iterator → Nat → Iterator | it, 0 => it | it, n+1 => forward it.next n def remainingToString : Iterator → String | ⟨s, i⟩ => s.extract i s.bsize /-- `(isPrefixOfRemaining it₁ it₂)` is `true` iff `it₁.remainingToString` is a prefix of `it₂.remainingToString`. -/ def isPrefixOfRemaining : Iterator → Iterator → Bool | ⟨s₁, i₁⟩, ⟨s₂, i₂⟩ => s₁.extract i₁ s₁.bsize = s₂.extract i₂ (i₂ + (s₁.bsize - i₁)) def nextn : Iterator → Nat → Iterator | it, 0 => it | it, i+1 => nextn it.next i def prevn : Iterator → Nat → Iterator | it, 0 => it | it, i+1 => prevn it.prev i end Iterator partial def offsetOfPosAux (s : String) (pos : Pos) (i : Pos) (offset : Nat) : Nat := if i == pos || s.atEnd i then offset else offsetOfPosAux s pos (s.next i) (offset+1) def offsetOfPos (s : String) (pos : Pos) : Nat := offsetOfPosAux s pos 0 0 @[specialize] partial def foldlAux {α : Type u} (f : α → Char → α) (s : String) (stopPos : Pos) (i : Pos) (a : α) : α := let rec loop (i : Pos) (a : α) := if i == stopPos then a else loop (s.next i) (f a (s.get i)) loop i a @[inline] def foldl {α : Type u} (f : α → Char → α) (a : α) (s : String) : α := foldlAux f s s.bsize 0 a @[specialize] partial def foldrAux {α : Type u} (f : Char → α → α) (a : α) (s : String) (stopPos : Pos) (i : Pos) : α := let rec loop (i : Pos) := if i == stopPos then a else f (s.get i) (loop (s.next i)) loop i @[inline] def foldr {α : Type u} (f : Char → α → α) (a : α) (s : String) : α := foldrAux f a s s.bsize 0 @[specialize] partial def anyAux (s : String) (stopPos : Pos) (p : Char → Bool) (i : Pos) : Bool := let rec loop (i : Pos) := if i == stopPos then false else if p (s.get i) then true else loop (s.next i) loop i @[inline] def any (s : String) (p : Char → Bool) : Bool := anyAux s s.bsize p 0 @[inline] def all (s : String) (p : Char → Bool) : Bool := !s.any (fun c => !p c) def contains (s : String) (c : Char) : Bool := s.any (fun a => a == c) @[specialize] partial def mapAux (f : Char → Char) (i : Pos) (s : String) : String := if s.atEnd i then s else let c := f (s.get i) let s := s.set i c mapAux f (s.next i) s @[inline] def map (f : Char → Char) (s : String) : String := mapAux f 0 s def isNat (s : String) : Bool := s.all fun c => c.isDigit def toNat? (s : String) : Option Nat := if s.isNat then some <| s.foldl (fun n c => n*10 + (c.toNat - '0'.toNat)) 0 else none /-- Return true iff `p` is a prefix of `s` -/ partial def isPrefixOf (p : String) (s : String) : Bool := let rec loop (i : Pos) := if p.atEnd i then true else let c₁ := p.get i let c₂ := s.get i c₁ == c₂ && loop (s.next i) p.length ≤ s.length && loop 0 end String namespace Substring @[inline] def isEmpty (ss : Substring) : Bool := ss.bsize == 0 @[inline] def toString : Substring → String | ⟨s, b, e⟩ => s.extract b e @[inline] def toIterator : Substring → String.Iterator | ⟨s, b, _⟩ => ⟨s, b⟩ /-- Return the codepoint at the given offset into the substring. -/ @[inline] def get : Substring → String.Pos → Char | ⟨s, b, _⟩, p => s.get (b+p) /-- Given an offset of a codepoint into the substring, return the offset there of the next codepoint. -/ @[inline] private def next : Substring → String.Pos → String.Pos | ⟨s, b, e⟩, p => let absP := b+p if absP = e then p else s.next absP - b /-- Given an offset of a codepoint into the substring, return the offset there of the previous codepoint. -/ @[inline] private def prev : Substring → String.Pos → String.Pos | ⟨s, b, _⟩, p => let absP := b+p if absP = b then p else s.prev absP - b private def nextn : Substring → Nat → String.Pos → String.Pos | ss, 0, p => p | ss, i+1, p => ss.nextn i (ss.next p) private def prevn : Substring → String.Pos → Nat → String.Pos | ss, 0, p => p | ss, i+1, p => ss.prevn i (ss.prev p) @[inline] def front (s : Substring) : Char := s.get 0 /-- Return the offset into `s` of the first occurence of `c` in `s`, or `s.bsize` if `c` doesn't occur. -/ @[inline] def posOf (s : Substring) (c : Char) : String.Pos := match s with | ⟨s, b, e⟩ => (String.posOfAux s c e b) - b @[inline] def drop : Substring → Nat → Substring | ss@⟨s, b, e⟩, n => ⟨s, b + ss.nextn n 0, e⟩ @[inline] def dropRight : Substring → Nat → Substring | ss@⟨s, b, e⟩, n => ⟨s, b, b + ss.prevn n ss.bsize⟩ @[inline] def take : Substring → Nat → Substring | ss@⟨s, b, e⟩, n => ⟨s, b, b + ss.nextn n 0⟩ @[inline] def takeRight : Substring → Nat → Substring | ss@⟨s, b, e⟩, n => ⟨s, b + ss.prevn n ss.bsize, e⟩ @[inline] def atEnd : Substring → String.Pos → Bool | ⟨s, b, e⟩, p => b + p == e @[inline] def extract : Substring → String.Pos → String.Pos → Substring | ⟨s, b, _⟩, b', e' => if b' ≥ e' then ⟨"", 0, 1⟩ else ⟨s, b+b', b+e'⟩ partial def splitOn (s : Substring) (sep : String := " ") : List Substring := if sep == "" then [s] else let stopPos := s.stopPos let str := s.str let rec loop (b i j : String.Pos) (r : List Substring) : List Substring := if i == stopPos then let r := if sep.atEnd j then "".toSubstring::{ str := str, startPos := b, stopPos := i-j } :: r else { str := str, startPos := b, stopPos := i } :: r r.reverse else if s.get i == sep.get j then let i := s.next i let j := sep.next j if sep.atEnd j then loop i i 0 ({ str := str, startPos := b, stopPos := i-j } :: r) else loop b i j r else loop b (s.next i) 0 r loop s.startPos s.startPos 0 [] @[inline] def foldl {α : Type u} (f : α → Char → α) (a : α) (s : Substring) : α := match s with | ⟨s, b, e⟩ => String.foldlAux f s e b a @[inline] def foldr {α : Type u} (f : Char → α → α) (a : α) (s : Substring) : α := match s with | ⟨s, b, e⟩ => String.foldrAux f a s e b @[inline] def any (s : Substring) (p : Char → Bool) : Bool := match s with | ⟨s, b, e⟩ => String.anyAux s e p b @[inline] def all (s : Substring) (p : Char → Bool) : Bool := !s.any (fun c => !p c) def contains (s : Substring) (c : Char) : Bool := s.any (fun a => a == c) @[specialize] private partial def takeWhileAux (s : String) (stopPos : String.Pos) (p : Char → Bool) (i : String.Pos) : String.Pos := if i == stopPos then i else if p (s.get i) then takeWhileAux s stopPos p (s.next i) else i @[inline] def takeWhile : Substring → (Char → Bool) → Substring | ⟨s, b, e⟩, p => let e := takeWhileAux s e p b; ⟨s, b, e⟩ @[inline] def dropWhile : Substring → (Char → Bool) → Substring | ⟨s, b, e⟩, p => let b := takeWhileAux s e p b; ⟨s, b, e⟩ @[specialize] private partial def takeRightWhileAux (s : String) (begPos : String.Pos) (p : Char → Bool) (i : String.Pos) : String.Pos := if i == begPos then i else let i' := s.prev i let c := s.get i' if !p c then i else takeRightWhileAux s begPos p i' @[inline] def takeRightWhile : Substring → (Char → Bool) → Substring | ⟨s, b, e⟩, p => let b := takeRightWhileAux s b p e ⟨s, b, e⟩ @[inline] def dropRightWhile : Substring → (Char → Bool) → Substring | ⟨s, b, e⟩, p => let e := takeRightWhileAux s b p e ⟨s, b, e⟩ @[inline] def trimLeft (s : Substring) : Substring := s.dropWhile Char.isWhitespace @[inline] def trimRight (s : Substring) : Substring := s.dropRightWhile Char.isWhitespace @[inline] def trim : Substring → Substring | ⟨s, b, e⟩ => let b := takeWhileAux s e Char.isWhitespace b let e := takeRightWhileAux s b Char.isWhitespace e ⟨s, b, e⟩ def isNat (s : Substring) : Bool := s.all fun c => c.isDigit def toNat? (s : Substring) : Option Nat := if s.isNat then some <| s.foldl (fun n c => n*10 + (c.toNat - '0'.toNat)) 0 else none def beq (ss1 ss2 : Substring) : Bool := -- TODO: should not allocate ss1.bsize == ss2.bsize && ss1.toString == ss2.toString instance hasBeq : BEq Substring := ⟨beq⟩ end Substring namespace String def drop (s : String) (n : Nat) : String := (s.toSubstring.drop n).toString def dropRight (s : String) (n : Nat) : String := (s.toSubstring.dropRight n).toString def take (s : String) (n : Nat) : String := (s.toSubstring.take n).toString def takeRight (s : String) (n : Nat) : String := (s.toSubstring.takeRight n).toString def takeWhile (s : String) (p : Char → Bool) : String := (s.toSubstring.takeWhile p).toString def dropWhile (s : String) (p : Char → Bool) : String := (s.toSubstring.dropWhile p).toString def takeRightWhile (s : String) (p : Char → Bool) : String := (s.toSubstring.takeRightWhile p).toString def dropRightWhile (s : String) (p : Char → Bool) : String := (s.toSubstring.dropRightWhile p).toString def startsWith (s pre : String) : Bool := s.toSubstring.take pre.length == pre.toSubstring def endsWith (s post : String) : Bool := s.toSubstring.takeRight post.length == post.toSubstring def trimRight (s : String) : String := s.toSubstring.trimRight.toString def trimLeft (s : String) : String := s.toSubstring.trimLeft.toString def trim (s : String) : String := s.toSubstring.trim.toString @[inline] def nextWhile (s : String) (p : Char → Bool) (i : String.Pos) : String.Pos := Substring.takeWhileAux s s.bsize p i @[inline] def nextUntil (s : String) (p : Char → Bool) (i : String.Pos) : String.Pos := nextWhile s (fun c => !p c) i def toUpper (s : String) : String := s.map Char.toUpper def toLower (s : String) : String := s.map Char.toLower def capitalize (s : String) := s.set 0 <| s.get 0 |>.toUpper def decapitalize (s : String) := s.set 0 <| s.get 0 |>.toLower end String protected def Char.toString (c : Char) : String := String.singleton c
c7aa1532221a223398f8da12db1e76a1d3a8a0c7
de44c57911f8f2292d4105ccefe4372f3880a7b7
/src/stlc.lean
445614448ae5bb292627f7e8a70623a3416f018a
[]
no_license
nyuichi/LeanHOL
108b1df4daab61b60b0160a7f56cf6b7dd8f57fe
8190f2d4234f0f39c9e7b5612e552e72ab002798
refs/heads/master
1,587,207,990,491
1,569,724,629,000
1,569,724,629,000
167,488,678
22
0
null
null
null
null
UTF-8
Lean
false
false
16,726
lean
-- 2. simply typed lambda calculus import moromoro import logic.basic namespace stlc inductive type : Type | base : type | arrow : type → type → type open type def type.repr : type → string | base := "ι" | (arrow t₁ t₂) := "(" ++ type.repr t₁ ++ " → " ++ type.repr t₂ ++ ")" instance type_has_repr : has_repr type := ⟨type.repr⟩ #eval (arrow (arrow base base) base) ---- variables ν : type → Type inductive term : type → Type | var : Π {t}, ν t → term t | lam : Π {t₁ t₂}, (ν t₁ → term t₂) → term (arrow t₁ t₂) | app : Π {t₁ t₂}, term (arrow t₁ t₂) → term t₁ → term t₂ open term def Term (t : type) : Type 1 := Π ν, term ν t variables {t t₁ t₂ t₃ : type} def term.repr' : Π {t : type}, term (λ t, ℕ) t → ℕ → string | _ (var n) _ := repr n | _ (lam f) lv := "(λ" ++ repr lv ++ "." ++ term.repr' (f lv) (lv + 1) ++ ")" | _ (app m₁ m₂) lv := "(" ++ term.repr' m₁ lv ++ " " ++ term.repr' m₂ lv ++ ")" def term.repr : Term t → string := λ m, term.repr' (m _) 0 ++ " : " ++ repr t instance Term_has_repr : has_repr (Term t) := ⟨ term.repr ⟩ def nat : type := arrow (arrow base base) (arrow base base) def zero : Term nat := λ ν, lam (λ f, lam (λ x, var x)) def succ : Term (arrow nat nat) := λ ν, lam (λ n, lam (λ f, lam (λ x, app (var f) (app (app (var n) (var f)) (var x))))) def App : Term (arrow t₁ t₂) → Term t₁ → Term t₂ := λ m₁ m₂ ν, app (m₁ ν) (m₂ ν) def succ_zero : Term nat := App succ zero #eval zero --> (λ0.(λ1.1)) : ((ι → ι) → (ι → ι)) #eval succ --> (λ0.(λ1.(λ2.(1 ((0 1) 2))))) : (((ι → ι) → (ι → ι)) → ((ι → ι) → (ι → ι))) #eval succ_zero --> ((λ0.(λ1.(λ2.(1 ((0 1) 2))))) (λ0.(λ1.1))) : ((ι → ι) → (ι → ι)) -- -- // error! -- def ω : Term _ := -- no such type -- λ ν, lam (λ x, app (var x) (var x)) ---- def domain : type → Type | base := term ν base | (arrow t₁ t₂) := domain t₁ → domain t₂ def Domain (t : type) : Type 1 := Π ν, domain ν t def eval' : Π {t : type}, term (domain ν) t → domain ν t | _ (var x) := x | _ (lam f) := λ x, eval' (f x) | _ (app m₁ m₂) := (eval' m₁) (eval' m₂) def eval : Term t → Domain t := λ m ν, eval' ν (m _) -- def nbe_wf : psum (Σ' {t : type}, domain ν t) (Σ' {t : type}, term ν t) → ℕ := -- λ v, match v with -- | (psum.inl x) := sizeof x.fst -- | (psum.inr x) := sizeof x.fst -- end -- mutual def reify, reflect -- with reify : Π {t : type}, domain ν t → term ν t -- | base ν := ν -- | (arrow t₁ t₂) f := lam (λ x, reify (f (reflect (var x)))) -- with reflect : Π {t : type}, term ν t → domain ν t -- | base m := m -- | (arrow t₁ t₂) f := λ x, reflect (app f (reify x)) -- using_well_founded -- { rel_tac := λ _ _, `[exact ⟨_, measure_wf (nbe_wf ν)⟩] } def reify_reflect : Π (t : type), (domain ν t → term ν t) × (term ν t → domain ν t) | base := ⟨ id, id ⟩ | (arrow t₁ t₂) := let r₁ := reify_reflect t₁ in let r₂ := reify_reflect t₂ in let reify (f : domain ν t₁ → domain ν t₂) := lam (λ x, r₂.1 (f (r₁.2 (var x)))) in let reflect (f : term ν (arrow t₁ t₂)) := λ x, r₂.2 (app f (r₁.1 x)) in ⟨reify, reflect⟩ def reify : Domain t → Term t := λ x ν, (reify_reflect ν t).1 (x ν) def normalize : Term t → Term t := reify ∘ eval #eval normalize zero #eval normalize (App succ zero) #eval normalize (App succ (App succ zero)) #eval normalize (App succ (App succ (App succ zero))) def i : Term (arrow (arrow base base) (arrow base base)) := λ ν, lam (λ f, var f) #eval i #eval normalize i instance : setoid (Term t) := ⟨inv_image eq normalize, inv_image.equivalence eq normalize eq_equivalence⟩ meta def canonicity : tactic unit := `[ try { unfold has_equiv.equiv setoid.r inv_image }, try { reflexivity } ] def one : Term (arrow (arrow base base) (arrow base base)) := λ ν, lam (λ f, lam (λ x, app (var f) (var x))) lemma zero_eqv_zero : zero ≈ zero := by canonicity lemma succ_zero_eqv_one : App succ zero ≈ one := by canonicity ---- variable {α : Type} inductive mem : α → list α → Type | here : Π {x l}, mem x (x :: l) | there : Π {x l y}, mem x l → mem x (y :: l) open mem local infix ` ∈' `:50 := mem inductive judgment₁ : list type → type → Type | var : Π {Γ t}, t ∈' Γ → judgment₁ Γ t | lam : Π {Γ t₁ t₂}, judgment₁ (t₁ :: Γ) t₂ → judgment₁ Γ (arrow t₁ t₂) | app : Π {Γ t₁ t₂}, judgment₁ Γ (arrow t₁ t₂) → judgment₁ Γ t₁ → judgment₁ Γ t₂ open judgment₁ variables {Γ Γ₁ Γ₂ : list type} def judgment₁.repr' : Π {Γ t}, judgment₁ Γ t → string | Γ _ (var h) := repr $ Γ.length - 1 - (h.rec_on (λ _ _, 0) (λ _ _ _ _ (n : ℕ), n + 1)) | Γ _ (lam m) := "(λ" ++ repr Γ.length ++ "." ++ judgment₁.repr' m ++ ")" | _ _ (app m₁ m₂) := "(" ++ judgment₁.repr' m₁ ++ " " ++ judgment₁.repr' m₂ ++ ")" def judgment₁.repr : Π {Γ t}, judgment₁ Γ t → string := λ Γ t m, let env := (Γ.foldr (λ t p, prod.mk (prod.mk p.2 t :: p.1) (p.2 + 1)) (prod.mk [] 0)).1 in let assigns := list.map (λ p, repr (prod.fst p) ++ " : " ++ repr (prod.snd p)) env in string.intercalate ", " assigns ++ " ⊢ " ++ judgment₁.repr' m ++ " : " ++ repr t instance : has_to_string (judgment₁ Γ t) := ⟨judgment₁.repr⟩ -- x₁ : ι → ι, x₀ : ι ⊢ λ y, x₀ : (ι → ι) → ι def ex1 : judgment₁ [arrow base base, base] (arrow (arrow base base) base) := lam (var (there (there here))) #eval ex1 -- "1 : (ι → ι), 0 : ι ⊢ (λ2.0) : ((ι → ι) → ι)" ---- inductive perm : list α → list α → Type -- proof relevant version | nil : perm [] [] | skip : Π {x : α} {l₁ l₂ : list α}, perm l₁ l₂ → perm (x :: l₁) (x :: l₂) | swap : Π {x y : α} {l : list α}, perm (y :: x :: l) (x :: y :: l) | trans : Π {l₁ l₂ l₃ : list α}, perm l₁ l₂ → perm l₂ l₃ → perm l₁ l₃ local infix ~ := perm def mem_perm {t : α} : Π {Γ₁ Γ₂}, Γ₁ ~ Γ₂ → t ∈' Γ₁ → t ∈' Γ₂ | _ _ perm.nil h := h | _ _ (perm.skip _) here := here | _ _ (perm.skip p) (there h) := there (mem_perm p h) | _ _ perm.swap here := there here | _ _ perm.swap (there here) := here | _ _ perm.swap (there (there h)) := there (there h) | _ _ (perm.trans p₁ p₂) h := mem_perm p₂ (mem_perm p₁ h) namespace judgment₁ def xchg : Π {Γ₁ Γ₂ t}, (Γ₁ ~ Γ₂) → judgment₁ Γ₁ t → judgment₁ Γ₂ t | _ _ _ p (var h) := var (mem_perm p h) | _ _ _ p (lam m) := lam (xchg (perm.skip p) m) | _ _ _ p (app m₁ m₂) := app (xchg p m₁) (xchg p m₂) def weak : Π {Γ t₁ t₂}, judgment₁ Γ t₁ → judgment₁ (t₂ :: Γ) t₁ | _ _ _ (var h) := var (there h) | _ _ _ (lam m) := lam (xchg perm.swap (weak m)) | _ _ _ (app m₁ m₂) := app (weak m₁) (weak m₂) def heightof : Π {Γ t}, judgment₁ Γ t → ℕ | _ _ (var h) := 1 | _ _ (lam m) := 1 + heightof m | _ _ (app m₁ m₂) := 1 + max (heightof m₁) (heightof m₂) lemma height_xchg_eq_height {m : judgment₁ Γ₁ t} : Π {Γ₂} {p : Γ₁ ~ Γ₂}, heightof (xchg p m) = heightof m := begin induction m with _ _ _ _ _ _ _ ih₁ _ _ _ _ _ ih₂ ih₃, { intros, refl }, { intros, unfold xchg heightof, rw ih₁ }, { intros, unfold xchg heightof, rw [ih₂, ih₃] } end def subst : Π {Γ t₁ t₂}, judgment₁ (t₁ :: Γ) t₂ → judgment₁ Γ t₁ → judgment₁ Γ t₂ | _ _ _ (var here) m := m | _ _ _ (var (there h)) m := var h | _ _ _ (app m₁ m₂) m := have heightof m₁ < heightof (app m₁ m₂), by unfold heightof; rw add_comm; from lt_add_of_le_of_pos (le_max_left _ _) zero_lt_one, have heightof m₂ < heightof (app m₁ m₂), by unfold heightof; rw add_comm; from lt_add_of_le_of_pos (le_max_right _ _) zero_lt_one, app (subst m₁ m) (subst m₂ m) | _ _ _ (lam m₁) m := have heightof (xchg perm.swap m₁) < heightof (lam m₁), by unfold heightof; rw height_xchg_eq_height; from lt_add_of_pos_of_le zero_lt_one (le_refl _), lam (subst (xchg perm.swap m₁) (weak m)) using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ v, heightof v.snd.snd.snd.fst)⟩] } def contr : judgment₁ (t₁ :: t₁ :: Γ) t₂ → judgment₁ (t₁ :: Γ) t₂ := λ m, subst m (var here) def abs : judgment₁ (t₁ :: Γ) t₂ → judgment₁ Γ (arrow t₁ t₂) := lam def antiabs : judgment₁ Γ (arrow t₁ t₂) → judgment₁ (t₁ :: Γ) t₂ := λ m, app (weak m) (var here) end judgment₁ ---- def type.foldl : list type → type → type := λ Γ t, list.foldl (λ r t, arrow t r) t Γ #eval type.foldl [arrow base base, base] base -- "(ι → ((ι → ι) → ι))" namespace judgment₁ inductive env : list type → Type | nil {} : env [] | step : Π {t Γ}, ν t → env Γ → env (t :: Γ) def to_term_var : Π {Γ t}, t ∈' Γ → env ν Γ → term ν t | (_ :: Γ) _ here (env.step x _) := term.var x | (_ :: Γ) _ (there h) (env.step _ Δ) := to_term_var h Δ def to_term' : Π {Γ t}, judgment₁ Γ t → env ν Γ → term ν t | _ _ (var h) Δ := to_term_var ν h Δ | _ _ (lam m) Δ := term.lam (λ x, to_term' m (env.step x Δ)) | _ _ (app m₁ m₂) Δ := term.app (to_term' m₁ Δ) (to_term' m₂ Δ) def foldl : Π {Γ t}, judgment₁ Γ t → judgment₁ [] (type.foldl Γ t) | [] _ m := m | (t :: Γ) _ m := foldl (lam m) def to_term : judgment₁ Γ t → Term (type.foldl Γ t) := λ m ν, to_term' ν (foldl m) env.nil end judgment₁ ---- variables {ν₁ ν₂ : type → Type} inductive wf : list (Σ t, ν₁ t × ν₂ t) → Π {t}, term ν₁ t → term ν₂ t → Type | var : Π {Γ t} {x₁ : ν₁ t} {x₂ : ν₂ t}, sigma.mk t (prod.mk x₁ x₂) ∈' Γ → wf Γ (var x₁) (var x₂) | lam : Π {Γ t₁ t₂} {f₁ : ν₁ t₁ → term ν₁ t₂} {f₂ : ν₂ t₁ → term ν₂ t₂}, (Π x₁ x₂, wf (⟨t₁, x₁, x₂⟩ :: Γ) (f₁ x₁) (f₂ x₂)) → wf Γ (lam f₁) (lam f₂) | app : Π {Γ t₁ t₂} {m₁ : term ν₁ (arrow t₁ t₂)} {m₂ : term ν₂ (arrow t₁ t₂)} {n₁ : term ν₁ t₁} {n₂ : term ν₂ t₁}, wf Γ m₁ m₂ → wf Γ n₁ n₂ → wf Γ (app m₁ n₁) (app m₂ n₂) def WF (t : type) (m : Term t) : Type 1 := Π ν₁ ν₂, wf [] (m ν₁) (m ν₂) constant term_wf : Π t m, WF t m def to_judgment₁_var : Π {Γ t} {x₁ : ν₁ t} {x₂ : ν₂ t}, (sigma.mk t (prod.mk x₁ x₂)) ∈' Γ → t ∈' (list.map (λ x, sigma.fst x) Γ) | _ _ _ _ here := here | _ _ _ _ (there h) := there (to_judgment₁_var h) def to_judgment₁' : Π {Γ t} {m₁ : term (λ x, unit) t} {m₂ : term (λ x, unit) t}, wf Γ m₁ m₂ → judgment₁ (list.map (λ x, sigma.fst x) Γ) t | _ _ _ _ (wf.var h) := var (to_judgment₁_var h) | _ _ _ _ (wf.lam f) := lam (to_judgment₁' (f () ())) | _ _ _ _ (wf.app m₁ m₂) := app (to_judgment₁' m₁) (to_judgment₁' m₂) noncomputable def to_judgment₁ : Term t → judgment₁ [] t := λ m, to_judgment₁' (term_wf _ m _ _) -------------- -- def judgment0 (t : type) := Π ν, term ν t -- def judgment1 (t₁ t₂ : type) := Π ν, ν t₁ → term ν t₂ -- term with one free variable def judgment₂ : list type → type → Type := λ Γ t, list.foldr (λ t α, ν t → α) (term ν t) Γ def Judgment₂ (Γ : list type) (t : type) : Type 1 := -- Type 1 Π ν, judgment₂ ν Γ t #reduce Judgment₂ [] base -- Π ν, term ν base #reduce Judgment₂ [base] base -- Π ν, ν base → term ν base #reduce Judgment₂ [base, base] base -- Π ν, ν base → ν base → term ν base #reduce Judgment₂ [base, arrow base base] base -- Π ν, ν base → ν (arrow base base) → term ν base def judgment₂.repr' : Π {Γ}, judgment₂ (λ t, ℕ) Γ t → ℕ → string | [] m lv := "⊢ " ++ term.repr' m lv | (t :: Γ) f lv := "(" ++ repr lv ++ " : " ++ repr t ++ ") " ++ judgment₂.repr' (f lv) (lv + 1) def judgment₂.repr : Judgment₂ Γ t → string := λ m, judgment₂.repr' (m _) 0 ++ " : " ++ repr t instance Judgment₂_has_repr : has_repr (Judgment₂ Γ t) := ⟨judgment₂.repr⟩ -- x₁ : ι → ι, x₂ : ι ⊢ (λ y : ι, x₂) : ι → ι def ex2 : Judgment₂ [arrow base base, base] (arrow base base) := λ ν, λ x₁ x₂, lam (λ y, var x₂) #eval ex2 -- "(0 : (ι → ι)) (1 : ι) ⊢ (λ2.1) : (ι → ι)" ----- def subst' : Π {t}, term (term ν) t → term ν t | _ (var m) := m | _ (lam f) := lam (λ x, subst' (f (var x))) | _ (app m₁ m₂) := app (subst' m₁) (subst' m₂) namespace judgment₂ def weak : Judgment₂ Γ t₂ → Judgment₂ (t₁ :: Γ) t₂ := λ m ν x, m ν def xchg' : Π {Γ₁ Γ₂}, (Γ₁ ~ Γ₂) → judgment₂ ν Γ₁ t → judgment₂ ν Γ₂ t | _ _ perm.nil m := m | _ _ (perm.skip h) m := λ x, xchg' h (m x) | _ _ perm.swap m := λ x₁ x₂, m x₂ x₁ | _ _ (perm.trans h₁ h₂) m := xchg' h₂ (xchg' h₁ m) def xchg : (Γ₁ ~ Γ₂) → Judgment₂ Γ₁ t → Judgment₂ Γ₂ t := λ h m ν, xchg' ν h (m ν) def subst'' : Π {Γ}, judgment₂ (term ν) (t₁ :: Γ) t₂ → judgment₂ ν Γ t₁ → judgment₂ ν Γ t₂ | [] m₁ m₂ := subst' ν (m₁ m₂) | (t :: Γ) f m := λ x, subst'' (λ x', f x' (var x)) (m x) def subst : Judgment₂ (t₁ :: Γ) t₂ → Judgment₂ Γ t₁ → Judgment₂ Γ t₂ := λ m₁ m₂ ν, subst'' ν (m₁ _) (m₂ ν) def lam' : Π {Γ}, judgment₂ ν (t₁ :: Γ) t₂ → judgment₂ ν Γ (arrow t₁ t₂) | [] m := lam (λ x, m x) | (t :: Γ) f := λ x, lam' (λ y, f y x) def lam : Judgment₂ (t₁ :: Γ) t₂ → Judgment₂ Γ (arrow t₁ t₂) := λ m ν, lam' ν (m ν) def app' : Π {Γ}, judgment₂ ν Γ (arrow t₁ t₂) → judgment₂ ν Γ t₁ → judgment₂ ν Γ t₂ | [] m₁ m₂ := app m₁ m₂ | (t :: Γ) f m := λ x, app' (f x) (m x) def app : Judgment₂ Γ (arrow t₁ t₂) → Judgment₂ Γ t₁ → Judgment₂ Γ t₂ := λ m₁ m₂ ν, app' ν (m₁ ν) (m₂ ν) def var' : Π {Γ}, judgment₂ ν (t :: Γ) t | [] := λ x, var x | (t :: Γ) := λ x y, var' x def var : Π {Γ}, t ∈' Γ → Judgment₂ Γ t | _ here := λ ν, var' ν | _ (there h) := weak (var h) def contr : Judgment₂ (t₁ :: t₁ :: Γ) t₂ → Judgment₂ (t₁ :: Γ) t₂ := -- same as judgment₁.contr λ m, subst m (var here) def nonfree (m : Judgment₂ (t₁ :: Γ) t₂) : Prop := ∃ m', m = weak m' -- ∃ m', ∀ ν, (λ x, (m ν) x) = (λ x, (m' ν)) -- lemma nonfree_var_lem (m : Judgment₂ (t₁ :: Γ) t₂) -- : nonfree m ↔ ∃ (m' : Judgment₂ Γ t₂), ∀ ν, (λ x, (m ν) x) = (λ x, (m' ν)) := -- begin -- unfold nonfree, -- split, -- { intro h, -- induction h, -- existsi h_w, -- intro ν, -- rw h_h, -- refl }, -- { intro h, -- induction h, -- existsi h_w, -- apply funext h_h } -- end end judgment₂ ---- def to_term : Judgment₂ [] t → Term t := id def to_judgment₂ : Term t → Judgment₂ [] t := id def type.foldr : list type → type → type := λ Γ t, list.foldr arrow t Γ namespace judgment₂ def abs' : Π {Γ}, judgment₂ ν Γ t → judgment₂ ν [] (type.foldr Γ t) | [] m := m | (t :: Γ) f := term.lam (λ x, abs' (f x)) def abs : Judgment₂ Γ t → Term (type.foldr Γ t) := λ m ν, abs' ν (m ν) def antiabs' : Π {Γ}, judgment₂ (term ν) [] (type.foldr Γ t) → judgment₂ ν Γ t | [] m := subst' ν m | (t :: Γ) m := match m with | (term.var x) := λ x, antiabs' (term.app m (term.var (term.var x))) | (term.lam f) := λ x, antiabs' (f (term.var x)) | (term.app m₁ m₂) := λ x, antiabs' (term.app m (term.var (term.var x))) end def antiabs : Judgment₂ [] (type.foldr Γ t) → Judgment₂ Γ t := λ m ν, antiabs' ν (m _) end judgment₂ instance Judgment₂.setoid : setoid (Judgment₂ Γ t) := ⟨inv_image eq (normalize ∘ to_term ∘ judgment₂.abs), inv_image.equivalence eq (normalize ∘ to_term ∘ judgment₂.abs) eq_equivalence⟩ def zero' : Judgment₂ [] (arrow (arrow base base) (arrow base base)) := (judgment₂.antiabs ∘ to_judgment₂) zero def one' : Judgment₂ [] (arrow (arrow base base) (arrow base base)) := (judgment₂.antiabs ∘ to_judgment₂) one def succ' : Judgment₂ [] (arrow (arrow (arrow base base) (arrow base base)) (arrow (arrow base base) (arrow base base))) := (judgment₂.antiabs ∘ to_judgment₂) succ lemma zero_approx_zero : zero' ≈ zero' := by canonicity lemma succ_zero_approx_one : judgment₂.app succ' zero' ≈ one' := by canonicity end stlc
20d77360cd3e14e4e0816e0df35a649aff75da0a
0005a183d2afe3c7d097776749c13513cae91b66
/src/pending_lemmas.lean
aac7299c2eb54201a427147a70ef94f419ca1b8e
[]
no_license
PatrickMassot/bigop
9f85014752aa632c270bafbd96400512839220eb
af53ad615b619e3c05fe119f98f939ff010f7e6d
refs/heads/master
1,584,009,287,023
1,562,778,117,000
1,562,778,117,000
130,576,309
1
1
null
null
null
null
UTF-8
Lean
false
false
5,604
lean
/- The lemmas in this file may be soon be in mathlib, if not already -/ import data.list.basic import data.int.basic import tactic.ring import tactic.linarith open list nat int variables {α : Type*} {β : Type*} lemma reverse_range'_map_range' (a b : ℕ) : reverse (range' a (b+1-a)) = map (λ i, a+b-i) (range' a (b+1-a)) := begin rw [reverse_range', range'_eq_map_range, list.map_map], apply map_congr, intros i H, simp at *, rw [nat.add_sub_add_left, nat.add_sub_cancel'], {refl}, apply le_of_not_le (λ h, _), rw sub_eq_zero_of_le h at H, exact not_lt_zero _ H end lemma filter_ext {α : Type*} {r: list α} (P P') [decidable_pred P] [decidable_pred P'] (HP : ∀ i ∈ r, P i = P' i) : filter P r = filter P' r := begin induction r with h t IH, { simp }, { have HPh : P h = P' h := HP h (by simp), have : ∀ (i : α), i ∈ t → P i = P' i, { intros i i_t, exact (HP i $ by simp [i_t]) }, by_cases H : P h, { have H' : P' h := HPh ▸ H, simp [H, H', IH this] }, { have H' : ¬ P' h := HPh ▸ H, simp [H, H', IH this] } } end lemma foldr_congr' {α : Type*} {β : Type*} {l : list α} (f f' : α → β → β) (s : β) (H : ∀ a ∈ l, ∀ b : β, f a b = f' a b) : foldr f s l = foldr f' s l := by induction l; simp * {contextual := tt} lemma range'_add_map (a b k : ℕ) : range' (a+k) b = map (λ x, x + k) (range' a b) := begin revert a, induction b with b IH; intro a, { refl }, { simpa using (IH $ a + 1) } end lemma range'_sub_map (a b k : ℕ) : range' a b = map (λ x, x - k) (range' (a+k) b) := begin suffices : (λ (x : ℕ), x - k) ∘ (λ (x : ℕ), x + k) = id, { rw [range'_add_map, list.map_map, this, map_id] }, { funext, simp [nat.add_sub_cancel_left] } end lemma filter_map_comm {I : Type*} {J : Type*} (f : I → J) (P : J → Prop) (r: list I) [decidable_pred P] : filter P (map f r) = map f (filter (P ∘ f) r) := begin induction r with h _ IH, { simp }, { by_cases H : P (f h) ; simp [filter_cons_of_pos, filter_cons_of_neg, H, IH] } end lemma list.eq_nil_iff_not_mem {α : Type*} (l : list α) : l = [] ↔ ∀ x, x ∉ l := ⟨λ h, by simp[h], begin intro H, cases l with h t, refl, exfalso, specialize H h, have : h ∈ list.cons h t, by simp, exact H this end⟩ lemma list.range_eq_nil (n : ℕ) : list.range n = [] ↔ n = 0 := begin rw list.eq_nil_iff_not_mem, simp [mem_range], split ; intro h, { exact eq_zero_of_le_zero (h 0) }, { rw h, exact nat.zero_le } end @[simp] lemma to_nat_zero : to_nat 0 = 0 := rfl lemma to_nat_eq_zero (a) : to_nat a = 0 ↔ a ≤ 0 := begin induction a with n, { change n = 0 ↔ of_nat n ≤ 0, split ; intro h, { rw h, refl }, { apply eq_zero_of_le_zero, rwa ←coe_nat_le_coe_nat_iff n 0 } }, { simp[to_nat] }, end lemma to_nat_sub_eq_zero (a b : ℤ) : to_nat (b - a) = 0 ↔ b ≤ a := by rw [←sub_nonpos, to_nat_eq_zero] lemma int.range_eq_nil (a b) : int.range a b = [] ↔ b ≤ a := by unfold int.range ; rw [list.map_eq_nil, list.range_eq_nil, to_nat_sub_eq_zero] lemma int.range_shift (a b k) : int.range (a+k) (b+k) = map (λ x, x+k) (int.range a b) := begin unfold int.range, rw [list.map_map, show b + k - (a + k) = b - a , by ring], congr, ext n, simp end lemma reverse_int_range_map_int_range (a b) : reverse (int.range a b) = map (λ i, a+b-i-(1 : ℤ)) (int.range a b) := begin by_cases h : a ≤ b, { unfold int.range, rw [←list.map_reverse, range_eq_range', reverse_range'], repeat { rw list.map_map }, change map (λ (x : ℕ), a + ↑(0 + to_nat (b - a) - 1 - x)) (range (to_nat (b - a))) = map (λ (x : ℕ), a + b - (a + x) - 1) (range' 0 (to_nat (b - a))), rw [zero_add, range_eq_range'], apply map_congr, intros n n_in, have n_lt := (list.mem_range'.1 n_in).right, rw zero_add at n_lt, have key : ↑(to_nat (b - a) - 1 - n) = b - a - 1 - n, { rw [nat.sub_sub, int.coe_nat_sub, to_nat_of_nonneg (sub_nonneg_of_le h), int.coe_nat_add], simp, linarith }, rw key, ring }, { rw (int.range_eq_nil a b).2 (le_of_not_le h), simp } end lemma to_nat_succ {a : ℤ} (h : 0 ≤ a) : to_nat a + 1 = to_nat (a+1) := begin cases a, { refl }, { exfalso, exact h } end lemma int_range_eq_concat {a b} (h : a < b) : int.range a b = concat (int.range a (b-1)) (b-1) := begin unfold int.range, have h' : 0 ≤ b - a - 1, by have := add_one_le_of_lt h ; linarith, have : b - 1 = (λ (r : ℕ), a + ↑r) (to_nat (b - a-1)), { change b - 1 = a + ↑(to_nat (b - a - 1)), rw to_nat_of_nonneg h', ring }, rw [this, ←map_concat], congr, simp only [function.comp_app], rw [to_nat_of_nonneg h', concat_eq_append, show a + (b - a - 1) - a = b - a - 1, by simp], convert list.range_concat _, rw to_nat_succ h', congr, ring end @[simp] protected lemma int.length_range (a b) : length (int.range a b) = to_nat (b-a) := by unfold int.range ; rw [length_map, length_range] @[simp] lemma nth_le_int_range (a b n h) : nth_le (int.range a b) n h = a + n := begin unfold int.range, rw nth_le_map, { simp }, { simpa using h } end @[simp] lemma filter_mem {α : Type*} (l : list α) [decidable_pred (λ i, i ∈ l)] : filter (λ i, i ∈ l) l = l := by simp [filter_eq_self.2] @[simp] lemma filter_true {α : Type*} (l : list α) : filter (λ i, true) l = l := by simp [filter_eq_self.2] lemma nth_le_cons {α : Type*} (a : α) (t n h) : nth_le (a :: t) (n+1) h = nth_le t n (lt_of_succ_lt_succ h) := rfl
eb4d4d6073d924752362f99bfdc34de4e76d2651
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/library/tools/super/subsumption.lean
25e3ae3f6a102442abff95278b586c42f084abbd
[ "Apache-2.0" ]
permissive
pacchiano/lean
9324b33f3ac3b5c5647285160f9f6ea8d0d767dc
fdadada3a970377a6df8afcd629a6f2eab6e84e8
refs/heads/master
1,611,357,380,399
1,489,870,101,000
1,489,870,101,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,456
lean
/- Copyright (c) 2016 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import .clause .prover_state open tactic monad namespace super private meta def try_subsume_core : list clause.literal → list clause.literal → tactic unit | [] _ := skip | small large := first $ do i ← small^.zip_with_index, j ← large^.zip_with_index, return $ do unify_lit i.1 j.1, try_subsume_core (small^.remove_nth i.2) (large^.remove_nth j.2) -- FIXME: this is incorrect if a quantifier is unused meta def try_subsume (small large : clause) : tactic unit := do small_open ← clause.open_metan small (clause.num_quants small), large_open ← clause.open_constn large (clause.num_quants large), guard $ small^.num_lits ≤ large^.num_lits, try_subsume_core small_open.1^.get_lits large_open.1^.get_lits meta def does_subsume (small large : clause) : tactic bool := (try_subsume small large >> return tt) <|> return ff meta def does_subsume_with_assertions (small large : derived_clause) : prover bool := do if small^.assertions^.subset_of large^.assertions then do does_subsume small^.c large^.c else return ff meta def any_tt {m : Type → Type} [monad m] (active : rb_map clause_id derived_clause) (pred : derived_clause → m bool) : m bool := active^.fold (return ff) $ λk a cont, do v ← pred a, if v then return tt else cont meta def any_tt_list {m : Type → Type} [monad m] {A} (pred : A → m bool) : list A → m bool | [] := return ff | (x::xs) := do v ← pred x, if v then return tt else any_tt_list xs @[super.inf] meta def forward_subsumption : inf_decl := inf_decl.mk 20 $ take given, do active ← get_active, sequence' $ do a ← active^.values, guard $ a^.id ≠ given^.id, return $ do ss ← does_subsume a^.c given^.c, if ss then remove_redundant given^.id [a] else return () meta def forward_subsumption_pre : prover unit := preprocessing_rule $ λnew, do active ← get_active, filter (λn, do do ss ← any_tt active (λa, if a^.assertions^.subset_of n^.assertions then do does_subsume a^.c n^.c else -- TODO: move to locked return ff), return (bnot ss)) new meta def subsumption_interreduction : list derived_clause → prover (list derived_clause) | (c::cs) := do -- TODO: move to locked cs_that_subsume_c ← filter (λd, does_subsume_with_assertions d c) cs, if ¬cs_that_subsume_c^.empty then -- TODO: update score subsumption_interreduction cs else do cs_not_subsumed_by_c ← filter (λd, lift bnot (does_subsume_with_assertions c d)) cs, cs' ← subsumption_interreduction cs_not_subsumed_by_c, return (c::cs') | [] := return [] meta def subsumption_interreduction_pre : prover unit := preprocessing_rule $ λnew, let new' := list.sort_on (λc : derived_clause, c^.c^.num_lits) new in subsumption_interreduction new' meta def keys_where_tt {m} {K V : Type} [monad m] (active : rb_map K V) (pred : V → m bool) : m (list K) := @rb_map.fold _ _ (m (list K)) active (return []) $ λk a cont, do v ← pred a, rest ← cont, return $ if v then k::rest else rest @[super.inf] meta def backward_subsumption : inf_decl := inf_decl.mk 20 $ λgiven, do active ← get_active, ss ← keys_where_tt active (λa, does_subsume given^.c a^.c), sequence' $ do id ← ss, guard (id ≠ given^.id), [remove_redundant id [given]] end super
3bc8470c993e0c5980b92f9359b41c9304bef0a6
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/data/real/pi.lean
6d2524c027cca01bdd52505ae8b7638cd7a67388
[ "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
10,601
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import analysis.complex.exponential namespace real variable (x : ℝ) /-- the series `sqrt_two_add_series x n` is `sqrt(2 + sqrt(2 + ... ))` with `n` square roots, starting with `x`. We define it here because `cos (pi / 2 ^ (n+1)) = sqrt_two_add_series 0 n / 2` -/ @[simp] noncomputable def sqrt_two_add_series (x : ℝ) : ℕ → ℝ | 0 := x | (n+1) := sqrt (2 + sqrt_two_add_series n) lemma sqrt_two_add_series_zero : sqrt_two_add_series x 0 = x := by simp lemma sqrt_two_add_series_one : sqrt_two_add_series 0 1 = sqrt 2 := by simp lemma sqrt_two_add_series_two : sqrt_two_add_series 0 2 = sqrt (2 + sqrt 2) := by simp lemma sqrt_two_add_series_zero_nonneg : ∀(n : ℕ), sqrt_two_add_series 0 n ≥ 0 | 0 := le_refl 0 | (n+1) := sqrt_nonneg _ lemma sqrt_two_add_series_nonneg {x : ℝ} (h : 0 ≤ x) : ∀(n : ℕ), sqrt_two_add_series x n ≥ 0 | 0 := h | (n+1) := sqrt_nonneg _ lemma sqrt_two_add_series_lt_two : ∀(n : ℕ), sqrt_two_add_series 0 n < 2 | 0 := by norm_num | (n+1) := begin refine lt_of_lt_of_le _ (le_of_eq $ sqrt_sqr $ le_of_lt two_pos), rw [sqrt_two_add_series, sqrt_lt], apply add_lt_of_lt_sub_left, apply lt_of_lt_of_le (sqrt_two_add_series_lt_two n), norm_num, apply add_nonneg, norm_num, apply sqrt_two_add_series_zero_nonneg, norm_num end lemma sqrt_two_add_series_succ (x : ℝ) : ∀(n : ℕ), sqrt_two_add_series x (n+1) = sqrt_two_add_series (sqrt (2 + x)) n | 0 := rfl | (n+1) := by rw [sqrt_two_add_series, sqrt_two_add_series_succ, sqrt_two_add_series] lemma sqrt_two_add_series_monotone_left {x y : ℝ} (h : x ≤ y) : ∀(n : ℕ), sqrt_two_add_series x n ≤ sqrt_two_add_series y n | 0 := h | (n+1) := begin rw [sqrt_two_add_series, sqrt_two_add_series], apply sqrt_le_sqrt, apply add_le_add_left, apply sqrt_two_add_series_monotone_left end lemma sqrt_two_add_series_step_up {a b n : ℕ} {z : ℝ} (c d : ℕ) (hz : sqrt_two_add_series (c/d) n ≤ z) (hb : b ≠ 0) (hd : d ≠ 0) (h : (2 * b + a) * d ^ 2 ≤ c ^ 2 * b) : sqrt_two_add_series (a/b) (n+1) ≤ z := begin refine le_trans _ hz, rw [sqrt_two_add_series_succ], apply sqrt_two_add_series_monotone_left, rwa [sqrt_le_left, div_pow, add_div_eq_mul_add_div, div_le_iff, mul_comm (_/_), ←mul_div_assoc, le_div_iff, ←nat.cast_pow, ←nat.cast_pow, ←@nat.cast_one ℝ, ←nat.cast_bit0, ←nat.cast_mul, ←nat.cast_mul, ←nat.cast_add, ←nat.cast_mul, nat.cast_le, mul_comm b], apply pow_pos, iterate 2 {apply nat.cast_pos.2, apply nat.pos_of_ne_zero, assumption}, exact nat.cast_ne_zero.2 hb, exact div_nonneg (nat.cast_nonneg _) (nat.cast_pos.2 $ nat.pos_of_ne_zero hd) end lemma sqrt_two_add_series_step_down {c d n : ℕ} {z : ℝ} (a b : ℕ) (hz : z ≤ sqrt_two_add_series (a/b) n) (hb : b ≠ 0) (hd : d ≠ 0) (h : a ^ 2 * d ≤ (2 * d + c) * b ^ 2) : z ≤ sqrt_two_add_series (c/d) (n+1) := begin apply le_trans hz, rw [sqrt_two_add_series_succ], apply sqrt_two_add_series_monotone_left, apply le_sqrt_of_sqr_le, rwa [div_pow, add_div_eq_mul_add_div, div_le_iff, mul_comm (_/_), ←mul_div_assoc, le_div_iff, ←nat.cast_pow, ←nat.cast_pow, ←@nat.cast_one ℝ, ←nat.cast_bit0, ←nat.cast_mul, ←nat.cast_mul, ←nat.cast_add, ←nat.cast_mul, nat.cast_le, mul_comm (b ^ 2)], swap, apply pow_pos, iterate 2 {apply nat.cast_pos.2, apply nat.pos_of_ne_zero, assumption}, exact nat.cast_ne_zero.2 hd, end @[simp] lemma cos_pi_over_two_pow : ∀(n : ℕ), cos (pi / 2 ^ (n+1)) = sqrt_two_add_series 0 n / 2 | 0 := by simp | (n+1) := begin symmetry, rw [div_eq_iff_mul_eq], symmetry, rw [sqrt_two_add_series, sqrt_eq_iff_sqr_eq, mul_pow, cos_square, ←mul_div_assoc, nat.add_succ, pow_succ, mul_div_mul_left, cos_pi_over_two_pow, add_mul], congr, norm_num, rw [mul_comm, pow_two, mul_assoc, ←mul_div_assoc, mul_div_cancel_left, ←mul_div_assoc, mul_div_cancel_left], norm_num, norm_num, norm_num, apply add_nonneg, norm_num, apply sqrt_two_add_series_zero_nonneg, norm_num, apply le_of_lt, apply mul_pos, apply cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two, { transitivity (0 : ℝ), rw neg_lt_zero, apply pi_div_two_pos, apply div_pos pi_pos, apply pow_pos, norm_num }, apply div_lt_div' (le_refl pi) _ pi_pos _, refine lt_of_le_of_lt (le_of_eq (pow_one _).symm) _, apply pow_lt_pow, norm_num, apply nat.succ_lt_succ, apply nat.succ_pos, all_goals {norm_num} end lemma sin_square_pi_over_two_pow (n : ℕ) : sin (pi / 2 ^ (n+1)) ^ 2 = 1 - (sqrt_two_add_series 0 n / 2) ^ 2 := by rw [sin_square, cos_pi_over_two_pow] lemma sin_square_pi_over_two_pow_succ (n : ℕ) : sin (pi / 2 ^ (n+2)) ^ 2 = 1 / 2 - sqrt_two_add_series 0 n / 4 := begin rw [sin_square_pi_over_two_pow, sqrt_two_add_series, div_pow, sqr_sqrt, add_div, ←sub_sub], congr, norm_num, norm_num, apply add_nonneg, norm_num, apply sqrt_two_add_series_zero_nonneg, end @[simp] lemma sin_pi_over_two_pow_succ (n : ℕ) : sin (pi / 2 ^ (n+2)) = sqrt (2 - sqrt_two_add_series 0 n) / 2 := begin symmetry, rw [div_eq_iff_mul_eq], symmetry, rw [sqrt_eq_iff_sqr_eq, mul_pow, sin_square_pi_over_two_pow_succ, sub_mul], { congr, norm_num, rw [mul_comm], convert mul_div_cancel' _ _, norm_num, norm_num }, { rw [sub_nonneg], apply le_of_lt, apply sqrt_two_add_series_lt_two }, apply le_of_lt, apply mul_pos, apply sin_pos_of_pos_of_lt_pi, { apply div_pos pi_pos, apply pow_pos, norm_num }, refine lt_of_lt_of_le _ (le_of_eq (div_one _)), rw [div_lt_div_left], refine lt_of_le_of_lt (le_of_eq (pow_zero 2).symm) _, apply pow_lt_pow, norm_num, apply nat.succ_pos, apply pi_pos, apply pow_pos, all_goals {norm_num} end lemma cos_pi_div_four : cos (pi / 4) = sqrt 2 / 2 := by { transitivity cos (pi / 2 ^ 2), congr, norm_num, simp } lemma sin_pi_div_four : sin (pi / 4) = sqrt 2 / 2 := by { transitivity sin (pi / 2 ^ 2), congr, norm_num, simp } lemma cos_pi_div_eight : cos (pi / 8) = sqrt (2 + sqrt 2) / 2 := by { transitivity cos (pi / 2 ^ 3), congr, norm_num, simp } lemma sin_pi_div_eight : sin (pi / 8) = sqrt (2 - sqrt 2) / 2 := by { transitivity sin (pi / 2 ^ 3), congr, norm_num, simp } lemma cos_pi_div_sixteen : cos (pi / 16) = sqrt (2 + sqrt (2 + sqrt 2)) / 2 := by { transitivity cos (pi / 2 ^ 4), congr, norm_num, simp } lemma sin_pi_div_sixteen : sin (pi / 16) = sqrt (2 - sqrt (2 + sqrt 2)) / 2 := by { transitivity sin (pi / 2 ^ 4), congr, norm_num, simp } lemma cos_pi_div_thirty_two : cos (pi / 32) = sqrt (2 + sqrt (2 + sqrt (2 + sqrt 2))) / 2 := by { transitivity cos (pi / 2 ^ 5), congr, norm_num, simp } lemma sin_pi_div_thirty_two : sin (pi / 32) = sqrt (2 - sqrt (2 + sqrt (2 + sqrt 2))) / 2 := by { transitivity sin (pi / 2 ^ 5), congr, norm_num, simp } lemma pi_gt_sqrt_two_add_series (n : ℕ) : pi > 2 ^ (n+1) * sqrt (2 - sqrt_two_add_series 0 n) := begin have : pi > sqrt (2 - sqrt_two_add_series 0 n) / 2 * 2 ^ (n+2), { apply mul_lt_of_lt_div, apply pow_pos, norm_num, rw [←sin_pi_over_two_pow_succ], apply sin_lt, apply div_pos pi_pos, apply pow_pos, norm_num }, apply lt_of_le_of_lt (le_of_eq _) this, rw [pow_succ _ (n+1), ←mul_assoc, div_mul_cancel, mul_comm], norm_num end lemma pi_lt_sqrt_two_add_series (n : ℕ) : pi < 2 ^ (n+1) * sqrt (2 - sqrt_two_add_series 0 n) + 1 / 4 ^ n := begin have : pi < (sqrt (2 - sqrt_two_add_series 0 n) / 2 + 1 / (2 ^ n) ^ 3 / 4) * 2 ^ (n+2), { rw [←div_lt_iff, ←sin_pi_over_two_pow_succ], refine lt_of_lt_of_le (lt_add_of_sub_right_lt (sin_gt_sub_cube _ _)) _, { apply div_pos pi_pos, apply pow_pos, norm_num }, { apply div_le_of_le_mul, apply pow_pos, norm_num, refine le_trans pi_le_four _, simp only [show ((4 : ℝ) = 2 ^ 2), by norm_num, mul_one], apply pow_le_pow, norm_num, apply le_add_of_nonneg_left, apply nat.zero_le }, apply add_le_add_left, rw div_le_div_right, apply le_div_of_mul_le, apply pow_pos, apply pow_pos, norm_num, rw [←mul_pow], refine le_trans _ (le_of_eq (one_pow 3)), apply pow_le_pow_of_le_left, { apply le_of_lt, apply mul_pos, apply div_pos pi_pos, apply pow_pos, norm_num, apply pow_pos, norm_num }, apply mul_le_of_le_div, apply pow_pos, norm_num, refine le_trans ((div_le_div_right _).mpr pi_le_four) _, apply pow_pos, norm_num, rw [pow_succ, pow_succ, ←mul_assoc, ←div_div_eq_div_mul], convert le_refl _, norm_num, norm_num, apply pow_pos, norm_num }, apply lt_of_lt_of_le this (le_of_eq _), rw [add_mul], congr' 1, { rw [pow_succ _ (n+1), ←mul_assoc, div_mul_cancel, mul_comm], norm_num }, rw [pow_succ, ←pow_mul, mul_comm n 2, pow_mul, show (2 : ℝ) ^ 2 = 4, by norm_num, pow_succ, pow_succ, ←mul_assoc (2 : ℝ), show (2 : ℝ) * 2 = 4, by norm_num, ←mul_assoc, div_mul_cancel, mul_comm ((2 : ℝ) ^ n), ←div_div_eq_div_mul, div_mul_cancel], apply pow_ne_zero, norm_num, norm_num end lemma pi_gt_three : pi > 3 := begin refine lt_of_le_of_lt _ (pi_gt_sqrt_two_add_series 1), rw [mul_comm], apply le_mul_of_div_le, norm_num, apply le_sqrt_of_sqr_le, rw [le_sub], rw show (0:ℝ) = (0:ℕ)/(1:ℕ), by rw [nat.cast_zero, zero_div], apply sqrt_two_add_series_step_up 23 16, all_goals {norm_num} end lemma pi_gt_314 : pi > 3.14 := begin refine lt_of_le_of_lt _ (pi_gt_sqrt_two_add_series 4), rw [mul_comm], apply le_mul_of_div_le, norm_num, apply le_sqrt_of_sqr_le, rw [le_sub, show (0:ℝ) = (0:ℕ)/(1:ℕ), by rw [nat.cast_zero, zero_div]], apply sqrt_two_add_series_step_up 99 70, apply sqrt_two_add_series_step_up 874 473, apply sqrt_two_add_series_step_up 1940 989, apply sqrt_two_add_series_step_up 1447 727, all_goals {norm_num} end lemma pi_lt_315 : pi < 3.15 := begin refine lt_of_lt_of_le (pi_lt_sqrt_two_add_series 4) _, apply add_le_of_le_sub_right, rw [mul_comm], apply mul_le_of_le_div, apply pow_pos, norm_num, rw [sqrt_le_left, sub_le, show (0:ℝ) = (0:ℕ)/(1:ℕ), by rw [nat.cast_zero, zero_div]], apply sqrt_two_add_series_step_down 140 99, apply sqrt_two_add_series_step_down 279 151, apply sqrt_two_add_series_step_down 51 26, apply sqrt_two_add_series_step_down 412 207, all_goals {norm_num} end /- A computation of the first 7 digits of pi is given here: <https://gist.github.com/fpvandoorn/5b405988bc2e61953d56e3597db16ecf> This is not included in mathlib, because of slow compilation time. -/ end real
f2932d482fb3ad95003b409989220a92fc358cfc
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/compiler/phashmap3.lean
8f54db813ad35753f9f2b72ffae775fa4284b1a4
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,832
lean
import Lean.Data.PersistentHashMap import Lean.Data.Format open Lean Std Lean.PersistentHashMap abbrev Map := PersistentHashMap Nat Nat partial def formatMap : Node Nat Nat → Format | Node.collision keys vals _ => Format.sbracket $ keys.size.fold (fun i fmt => let k := keys.get! i; let v := vals.get! i; let p := if i > 0 then fmt ++ format "," ++ Format.line else fmt; p ++ "c@" ++ Format.paren (format k ++ " => " ++ format v)) Format.nil | Node.entries entries => Format.sbracket $ entries.size.fold (fun i fmt => let entry := entries.get! i; let p := if i > 0 then fmt ++ format "," ++ Format.line else fmt; p ++ match entry with | Entry.null => "<null>" | Entry.ref node => formatMap node | Entry.entry k v => Format.paren (format k ++ " => " ++ format v)) Format.nil def checkState (m : Map) : IO Unit := do unless (m.stats.maxDepth == 1) do (IO.println "unexpected max depth"); unless (m.stats.numCollisions == 0) do (IO.println "unexpected number of collisions") def main : IO Unit := do let m : Map := PersistentHashMap.empty; let m := m.insert 1 1; let m := m.insert (32^5 + 1) 2; let max := PersistentHashMap.maxDepth.toNat; let m := m.insert (32^max + 1) 3; let m := m.insert (32^(max+1) + 1) 4; let m := m.insert (32^(max+2) + 1) 5; unless (m.stats.maxDepth == PersistentHashMap.maxDepth.toNat) do (IO.println "unexpected max depth"); unless (m.stats.numCollisions == 3) do (IO.println "unexpected number of collisions"); IO.println m.stats; let m := m.erase (32^(max+1) + 1); let m := m.erase (32^(max+2) + 1); let m := m.erase (32^max + 1); unless (m.stats.maxDepth == PersistentHashMap.maxDepth.toNat - 1) do (IO.println "unexpected max depth"); let m := m.erase (32^5 + 1); checkState m; IO.println m.stats
c4399f2e71ea0b0f7ab9b5ec694018d44d8618e6
7cef822f3b952965621309e88eadf618da0c8ae9
/src/data/nat/pairing.lean
55a8dbc81fad5c7fdac99189d55ee21791888068
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
3,836
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro Elegant pairing function. -/ import data.nat.sqrt open prod decidable namespace nat /-- Pairing function for the natural numbers. -/ def mkpair (a b : ℕ) : ℕ := if a < b then b*b + a else a*a + a + b /-- Unpairing function for the natural numbers. -/ def unpair (n : ℕ) : ℕ × ℕ := let s := sqrt n in if n - s*s < s then (n - s*s, s) else (s, n - s*s - s) @[simp] theorem mkpair_unpair (n : ℕ) : mkpair (unpair n).1 (unpair n).2 = n := let s := sqrt n in begin dsimp [unpair], change sqrt n with s, have sm : s * s + (n - s * s) = n := nat.add_sub_cancel' (sqrt_le _), by_cases h : n - s * s < s; simp [h, mkpair], { exact sm }, { have hl : n - s*s - s ≤ s := nat.sub_le_left_of_le_add (nat.sub_le_left_of_le_add $ by rw ← add_assoc; apply sqrt_le_add), suffices : s * s + (s + (n - s * s - s)) = n, {simpa [not_lt_of_ge hl]}, rwa [nat.add_sub_cancel' (le_of_not_gt h)] } end theorem mkpair_unpair' {n a b} (H : unpair n = (a, b)) : mkpair a b = n := by simpa [H] using mkpair_unpair n @[simp] theorem unpair_mkpair (a b : ℕ) : unpair (mkpair a b) = (a, b) := begin by_cases a < b; simp [h, mkpair], { show unpair (a + b * b) = (a, b), have be : sqrt (a + b * b) = b, { rw [add_comm, sqrt_add_eq], exact le_trans (le_of_lt h) (le_add_left _ _) }, simp [unpair, be, nat.add_sub_cancel, h] }, { show unpair (a + (b + a * a)) = (a, b), have ae : sqrt (a + (b + a * a)) = a, { rw [← add_assoc, add_comm, sqrt_add_eq], exact add_le_add_left (le_of_not_gt h) _ }, have : a ≤ a + (b + a * a) - a * a, { rw nat.add_sub_assoc (nat.le_add_left _ _), apply nat.le_add_right }, simp [unpair, ae, not_lt_of_ge this], show a + (b + a * a) - a * a - a = b, rw [nat.add_sub_assoc (nat.le_add_left _ _), nat.add_sub_cancel, nat.add_sub_cancel_left] } end theorem unpair_lt {n : ℕ} (n1 : 1 ≤ n) : (unpair n).1 < n := let s := sqrt n in begin simp [unpair], change sqrt n with s, by_cases h : n - s * s < s; simp [h], { exact lt_of_lt_of_le h (sqrt_le_self _) }, { simp at h, have s0 : 0 < s := sqrt_pos.2 n1, exact lt_of_le_of_lt h (nat.sub_lt_self n1 (mul_pos s0 s0)) } end theorem unpair_le_left : ∀ (n : ℕ), (unpair n).1 ≤ n | 0 := dec_trivial | (n+1) := le_of_lt (unpair_lt (nat.succ_pos _)) theorem le_mkpair_left (a b : ℕ) : a ≤ mkpair a b := by simpa using unpair_le_left (mkpair a b) theorem le_mkpair_right (a b : ℕ) : b ≤ mkpair a b := by by_cases h : a < b; simp [mkpair, h]; [exact le_trans (le_mul_self _) (le_add_left _ _), exact le_trans (le_add_right _ _) (le_add_left _ _)] theorem unpair_le_right (n : ℕ) : (unpair n).2 ≤ n := by simpa using le_mkpair_right n.unpair.1 n.unpair.2 theorem mkpair_lt_mkpair_left {a₁ a₂} (b) (h : a₁ < a₂) : mkpair a₁ b < mkpair a₂ b := begin by_cases h₁ : a₁ < b; simp [mkpair, h₁], { by_cases h₂ : a₂ < b; simp [mkpair, h₂, h], simp at h₂, exact add_lt_add_of_lt_of_le (lt_of_lt_of_le h₁ h₂) (le_trans (mul_self_le_mul_self h₂) (le_add_left _ _)) }, { simp at h₁, simp [not_lt_of_gt (lt_of_le_of_lt h₁ h)], exact add_lt_add h (add_lt_add_left (mul_self_lt_mul_self h) _) } end theorem mkpair_lt_mkpair_right (a) {b₁ b₂} (h : b₁ < b₂) : mkpair a b₁ < mkpair a b₂ := begin by_cases h₁ : a < b₁; simp [mkpair, h₁], { simp [mkpair, lt_trans h₁ h, h], exact mul_self_lt_mul_self h }, { by_cases h₂ : a < b₂; simp [mkpair, h₂, h], simp at h₁, rwa [add_comm, ← sqrt_lt, sqrt_add_eq], exact le_trans h₁ (le_add_left _ _) } end end nat
d1b7fee62dd17a01ce4e71be25f07d3215d1d71d
94637389e03c919023691dcd05bd4411b1034aa5
/src/assignments/assignment_3/assignment_3.lean
2f23986ba2f165b26852f0c78e608318bc26ec86
[]
no_license
kevinsullivan/complogic-s21
7c4eef2105abad899e46502270d9829d913e8afc
99039501b770248c8ceb39890be5dfe129dc1082
refs/heads/master
1,682,985,669,944
1,621,126,241,000
1,621,126,241,000
335,706,272
0
38
null
1,618,325,669,000
1,612,374,118,000
Lean
UTF-8
Lean
false
false
6,635
lean
/- HIGHER-ORDER FUNCTION WARMUP -/ /- 1. Write a function, double, that takes a natural number and returns its double. Write it using the following recursive definition: - double 0 = 0 - double (n' + 1) = double n' + 2 -/ -- ANSWER HERE /- 2. Write a function, map_list_nat, that takes as its arguments (1) a list, l, of natural numbers, and (2) a function, f, from nat to nat, and that returns a new list of natural numbers constructed by applying f to each element of l. Make f the first argument and l the second. The function will work by case analysis and recursion on l. -/ -- ANSWER HERE /- 3. Test your map_list_nat function by applying it to several lists, both empty and not, passing double as the function value. Include [], [2], and [1,2,3] in your set of test inputs and use comments to document the expected return values. -/ /- 4. In Lean, repr is an "overloaded" function. When applied to a value of a type for which it's defined (we'll see later how that happens) it returns a string representation of the value. It is defined for the nat type, and so when applied to a nat value it returns a corresponding string. It's "toString" for Lean. Here's an example. -/ #eval repr 5 /- Write a function map_list_nat_string that takes a list of nat values and returns a list of strings in which each nat in the given list has been converted to a string using repr. -/ -- ANSWER HERE /- 5. Write a function, filterZeros, that takes a list of natural numbers and returns the same list but with any and all zero values removed. Given [0], for example, it should return []; given [1,2,0,3,4,0, 0, 5] it should return [1,2,3,4,5]. -/ -- ANSWER HERE /- 6. Write a function, isEqN, that takes a natural number, n, and returns a function that takes a natural number, m, and returns true (tt) if m = n and that returns false (ff) otherwise. Be sure to test your function. -/ -- ANSWER HERE /- 7. Write a function filterNs that takes a function, pred, from nat to bool and a list, l, of natural numbers, and that returns a list like l but with all the numbers that satisfy the predicate function removed. Test your function using isEqN to produce a few predicate functions (functions that for a given argument return true or false). -/ -- ANSWER HERE /- 8. Write a function, iterate, that takes as its arguments (1) a function, f, of type nat → nat, and (2) a natural number, n, and that returns a function that takes an argument, (m : nat), and that returns the result of applying f to m n times. For example, if n = 3, it should return f (f (f m)). The result of applying f zero times is just m. Hint: use case analysis on n, and recursion. Test your function using nat.succ, your double function, and (nat.add 4) as function arguments. -/ -- ANSWER HERE /- 9. Write a function, list_add, that takes a list of natural numbers and returns the sum of all the numbers in the list. -/ -- ANSWER HERE /- 10. Write a function, list_mul, that takes a list of natural numbers and returns the product of all the numbers in the list. -/ -- ANSWER HERE /- 11. Write a function, list_has_zero, that takes a list of natural numbers and returns tt if the list contains any zero values and that returns false otherwise. Use isEqN in your solution. Test your solution on both empty and non-empty lists including lists that both have and don't have zero values. -/ -- ANSWER HERE /- 12. Write a function, compose_nat_nat, that takes two functions, f : ℕ → ℕ, and g : ℕ → ℕ, and that returns a function that takes a nat, n, and that returns g (f n). Test your function using at least nat.succ and double as argument values. -/ -- ANSWER HERE /- 13. Write a polymorphic map_box function of type Π (α β : Type u), (α → β) → box α → box β that takes a function, f, of type (α → β), and a box, b, containing a value of type α and that returns a box containing that value transformed by the application of f. -/ -- ANSWER HERE /- 14. Write a function, map_option, that takes a function, f, of type α → β and an option α and that transforms it into an option β, where none goes to none, and some (a : α) goes to some b, where b is a transformed by f. -/ -- ANSWER HERE /- 15. Write three functions, default_nat, default_bool, and default_list α, each taking no arguments (other than a type, argument, α, in the third case), and each returning a default value of the given type: a nat, a bool, and a list. Don't overthink this: Yes, a function that takes no arguments is basically a constant. You'll need to declare a universe variable for the list problem. -/ -- ANSWER HERE -- C style def comp (g f : nat → nat) : nat → nat := λ n, g (f n) -- lambda expressions def comp' : (nat → nat) → (nat → nat) → (nat → nat) := λ g f, λ n, g (f n) -- by cases def comp'' : (nat → nat) → (nat → nat) → (nat → nat) | g f := λ (n : ℕ), g (f n) def square (n : nat) := n * n def double (n : nat) := 2 * n def myFavFunc := comp' square double #check myFavFunc #eval myFavFunc 5 -- square (double 5) -- square 10 -- 100 def comp_nat_string : (nat → bool) → (string → nat) → (string → bool) := λ (nb : ℕ → bool), λ (sn : string → nat), λ (s : string), nb (sn s) def isStringEmpty := comp_nat_string (λ (n : nat), n=0) string.length #eval isStringEmpty "Hello" #eval isStringEmpty "" def yeah {α β γ : Type} (g : β → γ) (f : α → β) : (α → γ) := λ (a : α), g (f a) #reduce (yeah (λ (n : nat), (n=0 : bool)) string.length) "" #reduce (yeah square double) 5 #reduce (yeah (λ (n : nat), (n=0 : bool)) string.length) "" /- Write a function, iterate, that takes as its arguments (1) a function, f, of type nat → nat, and (2) a natural number, n, and that returns a function that takes an argument, (m : nat), and that returns the result of applying f to m n times. -/ def iterate : (nat → nat) → nat → (nat → nat) | f 0 := λ (m : nat), m | f (n' + 1) := λ m, _ #eval (iterate double 10) 1 /- Write a polymorphic map_box function of type Π (α β : Type u), (α → β) → box α → box β that takes a function, f, of type (α → β), and a box, b, containing a value of type α and that returns a box containing that value transformed by the application of f. -/ universe u structure box (α : Type u) : Type u := mk :: (val : α) def map_box : Π {α β : Type u}, (α → β) → (box α → box β) | _ _ f b := box.mk (f b.val) def b0 := box.mk 0 def f := nat.succ def q := map_box f #reduce q b0
73fa0bad34bb27786578a54a57de7763d0dd3d35
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/calculus/local_extr.lean
0b78a246c89595bd8bff5993fcaf94dc796ea137
[ "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
18,197
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.calculus.deriv import data.polynomial.field_division import topology.algebra.order.extend_from import topology.algebra.polynomial import topology.local_extr /-! # Local extrema of smooth functions ## Main definitions In a real normed space `E` we define `pos_tangent_cone_at (s : set E) (x : E)`. This would be the same as `tangent_cone_at ℝ≥0 s x` if we had a theory of normed semifields. This set is used in the proof of Fermat's Theorem (see below), and can be used to formalize [Lagrange multipliers](https://en.wikipedia.org/wiki/Lagrange_multiplier) and/or [Karush–Kuhn–Tucker conditions](https://en.wikipedia.org/wiki/Karush–Kuhn–Tucker_conditions). ## Main statements For each theorem name listed below, we also prove similar theorems for `min`, `extr` (if applicable)`, and `(f)deriv` instead of `has_fderiv`. * `is_local_max_on.has_fderiv_within_at_nonpos` : `f' y ≤ 0` whenever `a` is a local maximum of `f` on `s`, `f` has derivative `f'` at `a` within `s`, and `y` belongs to the positive tangent cone of `s` at `a`. * `is_local_max_on.has_fderiv_within_at_eq_zero` : In the settings of the previous theorem, if both `y` and `-y` belong to the positive tangent cone, then `f' y = 0`. * `is_local_max.has_fderiv_at_eq_zero` : [Fermat's Theorem](https://en.wikipedia.org/wiki/Fermat's_theorem_(stationary_points)), the derivative of a differentiable function at a local extremum point equals zero. * `exists_has_deriv_at_eq_zero` : [Rolle's Theorem](https://en.wikipedia.org/wiki/Rolle's_theorem): given a function `f` continuous on `[a, b]` and differentiable on `(a, b)`, there exists `c ∈ (a, b)` such that `f' c = 0`. ## Implementation notes For each mathematical fact we prove several versions of its formalization: * for maxima and minima; * using `has_fderiv*`/`has_deriv*` or `fderiv*`/`deriv*`. For the `fderiv*`/`deriv*` versions we omit the differentiability condition whenever it is possible due to the fact that `fderiv` and `deriv` are defined to be zero for non-differentiable functions. ## References * [Fermat's Theorem](https://en.wikipedia.org/wiki/Fermat's_theorem_(stationary_points)); * [Rolle's Theorem](https://en.wikipedia.org/wiki/Rolle's_theorem); * [Tangent cone](https://en.wikipedia.org/wiki/Tangent_cone); ## Tags local extremum, Fermat's Theorem, Rolle's Theorem -/ universes u v open filter set open_locale topological_space classical polynomial section module variables {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} {f' : E →L[ℝ] ℝ} /-- "Positive" tangent cone to `s` at `x`; the only difference from `tangent_cone_at` is that we require `c n → ∞` instead of `∥c n∥ → ∞`. One can think about `pos_tangent_cone_at` as `tangent_cone_at nnreal` but we have no theory of normed semifields yet. -/ def pos_tangent_cone_at (s : set E) (x : E) : set E := {y : E | ∃(c : ℕ → ℝ) (d : ℕ → E), (∀ᶠ n in at_top, x + d n ∈ s) ∧ (tendsto c at_top at_top) ∧ (tendsto (λn, c n • d n) at_top (𝓝 y))} lemma pos_tangent_cone_at_mono : monotone (λ s, pos_tangent_cone_at s a) := begin rintros s t hst y ⟨c, d, hd, hc, hcd⟩, exact ⟨c, d, mem_of_superset hd $ λ h hn, hst hn, hc, hcd⟩ end lemma mem_pos_tangent_cone_at_of_segment_subset {s : set E} {x y : E} (h : segment ℝ x y ⊆ s) : y - x ∈ pos_tangent_cone_at s x := begin let c := λn:ℕ, (2:ℝ)^n, let d := λn:ℕ, (c n)⁻¹ • (y-x), refine ⟨c, d, filter.univ_mem' (λn, h _), tendsto_pow_at_top_at_top_of_one_lt one_lt_two, _⟩, show x + d n ∈ segment ℝ x y, { rw segment_eq_image', refine ⟨(c n)⁻¹, ⟨_, _⟩, rfl⟩, exacts [inv_nonneg.2 (pow_nonneg zero_le_two _), inv_le_one (one_le_pow_of_one_le one_le_two _)] }, show tendsto (λ n, c n • d n) at_top (𝓝 (y - x)), { convert tendsto_const_nhds, ext n, simp only [d, smul_smul], rw [mul_inv_cancel, one_smul], exact pow_ne_zero _ two_ne_zero } end lemma mem_pos_tangent_cone_at_of_segment_subset' {s : set E} {x y : E} (h : segment ℝ x (x + y) ⊆ s) : y ∈ pos_tangent_cone_at s x := by simpa only [add_sub_cancel'] using mem_pos_tangent_cone_at_of_segment_subset h lemma pos_tangent_cone_at_univ : pos_tangent_cone_at univ a = univ := eq_univ_of_forall $ λ x, mem_pos_tangent_cone_at_of_segment_subset' (subset_univ _) /-- If `f` has a local max on `s` at `a`, `f'` is the derivative of `f` at `a` within `s`, and `y` belongs to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/ lemma is_local_max_on.has_fderiv_within_at_nonpos {s : set E} (h : is_local_max_on f s a) (hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a) : f' y ≤ 0 := begin rcases hy with ⟨c, d, hd, hc, hcd⟩, have hc' : tendsto (λ n, ∥c n∥) at_top at_top, from tendsto_at_top_mono (λ n, le_abs_self _) hc, refine le_of_tendsto (hf.lim at_top hd hc' hcd) _, replace hd : tendsto (λ n, a + d n) at_top (𝓝[s] (a + 0)), from tendsto_inf.2 ⟨tendsto_const_nhds.add (tangent_cone_at.lim_zero _ hc' hcd), by rwa tendsto_principal⟩, rw [add_zero] at hd, replace h : ∀ᶠ n in at_top, f (a + d n) ≤ f a, from mem_map.1 (hd h), replace hc : ∀ᶠ n in at_top, 0 ≤ c n, from mem_map.1 (hc (mem_at_top (0:ℝ))), filter_upwards [h, hc], simp only [smul_eq_mul, mem_preimage, subset_def], assume n hnf hn, exact mul_nonpos_of_nonneg_of_nonpos hn (sub_nonpos.2 hnf) end /-- If `f` has a local max on `s` at `a` and `y` belongs to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/ lemma is_local_max_on.fderiv_within_nonpos {s : set E} (h : is_local_max_on f s a) {y} (hy : y ∈ pos_tangent_cone_at s a) : (fderiv_within ℝ f s a : E → ℝ) y ≤ 0 := if hf : differentiable_within_at ℝ f s a then h.has_fderiv_within_at_nonpos hf.has_fderiv_within_at hy else by { rw fderiv_within_zero_of_not_differentiable_within_at hf, refl } /-- If `f` has a local max on `s` at `a`, `f'` is a derivative of `f` at `a` within `s`, and both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/ lemma is_local_max_on.has_fderiv_within_at_eq_zero {s : set E} (h : is_local_max_on f s a) (hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : f' y = 0 := le_antisymm (h.has_fderiv_within_at_nonpos hf hy) $ by simpa using h.has_fderiv_within_at_nonpos hf hy' /-- If `f` has a local max on `s` at `a` and both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y = 0`. -/ lemma is_local_max_on.fderiv_within_eq_zero {s : set E} (h : is_local_max_on f s a) {y} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : (fderiv_within ℝ f s a : E → ℝ) y = 0 := if hf : differentiable_within_at ℝ f s a then h.has_fderiv_within_at_eq_zero hf.has_fderiv_within_at hy hy' else by { rw fderiv_within_zero_of_not_differentiable_within_at hf, refl } /-- If `f` has a local min on `s` at `a`, `f'` is the derivative of `f` at `a` within `s`, and `y` belongs to the positive tangent cone of `s` at `a`, then `0 ≤ f' y`. -/ lemma is_local_min_on.has_fderiv_within_at_nonneg {s : set E} (h : is_local_min_on f s a) (hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a) : 0 ≤ f' y := by simpa using h.neg.has_fderiv_within_at_nonpos hf.neg hy /-- If `f` has a local min on `s` at `a` and `y` belongs to the positive tangent cone of `s` at `a`, then `0 ≤ f' y`. -/ lemma is_local_min_on.fderiv_within_nonneg {s : set E} (h : is_local_min_on f s a) {y} (hy : y ∈ pos_tangent_cone_at s a) : (0:ℝ) ≤ (fderiv_within ℝ f s a : E → ℝ) y := if hf : differentiable_within_at ℝ f s a then h.has_fderiv_within_at_nonneg hf.has_fderiv_within_at hy else by { rw [fderiv_within_zero_of_not_differentiable_within_at hf], refl } /-- If `f` has a local max on `s` at `a`, `f'` is a derivative of `f` at `a` within `s`, and both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/ lemma is_local_min_on.has_fderiv_within_at_eq_zero {s : set E} (h : is_local_min_on f s a) (hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : f' y = 0 := by simpa using h.neg.has_fderiv_within_at_eq_zero hf.neg hy hy' /-- If `f` has a local min on `s` at `a` and both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y = 0`. -/ lemma is_local_min_on.fderiv_within_eq_zero {s : set E} (h : is_local_min_on f s a) {y} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : (fderiv_within ℝ f s a : E → ℝ) y = 0 := if hf : differentiable_within_at ℝ f s a then h.has_fderiv_within_at_eq_zero hf.has_fderiv_within_at hy hy' else by { rw fderiv_within_zero_of_not_differentiable_within_at hf, refl } /-- **Fermat's Theorem**: the derivative of a function at a local minimum equals zero. -/ lemma is_local_min.has_fderiv_at_eq_zero (h : is_local_min f a) (hf : has_fderiv_at f f' a) : f' = 0 := begin ext y, apply (h.on univ).has_fderiv_within_at_eq_zero hf.has_fderiv_within_at; rw pos_tangent_cone_at_univ; apply mem_univ end /-- **Fermat's Theorem**: the derivative of a function at a local minimum equals zero. -/ lemma is_local_min.fderiv_eq_zero (h : is_local_min f a) : fderiv ℝ f a = 0 := if hf : differentiable_at ℝ f a then h.has_fderiv_at_eq_zero hf.has_fderiv_at else fderiv_zero_of_not_differentiable_at hf /-- **Fermat's Theorem**: the derivative of a function at a local maximum equals zero. -/ lemma is_local_max.has_fderiv_at_eq_zero (h : is_local_max f a) (hf : has_fderiv_at f f' a) : f' = 0 := neg_eq_zero.1 $ h.neg.has_fderiv_at_eq_zero hf.neg /-- **Fermat's Theorem**: the derivative of a function at a local maximum equals zero. -/ lemma is_local_max.fderiv_eq_zero (h : is_local_max f a) : fderiv ℝ f a = 0 := if hf : differentiable_at ℝ f a then h.has_fderiv_at_eq_zero hf.has_fderiv_at else fderiv_zero_of_not_differentiable_at hf /-- **Fermat's Theorem**: the derivative of a function at a local extremum equals zero. -/ lemma is_local_extr.has_fderiv_at_eq_zero (h : is_local_extr f a) : has_fderiv_at f f' a → f' = 0 := h.elim is_local_min.has_fderiv_at_eq_zero is_local_max.has_fderiv_at_eq_zero /-- **Fermat's Theorem**: the derivative of a function at a local extremum equals zero. -/ lemma is_local_extr.fderiv_eq_zero (h : is_local_extr f a) : fderiv ℝ f a = 0 := h.elim is_local_min.fderiv_eq_zero is_local_max.fderiv_eq_zero end module section real variables {f : ℝ → ℝ} {f' : ℝ} {a b : ℝ} /-- **Fermat's Theorem**: the derivative of a function at a local minimum equals zero. -/ lemma is_local_min.has_deriv_at_eq_zero (h : is_local_min f a) (hf : has_deriv_at f f' a) : f' = 0 := by simpa using continuous_linear_map.ext_iff.1 (h.has_fderiv_at_eq_zero (has_deriv_at_iff_has_fderiv_at.1 hf)) 1 /-- **Fermat's Theorem**: the derivative of a function at a local minimum equals zero. -/ lemma is_local_min.deriv_eq_zero (h : is_local_min f a) : deriv f a = 0 := if hf : differentiable_at ℝ f a then h.has_deriv_at_eq_zero hf.has_deriv_at else deriv_zero_of_not_differentiable_at hf /-- **Fermat's Theorem**: the derivative of a function at a local maximum equals zero. -/ lemma is_local_max.has_deriv_at_eq_zero (h : is_local_max f a) (hf : has_deriv_at f f' a) : f' = 0 := neg_eq_zero.1 $ h.neg.has_deriv_at_eq_zero hf.neg /-- **Fermat's Theorem**: the derivative of a function at a local maximum equals zero. -/ lemma is_local_max.deriv_eq_zero (h : is_local_max f a) : deriv f a = 0 := if hf : differentiable_at ℝ f a then h.has_deriv_at_eq_zero hf.has_deriv_at else deriv_zero_of_not_differentiable_at hf /-- **Fermat's Theorem**: the derivative of a function at a local extremum equals zero. -/ lemma is_local_extr.has_deriv_at_eq_zero (h : is_local_extr f a) : has_deriv_at f f' a → f' = 0 := h.elim is_local_min.has_deriv_at_eq_zero is_local_max.has_deriv_at_eq_zero /-- **Fermat's Theorem**: the derivative of a function at a local extremum equals zero. -/ lemma is_local_extr.deriv_eq_zero (h : is_local_extr f a) : deriv f a = 0 := h.elim is_local_min.deriv_eq_zero is_local_max.deriv_eq_zero end real section Rolle variables (f f' : ℝ → ℝ) {a b : ℝ} /-- A continuous function on a closed interval with `f a = f b` takes either its maximum or its minimum value at a point in the interior of the interval. -/ lemma exists_Ioo_extr_on_Icc (hab : a < b) (hfc : continuous_on f (Icc a b)) (hfI : f a = f b) : ∃ c ∈ Ioo a b, is_extr_on f (Icc a b) c := begin have ne : (Icc a b).nonempty, from nonempty_Icc.2 (le_of_lt hab), -- Consider absolute min and max points obtain ⟨c, cmem, cle⟩ : ∃ c ∈ Icc a b, ∀ x ∈ Icc a b, f c ≤ f x, from is_compact_Icc.exists_forall_le ne hfc, obtain ⟨C, Cmem, Cge⟩ : ∃ C ∈ Icc a b, ∀ x ∈ Icc a b, f x ≤ f C, from is_compact_Icc.exists_forall_ge ne hfc, by_cases hc : f c = f a, { by_cases hC : f C = f a, { have : ∀ x ∈ Icc a b, f x = f a, from λ x hx, le_antisymm (hC ▸ Cge x hx) (hc ▸ cle x hx), -- `f` is a constant, so we can take any point in `Ioo a b` rcases exists_between hab with ⟨c', hc'⟩, refine ⟨c', hc', or.inl _⟩, assume x hx, rw [mem_set_of_eq, this x hx, ← hC], exact Cge c' ⟨le_of_lt hc'.1, le_of_lt hc'.2⟩ }, { refine ⟨C, ⟨lt_of_le_of_ne Cmem.1 $ mt _ hC, lt_of_le_of_ne Cmem.2 $ mt _ hC⟩, or.inr Cge⟩, exacts [λ h, by rw h, λ h, by rw [h, hfI]] } }, { refine ⟨c, ⟨lt_of_le_of_ne cmem.1 $ mt _ hc, lt_of_le_of_ne cmem.2 $ mt _ hc⟩, or.inl cle⟩, exacts [λ h, by rw h, λ h, by rw [h, hfI]] } end /-- A continuous function on a closed interval with `f a = f b` has a local extremum at some point of the corresponding open interval. -/ lemma exists_local_extr_Ioo (hab : a < b) (hfc : continuous_on f (Icc a b)) (hfI : f a = f b) : ∃ c ∈ Ioo a b, is_local_extr f c := let ⟨c, cmem, hc⟩ := exists_Ioo_extr_on_Icc f hab hfc hfI in ⟨c, cmem, hc.is_local_extr $ Icc_mem_nhds cmem.1 cmem.2⟩ /-- **Rolle's Theorem** `has_deriv_at` version -/ lemma exists_has_deriv_at_eq_zero (hab : a < b) (hfc : continuous_on f (Icc a b)) (hfI : f a = f b) (hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) : ∃ c ∈ Ioo a b, f' c = 0 := let ⟨c, cmem, hc⟩ := exists_local_extr_Ioo f hab hfc hfI in ⟨c, cmem, hc.has_deriv_at_eq_zero $ hff' c cmem⟩ /-- **Rolle's Theorem** `deriv` version -/ lemma exists_deriv_eq_zero (hab : a < b) (hfc : continuous_on f (Icc a b)) (hfI : f a = f b) : ∃ c ∈ Ioo a b, deriv f c = 0 := let ⟨c, cmem, hc⟩ := exists_local_extr_Ioo f hab hfc hfI in ⟨c, cmem, hc.deriv_eq_zero⟩ variables {f f'} {l : ℝ} /-- **Rolle's Theorem**, a version for a function on an open interval: if `f` has derivative `f'` on `(a, b)` and has the same limit `l` at `𝓝[>] a` and `𝓝[<] b`, then `f' c = 0` for some `c ∈ (a, b)`. -/ lemma exists_has_deriv_at_eq_zero' (hab : a < b) (hfa : tendsto f (𝓝[>] a) (𝓝 l)) (hfb : tendsto f (𝓝[<] b) (𝓝 l)) (hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) : ∃ c ∈ Ioo a b, f' c = 0 := begin have : continuous_on f (Ioo a b) := λ x hx, (hff' x hx).continuous_at.continuous_within_at, have hcont := continuous_on_Icc_extend_from_Ioo hab.ne this hfa hfb, obtain ⟨c, hc, hcextr⟩ : ∃ c ∈ Ioo a b, is_local_extr (extend_from (Ioo a b) f) c, { apply exists_local_extr_Ioo _ hab hcont, rw eq_lim_at_right_extend_from_Ioo hab hfb, exact eq_lim_at_left_extend_from_Ioo hab hfa }, use [c, hc], apply (hcextr.congr _).has_deriv_at_eq_zero (hff' c hc), rw eventually_eq_iff_exists_mem, exact ⟨Ioo a b, Ioo_mem_nhds hc.1 hc.2, extend_from_extends this⟩ end /-- **Rolle's Theorem**, a version for a function on an open interval: if `f` has the same limit `l` at `𝓝[>] a` and `𝓝[<] b`, then `deriv f c = 0` for some `c ∈ (a, b)`. This version does not require differentiability of `f` because we define `deriv f c = 0` whenever `f` is not differentiable at `c`. -/ lemma exists_deriv_eq_zero' (hab : a < b) (hfa : tendsto f (𝓝[>] a) (𝓝 l)) (hfb : tendsto f (𝓝[<] b) (𝓝 l)) : ∃ c ∈ Ioo a b, deriv f c = 0 := classical.by_cases (assume h : ∀ x ∈ Ioo a b, differentiable_at ℝ f x, show ∃ c ∈ Ioo a b, deriv f c = 0, from exists_has_deriv_at_eq_zero' hab hfa hfb (λ x hx, (h x hx).has_deriv_at)) (assume h : ¬∀ x ∈ Ioo a b, differentiable_at ℝ f x, have h : ∃ x, x ∈ Ioo a b ∧ ¬differentiable_at ℝ f x, by { push_neg at h, exact h }, let ⟨c, hc, hcdiff⟩ := h in ⟨c, hc, deriv_zero_of_not_differentiable_at hcdiff⟩) end Rolle namespace polynomial lemma card_root_set_le_derivative {F : Type*} [field F] [algebra F ℝ] (p : F[X]) : fintype.card (p.root_set ℝ) ≤ fintype.card (p.derivative.root_set ℝ) + 1 := begin haveI : char_zero F := (ring_hom.char_zero_iff (algebra_map F ℝ).injective).mpr (by apply_instance), by_cases hp : p = 0, { simp_rw [hp, derivative_zero, root_set_zero, set.empty_card', zero_le_one] }, by_cases hp' : p.derivative = 0, { rw eq_C_of_nat_degree_eq_zero (nat_degree_eq_zero_of_derivative_eq_zero hp'), simp_rw [root_set_C, set.empty_card', zero_le] }, simp_rw [root_set_def, finset.coe_sort_coe, fintype.card_coe], refine finset.card_le_of_interleaved (λ x hx y hy hxy, _), rw [←finset.mem_coe, ←root_set_def, mem_root_set hp] at hx hy, obtain ⟨z, hz1, hz2⟩ := exists_deriv_eq_zero (λ x : ℝ, aeval x p) hxy p.continuous_aeval.continuous_on (hx.trans hy.symm), refine ⟨z, _, hz1⟩, rw [←finset.mem_coe, ←root_set_def, mem_root_set hp', ←hz2], simp_rw [aeval_def, ←eval_map, polynomial.deriv, derivative_map], end end polynomial
4e255b5a64abc4e57fe33a0ef6d5fb574f9de316
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/let2.lean
e37b9f9b4b2c18dfd07aa7d30d33550063de3bcb
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
450
lean
definition b := let a := true ∧ true, a := a ∧ a, a := a ∧ a, a := a ∧ a, a := a ∧ a, a := a ∧ a, a := a ∧ a, a := a ∧ a, a := a ∧ a, a := a ∧ a, a := a ∧ a, a := a ∧ a, a := a ∧ a, a := a ∧ a, a := a ∧ a, a := a ∧ a, a := a ∧ a in a check b
6bc2bbc6fe1f84d3a71ae8955335da162c18ca55
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/data/option/basic.lean
09f531b4bdefba500a4a66605f6005c8728071b2
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
10,445
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import tactic.basic namespace option variables {α : Type*} {β : Type*} {γ : Type*} lemma coe_def : (coe : α → option α) = some := rfl lemma some_ne_none (x : α) : some x ≠ none := λ h, option.no_confusion h @[simp] theorem get_mem : ∀ {o : option α} (h : is_some o), option.get h ∈ o | (some a) _ := rfl theorem get_of_mem {a : α} : ∀ {o : option α} (h : is_some o), a ∈ o → option.get h = a | _ _ rfl := rfl @[simp] lemma not_mem_none (a : α) : a ∉ (none : option α) := λ h, option.no_confusion h @[simp] lemma some_get : ∀ {x : option α} (h : is_some x), some (option.get h) = x | (some x) hx := rfl @[simp] lemma get_some (x : α) (h : is_some (some x)) : option.get h = x := rfl @[simp] lemma get_or_else_some (x y : α) : option.get_or_else (some x) y = x := rfl @[simp] lemma get_or_else_coe (x y : α) : option.get_or_else ↑x y = x := rfl lemma get_or_else_of_ne_none {x : option α} (hx : x ≠ none) (y : α) : some (x.get_or_else y) = x := by cases x; [contradiction, rw get_or_else_some] theorem mem_unique {o : option α} {a b : α} (ha : a ∈ o) (hb : b ∈ o) : a = b := option.some.inj $ ha.symm.trans hb theorem some_injective (α : Type*) : function.injective (@some α) := λ _ _, some_inj.mp /-- `option.map f` is injective if `f` is injective. -/ theorem map_injective {f : α → β} (Hf : function.injective f) : function.injective (option.map f) | none none H := rfl | (some a₁) (some a₂) H := by rw Hf (option.some.inj H) @[ext] theorem ext : ∀ {o₁ o₂ : option α}, (∀ a, a ∈ o₁ ↔ a ∈ o₂) → o₁ = o₂ | none none H := rfl | (some a) o H := ((H _).1 rfl).symm | o (some b) H := (H _).2 rfl theorem eq_none_iff_forall_not_mem {o : option α} : o = none ↔ (∀ a, a ∉ o) := ⟨λ e a h, by rw e at h; cases h, λ h, ext $ by simpa⟩ @[simp] theorem none_bind {α β} (f : α → option β) : none >>= f = none := rfl @[simp] theorem some_bind {α β} (a : α) (f : α → option β) : some a >>= f = f a := rfl @[simp] theorem none_bind' (f : α → option β) : none.bind f = none := rfl @[simp] theorem some_bind' (a : α) (f : α → option β) : (some a).bind f = f a := rfl @[simp] theorem bind_some : ∀ x : option α, x >>= some = x := @bind_pure α option _ _ @[simp] theorem bind_eq_some {α β} {x : option α} {f : α → option β} {b : β} : x >>= f = some b ↔ ∃ a, x = some a ∧ f a = some b := by cases x; simp @[simp] theorem bind_eq_some' {x : option α} {f : α → option β} {b : β} : x.bind f = some b ↔ ∃ a, x = some a ∧ f a = some b := by cases x; simp @[simp] theorem bind_eq_none' {o : option α} {f : α → option β} : o.bind f = none ↔ (∀ b a, a ∈ o → b ∉ f a) := by simp only [eq_none_iff_forall_not_mem, not_exists, not_and, mem_def, bind_eq_some'] @[simp] theorem bind_eq_none {α β} {o : option α} {f : α → option β} : o >>= f = none ↔ (∀ b a, a ∈ o → b ∉ f a) := bind_eq_none' lemma bind_comm {α β γ} {f : α → β → option γ} (a : option α) (b : option β) : a.bind (λx, b.bind (f x)) = b.bind (λy, a.bind (λx, f x y)) := by cases a; cases b; refl lemma bind_assoc (x : option α) (f : α → option β) (g : β → option γ) : (x.bind f).bind g = x.bind (λ y, (f y).bind g) := by cases x; refl lemma join_eq_some {x : option (option α)} {a : α} : x.join = some a ↔ x = some (some a) := by simp lemma join_ne_none {x : option (option α)} : x.join ≠ none ↔ ∃ z, x = some (some z) := by simp lemma join_ne_none' {x : option (option α)} : ¬(x.join = none) ↔ ∃ z, x = some (some z) := by simp lemma bind_id_eq_join {x : option (option α)} : x >>= id = x.join := by simp lemma join_eq_join : mjoin = @join α := funext (λ x, by rw [mjoin, bind_id_eq_join]) lemma bind_eq_bind {α β : Type*} {f : α → option β} {x : option α} : x >>= f = x.bind f := rfl @[simp] lemma map_eq_map {α β} {f : α → β} : (<$>) f = option.map f := rfl theorem map_none {α β} {f : α → β} : f <$> none = none := rfl theorem map_some {α β} {a : α} {f : α → β} : f <$> some a = some (f a) := rfl @[simp] theorem map_none' {f : α → β} : option.map f none = none := rfl @[simp] theorem map_some' {a : α} {f : α → β} : option.map f (some a) = some (f a) := rfl theorem map_eq_some {α β} {x : option α} {f : α → β} {b : β} : f <$> x = some b ↔ ∃ a, x = some a ∧ f a = b := by cases x; simp @[simp] theorem map_eq_some' {x : option α} {f : α → β} {b : β} : x.map f = some b ↔ ∃ a, x = some a ∧ f a = b := by cases x; simp lemma map_eq_none {α β} {x : option α} {f : α → β} : f <$> x = none ↔ x = none := by { cases x; simp only [map_none, map_some, eq_self_iff_true] } @[simp] lemma map_eq_none' {x : option α} {f : α → β} : x.map f = none ↔ x = none := by { cases x; simp only [map_none', map_some', eq_self_iff_true] } lemma map_congr {f g : α → β} {x : option α} (h : ∀ a ∈ x, f a = g a) : option.map f x = option.map g x := by { cases x; simp only [map_none', map_some', h, mem_def] } @[simp] theorem map_id' : option.map (@id α) = id := map_id @[simp] lemma map_map (h : β → γ) (g : α → β) (x : option α) : option.map h (option.map g x) = option.map (h ∘ g) x := by { cases x; simp only [map_none', map_some'] } lemma comp_map (h : β → γ) (g : α → β) (x : option α) : option.map (h ∘ g) x = option.map h (option.map g x) := (map_map _ _ _).symm @[simp] lemma map_comp_map (f : α → β) (g : β → γ) : option.map g ∘ option.map f = option.map (g ∘ f) := by { ext x, rw comp_map } lemma bind_map_comm {α β} {x : option (option α) } {f : α → β} : x >>= option.map f = x.map (option.map f) >>= id := by { cases x; simp } lemma join_map_eq_map_join {f : α → β} {x : option (option α)} : (x.map (option.map f)).join = x.join.map f := by { rcases x with _ | _ | x; simp } lemma join_join {x : option (option (option α))} : x.join.join = (x.map join).join := by { rcases x with _ | _ | _ | x; simp } lemma mem_of_mem_join {a : α} {x : option (option α)} (h : a ∈ x.join) : some a ∈ x := mem_def.mpr ((mem_def.mp h).symm ▸ join_eq_some.mp h) @[simp] theorem seq_some {α β} {a : α} {f : α → β} : some f <*> some a = some (f a) := rfl @[simp] theorem some_orelse' (a : α) (x : option α) : (some a).orelse x = some a := rfl @[simp] theorem some_orelse (a : α) (x : option α) : (some a <|> x) = some a := rfl @[simp] theorem none_orelse' (x : option α) : none.orelse x = x := by cases x; refl @[simp] theorem none_orelse (x : option α) : (none <|> x) = x := none_orelse' x @[simp] theorem orelse_none' (x : option α) : x.orelse none = x := by cases x; refl @[simp] theorem orelse_none (x : option α) : (x <|> none) = x := orelse_none' x @[simp] theorem is_some_none : @is_some α none = ff := rfl @[simp] theorem is_some_some {a : α} : is_some (some a) = tt := rfl theorem is_some_iff_exists {x : option α} : is_some x ↔ ∃ a, x = some a := by cases x; simp [is_some]; exact ⟨_, rfl⟩ @[simp] theorem is_none_none : @is_none α none = tt := rfl @[simp] theorem is_none_some {a : α} : is_none (some a) = ff := rfl @[simp] theorem not_is_some {a : option α} : is_some a = ff ↔ a.is_none = tt := by cases a; simp lemma eq_some_iff_get_eq {o : option α} {a : α} : o = some a ↔ ∃ h : o.is_some, option.get h = a := by cases o; simp lemma not_is_some_iff_eq_none {o : option α} : ¬o.is_some ↔ o = none := by cases o; simp lemma ne_none_iff_is_some {o : option α} : o ≠ none ↔ o.is_some := by cases o; simp lemma ne_none_iff_exists {o : option α} : o ≠ none ↔ ∃ (x : α), some x = o := by {cases o; simp} lemma ne_none_iff_exists' {o : option α} : o ≠ none ↔ ∃ (x : α), o = some x := ne_none_iff_exists.trans $ exists_congr $ λ _, eq_comm lemma bex_ne_none {p : option α → Prop} : (∃ x ≠ none, p x) ↔ ∃ x, p (some x) := ⟨λ ⟨x, hx, hp⟩, ⟨get $ ne_none_iff_is_some.1 hx, by rwa [some_get]⟩, λ ⟨x, hx⟩, ⟨some x, some_ne_none x, hx⟩⟩ lemma ball_ne_none {p : option α → Prop} : (∀ x ≠ none, p x) ↔ ∀ x, p (some x) := ⟨λ h x, h (some x) (some_ne_none x), λ h x hx, by simpa only [some_get] using h (get $ ne_none_iff_is_some.1 hx)⟩ theorem iget_mem [inhabited α] : ∀ {o : option α}, is_some o → o.iget ∈ o | (some a) _ := rfl theorem iget_of_mem [inhabited α] {a : α} : ∀ {o : option α}, a ∈ o → o.iget = a | _ rfl := rfl @[simp] theorem guard_eq_some {p : α → Prop} [decidable_pred p] {a b : α} : guard p a = some b ↔ a = b ∧ p a := by by_cases p a; simp [option.guard, h]; intro; contradiction @[simp] theorem guard_eq_some' {p : Prop} [decidable p] : ∀ u, _root_.guard p = some u ↔ p | () := by by_cases p; simp [guard, h, pure]; intro; contradiction theorem lift_or_get_choice {f : α → α → α} (h : ∀ a b, f a b = a ∨ f a b = b) : ∀ o₁ o₂, lift_or_get f o₁ o₂ = o₁ ∨ lift_or_get f o₁ o₂ = o₂ | none none := or.inl rfl | (some a) none := or.inl rfl | none (some b) := or.inr rfl | (some a) (some b) := by simpa [lift_or_get] using h a b @[simp] lemma lift_or_get_none_left {f} {b : option α} : lift_or_get f none b = b := by cases b; refl @[simp] lemma lift_or_get_none_right {f} {a : option α} : lift_or_get f a none = a := by cases a; refl @[simp] lemma lift_or_get_some_some {f} {a b : α} : lift_or_get f (some a) (some b) = f a b := rfl /-- given an element of `a : option α`, a default element `b : β` and a function `α → β`, apply this function to `a` if it comes from `α`, and return `b` otherwise. -/ def cases_on' : option α → β → (α → β) → β | none n s := n | (some a) n s := s a @[simp] lemma cases_on'_none (x : β) (f : α → β) : cases_on' none x f = x := rfl @[simp] lemma cases_on'_some (x : β) (f : α → β) (a : α) : cases_on' (some a) x f = f a := rfl @[simp] lemma cases_on'_coe (x : β) (f : α → β) (a : α) : cases_on' (a : option α) x f = f a := rfl @[simp] lemma cases_on'_none_coe (f : option α → β) (o : option α) : cases_on' o (f none) (f ∘ coe) = f o := by cases o; refl end option
d428a619de197c8810e88ef33e812263571bbb2d
dd4e652c749fea9ac77e404005cb3470e5f75469
/src/test.lean
369bbe53430a69622cc493bbb66c0b8e051d2e84
[]
no_license
skbaek/cvx
e32822ad5943541539966a37dee162b0a5495f55
c50c790c9116f9fac8dfe742903a62bdd7292c15
refs/heads/master
1,623,803,010,339
1,618,058,958,000
1,618,058,958,000
176,293,135
3
2
null
null
null
null
UTF-8
Lean
false
false
501
lean
import algebra.module analysis.normed_space.basic data.real.basic class real_inner_product_space (V : Type*) [add_comm_group V] extends vector_space ℝ V := (inner : V → V → ℝ) (inner_axioms : false /- (axioms omitted here) -/) instance is_normed_space (V : Type*) [add_comm_group V] [real_inner_product_space V] : normed_space ℝ V := sorry local attribute [-instance] is_normed_space set_option trace.class_instances true noncomputable example : add_comm_group ℝ := by apply_instance
69a794f186a6bb399eae6b2724f1bd4532fb6770
43390109ab88557e6090f3245c47479c123ee500
/src/M3P14/jacobi_sym.lean
59c05413fc31fa6320d51c2ebe4cbf32e26fcfce
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,916
lean
import data.nat.basic M3P14.order_zmodn_kmb data.int.basic M3P14.lqr data.nat.prime private theorem aux1 (a b : ℕ) (h : ¬a + 3 = b + 1) : b + 1 ≠ a + 3 := by {intro h2, exact absurd h2.symm h} private theorem aux2 (a b : ℕ) (h : a + 3 ≥ int.nat_abs ↑(nat.succ b)) : (a + 3) % (nat.succ b) < nat.succ (nat.succ (nat.succ a)) := begin simp at h, suffices : (a + 3) % (b + 1) < (a + 3), by simp [this], cases (classical.em (a + 3 = b + 1)), rw [h_1.symm, nat.mod_self], exact dec_trivial, have eq : int.nat_abs (1 + ↑b) = 1 + b, from int.nat_abs_of_nat (1 + b), have h2 : a + 3 ≥ b + 1, rw eq at h, rwa add_comm b 1, suffices : (nat.succ b) < nat.succ (nat.succ (nat.succ a)), from lt_trans (nat.mod_lt (a + 3) (nat.pos_iff_ne_zero.mpr (by trivial))) this, suffices : b + 1 ≤ a + 3, from lt_of_le_of_ne this (aux1 a b h_1), exact h2, end private theorem aux3 (a b : ℕ) (h : ¬a + 3 ≥ int.nat_abs ↑b) : b % (a + 3) < nat.succ (nat.succ (nat.succ a)) := begin suffices : (a+3) > 0, from nat.mod_lt b this, from dec_trivial, end private def jacobi_sym_pos : ℕ → ℕ → ℤ | a 0 := 0 | 0 (nat.succ b) := 0 | 1 (nat.succ b) := 1 | 2 (nat.succ b) := if (nat.succ b) % 8 = 1 ∨ (nat.succ b) % 8 = 7 then 1 else -1 | (nat.succ (nat.succ (nat.succ a))) (nat.succ b) := if h1 : (a+3) ≥ int.nat_abs (nat.succ b) then have (a + 3) % (nat.succ b) < nat.succ (nat.succ (nat.succ a)), from aux2 a b h1, jacobi_sym_pos ((a+3)%(nat.succ b)) (nat.succ b) else (if h2 : (a+3) % 2 = 0 then have 2 < nat.succ (nat.succ (nat.succ a)), from dec_trivial, have (a + 3) / 2 < nat.succ (nat.succ (nat.succ a)), from nat.div_lt_self dec_trivial dec_trivial, jacobi_sym_pos 2 (nat.succ b) * jacobi_sym_pos ((a+3)/2) (nat.succ b) else have (nat.succ b) % (a + 3) < nat.succ (nat.succ (nat.succ a)), from aux3 a (nat.succ b) h1, (if (a+3) % 4 = 1 ∨ (nat.succ b) % 4 = 1 then jacobi_sym_pos ((nat.succ b) % (a+3)) (a+3) else -(jacobi_sym_pos ((nat.succ b) % (a+3)) (a+3)))) using_well_founded {rel_tac:= λ _ _, `[exact ⟨_, measure_wf (psigma.fst)⟩ ]} private def jacobi_sym_aux : ℤ → ℤ → ℤ | a -[1+b] := 0 | (-1) b := if b % 4 = 1 then 1 else -1 | -[1+(nat.succ a)] b := have 1 < nat.succ (nat.succ a), from dec_trivial, jacobi_sym_pos (a+2) (int.nat_abs b) * jacobi_sym_aux (-1) b | a b := jacobi_sym_pos (int.nat_abs a) (int.nat_abs b) using_well_founded {rel_tac:= λ _ _, `[exact ⟨_, measure_wf (int.nat_abs ∘ psigma.fst)⟩ ]} /- Computes the Jacobi Symbol, extended to b even which will output 0, is it the Kronecker Symbol?-/ def jacobi_algorithm : ℤ → ℤ → ℤ | a 1 := 1 | a b := if b % 2 = 1 then jacobi_sym_aux a b else 0 -- an attempt at notation for the jacobi symbol local notation {a|b} := jacobi_algorithm a b #eval {8|1} #eval {-5|0} #eval {1236|200011} -- Thank you Chris lemma dvd_prod {α : Type*} [comm_semiring α] {a} {l : list α} (ha : a ∈ l) : a ∣ l.prod := let ⟨s, t, h⟩ := list.mem_split ha in by rw [h, list.prod_append, list.prod_cons, mul_left_comm]; exact dvd_mul_right _ _ -- New definition of Jacobi symbol for positive and odd b to prove theorems noncomputable definition jacobi_symbol {n : ℤ} (a : ℤ) (hn : n > 0 ∧ int.gcd 2 n = 1) := list.prod ((nat.factors n.nat_abs).pmap (λ (p : ℕ) hp, @legendre_sym p a hp) begin intros, have h1 : prime_int ↑a_1 = nat.prime a_1, refl, have h2 : int.nat_abs ↑a_1 = a_1, refl, rw [h1, h2], have h3 := nat.mem_factors H, have h4 : a_1 ≠ 2, { have j1 := nat.prod_factors (int.nat_abs_pos_of_ne_zero (ne.symm (ne_of_lt hn.1))), assume j2, have j3 : 2 = int.nat_abs 2, refl, have j4 := dvd_prod H, rw [j1,j2,j3] at j4, unfold int.gcd at hn, have j5 := nat.gcd_eq_left j4, have j6 : int.nat_abs 2 ≠ 1, from dec_trivial, exact absurd (hn.2) (eq.subst j5.symm j6), }, exact ⟨h3,h4⟩, end) -- Properties of Jacobi symbol (taken from Wikipedia) -- set_option trace.check true theorem jacobi_sym_eq_legendre_sym (a n : ℤ) (hn : prime_int n ∧ (int.nat_abs n) ≠ 2) : {a|n} = legendre_sym a hn := begin unfold legendre_sym, cases (classical.em (n = 1)), rw h at hn, have : ¬prime_int 1, unfold prime_int, suffices : ¬nat.prime 1, by simp [this], exact dec_trivial, exact absurd hn.1 this, --have h2 : n ≠ 1, by simp [h], rw [jacobi_algorithm.equations._eqn_2 a n h], cases (classical.em (n % 2 = 1)), simp [h_1], { split_ifs, { sorry }, { cases (classical.em (n ∣ a)), { sorry, }, { exact absurd (and.intro h_3 h_4) h_2, }, }, { sorry }, }, { split_ifs, repeat {exact absurd (odd_prime_int_is_odd hn) h_1}, } end lemma mod_eq_of_quad (a b n : ℤ) (hp: a ≡ b [ZMOD n]) : quadratic_res a n → quadratic_res b n := begin unfold quadratic_res, simp, intros, have h1 := int.nat_abs_dvd.2 (int.modeq.modeq_iff_dvd.1 hp.symm), have h := int.modeq.trans (int.modeq.modeq_iff_dvd.2 h1) a_1, existsi x, exact h, end theorem jacobi_sym_refl (a b n : ℤ) (hn : n > 0 ∧ int.gcd 2 n = 1) : a ≡ b [ZMOD n] → jacobi_symbol a hn = jacobi_symbol b hn := begin intros, unfold jacobi_symbol, simp, sorry, end theorem jacobi_sym_not_coprime (a n : ℤ) (hn : n > 0 ∧ int.gcd 2 n = 1) : int.gcd a n ≠ 1 → jacobi_symbol a hn = 0 := begin intros, unfold jacobi_symbol, simp, sorry, end theorem jacobi_sym_num_mul (a b n : ℤ) (hn : n > 0 ∧ int.gcd 2 n = 1) : jacobi_symbol (a*b) hn = jacobi_symbol a hn * jacobi_symbol b hn := sorry theorem jacobi_sym_denom_mul (a m n : ℤ) (hm : m > 0 ∧ int.gcd 2 m = 1) (hn : n > 0 ∧ int.gcd 2 n = 1) (hmn : m*n > 0 ∧ int.gcd 2 (m*n) = 1) : jacobi_symbol a hmn = jacobi_symbol a hm * jacobi_symbol a hn := sorry theorem jacobi_sym_quadratic_res (m n : ℤ) (hm : m > 0 ∧ int.gcd 2 m = 1) (hn : n > 0 ∧ int.gcd 2 n = 1) [has_pow ℤ ℤ] : int.gcd m n = 1 → jacobi_symbol m hn * jacobi_symbol n hm = (-1)^(((m-1)/2)*((n-1)/2)) := sorry theorem jacobi_num_zero (n : ℤ) (hn : n > 0 ∧ int.gcd 2 n = 1) : if n = 1 then jacobi_symbol 0 hn = 1 else jacobi_symbol 0 hn = 0 := sorry theorem jacobi_num_neg_one (n : ℤ) (hn : n > 0 ∧ int.gcd 2 n = 1) [has_pow ℤ ℤ] : jacobi_symbol (-1) hn = (-1)^((n-1)/2) := sorry theorem jacobi_num_two (n : ℤ) (hn : n > 0 ∧ int.gcd 2 n = 1) [has_pow ℤ ℤ] : jacobi_symbol 2 hn = (-1)^(((n^2)-1)/8) := sorry theorem jacobi_denom_one (a : ℤ) : {a|1} = 1 := by refl
2b610546915d15ca1014e60ab8a07a6801138c6b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/polynomial/eisenstein/basic.lean
3e3903a29d3906fb50a2d3e66e96b3f65b695d38
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
8,917
lean
/- Copyright (c) 2022 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import ring_theory.eisenstein_criterion import ring_theory.polynomial.scale_roots /-! # Eisenstein polynomials > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Given an ideal `𝓟` of a commutative semiring `R`, we say that a polynomial `f : R[X]` is *Eisenstein at `𝓟`* if `f.leading_coeff ∉ 𝓟`, `∀ n, n < f.nat_degree → f.coeff n ∈ 𝓟` and `f.coeff 0 ∉ 𝓟 ^ 2`. In this file we gather miscellaneous results about Eisenstein polynomials. ## Main definitions * `polynomial.is_eisenstein_at f 𝓟`: the property of being Eisenstein at `𝓟`. ## Main results * `polynomial.is_eisenstein_at.irreducible`: if a primitive `f` satisfies `f.is_eisenstein_at 𝓟`, where `𝓟.is_prime`, then `f` is irreducible. ## Implementation details We also define a notion `is_weakly_eisenstein_at` requiring only that `∀ n < f.nat_degree → f.coeff n ∈ 𝓟`. This makes certain results slightly more general and it is useful since it is sometimes better behaved (for example it is stable under `polynomial.map`). -/ universes u v w z variables {R : Type u} open ideal algebra finset open_locale big_operators polynomial namespace polynomial /-- Given an ideal `𝓟` of a commutative semiring `R`, we say that a polynomial `f : R[X]` is *weakly Eisenstein at `𝓟`* if `∀ n, n < f.nat_degree → f.coeff n ∈ 𝓟`. -/ @[mk_iff] structure is_weakly_eisenstein_at [comm_semiring R] (f : R[X]) (𝓟 : ideal R) : Prop := (mem : ∀ {n}, n < f.nat_degree → f.coeff n ∈ 𝓟) /-- Given an ideal `𝓟` of a commutative semiring `R`, we say that a polynomial `f : R[X]` is *Eisenstein at `𝓟`* if `f.leading_coeff ∉ 𝓟`, `∀ n, n < f.nat_degree → f.coeff n ∈ 𝓟` and `f.coeff 0 ∉ 𝓟 ^ 2`. -/ @[mk_iff] structure is_eisenstein_at [comm_semiring R] (f : R[X]) (𝓟 : ideal R) : Prop := (leading : f.leading_coeff ∉ 𝓟) (mem : ∀ {n}, n < f.nat_degree → f.coeff n ∈ 𝓟) (not_mem : f.coeff 0 ∉ 𝓟 ^ 2) namespace is_weakly_eisenstein_at section comm_semiring variables [comm_semiring R] {𝓟 : ideal R} {f : R[X]} (hf : f.is_weakly_eisenstein_at 𝓟) include hf lemma map {A : Type v} [comm_ring A] (φ : R →+* A) : (f.map φ).is_weakly_eisenstein_at (𝓟.map φ) := begin refine (is_weakly_eisenstein_at_iff _ _).2 (λ n hn, _), rw [coeff_map], exact mem_map_of_mem _ (hf.mem (lt_of_lt_of_le hn (nat_degree_map_le _ _))) end end comm_semiring section comm_ring variables [comm_ring R] {𝓟 : ideal R} {f : R[X]} (hf : f.is_weakly_eisenstein_at 𝓟) variables {S : Type v} [comm_ring S] [algebra R S] section principal variable {p : R} local notation `P` := submodule.span R {p} lemma exists_mem_adjoin_mul_eq_pow_nat_degree {x : S} (hx : aeval x f = 0) (hmo : f.monic) (hf : f.is_weakly_eisenstein_at P) : ∃ y ∈ adjoin R ({x} : set S), (algebra_map R S) p * y = x ^ (f.map (algebra_map R S)).nat_degree := begin rw [aeval_def, polynomial.eval₂_eq_eval_map, eval_eq_sum_range, range_add_one, sum_insert not_mem_range_self, sum_range, (hmo.map (algebra_map R S)).coeff_nat_degree, one_mul] at hx, replace hx := eq_neg_of_add_eq_zero_left hx, have : ∀ n < f.nat_degree, p ∣ f.coeff n, { intros n hn, refine mem_span_singleton.1 (by simpa using hf.mem hn) }, choose! φ hφ using this, conv_rhs at hx { congr, congr, skip, funext, rw [fin.coe_eq_val, coeff_map, hφ i.1 (lt_of_lt_of_le i.2 (nat_degree_map_le _ _)), ring_hom.map_mul, mul_assoc] }, rw [hx, ← mul_sum, neg_eq_neg_one_mul, ← mul_assoc (-1 : S), mul_comm (-1 : S), mul_assoc], refine ⟨-1 * ∑ (i : fin (f.map (algebra_map R S)).nat_degree), (algebra_map R S) (φ i.1) * x ^ i.1, _, rfl⟩, exact subalgebra.mul_mem _ (subalgebra.neg_mem _ (subalgebra.one_mem _)) (subalgebra.sum_mem _ (λ i hi, subalgebra.mul_mem _ (subalgebra.algebra_map_mem _ _) (subalgebra.pow_mem _ (subset_adjoin (set.mem_singleton x)) _))) end lemma exists_mem_adjoin_mul_eq_pow_nat_degree_le {x : S} (hx : aeval x f = 0) (hmo : f.monic) (hf : f.is_weakly_eisenstein_at P) : ∀ i, (f.map (algebra_map R S)).nat_degree ≤ i → ∃ y ∈ adjoin R ({x} : set S), (algebra_map R S) p * y = x ^ i := begin intros i hi, obtain ⟨k, hk⟩ := exists_add_of_le hi, rw [hk, pow_add], obtain ⟨y, hy, H⟩ := exists_mem_adjoin_mul_eq_pow_nat_degree hx hmo hf, refine ⟨y * x ^ k, _, _⟩, { exact subalgebra.mul_mem _ hy (subalgebra.pow_mem _ (subset_adjoin (set.mem_singleton x)) _) }, { rw [← mul_assoc _ y, H] } end end principal include hf lemma pow_nat_degree_le_of_root_of_monic_mem {x : R} (hroot : is_root f x) (hmo : f.monic) : ∀ i, f.nat_degree ≤ i → x ^ i ∈ 𝓟 := begin intros i hi, obtain ⟨k, hk⟩ := exists_add_of_le hi, rw [hk, pow_add], suffices : x ^ f.nat_degree ∈ 𝓟, { exact mul_mem_right (x ^ k) 𝓟 this }, rw [is_root.def, eval_eq_sum_range, finset.range_add_one, finset.sum_insert finset.not_mem_range_self, finset.sum_range, hmo.coeff_nat_degree, one_mul] at hroot, rw [eq_neg_of_add_eq_zero_left hroot, neg_mem_iff], refine submodule.sum_mem _ (λ i hi, mul_mem_right _ _ (hf.mem (fin.is_lt i))) end lemma pow_nat_degree_le_of_aeval_zero_of_monic_mem_map {x : S} (hx : aeval x f = 0) (hmo : f.monic) : ∀ i, (f.map (algebra_map R S)).nat_degree ≤ i → x ^ i ∈ 𝓟.map (algebra_map R S) := begin suffices : x ^ (f.map (algebra_map R S)).nat_degree ∈ 𝓟.map (algebra_map R S), { intros i hi, obtain ⟨k, hk⟩ := exists_add_of_le hi, rw [hk, pow_add], refine mul_mem_right _ _ this }, rw [aeval_def, eval₂_eq_eval_map, ← is_root.def] at hx, refine pow_nat_degree_le_of_root_of_monic_mem (hf.map _) hx (hmo.map _) _ rfl.le end end comm_ring end is_weakly_eisenstein_at section scale_roots variables {A : Type*} [comm_ring R] [comm_ring A] lemma scale_roots.is_weakly_eisenstein_at (p : R[X]) {x : R} {P : ideal R} (hP : x ∈ P) : (scale_roots p x).is_weakly_eisenstein_at P := begin refine ⟨λ i hi, _⟩, rw coeff_scale_roots, rw [nat_degree_scale_roots, ← tsub_pos_iff_lt] at hi, exact ideal.mul_mem_left _ _ (ideal.pow_mem_of_mem P hP _ hi) end lemma dvd_pow_nat_degree_of_eval₂_eq_zero {f : R →+* A} (hf : function.injective f) {p : R[X]} (hp : p.monic) (x y : R) (z : A) (h : p.eval₂ f z = 0) (hz : f x * z = f y) : x ∣ y ^ p.nat_degree := begin rw [← nat_degree_scale_roots p x, ← ideal.mem_span_singleton], refine (scale_roots.is_weakly_eisenstein_at _ (ideal.mem_span_singleton.mpr $ dvd_refl x)) .pow_nat_degree_le_of_root_of_monic_mem _ ((monic_scale_roots_iff x).mpr hp) _ le_rfl, rw injective_iff_map_eq_zero' at hf, have := scale_roots_eval₂_eq_zero f h, rwa [hz, polynomial.eval₂_at_apply, hf] at this end lemma dvd_pow_nat_degree_of_aeval_eq_zero [algebra R A] [nontrivial A] [no_zero_smul_divisors R A] {p : R[X]} (hp : p.monic) (x y : R) (z : A) (h : polynomial.aeval z p = 0) (hz : z * algebra_map R A x = algebra_map R A y) : x ∣ y ^ p.nat_degree := dvd_pow_nat_degree_of_eval₂_eq_zero (no_zero_smul_divisors.algebra_map_injective R A) hp x y z h ((mul_comm _ _).trans hz) end scale_roots namespace is_eisenstein_at section comm_semiring variables [comm_semiring R] {𝓟 : ideal R} {f : R[X]} (hf : f.is_eisenstein_at 𝓟) lemma _root_.polynomial.monic.leading_coeff_not_mem (hf : f.monic) (h : 𝓟 ≠ ⊤) : ¬f.leading_coeff ∈ 𝓟 := hf.leading_coeff.symm ▸ (ideal.ne_top_iff_one _).1 h lemma _root_.polynomial.monic.is_eisenstein_at_of_mem_of_not_mem (hf : f.monic) (h : 𝓟 ≠ ⊤) (hmem : ∀ {n}, n < f.nat_degree → f.coeff n ∈ 𝓟) (hnot_mem : f.coeff 0 ∉ 𝓟 ^ 2) : f.is_eisenstein_at 𝓟 := { leading := hf.leading_coeff_not_mem h, mem := λ n hn, hmem hn, not_mem := hnot_mem } include hf lemma is_weakly_eisenstein_at : is_weakly_eisenstein_at f 𝓟 := ⟨λ _, hf.mem⟩ lemma coeff_mem {n : ℕ} (hn : n ≠ f.nat_degree) : f.coeff n ∈ 𝓟 := begin cases ne_iff_lt_or_gt.1 hn, { exact hf.mem h }, { rw [coeff_eq_zero_of_nat_degree_lt h], exact ideal.zero_mem _} end end comm_semiring section is_domain variables [comm_ring R] [is_domain R] {𝓟 : ideal R} {f : R[X]} (hf : f.is_eisenstein_at 𝓟) /-- If a primitive `f` satisfies `f.is_eisenstein_at 𝓟`, where `𝓟.is_prime`, then `f` is irreducible. -/ lemma irreducible (hprime : 𝓟.is_prime) (hu : f.is_primitive) (hfd0 : 0 < f.nat_degree) : irreducible f := irreducible_of_eisenstein_criterion hprime hf.leading (λ n hn, hf.mem (coe_lt_degree.1 hn)) (nat_degree_pos_iff_degree_pos.1 hfd0) hf.not_mem hu end is_domain end is_eisenstein_at end polynomial
fa8d905fdd9c0aa306353dfbf84149fd1e171aab
b815abf92ce063fe0d1fabf5b42da483552aa3e8
/library/init/meta/simp_tactic.lean
1bb33ac4bc7afa0dee4fa6f9c4a29f1802c8057c
[ "Apache-2.0" ]
permissive
yodalee/lean
a368d842df12c63e9f79414ed7bbee805b9001ef
317989bf9ef6ae1dec7488c2363dbfcdc16e0756
refs/heads/master
1,610,551,176,860
1,481,430,138,000
1,481,646,441,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,711
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.meta.attribute init.meta.constructor_tactic import init.meta.relation_tactics init.meta.occurrences open tactic meta constant simp_lemmas : Type meta constant simp_lemmas.mk : simp_lemmas meta constant simp_lemmas.join : simp_lemmas → simp_lemmas → simp_lemmas meta constant simp_lemmas.erase : simp_lemmas → list name → simp_lemmas meta constant simp_lemmas.mk_default_core : transparency → tactic simp_lemmas meta constant simp_lemmas.add_core : transparency → simp_lemmas → expr → tactic simp_lemmas meta constant simp_lemmas.add_simp_core : transparency → simp_lemmas → name → tactic simp_lemmas meta constant simp_lemmas.add_congr_core : transparency → simp_lemmas → name → tactic simp_lemmas meta def simp_lemmas.mk_default : tactic simp_lemmas := simp_lemmas.mk_default_core reducible meta def simp_lemmas.add : simp_lemmas → expr → tactic simp_lemmas := simp_lemmas.add_core reducible meta def simp_lemmas.add_simp : simp_lemmas → name → tactic simp_lemmas := simp_lemmas.add_simp_core reducible meta def simp_lemmas.add_congr : simp_lemmas → name → tactic simp_lemmas := simp_lemmas.add_congr_core reducible meta def simp_lemmas.append : simp_lemmas → list expr → tactic simp_lemmas | sls [] := return sls | sls (l::ls) := do new_sls ← simp_lemmas.add sls l, simp_lemmas.append new_sls ls /- (simp_lemmas.rewrite_core m s prove R e) apply a simplification lemma from 's' - 'prove' is used to discharge proof obligations. - 'R' is the equivalence relation being used (e.g., 'eq', 'iff') - 'e' is the expression to be "simplified" Result (new_e, pr) is the new expression 'new_e' and a proof (pr : e R new_e) -/ meta constant simp_lemmas.rewrite_core : transparency → simp_lemmas → tactic unit → name → expr → tactic (expr × expr) meta def simp_lemmas.rewrite : simp_lemmas → tactic unit → name → expr → tactic (expr × expr) := simp_lemmas.rewrite_core reducible /- (simp_lemmas.drewrite s e) tries to rewrite 'e' using only refl lemmas in 's' -/ meta constant simp_lemmas.drewrite_core : transparency → simp_lemmas → expr → tactic expr meta def simp_lemmas.drewrite : simp_lemmas → expr → tactic expr := simp_lemmas.drewrite_core reducible /- (Definitional) Simplify the given expression using *only* reflexivity equality lemmas from the given set of lemmas. The resulting expression is definitionally equal to the input. -/ meta constant simp_lemmas.dsimplify_core (max_steps : nat) (visit_instances : bool) : simp_lemmas → expr → tactic expr meta constant is_valid_simp_lemma_cnst : transparency → name → tactic bool meta constant is_valid_simp_lemma : transparency → expr → tactic bool def default_max_steps := 10000000 meta def simp_lemmas.dsimplify : simp_lemmas → expr → tactic expr := simp_lemmas.dsimplify_core default_max_steps ff namespace tactic meta constant dsimplify_core /- The user state type. -/ {α : Type} /- Initial user data -/ (a : α) (max_steps : nat) /- If visit_instances = ff, then instance implicit arguments are not visited, but tactic will canonize them. -/ (visit_instances : bool) /- (pre a e) is invoked before visiting the children of subterm 'e', if it succeeds the result (new_a, new_e, flag) where - 'new_a' is the new value for the user data - 'new_e' is a new expression that must be definitionally equal to 'e', - 'flag' if tt 'new_e' children should be visited, and 'post' invoked. -/ (pre : α → expr → tactic (α × expr × bool)) /- (post a e) is invoked after visiting the children of subterm 'e', The output is similar to (pre a e), but the 'flag' indicates whether the new expression should be revisited or not. -/ (post : α → expr → tactic (α × expr × bool)) : expr → tactic (α × expr) meta def dsimplify (pre : expr → tactic (expr × bool)) (post : expr → tactic (expr × bool)) : expr → tactic expr := λ e, do (a, new_e) ← dsimplify_core () default_max_steps ff (λ u e, do r ← pre e, return (u, r)) (λ u e, do r ← post e, return (u, r)) e, return new_e meta constant dunfold_expr_core : transparency → expr → tactic expr meta def dunfold_expr : expr → tactic expr := dunfold_expr_core reducible meta constant unfold_projection_core : transparency → expr → tactic expr meta def unfold_projection : expr → tactic expr := unfold_projection_core reducible meta def dunfold_occs_core (m : transparency) (max_steps : nat) (occs : occurrences) (cs : list name) (e : expr) : tactic expr := let unfold (c : nat) (e : expr) : tactic (nat × expr × bool) := do guard (cs^.any e^.is_app_of), new_e ← dunfold_expr_core m e, if occs^.contains c then return (c+1, new_e, tt) else return (c+1, e, tt) in do (c, new_e) ← dsimplify_core 1 max_steps tt unfold (λ c e, failed) e, return new_e meta def dunfold_core (m : transparency) (max_steps : nat) (cs : list name) (e : expr) : tactic expr := let unfold (u : unit) (e : expr) : tactic (unit × expr × bool) := do guard (cs^.any e^.is_app_of), new_e ← dunfold_expr_core m e, return (u, new_e, tt) in do (c, new_e) ← dsimplify_core () max_steps tt (λ c e, failed) unfold e, return new_e meta def dunfold : list name → tactic unit := λ cs, target >>= dunfold_core reducible default_max_steps cs >>= change meta def dunfold_occs_of (occs : list nat) (c : name) : tactic unit := target >>= dunfold_occs_core reducible default_max_steps (occurrences.pos occs) [c] >>= change meta def dunfold_core_at (occs : occurrences) (cs : list name) (h : expr) : tactic unit := do num_reverted : ℕ ← revert h, (expr.pi n bi d b : expr) ← target | failed, new_d : expr ← dunfold_occs_core reducible default_max_steps occs cs d, change $ expr.pi n bi new_d b, intron num_reverted meta def dunfold_at (cs : list name) (h : expr) : tactic unit := do num_reverted : ℕ ← revert h, (expr.pi n bi d b : expr) ← target | failed, new_d : expr ← dunfold_core reducible default_max_steps cs d, change $ expr.pi n bi new_d b, intron num_reverted structure simplify_config := (max_steps : nat) (contextual : bool) (lift_eq : bool) (canonize_instances : bool) (canonize_proofs : bool) (use_axioms : bool) def default_simplify_config : simplify_config := { max_steps := default_max_steps, contextual := ff, lift_eq := tt, canonize_instances := tt, canonize_proofs := ff, use_axioms := tt } meta constant simplify_core (c : simplify_config) (s : simp_lemmas) (r : name) : expr → tactic (expr × expr) meta constant ext_simplify_core /- The user state type. -/ {α : Type} /- Initial user data -/ (a : α) (c : simplify_config) /- Congruence and simplification lemmas. Remark: the simplification lemmas at not applied automatically like in the simplify_core tactic. the caller must use them at pre/post. -/ (s : simp_lemmas) /- Tactic for dischaging hypothesis in conditional rewriting rules. The argument 'α' is the current user state. -/ (prove : α → tactic α) /- (pre a r s p e) is invoked before visiting the children of subterm 'e', 'r' is the simplification relation being used, 's' is the updated set of lemmas if 'contextual' is tt, 'p' is the "parent" expression (if there is one). if it succeeds the result is (new_a, new_e, new_pr, flag) where - 'new_a' is the new value for the user data - 'new_e' is a new expression s.t. 'e r new_e' - 'new_pr' is a proof for 'e r new_e', If it is none, the proof is assumed to be by reflexivity - 'flag' if tt 'new_e' children should be visited, and 'post' invoked. -/ (pre : α → simp_lemmas → name → option expr → expr → tactic (α × expr × option expr × bool)) /- (post a r s p e) is invoked after visiting the children of subterm 'e', The output is similar to (pre a r s p e), but the 'flag' indicates whether the new expression should be revisited or not. -/ (post : α → simp_lemmas → name → option expr → expr → tactic (α × expr × option expr × bool)) /- simplification relation -/ (r : name) : expr → tactic (α × expr × expr) meta def simplify (cfg : simplify_config) (extra_lemmas : list expr) (e : expr) : tactic (expr × expr) := do lemmas ← simp_lemmas.mk_default, new_lemmas ← lemmas^.append extra_lemmas, e_type ← infer_type e >>= whnf, simplify_core cfg new_lemmas `eq e meta def simplify_goal (cfg : simplify_config) (extra_lemmas : list expr) : tactic unit := do (new_target, heq) ← target >>= simplify cfg extra_lemmas, assert `htarget new_target, swap, ht ← get_local `htarget, mk_app `eq.mpr [heq, ht] >>= exact meta def simp : tactic unit := simplify_goal default_simplify_config [] >> try triv >> try (reflexivity_core reducible) meta def simp_using (hs : list expr) : tactic unit := simplify_goal default_simplify_config hs >> try triv meta def ctx_simp : tactic unit := simplify_goal {default_simplify_config with contextual := tt} [] >> try triv >> try (reflexivity_core reducible) meta def dsimp : tactic unit := do S ← simp_lemmas.mk_default, target >>= S^.dsimplify >>= change meta def dsimp_at (h : expr) : tactic unit := do num_reverted : ℕ ← revert h, (expr.pi n bi d b : expr) ← target | failed, S ← simp_lemmas.mk_default, h_simp ← S^.dsimplify d, change $ expr.pi n bi h_simp b, intron num_reverted private meta def is_equation : expr → bool | (expr.pi n bi d b) := is_equation b | e := match (expr.is_eq e) with (some a) := tt | none := ff end private meta def collect_eqs : list expr → tactic (list expr) | [] := return [] | (h :: hs) := do Eqs ← collect_eqs hs, htype ← infer_type h >>= whnf, return $ if is_equation htype then h :: Eqs else Eqs /- Simplify target using all hypotheses in the local context. -/ meta def simp_using_hs : tactic unit := local_context >>= collect_eqs >>= simp_using meta def simp_core_at (extra_lemmas : list expr) (h : expr) : tactic unit := do when (expr.is_local_constant h = ff) (fail "tactic simp_at failed, the given expression is not a hypothesis"), htype ← infer_type h, (new_htype, heq) ← simplify default_simplify_config extra_lemmas htype, assert (expr.local_pp_name h) new_htype, mk_app `eq.mp [heq, h] >>= exact, try $ clear h meta def simp_at : expr → tactic unit := simp_core_at [] meta def simp_at_using (hs : list expr) : expr → tactic unit := simp_core_at hs meta def simp_at_using_hs (h : expr) : tactic unit := do hs ← local_context >>= collect_eqs, simp_core_at (list.filter (ne h) hs) h meta def mk_eq_simp_ext (simp_ext : expr → tactic (expr × expr)) : tactic unit := do (lhs, rhs) ← target >>= match_eq, (new_rhs, heq) ← simp_ext lhs, unify rhs new_rhs, exact heq /- Simp attribute support -/ meta def to_simp_lemmas : simp_lemmas → list name → tactic simp_lemmas | S [] := return S | S (n::ns) := do S' ← S^.add_simp n, to_simp_lemmas S' ns meta def mk_simp_attr (attr_name : name) : command := do t ← to_expr `(caching_user_attribute simp_lemmas), a ← attr_name^.to_expr, v ← to_expr `(({ name := %%a, descr := "simplifier attribute", mk_cache := λ ns, do {tactic.to_simp_lemmas simp_lemmas.mk ns}, dependencies := [`reducibility] } : caching_user_attribute simp_lemmas)), add_decl (declaration.defn attr_name [] t v reducibility_hints.abbrev ff), attribute.register attr_name meta def get_user_simp_lemmas (attr_name : name) : tactic simp_lemmas := if attr_name = `default then simp_lemmas.mk_default else do cnst ← return (expr.const attr_name []), attr ← eval_expr (caching_user_attribute simp_lemmas) cnst, caching_user_attribute.get_cache attr meta def join_user_simp_lemmas_core : simp_lemmas → list name → tactic simp_lemmas | S [] := return S | S (attr_name::R) := do S' ← get_user_simp_lemmas attr_name, join_user_simp_lemmas_core (S^.join S') R meta def join_user_simp_lemmas : list name → tactic simp_lemmas | [] := simp_lemmas.mk_default | attr_names := join_user_simp_lemmas_core simp_lemmas.mk attr_names end tactic export tactic (mk_simp_attr)
1af899d4c4de2deaa6a00f2852af2ca5e99576c0
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/data/fintype/card.lean
20ac9009c5bc34b3a4ffb6fb6a1f9f0a51d6ae27
[ "Apache-2.0" ]
permissive
DanielFabian/mathlib
efc3a50b5dde303c59eeb6353ef4c35a345d7112
f520d07eba0c852e96fe26da71d85bf6d40fcc2a
refs/heads/master
1,668,739,922,971
1,595,201,756,000
1,595,201,756,000
279,469,476
0
0
null
1,594,696,604,000
1,594,696,604,000
null
UTF-8
Lean
false
false
15,319
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.fintype.basic import data.nat.choose /-! Results about "big operations" over a `fintype`, and consequent results about cardinalities of certain types. ## Implementation note This content had previously been in `data.fintype`, but was moved here to avoid requiring `algebra.big_operators` (and hence many other imports) as a dependency of `fintype`. -/ universes u v variables {α : Type*} {β : Type*} {γ : Type*} open_locale big_operators namespace fintype lemma card_eq_sum_ones {α} [fintype α] : fintype.card α = ∑ a : α, 1 := finset.card_eq_sum_ones _ section open finset variables {ι : Type*} [fintype ι] [decidable_eq ι] @[to_additive] lemma prod_extend_by_one [comm_monoid α] (s : finset ι) (f : ι → α) : ∏ i, (if i ∈ s then f i else 1) = ∏ i in s, f i := by rw [← prod_filter, filter_mem_eq_inter, univ_inter] end section variables {M : Type*} [fintype α] [comm_monoid M] @[to_additive] lemma prod_eq_one (f : α → M) (h : ∀ a, f a = 1) : (∏ a, f a) = 1 := finset.prod_eq_one $ λ a ha, h a @[to_additive] lemma prod_congr (f g : α → M) (h : ∀ a, f a = g a) : (∏ a, f a) = ∏ a, g a := finset.prod_congr rfl $ λ a ha, h a @[to_additive] lemma prod_unique [unique β] (f : β → M) : (∏ x, f x) = f (default β) := by simp only [finset.prod_singleton, univ_unique] /-- If a product of a `finset` of a subsingleton type has a given value, so do the terms in that product. -/ @[to_additive "If a sum of a `finset` of a subsingleton type has a given value, so do the terms in that sum."] lemma eq_of_subsingleton_of_prod_eq {ι : Type*} [subsingleton ι] {s : finset ι} {f : ι → M} {b : M} (h : ∏ i in s, f i = b) : ∀ i ∈ s, f i = b := finset.eq_of_card_le_one_of_prod_eq (finset.card_le_one_of_subsingleton s) h end end fintype open finset theorem fin.prod_univ_succ [comm_monoid β] {n:ℕ} (f : fin n.succ → β) : ∏ i, f i = f 0 * ∏ i : fin n, f i.succ := begin rw [fin.univ_succ, prod_insert, prod_image], { intros x _ y _ hxy, exact fin.succ.inj hxy }, { simpa using fin.succ_ne_zero } end @[simp, to_additive] theorem fin.prod_univ_zero [comm_monoid β] (f : fin 0 → β) : ∏ i, f i = 1 := rfl theorem fin.sum_univ_succ [add_comm_monoid β] {n:ℕ} (f : fin n.succ → β) : ∑ i, f i = f 0 + ∑ i : fin n, f i.succ := by apply @fin.prod_univ_succ (multiplicative β) attribute [to_additive] fin.prod_univ_succ theorem fin.prod_univ_cast_succ [comm_monoid β] {n:ℕ} (f : fin n.succ → β) : ∏ i, f i = (∏ i : fin n, f i.cast_succ) * f (fin.last n) := begin rw [fin.univ_cast_succ, prod_insert, prod_image, mul_comm], { intros x _ y _ hxy, exact fin.cast_succ_inj.mp hxy }, { simpa using fin.cast_succ_ne_last } end theorem fin.sum_univ_cast_succ [add_comm_monoid β] {n:ℕ} (f : fin n.succ → β) : ∑ i, f i = ∑ i : fin n, f i.cast_succ + f (fin.last n) := by apply @fin.prod_univ_cast_succ (multiplicative β) attribute [to_additive] fin.prod_univ_cast_succ @[simp] theorem fintype.card_sigma {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype.card (sigma β) = ∑ a, fintype.card (β a) := card_sigma _ _ -- FIXME ouch, this should be in the main file. @[simp] theorem fintype.card_sum (α β : Type*) [fintype α] [fintype β] : fintype.card (α ⊕ β) = fintype.card α + fintype.card β := by simp [sum.fintype, fintype.of_equiv_card] @[simp] lemma fintype.card_pi_finset [decidable_eq α] [fintype α] {δ : α → Type*} (t : Π a, finset (δ a)) : (fintype.pi_finset t).card = ∏ a, card (t a) := by simp [fintype.pi_finset, card_map] @[simp] lemma fintype.card_pi {β : α → Type*} [fintype α] [decidable_eq α] [f : Π a, fintype (β a)] : fintype.card (Π a, β a) = ∏ a, fintype.card (β a) := fintype.card_pi_finset _ -- FIXME ouch, this should be in the main file. @[simp] lemma fintype.card_fun [fintype α] [decidable_eq α] [fintype β] : fintype.card (α → β) = fintype.card β ^ fintype.card α := by rw [fintype.card_pi, finset.prod_const, nat.pow_eq_pow]; refl @[simp] lemma card_vector [fintype α] (n : ℕ) : fintype.card (vector α n) = fintype.card α ^ n := by rw fintype.of_equiv_card; simp @[simp, to_additive] lemma finset.prod_attach_univ [fintype α] [comm_monoid β] (f : {a : α // a ∈ @univ α _} → β) : ∏ x in univ.attach, f x = ∏ x, f ⟨x, (mem_univ _)⟩ := prod_bij (λ x _, x.1) (λ _ _, mem_univ _) (λ _ _ , by simp) (by simp) (λ b _, ⟨⟨b, mem_univ _⟩, by simp⟩) @[to_additive] lemma finset.range_prod_eq_univ_prod [comm_monoid β] (n : ℕ) (f : ℕ → β) : ∏ k in range n, f k = ∏ k : fin n, f k := begin symmetry, refine prod_bij (λ k hk, k) _ _ _ _, { rintro ⟨k, hk⟩ _, simp * }, { rintro ⟨k, hk⟩ _, simp * }, { intros, rwa fin.eq_iff_veq }, { intros k hk, rw mem_range at hk, exact ⟨⟨k, hk⟩, mem_univ _, rfl⟩ } end /-- Taking a product over `univ.pi t` is the same as taking the product over `fintype.pi_finset t`. `univ.pi t` and `fintype.pi_finset t` are essentially the same `finset`, but differ in the type of their element, `univ.pi t` is a `finset (Π a ∈ univ, t a)` and `fintype.pi_finset t` is a `finset (Π a, t a)`. -/ @[to_additive "Taking a sum over `univ.pi t` is the same as taking the sum over `fintype.pi_finset t`. `univ.pi t` and `fintype.pi_finset t` are essentially the same `finset`, but differ in the type of their element, `univ.pi t` is a `finset (Π a ∈ univ, t a)` and `fintype.pi_finset t` is a `finset (Π a, t a)`."] lemma finset.prod_univ_pi [decidable_eq α] [fintype α] [comm_monoid β] {δ : α → Type*} {t : Π (a : α), finset (δ a)} (f : (Π (a : α), a ∈ (univ : finset α) → δ a) → β) : ∏ x in univ.pi t, f x = ∏ x in fintype.pi_finset t, f (λ a _, x a) := prod_bij (λ x _ a, x a (mem_univ _)) (by simp) (by simp) (by simp [function.funext_iff] {contextual := tt}) (λ x hx, ⟨λ a _, x a, by simp * at *⟩) /-- The product over `univ` of a sum can be written as a sum over the product of sets, `fintype.pi_finset`. `finset.prod_sum` is an alternative statement when the product is not over `univ` -/ lemma finset.prod_univ_sum [decidable_eq α] [fintype α] [comm_semiring β] {δ : α → Type u_1} [Π (a : α), decidable_eq (δ a)] {t : Π (a : α), finset (δ a)} {f : Π (a : α), δ a → β} : ∏ a, ∑ b in t a, f a b = ∑ p in fintype.pi_finset t, ∏ x, f x (p x) := by simp only [finset.prod_attach_univ, prod_sum, finset.sum_univ_pi] /-- Summing `a^s.card * b^(n-s.card)` over all finite subsets `s` of a fintype of cardinality `n` gives `(a + b)^n`. The "good" proof involves expanding along all coordinates using the fact that `x^n` is multilinear, but multilinear maps are only available now over rings, so we give instead a proof reducing to the usual binomial theorem to have a result over semirings. -/ lemma fintype.sum_pow_mul_eq_add_pow (α : Type*) [fintype α] {R : Type*} [comm_semiring R] (a b : R) : ∑ s : finset α, a ^ s.card * b ^ (fintype.card α - s.card) = (a + b) ^ (fintype.card α) := finset.sum_pow_mul_eq_add_pow _ _ _ lemma fin.sum_pow_mul_eq_add_pow {n : ℕ} {R : Type*} [comm_semiring R] (a b : R) : ∑ s : finset (fin n), a ^ s.card * b ^ (n - s.card) = (a + b) ^ n := by simpa using fintype.sum_pow_mul_eq_add_pow (fin n) a b /-- It is equivalent to sum a function over `fin n` or `finset.range n`. -/ @[to_additive] lemma fin.prod_univ_eq_prod_range [comm_monoid α] (f : ℕ → α) (n : ℕ) : ∏ i : fin n, f i.val = ∏ i in finset.range n, f i := begin apply finset.prod_bij (λ (a : fin n) ha, a.val), { assume a ha, simp [a.2] }, { assume a ha, refl }, { assume a b ha hb H, exact (fin.ext_iff _ _).2 H }, { assume b hb, exact ⟨⟨b, list.mem_range.mp hb⟩, finset.mem_univ _, rfl⟩, } end @[to_additive] lemma finset.prod_equiv [fintype α] [fintype β] [comm_monoid γ] (e : α ≃ β) (f : β → γ) : ∏ i, f (e i) = ∏ i, f i := begin apply prod_bij (λ i hi, e i) (λ i hi, mem_univ _) _ (λ a b _ _ h, e.injective h), { assume b hb, rcases e.surjective b with ⟨a, ha⟩, exact ⟨a, mem_univ _, ha.symm⟩, }, { simp } end @[to_additive] lemma finset.prod_subtype {M : Type*} [comm_monoid M] {p : α → Prop} {F : fintype (subtype p)} {s : finset α} (h : ∀ x, x ∈ s ↔ p x) (f : α → M) : ∏ a in s, f a = ∏ a : subtype p, f a := have (∈ s) = p, from set.ext h, begin rw ← prod_attach, substI p, congr, simp [finset.ext_iff] end @[to_additive] lemma finset.prod_fiberwise [fintype β] [decidable_eq β] [comm_monoid γ] (s : finset α) (f : α → β) (g : α → γ) : ∏ b : β, ∏ a in s.filter (λ a, f a = b), g a = ∏ a in s, g a := begin classical, have key : ∏ (b : β), ∏ a in s.filter (λ a, f a = b), g a = ∏ (a : α) in univ.bind (λ (b : β), s.filter (λ a, f a = b)), g a := (@prod_bind _ _ β g _ _ finset.univ (λ b : β, s.filter (λ a, f a = b)) _).symm, { simp only [key, filter_congr_decidable], apply finset.prod_congr, { ext, simp only [mem_bind, mem_filter, mem_univ, exists_prop_of_true, exists_eq_right'] }, { intros, refl } }, { intros x hx y hy H z hz, apply H, simp only [mem_filter, inf_eq_inter, mem_inter] at hz, rw [← hz.1.2, ← hz.2.2] } end @[to_additive] lemma fintype.prod_fiberwise [fintype α] [fintype β] [decidable_eq β] [comm_monoid γ] (f : α → β) (g : α → γ) : (∏ b : β, ∏ a : {a // f a = b}, g (a : α)) = ∏ a, g a := begin rw [← finset.prod_equiv (equiv.sigma_preimage_equiv f) _, ← univ_sigma_univ, prod_sigma], refl end section open finset variables {α₁ : Type*} {α₂ : Type*} {M : Type*} [fintype α₁] [fintype α₂] [comm_monoid M] @[to_additive] lemma fintype.prod_sum_type (f : α₁ ⊕ α₂ → M) : (∏ x, f x) = (∏ a₁, f (sum.inl a₁)) * (∏ a₂, f (sum.inr a₂)) := begin classical, let s : finset (α₁ ⊕ α₂) := univ.image sum.inr, rw [← prod_sdiff (subset_univ s), ← @prod_image (α₁ ⊕ α₂) _ _ _ _ _ _ sum.inl, ← @prod_image (α₁ ⊕ α₂) _ _ _ _ _ _ sum.inr], { congr, rw finset.ext_iff, rintro (a|a); { simp only [mem_image, exists_eq, mem_sdiff, mem_univ, exists_false, exists_prop_of_true, not_false_iff, and_self, not_true, and_false], } }, all_goals { intros, solve_by_elim [sum.inl.inj, sum.inr.inj], } end end namespace list lemma prod_take_of_fn [comm_monoid α] {n : ℕ} (f : fin n → α) (i : ℕ) : ((of_fn f).take i).prod = ∏ j in finset.univ.filter (λ (j : fin n), j.val < i), f j := begin have A : ∀ (j : fin n), ¬ (j.val < 0) := λ j, not_lt_bot, induction i with i IH, { simp [A] }, by_cases h : i < n, { have : i < length (of_fn f), by rwa [length_of_fn f], rw prod_take_succ _ _ this, have A : ((finset.univ : finset (fin n)).filter (λ j, j.val < i + 1)) = ((finset.univ : finset (fin n)).filter (λ j, j.val < i)) ∪ {(⟨i, h⟩ : fin n)}, by { ext j, simp [nat.lt_succ_iff_lt_or_eq, fin.ext_iff, - add_comm] }, have B : _root_.disjoint (finset.filter (λ (j : fin n), j.val < i) finset.univ) (singleton (⟨i, h⟩ : fin n)), by simp, rw [A, finset.prod_union B, IH], simp }, { have A : (of_fn f).take i = (of_fn f).take i.succ, { rw ← length_of_fn f at h, have : length (of_fn f) ≤ i := not_lt.mp h, rw [take_all_of_le this, take_all_of_le (le_trans this (nat.le_succ _))] }, have B : ∀ (j : fin n), (j.val < i.succ) = (j.val < i), { assume j, have : j.val < i := lt_of_lt_of_le j.2 (not_lt.mp h), simp [this, lt_trans this (nat.lt_succ_self _)] }, simp [← A, B, IH] } end -- `to_additive` does not work on `prod_take_of_fn` because of `0 : ℕ` in the proof. Copy-paste the -- proof instead... lemma sum_take_of_fn [add_comm_monoid α] {n : ℕ} (f : fin n → α) (i : ℕ) : ((of_fn f).take i).sum = ∑ j in finset.univ.filter (λ (j : fin n), j.val < i), f j := begin have A : ∀ (j : fin n), ¬ (j.val < 0) := λ j, not_lt_bot, induction i with i IH, { simp [A] }, by_cases h : i < n, { have : i < length (of_fn f), by rwa [length_of_fn f], rw sum_take_succ _ _ this, have A : ((finset.univ : finset (fin n)).filter (λ j, j.val < i + 1)) = ((finset.univ : finset (fin n)).filter (λ j, j.val < i)) ∪ singleton (⟨i, h⟩ : fin n), by { ext j, simp [nat.lt_succ_iff_lt_or_eq, fin.ext_iff, - add_comm] }, have B : _root_.disjoint (finset.filter (λ (j : fin n), j.val < i) finset.univ) (singleton (⟨i, h⟩ : fin n)), by simp, rw [A, finset.sum_union B, IH], simp }, { have A : (of_fn f).take i = (of_fn f).take i.succ, { rw ← length_of_fn f at h, have : length (of_fn f) ≤ i := not_lt.mp h, rw [take_all_of_le this, take_all_of_le (le_trans this (nat.le_succ _))] }, have B : ∀ (j : fin n), (j.val < i.succ) = (j.val < i), { assume j, have : j.val < i := lt_of_lt_of_le j.2 (not_lt.mp h), simp [this, lt_trans this (nat.lt_succ_self _)] }, simp [← A, B, IH] } end attribute [to_additive] prod_take_of_fn @[to_additive] lemma prod_of_fn [comm_monoid α] {n : ℕ} {f : fin n → α} : (of_fn f).prod = ∏ i, f i := begin convert prod_take_of_fn f n, { rw [take_all_of_le (le_of_eq (length_of_fn f))] }, { have : ∀ (j : fin n), j.val < n := λ j, j.2, simp [this] } end lemma alternating_sum_eq_finset_sum {G : Type*} [add_comm_group G] : ∀ (L : list G), alternating_sum L = ∑ i : fin L.length, (-1 : ℤ) ^ (i : ℕ) •ℤ L.nth_le i i.2 | [] := by { rw [alternating_sum, finset.sum_eq_zero], rintro ⟨i, ⟨⟩⟩ } | (g :: []) := begin show g = ∑ i : fin 1, (-1 : ℤ) ^ (i : ℕ) •ℤ [g].nth_le i i.2, rw [fin.sum_univ_succ], simp, end | (g :: h :: L) := calc g - h + L.alternating_sum = g - h + ∑ i : fin L.length, (-1 : ℤ) ^ (i : ℕ) •ℤ L.nth_le i i.2 : congr_arg _ (alternating_sum_eq_finset_sum _) ... = ∑ i : fin (L.length + 2), (-1 : ℤ) ^ (i : ℕ) •ℤ list.nth_le (g :: h :: L) i _ : begin rw [fin.sum_univ_succ, fin.sum_univ_succ, sub_eq_add_neg, add_assoc], unfold_coes, simp [nat.succ_eq_add_one, pow_add], refl, end @[to_additive] lemma alternating_prod_eq_finset_prod {G : Type*} [comm_group G] : ∀ (L : list G), alternating_prod L = ∏ i : fin L.length, (L.nth_le i i.2) ^ ((-1 : ℤ) ^ (i : ℕ)) | [] := by { rw [alternating_prod, finset.prod_eq_one], rintro ⟨i, ⟨⟩⟩ } | (g :: []) := begin show g = ∏ i : fin 1, [g].nth_le i i.2 ^ (-1 : ℤ) ^ (i : ℕ), rw [fin.prod_univ_succ], simp, end | (g :: h :: L) := calc g * h⁻¹ * L.alternating_prod = g * h⁻¹ * ∏ i : fin L.length, L.nth_le i i.2 ^ (-1 : ℤ) ^ (i : ℕ) : congr_arg _ (alternating_prod_eq_finset_prod _) ... = ∏ i : fin (L.length + 2), list.nth_le (g :: h :: L) i _ ^ (-1 : ℤ) ^ (i : ℕ) : begin rw [fin.prod_univ_succ, fin.prod_univ_succ, mul_assoc], unfold_coes, simp [nat.succ_eq_add_one, pow_add], refl, end end list
920ece963928240399467693e1f2ce8a57fa3fca
af6139dd14451ab8f69cf181cf3a20f22bd699be
/library/init/meta/match_tactic.lean
3ae618dce614bedbf418f1f6b340198231fef471
[ "Apache-2.0" ]
permissive
gitter-badger/lean-1
1cca01252d3113faa45681b6a00e1b5e3a0f6203
5c7ade4ee4f1cdf5028eabc5db949479d6737c85
refs/heads/master
1,611,425,383,521
1,487,871,140,000
1,487,871,140,000
82,995,612
0
0
null
1,487,905,618,000
1,487,905,618,000
null
UTF-8
Lean
false
false
4,232
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 structure pattern := /- Term to match. -/ (target : expr) /- Set of universes that is instantiated for each successful match. -/ (uoutput : list level) /- Set of terms that is instantiated for each successful match. -/ (moutput : list expr) /- Number of (temporary) universe meta-variables in this pattern. -/ (nuvars : nat) /- Number of (temporary) meta-variables in this pattern. -/ (nmvars : nat) /- (mk_pattern ls es t u o) creates a new pattern with (length ls) universe meta-variables and (length es) meta-variables. In the produced pattern p, we have that - (pattern.target p) is the term t where the universes ls and expressions es have been replaced with temporary meta-variables. - (pattern.uoutput p) is the list u where the universes ls have been replaced with temporary meta-variables. - (pattern.moutput p) is the list o where the universes ls and expressions es have been replaced with temporary meta-variables. - (pattern.nuvars p) = length ls - (pattern.nmvars p) = length es The tactic fails if o and the types of es do not contain all universes ls and expressions es. -/ meta constant mk_pattern : list level → list expr → expr → list level → list expr → tactic pattern /- (mk_pattern_core m p e) matches (pattern.target p) and e using transparency m. If the matching is successful, then return the instantiation of (pattern.output p). The tactic fails if not all (temporary) meta-variables are assigned. -/ meta constant match_pattern_core : transparency → pattern → expr → tactic (list level × list expr) meta def match_pattern (p : pattern) (e : expr) : tactic (list expr) := fmap prod.snd (match_pattern_core semireducible p e) open expr /- Helper function for converting a term (λ x_1 ... x_n, t) into a pattern where x_1 ... x_n are metavariables -/ private meta def to_pattern_core : expr → tactic (expr × list expr) | (lam n bi d b) := do id ← mk_fresh_name, x ← return $ local_const id n bi d, new_b ← return $ instantiate_var b x, (p, xs) ← to_pattern_core new_b, return (p, x::xs) | e := return (e, []) /- Given a pre-term of the form (λ x_1 ... x_n, t[x_1, ..., x_n]), converts it into the pattern t[?x_1, ..., ?x_n] -/ meta def pexpr_to_pattern (p : pexpr) : tactic pattern := do e ← to_expr p, (new_p, xs) ← to_pattern_core e, mk_pattern [] xs new_p [] xs /- Convert pre-term into a pattern and try to match e. Given p of the form (λ x_1 ... x_n, t[x_1, ..., x_n]), a successful match will produce a list of length n. -/ meta def match_expr (p : pexpr) (e : expr) : tactic (list expr) := do new_p ← pexpr_to_pattern p, match_pattern new_p e private meta def match_subexpr_core : pattern → list expr → tactic (list expr) | p [] := failed | p (e::es) := match_pattern p e <|> match_subexpr_core p es <|> if is_app e then match_subexpr_core p (get_app_args e) else failed /- Similar to match_expr, but it tries to match a subexpression of e. Remark: the procedure does not go inside binders. -/ meta def match_subexpr (p : pexpr) (e : expr) : tactic (list expr) := do new_p ← pexpr_to_pattern p, match_subexpr_core new_p [e] /- Match the main goal target. -/ meta def match_target (p : pexpr) : tactic (list expr) := target >>= match_expr p /- Match a subterm in the main goal target. -/ meta def match_target_subexpr (p : pexpr) : tactic (list expr) := target >>= match_subexpr p private meta def match_hypothesis_core : pattern → list expr → tactic (expr × list expr) | p [] := failed | p (h::hs) := do h_type ← infer_type h, (do r ← match_pattern p h_type, return (h, r)) <|> match_hypothesis_core p hs /- Match hypothesis in the main goal target. The result is pair (hypothesis, substitution). -/ meta def match_hypothesis (p : pexpr) : tactic (expr × list expr) := do ctx ← local_context, new_p ← pexpr_to_pattern p, match_hypothesis_core new_p ctx end tactic
91f62bd10998bc7320f0f1a9cc47179e3640e129
e953c38599905267210b87fb5d82dcc3e52a4214
/library/logic/identities.lean
093b70f3a7087e09cd580e55eec0394e3c914bda
[ "Apache-2.0" ]
permissive
c-cube/lean
563c1020bff98441c4f8ba60111fef6f6b46e31b
0fb52a9a139f720be418dafac35104468e293b66
refs/heads/master
1,610,753,294,113
1,440,451,356,000
1,440,499,588,000
41,748,334
0
0
null
1,441,122,656,000
1,441,122,656,000
null
UTF-8
Lean
false
false
3,990
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura Useful logical identities. Since we are not using propositional extensionality, some of the calculations use the type class support provided by logic.instances. -/ import logic.connectives logic.instances logic.quantifiers logic.cast open relation decidable relation.iff_ops theorem or.right_comm (a b c : Prop) : (a ∨ b) ∨ c ↔ (a ∨ c) ∨ b := calc (a ∨ b) ∨ c ↔ a ∨ (b ∨ c) : or.assoc ... ↔ a ∨ (c ∨ b) : {or.comm} ... ↔ (a ∨ c) ∨ b : iff.symm or.assoc theorem or.left_comm [simp] (a b c : Prop) : a ∨ (b ∨ c) ↔ b ∨ (a ∨ c) := calc a ∨ (b ∨ c) ↔ (a ∨ b) ∨ c : iff.symm or.assoc ... ↔ (b ∨ a) ∨ c : {or.comm} ... ↔ b ∨ (a ∨ c) : or.assoc theorem and.right_comm (a b c : Prop) : (a ∧ b) ∧ c ↔ (a ∧ c) ∧ b := calc (a ∧ b) ∧ c ↔ a ∧ (b ∧ c) : and.assoc ... ↔ a ∧ (c ∧ b) : {and.comm} ... ↔ (a ∧ c) ∧ b : iff.symm and.assoc theorem and.left_comm [simp] (a b c : Prop) : a ∧ (b ∧ c) ↔ b ∧ (a ∧ c) := calc a ∧ (b ∧ c) ↔ (a ∧ b) ∧ c : iff.symm and.assoc ... ↔ (b ∧ a) ∧ c : {and.comm} ... ↔ b ∧ (a ∧ c) : and.assoc theorem not_not_iff {a : Prop} [D : decidable a] : (¬¬a) ↔ a := iff.intro by_contradiction not_not_intro theorem not_not_elim {a : Prop} [D : decidable a] : ¬¬a → a := by_contradiction theorem not_or_iff_not_and_not {a b : Prop} : ¬(a ∨ b) ↔ ¬a ∧ ¬b := or.imp_distrib theorem not_and_iff_not_or_not {a b : Prop} [Da : decidable a] : ¬(a ∧ b) ↔ ¬a ∨ ¬b := iff.intro (λH, by_cases (λa, or.inr (not.mto (and.intro a) H)) or.inl) (or.rec (not.mto and.left) (not.mto and.right)) theorem imp_iff_not_or {a b : Prop} [Da : decidable a] : (a → b) ↔ ¬a ∨ b := iff.intro (by_cases (λHa H, or.inr (H Ha)) (λHa H, or.inl Ha)) (or.rec not.elim imp.intro) theorem not_implies_iff_and_not {a b : Prop} [Da : decidable a] : ¬(a → b) ↔ a ∧ ¬b := calc ¬(a → b) ↔ ¬(¬a ∨ b) : {imp_iff_not_or} ... ↔ ¬¬a ∧ ¬b : not_or_iff_not_and_not ... ↔ a ∧ ¬b : {not_not_iff} theorem peirce {a b : Prop} [D : decidable a] : ((a → b) → a) → a := by_cases imp.intro (imp.syl imp.mp not.elim) theorem forall_not_of_not_exists {A : Type} {p : A → Prop} [D : ∀x, decidable (p x)] (H : ¬∃x, p x) : ∀x, ¬p x := take x, by_cases (assume Hp : p x, absurd (exists.intro x Hp) H) imp.id theorem forall_of_not_exists_not {A : Type} {p : A → Prop} [D : decidable_pred p] : ¬(∃ x, ¬p x) → ∀ x, p x := imp.syl (forall_imp_forall (λa, not_not_elim)) forall_not_of_not_exists theorem exists_not_of_not_forall {A : Type} {p : A → Prop} [D : ∀x, decidable (p x)] [D' : decidable (∃x, ¬p x)] (H : ¬∀x, p x) : ∃x, ¬p x := by_contradiction (λH1, absurd (λx, not_not_elim (forall_not_of_not_exists H1 x)) H) theorem exists_of_not_forall_not {A : Type} {p : A → Prop} [D : ∀x, decidable (p x)] [D' : decidable (∃x, p x)] (H : ¬∀x, ¬ p x) : ∃x, p x := by_contradiction (imp.syl H forall_not_of_not_exists) theorem ne_self_iff_false {A : Type} (a : A) : (a ≠ a) ↔ false := iff.intro false.of_ne false.elim theorem eq_self_iff_true [simp] {A : Type} (a : A) : (a = a) ↔ true := iff_true_intro rfl theorem heq_self_iff_true [simp] {A : Type} (a : A) : (a == a) ↔ true := iff_true_intro (heq.refl a) theorem iff_not_self [simp] (a : Prop) : (a ↔ ¬a) ↔ false := iff_false_intro (λH, have H' : ¬a, from (λHa, (mp H Ha) Ha), H' (iff.mpr H H')) theorem true_iff_false [simp] : (true ↔ false) ↔ false := not_true ▸ (iff_not_self true) theorem false_iff_true [simp] : (false ↔ true) ↔ false := not_false_iff ▸ (iff_not_self false)
49fc3bfc64916a53249a0920d7b086b825ce0212
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/linear_algebra/basis.lean
6cfc7b474c5741266cdb831af80c29ec1835e774
[ "Apache-2.0" ]
permissive
DanielFabian/mathlib
efc3a50b5dde303c59eeb6353ef4c35a345d7112
f520d07eba0c852e96fe26da71d85bf6d40fcc2a
refs/heads/master
1,668,739,922,971
1,595,201,756,000
1,595,201,756,000
279,469,476
0
0
null
1,594,696,604,000
1,594,696,604,000
null
UTF-8
Lean
false
false
54,582
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Alexander Bentkamp -/ import linear_algebra.finsupp import linear_algebra.projection import order.zorn import data.fintype.card /-! # Linear independence and bases This file defines linear independence and bases in a module or vector space. It is inspired by Isabelle/HOL's linear algebra, and hence indirectly by HOL Light. ## Main definitions All definitions are given for families of vectors, i.e. `v : ι → M` where `M` is the module or vector space and `ι : Type*` is an arbitrary indexing type. * `linear_independent R v` states that the elements of the family `v` are linearly independent. * `linear_independent.repr hv x` returns the linear combination representing `x : span R (range v)` on the linearly independent vectors `v`, given `hv : linear_independent R v` (using classical choice). `linear_independent.repr hv` is provided as a linear map. * `is_basis R v` states that the vector family `v` is a basis, i.e. it is linearly independent and spans the entire space. * `is_basis.repr hv x` is the basis version of `linear_independent.repr hv x`. It returns the linear combination representing `x : M` on a basis `v` of `M` (using classical choice). The argument `hv` must be a proof that `is_basis R v`. `is_basis.repr hv` is given as a linear map as well. * `is_basis.constr hv f` constructs a linear map `M₁ →ₗ[R] M₂` given the values `f : ι → M₂` at the basis `v : ι → M₁`, given `hv : is_basis R v`. ## Main statements * `is_basis.ext` states that two linear maps are equal if they coincide on a basis. * `exists_is_basis` states that every vector space has a basis. ## Implementation notes We use families instead of sets because it allows us to say that two identical vectors are linearly dependent. For bases, this is useful as well because we can easily derive ordered bases by using an ordered index type `ι`. If you want to use sets, use the family `(λ x, x : s → M)` given a set `s : set M`. The lemmas `linear_independent.to_subtype_range` and `linear_independent.of_subtype_range` connect those two worlds. ## Tags linearly dependent, linear dependence, linearly independent, linear independence, basis -/ noncomputable theory open function set submodule open_locale classical big_operators universe u variables {ι : Type*} {ι' : Type*} {R : Type*} {K : Type*} {M : Type*} {M' : Type*} {V : Type u} {V' : Type*} section module variables {v : ι → M} variables [ring R] [add_comm_group M] [add_comm_group M'] variables [module R M] [module R M'] variables {a b : R} {x y : M} variables (R) (v) /-- Linearly independent family of vectors -/ def linear_independent : Prop := (finsupp.total ι M R v).ker = ⊥ variables {R} {v} theorem linear_independent_iff : linear_independent R v ↔ ∀l, finsupp.total ι M R v l = 0 → l = 0 := by simp [linear_independent, linear_map.ker_eq_bot'] theorem linear_independent_iff' : linear_independent R v ↔ ∀ s : finset ι, ∀ g : ι → R, ∑ i in s, g i • v i = 0 → ∀ i ∈ s, g i = 0 := linear_independent_iff.trans ⟨λ hf s g hg i his, have h : _ := hf (∑ i in s, finsupp.single i (g i)) $ by simpa only [linear_map.map_sum, finsupp.total_single] using hg, calc g i = (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single i (g i)) : by rw [finsupp.lapply_apply, finsupp.single_eq_same] ... = ∑ j in s, (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single j (g j)) : eq.symm $ finset.sum_eq_single i (λ j hjs hji, by rw [finsupp.lapply_apply, finsupp.single_eq_of_ne hji]) (λ hnis, hnis.elim his) ... = (∑ j in s, finsupp.single j (g j)) i : (finsupp.lapply i : (ι →₀ R) →ₗ[R] R).map_sum.symm ... = 0 : finsupp.ext_iff.1 h i, λ hf l hl, finsupp.ext $ λ i, classical.by_contradiction $ λ hni, hni $ hf _ _ hl _ $ finsupp.mem_support_iff.2 hni⟩ theorem linear_dependent_iff : ¬ linear_independent R v ↔ ∃ s : finset ι, ∃ g : ι → R, s.sum (λ i, g i • v i) = 0 ∧ (∃ i ∈ s, g i ≠ 0) := begin rw linear_independent_iff', simp only [exists_prop, classical.not_forall], end lemma linear_independent_empty_type (h : ¬ nonempty ι) : linear_independent R v := begin rw [linear_independent_iff], intros, ext i, exact false.elim (not_nonempty_iff_imp_false.1 h i) end lemma linear_independent.ne_zero {i : ι} (ne : 0 ≠ (1:R)) (hv : linear_independent R v) : v i ≠ 0 := λ h, ne $ eq.symm begin suffices : (finsupp.single i 1 : ι →₀ R) i = 0, {simpa}, rw linear_independent_iff.1 hv (finsupp.single i 1), {simp}, {simp [h]} end lemma linear_independent.comp (h : linear_independent R v) (f : ι' → ι) (hf : injective f) : linear_independent R (v ∘ f) := begin rw [linear_independent_iff, finsupp.total_comp], intros l hl, have h_map_domain : ∀ x, (finsupp.map_domain f l) (f x) = 0, by rw linear_independent_iff.1 h (finsupp.map_domain f l) hl; simp, ext, convert h_map_domain a, simp only [finsupp.map_domain_apply hf], end lemma linear_independent_of_zero_eq_one (zero_eq_one : (0 : R) = 1) : linear_independent R v := linear_independent_iff.2 (λ l hl, finsupp.eq_zero_of_zero_eq_one zero_eq_one _) lemma linear_independent.unique (hv : linear_independent R v) {l₁ l₂ : ι →₀ R} : finsupp.total ι M R v l₁ = finsupp.total ι M R v l₂ → l₁ = l₂ := by apply linear_map.ker_eq_bot.1 hv lemma linear_independent.injective (zero_ne_one : (0 : R) ≠ 1) (hv : linear_independent R v) : injective v := begin intros i j hij, let l : ι →₀ R := finsupp.single i (1 : R) - finsupp.single j 1, have h_total : finsupp.total ι M R v l = 0, { rw finsupp.total_apply, rw finsupp.sum_sub_index, { simp [finsupp.sum_single_index, hij] }, { intros, apply sub_smul } }, have h_single_eq : finsupp.single i (1 : R) = finsupp.single j 1, { rw linear_independent_iff at hv, simp [eq_add_of_sub_eq' (hv l h_total)] }, show i = j, { apply or.elim ((finsupp.single_eq_single_iff _ _ _ _).1 h_single_eq), simp, exact λ h, false.elim (zero_ne_one.symm h.1) } end lemma linear_independent_span (hs : linear_independent R v) : @linear_independent ι R (span R (range v)) (λ i : ι, ⟨v i, subset_span (mem_range_self i)⟩) _ _ _ := begin rw linear_independent_iff at *, intros l hl, apply hs l, have := congr_arg (submodule.subtype (span R (range v))) hl, convert this, rw [finsupp.total_apply, finsupp.total_apply], unfold finsupp.sum, rw linear_map.map_sum (submodule.subtype (span R (range v))), simp end section subtype /-! The following lemmas use the subtype defined by a set in `M` as the index set `ι`. -/ theorem linear_independent_comp_subtype {s : set ι} : linear_independent R (v ∘ coe : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total ι M R v) l = 0 → l = 0 := begin rw [linear_independent_iff, finsupp.total_comp], simp only [linear_map.comp_apply], split, { intros h l hl₁ hl₂, have h_bij : bij_on coe (coe ⁻¹' ↑l.support : set s) ↑l.support, { apply bij_on.mk, { apply maps_to_preimage }, { apply subtype.coe_injective.inj_on }, intros i hi, rw [image_preimage_eq_inter_range, subtype.range_coe], exact ⟨hi, (finsupp.mem_supported _ _).1 hl₁ hi⟩ }, show l = 0, { apply finsupp.eq_zero_of_comap_domain_eq_zero (coe : s → ι) _ h_bij, apply h, convert hl₂, rw [finsupp.lmap_domain_apply, finsupp.map_domain_comap_domain], exact subtype.coe_injective, rw subtype.range_coe, exact (finsupp.mem_supported _ _).1 hl₁ } }, { intros h l hl, have hl' : finsupp.total ι M R v (finsupp.emb_domain ⟨coe, subtype.coe_injective⟩ l) = 0, { rw finsupp.emb_domain_eq_map_domain ⟨coe, subtype.coe_injective⟩ l, apply hl }, apply finsupp.emb_domain_inj.1, rw [h (finsupp.emb_domain ⟨coe, subtype.coe_injective⟩ l) _ hl', finsupp.emb_domain_zero], rw [finsupp.mem_supported, finsupp.support_emb_domain], intros x hx, rw [finset.mem_coe, finset.mem_map] at hx, rcases hx with ⟨i, x', hx'⟩, rw ←hx', simp } end theorem linear_independent_subtype {s : set M} : linear_independent R (λ x, x : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total M M R id) l = 0 → l = 0 := by apply @linear_independent_comp_subtype _ _ _ id theorem linear_independent_comp_subtype_disjoint {s : set ι} : linear_independent R (v ∘ coe : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total ι M R v).ker := by rw [linear_independent_comp_subtype, linear_map.disjoint_ker] theorem linear_independent_subtype_disjoint {s : set M} : linear_independent R (λ x, x : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total M M R id).ker := by apply @linear_independent_comp_subtype_disjoint _ _ _ id theorem linear_independent_iff_total_on {s : set M} : linear_independent R (λ x, x : s → M) ↔ (finsupp.total_on M M R id s).ker = ⊥ := by rw [finsupp.total_on, linear_map.ker, linear_map.comap_cod_restrict, map_bot, comap_bot, linear_map.ker_comp, linear_independent_subtype_disjoint, disjoint, ← map_comap_subtype, map_le_iff_le_comap, comap_bot, ker_subtype, le_bot_iff] lemma linear_independent.to_subtype_range (hv : linear_independent R v) : linear_independent R (λ x, x : range v → M) := begin by_cases zero_eq_one : (0 : R) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, rw linear_independent_subtype, intros l hl₁ hl₂, have h_bij : bij_on v (v ⁻¹' ↑l.support) ↑l.support, { apply bij_on.mk, { apply maps_to_preimage }, { apply (linear_independent.injective zero_eq_one hv).inj_on }, intros x hx, rcases mem_range.1 (((finsupp.mem_supported _ _).1 hl₁ : ↑(l.support) ⊆ range v) hx) with ⟨i, hi⟩, rw mem_image, use i, rw [mem_preimage, hi], exact ⟨hx, rfl⟩ }, apply finsupp.eq_zero_of_comap_domain_eq_zero v l h_bij, apply linear_independent_iff.1 hv, rw [finsupp.total_comap_domain, finset.sum_preimage_of_bij v l.support h_bij (λ (x : M), l x • x)], rwa [finsupp.total_apply, finsupp.sum] at hl₂ end lemma linear_independent.of_subtype_range (hv : injective v) (h : linear_independent R (λ x, x : range v → M)) : linear_independent R v := begin rw linear_independent_iff, intros l hl, apply finsupp.map_domain_injective hv, apply linear_independent_subtype.1 h (l.map_domain v), { rw finsupp.mem_supported, intros x hx, have := finset.mem_coe.2 (finsupp.map_domain_support hx), rw finset.coe_image at this, apply set.image_subset_range _ _ this, }, { rwa [finsupp.total_map_domain _ _ hv, left_id] } end lemma linear_independent.restrict_of_comp_subtype {s : set ι} (hs : linear_independent R (v ∘ coe : s → M)) : linear_independent R (s.restrict v) := begin have h_restrict : restrict v s = v ∘ coe := rfl, rw [linear_independent_iff, h_restrict, finsupp.total_comp], intros l hl, have h_map_domain_subtype_eq_0 : l.map_domain coe = 0, { rw linear_independent_comp_subtype at hs, apply hs (finsupp.lmap_domain R R coe l) _ hl, rw finsupp.mem_supported, simp, intros x hx, have := finset.mem_coe.2 (finsupp.map_domain_support (finset.mem_coe.1 hx)), rw finset.coe_image at this, exact subtype.coe_image_subset _ _ this }, apply @finsupp.map_domain_injective _ (subtype s) ι, { apply subtype.coe_injective }, { simpa }, end variables (R M) lemma linear_independent_empty : linear_independent R (λ x, x : (∅ : set M) → M) := by simp [linear_independent_subtype_disjoint] variables {R M} lemma linear_independent.mono {t s : set M} (h : t ⊆ s) : linear_independent R (λ x, x : s → M) → linear_independent R (λ x, x : t → M) := begin simp only [linear_independent_subtype_disjoint], exact (disjoint.mono_left (finsupp.supported_mono h)) end lemma linear_independent.union {s t : set M} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M)) (hst : disjoint (span R s) (span R t)) : linear_independent R (λ x, x : (s ∪ t) → M) := begin rw [linear_independent_subtype_disjoint, disjoint_def, finsupp.supported_union], intros l h₁ h₂, rw mem_sup at h₁, rcases h₁ with ⟨ls, hls, lt, hlt, rfl⟩, have h_ls_mem_t : finsupp.total M M R id ls ∈ span R t, { rw [← image_id t, finsupp.span_eq_map_total], apply (add_mem_iff_left (map _ _) (mem_image_of_mem _ hlt)).1, rw [← linear_map.map_add, linear_map.mem_ker.1 h₂], apply zero_mem }, have h_lt_mem_s : finsupp.total M M R id lt ∈ span R s, { rw [← image_id s, finsupp.span_eq_map_total], apply (add_mem_iff_left (map _ _) (mem_image_of_mem _ hls)).1, rw [← linear_map.map_add, add_comm, linear_map.mem_ker.1 h₂], apply zero_mem }, have h_ls_mem_s : (finsupp.total M M R id) ls ∈ span R s, { rw ← image_id s, apply (finsupp.mem_span_iff_total _).2 ⟨ls, hls, rfl⟩ }, have h_lt_mem_t : (finsupp.total M M R id) lt ∈ span R t, { rw ← image_id t, apply (finsupp.mem_span_iff_total _).2 ⟨lt, hlt, rfl⟩ }, have h_ls_0 : ls = 0 := disjoint_def.1 (linear_independent_subtype_disjoint.1 hs) _ hls (linear_map.mem_ker.2 $ disjoint_def.1 hst (finsupp.total M M R id ls) h_ls_mem_s h_ls_mem_t), have h_lt_0 : lt = 0 := disjoint_def.1 (linear_independent_subtype_disjoint.1 ht) _ hlt (linear_map.mem_ker.2 $ disjoint_def.1 hst (finsupp.total M M R id lt) h_lt_mem_s h_lt_mem_t), show ls + lt = 0, by simp [h_ls_0, h_lt_0], end lemma linear_independent_of_finite (s : set M) (H : ∀ t ⊆ s, finite t → linear_independent R (λ x, x : t → M)) : linear_independent R (λ x, x : s → M) := linear_independent_subtype.2 $ λ l hl, linear_independent_subtype.1 (H _ hl (finset.finite_to_set _)) l (subset.refl _) lemma linear_independent_Union_of_directed {η : Type*} {s : η → set M} (hs : directed (⊆) s) (h : ∀ i, linear_independent R (λ x, x : s i → M)) : linear_independent R (λ x, x : (⋃ i, s i) → M) := begin by_cases hη : nonempty η, { refine linear_independent_of_finite (⋃ i, s i) (λ t ht ft, _), rcases finite_subset_Union ft ht with ⟨I, fi, hI⟩, rcases hs.finset_le hη fi.to_finset with ⟨i, hi⟩, exact (h i).mono (subset.trans hI $ bUnion_subset $ λ j hj, hi j (finite.mem_to_finset.2 hj)) }, { refine (linear_independent_empty _ _).mono _, rintro _ ⟨_, ⟨i, _⟩, _⟩, exact hη ⟨i⟩ } end lemma linear_independent_sUnion_of_directed {s : set (set M)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, linear_independent R (λ x, x : (a : set M) → M)) : linear_independent R (λ x, x : (⋃₀ s) → M) := by rw sUnion_eq_Union; exact linear_independent_Union_of_directed ((directed_on_iff_directed _).1 hs) (by simpa using h) lemma linear_independent_bUnion_of_directed {η} {s : set η} {t : η → set M} (hs : directed_on (t ⁻¹'o (⊆)) s) (h : ∀a∈s, linear_independent R (λ x, x : t a → M)) : linear_independent R (λ x, x : (⋃a∈s, t a) → M) := by rw bUnion_eq_Union; exact linear_independent_Union_of_directed ((directed_comp _ _ _).2 $ (directed_on_iff_directed _).1 hs) (by simpa using h) lemma linear_independent_Union_finite_subtype {ι : Type*} {f : ι → set M} (hl : ∀i, linear_independent R (λ x, x : f i → M)) (hd : ∀i, ∀t:set ι, finite t → i ∉ t → disjoint (span R (f i)) (⨆i∈t, span R (f i))) : linear_independent R (λ x, x : (⋃i, f i) → M) := begin rw [Union_eq_Union_finset f], apply linear_independent_Union_of_directed, apply directed_of_sup, exact (assume t₁ t₂ ht, Union_subset_Union $ assume i, Union_subset_Union_const $ assume h, ht h), assume t, rw [set.Union, ← finset.sup_eq_supr], refine t.induction_on _ _, { rw finset.sup_empty, apply linear_independent_empty_type (not_nonempty_iff_imp_false.2 _), exact λ x, set.not_mem_empty x (subtype.mem x) }, { rintros ⟨i⟩ s his ih, rw [finset.sup_insert], refine (hl _).union ih _, rw [finset.sup_eq_supr], refine (hd i _ _ his).mono_right _, { simp only [(span_Union _).symm], refine span_mono (@supr_le_supr2 (set M) _ _ _ _ _ _), rintros ⟨i⟩, exact ⟨i, le_refl _⟩ }, { change finite (plift.up ⁻¹' ↑s), exact s.finite_to_set.preimage (assume i j _ _, plift.up.inj) } } end lemma linear_independent_Union_finite {η : Type*} {ιs : η → Type*} {f : Π j : η, ιs j → M} (hindep : ∀j, linear_independent R (f j)) (hd : ∀i, ∀t:set η, finite t → i ∉ t → disjoint (span R (range (f i))) (⨆i∈t, span R (range (f i)))) : linear_independent R (λ ji : Σ j, ιs j, f ji.1 ji.2) := begin by_cases zero_eq_one : (0 : R) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, apply linear_independent.of_subtype_range, { rintros ⟨x₁, x₂⟩ ⟨y₁, y₂⟩ hxy, by_cases h_cases : x₁ = y₁, subst h_cases, { apply sigma.eq, rw linear_independent.injective zero_eq_one (hindep _) hxy, refl }, { have h0 : f x₁ x₂ = 0, { apply disjoint_def.1 (hd x₁ {y₁} (finite_singleton y₁) (λ h, h_cases (eq_of_mem_singleton h))) (f x₁ x₂) (subset_span (mem_range_self _)), rw supr_singleton, simp only at hxy, rw hxy, exact (subset_span (mem_range_self y₂)) }, exact false.elim ((hindep x₁).ne_zero zero_eq_one h0) } }, rw range_sigma_eq_Union_range, apply linear_independent_Union_finite_subtype (λ j, (hindep j).to_subtype_range) hd, end end subtype section repr variables (hv : linear_independent R v) /-- Canonical isomorphism between linear combinations and the span of linearly independent vectors. -/ def linear_independent.total_equiv (hv : linear_independent R v) : (ι →₀ R) ≃ₗ[R] span R (range v) := begin apply linear_equiv.of_bijective (linear_map.cod_restrict (span R (range v)) (finsupp.total ι M R v) _), { rw linear_map.ker_cod_restrict, apply hv }, { rw [linear_map.range, linear_map.map_cod_restrict, ← linear_map.range_le_iff_comap, range_subtype, map_top], rw finsupp.range_total, apply le_refl (span R (range v)) }, { intro l, rw ← finsupp.range_total, rw linear_map.mem_range, apply mem_range_self l } end /-- Linear combination representing a vector in the span of linearly independent vectors. Given a family of linearly independent vectors, we can represent any vector in their span as a linear combination of these vectors. These are provided by this linear map. It is simply one direction of `linear_independent.total_equiv`. -/ def linear_independent.repr (hv : linear_independent R v) : span R (range v) →ₗ[R] ι →₀ R := hv.total_equiv.symm lemma linear_independent.total_repr (x) : finsupp.total ι M R v (hv.repr x) = x := subtype.ext_iff.1 (linear_equiv.apply_symm_apply hv.total_equiv x) lemma linear_independent.total_comp_repr : (finsupp.total ι M R v).comp hv.repr = submodule.subtype _ := linear_map.ext $ hv.total_repr lemma linear_independent.repr_ker : hv.repr.ker = ⊥ := by rw [linear_independent.repr, linear_equiv.ker] lemma linear_independent.repr_range : hv.repr.range = ⊤ := by rw [linear_independent.repr, linear_equiv.range] lemma linear_independent.repr_eq {l : ι →₀ R} {x} (eq : finsupp.total ι M R v l = ↑x) : hv.repr x = l := begin have : ↑((linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l) = finsupp.total ι M R v l := rfl, have : (linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l = x, { rw eq at this, exact subtype.ext_iff.2 this }, rw ←linear_equiv.symm_apply_apply hv.total_equiv l, rw ←this, refl, end lemma linear_independent.repr_eq_single (i) (x) (hx : ↑x = v i) : hv.repr x = finsupp.single i 1 := begin apply hv.repr_eq, simp [finsupp.total_single, hx] end -- TODO: why is this so slow? lemma linear_independent_iff_not_smul_mem_span : linear_independent R v ↔ (∀ (i : ι) (a : R), a • (v i) ∈ span R (v '' (univ \ {i})) → a = 0) := ⟨ λ hv i a ha, begin rw [finsupp.span_eq_map_total, mem_map] at ha, rcases ha with ⟨l, hl, e⟩, rw sub_eq_zero.1 (linear_independent_iff.1 hv (l - finsupp.single i a) (by simp [e])) at hl, by_contra hn, exact (not_mem_of_mem_diff (hl $ by simp [hn])) (mem_singleton _), end, λ H, linear_independent_iff.2 $ λ l hl, begin ext i, simp only [finsupp.zero_apply], by_contra hn, refine hn (H i _ _), refine (finsupp.mem_span_iff_total _).2 ⟨finsupp.single i (l i) - l, _, _⟩, { rw finsupp.mem_supported', intros j hj, have hij : j = i := classical.not_not.1 (λ hij : j ≠ i, hj ((mem_diff _).2 ⟨mem_univ _, λ h, hij (eq_of_mem_singleton h)⟩)), simp [hij] }, { simp [hl] } end⟩ end repr lemma surjective_of_linear_independent_of_span (hv : linear_independent R v) (f : ι' ↪ ι) (hss : range v ⊆ span R (range (v ∘ f))) (zero_ne_one : 0 ≠ (1 : R)): surjective f := begin intros i, let repr : (span R (range (v ∘ f)) : Type*) → ι' →₀ R := (hv.comp f f.injective).repr, let l := (repr ⟨v i, hss (mem_range_self i)⟩).map_domain f, have h_total_l : finsupp.total ι M R v l = v i, { dsimp only [l], rw finsupp.total_map_domain, rw (hv.comp f f.injective).total_repr, { refl }, { exact f.injective } }, have h_total_eq : (finsupp.total ι M R v) l = (finsupp.total ι M R v) (finsupp.single i 1), by rw [h_total_l, finsupp.total_single, one_smul], have l_eq : l = _ := linear_map.ker_eq_bot.1 hv h_total_eq, dsimp only [l] at l_eq, rw ←finsupp.emb_domain_eq_map_domain at l_eq, rcases finsupp.single_of_emb_domain_single (repr ⟨v i, _⟩) f i (1 : R) zero_ne_one.symm l_eq with ⟨i', hi'⟩, use i', exact hi'.2 end lemma eq_of_linear_independent_of_span_subtype {s t : set M} (zero_ne_one : (0 : R) ≠ 1) (hs : linear_independent R (λ x, x : s → M)) (h : t ⊆ s) (hst : s ⊆ span R t) : s = t := begin let f : t ↪ s := ⟨λ x, ⟨x.1, h x.2⟩, λ a b hab, subtype.coe_injective (subtype.mk.inj hab)⟩, have h_surj : surjective f, { apply surjective_of_linear_independent_of_span hs f _ zero_ne_one, convert hst; simp [f, comp], }, show s = t, { apply subset.antisymm _ h, intros x hx, rcases h_surj ⟨x, hx⟩ with ⟨y, hy⟩, convert y.mem, rw ← subtype.mk.inj hy, refl } end open linear_map lemma linear_independent.image (hv : linear_independent R v) {f : M →ₗ M'} (hf_inj : disjoint (span R (range v)) f.ker) : linear_independent R (f ∘ v) := begin rw [disjoint, ← set.image_univ, finsupp.span_eq_map_total, map_inf_eq_map_inf_comap, map_le_iff_le_comap, comap_bot, finsupp.supported_univ, top_inf_eq] at hf_inj, unfold linear_independent at hv, rw hv at hf_inj, haveI : inhabited M := ⟨0⟩, rw [linear_independent, finsupp.total_comp], rw [@finsupp.lmap_domain_total _ _ R _ _ _ _ _ _ _ _ _ _ f, ker_comp, eq_bot_iff], apply hf_inj, exact λ _, rfl, end lemma linear_independent.image_subtype {s : set M} {f : M →ₗ M'} (hs : linear_independent R (λ x, x : s → M)) (hf_inj : disjoint (span R s) f.ker) : linear_independent R (λ x, x : f '' s → M') := begin rw [disjoint, ← set.image_id s, finsupp.span_eq_map_total, map_inf_eq_map_inf_comap, map_le_iff_le_comap, comap_bot] at hf_inj, haveI : inhabited M := ⟨0⟩, rw [linear_independent_subtype_disjoint, disjoint, ← finsupp.lmap_domain_supported _ _ f, map_inf_eq_map_inf_comap, map_le_iff_le_comap, ← ker_comp], rw [@finsupp.lmap_domain_total _ _ R _ _ _, ker_comp], { exact le_trans (le_inf inf_le_left hf_inj) (le_trans (linear_independent_subtype_disjoint.1 hs) bot_le) }, { simp } end lemma linear_independent.inl_union_inr {s : set M} {t : set M'} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M')) : linear_independent R (λ x, x : inl R M M' '' s ∪ inr R M M' '' t → M × M') := begin refine (hs.image_subtype _).union (ht.image_subtype _) _; [simp, simp, skip], simp only [span_image], simp [disjoint_iff, prod_inf_prod] end lemma linear_independent_inl_union_inr' {v : ι → M} {v' : ι' → M'} (hv : linear_independent R v) (hv' : linear_independent R v') : linear_independent R (sum.elim (inl R M M' ∘ v) (inr R M M' ∘ v')) := begin by_cases zero_eq_one : (0 : R) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, have inj_v : injective v := (linear_independent.injective zero_eq_one hv), have inj_v' : injective v' := (linear_independent.injective zero_eq_one hv'), apply linear_independent.of_subtype_range, { apply sum.elim_injective, { exact prod.inl_injective.comp inj_v }, { exact prod.inr_injective.comp inj_v' }, { intros, simp [hv.ne_zero zero_eq_one] } }, { rw sum.elim_range, refine (hv.image _).to_subtype_range.union (hv'.image _).to_subtype_range _; [simp, simp, skip], apply disjoint_inl_inr.mono _ _; simp only [set.range_comp, span_image, linear_map.map_le_range] } end /-- Dedekind's linear independence of characters -/ -- See, for example, Keith Conrad's note <https://kconrad.math.uconn.edu/blurbs/galoistheory/linearchar.pdf> theorem linear_independent_monoid_hom (G : Type*) [monoid G] (L : Type*) [integral_domain L] : @linear_independent _ L (G → L) (λ f, f : (G →* L) → (G → L)) _ _ _ := by letI := classical.dec_eq (G →* L); letI : mul_action L L := distrib_mul_action.to_mul_action; -- We prove linear independence by showing that only the trivial linear combination vanishes. exact linear_independent_iff'.2 -- To do this, we use `finset` induction, (λ s, finset.induction_on s (λ g hg i, false.elim) $ λ a s has ih g hg, -- Here -- * `a` is a new character we will insert into the `finset` of characters `s`, -- * `ih` is the fact that only the trivial linear combination of characters in `s` is zero -- * `hg` is the fact that `g` are the coefficients of a linear combination summing to zero -- and it remains to prove that `g` vanishes on `insert a s`. -- We now make the key calculation: -- For any character `i` in the original `finset`, we have `g i • i = g i • a` as functions on the monoid `G`. have h1 : ∀ i ∈ s, (g i • i : G → L) = g i • a, from λ i his, funext $ λ x : G, -- We prove these expressions are equal by showing -- the differences of their values on each monoid element `x` is zero eq_of_sub_eq_zero $ ih (λ j, g j * j x - g j * a x) (funext $ λ y : G, calc -- After that, it's just a chase scene. (∑ i in s, ((g i * i x - g i * a x) • i : G → L)) y = ∑ i in s, (g i * i x - g i * a x) * i y : pi.finset_sum_apply _ _ _ ... = ∑ i in s, (g i * i x * i y - g i * a x * i y) : finset.sum_congr rfl (λ _ _, sub_mul _ _ _) ... = ∑ i in s, g i * i x * i y - ∑ i in s, g i * a x * i y : finset.sum_sub_distrib ... = (g a * a x * a y + ∑ i in s, g i * i x * i y) - (g a * a x * a y + ∑ i in s, g i * a x * i y) : by rw add_sub_add_left_eq_sub ... = ∑ i in insert a s, g i * i x * i y - ∑ i in insert a s, g i * a x * i y : by rw [finset.sum_insert has, finset.sum_insert has] ... = ∑ i in insert a s, g i * i (x * y) - ∑ i in insert a s, a x * (g i * i y) : congr (congr_arg has_sub.sub (finset.sum_congr rfl $ λ i _, by rw [i.map_mul, mul_assoc])) (finset.sum_congr rfl $ λ _ _, by rw [mul_assoc, mul_left_comm]) ... = (∑ i in insert a s, (g i • i : G → L)) (x * y) - a x * (∑ i in insert a s, (g i • i : G → L)) y : by rw [pi.finset_sum_apply, pi.finset_sum_apply, finset.mul_sum]; refl ... = 0 - a x * 0 : by rw hg; refl ... = 0 : by rw [mul_zero, sub_zero]) i his, -- On the other hand, since `a` is not already in `s`, for any character `i ∈ s` -- there is some element of the monoid on which it differs from `a`. have h2 : ∀ i : G →* L, i ∈ s → ∃ y, i y ≠ a y, from λ i his, classical.by_contradiction $ λ h, have hia : i = a, from monoid_hom.ext $ λ y, classical.by_contradiction $ λ hy, h ⟨y, hy⟩, has $ hia ▸ his, -- From these two facts we deduce that `g` actually vanishes on `s`, have h3 : ∀ i ∈ s, g i = 0, from λ i his, let ⟨y, hy⟩ := h2 i his in have h : g i • i y = g i • a y, from congr_fun (h1 i his) y, or.resolve_right (mul_eq_zero.1 $ by rw [mul_sub, sub_eq_zero]; exact h) (sub_ne_zero_of_ne hy), -- And so, using the fact that the linear combination over `s` and over `insert a s` both vanish, -- we deduce that `g a = 0`. have h4 : g a = 0, from calc g a = g a * 1 : (mul_one _).symm ... = (g a • a : G → L) 1 : by rw ← a.map_one; refl ... = (∑ i in insert a s, (g i • i : G → L)) 1 : begin rw finset.sum_eq_single a, { intros i his hia, rw finset.mem_insert at his, rw [h3 i (his.resolve_left hia), zero_smul] }, { intros haas, exfalso, apply haas, exact finset.mem_insert_self a s } end ... = 0 : by rw hg; refl, -- Now we're done; the last two facts together imply that `g` vanishes on every element of `insert a s`. (finset.forall_mem_insert _ _ _).2 ⟨h4, h3⟩) lemma le_of_span_le_span {s t u: set M} (zero_ne_one : (0 : R) ≠ 1) (hl : linear_independent R (coe : u → M )) (hsu : s ⊆ u) (htu : t ⊆ u) (hst : span R s ≤ span R t) : s ⊆ t := begin have := eq_of_linear_independent_of_span_subtype zero_ne_one (hl.mono (set.union_subset hsu htu)) (set.subset_union_right _ _) (set.union_subset (set.subset.trans subset_span hst) subset_span), rw ← this, apply set.subset_union_left end lemma span_le_span_iff {s t u: set M} (zero_ne_one : (0 : R) ≠ 1) (hl : linear_independent R (coe : u → M)) (hsu : s ⊆ u) (htu : t ⊆ u) : span R s ≤ span R t ↔ s ⊆ t := ⟨le_of_span_le_span zero_ne_one hl hsu htu, span_mono⟩ variables (R) (v) /-- A family of vectors is a basis if it is linearly independent and all vectors are in the span. -/ def is_basis := linear_independent R v ∧ span R (range v) = ⊤ variables {R} {v} section is_basis variables {s t : set M} (hv : is_basis R v) lemma is_basis.mem_span (hv : is_basis R v) : ∀ x, x ∈ span R (range v) := eq_top_iff'.1 hv.2 lemma is_basis.comp (hv : is_basis R v) (f : ι' → ι) (hf : bijective f) : is_basis R (v ∘ f) := begin split, { apply hv.1.comp f hf.1 }, { rw[set.range_comp, range_iff_surjective.2 hf.2, image_univ, hv.2] } end lemma is_basis.injective (hv : is_basis R v) (zero_ne_one : (0 : R) ≠ 1) : injective v := λ x y h, linear_independent.injective zero_ne_one hv.1 h lemma is_basis.range (hv : is_basis R v) : is_basis R (λ x, x : range v → M) := ⟨hv.1.to_subtype_range, by { convert hv.2, ext i, exact ⟨λ ⟨p, hp⟩, hp ▸ p.2, λ hi, ⟨⟨i, hi⟩, rfl⟩⟩ }⟩ /-- Given a basis, any vector can be written as a linear combination of the basis vectors. They are given by this linear map. This is one direction of `module_equiv_finsupp`. -/ def is_basis.repr : M →ₗ (ι →₀ R) := (hv.1.repr).comp (linear_map.id.cod_restrict _ hv.mem_span) lemma is_basis.total_repr (x) : finsupp.total ι M R v (hv.repr x) = x := hv.1.total_repr ⟨x, _⟩ lemma is_basis.total_comp_repr : (finsupp.total ι M R v).comp hv.repr = linear_map.id := linear_map.ext hv.total_repr lemma is_basis.repr_ker : hv.repr.ker = ⊥ := linear_map.ker_eq_bot.2 $ left_inverse.injective hv.total_repr lemma is_basis.repr_range : hv.repr.range = finsupp.supported R R univ := by rw [is_basis.repr, linear_map.range, submodule.map_comp, linear_map.map_cod_restrict, submodule.map_id, comap_top, map_top, hv.1.repr_range, finsupp.supported_univ] lemma is_basis.repr_total (x : ι →₀ R) (hx : x ∈ finsupp.supported R R (univ : set ι)) : hv.repr (finsupp.total ι M R v x) = x := begin rw [← hv.repr_range, linear_map.mem_range] at hx, cases hx with w hw, rw [← hw, hv.total_repr], end lemma is_basis.repr_eq_single {i} : hv.repr (v i) = finsupp.single i 1 := by apply hv.1.repr_eq_single; simp /-- Construct a linear map given the value at the basis. -/ def is_basis.constr (f : ι → M') : M →ₗ[R] M' := (finsupp.total M' M' R id).comp $ (finsupp.lmap_domain R R f).comp hv.repr theorem is_basis.constr_apply (f : ι → M') (x : M) : (hv.constr f : M → M') x = (hv.repr x).sum (λb a, a • f b) := by dsimp [is_basis.constr]; rw [finsupp.total_apply, finsupp.sum_map_domain_index]; simp [add_smul] lemma is_basis.ext {f g : M →ₗ[R] M'} (hv : is_basis R v) (h : ∀i, f (v i) = g (v i)) : f = g := begin apply linear_map.ext (λ x, linear_eq_on (range v) _ (hv.mem_span x)), exact (λ y hy, exists.elim (set.mem_range.1 hy) (λ i hi, by rw ←hi; exact h i)) end @[simp] lemma constr_basis {f : ι → M'} {i : ι} (hv : is_basis R v) : (hv.constr f : M → M') (v i) = f i := by simp [is_basis.constr_apply, hv.repr_eq_single, finsupp.sum_single_index] lemma constr_eq {g : ι → M'} {f : M →ₗ[R] M'} (hv : is_basis R v) (h : ∀i, g i = f (v i)) : hv.constr g = f := hv.ext $ λ i, (constr_basis hv).trans (h i) lemma constr_self (f : M →ₗ[R] M') : hv.constr (λ i, f (v i)) = f := constr_eq hv $ λ x, rfl lemma constr_zero (hv : is_basis R v) : hv.constr (λi, (0 : M')) = 0 := constr_eq hv $ λ x, rfl lemma constr_add {g f : ι → M'} (hv : is_basis R v) : hv.constr (λi, f i + g i) = hv.constr f + hv.constr g := constr_eq hv $ λ b, by simp lemma constr_neg {f : ι → M'} (hv : is_basis R v) : hv.constr (λi, - f i) = - hv.constr f := constr_eq hv $ λ b, by simp lemma constr_sub {g f : ι → M'} (hs : is_basis R v) : hv.constr (λi, f i - g i) = hs.constr f - hs.constr g := by simp [sub_eq_add_neg, constr_add, constr_neg] -- this only works on functions if `R` is a commutative ring lemma constr_smul {ι R M} [comm_ring R] [add_comm_group M] [module R M] {v : ι → R} {f : ι → M} {a : R} (hv : is_basis R v) : hv.constr (λb, a • f b) = a • hv.constr f := constr_eq hv $ by simp [constr_basis hv] {contextual := tt} lemma constr_range [nonempty ι] (hv : is_basis R v) {f : ι → M'} : (hv.constr f).range = span R (range f) := by rw [is_basis.constr, linear_map.range_comp, linear_map.range_comp, is_basis.repr_range, finsupp.lmap_domain_supported, ←set.image_univ, ←finsupp.span_eq_map_total, image_id] /-- Canonical equivalence between a module and the linear combinations of basis vectors. -/ def module_equiv_finsupp (hv : is_basis R v) : M ≃ₗ[R] ι →₀ R := (hv.1.total_equiv.trans (linear_equiv.of_top _ hv.2)).symm @[simp] theorem module_equiv_finsupp_apply_basis (hv : is_basis R v) (i : ι) : module_equiv_finsupp hv (v i) = finsupp.single i 1 := (linear_equiv.symm_apply_eq _).2 $ by simp [linear_independent.total_equiv] /-- Isomorphism between the two modules, given two modules `M` and `M'` with respective bases `v` and `v'` and a bijection between the indexing sets of the two bases. -/ def equiv_of_is_basis {v : ι → M} {v' : ι' → M'} (hv : is_basis R v) (hv' : is_basis R v') (e : ι ≃ ι') : M ≃ₗ[R] M' := { inv_fun := hv'.constr (v ∘ e.symm), left_inv := have (hv'.constr (v ∘ e.symm)).comp (hv.constr (v' ∘ e)) = linear_map.id, from hv.ext $ by simp, λ x, congr_arg (λ h : M →ₗ[R] M, h x) this, right_inv := have (hv.constr (v' ∘ e)).comp (hv'.constr (v ∘ e.symm)) = linear_map.id, from hv'.ext $ by simp, λ y, congr_arg (λ h : M' →ₗ[R] M', h y) this, ..hv.constr (v' ∘ e) } /-- Isomorphism between the two modules, given two modules `M` and `M'` with respective bases `v` and `v'` and a bijection between the two bases. -/ def equiv_of_is_basis' {v : ι → M} {v' : ι' → M'} (f : M → M') (g : M' → M) (hv : is_basis R v) (hv' : is_basis R v') (hf : ∀i, f (v i) ∈ range v') (hg : ∀i, g (v' i) ∈ range v) (hgf : ∀i, g (f (v i)) = v i) (hfg : ∀i, f (g (v' i)) = v' i) : M ≃ₗ M' := { inv_fun := hv'.constr (g ∘ v'), left_inv := have (hv'.constr (g ∘ v')).comp (hv.constr (f ∘ v)) = linear_map.id, from hv.ext $ λ i, exists.elim (hf i) (λ i' hi', by simp [constr_basis, hi'.symm]; rw [hi', hgf]), λ x, congr_arg (λ h:M →ₗ[R] M, h x) this, right_inv := have (hv.constr (f ∘ v)).comp (hv'.constr (g ∘ v')) = linear_map.id, from hv'.ext $ λ i', exists.elim (hg i') (λ i hi, by simp [constr_basis, hi.symm]; rw [hi, hfg]), λ y, congr_arg (λ h:M' →ₗ[R] M', h y) this, ..hv.constr (f ∘ v) } lemma is_basis_inl_union_inr {v : ι → M} {v' : ι' → M'} (hv : is_basis R v) (hv' : is_basis R v') : is_basis R (sum.elim (inl R M M' ∘ v) (inr R M M' ∘ v')) := begin split, apply linear_independent_inl_union_inr' hv.1 hv'.1, rw [sum.elim_range, span_union, set.range_comp, span_image (inl R M M'), hv.2, map_top, set.range_comp, span_image (inr R M M'), hv'.2, map_top], exact linear_map.sup_range_inl_inr end end is_basis lemma is_basis_singleton_one (R : Type*) [unique ι] [ring R] : is_basis R (λ (_ : ι), (1 : R)) := begin split, { refine linear_independent_iff.2 (λ l, _), rw [finsupp.unique_single l, finsupp.total_single, smul_eq_mul, mul_one], intro hi, simp [hi] }, { refine top_unique (λ _ _, _), simp [submodule.mem_span_singleton] } end protected lemma linear_equiv.is_basis (hs : is_basis R v) (f : M ≃ₗ[R] M') : is_basis R (f ∘ v) := begin split, { apply @linear_independent.image _ _ _ _ _ _ _ _ _ _ hs.1 (f : M →ₗ[R] M'), simp [linear_equiv.ker f] }, { rw set.range_comp, have : span R ((f : M →ₗ[R] M') '' range v) = ⊤, { rw [span_image (f : M →ₗ[R] M'), hs.2], simp }, exact this } end lemma is_basis_span (hs : linear_independent R v) : @is_basis ι R (span R (range v)) (λ i : ι, ⟨v i, subset_span (mem_range_self _)⟩) _ _ _ := begin split, { apply linear_independent_span hs }, { rw eq_top_iff', intro x, have h₁ : subtype.val '' set.range (λ i, subtype.mk (v i) _) = range v, by rw ←set.range_comp, have h₂ : map (submodule.subtype _) (span R (set.range (λ i, subtype.mk (v i) _))) = span R (range v), by rw [←span_image, submodule.subtype_eq_val, h₁], have h₃ : (x : M) ∈ map (submodule.subtype _) (span R (set.range (λ i, subtype.mk (v i) _))), by rw h₂; apply subtype.mem x, rcases mem_map.1 h₃ with ⟨y, hy₁, hy₂⟩, have h_x_eq_y : x = y, by rw [subtype.ext_iff, ← hy₂]; simp, rw h_x_eq_y, exact hy₁ } end lemma is_basis_empty (h_empty : ¬ nonempty ι) (h : ∀x:M, x = 0) : is_basis R (λ x : ι, (0 : M)) := ⟨ linear_independent_empty_type h_empty, eq_top_iff'.2 $ assume x, (h x).symm ▸ submodule.zero_mem _ ⟩ lemma is_basis_empty_bot (h_empty : ¬ nonempty ι) : is_basis R (λ _ : ι, (0 : (⊥ : submodule R M))) := begin apply is_basis_empty h_empty, intro x, apply subtype.ext_iff_val.2, exact (submodule.mem_bot R).1 (subtype.mem x), end open fintype variables [fintype ι] (h : is_basis R v) /-- A module over `R` with a finite basis is linearly equivalent to functions from its basis to `R`. -/ def equiv_fun_basis : M ≃ₗ[R] (ι → R) := linear_equiv.trans (module_equiv_finsupp h) { to_fun := finsupp.to_fun, map_add' := λ x y, by ext; exact finsupp.add_apply, map_smul' := λ x y, by ext; exact finsupp.smul_apply, ..finsupp.equiv_fun_on_fintype } /-- A module over a finite ring that admits a finite basis is finite. -/ def module.fintype_of_fintype [fintype R] : fintype M := fintype.of_equiv _ (equiv_fun_basis h).to_equiv.symm theorem module.card_fintype [fintype R] [fintype M] : card M = (card R) ^ (card ι) := calc card M = card (ι → R) : card_congr (equiv_fun_basis h).to_equiv ... = card R ^ card ι : card_fun /-- Given a basis `v` indexed by `ι`, the canonical linear equivalence between `ι → R` and `M` maps a function `x : ι → R` to the linear combination `∑_i x i • v i`. -/ @[simp] lemma equiv_fun_basis_symm_apply (x : ι → R) : (equiv_fun_basis h).symm x = ∑ i, x i • v i := begin change finsupp.sum ((finsupp.equiv_fun_on_fintype.symm : (ι → R) ≃ (ι →₀ R)) x) (λ (i : ι) (a : R), a • v i) = ∑ i, x i • v i, dsimp [finsupp.equiv_fun_on_fintype, finsupp.sum], rw finset.sum_filter, refine finset.sum_congr rfl (λi hi, _), by_cases H : x i = 0, { simp [H] }, { simp [H], refl } end end module section vector_space variables {v : ι → V} [field K] [add_comm_group V] [add_comm_group V'] [vector_space K V] [vector_space K V'] {s t : set V} {x y z : V} include K open submodule /- TODO: some of the following proofs can generalized with a zero_ne_one predicate type class (instead of a data containing type class) -/ section lemma mem_span_insert_exchange : x ∈ span K (insert y s) → x ∉ span K s → y ∈ span K (insert x s) := begin simp [mem_span_insert], rintro a z hz rfl h, refine ⟨a⁻¹, -a⁻¹ • z, smul_mem _ _ hz, _⟩, have a0 : a ≠ 0, {rintro rfl, simp * at *}, simp [a0, smul_add, smul_smul] end end lemma linear_independent_iff_not_mem_span : linear_independent K v ↔ (∀i, v i ∉ span K (v '' (univ \ {i}))) := begin apply linear_independent_iff_not_smul_mem_span.trans, split, { intros h i h_in_span, apply one_ne_zero (h i 1 (by simp [h_in_span])) }, { intros h i a ha, by_contradiction ha', exact false.elim (h _ ((smul_mem_iff _ ha').1 ha)) } end lemma linear_independent_unique [unique ι] (h : v (default ι) ≠ 0): linear_independent K v := begin rw linear_independent_iff, intros l hl, ext i, rw [unique.eq_default i, finsupp.zero_apply], by_contra hc, have := smul_smul (l (default ι))⁻¹ (l (default ι)) (v (default ι)), rw [finsupp.unique_single l, finsupp.total_single] at hl, rw [hl, inv_mul_cancel hc, smul_zero, one_smul] at this, exact h this.symm end lemma linear_independent_singleton {x : V} (hx : x ≠ 0) : linear_independent K (λ x, x : ({x} : set V) → V) := begin apply @linear_independent_unique _ _ _ _ _ _ _ _ _, apply set.unique_singleton, apply hx, end lemma disjoint_span_singleton {p : submodule K V} {x : V} (x0 : x ≠ 0) : disjoint p (span K {x}) ↔ x ∉ p := ⟨λ H xp, x0 (disjoint_def.1 H _ xp (singleton_subset_iff.1 subset_span:_)), begin simp [disjoint_def, mem_span_singleton], rintro xp y yp a rfl, by_cases a0 : a = 0, {simp [a0]}, exact xp.elim ((smul_mem_iff p a0).1 yp), end⟩ lemma linear_independent.insert (hs : linear_independent K (λ b, b : s → V)) (hx : x ∉ span K s) : linear_independent K (λ b, b : insert x s → V) := begin rw ← union_singleton, have x0 : x ≠ 0 := mt (by rintro rfl; apply zero_mem _) hx, apply hs.union (linear_independent_singleton x0), rwa [disjoint_span_singleton x0] end lemma exists_linear_independent (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : ∃b⊆t, s ⊆ b ∧ t ⊆ span K b ∧ linear_independent K (λ x, x : b → V) := begin rcases zorn.zorn_subset₀ {b | b ⊆ t ∧ linear_independent K (λ x, x : b → V)} _ _ ⟨hst, hs⟩ with ⟨b, ⟨bt, bi⟩, sb, h⟩, { refine ⟨b, bt, sb, λ x xt, _, bi⟩, by_contra hn, apply hn, rw ← h _ ⟨insert_subset.2 ⟨xt, bt⟩, bi.insert hn⟩ (subset_insert _ _), exact subset_span (mem_insert _ _) }, { refine λ c hc cc c0, ⟨⋃₀ c, ⟨_, _⟩, λ x, _⟩, { exact sUnion_subset (λ x xc, (hc xc).1) }, { exact linear_independent_sUnion_of_directed cc.directed_on (λ x xc, (hc xc).2) }, { exact subset_sUnion_of_mem } } end lemma exists_subset_is_basis (hs : linear_independent K (λ x, x : s → V)) : ∃b, s ⊆ b ∧ is_basis K (coe : b → V) := let ⟨b, hb₀, hx, hb₂, hb₃⟩ := exists_linear_independent hs (@subset_univ _ _) in ⟨ b, hx, @linear_independent.restrict_of_comp_subtype _ _ _ id _ _ _ _ hb₃, by simp; exact eq_top_iff.2 hb₂⟩ lemma exists_sum_is_basis (hs : linear_independent K v) : ∃ (ι' : Type u) (v' : ι' → V), is_basis K (sum.elim v v') := begin -- This is a hack: we jump through hoops to reuse `exists_subset_is_basis`. let s := set.range v, let e : ι ≃ s := equiv.set.range v (hs.injective zero_ne_one), have : (λ x, x : s → V) = v ∘ e.symm := by { funext, dsimp, rw [equiv.set.apply_range_symm v], }, have : linear_independent K (λ x, x : s → V), { rw this, exact linear_independent.comp hs _ (e.symm.injective), }, obtain ⟨b, ss, is⟩ := exists_subset_is_basis this, let e' : ι ⊕ (b \ s : set V) ≃ b := calc ι ⊕ (b \ s : set V) ≃ s ⊕ (b \ s : set V) : equiv.sum_congr e (equiv.refl _) ... ≃ b : equiv.set.sum_diff_subset ss, refine ⟨(b \ s : set V), λ x, x.1, _⟩, convert is_basis.comp is e' _, { funext x, cases x; simp; refl, }, { exact e'.bijective, }, end variables (K V) lemma exists_is_basis : ∃b : set V, is_basis K (λ i, i : b → V) := let ⟨b, _, hb⟩ := exists_subset_is_basis (linear_independent_empty K V : _) in ⟨b, hb⟩ variables {K V} -- TODO(Mario): rewrite? lemma exists_of_linear_independent_of_finite_span {t : finset V} (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ (span K ↑t : submodule K V)) : ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = t.card := have ∀t, ∀(s' : finset V), ↑s' ⊆ s → s ∩ ↑t = ∅ → s ⊆ (span K ↑(s' ∪ t) : submodule K V) → ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = (s' ∪ t).card := assume t, finset.induction_on t (assume s' hs' _ hss', have s = ↑s', from eq_of_linear_independent_of_span_subtype zero_ne_one hs hs' $ by simpa using hss', ⟨s', by simp [this]⟩) (assume b₁ t hb₁t ih s' hs' hst hss', have hb₁s : b₁ ∉ s, from assume h, have b₁ ∈ s ∩ ↑(insert b₁ t), from ⟨h, finset.mem_insert_self _ _⟩, by rwa [hst] at this, have hb₁s' : b₁ ∉ s', from assume h, hb₁s $ hs' h, have hst : s ∩ ↑t = ∅, from eq_empty_of_subset_empty $ subset.trans (by simp [inter_subset_inter, subset.refl]) (le_of_eq hst), classical.by_cases (assume : s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨u, hust, hsu, eq⟩ := ih _ hs' hst this in have hb₁u : b₁ ∉ u, from assume h, (hust h).elim hb₁s hb₁t, ⟨insert b₁ u, by simp [insert_subset_insert hust], subset.trans hsu (by simp), by simp [eq, hb₁t, hb₁s', hb₁u]⟩) (assume : ¬ s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨b₂, hb₂s, hb₂t⟩ := not_subset.mp this in have hb₂t' : b₂ ∉ s' ∪ t, from assume h, hb₂t $ subset_span h, have s ⊆ (span K ↑(insert b₂ s' ∪ t) : submodule K V), from assume b₃ hb₃, have ↑(s' ∪ insert b₁ t) ⊆ insert b₁ (insert b₂ ↑(s' ∪ t) : set V), by simp [insert_eq, -singleton_union, -union_singleton, union_subset_union, subset.refl, subset_union_right], have hb₃ : b₃ ∈ span K (insert b₁ (insert b₂ ↑(s' ∪ t) : set V)), from span_mono this (hss' hb₃), have s ⊆ (span K (insert b₁ ↑(s' ∪ t)) : submodule K V), by simpa [insert_eq, -singleton_union, -union_singleton] using hss', have hb₁ : b₁ ∈ span K (insert b₂ ↑(s' ∪ t)), from mem_span_insert_exchange (this hb₂s) hb₂t, by rw [span_insert_eq_span hb₁] at hb₃; simpa using hb₃, let ⟨u, hust, hsu, eq⟩ := ih _ (by simp [insert_subset, hb₂s, hs']) hst this in ⟨u, subset.trans hust $ union_subset_union (subset.refl _) (by simp [subset_insert]), hsu, by simp [eq, hb₂t', hb₁t, hb₁s']⟩)), begin have eq : t.filter (λx, x ∈ s) ∪ t.filter (λx, x ∉ s) = t, { ext1 x, by_cases x ∈ s; simp * }, apply exists.elim (this (t.filter (λx, x ∉ s)) (t.filter (λx, x ∈ s)) (by simp [set.subset_def]) (by simp [set.ext_iff] {contextual := tt}) (by rwa [eq])), intros u h, exact ⟨u, subset.trans h.1 (by simp [subset_def, and_imp, or_imp_distrib] {contextual:=tt}), h.2.1, by simp only [h.2.2, eq]⟩ end lemma exists_finite_card_le_of_finite_of_linear_independent_of_span (ht : finite t) (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ span K t) : ∃h : finite s, h.to_finset.card ≤ ht.to_finset.card := have s ⊆ (span K ↑(ht.to_finset) : submodule K V), by simp; assumption, let ⟨u, hust, hsu, eq⟩ := exists_of_linear_independent_of_finite_span hs this in have finite s, from u.finite_to_set.subset hsu, ⟨this, by rw [←eq]; exact (finset.card_le_of_subset $ finset.coe_subset.mp $ by simp [hsu])⟩ lemma linear_map.exists_left_inverse_of_injective (f : V →ₗ[K] V') (hf_inj : f.ker = ⊥) : ∃g:V' →ₗ V, g.comp f = linear_map.id := begin rcases exists_is_basis K V with ⟨B, hB⟩, have hB₀ : _ := hB.1.to_subtype_range, have : linear_independent K (λ x, x : f '' B → V'), { have h₁ := hB₀.image_subtype (show disjoint (span K (range (λ i : B, i.val))) (linear_map.ker f), by simp [hf_inj]), rwa subtype.range_coe at h₁ }, rcases exists_subset_is_basis this with ⟨C, BC, hC⟩, haveI : inhabited V := ⟨0⟩, use hC.constr (C.restrict (inv_fun f)), refine hB.ext (λ b, _), rw image_subset_iff at BC, have : f b = (⟨f b, BC b.2⟩ : C) := rfl, dsimp, rw [this, constr_basis hC], exact left_inverse_inv_fun (linear_map.ker_eq_bot.1 hf_inj) _ end lemma submodule.exists_is_compl (p : submodule K V) : ∃ q : submodule K V, is_compl p q := let ⟨f, hf⟩ := p.subtype.exists_left_inverse_of_injective p.ker_subtype in ⟨f.ker, linear_map.is_compl_of_proj $ linear_map.ext_iff.1 hf⟩ lemma linear_map.exists_right_inverse_of_surjective (f : V →ₗ[K] V') (hf_surj : f.range = ⊤) : ∃g:V' →ₗ V, f.comp g = linear_map.id := begin rcases exists_is_basis K V' with ⟨C, hC⟩, haveI : inhabited V := ⟨0⟩, use hC.constr (C.restrict (inv_fun f)), refine hC.ext (λ c, _), simp [constr_basis hC, right_inverse_inv_fun (linear_map.range_eq_top.1 hf_surj) c] end open submodule linear_map theorem quotient_prod_linear_equiv (p : submodule K V) : nonempty ((p.quotient × p) ≃ₗ[K] V) := let ⟨q, hq⟩ := p.exists_is_compl in nonempty.intro $ ((quotient_equiv_of_is_compl p q hq).prod (linear_equiv.refl _ _)).trans (prod_equiv_of_is_compl q p hq.symm) open fintype variables (K) (V) theorem vector_space.card_fintype [fintype K] [fintype V] : ∃ n : ℕ, card V = (card K) ^ n := exists.elim (exists_is_basis K V) $ λ b hb, ⟨card b, module.card_fintype hb⟩ end vector_space namespace pi open set linear_map section module variables {η : Type*} {ιs : η → Type*} {Ms : η → Type*} variables [ring R] [∀i, add_comm_group (Ms i)] [∀i, module R (Ms i)] lemma linear_independent_std_basis (v : Πj, ιs j → (Ms j)) (hs : ∀i, linear_independent R (v i)) : linear_independent R (λ (ji : Σ j, ιs j), std_basis R Ms ji.1 (v ji.1 ji.2)) := begin have hs' : ∀j : η, linear_independent R (λ i : ιs j, std_basis R Ms j (v j i)), { intro j, apply linear_independent.image (hs j), simp [ker_std_basis] }, apply linear_independent_Union_finite hs', { assume j J _ hiJ, simp [(set.Union.equations._eqn_1 _).symm, submodule.span_image, submodule.span_Union], have h₀ : ∀ j, span R (range (λ (i : ιs j), std_basis R Ms j (v j i))) ≤ range (std_basis R Ms j), { intro j, rw [span_le, linear_map.range_coe], apply range_comp_subset_range }, have h₁ : span R (range (λ (i : ιs j), std_basis R Ms j (v j i))) ≤ ⨆ i ∈ {j}, range (std_basis R Ms i), { rw @supr_singleton _ _ _ (λ i, linear_map.range (std_basis R (λ (j : η), Ms j) i)), apply h₀ }, have h₂ : (⨆ j ∈ J, span R (range (λ (i : ιs j), std_basis R Ms j (v j i)))) ≤ ⨆ j ∈ J, range (std_basis R (λ (j : η), Ms j) j) := supr_le_supr (λ i, supr_le_supr (λ H, h₀ i)), have h₃ : disjoint (λ (i : η), i ∈ {j}) J, { convert set.disjoint_singleton_left.2 hiJ, rw ←@set_of_mem_eq _ {j}, refl }, exact (disjoint_std_basis_std_basis _ _ _ _ h₃).mono h₁ h₂ } end variable [fintype η] lemma is_basis_std_basis (s : Πj, ιs j → (Ms j)) (hs : ∀j, is_basis R (s j)) : is_basis R (λ (ji : Σ j, ιs j), std_basis R Ms ji.1 (s ji.1 ji.2)) := begin split, { apply linear_independent_std_basis _ (assume i, (hs i).1) }, have h₁ : Union (λ j, set.range (std_basis R Ms j ∘ s j)) ⊆ range (λ (ji : Σ (j : η), ιs j), (std_basis R Ms (ji.fst)) (s (ji.fst) (ji.snd))), { apply Union_subset, intro i, apply range_comp_subset_range (λ x : ιs i, (⟨i, x⟩ : Σ (j : η), ιs j)) (λ (ji : Σ (j : η), ιs j), std_basis R Ms (ji.fst) (s (ji.fst) (ji.snd))) }, have h₂ : ∀ i, span R (range (std_basis R Ms i ∘ s i)) = range (std_basis R Ms i), { intro i, rw [set.range_comp, submodule.span_image, (assume i, (hs i).2), submodule.map_top] }, apply eq_top_mono, apply span_mono h₁, rw span_Union, simp only [h₂], apply supr_range_std_basis end section variables (R η) lemma is_basis_fun₀ : is_basis R (λ (ji : Σ (j : η), unit), (std_basis R (λ (i : η), R) (ji.fst)) 1) := @is_basis_std_basis R η (λi:η, unit) (λi:η, R) _ _ _ _ (λ _ _, (1 : R)) (assume i, @is_basis_singleton_one _ _ _ _) lemma is_basis_fun : is_basis R (λ i, std_basis R (λi:η, R) i 1) := begin apply (is_basis_fun₀ R η).comp (λ i, ⟨i, punit.star⟩), apply bijective_iff_has_inverse.2, use sigma.fst, simp [function.left_inverse, function.right_inverse] end end end module end pi
2f96e8384b3f57d4c98b6f92c72738881d677117
947b78d97130d56365ae2ec264df196ce769371a
/stage0/src/Lean/Compiler/IR/LiveVars.lean
0dc2e30cf4772167aa5badac449c3b7764ab61fd
[ "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
6,847
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.Compiler.IR.Basic import Lean.Compiler.IR.FreeVars namespace Lean namespace IR /- Remark: in the paper "Counting Immutable Beans" the concepts of free and live variables coincide because the paper does *not* consider join points. For example, consider the function body `B` ``` let x := ctor_0; jmp block_1 x ``` in a context where we have the join point `block_1` defined as ``` block_1 (x : obj) : obj := let z := ctor_0 x y; ret z `` The variable `y` is live in the function body `B` since it occurs in `block_1` which is "invoked" by `B`. -/ namespace IsLive /- We use `State Context` instead of `ReaderT Context Id` because we remove non local joint points from `Context` whenever we visit them instead of maintaining a set of visited non local join points. Remark: we don't need to track local join points because we assume there is no variable or join point shadowing in our IR. -/ abbrev M := StateM LocalContext @[inline] def visitVar (w : Index) (x : VarId) : M Bool := pure (HasIndex.visitVar w x) @[inline] def visitJP (w : Index) (x : JoinPointId) : M Bool := pure (HasIndex.visitJP w x) @[inline] def visitArg (w : Index) (a : Arg) : M Bool := pure (HasIndex.visitArg w a) @[inline] def visitArgs (w : Index) (as : Array Arg) : M Bool := pure (HasIndex.visitArgs w as) @[inline] def visitExpr (w : Index) (e : Expr) : M Bool := pure (HasIndex.visitExpr w e) partial def visitFnBody (w : Index) : FnBody → M Bool | FnBody.vdecl x _ v b => visitExpr w v <||> visitFnBody b | FnBody.jdecl j ys v b => visitFnBody v <||> visitFnBody b | FnBody.set x _ y b => visitVar w x <||> visitArg w y <||> visitFnBody b | FnBody.uset x _ y b => visitVar w x <||> visitVar w y <||> visitFnBody b | FnBody.sset x _ _ y _ b => visitVar w x <||> visitVar w y <||> visitFnBody b | FnBody.setTag x _ b => visitVar w x <||> visitFnBody b | FnBody.inc x _ _ _ b => visitVar w x <||> visitFnBody b | FnBody.dec x _ _ _ b => visitVar w x <||> visitFnBody b | FnBody.del x b => visitVar w x <||> visitFnBody b | FnBody.mdata _ b => visitFnBody b | FnBody.jmp j ys => visitArgs w ys <||> do { ctx ← get; match ctx.getJPBody j with | some b => -- `j` is not a local join point since we assume we cannot shadow join point declarations. -- Instead of marking the join points that we have already been visited, we permanently remove `j` from the context. set (ctx.eraseJoinPointDecl j) *> visitFnBody b | none => -- `j` must be a local join point. So do nothing since we have already visite its body. pure false } | FnBody.ret x => visitArg w x | FnBody.case _ x _ alts => visitVar w x <||> alts.anyM (fun alt => visitFnBody alt.body) | FnBody.unreachable => pure false end IsLive /- Return true if `x` is live in the function body `b` in the context `ctx`. Remark: the context only needs to contain all (free) join point declarations. Recall that we say that a join point `j` is free in `b` if `b` contains `FnBody.jmp j ys` and `j` is not local. -/ def FnBody.hasLiveVar (b : FnBody) (ctx : LocalContext) (x : VarId) : Bool := (IsLive.visitFnBody x.idx b).run' ctx abbrev LiveVarSet := VarIdSet abbrev JPLiveVarMap := Std.RBMap JoinPointId LiveVarSet (fun j₁ j₂ => j₁.idx < j₂.idx) instance LiveVarSet.inhabited : Inhabited LiveVarSet := ⟨{}⟩ def mkLiveVarSet (x : VarId) : LiveVarSet := Std.RBTree.empty.insert x namespace LiveVars abbrev Collector := LiveVarSet → LiveVarSet @[inline] private def skip : Collector := fun s => s @[inline] private def collectVar (x : VarId) : Collector := fun s => s.insert x private def collectArg : Arg → Collector | Arg.var x => collectVar x | irrelevant => skip @[specialize] private def collectArray {α : Type} (as : Array α) (f : α → Collector) : Collector := fun s => as.foldl (fun s a => f a s) s private def collectArgs (as : Array Arg) : Collector := collectArray as collectArg private def accumulate (s' : LiveVarSet) : Collector := fun s => s'.fold (fun s x => s.insert x) s private def collectJP (m : JPLiveVarMap) (j : JoinPointId) : Collector := match m.find? j with | some xs => accumulate xs | none => skip -- unreachable for well-formed code private def bindVar (x : VarId) : Collector := fun s => s.erase x private def bindParams (ps : Array Param) : Collector := fun s => ps.foldl (fun s p => s.erase p.x) s def collectExpr : Expr → Collector | Expr.ctor _ ys => collectArgs ys | Expr.reset _ x => collectVar x | Expr.reuse x _ _ ys => collectVar x ∘ collectArgs ys | Expr.proj _ x => collectVar x | Expr.uproj _ x => collectVar x | Expr.sproj _ _ x => collectVar x | Expr.fap _ ys => collectArgs ys | Expr.pap _ ys => collectArgs ys | Expr.ap x ys => collectVar x ∘ collectArgs ys | Expr.box _ x => collectVar x | Expr.unbox x => collectVar x | Expr.lit v => skip | Expr.isShared x => collectVar x | Expr.isTaggedPtr x => collectVar x partial def collectFnBody : FnBody → JPLiveVarMap → Collector | FnBody.vdecl x _ v b, m => collectExpr v ∘ bindVar x ∘ collectFnBody b m | FnBody.jdecl j ys v b, m => let jLiveVars := (bindParams ys ∘ collectFnBody v m) {}; let m := m.insert j jLiveVars; collectFnBody b m | FnBody.set x _ y b, m => collectVar x ∘ collectArg y ∘ collectFnBody b m | FnBody.setTag x _ b, m => collectVar x ∘ collectFnBody b m | FnBody.uset x _ y b, m => collectVar x ∘ collectVar y ∘ collectFnBody b m | FnBody.sset x _ _ y _ b, m => collectVar x ∘ collectVar y ∘ collectFnBody b m | FnBody.inc x _ _ _ b, m => collectVar x ∘ collectFnBody b m | FnBody.dec x _ _ _ b, m => collectVar x ∘ collectFnBody b m | FnBody.del x b, m => collectVar x ∘ collectFnBody b m | FnBody.mdata _ b, m => collectFnBody b m | FnBody.ret x, m => collectArg x | FnBody.case _ x _ alts, m => collectVar x ∘ collectArray alts (fun alt => collectFnBody alt.body m) | FnBody.unreachable, m => skip | FnBody.jmp j xs, m => collectJP m j ∘ collectArgs xs def updateJPLiveVarMap (j : JoinPointId) (ys : Array Param) (v : FnBody) (m : JPLiveVarMap) : JPLiveVarMap := let jLiveVars := (bindParams ys ∘ collectFnBody v m) {}; m.insert j jLiveVars end LiveVars def updateLiveVars (e : Expr) (v : LiveVarSet) : LiveVarSet := LiveVars.collectExpr e v def collectLiveVars (b : FnBody) (m : JPLiveVarMap) (v : LiveVarSet := {}) : LiveVarSet := LiveVars.collectFnBody b m v export LiveVars (updateJPLiveVarMap) end IR end Lean
a96a694fe6aed37d1bdd219835367d172b7e455d
94e33a31faa76775069b071adea97e86e218a8ee
/src/analysis/inner_product_space/gram_schmidt_ortho.lean
554ce5e0359fb64ceae5bb6bee7d751941d5a518
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
11,756
lean
/- Copyright (c) 2022 Jiale Miao. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jiale Miao, Kevin Buzzard, Alexander Bentkamp -/ import analysis.inner_product_space.projection import order.well_founded_set import analysis.inner_product_space.pi_L2 /-! # Gram-Schmidt Orthogonalization and Orthonormalization In this file we introduce Gram-Schmidt Orthogonalization and Orthonormalization. The Gram-Schmidt process takes a set of vectors as input and outputs a set of orthogonal vectors which have the same span. ## Main results - `gram_schmidt` : the Gram-Schmidt process - `gram_schmidt_orthogonal` : `gram_schmidt` produces an orthogonal system of vectors. - `span_gram_schmidt` : `gram_schmidt` preserves span of vectors. - `gram_schmidt_ne_zero` : If the input vectors of `gram_schmidt` are linearly independent, then the output vectors are non-zero. - `gram_schmidt_basis` : The basis produced by the Gram-Schmidt process when given a basis as input. - `gram_schmidt_normed` : the normalized `gram_schmidt` (i.e each vector in `gram_schmidt_normed` has unit length.) - `gram_schmidt_orthornormal` : `gram_schmidt_normed` produces an orthornormal system of vectors. ## TODO Construct a version with an orthonormal basis from Gram-Schmidt process. -/ open_locale big_operators open finset variables (𝕜 : Type*) {E : Type*} [is_R_or_C 𝕜] [inner_product_space 𝕜 E] variables {ι : Type*} [linear_order ι] [locally_finite_order_bot ι] [is_well_order ι (<)] local attribute [instance] is_well_order.to_has_well_founded local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y /-- The Gram-Schmidt process takes a set of vectors as input and outputs a set of orthogonal vectors which have the same span. -/ noncomputable def gram_schmidt (f : ι → E) : ι → E | n := f n - ∑ i : Iio n, orthogonal_projection (𝕜 ∙ gram_schmidt i) (f n) using_well_founded { dec_tac := `[exact mem_Iio.1 i.2] } /-- This lemma uses `∑ i in` instead of `∑ i :`.-/ lemma gram_schmidt_def (f : ι → E) (n : ι): gram_schmidt 𝕜 f n = f n - ∑ i in Iio n, orthogonal_projection (𝕜 ∙ gram_schmidt 𝕜 f i) (f n) := by { rw [←sum_attach, attach_eq_univ, gram_schmidt], refl } lemma gram_schmidt_def' (f : ι → E) (n : ι): f n = gram_schmidt 𝕜 f n + ∑ i in Iio n, orthogonal_projection (𝕜 ∙ gram_schmidt 𝕜 f i) (f n) := by rw [gram_schmidt_def, sub_add_cancel] @[simp] lemma gram_schmidt_zero {ι : Type*} [linear_order ι] [locally_finite_order ι] [order_bot ι] [is_well_order ι (<)] (f : ι → E) : gram_schmidt 𝕜 f ⊥ = f ⊥ := by rw [gram_schmidt_def, Iio_eq_Ico, finset.Ico_self, finset.sum_empty, sub_zero] /-- **Gram-Schmidt Orthogonalisation**: `gram_schmidt` produces an orthogonal system of vectors. -/ theorem gram_schmidt_orthogonal (f : ι → E) {a b : ι} (h₀ : a ≠ b) : ⟪gram_schmidt 𝕜 f a, gram_schmidt 𝕜 f b⟫ = 0 := begin suffices : ∀ a b : ι, a < b → ⟪gram_schmidt 𝕜 f a, gram_schmidt 𝕜 f b⟫ = 0, { cases h₀.lt_or_lt with ha hb, { exact this _ _ ha, }, { rw inner_eq_zero_sym, exact this _ _ hb, }, }, clear h₀ a b, intros a b h₀, revert a, apply well_founded.induction (@is_well_order.wf ι (<) _) b, intros b ih a h₀, simp only [gram_schmidt_def 𝕜 f b, inner_sub_right, inner_sum, orthogonal_projection_singleton, inner_smul_right], rw finset.sum_eq_single_of_mem a (finset.mem_Iio.mpr h₀), { by_cases h : gram_schmidt 𝕜 f a = 0, { simp only [h, inner_zero_left, zero_div, zero_mul, sub_zero], }, { rw [← inner_self_eq_norm_sq_to_K, div_mul_cancel, sub_self], rwa [ne.def, inner_self_eq_zero], }, }, simp_intros i hi hia only [finset.mem_range], simp only [mul_eq_zero, div_eq_zero_iff, inner_self_eq_zero], right, cases hia.lt_or_lt with hia₁ hia₂, { rw inner_eq_zero_sym, exact ih a h₀ i hia₁ }, { exact ih i (mem_Iio.1 hi) a hia₂ } end /-- This is another version of `gram_schmidt_orthogonal` using `pairwise` instead. -/ theorem gram_schmidt_pairwise_orthogonal (f : ι → E) : pairwise (λ a b, ⟪gram_schmidt 𝕜 f a, gram_schmidt 𝕜 f b⟫ = 0) := λ a b, gram_schmidt_orthogonal 𝕜 f open submodule set order lemma mem_span_gram_schmidt (f : ι → E) {i j : ι} (hij : i ≤ j) : f i ∈ span 𝕜 (gram_schmidt 𝕜 f '' Iic j) := begin rw [gram_schmidt_def' 𝕜 f i], simp_rw orthogonal_projection_singleton, exact submodule.add_mem _ (subset_span $ mem_image_of_mem _ hij) (submodule.sum_mem _ $ λ k hk, smul_mem (span 𝕜 (gram_schmidt 𝕜 f '' Iic j)) _ $ subset_span $ mem_image_of_mem (gram_schmidt 𝕜 f) $ (finset.mem_Iio.1 hk).le.trans hij), end lemma gram_schmidt_mem_span (f : ι → E) : ∀ {j i}, i ≤ j → gram_schmidt 𝕜 f i ∈ span 𝕜 (f '' Iic j) | j := λ i hij, begin rw [gram_schmidt_def 𝕜 f i], simp_rw orthogonal_projection_singleton, refine submodule.sub_mem _ (subset_span (mem_image_of_mem _ hij)) (submodule.sum_mem _ $ λ k hk, _), let hkj : k < j := (finset.mem_Iio.1 hk).trans_le hij, exact smul_mem _ _ (span_mono (image_subset f $ Iic_subset_Iic.2 hkj.le) $ gram_schmidt_mem_span le_rfl), end using_well_founded { dec_tac := `[assumption] } lemma span_gram_schmidt_Iic (f : ι → E) (c : ι) : span 𝕜 (gram_schmidt 𝕜 f '' Iic c) = span 𝕜 (f '' Iic c) := span_eq_span (set.image_subset_iff.2 $ λ i, gram_schmidt_mem_span _ _) $ set.image_subset_iff.2 $ λ i, mem_span_gram_schmidt _ _ lemma span_gram_schmidt_Iio (f : ι → E) (c : ι) : span 𝕜 (gram_schmidt 𝕜 f '' Iio c) = span 𝕜 (f '' Iio c) := span_eq_span (set.image_subset_iff.2 $ λ i hi, span_mono (image_subset _ $ Iic_subset_Iio.2 hi) $ gram_schmidt_mem_span _ _ le_rfl) $ set.image_subset_iff.2 $ λ i hi, span_mono (image_subset _ $ Iic_subset_Iio.2 hi) $ mem_span_gram_schmidt _ _ le_rfl /-- `gram_schmidt` preserves span of vectors. -/ lemma span_gram_schmidt (f : ι → E) : span 𝕜 (range (gram_schmidt 𝕜 f)) = span 𝕜 (range f) := span_eq_span (range_subset_iff.2 $ λ i, span_mono (image_subset_range _ _) $ gram_schmidt_mem_span _ _ le_rfl) $ range_subset_iff.2 $ λ i, span_mono (image_subset_range _ _) $ mem_span_gram_schmidt _ _ le_rfl lemma gram_schmidt_ne_zero_coe (f : ι → E) (n : ι) (h₀ : linear_independent 𝕜 (f ∘ (coe : set.Iic n → ι))) : gram_schmidt 𝕜 f n ≠ 0 := begin by_contra h, have h₁ : f n ∈ span 𝕜 (f '' Iio n), { rw [← span_gram_schmidt_Iio 𝕜 f n, gram_schmidt_def' _ f, h, zero_add], apply submodule.sum_mem _ _, simp_intros a ha only [finset.mem_Ico], simp only [set.mem_image, set.mem_Iio, orthogonal_projection_singleton], apply submodule.smul_mem _ _ _, rw finset.mem_Iio at ha, refine subset_span ⟨a, ha, by refl⟩ }, have h₂ : (f ∘ (coe : set.Iic n → ι)) ⟨n, le_refl n⟩ ∈ span 𝕜 (f ∘ (coe : set.Iic n → ι) '' Iio ⟨n, le_refl n⟩), { rw [image_comp], convert h₁ using 3, ext i, simpa using @le_of_lt _ _ i n }, apply linear_independent.not_mem_span_image h₀ _ h₂, simp only [set.mem_Iio, lt_self_iff_false, not_false_iff] end /-- If the input vectors of `gram_schmidt` are linearly independent, then the output vectors are non-zero. -/ lemma gram_schmidt_ne_zero (f : ι → E) (n : ι) (h₀ : linear_independent 𝕜 f) : gram_schmidt 𝕜 f n ≠ 0 := gram_schmidt_ne_zero_coe _ _ _ (linear_independent.comp h₀ _ subtype.coe_injective) /-- `gram_schmidt` produces a triangular matrix of vectors when given a basis. -/ lemma gram_schmidt_triangular {i j : ι} (hij : i < j) (b : basis ι 𝕜 E) : b.repr (gram_schmidt 𝕜 b i) j = 0 := begin have : gram_schmidt 𝕜 b i ∈ span 𝕜 (gram_schmidt 𝕜 b '' set.Iio j), from subset_span ((set.mem_image _ _ _).2 ⟨i, hij, rfl⟩), have : gram_schmidt 𝕜 b i ∈ span 𝕜 (b '' set.Iio j), by rwa [← span_gram_schmidt_Iio 𝕜 b j], have : ↑(((b.repr) (gram_schmidt 𝕜 b i)).support) ⊆ set.Iio j, from basis.repr_support_subset_of_mem_span b (set.Iio j) this, exact (finsupp.mem_supported' _ _).1 ((finsupp.mem_supported 𝕜 _).2 this) j (not_mem_Iio.2 (le_refl j)), end /-- `gram_schmidt` produces linearly independent vectors when given linearly independent vectors. -/ lemma gram_schmidt_linear_independent (f : ι → E) (h₀ : linear_independent 𝕜 f) : linear_independent 𝕜 (gram_schmidt 𝕜 f) := linear_independent_of_ne_zero_of_inner_eq_zero (λ i, gram_schmidt_ne_zero _ _ _ h₀) (λ i j, gram_schmidt_orthogonal 𝕜 f) /-- When given a basis, `gram_schmidt` produces a basis. -/ noncomputable def gram_schmidt_basis (b : basis ι 𝕜 E) : basis ι 𝕜 E := basis.mk (gram_schmidt_linear_independent 𝕜 b b.linear_independent) ((span_gram_schmidt 𝕜 b).trans b.span_eq) lemma coe_gram_schmidt_basis (b : basis ι 𝕜 E) : (gram_schmidt_basis 𝕜 b : ι → E) = gram_schmidt 𝕜 b := basis.coe_mk _ _ /-- the normalized `gram_schmidt` (i.e each vector in `gram_schmidt_normed` has unit length.) -/ noncomputable def gram_schmidt_normed (f : ι → E) (n : ι) : E := (∥gram_schmidt 𝕜 f n∥ : 𝕜)⁻¹ • (gram_schmidt 𝕜 f n) lemma gram_schmidt_normed_unit_length_coe (f : ι → E) (n : ι) (h₀ : linear_independent 𝕜 (f ∘ (coe : set.Iic n → ι))) : ∥gram_schmidt_normed 𝕜 f n∥ = 1 := by simp only [gram_schmidt_ne_zero_coe 𝕜 f n h₀, gram_schmidt_normed, norm_smul_inv_norm, ne.def, not_false_iff] lemma gram_schmidt_normed_unit_length (f : ι → E) (n : ι) (h₀ : linear_independent 𝕜 f) : ∥gram_schmidt_normed 𝕜 f n∥ = 1 := gram_schmidt_normed_unit_length_coe _ _ _ (linear_independent.comp h₀ _ subtype.coe_injective) /-- **Gram-Schmidt Orthonormalization**: `gram_schmidt_normed` produces an orthornormal system of vectors. -/ theorem gram_schmidt_orthonormal (f : ι → E) (h₀ : linear_independent 𝕜 f) : orthonormal 𝕜 (gram_schmidt_normed 𝕜 f) := begin unfold orthonormal, split, { simp only [gram_schmidt_normed_unit_length, h₀, eq_self_iff_true, implies_true_iff], }, { intros i j hij, simp only [gram_schmidt_normed, inner_smul_left, inner_smul_right, is_R_or_C.conj_inv, is_R_or_C.conj_of_real, mul_eq_zero, inv_eq_zero, is_R_or_C.of_real_eq_zero, norm_eq_zero], repeat { right }, exact gram_schmidt_orthogonal 𝕜 f hij } end lemma span_gram_schmidt_normed (f : ι → E) (s : set ι) : span 𝕜 (gram_schmidt_normed 𝕜 f '' s) = span 𝕜 (gram_schmidt 𝕜 f '' s) := begin refine span_eq_span (set.image_subset_iff.2 $ λ i hi, smul_mem _ _ $ subset_span $ mem_image_of_mem _ hi) (set.image_subset_iff.2 $ λ i hi, span_mono (image_subset _ $ singleton_subset_set_iff.2 hi) _), simp only [coe_singleton, set.image_singleton], by_cases h : gram_schmidt 𝕜 f i = 0, { simp [h] }, { refine mem_span_singleton.2 ⟨∥gram_schmidt 𝕜 f i∥, smul_inv_smul₀ _ _⟩, exact_mod_cast (norm_ne_zero_iff.2 h) } end lemma span_gram_schmidt_normed_range (f : ι → E) : span 𝕜 (range (gram_schmidt_normed 𝕜 f)) = span 𝕜 (range (gram_schmidt 𝕜 f)) := by simpa only [image_univ.symm] using span_gram_schmidt_normed 𝕜 f univ /-- When given a basis, `gram_schmidt_normed` produces an orthonormal basis. -/ noncomputable def gram_schmidt_orthonormal_basis [fintype ι] (b : basis ι 𝕜 E) : orthonormal_basis ι 𝕜 E := orthonormal_basis.mk (gram_schmidt_orthonormal 𝕜 b b.linear_independent) (((span_gram_schmidt_normed_range 𝕜 b).trans (span_gram_schmidt 𝕜 b)).trans b.span_eq)
1b1c7024b8c58b39e4ae06791af0da757d692af3
46125763b4dbf50619e8846a1371029346f4c3db
/src/algebra/category/Mon/basic.lean
a4da1058ce8b1e3976377bb9d5231a58a47774a4
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
7,087
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.concrete_category import algebra.group.hom import data.equiv.algebra import algebra.punit_instances /-! # Category instances for monoid, add_monoid, comm_monoid, and add_comm_monoid. We introduce the bundled categories: * `Mon` * `AddMon` * `CommMon` * `AddCommMon` along with the relevant forgetful functors between them. ## Implementation notes See Note [locally reducible category instances] TODO: Probably @[derive] should be able to create instances of the required form (without `id`), and then we could use that instead of this obscure `local attribute [reducible]` method. -/ library_note "locally reducible category instances" "We make SemiRing (and the other categories) locally reducible in order to define its instances. This is because writing, for example, ``` instance : concrete_category SemiRing := by { delta SemiRing, apply_instance } ``` results in an instance of the form `id (bundled_hom.concrete_category _)` and this `id`, not being [reducible], prevents a later instance search (once SemiRing is no longer reducible) from seeing that the morphisms of SemiRing are really semiring morphisms (`→+*`), and therefore have a coercion to functions, for example. It's especially important that the `has_coe_to_sort` instance not contain an extra `id` as we want the `semiring ↥R` instance to also apply to `semiring R.α` (it seems to be impractical to guarantee that we always access `R.α` through the coercion rather than directly)." universes u v open category_theory /-- The category of monoids and monoid morphisms. -/ @[to_additive AddMon] def Mon : Type (u+1) := bundled monoid namespace Mon /-- Construct a bundled Mon from the underlying type and typeclass. -/ @[to_additive] def of (M : Type u) [monoid M] : Mon := bundled.of M @[to_additive] instance : inhabited Mon := -- The default instance for `monoid punit` is derived via `punit.comm_ring`, -- which breaks to_additive. ⟨@of punit $ @group.to_monoid _ $ @comm_group.to_group _ punit.comm_group⟩ local attribute [reducible] Mon @[to_additive] instance : has_coe_to_sort Mon := infer_instance -- short-circuit type class inference @[to_additive add_monoid] instance (M : Mon) : monoid M := M.str @[to_additive] instance bundled_hom : bundled_hom @monoid_hom := ⟨@monoid_hom.to_fun, @monoid_hom.id, @monoid_hom.comp, @monoid_hom.coe_inj⟩ @[to_additive] instance : concrete_category Mon := infer_instance -- short-circuit type class inference end Mon /-- The category of commutative monoids and monoid morphisms. -/ @[to_additive AddCommMon] def CommMon : Type (u+1) := induced_category Mon (bundled.map @comm_monoid.to_monoid) namespace CommMon /-- Construct a bundled CommMon from the underlying type and typeclass. -/ @[to_additive] def of (M : Type u) [comm_monoid M] : CommMon := bundled.of M @[to_additive] instance : inhabited CommMon := -- The default instance for `comm_monoid punit` is derived via `punit.comm_ring`, -- which breaks to_additive. ⟨@of punit $ @comm_group.to_comm_monoid _ punit.comm_group⟩ local attribute [reducible] CommMon @[to_additive] instance : has_coe_to_sort CommMon := infer_instance -- short-circuit type class inference @[to_additive add_comm_monoid] instance (M : CommMon) : comm_monoid M := M.str @[to_additive] instance : concrete_category CommMon := infer_instance -- short-circuit type class inference @[to_additive has_forget_to_AddMon] instance has_forget_to_Mon : has_forget₂ CommMon Mon := infer_instance -- short-circuit type class inference end CommMon -- We verify that the coercions of morphisms to functions work correctly: example {R S : Mon} (f : R ⟶ S) : (R : Type) → (S : Type) := f example {R S : CommMon} (f : R ⟶ S) : (R : Type) → (S : Type) := f variables {X Y : Type u} section variables [monoid X] [monoid Y] /-- Build an isomorphism in the category `Mon` from a `mul_equiv` between `monoid`s. -/ @[to_additive add_equiv.to_AddMon_iso "Build an isomorphism in the category `AddMon` from a `add_equiv` between `add_monoid`s."] def mul_equiv.to_Mon_iso (e : X ≃* Y) : Mon.of X ≅ Mon.of Y := { hom := e.to_monoid_hom, inv := e.symm.to_monoid_hom } @[simp, to_additive add_equiv.to_AddMon_iso_hom] lemma mul_equiv.to_Mon_iso_hom {e : X ≃* Y} : e.to_Mon_iso.hom = e.to_monoid_hom := rfl @[simp, to_additive add_equiv.to_AddMon_iso_inv] lemma mul_equiv.to_Mon_iso_inv {e : X ≃* Y} : e.to_Mon_iso.inv = e.symm.to_monoid_hom := rfl end section variables [comm_monoid X] [comm_monoid Y] /-- Build an isomorphism in the category `CommMon` from a `mul_equiv` between `comm_monoid`s. -/ @[to_additive add_equiv.to_AddCommMon_iso "Build an isomorphism in the category `AddCommMon` from a `add_equiv` between `add_comm_monoid`s."] def mul_equiv.to_CommMon_iso (e : X ≃* Y) : CommMon.of X ≅ CommMon.of Y := { hom := e.to_monoid_hom, inv := e.symm.to_monoid_hom } @[simp, to_additive add_equiv.to_AddCommMon_iso_hom] lemma mul_equiv.to_CommMon_iso_hom {e : X ≃* Y} : e.to_CommMon_iso.hom = e.to_monoid_hom := rfl @[simp, to_additive add_equiv.to_AddCommMon_iso_inv] lemma mul_equiv.to_CommMon_iso_inv {e : X ≃* Y} : e.to_CommMon_iso.inv = e.symm.to_monoid_hom := rfl end namespace category_theory.iso /-- Build a `mul_equiv` from an isomorphism in the category `Mon`. -/ @[to_additive AddMond_iso_to_add_equiv "Build an `add_equiv` from an isomorphism in the category `AddMon`."] def Mon_iso_to_mul_equiv {X Y : Mon.{u}} (i : X ≅ Y) : X ≃* Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := by tidy, right_inv := by tidy, map_mul' := by tidy }. /-- Build a `mul_equiv` from an isomorphism in the category `CommMon`. -/ @[to_additive AddCommMon_iso_to_add_equiv "Build an `add_equiv` from an isomorphism in the category `AddCommMon`."] def CommMon_iso_to_mul_equiv {X Y : CommMon.{u}} (i : X ≅ Y) : X ≃* Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := by tidy, right_inv := by tidy, map_mul' := by tidy }. end category_theory.iso /-- multiplicative equivalences between `monoid`s are the same as (isomorphic to) isomorphisms in `Mon` -/ @[to_additive add_equiv_iso_AddMon_iso "additive equivalences between `add_monoid`s are the same as (isomorphic to) isomorphisms in `AddMon`"] def mul_equiv_iso_Mon_iso {X Y : Type u} [monoid X] [monoid Y] : (X ≃* Y) ≅ (Mon.of X ≅ Mon.of Y) := { hom := λ e, e.to_Mon_iso, inv := λ i, i.Mon_iso_to_mul_equiv, } /-- multiplicative equivalences between `comm_monoid`s are the same as (isomorphic to) isomorphisms in `CommMon` -/ @[to_additive add_equiv_iso_AddCommMon_iso "additive equivalences between `add_comm_monoid`s are the same as (isomorphic to) isomorphisms in `AddCommMon`"] def mul_equiv_iso_CommMon_iso {X Y : Type u} [comm_monoid X] [comm_monoid Y] : (X ≃* Y) ≅ (CommMon.of X ≅ CommMon.of Y) := { hom := λ e, e.to_CommMon_iso, inv := λ i, i.CommMon_iso_to_mul_equiv, }
72ae1dd11c82b4f822327a3a2af3810071185f8c
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/ring_theory/algebra.lean
735137c4de3880361124eab74eeeb9ca97cee2aa
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
27,477
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Yury Kudryashov -/ import data.matrix.basic import linear_algebra.tensor_product import algebra.commute import data.equiv.ring /-! # Algebra over Commutative Semiring (under category) In this file we define algebra over commutative (semi)rings, algebra homomorphisms `alg_hom`, algebra equivalences `alg_equiv`, and `subalgebra`s. We also define usual operations on `alg_hom`s (`id`, `comp`) and subalgebras (`map`, `comap`). ## Notations * `A →ₐ[R] B` : `R`-algebra homomorphism from `A` to `B`. * `A ≃ₐ[R] B` : `R`-algebra equivalence from `A` to `B`. -/ noncomputable theory universes u v w u₁ v₁ open_locale tensor_product section prio -- We set this priority to 0 later in this file set_option default_priority 200 -- see Note [default priority] /-- The category of R-algebras where R is a commutative ring is the under category R ↓ CRing. In the categorical setting we have a forgetful functor R-Alg ⥤ R-Mod. However here it extends module in order to preserve definitional equality in certain cases. -/ @[nolint has_inhabited_instance] class algebra (R : Type u) (A : Type v) [comm_semiring R] [semiring A] extends has_scalar R A, R →+* A := (commutes' : ∀ r x, to_fun r * x = x * to_fun r) (smul_def' : ∀ r x, r • x = to_fun r * x) end prio /-- Embedding `R →+* A` given by `algebra` structure. -/ def algebra_map (R : Type u) (A : Type v) [comm_semiring R] [semiring A] [algebra R A] : R →+* A := algebra.to_ring_hom /-- Creating an algebra from a morphism to the center of a semiring. -/ def ring_hom.to_algebra' {R S} [comm_semiring R] [semiring S] (i : R →+* S) (h : ∀ c x, i c * x = x * i c) : algebra R S := { smul := λ c x, i c * x, commutes' := h, smul_def' := λ c x, rfl, .. i} /-- Creating an algebra from a morphism to a commutative semiring. -/ def ring_hom.to_algebra {R S} [comm_semiring R] [comm_semiring S] (i : R →+* S) : algebra R S := i.to_algebra' $ λ _, mul_comm _ namespace algebra variables {R : Type u} {S : Type v} {A : Type w} /-- Let `R` be a commutative semiring, let `A` be a semiring with a `semimodule R` structure. If `(r • 1) * x = x * (r • 1) = r • x` for all `r : R` and `x : A`, then `A` is an `algebra` over `R`. -/ def of_semimodule' [comm_semiring R] [semiring A] [semimodule R A] (h₁ : ∀ (r : R) (x : A), (r • 1) * x = r • x) (h₂ : ∀ (r : R) (x : A), x * (r • 1) = r • x) : algebra R A := { to_fun := λ r, r • 1, map_one' := one_smul _ _, map_mul' := λ r₁ r₂, by rw [h₁, mul_smul], map_zero' := zero_smul _ _, map_add' := λ r₁ r₂, add_smul r₁ r₂ 1, commutes' := λ r x, by simp only [h₁, h₂], smul_def' := λ r x, by simp only [h₁] } /-- Let `R` be a commutative semiring, let `A` be a semiring with a `semimodule R` structure. If `(r • x) * y = x * (r • y) = r • (x * y)` for all `r : R` and `x y : A`, then `A` is an `algebra` over `R`. -/ def of_semimodule [comm_semiring R] [semiring A] [semimodule R A] (h₁ : ∀ (r : R) (x y : A), (r • x) * y = r • (x * y)) (h₂ : ∀ (r : R) (x y : A), x * (r • y) = r • (x * y)) : algebra R A := of_semimodule' (λ r x, by rw [h₁, one_mul]) (λ r x, by rw [h₂, mul_one]) section semiring variables [comm_semiring R] [comm_semiring S] [semiring A] [algebra R A] lemma smul_def'' (r : R) (x : A) : r • x = algebra_map R A r * x := algebra.smul_def' r x @[priority 200] -- see Note [lower instance priority] instance to_semimodule : semimodule R A := { one_smul := by simp [smul_def''], mul_smul := by simp [smul_def'', mul_assoc], smul_add := by simp [smul_def'', mul_add], smul_zero := by simp [smul_def''], add_smul := by simp [smul_def'', add_mul], zero_smul := by simp [smul_def''] } -- from now on, we don't want to use the following instance anymore attribute [instance, priority 0] algebra.to_has_scalar lemma smul_def (r : R) (x : A) : r • x = algebra_map R A r * x := algebra.smul_def' r x theorem commutes (r : R) (x : A) : algebra_map R A r * x = x * algebra_map R A r := algebra.commutes' r x theorem left_comm (r : R) (x y : A) : x * (algebra_map R A r * y) = algebra_map R A r * (x * y) := by rw [← mul_assoc, ← commutes, mul_assoc] @[simp] lemma mul_smul_comm (s : R) (x y : A) : x * (s • y) = s • (x * y) := by rw [smul_def, smul_def, left_comm] @[simp] lemma smul_mul_assoc (r : R) (x y : A) : (r • x) * y = r • (x * y) := by rw [smul_def, smul_def, mul_assoc] end semiring -- TODO (semimodule linear maps): once we have them, port next section to semirings section ring variables [comm_ring R] [ring A] [algebra R A] @[priority 200] -- see Note [lower instance priority] instance to_module : module R A := { .. algebra.to_semimodule } /-- Creating an algebra from a subring. This is the dual of ring extension. -/ instance of_subring (S : set R) [is_subring S] : algebra S R := ring_hom.to_algebra ⟨coe, rfl, λ _ _, rfl, rfl, λ _ _, rfl⟩ variables (R A) /-- The multiplication in an algebra is a bilinear map. -/ def lmul : A →ₗ A →ₗ A := linear_map.mk₂ R (*) (λ x y z, add_mul x y z) (λ c x y, by rw [smul_def, smul_def, mul_assoc _ x y]) (λ x y z, mul_add x y z) (λ c x y, by rw [smul_def, smul_def, left_comm]) /-- The multiplication on the left in an algebra is a linear map. -/ def lmul_left (r : A) : A →ₗ A := lmul R A r /-- The multiplication on the right in an algebra is a linear map. -/ def lmul_right (r : A) : A →ₗ A := (lmul R A).flip r variables {R A} @[simp] lemma lmul_apply (p q : A) : lmul R A p q = p * q := rfl @[simp] lemma lmul_left_apply (p q : A) : lmul_left R A p q = p * q := rfl @[simp] lemma lmul_right_apply (p q : A) : lmul_right R A p q = q * p := rfl end ring end algebra instance module.endomorphism_algebra (R : Type u) (M : Type v) [comm_ring R] [add_comm_group M] [module R M] : algebra R (M →ₗ[R] M) := { to_fun := λ r, r • linear_map.id, map_one' := one_smul _ _, map_zero' := zero_smul _ _, map_add' := λ r₁ r₂, add_smul _ _ _, map_mul' := λ r₁ r₂, by { ext x, simp [mul_smul] }, commutes' := by { intros, ext, simp }, smul_def' := by { intros, ext, simp } } instance matrix_algebra (n : Type u) (R : Type v) [fintype n] [decidable_eq n] [comm_semiring R] : algebra R (matrix n n R) := { to_fun := λ r, r • 1, map_one' := one_smul _ _, map_mul' := λ r₁ r₂, by { ext, simp [mul_assoc] }, map_zero' := zero_smul _ _, map_add' := λ _ _, add_smul _ _ _, commutes' := by { intros, simp }, smul_def' := by { intros, simp } } set_option old_structure_cmd true /-- Defining the homomorphism in the category R-Alg. -/ @[nolint has_inhabited_instance] structure alg_hom (R : Type u) (A : Type v) (B : Type w) [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] extends ring_hom A B := (commutes' : ∀ r : R, to_fun (algebra_map R A r) = algebra_map R B r) run_cmd tactic.add_doc_string `alg_hom.to_ring_hom "Reinterpret an `alg_hom` as a `ring_hom`" infixr ` →ₐ `:25 := alg_hom _ notation A ` →ₐ[`:25 R `] ` B := alg_hom R A B namespace alg_hom variables {R : Type u} {A : Type v} {B : Type w} {C : Type u₁} {D : Type v₁} section semiring variables [comm_semiring R] [semiring A] [semiring B] [semiring C] [semiring D] variables [algebra R A] [algebra R B] [algebra R C] [algebra R D] instance : has_coe_to_fun (A →ₐ[R] B) := ⟨_, λ f, f.to_fun⟩ instance coe_ring_hom : has_coe (A →ₐ[R] B) (A →+* B) := ⟨alg_hom.to_ring_hom⟩ instance coe_monoid_hom : has_coe (A →ₐ[R] B) (A →* B) := ⟨λ f, ↑(f : A →+* B)⟩ instance coe_add_monoid_hom : has_coe (A →ₐ[R] B) (A →+ B) := ⟨λ f, ↑(f : A →+* B)⟩ @[simp, norm_cast] lemma coe_mk {f : A → B} (h₁ h₂ h₃ h₄ h₅) : ⇑(⟨f, h₁, h₂, h₃, h₄, h₅⟩ : A →ₐ[R] B) = f := rfl @[simp, norm_cast] lemma coe_to_ring_hom (f : A →ₐ[R] B) : ⇑(f : A →+* B) = f := rfl @[norm_cast] lemma coe_to_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →* B) = f := rfl @[norm_cast] lemma coe_to_add_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →+ B) = f := rfl variables (φ : A →ₐ[R] B) theorem coe_fn_inj ⦃φ₁ φ₂ : A →ₐ[R] B⦄ (H : ⇑φ₁ = φ₂) : φ₁ = φ₂ := by { cases φ₁, cases φ₂, congr, exact H } theorem coe_ring_hom_inj : function.injective (coe : (A →ₐ[R] B) → (A →+* B)) := λ φ₁ φ₂ H, coe_fn_inj $ show ((φ₁ : (A →+* B)) : A → B) = ((φ₂ : (A →+* B)) : A → B), from congr_arg _ H theorem coe_monoid_hom_inj : function.injective (coe : (A →ₐ[R] B) → (A →* B)) := function.injective_comp ring_hom.coe_monoid_hom_inj coe_ring_hom_inj theorem coe_add_monoid_hom_inj : function.injective (coe : (A →ₐ[R] B) → (A →+ B)) := function.injective_comp ring_hom.coe_add_monoid_hom_inj coe_ring_hom_inj @[ext] theorem ext ⦃φ₁ φ₂ : A →ₐ[R] B⦄ (H : ∀ x, φ₁ x = φ₂ x) : φ₁ = φ₂ := coe_fn_inj $ funext H theorem commutes (r : R) : φ (algebra_map R A r) = algebra_map R B r := φ.commutes' r theorem comp_algebra_map : φ.to_ring_hom.comp (algebra_map R A) = algebra_map R B := ring_hom.ext $ φ.commutes @[simp] lemma map_add (r s : A) : φ (r + s) = φ r + φ s := φ.to_ring_hom.map_add r s @[simp] lemma map_zero : φ 0 = 0 := φ.to_ring_hom.map_zero @[simp] lemma map_mul (x y) : φ (x * y) = φ x * φ y := φ.to_ring_hom.map_mul x y @[simp] lemma map_one : φ 1 = 1 := φ.to_ring_hom.map_one @[simp] lemma map_smul (r : R) (x : A) : φ (r • x) = r • φ x := by simp only [algebra.smul_def, map_mul, commutes] @[simp] lemma map_pow (x : A) (n : ℕ) : φ (x ^ n) = (φ x) ^ n := φ.to_ring_hom.map_pow x n lemma map_sum {ι : Type*} (f : ι → A) (s : finset ι) : φ (s.sum f) = s.sum (λx, φ (f x)) := φ.to_ring_hom.map_sum f s section variables (R A) /-- Identity map as an `alg_hom`. -/ protected def id : A →ₐ[R] A := { commutes' := λ _, rfl, ..ring_hom.id A } end @[simp] lemma id_apply (p : A) : alg_hom.id R A p = p := rfl /-- Composition of algebra homeomorphisms. -/ def comp (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : A →ₐ[R] C := { commutes' := λ r : R, by rw [← φ₁.commutes, ← φ₂.commutes]; refl, .. φ₁.to_ring_hom.comp ↑φ₂ } @[simp] lemma comp_apply (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) (p : A) : φ₁.comp φ₂ p = φ₁ (φ₂ p) := rfl @[simp] theorem comp_id : φ.comp (alg_hom.id R A) = φ := ext $ λ x, rfl @[simp] theorem id_comp : (alg_hom.id R B).comp φ = φ := ext $ λ x, rfl theorem comp_assoc (φ₁ : C →ₐ[R] D) (φ₂ : B →ₐ[R] C) (φ₃ : A →ₐ[R] B) : (φ₁.comp φ₂).comp φ₃ = φ₁.comp (φ₂.comp φ₃) := ext $ λ x, rfl end semiring section comm_semiring variables [comm_semiring R] [comm_semiring A] [comm_semiring B] variables [algebra R A] [algebra R B] variables (φ : A →ₐ[R] B) lemma map_prod {ι : Type*} (f : ι → A) (s : finset ι) : φ (s.prod f) = s.prod (λx, φ (f x)) := φ.to_ring_hom.map_prod f s end comm_semiring variables [comm_ring R] [ring A] [ring B] [ring C] variables [algebra R A] [algebra R B] [algebra R C] (φ : A →ₐ[R] B) @[simp] lemma map_neg (x) : φ (-x) = -φ x := φ.to_ring_hom.map_neg x @[simp] lemma map_sub (x y) : φ (x - y) = φ x - φ y := φ.to_ring_hom.map_sub x y /-- R-Alg ⥤ R-Mod -/ def to_linear_map : A →ₗ B := { to_fun := φ, add := φ.map_add, smul := φ.map_smul } @[simp] lemma to_linear_map_apply (p : A) : φ.to_linear_map p = φ p := rfl theorem to_linear_map_inj {φ₁ φ₂ : A →ₐ[R] B} (H : φ₁.to_linear_map = φ₂.to_linear_map) : φ₁ = φ₂ := ext $ λ x, show φ₁.to_linear_map x = φ₂.to_linear_map x, by rw H @[simp] lemma comp_to_linear_map (f : A →ₐ[R] B) (g : B →ₐ[R] C) : (g.comp f).to_linear_map = g.to_linear_map.comp f.to_linear_map := rfl end alg_hom set_option old_structure_cmd true /-- An equivalence of algebras is an equivalence of rings commuting with the actions of scalars. -/ structure alg_equiv (R : Type u) (A : Type v) (B : Type w) [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] extends A ≃ B, A ≃* B, A ≃+ B, A ≃+* B := (commutes' : ∀ r : R, to_fun (algebra_map R A r) = algebra_map R B r) attribute [nolint doc_blame] alg_equiv.to_ring_equiv attribute [nolint doc_blame] alg_equiv.to_equiv attribute [nolint doc_blame] alg_equiv.to_add_equiv attribute [nolint doc_blame] alg_equiv.to_mul_equiv notation A ` ≃ₐ[`:50 R `] ` A' := alg_equiv R A A' namespace alg_equiv variables {R : Type u} {A₁ : Type v} {A₂ : Type w} {A₃ : Type u₁} variables [comm_semiring R] [semiring A₁] [semiring A₂] [semiring A₃] variables [algebra R A₁] [algebra R A₂] [algebra R A₃] instance : has_coe_to_fun (A₁ ≃ₐ[R] A₂) := ⟨_, alg_equiv.to_fun⟩ instance has_coe_to_ring_equiv : has_coe (A₁ ≃ₐ[R] A₂) (A₁ ≃+* A₂) := ⟨alg_equiv.to_ring_equiv⟩ @[simp, norm_cast] lemma coe_ring_equiv (e : A₁ ≃ₐ[R] A₂) : ((e : A₁ ≃+* A₂) : A₁ → A₂) = e := rfl @[simp] lemma map_add (e : A₁ ≃ₐ[R] A₂) : ∀ x y, e (x + y) = e x + e y := e.to_add_equiv.map_add @[simp] lemma map_zero (e : A₁ ≃ₐ[R] A₂) : e 0 = 0 := e.to_add_equiv.map_zero @[simp] lemma map_mul (e : A₁ ≃ₐ[R] A₂) : ∀ x y, e (x * y) = (e x) * (e y) := e.to_mul_equiv.map_mul @[simp] lemma map_one (e : A₁ ≃ₐ[R] A₂) : e 1 = 1 := e.to_mul_equiv.map_one @[simp] lemma commutes (e : A₁ ≃ₐ[R] A₂) : ∀ (r : R), e (algebra_map R A₁ r) = algebra_map R A₂ r := e.commutes' @[simp] lemma map_neg {A₁ : Type v} {A₂ : Type w} [ring A₁] [ring A₂] [algebra R A₁] [algebra R A₂] (e : A₁ ≃ₐ[R] A₂) : ∀ x, e (-x) = -(e x) := e.to_add_equiv.map_neg @[simp] lemma map_sub {A₁ : Type v} {A₂ : Type w} [ring A₁] [ring A₂] [algebra R A₁] [algebra R A₂] (e : A₁ ≃ₐ[R] A₂) : ∀ x y, e (x - y) = e x - e y := e.to_add_equiv.map_sub instance has_coe_to_alg_hom : has_coe (A₁ ≃ₐ[R] A₂) (A₁ →ₐ[R] A₂) := ⟨λ e, { map_one' := e.map_one, map_zero' := e.map_zero, ..e }⟩ @[simp, norm_cast] lemma coe_to_alg_equiv (e : A₁ ≃ₐ[R] A₂) : ((e : A₁ →ₐ[R] A₂) : A₁ → A₂) = e := rfl lemma injective (e : A₁ ≃ₐ[R] A₂) : function.injective e := e.to_equiv.injective lemma surjective (e : A₁ ≃ₐ[R] A₂) : function.surjective e := e.to_equiv.surjective lemma bijective (e : A₁ ≃ₐ[R] A₂) : function.bijective e := e.to_equiv.bijective instance : has_one (A₁ ≃ₐ[R] A₁) := ⟨{commutes' := λ r, rfl, ..(1 : A₁ ≃+* A₁)}⟩ instance : inhabited (A₁ ≃ₐ[R] A₁) := ⟨1⟩ /-- Algebra equivalences are reflexive. -/ @[refl] def refl : A₁ ≃ₐ[R] A₁ := 1 /-- Algebra equivalences are symmetric. -/ @[symm] def symm (e : A₁ ≃ₐ[R] A₂) : A₂ ≃ₐ[R] A₁ := { commutes' := λ r, by { rw ←e.to_ring_equiv.symm_apply_apply (algebra_map R A₁ r), congr, change _ = e _, rw e.commutes, }, ..e.to_ring_equiv.symm, } /-- Algebra equivalences are transitive. -/ @[trans] def trans (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) : A₁ ≃ₐ[R] A₃ := { commutes' := λ r, show e₂.to_fun (e₁.to_fun _) = _, by rw [e₁.commutes', e₂.commutes'], ..(e₁.to_ring_equiv.trans e₂.to_ring_equiv), } @[simp] lemma apply_symm_apply (e : A₁ ≃ₐ[R] A₂) : ∀ x, e (e.symm x) = x := e.to_equiv.apply_symm_apply @[simp] lemma symm_apply_apply (e : A₁ ≃ₐ[R] A₂) : ∀ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply end alg_equiv namespace algebra variables (R : Type u) (S : Type v) (A : Type w) include R S A /-- `comap R S A` is a type alias for `A`, and has an R-algebra structure defined on it when `algebra R S` and `algebra S A`. -/ /- This is done to avoid a type class search with meta-variables `algebra R ?m_1` and `algebra ?m_1 A -/ /- The `nolint` attribute is added because it has unused arguments `R` and `S`, but these are necessary for synthesizing the appropriate type classes -/ @[nolint unused_arguments] def comap : Type w := A instance comap.inhabited [h : inhabited A] : inhabited (comap R S A) := h instance comap.semiring [h : semiring A] : semiring (comap R S A) := h instance comap.ring [h : ring A] : ring (comap R S A) := h instance comap.comm_semiring [h : comm_semiring A] : comm_semiring (comap R S A) := h instance comap.comm_ring [h : comm_ring A] : comm_ring (comap R S A) := h instance comap.algebra' [comm_semiring S] [semiring A] [h : algebra S A] : algebra S (comap R S A) := h /-- Identity homomorphism `A →ₐ[S] comap R S A`. -/ def comap.to_comap [comm_semiring S] [semiring A] [algebra S A] : A →ₐ[S] comap R S A := alg_hom.id S A /-- Identity homomorphism `comap R S A →ₐ[S] A`. -/ def comap.of_comap [comm_semiring S] [semiring A] [algebra S A] : comap R S A →ₐ[S] A := alg_hom.id S A variables [comm_semiring R] [comm_semiring S] [semiring A] [algebra R S] [algebra S A] /-- `R ⟶ S` induces `S-Alg ⥤ R-Alg` -/ instance comap.algebra : algebra R (comap R S A) := { smul := λ r x, (algebra_map R S r • x : A), commutes' := λ r x, algebra.commutes _ _, smul_def' := λ _ _, algebra.smul_def _ _, .. (algebra_map S A).comp (algebra_map R S) } /-- Embedding of `S` into `comap R S A`. -/ def to_comap : S →ₐ[R] comap R S A := { commutes' := λ r, rfl, .. algebra_map S A } theorem to_comap_apply (x) : to_comap R S A x = algebra_map S A x := rfl end algebra namespace alg_hom variables {R : Type u} {S : Type v} {A : Type w} {B : Type u₁} variables [comm_semiring R] [comm_semiring S] [semiring A] [semiring B] variables [algebra R S] [algebra S A] [algebra S B] (φ : A →ₐ[S] B) include R /-- R ⟶ S induces S-Alg ⥤ R-Alg -/ def comap : algebra.comap R S A →ₐ[R] algebra.comap R S B := { commutes' := λ r, φ.commutes (algebra_map R S r) ..φ } end alg_hom namespace rat instance algebra_rat {α} [division_ring α] [char_zero α] : algebra ℚ α := (rat.cast_hom α).to_algebra' $ λ r x, (commute.cast_int_left x r.1).div_left (commute.cast_nat_left x r.2) end rat /-- A subalgebra is a subring that includes the range of `algebra_map`. -/ structure subalgebra (R : Type u) (A : Type v) [comm_ring R] [ring A] [algebra R A] : Type v := (carrier : set A) [subring : is_subring carrier] (range_le' : set.range (algebra_map R A) ≤ carrier) namespace subalgebra variables {R : Type u} {A : Type v} variables [comm_ring R] [ring A] [algebra R A] include R instance : has_coe (subalgebra R A) (set A) := ⟨λ S, S.carrier⟩ lemma range_le (S : subalgebra R A) : set.range (algebra_map R A) ≤ S := S.range_le' instance : has_mem A (subalgebra R A) := ⟨λ x S, x ∈ (S : set A)⟩ variables {A} theorem mem_coe {x : A} {s : subalgebra R A} : x ∈ (s : set A) ↔ x ∈ s := iff.rfl @[ext] theorem ext {S T : subalgebra R A} (h : ∀ x : A, x ∈ S ↔ x ∈ T) : S = T := by cases S; cases T; congr; ext x; exact h x theorem ext_iff {S T : subalgebra R A} : S = T ↔ ∀ x : A, x ∈ S ↔ x ∈ T := ⟨λ h x, by rw h, ext⟩ variables (S : subalgebra R A) instance : is_subring (S : set A) := S.subring instance : ring S := @@subtype.ring _ S.is_subring instance : inhabited S := ⟨0⟩ instance (R : Type u) (A : Type v) [comm_ring R] [comm_ring A] [algebra R A] (S : subalgebra R A) : comm_ring S := @@subtype.comm_ring _ S.is_subring instance algebra : algebra R S := { smul := λ (c:R) x, ⟨c • x.1, by rw algebra.smul_def; exact @@is_submonoid.mul_mem _ S.2.2 (S.3 ⟨c, rfl⟩) x.2⟩, commutes' := λ c x, subtype.eq $ algebra.commutes _ _, smul_def' := λ c x, subtype.eq $ algebra.smul_def _ _, .. (algebra_map R A).cod_restrict S $ λ x, S.range_le ⟨x, rfl⟩ } instance to_algebra (R : Type u) (A : Type v) [comm_ring R] [comm_ring A] [algebra R A] (S : subalgebra R A) : algebra S A := algebra.of_subring _ /-- Embedding of a subalgebra into the algebra. -/ def val : S →ₐ[R] A := by refine_struct { to_fun := subtype.val }; intros; refl /-- Convert a `subalgebra` to `submodule` -/ def to_submodule : submodule R A := { carrier := S, zero := (0:S).2, add := λ x y hx hy, (⟨x, hx⟩ + ⟨y, hy⟩ : S).2, smul := λ c x hx, (algebra.smul_def c x).symm ▸ (⟨algebra_map R A c, S.range_le ⟨c, rfl⟩⟩ * ⟨x, hx⟩:S).2 } instance coe_to_submodule : has_coe (subalgebra R A) (submodule R A) := ⟨to_submodule⟩ instance to_submodule.is_subring : is_subring ((S : submodule R A) : set A) := S.2 instance : partial_order (subalgebra R A) := { le := λ S T, (S : set A) ≤ (T : set A), le_refl := λ _, le_refl _, le_trans := λ _ _ _, le_trans, le_antisymm := λ S T hst hts, ext $ λ x, ⟨@hst x, @hts x⟩ } /-- Reinterpret an `S`-subalgebra as an `R`-subalgebra in `comap R S A`. -/ def comap {R : Type u} {S : Type v} {A : Type w} [comm_ring R] [comm_ring S] [ring A] [algebra R S] [algebra S A] (iSB : subalgebra S A) : subalgebra R (algebra.comap R S A) := { carrier := (iSB : set A), subring := iSB.is_subring, range_le' := λ a ⟨r, hr⟩, hr ▸ iSB.range_le ⟨_, rfl⟩ } /-- If `S` is an `R`-subalgebra of `A` and `T` is an `S`-subalgebra of `A`, then `T` is an `R`-subalgebra of `A`. -/ def under {R : Type u} {A : Type v} [comm_ring R] [comm_ring A] {i : algebra R A} (S : subalgebra R A) (T : subalgebra S A) : subalgebra R A := { carrier := T, range_le' := (λ a ⟨r, hr⟩, hr ▸ T.range_le ⟨⟨algebra_map R A r, S.range_le ⟨r, rfl⟩⟩, rfl⟩) } lemma mul_mem (A' : subalgebra R A) (x y : A) : x ∈ A' → y ∈ A' → x * y ∈ A' := @is_submonoid.mul_mem A _ A' _ x y end subalgebra namespace alg_hom variables {R : Type u} {A : Type v} {B : Type w} variables [comm_ring R] [ring A] [ring B] [algebra R A] [algebra R B] variables (φ : A →ₐ[R] B) /-- Range of an `alg_hom` as a subalgebra. -/ protected def range (φ : A →ₐ[R] B) : subalgebra R B := begin haveI : is_subring (set.range φ) := show is_subring (set.range φ.to_ring_hom), by apply_instance, exact ⟨set.range φ, λ y ⟨r, hr⟩, ⟨algebra_map R A r, hr ▸ φ.commutes r⟩⟩ end end alg_hom namespace algebra variables (R : Type u) (A : Type v) variables [comm_semiring R] [semiring A] [algebra R A] instance id : algebra R R := (ring_hom.id R).to_algebra namespace id @[simp] lemma map_eq_self (x : R) : algebra_map R R x = x := rfl @[simp] lemma smul_eq_mul (x y : R) : x • y = x * y := rfl end id /-- `algebra_map` as an `alg_hom`. -/ def of_id : R →ₐ[R] A := { commutes' := λ _, rfl, .. algebra_map R A } variables {R} theorem of_id_apply (r) : of_id R A r = algebra_map R A r := rfl end algebra namespace algebra variables (R : Type u) {A : Type v} [comm_ring R] [ring A] [algebra R A] /-- The minimal subalgebra that includes `s`. -/ def adjoin (s : set A) : subalgebra R A := { carrier := ring.closure (set.range (algebra_map R A) ∪ s), range_le' := le_trans (set.subset_union_left _ _) ring.subset_closure } variables {R} protected lemma gc : galois_connection (adjoin R : set A → subalgebra R A) coe := λ s S, ⟨λ H, le_trans (le_trans (set.subset_union_right _ _) ring.subset_closure) H, λ H, ring.closure_subset $ set.union_subset S.range_le H⟩ /-- Galois insertion between `adjoin` and `coe`. -/ protected def gi : galois_insertion (adjoin R : set A → subalgebra R A) coe := { choice := λ s hs, adjoin R s, gc := algebra.gc, le_l_u := λ S, (algebra.gc (S : set A) (adjoin R S)).1 $ le_refl _, choice_eq := λ _ _, rfl } instance : complete_lattice (subalgebra R A) := galois_insertion.lift_complete_lattice algebra.gi instance : inhabited (subalgebra R A) := ⟨⊥⟩ theorem mem_bot {x : A} : x ∈ (⊥ : subalgebra R A) ↔ x ∈ set.range (algebra_map R A) := suffices (⊥ : subalgebra R A) = (of_id R A).range, by rw this; refl, le_antisymm bot_le $ subalgebra.range_le _ theorem mem_top {x : A} : x ∈ (⊤ : subalgebra R A) := ring.mem_closure $ or.inr trivial theorem eq_top_iff {S : subalgebra R A} : S = ⊤ ↔ ∀ x : A, x ∈ S := ⟨λ h x, by rw h; exact mem_top, λ h, by ext x; exact ⟨λ _, mem_top, λ _, h x⟩⟩ /-- `alg_hom` to `⊤ : subalgebra R A`. -/ def to_top : A →ₐ[R] (⊤ : subalgebra R A) := by refine_struct { to_fun := λ x, (⟨x, mem_top⟩ : (⊤ : subalgebra R A)) }; intros; refl end algebra section int variables (R : Type*) [ring R] /-- Reinterpret a `ring_hom` as a `ℤ`-algebra homomorphism. -/ def alg_hom_int {R : Type u} [comm_ring R] [algebra ℤ R] {S : Type v} [comm_ring S] [algebra ℤ S] (f : R →+* S) : R →ₐ[ℤ] S := { commutes' := λ i, show f _ = _, by simp, .. f } /-- CRing ⥤ ℤ-Alg -/ instance algebra_int : algebra ℤ R := { commutes' := λ x y, commute.cast_int_left _ _, smul_def' := λ _ _, gsmul_eq_mul _ _, .. int.cast_ring_hom R } variables {R} /-- A subring is a `ℤ`-subalgebra. -/ def subalgebra_of_subring (S : set R) [is_subring S] : subalgebra ℤ R := { carrier := S, range_le' := by { rintros _ ⟨i, rfl⟩, rw [ring_hom.eq_int_cast, ← gsmul_one], exact is_add_subgroup.gsmul_mem is_submonoid.one_mem } } @[simp] lemma mem_subalgebra_of_subring {x : R} {S : set R} [is_subring S] : x ∈ subalgebra_of_subring S ↔ x ∈ S := iff.rfl section span_int open submodule lemma span_int_eq_add_group_closure (s : set R) : ↑(span ℤ s) = add_group.closure s := set.subset.antisymm (λ x hx, span_induction hx (λ _, add_group.mem_closure) is_add_submonoid.zero_mem (λ a b ha hb, is_add_submonoid.add_mem ha hb) (λ n a ha, by { exact is_add_subgroup.gsmul_mem ha })) (add_group.closure_subset subset_span) @[simp] lemma span_int_eq (s : set R) [is_add_subgroup s] : (↑(span ℤ s) : set R) = s := by rw [span_int_eq_add_group_closure, add_group.closure_add_subgroup] end span_int end int section restrict_scalars /- In this section, we describe restriction of scalars: if `S` is an algebra over `R`, then `S`-modules are also `R`-modules. -/ variables (R : Type*) [comm_ring R] (S : Type*) [ring S] [algebra R S] (E : Type*) [add_comm_group E] [module S E] {F : Type*} [add_comm_group F] [module S F] /-- When `E` is a module over a ring `S`, and `S` is an algebra over `R`, then `E` inherits a module structure over `R`, called `module.restrict S R E`. Not registered as an instance as `S` can not be inferred. -/ def module.restrict_scalars : module R E := { smul := λc x, (algebra_map R S c) • x, one_smul := by simp, mul_smul := by simp [mul_smul], smul_add := by simp [smul_add], smul_zero := by simp [smul_zero], add_smul := by simp [add_smul], zero_smul := by simp [zero_smul] } variables {S E} local attribute [instance] module.restrict_scalars /-- The `R`-linear map induced by an `S`-linear map when `S` is an algebra over `R`. -/ def linear_map.restrict_scalars (f : E →ₗ[S] F) : E →ₗ[R] F := { to_fun := f.to_fun, add := λx y, f.map_add x y, smul := λc x, f.map_smul (algebra_map R S c) x } @[simp, norm_cast squash] lemma linear_map.coe_restrict_scalars_eq_coe (f : E →ₗ[S] F) : (f.restrict_scalars R : E → F) = f := rfl end restrict_scalars
c11a705b167e0af16f07a6aecf556f4c13d875fb
5d166a16ae129621cb54ca9dde86c275d7d2b483
/tests/lean/elab_error_recovery.lean
6af7671eb0100482e8d3eb88a78ae59d0ea341cf
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
437
lean
def half_baked : ℕ → ℕ | 3 := 2 -- type mismatches | 0 := 1 + "" -- placeholders | 5 := _ + 4 -- missing typeclass instances | 42 := if 2 ∈ 3 then 3 else _ -- exceptions during tactic evaluation | 7 := by do undefined -- nested elaboration errors | _ := begin exact [] end #print half_baked._main #reduce half_baked 3 #reduce half_baked 5 #eval half_baked 3 -- type errors in binders #check ∀ x : nat.zero, x = x
0713ca3c97a9da595045f0a508a9f8942d372f8f
7541ac8517945d0f903ff5397e13e2ccd7c10573
/src/category_theory/tactics/obviously.lean
163dc7d12bf9c25423dda2b31215c87f72a2c135
[]
no_license
ramonfmir/lean-category-theory
29b6bad9f62c2cdf7517a3135e5a12b340b4ed90
be516bcbc2dc21b99df2bcb8dde0d1e8de79c9ad
refs/heads/master
1,586,110,684,637
1,541,927,184,000
1,541,927,184,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
471
lean
import category_theory.natural_isomorphism import category_theory.products import category_theory.types import category_theory.fully_faithful import category_theory.yoneda import category_theory.limits.cones import tidy.tidy open category_theory @[suggest] def use_category_theory := `category_theory attribute [elim] full.preimage attribute [forward] faithful.injectivity attribute [search] yoneda.obj_map_id -- attribute [search] cone_morphism.w cocone_morphism.w
aef9d0aec33a06d22c588a9e5d8387dae0d2654d
302b541ac2e998a523ae04da7673fd0932ded126
/workspace/demo.lean
ff9f924b6494b243c94ab7d534960a544a720798
[]
no_license
mattweingarten/lambdapure
4aeff69e8e3b8e78ea3c0a2b9b61770ef5a689b1
f920a4ad78e6b1e3651f30bf8445c9105dfa03a8
refs/heads/master
1,680,665,168,790
1,618,420,180,000
1,618,420,180,000
310,816,264
2
1
null
null
null
null
UTF-8
Lean
false
false
205
lean
set_option trace.compiler.ir.init true def const := 1 def baz (x : Nat) := x def higherorder (f: Nat -> Nat ) (x: Nat) := f x def higherorder2 (f: Nat -> Nat -> Nat) (x:Nat) (y:Nat) := f x y
fc223a1594abaed9f63159d8523ab853c28be6b1
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/number_theory/sum_two_squares.lean
70dbb070207a3a3374ee8e09a0bcc926713cc9e6
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
822
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.zsqrtd.gaussian_int /-! # Sums of two squares Proof of Fermat's theorem on the sum of two squares. Every prime congruent to 1 mod 4 is the sum of two squares -/ open gaussian_int principal_ideal_ring namespace nat namespace prime /-- Fermat's theorem on the sum of two squares. Every prime congruent to 1 mod 4 is the sum of two squares -/ lemma sum_two_squares (p : ℕ) [hp : _root_.fact p.prime] (hp1 : p % 4 = 1) : ∃ a b : ℕ, a ^ 2 + b ^ 2 = p := begin apply sum_two_squares_of_nat_prime_of_not_irreducible p, rw [principal_ideal_ring.irreducible_iff_prime, prime_iff_mod_four_eq_three_of_nat_prime p, hp1], norm_num end end prime end nat
cdcde0b6116a822c73d187802a5ce3def1a10bd8
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/system/io_auto.lean
98a250acc89a1133b8db1bb47d26847bc0a15338
[]
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
6,931
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Luke Nelson, Jared Roesch and Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.Lean3Lib.system.io_interface universes u_1 namespace Mathlib /- The following constants have a builtin implementation -/ axiom io_core : Type → Type → Type /- Auxiliary definition used in the builtin implementation of monad_io_random_impl -/ def io_rand_nat : std_gen → ℕ → ℕ → ℕ × std_gen := rand_nat instance monad_io_impl : monad_io io_core instance monad_io_terminal_impl : monad_io_terminal io_core instance monad_io_net_system_impl : monad_io_net_system io_core instance monad_io_file_system_impl : monad_io_file_system io_core instance monad_io_environment_impl : monad_io_environment io_core instance monad_io_process_impl : monad_io_process io_core instance monad_io_random_impl : monad_io_random io_core protected instance io_core_is_monad (e : Type) : Monad (io_core e) := Mathlib.monad_io_is_monad io_core e protected instance io_core_is_monad_fail : monad_fail (io_core io.error) := Mathlib.monad_io_is_monad_fail io_core protected instance io_core_is_alternative : alternative (io_core io.error) := Mathlib.monad_io_is_alternative io_core def io (α : Type) := io_core sorry α namespace io /- Remark: the following definitions can be generalized and defined for any (m : Type -> Type -> Type) that implements the required type classes. However, the generalized versions are very inconvenient to use, (example: `#eval io.put_str "hello world"` does not work because we don't have enough information to infer `m`.). -/ def iterate {e : Type} {α : Type} (a : α) (f : α → io_core e (Option α)) : io_core e α := monad_io.iterate e α a f def forever {e : Type} (a : io_core e Unit) : io_core e Unit := iterate Unit.unit fun (_x : Unit) => a >> return (some Unit.unit) -- TODO(Leo): delete after we merge #1881 def catch {e₁ : Type} {e₂ : Type} {α : Type} (a : io_core e₁ α) (b : e₁ → io_core e₂ α) : io_core e₂ α := monad_io.catch e₁ e₂ α a b def finally {α : Type} {e : Type} (a : io_core e α) (cleanup : io_core e Unit) : io_core e α := do let res ← catch (sum.inr <$> a) (return ∘ sum.inl) cleanup sorry protected def fail {α : Type} (s : string) : io α := monad_io.fail error α (error.other s) def put_str : string → io Unit := monad_io_terminal.put_str def put_str_ln (s : string) : io Unit := put_str s >> put_str (string.str string.empty (char.of_nat (bit0 (bit1 (bit0 1))))) def get_line : io string := monad_io_terminal.get_line def cmdline_args : io (List string) := return (monad_io_terminal.cmdline_args io_core) def print {α : Type u_1} [has_to_string α] (s : α) : io Unit := function.comp put_str to_string s def print_ln {α : Type u_1} [has_to_string α] (s : α) : io Unit := print s >> put_str (string.str string.empty (char.of_nat (bit0 (bit1 (bit0 1))))) def handle := monad_io.handle io_core def mk_file_handle (s : string) (m : mode) (bin : optParam Bool false) : io handle := monad_io_file_system.mk_file_handle s m bin def stdin : io handle := monad_io_file_system.stdin def stderr : io handle := monad_io_file_system.stderr def stdout : io handle := monad_io_file_system.stdout namespace env def get (env_var : string) : io (Option string) := monad_io_environment.get_env env_var /-- get the current working directory -/ def get_cwd : io string := monad_io_environment.get_cwd /-- set the current working directory -/ def set_cwd (cwd : string) : io Unit := monad_io_environment.set_cwd cwd end env namespace net def socket := monad_io_net_system.socket io_core def listen : string → ℕ → io socket := monad_io_net_system.listen def accept : socket → io socket := monad_io_net_system.accept def connect : string → io socket := monad_io_net_system.connect def recv : socket → ℕ → io char_buffer := monad_io_net_system.recv def send : socket → char_buffer → io Unit := monad_io_net_system.send def close : socket → io Unit := monad_io_net_system.close end net namespace fs def is_eof : handle → io Bool := monad_io_file_system.is_eof def flush : handle → io Unit := monad_io_file_system.flush def close : handle → io Unit := monad_io_file_system.close def read : handle → ℕ → io char_buffer := monad_io_file_system.read def write : handle → char_buffer → io Unit := monad_io_file_system.write def get_char (h : handle) : io char := sorry def get_line : handle → io char_buffer := monad_io_file_system.get_line def put_char (h : handle) (c : char) : io Unit := write h (buffer.push_back mk_buffer c) def put_str (h : handle) (s : string) : io Unit := write h (buffer.append_string mk_buffer s) def put_str_ln (h : handle) (s : string) : io Unit := put_str h s >> put_str h (string.str string.empty (char.of_nat (bit0 (bit1 (bit0 1))))) def read_to_end (h : handle) : io char_buffer := iterate mk_buffer fun (r : char_buffer) => do let done ← is_eof h ite (↥done) (return none) (do let c ← read h (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 1)))))))))) return (some (r ++ c))) def read_file (s : string) (bin : optParam Bool false) : io char_buffer := do let h ← mk_file_handle s mode.read bin read_to_end h def file_exists : string → io Bool := monad_io_file_system.file_exists def dir_exists : string → io Bool := monad_io_file_system.dir_exists def remove : string → io Unit := monad_io_file_system.remove def rename : string → string → io Unit := monad_io_file_system.rename def mkdir (path : string) (recursive : optParam Bool false) : io Bool := monad_io_file_system.mkdir path recursive def rmdir : string → io Bool := monad_io_file_system.rmdir end fs namespace proc def child := monad_io_process.child io_core def child.stdin : child → handle := monad_io_process.stdin def child.stdout : child → handle := monad_io_process.stdout def child.stderr : child → handle := monad_io_process.stderr def spawn (p : process.spawn_args) : io child := monad_io_process.spawn p def wait (c : child) : io ℕ := monad_io_process.wait c def sleep (n : ℕ) : io Unit := monad_io_process.sleep n end proc def set_rand_gen : std_gen → io Unit := monad_io_random.set_rand_gen def rand (lo : optParam ℕ (prod.fst std_range)) (hi : optParam ℕ (prod.snd std_range)) : io ℕ := monad_io_random.rand lo hi end io /-- Run the external process specified by `args`. The process will run to completion with its output captured by a pipe, and read into `string` which is then returned. -/ def io.cmd (args : io.process.spawn_args) : io string := sorry end Mathlib
6af0782a84fafa8b76af630e0279916cd108e8cb
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/level_bug2.lean
47121f0a35da47b4e79498cfe40293648db96c97
[ "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
149
lean
definition f (a : Type) := Π r : Type, (a → r) → r definition blah2 {a : Type} {r : Type} (sa : f a) (k : a → r) : sa r k = sa r k := rfl
16da9d49ebcf988e500b44ca8be13d15b8e02727
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/bool/default_auto.lean
771edf5947172cf3276fc6b0af95a2db1cd056d2
[]
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
309
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.data.bool.basic import Mathlib.Lean3Lib.init.data.bool.lemmas namespace Mathlib end Mathlib
90eaf297ff00487ec87de22c60d86f228e0f3283
2cf781335f4a6706b7452ab07ce323201e2e101f
/lean/common.lean
33da00cda570c78339096dd2987d41ad32570883
[ "Apache-2.0" ]
permissive
simonjwinwood/reopt-vcg
697cdd5e68366b5aa3298845eebc34fc97ccfbe2
6aca24e759bff4f2230bb58270bac6746c13665e
refs/heads/master
1,586,353,878,347
1,549,667,148,000
1,549,667,148,000
159,409,828
0
0
null
1,543,358,444,000
1,543,358,444,000
null
UTF-8
Lean
false
false
25,254
lean
import .coe1 import .tactic def unlines : list string → string := list.foldr (λx r, x ++ "\n" ++ r) "" -- Library for buidling s expressions namespace sexp def app (s:string) (l:list string) := "(" ++ s ++ list.foldr (λx r, " " ++ x ++ r) ")" l -- Pretty print def from_list : list string → string | [] := "()" | (s::l) := app s l def indent : string → string | s := " " ++ s end sexp def paren_if : bool → string → string | tt s := "(" ++ s ++ ")" | ff s := s ------------------------------------------------------------------------ -- Coercisions namespace mc_semantics ------------------------------------------------------------------------ -- arg_index @[reducible] def arg_index := nat def arg_index.pp (idx:arg_index) : string := sexp.app "arg" [idx.repr] ------------------------------------------------------------------------ -- nat_expr inductive nat_expr : Type | lit : nat → nat_expr | var : arg_index → nat_expr | add : nat_expr → nat_expr → nat_expr | sub : nat_expr → nat_expr → nat_expr | mul : nat_expr → nat_expr → nat_expr -- div x y is floor (x / y) | div : nat_expr → nat_expr → nat_expr namespace nat_expr protected def zero : nat_expr := lit 0 protected def one : nat_expr := lit 1 protected def do_add : nat_expr → nat_expr → nat_expr | (lit x) (lit y) := lit (x+y) | x y := add x y protected def do_sub : nat_expr → nat_expr → nat_expr | (lit x) (lit y) := lit (x-y) | x y := sub x y protected def do_mul : nat_expr → nat_expr → nat_expr | (lit x) (lit y) := lit (x*y) | x y := mul x y protected def do_div : nat_expr → nat_expr → nat_expr | (lit x) (lit y) := lit (x/y) | x y := div x y instance : has_zero nat_expr := ⟨nat_expr.zero⟩ instance : has_one nat_expr := ⟨nat_expr.one⟩ instance : has_add nat_expr := ⟨nat_expr.do_add⟩ instance : has_sub nat_expr := ⟨nat_expr.do_sub⟩ instance : has_mul nat_expr := ⟨nat_expr.do_mul⟩ instance : has_div nat_expr := ⟨nat_expr.do_div⟩ protected def pp : nat_expr → string | (lit x) := x.repr | (var x) := x.pp | (add x y) := sexp.app "addNat" [x.pp, y.pp] | (sub x y) := sexp.app "subNat" [x.pp, y.pp] | (mul x y) := sexp.app "mulNat" [x.pp, y.pp] | (div x y) := sexp.app "divNat" [x.pp, y.pp] instance : has_repr nat_expr := ⟨nat_expr.pp⟩ instance nat_coe_nat_expr : has_coe ℕ nat_expr := ⟨λx, lit x⟩ end nat_expr ------------------------------------------------------------------------ -- one_of inductive one_of (l:list ℕ) : Type | var{} : arg_index → one_of namespace one_of def to_nat_expr {l:list ℕ} : one_of l → nat_expr | (one_of.var i) := nat_expr.var i protected def pp {l:list ℕ} (x:one_of l) := x.to_nat_expr.pp instance (l:list ℕ) : has_coe (one_of l) nat_expr := ⟨ one_of.to_nat_expr ⟩ end one_of local notation ℕ := nat_expr inductive type | bv (w:ℕ) : type | bit : type | float : type | double : type | x86_80 : type -- A function from arg to res | fn (arg:type) (res:type) : type namespace type protected def pp' : Π(in_fun:bool), type → string | _ (bv w) := sexp.app "bv" [w.pp] | _ bit := "bit" | _ float := "float" | _ double := "double" | _ x86_80 := "x86_80" | in_fun (fn a r) := if in_fun then a.pp' ff ++ " " ++ r.pp' tt else sexp.app "fun" [a.pp' ff, r.pp' tt] protected def pp : type → string := type.pp' ff end type end mc_semantics ------------------------------------------------------------------------ -- X86 namespace x86 open mc_semantics open mc_semantics.type ------------------------------------------------------------------------ -- type local notation ℕ := nat_expr -- Denotes the type of a register. inductive gpreg_type : Type | reg8l : gpreg_type | reg16 : gpreg_type | reg32 : gpreg_type | reg64 : gpreg_type namespace gpreg_type @[reducible] def width : gpreg_type → ℕ | reg8l := 8 | reg16 := 16 | reg32 := 32 | reg64 := 64 end gpreg_type -- Type for x86 registers inductive reg : type → Type | concrete_gpreg (idx:fin 16) (tp:gpreg_type) : reg (bv (tp.width)) | concrete_flagreg (idx:fin 32) : reg bit namespace reg protected def gpreg_prefix (x:fin 16) : string := match x.val with | 0 := "a" | v := "r" ++ v.repr end protected def r8l_names : list string := [ "al", "cl", "dl", "bl" , "spl", "bpl", "sil", "dil" , "r8b" , "r9b" , "r10b", "r11b" , "r12b", "r13b", "r14b", "r15b" ] protected def r16_names : list string := [ "ax", "cx", "dx", "bx" , "sp", "bp", "si", "di" , "r8w" , "r9w" , "r10w", "r11w" , "r12w", "r13w", "r14w", "r15w" ] protected def r32_names : list string := [ "eax", "ecx", "edx", "ebx" , "esp", "ebp", "esi", "edi" , "r8d" , "r9d" , "r10d", "r11d" , "r12d", "r13d", "r14d", "r15d" ] protected def r64_names : list string := [ "rax", "rcx", "rdx", "rbx" , "rsp", "rbp", "rsi", "rdi" , "r8" , "r9" , "r10", "r11" , "r12", "r13", "r14", "r15" ] protected def flag_names : list string := [ "cf", "RESERVED_1", "pf", "RESERVED_3", "af", "RESERVED_5", "zf", "sf" , "tf", "if", "df", "of", "iopl1", "iopl2", "nt", "RESERVED_15" , "rf", "vm", "ac", "vif", "vip", "id" ] protected def repr : Π{tp:type}, reg tp → string | ._ (concrete_gpreg idx tp) := "$" ++ match tp with | gpreg_type.reg8l := list.nth_le reg.r8l_names idx.val idx.is_lt | gpreg_type.reg16 := list.nth_le reg.r16_names idx.val idx.is_lt | gpreg_type.reg32 := list.nth_le reg.r32_names idx.val idx.is_lt | gpreg_type.reg64 := list.nth_le reg.r64_names idx.val idx.is_lt end | ._ (concrete_flagreg idx) := "$" ++ match list.nth reg.flag_names idx.val with | (option.some nm) := nm | option.none := "REVERSED_" ++ idx.val.repr end end reg -- Denotes an address. inductive addr (tp:type) : Type | arg {} (idx: arg_index) : addr namespace addr protected def repr {tp:type} : addr tp → string | (arg idx) := idx.pp end addr --- Expressions that may appear on the left-hand side of an assignment. inductive lhs : type → Type | reg {tp:type} (r:reg tp) : lhs tp -- A value that must be an address. | addr {tp:type} (a:addr tp) : lhs tp -- An argument that may be either a register or address. | arg (idx:arg_index) (tp:type) : lhs tp -- ST reg with the offset relative to the current stack top value. | streg (idx : fin 8) : lhs x86_80 namespace lhs -- Pretty printer for lhs protected def repr : Π {tp:type}, lhs tp → string | _ (reg r) := r.repr | ._ (addr a) := a.repr | _ (arg idx tp) := idx.pp | ._ (streg idx) := "st" ++ idx.val.repr end lhs section def reg8l (i:fin 16) := lhs.reg $ reg.concrete_gpreg i gpreg_type.reg8l def reg8h (i:fin 16) := lhs.reg $ reg.concrete_gpreg (16+i) gpreg_type.reg8l def al := reg8l 0 def cl := reg8l 1 def dl := reg8l 2 def bl := reg8l 3 def spl := reg8l 4 def bpl := reg8l 5 def sil := reg8l 6 def dil := reg8l 7 def ah := reg8h 0 def reg16 (i:fin 16) := lhs.reg $ reg.concrete_gpreg i gpreg_type.reg16 def ax := reg16 0 def cx := reg16 1 def dx := reg16 2 def bx := reg16 3 def reg32 (i:fin 16) := lhs.reg $ reg.concrete_gpreg i gpreg_type.reg32 def eax := reg32 0 def ecx := reg32 1 def edx := reg32 2 def ebx := reg32 3 def reg64 (i:fin 16) := lhs.reg $ reg.concrete_gpreg i gpreg_type.reg64 def rax := reg64 0 def rcx := reg64 1 def rdx := reg64 2 def rbx := reg64 3 def rsp := reg64 4 def rbp := reg64 5 def rsi := reg64 6 def rdi := reg64 7 def r8 := reg64 8 def r9 := reg64 9 def r10 := reg64 10 def r11 := reg64 11 def r12 := reg64 12 def r13 := reg64 13 def r14 := reg64 14 def r15 := reg64 15 def flagreg (i:fin 32) := lhs.reg $ reg.concrete_flagreg i def cf := flagreg 0 def pf := flagreg 2 def af := flagreg 4 def zf := flagreg 6 def sf := flagreg 7 def tf := flagreg 8 def if' := flagreg 9 def df := flagreg 10 def of := flagreg 11 def st0 : lhs x86_80 := lhs.streg 0 end local infixr `.→`:30 := fn -- This denotes primitive operations that are part of the semantics. inductive prim : type → Type -- `(add i)` returns the sum of two i-bit numbers. | add (i:ℕ) : prim (bv i .→ bv i .→ bv i) -- `(adc i)` returns the sum of two i-bit numbers and a carry bit. | adc (i:ℕ) : prim (bv i .→ bv i .→ bit .→ bv i) -- `(mul i)` returns the product of two i-bit numbers. | mul (i:ℕ) : prim (bv i .→ bv i .→ bv i) -- `(quot i)` returns the quotient of two i-bit numbers. | quot (i:ℕ) : prim (bv i .→ bv i .→ bv i) -- `(rem i)` returns the remainder of two i-bit numbers. | rem (i:ℕ) : prim (bv i .→ bv i .→ bv i) -- `(squot i)` returns the signed quotient of two i-bit numbers. | squot (i:ℕ) : prim (bv i .→ bv i .→ bv i) -- `(srem i)` returns the signed remainder of two i-bit numbers. | srem (i:ℕ) : prim (bv i .→ bv i .→ bv i) -- `(slice w u l)` takes bits `u` through `l` out of a `w`-bit number. | slice (w:ℕ) (u:ℕ) (l:ℕ) : prim (bv w .→ bv (u+1-l)) -- `(sext i o)` sign extends an `i`-bit number to a `o`-bit number. | sext (i:ℕ) (o:ℕ) : prim (bv i .→ bv o) -- `(uext i o)` unsigned extension of an `i`-bit number to a `o`-bit number. | uext (i:ℕ) (o:ℕ) : prim (bv i .→ bv o) -- `(trunc i o)` truncates an `i`-bit number to a `o`-bit number. | trunc (i:ℕ) (o:ℕ) : prim (bv i .→ bv o) -- `(bsf i)` returns the index of least-significant bit that is 1. | bsf (i:ℕ) : prim (bv i .→ bv i) -- `(bsr i)` returns the index of most-significant bit that is 1. | bsr (i:ℕ) : prim (bv i .→ bv i) -- `(bswap i)` reverses the bytes in the bitvector. | bswap (i:ℕ) : prim (bv i .→ bv i) -- `zero` is the zero bit | zero : prim bit -- `one` is the one bit | one : prim bit -- `(eq tp)` returns `true` if two values are equal. | eq (tp:type) : prim (tp .→ tp .→ bit) -- `(neq tp)` returns `true` if two values are not equal. | neq (tp:type) : prim (tp .→ tp .→ bit) -- `(neg tp)` Two's Complement negation. | neg (i:ℕ) : prim (bv i .→ bv i) -- `x87_fadd` adds two extended precision values using the flags in the x87 register. | x87_fadd : prim (x86_80 .→ x86_80 .→ x86_80) -- `float_to_x86_80` converts a float to an extended precision number (lossless) | float_to_x86_80 : prim (float .→ x86_80) -- `double_to_x86_80` converts a double to an extended precision number (lossless) | double_to_x86_80 : prim (double .→ x86_80) -- `bv_to_x86_80` converts a bitvector to an extended precision number (lossless) | bv_to_x86_80 (w : one_of [16,32]) : prim (bv w .→ x86_80) -- `bvnat` constructs a bit vector from a natural number. | bvnat (w:ℕ) : ℕ → prim (bv w) -- `(bvadd i)` adds two i-bit bitvectors. | bvadd (i:ℕ) : prim (bv i .→ bv i .→ bv i) -- `(bvsub i)` substracts two i-bit bitvectors. | bvsub (i:ℕ) : prim (bv i .→ bv i .→ bv i) -- `(ssbb_overflows i)` true if signed sub overflows, the bit -- is a borrow bit. | ssbb_overflows (i:ℕ) : prim (bv i .→ bv i .→ bit .→ bit) -- `(usbb_overflows i)` true if unsigned sub overflows, -- the bit is a borrow bit. | usbb_overflows (i:ℕ) : prim (bv i .→ bv i .→ bit .→ bit) | uadc_overflows (i:ℕ) : prim (bv i .→ bv i .→ bit .→ bit) | sadc_overflows (i:ℕ) : prim (bv i .→ bv i .→ bit .→ bit) | and (i:ℕ) : prim (bv i .→ bv i .→ bv i) | or (i:ℕ) : prim (bv i .→ bv i .→ bv i) | xor (i:ℕ) : prim (bv i .→ bv i .→ bv i) | shl (i:ℕ) : prim (bv i .→ bv i .→ bv i) -- `(bvbit i)` interprets the second argument as a bit index and returns -- that bit from the first argument. | bvbit (i:ℕ) : prim (bv i .→ bv i .→ bit) | complement (i:ℕ) : prim (bv i .→ bv i) | bvcat (i:ℕ) : prim (bv i .→ bv i .→ bv (2*i)) | bv_least_nibble (i:ℕ) : prim (bv i .→ bv 4) | msb (i:ℕ) : prim (bv i .→ bit) | least_byte (i:ℕ) : prim (bv i .→ bv 8) | even_parity (i:ℕ) : prim (bv i .→ bit) namespace prim def pp : Π{tp:type}, prim tp → string | ._ (add i) := "add " ++ i.pp | ._ (adc i) := "adc " ++ i.pp | ._ (mul i) := "mul " ++ i.pp | ._ (quot i) := "quot " ++ i.pp | ._ (rem i) := "rem " ++ i.pp | ._ (squot i) := "squot " ++ i.pp | ._ (srem i) := "srem " ++ i.pp | ._ (slice w u l) := "slice " ++ w.pp ++ " " ++ u.pp ++ " " ++ l.pp | ._ (sext i o) := "sext " ++ i.pp ++ " " ++ o.pp | ._ (uext i o) := "uext " ++ i.pp ++ " " ++ o.pp | ._ (trunc i o) := "trunc " ++ i.pp ++ " " ++ o.pp | ._ (bsf i) := "bsf " ++ i.pp | ._ (bsr i) := "bsr " ++ i.pp | ._ (bswap i) := "bswap " ++ i.pp | ._ zero := sexp.app "bit" ["0"] | ._ one := sexp.app "bit" ["1"] | ._ (eq tp) := "eq " ++ tp.pp | ._ (neq tp) := "neq " ++ tp.pp | ._ (neg tp) := "neg " ++ tp.pp | ._ x87_fadd := "x87_fadd" | ._ float_to_x86_80 := "float_to_x86_80" | ._ double_to_x86_80 := "double_to_X86_80" | ._ (bv_to_x86_80 w) := "sext " ++ w.pp | ._ (bvnat w n) := sexp.app "bvnat" [w.pp, n.pp] | ._ (bvadd i) := "bvadd " ++ i.pp | ._ (bvsub i) := "bvsub " ++ i.pp | ._ (ssbb_overflows i) := "ssbb_overflows " ++ i.pp | ._ (usbb_overflows i) := "usbb_overflows " ++ i.pp | ._ (uadc_overflows i) := "uadc_overflows " ++ i.pp | ._ (sadc_overflows i) := "sadc_overflows " ++ i.pp | ._ (and i) := "and " ++ i.pp | ._ (or i) := "or " ++ i.pp | ._ (xor i) := "xor " ++ i.pp | ._ (shl i) := "shl " ++ i.pp | ._ (bvbit i) := "bvbit " ++ i.pp | ._ (complement i) := "complement " ++ i.pp | ._ (bvcat i) := "bvcat " ++ i.pp | ._ (bv_least_nibble i) := "bv_least_nibble" ++ i.pp | ._ (msb i) := "msb " ++ i.pp | ._ (least_byte i) := "least_byte " ++ i.pp | ._ (even_parity i) := "even_parity " ++ i.pp end prim -- Type for expressions. inductive expression : type → Type -- Create a expression our of a primitive | primitive {rtp:type} (o:prim rtp) : expression rtp -- Apply a function to an argument. | app {rtp:type} {tp:type} (f : expression (type.fn tp rtp)) (a : expression tp) : expression rtp -- Get the expression associated with the assignable expression. | get {tp:type} (l:lhs tp) : expression tp -- Return the expression in the local variable at the given index. | get_local (idx:ℕ) (tp:type) : expression tp namespace expression instance (rtp:type) : has_coe (prim rtp) (expression rtp) := ⟨expression.primitive⟩ instance (a:type) (f:type) : has_coe_to_fun (expression (type.fn a f)) := { F := λ_, Π(y:expression a), expression f , coe := app } def bvadd : Π{w:ℕ}, expression (bv w) → expression (bv w) → expression (bv w) | ._ (primitive (prim.bvnat ._ n)) (primitive (prim.bvnat w m)) := prim.bvnat w (n + m) | i x y := prim.bvadd i x y def bvsub : Π{w:ℕ}, expression (bv w) → expression (bv w) → expression (bv w) | ._ (primitive (prim.bvnat ._ n)) (primitive (prim.bvnat w m)) := prim.bvnat w (n - m) | i x y := prim.bvsub i x y def bvneg : Π{w:ℕ}, expression (bv w) → expression (bv w) | _ x := app (primitive (prim.neg _)) x instance (w:ℕ) : has_zero (expression (bv w)) := ⟨prim.bvnat w 0⟩ instance (w:ℕ) : has_one (expression (bv w)) := ⟨prim.bvnat w 1⟩ instance (w:ℕ) : has_add (expression (bv w)) := ⟨bvadd⟩ instance (w:ℕ) : has_sub (expression (bv w)) := ⟨bvsub⟩ instance (w:ℕ) : has_neg (expression (bv w)) := ⟨bvneg⟩ def adc {w:ℕ} (x y : expression (bv w)) (b : expression bit) : expression (bv w) := prim.adc w x y b def bswap {w:ℕ} (v : expression (bv w)) : expression (bv w) := prim.bswap w v -- TODO: quot should probably be an action to emulate generating an interrupt def quot {w:ℕ} (x y : expression (bv w)) : expression (bv w) := prim.quot w x y def rem {w:ℕ} (x y : expression (bv w)) : expression (bv w) := prim.rem w x y def signed_quot {w:ℕ} (x y : expression (bv w)) : expression (bv w) := prim.squot w x y def signed_rem {w:ℕ} (x y : expression (bv w)) : expression (bv w) := prim.srem w x y protected def is_app : Π{tp:type}, expression tp → bool | ._ (app _ _) := tt | _ _ := ff protected def pp_args : Π{tp:type}, expression tp → string | ._ (primitive o) := o.pp | ._ (app f a) := f.pp_args ++ " " ++ paren_if a.is_app a.pp_args | ._ (get lhs) := lhs.repr | ._ (get_local idx tp) := sexp.app "local" [idx.pp] protected def pp {tp:type} (v:expression tp) := paren_if v.is_app v.pp_args instance (tp:type) : has_repr (expression tp) := ⟨expression.pp⟩ instance addr_is_expression (tp:type) : has_coe (addr tp) (expression tp) := ⟨ expression.get ∘ lhs.addr ⟩ instance type_is_sort : has_coe_to_sort type := ⟨Type, expression⟩ instance all_lhs_is_expression : has_coe1 lhs expression := ⟨λ_, expression.get⟩ instance lhs_is_expression (tp:type) : has_coe (lhs tp) (expression tp) := ⟨expression.get⟩ end expression -- Operations on expressions def slice {w:nat_expr} (x:expression (bv w)) (u:nat_expr) (l:nat_expr) : expression (bv (u+1-l)) := prim.slice w u l x def trunc {w:nat_expr} (x: bv w) (o:nat_expr) : bv o := prim.trunc w o x def bsf {w:nat_expr} (x: bv w) : bv w := prim.bsf w x def bsr {w:nat_expr} (x: bv w) : bv w := prim.bsr w x def sext {w:nat_expr} (x: bv w) (o:nat_expr) : bv o := prim.sext w o x def uext {w:nat_expr} (x: bv w) (o:nat_expr) : bv o := prim.uext w o x def neq {tp:type} (x y : tp) : bit := prim.neq tp x y def eq {tp:type} (x y : tp) : bit := prim.eq tp x y def one : bit := prim.one def zero : bit := prim.zero instance bv_has_mul (w:nat_expr) : has_mul (bv w) := ⟨λx y, prim.mul w x y⟩ -- Add two 80-bit numbers using the current x87 floating point control. def x87_fadd (x y : x86_80) : x86_80 := prim.x87_fadd x y instance float_extends_to_80 : has_coe float x86_80 := ⟨prim.float_to_x86_80⟩ instance double_extends_to_80 : has_coe double x86_80 := ⟨prim.double_to_x86_80⟩ -- These are lossless conversions. instance bv_to_x86_80 (w:one_of [16,32]) : has_coe (bv w) x86_80 := ⟨prim.bv_to_x86_80 w⟩ ------------------------------------------------------------------------ -- event -- These are a type of action that may have side effects, but do -- not return values. inductive event | syscall : event | unsupported (msg:string) : event | pop_x87_register_stack : event | call (addr: bv 64) : event | jmp (addr: bv 64) : event | ret : event | hlt : event | xchg {w : nat_expr} (addr1: bv w) (addr2: bv w) : event namespace event protected def pp : event → string | syscall := "(syscall)" | (unsupported msg) := "(unsupported " ++ msg ++ ")" | pop_x87_register_stack := "(pop_x87_register_stack)" | (call addr) := "(call " ++ addr.pp ++ ")" | (jmp addr) := "(jmp " ++ addr.pp ++ ")" | ret := "(ret)" | hlt := "(hlt)" | (xchg addr1 addr2) := "(xchg " ++ addr1.pp ++ " " ++ addr2.pp ++ ")" end event ------------------------------------------------------------------------ -- action -- Denotes updates to program state from register. inductive action | set {tp:type} (l:lhs tp) (v:expression tp) : action | local_def {tp:type} (idx:ℕ) (v:expression tp) : action | event (e:event) : action | mk_undef {tp:type} (l:lhs tp) : action namespace action protected def repr : action → string | (set l r) := sexp.app "set" [l.repr, r.pp] | (local_def idx v) := sexp.app "var" [idx.pp, v.pp] | (event e) := e.pp | (mk_undef v) := sexp.app "mk_undef" [v.repr] end action ------------------------------------------------------------------------ -- binding inductive binding | one_of : list nat → binding | lhs : type → binding | expression : type → binding namespace binding def pp : binding → string | (one_of l) := sexp.app "one_of" (nat.repr <$> l) | (lhs tp) := sexp.app "lhs" [tp.pp] | (expression tp) := sexp.app "expression" [tp.pp] end binding ------------------------------------------------------------------------ -- context structure context := (bindings : list binding) def context.length (c:context) : arg_index := c.bindings.length def context.add (b:binding) (ctx:context) : context := { bindings := b :: ctx.bindings } instance : has_insert binding context := ⟨context.add⟩ instance : has_emptyc context := ⟨{bindings := []}⟩ ------------------------------------------------------------------------ -- Patterns structure pattern := (context : context) (actions : list action) namespace pattern private def pp_bindings : nat → list binding → string | i [] := "" | i (b::r) := sexp.indent (sexp.indent (sexp.app "arg" [i.repr, b.pp] ++ "\n")) ++ pp_bindings (i+1) r private def pp_action (m:action) : string := sexp.indent (sexp.indent m.repr) protected def pp (p:pattern) : string := "(pattern\n" ++ pp_bindings 0 p.context.bindings.reverse ++ unlines (pp_action <$> p.actions) ++ sexp.indent ")" end pattern ------------------------------------------------------------------------ -- instruction structure instruction := (mnemonic:string) (patterns:list pattern) namespace instruction def repr (i:instruction) : string := "(instruction " ++ i.mnemonic ++ "\n" ++ unlines (sexp.indent <$> pattern.pp <$> i.patterns) ++ ")" instance : has_repr instruction := ⟨instruction.repr⟩ end instruction ------------------------------------------------------------------------ -- is_bound_var -- Class for types that may be used as arguments in defining semantics. class is_bound_var (tp:Type) := (to_binding{} : binding) (mk_arg{} : arg_index → tp) instance one_of_is_bound_var (range:list nat) : is_bound_var (one_of range) := { to_binding := binding.one_of range , mk_arg := one_of.var } instance lhs_is_bound_var (tp:type) : is_bound_var (lhs tp) := { to_binding := binding.lhs tp , mk_arg := λi, lhs.arg i tp } instance expression_is_bound_var (tp:type) : is_bound_var (expression tp) := { to_binding := binding.expression tp , mk_arg := λi, expression.get (lhs.arg i tp) } ------------------------------------------------------------------------ -- semantics structure semantics_state : Type := -- Actions seen so far in reverse order. (actions : list action) -- Number of local constants to use. (local_variable_count : ℕ) namespace semantics_state def init : semantics_state := { actions := [] , local_variable_count := 0 } end semantics_state structure semantics (α:Type) := (monad : state semantics_state α) instance : monad semantics := { pure := λ_ x, { monad := pure x } , bind := λ_ _ m h, { monad := m.monad >>= λv, (h v).monad } , map := λ_ _ f m, { monad := f <$> m.monad } } namespace semantics --- Get the index to use for the next local variable. protected def next_local_index : semantics ℕ := { monad := do s ← state_t.get, state_t.put {s with local_variable_count := s.local_variable_count + 1 }, return s.local_variable_count } --- Add an action to the list of actions. protected def add_action (e:action) : semantics unit := { monad := state_t.modify (λs, { s with actions := e :: s.actions}) } def record_event (e:event) : semantics unit := semantics.add_action (action.event e) -- Record that some code path is unsupported. def unsupported (msg:string) := record_event (event.unsupported msg) --- Set the expression of the left-hand side to the expression. def set {tp:type} (l:lhs tp) (v:expression tp) : semantics unit := semantics.add_action (action.set l v) --- Evaluate the given expression and return a local expression that will not mutate. def eval {tp : type} (v:expression tp) : semantics (expression tp) := do idx ← semantics.next_local_index, semantics.add_action (action.local_def idx v), return (expression.get_local idx tp) protected def run (m:semantics unit) : list action := do (m.monad.run semantics_state.init).snd.actions.reverse end semantics ------------------------------------------------------------------------ -- pattern_def -- Class for functions of form λ... -> semantics unit -- -- This is used to define patterns with lambdas to bind arguments. The context variable -- is needed so that we can infer how many variables have been bound outside of the -- current context. class pattern_def (ctx : context) (tp:Type) := { define{} : tp → pattern } instance semantics_is_pattern_def (ctx : context) : pattern_def ctx (semantics unit) := { define := λm, { context := ctx , actions := semantics.run m } } instance pi_is_pattern_def (tp:Type) [is_bound_var tp] (ctx:context) (β:tp → Type) [pattern_def (insert (is_bound_var.to_binding tp) ctx) (β (is_bound_var.mk_arg ctx.length))] : pattern_def ctx (Π(w: tp), β w) := { define := λf, do pattern_def.define (insert (is_bound_var.to_binding tp) ctx) (f (is_bound_var.mk_arg ctx.length)) } -- Contains a list of patten matches defined using a monadic syntax. def pattern_list : Type → Type := state (list pattern) instance pattern_list_is_monad : monad pattern_list := begin simp [pattern_list], apply_instance, end -- Record pattern in current instruction def mk_pattern {α:Type} [h : pattern_def ∅ α] (x:α) : pattern_list unit := do state_t.modify (list.cons (pattern_def.define ∅ x)) ------------------------------------------------------------------------ -- definst def definst (mnem:string) (pat: pattern_list unit) : instruction := { mnemonic := mnem , patterns := (pat.run []).snd.reverse } end x86
0ed9dcc3ad1b8700e838d9f5c221054a0b7b9ca4
4727251e0cd73359b15b664c3170e5d754078599
/src/order/order_iso_nat.lean
2fd69aadeb8e79b7c5e74aab89d2e080bcab4362
[ "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
9,335
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.nat.lattice import logic.denumerable import logic.function.iterate import order.hom.basic /-! # Relation embeddings from the naturals This file allows translation from monotone functions `ℕ → α` to order embeddings `ℕ ↪ α` and defines the limit value of an eventually-constant sequence. ## Main declarations * `nat_lt`/`nat_gt`: Make an order embedding `ℕ ↪ α` from an increasing/decreasing function `ℕ → α`. * `monotonic_sequence_limit`: The limit of an eventually-constant monotone sequence `ℕ →o α`. * `monotonic_sequence_limit_index`: The index of the first occurence of `monotonic_sequence_limit` in the sequence. -/ namespace rel_embedding variables {α : Type*} {r : α → α → Prop} [is_strict_order α r] /-- If `f` is a strictly `r`-increasing sequence, then this returns `f` as an order embedding. -/ def nat_lt (f : ℕ → α) (H : ∀ n : ℕ, r (f n) (f (n + 1))) : ((<) : ℕ → ℕ → Prop) ↪r r := of_monotone f $ nat.rel_of_forall_rel_succ_of_lt r H @[simp] lemma nat_lt_apply {f : ℕ → α} {H : ∀ n : ℕ, r (f n) (f (n + 1))} {n : ℕ} : nat_lt f H n = f n := rfl /-- If `f` is a strictly `r`-decreasing sequence, then this returns `f` as an order embedding. -/ def nat_gt (f : ℕ → α) (H : ∀ n : ℕ, r (f (n + 1)) (f n)) : ((>) : ℕ → ℕ → Prop) ↪r r := by haveI := is_strict_order.swap r; exact rel_embedding.swap (nat_lt f H) theorem well_founded_iff_no_descending_seq : well_founded r ↔ is_empty (((>) : ℕ → ℕ → Prop) ↪r r) := ⟨λ ⟨h⟩, ⟨λ ⟨f, o⟩, suffices ∀ a, acc r a → ∀ n, a ≠ f n, from this (f 0) (h _) 0 rfl, λ a ac, begin induction ac with a _ IH, rintro n rfl, exact IH (f (n+1)) (o.2 (nat.lt_succ_self _)) _ rfl end⟩, λ E, ⟨λ a, classical.by_contradiction $ λ na, let ⟨f, h⟩ := classical.axiom_of_choice $ show ∀ x : {a // ¬ acc r a}, ∃ y : {a // ¬ acc r a}, r y.1 x.1, from λ ⟨x, h⟩, classical.by_contradiction $ λ hn, h $ ⟨_, λ y h, classical.by_contradiction $ λ na, hn ⟨⟨y, na⟩, h⟩⟩ in E.elim' (nat_gt (λ n, (f^[n] ⟨a, na⟩).1) $ λ n, by { rw [function.iterate_succ'], apply h })⟩⟩ end rel_embedding namespace nat variables (s : set ℕ) [decidable_pred (∈ s)] [infinite s] /-- An order embedding from `ℕ` to itself with a specified range -/ def order_embedding_of_set : ℕ ↪o ℕ := (rel_embedding.order_embedding_of_lt_embedding (rel_embedding.nat_lt (nat.subtype.of_nat s) (λ n, nat.subtype.lt_succ_self _))).trans (order_embedding.subtype s) /-- `nat.subtype.of_nat` as an order isomorphism between `ℕ` and an infinite decidable subset. See also `nat.nth` for a version where the subset may be finite. -/ noncomputable def subtype.order_iso_of_nat : ℕ ≃o s := rel_iso.of_surjective (rel_embedding.order_embedding_of_lt_embedding (rel_embedding.nat_lt (nat.subtype.of_nat s) (λ n, nat.subtype.lt_succ_self _))) nat.subtype.of_nat_surjective variable {s} @[simp] lemma coe_order_embedding_of_set : ⇑(order_embedding_of_set s) = coe ∘ subtype.of_nat s := rfl lemma order_embedding_of_set_apply {n : ℕ} : order_embedding_of_set s n = subtype.of_nat s n := rfl @[simp] lemma subtype.order_iso_of_nat_apply {n : ℕ} : subtype.order_iso_of_nat s n = subtype.of_nat s n := by { simp [subtype.order_iso_of_nat] } variable (s) lemma order_embedding_of_set_range : set.range (nat.order_embedding_of_set s) = s := subtype.coe_comp_of_nat_range theorem exists_subseq_of_forall_mem_union {α : Type*} {s t : set α} (e : ℕ → α) (he : ∀ n, e n ∈ s ∪ t) : ∃ g : ℕ ↪o ℕ, (∀ n, e (g n) ∈ s) ∨ (∀ n, e (g n) ∈ t) := begin classical, have : infinite (e ⁻¹' s) ∨ infinite (e ⁻¹' t), by simp only [set.infinite_coe_iff, ← set.infinite_union, ← set.preimage_union, set.eq_univ_of_forall (λ n, set.mem_preimage.2 (he n)), set.infinite_univ], casesI this, exacts [⟨nat.order_embedding_of_set (e ⁻¹' s), or.inl $ λ n, (nat.subtype.of_nat (e ⁻¹' s) _).2⟩, ⟨nat.order_embedding_of_set (e ⁻¹' t), or.inr $ λ n, (nat.subtype.of_nat (e ⁻¹' t) _).2⟩] end end nat theorem exists_increasing_or_nonincreasing_subseq' {α : Type*} (r : α → α → Prop) (f : ℕ → α) : ∃ (g : ℕ ↪o ℕ), (∀ n : ℕ, r (f (g n)) (f (g (n + 1)))) ∨ (∀ m n : ℕ, m < n → ¬ r (f (g m)) (f (g n))) := begin classical, let bad : set ℕ := { m | ∀ n, m < n → ¬ r (f m) (f n) }, by_cases hbad : infinite bad, { haveI := hbad, refine ⟨nat.order_embedding_of_set bad, or.intro_right _ (λ m n mn, _)⟩, have h := set.mem_range_self m, rw nat.order_embedding_of_set_range bad at h, exact h _ ((order_embedding.lt_iff_lt _).2 mn) }, { rw [set.infinite_coe_iff, set.infinite, not_not] at hbad, obtain ⟨m, hm⟩ : ∃ m, ∀ n, m ≤ n → ¬ n ∈ bad, { by_cases he : hbad.to_finset.nonempty, { refine ⟨(hbad.to_finset.max' he).succ, λ n hn nbad, nat.not_succ_le_self _ (hn.trans (hbad.to_finset.le_max' n (hbad.mem_to_finset.2 nbad)))⟩ }, { exact ⟨0, λ n hn nbad, he ⟨n, hbad.mem_to_finset.2 nbad⟩⟩ } }, have h : ∀ (n : ℕ), ∃ (n' : ℕ), n < n' ∧ r (f (n + m)) (f (n' + m)), { intro n, have h := hm _ (le_add_of_nonneg_left n.zero_le), simp only [exists_prop, not_not, set.mem_set_of_eq, not_forall] at h, obtain ⟨n', hn1, hn2⟩ := h, obtain ⟨x, hpos, rfl⟩ := exists_pos_add_of_lt hn1, refine ⟨n + x, add_lt_add_left hpos n, _⟩, rw [add_assoc, add_comm x m, ← add_assoc], exact hn2 }, let g' : ℕ → ℕ := @nat.rec (λ _, ℕ) m (λ n gn, nat.find (h gn)), exact ⟨(rel_embedding.nat_lt (λ n, g' n + m) (λ n, nat.add_lt_add_right (nat.find_spec (h (g' n))).1 m)).order_embedding_of_lt_embedding, or.intro_left _ (λ n, (nat.find_spec (h (g' n))).2)⟩ } end /-- This is the infinitary Erdős–Szekeres theorem, and an important lemma in the usual proof of Bolzano-Weierstrass for `ℝ`. -/ theorem exists_increasing_or_nonincreasing_subseq {α : Type*} (r : α → α → Prop) [is_trans α r] (f : ℕ → α) : ∃ (g : ℕ ↪o ℕ), (∀ m n : ℕ, m < n → r (f (g m)) (f (g n))) ∨ (∀ m n : ℕ, m < n → ¬ r (f (g m)) (f (g n))) := begin obtain ⟨g, hr | hnr⟩ := exists_increasing_or_nonincreasing_subseq' r f, { refine ⟨g, or.intro_left _ (λ m n mn, _)⟩, obtain ⟨x, rfl⟩ := le_iff_exists_add.1 (nat.succ_le_iff.2 mn), induction x with x ih, { apply hr }, { apply is_trans.trans _ _ _ _ (hr _), exact ih (lt_of_lt_of_le m.lt_succ_self (nat.le_add_right _ _)) } }, { exact ⟨g, or.intro_right _ hnr⟩ } end /-- The "monotone chain condition" below is sometimes a convenient form of well foundedness. -/ lemma well_founded.monotone_chain_condition (α : Type*) [partial_order α] : well_founded ((>) : α → α → Prop) ↔ ∀ (a : ℕ →o α), ∃ n, ∀ m, n ≤ m → a n = a m := begin split; intros h, { rw well_founded.well_founded_iff_has_max' at h, intros a, have hne : (set.range a).nonempty, { use a 0, simp, }, obtain ⟨x, ⟨n, hn⟩, range_bounded⟩ := h _ hne, use n, intros m hm, rw ← hn at range_bounded, symmetry, apply range_bounded (a m) (set.mem_range_self _) (a.monotone hm), }, { rw rel_embedding.well_founded_iff_no_descending_seq, refine ⟨λ a, _⟩, obtain ⟨n, hn⟩ := h (a.swap : ((<) : ℕ → ℕ → Prop) →r ((<) : α → α → Prop)).to_order_hom, exact n.succ_ne_self.symm (rel_embedding.to_order_hom_injective _ (hn _ n.le_succ)), }, end /-- Given an eventually-constant monotone sequence `a₀ ≤ a₁ ≤ a₂ ≤ ...` in a partially-ordered type, `monotonic_sequence_limit_index a` is the least natural number `n` for which `aₙ` reaches the constant value. For sequences that are not eventually constant, `monotonic_sequence_limit_index a` is defined, but is a junk value. -/ noncomputable def monotonic_sequence_limit_index {α : Type*} [preorder α] (a : ℕ →o α) : ℕ := Inf { n | ∀ m, n ≤ m → a n = a m } /-- The constant value of an eventually-constant monotone sequence `a₀ ≤ a₁ ≤ a₂ ≤ ...` in a partially-ordered type. -/ noncomputable def monotonic_sequence_limit {α : Type*} [preorder α] (a : ℕ →o α) := a (monotonic_sequence_limit_index a) lemma well_founded.supr_eq_monotonic_sequence_limit {α : Type*} [complete_lattice α] (h : well_founded ((>) : α → α → Prop)) (a : ℕ →o α) : (⨆ m, a m) = monotonic_sequence_limit a := begin suffices : (⨆ (m : ℕ), a m) ≤ monotonic_sequence_limit a, { exact le_antisymm this (le_supr a _), }, apply supr_le, intros m, by_cases hm : m ≤ monotonic_sequence_limit_index a, { exact a.monotone hm, }, { replace hm := le_of_not_le hm, let S := { n | ∀ m, n ≤ m → a n = a m }, have hInf : Inf S ∈ S, { refine nat.Inf_mem _, rw well_founded.monotone_chain_condition at h, exact h a, }, change Inf S ≤ m at hm, change a m ≤ a (Inf S), rw hInf m hm, }, end
246c47ae41cbeaf399a20a1ae750723fba2624ad
351a46035517d2a1985619b8cabdf263754d343a
/src/ch18.lean
6c08a5c6d2dd150c9deb6d36a25987b4f66404bc
[]
no_license
kaychaks/logic_proof
accc212517b613caca92c10db77e6aaf6b7ccfbc
90f3bf0acbabf558ba2f82dee968255d8bfe2de1
refs/heads/master
1,587,001,734,509
1,548,235,051,000
1,548,235,051,000
165,186,786
0
0
null
null
null
null
UTF-8
Lean
false
false
3,126
lean
open nat namespace hidden theorem add_distrib (m n k: nat) : m * (n + k) = m * n + m * k := nat.rec_on k (show m * (n + 0) = m * n + m * 0, by rw [mul_zero , add_zero, add_zero]) (assume k, assume ih : m * (n + k) = m * n + m * k, show m * (n + succ k) = m * n + m * succ k, from calc m * (n + succ k) = m * succ (n + k) : by rw add_succ ... = m * (n + k) + m : by rw mul_succ ... = m * n + m * k + m : by rw ih ... = m * n + (m * k + m) : by rw add_assoc ... = m * n + m * succ k : by rw mul_succ ) theorem zero_mul (n : nat) : 0 * n = 0 := nat.rec_on n (show 0 * 0 = 0, from rfl) (assume n, assume ih : 0 * n = 0, show 0 * succ n = 0, from calc 0 * succ n = 0 * n + 0 : by rw mul_succ ... = 0 + 0 : by rw ih ... = 0 : by rw zero_add) theorem one_mul (n : nat) : 1 * n = n := nat.rec_on n (show 1 * 0 = 0, by rw mul_zero) (assume n, assume ih: 1 * n = n, show 1 * succ n = succ n, from calc 1 * succ n = 1 * n + 1 : by rw mul_succ ... = n + 1 : by rw ih ... = succ n : rfl) theorem mul_assoc (m n k : nat) : m * (n * k) = (m * n) * k := nat.rec_on k (show m * (n * 0) = (m * n) * 0, by rw [mul_zero, mul_zero, mul_zero]) (assume k, assume ih : m * (n * k) = (m * n) * k, show m * (n * succ k) = (m * n) * succ k, from calc m * (n * succ k) = m * (n * k + n) : by rw mul_succ ... = m * (n * k) + m * n : by rw add_distrib ... = (m * n) * k + m * n : by rw ih ... = (m * n) * succ k : by rw mul_succ) theorem mul_comm (m n : nat) : m * n = n * m := nat.rec_on n (show m * 0 = 0 * m, by rw [zero_mul,mul_zero]) (assume n, assume ih: m * n = n * m, show m * succ n = succ n * m, from calc m * succ n = m * n + m : by rw mul_succ ... = n * m + m : by rw ih ... = succ n * m : by rw succ_mul) -- END end hidden open nat namespace hidden -- BEGIN theorem T1 : ∀ m n : nat, m > n → (m = n + 1) ∨ (m > n + 1) := assume m n, assume h, have h1: succ n ≤ m, from succ_le_of_lt h, have h2 : n + 1 < m ∨ n + 1 = m, from iff.elim_left le_iff_lt_or_eq h1, or.elim h2 (assume : n + 1 < m, show m = n + 1 ∨ m > n + 1, from or.inr this) (assume : n + 1 = m, have m = n + 1, from eq.symm this, show m = n + 1 ∨ m > n + 1, from or.inl this) theorem T2: ∀ n : nat, n = 0 ∨ n > 0 := assume n, have 0 = n ∨ 0 < n, from or.swap $ iff.elim_left le_iff_lt_or_eq $ zero_le n, or.elim this (assume h1, or.inl (eq.symm h1)) (assume h1, or.inr h1) theorem T3 (m n : nat) : n + m = 0 → n = 0 ∧ m = 0 := assume h, have h1: n ≥ 0, from zero_le n, have h2: m ≥ 0, from zero_le m, iff.elim_left (add_eq_zero_iff_eq_zero_and_eq_zero_of_nonneg_of_nonneg h1 h2) h theorem T4 (n m k : nat) : n * k < m * k → k > 0 ∧ n < m := assume h, have h1 : k ≥ 0, from zero_le k, have h2 : n < m, from lt_of_mul_lt_mul_right h h1, have h3: k ≠ 0, from assume : k = 0, have n * 0 < m * 0, from (this ▸ h), lt_le_antisymm this (zero_le 0), have h4: k > 0, from lt_of_le_of_ne h1 h3.symm, ⟨ h4 , h2 ⟩ -- END end hidden
9d4b74b0c45d3a06a0780ab7467b8a090f2aa8d8
8eeb99d0fdf8125f5d39a0ce8631653f588ee817
/src/topology/sequences.lean
eec7d92e695cfd4c4a66a022270dcd161e95de34
[ "Apache-2.0" ]
permissive
jesse-michael-han/mathlib
a15c58378846011b003669354cbab7062b893cfe
fa6312e4dc971985e6b7708d99a5bc3062485c89
refs/heads/master
1,625,200,760,912
1,602,081,753,000
1,602,081,753,000
181,787,230
0
0
null
1,555,460,682,000
1,555,460,682,000
null
UTF-8
Lean
false
false
18,849
lean
/- Copyright (c) 2018 Jan-David Salchow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jan-David Salchow, Patrick Massot -/ import topology.bases import topology.subset_properties import topology.metric_space.basic /-! # Sequences in topological spaces In this file we define sequences in topological spaces and show how they are related to filters and the topology. In particular, we * define the sequential closure of a set and prove that it's contained in the closure, * define a type class "sequential_space" in which closure and sequential closure agree, * define sequential continuity and show that it coincides with continuity in sequential spaces, * provide an instance that shows that every first-countable (and in particular metric) space is a sequential space. * define sequential compactness, prove that compactness implies sequential compactness in first countable spaces, and prove they are equivalent for uniform spaces having a countable uniformity basis (in particular metric spaces). -/ open set filter open_locale topological_space variables {α : Type*} {β : Type*} local notation f ` ⟶ ` limit := tendsto f at_top (𝓝 limit) /-! ### Sequential closures, sequential continuity, and sequential spaces. -/ section topological_space variables [topological_space α] [topological_space β] /-- A sequence converges in the sence of topological spaces iff the associated statement for filter holds. -/ lemma topological_space.seq_tendsto_iff {x : ℕ → α} {limit : α} : tendsto x at_top (𝓝 limit) ↔ ∀ U : set α, limit ∈ U → is_open U → ∃ N, ∀ n ≥ N, (x n) ∈ U := (at_top_basis.tendsto_iff (nhds_basis_opens limit)).trans $ by simp only [and_imp, exists_prop, true_and, set.mem_Ici, ge_iff_le, id] /-- The sequential closure of a subset M ⊆ α of a topological space α is the set of all p ∈ α which arise as limit of sequences in M. -/ def sequential_closure (M : set α) : set α := {p | ∃ x : ℕ → α, (∀ n : ℕ, x n ∈ M) ∧ (x ⟶ p)} lemma subset_sequential_closure (M : set α) : M ⊆ sequential_closure M := assume p (_ : p ∈ M), show p ∈ sequential_closure M, from ⟨λ n, p, assume n, ‹p ∈ M›, tendsto_const_nhds⟩ /-- A set `s` is sequentially closed if for any converging sequence `x n` of elements of `s`, the limit belongs to `s` as well. -/ def is_seq_closed (s : set α) : Prop := s = sequential_closure s /-- A convenience lemma for showing that a set is sequentially closed. -/ lemma is_seq_closed_of_def {A : set α} (h : ∀(x : ℕ → α) (p : α), (∀ n : ℕ, x n ∈ A) → (x ⟶ p) → p ∈ A) : is_seq_closed A := show A = sequential_closure A, from subset.antisymm (subset_sequential_closure A) (show ∀ p, p ∈ sequential_closure A → p ∈ A, from (assume p ⟨x, _, _⟩, show p ∈ A, from h x p ‹∀ n : ℕ, ((x n) ∈ A)› ‹(x ⟶ p)›)) /-- The sequential closure of a set is contained in the closure of that set. The converse is not true. -/ lemma sequential_closure_subset_closure (M : set α) : sequential_closure M ⊆ closure M := assume p ⟨x, xM, xp⟩, mem_closure_of_tendsto xp (univ_mem_sets' xM) /-- A set is sequentially closed if it is closed. -/ lemma is_seq_closed_of_is_closed (M : set α) (_ : is_closed M) : is_seq_closed M := suffices sequential_closure M ⊆ M, from set.eq_of_subset_of_subset (subset_sequential_closure M) this, calc sequential_closure M ⊆ closure M : sequential_closure_subset_closure M ... = M : is_closed.closure_eq ‹is_closed M› /-- The limit of a convergent sequence in a sequentially closed set is in that set.-/ lemma mem_of_is_seq_closed {A : set α} (_ : is_seq_closed A) {x : ℕ → α} (_ : ∀ n, x n ∈ A) {limit : α} (_ : (x ⟶ limit)) : limit ∈ A := have limit ∈ sequential_closure A, from show ∃ x : ℕ → α, (∀ n : ℕ, x n ∈ A) ∧ (x ⟶ limit), from ⟨x, ‹∀ n, x n ∈ A›, ‹(x ⟶ limit)›⟩, eq.subst (eq.symm ‹is_seq_closed A›) ‹limit ∈ sequential_closure A› /-- The limit of a convergent sequence in a closed set is in that set.-/ lemma mem_of_is_closed_sequential {A : set α} (_ : is_closed A) {x : ℕ → α} (_ : ∀ n, x n ∈ A) {limit : α} (_ : x ⟶ limit) : limit ∈ A := mem_of_is_seq_closed (is_seq_closed_of_is_closed A ‹is_closed A›) ‹∀ n, x n ∈ A› ‹(x ⟶ limit)› /-- A sequential space is a space in which 'sequences are enough to probe the topology'. This can be formalised by demanding that the sequential closure and the closure coincide. The following statements show that other topological properties can be deduced from sequences in sequential spaces. -/ class sequential_space (α : Type*) [topological_space α] : Prop := (sequential_closure_eq_closure : ∀ M : set α, sequential_closure M = closure M) /-- In a sequential space, a set is closed iff it's sequentially closed. -/ lemma is_seq_closed_iff_is_closed [sequential_space α] {M : set α} : is_seq_closed M ↔ is_closed M := iff.intro (assume _, closure_eq_iff_is_closed.mp (eq.symm (calc M = sequential_closure M : by assumption ... = closure M : sequential_space.sequential_closure_eq_closure M))) (is_seq_closed_of_is_closed M) /-- In a sequential space, a point belongs to the closure of a set iff it is a limit of a sequence taking values in this set. -/ lemma mem_closure_iff_seq_limit [sequential_space α] {s : set α} {a : α} : a ∈ closure s ↔ ∃ x : ℕ → α, (∀ n : ℕ, x n ∈ s) ∧ (x ⟶ a) := by { rw ← sequential_space.sequential_closure_eq_closure, exact iff.rfl } /-- A function between topological spaces is sequentially continuous if it commutes with limit of convergent sequences. -/ def sequentially_continuous (f : α → β) : Prop := ∀ (x : ℕ → α), ∀ {limit : α}, (x ⟶ limit) → (f∘x ⟶ f limit) /- A continuous function is sequentially continuous. -/ lemma continuous.to_sequentially_continuous {f : α → β} (_ : continuous f) : sequentially_continuous f := assume x limit (_ : x ⟶ limit), have tendsto f (𝓝 limit) (𝓝 (f limit)), from continuous.tendsto ‹continuous f› limit, show (f ∘ x) ⟶ (f limit), from tendsto.comp this ‹(x ⟶ limit)› /-- In a sequential space, continuity and sequential continuity coincide. -/ lemma continuous_iff_sequentially_continuous {f : α → β} [sequential_space α] : continuous f ↔ sequentially_continuous f := iff.intro (assume _, ‹continuous f›.to_sequentially_continuous) (assume : sequentially_continuous f, show continuous f, from suffices h : ∀ {A : set β}, is_closed A → is_seq_closed (f ⁻¹' A), from continuous_iff_is_closed.mpr (assume A _, is_seq_closed_iff_is_closed.mp $ h ‹is_closed A›), assume A (_ : is_closed A), is_seq_closed_of_def $ assume (x : ℕ → α) p (_ : ∀ n, f (x n) ∈ A) (_ : x ⟶ p), have (f ∘ x) ⟶ (f p), from ‹sequentially_continuous f› x ‹(x ⟶ p)›, show f p ∈ A, from mem_of_is_closed_sequential ‹is_closed A› ‹∀ n, f (x n) ∈ A› ‹(f∘x ⟶ f p)›) end topological_space namespace topological_space namespace first_countable_topology variables [topological_space α] [first_countable_topology α] /-- Every first-countable space is sequential. -/ @[priority 100] -- see Note [lower instance priority] instance : sequential_space α := ⟨show ∀ M, sequential_closure M = closure M, from assume M, suffices closure M ⊆ sequential_closure M, from set.subset.antisymm (sequential_closure_subset_closure M) this, -- For every p ∈ closure M, we need to construct a sequence x in M that converges to p: assume (p : α) (hp : p ∈ closure M), -- Since we are in a first-countable space, the neighborhood filter around `p` has a decreasing -- basis `U` indexed by `ℕ`. let ⟨U, hU ⟩ := (nhds_generated_countable p).has_antimono_basis in -- Since `p ∈ closure M`, there is an element in each `M ∩ U i` have hp : ∀ (i : ℕ), ∃ (y : α), y ∈ M ∧ y ∈ U i, by simpa using (mem_closure_iff_nhds_basis hU.1).mp hp, begin -- The axiom of (countable) choice builds our sequence from the later fact choose u hu using hp, rw forall_and_distrib at hu, -- It clearly takes values in `M` use [u, hu.1], -- and converges to `p` because the basis is decreasing. apply hU.tendsto hu.2, end⟩ end first_countable_topology end topological_space section seq_compact open topological_space topological_space.first_countable_topology variables [topological_space α] /-- A set `s` is sequentially compact if every sequence taking values in `s` has a converging subsequence. -/ def is_seq_compact (s : set α) := ∀ ⦃u : ℕ → α⦄, (∀ n, u n ∈ s) → ∃ (x ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) /-- A space `α` is sequentially compact if every sequence in `α` has a converging subsequence. -/ class seq_compact_space (α : Type*) [topological_space α] : Prop := (seq_compact_univ : is_seq_compact (univ : set α)) lemma is_seq_compact.subseq_of_frequently_in {s : set α} (hs : is_seq_compact s) {u : ℕ → α} (hu : ∃ᶠ n in at_top, u n ∈ s) : ∃ (x ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) := let ⟨ψ, hψ, huψ⟩ := extraction_of_frequently_at_top hu, ⟨x, x_in, φ, hφ, h⟩ := hs huψ in ⟨x, x_in, ψ ∘ φ, hψ.comp hφ, h⟩ lemma seq_compact_space.tendsto_subseq [seq_compact_space α] (u : ℕ → α) : ∃ x (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) := let ⟨x, _, φ, mono, h⟩ := seq_compact_space.seq_compact_univ (by simp : ∀ n, u n ∈ univ) in ⟨x, φ, mono, h⟩ section first_countable_topology variables [first_countable_topology α] open topological_space.first_countable_topology lemma is_compact.is_seq_compact {s : set α} (hs : is_compact s) : is_seq_compact s := λ u u_in, let ⟨x, x_in, hx⟩ := @hs (map u at_top) _ (le_principal_iff.mpr (univ_mem_sets' u_in : _)) in ⟨x, x_in, tendsto_subseq hx⟩ lemma is_compact.tendsto_subseq' {s : set α} {u : ℕ → α} (hs : is_compact s) (hu : ∃ᶠ n in at_top, u n ∈ s) : ∃ (x ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) := hs.is_seq_compact.subseq_of_frequently_in hu lemma is_compact.tendsto_subseq {s : set α} {u : ℕ → α} (hs : is_compact s) (hu : ∀ n, u n ∈ s) : ∃ (x ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) := hs.is_seq_compact hu @[priority 100] -- see Note [lower instance priority] instance first_countable_topology.seq_compact_of_compact [compact_space α] : seq_compact_space α := ⟨compact_univ.is_seq_compact⟩ lemma compact_space.tendsto_subseq [compact_space α] (u : ℕ → α) : ∃ x (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) := seq_compact_space.tendsto_subseq u end first_countable_topology end seq_compact section uniform_space_seq_compact open_locale uniformity open uniform_space prod variables [uniform_space β] {s : set β} lemma lebesgue_number_lemma_seq {ι : Type*} {c : ι → set β} (hs : is_seq_compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) (hU : is_countably_generated (𝓤 β)) : ∃ V ∈ 𝓤 β, symmetric_rel V ∧ ∀ x ∈ s, ∃ i, ball x V ⊆ c i := begin classical, obtain ⟨V, hV, Vsymm⟩ : ∃ V : ℕ → set (β × β), (𝓤 β).has_antimono_basis (λ _, true) V ∧ ∀ n, swap ⁻¹' V n = V n, from uniform_space.has_seq_basis hU, clear hU, suffices : ∃ n, ∀ x ∈ s, ∃ i, ball x (V n) ⊆ c i, { cases this with n hn, exact ⟨V n, hV.to_has_basis.mem_of_mem trivial, Vsymm n, hn⟩ }, by_contradiction H, obtain ⟨x, x_in, hx⟩ : ∃ x : ℕ → β, (∀ n, x n ∈ s) ∧ ∀ n i, ¬ ball (x n) (V n) ⊆ c i, { push_neg at H, choose x hx using H, exact ⟨x, forall_and_distrib.mp hx⟩ }, clear H, obtain ⟨x₀, x₀_in, φ, φ_mono, hlim⟩ : ∃ (x₀ ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ (x ∘ φ ⟶ x₀), from hs x_in, clear hs, obtain ⟨i₀, x₀_in⟩ : ∃ i₀, x₀ ∈ c i₀, { rcases hc₂ x₀_in with ⟨_, ⟨i₀, rfl⟩, x₀_in_c⟩, exact ⟨i₀, x₀_in_c⟩ }, clear hc₂, obtain ⟨n₀, hn₀⟩ : ∃ n₀, ball x₀ (V n₀) ⊆ c i₀, { rcases (nhds_basis_uniformity hV.to_has_basis).mem_iff.mp (is_open_iff_mem_nhds.mp (hc₁ i₀) _ x₀_in) with ⟨n₀, _, h⟩, use n₀, rwa ← ball_eq_of_symmetry (Vsymm n₀) at h }, clear hc₁, obtain ⟨W, W_in, hWW⟩ : ∃ W ∈ 𝓤 β, W ○ W ⊆ V n₀, from comp_mem_uniformity_sets (hV.to_has_basis.mem_of_mem trivial), obtain ⟨N, x_φ_N_in, hVNW⟩ : ∃ N, x (φ N) ∈ ball x₀ W ∧ V (φ N) ⊆ W, { obtain ⟨N₁, h₁⟩ : ∃ N₁, ∀ n ≥ N₁, x (φ n) ∈ ball x₀ W, from (tendsto_at_top' (λ (b : ℕ), (x ∘ φ) b) (𝓝 x₀)).mp hlim _ (mem_nhds_left x₀ W_in), obtain ⟨N₂, h₂⟩ : ∃ N₂, V (φ N₂) ⊆ W, { rcases hV.to_has_basis.mem_iff.mp W_in with ⟨N, _, hN⟩, use N, exact subset.trans (hV.decreasing trivial trivial $ φ_mono.id_le _) hN }, have : φ N₂ ≤ φ (max N₁ N₂), from φ_mono.le_iff_le.mpr (le_max_right _ _), exact ⟨max N₁ N₂, h₁ _ (le_max_left _ _), subset.trans (hV.decreasing trivial trivial this) h₂⟩ }, suffices : ball (x (φ N)) (V (φ N)) ⊆ c i₀, from hx (φ N) i₀ this, calc ball (x $ φ N) (V $ φ N) ⊆ ball (x $ φ N) W : preimage_mono hVNW ... ⊆ ball x₀ (V n₀) : ball_subset_of_comp_subset x_φ_N_in hWW ... ⊆ c i₀ : hn₀, end lemma is_seq_compact.totally_bounded (h : is_seq_compact s) : totally_bounded s := begin classical, apply totally_bounded_of_forall_symm, unfold is_seq_compact at h, contrapose! h, rcases h with ⟨V, V_in, V_symm, h⟩, simp_rw [not_subset] at h, have : ∀ (t : set β), finite t → ∃ a, a ∈ s ∧ a ∉ ⋃ y ∈ t, ball y V, { intros t ht, obtain ⟨a, a_in, H⟩ : ∃ a ∈ s, ∀ (x : β), x ∈ t → (x, a) ∉ V, by simpa [ht] using h t, use [a, a_in], intro H', obtain ⟨x, x_in, hx⟩ := mem_bUnion_iff.mp H', exact H x x_in hx }, cases seq_of_forall_finite_exists this with u hu, clear h this, simp [forall_and_distrib] at hu, cases hu with u_in hu, use [u, u_in], clear u_in, intros x x_in φ, intros hφ huφ, obtain ⟨N, hN⟩ : ∃ N, ∀ p q, p ≥ N → q ≥ N → (u (φ p), u (φ q)) ∈ V, from huφ.cauchy_seq.mem_entourage V_in, specialize hN N (N+1) (le_refl N) (nat.le_succ N), specialize hu (φ $ N+1) (φ N) (hφ $ lt_add_one N), exact hu hN, end protected lemma is_seq_compact.is_compact (h : is_countably_generated $ 𝓤 β) (hs : is_seq_compact s) : is_compact s := begin classical, rw compact_iff_finite_subcover, intros ι U Uop s_sub, rcases lebesgue_number_lemma_seq hs Uop s_sub h with ⟨V, V_in, Vsymm, H⟩, rcases totally_bounded_iff_subset.mp hs.totally_bounded V V_in with ⟨t,t_sub, tfin, ht⟩, have : ∀ x : t, ∃ (i : ι), ball x.val V ⊆ U i, { rintros ⟨x, x_in⟩, exact H x (t_sub x_in) }, choose i hi using this, haveI : fintype t := tfin.fintype, use finset.image i finset.univ, transitivity ⋃ y ∈ t, ball y V, { intros x x_in, specialize ht x_in, rw mem_bUnion_iff at *, simp_rw ball_eq_of_symmetry Vsymm, exact ht }, { apply bUnion_subset_bUnion, intros x x_in, exact ⟨i ⟨x, x_in⟩, finset.mem_image_of_mem _ (finset.mem_univ _), hi ⟨x, x_in⟩⟩ }, end protected lemma uniform_space.compact_iff_seq_compact (h : is_countably_generated $ 𝓤 β) : is_compact s ↔ is_seq_compact s := begin haveI := uniform_space.first_countable_topology h, exact ⟨λ H, H.is_seq_compact, λ H, H.is_compact h⟩ end lemma uniform_space.compact_space_iff_seq_compact_space (H : is_countably_generated $ 𝓤 β) : compact_space β ↔ seq_compact_space β := have key : is_compact univ ↔ is_seq_compact univ := uniform_space.compact_iff_seq_compact H, ⟨λ ⟨h⟩, ⟨key.mp h⟩, λ ⟨h⟩, ⟨key.mpr h⟩⟩ end uniform_space_seq_compact section metric_seq_compact variables [metric_space β] {s : set β} open metric /-- A version of Bolzano-Weistrass: in a metric space, is_compact s ↔ is_seq_compact s -/ lemma metric.compact_iff_seq_compact : is_compact s ↔ is_seq_compact s := uniform_space.compact_iff_seq_compact emetric.uniformity_has_countable_basis /-- A version of Bolzano-Weistrass: in a proper metric space (eg. $ℝ^n$), every bounded sequence has a converging subsequence. This version assumes only that the sequence is frequently in some bounded set. -/ lemma tendsto_subseq_of_frequently_bounded [proper_space β] (hs : bounded s) {u : ℕ → β} (hu : ∃ᶠ n in at_top, u n ∈ s) : ∃ b ∈ closure s, ∃ φ : ℕ → ℕ, strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 b) := begin have hcs : is_compact (closure s) := compact_iff_closed_bounded.mpr ⟨is_closed_closure, bounded_closure_of_bounded hs⟩, replace hcs : is_seq_compact (closure s), by rwa metric.compact_iff_seq_compact at hcs, have hu' : ∃ᶠ n in at_top, u n ∈ closure s, { apply frequently.mono hu, intro n, apply subset_closure }, exact hcs.subseq_of_frequently_in hu', end /-- A version of Bolzano-Weistrass: in a proper metric space (eg. $ℝ^n$), every bounded sequence has a converging subsequence. -/ lemma tendsto_subseq_of_bounded [proper_space β] (hs : bounded s) {u : ℕ → β} (hu : ∀ n, u n ∈ s) : ∃ b ∈ closure s, ∃ φ : ℕ → ℕ, strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 b) := tendsto_subseq_of_frequently_bounded hs $ frequently_of_forall hu lemma metric.compact_space_iff_seq_compact_space : compact_space β ↔ seq_compact_space β := uniform_space.compact_space_iff_seq_compact_space emetric.uniformity_has_countable_basis lemma seq_compact.lebesgue_number_lemma_of_metric {ι : Type*} {c : ι → set β} (hs : is_seq_compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ δ > 0, ∀ x ∈ s, ∃ i, ball x δ ⊆ c i := begin rcases lebesgue_number_lemma_seq hs hc₁ hc₂ emetric.uniformity_has_countable_basis with ⟨V, V_in, _, hV⟩, rcases uniformity_basis_dist.mem_iff.mp V_in with ⟨δ, δ_pos, h⟩, use [δ, δ_pos], intros x x_in, rcases hV x x_in with ⟨i, hi⟩, use i, have := ball_mono h x, rw ball_eq_ball' at this, exact subset.trans this hi, end end metric_seq_compact
67019a541ed69d10c10c7f1edb9401e849f84216
e0b0b1648286e442507eb62344760d5cd8d13f2d
/src/Lean/Elab/Binders.lean
08544376a4c887f5a17e1290f648d9bb3e93ee96
[ "Apache-2.0" ]
permissive
MULXCODE/lean4
743ed389e05e26e09c6a11d24607ad5a697db39b
4675817a9e89824eca37192364cd47a4027c6437
refs/heads/master
1,682,231,879,857
1,620,423,501,000
1,620,423,501,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,893
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.Elab.Quotation.Precheck import Lean.Elab.Term import Lean.Parser.Term namespace Lean.Elab.Term open Meta open Lean.Parser.Term /-- Given syntax of the forms a) (`:` term)? b) `:` term return `term` if it is present, or a hole if not. -/ private def expandBinderType (ref : Syntax) (stx : Syntax) : Syntax := if stx.getNumArgs == 0 then mkHole ref else stx[1] /-- Given syntax of the form `ident <|> hole`, return `ident`. If `hole`, then we create a new anonymous name. -/ private def expandBinderIdent (stx : Syntax) : TermElabM Syntax := match stx with | `(_) => mkFreshIdent stx | _ => pure stx /-- Given syntax of the form `(ident >> " : ")?`, return `ident`, or a new instance name. -/ private def expandOptIdent (stx : Syntax) : TermElabM Syntax := do if stx.isNone then let id ← withFreshMacroScope <| MonadQuotation.addMacroScope `inst return mkIdentFrom stx id else return stx[0] structure BinderView where id : Syntax type : Syntax bi : BinderInfo partial def quoteAutoTactic : Syntax → TermElabM Syntax | stx@(Syntax.ident _ _ _ _) => throwErrorAt stx "invalid auto tactic, identifier is not allowed" | stx@(Syntax.node k args) => do if stx.isAntiquot then throwErrorAt stx "invalid auto tactic, antiquotation is not allowed" else let mut quotedArgs ← `(Array.empty) for arg in args do if k == nullKind && (arg.isAntiquotSuffixSplice || arg.isAntiquotSplice) then throwErrorAt arg "invalid auto tactic, antiquotation is not allowed" else let quotedArg ← quoteAutoTactic arg quotedArgs ← `(Array.push $quotedArgs $quotedArg) `(Syntax.node $(quote k) $quotedArgs) | Syntax.atom info val => `(mkAtom $(quote val)) | Syntax.missing => unreachable! def declareTacticSyntax (tactic : Syntax) : TermElabM Name := withFreshMacroScope do let name ← MonadQuotation.addMacroScope `_auto let type := Lean.mkConst `Lean.Syntax let tactic ← quoteAutoTactic tactic let val ← elabTerm tactic type let val ← instantiateMVars val trace[Elab.autoParam] val let decl := Declaration.defnDecl { name := name, levelParams := [], type := type, value := val, hints := ReducibilityHints.opaque, safety := DefinitionSafety.safe } addDecl decl compileDecl decl return name /- Expand `optional (binderTactic <|> binderDefault)` def binderTactic := leading_parser " := " >> " by " >> tacticParser def binderDefault := leading_parser " := " >> termParser -/ private def expandBinderModifier (type : Syntax) (optBinderModifier : Syntax) : TermElabM Syntax := do if optBinderModifier.isNone then return type else let modifier := optBinderModifier[0] let kind := modifier.getKind if kind == `Lean.Parser.Term.binderDefault then let defaultVal := modifier[1] `(optParam $type $defaultVal) else if kind == `Lean.Parser.Term.binderTactic then let tac := modifier[2] let name ← declareTacticSyntax tac `(autoParam $type $(mkIdentFrom tac name)) else throwUnsupportedSyntax private def getBinderIds (ids : Syntax) : TermElabM (Array Syntax) := ids.getArgs.mapM fun id => let k := id.getKind if k == identKind || k == `Lean.Parser.Term.hole then return id else throwErrorAt id "identifier or `_` expected" /- Recall that ``` def typeSpec := leading_parser " : " >> termParser def optType : Parser := optional typeSpec ``` -/ def expandOptType (ref : Syntax) (optType : Syntax) : Syntax := if optType.isNone then mkHole ref else optType[0][1] private def matchBinder (stx : Syntax) : TermElabM (Array BinderView) := do let k := stx.getKind if k == `Lean.Parser.Term.simpleBinder then -- binderIdent+ >> optType let ids ← getBinderIds stx[0] let type := expandOptType stx stx[1] ids.mapM fun id => do pure { id := (← expandBinderIdent id), type := type, bi := BinderInfo.default } else if k == `Lean.Parser.Term.explicitBinder then -- `(` binderIdent+ binderType (binderDefault <|> binderTactic)? `)` let ids ← getBinderIds stx[1] let type := expandBinderType stx stx[2] let optModifier := stx[3] let type ← expandBinderModifier type optModifier ids.mapM fun id => do pure { id := (← expandBinderIdent id), type := type, bi := BinderInfo.default } else if k == `Lean.Parser.Term.implicitBinder then -- `{` binderIdent+ binderType `}` let ids ← getBinderIds stx[1] let type := expandBinderType stx stx[2] ids.mapM fun id => do pure { id := (← expandBinderIdent id), type := type, bi := BinderInfo.implicit } else if k == `Lean.Parser.Term.instBinder then -- `[` optIdent type `]` let id ← expandOptIdent stx[1] let type := stx[2] pure #[ { id := id, type := type, bi := BinderInfo.instImplicit } ] else throwUnsupportedSyntax private def registerFailedToInferBinderTypeInfo (type : Expr) (ref : Syntax) : TermElabM Unit := registerCustomErrorIfMVar type ref "failed to infer binder type" private def addLocalVarInfoCore (lctx : LocalContext) (stx : Syntax) (fvar : Expr) : TermElabM Unit := do if (← getInfoState).enabled then pushInfoTree <| InfoTree.node (children := {}) <| Info.ofTermInfo { lctx := lctx, expr := fvar, stx := stx } private def addLocalVarInfo (stx : Syntax) (fvar : Expr) : TermElabM Unit := do addLocalVarInfoCore (← getLCtx) stx fvar private def ensureAtomicBinderName (binderView : BinderView) : TermElabM Unit := let n := binderView.id.getId.eraseMacroScopes unless n.isAtomic do throwErrorAt binderView.id "invalid binder name '{n}', it must be atomic" register_builtin_option checkBinderAnnotations : Bool := { defValue := true descr := "check whether type is a class instance whenever the binder annotation `[...]` is used" } private partial def elabBinderViews {α} (binderViews : Array BinderView) (fvars : Array Expr) (k : Array Expr → TermElabM α) : TermElabM α := let rec loop (i : Nat) (fvars : Array Expr) : TermElabM α := do if h : i < binderViews.size then let binderView := binderViews.get ⟨i, h⟩ ensureAtomicBinderName binderView let type ← elabType binderView.type registerFailedToInferBinderTypeInfo type binderView.type if binderView.bi.isInstImplicit && checkBinderAnnotations.get (← getOptions) then unless (← isClass? type).isSome do throwErrorAt binderView.type "invalid binder annotation, type is not a class instance{indentExpr type}\nuse the command `set_option checkBinderAnnotations false` to disable the check" withLocalDecl binderView.id.getId binderView.bi type fun fvar => do addLocalVarInfo binderView.id fvar loop (i+1) (fvars.push fvar) else k fvars loop 0 fvars private partial def elabBindersAux {α} (binders : Array Syntax) (k : Array Expr → TermElabM α) : TermElabM α := let rec loop (i : Nat) (fvars : Array Expr) : TermElabM α := do if h : i < binders.size then let binderViews ← matchBinder (binders.get ⟨i, h⟩) elabBinderViews binderViews fvars <| loop (i+1) else k fvars loop 0 #[] /-- Elaborate the given binders (i.e., `Syntax` objects for `simpleBinder <|> bracketedBinder`), update the local context, set of local instances, reset instance chache (if needed), and then execute `x` with the updated context. -/ def elabBinders {α} (binders : Array Syntax) (k : Array Expr → TermElabM α) : TermElabM α := withoutPostponingUniverseConstraints do if binders.isEmpty then k #[] else elabBindersAux binders k @[inline] def elabBinder {α} (binder : Syntax) (x : Expr → TermElabM α) : TermElabM α := elabBinders #[binder] fun fvars => x fvars[0] @[builtinTermElab «forall»] def elabForall : TermElab := fun stx _ => match stx with | `(forall $binders*, $term) => elabBinders binders fun xs => do let e ← elabType term mkForallFVars xs e | _ => throwUnsupportedSyntax @[builtinTermElab arrow] def elabArrow : TermElab := adaptExpander fun stx => match stx with | `($dom:term -> $rng) => `(forall (a : $dom), $rng) | _ => throwUnsupportedSyntax @[builtinTermElab depArrow] def elabDepArrow : TermElab := fun stx _ => -- bracketedBinder `->` term let binder := stx[0] let term := stx[2] elabBinders #[binder] fun xs => do mkForallFVars xs (← elabType term) /-- Auxiliary functions for converting `id_1 ... id_n` application into `#[id_1, ..., id_m]` It is used at `expandFunBinders`. -/ private partial def getFunBinderIds? (stx : Syntax) : OptionT MacroM (Array Syntax) := let convertElem (stx : Syntax) : OptionT MacroM Syntax := match stx with | `(_) => do let ident ← mkFreshIdent stx; pure ident | `($id:ident) => return id | _ => failure match stx with | `($f $args*) => do let mut acc := #[].push (← convertElem f) for arg in args do acc := acc.push (← convertElem arg) return acc | _ => return #[].push (← convertElem stx) /-- Auxiliary function for expanding `fun` notation binders. Recall that `fun` parser is defined as ``` def funBinder : Parser := implicitBinder <|> instBinder <|> termParser maxPrec leading_parser unicodeSymbol "λ" "fun" >> many1 funBinder >> "=>" >> termParser ``` to allow notation such as `fun (a, b) => a + b`, where `(a, b)` should be treated as a pattern. The result is a pair `(explicitBinders, newBody)`, where `explicitBinders` is syntax of the form ``` `(` ident `:` term `)` ``` which can be elaborated using `elabBinders`, and `newBody` is the updated `body` syntax. We update the `body` syntax when expanding the pattern notation. Example: `fun (a, b) => a + b` expands into `fun _a_1 => match _a_1 with | (a, b) => a + b`. See local function `processAsPattern` at `expandFunBindersAux`. The resulting `Bool` is true if a pattern was found. We use it "mark" a macro expansion. -/ partial def expandFunBinders (binders : Array Syntax) (body : Syntax) : MacroM (Array Syntax × Syntax × Bool) := let rec loop (body : Syntax) (i : Nat) (newBinders : Array Syntax) := do if h : i < binders.size then let binder := binders.get ⟨i, h⟩ let processAsPattern : Unit → MacroM (Array Syntax × Syntax × Bool) := fun _ => do let pattern := binder let major ← mkFreshIdent binder let (binders, newBody, _) ← loop body (i+1) (newBinders.push $ mkExplicitBinder major (mkHole binder)) let newBody ← `(match $major:ident with | $pattern => $newBody) pure (binders, newBody, true) match binder with | Syntax.node `Lean.Parser.Term.implicitBinder _ => loop body (i+1) (newBinders.push binder) | Syntax.node `Lean.Parser.Term.instBinder _ => loop body (i+1) (newBinders.push binder) | Syntax.node `Lean.Parser.Term.explicitBinder _ => loop body (i+1) (newBinders.push binder) | Syntax.node `Lean.Parser.Term.simpleBinder _ => loop body (i+1) (newBinders.push binder) | Syntax.node `Lean.Parser.Term.hole _ => let ident ← mkFreshIdent binder let type := binder loop body (i+1) (newBinders.push <| mkExplicitBinder ident type) | Syntax.node `Lean.Parser.Term.paren args => -- `(` (termParser >> parenSpecial)? `)` -- parenSpecial := (tupleTail <|> typeAscription)? let binderBody := binder[1] if binderBody.isNone then processAsPattern () else let idents := binderBody[0] let special := binderBody[1] if special.isNone then processAsPattern () else if special[0].getKind != `Lean.Parser.Term.typeAscription then processAsPattern () else -- typeAscription := `:` term let type := special[0][1] match (← getFunBinderIds? idents) with | some idents => loop body (i+1) (newBinders ++ idents.map (fun ident => mkExplicitBinder ident type)) | none => processAsPattern () | Syntax.ident .. => let type := mkHole binder loop body (i+1) (newBinders.push <| mkExplicitBinder binder type) | _ => processAsPattern () else pure (newBinders, body, false) loop body 0 #[] namespace FunBinders structure State where fvars : Array Expr := #[] lctx : LocalContext localInsts : LocalInstances expectedType? : Option Expr := none private def propagateExpectedType (fvar : Expr) (fvarType : Expr) (s : State) : TermElabM State := do match s.expectedType? with | none => pure s | some expectedType => let expectedType ← whnfForall expectedType match expectedType with | Expr.forallE _ d b _ => discard <| isDefEq fvarType d let b := b.instantiate1 fvar pure { s with expectedType? := some b } | _ => pure { s with expectedType? := none } private partial def elabFunBinderViews (binderViews : Array BinderView) (i : Nat) (s : State) : TermElabM State := do if h : i < binderViews.size then let binderView := binderViews.get ⟨i, h⟩ ensureAtomicBinderName binderView withRef binderView.type <| withLCtx s.lctx s.localInsts do let type ← elabType binderView.type registerFailedToInferBinderTypeInfo type binderView.type let fvarId ← mkFreshFVarId let fvar := mkFVar fvarId let s := { s with fvars := s.fvars.push fvar } -- dbgTrace (toString binderView.id.getId ++ " : " ++ toString type) /- We do **not** want to support default and auto arguments in lambda abstractions. Example: `fun (x : Nat := 10) => x+1`. We do not believe this is an useful feature, and it would complicate the logic here. -/ let lctx := s.lctx.mkLocalDecl fvarId binderView.id.getId type binderView.bi addLocalVarInfoCore lctx binderView.id fvar let s ← withRef binderView.id <| propagateExpectedType fvar type s let s := { s with lctx := lctx } match (← isClass? type) with | none => elabFunBinderViews binderViews (i+1) s | some className => resettingSynthInstanceCache do let localInsts := s.localInsts.push { className := className, fvar := mkFVar fvarId } elabFunBinderViews binderViews (i+1) { s with localInsts := localInsts } else pure s partial def elabFunBindersAux (binders : Array Syntax) (i : Nat) (s : State) : TermElabM State := do if h : i < binders.size then let binderViews ← matchBinder (binders.get ⟨i, h⟩) let s ← elabFunBinderViews binderViews 0 s elabFunBindersAux binders (i+1) s else pure s end FunBinders def elabFunBinders {α} (binders : Array Syntax) (expectedType? : Option Expr) (x : Array Expr → Option Expr → TermElabM α) : TermElabM α := if binders.isEmpty then x #[] expectedType? else do let lctx ← getLCtx let localInsts ← getLocalInstances let s ← FunBinders.elabFunBindersAux binders 0 { lctx := lctx, localInsts := localInsts, expectedType? := expectedType? } resettingSynthInstanceCacheWhen (s.localInsts.size > localInsts.size) <| withLCtx s.lctx s.localInsts <| x s.fvars s.expectedType? /- Helper function for `expandEqnsIntoMatch` -/ private def getMatchAltsNumPatterns (matchAlts : Syntax) : Nat := let alt0 := matchAlts[0][0] let pats := alt0[1].getSepArgs pats.size def expandWhereDecls (whereDecls : Syntax) (body : Syntax) : MacroM Syntax := match whereDecls with | `(whereDecls|where $[$decls:letRecDecl $[;]?]*) => `(let rec $decls:letRecDecl,*; $body) | _ => Macro.throwUnsupported def expandWhereDeclsOpt (whereDeclsOpt : Syntax) (body : Syntax) : MacroM Syntax := if whereDeclsOpt.isNone then body else expandWhereDecls whereDeclsOpt[0] body /- Helper function for `expandMatchAltsIntoMatch` -/ private def expandMatchAltsIntoMatchAux (matchAlts : Syntax) (matchTactic : Bool) : Nat → Array Syntax → MacroM Syntax | 0, discrs => do if matchTactic then `(tactic|match $[$discrs:term],* with $matchAlts:matchAlts) else `(match $[$discrs:term],* with $matchAlts:matchAlts) | n+1, discrs => withFreshMacroScope do let x ← `(x) let d ← `(@$x:ident) -- See comment below let body ← expandMatchAltsIntoMatchAux matchAlts matchTactic n (discrs.push d) if matchTactic then `(tactic| intro $x:term; $body:tactic) else `(@fun $x => $body) /-- Expand `matchAlts` syntax into a full `match`-expression. Example ``` | 0, true => alt_1 | i, _ => alt_2 ``` expands into (for tactic == false) ``` fun x_1 x_2 => match @x_1, @x_2 with | 0, true => alt_1 | i, _ => alt_2 ``` and (for tactic == true) ``` intro x_1; intro x_2; match @x_1, @x_2 with | 0, true => alt_1 | i, _ => alt_2 ``` Remark: we add `@` to make sure we don't consume implicit arguments, and to make the behavior consistent with `fun`. Example: ``` inductive T : Type 1 := | mkT : (forall {a : Type}, a -> a) -> T def makeT (f : forall {a : Type}, a -> a) : T := mkT f def makeT' : (forall {a : Type}, a -> a) -> T | f => mkT f ``` The two definitions should be elaborated without errors and be equivalent. -/ def expandMatchAltsIntoMatch (ref : Syntax) (matchAlts : Syntax) (tactic := false) : MacroM Syntax := withRef ref <| expandMatchAltsIntoMatchAux matchAlts tactic (getMatchAltsNumPatterns matchAlts) #[] def expandMatchAltsIntoMatchTactic (ref : Syntax) (matchAlts : Syntax) : MacroM Syntax := withRef ref <| expandMatchAltsIntoMatchAux matchAlts true (getMatchAltsNumPatterns matchAlts) #[] /-- Similar to `expandMatchAltsIntoMatch`, but supports an optional `where` clause. Expand `matchAltsWhereDecls` into `let rec` + `match`-expression. Example ``` | 0, true => ... f 0 ... | i, _ => ... f i + g i ... where f x := g x + 1 g : Nat → Nat | 0 => 1 | x+1 => f x ``` expands into ``` fux x_1 x_2 => let rec f x := g x + 1, g : Nat → Nat | 0 => 1 | x+1 => f x match x_1, x_2 with | 0, true => ... f 0 ... | i, _ => ... f i + g i ... ``` -/ def expandMatchAltsWhereDecls (matchAltsWhereDecls : Syntax) : MacroM Syntax := let matchAlts := matchAltsWhereDecls[0] let whereDeclsOpt := matchAltsWhereDecls[1] let rec loop (i : Nat) (discrs : Array Syntax) : MacroM Syntax := match i with | 0 => do let matchStx ← `(match $[$discrs:term],* with $matchAlts:matchAlts) if whereDeclsOpt.isNone then return matchStx else expandWhereDeclsOpt whereDeclsOpt matchStx | n+1 => withFreshMacroScope do let d ← `(@x) -- See comment at `expandMatchAltsIntoMatch` let body ← loop n (discrs.push d) `(@fun x => $body) loop (getMatchAltsNumPatterns matchAlts) #[] @[builtinMacro Lean.Parser.Term.fun] partial def expandFun : Macro | `(fun $binders* => $body) => do let (binders, body, expandedPattern) ← expandFunBinders binders body if expandedPattern then `(fun $binders* => $body) else Macro.throwUnsupported | stx@`(fun $m:matchAlts) => expandMatchAltsIntoMatch stx m | _ => Macro.throwUnsupported open Lean.Elab.Term.Quotation in @[builtinQuotPrecheck Lean.Parser.Term.fun] def precheckFun : Precheck | `(fun $binders* => $body) => do let (binders, body, expandedPattern) ← liftMacroM <| expandFunBinders binders body let mut ids := #[] for b in binders do for v in ← matchBinder b do Quotation.withNewLocals ids <| precheck v.type ids := ids.push v.id.getId Quotation.withNewLocals ids <| precheck body | _ => throwUnsupportedSyntax @[builtinTermElab «fun»] partial def elabFun : TermElab := fun stx expectedType? => match stx with | `(fun $binders* => $body) => do -- We can assume all `match` binders have been iteratively expanded by the above macro here, though -- we still need to call `expandFunBinders` once to obtain `binders` in a normal form -- expected by `elabFunBinder`. let (binders, body, expandedPattern) ← liftMacroM <| expandFunBinders binders body elabFunBinders binders expectedType? fun xs expectedType? => do /- We ensure the expectedType here since it will force coercions to be applied if needed. If we just use `elabTerm`, then we will need to a coercion `Coe (α → β) (α → δ)` whenever there is a coercion `Coe β δ`, and another instance for the dependent version. -/ let e ← elabTermEnsuringType body expectedType? mkLambdaFVars xs e | _ => throwUnsupportedSyntax /- If `useLetExpr` is true, then a kernel let-expression `let x : type := val; body` is created. Otherwise, we create a term of the form `(fun (x : type) => body) val` The default elaboration order is `binders`, `typeStx`, `valStx`, and `body`. If `elabBodyFirst == true`, then we use the order `binders`, `typeStx`, `body`, and `valStx`. -/ def elabLetDeclAux (id : Syntax) (binders : Array Syntax) (typeStx : Syntax) (valStx : Syntax) (body : Syntax) (expectedType? : Option Expr) (useLetExpr : Bool) (elabBodyFirst : Bool) : TermElabM Expr := do let (type, val, arity) ← elabBinders binders fun xs => do let type ← elabType typeStx registerCustomErrorIfMVar type typeStx "failed to infer 'let' declaration type" if elabBodyFirst then let type ← mkForallFVars xs type let val ← mkFreshExprMVar type pure (type, val, xs.size) else let val ← elabTermEnsuringType valStx type let type ← mkForallFVars xs type let val ← mkLambdaFVars xs val pure (type, val, xs.size) trace[Elab.let.decl] "{id.getId} : {type} := {val}" let result ← if useLetExpr then withLetDecl id.getId type val fun x => do addLocalVarInfo id x let body ← elabTermEnsuringType body expectedType? let body ← instantiateMVars body mkLetFVars #[x] body else let f ← withLocalDecl id.getId BinderInfo.default type fun x => do addLocalVarInfo id x let body ← elabTermEnsuringType body expectedType? let body ← instantiateMVars body mkLambdaFVars #[x] body pure <| mkApp f val if elabBodyFirst then forallBoundedTelescope type arity fun xs type => do let valResult ← elabTermEnsuringType valStx type let valResult ← mkLambdaFVars xs valResult unless (← isDefEq val valResult) do throwError "unexpected error when elaborating 'let'" pure result structure LetIdDeclView where id : Syntax binders : Array Syntax type : Syntax value : Syntax def mkLetIdDeclView (letIdDecl : Syntax) : LetIdDeclView := -- `letIdDecl` is of the form `ident >> many bracketedBinder >> optType >> " := " >> termParser let id := letIdDecl[0] let binders := letIdDecl[1].getArgs let optType := letIdDecl[2] let type := expandOptType letIdDecl optType let value := letIdDecl[4] { id := id, binders := binders, type := type, value := value } def expandLetEqnsDecl (letDecl : Syntax) : MacroM Syntax := do let ref := letDecl let matchAlts := letDecl[3] let val ← expandMatchAltsIntoMatch ref matchAlts return Syntax.node `Lean.Parser.Term.letIdDecl #[letDecl[0], letDecl[1], letDecl[2], mkAtomFrom ref " := ", val] def elabLetDeclCore (stx : Syntax) (expectedType? : Option Expr) (useLetExpr : Bool) (elabBodyFirst : Bool) : TermElabM Expr := do let ref := stx let letDecl := stx[1][0] let body := stx[3] if letDecl.getKind == `Lean.Parser.Term.letIdDecl then let { id := id, binders := binders, type := type, value := val } := mkLetIdDeclView letDecl elabLetDeclAux id binders type val body expectedType? useLetExpr elabBodyFirst else if letDecl.getKind == `Lean.Parser.Term.letPatDecl then -- node `Lean.Parser.Term.letPatDecl $ try (termParser >> pushNone >> optType >> " := ") >> termParser let pat := letDecl[0] let optType := letDecl[2] let type := expandOptType stx optType let val := letDecl[4] let stxNew ← `(let x : $type := $val; match x with | $pat => $body) let stxNew := match useLetExpr, elabBodyFirst with | true, false => stxNew | true, true => stxNew.setKind `Lean.Parser.Term.«let_delayed» | false, false => stxNew.setKind `Lean.Parser.Term.«let_fun» | false, true => unreachable! withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? else if letDecl.getKind == `Lean.Parser.Term.letEqnsDecl then let letDeclIdNew ← liftMacroM <| expandLetEqnsDecl letDecl let declNew := stx[1].setArg 0 letDeclIdNew let stxNew := stx.setArg 1 declNew withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? else throwUnsupportedSyntax @[builtinTermElab «let»] def elabLetDecl : TermElab := fun stx expectedType? => elabLetDeclCore stx expectedType? true false @[builtinTermElab «let_fun»] def elabLetFunDecl : TermElab := fun stx expectedType? => elabLetDeclCore stx expectedType? false false @[builtinTermElab «let_delayed»] def elabLetDelayedDecl : TermElab := fun stx expectedType? => elabLetDeclCore stx expectedType? true true builtin_initialize registerTraceClass `Elab.let end Lean.Elab.Term