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
28941c03cf1791297e74ecc7e07812543118ae9c
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/real/cau_seq_completion.lean
6a4db83b80edca60e9f59a40cba378c663ff9bfc
[ "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
12,887
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Robert Y. Lewis -/ import data.real.cau_seq /-! # Cauchy completion > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file generalizes the Cauchy completion of `(ℚ, abs)` to the completion of a ring with absolute value. -/ namespace cau_seq.completion open cau_seq section variables {α : Type*} [linear_ordered_field α] variables {β : Type*} [ring β] (abv : β → α) [is_absolute_value abv] /-- The Cauchy completion of a ring with absolute value. -/ def Cauchy := @quotient (cau_seq _ abv) cau_seq.equiv variables {abv} /-- The map from Cauchy sequences into the Cauchy completion. -/ def mk : cau_seq _ abv → Cauchy abv := quotient.mk @[simp] theorem mk_eq_mk (f) : @eq (Cauchy abv) ⟦f⟧ (mk f) := rfl theorem mk_eq {f g : cau_seq _ abv} : mk f = mk g ↔ f ≈ g := quotient.eq /-- The map from the original ring into the Cauchy completion. -/ def of_rat (x : β) : Cauchy abv := mk (const abv x) instance : has_zero (Cauchy abv) := ⟨of_rat 0⟩ instance : has_one (Cauchy abv) := ⟨of_rat 1⟩ instance : inhabited (Cauchy abv) := ⟨0⟩ theorem of_rat_zero : (of_rat 0 : Cauchy abv) = 0 := rfl theorem of_rat_one : (of_rat 1 : Cauchy abv) = 1 := rfl @[simp] theorem mk_eq_zero {f : cau_seq _ abv} : mk f = 0 ↔ lim_zero f := by have : mk f = 0 ↔ lim_zero (f - 0) := quotient.eq; rwa sub_zero at this instance : has_add (Cauchy abv) := ⟨quotient.map₂ (+) $ λ f₁ g₁ hf f₂ g₂ hg, add_equiv_add hf hg⟩ @[simp] theorem mk_add (f g : cau_seq β abv) : mk f + mk g = mk (f + g) := rfl instance : has_neg (Cauchy abv) := ⟨quotient.map has_neg.neg $ λ f₁ f₂ hf, neg_equiv_neg hf⟩ @[simp] theorem mk_neg (f : cau_seq β abv) : -mk f = mk (-f) := rfl instance : has_mul (Cauchy abv) := ⟨quotient.map₂ (*) $ λ f₁ g₁ hf f₂ g₂ hg, mul_equiv_mul hf hg⟩ @[simp] theorem mk_mul (f g : cau_seq β abv) : mk f * mk g = mk (f * g) := rfl instance : has_sub (Cauchy abv) := ⟨quotient.map₂ has_sub.sub $ λ f₁ g₁ hf f₂ g₂ hg, sub_equiv_sub hf hg⟩ @[simp] theorem mk_sub (f g : cau_seq β abv) : mk f - mk g = mk (f - g) := rfl instance {γ : Type*} [has_smul γ β] [is_scalar_tower γ β β] : has_smul γ (Cauchy abv) := ⟨λ c, quotient.map ((•) c) $ λ f₁ g₁ hf, smul_equiv_smul _ hf⟩ @[simp] theorem mk_smul {γ : Type*} [has_smul γ β] [is_scalar_tower γ β β] (c : γ) (f : cau_seq β abv) : c • mk f = mk (c • f) := rfl instance : has_pow (Cauchy abv) ℕ := ⟨λ x n, quotient.map (^ n) (λ f₁ g₁ hf, pow_equiv_pow hf _) x⟩ @[simp] theorem mk_pow (n : ℕ) (f : cau_seq β abv) : mk f ^ n = mk (f ^ n) := rfl instance : has_nat_cast (Cauchy abv) := ⟨λ n, mk n⟩ instance : has_int_cast (Cauchy abv) := ⟨λ n, mk n⟩ @[simp] theorem of_rat_nat_cast (n : ℕ) : (of_rat n : Cauchy abv) = n := rfl @[simp] theorem of_rat_int_cast (z : ℤ) : (of_rat z : Cauchy abv) = z := rfl theorem of_rat_add (x y : β) : of_rat (x + y) = (of_rat x + of_rat y : Cauchy abv) := congr_arg mk (const_add _ _) theorem of_rat_neg (x : β) : of_rat (-x) = (-of_rat x : Cauchy abv) := congr_arg mk (const_neg _) theorem of_rat_mul (x y : β) : of_rat (x * y) = (of_rat x * of_rat y : Cauchy abv) := congr_arg mk (const_mul _ _) private lemma zero_def : 0 = (mk 0 : Cauchy abv) := rfl private lemma one_def : 1 = (mk 1 : Cauchy abv) := rfl instance : ring (Cauchy abv) := function.surjective.ring mk (surjective_quotient_mk _) zero_def.symm one_def.symm (λ _ _, (mk_add _ _).symm) (λ _ _, (mk_mul _ _).symm) (λ _, (mk_neg _).symm) (λ _ _, (mk_sub _ _).symm) (λ _ _, (mk_smul _ _).symm) (λ _ _, (mk_smul _ _).symm) (λ _ _, (mk_pow _ _).symm) (λ _, rfl) (λ _, rfl) /-- `cau_seq.completion.of_rat` as a `ring_hom` -/ @[simps] def of_rat_ring_hom : β →+* Cauchy abv := { to_fun := of_rat, map_zero' := of_rat_zero, map_one' := of_rat_one, map_add' := of_rat_add, map_mul' := of_rat_mul, } theorem of_rat_sub (x y : β) : of_rat (x - y) = (of_rat x - of_rat y : Cauchy abv) := congr_arg mk (const_sub _ _) end section variables {α : Type*} [linear_ordered_field α] variables {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv] instance : comm_ring (Cauchy abv) := function.surjective.comm_ring mk (surjective_quotient_mk _) zero_def.symm one_def.symm (λ _ _, (mk_add _ _).symm) (λ _ _, (mk_mul _ _).symm) (λ _, (mk_neg _).symm) (λ _ _, (mk_sub _ _).symm) (λ _ _, (mk_smul _ _).symm) (λ _ _, (mk_smul _ _).symm) (λ _ _, (mk_pow _ _).symm) (λ _, rfl) (λ _, rfl) end open_locale classical section variables {α : Type*} [linear_ordered_field α] variables {β : Type*} [division_ring β] {abv : β → α} [is_absolute_value abv] instance : has_rat_cast (Cauchy abv) := ⟨λ q, of_rat q⟩ @[simp] theorem of_rat_rat_cast (q : ℚ) : of_rat (↑q : β) = (q : Cauchy abv) := rfl noncomputable instance : has_inv (Cauchy abv) := ⟨λ x, quotient.lift_on x (λ f, mk $ if h : lim_zero f then 0 else inv f h) $ λ f g fg, begin have := lim_zero_congr fg, by_cases hf : lim_zero f, { simp [hf, this.1 hf, setoid.refl] }, { have hg := mt this.2 hf, simp [hf, hg], have If : mk (inv f hf) * mk f = 1 := mk_eq.2 (inv_mul_cancel hf), have Ig : mk (inv g hg) * mk g = 1 := mk_eq.2 (inv_mul_cancel hg), have Ig' : mk g * mk (inv g hg) = 1 := mk_eq.2 (mul_inv_cancel hg), rw [mk_eq.2 fg, ← Ig] at If, rw [← mul_one (mk (inv f hf)), ← Ig', ← mul_assoc, If, mul_assoc, Ig', mul_one] } end⟩ @[simp] theorem inv_zero : (0 : Cauchy abv)⁻¹ = 0 := congr_arg mk $ by rw dif_pos; [refl, exact zero_lim_zero] @[simp] theorem inv_mk {f} (hf) : (@mk α _ β _ abv _ f)⁻¹ = mk (inv f hf) := congr_arg mk $ by rw dif_neg lemma cau_seq_zero_ne_one : ¬ (0 : cau_seq _ abv) ≈ 1 := λ h, have lim_zero (1 - 0), from setoid.symm h, have lim_zero 1, by simpa, one_ne_zero $ const_lim_zero.1 this lemma zero_ne_one : (0 : Cauchy abv) ≠ 1 := λ h, cau_seq_zero_ne_one $ mk_eq.1 h protected theorem inv_mul_cancel {x : Cauchy abv} : x ≠ 0 → x⁻¹ * x = 1 := quotient.induction_on x $ λ f hf, begin simp at hf, simp [hf], exact quotient.sound (cau_seq.inv_mul_cancel hf) end protected theorem mul_inv_cancel {x : Cauchy abv} : x ≠ 0 → x * x⁻¹ = 1 := quotient.induction_on x $ λ f hf, begin simp at hf, simp [hf], exact quotient.sound (cau_seq.mul_inv_cancel hf) end theorem of_rat_inv (x : β) : of_rat (x⁻¹) = ((of_rat x)⁻¹ : Cauchy abv) := congr_arg mk $ by split_ifs with h; [simp [const_lim_zero.1 h], refl] /-- The Cauchy completion forms a division ring. -/ noncomputable instance : division_ring (Cauchy abv) := { inv := has_inv.inv, mul_inv_cancel := λ x, cau_seq.completion.mul_inv_cancel, exists_pair_ne := ⟨0, 1, zero_ne_one⟩, inv_zero := inv_zero, rat_cast := λ q, of_rat q, rat_cast_mk := λ n d hd hnd, by rw [rat.cast_mk', of_rat_mul, of_rat_int_cast, of_rat_inv, of_rat_nat_cast], .. Cauchy.ring } theorem of_rat_div (x y : β) : of_rat (x / y) = (of_rat x / of_rat y : Cauchy abv) := by simp only [div_eq_mul_inv, of_rat_inv, of_rat_mul] /-- Show the first 10 items of a representative of this equivalence class of cauchy sequences. The representative chosen is the one passed in the VM to `quot.mk`, so two cauchy sequences converging to the same number may be printed differently. -/ meta instance [has_repr β] : has_repr (Cauchy abv) := { repr := λ r, let N := 10, seq := r.unquot in "(sorry /- " ++ (", ".intercalate $ (list.range N).map $ repr ∘ seq) ++ ", ... -/)" } end section variables {α : Type*} [linear_ordered_field α] variables {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] /-- The Cauchy completion forms a field. -/ noncomputable instance : field (Cauchy abv) := { .. Cauchy.division_ring, .. Cauchy.comm_ring } end end cau_seq.completion variables {α : Type*} [linear_ordered_field α] namespace cau_seq section variables (β : Type*) [ring β] (abv : β → α) [is_absolute_value abv] /-- A class stating that a ring with an absolute value is complete, i.e. every Cauchy sequence has a limit. -/ class is_complete : Prop := (is_complete : ∀ s : cau_seq β abv, ∃ b : β, s ≈ const abv b) end section variables {β : Type*} [ring β] {abv : β → α} [is_absolute_value abv] variable [is_complete β abv] lemma complete : ∀ s : cau_seq β abv, ∃ b : β, s ≈ const abv b := is_complete.is_complete /-- The limit of a Cauchy sequence in a complete ring. Chosen non-computably. -/ noncomputable def lim (s : cau_seq β abv) : β := classical.some (complete s) lemma equiv_lim (s : cau_seq β abv) : s ≈ const abv (lim s) := classical.some_spec (complete s) lemma eq_lim_of_const_equiv {f : cau_seq β abv} {x : β} (h : cau_seq.const abv x ≈ f) : x = lim f := const_equiv.mp $ setoid.trans h $ equiv_lim f lemma lim_eq_of_equiv_const {f : cau_seq β abv} {x : β} (h : f ≈ cau_seq.const abv x) : lim f = x := (eq_lim_of_const_equiv $ setoid.symm h).symm lemma lim_eq_lim_of_equiv {f g : cau_seq β abv} (h : f ≈ g) : lim f = lim g := lim_eq_of_equiv_const $ setoid.trans h $ equiv_lim g @[simp] lemma lim_const (x : β) : lim (const abv x) = x := lim_eq_of_equiv_const $ setoid.refl _ lemma lim_add (f g : cau_seq β abv) : lim f + lim g = lim (f + g) := eq_lim_of_const_equiv $ show lim_zero (const abv (lim f + lim g) - (f + g)), by rw [const_add, add_sub_add_comm]; exact add_lim_zero (setoid.symm (equiv_lim f)) (setoid.symm (equiv_lim g)) lemma lim_mul_lim (f g : cau_seq β abv) : lim f * lim g = lim (f * g) := eq_lim_of_const_equiv $ show lim_zero (const abv (lim f * lim g) - f * g), from have h : const abv (lim f * lim g) - f * g = (const abv (lim f) - f) * g + const abv (lim f) * (const abv (lim g) - g) := by simp [const_mul (lim f), mul_add, add_mul, sub_eq_add_neg, add_comm, add_left_comm], by rw h; exact add_lim_zero (mul_lim_zero_left _ (setoid.symm (equiv_lim _))) (mul_lim_zero_right _ (setoid.symm (equiv_lim _))) lemma lim_mul (f : cau_seq β abv) (x : β) : lim f * x = lim (f * const abv x) := by rw [← lim_mul_lim, lim_const] lemma lim_neg (f : cau_seq β abv) : lim (-f) = -lim f := lim_eq_of_equiv_const (show lim_zero (-f - const abv (-lim f)), by rw [const_neg, sub_neg_eq_add, add_comm, ← sub_eq_add_neg]; exact setoid.symm (equiv_lim f)) lemma lim_eq_zero_iff (f : cau_seq β abv) : lim f = 0 ↔ lim_zero f := ⟨assume h, by have hf := equiv_lim f; rw h at hf; exact (lim_zero_congr hf).mpr (const_lim_zero.mpr rfl), assume h, have h₁ : f = (f - const abv 0) := ext (λ n, by simp [sub_apply, const_apply]), by rw h₁ at h; exact lim_eq_of_equiv_const h ⟩ end section variables {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] [is_complete β abv] lemma lim_inv {f : cau_seq β abv} (hf : ¬ lim_zero f) : lim (inv f hf) = (lim f)⁻¹ := have hl : lim f ≠ 0 := by rwa ← lim_eq_zero_iff at hf, lim_eq_of_equiv_const $ show lim_zero (inv f hf - const abv (lim f)⁻¹), from have h₁ : ∀ (g f : cau_seq β abv) (hf : ¬ lim_zero f), lim_zero (g - f * inv f hf * g) := λ g f hf, by rw [← one_mul g, ← mul_assoc, ← sub_mul, mul_one, mul_comm, mul_comm f]; exact mul_lim_zero_right _ (setoid.symm (cau_seq.inv_mul_cancel _)), have h₂ : lim_zero ((inv f hf - const abv (lim f)⁻¹) - (const abv (lim f) - f) * (inv f hf * const abv (lim f)⁻¹)) := by rw [sub_mul, ← sub_add, sub_sub, sub_add_eq_sub_sub, sub_right_comm, sub_add]; exact show lim_zero (inv f hf - const abv (lim f) * (inv f hf * const abv (lim f)⁻¹) - (const abv (lim f)⁻¹ - f * (inv f hf * const abv (lim f)⁻¹))), from sub_lim_zero (by rw [← mul_assoc, mul_right_comm, const_inv hl]; exact h₁ _ _ _) (by rw [← mul_assoc]; exact h₁ _ _ _), (lim_zero_congr h₂).mpr $ mul_lim_zero_left _ (setoid.symm (equiv_lim f)) end section variables [is_complete α abs] lemma lim_le {f : cau_seq α abs} {x : α} (h : f ≤ cau_seq.const abs x) : lim f ≤ x := cau_seq.const_le.1 $ cau_seq.le_of_eq_of_le (setoid.symm (equiv_lim f)) h lemma le_lim {f : cau_seq α abs} {x : α} (h : cau_seq.const abs x ≤ f) : x ≤ lim f := cau_seq.const_le.1 $ cau_seq.le_of_le_of_eq h (equiv_lim f) lemma lt_lim {f : cau_seq α abs} {x : α} (h : cau_seq.const abs x < f) : x < lim f := cau_seq.const_lt.1 $ cau_seq.lt_of_lt_of_eq h (equiv_lim f) lemma lim_lt {f : cau_seq α abs} {x : α} (h : f < cau_seq.const abs x) : lim f < x := cau_seq.const_lt.1 $ cau_seq.lt_of_eq_of_lt (setoid.symm (equiv_lim f)) h end end cau_seq
4eda5b203cc9a56463df7533f861777516d16916
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
/src/number_theory/arithmetic_function.lean
3b31c691341be0efc9b56769272931e9f4515e9e
[ "Apache-2.0" ]
permissive
molodiuc/mathlib
cae2ba3ef1601c1f42ca0b625c79b061b63fef5b
98ebe5a6739fbe254f9ee9d401882d4388f91035
refs/heads/master
1,674,237,127,059
1,606,353,533,000
1,606,353,533,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
23,705
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import algebra.big_operators.ring import number_theory.divisors import algebra.squarefree import algebra.invertible /-! # Arithmetic Functions and Dirichlet Convolution This file defines arithmetic functions, which are functions from `ℕ` to a specified type that map 0 to 0. In the literature, they are often instead defined as functions from `ℕ+`. These arithmetic functions are endowed with a multiplication, given by Dirichlet convolution, and pointwise addition, to form the Dirichlet ring. ## Main Definitions * `arithmetic_function R` consists of functions `f : ℕ → R` such that `f 0 = 0`. * An arithmetic function `f` `is_multiplicative` when `x.coprime y → f (x * y) = f x * f y`. * The pointwise operations `pmul` and `ppow` differ from the multiplication and power instances on `arithmetic_function R`, which use Dirichlet multiplication. * `ζ` is the arithmetic function such that `ζ x = 1` for `0 < x`. * `σ k` is the arithmetic function such that `σ k x = ∑ y in divisors x, y ^ k` for `0 < x`. * `pow k` is the arithmetic function such that `pow k x = x ^ k` for `0 < x`. * `id` is the identity arithmetic function on `ℕ`. * `ω n` is the number of distinct prime factors of `n`. * `Ω n` is the number of prime factors of `n` counted with multiplicity. * `μ` is the Möbius function. ## Notation The arithmetic functions `ζ` and `σ` have Greek letter names, which are localized notation in the namespace `arithmetic_function`. ## Tags arithmetic functions, dirichlet convolution, divisors -/ open finset open_locale big_operators namespace nat variable (R : Type*) /-- An arithmetic function is a function from `ℕ` that maps 0 to 0. In the literature, they are often instead defined as functions from `ℕ+`. Multiplication on `arithmetic_functions` is by Dirichlet convolution. -/ @[derive [has_coe_to_fun, has_zero, inhabited]] def arithmetic_function [has_zero R] := zero_hom ℕ R variable {R} namespace arithmetic_function section has_zero variable [has_zero R] @[simp] lemma to_fun_eq (f : arithmetic_function R) : f.to_fun = f := rfl @[simp] lemma map_zero {f : arithmetic_function R} : f 0 = 0 := zero_hom.map_zero' f theorem coe_inj {f g : arithmetic_function R} : (f : ℕ → R) = g ↔ f = g := ⟨λ h, zero_hom.coe_inj h, λ h, h ▸ rfl⟩ @[simp] lemma zero_apply {x : ℕ} : (0 : arithmetic_function R) x = 0 := zero_hom.zero_apply x @[ext] theorem ext ⦃f g : arithmetic_function R⦄ (h : ∀ x, f x = g x) : f = g := zero_hom.ext h theorem ext_iff {f g : arithmetic_function R} : f = g ↔ ∀ x, f x = g x := zero_hom.ext_iff section has_one variable [has_one R] instance : has_one (arithmetic_function R) := ⟨⟨λ x, ite (x = 1) 1 0, rfl⟩⟩ @[simp] lemma one_one : (1 : arithmetic_function R) 1 = 1 := rfl @[simp] lemma one_apply_ne {x : ℕ} (h : x ≠ 1) : (1 : arithmetic_function R) x = 0 := if_neg h end has_one end has_zero instance nat_coe [semiring R] : has_coe (arithmetic_function ℕ) (arithmetic_function R) := ⟨λ f, ⟨↑(f : ℕ → ℕ), by { transitivity ↑(f 0), refl, simp }⟩⟩ @[simp] lemma nat_coe_apply [semiring R] {f : arithmetic_function ℕ} {x : ℕ} : (f : arithmetic_function R) x = f x := rfl instance int_coe [ring R] : has_coe (arithmetic_function ℤ) (arithmetic_function R) := ⟨λ f, ⟨↑(f : ℕ → ℤ), by { transitivity ↑(f 0), refl, simp }⟩⟩ @[simp] lemma int_coe_apply [ring R] {f : arithmetic_function ℤ} {x : ℕ} : (f : arithmetic_function R) x = f x := rfl @[simp] lemma coe_coe [ring R] {f : arithmetic_function ℕ} : ((f : arithmetic_function ℤ) : arithmetic_function R) = f := by { ext, simp, } section add_monoid variable [add_monoid R] instance : has_add (arithmetic_function R) := ⟨λ f g, ⟨λ n, f n + g n, by simp⟩⟩ @[simp] lemma add_apply {f g : arithmetic_function R} {n : ℕ} : (f + g) n = f n + g n := rfl instance : add_monoid (arithmetic_function R) := { add_assoc := λ _ _ _, ext (λ _, add_assoc _ _ _), zero_add := λ _, ext (λ _, zero_add _), add_zero := λ _, ext (λ _, add_zero _), .. arithmetic_function.has_zero R, .. arithmetic_function.has_add } end add_monoid instance [add_comm_monoid R] : add_comm_monoid (arithmetic_function R) := { add_comm := λ _ _, ext (λ _, add_comm _ _), .. arithmetic_function.add_monoid } instance [add_group R] : add_group (arithmetic_function R) := { neg := λ f, ⟨λ n, - f n, by simp⟩, add_left_neg := λ _, ext (λ _, add_left_neg _), .. arithmetic_function.add_monoid } instance [add_comm_group R] : add_comm_group (arithmetic_function R) := { .. arithmetic_function.add_comm_monoid, .. arithmetic_function.add_group } section dirichlet_ring variable [semiring R] /-- The Dirichlet convolution of two arithmetic functions `f` and `g` is another arithmetic function such that `(f * g) n` is the sum of `f x * g y` over all `(x,y)` such that `x * y = n`. -/ instance : has_mul (arithmetic_function R) := ⟨λ f g, ⟨λ n, ∑ x in divisors_antidiagonal n, f x.fst * g x.snd, by simp⟩⟩ @[simp] lemma mul_apply {f g : arithmetic_function R} {n : ℕ} : (f * g) n = ∑ x in divisors_antidiagonal n, f x.fst * g x.snd := rfl instance : monoid (arithmetic_function R) := { one_mul := λ f, begin ext, rw mul_apply, by_cases x0 : x = 0, {simp [x0]}, have h : {(1,x)} ⊆ divisors_antidiagonal x := by simp [x0], rw ← sum_subset h, {simp}, intros y ymem ynmem, have y1ne : y.fst ≠ 1, { intro con, simp only [con, mem_divisors_antidiagonal, one_mul, ne.def] at ymem, simp only [mem_singleton, prod.ext_iff] at ynmem, tauto }, simp [y1ne], end, mul_one := λ f, begin ext, rw mul_apply, by_cases x0 : x = 0, {simp [x0]}, have h : {(x,1)} ⊆ divisors_antidiagonal x := by simp [x0], rw ← sum_subset h, {simp}, intros y ymem ynmem, have y2ne : y.snd ≠ 1, { intro con, simp only [con, mem_divisors_antidiagonal, mul_one, ne.def] at ymem, simp only [mem_singleton, prod.ext_iff] at ynmem, tauto }, simp [y2ne], end, mul_assoc := λ f g h, begin ext n, simp only [mul_apply], have := @finset.sum_sigma (ℕ × ℕ) R _ _ (divisors_antidiagonal n) (λ p, (divisors_antidiagonal p.1)) (λ x, f x.2.1 * g x.2.2 * h x.1.2), convert this.symm using 1; clear this, { apply finset.sum_congr rfl, intros p hp, exact finset.sum_mul }, have := @finset.sum_sigma (ℕ × ℕ) R _ _ (divisors_antidiagonal n) (λ p, (divisors_antidiagonal p.2)) (λ x, f x.1.1 * (g x.2.1 * h x.2.2)), convert this.symm using 1; clear this, { apply finset.sum_congr rfl, intros p hp, rw finset.mul_sum }, apply finset.sum_bij, swap 5, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, exact ⟨(k, l*j), (l, j)⟩ }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, simp only [finset.mem_sigma, mem_divisors_antidiagonal] at H ⊢, finish }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, simp only [mul_assoc] }, { rintros ⟨⟨a,b⟩, ⟨c,d⟩⟩ ⟨⟨i,j⟩, ⟨k,l⟩⟩ H₁ H₂, simp only [finset.mem_sigma, mem_divisors_antidiagonal, and_imp, prod.mk.inj_iff, add_comm, heq_iff_eq] at H₁ H₂ ⊢, finish }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, refine ⟨⟨(i*k, l), (i, k)⟩, _, _⟩; { simp only [finset.mem_sigma, mem_divisors_antidiagonal] at H ⊢, finish } } end, .. arithmetic_function.has_one, .. arithmetic_function.has_mul } instance : semiring (arithmetic_function R) := { zero_mul := λ f, by { ext, simp, }, mul_zero := λ f, by { ext, simp, }, left_distrib := λ a b c, by { ext, simp [← sum_add_distrib, mul_add] }, right_distrib := λ a b c, by { ext, simp [← sum_add_distrib, add_mul] }, .. arithmetic_function.has_zero R, .. arithmetic_function.has_mul, .. arithmetic_function.has_add, .. arithmetic_function.add_comm_monoid, .. arithmetic_function.monoid } end dirichlet_ring instance [comm_semiring R] : comm_semiring (arithmetic_function R) := { mul_comm := λ f g, by { ext, rw [mul_apply, ← map_swap_divisors_antidiagonal, sum_map], simp [mul_comm] }, .. arithmetic_function.semiring } instance [comm_ring R] : comm_ring (arithmetic_function R) := { .. arithmetic_function.add_comm_group, .. arithmetic_function.comm_semiring } section zeta /-- `ζ 0 = 0`, otherwise `ζ x = 1`. The Dirichlet Series is the Riemann ζ. -/ def zeta [has_zero R] [has_one R] : arithmetic_function R := ⟨λ x, ite (x = 0) 0 1, rfl⟩ localized "notation `ζ` := zeta" in arithmetic_function @[simp] lemma zeta_apply [has_zero R] [has_one R] {x : ℕ} : (ζ x : R) = if (x = 0) then 0 else 1 := rfl lemma zeta_apply_ne [has_zero R] [has_one R] {x : ℕ} (h : x ≠ 0) : ζ x = (1 : R) := if_neg h theorem zeta_mul_apply [semiring R] {f : arithmetic_function R} {x : ℕ} : (ζ * f) x = ∑ i in divisors x, f i := begin rw mul_apply, transitivity ∑ i in divisors_antidiagonal x, f i.snd, { apply sum_congr rfl, intros i hi, rcases mem_divisors_antidiagonal.1 hi with ⟨rfl, h⟩, rw [zeta_apply_ne (left_ne_zero_of_mul h), one_mul] }, { apply sum_bij (λ i h, prod.snd i), { rintros ⟨a, b⟩ h, simp [snd_mem_divisors_of_mem_antidiagonal h] }, { rintros ⟨a, b⟩ h, refl }, { rintros ⟨a1, b1⟩ ⟨a2, b2⟩ h1 h2 h, dsimp at h, rw h at *, rw mem_divisors_antidiagonal at *, ext, swap, {refl}, simp only [prod.fst, prod.snd] at *, apply nat.eq_of_mul_eq_mul_right _ (eq.trans h1.1 h2.1.symm), rcases h1 with ⟨rfl, h⟩, apply nat.pos_of_ne_zero (right_ne_zero_of_mul h) }, { intros a ha, rcases mem_divisors.1 ha with ⟨⟨b, rfl⟩, ne0⟩, use (b, a), simp [ne0, mul_comm] } } end theorem mul_zeta_apply [semiring R] {f : arithmetic_function R} {x : ℕ} : (f * ζ) x = ∑ i in divisors x, f i := begin apply opposite.op_injective, rw [op_sum], convert @zeta_mul_apply Rᵒᵖ _ { to_fun := opposite.op ∘ f, map_zero' := by simp} x, rw [mul_apply, mul_apply, op_sum], conv_lhs { rw ← map_swap_divisors_antidiagonal, }, rw sum_map, apply sum_congr rfl, intros y hy, by_cases h1 : y.fst = 0, { simp [function.comp_apply, h1] }, { simp only [h1, mul_one, one_mul, prod.fst_swap, function.embedding.coe_fn_mk, prod.snd_swap, if_false, zeta_apply, zero_hom.coe_mk] } end end zeta open_locale arithmetic_function section pmul /-- This is the pointwise product of `arithmetic_function`s. -/ def pmul [mul_zero_class R] (f g : arithmetic_function R) : arithmetic_function R := ⟨λ x, f x * g x, by simp⟩ @[simp] lemma pmul_apply [mul_zero_class R] {f g : arithmetic_function R} {x : ℕ} : f.pmul g x = f x * g x := rfl lemma pmul_comm [comm_monoid_with_zero R] (f g : arithmetic_function R) : f.pmul g = g.pmul f := by { ext, simp [mul_comm] } variable [monoid_with_zero R] @[simp] lemma pmul_zeta (f : arithmetic_function R) : f.pmul ζ = f := begin ext x, cases x; simp [nat.succ_ne_zero], end @[simp] lemma zeta_pmul (f : arithmetic_function R) : (ζ).pmul f = f := begin ext x, cases x; simp [nat.succ_ne_zero], end /-- This is the pointwise power of `arithmetic_function`s. -/ def ppow (f : arithmetic_function R) (k : ℕ) : arithmetic_function R := if h0 : k = 0 then ζ else ⟨λ x, (f x) ^ k, by { rw [map_zero], exact zero_pow (nat.pos_of_ne_zero h0) }⟩ @[simp] lemma ppow_zero {f : arithmetic_function R} : f.ppow 0 = ζ := by rw [ppow, dif_pos rfl] @[simp] lemma ppow_apply {f : arithmetic_function R} {k x : ℕ} (kpos : 0 < k) : f.ppow k x = (f x) ^ k := by { rw [ppow, dif_neg (ne_of_gt kpos)], refl } lemma ppow_succ {f : arithmetic_function R} {k : ℕ} : f.ppow (k + 1) = f.pmul (f.ppow k) := begin ext x, rw [ppow_apply (nat.succ_pos k), pow_succ], induction k; simp, end lemma ppow_succ' {f : arithmetic_function R} {k : ℕ} {kpos : 0 < k} : f.ppow (k + 1) = (f.ppow k).pmul f := begin ext x, rw [ppow_apply (nat.succ_pos k), pow_succ'], induction k; simp, end end pmul /-- Multiplicative functions -/ def is_multiplicative [monoid_with_zero R] (f : arithmetic_function R) : Prop := f 1 = 1 ∧ (∀ {m n : ℕ}, m.coprime n → f (m * n) = f m * f n) namespace is_multiplicative section monoid_with_zero variable [monoid_with_zero R] @[simp] lemma map_one {f : arithmetic_function R} (h : f.is_multiplicative) : f 1 = 1 := h.1 @[simp] lemma map_mul_of_coprime {f : arithmetic_function R} (hf : f.is_multiplicative) {m n : ℕ} (h : m.coprime n) : f (m * n) = f m * f n := hf.2 h end monoid_with_zero lemma nat_cast {f : arithmetic_function ℕ} [semiring R] (h : f.is_multiplicative) : is_multiplicative (f : arithmetic_function R) := ⟨by simp [h], λ m n cop, by simp [cop, h]⟩ lemma int_cast {f : arithmetic_function ℤ} [ring R] (h : f.is_multiplicative) : is_multiplicative (f : arithmetic_function R) := ⟨by simp [h], λ m n cop, by simp [cop, h]⟩ lemma mul [comm_semiring R] {f g : arithmetic_function R} (hf : f.is_multiplicative) (hg : g.is_multiplicative) : is_multiplicative (f * g) := ⟨by { simp [hf, hg], }, begin simp only [mul_apply], intros m n cop, rw sum_mul_sum, symmetry, apply sum_bij (λ (x : (ℕ × ℕ) × ℕ × ℕ) h, (x.1.1 * x.2.1, x.1.2 * x.2.2)), { rintros ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ h, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at h, rcases h with ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩, simp only [mem_divisors_antidiagonal, nat.mul_eq_zero, ne.def], split, {ring}, rw nat.mul_eq_zero at *, apply not_or ha hb }, { rintros ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ h, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at h, rcases h with ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩, dsimp only, rw [hf.map_mul_of_coprime cop.coprime_mul_right.coprime_mul_right_right, hg.map_mul_of_coprime cop.coprime_mul_left.coprime_mul_left_right], ring, }, { rintros ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ ⟨⟨c1, c2⟩, ⟨d1, d2⟩⟩ hab hcd h, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at hab, rcases hab with ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at hcd, simp only [prod.mk.inj_iff] at h, ext; dsimp only, { transitivity nat.gcd (a1 * a2) (a1 * b1), { rw [nat.gcd_mul_left, cop.coprime_mul_left.coprime_mul_right_right.gcd_eq_one, mul_one] }, { rw [← hcd.1.1, ← hcd.2.1] at cop, rw [← hcd.1.1, h.1, nat.gcd_mul_left, cop.coprime_mul_left.coprime_mul_right_right.gcd_eq_one, mul_one] } }, { transitivity nat.gcd (a1 * a2) (a2 * b2), { rw [mul_comm, nat.gcd_mul_left, cop.coprime_mul_right.coprime_mul_left_right.gcd_eq_one, mul_one] }, { rw [← hcd.1.1, ← hcd.2.1] at cop, rw [← hcd.1.1, h.2, mul_comm, nat.gcd_mul_left, cop.coprime_mul_right.coprime_mul_left_right.gcd_eq_one, mul_one] } }, { transitivity nat.gcd (b1 * b2) (a1 * b1), { rw [mul_comm, nat.gcd_mul_right, cop.coprime_mul_right.coprime_mul_left_right.symm.gcd_eq_one, one_mul] }, { rw [← hcd.1.1, ← hcd.2.1] at cop, rw [← hcd.2.1, h.1, mul_comm c1 d1, nat.gcd_mul_left, cop.coprime_mul_right.coprime_mul_left_right.symm.gcd_eq_one, mul_one] } }, { transitivity nat.gcd (b1 * b2) (a2 * b2), { rw [nat.gcd_mul_right, cop.coprime_mul_left.coprime_mul_right_right.symm.gcd_eq_one, one_mul] }, { rw [← hcd.1.1, ← hcd.2.1] at cop, rw [← hcd.2.1, h.2, nat.gcd_mul_right, cop.coprime_mul_left.coprime_mul_right_right.symm.gcd_eq_one, one_mul] } } }, { rintros ⟨b1, b2⟩ h, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at h, use ((b1.gcd m, b2.gcd m), (b1.gcd n, b2.gcd n)), simp only [exists_prop, prod.mk.inj_iff, ne.def, mem_product, mem_divisors_antidiagonal], rw [← cop.gcd_mul _, ← cop.gcd_mul _, ← h.1, nat.gcd_mul_gcd_of_coprime_of_mul_eq_mul cop h.1, nat.gcd_mul_gcd_of_coprime_of_mul_eq_mul cop.symm _], { rw [nat.mul_eq_zero, decidable.not_or_iff_and_not] at h, simp [h.2.1, h.2.2] }, rw [mul_comm n m, h.1] } end⟩ lemma pmul [comm_semiring R] {f g : arithmetic_function R} (hf : f.is_multiplicative) (hg : g.is_multiplicative) : is_multiplicative (f.pmul g) := ⟨by { simp [hf, hg], }, λ m n cop, begin simp only [pmul_apply, hf.map_mul_of_coprime cop, hg.map_mul_of_coprime cop], ring, end⟩ end is_multiplicative section special_functions /-- The identity on `ℕ` as an `arithmetic_function`. -/ def id : arithmetic_function ℕ := ⟨id, rfl⟩ @[simp] lemma id_apply {x : ℕ} : id x = x := rfl /-- `pow k n = n ^ k`, except `pow 0 0 = 0`. -/ def pow (k : ℕ) : arithmetic_function ℕ := id.ppow k @[simp] lemma pow_apply {k n : ℕ} : pow k n = if (k = 0 ∧ n = 0) then 0 else n ^ k := begin cases k, { simp [pow] }, simp [pow, (ne_of_lt (nat.succ_pos k)).symm], end /-- `σ k n` is the sum of the `k`th powers of the divisors of `n` -/ def sigma (k : ℕ) : arithmetic_function ℕ := ⟨λ n, ∑ d in divisors n, d ^ k, by simp⟩ localized "notation `σ` := sigma" in arithmetic_function @[simp] lemma sigma_apply {k n : ℕ} : σ k n = ∑ d in divisors n, d ^ k := rfl lemma sigma_one_apply {n : ℕ} : σ 1 n = ∑ d in divisors n, d := by simp lemma zeta_mul_pow_eq_sigma {k : ℕ} : ζ * pow k = σ k := begin ext, rw [sigma, zeta_mul_apply], apply sum_congr rfl, intros x hx, rw [pow_apply, if_neg (not_and_of_not_right _ _)], contrapose! hx, simp [hx], end lemma is_multiplicative_zeta [semiring R] : is_multiplicative (ζ : arithmetic_function R) := ⟨by simp, λ m n cop, begin cases m, {simp}, cases n, {simp}, rw [zeta_apply_ne (mul_ne_zero _ _), zeta_apply_ne, zeta_apply_ne, mul_one], repeat { apply nat.succ_ne_zero }, end⟩ lemma is_multiplicative_id : is_multiplicative arithmetic_function.id := ⟨rfl, λ _ _ _, rfl⟩ lemma is_multiplicative.ppow [comm_semiring R] {f : arithmetic_function R} (hf : f.is_multiplicative) {k : ℕ} : is_multiplicative (f.ppow k) := begin induction k with k hi, { exact is_multiplicative_zeta }, { rw ppow_succ, apply hf.pmul hi }, end lemma is_multiplicative_pow {k : ℕ} : is_multiplicative (pow k) := is_multiplicative_id.ppow lemma is_multiplicative_sigma {k : ℕ} : is_multiplicative (sigma k) := begin rw [← zeta_mul_pow_eq_sigma], apply ((is_multiplicative_zeta).mul is_multiplicative_pow) end /-- `Ω n` is the number of prime factors of `n`. -/ def card_factors : arithmetic_function ℕ := ⟨λ n, n.factors.length, rfl⟩ localized "notation `Ω` := card_factors" in arithmetic_function lemma card_factors_apply {n : ℕ} : Ω n = n.factors.length := rfl @[simp] lemma card_factors_one : Ω 1 = 0 := rfl lemma card_factors_eq_one_iff_prime {n : ℕ} : Ω n = 1 ↔ n.prime := begin refine ⟨λ h, _, λ h, list.length_eq_one.2 ⟨n, factors_prime h⟩⟩, cases n, { contrapose! h, simp }, rcases list.length_eq_one.1 h with ⟨x, hx⟩, rw [← prod_factors n.succ_pos, hx, list.prod_singleton], apply mem_factors, rw [hx, list.mem_singleton] end lemma card_factors_mul {m n : ℕ} (m0 : m ≠ 0) (n0 : n ≠ 0) : Ω (m * n) = Ω m + Ω n := by rw [card_factors_apply, card_factors_apply, card_factors_apply, ← multiset.coe_card, ← factors_eq, unique_factorization_monoid.factors_mul m0 n0, factors_eq, factors_eq, multiset.card_add, multiset.coe_card, multiset.coe_card] lemma card_factors_multiset_prod {s : multiset ℕ} (h0 : s.prod ≠ 0) : Ω s.prod = (multiset.map Ω s).sum := begin revert h0, apply s.induction_on, { intro h, refl }, intros a t h h0, rw [multiset.prod_cons, mul_ne_zero_iff] at h0, simp [h0, card_factors_mul, h], end /-- `ω n` is the number of distinct prime factors of `n`. -/ def card_distinct_factors : arithmetic_function ℕ := ⟨λ n, n.factors.erase_dup.length, rfl⟩ localized "notation `ω` := card_distinct_factors" in arithmetic_function @[simp] lemma card_distinct_factors_zero : ω 0 = 0 := rfl lemma card_distinct_factors_apply {n : ℕ} : ω n = n.factors.erase_dup.length := rfl lemma card_distinct_factors_eq_card_factors_iff_squarefree {n : ℕ} (h0 : n ≠ 0) : ω n = Ω n ↔ squarefree n := begin rw [squarefree_iff_nodup_factors h0, card_distinct_factors_apply], split; intro h, { rw ← list.eq_of_sublist_of_length_eq n.factors.erase_dup_sublist h, apply list.nodup_erase_dup }, { rw list.erase_dup_eq_self.2 h, refl } end /-- `μ` is the Möbius function. If `n` is squarefree with an even number of distinct prime factors, `μ n = 1`. If `n` is squarefree with an odd number of distinct prime factors, `μ n = -1`. If `n` is not squarefree, `μ n = 0`. -/ def moebius : arithmetic_function ℤ := ⟨λ n, if squarefree n then (-1) ^ (card_factors n) else 0, by simp⟩ localized "notation `μ` := moebius" in arithmetic_function @[simp] lemma moebius_apply_of_squarefree {n : ℕ} (h : squarefree n): μ n = (-1) ^ (card_factors n) := if_pos h @[simp] lemma moebius_eq_zero_of_not_squarefree {n : ℕ} (h : ¬ squarefree n): μ n = 0 := if_neg h lemma moebius_ne_zero_iff_squarefree {n : ℕ} : μ n ≠ 0 ↔ squarefree n := begin split; intro h, { contrapose! h, simp [h] }, { simp [h, pow_ne_zero] } end lemma moebius_ne_zero_iff_eq_or {n : ℕ} : μ n ≠ 0 ↔ μ n = 1 ∨ μ n = -1 := begin split; intro h, { rw moebius_ne_zero_iff_squarefree at h, rw moebius_apply_of_squarefree h, apply neg_one_pow_eq_or }, { rcases h with h | h; simp [h] } end open unique_factorization_monoid /-- Moebius Inversion -/ @[simp] lemma moebius_mul_zeta : μ * ζ = 1 := begin ext x, cases x, simp, cases x, simp, rw [mul_zeta_apply, one_apply_ne (ne_of_gt (succ_lt_succ (nat.succ_pos _)))], rw ← sum_filter_ne_zero, simp only [moebius_ne_zero_iff_squarefree], transitivity, convert (sum_divisors_filter_squarefree (nat.succ_ne_zero _)), apply eq.trans (sum_congr rfl _) (sum_powerset_neg_one_pow_card_of_nonempty _), { intros y hy, rw [finset.mem_powerset, ← finset.val_le_iff, multiset.to_finset_val] at hy, have h : unique_factorization_monoid.factors y.val.prod = y.val, { apply factors_multiset_prod_of_irreducible, intros z hz, apply irreducible_of_factor _ (multiset.subset_of_le (le_trans hy (multiset.erase_dup_le _)) hz) }, rw [if_pos], { rw [card_factors_apply, ← multiset.coe_card, ← factors_eq, h, finset.card] }, rw [unique_factorization_monoid.squarefree_iff_nodup_factors, h], { apply y.nodup }, rw [ne.def, multiset.prod_eq_zero_iff], intro con, rw ← h at con, exact not_irreducible_zero (irreducible_of_factor 0 con) }, { rw finset.nonempty, rcases wf_dvd_monoid.exists_irreducible_factor _ (nat.succ_ne_zero _) with ⟨i, hi⟩, { rcases exists_mem_factors_of_dvd (nat.succ_ne_zero _) hi.1 hi.2 with ⟨j, hj, hj2⟩, use j, apply multiset.mem_to_finset.2 hj }, rw nat.is_unit_iff, omega }, end @[simp] lemma zeta_mul_moebius : ζ * μ = 1 := by rw [mul_comm, moebius_mul_zeta] instance : invertible ζ := { inv_of := μ, inv_of_mul_self := moebius_mul_zeta, mul_inv_of_self := zeta_mul_moebius} end special_functions end arithmetic_function end nat
35b05f8cc946c1bff8c0c8f4c3563be55434eca9
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/complex/abs_max.lean
5690a779be8603914eaeb9726398886fb31684bd
[ "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
22,854
lean
/- Copyright (c) 2022 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import analysis.complex.cauchy_integral import analysis.normed_space.completion import analysis.normed_space.extr import topology.algebra.order.extr_closure /-! # Maximum modulus principle > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove several versions of the maximum modulus principle. There are several statements that can be called "the maximum modulus principle" for maps between normed complex spaces. They differ by assumptions on the domain (any space, a nontrivial space, a finite dimensional space), assumptions on the codomain (any space, a strictly convex space), and by conclusion (either equality of norms or of the values of the function). ## Main results ### Theorems for any codomain Consider a function `f : E → F` that is complex differentiable on a set `s`, is continuous on its closure, and `‖f x‖` has a maximum on `s` at `c`. We prove the following theorems. - `complex.norm_eq_on_closed_ball_of_is_max_on`: if `s = metric.ball c r`, then `‖f x‖ = ‖f c‖` for any `x` from the corresponding closed ball; - `complex.norm_eq_norm_of_is_max_on_of_ball_subset`: if `metric.ball c (dist w c) ⊆ s`, then `‖f w‖ = ‖f c‖`; - `complex.norm_eq_on_of_is_preconnected_of_is_max_on`: if `U` is an open (pre)connected set, `f` is complex differentiable on `U`, and `‖f x‖` has a maximum on `U` at `c ∈ U`, then `‖f x‖ = ‖f c‖` for all `x ∈ U`; - `complex.norm_eq_on_closure_of_is_preconnected_of_is_max_on`: if `s` is open and (pre)connected and `c ∈ s`, then `‖f x‖ = ‖f c‖` for all `x ∈ closure s`; - `complex.norm_eventually_eq_of_is_local_max`: if `f` is complex differentiable in a neighborhood of `c` and `‖f x‖` has a local maximum at `c`, then `‖f x‖` is locally a constant in a neighborhood of `c`. ### Theorems for a strictly convex codomain If the codomain `F` is a strictly convex space, then in the lemmas from the previous section we can prove `f w = f c` instead of `‖f w‖ = ‖f c‖`, see `complex.eq_on_of_is_preconnected_of_is_max_on_norm`, `complex.eq_on_closure_of_is_preconnected_of_is_max_on_norm`, `complex.eq_of_is_max_on_of_ball_subset`, `complex.eq_on_closed_ball_of_is_max_on_norm`, and `complex.eventually_eq_of_is_local_max_norm`. ### Values on the frontier Finally, we prove some corollaries that relate the (norm of the) values of a function on a set to its values on the frontier of the set. All these lemmas assume that `E` is a nontrivial space. In this section `f g : E → F` are functions that are complex differentiable on a bounded set `s` and are continuous on its closure. We prove the following theorems. - `complex.exists_mem_frontier_is_max_on_norm`: If `E` is a finite dimensional space and `s` is a nonempty bounded set, then there exists a point `z ∈ frontier s` such that `λ z, ‖f z‖` takes it maximum value on `closure s` at `z`. - `complex.norm_le_of_forall_mem_frontier_norm_le`: if `‖f z‖ ≤ C` for all `z ∈ frontier s`, then `‖f z‖ ≤ C` for all `z ∈ s`; note that this theorem does not require `E` to be a finite dimensional space. - `complex.eq_on_closure_of_eq_on_frontier`: if `f x = g x` on the frontier of `s`, then `f x = g x` on `closure s`; - `complex.eq_on_of_eq_on_frontier`: if `f x = g x` on the frontier of `s`, then `f x = g x` on `s`. ## Tags maximum modulus principle, complex analysis -/ open topological_space metric set filter asymptotics function measure_theory affine_map open_locale topology filter nnreal real universes u v w variables {E : Type u} [normed_add_comm_group E] [normed_space ℂ E] {F : Type v} [normed_add_comm_group F] [normed_space ℂ F] local postfix `̂`:100 := uniform_space.completion namespace complex /-! ### Auxiliary lemmas We split the proof into a series of lemmas. First we prove the principle for a function `f : ℂ → F` with an additional assumption that `F` is a complete space, then drop unneeded assumptions one by one. The lemmas with names `*_auxₙ` are considered to be private and should not be used outside of this file. -/ lemma norm_max_aux₁ [complete_space F] {f : ℂ → F} {z w : ℂ} (hd : diff_cont_on_cl ℂ f (ball z (dist w z))) (hz : is_max_on (norm ∘ f) (closed_ball z (dist w z)) z) : ‖f w‖ = ‖f z‖ := begin /- Consider a circle of radius `r = dist w z`. -/ set r : ℝ := dist w z, have hw : w ∈ closed_ball z r, from mem_closed_ball.2 le_rfl, /- Assume the converse. Since `‖f w‖ ≤ ‖f z‖`, we have `‖f w‖ < ‖f z‖`. -/ refine (is_max_on_iff.1 hz _ hw).antisymm (not_lt.1 _), rintro hw_lt : ‖f w‖ < ‖f z‖, have hr : 0 < r, from dist_pos.2 (ne_of_apply_ne (norm ∘ f) hw_lt.ne), /- Due to Cauchy integral formula, it suffices to prove the following inequality. -/ suffices : ‖∮ ζ in C(z, r), (ζ - z)⁻¹ • f ζ‖ < 2 * π * ‖f z‖, { refine this.ne _, have A : ∮ ζ in C(z, r), (ζ - z)⁻¹ • f ζ = (2 * π * I : ℂ) • f z := hd.circle_integral_sub_inv_smul (mem_ball_self hr), simp [A, norm_smul, real.pi_pos.le] }, suffices : ‖∮ ζ in C(z, r), (ζ - z)⁻¹ • f ζ‖ < 2 * π * r * (‖f z‖ / r), by rwa [mul_assoc, mul_div_cancel' _ hr.ne'] at this, /- This inequality is true because `‖(ζ - z)⁻¹ • f ζ‖ ≤ ‖f z‖ / r` for all `ζ` on the circle and this inequality is strict at `ζ = w`. -/ have hsub : sphere z r ⊆ closed_ball z r, from sphere_subset_closed_ball, refine circle_integral.norm_integral_lt_of_norm_le_const_of_lt hr _ _ ⟨w, rfl, _⟩, show continuous_on (λ (ζ : ℂ), (ζ - z)⁻¹ • f ζ) (sphere z r), { refine ((continuous_on_id.sub continuous_on_const).inv₀ _).smul (hd.continuous_on_ball.mono hsub), exact λ ζ hζ, sub_ne_zero.2 (ne_of_mem_sphere hζ hr.ne') }, show ∀ ζ ∈ sphere z r, ‖(ζ - z)⁻¹ • f ζ‖ ≤ ‖f z‖ / r, { rintros ζ (hζ : abs (ζ - z) = r), rw [le_div_iff hr, norm_smul, norm_inv, norm_eq_abs, hζ, mul_comm, mul_inv_cancel_left₀ hr.ne'], exact hz (hsub hζ) }, show ‖(w - z)⁻¹ • f w‖ < ‖f z‖ / r, { rw [norm_smul, norm_inv, norm_eq_abs, ← div_eq_inv_mul], exact (div_lt_div_right hr).2 hw_lt } end /-! Now we drop the assumption `complete_space F` by embedding `F` into its completion. -/ lemma norm_max_aux₂ {f : ℂ → F} {z w : ℂ} (hd : diff_cont_on_cl ℂ f (ball z (dist w z))) (hz : is_max_on (norm ∘ f) (closed_ball z (dist w z)) z) : ‖f w‖ = ‖f z‖ := begin set e : F →L[ℂ] F̂ := uniform_space.completion.to_complL, have he : ∀ x, ‖e x‖ = ‖x‖, from uniform_space.completion.norm_coe, replace hz : is_max_on (norm ∘ (e ∘ f)) (closed_ball z (dist w z)) z, by simpa only [is_max_on, (∘), he] using hz, simpa only [he] using norm_max_aux₁ (e.differentiable.comp_diff_cont_on_cl hd) hz end /-! Then we replace the assumption `is_max_on (norm ∘ f) (closed_ball z r) z` with a seemingly weaker assumption `is_max_on (norm ∘ f) (ball z r) z`. -/ lemma norm_max_aux₃ {f : ℂ → F} {z w : ℂ} {r : ℝ} (hr : dist w z = r) (hd : diff_cont_on_cl ℂ f (ball z r)) (hz : is_max_on (norm ∘ f) (ball z r) z) : ‖f w‖ = ‖f z‖ := begin subst r, rcases eq_or_ne w z with rfl|hne, { refl }, rw ← dist_ne_zero at hne, exact norm_max_aux₂ hd (closure_ball z hne ▸ hz.closure hd.continuous_on.norm) end /-! ### Maximum modulus principle for any codomain If we do not assume that the codomain is a strictly convex space, then we can only claim that the **norm** `‖f x‖` is locally constant. -/ /-! Finally, we generalize the theorem from a disk in `ℂ` to a closed ball in any normed space. -/ /-- **Maximum modulus principle** on a closed ball: if `f : E → F` is continuous on a closed ball, is complex differentiable on the corresponding open ball, and the norm `‖f w‖` takes its maximum value on the open ball at its center, then the norm `‖f w‖` is constant on the closed ball. -/ lemma norm_eq_on_closed_ball_of_is_max_on {f : E → F} {z : E} {r : ℝ} (hd : diff_cont_on_cl ℂ f (ball z r)) (hz : is_max_on (norm ∘ f) (ball z r) z) : eq_on (norm ∘ f) (const E ‖f z‖) (closed_ball z r) := begin intros w hw, rw [mem_closed_ball, dist_comm] at hw, rcases eq_or_ne z w with rfl|hne, { refl }, set e : ℂ → E := line_map z w, have hde : differentiable ℂ e := (differentiable_id.smul_const (w - z)).add_const z, suffices : ‖(f ∘ e) (1 : ℂ)‖ = ‖(f ∘ e) (0 : ℂ)‖, by simpa [e], have hr : dist (1 : ℂ) 0 = 1, by simp, have hball : maps_to e (ball 0 1) (ball z r), { refine ((lipschitz_with_line_map z w).maps_to_ball (mt nndist_eq_zero.1 hne) 0 1).mono subset.rfl _, simpa only [line_map_apply_zero, mul_one, coe_nndist] using ball_subset_ball hw }, exact norm_max_aux₃ hr (hd.comp hde.diff_cont_on_cl hball) (hz.comp_maps_to hball (line_map_apply_zero z w)) end /-- **Maximum modulus principle**: if `f : E → F` is complex differentiable on a set `s`, the norm of `f` takes it maximum on `s` at `z`, and `w` is a point such that the closed ball with center `z` and radius `dist w z` is included in `s`, then `‖f w‖ = ‖f z‖`. -/ lemma norm_eq_norm_of_is_max_on_of_ball_subset {f : E → F} {s : set E} {z w : E} (hd : diff_cont_on_cl ℂ f s) (hz : is_max_on (norm ∘ f) s z) (hsub : ball z (dist w z) ⊆ s) : ‖f w‖ = ‖f z‖ := norm_eq_on_closed_ball_of_is_max_on (hd.mono hsub) (hz.on_subset hsub) (mem_closed_ball.2 le_rfl) /-- **Maximum modulus principle**: if `f : E → F` is complex differentiable in a neighborhood of `c` and the norm `‖f z‖` has a local maximum at `c`, then `‖f z‖` is locally constant in a neighborhood of `c`. -/ lemma norm_eventually_eq_of_is_local_max {f : E → F} {c : E} (hd : ∀ᶠ z in 𝓝 c, differentiable_at ℂ f z) (hc : is_local_max (norm ∘ f) c) : ∀ᶠ y in 𝓝 c, ‖f y‖ = ‖f c‖ := begin rcases nhds_basis_closed_ball.eventually_iff.1 (hd.and hc) with ⟨r, hr₀, hr⟩, exact nhds_basis_closed_ball.eventually_iff.2 ⟨r, hr₀, norm_eq_on_closed_ball_of_is_max_on (differentiable_on.diff_cont_on_cl $ λ x hx, (hr $ closure_ball_subset_closed_ball hx).1.differentiable_within_at) (λ x hx, (hr $ ball_subset_closed_ball hx).2)⟩ end lemma is_open_set_of_mem_nhds_and_is_max_on_norm {f : E → F} {s : set E} (hd : differentiable_on ℂ f s) : is_open {z | s ∈ 𝓝 z ∧ is_max_on (norm ∘ f) s z} := begin refine is_open_iff_mem_nhds.2 (λ z hz, (eventually_eventually_nhds.2 hz.1).and _), replace hd : ∀ᶠ w in 𝓝 z, differentiable_at ℂ f w, from hd.eventually_differentiable_at hz.1, exact (norm_eventually_eq_of_is_local_max hd $ (hz.2.is_local_max hz.1)).mono (λ x hx y hy, le_trans (hz.2 hy) hx.ge) end /-- **Maximum modulus principle** on a connected set. Let `U` be a (pre)connected open set in a complex normed space. Let `f : E → F` be a function that is complex differentiable on `U`. Suppose that `‖f x‖` takes its maximum value on `U` at `c ∈ U`. Then `‖f x‖ = ‖f c‖` for all `x ∈ U`. -/ lemma norm_eq_on_of_is_preconnected_of_is_max_on {f : E → F} {U : set E} {c : E} (hc : is_preconnected U) (ho : is_open U) (hd : differentiable_on ℂ f U) (hcU : c ∈ U) (hm : is_max_on (norm ∘ f) U c) : eq_on (norm ∘ f) (const E ‖f c‖) U := begin set V := U ∩ {z | is_max_on (norm ∘ f) U z}, have hV : ∀ x ∈ V, ‖f x‖ = ‖f c‖, from λ x hx, le_antisymm (hm hx.1) (hx.2 hcU), suffices : U ⊆ V, from λ x hx, hV x (this hx), have hVo : is_open V, { simpa only [ho.mem_nhds_iff, set_of_and, set_of_mem_eq] using is_open_set_of_mem_nhds_and_is_max_on_norm hd }, have hVne : (U ∩ V).nonempty := ⟨c, hcU, hcU, hm⟩, set W := U ∩ {z | ‖f z‖ ≠ ‖f c‖}, have hWo : is_open W, from hd.continuous_on.norm.preimage_open_of_open ho is_open_ne, have hdVW : disjoint V W, from disjoint_left.mpr (λ x hxV hxW, hxW.2 (hV x hxV)), have hUVW : U ⊆ V ∪ W, from λ x hx, (eq_or_ne (‖f x‖) (‖f c‖)).imp (λ h, ⟨hx, λ y hy, (hm hy).out.trans_eq h.symm⟩) (and.intro hx), exact hc.subset_left_of_subset_union hVo hWo hdVW hUVW hVne, end /-- **Maximum modulus principle** on a connected set. Let `U` be a (pre)connected open set in a complex normed space. Let `f : E → F` be a function that is complex differentiable on `U` and is continuous on its closure. Suppose that `‖f x‖` takes its maximum value on `U` at `c ∈ U`. Then `‖f x‖ = ‖f c‖` for all `x ∈ closure U`. -/ lemma norm_eq_on_closure_of_is_preconnected_of_is_max_on {f : E → F} {U : set E} {c : E} (hc : is_preconnected U) (ho : is_open U) (hd : diff_cont_on_cl ℂ f U) (hcU : c ∈ U) (hm : is_max_on (norm ∘ f) U c) : eq_on (norm ∘ f) (const E ‖f c‖) (closure U) := (norm_eq_on_of_is_preconnected_of_is_max_on hc ho hd.differentiable_on hcU hm).of_subset_closure hd.continuous_on.norm continuous_on_const subset_closure subset.rfl section strict_convex /-! ### The case of a strictly convex codomain If the codomain `F` is a strictly convex space, then we can claim equalities like `f w = f z` instead of `‖f w‖ = ‖f z‖`. Instead of repeating the proof starting with lemmas about integrals, we apply a corresponding lemma above twice: for `f` and for `λ x, f x + f c`. Then we have `‖f w‖ = ‖f z‖` and `‖f w + f z‖ = ‖f z + f z‖`, thus `‖f w + f z‖ = ‖f w‖ + ‖f z‖`. This is only possible if `f w = f z`, see `eq_of_norm_eq_of_norm_add_eq`. -/ variables [strict_convex_space ℝ F] /-- **Maximum modulus principle** on a connected set. Let `U` be a (pre)connected open set in a complex normed space. Let `f : E → F` be a function that is complex differentiable on `U`. Suppose that `‖f x‖` takes its maximum value on `U` at `c ∈ U`. Then `f x = f c` for all `x ∈ U`. TODO: change assumption from `is_max_on` to `is_local_max`. -/ lemma eq_on_of_is_preconnected_of_is_max_on_norm {f : E → F} {U : set E} {c : E} (hc : is_preconnected U) (ho : is_open U) (hd : differentiable_on ℂ f U) (hcU : c ∈ U) (hm : is_max_on (norm ∘ f) U c) : eq_on f (const E (f c)) U := λ x hx, have H₁ : ‖f x‖ = ‖f c‖, from norm_eq_on_of_is_preconnected_of_is_max_on hc ho hd hcU hm hx, have H₂ : ‖f x + f c‖ = ‖f c + f c‖, from norm_eq_on_of_is_preconnected_of_is_max_on hc ho (hd.add_const _) hcU hm.norm_add_self hx, eq_of_norm_eq_of_norm_add_eq H₁ $ by simp only [H₂, same_ray.rfl.norm_add, H₁] /-- **Maximum modulus principle** on a connected set. Let `U` be a (pre)connected open set in a complex normed space. Let `f : E → F` be a function that is complex differentiable on `U` and is continuous on its closure. Suppose that `‖f x‖` takes its maximum value on `U` at `c ∈ U`. Then `f x = f c` for all `x ∈ closure U`. -/ lemma eq_on_closure_of_is_preconnected_of_is_max_on_norm {f : E → F} {U : set E} {c : E} (hc : is_preconnected U) (ho : is_open U) (hd : diff_cont_on_cl ℂ f U) (hcU : c ∈ U) (hm : is_max_on (norm ∘ f) U c) : eq_on f (const E (f c)) (closure U) := (eq_on_of_is_preconnected_of_is_max_on_norm hc ho hd.differentiable_on hcU hm).of_subset_closure hd.continuous_on continuous_on_const subset_closure subset.rfl /-- **Maximum modulus principle**. Let `f : E → F` be a function between complex normed spaces. Suppose that the codomain `F` is a strictly convex space, `f` is complex differentiable on a set `s`, `f` is continuous on the closure of `s`, the norm of `f` takes it maximum on `s` at `z`, and `w` is a point such that the closed ball with center `z` and radius `dist w z` is included in `s`, then `f w = f z`. -/ lemma eq_of_is_max_on_of_ball_subset {f : E → F} {s : set E} {z w : E} (hd : diff_cont_on_cl ℂ f s) (hz : is_max_on (norm ∘ f) s z) (hsub : ball z (dist w z) ⊆ s) : f w = f z := have H₁ : ‖f w‖ = ‖f z‖, from norm_eq_norm_of_is_max_on_of_ball_subset hd hz hsub, have H₂ : ‖f w + f z‖ = ‖f z + f z‖, from norm_eq_norm_of_is_max_on_of_ball_subset (hd.add_const _) hz.norm_add_self hsub, eq_of_norm_eq_of_norm_add_eq H₁ $ by simp only [H₂, same_ray.rfl.norm_add, H₁] /-- **Maximum modulus principle** on a closed ball. Suppose that a function `f : E → F` from a normed complex space to a strictly convex normed complex space has the following properties: - it is continuous on a closed ball `metric.closed_ball z r`, - it is complex differentiable on the corresponding open ball; - the norm `‖f w‖` takes its maximum value on the open ball at its center. Then `f` is a constant on the closed ball. -/ lemma eq_on_closed_ball_of_is_max_on_norm {f : E → F} {z : E} {r : ℝ} (hd : diff_cont_on_cl ℂ f (ball z r)) (hz : is_max_on (norm ∘ f) (ball z r) z) : eq_on f (const E (f z)) (closed_ball z r) := λ x hx, eq_of_is_max_on_of_ball_subset hd hz $ ball_subset_ball hx /-- **Maximum modulus principle**: if `f : E → F` is complex differentiable in a neighborhood of `c` and the norm `‖f z‖` has a local maximum at `c`, then `f` is locally constant in a neighborhood of `c`. -/ lemma eventually_eq_of_is_local_max_norm {f : E → F} {c : E} (hd : ∀ᶠ z in 𝓝 c, differentiable_at ℂ f z) (hc : is_local_max (norm ∘ f) c) : ∀ᶠ y in 𝓝 c, f y = f c := begin rcases nhds_basis_closed_ball.eventually_iff.1 (hd.and hc) with ⟨r, hr₀, hr⟩, exact nhds_basis_closed_ball.eventually_iff.2 ⟨r, hr₀, eq_on_closed_ball_of_is_max_on_norm (differentiable_on.diff_cont_on_cl $ λ x hx, (hr $ closure_ball_subset_closed_ball hx).1.differentiable_within_at) (λ x hx, (hr $ ball_subset_closed_ball hx).2)⟩ end lemma eventually_eq_or_eq_zero_of_is_local_min_norm {f : E → ℂ} {c : E} (hf : ∀ᶠ z in 𝓝 c, differentiable_at ℂ f z) (hc : is_local_min (norm ∘ f) c) : (∀ᶠ z in 𝓝 c, f z = f c) ∨ (f c = 0) := begin refine or_iff_not_imp_right.mpr (λ h, _), have h1 : ∀ᶠ z in 𝓝 c, f z ≠ 0 := hf.self_of_nhds.continuous_at.eventually_ne h, have h2 : is_local_max (norm ∘ f)⁻¹ c := hc.inv (h1.mono (λ z, norm_pos_iff.mpr)), have h3 : is_local_max (norm ∘ f⁻¹) c := by { refine h2.congr (eventually_of_forall _); simp }, have h4 : ∀ᶠ z in 𝓝 c, differentiable_at ℂ f⁻¹ z, by filter_upwards [hf, h1] with z h using h.inv, filter_upwards [eventually_eq_of_is_local_max_norm h4 h3] with z using inv_inj.mp end end strict_convex /-! ### Maximum on a set vs maximum on its frontier In this section we prove corollaries of the maximum modulus principle that relate the values of a function on a set to its values on the frontier of this set. -/ variable [nontrivial E] /-- **Maximum modulus principle**: if `f : E → F` is complex differentiable on a nonempty bounded set `U` and is continuous on its closure, then there exists a point `z ∈ frontier U` such that `λ z, ‖f z‖` takes it maximum value on `closure U` at `z`. -/ lemma exists_mem_frontier_is_max_on_norm [finite_dimensional ℂ E] {f : E → F} {U : set E} (hb : bounded U) (hne : U.nonempty) (hd : diff_cont_on_cl ℂ f U) : ∃ z ∈ frontier U, is_max_on (norm ∘ f) (closure U) z := begin have hc : is_compact (closure U), from hb.is_compact_closure, obtain ⟨w, hwU, hle⟩ : ∃ w ∈ closure U, is_max_on (norm ∘ f) (closure U) w, from hc.exists_forall_ge hne.closure hd.continuous_on.norm, rw [closure_eq_interior_union_frontier, mem_union] at hwU, cases hwU, rotate, { exact ⟨w, hwU, hle⟩ }, have : interior U ≠ univ, from ne_top_of_le_ne_top hc.ne_univ interior_subset_closure, rcases exists_mem_frontier_inf_dist_compl_eq_dist hwU this with ⟨z, hzU, hzw⟩, refine ⟨z, frontier_interior_subset hzU, λ x hx, (mem_set_of_eq.mp $ hle hx).trans_eq _⟩, refine (norm_eq_norm_of_is_max_on_of_ball_subset hd (hle.on_subset subset_closure) _).symm, rw [dist_comm, ← hzw], exact ball_inf_dist_compl_subset.trans interior_subset end /-- **Maximum modulus principle**: if `f : E → F` is complex differentiable on a bounded set `U` and `‖f z‖ ≤ C` for any `z ∈ frontier U`, then the same is true for any `z ∈ closure U`. -/ lemma norm_le_of_forall_mem_frontier_norm_le {f : E → F} {U : set E} (hU : bounded U) (hd : diff_cont_on_cl ℂ f U) {C : ℝ} (hC : ∀ z ∈ frontier U, ‖f z‖ ≤ C) {z : E} (hz : z ∈ closure U) : ‖f z‖ ≤ C := begin rw [closure_eq_self_union_frontier, union_comm, mem_union] at hz, cases hz, { exact hC z hz }, /- In case of a finite dimensional domain, one can just apply `complex.exists_mem_frontier_is_max_on_norm`. To make it work in any Banach space, we restrict the function to a line first. -/ rcases exists_ne z with ⟨w, hne⟩, set e : ℂ → E := line_map z w, have hde : differentiable ℂ e := (differentiable_id.smul_const (w - z)).add_const z, have hL : antilipschitz_with (nndist z w)⁻¹ e, from antilipschitz_with_line_map hne.symm, replace hd : diff_cont_on_cl ℂ (f ∘ e) (e ⁻¹' U), from hd.comp hde.diff_cont_on_cl (maps_to_preimage _ _), have h₀ : (0 : ℂ) ∈ e ⁻¹' U, by simpa only [e, mem_preimage, line_map_apply_zero], rcases exists_mem_frontier_is_max_on_norm (hL.bounded_preimage hU) ⟨0, h₀⟩ hd with ⟨ζ, hζU, hζ⟩, calc ‖f z‖ = ‖f (e 0)‖ : by simp only [e, line_map_apply_zero] ... ≤ ‖f (e ζ)‖ : hζ (subset_closure h₀) ... ≤ C : hC _ (hde.continuous.frontier_preimage_subset _ hζU) end /-- If two complex differentiable functions `f g : E → F` are equal on the boundary of a bounded set `U`, then they are equal on `closure U`. -/ lemma eq_on_closure_of_eq_on_frontier {f g : E → F} {U : set E} (hU : bounded U) (hf : diff_cont_on_cl ℂ f U) (hg : diff_cont_on_cl ℂ g U) (hfg : eq_on f g (frontier U)) : eq_on f g (closure U) := begin suffices H : ∀ z ∈ closure U, ‖(f - g) z‖ ≤ 0, by simpa [sub_eq_zero] using H, refine λ z hz, norm_le_of_forall_mem_frontier_norm_le hU (hf.sub hg) (λ w hw, _) hz, simp [hfg hw] end /-- If two complex differentiable functions `f g : E → F` are equal on the boundary of a bounded set `U`, then they are equal on `U`. -/ lemma eq_on_of_eq_on_frontier {f g : E → F} {U : set E} (hU : bounded U) (hf : diff_cont_on_cl ℂ f U) (hg : diff_cont_on_cl ℂ g U) (hfg : eq_on f g (frontier U)) : eq_on f g U := (eq_on_closure_of_eq_on_frontier hU hf hg hfg).mono subset_closure end complex
d4a23637bda224ff7d08fc4c9296308155a77bd4
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/run/unzip_bug.lean
f5fcad27b8de95c8ab8bbc92298aef5a68bf3c14
[ "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
391
lean
import data.examples.vector open nat vector prod variables {A B : Type} definition unzip : Π {n : nat}, vector (A × B) n → vector A n × vector B n | @unzip ⌞zero⌟ nil := (nil, nil) | @unzip ⌞succ n⌟ ((a, b) :: v) := match unzip v with (va, vb) := (a :: va, b :: vb) end example : unzip ((1, 20) :: (2, 30) :: nil) = (1 :: 2 :: nil, 20 :: 30 :: nil) := rfl
e1f86e91baa9f076edec1b15d590731b10e1dc90
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/conv/conv.lean
987856aea2b0072c191bc7db5e11be34e1327b49
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
1,544
lean
/- Copyright (c) 2019 Lucas Allen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Lucas Allen -/ import tactic.converter.interactive /-! # Tests for the `conv` tactic inside the interactive `conv` monad -/ example (a b c d : ℕ) (h₁ : b = c) (h₂ : a + c = a + d) : a + b = a + d := begin conv { --| a + b = a + d --Conv to the left hand side to_lhs, -- | a + b --Zoom into the left hand side. conv { -- | a + b congr, -- two goals: | a and | b skip, -- | b rw h₁, -- | c }, -- | a + c --At this point, to get back to this position, without zoom, we would need to close --this conv block, and open a new one. rw h₂, -- | a + d }, -- goals accomplished end example : 1 + (5 * 8) - (3 * 14) + (4 * 99 - 45) - 350 = 1 := begin have h₁ : 5 * 8 = 40, from dec_trivial, have h₂ : 3 * 14 = 42, from dec_trivial, have h₃ : 4 * 99 - 45 = 351, from dec_trivial, conv { to_lhs, -- conv to the left hand side conv { -- zooming in to rewrite 4 * 99 - 45 to 351 congr, congr, skip, rw h₃, }, -- returning to the left hand side, note we don't need to open a new conv block conv { -- zooming in to rewrite 3 * 14 to 42 congr, congr, congr, skip, rw h₂, }, -- returning to the left hand side conv { -- zooming in to rewrite 5 * 8 to 40 congr, congr, congr, congr, skip, rw h₁, }, -- returning to the left hand side }, end
ff0d016e28cbd4f2bbb3ffafee1981426f6a17e8
737dc4b96c97368cb66b925eeea3ab633ec3d702
/stage0/src/Lean/PrettyPrinter/Formatter.lean
2fa810a7f126c8adf8b1b2a7088bd7d2ec052f8e
[ "Apache-2.0" ]
permissive
Bioye97/lean4
1ace34638efd9913dc5991443777b01a08983289
bc3900cbb9adda83eed7e6affeaade7cfd07716d
refs/heads/master
1,690,589,820,211
1,631,051,000,000
1,631,067,598,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,524
lean
/- Copyright (c) 2020 Sebastian Ullrich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ import Lean.CoreM import Lean.Parser.Extension import Lean.KeyedDeclsAttribute import Lean.ParserCompiler.Attribute import Lean.PrettyPrinter.Basic /-! The formatter turns a `Syntax` tree into a `Format` object, inserting both mandatory whitespace (to separate adjacent tokens) as well as "pretty" optional whitespace. The basic approach works much like the parenthesizer: A right-to-left traversal over the syntax tree, driven by parser-specific handlers registered via attributes. The traversal is right-to-left so that when emitting a token, we already know the text following it and can decide whether or not whitespace between the two is necessary. -/ namespace Lean namespace PrettyPrinter namespace Formatter structure Context where options : Options table : Parser.TokenTable structure State where stxTrav : Syntax.Traverser -- Textual content of `stack` up to the first whitespace (not enclosed in an escaped ident). We assume that the textual -- content of `stack` is modified only by `pushText` and `pushLine`, so `leadWord` is adjusted there accordingly. leadWord : String := "" -- Stack of generated Format objects, analogous to the Syntax stack in the parser. -- Note, however, that the stack is reversed because of the right-to-left traversal. stack : Array Format := #[] end Formatter abbrev FormatterM := ReaderT Formatter.Context $ StateRefT Formatter.State CoreM @[inline] def FormatterM.orElse {α} (p₁ : FormatterM α) (p₂ : Unit → FormatterM α) : FormatterM α := do let s ← get catchInternalId backtrackExceptionId p₁ (fun _ => do set s; p₂ ()) instance {α} : OrElse (FormatterM α) := ⟨FormatterM.orElse⟩ abbrev Formatter := FormatterM Unit unsafe def mkFormatterAttribute : IO (KeyedDeclsAttribute Formatter) := KeyedDeclsAttribute.init { builtinName := `builtinFormatter, name := `formatter, descr := "Register a formatter for a parser. [formatter k] registers a declaration of type `Lean.PrettyPrinter.Formatter` for the `SyntaxNodeKind` `k`.", valueTypeName := `Lean.PrettyPrinter.Formatter, evalKey := fun builtin stx => do let env ← getEnv let id ← Attribute.Builtin.getId stx -- `isValidSyntaxNodeKind` is updated only in the next stage for new `[builtin*Parser]`s, but we try to -- synthesize a formatter for it immediately, so we just check for a declaration in this case if (builtin && (env.find? id).isSome) || Parser.isValidSyntaxNodeKind env id then pure id else throwError "invalid [formatter] argument, unknown syntax kind '{id}'" } `Lean.PrettyPrinter.formatterAttribute @[builtinInit mkFormatterAttribute] constant formatterAttribute : KeyedDeclsAttribute Formatter unsafe def mkCombinatorFormatterAttribute : IO ParserCompiler.CombinatorAttribute := ParserCompiler.registerCombinatorAttribute `combinatorFormatter "Register a formatter for a parser combinator. [combinatorFormatter c] registers a declaration of type `Lean.PrettyPrinter.Formatter` for the `Parser` declaration `c`. Note that, unlike with [formatter], this is not a node kind since combinators usually do not introduce their own node kinds. The tagged declaration may optionally accept parameters corresponding to (a prefix of) those of `c`, where `Parser` is replaced with `Formatter` in the parameter types." @[builtinInit mkCombinatorFormatterAttribute] constant combinatorFormatterAttribute : ParserCompiler.CombinatorAttribute namespace Formatter open Lean.Core open Lean.Parser def throwBacktrack {α} : FormatterM α := throw $ Exception.internal backtrackExceptionId instance : Syntax.MonadTraverser FormatterM := ⟨{ get := State.stxTrav <$> get, set := fun t => modify (fun st => { st with stxTrav := t }), modifyGet := fun f => modifyGet (fun st => let (a, t) := f st.stxTrav; (a, { st with stxTrav := t })) }⟩ open Syntax.MonadTraverser def getStack : FormatterM (Array Format) := do let st ← get pure st.stack def getStackSize : FormatterM Nat := do let stack ← getStack; pure stack.size def setStack (stack : Array Format) : FormatterM Unit := modify fun st => { st with stack := stack } def push (f : Format) : FormatterM Unit := modify fun st => { st with stack := st.stack.push f } def pushLine : FormatterM Unit := do push Format.line; modify fun st => { st with leadWord := "" } /-- Execute `x` at the right-most child of the current node, if any, then advance to the left. -/ def visitArgs (x : FormatterM Unit) : FormatterM Unit := do let stx ← getCur if stx.getArgs.size > 0 then goDown (stx.getArgs.size - 1) *> x <* goUp goLeft /-- Execute `x`, pass array of generated Format objects to `fn`, and push result. -/ def fold (fn : Array Format → Format) (x : FormatterM Unit) : FormatterM Unit := do let sp ← getStackSize x let stack ← getStack let f := fn $ stack.extract sp stack.size setStack $ (stack.shrink sp).push f /-- Execute `x` and concatenate generated Format objects. -/ def concat (x : FormatterM Unit) : FormatterM Unit := do fold (Array.foldl (fun acc f => if acc.isNil then f else f ++ acc) Format.nil) x def indent (x : Formatter) (indent : Option Int := none) : Formatter := do concat x let ctx ← read let indent := indent.getD $ Std.Format.getIndent ctx.options modify fun st => { st with stack := st.stack.modify (st.stack.size - 1) (Format.nest indent) } def group (x : Formatter) : Formatter := do concat x modify fun st => { st with stack := st.stack.modify (st.stack.size - 1) Format.fill } /-- If `pos?` has a position, run `x` and tag its results with that position. Otherwise just run `x`. -/ def withMaybeTag (pos? : Option String.Pos) (x : FormatterM Unit) : Formatter := do if let some p := pos? then concat x modify fun st => { st with stack := st.stack.modify (st.stack.size - 1) (Format.tag p) } else x @[combinatorFormatter Lean.Parser.orelse] def orelse.formatter (p1 p2 : Formatter) : Formatter := -- HACK: We have no (immediate) information on which side of the orelse could have produced the current node, so try -- them in turn. Uses the syntax traverser non-linearly! p1 <|> p2 -- `mkAntiquot` is quite complex, so we'd rather have its formatter synthesized below the actual parser definition. -- Note that there is a mutual recursion -- `categoryParser -> mkAntiquot -> termParser -> categoryParser`, so we need to introduce an indirection somewhere -- anyway. @[extern "lean_mk_antiquot_formatter"] constant mkAntiquot.formatter' (name : String) (kind : Option SyntaxNodeKind) (anonymous := true) : Formatter -- break up big mutual recursion @[extern "lean_pretty_printer_formatter_interpret_parser_descr"] constant interpretParserDescr' : ParserDescr → CoreM Formatter unsafe def formatterForKindUnsafe (k : SyntaxNodeKind) : Formatter := do if k == `missing then push "<missing>" goLeft else let stx ← getCur let f ← runForNodeKind formatterAttribute k interpretParserDescr' withMaybeTag stx.getPos? f @[implementedBy formatterForKindUnsafe] constant formatterForKind (k : SyntaxNodeKind) : Formatter @[combinatorFormatter Lean.Parser.withAntiquot] def withAntiquot.formatter (antiP p : Formatter) : Formatter := -- TODO: could be optimized using `isAntiquot` (which would have to be moved), but I'd rather -- fix the backtracking hack outright. orelse.formatter antiP p @[combinatorFormatter Lean.Parser.withAntiquotSuffixSplice] def withAntiquotSuffixSplice.formatter (k : SyntaxNodeKind) (p suffix : Formatter) : Formatter := do if (← getCur).isAntiquotSuffixSplice then visitArgs <| suffix *> p else p @[combinatorFormatter Lean.Parser.tokenWithAntiquot] def tokenWithAntiquot.formatter (p : Formatter) : Formatter := do if (← getCur).isTokenAntiquot then visitArgs p else p @[combinatorFormatter Lean.Parser.categoryParser] def categoryParser.formatter (cat : Name) : Formatter := group $ indent do let stx ← getCur trace[PrettyPrinter.format] "formatting {indentD (format stx)}" if stx.getKind == `choice then visitArgs do -- format only last choice -- TODO: We could use elaborator data here to format the chosen child when available formatterForKind (← getCur).getKind else withAntiquot.formatter (mkAntiquot.formatter' cat.toString none) (formatterForKind stx.getKind) @[combinatorFormatter Lean.Parser.categoryParserOfStack] def categoryParserOfStack.formatter (offset : Nat) : Formatter := do let st ← get let stx := st.stxTrav.parents.back.getArg (st.stxTrav.idxs.back - offset) categoryParser.formatter stx.getId @[combinatorFormatter Lean.Parser.parserOfStack] def parserOfStack.formatter (offset : Nat) (prec : Nat := 0) : Formatter := do let st ← get let stx := st.stxTrav.parents.back.getArg (st.stxTrav.idxs.back - offset) formatterForKind stx.getKind @[combinatorFormatter Lean.Parser.error] def error.formatter (msg : String) : Formatter := pure () @[combinatorFormatter Lean.Parser.errorAtSavedPos] def errorAtSavedPos.formatter (msg : String) (delta : Bool) : Formatter := pure () @[combinatorFormatter Lean.Parser.atomic] def atomic.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.lookahead] def lookahead.formatter (p : Formatter) : Formatter := pure () @[combinatorFormatter Lean.Parser.notFollowedBy] def notFollowedBy.formatter (p : Formatter) : Formatter := pure () @[combinatorFormatter Lean.Parser.andthen] def andthen.formatter (p1 p2 : Formatter) : Formatter := p2 *> p1 def checkKind (k : SyntaxNodeKind) : FormatterM Unit := do let stx ← getCur if k != stx.getKind then trace[PrettyPrinter.format.backtrack] "unexpected node kind '{stx.getKind}', expected '{k}'" throwBacktrack @[combinatorFormatter Lean.Parser.node] def node.formatter (k : SyntaxNodeKind) (p : Formatter) : Formatter := do checkKind k; visitArgs p @[combinatorFormatter Lean.Parser.trailingNode] def trailingNode.formatter (k : SyntaxNodeKind) (_ _ : Nat) (p : Formatter) : Formatter := do checkKind k visitArgs do p; -- leading term, not actually produced by `p` categoryParser.formatter `foo def parseToken (s : String) : FormatterM ParserState := do -- include comment tokens, e.g. when formatting `- -0` (Parser.andthenFn Parser.whitespace (Parser.tokenFn [])) { input := s, fileName := "", fileMap := FileMap.ofString "", prec := 0, env := ← getEnv, options := ← getOptions, tokens := (← read).table } (Parser.mkParserState s) def pushTokenCore (tk : String) : FormatterM Unit := do if tk.toSubstring.dropRightWhile (fun s => s == ' ') == tk.toSubstring then push tk else pushLine push tk.trimRight def pushToken (info : SourceInfo) (tk : String) : FormatterM Unit := do match info with | SourceInfo.original _ _ ss _ => -- preserve non-whitespace content (i.e. comments) let ss' := ss.trim if !ss'.isEmpty then let ws := { ss with startPos := ss'.stopPos } if ws.contains '\n' then push s!"\n{ss'}" else push s!" {ss'}" modify fun st => { st with leadWord := "" } | _ => pure () let st ← get -- If there is no space between `tk` and the next word, see if we would parse more than `tk` as a single token if st.leadWord != "" && tk.trimRight == tk then let tk' := tk.trimLeft let t ← parseToken $ tk' ++ st.leadWord if t.pos <= tk'.bsize then -- stopped within `tk` => use it as is, extend `leadWord` if not prefixed by whitespace pushTokenCore tk modify fun st => { st with leadWord := if tk.trimLeft == tk then tk ++ st.leadWord else "" } else -- stopped after `tk` => add space pushTokenCore $ tk ++ " " modify fun st => { st with leadWord := if tk.trimLeft == tk then tk else "" } else -- already separated => use `tk` as is pushTokenCore tk modify fun st => { st with leadWord := if tk.trimLeft == tk then tk else "" } match info with | SourceInfo.original ss _ _ _ => -- preserve non-whitespace content (i.e. comments) let ss' := ss.trim if !ss'.isEmpty then let ws := { ss with startPos := ss'.stopPos } if ws.contains '\n' then do -- Indentation is automatically increased when entering a category, but comments should be aligned -- with the actual token, so dedent indent (push s!"{ss'}\n") (some ((0:Int) - Std.Format.getIndent (← getOptions))) else push s!"{ss'} " modify fun st => { st with leadWord := "" } | _ => pure () @[combinatorFormatter Lean.Parser.symbolNoAntiquot] def symbolNoAntiquot.formatter (sym : String) : Formatter := do let stx ← getCur if stx.isToken sym then do let (Syntax.atom info _) ← pure stx | unreachable! pushToken info sym goLeft else do trace[PrettyPrinter.format.backtrack] "unexpected syntax '{format stx}', expected symbol '{sym}'" throwBacktrack @[combinatorFormatter Lean.Parser.nonReservedSymbolNoAntiquot] def nonReservedSymbolNoAntiquot.formatter := symbolNoAntiquot.formatter @[combinatorFormatter Lean.Parser.rawCh] def rawCh.formatter (ch : Char) := symbolNoAntiquot.formatter ch.toString @[combinatorFormatter Lean.Parser.unicodeSymbolNoAntiquot] def unicodeSymbolNoAntiquot.formatter (sym asciiSym : String) : Formatter := do let Syntax.atom info val ← getCur | throwError m!"not an atom: {← getCur}" if val == sym.trim then pushToken info sym else pushToken info asciiSym; goLeft @[combinatorFormatter Lean.Parser.identNoAntiquot] def identNoAntiquot.formatter : Formatter := do checkKind identKind let Syntax.ident info _ id _ ← getCur | throwError m!"not an ident: {← getCur}" let id := id.simpMacroScopes pushToken info id.toString goLeft @[combinatorFormatter Lean.Parser.rawIdentNoAntiquot] def rawIdentNoAntiquot.formatter : Formatter := do checkKind identKind let Syntax.ident info _ id _ ← getCur | throwError m!"not an ident: {← getCur}" pushToken info id.toString goLeft @[combinatorFormatter Lean.Parser.identEq] def identEq.formatter (id : Name) := rawIdentNoAntiquot.formatter def visitAtom (k : SyntaxNodeKind) : Formatter := do let stx ← getCur if k != Name.anonymous then checkKind k let Syntax.atom info val ← pure $ stx.ifNode (fun n => n.getArg 0) (fun _ => stx) | throwError m!"not an atom: {stx}" pushToken info val goLeft @[combinatorFormatter Lean.Parser.charLitNoAntiquot] def charLitNoAntiquot.formatter := visitAtom charLitKind @[combinatorFormatter Lean.Parser.strLitNoAntiquot] def strLitNoAntiquot.formatter := visitAtom strLitKind @[combinatorFormatter Lean.Parser.nameLitNoAntiquot] def nameLitNoAntiquot.formatter := visitAtom nameLitKind @[combinatorFormatter Lean.Parser.numLitNoAntiquot] def numLitNoAntiquot.formatter := visitAtom numLitKind @[combinatorFormatter Lean.Parser.scientificLitNoAntiquot] def scientificLitNoAntiquot.formatter := visitAtom scientificLitKind @[combinatorFormatter Lean.Parser.fieldIdx] def fieldIdx.formatter := visitAtom fieldIdxKind @[combinatorFormatter Lean.Parser.manyNoAntiquot] def manyNoAntiquot.formatter (p : Formatter) : Formatter := do let stx ← getCur visitArgs $ stx.getArgs.size.forM fun _ => p @[combinatorFormatter Lean.Parser.many1NoAntiquot] def many1NoAntiquot.formatter (p : Formatter) : Formatter := manyNoAntiquot.formatter p @[combinatorFormatter Lean.Parser.optionalNoAntiquot] def optionalNoAntiquot.formatter (p : Formatter) : Formatter := visitArgs p @[combinatorFormatter Lean.Parser.many1Unbox] def many1Unbox.formatter (p : Formatter) : Formatter := do let stx ← getCur if stx.getKind == nullKind then do manyNoAntiquot.formatter p else p @[combinatorFormatter Lean.Parser.sepByNoAntiquot] def sepByNoAntiquot.formatter (p pSep : Formatter) : Formatter := do let stx ← getCur visitArgs $ (List.range stx.getArgs.size).reverse.forM $ fun i => if i % 2 == 0 then p else pSep @[combinatorFormatter Lean.Parser.sepBy1NoAntiquot] def sepBy1NoAntiquot.formatter := sepByNoAntiquot.formatter @[combinatorFormatter Lean.Parser.withPosition] def withPosition.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.withoutPosition] def withoutPosition.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.withForbidden] def withForbidden.formatter (tk : Token) (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.withoutForbidden] def withoutForbidden.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.withoutInfo] def withoutInfo.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.setExpected] def setExpected.formatter (expected : List String) (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.incQuotDepth] def incQuotDepth.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.decQuotDepth] def decQuotDepth.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.suppressInsideQuot] def suppressInsideQuot.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.evalInsideQuot] def evalInsideQuot.formatter (declName : Name) (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.checkWsBefore] def checkWsBefore.formatter : Formatter := do let st ← get if st.leadWord != "" then pushLine @[combinatorFormatter Lean.Parser.checkPrec] def checkPrec.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkLhsPrec] def checkLhsPrec.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.setLhsPrec] def setLhsPrec.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkStackTop] def checkStackTop.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkNoWsBefore] def checkNoWsBefore.formatter : Formatter := -- prevent automatic whitespace insertion modify fun st => { st with leadWord := "" } @[combinatorFormatter Lean.Parser.checkLinebreakBefore] def checkLinebreakBefore.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkTailWs] def checkTailWs.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkColGe] def checkColGe.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkColGt] def checkColGt.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkLineEq] def checkLineEq.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.eoi] def eoi.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.notFollowedByCategoryToken] def notFollowedByCategoryToken.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkNoImmediateColon] def checkNoImmediateColon.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkInsideQuot] def checkInsideQuot.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.checkOutsideQuot] def checkOutsideQuot.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.skip] def skip.formatter : Formatter := pure () @[combinatorFormatter Lean.Parser.pushNone] def pushNone.formatter : Formatter := goLeft @[combinatorFormatter Lean.Parser.withOpenDecl] def withOpenDecl.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.withOpen] def withOpen.formatter (p : Formatter) : Formatter := p @[combinatorFormatter Lean.Parser.interpolatedStr] def interpolatedStr.formatter (p : Formatter) : Formatter := do visitArgs $ (← getCur).getArgs.reverse.forM fun chunk => match chunk.isLit? interpolatedStrLitKind with | some str => push str *> goLeft | none => p @[combinatorFormatter Lean.Parser.dbgTraceState] def dbgTraceState.formatter (label : String) (p : Formatter) : Formatter := p @[combinatorFormatter ite, macroInline] def ite {α : Type} (c : Prop) [h : Decidable c] (t e : Formatter) : Formatter := if c then t else e abbrev FormatterAliasValue := AliasValue Formatter builtin_initialize formatterAliasesRef : IO.Ref (NameMap FormatterAliasValue) ← IO.mkRef {} def registerAlias (aliasName : Name) (v : FormatterAliasValue) : IO Unit := do Parser.registerAliasCore formatterAliasesRef aliasName v instance : Coe Formatter FormatterAliasValue := { coe := AliasValue.const } instance : Coe (Formatter → Formatter) FormatterAliasValue := { coe := AliasValue.unary } instance : Coe (Formatter → Formatter → Formatter) FormatterAliasValue := { coe := AliasValue.binary } end Formatter open Formatter def format (formatter : Formatter) (stx : Syntax) : CoreM Format := do trace[PrettyPrinter.format.input] "{Std.format stx}" let options ← getOptions let table ← Parser.builtinTokenTable.get catchInternalId backtrackExceptionId (do let (_, st) ← (concat formatter { table := table, options := options }).run { stxTrav := Syntax.Traverser.fromSyntax stx }; pure $ Format.fill $ st.stack.get! 0) (fun _ => throwError "format: uncaught backtrack exception") def formatTerm := format $ categoryParser.formatter `term def formatCommand := format $ categoryParser.formatter `command builtin_initialize registerTraceClass `PrettyPrinter.format; end PrettyPrinter end Lean
61b314013bc45e1cdb8466fb8da53b24e898f158
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/blast9.lean
ee4e2370b73fb8498bad8df0b2074fe79a9f17aa
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
287
lean
import data.list open list set_option blast.strategy "preprocess" example (p : Prop) (a b c : nat) : [a, b, c] = [] → p := by blast set_option blast.strategy "simple" lemma l1 (a b c d e f : nat) : [a, b, c] = [d, e, f] → a = d ∧ b = e ∧ c = f := by blast reveal l1 print l1
53aab607716f2e3eb7a5df25926b386953053062
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/analysis/complex/basic.lean
95373cf3562459a0b679f138f0c907112c4f907b
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
10,532
lean
/- Copyright (c) Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import data.complex.determinant import data.complex.is_R_or_C /-! # Normed space structure on `ℂ`. This file gathers basic facts on complex numbers of an analytic nature. ## Main results This file registers `ℂ` as a normed field, expresses basic properties of the norm, and gives tools on the real vector space structure of `ℂ`. Notably, in the namespace `complex`, it defines functions: * `re_clm` * `im_clm` * `of_real_clm` * `conj_cle` They are bundled versions of the real part, the imaginary part, the embedding of `ℝ` in `ℂ`, and the complex conjugate as continuous `ℝ`-linear maps. The last two are also bundled as linear isometries in `of_real_li` and `conj_lie`. We also register the fact that `ℂ` is an `is_R_or_C` field. -/ noncomputable theory namespace complex open_locale complex_conjugate instance : has_norm ℂ := ⟨abs⟩ instance : normed_group ℂ := normed_group.of_core ℂ { norm_eq_zero_iff := λ z, abs_eq_zero, triangle := abs_add, norm_neg := abs_neg } instance : normed_field ℂ := { norm := abs, dist_eq := λ _ _, rfl, norm_mul' := abs_mul, .. complex.field } instance : nondiscrete_normed_field ℂ := { non_trivial := ⟨2, by simp [norm]; norm_num⟩ } instance {R : Type*} [normed_field R] [normed_algebra R ℝ] : normed_algebra R ℂ := { norm_algebra_map_eq := λ x, (abs_of_real $ algebra_map R ℝ x).trans (norm_algebra_map_eq ℝ x), to_algebra := complex.algebra } /-- The module structure from `module.complex_to_real` is a normed space. -/ @[priority 900] -- see Note [lower instance priority] instance _root_.normed_space.complex_to_real {E : Type*} [normed_group E] [normed_space ℂ E] : normed_space ℝ E := normed_space.restrict_scalars ℝ ℂ E @[simp] lemma norm_eq_abs (z : ℂ) : ∥z∥ = abs z := rfl lemma dist_eq (z w : ℂ) : dist z w = abs (z - w) := rfl @[simp] lemma norm_real (r : ℝ) : ∥(r : ℂ)∥ = ∥r∥ := abs_of_real _ @[simp] lemma norm_rat (r : ℚ) : ∥(r : ℂ)∥ = |(r : ℝ)| := suffices ∥((r : ℝ) : ℂ)∥ = |r|, by simpa, by rw [norm_real, real.norm_eq_abs] @[simp] lemma norm_nat (n : ℕ) : ∥(n : ℂ)∥ = n := abs_of_nat _ @[simp] lemma norm_int {n : ℤ} : ∥(n : ℂ)∥ = |n| := suffices ∥((n : ℝ) : ℂ)∥ = |n|, by simpa, by rw [norm_real, real.norm_eq_abs] lemma norm_int_of_nonneg {n : ℤ} (hn : 0 ≤ n) : ∥(n : ℂ)∥ = n := by rw [norm_int, _root_.abs_of_nonneg]; exact int.cast_nonneg.2 hn @[continuity] lemma continuous_abs : continuous abs := continuous_norm @[continuity] lemma continuous_norm_sq : continuous norm_sq := by simpa [← norm_sq_eq_abs] using continuous_abs.pow 2 /-- The `abs` function on `ℂ` is proper. -/ lemma tendsto_abs_cocompact_at_top : filter.tendsto abs (filter.cocompact ℂ) filter.at_top := tendsto_norm_cocompact_at_top /-- The `norm_sq` function on `ℂ` is proper. -/ lemma tendsto_norm_sq_cocompact_at_top : filter.tendsto norm_sq (filter.cocompact ℂ) filter.at_top := by simpa [mul_self_abs] using tendsto_abs_cocompact_at_top.at_top_mul_at_top tendsto_abs_cocompact_at_top open continuous_linear_map /-- Continuous linear map version of the real part function, from `ℂ` to `ℝ`. -/ def re_clm : ℂ →L[ℝ] ℝ := re_lm.mk_continuous 1 (λ x, by simp [real.norm_eq_abs, abs_re_le_abs]) @[continuity] lemma continuous_re : continuous re := re_clm.continuous @[simp] lemma re_clm_coe : (coe (re_clm) : ℂ →ₗ[ℝ] ℝ) = re_lm := rfl @[simp] lemma re_clm_apply (z : ℂ) : (re_clm : ℂ → ℝ) z = z.re := rfl @[simp] lemma re_clm_norm : ∥re_clm∥ = 1 := le_antisymm (linear_map.mk_continuous_norm_le _ zero_le_one _) $ calc 1 = ∥re_clm 1∥ : by simp ... ≤ ∥re_clm∥ : unit_le_op_norm _ _ (by simp) /-- Continuous linear map version of the real part function, from `ℂ` to `ℝ`. -/ def im_clm : ℂ →L[ℝ] ℝ := im_lm.mk_continuous 1 (λ x, by simp [real.norm_eq_abs, abs_im_le_abs]) @[continuity] lemma continuous_im : continuous im := im_clm.continuous @[simp] lemma im_clm_coe : (coe (im_clm) : ℂ →ₗ[ℝ] ℝ) = im_lm := rfl @[simp] lemma im_clm_apply (z : ℂ) : (im_clm : ℂ → ℝ) z = z.im := rfl @[simp] lemma im_clm_norm : ∥im_clm∥ = 1 := le_antisymm (linear_map.mk_continuous_norm_le _ zero_le_one _) $ calc 1 = ∥im_clm I∥ : by simp ... ≤ ∥im_clm∥ : unit_le_op_norm _ _ (by simp) lemma restrict_scalars_one_smul_right' {E : Type*} [normed_group E] [normed_space ℂ E] (x : E) : continuous_linear_map.restrict_scalars ℝ ((1 : ℂ →L[ℂ] ℂ).smul_right x : ℂ →L[ℂ] E) = re_clm.smul_right x + I • im_clm.smul_right x := by { ext ⟨a, b⟩, simp [mk_eq_add_mul_I, add_smul, mul_smul, smul_comm I] } lemma restrict_scalars_one_smul_right (x : ℂ) : continuous_linear_map.restrict_scalars ℝ ((1 : ℂ →L[ℂ] ℂ).smul_right x : ℂ →L[ℂ] ℂ) = x • 1 := by { ext1 z, dsimp, apply mul_comm } /-- The complex-conjugation function from `ℂ` to itself is an isometric linear equivalence. -/ def conj_lie : ℂ ≃ₗᵢ[ℝ] ℂ := ⟨conj_ae.to_linear_equiv, abs_conj⟩ @[simp] lemma conj_lie_apply (z : ℂ) : conj_lie z = conj z := rfl lemma isometry_conj : isometry (conj : ℂ → ℂ) := conj_lie.isometry /-- The determinant of `conj_lie`, as a linear map. -/ @[simp] lemma det_conj_lie : (conj_lie.to_linear_equiv : ℂ →ₗ[ℝ] ℂ).det = -1 := det_conj_ae /-- The determinant of `conj_lie`, as a linear equiv. -/ @[simp] lemma linear_equiv_det_conj_lie : conj_lie.to_linear_equiv.det = -1 := linear_equiv_det_conj_ae @[continuity] lemma continuous_conj : continuous (conj : ℂ → ℂ) := conj_lie.continuous /-- Continuous linear equiv version of the conj function, from `ℂ` to `ℂ`. -/ def conj_cle : ℂ ≃L[ℝ] ℂ := conj_lie @[simp] lemma conj_cle_coe : conj_cle.to_linear_equiv = conj_ae.to_linear_equiv := rfl @[simp] lemma conj_cle_apply (z : ℂ) : conj_cle z = conj z := rfl @[simp] lemma conj_cle_norm : ∥(conj_cle : ℂ →L[ℝ] ℂ)∥ = 1 := conj_lie.to_linear_isometry.norm_to_continuous_linear_map /-- Linear isometry version of the canonical embedding of `ℝ` in `ℂ`. -/ def of_real_li : ℝ →ₗᵢ[ℝ] ℂ := ⟨of_real_am.to_linear_map, norm_real⟩ lemma isometry_of_real : isometry (coe : ℝ → ℂ) := of_real_li.isometry @[continuity] lemma continuous_of_real : continuous (coe : ℝ → ℂ) := of_real_li.continuous /-- Continuous linear map version of the canonical embedding of `ℝ` in `ℂ`. -/ def of_real_clm : ℝ →L[ℝ] ℂ := of_real_li.to_continuous_linear_map @[simp] lemma of_real_clm_coe : (of_real_clm : ℝ →ₗ[ℝ] ℂ) = of_real_am.to_linear_map := rfl @[simp] lemma of_real_clm_apply (x : ℝ) : of_real_clm x = x := rfl @[simp] lemma of_real_clm_norm : ∥of_real_clm∥ = 1 := of_real_li.norm_to_continuous_linear_map noncomputable instance : is_R_or_C ℂ := { re := ⟨complex.re, complex.zero_re, complex.add_re⟩, im := ⟨complex.im, complex.zero_im, complex.add_im⟩, I := complex.I, I_re_ax := by simp only [add_monoid_hom.coe_mk, complex.I_re], I_mul_I_ax := by simp only [complex.I_mul_I, eq_self_iff_true, or_true], re_add_im_ax := λ z, by simp only [add_monoid_hom.coe_mk, complex.re_add_im, complex.coe_algebra_map, complex.of_real_eq_coe], of_real_re_ax := λ r, by simp only [add_monoid_hom.coe_mk, complex.of_real_re, complex.coe_algebra_map, complex.of_real_eq_coe], of_real_im_ax := λ r, by simp only [add_monoid_hom.coe_mk, complex.of_real_im, complex.coe_algebra_map, complex.of_real_eq_coe], mul_re_ax := λ z w, by simp only [complex.mul_re, add_monoid_hom.coe_mk], mul_im_ax := λ z w, by simp only [add_monoid_hom.coe_mk, complex.mul_im], conj_re_ax := λ z, rfl, conj_im_ax := λ z, rfl, conj_I_ax := by simp only [complex.conj_I, ring_hom.coe_mk], norm_sq_eq_def_ax := λ z, by simp only [←complex.norm_sq_eq_abs, ←complex.norm_sq_apply, add_monoid_hom.coe_mk, complex.norm_eq_abs], mul_im_I_ax := λ z, by simp only [mul_one, add_monoid_hom.coe_mk, complex.I_im], inv_def_ax := λ z, by simp only [complex.inv_def, complex.norm_sq_eq_abs, complex.coe_algebra_map, complex.of_real_eq_coe, complex.norm_eq_abs], div_I_ax := complex.div_I } section variables {α β γ : Type*} [add_comm_monoid α] [topological_space α] [add_comm_monoid γ] [topological_space γ] /-- The natural `add_equiv` from `ℂ` to `ℝ × ℝ`. -/ @[simps apply symm_apply_re symm_apply_im { simp_rhs := tt }] def equiv_real_prod_add_hom : ℂ ≃+ ℝ × ℝ := { map_add' := by simp, .. equiv_real_prod } /-- The natural `linear_equiv` from `ℂ` to `ℝ × ℝ`. -/ @[simps apply symm_apply_re symm_apply_im { simp_rhs := tt }] def equiv_real_prod_add_hom_lm : ℂ ≃ₗ[ℝ] ℝ × ℝ := { map_smul' := by simp [equiv_real_prod_add_hom], .. equiv_real_prod_add_hom } /-- The natural `continuous_linear_equiv` from `ℂ` to `ℝ × ℝ`. -/ @[simps apply symm_apply_re symm_apply_im { simp_rhs := tt }] def equiv_real_prodₗ : ℂ ≃L[ℝ] ℝ × ℝ := equiv_real_prod_add_hom_lm.to_continuous_linear_equiv end lemma has_sum_iff {α} (f : α → ℂ) (c : ℂ) : has_sum f c ↔ has_sum (λ x, (f x).re) c.re ∧ has_sum (λ x, (f x).im) c.im := begin -- For some reason, `continuous_linear_map.has_sum` is orders of magnitude faster than -- `has_sum.mapL` here: refine ⟨λ h, ⟨re_clm.has_sum h, im_clm.has_sum h⟩, _⟩, rintro ⟨h₁, h₂⟩, convert (h₁.prod_mk h₂).mapL equiv_real_prodₗ.symm.to_continuous_linear_map, { ext x; refl }, { cases c, refl } end end complex namespace is_R_or_C local notation `reC` := @is_R_or_C.re ℂ _ local notation `imC` := @is_R_or_C.im ℂ _ local notation `IC` := @is_R_or_C.I ℂ _ local notation `absC` := @is_R_or_C.abs ℂ _ local notation `norm_sqC` := @is_R_or_C.norm_sq ℂ _ @[simp] lemma re_to_complex {x : ℂ} : reC x = x.re := rfl @[simp] lemma im_to_complex {x : ℂ} : imC x = x.im := rfl @[simp] lemma I_to_complex : IC = complex.I := rfl @[simp] lemma norm_sq_to_complex {x : ℂ} : norm_sqC x = complex.norm_sq x := by simp [is_R_or_C.norm_sq, complex.norm_sq] @[simp] lemma abs_to_complex {x : ℂ} : absC x = complex.abs x := by simp [is_R_or_C.abs, complex.abs] end is_R_or_C
206ffb2a80e09bd57e6b5457392a5b01d915a9ff
9ad8d18fbe5f120c22b5e035bc240f711d2cbd7e
/src/homotopy/upper.lean
d6b89fbd7e692009330ebf60483804eff2c5c79e
[]
no_license
agusakov/lean_lib
c0e9cc29fc7d2518004e224376adeb5e69b5cc1a
f88d162da2f990b87c4d34f5f46bbca2bbc5948e
refs/heads/master
1,642,141,461,087
1,557,395,798,000
1,557,395,798,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,862
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland Given a finite poset `P`, we define `upper P` to be the set of subsets `U ⊆ P` that are closed upwards. We order this by *reverse* inclusion, to ensure that the map `u : p ↦ {x : p ≤ x}` is a morphism of posets. We prove that `upper P` is a bounded distributive lattice with this order. -/ import homotopy.poset universes uP uQ uR uS variables (P : Type uP) [decidable_eq P] [fintype P] variables [partial_order P] [decidable_rel (has_le.le : P → P → Prop)] namespace poset variable {P} def is_upper : finset P → Prop := λ (U : finset P), ∀ (p₀ p₁ : P), (p₀ ≤ p₁) → (p₀ ∈ U) → (p₁ ∈ U) variable (P) lemma is_upper_empty : is_upper (@finset.empty P) := λ p₀ p₁ hp hU, (finset.not_mem_empty p₀ hU).elim lemma is_upper_univ : is_upper (@finset.univ P _) := λ p₀ p₁ hp hU, (finset.mem_univ p₁) variable {P} lemma is_upper_union (U V : finset P) (hU : is_upper U) (hV : is_upper V) : is_upper (U ∪ V) := λ p₀ p₁ hp hpUV, begin rcases (finset.mem_union.mp hpUV) with hpU | hpV, {exact finset.mem_union_left V (hU p₀ p₁ hp hpU)}, {exact finset.mem_union_right U (hV p₀ p₁ hp hpV)}, end lemma is_upper_inter (U V : finset P) (hU : is_upper U) (hV : is_upper V) : is_upper (U ∩ V) := λ p₀ p₁ hp hpUV, begin replace hpUV := finset.mem_inter.mp hpUV, apply finset.mem_inter.mpr, split, {exact (hU p₀ p₁ hp hpUV.left)}, {exact (hV p₀ p₁ hp hpUV.right)}, end def distrib (U V W : finset P) : U ∩ (V ∪ W) ⊆ (U ∩ V) ∪ (U ∩ W) := begin intros A h, rw[finset.mem_inter,finset.mem_union] at h, rw[finset.mem_union,finset.mem_inter,finset.mem_inter], rcases h with ⟨hU,hV | hW⟩, exact or.inl ⟨hU,hV⟩, exact or.inr ⟨hU,hW⟩ end variable (P) def upper := { U : finset P // is_upper U } namespace upper instance : has_mem P (upper P) := ⟨λ p U, p ∈ U.val⟩ instance bdl : lattice.bounded_distrib_lattice (upper P) := { le := λ U V, V.val ⊆ U.val, le_refl := λ U, le_refl U.val, le_antisymm := λ U V (h0 : V.val ⊆ U.val) (h1 : U.val ⊆ V.val), begin apply subtype.eq, exact le_antisymm h1 h0, end, le_trans := λ U V W (h0 : V.val ⊆ U.val) (h1 : W.val ⊆ V.val), @le_trans (finset P) _ W.val V.val U.val h1 h0, bot := ⟨finset.univ,is_upper_univ P⟩, top := ⟨finset.empty,is_upper_empty P⟩, inf := λ U V, ⟨U.val ∪ V.val, is_upper_union U.val V.val U.property V.property⟩, sup := λ U V, ⟨U.val ∩ V.val, is_upper_inter U.val V.val U.property V.property⟩, bot_le := λ U,finset.subset_univ U.val, le_top := λ U,finset.empty_subset U.val, le_sup_left := λ U V,finset.inter_subset_left U.val V.val, le_sup_right := λ U V,finset.inter_subset_right U.val V.val, sup_le := λ U V W (U_le_W : W.val ⊆ U.val) (V_le_W : W.val ⊆ V.val), finset.subset_inter U_le_W V_le_W, inf_le_left := λ U V,finset.subset_union_left U.val V.val, inf_le_right := λ U V,finset.subset_union_right U.val V.val, le_inf := λ U V W (U_le_V : V.val ⊆ U.val) (U_le_W : W.val ⊆ U.val), finset.union_subset U_le_V U_le_W, le_sup_inf := λ U V W A h, distrib U.val V.val W.val h, } variable {P} /- We embed `P` in `upper P` using the map `u : A ↦ { B : A ⊆ B }` -/ def u : P → upper P := λ p, ⟨finset.univ.filter (λ q, p ≤ q), begin intros q r hqr hpq, replace hpq := (finset.mem_filter.mp hpq).right, exact finset.mem_filter.mpr ⟨finset.mem_univ r,le_trans hpq hqr⟩, end ⟩ end upper end poset
edf0ce937762913debed1d5db6d0c6b2229dae90
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/algebra/linear_ordered_comm_group_with_zero.lean
cd282c95f3c5087fc854c193327bd5c983811bb2
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
5,954
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Johan Commelin, Patrick Massot -/ import algebra.ordered_group import algebra.group_with_zero import algebra.group_with_zero_power /-! # Linearly ordered commutative groups with a zero element adjoined This file sets up a special class of linearly ordered commutative monoids that show up as the target of so-called “valuations” in algebraic number theory. Usually, in the informal literature, these objects are constructed by taking a linearly ordered commutative group Γ and formally adjoining a zero element: Γ ∪ {0}. The disadvantage is that a type such as `nnreal` is not of that form, whereas it is a very common target for valuations. The solutions is to use a typeclass, and that is exactly what we do in this file. -/ set_option old_structure_cmd true set_option default_priority 100 -- see Note [default priority] /-- A linearly ordered commutative group with a zero element. -/ class linear_ordered_comm_group_with_zero (α : Type*) extends linear_order α, comm_group_with_zero α := (mul_le_mul_left : ∀ {a b : α}, a ≤ b → ∀ c : α, c * a ≤ c * b) (zero_le_one : (0:α) ≤ 1) variables {α : Type*} [linear_ordered_comm_group_with_zero α] variables {a b c d x y z : α} local attribute [instance] classical.prop_decidable /-- Every linearly ordered commutative group with zero is an ordered commutative monoid.-/ instance linear_ordered_comm_group_with_zero.to_ordered_comm_monoid : ordered_comm_monoid α := { lt_of_mul_lt_mul_left := λ a b c h, by { contrapose! h, exact linear_ordered_comm_group_with_zero.mul_le_mul_left h a } .. ‹linear_ordered_comm_group_with_zero α› } section linear_ordered_comm_monoid /- The following facts are true more generally in a (linearly) ordered commutative monoid. -/ lemma one_le_pow_of_one_le' {n : ℕ} (H : 1 ≤ x) : 1 ≤ x^n := begin induction n with n ih, { exact le_refl 1 }, { exact one_le_mul_of_one_le_of_one_le H ih } end lemma pow_le_one_of_le_one {n : ℕ} (H : x ≤ 1) : x^n ≤ 1 := begin induction n with n ih, { exact le_refl 1 }, { exact mul_le_one_of_le_one_of_le_one H ih } end lemma eq_one_of_pow_eq_one {n : ℕ} (hn : n ≠ 0) (H : x ^ n = 1) : x = 1 := begin rcases nat.exists_eq_succ_of_ne_zero hn with ⟨n, rfl⟩, clear hn, induction n with n ih, { simpa using H }, { cases le_total x 1, all_goals { have h1 := mul_le_mul_right' h, rw pow_succ at H, rw [H, one_mul] at h1 }, { have h2 := pow_le_one_of_le_one h, exact ih (le_antisymm h2 h1) }, { have h2 := one_le_pow_of_one_le' h, exact ih (le_antisymm h1 h2) } } end lemma pow_eq_one_iff {n : ℕ} (hn : n ≠ 0) : x ^ n = 1 ↔ x = 1 := ⟨eq_one_of_pow_eq_one hn, by { rintro rfl, exact one_pow _ }⟩ lemma one_le_pow_iff {n : ℕ} (hn : n ≠ 0) : 1 ≤ x^n ↔ 1 ≤ x := begin refine ⟨_, one_le_pow_of_one_le'⟩, contrapose!, intro h, apply lt_of_le_of_ne (pow_le_one_of_le_one (le_of_lt h)), rw [ne.def, pow_eq_one_iff hn], exact ne_of_lt h, end lemma pow_le_one_iff {n : ℕ} (hn : n ≠ 0) : x^n ≤ 1 ↔ x ≤ 1 := begin refine ⟨_, pow_le_one_of_le_one⟩, contrapose!, intro h, apply lt_of_le_of_ne (one_le_pow_of_one_le' (le_of_lt h)), rw [ne.def, eq_comm, pow_eq_one_iff hn], exact ne_of_gt h, end end linear_ordered_comm_monoid lemma zero_le_one' : (0 : α) ≤ 1 := linear_ordered_comm_group_with_zero.zero_le_one lemma zero_lt_one' : (0 : α) < 1 := lt_of_le_of_ne zero_le_one' zero_ne_one @[simp] lemma zero_le' : 0 ≤ a := by simpa only [mul_zero, mul_one] using mul_le_mul_left' zero_le_one' @[simp] lemma not_lt_zero' : ¬a < 0 := not_lt_of_le zero_le' @[simp] lemma le_zero_iff : a ≤ 0 ↔ a = 0 := ⟨λ h, le_antisymm h zero_le', λ h, h ▸ le_refl _⟩ lemma zero_lt_iff : 0 < a ↔ a ≠ 0 := ⟨ne_of_gt, λ h, lt_of_le_of_ne zero_le' h.symm⟩ lemma le_of_le_mul_right (h : c ≠ 0) (hab : a * c ≤ b * c) : a ≤ b := by simpa [h] using (mul_le_mul_right' hab : a * c * c⁻¹ ≤ b * c * c⁻¹) lemma le_mul_inv_of_mul_le (h : c ≠ 0) (hab : a * c ≤ b) : a ≤ b * c⁻¹ := le_of_le_mul_right h (by simpa [h] using hab) lemma mul_inv_le_of_le_mul (h : c ≠ 0) (hab : a ≤ b * c) : a * c⁻¹ ≤ b := le_of_le_mul_right h (by simpa [h] using hab) lemma div_le_div' (a b c d : α) (hb : b ≠ 0) (hd : d ≠ 0) : a * b⁻¹ ≤ c * d⁻¹ ↔ a * d ≤ c * b := begin by_cases ha : a = 0, { simp [ha] }, by_cases hc : c = 0, { simp [inv_ne_zero hb, hc, hd], }, exact (div_le_div_iff' (units.mk0 a ha) (units.mk0 b hb) (units.mk0 c hc) (units.mk0 d hd)), end lemma ne_zero_of_lt (h : b < a) : a ≠ 0 := λ h1, not_lt_zero' $ show b < 0, from h1 ▸ h @[simp] lemma zero_lt_unit (u : units α) : (0 : α) < u := zero_lt_iff.2 $ unit_ne_zero u lemma mul_lt_mul'''' (hab : a < b) (hcd : c < d) : a * c < b * d := have hb : b ≠ 0 := ne_zero_of_lt hab, have hd : d ≠ 0 := ne_zero_of_lt hcd, if ha : a = 0 then by { rw [ha, zero_mul, zero_lt_iff], exact mul_ne_zero hb hd } else if hc : c = 0 then by { rw [hc, mul_zero, zero_lt_iff], exact mul_ne_zero hb hd } else @mul_lt_mul''' _ _ (units.mk0 a ha) (units.mk0 b hb) (units.mk0 c hc) (units.mk0 d hd) hab hcd lemma mul_inv_lt_of_lt_mul' (h : x < y * z) : x * z⁻¹ < y := have hz : z ≠ 0 := (mul_ne_zero_iff.1 $ ne_zero_of_lt h).2, by { contrapose! h, simpa only [inv_inv'] using mul_inv_le_of_le_mul (inv_ne_zero hz) h } lemma mul_lt_right' (c : α) (h : a < b) (hc : c ≠ 0) : a * c < b * c := by { contrapose! h, exact le_of_le_mul_right hc h } lemma inv_lt_inv'' (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ < b⁻¹ ↔ b < a := @inv_lt_inv_iff _ _ (units.mk0 a ha) (units.mk0 b hb) lemma inv_le_inv'' (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := @inv_le_inv_iff _ _ (units.mk0 a ha) (units.mk0 b hb)
3b689d9f5a3e097c421e5f304eba994cc74e6bc8
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/group_theory/commuting_probability.lean
bc035f0065209fa13f6b5216aed3cada3134a29e
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
5,009
lean
/- Copyright (c) 2022 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import algebra.group.conj_finite import group_theory.abelianization import group_theory.group_action.conj_act import group_theory.group_action.quotient import group_theory.index /-! # Commuting Probability > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file introduces the commuting probability of finite groups. ## Main definitions * `comm_prob`: The commuting probability of a finite type with a multiplication operation. ## Todo * Neumann's theorem. -/ noncomputable theory open_locale classical open_locale big_operators open fintype variables (M : Type*) [has_mul M] /-- The commuting probability of a finite type with a multiplication operation -/ def comm_prob : ℚ := nat.card {p : M × M // p.1 * p.2 = p.2 * p.1} / nat.card M ^ 2 lemma comm_prob_def : comm_prob M = nat.card {p : M × M // p.1 * p.2 = p.2 * p.1} / nat.card M ^ 2 := rfl variables [finite M] lemma comm_prob_pos [h : nonempty M] : 0 < comm_prob M := h.elim (λ x, div_pos (nat.cast_pos.mpr (finite.card_pos_iff.mpr ⟨⟨(x, x), rfl⟩⟩)) (pow_pos (nat.cast_pos.mpr finite.card_pos) 2)) lemma comm_prob_le_one : comm_prob M ≤ 1 := begin refine div_le_one_of_le _ (sq_nonneg (nat.card M)), rw [←nat.cast_pow, nat.cast_le, sq, ←nat.card_prod], apply finite.card_subtype_le, end variables {M} lemma comm_prob_eq_one_iff [h : nonempty M] : comm_prob M = 1 ↔ commutative ((*) : M → M → M) := begin haveI := fintype.of_finite M, rw [comm_prob, ←set.coe_set_of, nat.card_eq_fintype_card, nat.card_eq_fintype_card], rw [div_eq_one_iff_eq, ←nat.cast_pow, nat.cast_inj, sq, ←card_prod, set_fintype_card_eq_univ_iff, set.eq_univ_iff_forall], { exact ⟨λ h x y, h (x, y), λ h x, h x.1 x.2⟩ }, { exact pow_ne_zero 2 (nat.cast_ne_zero.mpr card_ne_zero) }, end variables (G : Type*) [group G] [finite G] lemma card_comm_eq_card_conj_classes_mul_card : nat.card {p : G × G // p.1 * p.2 = p.2 * p.1} = nat.card (conj_classes G) * nat.card G := begin haveI := fintype.of_finite G, simp only [nat.card_eq_fintype_card], convert calc card {p : G × G // p.1 * p.2 = p.2 * p.1} = card (Σ g, {h // g * h = h * g}) : card_congr (equiv.subtype_prod_equiv_sigma_subtype (λ g h : G, g * h = h * g)) ... = ∑ g, card {h // g * h = h * g} : card_sigma _ ... = ∑ g, card (mul_action.fixed_by (conj_act G) G g) : sum_equiv conj_act.to_conj_act.to_equiv _ _ (λ g, card_congr' $ congr_arg _ $ funext $ λ h, mul_inv_eq_iff_eq_mul.symm.to_eq) ... = card (quotient (mul_action.orbit_rel (conj_act G) G)) * card G : mul_action.sum_card_fixed_by_eq_card_orbits_mul_card_group (conj_act G) G ... = card (quotient (is_conj.setoid G)) * card G : have this : mul_action.orbit_rel (conj_act G) G = is_conj.setoid G := setoid.ext (λ g h, (setoid.comm' _).trans is_conj_iff.symm), by cc end lemma comm_prob_def' : comm_prob G = nat.card (conj_classes G) / nat.card G := begin rw [comm_prob, card_comm_eq_card_conj_classes_mul_card, nat.cast_mul, sq], exact mul_div_mul_right _ _ (nat.cast_ne_zero.mpr finite.card_pos.ne'), end variables {G} (H : subgroup G) lemma subgroup.comm_prob_subgroup_le : comm_prob H ≤ comm_prob G * H.index ^ 2 := begin /- After rewriting with `comm_prob_def`, we reduce to showing that `G` has at least as many commuting pairs as `H`. -/ rw [comm_prob_def, comm_prob_def, div_le_iff, mul_assoc, ←mul_pow, ←nat.cast_mul, mul_comm H.index, H.card_mul_index, div_mul_cancel, nat.cast_le], { refine finite.card_le_of_injective (λ p, ⟨⟨p.1.1, p.1.2⟩, subtype.ext_iff.mp p.2⟩) _, exact λ p q h, by simpa only [subtype.ext_iff, prod.ext_iff] using h }, { exact pow_ne_zero 2 (nat.cast_ne_zero.mpr finite.card_pos.ne') }, { exact pow_pos (nat.cast_pos.mpr finite.card_pos) 2 }, end lemma subgroup.comm_prob_quotient_le [H.normal] : comm_prob (G ⧸ H) ≤ comm_prob G * nat.card H := begin /- After rewriting with `comm_prob_def'`, we reduce to showing that `G` has at least as many conjugacy classes as `G ⧸ H`. -/ rw [comm_prob_def', comm_prob_def', div_le_iff, mul_assoc, ←nat.cast_mul, ←subgroup.index, H.card_mul_index, div_mul_cancel, nat.cast_le], { apply finite.card_le_of_surjective, show function.surjective (conj_classes.map (quotient_group.mk' H)), exact (conj_classes.map_surjective quotient.surjective_quotient_mk') }, { exact nat.cast_ne_zero.mpr finite.card_pos.ne' }, { exact nat.cast_pos.mpr finite.card_pos }, end variables (G) lemma inv_card_commutator_le_comm_prob : (↑(nat.card (commutator G)))⁻¹ ≤ comm_prob G := (inv_pos_le_iff_one_le_mul (by exact nat.cast_pos.mpr finite.card_pos)).mpr (le_trans (ge_of_eq (comm_prob_eq_one_iff.mpr (abelianization.comm_group G).mul_comm)) (commutator G).comm_prob_quotient_le)
78327fdf367943a4cb77a687976eba6e53741747
36938939954e91f23dec66a02728db08a7acfcf9
/lean4/app/LoadLLVM.lean
be21e3e6e0563f01deedfa20eb56071e57adee6a
[]
no_license
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
436
lean
import LeanLLVM.LLVMLib namespace ReoptVCG /-- Load the LLVM module in the given file. This function is pulled into its own module due to compilation time concerns (i.e., it's dependency on details of LLVMLib). --/ def loadLLVMModule (filePath : String) : IO LLVM.Module := do ctx ← LLVM.FFI.newContext; mb ← LLVM.FFI.newMemoryBufferFromFile filePath; b ← LLVM.FFI.parseAssembly mb ctx; LLVM.loadModule b end ReoptVCG
f9cf28f9a86251785bfcb12b8c95b2ec720ad81f
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/category_theory/punit.lean
2d58474cdca4c5294d18b00dabf449121b6425e6
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
1,757
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import category_theory.const import category_theory.discrete_category universes v u -- declare the `v`'s first; see `category_theory.category` for an explanation namespace category_theory namespace functor variables (C : Type u) [category.{v} C] /-- The constant functor sending everything to `punit.star`. -/ def star : C ⥤ discrete punit := (functor.const _).obj punit.star variable {C} /-- Any two functors to `discrete punit` are isomorphic. -/ def punit_ext (F G : C ⥤ discrete punit) : F ≅ G := nat_iso.of_components (λ _, eq_to_iso dec_trivial) (λ _ _ _, dec_trivial) /-- Any two functors to `discrete punit` are *equal*. You probably want to use `punit_ext` instead of this. -/ lemma punit_ext' (F G : C ⥤ discrete punit) : F = G := functor.ext (λ _, dec_trivial) (λ _ _ _, dec_trivial) /-- The functor from `discrete punit` sending everything to the given object. -/ abbreviation from_punit (X : C) : discrete punit ⥤ C := (functor.const _).obj X /-- Functors from `discrete punit` are equivalent to the category itself. -/ @[simps] def equiv : (discrete punit ⥤ C) ≌ C := { functor := { obj := λ F, F.obj punit.star, map := λ F G θ, θ.app punit.star }, inverse := functor.const _, unit_iso := begin apply nat_iso.of_components _ _, intro X, apply discrete.nat_iso, rintro ⟨⟩, apply iso.refl _, intros, ext ⟨⟩, simp, end, counit_iso := begin refine nat_iso.of_components iso.refl _, intros X Y f, dsimp, simp, -- See note [dsimp, simp]. end } end functor end category_theory
7500ba0dde65cb45a264a9849e47c0188b56739b
618003631150032a5676f229d13a079ac875ff77
/src/set_theory/game.lean
0eb7c9546187a91c48b934dcb43b5e0039c6bcef
[ "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
5,402
lean
/- Copyright (c) 2019 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Mario Carneiro, Isabel Longbottom, Scott Morrison -/ import set_theory.pgame /-! # Combinatorial games. In this file we define the quotient of pre-games by the equivalence relation `p ≈ q ↔ p ≤ q ∧ q ≤ p`, and construct an instance `add_comm_group game`, as well as an instance `partial_order game` (although note carefully the warning that the `<` field in this instance is not the usual relation on combinatorial games). -/ universes u local infix ` ≈ ` := pgame.equiv instance pgame.setoid : setoid pgame := ⟨λ x y, x ≈ y, λ x, pgame.equiv_refl _, λ x y, pgame.equiv_symm, λ x y z, pgame.equiv_trans⟩ /-- The type of combinatorial games. In ZFC, a combinatorial game is constructed from two sets of combinatorial games that have been constructed at an earlier stage. To do this in type theory, we say that a combinatorial pre-game is built inductively from two families of combinatorial games indexed over any type in Type u. The resulting type `pgame.{u}` lives in `Type (u+1)`, reflecting that it is a proper class in ZFC. A combinatorial game is then constructed by quotienting by the equivalence `x ≈ y ↔ x ≤ y ∧ y ≤ x`. -/ def game := quotient pgame.setoid open pgame namespace game /-- The relation `x ≤ y` on games. -/ def le : game → game → Prop := quotient.lift₂ (λ x y, x ≤ y) (λ x₁ y₁ x₂ y₂ hx hy, propext (le_congr hx hy)) instance : has_le game := { le := le } @[refl] theorem le_refl : ∀ x : game, x ≤ x := by { rintro ⟨x⟩, apply pgame.le_refl } @[trans] theorem le_trans : ∀ x y z : game, x ≤ y → y ≤ z → x ≤ z := by { rintro ⟨x⟩ ⟨y⟩ ⟨z⟩, apply pgame.le_trans } theorem le_antisymm : ∀ x y : game, x ≤ y → y ≤ x → x = y := by { rintro ⟨x⟩ ⟨y⟩ h₁ h₂, apply quot.sound, exact ⟨h₁, h₂⟩ } /-- The relation `x < y` on games. -/ -- We don't yet make this into an instance, because it will conflict with the (incorrect) notion -- of `<` provided by `partial_order` later. def lt : game → game → Prop := quotient.lift₂ (λ x y, x < y) (λ x₁ y₁ x₂ y₂ hx hy, propext (lt_congr hx hy)) theorem not_le : ∀ {x y : game}, ¬ (x ≤ y) ↔ (lt y x) := by { rintro ⟨x⟩ ⟨y⟩, exact not_le } instance : has_zero game := ⟨⟦0⟧⟩ instance : inhabited game := ⟨0⟩ instance : has_one game := ⟨⟦1⟧⟩ /-- The negation of `{L | R}` is `{-R | -L}`. -/ def neg : game → game := quot.lift (λ x, ⟦-x⟧) (λ x y h, quot.sound (@neg_congr x y h)) instance : has_neg game := { neg := neg } /-- The sum of `x = {xL | xR}` and `y = {yL | yR}` is `{xL + y, x + yL | xR + y, x + yR}`. -/ def add : game → game → game := quotient.lift₂ (λ x y : pgame, ⟦x + y⟧) (λ x₁ y₁ x₂ y₂ hx hy, quot.sound (pgame.add_congr hx hy)) instance : has_add game := ⟨add⟩ theorem add_assoc : ∀ (x y z : game), (x + y) + z = x + (y + z) := begin rintros ⟨x⟩ ⟨y⟩ ⟨z⟩, apply quot.sound, exact add_assoc_equiv end instance : add_semigroup game.{u} := { add_assoc := add_assoc, ..game.has_add } theorem add_zero : ∀ (x : game), x + 0 = x := begin rintro ⟨x⟩, apply quot.sound, apply add_zero_equiv end theorem zero_add : ∀ (x : game), 0 + x = x := begin rintro ⟨x⟩, apply quot.sound, apply zero_add_equiv end instance : add_monoid game := { add_zero := add_zero, zero_add := zero_add, ..game.has_zero, ..game.add_semigroup } theorem add_left_neg : ∀ (x : game), (-x) + x = 0 := begin rintro ⟨x⟩, apply quot.sound, apply add_left_neg_equiv end instance : add_group game := { add_left_neg := add_left_neg, ..game.has_neg, ..game.add_monoid } theorem add_comm : ∀ (x y : game), x + y = y + x := begin rintros ⟨x⟩ ⟨y⟩, apply quot.sound, exact add_comm_equiv end instance : add_comm_semigroup game := { add_comm := add_comm, ..game.add_semigroup } instance : add_comm_group game := { ..game.add_comm_semigroup, ..game.add_group } theorem add_le_add_left : ∀ (a b : game), a ≤ b → ∀ (c : game), c + a ≤ c + b := begin rintro ⟨a⟩ ⟨b⟩ h ⟨c⟩, apply pgame.add_le_add_left h, end -- While it is very tempting to define a `partial_order` on games, and prove -- that games form an `ordered_add_comm_group`, it is a bit dangerous. -- The relations `≤` and `<` on games do not satisfy -- `lt_iff_le_not_le : ∀ a b : α, a < b ↔ (a ≤ b ∧ ¬ b ≤ a)` -- (Consider `a = 0`, `b = star`.) -- (`lt_iff_le_not_le` is satisfied by surreal numbers, however.) -- Thus we can not use `<` when defining a `partial_order`. -- Because of this issue, we define the `partial_order` and `ordered_add_comm_group` instances, -- but do not actually mark them as instances, for safety. /-- The `<` operation provided by this partial order is not the usual `<` on games! -/ def game_partial_order : partial_order game := { le_refl := le_refl, le_trans := le_trans, le_antisymm := le_antisymm, ..game.has_le } local attribute [instance] game_partial_order /-- The `<` operation provided by this `ordered_add_comm_group` is not the usual `<` on games! -/ def ordered_add_comm_group_game : ordered_add_comm_group game := ordered_add_comm_group.mk' add_le_add_left end game
3315212152cbf11b1d39c8afbd169f461029b04e
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/Lake/DSL/Package.lean
13269eaeaca8455521ec07e5ad0664756d03fe48
[ "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,119
lean
/- Copyright (c) 2021 Mac Malone. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mac Malone -/ import Lake.Config.Package import Lake.DSL.Attributes import Lake.DSL.DeclUtil namespace Lake.DSL open Lean Parser Command /-- The name given to the definition created by the `package` syntax. -/ def packageDeclName := `_package /-- Defines the configuration of a Lake package. Has many forms: ```lean package «pkg-name» package «pkg-name» { /- config opts -/ } package «pkg-name» where /- config opts -/ package «pkg-name» : PackageConfig := /- config -/ ``` There can only be one `package` declaration per Lake configuration file. The defined package configuration will be available for reference as `_package`. -/ scoped macro (name := packageDecl) doc?:optional(docComment) attrs?:optional(Term.attributes) "package " sig:structDeclSig : command => do let attr ← `(Term.attrInstance| «package») let ty := mkCIdentFrom (← getRef) ``PackageConfig let attrs := #[attr] ++ expandAttrs attrs? mkConfigStructDecl packageDeclName doc? attrs ty sig
1c84ea5b4465341e1431de8e41384c0616cda5d8
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/data/finsupp/basic.lean
6eb83903dad69d92474a19de3aa6ec231ac2e78a
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
119,409
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Scott Morrison -/ import algebra.hom.group_action import algebra.indicator_function import data.finset.preimage import data.list.alist /-! # Type of functions with finite support For any type `α` and a type `M` with zero, we define the type `finsupp α M` (notation: `α →₀ M`) of finitely supported functions from `α` to `M`, i.e. the functions which are zero everywhere on `α` except on a finite set. Functions with finite support are used (at least) in the following parts of the library: * `monoid_algebra R M` and `add_monoid_algebra R M` are defined as `M →₀ R`; * polynomials and multivariate polynomials are defined as `add_monoid_algebra`s, hence they use `finsupp` under the hood; * the linear combination of a family of vectors `v i` with coefficients `f i` (as used, e.g., to define linearly independent family `linear_independent`) is defined as a map `finsupp.total : (ι → M) → (ι →₀ R) →ₗ[R] M`. Some other constructions are naturally equivalent to `α →₀ M` with some `α` and `M` but are defined in a different way in the library: * `multiset α ≃+ α →₀ ℕ`; * `free_abelian_group α ≃+ α →₀ ℤ`. Most of the theory assumes that the range is a commutative additive monoid. This gives us the big sum operator as a powerful way to construct `finsupp` elements. Many constructions based on `α →₀ M` use `semireducible` type tags to avoid reusing unwanted type instances. E.g., `monoid_algebra`, `add_monoid_algebra`, and types based on these two have non-pointwise multiplication. ## Main declarations * `finsupp`: The type of finitely supported functions from `α` to `β`. * `finsupp.single`: The `finsupp` which is nonzero in exactly one point. * `finsupp.update`: Changes one value of a `finsupp`. * `finsupp.erase`: Replaces one value of a `finsupp` by `0`. * `finsupp.on_finset`: The restriction of a function to a `finset` as a `finsupp`. * `finsupp.map_range`: Composition of a `zero_hom` with a `finsupp`. * `finsupp.emb_domain`: Maps the domain of a `finsupp` by an embedding. * `finsupp.map_domain`: Maps the domain of a `finsupp` by a function and by summing. * `finsupp.comap_domain`: Postcomposition of a `finsupp` with a function injective on the preimage of its support. * `finsupp.zip_with`: Postcomposition of two `finsupp`s with a function `f` such that `f 0 0 = 0`. * `finsupp.sum`: Sum of the values of a `finsupp`. * `finsupp.prod`: Product of the nonzero values of a `finsupp`. ## Notations This file adds `α →₀ M` as a global notation for `finsupp α M`. We also use the following convention for `Type*` variables in this file * `α`, `β`, `γ`: types with no additional structure that appear as the first argument to `finsupp` somewhere in the statement; * `ι` : an auxiliary index type; * `M`, `M'`, `N`, `P`: types with `has_zero` or `(add_)(comm_)monoid` structure; `M` is also used for a (semi)module over a (semi)ring. * `G`, `H`: groups (commutative or not, multiplicative or additive); * `R`, `S`: (semi)rings. ## Implementation notes This file is a `noncomputable theory` and uses classical logic throughout. ## TODO * This file is currently ~2.7K lines long, so it should be splitted into smaller chunks. One option would be to move all the sum and product stuff to `algebra.big_operators.finsupp` and move the definitions that depend on it to new files under `data.finsupp.`. * Expand the list of definitions and important lemmas to the module docstring. -/ noncomputable theory open finset function open_locale classical big_operators variables {α β γ ι M M' N P G H R S : Type*} /-- `finsupp α M`, denoted `α →₀ M`, is the type of functions `f : α → M` such that `f x = 0` for all but finitely many `x`. -/ structure finsupp (α : Type*) (M : Type*) [has_zero M] := (support : finset α) (to_fun : α → M) (mem_support_to_fun : ∀a, a ∈ support ↔ to_fun a ≠ 0) infixr ` →₀ `:25 := finsupp namespace finsupp /-! ### Basic declarations about `finsupp` -/ section basic variable [has_zero M] instance fun_like : fun_like (α →₀ M) α (λ _, M) := ⟨to_fun, begin rintro ⟨s, f, hf⟩ ⟨t, g, hg⟩ (rfl : f = g), congr', ext a, exact (hf _).trans (hg _).symm, end⟩ /-- Helper instance for when there are too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (α →₀ M) (λ _, α → M) := fun_like.has_coe_to_fun @[ext] lemma ext {f g : α →₀ M} (h : ∀ a, f a = g a) : f = g := fun_like.ext _ _ h /-- Deprecated. Use `fun_like.ext_iff` instead. -/ lemma ext_iff {f g : α →₀ M} : f = g ↔ ∀ a, f a = g a := fun_like.ext_iff /-- Deprecated. Use `fun_like.coe_fn_eq` instead. -/ lemma coe_fn_inj {f g : α →₀ M} : (f : α → M) = g ↔ f = g := fun_like.coe_fn_eq /-- Deprecated. Use `fun_like.coe_injective` instead. -/ lemma coe_fn_injective : @function.injective (α →₀ M) (α → M) coe_fn := fun_like.coe_injective /-- Deprecated. Use `fun_like.congr_fun` instead. -/ lemma congr_fun {f g : α →₀ M} (h : f = g) (a : α) : f a = g a := fun_like.congr_fun h _ @[simp] lemma coe_mk (f : α → M) (s : finset α) (h : ∀ a, a ∈ s ↔ f a ≠ 0) : ⇑(⟨s, f, h⟩ : α →₀ M) = f := rfl instance : has_zero (α →₀ M) := ⟨⟨∅, 0, λ _, ⟨false.elim, λ H, H rfl⟩⟩⟩ @[simp] lemma coe_zero : ⇑(0 : α →₀ M) = 0 := rfl lemma zero_apply {a : α} : (0 : α →₀ M) a = 0 := rfl @[simp] lemma support_zero : (0 : α →₀ M).support = ∅ := rfl instance : inhabited (α →₀ M) := ⟨0⟩ @[simp] lemma mem_support_iff {f : α →₀ M} : ∀{a:α}, a ∈ f.support ↔ f a ≠ 0 := f.mem_support_to_fun @[simp, norm_cast] lemma fun_support_eq (f : α →₀ M) : function.support f = f.support := set.ext $ λ x, mem_support_iff.symm lemma not_mem_support_iff {f : α →₀ M} {a} : a ∉ f.support ↔ f a = 0 := not_iff_comm.1 mem_support_iff.symm @[simp, norm_cast] lemma coe_eq_zero {f : α →₀ M} : (f : α → M) = 0 ↔ f = 0 := by rw [← coe_zero, coe_fn_inj] lemma ext_iff' {f g : α →₀ M} : f = g ↔ f.support = g.support ∧ ∀ x ∈ f.support, f x = g x := ⟨λ h, h ▸ ⟨rfl, λ _ _, rfl⟩, λ ⟨h₁, h₂⟩, ext $ λ a, if h : a ∈ f.support then h₂ a h else have hf : f a = 0, from not_mem_support_iff.1 h, have hg : g a = 0, by rwa [h₁, not_mem_support_iff] at h, by rw [hf, hg]⟩ @[simp] lemma support_eq_empty {f : α →₀ M} : f.support = ∅ ↔ f = 0 := by exact_mod_cast @function.support_eq_empty_iff _ _ _ f lemma support_nonempty_iff {f : α →₀ M} : f.support.nonempty ↔ f ≠ 0 := by simp only [finsupp.support_eq_empty, finset.nonempty_iff_ne_empty, ne.def] lemma nonzero_iff_exists {f : α →₀ M} : f ≠ 0 ↔ ∃ a : α, f a ≠ 0 := by simp [← finsupp.support_eq_empty, finset.eq_empty_iff_forall_not_mem] lemma card_support_eq_zero {f : α →₀ M} : card f.support = 0 ↔ f = 0 := by simp instance [decidable_eq α] [decidable_eq M] : decidable_eq (α →₀ M) := assume f g, decidable_of_iff (f.support = g.support ∧ (∀a∈f.support, f a = g a)) ext_iff'.symm lemma finite_support (f : α →₀ M) : set.finite (function.support f) := f.fun_support_eq.symm ▸ f.support.finite_to_set lemma support_subset_iff {s : set α} {f : α →₀ M} : ↑f.support ⊆ s ↔ (∀a∉s, f a = 0) := by simp only [set.subset_def, mem_coe, mem_support_iff]; exact forall_congr (assume a, not_imp_comm) /-- Given `fintype α`, `equiv_fun_on_fintype` is the `equiv` between `α →₀ β` and `α → β`. (All functions on a finite type are finitely supported.) -/ @[simps] def equiv_fun_on_fintype [fintype α] : (α →₀ M) ≃ (α → M) := ⟨λf a, f a, λf, mk (finset.univ.filter $ λa, f a ≠ 0) f (by simp only [true_and, finset.mem_univ, iff_self, finset.mem_filter, finset.filter_congr_decidable, forall_true_iff]), begin intro f, ext a, refl end, begin intro f, ext a, refl end⟩ @[simp] lemma equiv_fun_on_fintype_symm_coe {α} [fintype α] (f : α →₀ M) : equiv_fun_on_fintype.symm f = f := by { ext, simp [equiv_fun_on_fintype], } /-- If `α` has a unique term, then the type of finitely supported functions `α →₀ β` is equivalent to `β`. -/ @[simps] noncomputable def _root_.equiv.finsupp_unique {ι : Type*} [unique ι] : (ι →₀ M) ≃ M := finsupp.equiv_fun_on_fintype.trans (equiv.fun_unique ι M) end basic /-! ### Declarations about `single` -/ section single variables [has_zero M] {a a' : α} {b : M} /-- `single a b` is the finitely supported function which has value `b` at `a` and zero otherwise. -/ def single (a : α) (b : M) : α →₀ M := ⟨if b = 0 then ∅ else {a}, λ a', if a = a' then b else 0, λ a', begin by_cases hb : b = 0; by_cases a = a'; simp only [hb, h, if_pos, if_false, mem_singleton], { exact ⟨false.elim, λ H, H rfl⟩ }, { exact ⟨false.elim, λ H, H rfl⟩ }, { exact ⟨λ _, hb, λ _, rfl⟩ }, { exact ⟨λ H _, h H.symm, λ H, (H rfl).elim⟩ } end⟩ lemma single_apply [decidable (a = a')] : single a b a' = if a = a' then b else 0 := by convert rfl lemma single_eq_indicator : ⇑(single a b) = set.indicator {a} (λ _, b) := by { ext, simp [single_apply, set.indicator, @eq_comm _ a] } @[simp] lemma single_eq_same : (single a b : α →₀ M) a = b := if_pos rfl @[simp] lemma single_eq_of_ne (h : a ≠ a') : (single a b : α →₀ M) a' = 0 := if_neg h lemma single_eq_update [decidable_eq α] (a : α) (b : M) : ⇑(single a b) = function.update 0 a b := by rw [single_eq_indicator, ← set.piecewise_eq_indicator, set.piecewise_singleton] lemma single_eq_pi_single [decidable_eq α] (a : α) (b : M) : ⇑(single a b) = pi.single a b := single_eq_update a b @[simp] lemma single_zero (a : α) : (single a 0 : α →₀ M) = 0 := coe_fn_injective $ by simpa only [single_eq_update, coe_zero] using function.update_eq_self a (0 : α → M) lemma single_of_single_apply (a a' : α) (b : M) : single a ((single a' b) a) = single a' (single a' b) a := begin rw [single_apply, single_apply], ext, split_ifs, { rw h, }, { rw [zero_apply, single_apply, if_t_t], }, end lemma support_single_ne_zero (a : α) (hb : b ≠ 0) : (single a b).support = {a} := if_neg hb lemma support_single_subset : (single a b).support ⊆ {a} := show ite _ _ _ ⊆ _, by split_ifs; [exact empty_subset _, exact subset.refl _] lemma single_apply_mem (x) : single a b x ∈ ({0, b} : set M) := by rcases em (a = x) with (rfl|hx); [simp, simp [single_eq_of_ne hx]] lemma range_single_subset : set.range (single a b) ⊆ {0, b} := set.range_subset_iff.2 single_apply_mem /-- `finsupp.single a b` is injective in `b`. For the statement that it is injective in `a`, see `finsupp.single_left_injective` -/ lemma single_injective (a : α) : function.injective (single a : M → α →₀ M) := assume b₁ b₂ eq, have (single a b₁ : α →₀ M) a = (single a b₂ : α →₀ M) a, by rw eq, by rwa [single_eq_same, single_eq_same] at this lemma single_apply_eq_zero {a x : α} {b : M} : single a b x = 0 ↔ (x = a → b = 0) := by simp [single_eq_indicator] lemma single_apply_ne_zero {a x : α} {b : M} : single a b x ≠ 0 ↔ (x = a ∧ b ≠ 0) := by simp [single_apply_eq_zero] lemma mem_support_single (a a' : α) (b : M) : a ∈ (single a' b).support ↔ a = a' ∧ b ≠ 0 := by simp [single_apply_eq_zero, not_or_distrib] lemma eq_single_iff {f : α →₀ M} {a b} : f = single a b ↔ f.support ⊆ {a} ∧ f a = b := begin refine ⟨λ h, h.symm ▸ ⟨support_single_subset, single_eq_same⟩, _⟩, rintro ⟨h, rfl⟩, ext x, by_cases hx : a = x; simp only [hx, single_eq_same, single_eq_of_ne, ne.def, not_false_iff], exact not_mem_support_iff.1 (mt (λ hx, (mem_singleton.1 (h hx)).symm) hx) end lemma single_eq_single_iff (a₁ a₂ : α) (b₁ b₂ : M) : single a₁ b₁ = single a₂ b₂ ↔ ((a₁ = a₂ ∧ b₁ = b₂) ∨ (b₁ = 0 ∧ b₂ = 0)) := begin split, { assume eq, by_cases a₁ = a₂, { refine or.inl ⟨h, _⟩, rwa [h, (single_injective a₂).eq_iff] at eq }, { rw [ext_iff] at eq, have h₁ := eq a₁, have h₂ := eq a₂, simp only [single_eq_same, single_eq_of_ne h, single_eq_of_ne (ne.symm h)] at h₁ h₂, exact or.inr ⟨h₁, h₂.symm⟩ } }, { rintros (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩), { refl }, { rw [single_zero, single_zero] } } end /-- `finsupp.single a b` is injective in `a`. For the statement that it is injective in `b`, see `finsupp.single_injective` -/ lemma single_left_injective (h : b ≠ 0) : function.injective (λ a : α, single a b) := λ a a' H, (((single_eq_single_iff _ _ _ _).mp H).resolve_right $ λ hb, h hb.1).left lemma single_left_inj (h : b ≠ 0) : single a b = single a' b ↔ a = a' := (single_left_injective h).eq_iff lemma support_single_ne_bot (i : α) (h : b ≠ 0) : (single i b).support ≠ ⊥ := by simpa only [support_single_ne_zero _ h] using singleton_ne_empty _ lemma support_single_disjoint [decidable_eq α] {b' : M} (hb : b ≠ 0) (hb' : b' ≠ 0) {i j : α} : disjoint (single i b).support (single j b').support ↔ i ≠ j := by rw [support_single_ne_zero _ hb, support_single_ne_zero _ hb', disjoint_singleton] @[simp] lemma single_eq_zero : single a b = 0 ↔ b = 0 := by simp [ext_iff, single_eq_indicator] lemma single_swap (a₁ a₂ : α) (b : M) : single a₁ b a₂ = single a₂ b a₁ := by simp only [single_apply]; ac_refl instance [nonempty α] [nontrivial M] : nontrivial (α →₀ M) := begin inhabit α, rcases exists_ne (0 : M) with ⟨x, hx⟩, exact nontrivial_of_ne (single default x) 0 (mt single_eq_zero.1 hx) end lemma unique_single [unique α] (x : α →₀ M) : x = single default (x default) := ext $ unique.forall_iff.2 single_eq_same.symm @[ext] lemma unique_ext [unique α] {f g : α →₀ M} (h : f default = g default) : f = g := ext $ λ a, by rwa [unique.eq_default a] lemma unique_ext_iff [unique α] {f g : α →₀ M} : f = g ↔ f default = g default := ⟨λ h, h ▸ rfl, unique_ext⟩ @[simp] lemma unique_single_eq_iff [unique α] {b' : M} : single a b = single a' b' ↔ b = b' := by rw [unique_ext_iff, unique.eq_default a, unique.eq_default a', single_eq_same, single_eq_same] lemma support_eq_singleton {f : α →₀ M} {a : α} : f.support = {a} ↔ f a ≠ 0 ∧ f = single a (f a) := ⟨λ h, ⟨mem_support_iff.1 $ h.symm ▸ finset.mem_singleton_self a, eq_single_iff.2 ⟨subset_of_eq h, rfl⟩⟩, λ h, h.2.symm ▸ support_single_ne_zero _ h.1⟩ lemma support_eq_singleton' {f : α →₀ M} {a : α} : f.support = {a} ↔ ∃ b ≠ 0, f = single a b := ⟨λ h, let h := support_eq_singleton.1 h in ⟨_, h.1, h.2⟩, λ ⟨b, hb, hf⟩, hf.symm ▸ support_single_ne_zero _ hb⟩ lemma card_support_eq_one {f : α →₀ M} : card f.support = 1 ↔ ∃ a, f a ≠ 0 ∧ f = single a (f a) := by simp only [card_eq_one, support_eq_singleton] lemma card_support_eq_one' {f : α →₀ M} : card f.support = 1 ↔ ∃ a (b ≠ 0), f = single a b := by simp only [card_eq_one, support_eq_singleton'] lemma support_subset_singleton {f : α →₀ M} {a : α} : f.support ⊆ {a} ↔ f = single a (f a) := ⟨λ h, eq_single_iff.mpr ⟨h, rfl⟩, λ h, (eq_single_iff.mp h).left⟩ lemma support_subset_singleton' {f : α →₀ M} {a : α} : f.support ⊆ {a} ↔ ∃ b, f = single a b := ⟨λ h, ⟨f a, support_subset_singleton.mp h⟩, λ ⟨b, hb⟩, by rw [hb, support_subset_singleton, single_eq_same]⟩ lemma card_support_le_one [nonempty α] {f : α →₀ M} : card f.support ≤ 1 ↔ ∃ a, f = single a (f a) := by simp only [card_le_one_iff_subset_singleton, support_subset_singleton] lemma card_support_le_one' [nonempty α] {f : α →₀ M} : card f.support ≤ 1 ↔ ∃ a b, f = single a b := by simp only [card_le_one_iff_subset_singleton, support_subset_singleton'] @[simp] lemma equiv_fun_on_fintype_single [decidable_eq α] [fintype α] (x : α) (m : M) : (@finsupp.equiv_fun_on_fintype α M _ _) (finsupp.single x m) = pi.single x m := by { ext, simp [finsupp.single_eq_pi_single, finsupp.equiv_fun_on_fintype], } @[simp] lemma equiv_fun_on_fintype_symm_single [decidable_eq α] [fintype α] (x : α) (m : M) : (@finsupp.equiv_fun_on_fintype α M _ _).symm (pi.single x m) = finsupp.single x m := by { ext, simp [finsupp.single_eq_pi_single, finsupp.equiv_fun_on_fintype], } end single /-! ### Declarations about `update` -/ section update variables [has_zero M] (f : α →₀ M) (a : α) (b : M) (i : α) /-- Replace the value of a `α →₀ M` at a given point `a : α` by a given value `b : M`. If `b = 0`, this amounts to removing `a` from the `finsupp.support`. Otherwise, if `a` was not in the `finsupp.support`, it is added to it. This is the finitely-supported version of `function.update`. -/ def update : α →₀ M := ⟨if b = 0 then f.support.erase a else insert a f.support, function.update f a b, λ i, begin simp only [function.update_apply, ne.def], split_ifs with hb ha ha hb; simp [ha, hb] end⟩ @[simp] lemma coe_update [decidable_eq α] : (f.update a b : α → M) = function.update f a b := by convert rfl @[simp] lemma update_self : f.update a (f a) = f := by { ext, simp } lemma support_update [decidable_eq α] : support (f.update a b) = if b = 0 then f.support.erase a else insert a f.support := by convert rfl @[simp] lemma support_update_zero [decidable_eq α] : support (f.update a 0) = f.support.erase a := by convert if_pos rfl variables {b} lemma support_update_ne_zero [decidable_eq α] (h : b ≠ 0) : support (f.update a b) = insert a f.support := by convert if_neg h end update /-! ### Declarations about `on_finset` -/ section on_finset variables [has_zero M] /-- `on_finset s f hf` is the finsupp function representing `f` restricted to the finset `s`. The function needs to be `0` outside of `s`. Use this when the set needs to be filtered anyways, otherwise a better set representation is often available. -/ def on_finset (s : finset α) (f : α → M) (hf : ∀a, f a ≠ 0 → a ∈ s) : α →₀ M := ⟨s.filter (λa, f a ≠ 0), f, by simpa⟩ @[simp] lemma on_finset_apply {s : finset α} {f : α → M} {hf a} : (on_finset s f hf : α →₀ M) a = f a := rfl @[simp] lemma support_on_finset_subset {s : finset α} {f : α → M} {hf} : (on_finset s f hf).support ⊆ s := filter_subset _ _ @[simp] lemma mem_support_on_finset {s : finset α} {f : α → M} (hf : ∀ (a : α), f a ≠ 0 → a ∈ s) {a : α} : a ∈ (finsupp.on_finset s f hf).support ↔ f a ≠ 0 := by rw [finsupp.mem_support_iff, finsupp.on_finset_apply] lemma support_on_finset {s : finset α} {f : α → M} (hf : ∀ (a : α), f a ≠ 0 → a ∈ s) : (finsupp.on_finset s f hf).support = s.filter (λ a, f a ≠ 0) := rfl end on_finset section of_support_finite variables [has_zero M] /-- The natural `finsupp` induced by the function `f` given that it has finite support. -/ noncomputable def of_support_finite (f : α → M) (hf : (function.support f).finite) : α →₀ M := { support := hf.to_finset, to_fun := f, mem_support_to_fun := λ _, hf.mem_to_finset } lemma of_support_finite_coe {f : α → M} {hf : (function.support f).finite} : (of_support_finite f hf : α → M) = f := rfl instance : can_lift (α → M) (α →₀ M) := { coe := coe_fn, cond := λ f, (function.support f).finite, prf := λ f hf, ⟨of_support_finite f hf, rfl⟩ } end of_support_finite /-! ### Declarations about `map_range` -/ section map_range variables [has_zero M] [has_zero N] [has_zero P] /-- The composition of `f : M → N` and `g : α →₀ M` is `map_range f hf g : α →₀ N`, well-defined when `f 0 = 0`. This preserves the structure on `f`, and exists in various bundled forms for when `f` is itself bundled: * `finsupp.map_range.equiv` * `finsupp.map_range.zero_hom` * `finsupp.map_range.add_monoid_hom` * `finsupp.map_range.add_equiv` * `finsupp.map_range.linear_map` * `finsupp.map_range.linear_equiv` -/ def map_range (f : M → N) (hf : f 0 = 0) (g : α →₀ M) : α →₀ N := on_finset g.support (f ∘ g) $ assume a, by rw [mem_support_iff, not_imp_not]; exact λ H, (congr_arg f H).trans hf @[simp] lemma map_range_apply {f : M → N} {hf : f 0 = 0} {g : α →₀ M} {a : α} : map_range f hf g a = f (g a) := rfl @[simp] lemma map_range_zero {f : M → N} {hf : f 0 = 0} : map_range f hf (0 : α →₀ M) = 0 := ext $ λ a, by simp only [hf, zero_apply, map_range_apply] @[simp] lemma map_range_id (g : α →₀ M) : map_range id rfl g = g := ext $ λ _, rfl lemma map_range_comp (f : N → P) (hf : f 0 = 0) (f₂ : M → N) (hf₂ : f₂ 0 = 0) (h : (f ∘ f₂) 0 = 0) (g : α →₀ M) : map_range (f ∘ f₂) h g = map_range f hf (map_range f₂ hf₂ g) := ext $ λ _, rfl lemma support_map_range {f : M → N} {hf : f 0 = 0} {g : α →₀ M} : (map_range f hf g).support ⊆ g.support := support_on_finset_subset @[simp] lemma map_range_single {f : M → N} {hf : f 0 = 0} {a : α} {b : M} : map_range f hf (single a b) = single a (f b) := ext $ λ a', show f (ite _ _ _) = ite _ _ _, by split_ifs; [refl, exact hf] lemma support_map_range_of_injective {e : M → N} (he0 : e 0 = 0) (f : ι →₀ M) (he : function.injective e) : (finsupp.map_range e he0 f).support = f.support := begin ext, simp only [finsupp.mem_support_iff, ne.def, finsupp.map_range_apply], exact he.ne_iff' he0, end end map_range /-! ### Declarations about `emb_domain` -/ section emb_domain variables [has_zero M] [has_zero N] /-- Given `f : α ↪ β` and `v : α →₀ M`, `emb_domain f v : β →₀ M` is the finitely supported function whose value at `f a : β` is `v a`. For a `b : β` outside the range of `f`, it is zero. -/ def emb_domain (f : α ↪ β) (v : α →₀ M) : β →₀ M := begin refine ⟨v.support.map f, λa₂, if h : a₂ ∈ v.support.map f then v (v.support.choose (λa₁, f a₁ = a₂) _) else 0, _⟩, { rcases finset.mem_map.1 h with ⟨a, ha, rfl⟩, exact exists_unique.intro a ⟨ha, rfl⟩ (assume b ⟨_, hb⟩, f.injective hb) }, { assume a₂, split_ifs, { simp only [h, true_iff, ne.def], rw [← not_mem_support_iff, not_not], apply finset.choose_mem }, { simp only [h, ne.def, ne_self_iff_false] } } end @[simp] lemma support_emb_domain (f : α ↪ β) (v : α →₀ M) : (emb_domain f v).support = v.support.map f := rfl @[simp] lemma emb_domain_zero (f : α ↪ β) : (emb_domain f 0 : β →₀ M) = 0 := rfl @[simp] lemma emb_domain_apply (f : α ↪ β) (v : α →₀ M) (a : α) : emb_domain f v (f a) = v a := begin change dite _ _ _ = _, split_ifs; rw [finset.mem_map' f] at h, { refine congr_arg (v : α → M) (f.inj' _), exact finset.choose_property (λa₁, f a₁ = f a) _ _ }, { exact (not_mem_support_iff.1 h).symm } end lemma emb_domain_notin_range (f : α ↪ β) (v : α →₀ M) (a : β) (h : a ∉ set.range f) : emb_domain f v a = 0 := begin refine dif_neg (mt (assume h, _) h), rcases finset.mem_map.1 h with ⟨a, h, rfl⟩, exact set.mem_range_self a end lemma emb_domain_injective (f : α ↪ β) : function.injective (emb_domain f : (α →₀ M) → (β →₀ M)) := λ l₁ l₂ h, ext $ λ a, by simpa only [emb_domain_apply] using ext_iff.1 h (f a) @[simp] lemma emb_domain_inj {f : α ↪ β} {l₁ l₂ : α →₀ M} : emb_domain f l₁ = emb_domain f l₂ ↔ l₁ = l₂ := (emb_domain_injective f).eq_iff @[simp] lemma emb_domain_eq_zero {f : α ↪ β} {l : α →₀ M} : emb_domain f l = 0 ↔ l = 0 := (emb_domain_injective f).eq_iff' $ emb_domain_zero f lemma emb_domain_map_range (f : α ↪ β) (g : M → N) (p : α →₀ M) (hg : g 0 = 0) : emb_domain f (map_range g hg p) = map_range g hg (emb_domain f p) := begin ext a, by_cases a ∈ set.range f, { rcases h with ⟨a', rfl⟩, rw [map_range_apply, emb_domain_apply, emb_domain_apply, map_range_apply] }, { rw [map_range_apply, emb_domain_notin_range, emb_domain_notin_range, ← hg]; assumption } end lemma single_of_emb_domain_single (l : α →₀ M) (f : α ↪ β) (a : β) (b : M) (hb : b ≠ 0) (h : l.emb_domain f = single a b) : ∃ x, l = single x b ∧ f x = a := begin have h_map_support : finset.map f (l.support) = {a}, by rw [←support_emb_domain, h, support_single_ne_zero _ hb]; refl, have ha : a ∈ finset.map f (l.support), by simp only [h_map_support, finset.mem_singleton], rcases finset.mem_map.1 ha with ⟨c, hc₁, hc₂⟩, use c, split, { ext d, rw [← emb_domain_apply f l, h], by_cases h_cases : c = d, { simp only [eq.symm h_cases, hc₂, single_eq_same] }, { rw [single_apply, single_apply, if_neg, if_neg h_cases], by_contra hfd, exact h_cases (f.injective (hc₂.trans hfd)) } }, { exact hc₂ } end @[simp] lemma emb_domain_single (f : α ↪ β) (a : α) (m : M) : emb_domain f (single a m) = single (f a) m := begin ext b, by_cases h : b ∈ set.range f, { rcases h with ⟨a', rfl⟩, simp [single_apply], }, { simp only [emb_domain_notin_range, h, single_apply, not_false_iff], rw if_neg, rintro rfl, simpa using h, }, end end emb_domain /-! ### Declarations about `zip_with` -/ section zip_with variables [has_zero M] [has_zero N] [has_zero P] /-- `zip_with f hf g₁ g₂` is the finitely supported function satisfying `zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a)`, and it is well-defined when `f 0 0 = 0`. -/ def zip_with (f : M → N → P) (hf : f 0 0 = 0) (g₁ : α →₀ M) (g₂ : α →₀ N) : α →₀ P := on_finset (g₁.support ∪ g₂.support) (λa, f (g₁ a) (g₂ a)) $ λ a H, begin simp only [mem_union, mem_support_iff, ne], rw [← not_and_distrib], rintro ⟨h₁, h₂⟩, rw [h₁, h₂] at H, exact H hf end @[simp] lemma zip_with_apply {f : M → N → P} {hf : f 0 0 = 0} {g₁ : α →₀ M} {g₂ : α →₀ N} {a : α} : zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a) := rfl lemma support_zip_with [D : decidable_eq α] {f : M → N → P} {hf : f 0 0 = 0} {g₁ : α →₀ M} {g₂ : α →₀ N} : (zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support := by rw subsingleton.elim D; exact support_on_finset_subset end zip_with /-! ### Declarations about `erase` -/ section erase variables [has_zero M] /-- `erase a f` is the finitely supported function equal to `f` except at `a` where it is equal to `0`. -/ def erase (a : α) (f : α →₀ M) : α →₀ M := ⟨f.support.erase a, (λa', if a' = a then 0 else f a'), assume a', by rw [mem_erase, mem_support_iff]; split_ifs; [exact ⟨λ H _, H.1 h, λ H, (H rfl).elim⟩, exact and_iff_right h]⟩ @[simp] lemma support_erase [decidable_eq α] {a : α} {f : α →₀ M} : (f.erase a).support = f.support.erase a := by convert rfl @[simp] lemma erase_same {a : α} {f : α →₀ M} : (f.erase a) a = 0 := if_pos rfl @[simp] lemma erase_ne {a a' : α} {f : α →₀ M} (h : a' ≠ a) : (f.erase a) a' = f a' := if_neg h @[simp] lemma erase_single {a : α} {b : M} : (erase a (single a b)) = 0 := begin ext s, by_cases hs : s = a, { rw [hs, erase_same], refl }, { rw [erase_ne hs], exact single_eq_of_ne (ne.symm hs) } end lemma erase_single_ne {a a' : α} {b : M} (h : a ≠ a') : (erase a (single a' b)) = single a' b := begin ext s, by_cases hs : s = a, { rw [hs, erase_same, single_eq_of_ne (h.symm)] }, { rw [erase_ne hs] } end @[simp] lemma erase_of_not_mem_support {f : α →₀ M} {a} (haf : a ∉ f.support) : erase a f = f := begin ext b, by_cases hab : b = a, { rwa [hab, erase_same, eq_comm, ←not_mem_support_iff] }, { rw erase_ne hab } end @[simp] lemma erase_zero (a : α) : erase a (0 : α →₀ M) = 0 := by rw [← support_eq_empty, support_erase, support_zero, erase_empty] end erase /-! ### Declarations about `graph` -/ section graph variable [has_zero M] /-- The graph of a finitely supported function over its support, i.e. the finset of input and output pairs with non-zero outputs. -/ def graph (f : α →₀ M) : finset (α × M) := f.support.map ⟨λ a, prod.mk a (f a), λ x y h, (prod.mk.inj h).1⟩ lemma mk_mem_graph_iff {a : α} {m : M} {f : α →₀ M} : (a, m) ∈ f.graph ↔ f a = m ∧ m ≠ 0 := begin simp_rw [graph, mem_map, mem_support_iff], split, { rintro ⟨b, ha, rfl, -⟩, exact ⟨rfl, ha⟩ }, { rintro ⟨rfl, ha⟩, exact ⟨a, ha, rfl⟩ } end @[simp] lemma mem_graph_iff {c : α × M} {f : α →₀ M} : c ∈ f.graph ↔ f c.1 = c.2 ∧ c.2 ≠ 0 := by { cases c, exact mk_mem_graph_iff } lemma mk_mem_graph (f : α →₀ M) {a : α} (ha : a ∈ f.support) : (a, f a) ∈ f.graph := mk_mem_graph_iff.2 ⟨rfl, mem_support_iff.1 ha⟩ lemma apply_eq_of_mem_graph {a : α} {m : M} {f : α →₀ M} (h : (a, m) ∈ f.graph) : f a = m := (mem_graph_iff.1 h).1 @[simp] lemma not_mem_graph_snd_zero (a : α) (f : α →₀ M) : (a, (0 : M)) ∉ f.graph := λ h, (mem_graph_iff.1 h).2.irrefl @[simp] lemma image_fst_graph (f : α →₀ M) : f.graph.image prod.fst = f.support := by simp only [graph, map_eq_image, image_image, embedding.coe_fn_mk, (∘), image_id'] lemma graph_injective (α M) [has_zero M] : injective (@graph α M _) := begin intros f g h, have hsup : f.support = g.support, by rw [← image_fst_graph, h, image_fst_graph], refine ext_iff'.2 ⟨hsup, λ x hx, apply_eq_of_mem_graph $ h.symm ▸ _⟩, exact mk_mem_graph _ (hsup ▸ hx) end @[simp] lemma graph_inj {f g : α →₀ M} : f.graph = g.graph ↔ f = g := (graph_injective α M).eq_iff @[simp] lemma graph_zero : graph (0 : α →₀ M) = ∅ := by simp [graph] @[simp] lemma graph_eq_empty {f : α →₀ M} : f.graph = ∅ ↔ f = 0 := (graph_injective α M).eq_iff' graph_zero /-- Produce an association list for the finsupp over its support using choice. -/ @[simps] def to_alist (f : α →₀ M) : alist (λ x : α, M) := ⟨f.graph.to_list.map prod.to_sigma, begin rw [list.nodupkeys, list.keys, list.map_map, prod.fst_comp_to_sigma, list.nodup_map_iff_inj_on], { rintros ⟨b, m⟩ hb ⟨c, n⟩ hc (rfl : b = c), rw [mem_to_list, finsupp.mem_graph_iff] at hb hc, dsimp at hb hc, rw [←hc.1, hb.1] }, { apply nodup_to_list } end⟩ @[simp] lemma to_alist_keys_to_finset (f : α →₀ M) : f.to_alist.keys.to_finset = f.support := by { ext, simp [to_alist, alist.mem_keys, alist.keys, list.keys] } @[simp] lemma mem_to_alist {f : α →₀ M} {x : α} : x ∈ f.to_alist ↔ f x ≠ 0 := by rw [alist.mem_keys, ←list.mem_to_finset, to_alist_keys_to_finset, mem_support_iff] end graph end finsupp /-! ### Declarations about `alist.lookup_finsupp` -/ section lookup_finsupp variable [has_zero M] namespace alist open list /-- Converts an association list into a finitely supported function via `alist.lookup`, sending absent keys to zero. -/ @[simps] def lookup_finsupp (l : alist (λ x : α, M)) : α →₀ M := { support := (l.1.filter $ λ x, sigma.snd x ≠ 0).keys.to_finset, to_fun := λ a, (l.lookup a).get_or_else 0, mem_support_to_fun := λ a, begin simp_rw [mem_to_finset, list.mem_keys, list.mem_filter, ←mem_lookup_iff], cases lookup a l; simp end } alias lookup_finsupp_to_fun ← lookup_finsupp_apply @[simp] lemma to_alist_lookup_finsupp (f : α →₀ M) : f.to_alist.lookup_finsupp = f := begin ext, by_cases h : f a = 0, { suffices : f.to_alist.lookup a = none, { simp [h, this] }, { simp [lookup_eq_none, h] } }, { suffices : f.to_alist.lookup a = some (f a), { simp [h, this] }, { apply mem_lookup_iff.2, simpa using h } } end lemma lookup_finsupp_surjective : surjective (@lookup_finsupp α M _) := λ f, ⟨_, to_alist_lookup_finsupp f⟩ end alist end lookup_finsupp namespace finsupp /-! ### Declarations about `sum` and `prod` In most of this section, the domain `β` is assumed to be an `add_monoid`. -/ section sum_prod /-- `prod f g` is the product of `g a (f a)` over the support of `f`. -/ @[to_additive "`sum f g` is the sum of `g a (f a)` over the support of `f`. "] def prod [has_zero M] [comm_monoid N] (f : α →₀ M) (g : α → M → N) : N := ∏ a in f.support, g a (f a) variables [has_zero M] [has_zero M'] [comm_monoid N] @[to_additive] lemma prod_of_support_subset (f : α →₀ M) {s : finset α} (hs : f.support ⊆ s) (g : α → M → N) (h : ∀ i ∈ s, g i 0 = 1) : f.prod g = ∏ x in s, g x (f x) := finset.prod_subset hs $ λ x hxs hx, h x hxs ▸ congr_arg (g x) $ not_mem_support_iff.1 hx @[to_additive] lemma prod_fintype [fintype α] (f : α →₀ M) (g : α → M → N) (h : ∀ i, g i 0 = 1) : f.prod g = ∏ i, g i (f i) := f.prod_of_support_subset (subset_univ _) g (λ x _, h x) @[simp, to_additive] lemma prod_single_index {a : α} {b : M} {h : α → M → N} (h_zero : h a 0 = 1) : (single a b).prod h = h a b := calc (single a b).prod h = ∏ x in {a}, h x (single a b x) : prod_of_support_subset _ support_single_subset h $ λ x hx, (mem_singleton.1 hx).symm ▸ h_zero ... = h a b : by simp @[to_additive] lemma prod_map_range_index {f : M → M'} {hf : f 0 = 0} {g : α →₀ M} {h : α → M' → N} (h0 : ∀a, h a 0 = 1) : (map_range f hf g).prod h = g.prod (λa b, h a (f b)) := finset.prod_subset support_map_range $ λ _ _ H, by rw [not_mem_support_iff.1 H, h0] @[simp, to_additive] lemma prod_zero_index {h : α → M → N} : (0 : α →₀ M).prod h = 1 := rfl @[to_additive] lemma prod_comm (f : α →₀ M) (g : β →₀ M') (h : α → M → β → M' → N) : f.prod (λ x v, g.prod (λ x' v', h x v x' v')) = g.prod (λ x' v', f.prod (λ x v, h x v x' v')) := finset.prod_comm @[simp, to_additive] lemma prod_ite_eq [decidable_eq α] (f : α →₀ M) (a : α) (b : α → M → N) : f.prod (λ x v, ite (a = x) (b x v) 1) = ite (a ∈ f.support) (b a (f a)) 1 := by { dsimp [finsupp.prod], rw f.support.prod_ite_eq, } @[simp] lemma sum_ite_self_eq [decidable_eq α] {N : Type*} [add_comm_monoid N] (f : α →₀ N) (a : α) : f.sum (λ x v, ite (a = x) v 0) = f a := by { convert f.sum_ite_eq a (λ x, id), simp [ite_eq_right_iff.2 eq.symm] } /-- A restatement of `prod_ite_eq` with the equality test reversed. -/ @[simp, to_additive "A restatement of `sum_ite_eq` with the equality test reversed."] lemma prod_ite_eq' [decidable_eq α] (f : α →₀ M) (a : α) (b : α → M → N) : f.prod (λ x v, ite (x = a) (b x v) 1) = ite (a ∈ f.support) (b a (f a)) 1 := by { dsimp [finsupp.prod], rw f.support.prod_ite_eq', } @[simp] lemma sum_ite_self_eq' [decidable_eq α] {N : Type*} [add_comm_monoid N] (f : α →₀ N) (a : α) : f.sum (λ x v, ite (x = a) v 0) = f a := by { convert f.sum_ite_eq' a (λ x, id), simp [ite_eq_right_iff.2 eq.symm] } @[simp] lemma prod_pow [fintype α] (f : α →₀ ℕ) (g : α → N) : f.prod (λ a b, g a ^ b) = ∏ a, g a ^ (f a) := f.prod_fintype _ $ λ a, pow_zero _ /-- If `g` maps a second argument of 0 to 1, then multiplying it over the result of `on_finset` is the same as multiplying it over the original `finset`. -/ @[to_additive "If `g` maps a second argument of 0 to 0, summing it over the result of `on_finset` is the same as summing it over the original `finset`."] lemma on_finset_prod {s : finset α} {f : α → M} {g : α → M → N} (hf : ∀a, f a ≠ 0 → a ∈ s) (hg : ∀ a, g a 0 = 1) : (on_finset s f hf).prod g = ∏ a in s, g a (f a) := finset.prod_subset support_on_finset_subset $ by simp [*] { contextual := tt } /-- Taking a product over `f : α →₀ M` is the same as multiplying the value on a single element `y ∈ f.support` by the product over `erase y f`. -/ @[to_additive /-" Taking a sum over over `f : α →₀ M` is the same as adding the value on a single element `y ∈ f.support` to the sum over `erase y f`. "-/] lemma mul_prod_erase (f : α →₀ M) (y : α) (g : α → M → N) (hyf : y ∈ f.support) : g y (f y) * (erase y f).prod g = f.prod g := begin rw [finsupp.prod, finsupp.prod, ←finset.mul_prod_erase _ _ hyf, finsupp.support_erase, finset.prod_congr rfl], intros h hx, rw finsupp.erase_ne (ne_of_mem_erase hx), end /-- Generalization of `finsupp.mul_prod_erase`: if `g` maps a second argument of 0 to 1, then its product over `f : α →₀ M` is the same as multiplying the value on any element `y : α` by the product over `erase y f`. -/ @[to_additive /-" Generalization of `finsupp.add_sum_erase`: if `g` maps a second argument of 0 to 0, then its sum over `f : α →₀ M` is the same as adding the value on any element `y : α` to the sum over `erase y f`. "-/] lemma mul_prod_erase' (f : α →₀ M) (y : α) (g : α → M → N) (hg : ∀ (i : α), g i 0 = 1) : g y (f y) * (erase y f).prod g = f.prod g := begin classical, by_cases hyf : y ∈ f.support, { exact finsupp.mul_prod_erase f y g hyf }, { rw [not_mem_support_iff.mp hyf, hg y, erase_of_not_mem_support hyf, one_mul] }, end @[to_additive] lemma _root_.submonoid_class.finsupp_prod_mem {S : Type*} [set_like S N] [submonoid_class S N] (s : S) (f : α →₀ M) (g : α → M → N) (h : ∀ c, f c ≠ 0 → g c (f c) ∈ s) : f.prod g ∈ s := prod_mem $ λ i hi, h _ (finsupp.mem_support_iff.mp hi) @[to_additive] lemma prod_congr {f : α →₀ M} {g1 g2 : α → M → N} (h : ∀ x ∈ f.support, g1 x (f x) = g2 x (f x)) : f.prod g1 = f.prod g2 := finset.prod_congr rfl h end sum_prod /-! ### Additive monoid structure on `α →₀ M` -/ section add_zero_class variables [add_zero_class M] instance : has_add (α →₀ M) := ⟨zip_with (+) (add_zero 0)⟩ @[simp] lemma coe_add (f g : α →₀ M) : ⇑(f + g) = f + g := rfl lemma add_apply (g₁ g₂ : α →₀ M) (a : α) : (g₁ + g₂) a = g₁ a + g₂ a := rfl lemma support_add [decidable_eq α] {g₁ g₂ : α →₀ M} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support := support_zip_with lemma support_add_eq [decidable_eq α] {g₁ g₂ : α →₀ M} (h : disjoint g₁.support g₂.support) : (g₁ + g₂).support = g₁.support ∪ g₂.support := le_antisymm support_zip_with $ assume a ha, (finset.mem_union.1 ha).elim (assume ha, have a ∉ g₂.support, from disjoint_left.1 h ha, by simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, add_zero]) (assume ha, have a ∉ g₁.support, from disjoint_right.1 h ha, by simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, zero_add]) @[simp] lemma single_add (a : α) (b₁ b₂ : M) : single a (b₁ + b₂) = single a b₁ + single a b₂ := ext $ assume a', begin by_cases h : a = a', { rw [h, add_apply, single_eq_same, single_eq_same, single_eq_same] }, { rw [add_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, zero_add] } end instance : add_zero_class (α →₀ M) := fun_like.coe_injective.add_zero_class _ coe_zero coe_add /-- `finsupp.single` as an `add_monoid_hom`. See `finsupp.lsingle` for the stronger version as a linear map. -/ @[simps] def single_add_hom (a : α) : M →+ α →₀ M := ⟨single a, single_zero a, single_add a⟩ /-- Evaluation of a function `f : α →₀ M` at a point as an additive monoid homomorphism. See `finsupp.lapply` for the stronger version as a linear map. -/ @[simps apply] def apply_add_hom (a : α) : (α →₀ M) →+ M := ⟨λ g, g a, zero_apply, λ _ _, add_apply _ _ _⟩ /-- Coercion from a `finsupp` to a function type is an `add_monoid_hom`. -/ @[simps] noncomputable def coe_fn_add_hom : (α →₀ M) →+ (α → M) := { to_fun := coe_fn, map_zero' := coe_zero, map_add' := coe_add } lemma update_eq_single_add_erase (f : α →₀ M) (a : α) (b : M) : f.update a b = single a b + f.erase a := begin ext j, rcases eq_or_ne a j with rfl|h, { simp }, { simp [function.update_noteq h.symm, single_apply, h, erase_ne, h.symm] } end lemma update_eq_erase_add_single (f : α →₀ M) (a : α) (b : M) : f.update a b = f.erase a + single a b := begin ext j, rcases eq_or_ne a j with rfl|h, { simp }, { simp [function.update_noteq h.symm, single_apply, h, erase_ne, h.symm] } end lemma single_add_erase (a : α) (f : α →₀ M) : single a (f a) + f.erase a = f := by rw [←update_eq_single_add_erase, update_self] lemma erase_add_single (a : α) (f : α →₀ M) : f.erase a + single a (f a) = f := by rw [←update_eq_erase_add_single, update_self] @[simp] lemma erase_add (a : α) (f f' : α →₀ M) : erase a (f + f') = erase a f + erase a f' := begin ext s, by_cases hs : s = a, { rw [hs, add_apply, erase_same, erase_same, erase_same, add_zero] }, rw [add_apply, erase_ne hs, erase_ne hs, erase_ne hs, add_apply], end /-- `finsupp.erase` as an `add_monoid_hom`. -/ @[simps] def erase_add_hom (a : α) : (α →₀ M) →+ (α →₀ M) := { to_fun := erase a, map_zero' := erase_zero a, map_add' := erase_add a } @[elab_as_eliminator] protected theorem induction {p : (α →₀ M) → Prop} (f : α →₀ M) (h0 : p 0) (ha : ∀a b (f : α →₀ M), a ∉ f.support → b ≠ 0 → p f → p (single a b + f)) : p f := suffices ∀s (f : α →₀ M), f.support = s → p f, from this _ _ rfl, assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $ assume a s has ih f hf, suffices p (single a (f a) + f.erase a), by rwa [single_add_erase] at this, begin apply ha, { rw [support_erase, mem_erase], exact λ H, H.1 rfl }, { rw [← mem_support_iff, hf], exact mem_insert_self _ _ }, { apply ih _ _, rw [support_erase, hf, finset.erase_insert has] } end lemma induction₂ {p : (α →₀ M) → Prop} (f : α →₀ M) (h0 : p 0) (ha : ∀a b (f : α →₀ M), a ∉ f.support → b ≠ 0 → p f → p (f + single a b)) : p f := suffices ∀s (f : α →₀ M), f.support = s → p f, from this _ _ rfl, assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $ assume a s has ih f hf, suffices p (f.erase a + single a (f a)), by rwa [erase_add_single] at this, begin apply ha, { rw [support_erase, mem_erase], exact λ H, H.1 rfl }, { rw [← mem_support_iff, hf], exact mem_insert_self _ _ }, { apply ih _ _, rw [support_erase, hf, finset.erase_insert has] } end lemma induction_linear {p : (α →₀ M) → Prop} (f : α →₀ M) (h0 : p 0) (hadd : ∀ f g : α →₀ M, p f → p g → p (f + g)) (hsingle : ∀ a b, p (single a b)) : p f := induction₂ f h0 (λ a b f _ _ w, hadd _ _ w (hsingle _ _)) @[simp] lemma add_closure_set_of_eq_single : add_submonoid.closure {f : α →₀ M | ∃ a b, f = single a b} = ⊤ := top_unique $ λ x hx, finsupp.induction x (add_submonoid.zero_mem _) $ λ a b f ha hb hf, add_submonoid.add_mem _ (add_submonoid.subset_closure $ ⟨a, b, rfl⟩) hf /-- If two additive homomorphisms from `α →₀ M` are equal on each `single a b`, then they are equal. -/ lemma add_hom_ext [add_zero_class N] ⦃f g : (α →₀ M) →+ N⦄ (H : ∀ x y, f (single x y) = g (single x y)) : f = g := begin refine add_monoid_hom.eq_of_eq_on_mdense add_closure_set_of_eq_single _, rintro _ ⟨x, y, rfl⟩, apply H end /-- If two additive homomorphisms from `α →₀ M` are equal on each `single a b`, then they are equal. We formulate this using equality of `add_monoid_hom`s so that `ext` tactic can apply a type-specific extensionality lemma after this one. E.g., if the fiber `M` is `ℕ` or `ℤ`, then it suffices to verify `f (single a 1) = g (single a 1)`. -/ @[ext] lemma add_hom_ext' [add_zero_class N] ⦃f g : (α →₀ M) →+ N⦄ (H : ∀ x, f.comp (single_add_hom x) = g.comp (single_add_hom x)) : f = g := add_hom_ext $ λ x, add_monoid_hom.congr_fun (H x) lemma mul_hom_ext [mul_one_class N] ⦃f g : multiplicative (α →₀ M) →* N⦄ (H : ∀ x y, f (multiplicative.of_add $ single x y) = g (multiplicative.of_add $ single x y)) : f = g := monoid_hom.ext $ add_monoid_hom.congr_fun $ @add_hom_ext α M (additive N) _ _ f.to_additive'' g.to_additive'' H @[ext] lemma mul_hom_ext' [mul_one_class N] {f g : multiplicative (α →₀ M) →* N} (H : ∀ x, f.comp (single_add_hom x).to_multiplicative = g.comp (single_add_hom x).to_multiplicative) : f = g := mul_hom_ext $ λ x, monoid_hom.congr_fun (H x) lemma map_range_add [add_zero_class N] {f : M → N} {hf : f 0 = 0} (hf' : ∀ x y, f (x + y) = f x + f y) (v₁ v₂ : α →₀ M) : map_range f hf (v₁ + v₂) = map_range f hf v₁ + map_range f hf v₂ := ext $ λ a, by simp only [hf', add_apply, map_range_apply] /-- Bundle `emb_domain f` as an additive map from `α →₀ M` to `β →₀ M`. -/ @[simps] def emb_domain.add_monoid_hom (f : α ↪ β) : (α →₀ M) →+ β →₀ M := { to_fun := λ v, emb_domain f v, map_zero' := by simp, map_add' := λ v w, begin ext b, by_cases h : b ∈ set.range f, { rcases h with ⟨a, rfl⟩, simp, }, { simp [emb_domain_notin_range, h], }, end, } @[simp] lemma emb_domain_add (f : α ↪ β) (v w : α →₀ M) : emb_domain f (v + w) = emb_domain f v + emb_domain f w := (emb_domain.add_monoid_hom f).map_add v w end add_zero_class section add_monoid variables [add_monoid M] /-- Note the general `finsupp.has_smul` instance doesn't apply as `ℕ` is not distributive unless `β i`'s addition is commutative. -/ instance has_nat_scalar : has_smul ℕ (α →₀ M) := ⟨λ n v, v.map_range ((•) n) (nsmul_zero _)⟩ instance : add_monoid (α →₀ M) := fun_like.coe_injective.add_monoid _ coe_zero coe_add (λ _ _, rfl) end add_monoid end finsupp @[to_additive] lemma map_finsupp_prod [has_zero M] [comm_monoid N] [comm_monoid P] {H : Type*} [monoid_hom_class H N P] (h : H) (f : α →₀ M) (g : α → M → N) : h (f.prod g) = f.prod (λ a b, h (g a b)) := map_prod h _ _ /-- Deprecated, use `_root_.map_finsupp_prod` instead. -/ @[to_additive "Deprecated, use `_root_.map_finsupp_sum` instead."] protected lemma mul_equiv.map_finsupp_prod [has_zero M] [comm_monoid N] [comm_monoid P] (h : N ≃* P) (f : α →₀ M) (g : α → M → N) : h (f.prod g) = f.prod (λ a b, h (g a b)) := map_finsupp_prod h f g /-- Deprecated, use `_root_.map_finsupp_prod` instead. -/ @[to_additive "Deprecated, use `_root_.map_finsupp_sum` instead."] protected lemma monoid_hom.map_finsupp_prod [has_zero M] [comm_monoid N] [comm_monoid P] (h : N →* P) (f : α →₀ M) (g : α → M → N) : h (f.prod g) = f.prod (λ a b, h (g a b)) := map_finsupp_prod h f g /-- Deprecated, use `_root_.map_finsupp_sum` instead. -/ protected lemma ring_hom.map_finsupp_sum [has_zero M] [semiring R] [semiring S] (h : R →+* S) (f : α →₀ M) (g : α → M → R) : h (f.sum g) = f.sum (λ a b, h (g a b)) := map_finsupp_sum h f g /-- Deprecated, use `_root_.map_finsupp_prod` instead. -/ protected lemma ring_hom.map_finsupp_prod [has_zero M] [comm_semiring R] [comm_semiring S] (h : R →+* S) (f : α →₀ M) (g : α → M → R) : h (f.prod g) = f.prod (λ a b, h (g a b)) := map_finsupp_prod h f g @[to_additive] lemma monoid_hom.coe_finsupp_prod [has_zero β] [monoid N] [comm_monoid P] (f : α →₀ β) (g : α → β → N →* P) : ⇑(f.prod g) = f.prod (λ i fi, g i fi) := monoid_hom.coe_finset_prod _ _ @[simp, to_additive] lemma monoid_hom.finsupp_prod_apply [has_zero β] [monoid N] [comm_monoid P] (f : α →₀ β) (g : α → β → N →* P) (x : N) : f.prod g x = f.prod (λ i fi, g i fi x) := monoid_hom.finset_prod_apply _ _ _ namespace finsupp instance [add_comm_monoid M] : add_comm_monoid (α →₀ M) := fun_like.coe_injective.add_comm_monoid _ coe_zero coe_add (λ _ _, rfl) instance [add_group G] : has_neg (α →₀ G) := ⟨map_range (has_neg.neg) neg_zero⟩ @[simp] lemma coe_neg [add_group G] (g : α →₀ G) : ⇑(-g) = -g := rfl lemma neg_apply [add_group G] (g : α →₀ G) (a : α) : (- g) a = - g a := rfl instance [add_group G] : has_sub (α →₀ G) := ⟨zip_with has_sub.sub (sub_zero _)⟩ @[simp] lemma coe_sub [add_group G] (g₁ g₂ : α →₀ G) : ⇑(g₁ - g₂) = g₁ - g₂ := rfl lemma sub_apply [add_group G] (g₁ g₂ : α →₀ G) (a : α) : (g₁ - g₂) a = g₁ a - g₂ a := rfl /-- Note the general `finsupp.has_smul` instance doesn't apply as `ℤ` is not distributive unless `β i`'s addition is commutative. -/ instance has_int_scalar [add_group G] : has_smul ℤ (α →₀ G) := ⟨λ n v, v.map_range ((•) n) (zsmul_zero _)⟩ instance [add_group G] : add_group (α →₀ G) := fun_like.coe_injective.add_group _ coe_zero coe_add coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) instance [add_comm_group G] : add_comm_group (α →₀ G) := fun_like.coe_injective.add_comm_group _ coe_zero coe_add coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) lemma single_add_single_eq_single_add_single [add_comm_monoid M] {k l m n : α} {u v : M} (hu : u ≠ 0) (hv : v ≠ 0) : single k u + single l v = single m u + single n v ↔ (k = m ∧ l = n) ∨ (u = v ∧ k = n ∧ l = m) ∨ (u + v = 0 ∧ k = l ∧ m = n) := begin simp_rw [fun_like.ext_iff, coe_add, single_eq_pi_single, ←funext_iff], exact pi.single_add_single_eq_single_add_single hu hv, end lemma single_multiset_sum [add_comm_monoid M] (s : multiset M) (a : α) : single a s.sum = (s.map (single a)).sum := multiset.induction_on s (single_zero _) $ λ a s ih, by rw [multiset.sum_cons, single_add, ih, multiset.map_cons, multiset.sum_cons] lemma single_finset_sum [add_comm_monoid M] (s : finset ι) (f : ι → M) (a : α) : single a (∑ b in s, f b) = ∑ b in s, single a (f b) := begin transitivity, apply single_multiset_sum, rw [multiset.map_map], refl end lemma single_sum [has_zero M] [add_comm_monoid N] (s : ι →₀ M) (f : ι → M → N) (a : α) : single a (s.sum f) = s.sum (λd c, single a (f d c)) := single_finset_sum _ _ _ @[to_additive] lemma prod_neg_index [add_group G] [comm_monoid M] {g : α →₀ G} {h : α → G → M} (h0 : ∀a, h a 0 = 1) : (-g).prod h = g.prod (λa b, h a (- b)) := prod_map_range_index h0 @[simp] lemma support_neg [add_group G] (f : α →₀ G) : support (-f) = support f := finset.subset.antisymm support_map_range (calc support f = support (- (- f)) : congr_arg support (neg_neg _).symm ... ⊆ support (- f) : support_map_range) lemma support_sub [decidable_eq α] [add_group G] {f g : α →₀ G} : support (f - g) ⊆ support f ∪ support g := begin rw [sub_eq_add_neg, ←support_neg g], exact support_add, end lemma erase_eq_sub_single [add_group G] (f : α →₀ G) (a : α) : f.erase a = f - single a (f a) := begin ext a', rcases eq_or_ne a a' with rfl|h, { simp }, { simp [erase_ne h.symm, single_eq_of_ne h] } end lemma update_eq_sub_add_single [add_group G] (f : α →₀ G) (a : α) (b : G) : f.update a b = f - single a (f a) + single a b := by rw [update_eq_erase_add_single, erase_eq_sub_single] lemma finset_sum_apply [add_comm_monoid N] (S : finset ι) (f : ι → α →₀ N) (a : α) : (∑ i in S, f i) a = ∑ i in S, f i a := (apply_add_hom a : (α →₀ N) →+ _).map_sum _ _ @[simp] lemma sum_apply [has_zero M] [add_comm_monoid N] {f : α →₀ M} {g : α → M → β →₀ N} {a₂ : β} : (f.sum g) a₂ = f.sum (λa₁ b, g a₁ b a₂) := finset_sum_apply _ _ _ lemma coe_finset_sum [add_comm_monoid N] (S : finset ι) (f : ι → α →₀ N) : ⇑(∑ i in S, f i) = ∑ i in S, f i := (coe_fn_add_hom : (α →₀ N) →+ _).map_sum _ _ lemma coe_sum [has_zero M] [add_comm_monoid N] (f : α →₀ M) (g : α → M → β →₀ N) : ⇑(f.sum g) = f.sum (λ a₁ b, g a₁ b) := coe_finset_sum _ _ lemma support_sum [decidable_eq β] [has_zero M] [add_comm_monoid N] {f : α →₀ M} {g : α → M → (β →₀ N)} : (f.sum g).support ⊆ f.support.bUnion (λa, (g a (f a)).support) := have ∀ c, f.sum (λ a b, g a b c) ≠ 0 → (∃ a, f a ≠ 0 ∧ ¬ (g a (f a)) c = 0), from assume a₁ h, let ⟨a, ha, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in ⟨a, mem_support_iff.mp ha, ne⟩, by simpa only [finset.subset_iff, mem_support_iff, finset.mem_bUnion, sum_apply, exists_prop] lemma support_finset_sum [decidable_eq β] [add_comm_monoid M] {s : finset α} {f : α → (β →₀ M)} : (finset.sum s f).support ⊆ s.bUnion (λ x, (f x).support) := begin rw ←finset.sup_eq_bUnion, induction s using finset.cons_induction_on with a s ha ih, { refl }, { rw [finset.sum_cons, finset.sup_cons], exact support_add.trans (finset.union_subset_union (finset.subset.refl _) ih), }, end @[simp] lemma sum_zero [has_zero M] [add_comm_monoid N] {f : α →₀ M} : f.sum (λa b, (0 : N)) = 0 := finset.sum_const_zero @[simp, to_additive] lemma prod_mul [has_zero M] [comm_monoid N] {f : α →₀ M} {h₁ h₂ : α → M → N} : f.prod (λa b, h₁ a b * h₂ a b) = f.prod h₁ * f.prod h₂ := finset.prod_mul_distrib @[simp, to_additive] lemma prod_inv [has_zero M] [comm_group G] {f : α →₀ M} {h : α → M → G} : f.prod (λa b, (h a b)⁻¹) = (f.prod h)⁻¹ := (map_prod ((monoid_hom.id G)⁻¹) _ _).symm @[simp] lemma sum_sub [has_zero M] [add_comm_group G] {f : α →₀ M} {h₁ h₂ : α → M → G} : f.sum (λa b, h₁ a b - h₂ a b) = f.sum h₁ - f.sum h₂ := finset.sum_sub_distrib /-- Taking the product under `h` is an additive-to-multiplicative homomorphism of finsupps, if `h` is an additive-to-multiplicative homomorphism on the support. This is a more general version of `finsupp.prod_add_index'`; the latter has simpler hypotheses. -/ @[to_additive "Taking the product under `h` is an additive homomorphism of finsupps, if `h` is an additive homomorphism on the support. This is a more general version of `finsupp.sum_add_index'`; the latter has simpler hypotheses."] lemma prod_add_index [add_zero_class M] [comm_monoid N] {f g : α →₀ M} {h : α → M → N} (h_zero : ∀ a ∈ f.support ∪ g.support, h a 0 = 1) (h_add : ∀ (a ∈ f.support ∪ g.support) b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f + g).prod h = f.prod h * g.prod h := begin rw [finsupp.prod_of_support_subset f (subset_union_left _ g.support) h h_zero, finsupp.prod_of_support_subset g (subset_union_right f.support _) h h_zero, ←finset.prod_mul_distrib, finsupp.prod_of_support_subset (f + g) finsupp.support_add h h_zero], exact finset.prod_congr rfl (λ x hx, (by apply h_add x hx)), end /-- Taking the product under `h` is an additive-to-multiplicative homomorphism of finsupps, if `h` is an additive-to-multiplicative homomorphism. This is a more specialized version of `finsupp.prod_add_index` with simpler hypotheses. -/ @[to_additive "Taking the sum under `h` is an additive homomorphism of finsupps, if `h` is an additive homomorphism. This is a more specific version of `finsupp.sum_add_index` with simpler hypotheses."] lemma prod_add_index' [add_zero_class M] [comm_monoid N] {f g : α →₀ M} {h : α → M → N} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f + g).prod h = f.prod h * g.prod h := prod_add_index (λ a ha, h_zero a) (λ a ha, h_add a) @[simp] lemma sum_hom_add_index [add_zero_class M] [add_comm_monoid N] {f g : α →₀ M} (h : α → M →+ N) : (f + g).sum (λ x, h x) = f.sum (λ x, h x) + g.sum (λ x, h x) := sum_add_index' (λ a, (h a).map_zero) (λ a, (h a).map_add) @[simp] lemma prod_hom_add_index [add_zero_class M] [comm_monoid N] {f g : α →₀ M} (h : α → multiplicative M →* N) : (f + g).prod (λ a b, h a (multiplicative.of_add b)) = f.prod (λ a b, h a (multiplicative.of_add b)) * g.prod (λ a b, h a (multiplicative.of_add b)) := prod_add_index' (λ a, (h a).map_one) (λ a, (h a).map_mul) /-- The canonical isomorphism between families of additive monoid homomorphisms `α → (M →+ N)` and monoid homomorphisms `(α →₀ M) →+ N`. -/ def lift_add_hom [add_zero_class M] [add_comm_monoid N] : (α → M →+ N) ≃+ ((α →₀ M) →+ N) := { to_fun := λ F, { to_fun := λ f, f.sum (λ x, F x), map_zero' := finset.sum_empty, map_add' := λ _ _, sum_add_index' (λ x, (F x).map_zero) (λ x, (F x).map_add) }, inv_fun := λ F x, F.comp $ single_add_hom x, left_inv := λ F, by { ext, simp }, right_inv := λ F, by { ext, simp }, map_add' := λ F G, by { ext, simp } } @[simp] lemma lift_add_hom_apply [add_comm_monoid M] [add_comm_monoid N] (F : α → M →+ N) (f : α →₀ M) : lift_add_hom F f = f.sum (λ x, F x) := rfl @[simp] lemma lift_add_hom_symm_apply [add_comm_monoid M] [add_comm_monoid N] (F : (α →₀ M) →+ N) (x : α) : lift_add_hom.symm F x = F.comp (single_add_hom x) := rfl lemma lift_add_hom_symm_apply_apply [add_comm_monoid M] [add_comm_monoid N] (F : (α →₀ M) →+ N) (x : α) (y : M) : lift_add_hom.symm F x y = F (single x y) := rfl @[simp] lemma lift_add_hom_single_add_hom [add_comm_monoid M] : lift_add_hom (single_add_hom : α → M →+ α →₀ M) = add_monoid_hom.id _ := lift_add_hom.to_equiv.apply_eq_iff_eq_symm_apply.2 rfl @[simp] lemma sum_single [add_comm_monoid M] (f : α →₀ M) : f.sum single = f := add_monoid_hom.congr_fun lift_add_hom_single_add_hom f @[simp] lemma sum_univ_single [add_comm_monoid M] [fintype α] (i : α) (m : M) : ∑ (j : α), (single i m) j = m := by simp [single] @[simp] lemma sum_univ_single' [add_comm_monoid M] [fintype α] (i : α) (m : M) : ∑ (j : α), (single j m) i = m := by simp [single] @[simp] lemma lift_add_hom_apply_single [add_comm_monoid M] [add_comm_monoid N] (f : α → M →+ N) (a : α) (b : M) : lift_add_hom f (single a b) = f a b := sum_single_index (f a).map_zero @[simp] lemma lift_add_hom_comp_single [add_comm_monoid M] [add_comm_monoid N] (f : α → M →+ N) (a : α) : (lift_add_hom f).comp (single_add_hom a) = f a := add_monoid_hom.ext $ λ b, lift_add_hom_apply_single f a b lemma comp_lift_add_hom [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] (g : N →+ P) (f : α → M →+ N) : g.comp (lift_add_hom f) = lift_add_hom (λ a, g.comp (f a)) := lift_add_hom.symm_apply_eq.1 $ funext $ λ a, by rw [lift_add_hom_symm_apply, add_monoid_hom.comp_assoc, lift_add_hom_comp_single] lemma sum_sub_index [add_comm_group β] [add_comm_group γ] {f g : α →₀ β} {h : α → β → γ} (h_sub : ∀a b₁ b₂, h a (b₁ - b₂) = h a b₁ - h a b₂) : (f - g).sum h = f.sum h - g.sum h := (lift_add_hom (λ a, add_monoid_hom.of_map_sub (h a) (h_sub a))).map_sub f g @[to_additive] lemma prod_emb_domain [has_zero M] [comm_monoid N] {v : α →₀ M} {f : α ↪ β} {g : β → M → N} : (v.emb_domain f).prod g = v.prod (λ a b, g (f a) b) := begin rw [prod, prod, support_emb_domain, finset.prod_map], simp_rw emb_domain_apply, end @[to_additive] lemma prod_finset_sum_index [add_comm_monoid M] [comm_monoid N] {s : finset ι} {g : ι → α →₀ M} {h : α → M → N} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : ∏ i in s, (g i).prod h = (∑ i in s, g i).prod h := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, sum_insert has, prod_add_index' h_zero h_add] @[to_additive] lemma prod_sum_index [add_comm_monoid M] [add_comm_monoid N] [comm_monoid P] {f : α →₀ M} {g : α → M → β →₀ N} {h : β → N → P} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f.sum g).prod h = f.prod (λa b, (g a b).prod h) := (prod_finset_sum_index h_zero h_add).symm lemma multiset_sum_sum_index [add_comm_monoid M] [add_comm_monoid N] (f : multiset (α →₀ M)) (h : α → M → N) (h₀ : ∀a, h a 0 = 0) (h₁ : ∀ (a : α) (b₁ b₂ : M), h a (b₁ + b₂) = h a b₁ + h a b₂) : (f.sum.sum h) = (f.map $ λg:α →₀ M, g.sum h).sum := multiset.induction_on f rfl $ assume a s ih, by rw [multiset.sum_cons, multiset.map_cons, multiset.sum_cons, sum_add_index' h₀ h₁, ih] lemma support_sum_eq_bUnion {α : Type*} {ι : Type*} {M : Type*} [add_comm_monoid M] {g : ι → α →₀ M} (s : finset ι) (h : ∀ i₁ i₂, i₁ ≠ i₂ → disjoint (g i₁).support (g i₂).support) : (∑ i in s, g i).support = s.bUnion (λ i, (g i).support) := begin apply finset.induction_on s, { simp }, { intros i s hi, simp only [hi, sum_insert, not_false_iff, bUnion_insert], intro hs, rw [finsupp.support_add_eq, hs], rw [hs], intros x hx, simp only [mem_bUnion, exists_prop, inf_eq_inter, ne.def, mem_inter] at hx, obtain ⟨hxi, j, hj, hxj⟩ := hx, have hn : i ≠ j := λ H, hi (H.symm ▸ hj), apply h _ _ hn, simp [hxi, hxj] } end lemma multiset_map_sum [has_zero M] {f : α →₀ M} {m : β → γ} {h : α → M → multiset β} : multiset.map m (f.sum h) = f.sum (λa b, (h a b).map m) := (multiset.map_add_monoid_hom m).map_sum _ f.support lemma multiset_sum_sum [has_zero M] [add_comm_monoid N] {f : α →₀ M} {h : α → M → multiset N} : multiset.sum (f.sum h) = f.sum (λa b, multiset.sum (h a b)) := (multiset.sum_add_monoid_hom : multiset N →+ N).map_sum _ f.support /-- For disjoint `f1` and `f2`, and function `g`, the product of the products of `g` over `f1` and `f2` equals the product of `g` over `f1 + f2` -/ @[to_additive "For disjoint `f1` and `f2`, and function `g`, the sum of the sums of `g` over `f1` and `f2` equals the sum of `g` over `f1 + f2`"] lemma prod_add_index_of_disjoint [add_comm_monoid M] {f1 f2 : α →₀ M} (hd : disjoint f1.support f2.support) {β : Type*} [comm_monoid β] (g : α → M → β) : (f1 + f2).prod g = f1.prod g * f2.prod g := have ∀ {f1 f2 : α →₀ M}, disjoint f1.support f2.support → ∏ x in f1.support, g x (f1 x + f2 x) = f1.prod g := λ f1 f2 hd, finset.prod_congr rfl (λ x hx, by simp only [not_mem_support_iff.mp (disjoint_left.mp hd hx), add_zero]), by simp_rw [← this hd, ← this hd.symm, add_comm (f2 _), finsupp.prod, support_add_eq hd, prod_union hd, add_apply] lemma prod_dvd_prod_of_subset_of_dvd [add_comm_monoid M] [comm_monoid N] {f1 f2 : α →₀ M} {g1 g2 : α → M → N} (h1 : f1.support ⊆ f2.support) (h2 : ∀ (a : α), a ∈ f1.support → g1 a (f1 a) ∣ g2 a (f2 a)) : f1.prod g1 ∣ f2.prod g2 := begin simp only [finsupp.prod, finsupp.prod_mul], rw [←sdiff_union_of_subset h1, prod_union sdiff_disjoint], apply dvd_mul_of_dvd_right, apply prod_dvd_prod_of_dvd, exact h2, end section map_range section equiv variables [has_zero M] [has_zero N] [has_zero P] /-- `finsupp.map_range` as an equiv. -/ @[simps apply] def map_range.equiv (f : M ≃ N) (hf : f 0 = 0) (hf' : f.symm 0 = 0) : (α →₀ M) ≃ (α →₀ N) := { to_fun := (map_range f hf : (α →₀ M) → (α →₀ N)), inv_fun := (map_range f.symm hf' : (α →₀ N) → (α →₀ M)), left_inv := λ x, begin rw ←map_range_comp _ _ _ _; simp_rw equiv.symm_comp_self, { exact map_range_id _ }, { refl }, end, right_inv := λ x, begin rw ←map_range_comp _ _ _ _; simp_rw equiv.self_comp_symm, { exact map_range_id _ }, { refl }, end } @[simp] lemma map_range.equiv_refl : map_range.equiv (equiv.refl M) rfl rfl = equiv.refl (α →₀ M) := equiv.ext map_range_id lemma map_range.equiv_trans (f : M ≃ N) (hf : f 0 = 0) (hf') (f₂ : N ≃ P) (hf₂ : f₂ 0 = 0) (hf₂') : (map_range.equiv (f.trans f₂) (by rw [equiv.trans_apply, hf, hf₂]) (by rw [equiv.symm_trans_apply, hf₂', hf']) : (α →₀ _) ≃ _) = (map_range.equiv f hf hf').trans (map_range.equiv f₂ hf₂ hf₂') := equiv.ext $ map_range_comp _ _ _ _ _ @[simp] lemma map_range.equiv_symm (f : M ≃ N) (hf hf') : ((map_range.equiv f hf hf').symm : (α →₀ _) ≃ _) = map_range.equiv f.symm hf' hf := equiv.ext $ λ x, rfl end equiv section zero_hom variables [has_zero M] [has_zero N] [has_zero P] /-- Composition with a fixed zero-preserving homomorphism is itself an zero-preserving homomorphism on functions. -/ @[simps] def map_range.zero_hom (f : zero_hom M N) : zero_hom (α →₀ M) (α →₀ N) := { to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)), map_zero' := map_range_zero } @[simp] lemma map_range.zero_hom_id : map_range.zero_hom (zero_hom.id M) = zero_hom.id (α →₀ M) := zero_hom.ext map_range_id lemma map_range.zero_hom_comp (f : zero_hom N P) (f₂ : zero_hom M N) : (map_range.zero_hom (f.comp f₂) : zero_hom (α →₀ _) _) = (map_range.zero_hom f).comp (map_range.zero_hom f₂) := zero_hom.ext $ map_range_comp _ _ _ _ _ end zero_hom section add_monoid_hom variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] /-- Composition with a fixed additive homomorphism is itself an additive homomorphism on functions. -/ @[simps] def map_range.add_monoid_hom (f : M →+ N) : (α →₀ M) →+ (α →₀ N) := { to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)), map_zero' := map_range_zero, map_add' := λ a b, map_range_add f.map_add _ _ } @[simp] lemma map_range.add_monoid_hom_id : map_range.add_monoid_hom (add_monoid_hom.id M) = add_monoid_hom.id (α →₀ M) := add_monoid_hom.ext map_range_id lemma map_range.add_monoid_hom_comp (f : N →+ P) (f₂ : M →+ N) : (map_range.add_monoid_hom (f.comp f₂) : (α →₀ _) →+ _) = (map_range.add_monoid_hom f).comp (map_range.add_monoid_hom f₂) := add_monoid_hom.ext $ map_range_comp _ _ _ _ _ @[simp] lemma map_range.add_monoid_hom_to_zero_hom (f : M →+ N) : (map_range.add_monoid_hom f).to_zero_hom = (map_range.zero_hom f.to_zero_hom : zero_hom (α →₀ _) _) := zero_hom.ext $ λ _, rfl lemma map_range_multiset_sum (f : M →+ N) (m : multiset (α →₀ M)) : map_range f f.map_zero m.sum = (m.map $ λx, map_range f f.map_zero x).sum := (map_range.add_monoid_hom f : (α →₀ _) →+ _).map_multiset_sum _ lemma map_range_finset_sum (f : M →+ N) (s : finset ι) (g : ι → (α →₀ M)) : map_range f f.map_zero (∑ x in s, g x) = ∑ x in s, map_range f f.map_zero (g x) := (map_range.add_monoid_hom f : (α →₀ _) →+ _).map_sum _ _ /-- `finsupp.map_range.add_monoid_hom` as an equiv. -/ @[simps apply] def map_range.add_equiv (f : M ≃+ N) : (α →₀ M) ≃+ (α →₀ N) := { to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)), inv_fun := (map_range f.symm f.symm.map_zero : (α →₀ N) → (α →₀ M)), left_inv := λ x, begin rw ←map_range_comp _ _ _ _; simp_rw add_equiv.symm_comp_self, { exact map_range_id _ }, { refl }, end, right_inv := λ x, begin rw ←map_range_comp _ _ _ _; simp_rw add_equiv.self_comp_symm, { exact map_range_id _ }, { refl }, end, ..(map_range.add_monoid_hom f.to_add_monoid_hom) } @[simp] lemma map_range.add_equiv_refl : map_range.add_equiv (add_equiv.refl M) = add_equiv.refl (α →₀ M) := add_equiv.ext map_range_id lemma map_range.add_equiv_trans (f : M ≃+ N) (f₂ : N ≃+ P) : (map_range.add_equiv (f.trans f₂) : (α →₀ _) ≃+ _) = (map_range.add_equiv f).trans (map_range.add_equiv f₂) := add_equiv.ext $ map_range_comp _ _ _ _ _ @[simp] lemma map_range.add_equiv_symm (f : M ≃+ N) : ((map_range.add_equiv f).symm : (α →₀ _) ≃+ _) = map_range.add_equiv f.symm := add_equiv.ext $ λ x, rfl @[simp] lemma map_range.add_equiv_to_add_monoid_hom (f : M ≃+ N) : (map_range.add_equiv f : (α →₀ _) ≃+ _).to_add_monoid_hom = (map_range.add_monoid_hom f.to_add_monoid_hom : (α →₀ _) →+ _) := add_monoid_hom.ext $ λ _, rfl @[simp] lemma map_range.add_equiv_to_equiv (f : M ≃+ N) : (map_range.add_equiv f).to_equiv = (map_range.equiv f.to_equiv f.map_zero f.symm.map_zero : (α →₀ _) ≃ _) := equiv.ext $ λ _, rfl end add_monoid_hom end map_range /-! ### Declarations about `map_domain` -/ section map_domain variables [add_comm_monoid M] {v v₁ v₂ : α →₀ M} /-- Given `f : α → β` and `v : α →₀ M`, `map_domain f v : β →₀ M` is the finitely supported function whose value at `a : β` is the sum of `v x` over all `x` such that `f x = a`. -/ def map_domain (f : α → β) (v : α →₀ M) : β →₀ M := v.sum $ λa, single (f a) lemma map_domain_apply {f : α → β} (hf : function.injective f) (x : α →₀ M) (a : α) : map_domain f x (f a) = x a := begin rw [map_domain, sum_apply, sum, finset.sum_eq_single a, single_eq_same], { assume b _ hba, exact single_eq_of_ne (hf.ne hba) }, { assume h, rw [not_mem_support_iff.1 h, single_zero, zero_apply] } end lemma map_domain_notin_range {f : α → β} (x : α →₀ M) (a : β) (h : a ∉ set.range f) : map_domain f x a = 0 := begin rw [map_domain, sum_apply, sum], exact finset.sum_eq_zero (assume a' h', single_eq_of_ne $ assume eq, h $ eq ▸ set.mem_range_self _) end @[simp] lemma map_domain_id : map_domain id v = v := sum_single _ lemma map_domain_comp {f : α → β} {g : β → γ} : map_domain (g ∘ f) v = map_domain g (map_domain f v) := begin refine ((sum_sum_index _ _).trans _).symm, { intro, exact single_zero _ }, { intro, exact single_add _ }, refine sum_congr (λ _ _, sum_single_index _), { exact single_zero _ } end @[simp] lemma map_domain_single {f : α → β} {a : α} {b : M} : map_domain f (single a b) = single (f a) b := sum_single_index $ single_zero _ @[simp] lemma map_domain_zero {f : α → β} : map_domain f (0 : α →₀ M) = (0 : β →₀ M) := sum_zero_index lemma map_domain_congr {f g : α → β} (h : ∀x∈v.support, f x = g x) : v.map_domain f = v.map_domain g := finset.sum_congr rfl $ λ _ H, by simp only [h _ H] lemma map_domain_add {f : α → β} : map_domain f (v₁ + v₂) = map_domain f v₁ + map_domain f v₂ := sum_add_index' (λ _, single_zero _) (λ _, single_add _) @[simp] lemma map_domain_equiv_apply {f : α ≃ β} (x : α →₀ M) (a : β) : map_domain f x a = x (f.symm a) := begin conv_lhs { rw ←f.apply_symm_apply a }, exact map_domain_apply f.injective _ _, end /-- `finsupp.map_domain` is an `add_monoid_hom`. -/ @[simps] def map_domain.add_monoid_hom (f : α → β) : (α →₀ M) →+ (β →₀ M) := { to_fun := map_domain f, map_zero' := map_domain_zero, map_add' := λ _ _, map_domain_add} @[simp] lemma map_domain.add_monoid_hom_id : map_domain.add_monoid_hom id = add_monoid_hom.id (α →₀ M) := add_monoid_hom.ext $ λ _, map_domain_id lemma map_domain.add_monoid_hom_comp (f : β → γ) (g : α → β) : (map_domain.add_monoid_hom (f ∘ g) : (α →₀ M) →+ (γ →₀ M)) = (map_domain.add_monoid_hom f).comp (map_domain.add_monoid_hom g) := add_monoid_hom.ext $ λ _, map_domain_comp lemma map_domain_finset_sum {f : α → β} {s : finset ι} {v : ι → α →₀ M} : map_domain f (∑ i in s, v i) = ∑ i in s, map_domain f (v i) := (map_domain.add_monoid_hom f : (α →₀ M) →+ β →₀ M).map_sum _ _ lemma map_domain_sum [has_zero N] {f : α → β} {s : α →₀ N} {v : α → N → α →₀ M} : map_domain f (s.sum v) = s.sum (λa b, map_domain f (v a b)) := (map_domain.add_monoid_hom f : (α →₀ M) →+ β →₀ M).map_finsupp_sum _ _ lemma map_domain_support [decidable_eq β] {f : α → β} {s : α →₀ M} : (s.map_domain f).support ⊆ s.support.image f := finset.subset.trans support_sum $ finset.subset.trans (finset.bUnion_mono $ assume a ha, support_single_subset) $ by rw [finset.bUnion_singleton]; exact subset.refl _ lemma map_domain_apply' (S : set α) {f : α → β} (x : α →₀ M) (hS : (x.support : set α) ⊆ S) (hf : set.inj_on f S) {a : α} (ha : a ∈ S) : map_domain f x (f a) = x a := begin rw [map_domain, sum_apply, sum], simp_rw single_apply, have : ∀ (b : α) (ha1 : b ∈ x.support), (if f b = f a then x b else 0) = if f b = f a then x a else 0, { intros b hb, refine if_ctx_congr iff.rfl (λ hh, _) (λ _, rfl), rw hf (hS hb) ha hh, }, conv in (ite _ _ _) { rw [this _ H], }, by_cases ha : a ∈ x.support, { rw [← finset.add_sum_erase _ _ ha, if_pos rfl], convert add_zero _, have : ∀ i ∈ x.support.erase a, f i ≠ f a, { intros i hi, exact (finset.ne_of_mem_erase hi) ∘ (hf (hS $ finset.mem_of_mem_erase hi) (hS ha)), }, conv in (ite _ _ _) { rw if_neg (this x H), }, exact finset.sum_const_zero, }, { rw [mem_support_iff, not_not] at ha, simp [ha], } end lemma map_domain_support_of_inj_on [decidable_eq β] {f : α → β} (s : α →₀ M) (hf : set.inj_on f s.support) : (map_domain f s).support = finset.image f s.support := finset.subset.antisymm map_domain_support $ begin intros x hx, simp only [mem_image, exists_prop, mem_support_iff, ne.def] at hx, rcases hx with ⟨hx_w, hx_h_left, rfl⟩, simp only [mem_support_iff, ne.def], rw map_domain_apply' (↑s.support : set _) _ _ hf, { exact hx_h_left, }, { simp only [mem_coe, mem_support_iff, ne.def], exact hx_h_left, }, { exact subset.refl _, }, end lemma map_domain_support_of_injective [decidable_eq β] {f : α → β} (hf : function.injective f) (s : α →₀ M) : (map_domain f s).support = finset.image f s.support := map_domain_support_of_inj_on s (hf.inj_on _) @[to_additive] lemma prod_map_domain_index [comm_monoid N] {f : α → β} {s : α →₀ M} {h : β → M → N} (h_zero : ∀b, h b 0 = 1) (h_add : ∀b m₁ m₂, h b (m₁ + m₂) = h b m₁ * h b m₂) : (map_domain f s).prod h = s.prod (λa m, h (f a) m) := (prod_sum_index h_zero h_add).trans $ prod_congr $ λ _ _, prod_single_index (h_zero _) /-- A version of `sum_map_domain_index` that takes a bundled `add_monoid_hom`, rather than separate linearity hypotheses. -/ -- Note that in `prod_map_domain_index`, `M` is still an additive monoid, -- so there is no analogous version in terms of `monoid_hom`. @[simp] lemma sum_map_domain_index_add_monoid_hom [add_comm_monoid N] {f : α → β} {s : α →₀ M} (h : β → M →+ N) : (map_domain f s).sum (λ b m, h b m) = s.sum (λ a m, h (f a) m) := @sum_map_domain_index _ _ _ _ _ _ _ _ (λ b m, h b m) (λ b, (h b).map_zero) (λ b m₁ m₂, (h b).map_add _ _) lemma emb_domain_eq_map_domain (f : α ↪ β) (v : α →₀ M) : emb_domain f v = map_domain f v := begin ext a, by_cases a ∈ set.range f, { rcases h with ⟨a, rfl⟩, rw [map_domain_apply f.injective, emb_domain_apply] }, { rw [map_domain_notin_range, emb_domain_notin_range]; assumption } end @[to_additive] lemma prod_map_domain_index_inj [comm_monoid N] {f : α → β} {s : α →₀ M} {h : β → M → N} (hf : function.injective f) : (s.map_domain f).prod h = s.prod (λa b, h (f a) b) := by rw [←function.embedding.coe_fn_mk f hf, ←emb_domain_eq_map_domain, prod_emb_domain] lemma map_domain_injective {f : α → β} (hf : function.injective f) : function.injective (map_domain f : (α →₀ M) → (β →₀ M)) := begin assume v₁ v₂ eq, ext a, have : map_domain f v₁ (f a) = map_domain f v₂ (f a), { rw eq }, rwa [map_domain_apply hf, map_domain_apply hf] at this, end /-- When `f` is an embedding we have an embedding `(α →₀ ℕ) ↪ (β →₀ ℕ)` given by `map_domain`. -/ @[simps] def map_domain_embedding {α β : Type*} (f : α ↪ β) : (α →₀ ℕ) ↪ β →₀ ℕ := ⟨finsupp.map_domain f, finsupp.map_domain_injective f.injective⟩ lemma map_domain.add_monoid_hom_comp_map_range [add_comm_monoid N] (f : α → β) (g : M →+ N) : (map_domain.add_monoid_hom f).comp (map_range.add_monoid_hom g) = (map_range.add_monoid_hom g).comp (map_domain.add_monoid_hom f) := by { ext, simp } /-- When `g` preserves addition, `map_range` and `map_domain` commute. -/ lemma map_domain_map_range [add_comm_monoid N] (f : α → β) (v : α →₀ M) (g : M → N) (h0 : g 0 = 0) (hadd : ∀ x y, g (x + y) = g x + g y) : map_domain f (map_range g h0 v) = map_range g h0 (map_domain f v) := let g' : M →+ N := { to_fun := g, map_zero' := h0, map_add' := hadd} in add_monoid_hom.congr_fun (map_domain.add_monoid_hom_comp_map_range f g') v lemma sum_update_add [add_comm_monoid α] [add_comm_monoid β] (f : ι →₀ α) (i : ι) (a : α) (g : ι → α → β) (hg : ∀ i, g i 0 = 0) (hgg : ∀ (j : ι) (a₁ a₂ : α), g j (a₁ + a₂) = g j a₁ + g j a₂) : (f.update i a).sum g + g i (f i) = f.sum g + g i a := begin rw [update_eq_erase_add_single, sum_add_index' hg hgg], conv_rhs { rw ← finsupp.update_self f i }, rw [update_eq_erase_add_single, sum_add_index' hg hgg, add_assoc, add_assoc], congr' 1, rw [add_comm, sum_single_index (hg _), sum_single_index (hg _)], end lemma map_domain_inj_on (S : set α) {f : α → β} (hf : set.inj_on f S) : set.inj_on (map_domain f : (α →₀ M) → (β →₀ M)) {w | (w.support : set α) ⊆ S} := begin intros v₁ hv₁ v₂ hv₂ eq, ext a, by_cases h : a ∈ v₁.support ∪ v₂.support, { rw [← map_domain_apply' S _ hv₁ hf _, ← map_domain_apply' S _ hv₂ hf _, eq]; { apply set.union_subset hv₁ hv₂, exact_mod_cast h, }, }, { simp only [decidable.not_or_iff_and_not, mem_union, not_not, mem_support_iff] at h, simp [h], }, end end map_domain /-! ### Declarations about `comap_domain` -/ section comap_domain /-- Given `f : α → β`, `l : β →₀ M` and a proof `hf` that `f` is injective on the preimage of `l.support`, `comap_domain f l hf` is the finitely supported function from `α` to `M` given by composing `l` with `f`. -/ @[simps support] def comap_domain [has_zero M] (f : α → β) (l : β →₀ M) (hf : set.inj_on f (f ⁻¹' ↑l.support)) : α →₀ M := { support := l.support.preimage f hf, to_fun := (λ a, l (f a)), mem_support_to_fun := begin intros a, simp only [finset.mem_def.symm, finset.mem_preimage], exact l.mem_support_to_fun (f a), end } @[simp] lemma comap_domain_apply [has_zero M] (f : α → β) (l : β →₀ M) (hf : set.inj_on f (f ⁻¹' ↑l.support)) (a : α) : comap_domain f l hf a = l (f a) := rfl lemma sum_comap_domain [has_zero M] [add_comm_monoid N] (f : α → β) (l : β →₀ M) (g : β → M → N) (hf : set.bij_on f (f ⁻¹' ↑l.support) ↑l.support) : (comap_domain f l hf.inj_on).sum (g ∘ f) = l.sum g := begin simp only [sum, comap_domain_apply, (∘)], simp [comap_domain, finset.sum_preimage_of_bij f _ _ (λ x, g x (l x))], end lemma eq_zero_of_comap_domain_eq_zero [add_comm_monoid M] (f : α → β) (l : β →₀ M) (hf : set.bij_on f (f ⁻¹' ↑l.support) ↑l.support) : comap_domain f l hf.inj_on = 0 → l = 0 := begin rw [← support_eq_empty, ← support_eq_empty, comap_domain], simp only [finset.ext_iff, finset.not_mem_empty, iff_false, mem_preimage], assume h a ha, cases hf.2.2 ha with b hb, exact h b (hb.2.symm ▸ ha) end section f_injective section has_zero variables [has_zero M] /-- Note the `hif` argument is needed for this to work in `rw`. -/ @[simp] lemma comap_domain_zero (f : α → β) (hif : set.inj_on f (f ⁻¹' ↑((0 : β →₀ M).support)) := set.inj_on_empty _) : comap_domain f (0 : β →₀ M) hif = (0 : α →₀ M) := by { ext, refl } @[simp] lemma comap_domain_single (f : α → β) (a : α) (m : M) (hif : set.inj_on f (f ⁻¹' (single (f a) m).support)) : comap_domain f (finsupp.single (f a) m) hif = finsupp.single a m := begin rcases eq_or_ne m 0 with rfl | hm, { simp only [single_zero, comap_domain_zero] }, { rw [eq_single_iff, comap_domain_apply, comap_domain_support, ← finset.coe_subset, coe_preimage, support_single_ne_zero _ hm, coe_singleton, coe_singleton, single_eq_same], rw [support_single_ne_zero _ hm, coe_singleton] at hif, exact ⟨λ x hx, hif hx rfl hx, rfl⟩ } end end has_zero section add_zero_class variables [add_zero_class M] {f : α → β} lemma comap_domain_add (v₁ v₂ : β →₀ M) (hv₁ : set.inj_on f (f ⁻¹' ↑(v₁.support))) (hv₂ : set.inj_on f (f ⁻¹' ↑(v₂.support))) (hv₁₂ : set.inj_on f (f ⁻¹' ↑((v₁ + v₂).support))) : comap_domain f (v₁ + v₂) hv₁₂ = comap_domain f v₁ hv₁ + comap_domain f v₂ hv₂ := by { ext, simp only [comap_domain_apply, coe_add, pi.add_apply] } /-- A version of `finsupp.comap_domain_add` that's easier to use. -/ lemma comap_domain_add_of_injective (hf : function.injective f) (v₁ v₂ : β →₀ M) : comap_domain f (v₁ + v₂) (hf.inj_on _) = comap_domain f v₁ (hf.inj_on _) + comap_domain f v₂ (hf.inj_on _) := comap_domain_add _ _ _ _ _ /-- `finsupp.comap_domain` is an `add_monoid_hom`. -/ @[simps] def comap_domain.add_monoid_hom (hf : function.injective f) : (β →₀ M) →+ (α →₀ M) := { to_fun := λ x, comap_domain f x (hf.inj_on _), map_zero' := comap_domain_zero f, map_add' := comap_domain_add_of_injective hf } end add_zero_class variables [add_comm_monoid M] (f : α → β) lemma map_domain_comap_domain (hf : function.injective f) (l : β →₀ M) (hl : ↑l.support ⊆ set.range f) : map_domain f (comap_domain f l (hf.inj_on _)) = l := begin ext a, by_cases h_cases: a ∈ set.range f, { rcases set.mem_range.1 h_cases with ⟨b, hb⟩, rw [hb.symm, map_domain_apply hf, comap_domain_apply] }, { rw map_domain_notin_range _ _ h_cases, by_contra h_contr, apply h_cases (hl $ finset.mem_coe.2 $ mem_support_iff.2 $ λ h, h_contr h.symm) } end end f_injective end comap_domain section option /-- Restrict a finitely supported function on `option α` to a finitely supported function on `α`. -/ def some [has_zero M] (f : option α →₀ M) : α →₀ M := f.comap_domain option.some (λ _, by simp) @[simp] lemma some_apply [has_zero M] (f : option α →₀ M) (a : α) : f.some a = f (option.some a) := rfl @[simp] lemma some_zero [has_zero M] : (0 : option α →₀ M).some = 0 := by { ext, simp, } @[simp] lemma some_add [add_comm_monoid M] (f g : option α →₀ M) : (f + g).some = f.some + g.some := by { ext, simp, } @[simp] lemma some_single_none [has_zero M] (m : M) : (single none m : option α →₀ M).some = 0 := by { ext, simp, } @[simp] lemma some_single_some [has_zero M] (a : α) (m : M) : (single (option.some a) m : option α →₀ M).some = single a m := by { ext b, simp [single_apply], } @[to_additive] lemma prod_option_index [add_comm_monoid M] [comm_monoid N] (f : option α →₀ M) (b : option α → M → N) (h_zero : ∀ o, b o 0 = 1) (h_add : ∀ o m₁ m₂, b o (m₁ + m₂) = b o m₁ * b o m₂) : f.prod b = b none (f none) * f.some.prod (λ a, b (option.some a)) := begin apply induction_linear f, { simp [h_zero], }, { intros f₁ f₂ h₁ h₂, rw [finsupp.prod_add_index, h₁, h₂, some_add, finsupp.prod_add_index], simp only [h_add, pi.add_apply, finsupp.coe_add], rw mul_mul_mul_comm, all_goals { simp [h_zero, h_add], }, }, { rintros (_|a) m; simp [h_zero, h_add], } end lemma sum_option_index_smul [semiring R] [add_comm_monoid M] [module R M] (f : option α →₀ R) (b : option α → M) : f.sum (λ o r, r • b o) = f none • b none + f.some.sum (λ a r, r • b (option.some a)) := f.sum_option_index _ (λ _, zero_smul _ _) (λ _ _ _, add_smul _ _ _) end option /-! ### Declarations about `equiv_congr_left` -/ section equiv_congr_left variable [has_zero M] /-- Given `f : α ≃ β`, we can map `l : α →₀ M` to `equiv_map_domain f l : β →₀ M` (computably) by mapping the support forwards and the function backwards. -/ def equiv_map_domain (f : α ≃ β) (l : α →₀ M) : β →₀ M := { support := l.support.map f.to_embedding, to_fun := λ a, l (f.symm a), mem_support_to_fun := λ a, by simp only [finset.mem_map_equiv, mem_support_to_fun]; refl } @[simp] lemma equiv_map_domain_apply (f : α ≃ β) (l : α →₀ M) (b : β) : equiv_map_domain f l b = l (f.symm b) := rfl lemma equiv_map_domain_symm_apply (f : α ≃ β) (l : β →₀ M) (a : α) : equiv_map_domain f.symm l a = l (f a) := rfl @[simp] lemma equiv_map_domain_refl (l : α →₀ M) : equiv_map_domain (equiv.refl _) l = l := by ext x; refl lemma equiv_map_domain_refl' : equiv_map_domain (equiv.refl _) = @id (α →₀ M) := by ext x; refl lemma equiv_map_domain_trans (f : α ≃ β) (g : β ≃ γ) (l : α →₀ M) : equiv_map_domain (f.trans g) l = equiv_map_domain g (equiv_map_domain f l) := by ext x; refl lemma equiv_map_domain_trans' (f : α ≃ β) (g : β ≃ γ) : @equiv_map_domain _ _ M _ (f.trans g) = equiv_map_domain g ∘ equiv_map_domain f := by ext x; refl @[simp] lemma equiv_map_domain_single (f : α ≃ β) (a : α) (b : M) : equiv_map_domain f (single a b) = single (f a) b := by ext x; simp only [single_apply, equiv.apply_eq_iff_eq_symm_apply, equiv_map_domain_apply]; congr @[simp] lemma equiv_map_domain_zero {f : α ≃ β} : equiv_map_domain f (0 : α →₀ M) = (0 : β →₀ M) := by ext x; simp only [equiv_map_domain_apply, coe_zero, pi.zero_apply] lemma equiv_map_domain_eq_map_domain {M} [add_comm_monoid M] (f : α ≃ β) (l : α →₀ M) : equiv_map_domain f l = map_domain f l := by ext x; simp [map_domain_equiv_apply] /-- Given `f : α ≃ β`, the finitely supported function spaces are also in bijection: `(α →₀ M) ≃ (β →₀ M)`. This is the finitely-supported version of `equiv.Pi_congr_left`. -/ def equiv_congr_left (f : α ≃ β) : (α →₀ M) ≃ (β →₀ M) := by refine ⟨equiv_map_domain f, equiv_map_domain f.symm, λ f, _, λ f, _⟩; ext x; simp only [equiv_map_domain_apply, equiv.symm_symm, equiv.symm_apply_apply, equiv.apply_symm_apply] @[simp] lemma equiv_congr_left_apply (f : α ≃ β) (l : α →₀ M) : equiv_congr_left f l = equiv_map_domain f l := rfl @[simp] lemma equiv_congr_left_symm (f : α ≃ β) : (@equiv_congr_left _ _ M _ f).symm = equiv_congr_left f.symm := rfl end equiv_congr_left /-! ### Declarations about `filter` -/ section filter section has_zero variables [has_zero M] (p : α → Prop) (f : α →₀ M) /-- `filter p f` is the function which is `f a` if `p a` is true and 0 otherwise. -/ def filter (p : α → Prop) (f : α →₀ M) : α →₀ M := { to_fun := λ a, if p a then f a else 0, support := f.support.filter (λ a, p a), mem_support_to_fun := λ a, by split_ifs; { simp only [h, mem_filter, mem_support_iff], tauto } } lemma filter_apply (a : α) [D : decidable (p a)] : f.filter p a = if p a then f a else 0 := by rw subsingleton.elim D; refl lemma filter_eq_indicator : ⇑(f.filter p) = set.indicator {x | p x} f := rfl lemma filter_eq_zero_iff : f.filter p = 0 ↔ ∀ x, p x → f x = 0 := by simp only [fun_like.ext_iff, filter_eq_indicator, zero_apply, set.indicator_apply_eq_zero, set.mem_set_of_eq] lemma filter_eq_self_iff : f.filter p = f ↔ ∀ x, f x ≠ 0 → p x := by simp only [fun_like.ext_iff, filter_eq_indicator, set.indicator_apply_eq_self, set.mem_set_of_eq, not_imp_comm] @[simp] lemma filter_apply_pos {a : α} (h : p a) : f.filter p a = f a := if_pos h @[simp] lemma filter_apply_neg {a : α} (h : ¬ p a) : f.filter p a = 0 := if_neg h @[simp] lemma support_filter [D : decidable_pred p] : (f.filter p).support = f.support.filter p := by rw subsingleton.elim D; refl lemma filter_zero : (0 : α →₀ M).filter p = 0 := by rw [← support_eq_empty, support_filter, support_zero, finset.filter_empty] @[simp] lemma filter_single_of_pos {a : α} {b : M} (h : p a) : (single a b).filter p = single a b := (filter_eq_self_iff _ _).2 $ λ x hx, (single_apply_ne_zero.1 hx).1.symm ▸ h @[simp] lemma filter_single_of_neg {a : α} {b : M} (h : ¬ p a) : (single a b).filter p = 0 := (filter_eq_zero_iff _ _).2 $ λ x hpx, single_apply_eq_zero.2 $ λ hxa, absurd hpx (hxa.symm ▸ h) @[to_additive] lemma prod_filter_index [comm_monoid N] (g : α → M → N) : (f.filter p).prod g = ∏ x in (f.filter p).support, g x (f x) := begin refine finset.prod_congr rfl (λ x hx, _), rw [support_filter, finset.mem_filter] at hx, rw [filter_apply_pos _ _ hx.2] end @[simp, to_additive] lemma prod_filter_mul_prod_filter_not [comm_monoid N] (g : α → M → N) : (f.filter p).prod g * (f.filter (λ a, ¬ p a)).prod g = f.prod g := by simp_rw [prod_filter_index, support_filter, prod_filter_mul_prod_filter_not, finsupp.prod] @[simp, to_additive] lemma prod_div_prod_filter [comm_group G] (g : α → M → G) : f.prod g / (f.filter p).prod g = (f.filter (λ a, ¬p a)).prod g := div_eq_of_eq_mul' (prod_filter_mul_prod_filter_not _ _ _).symm end has_zero lemma filter_pos_add_filter_neg [add_zero_class M] (f : α →₀ M) (p : α → Prop) : f.filter p + f.filter (λa, ¬ p a) = f := coe_fn_injective $ set.indicator_self_add_compl {x | p x} f end filter /-! ### Declarations about `frange` -/ section frange variables [has_zero M] /-- `frange f` is the image of `f` on the support of `f`. -/ def frange (f : α →₀ M) : finset M := finset.image f f.support theorem mem_frange {f : α →₀ M} {y : M} : y ∈ f.frange ↔ y ≠ 0 ∧ ∃ x, f x = y := finset.mem_image.trans ⟨λ ⟨x, hx1, hx2⟩, ⟨hx2 ▸ mem_support_iff.1 hx1, x, hx2⟩, λ ⟨hy, x, hx⟩, ⟨x, mem_support_iff.2 (hx.symm ▸ hy), hx⟩⟩ theorem zero_not_mem_frange {f : α →₀ M} : (0:M) ∉ f.frange := λ H, (mem_frange.1 H).1 rfl theorem frange_single {x : α} {y : M} : frange (single x y) ⊆ {y} := λ r hr, let ⟨t, ht1, ht2⟩ := mem_frange.1 hr in ht2 ▸ (by rw single_apply at ht2 ⊢; split_ifs at ht2 ⊢; [exact finset.mem_singleton_self _, cc]) end frange /-! ### Declarations about `subtype_domain` -/ section subtype_domain section zero variables [has_zero M] {p : α → Prop} /-- `subtype_domain p f` is the restriction of the finitely supported function `f` to the subtype `p`. -/ def subtype_domain (p : α → Prop) (f : α →₀ M) : (subtype p →₀ M) := ⟨f.support.subtype p, f ∘ coe, λ a, by simp only [mem_subtype, mem_support_iff]⟩ @[simp] lemma support_subtype_domain [D : decidable_pred p] {f : α →₀ M} : (subtype_domain p f).support = f.support.subtype p := by rw subsingleton.elim D; refl @[simp] lemma subtype_domain_apply {a : subtype p} {v : α →₀ M} : (subtype_domain p v) a = v (a.val) := rfl @[simp] lemma subtype_domain_zero : subtype_domain p (0 : α →₀ M) = 0 := rfl lemma subtype_domain_eq_zero_iff' {f : α →₀ M} : f.subtype_domain p = 0 ↔ ∀ x, p x → f x = 0 := by simp_rw [← support_eq_empty, support_subtype_domain, subtype_eq_empty, not_mem_support_iff] lemma subtype_domain_eq_zero_iff {f : α →₀ M} (hf : ∀ x ∈ f.support , p x) : f.subtype_domain p = 0 ↔ f = 0 := subtype_domain_eq_zero_iff'.trans ⟨λ H, ext $ λ x, if hx : p x then H x hx else not_mem_support_iff.1 $ mt (hf x) hx, λ H x _, by simp [H]⟩ @[to_additive] lemma prod_subtype_domain_index [comm_monoid N] {v : α →₀ M} {h : α → M → N} (hp : ∀x∈v.support, p x) : (v.subtype_domain p).prod (λa b, h a b) = v.prod h := prod_bij (λp _, p.val) (λ _, mem_subtype.1) (λ _ _, rfl) (λ _ _ _ _, subtype.eq) (λ b hb, ⟨⟨b, hp b hb⟩, mem_subtype.2 hb, rfl⟩) end zero section add_zero_class variables [add_zero_class M] {p : α → Prop} {v v' : α →₀ M} @[simp] lemma subtype_domain_add {v v' : α →₀ M} : (v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p := ext $ λ _, rfl /-- `subtype_domain` but as an `add_monoid_hom`. -/ def subtype_domain_add_monoid_hom : (α →₀ M) →+ subtype p →₀ M := { to_fun := subtype_domain p, map_zero' := subtype_domain_zero, map_add' := λ _ _, subtype_domain_add } /-- `finsupp.filter` as an `add_monoid_hom`. -/ def filter_add_hom (p : α → Prop) : (α →₀ M) →+ (α →₀ M) := { to_fun := filter p, map_zero' := filter_zero p, map_add' := λ f g, coe_fn_injective $ set.indicator_add {x | p x} f g } @[simp] lemma filter_add {v v' : α →₀ M} : (v + v').filter p = v.filter p + v'.filter p := (filter_add_hom p).map_add v v' end add_zero_class section comm_monoid variables [add_comm_monoid M] {p : α → Prop} lemma subtype_domain_sum {s : finset ι} {h : ι → α →₀ M} : (∑ c in s, h c).subtype_domain p = ∑ c in s, (h c).subtype_domain p := (subtype_domain_add_monoid_hom : _ →+ subtype p →₀ M).map_sum _ s lemma subtype_domain_finsupp_sum [has_zero N] {s : β →₀ N} {h : β → N → α →₀ M} : (s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) := subtype_domain_sum lemma filter_sum (s : finset ι) (f : ι → α →₀ M) : (∑ a in s, f a).filter p = ∑ a in s, filter p (f a) := (filter_add_hom p : (α →₀ M) →+ _).map_sum f s lemma filter_eq_sum (p : α → Prop) [D : decidable_pred p] (f : α →₀ M) : f.filter p = ∑ i in f.support.filter p, single i (f i) := (f.filter p).sum_single.symm.trans $ finset.sum_congr (by rw subsingleton.elim D; refl) $ λ x hx, by rw [filter_apply_pos _ _ (mem_filter.1 hx).2] end comm_monoid section group variables [add_group G] {p : α → Prop} {v v' : α →₀ G} @[simp] lemma subtype_domain_neg : (- v).subtype_domain p = - v.subtype_domain p := ext $ λ _, rfl @[simp] lemma subtype_domain_sub : (v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p := ext $ λ _, rfl @[simp] lemma single_neg (a : α) (b : G) : single a (-b) = -single a b := (single_add_hom a : G →+ _).map_neg b @[simp] lemma single_sub (a : α) (b₁ b₂ : G) : single a (b₁ - b₂) = single a b₁ - single a b₂ := (single_add_hom a : G →+ _).map_sub b₁ b₂ @[simp] lemma erase_neg (a : α) (f : α →₀ G) : erase a (-f) = -erase a f := (erase_add_hom a : (_ →₀ G) →+ _).map_neg f @[simp] lemma erase_sub (a : α) (f₁ f₂ : α →₀ G) : erase a (f₁ - f₂) = erase a f₁ - erase a f₂ := (erase_add_hom a : (_ →₀ G) →+ _).map_sub f₁ f₂ @[simp] lemma filter_neg (p : α → Prop) (f : α →₀ G) : filter p (-f) = -filter p f := (filter_add_hom p : (_ →₀ G) →+ _).map_neg f @[simp] lemma filter_sub (p : α → Prop) (f₁ f₂ : α →₀ G) : filter p (f₁ - f₂) = filter p f₁ - filter p f₂ := (filter_add_hom p : (_ →₀ G) →+ _).map_sub f₁ f₂ end group end subtype_domain lemma mem_support_multiset_sum [add_comm_monoid M] {s : multiset (α →₀ M)} (a : α) : a ∈ s.sum.support → ∃f∈s, a ∈ (f : α →₀ M).support := multiset.induction_on s false.elim begin assume f s ih ha, by_cases a ∈ f.support, { exact ⟨f, multiset.mem_cons_self _ _, h⟩ }, { simp only [multiset.sum_cons, mem_support_iff, add_apply, not_mem_support_iff.1 h, zero_add] at ha, rcases ih (mem_support_iff.2 ha) with ⟨f', h₀, h₁⟩, exact ⟨f', multiset.mem_cons_of_mem h₀, h₁⟩ } end lemma mem_support_finset_sum [add_comm_monoid M] {s : finset ι} {h : ι → α →₀ M} (a : α) (ha : a ∈ (∑ c in s, h c).support) : ∃ c ∈ s, a ∈ (h c).support := let ⟨f, hf, hfa⟩ := mem_support_multiset_sum a ha in let ⟨c, hc, eq⟩ := multiset.mem_map.1 hf in ⟨c, hc, eq.symm ▸ hfa⟩ /-! ### Declarations about `curry` and `uncurry` -/ section curry_uncurry variables [add_comm_monoid M] [add_comm_monoid N] /-- Given a finitely supported function `f` from a product type `α × β` to `γ`, `curry f` is the "curried" finitely supported function from `α` to the type of finitely supported functions from `β` to `γ`. -/ protected def curry (f : (α × β) →₀ M) : α →₀ (β →₀ M) := f.sum $ λp c, single p.1 (single p.2 c) @[simp] lemma curry_apply (f : (α × β) →₀ M) (x : α) (y : β) : f.curry x y = f (x, y) := begin have : ∀ (b : α × β), single b.fst (single b.snd (f b)) x y = if b = (x, y) then f b else 0, { rintros ⟨b₁, b₂⟩, simp [single_apply, ite_apply, prod.ext_iff, ite_and], split_ifs; simp [single_apply, *] }, rw [finsupp.curry, sum_apply, sum_apply, finsupp.sum, finset.sum_eq_single, this, if_pos rfl], { intros b hb b_ne, rw [this b, if_neg b_ne] }, { intros hxy, rw [this (x, y), if_pos rfl, not_mem_support_iff.mp hxy] } end lemma sum_curry_index (f : (α × β) →₀ M) (g : α → β → M → N) (hg₀ : ∀ a b, g a b 0 = 0) (hg₁ : ∀a b c₀ c₁, g a b (c₀ + c₁) = g a b c₀ + g a b c₁) : f.curry.sum (λa f, f.sum (g a)) = f.sum (λp c, g p.1 p.2 c) := begin rw [finsupp.curry], transitivity, { exact sum_sum_index (assume a, sum_zero_index) (assume a b₀ b₁, sum_add_index' (assume a, hg₀ _ _) (assume c d₀ d₁, hg₁ _ _ _ _)) }, congr, funext p c, transitivity, { exact sum_single_index sum_zero_index }, exact sum_single_index (hg₀ _ _) end /-- Given a finitely supported function `f` from `α` to the type of finitely supported functions from `β` to `M`, `uncurry f` is the "uncurried" finitely supported function from `α × β` to `M`. -/ protected def uncurry (f : α →₀ (β →₀ M)) : (α × β) →₀ M := f.sum $ λa g, g.sum $ λb c, single (a, b) c /-- `finsupp_prod_equiv` defines the `equiv` between `((α × β) →₀ M)` and `(α →₀ (β →₀ M))` given by currying and uncurrying. -/ def finsupp_prod_equiv : ((α × β) →₀ M) ≃ (α →₀ (β →₀ M)) := by refine ⟨finsupp.curry, finsupp.uncurry, λ f, _, λ f, _⟩; simp only [ finsupp.curry, finsupp.uncurry, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, prod.mk.eta, (single_sum _ _ _).symm, sum_single] lemma filter_curry (f : α × β →₀ M) (p : α → Prop) : (f.filter (λa:α×β, p a.1)).curry = f.curry.filter p := begin rw [finsupp.curry, finsupp.curry, finsupp.sum, finsupp.sum, filter_sum, support_filter, sum_filter], refine finset.sum_congr rfl _, rintros ⟨a₁, a₂⟩ ha, dsimp only, split_ifs, { rw [filter_apply_pos, filter_single_of_pos]; exact h }, { rwa [filter_single_of_neg] } end lemma support_curry [decidable_eq α] (f : α × β →₀ M) : f.curry.support ⊆ f.support.image prod.fst := begin rw ← finset.bUnion_singleton, refine finset.subset.trans support_sum _, refine finset.bUnion_mono (assume a _, support_single_subset) end end curry_uncurry section sum /-- `finsupp.sum_elim f g` maps `inl x` to `f x` and `inr y` to `g y`. -/ def sum_elim {α β γ : Type*} [has_zero γ] (f : α →₀ γ) (g : β →₀ γ) : α ⊕ β →₀ γ := on_finset ((f.support.map ⟨_, sum.inl_injective⟩) ∪ g.support.map ⟨_, sum.inr_injective⟩) (sum.elim f g) (λ ab h, by { cases ab with a b; simp only [sum.elim_inl, sum.elim_inr] at h; simpa }) @[simp] lemma coe_sum_elim {α β γ : Type*} [has_zero γ] (f : α →₀ γ) (g : β →₀ γ) : ⇑(sum_elim f g) = sum.elim f g := rfl lemma sum_elim_apply {α β γ : Type*} [has_zero γ] (f : α →₀ γ) (g : β →₀ γ) (x : α ⊕ β) : sum_elim f g x = sum.elim f g x := rfl lemma sum_elim_inl {α β γ : Type*} [has_zero γ] (f : α →₀ γ) (g : β →₀ γ) (x : α) : sum_elim f g (sum.inl x) = f x := rfl lemma sum_elim_inr {α β γ : Type*} [has_zero γ] (f : α →₀ γ) (g : β →₀ γ) (x : β) : sum_elim f g (sum.inr x) = g x := rfl /-- The equivalence between `(α ⊕ β) →₀ γ` and `(α →₀ γ) × (β →₀ γ)`. This is the `finsupp` version of `equiv.sum_arrow_equiv_prod_arrow`. -/ @[simps apply symm_apply] def sum_finsupp_equiv_prod_finsupp {α β γ : Type*} [has_zero γ] : ((α ⊕ β) →₀ γ) ≃ (α →₀ γ) × (β →₀ γ) := { to_fun := λ f, ⟨f.comap_domain sum.inl (sum.inl_injective.inj_on _), f.comap_domain sum.inr (sum.inr_injective.inj_on _)⟩, inv_fun := λ fg, sum_elim fg.1 fg.2, left_inv := λ f, by { ext ab, cases ab with a b; simp }, right_inv := λ fg, by { ext; simp } } lemma fst_sum_finsupp_equiv_prod_finsupp {α β γ : Type*} [has_zero γ] (f : (α ⊕ β) →₀ γ) (x : α) : (sum_finsupp_equiv_prod_finsupp f).1 x = f (sum.inl x) := rfl lemma snd_sum_finsupp_equiv_prod_finsupp {α β γ : Type*} [has_zero γ] (f : (α ⊕ β) →₀ γ) (y : β) : (sum_finsupp_equiv_prod_finsupp f).2 y = f (sum.inr y) := rfl lemma sum_finsupp_equiv_prod_finsupp_symm_inl {α β γ : Type*} [has_zero γ] (fg : (α →₀ γ) × (β →₀ γ)) (x : α) : (sum_finsupp_equiv_prod_finsupp.symm fg) (sum.inl x) = fg.1 x := rfl lemma sum_finsupp_equiv_prod_finsupp_symm_inr {α β γ : Type*} [has_zero γ] (fg : (α →₀ γ) × (β →₀ γ)) (y : β) : (sum_finsupp_equiv_prod_finsupp.symm fg) (sum.inr y) = fg.2 y := rfl variables [add_monoid M] /-- The additive equivalence between `(α ⊕ β) →₀ M` and `(α →₀ M) × (β →₀ M)`. This is the `finsupp` version of `equiv.sum_arrow_equiv_prod_arrow`. -/ @[simps apply symm_apply] def sum_finsupp_add_equiv_prod_finsupp {α β : Type*} : ((α ⊕ β) →₀ M) ≃+ (α →₀ M) × (β →₀ M) := { map_add' := by { intros, ext; simp only [equiv.to_fun_as_coe, prod.fst_add, prod.snd_add, add_apply, snd_sum_finsupp_equiv_prod_finsupp, fst_sum_finsupp_equiv_prod_finsupp] }, .. sum_finsupp_equiv_prod_finsupp } lemma fst_sum_finsupp_add_equiv_prod_finsupp {α β : Type*} (f : (α ⊕ β) →₀ M) (x : α) : (sum_finsupp_add_equiv_prod_finsupp f).1 x = f (sum.inl x) := rfl lemma snd_sum_finsupp_add_equiv_prod_finsupp {α β : Type*} (f : (α ⊕ β) →₀ M) (y : β) : (sum_finsupp_add_equiv_prod_finsupp f).2 y = f (sum.inr y) := rfl lemma sum_finsupp_add_equiv_prod_finsupp_symm_inl {α β : Type*} (fg : (α →₀ M) × (β →₀ M)) (x : α) : (sum_finsupp_add_equiv_prod_finsupp.symm fg) (sum.inl x) = fg.1 x := rfl lemma sum_finsupp_add_equiv_prod_finsupp_symm_inr {α β : Type*} (fg : (α →₀ M) × (β →₀ M)) (y : β) : (sum_finsupp_add_equiv_prod_finsupp.symm fg) (sum.inr y) = fg.2 y := rfl end sum section variables [has_zero M] [monoid_with_zero R] [mul_action_with_zero R M] @[simp] lemma single_smul (a b : α) (f : α → M) (r : R) : (single a r b) • (f a) = single a (r • f b) b := by by_cases a = b; simp [h] end section variables [monoid G] [mul_action G α] [add_comm_monoid M] /-- Scalar multiplication acting on the domain. This is not an instance as it would conflict with the action on the range. See the `instance_diamonds` test for examples of such conflicts. -/ def comap_has_smul : has_smul G (α →₀ M) := { smul := λ g, map_domain ((•) g) } local attribute [instance] comap_has_smul lemma comap_smul_def (g : G) (f : α →₀ M) : g • f = map_domain ((•) g) f := rfl @[simp] lemma comap_smul_single (g : G) (a : α) (b : M) : g • single a b = single (g • a) b := map_domain_single /-- `finsupp.comap_has_smul` is multiplicative -/ def comap_mul_action : mul_action G (α →₀ M) := { one_smul := λ f, by rw [comap_smul_def, one_smul_eq_id, map_domain_id], mul_smul := λ g g' f, by rw [comap_smul_def, comap_smul_def, comap_smul_def, ←comp_smul_left, map_domain_comp], } local attribute [instance] comap_mul_action /-- `finsupp.comap_has_smul` is distributive -/ def comap_distrib_mul_action : distrib_mul_action G (α →₀ M) := { smul_zero := λ g, by { ext, dsimp [(•)], simp, }, smul_add := λ g f f', by { ext, dsimp [(•)], simp [map_domain_add], }, } end section variables [group G] [mul_action G α] [add_comm_monoid M] local attribute [instance] comap_has_smul comap_mul_action comap_distrib_mul_action /-- When `G` is a group, `finsupp.comap_has_smul` acts by precomposition with the action of `g⁻¹`. -/ @[simp] lemma comap_smul_apply (g : G) (f : α →₀ M) (a : α) : (g • f) a = f (g⁻¹ • a) := begin conv_lhs { rw ←smul_inv_smul g a }, exact map_domain_apply (mul_action.injective g) _ (g⁻¹ • a), end end section instance [monoid R] [add_monoid M] [distrib_mul_action R M] : has_smul R (α →₀ M) := ⟨λa v, v.map_range ((•) a) (smul_zero _)⟩ /-! Throughout this section, some `monoid` and `semiring` arguments are specified with `{}` instead of `[]`. See note [implicit instance arguments]. -/ @[simp] lemma coe_smul {_ : monoid R} [add_monoid M] [distrib_mul_action R M] (b : R) (v : α →₀ M) : ⇑(b • v) = b • v := rfl lemma smul_apply {_ : monoid R} [add_monoid M] [distrib_mul_action R M] (b : R) (v : α →₀ M) (a : α) : (b • v) a = b • (v a) := rfl lemma _root_.is_smul_regular.finsupp {_ : monoid R} [add_monoid M] [distrib_mul_action R M] {k : R} (hk : is_smul_regular M k) : is_smul_regular (α →₀ M) k := λ _ _ h, ext $ λ i, hk (congr_fun h i) instance [monoid R] [nonempty α] [add_monoid M] [distrib_mul_action R M] [has_faithful_smul R M] : has_faithful_smul R (α →₀ M) := { eq_of_smul_eq_smul := λ r₁ r₂ h, let ⟨a⟩ := ‹nonempty α› in eq_of_smul_eq_smul $ λ m : M, by simpa using congr_fun (h (single a m)) a } variables (α M) instance [monoid R] [add_monoid M] [distrib_mul_action R M] : distrib_mul_action R (α →₀ M) := { smul := (•), smul_add := λ a x y, ext $ λ _, smul_add _ _ _, one_smul := λ x, ext $ λ _, one_smul _ _, mul_smul := λ r s x, ext $ λ _, mul_smul _ _ _, smul_zero := λ x, ext $ λ _, smul_zero _ } instance [monoid R] [monoid S] [add_monoid M] [distrib_mul_action R M] [distrib_mul_action S M] [has_smul R S] [is_scalar_tower R S M] : is_scalar_tower R S (α →₀ M) := { smul_assoc := λ r s a, ext $ λ _, smul_assoc _ _ _ } instance [monoid R] [monoid S] [add_monoid M] [distrib_mul_action R M] [distrib_mul_action S M] [smul_comm_class R S M] : smul_comm_class R S (α →₀ M) := { smul_comm := λ r s a, ext $ λ _, smul_comm _ _ _ } instance [monoid R] [add_monoid M] [distrib_mul_action R M] [distrib_mul_action Rᵐᵒᵖ M] [is_central_scalar R M] : is_central_scalar R (α →₀ M) := { op_smul_eq_smul := λ r a, ext $ λ _, op_smul_eq_smul _ _ } instance [semiring R] [add_comm_monoid M] [module R M] : module R (α →₀ M) := { smul := (•), zero_smul := λ x, ext $ λ _, zero_smul _ _, add_smul := λ a x y, ext $ λ _, add_smul _ _ _, .. finsupp.distrib_mul_action α M } variables {α M} {R} lemma support_smul {_ : monoid R} [add_monoid M] [distrib_mul_action R M] {b : R} {g : α →₀ M} : (b • g).support ⊆ g.support := λ a, by { simp only [smul_apply, mem_support_iff, ne.def], exact mt (λ h, h.symm ▸ smul_zero _) } @[simp] lemma support_smul_eq [semiring R] [add_comm_monoid M] [module R M] [no_zero_smul_divisors R M] {b : R} (hb : b ≠ 0) {g : α →₀ M} : (b • g).support = g.support := finset.ext (λ a, by simp [finsupp.smul_apply, hb]) section variables {p : α → Prop} @[simp] lemma filter_smul {_ : monoid R} [add_monoid M] [distrib_mul_action R M] {b : R} {v : α →₀ M} : (b • v).filter p = b • v.filter p := coe_fn_injective $ set.indicator_const_smul {x | p x} b v end lemma map_domain_smul {_ : monoid R} [add_comm_monoid M] [distrib_mul_action R M] {f : α → β} (b : R) (v : α →₀ M) : map_domain f (b • v) = b • map_domain f v := map_domain_map_range _ _ _ _ (smul_add b) @[simp] lemma smul_single {_ : monoid R} [add_monoid M] [distrib_mul_action R M] (c : R) (a : α) (b : M) : c • finsupp.single a b = finsupp.single a (c • b) := map_range_single @[simp] lemma smul_single' {_ : semiring R} (c : R) (a : α) (b : R) : c • finsupp.single a b = finsupp.single a (c * b) := smul_single _ _ _ lemma map_range_smul {_ : monoid R} [add_monoid M] [distrib_mul_action R M] [add_monoid N] [distrib_mul_action R N] {f : M → N} {hf : f 0 = 0} (c : R) (v : α →₀ M) (hsmul : ∀ x, f (c • x) = c • f x) : map_range f hf (c • v) = c • map_range f hf v := begin erw ←map_range_comp, have : (f ∘ (•) c) = ((•) c ∘ f) := funext hsmul, simp_rw this, apply map_range_comp, rw [function.comp_apply, smul_zero, hf], end lemma smul_single_one [semiring R] (a : α) (b : R) : b • single a 1 = single a b := by rw [smul_single, smul_eq_mul, mul_one] lemma comap_domain_smul [add_monoid M] [monoid R] [distrib_mul_action R M] {f : α → β} (r : R) (v : β →₀ M) (hfv : set.inj_on f (f ⁻¹' ↑(v.support))) (hfrv : set.inj_on f (f ⁻¹' ↑((r • v).support)) := hfv.mono $ set.preimage_mono $ finset.coe_subset.mpr support_smul): comap_domain f (r • v) hfrv = r • comap_domain f v hfv := by { ext, refl } /-- A version of `finsupp.comap_domain_smul` that's easier to use. -/ lemma comap_domain_smul_of_injective [add_monoid M] [monoid R] [distrib_mul_action R M] {f : α → β} (hf : function.injective f) (r : R) (v : β →₀ M) : comap_domain f (r • v) (hf.inj_on _) = r • comap_domain f v (hf.inj_on _) := comap_domain_smul _ _ _ _ end lemma sum_smul_index [semiring R] [add_comm_monoid M] {g : α →₀ R} {b : R} {h : α → R → M} (h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi a, h i (b * a)) := finsupp.sum_map_range_index h0 lemma sum_smul_index' [monoid R] [add_monoid M] [distrib_mul_action R M] [add_comm_monoid N] {g : α →₀ M} {b : R} {h : α → M → N} (h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi c, h i (b • c)) := finsupp.sum_map_range_index h0 /-- A version of `finsupp.sum_smul_index'` for bundled additive maps. -/ lemma sum_smul_index_add_monoid_hom [monoid R] [add_monoid M] [add_comm_monoid N] [distrib_mul_action R M] {g : α →₀ M} {b : R} {h : α → M →+ N} : (b • g).sum (λ a, h a) = g.sum (λ i c, h i (b • c)) := sum_map_range_index (λ i, (h i).map_zero) instance [semiring R] [add_comm_monoid M] [module R M] {ι : Type*} [no_zero_smul_divisors R M] : no_zero_smul_divisors R (ι →₀ M) := ⟨λ c f h, or_iff_not_imp_left.mpr (λ hc, finsupp.ext (λ i, (smul_eq_zero.mp (finsupp.ext_iff.mp h i)).resolve_left hc))⟩ section distrib_mul_action_hom variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid N] [distrib_mul_action R M] [distrib_mul_action R N] /-- `finsupp.single` as a `distrib_mul_action_hom`. See also `finsupp.lsingle` for the version as a linear map. -/ def distrib_mul_action_hom.single (a : α) : M →+[R] (α →₀ M) := { map_smul' := λ k m, by simp only [add_monoid_hom.to_fun_eq_coe, single_add_hom_apply, smul_single], .. single_add_hom a } lemma distrib_mul_action_hom_ext {f g : (α →₀ M) →+[R] N} (h : ∀ (a : α) (m : M), f (single a m) = g (single a m)) : f = g := distrib_mul_action_hom.to_add_monoid_hom_injective $ add_hom_ext h /-- See note [partially-applied ext lemmas]. -/ @[ext] lemma distrib_mul_action_hom_ext' {f g : (α →₀ M) →+[R] N} (h : ∀ (a : α), f.comp (distrib_mul_action_hom.single a) = g.comp (distrib_mul_action_hom.single a)) : f = g := distrib_mul_action_hom_ext $ λ a, distrib_mul_action_hom.congr_fun (h a) end distrib_mul_action_hom section variables [has_zero R] /-- The `finsupp` version of `pi.unique`. -/ instance unique_of_right [subsingleton R] : unique (α →₀ R) := fun_like.coe_injective.unique /-- The `finsupp` version of `pi.unique_of_is_empty`. -/ instance unique_of_left [is_empty α] : unique (α →₀ R) := fun_like.coe_injective.unique end /-- Given an `add_comm_monoid M` and `s : set α`, `restrict_support_equiv s M` is the `equiv` between the subtype of finitely supported functions with support contained in `s` and the type of finitely supported functions from `s`. -/ def restrict_support_equiv (s : set α) (M : Type*) [add_comm_monoid M] : {f : α →₀ M // ↑f.support ⊆ s } ≃ (s →₀ M) := begin refine ⟨λf, subtype_domain (λx, x ∈ s) f.1, λ f, ⟨f.map_domain subtype.val, _⟩, _, _⟩, { refine set.subset.trans (finset.coe_subset.2 map_domain_support) _, rw [finset.coe_image, set.image_subset_iff], exact assume x hx, x.2 }, { rintros ⟨f, hf⟩, apply subtype.eq, ext a, dsimp only, refine classical.by_cases (assume h : a ∈ set.range (subtype.val : s → α), _) (assume h, _), { rcases h with ⟨x, rfl⟩, rw [map_domain_apply subtype.val_injective, subtype_domain_apply] }, { convert map_domain_notin_range _ _ h, rw [← not_mem_support_iff], refine mt _ h, exact assume ha, ⟨⟨a, hf ha⟩, rfl⟩ } }, { assume f, ext ⟨a, ha⟩, dsimp only, rw [subtype_domain_apply, map_domain_apply subtype.val_injective] } end /-- Given `add_comm_monoid M` and `e : α ≃ β`, `dom_congr e` is the corresponding `equiv` between `α →₀ M` and `β →₀ M`. This is `finsupp.equiv_congr_left` as an `add_equiv`. -/ @[simps apply] protected def dom_congr [add_comm_monoid M] (e : α ≃ β) : (α →₀ M) ≃+ (β →₀ M) := { to_fun := equiv_map_domain e, inv_fun := equiv_map_domain e.symm, left_inv := λ v, begin simp only [← equiv_map_domain_trans, equiv.self_trans_symm], exact equiv_map_domain_refl _ end, right_inv := begin assume v, simp only [← equiv_map_domain_trans, equiv.symm_trans_self], exact equiv_map_domain_refl _ end, map_add' := λ a b, by simp only [equiv_map_domain_eq_map_domain]; exact map_domain_add } @[simp] lemma dom_congr_refl [add_comm_monoid M] : finsupp.dom_congr (equiv.refl α) = add_equiv.refl (α →₀ M) := add_equiv.ext $ λ _, equiv_map_domain_refl _ @[simp] lemma dom_congr_symm [add_comm_monoid M] (e : α ≃ β) : (finsupp.dom_congr e).symm = (finsupp.dom_congr e.symm : (β →₀ M) ≃+ (α →₀ M)):= add_equiv.ext $ λ _, rfl @[simp] lemma dom_congr_trans [add_comm_monoid M] (e : α ≃ β) (f : β ≃ γ) : (finsupp.dom_congr e).trans (finsupp.dom_congr f) = (finsupp.dom_congr (e.trans f) : (α →₀ M) ≃+ _) := add_equiv.ext $ λ _, (equiv_map_domain_trans _ _ _).symm end finsupp namespace finsupp /-! ### Declarations about sigma types -/ section sigma variables {αs : ι → Type*} [has_zero M] (l : (Σ i, αs i) →₀ M) /-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `M` and an index element `i : ι`, `split l i` is the `i`th component of `l`, a finitely supported function from `as i` to `M`. This is the `finsupp` version of `sigma.curry`. -/ def split (i : ι) : αs i →₀ M := l.comap_domain (sigma.mk i) (λ x1 x2 _ _ hx, heq_iff_eq.1 (sigma.mk.inj hx).2) lemma split_apply (i : ι) (x : αs i) : split l i x = l ⟨i, x⟩ := begin dunfold split, rw comap_domain_apply end /-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `β`, `split_support l` is the finset of indices in `ι` that appear in the support of `l`. -/ def split_support : finset ι := l.support.image sigma.fst lemma mem_split_support_iff_nonzero (i : ι) : i ∈ split_support l ↔ split l i ≠ 0 := begin rw [split_support, mem_image, ne.def, ← support_eq_empty, ← ne.def, ← finset.nonempty_iff_ne_empty, split, comap_domain, finset.nonempty], simp only [exists_prop, finset.mem_preimage, exists_and_distrib_right, exists_eq_right, mem_support_iff, sigma.exists, ne.def] end /-- Given `l`, a finitely supported function from the sigma type `Σ i, αs i` to `β` and an `ι`-indexed family `g` of functions from `(αs i →₀ β)` to `γ`, `split_comp` defines a finitely supported function from the index type `ι` to `γ` given by composing `g i` with `split l i`. -/ def split_comp [has_zero N] (g : Π i, (αs i →₀ M) → N) (hg : ∀ i x, x = 0 ↔ g i x = 0) : ι →₀ N := { support := split_support l, to_fun := λ i, g i (split l i), mem_support_to_fun := begin intros i, rw [mem_split_support_iff_nonzero, not_iff_not, hg], end } lemma sigma_support : l.support = l.split_support.sigma (λ i, (l.split i).support) := by simp only [finset.ext_iff, split_support, split, comap_domain, mem_image, mem_preimage, sigma.forall, mem_sigma]; tauto lemma sigma_sum [add_comm_monoid N] (f : (Σ (i : ι), αs i) → M → N) : l.sum f = ∑ i in split_support l, (split l i).sum (λ (a : αs i) b, f ⟨i, a⟩ b) := by simp only [sum, sigma_support, sum_sigma, split_apply] variables {η : Type*} [fintype η] {ιs : η → Type*} [has_zero α] /-- On a `fintype η`, `finsupp.split` is an equivalence between `(Σ (j : η), ιs j) →₀ α` and `Π j, (ιs j →₀ α)`. This is the `finsupp` version of `equiv.Pi_curry`. -/ noncomputable def sigma_finsupp_equiv_pi_finsupp : ((Σ j, ιs j) →₀ α) ≃ Π j, (ιs j →₀ α) := { to_fun := split, inv_fun := λ f, on_finset (finset.univ.sigma (λ j, (f j).support)) (λ ji, f ji.1 ji.2) (λ g hg, finset.mem_sigma.mpr ⟨finset.mem_univ _, mem_support_iff.mpr hg⟩), left_inv := λ f, by { ext, simp [split] }, right_inv := λ f, by { ext, simp [split] } } @[simp] lemma sigma_finsupp_equiv_pi_finsupp_apply (f : (Σ j, ιs j) →₀ α) (j i) : sigma_finsupp_equiv_pi_finsupp f j i = f ⟨j, i⟩ := rfl /-- On a `fintype η`, `finsupp.split` is an additive equivalence between `(Σ (j : η), ιs j) →₀ α` and `Π j, (ιs j →₀ α)`. This is the `add_equiv` version of `finsupp.sigma_finsupp_equiv_pi_finsupp`. -/ noncomputable def sigma_finsupp_add_equiv_pi_finsupp {α : Type*} {ιs : η → Type*} [add_monoid α] : ((Σ j, ιs j) →₀ α) ≃+ Π j, (ιs j →₀ α) := { map_add' := λ f g, by { ext, simp }, .. sigma_finsupp_equiv_pi_finsupp } @[simp] lemma sigma_finsupp_add_equiv_pi_finsupp_apply {α : Type*} {ιs : η → Type*} [add_monoid α] (f : (Σ j, ιs j) →₀ α) (j i) : sigma_finsupp_add_equiv_pi_finsupp f j i = f ⟨j, i⟩ := rfl end sigma end finsupp section cast_finsupp variables [has_zero M] (f : α →₀ M) namespace nat @[simp, norm_cast] lemma cast_finsupp_prod [comm_semiring R] (g : α → M → ℕ) : (↑(f.prod g) : R) = f.prod (λ a b, ↑(g a b)) := nat.cast_prod _ _ @[simp, norm_cast] lemma cast_finsupp_sum [comm_semiring R] (g : α → M → ℕ) : (↑(f.sum g) : R) = f.sum (λ a b, ↑(g a b)) := nat.cast_sum _ _ end nat namespace int @[simp, norm_cast] lemma cast_finsupp_prod [comm_ring R] (g : α → M → ℤ) : (↑(f.prod g) : R) = f.prod (λ a b, ↑(g a b)) := int.cast_prod _ _ @[simp, norm_cast] lemma cast_finsupp_sum [comm_ring R] (g : α → M → ℤ) : (↑(f.sum g) : R) = f.sum (λ a b, ↑(g a b)) := int.cast_sum _ _ end int namespace rat @[simp, norm_cast] lemma cast_finsupp_sum [division_ring R] [char_zero R] (g : α → M → ℚ) : (↑(f.sum g) : R) = f.sum (λ a b, g a b) := cast_sum _ _ @[simp, norm_cast] lemma cast_finsupp_prod [field R] [char_zero R] (g : α → M → ℚ) : (↑(f.prod g) : R) = f.prod (λ a b, g a b) := cast_prod _ _ end rat end cast_finsupp
c19b62aaa093bdb03682925b6be494aa8b10f829
2de8c1580f92bb6c28b60135f589fe9d0513faba
/src/user_classes.lean
a185e232cfbf81d20e7c7328b9010520c4bc50ef
[]
no_license
FCL-lean/verification
44a52e40ab78b18654b8d61bb55c2c912a40d2f4
be02c698c0ca78b18762e3fe7749cdc72a55d197
refs/heads/master
1,585,960,207,309
1,560,259,990,000
1,560,259,990,000
155,650,137
0
0
null
1,541,039,704,000
1,541,038,972,000
Lean
UTF-8
Lean
false
false
692
lean
import algebra.ordered_group algebra.ordered_ring section old_structure_cmd set_option old_structure_cmd true class decidable_canonically_ordered_monoid (α : Type*) extends canonically_ordered_monoid α, decidable_linear_ordered_cancel_comm_monoid α class is_well_founded (α : Type*) (r : α → α → Prop) := (wf : well_founded r) class is_monomial_order (α : Type*) [has_add α] (r : α → α → Prop) := (monomial_order : ∀ a b : α, r a b → ∀ c : α, r (c + a) (c + b)) end old_structure_cmd instance : decidable_canonically_ordered_monoid ℕ := { ..nat.canonically_ordered_comm_semiring, ..nat.decidable_linear_ordered_cancel_comm_monoid }
01b9dd9c19081f46f69f202d10dddc3c4b4046a3
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/1850.lean
b3511b52226c17707027102f25e7ab6de0971c9d
[ "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
77
lean
example : Nat := let n := 0 n.succ + (m |>.succ) + m.succ where m := 1
2a54710029a715677d0801bf807356a181c337cf
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Meta/CollectFVars.lean
c6339bc4822a68cba8e1397151f1c45d775a29de
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
1,295
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Util.CollectFVars import Lean.Meta.Basic namespace Lean.Meta open Meta def collectUsedFVars (e : Expr) : StateRefT CollectFVars.State MetaM Unit := do let e ← instantiateMVars e modify fun used => collectFVars used e def collectUsedFVarsAtFVars (fvars : Array Expr) : StateRefT CollectFVars.State MetaM Unit := fvars.forM fun fvar => do let fvarType ← inferType fvar collectUsedFVars fvarType def removeUnused (vars : Array Expr) (used : CollectFVars.State) : MetaM (LocalContext × LocalInstances × Array Expr) := do let localInsts ← getLocalInstances let lctx ← getLCtx let (lctx, localInsts, newVars, _) ← vars.foldrM (fun var (lctx, localInsts, newVars, used) => do if used.fvarSet.contains var.fvarId! then let varType ← inferType var let (_, used) ← (collectUsedFVars varType).run used pure (lctx, localInsts, newVars.push var, used) else pure (lctx.erase var.fvarId!, localInsts.erase var.fvarId!, newVars, used)) (lctx, localInsts, #[], used) pure (lctx, localInsts, newVars.reverse) end Lean.Meta
03ad80e50678ebfd0a07ddc16ca3f45a655b78ef
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/analysis/normed_space/bounded_linear_maps.lean
c58e638af9ac324abdd4b867845fe41399cb92cb
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
13,620
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl Continuous linear functions -- functions between normed vector spaces which are bounded and linear. -/ import algebra.field import analysis.normed_space.operator_norm noncomputable theory local attribute [instance] classical.prop_decidable local notation f ` →_{`:50 a `} `:0 b := filter.tendsto f (nhds a) (nhds b) open filter (tendsto) open metric variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] variables {G : Type*} [normed_group G] [normed_space 𝕜 G] set_option class.instance_max_depth 70 structure is_bounded_linear_map (𝕜 : Type*) [normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] (f : E → F) extends is_linear_map 𝕜 f : Prop := (bound : ∃ M > 0, ∀ x : E, ∥ f x ∥ ≤ M * ∥ x ∥) lemma is_linear_map.with_bound {f : E → F} (hf : is_linear_map 𝕜 f) (M : ℝ) (h : ∀ x : E, ∥ f x ∥ ≤ M * ∥ x ∥) : is_bounded_linear_map 𝕜 f := ⟨ hf, classical.by_cases (assume : M ≤ 0, ⟨1, zero_lt_one, assume x, le_trans (h x) $ mul_le_mul_of_nonneg_right (le_trans this zero_le_one) (norm_nonneg x)⟩) (assume : ¬ M ≤ 0, ⟨M, lt_of_not_ge this, h⟩)⟩ /-- A continuous linear map satisfies `is_bounded_linear_map` -/ lemma continuous_linear_map.is_bounded_linear_map (f : E →L[𝕜] F) : is_bounded_linear_map 𝕜 f := { bound := f.bound, ..f.to_linear_map } namespace is_bounded_linear_map def to_linear_map (f : E → F) (h : is_bounded_linear_map 𝕜 f) : E →ₗ[𝕜] F := (is_linear_map.mk' _ h.to_is_linear_map) /-- Construct a continuous linear map from is_bounded_linear_map -/ def to_continuous_linear_map {f : E → F} (hf : is_bounded_linear_map 𝕜 f) : E →L[𝕜] F := { cont := let ⟨C, Cpos, hC⟩ := hf.bound in linear_map.continuous_of_bound _ C hC, ..to_linear_map f hf} lemma zero : is_bounded_linear_map 𝕜 (λ (x:E), (0:F)) := (0 : E →ₗ F).is_linear.with_bound 0 $ by simp [le_refl] lemma id : is_bounded_linear_map 𝕜 (λ (x:E), x) := linear_map.id.is_linear.with_bound 1 $ by simp [le_refl] lemma fst : is_bounded_linear_map 𝕜 (λ x : E × F, x.1) := begin refine (linear_map.fst 𝕜 E F).is_linear.with_bound 1 (λx, _), rw one_mul, exact le_max_left _ _ end lemma snd : is_bounded_linear_map 𝕜 (λ x : E × F, x.2) := begin refine (linear_map.snd 𝕜 E F).is_linear.with_bound 1 (λx, _), rw one_mul, exact le_max_right _ _ end variables { f g : E → F } lemma smul (c : 𝕜) (hf : is_bounded_linear_map 𝕜 f) : is_bounded_linear_map 𝕜 (λ e, c • f e) := let ⟨hlf, M, hMp, hM⟩ := hf in (c • hlf.mk' f).is_linear.with_bound (∥c∥ * M) $ assume x, calc ∥c • f x∥ = ∥c∥ * ∥f x∥ : norm_smul c (f x) ... ≤ ∥c∥ * (M * ∥x∥) : mul_le_mul_of_nonneg_left (hM _) (norm_nonneg _) ... = (∥c∥ * M) * ∥x∥ : (mul_assoc _ _ _).symm lemma neg (hf : is_bounded_linear_map 𝕜 f) : is_bounded_linear_map 𝕜 (λ e, -f e) := begin rw show (λ e, -f e) = (λ e, (-1 : 𝕜) • f e), { funext, simp }, exact smul (-1) hf end lemma add (hf : is_bounded_linear_map 𝕜 f) (hg : is_bounded_linear_map 𝕜 g) : is_bounded_linear_map 𝕜 (λ e, f e + g e) := let ⟨hlf, Mf, hMfp, hMf⟩ := hf in let ⟨hlg, Mg, hMgp, hMg⟩ := hg in (hlf.mk' _ + hlg.mk' _).is_linear.with_bound (Mf + Mg) $ assume x, calc ∥f x + g x∥ ≤ ∥f x∥ + ∥g x∥ : norm_triangle _ _ ... ≤ Mf * ∥x∥ + Mg * ∥x∥ : add_le_add (hMf x) (hMg x) ... ≤ (Mf + Mg) * ∥x∥ : by rw add_mul lemma sub (hf : is_bounded_linear_map 𝕜 f) (hg : is_bounded_linear_map 𝕜 g) : is_bounded_linear_map 𝕜 (λ e, f e - g e) := add hf (neg hg) lemma comp {g : F → G} (hg : is_bounded_linear_map 𝕜 g) (hf : is_bounded_linear_map 𝕜 f) : is_bounded_linear_map 𝕜 (g ∘ f) := let ⟨hlg, Mg, hMgp, hMg⟩ := hg in let ⟨hlf, Mf, hMfp, hMf⟩ := hf in ((hlg.mk' _).comp (hlf.mk' _)).is_linear.with_bound (Mg * Mf) $ assume x, calc ∥g (f x)∥ ≤ Mg * ∥f x∥ : hMg _ ... ≤ Mg * (Mf * ∥x∥) : mul_le_mul_of_nonneg_left (hMf _) (le_of_lt hMgp) ... = Mg * Mf * ∥x∥ : (mul_assoc _ _ _).symm lemma tendsto (x : E) (hf : is_bounded_linear_map 𝕜 f) : f →_{x} (f x) := let ⟨hf, M, hMp, hM⟩ := hf in tendsto_iff_norm_tendsto_zero.2 $ squeeze_zero (assume e, norm_nonneg _) (assume e, calc ∥f e - f x∥ = ∥hf.mk' f (e - x)∥ : by rw (hf.mk' _).map_sub e x; refl ... ≤ M * ∥e - x∥ : hM (e - x)) (suffices (λ (e : E), M * ∥e - x∥) →_{x} (M * 0), by simpa, tendsto_mul tendsto_const_nhds (lim_norm _)) lemma continuous (hf : is_bounded_linear_map 𝕜 f) : continuous f := continuous_iff_continuous_at.2 $ λ _, hf.tendsto _ lemma lim_zero_bounded_linear_map (hf : is_bounded_linear_map 𝕜 f) : (f →_{0} 0) := (hf.1.mk' _).map_zero ▸ continuous_iff_continuous_at.1 hf.continuous 0 section open asymptotics filter theorem is_O_id {f : E → F} (h : is_bounded_linear_map 𝕜 f) (l : filter E) : is_O f (λ x, x) l := let ⟨M, hMp, hM⟩ := h.bound in ⟨M, hMp, mem_sets_of_superset univ_mem_sets (λ x _, hM x)⟩ theorem is_O_comp {g : F → G} (hg : is_bounded_linear_map 𝕜 g) {f : E → F} (l : filter E) : is_O (λ x', g (f x')) f l := ((hg.is_O_id ⊤).comp _).mono (map_le_iff_le_comap.mp lattice.le_top) theorem is_O_sub {f : E → F} (h : is_bounded_linear_map 𝕜 f) (l : filter E) (x : E) : is_O (λ x', f (x' - x)) (λ x', x' - x) l := is_O_comp h l end end is_bounded_linear_map section set_option class.instance_max_depth 180 lemma is_bounded_linear_map_prod_iso : is_bounded_linear_map 𝕜 (λ(p : (E →L[𝕜] F) × (E →L[𝕜] G)), (continuous_linear_map.prod p.1 p.2 : (E →L[𝕜] (F × G)))) := begin refine is_linear_map.with_bound ⟨λu v, rfl, λc u, rfl⟩ 1 (λp, _), simp only [norm, one_mul], refine continuous_linear_map.op_norm_le_bound _ (le_trans (norm_nonneg _) (le_max_left _ _)) (λu, _), simp only [norm, continuous_linear_map.prod, max_le_iff], split, { calc ∥p.1 u∥ ≤ ∥p.1∥ * ∥u∥ : continuous_linear_map.le_op_norm _ _ ... ≤ max (∥p.1∥) (∥p.2∥) * ∥u∥ : mul_le_mul_of_nonneg_right (le_max_left _ _) (norm_nonneg _) }, { calc ∥p.2 u∥ ≤ ∥p.2∥ * ∥u∥ : continuous_linear_map.le_op_norm _ _ ... ≤ max (∥p.1∥) (∥p.2∥) * ∥u∥ : mul_le_mul_of_nonneg_right (le_max_right _ _) (norm_nonneg _) } end lemma continuous_linear_map.is_bounded_linear_map_comp_left (g : continuous_linear_map 𝕜 F G) : is_bounded_linear_map 𝕜 (λ(f : E →L[𝕜] F), continuous_linear_map.comp g f) := begin refine is_linear_map.with_bound ⟨λu v, _, λc u, _⟩ (∥g∥) (λu, continuous_linear_map.op_norm_comp_le _ _), { ext x, change g ((u+v) x) = g (u x) + g (v x), have : (u+v) x = u x + v x := rfl, rw [this, g.map_add] }, { ext x, change g ((c • u) x) = c • g (u x), have : (c • u) x = c • u x := rfl, rw [this, continuous_linear_map.map_smul] } end lemma continuous_linear_map.is_bounded_linear_map_comp_right (f : continuous_linear_map 𝕜 E F) : is_bounded_linear_map 𝕜 (λ(g : F →L[𝕜] G), continuous_linear_map.comp g f) := begin refine is_linear_map.with_bound ⟨λu v, rfl, λc u, rfl⟩ (∥f∥) (λg, _), rw mul_comm, exact continuous_linear_map.op_norm_comp_le _ _ end end section bilinear_map variable (𝕜) structure is_bounded_bilinear_map (f : E × F → G) : Prop := (add_left : ∀(x₁ x₂ : E) (y : F), f (x₁ + x₂, y) = f (x₁, y) + f (x₂, y)) (smul_left : ∀(c : 𝕜) (x : E) (y : F), f (c • x, y) = c • f (x,y)) (add_right : ∀(x : E) (y₁ y₂ : F), f (x, y₁ + y₂) = f (x, y₁) + f (x, y₂)) (smul_right : ∀(c : 𝕜) (x : E) (y : F), f (x, c • y) = c • f (x,y)) (bound : ∃C>0, ∀(x : E) (y : F), ∥f (x, y)∥ ≤ C * ∥x∥ * ∥y∥) variable {𝕜} variable {f : E × F → G} lemma is_bounded_bilinear_map.map_sub_left (h : is_bounded_bilinear_map 𝕜 f) {x y : E} {z : F} : f (x - y, z) = f (x, z) - f(y, z) := calc f (x - y, z) = f (x + (-1 : 𝕜) • y, z) : by simp ... = f (x, z) + (-1 : 𝕜) • f (y, z) : by simp only [h.add_left, h.smul_left] ... = f (x, z) - f (y, z) : by simp lemma is_bounded_bilinear_map.map_sub_right (h : is_bounded_bilinear_map 𝕜 f) {x : E} {y z : F} : f (x, y - z) = f (x, y) - f (x, z) := calc f (x, y - z) = f (x, y + (-1 : 𝕜) • z) : by simp ... = f (x, y) + (-1 : 𝕜) • f (x, z) : by simp only [h.add_right, h.smul_right] ... = f (x, y) - f (x, z) : by simp lemma is_bounded_bilinear_map_smul : is_bounded_bilinear_map 𝕜 (λ (p : 𝕜 × E), p.1 • p.2) := { add_left := add_smul, smul_left := λc x y, by simp [smul_smul], add_right := smul_add, smul_right := λc x y, by simp [smul_smul, mul_comm], bound := ⟨1, zero_lt_one, λx y, by simp [norm_smul]⟩ } lemma is_bounded_bilinear_map_mul : is_bounded_bilinear_map 𝕜 (λ (p : 𝕜 × 𝕜), p.1 * p.2) := is_bounded_bilinear_map_smul lemma is_bounded_bilinear_map_comp : is_bounded_bilinear_map 𝕜 (λ(p : (E →L[𝕜] F) × (F →L[𝕜] G)), p.2.comp p.1) := { add_left := λx₁ x₂ y, begin ext z, change y (x₁ z + x₂ z) = y (x₁ z) + y (x₂ z), rw y.map_add end, smul_left := λc x y, begin ext z, change y (c • (x z)) = c • y (x z), rw continuous_linear_map.map_smul end, add_right := λx y₁ y₂, rfl, smul_right := λc x y, rfl, bound := ⟨1, zero_lt_one, λx y, calc ∥continuous_linear_map.comp ((x, y).snd) ((x, y).fst)∥ ≤ ∥y∥ * ∥x∥ : continuous_linear_map.op_norm_comp_le _ _ ... = 1 * ∥x∥ * ∥ y∥ : by ring ⟩ } lemma is_bounded_bilinear_map_apply : is_bounded_bilinear_map 𝕜 (λp : (E →L[𝕜] F) × E, p.1 p.2) := { add_left := by simp, smul_left := by simp, add_right := by simp, smul_right := by simp, bound := ⟨1, zero_lt_one, by simp [continuous_linear_map.le_op_norm]⟩ } /-- Definition of the derivative of a bilinear map `f`, given at a point `p` by `q ↦ f(p.1, q.2) + f(q.1, p.2)` as in the standard formula for the derivative of a product. We define this function here a bounded linear map from `E × F` to `G`. The fact that this is indeed the derivative of `f` is proved in `is_bounded_bilinear_map.has_fderiv_at` in `deriv.lean`-/ def is_bounded_bilinear_map.linear_deriv (h : is_bounded_bilinear_map 𝕜 f) (p : E × F) : (E × F) →ₗ[𝕜] G := { to_fun := λq, f (p.1, q.2) + f (q.1, p.2), add := λq₁ q₂, begin change f (p.1, q₁.2 + q₂.2) + f (q₁.1 + q₂.1, p.2) = f (p.1, q₁.2) + f (q₁.1, p.2) + (f (p.1, q₂.2) + f (q₂.1, p.2)), simp [h.add_left, h.add_right] end, smul := λc q, begin change f (p.1, c • q.2) + f (c • q.1, p.2) = c • (f (p.1, q.2) + f (q.1, p.2)), simp [h.smul_left, h.smul_right, smul_add] end } def is_bounded_bilinear_map.deriv (h : is_bounded_bilinear_map 𝕜 f) (p : E × F) : (E × F) →L[𝕜] G := (h.linear_deriv p).with_bound $ begin rcases h.bound with ⟨C, Cpos, hC⟩, refine ⟨C * ∥p.1∥ + C * ∥p.2∥, λq, _⟩, calc ∥f (p.1, q.2) + f (q.1, p.2)∥ ≤ ∥f (p.1, q.2)∥ + ∥f (q.1, p.2)∥ : norm_triangle _ _ ... ≤ C * ∥p.1∥ * ∥q.2∥ + C * ∥q.1∥ * ∥p.2∥ : add_le_add (hC _ _) (hC _ _) ... ≤ C * ∥p.1∥ * ∥q∥ + C * ∥q∥ * ∥p.2∥ : begin apply add_le_add, exact mul_le_mul_of_nonneg_left (le_max_right _ _) (mul_nonneg (le_of_lt Cpos) (norm_nonneg _)), apply mul_le_mul_of_nonneg_right _ (norm_nonneg _), exact mul_le_mul_of_nonneg_left (le_max_left _ _) (le_of_lt Cpos), end ... = (C * ∥p.1∥ + C * ∥p.2∥) * ∥q∥ : by ring end @[simp] lemma is_bounded_bilinear_map_deriv_coe (h : is_bounded_bilinear_map 𝕜 f) (p q : E × F) : h.deriv p q = f (p.1, q.2) + f (q.1, p.2) := rfl set_option class.instance_max_depth 95 /-- Given a bounded bilinear map `f`, the map associating to a point `p` the derivative of `f` at `p` is itself a bounded linear map. -/ lemma is_bounded_bilinear_map.is_bounded_linear_map_deriv (h : is_bounded_bilinear_map 𝕜 f) : is_bounded_linear_map 𝕜 (λp : E × F, h.deriv p) := begin rcases h.bound with ⟨C, Cpos, hC⟩, refine is_linear_map.with_bound ⟨λp₁ p₂, _, λc p, _⟩ (C + C) (λp, _), { ext q, simp [h.add_left, h.add_right] }, { ext q, simp [h.smul_left, h.smul_right, smul_add] }, { refine continuous_linear_map.op_norm_le_bound _ (mul_nonneg (add_nonneg (le_of_lt Cpos) (le_of_lt Cpos)) (norm_nonneg _)) (λq, _), calc ∥f (p.1, q.2) + f (q.1, p.2)∥ ≤ ∥f (p.1, q.2)∥ + ∥f (q.1, p.2)∥ : norm_triangle _ _ ... ≤ C * ∥p.1∥ * ∥q.2∥ + C * ∥q.1∥ * ∥p.2∥ : add_le_add (hC _ _) (hC _ _) ... ≤ C * ∥p∥ * ∥q∥ + C * ∥q∥ * ∥p∥ : by apply_rules [add_le_add, mul_le_mul, norm_nonneg, le_of_lt Cpos, le_refl, le_max_left, le_max_right, mul_nonneg, norm_nonneg, norm_nonneg, norm_nonneg] ... = (C + C) * ∥p∥ * ∥q∥ : by ring }, end end bilinear_map
b1f254b2eaea92bde782d7a52abbe2e3459f66a8
42610cc2e5db9c90269470365e6056df0122eaa0
/library/theories/finite_group_theory/extra_subgroup.lean
fe1d055b647c42f63c3ff16f95333789316b5d3d
[ "Apache-2.0" ]
permissive
tomsib2001/lean
2ab59bfaebd24a62109f800dcf4a7139ebd73858
eb639a7d53fb40175bea5c8da86b51d14bb91f76
refs/heads/master
1,586,128,387,740
1,468,968,950,000
1,468,968,950,000
61,027,234
0
0
null
1,465,813,585,000
1,465,813,585,000
null
UTF-8
Lean
false
false
11,135
lean
import data algebra.group data theories.finite_group_theory.subgroup open function eq.ops open set 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 -- variable (F : set A) -- variable [subgF : is_subgroup F] -- include subgF -- definition in_lcoset_of [reducible] H (a b : A) := a ∈ b ∘> H -- definition in_rcoset_of [reducible] H (a b : A) := a ∈ H <∘ b -- definition same_lcoset_of [reducible] H (a b : A) := a ∘> H = b ∘> H -- definition same_rcoset_of [reducible] H (a b : A) := H <∘ a = H <∘ b definition same_left_right_coset_on (F : set A) (N : set A) := ∀ x, x ∈ F → 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_of [class] (F : set A) [subgF : is_subgroup F] (N : set A) extends is_subgroup N := (normal : same_left_right_coset_on F N) end section subgroup -- variable {A : Type} -- variable [s : group A] -- include s -- variable {H : set A} -- variable [is_subg : is_subgroup H] -- include is_subg -- section set_reducible -- local attribute set [reducible] -- lemma subg_has_one : H (1 : A) := @is_subgroup.has_one A s H is_subg -- lemma subg_mul_closed : mul_closed_on H := @is_subgroup.mul_closed A s H is_subg -- lemma subg_has_inv : subgroup.has_inv H := @is_subgroup.has_inv A s H is_subg -- lemma subgroup_coset_id : ∀ a, a ∈ H → (a ∘> H = H ∧ H <∘ a = H) := -- take a, assume PHa : H a, -- have Pl : a ∘> H ⊆ H, from closed_lcontract a H subg_mul_closed PHa, -- have Pr : H <∘ a ⊆ H, from closed_rcontract a H subg_mul_closed PHa, -- have PHainv : H a⁻¹, from subg_has_inv a PHa, -- and.intro -- (ext (assume x, -- begin -- esimp [glcoset, mem], -- apply iff.intro, -- apply Pl, -- intro PHx, exact (subg_mul_closed a⁻¹ x PHainv PHx) -- end)) -- (ext (assume x, -- begin -- esimp [grcoset, mem], -- apply iff.intro, -- apply Pr, -- intro PHx, exact (subg_mul_closed x a⁻¹ PHx PHainv) -- end)) -- lemma subgroup_lcoset_id : ∀ a, a ∈ H → a ∘> H = H := -- take a, assume PHa : H a, -- and.left (subgroup_coset_id a PHa) -- lemma subgroup_rcoset_id : ∀ a, a ∈ H → H <∘ a = H := -- take a, assume PHa : H a, -- and.right (subgroup_coset_id a PHa) -- lemma subg_in_coset_refl (a : A) : a ∈ a ∘> H ∧ a ∈ H <∘ a := -- have PH1 : H 1, from subg_has_one, -- have PHinvaa : H (a⁻¹*a), from (eq.symm (mul.left_inv a)) ▸ PH1, -- have PHainva : H (a*a⁻¹), from (eq.symm (mul.right_inv a)) ▸ PH1, -- and.intro PHinvaa PHainva -- end set_reducible -- lemma subg_in_lcoset_same_lcoset (a b : A) : in_lcoset H a b → same_lcoset H a b := -- assume Pa_in_b : H (b⁻¹*a), -- have Pbinva : b⁻¹*a ∘> H = H, from subgroup_lcoset_id (b⁻¹*a) Pa_in_b, -- have Pb_binva : b ∘> b⁻¹*a ∘> H = b ∘> H, from Pbinva ▸ rfl, -- have Pbbinva : b*(b⁻¹*a)∘>H = b∘>H, from glcoset_compose b (b⁻¹*a) H ▸ Pb_binva, -- mul_inv_cancel_left b a ▸ Pbbinva -- lemma subg_same_lcoset_in_lcoset (a b : A) : same_lcoset H a b → in_lcoset H a b := -- assume Psame : a∘>H = b∘>H, -- have Pa : a ∈ a∘>H, from and.left (subg_in_coset_refl a), -- by exact (Psame ▸ Pa) -- lemma subg_lcoset_same (a b : A) : in_lcoset H a b = (a∘>H = b∘>H) := -- propext(iff.intro (subg_in_lcoset_same_lcoset a b) (subg_same_lcoset_in_lcoset a b)) -- lemma subg_rcoset_same (a b : A) : in_rcoset H a b = (H<∘a = H<∘b) := -- propext(iff.intro -- (assume Pa_in_b : H (a*b⁻¹), -- have Pabinv : H<∘a*b⁻¹ = H, from subgroup_rcoset_id (a*b⁻¹) Pa_in_b, -- have Pabinv_b : H <∘ a*b⁻¹ <∘ b = H <∘ b, from Pabinv ▸ rfl, -- have Pabinvb : H <∘ a*b⁻¹*b = H <∘ b, from grcoset_compose (a*b⁻¹) b H ▸ Pabinv_b, -- inv_mul_cancel_right a b ▸ Pabinvb) -- (assume Psame, -- have Pa : a ∈ H<∘a, from and.right (subg_in_coset_refl a), -- by exact (Psame ▸ Pa))) -- lemma subg_same_lcoset.refl (a : A) : same_lcoset H a a := rfl -- lemma subg_same_rcoset.refl (a : A) : same_rcoset H a a := rfl -- lemma subg_same_lcoset.symm (a b : A) : same_lcoset H a b → same_lcoset H b a := eq.symm -- lemma subg_same_rcoset.symm (a b : A) : same_rcoset H a b → same_rcoset H b a := eq.symm -- lemma subg_same_lcoset.trans (a b c : A) : same_lcoset H a b → same_lcoset H b c → same_lcoset H a c := -- eq.trans -- lemma subg_same_rcoset.trans (a b c : A) : same_rcoset H a b → same_rcoset H b c → same_rcoset H a c := -- eq.trans -- variable {S : set A} -- lemma subg_lcoset_subset_subg (Psub : S ⊆ H) (a : A) : a ∈ H → a ∘> S ⊆ H := -- assume Pin, have P : a ∘> S ⊆ a ∘> H, from glcoset_sub a S H Psub, -- subgroup_lcoset_id a Pin ▸ P end subgroup section normal_subg open quot variable {A : Type} variable [s : group A] include s variable (N : set A) variable (F : set A) variable [subgF : is_subgroup F] include subgF -- N is a normal subgroup of F variable [is_nsubg : is_normal_subgroup_of F N] include is_nsubg local notation a `~` b := same_lcoset N a b -- note : does not bind as strong as → lemma nsubg_normal_F : same_left_right_coset_on F N := @is_normal_subgroup_of.normal A s F subgF N is_nsubg lemma nsubg_same_lcoset_product_F : ∀ a1 a2 b1 b2, a1 ∈ F → a2 ∈ F → b1 ∈ F → b2 ∈ F → (a1 ~ b1) → (a2 ~ b2) → ((a1*a2) ~ (b1*b2)) := take a1 a2 b1 b2 Ha1 Ha2 Hb1 Hb2, assume Psame1 : a1 ∘> N = b1 ∘> N, assume Psame2 : a2 ∘> N = b2 ∘> N, have Hb1b2 : b1 * b2 ∈ F, from begin apply subg_mul_closed, exact Hb1, exact Hb2 end, calc a1*a2 ∘> N = a1 ∘> a2 ∘> N : glcoset_compose ... = a1 ∘> b2 ∘> N : by rewrite Psame2 ... = a1 ∘> (N <∘ b2) : by rewrite (nsubg_normal_F N F b2 Hb2) ... = (a1 ∘> N) <∘ b2 : by rewrite lcoset_rcoset_assoc ... = (b1 ∘> N) <∘ b2 : by rewrite Psame1 ... = N <∘ b1 <∘ b2 : by rewrite (nsubg_normal_F N F b1 Hb1) ... = N <∘ (b1*b2) : by rewrite grcoset_compose ... = (b1*b2) ∘> N : by rewrite (nsubg_normal_F N F (b1*b2) Hb1b2) example (a b : A) : (a⁻¹ ~ b⁻¹) = (a⁻¹ ∘> N = b⁻¹ ∘> N) := rfl lemma nsubg_same_lcoset_inv_F : ∀ a b, a ∈ F → b ∈ F → (a ~ b) → (a⁻¹ ~ b⁻¹) := take a b Ha Hb, assume Psame : a ∘> N = b ∘> N, have Hbinv : b⁻¹ ∈ F, from begin apply subg_has_inv, exact Hb end, 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_F N F (b⁻¹) Hbinv) ... = (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_F N F (b⁻¹) Hbinv) definition nsubg_setoid_F [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_onF : Type := quot (nsubg_setoid_F N F) -- check coset_of_onF -- 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 -- 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
a8b4095b01e25f1f962f5b52625ccb083cd9bd50
f5f7e6fae601a5fe3cac7cc3ed353ed781d62419
/src/category_theory/opposites.lean
ff936471b41f6bdeeb2a502cc80c85058a4c5e8f
[ "Apache-2.0" ]
permissive
EdAyers/mathlib
9ecfb2f14bd6caad748b64c9c131befbff0fb4e0
ca5d4c1f16f9c451cf7170b10105d0051db79e1b
refs/heads/master
1,626,189,395,845
1,555,284,396,000
1,555,284,396,000
144,004,030
0
0
Apache-2.0
1,533,727,664,000
1,533,727,663,000
null
UTF-8
Lean
false
false
7,558
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison import category_theory.products import category_theory.types import category_theory.natural_isomorphism namespace category_theory universes v₁ v₂ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation /-- The type of objects of the opposite of C (which should be a category). In order to avoid confusion between C and its opposite category, we set up the type of objects `opposite C` using the following pattern, which will be repeated later for the morphisms. 1. Define `opposite C := C`. 2. Define the isomorphisms `op : C → opposite C`, `unop : opposite C → C`. 3. Make the definition `opposite` irreducible. This has the following consequences. * `opposite C` and `C` are distinct types in the elaborator, so you must use `op` and `unop` explicitly to convert between them. * Both `unop (op X) = X` and `op (unop X) = X` are definitional equalities. Notably, every object of the opposite category is definitionally of the form `op X`, which greatly simplifies the definition of the structure of the opposite category, for example. (If Lean supported definitional eta equality for records, we could achieve the same goals using a structure with one field.) -/ def opposite (C : Sort u₁) : Sort u₁ := C -- Use a high right binding power (like that of postfix ⁻¹) so that, for example, -- `presheaf Cᵒᵖ` parses as `presheaf (Cᵒᵖ)` and not `(presheaf C)ᵒᵖ`. notation C `ᵒᵖ`:std.prec.max_plus := opposite C variables {C : Sort u₁} def op (X : C) : Cᵒᵖ := X def unop (X : Cᵒᵖ) : C := X attribute [irreducible] opposite @[simp] lemma unop_op (X : C) : unop (op X) = X := rfl @[simp] lemma op_unop (X : Cᵒᵖ) : op (unop X) = X := rfl lemma op_inj : function.injective (@op C) := by { rintros _ _ ⟨ ⟩, refl } lemma unop_inj : function.injective (@unop C) := by { rintros _ _ ⟨ ⟩, refl } section has_hom variables [𝒞 : has_hom.{v₁} C] include 𝒞 /-- The hom types of the opposite of a category (or graph). As with the objects, we'll make this irreducible below. Use `f.op` and `f.unop` to convert between morphisms of C and morphisms of Cᵒᵖ. -/ instance has_hom.opposite : has_hom Cᵒᵖ := { hom := λ X Y, unop Y ⟶ unop X } def has_hom.hom.op {X Y : C} (f : X ⟶ Y) : op Y ⟶ op X := f def has_hom.hom.unop {X Y : Cᵒᵖ} (f : X ⟶ Y) : unop Y ⟶ unop X := f attribute [irreducible] has_hom.opposite lemma has_hom.hom.op_inj {X Y : C} : function.injective (has_hom.hom.op : (X ⟶ Y) → (op Y ⟶ op X)) := λ _ _ H, congr_arg has_hom.hom.unop H lemma has_hom.hom.unop_inj {X Y : Cᵒᵖ} : function.injective (has_hom.hom.unop : (X ⟶ Y) → (unop Y ⟶ unop X)) := λ _ _ H, congr_arg has_hom.hom.op H @[simp] lemma has_hom.hom.unop_op {X Y : C} {f : X ⟶ Y} : f.op.unop = f := rfl @[simp] lemma has_hom.hom.op_unop {X Y : Cᵒᵖ} {f : X ⟶ Y} : f.unop.op = f := rfl end has_hom variables [𝒞 : category.{v₁} C] include 𝒞 instance category.opposite : category.{v₁} Cᵒᵖ := { comp := λ _ _ _ f g, (g.unop ≫ f.unop).op, id := λ X, (𝟙 (unop X)).op } @[simp] lemma op_comp {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} : (f ≫ g).op = g.op ≫ f.op := rfl @[simp] lemma op_id {X : C} : (𝟙 X).op = 𝟙 (op X) := rfl @[simp] lemma unop_comp {X Y Z : Cᵒᵖ} {f : X ⟶ Y} {g : Y ⟶ Z} : (f ≫ g).unop = g.unop ≫ f.unop := rfl @[simp] lemma unop_id {X : Cᵒᵖ} : (𝟙 X).unop = 𝟙 (unop X) := rfl @[simp] lemma unop_id_op {X : C} : (𝟙 (op X)).unop = 𝟙 X := rfl @[simp] lemma op_id_unop {X : Cᵒᵖ} : (𝟙 (unop X)).op = 𝟙 X := rfl def op_op : (Cᵒᵖ)ᵒᵖ ⥤ C := { obj := λ X, unop (unop X), map := λ X Y f, f.unop.unop } -- TODO this is an equivalence namespace functor section variables {D : Sort u₂} [𝒟 : category.{v₂} D] include 𝒟 variables {C D} protected definition op (F : C ⥤ D) : Cᵒᵖ ⥤ Dᵒᵖ := { obj := λ X, op (F.obj (unop X)), map := λ X Y f, (F.map f.unop).op } @[simp] lemma op_obj (F : C ⥤ D) (X : Cᵒᵖ) : (F.op).obj X = op (F.obj (unop X)) := rfl @[simp] lemma op_map (F : C ⥤ D) {X Y : Cᵒᵖ} (f : X ⟶ Y) : (F.op).map f = (F.map f.unop).op := rfl protected definition unop (F : Cᵒᵖ ⥤ Dᵒᵖ) : C ⥤ D := { obj := λ X, unop (F.obj (op X)), map := λ X Y f, (F.map f.op).unop } @[simp] lemma unop_obj (F : Cᵒᵖ ⥤ Dᵒᵖ) (X : C) : (F.unop).obj X = unop (F.obj (op X)) := rfl @[simp] lemma unop_map (F : Cᵒᵖ ⥤ Dᵒᵖ) {X Y : C} (f : X ⟶ Y) : (F.unop).map f = (F.map f.op).unop := rfl variables (C D) definition op_hom : (C ⥤ D)ᵒᵖ ⥤ (Cᵒᵖ ⥤ Dᵒᵖ) := { obj := λ F, (unop F).op, map := λ F G α, { app := λ X, (α.unop.app (unop X)).op, naturality' := λ X Y f, has_hom.hom.unop_inj $ eq.symm (α.unop.naturality f.unop) } } @[simp] lemma op_hom.obj (F : (C ⥤ D)ᵒᵖ) : (op_hom C D).obj F = (unop F).op := rfl @[simp] lemma op_hom.map_app {F G : (C ⥤ D)ᵒᵖ} (α : F ⟶ G) (X : Cᵒᵖ) : ((op_hom C D).map α).app X = (α.unop.app (unop X)).op := rfl definition op_inv : (Cᵒᵖ ⥤ Dᵒᵖ) ⥤ (C ⥤ D)ᵒᵖ := { obj := λ F, op F.unop, map := λ F G α, has_hom.hom.op { app := λ X, (α.app (op X)).unop, naturality' := λ X Y f, has_hom.hom.op_inj $ eq.symm (α.naturality f.op) } } @[simp] lemma op_inv.obj (F : Cᵒᵖ ⥤ Dᵒᵖ) : (op_inv C D).obj F = op F.unop := rfl @[simp] lemma op_inv.map_app {F G : Cᵒᵖ ⥤ Dᵒᵖ} (α : F ⟶ G) (X : C) : (((op_inv C D).map α).unop).app X = (α.app (op X)).unop := rfl -- TODO show these form an equivalence instance {F : C ⥤ D} [full F] : full F.op := { preimage := λ X Y f, (F.preimage f.unop).op } instance {F : C ⥤ D} [faithful F] : faithful F.op := { injectivity' := λ X Y f g h, has_hom.hom.unop_inj $ by simpa using injectivity F (has_hom.hom.op_inj h) } end section omit 𝒞 variables (E : Type u₁) [ℰ : category.{v₁+1} E] include ℰ /-- `functor.hom` is the hom-pairing, sending (X,Y) to X → Y, contravariant in X and covariant in Y. -/ definition hom : Eᵒᵖ × E ⥤ Type v₁ := { obj := λ p, unop p.1 ⟶ p.2, map := λ X Y f, λ h, f.1.unop ≫ h ≫ f.2 } @[simp] lemma hom_obj (X : Eᵒᵖ × E) : (functor.hom E).obj X = (unop X.1 ⟶ X.2) := rfl @[simp] lemma hom_pairing_map {X Y : Eᵒᵖ × E} (f : X ⟶ Y) : (functor.hom E).map f = λ h, f.1.unop ≫ h ≫ f.2 := rfl end end functor -- TODO the following definitions do not belong here omit 𝒞 variables (E : Type u₁) instance opposite.has_one [has_one E] : has_one (Eᵒᵖ) := { one := op 1 } instance opposite.has_mul [has_mul E] : has_mul (Eᵒᵖ) := { mul := λ x y, op $ unop y * unop x } @[simp] lemma opposite.unop_one [has_one E] : unop (1 : Eᵒᵖ) = (1 : E) := rfl @[simp] lemma opposite.unop_mul [has_mul E] (xs ys : Eᵒᵖ) : unop (xs * ys) = (unop ys * unop xs : E) := rfl @[simp] lemma opposite.op_one [has_one E] : op (1 : E) = 1 := rfl @[simp] lemma opposite.op_mul [has_mul E] (xs ys : E) : op (xs * ys) = (op ys * op xs) := rfl instance opposite.monoid [monoid E] : monoid (Eᵒᵖ) := { one := op 1, mul := λ x y, op $ unop y * unop x, mul_one := by { intros, apply unop_inj, simp }, one_mul := by { intros, simp }, mul_assoc := by { intros, simp [mul_assoc], } } end category_theory
96a2e6328c1e0225b13758fdc47cd280c0a7dfd8
618003631150032a5676f229d13a079ac875ff77
/src/linear_algebra/quadratic_form.lean
d47eaa8b09650e4e1bd1876211b6ae4c5670a8c4
[ "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
14,364
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Anne Baanen -/ import algebra.invertible import linear_algebra.bilinear_form import linear_algebra.determinant import linear_algebra.special_linear_group /-! # Quadratic forms This file defines quadratic forms over a `R`-module `M`. A quadratic form is a map `Q : M → R` such that (`to_fun_smul`) `Q (a • x) = a * a * Q x` (`polar_...`) The map `polar Q := λ x y, Q (x + y) - Q x - Q y` is bilinear. They come with a scalar multiplication, `(a • Q) x = Q (a • x) = a * a * Q x`, and composition with linear maps `f`, `Q.comp f x = Q (f x)`. ## Main definitions * `quadratic_form.associated`: associated bilinear form * `quadratic_form.pos_def`: positive definite quadratic forms * `quadratic_form.discr`: discriminant of a quadratic form ## Main statements * `quadratic_form.associated_left_inverse`, * `quadratic_form.associated_right_inverse`: in a commutative ring where 2 has an inverse, there is a correspondence between quadratic forms and symmetric bilinear forms ## Notation In this file, the variable `R` is used when a `ring` structure is sufficient and `R₁` is used when specifically a `comm_ring` is required. This allows us to keep `[module R M]` and `[module R₁ M]` assumptions in the variables without confusion between `*` from `ring` and `*` from `comm_ring`. ## References * https://en.wikipedia.org/wiki/Quadratic_form * https://en.wikipedia.org/wiki/Discriminant#Quadratic_forms ## Tags quadratic form, homogeneous polynomial, quadratic polynomial -/ universes u v w variables {R : Type u} {M : Type v} [add_comm_group M] [ring R] variables {R₁ : Type u} [comm_ring R₁] [module R₁ M] /-- Up to a factor 2, `Q.polar` is the associated bilinear form for a quadratic form `Q`.d Source of this name: https://en.wikipedia.org/wiki/Quadratic_form#Generalization -/ def quadratic_form.polar (f : M → R) (x y : M) := f (x + y) - f x - f y variables [module R M] open quadratic_form /-- A quadratic form over a module. -/ structure quadratic_form (R : Type u) (M : Type v) [ring R] [add_comm_group M] [module R M] := (to_fun : M → R) (to_fun_smul : ∀ (a : R) (x : M), to_fun (a • x) = a * a * to_fun x) (polar_add_left : ∀ (x x' y : M), polar to_fun (x + x') y = polar to_fun x y + polar to_fun x' y) (polar_smul_left : ∀ (a : R) (x y : M), polar to_fun (a • x) y = a • polar to_fun x y) (polar_add_right : ∀ (x y y' : M), polar to_fun x (y + y') = polar to_fun x y + polar to_fun x y') (polar_smul_right : ∀ (a : R) (x y : M), polar to_fun x (a • y) = a • polar to_fun x y) namespace quadratic_form variables {Q : quadratic_form R M} instance : has_coe_to_fun (quadratic_form R M) := ⟨_, λ B, B.to_fun⟩ /-- The `simp` normal form for a quadratic form is `coe_fn`, not `to_fun`. -/ @[simp] lemma to_fun_eq_apply : Q.to_fun = ⇑ Q := rfl lemma map_smul (a : R) (x : M) : Q (a • x) = a * a * Q x := Q.to_fun_smul a x lemma map_add_self (x : M) : Q (x + x) = 4 * Q x := by { rw [←one_smul R x, ←add_smul, map_smul], norm_num } lemma map_zero : Q 0 = 0 := by rw [←@zero_smul R _ _ _ _ (0 : M), map_smul, zero_mul, zero_mul] lemma map_neg (x : M) : Q (-x) = Q x := by rw [←@neg_one_smul R _ _ _ _ x, map_smul, neg_one_mul, neg_neg, one_mul] lemma map_sub (x y : M) : Q (x - y) = Q (y - x) := by rw [←neg_sub, map_neg] variable {Q' : quadratic_form R M} @[ext] lemma ext (H : ∀ (x : M), Q x = Q' x) : Q = Q' := by { cases Q, cases Q', congr, funext, apply H } instance : has_zero (quadratic_form R M) := ⟨ { to_fun := λ x, 0, to_fun_smul := λ a x, by simp, polar_add_left := λ x x' y, by simp [polar], polar_smul_left := λ a x y, by simp [polar], polar_add_right := λ x y y', by simp [polar], polar_smul_right := λ a x y, by simp [polar] } ⟩ instance : inhabited (quadratic_form R M) := ⟨0⟩ instance : has_scalar R₁ (quadratic_form R₁ M) := ⟨ λ a Q, { to_fun := λ x, Q (a • x), to_fun_smul := λ b x, by rw [smul_comm, map_smul], polar_add_left := λ x x' y, by convert Q.polar_add_left (a • x) (a • x') (a • y) using 1; simp [polar, smul_add], polar_smul_left := λ b x y, by convert Q.polar_smul_left b (a • x) (a • y) using 1; simp [polar, smul_add, smul_comm], polar_add_right := λ x y y', by convert Q.polar_add_right (a • x) (a • y) (a • y') using 1; simp [polar, smul_add], polar_smul_right := λ b x y, by convert Q.polar_smul_right b (a • x) (a • y) using 1; simp [polar, smul_add, smul_comm] } ⟩ @[simp] lemma smul_apply (a : R₁) (Q : quadratic_form R₁ M) (x : M) : (a • Q) x = Q (a • x) := rfl instance : mul_action R₁ (quadratic_form R₁ M) := { mul_smul := λ a b Q, ext (λ x, by simp [mul_smul, smul_comm]), one_smul := λ Q, ext (λ x, by simp), ..quadratic_form.has_scalar } section comp variables {N : Type v} [add_comm_group N] [module R N] /-- Compose the quadratic form with a linear function. -/ def comp (Q : quadratic_form R N) (f : M →ₗ[R] N) : quadratic_form R M := { to_fun := λ x, Q (f x), to_fun_smul := λ a x, by simp [map_smul], polar_add_left := λ x x' y, by convert Q.polar_add_left (f x) (f x') (f y) using 1; simp [polar], polar_smul_left := λ a x y, by convert Q.polar_smul_left a (f x) (f y) using 1; simp [polar], polar_add_right := λ x y y', by convert Q.polar_add_right (f x) (f y) (f y') using 1; simp [polar], polar_smul_right := λ a x y, by convert Q.polar_smul_right a (f x) (f y) using 1; simp [polar] } @[simp] lemma comp_apply (Q : quadratic_form R N) (f : M →ₗ[R] N) (x : M) : (Q.comp f) x = Q (f x) := rfl end comp end quadratic_form /-! ### Associated bilinear forms Over a commutative ring with an inverse of 2, the theory of quadratic forms is basically identical to that of symmetric bilinear forms. The map from quadratic forms to bilinear forms giving this identification is called the `associated` quadratic form. -/ variables {B : bilin_form R M} namespace bilin_form open quadratic_form lemma polar_to_quadratic_form (x y : M) : polar (λ x, B x x) x y = B x y + B y x := by simp [polar, add_left, add_right, sub_eq_add_neg _ (B y y), add_comm (B y x) _, add_assoc] /-- A bilinear form gives a quadratic form by applying the argument twice. -/ def to_quadratic_form (B : bilin_form R M) : quadratic_form R M := ⟨ λ x, B x x, λ a x, by simp [smul_left, smul_right, mul_assoc], λ x x' y, by simp [polar_to_quadratic_form, add_left, add_right, add_left_comm, add_assoc], λ a x y, by simp [polar_to_quadratic_form, smul_left, smul_right, mul_add], λ x y y', by simp [polar_to_quadratic_form, add_left, add_right, add_left_comm, add_assoc], λ a x y, by simp [polar_to_quadratic_form, smul_left, smul_right, mul_add] ⟩ @[simp] lemma to_quadratic_form_apply (B : bilin_form R M) (x : M) : B.to_quadratic_form x = B x x := rfl end bilin_form namespace quadratic_form open bilin_form sym_bilin_form section associated variables [invertible (2 : R₁)] {B₁ : bilin_form R₁ M} (Q : quadratic_form R₁ M) /-- `Q.associated` is the symmetric bilinear form associated to a quadratic form `Q`. -/ def associated : bilin_form R₁ M := { bilin := λ x y, ⅟2 * polar Q x y, bilin_add_left := λ x y z, by { erw [← mul_add, Q.polar_add_left], refl }, bilin_smul_left := λ x y z, by { erw [← mul_left_comm, Q.polar_smul_left], refl }, bilin_add_right := λ x y z, by { erw [← mul_add, Q.polar_add_right], refl }, bilin_smul_right := λ x y z, by { erw [← mul_left_comm, Q.polar_smul_right], refl } } @[simp] lemma associated_apply (x y : M) : Q.associated x y = ⅟2 * (Q (x + y) - Q x - Q y) := rfl lemma associated_is_sym : is_sym Q.associated := λ x y, by simp [add_comm, add_left_comm, sub_eq_add_neg] @[simp] lemma associated_smul (a : R₁) : (a • Q).associated = (a * a) • Q.associated := by { ext, simp [bilin_form.smul_apply, map_smul, mul_sub, mul_left_comm] } @[simp] lemma associated_comp {N : Type v} [add_comm_group N] [module R₁ N] (f : N →ₗ[R₁] M) : (Q.comp f).associated = Q.associated.comp f f := by { ext, simp } lemma associated_to_quadratic_form (B : bilin_form R₁ M) (x y : M) : B.to_quadratic_form.associated x y = ⅟2 * (B x y + B y x) := by simp [associated_apply, ←polar_to_quadratic_form, polar] lemma associated_left_inverse (h : is_sym B₁) : B₁.to_quadratic_form.associated = B₁ := bilin_form.ext $ λ x y, by rw [associated_to_quadratic_form, sym h x y, ←two_mul, ←mul_assoc, inv_of_mul_self, one_mul] lemma associated_right_inverse : Q.associated.to_quadratic_form = Q := quadratic_form.ext $ λ x, calc Q.associated.to_quadratic_form x = ⅟2 * (Q x + Q x) : by simp [map_add_self, bit0, add_mul, add_assoc] ... = Q x : by rw [← two_mul (Q x), ←mul_assoc, inv_of_mul_self, one_mul] end associated section pos_def variables {R₂ : Type u} [ordered_ring R₂] [module R₂ M] {Q₂ : quadratic_form R₂ M} /-- A positive definite quadratic form is positive on nonzero vectors. -/ def pos_def (Q₂ : quadratic_form R₂ M) : Prop := ∀ x ≠ 0, 0 < Q₂ x lemma smul_pos_def_of_smul_nonzero {R} [linear_ordered_comm_ring R] [module R M] {Q : quadratic_form R M} (h : pos_def Q) {a : R} : (∀ x ≠ (0 : M), a • x ≠ 0) → pos_def (a • Q) := λ ha x hx, h (a • x) (ha x hx) lemma smul_pos_def_of_nonzero {K : Type u} [linear_ordered_field K] [module K M] {Q : quadratic_form K M} (h : pos_def Q) {a : K} : a ≠ 0 → pos_def (a • Q) := λ ha x hx, h (a • x) (λ hax, (smul_eq_zero.mp hax).elim ha hx) end pos_def end quadratic_form section /-! ### Quadratic forms and matrices Connect quadratic forms and matrices, in order to explicitly compute with them. The convention is twos out, so there might be a factor 2⁻¹ in the entries of the matrix. The determinant of the matrix is the discriminant of the quadratic form. -/ variables {n : Type w} [fintype n] /-- `M.to_quadratic_form` is the map `λ x, col x ⬝ M ⬝ row x` as a quadratic form. -/ def matrix.to_quadratic_form (M : matrix n n R₁) : quadratic_form R₁ (n → R₁) := M.to_bilin_form.to_quadratic_form variables [decidable_eq n] [invertible (2 : R₁)] /-- A matrix representation of the quadratic form. -/ def quadratic_form.to_matrix (Q : quadratic_form R₁ (n → R₁)) : matrix n n R₁ := Q.associated.to_matrix open quadratic_form lemma quadratic_form.to_matrix_smul (a : R₁) (Q : quadratic_form R₁ (n → R₁)) : (a • Q).to_matrix = (a * a) • Q.to_matrix := by simp_rw [to_matrix, associated_smul, mul_smul, bilin_form.to_matrix_smul] end namespace quadratic_form variables {n : Type w} [fintype n] variables [decidable_eq n] [invertible (2 : R₁)] variables {m : Type w} [fintype m] [decidable_eq m] open_locale matrix @[simp] lemma to_matrix_comp (Q : quadratic_form R₁ (m → R₁)) (f : (n → R₁) →ₗ[R₁] (m → R₁)) : (Q.comp f).to_matrix = f.to_matrixᵀ ⬝ Q.to_matrix ⬝ f.to_matrix := by { ext, simp [to_matrix, bilin_form.to_matrix_comp] } section discriminant variables {Q : quadratic_form R₁ (n → R₁)} /-- The discriminant of a quadratic form generalizes the discriminant of a quadratic polynomial. -/ def discr (Q : quadratic_form R₁ (n → R₁)) : R₁ := Q.to_matrix.det lemma discr_smul (a : R₁) : (a • Q).discr = (a * a) ^ fintype.card n * Q.discr := by simp [discr, to_matrix_smul] lemma discr_comp (f : (n → R₁) →ₗ[R₁] (n → R₁)) : (Q.comp f).discr = f.to_matrix.det * f.to_matrix.det * Q.discr := by simp [discr, mul_left_comm, mul_comm] end discriminant end quadratic_form namespace quadratic_form variables {M₁ : Type*} {M₂ : Type*} {M₃ : Type*} variables [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₃] variables [module R M₁] [module R M₂] [module R M₃] /-- An isometry between two quadratic spaces `M₁, Q₁` and `M₂, Q₂` over a ring `R`, is a linear equivalence between `M₁` and `M₂` that commutes with the quadratic forms. -/ @[nolint has_inhabited_instance] structure isometry (Q₁ : quadratic_form R M₁) (Q₂ : quadratic_form R M₂) extends M₁ ≃ₗ[R] M₂ := (map_app' : ∀ m, Q₂ (to_fun m) = Q₁ m) /-- Two quadratic forms over a ring `R` are equivalent if there exists an isometry between them: a linear equivalence that transforms one quadratic form into the other. -/ def equivalent (Q₁ : quadratic_form R M₁) (Q₂ : quadratic_form R M₂) := nonempty (Q₁.isometry Q₂) namespace isometry variables {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} {Q₃ : quadratic_form R M₃} instance : has_coe (Q₁.isometry Q₂) (M₁ ≃ₗ[R] M₂) := ⟨isometry.to_linear_equiv⟩ instance : has_coe_to_fun (Q₁.isometry Q₂) := { F := λ _, M₁ → M₂, coe := λ f, ⇑(f : M₁ ≃ₗ[R] M₂) } @[simp] lemma map_app (f : Q₁.isometry Q₂) (m : M₁) : Q₂ (f m) = Q₁ m := f.map_app' m /-- The identity isometry from a quadratic form to itself. -/ @[refl] def refl (Q : quadratic_form R M) : Q.isometry Q := { map_app' := λ m, rfl, .. linear_equiv.refl R M } /-- The inverse isometry of an isometry between two quadratic forms. -/ @[symm] def symm (f : Q₁.isometry Q₂) : Q₂.isometry Q₁ := { map_app' := by { intro m, rw ← f.map_app, congr, exact f.to_linear_equiv.apply_symm_apply m }, .. (f : M₁ ≃ₗ[R] M₂).symm } /-- The composition of two isometries between quadratic forms. -/ @[trans] def trans (f : Q₁.isometry Q₂) (g : Q₂.isometry Q₃) : Q₁.isometry Q₃ := { map_app' := by { intro m, rw [← f.map_app, ← g.map_app], refl }, .. (f : M₁ ≃ₗ[R] M₂).trans (g : M₂ ≃ₗ[R] M₃) } end isometry namespace equivalent variables {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} {Q₃ : quadratic_form R M₃} @[refl] lemma refl (Q : quadratic_form R M) : Q.equivalent Q := ⟨isometry.refl Q⟩ @[symm] lemma symm (h : Q₁.equivalent Q₂) : Q₂.equivalent Q₁ := h.elim $ λ f, ⟨f.symm⟩ @[trans] lemma trans (h : Q₁.equivalent Q₂) (h' : Q₂.equivalent Q₃) : Q₁.equivalent Q₃ := h'.elim $ h.elim $ λ f g, ⟨f.trans g⟩ end equivalent end quadratic_form
4b76548cd3a0be82c3b6a4958bb6c81809dc6224
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/elabissues/typeclass_triggers_typeclass.lean
a5b05b826189d05aa4e74f20a217addc3166043e
[ "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,095
lean
/- Here is an example where typeclass resolution triggers nested typeclass resolution. -/ class Ring (α : Type) : Type := (x : Unit) class Double (α : Type) : Type := (x : Unit) class Foo (α : Type) [Double α] : Type := (x : Unit) instance RingToDouble (α : Type) [Ring α] : Double α := Double.mk α () -- Note: The return type is really `@Foo α (@RingToDouble α s)`. instance RingFoo (α : Type) [s : Ring α] : Foo α := Foo.mk α () instance RingInt : Ring Int := Ring.mk Int () instance DoubleInt : Double Int := Double.mk Int () def foo [@Foo Int DoubleInt] : Unit := () set_option pp.all true set_option trace.class_instances true set_option trace.type_context.complete_instance true #check @foo _ /- [class_instances] class-instance resolution trace [class_instances] (0) ?x_0 : @Foo Int DoubleInt := @RingFoo ?x_1 ?x_2 [type_context.complete_instance] about to synth: Ring Int [class_instances] class-instance resolution trace [class_instances] (0) ?x_3 : Ring Int := RingInt [class_instances] (1) ?x_2 : Ring Int := RingInt @foo (@RingFoo Int RingInt) : Unit -/
d4788ac49aa692440638ef989bceab7d82198bc8
367134ba5a65885e863bdc4507601606690974c1
/src/ring_theory/eisenstein_criterion.lean
37ce9c026a1e348da16aa274e36e2327e9bb0b86
[ "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
5,623
lean
/- Copyright (c) 2020 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import ring_theory.ideal.operations import data.polynomial.ring_division import tactic.apply_fun import ring_theory.prime /-! # Eisenstein's criterion A proof of a slight generalisation of Eisenstein's criterion for the irreducibility of a polynomial over an integral domain. -/ open polynomial ideal.quotient variables {R : Type*} [integral_domain R] namespace polynomial namespace eisenstein_criterion_aux /- Section for auxiliary lemmas used in the proof of `irreducible_of_eisenstein_criterion`-/ lemma map_eq_C_mul_X_pow_of_forall_coeff_mem {f : polynomial R} {P : ideal R} (hfP : ∀ (n : ℕ), ↑n < f.degree → f.coeff n ∈ P) (hf0 : f ≠ 0) : map (mk P) f = C ((mk P) f.leading_coeff) * X ^ f.nat_degree := polynomial.ext (λ n, begin rcases lt_trichotomy ↑n (degree f) with h | h | h, { erw [coeff_map, eq_zero_iff_mem.2 (hfP n h), coeff_C_mul, coeff_X_pow, if_neg, mul_zero], rintro rfl, exact not_lt_of_ge degree_le_nat_degree h }, { have : nat_degree f = n, from nat_degree_eq_of_degree_eq_some h.symm, rw [coeff_C_mul, coeff_X_pow, if_pos this.symm, mul_one, leading_coeff, this, coeff_map] }, { rw [coeff_eq_zero_of_degree_lt, coeff_eq_zero_of_degree_lt], { refine lt_of_le_of_lt (degree_C_mul_X_pow_le _ _) _, rwa ← degree_eq_nat_degree hf0 }, { exact lt_of_le_of_lt (degree_map_le _) h } } end) lemma le_nat_degree_of_map_eq_mul_X_pow {n : ℕ} {P : ideal R} (hP : P.is_prime) {q : polynomial R} {c : polynomial P.quotient} (hq : map (mk P) q = c * X ^ n) (hc0 : c.degree = 0) : n ≤ q.nat_degree := with_bot.coe_le_coe.1 (calc ↑n = degree (q.map (mk P)) : by rw [hq, degree_mul, hc0, zero_add, degree_pow, degree_X, nsmul_one, nat.cast_with_bot] ... ≤ degree q : degree_map_le _ ... ≤ nat_degree q : degree_le_nat_degree) lemma eval_zero_mem_ideal_of_eq_mul_X_pow {n : ℕ} {P : ideal R} {q : polynomial R} {c : polynomial P.quotient} (hq : map (mk P) q = c * X ^ n) (hn0 : 0 < n) : eval 0 q ∈ P := by rw [← coeff_zero_eq_eval_zero, ← eq_zero_iff_mem, ← coeff_map, coeff_zero_eq_eval_zero, hq, eval_mul, eval_pow, eval_X, zero_pow hn0, mul_zero] lemma is_unit_of_nat_degree_eq_zero_of_forall_dvd_is_unit {p q : polynomial R} (hu : ∀ (x : R), C x ∣ p * q → is_unit x) (hpm : p.nat_degree = 0) : is_unit p := begin rw [eq_C_of_degree_le_zero (nat_degree_eq_zero_iff_degree_le_zero.1 hpm), is_unit_C], refine hu _ _, rw [← eq_C_of_degree_le_zero (nat_degree_eq_zero_iff_degree_le_zero.1 hpm)], exact dvd_mul_right _ _ end end eisenstein_criterion_aux open eisenstein_criterion_aux /-- If `f` is a non constant polynomial with coefficients in `R`, and `P` is a prime ideal in `R`, then if every coefficient in `R` except the leading coefficient is in `P`, and the trailing coefficient is not in `P^2` and no non units in `R` divide `f`, then `f` is irreducible. -/ theorem irreducible_of_eisenstein_criterion {f : polynomial R} {P : ideal R} (hP : P.is_prime) (hfl : f.leading_coeff ∉ P) (hfP : ∀ n : ℕ, ↑n < degree f → f.coeff n ∈ P) (hfd0 : 0 < degree f) (h0 : f.coeff 0 ∉ P^2) (hu : ∀ x : R, C x ∣ f → is_unit x) : irreducible f := have hf0 : f ≠ 0, from λ _, by simp only [*, not_true, submodule.zero_mem, coeff_zero] at *, have hf : f.map (mk P) = C (mk P (leading_coeff f)) * X ^ nat_degree f, from map_eq_C_mul_X_pow_of_forall_coeff_mem hfP hf0, have hfd0 : 0 < f.nat_degree, from with_bot.coe_lt_coe.1 (lt_of_lt_of_le hfd0 degree_le_nat_degree), ⟨mt degree_eq_zero_of_is_unit (λ h, by simp only [*, lt_irrefl] at *), begin rintros p q rfl, rw [map_mul] at hf, rcases mul_eq_mul_prime_pow (show prime (X : polynomial (ideal.quotient P)), from prime_of_degree_eq_one_of_monic degree_X monic_X) hf with ⟨m, n, b, c, hmnd, hbc, hp, hq⟩, have hmn : 0 < m → 0 < n → false, { assume hm0 hn0, refine h0 _, rw [coeff_zero_eq_eval_zero, eval_mul, pow_two], exact ideal.mul_mem_mul (eval_zero_mem_ideal_of_eq_mul_X_pow hp hm0) (eval_zero_mem_ideal_of_eq_mul_X_pow hq hn0) }, have hpql0 : (mk P) (p * q).leading_coeff ≠ 0, { rwa [ne.def, eq_zero_iff_mem] }, have hp0 : p ≠ 0, from λ h, by simp only [*, zero_mul, eq_self_iff_true, not_true, ne.def] at *, have hq0 : q ≠ 0, from λ h, by simp only [*, eq_self_iff_true, not_true, ne.def, mul_zero] at *, have hbc0 : degree b = 0 ∧ degree c = 0, { apply_fun degree at hbc, rwa [degree_C hpql0, degree_mul, eq_comm, nat.with_bot.add_eq_zero_iff] at hbc }, have hmp : m ≤ nat_degree p, from le_nat_degree_of_map_eq_mul_X_pow hP hp hbc0.1, have hnq : n ≤ nat_degree q, from le_nat_degree_of_map_eq_mul_X_pow hP hq hbc0.2, have hpmqn : p.nat_degree = m ∧ q.nat_degree = n, { rw [nat_degree_mul hp0 hq0] at hmnd, clear_except hmnd hmp hnq, contrapose hmnd, apply ne_of_lt, rw not_and_distrib at hmnd, cases hmnd, { exact add_lt_add_of_lt_of_le (lt_of_le_of_ne hmp (ne.symm hmnd)) hnq }, { exact add_lt_add_of_le_of_lt hmp (lt_of_le_of_ne hnq (ne.symm hmnd)) } }, obtain rfl | rfl : m = 0 ∨ n = 0, { rwa [pos_iff_ne_zero, pos_iff_ne_zero, imp_false, not_not, ← or_iff_not_imp_left] at hmn }, { exact or.inl (is_unit_of_nat_degree_eq_zero_of_forall_dvd_is_unit hu hpmqn.1) }, { exact or.inr (is_unit_of_nat_degree_eq_zero_of_forall_dvd_is_unit (by simpa only [mul_comm] using hu) hpmqn.2) } end⟩ end polynomial
358e7bb6ba7d7514af54adfe273fee809d62c3a8
3b15c7b0b62d8ada1399c112ad88a529e6bfa115
/stage0/src/Lean/Server/FileWorker/WidgetRequests.lean
1c0d3a385ad768033519dc269243dda34c62d24b
[ "Apache-2.0" ]
permissive
stephenbrady/lean4
74bf5cae8a433e9c815708ce96c9e54a5caf2115
b1bd3fc304d0f7bc6810ec78bfa4c51476d263f9
refs/heads/master
1,692,621,473,161
1,634,308,743,000
1,634,310,749,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,426
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki -/ import Lean.Widget.InteractiveCode import Lean.Widget.InteractiveGoal import Lean.Widget.InteractiveDiagnostic import Lean.Server.Rpc.RequestHandling import Lean.Server.FileWorker.RequestHandling /-! Registers all widget-related RPC procedures. -/ namespace Lean.Widget open Server structure MsgToInteractive where msg : WithRpcRef MessageData indent : Nat deriving Inhabited, RpcEncoding builtin_initialize registerRpcCallHandler `Lean.Widget.InteractiveDiagnostics.msgToInteractive MsgToInteractive (TaggedText MsgEmbed) fun ⟨⟨m⟩, i⟩ => RequestM.asTask do msgToInteractive m i structure InfoPopup where type : Option CodeWithInfos exprExplicit : Option CodeWithInfos doc : Option String deriving Inhabited, RpcEncoding builtin_initialize registerRpcCallHandler `Lean.Widget.InteractiveDiagnostics.infoToInteractive (WithRpcRef InfoWithCtx) InfoPopup fun ⟨i⟩ => RequestM.asTask do i.ctx.runMetaM i.info.lctx do let type? ← match (← i.info.type?) with | some type => some <$> exprToInteractive type | none => none let exprExplicit? ← match i.info with | Elab.Info.ofTermInfo ti => some <$> exprToInteractiveExplicit ti.expr | Elab.Info.ofFieldInfo fi => some (TaggedText.text fi.fieldName.toString) | _ => none return { type := type? exprExplicit := exprExplicit? doc := ← i.info.docString? : InfoPopup } builtin_initialize registerRpcCallHandler `Lean.Widget.getInteractiveGoals Lsp.PlainGoalParams (Option InteractiveGoals) FileWorker.getInteractiveGoals registerRpcCallHandler `Lean.Widget.getInteractiveTermGoal Lsp.PlainTermGoalParams (Option InteractiveTermGoal) FileWorker.getInteractiveTermGoal open RequestM in def getInteractiveDiagnostics (_ : Json) : RequestM (RequestTask (Array InteractiveDiagnostic)) := do let doc ← readDoc let t₁ ← doc.cmdSnaps.waitAll t₁.map fun (snaps, _) => snaps.getLast!.interactiveDiags.toArray builtin_initialize registerRpcCallHandler `Lean.Widget.getInteractiveDiagnostics Json (Array InteractiveDiagnostic) getInteractiveDiagnostics end Lean.Widget
da0d4eb27cd5f26c2d2053d38631e77c52595425
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/logic/quantifiers.lean
1d23cb6e065df320b7cf2f7dbe60e28379ef1fd5
[ "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
3,116
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad Universal and existential quantifiers. See also init.logic. -/ import .connectives open inhabited nonempty theorem exists_imp_distrib {A : Type} {B : Prop} {P : A → Prop} : ((∃ a : A, P a) → B) ↔ (∀ a : A, P a → B) := iff.intro (λ e x H, e (exists.intro x H)) Exists.rec theorem forall_iff_not_exists {A : Type} {P : A → Prop} : (¬ ∃ a : A, P a) ↔ ∀ a : A, ¬ P a := exists_imp_distrib theorem not_forall_not_of_exists {A : Type} {p : A → Prop} (H : ∃ x, p x) : ¬ ∀ x, ¬ p x := sorry /- assume H1 : ∀ x, ¬ p x, obtain (w : A) (Hw : p w), from H, absurd Hw (H1 w) -/ theorem not_exists_not_of_forall {A : Type} {p : A → Prop} (H2 : ∀ x, p x) : ¬ ∃ x, ¬p x := sorry /- assume H1 : ∃ x, ¬ p x, obtain (w : A) (Hw : ¬ p w), from H1, absurd (H2 w) Hw -/ theorem not_forall_of_exists_not {A : Type} {P : A → Prop} (H : ∃ a : A, ¬ P a) : ¬ ∀ a : A, P a := assume H', not_exists_not_of_forall H' H theorem forall_true_iff_true (A : Type) : (∀ x : A, true) ↔ true := iff_true_intro (λH, trivial) theorem forall_p_iff_p (A : Type) [H : inhabited A] (p : Prop) : (∀ x : A, p) ↔ p := iff.intro (inhabited.destruct H) (λ Hr x, Hr) theorem exists_p_iff_p (A : Type) [H : inhabited A] (p : Prop) : (∃ x : A, p) ↔ p := iff.intro (Exists.rec (λ x Hp, Hp)) (inhabited.destruct H exists.intro) theorem forall_and_distribute {A : Type} (φ ψ : A → Prop) : (∀ x, φ x ∧ ψ x) ↔ (∀ x, φ x) ∧ (∀ x, ψ x) := iff.intro (assume H, and.intro (take x, and.left (H x)) (take x, and.right (H x))) (assume H x, and.intro (and.left H x) (and.right H x)) theorem exists_or_distribute {A : Type} (φ ψ : A → Prop) : (∃ x, φ x ∨ ψ x) ↔ (∃ x, φ x) ∨ (∃ x, ψ x) := iff.intro (Exists.rec (λ x, or.imp (exists.intro x) (exists.intro x))) (or.rec (exists_imp_exists (λ x, or.inl)) (exists_imp_exists (λ x, or.inr))) section open decidable variables {A : Type} (P : A → Prop) (a : A) [H : decidable (P a)] include H attribute [instance] definition decidable_forall_eq : decidable (∀ x, x = a → P x) := if pa : P a then tt (λ x heq, eq.substr heq pa) else ff (not.mto (λH, H a rfl) pa) attribute [instance] definition decidable_exists_eq : decidable (∃ x, x = a ∧ P x) := if pa : P a then tt (exists.intro a (and.intro rfl pa)) else ff (Exists.rec (λh, and.rec (λheq, eq.substr heq pa))) end /- definite description -/ section local attribute classical.prop_decidable [instance] noncomputable definition the {A : Type} {p : A → Prop} (H : ∃! x, p x) : A := classical.some (exists_of_exists_unique H) theorem the_spec {A : Type} {p : A → Prop} (H : ∃! x, p x) : p (the H) := classical.some_spec (exists_of_exists_unique H) theorem eq_the {A : Type} {p : A → Prop} (H : ∃! x, p x) {y : A} (Hy : p y) : y = the H := unique_of_exists_unique H Hy (the_spec H) end
e655c918d30156bb5dd918d3f42c5d52b1fe9d21
32da3d0f92cab08875472ef6cacc1931c2b3eafa
/src/set_theory/cardinal_ordinal.lean
1f48e5c010604973156ce06dfa7bb010ed29c147
[ "Apache-2.0" ]
permissive
karthiknadig/mathlib
b6073c3748860bfc9a3e55da86afcddba62dc913
33a86cfff12d7f200d0010cd03b95e9b69a6c1a5
refs/heads/master
1,676,389,371,851
1,610,061,127,000
1,610,061,127,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
35,676
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl, Mario Carneiro -/ import set_theory.ordinal_arithmetic import tactic.omega /-! # Cardinals and ordinals Relationships between cardinals and ordinals, properties of cardinals that are proved using ordinals. ## Main definitions and results * The `aleph'` function gives the cardinals listed by their ordinal index, and is the inverse of `aleph_idx`. `aleph' n = n`, `aleph' ω = ω`, `aleph' (ω + 1) = ℵ₁`, etc. It is an order isomorphism between ordinals and cardinals. * The `aleph` function gives the infinite cardinals listed by their ordinal index. `aleph 0 = ω`, `aleph 1 = succ ω` is the first uncountable cardinal, and so on. * `mul_eq_max` and `add_eq_max` state that the product (resp. sum) of two infinite cardinals is just their maximum. Several variations around this fact are also given. * `mk_list_eq_mk` : when `α` is infinite, `α` and `list α` have the same cardinality. * simp lemmas for inequalities between `bit0 a` and `bit1 b` are registered, making simp able to prove inequalities about numeral cardinals. -/ noncomputable theory open function cardinal set equiv open_locale classical cardinal universes u v w namespace cardinal section using_ordinals open ordinal theorem ord_is_limit {c} (co : omega ≤ c) : (ord c).is_limit := begin refine ⟨λ h, omega_ne_zero _, λ a, lt_imp_lt_of_le_imp_le _⟩, { rw [← ordinal.le_zero, ord_le] at h, simpa only [card_zero, le_zero] using le_trans co h }, { intro h, rw [ord_le] at h ⊢, rwa [← @add_one_of_omega_le (card a), ← card_succ], rw [← ord_le, ← le_succ_of_is_limit, ord_le], { exact le_trans co h }, { rw ord_omega, exact omega_is_limit } } end /-- The `aleph'` index function, which gives the ordinal index of a cardinal. (The `aleph'` part is because unlike `aleph` this counts also the finite stages. So `aleph_idx n = n`, `aleph_idx ω = ω`, `aleph_idx ℵ₁ = ω + 1` and so on.) In this definition, we register additionally that this function is an initial segment, i.e., it is order preserving and its range is an initial segment of the ordinals. For the basic function version, see `aleph_idx`. For an upgraded version stating that the range is everything, see `aleph_idx.rel_iso`. -/ def aleph_idx.initial_seg : @initial_seg cardinal ordinal (<) (<) := @rel_embedding.collapse cardinal ordinal (<) (<) _ cardinal.ord.order_embedding.lt_embedding /-- The `aleph'` index function, which gives the ordinal index of a cardinal. (The `aleph'` part is because unlike `aleph` this counts also the finite stages. So `aleph_idx n = n`, `aleph_idx ω = ω`, `aleph_idx ℵ₁ = ω + 1` and so on.) For an upgraded version stating that the range is everything, see `aleph_idx.rel_iso`. -/ def aleph_idx : cardinal → ordinal := aleph_idx.initial_seg @[simp] theorem aleph_idx.initial_seg_coe : (aleph_idx.initial_seg : cardinal → ordinal) = aleph_idx := rfl @[simp] theorem aleph_idx_lt {a b} : aleph_idx a < aleph_idx b ↔ a < b := aleph_idx.initial_seg.to_rel_embedding.map_rel_iff @[simp] theorem aleph_idx_le {a b} : aleph_idx a ≤ aleph_idx b ↔ a ≤ b := by rw [← not_lt, ← not_lt, aleph_idx_lt] theorem aleph_idx.init {a b} : b < aleph_idx a → ∃ c, aleph_idx c = b := aleph_idx.initial_seg.init _ _ /-- The `aleph'` index function, which gives the ordinal index of a cardinal. (The `aleph'` part is because unlike `aleph` this counts also the finite stages. So `aleph_idx n = n`, `aleph_idx ω = ω`, `aleph_idx ℵ₁ = ω + 1` and so on.) In this version, we register additionally that this function is an order isomorphism between cardinals and ordinals. For the basic function version, see `aleph_idx`. -/ def aleph_idx.rel_iso : @rel_iso cardinal.{u} ordinal.{u} (<) (<) := @rel_iso.of_surjective cardinal.{u} ordinal.{u} (<) (<) aleph_idx.initial_seg.{u} $ (initial_seg.eq_or_principal aleph_idx.initial_seg.{u}).resolve_right $ λ ⟨o, e⟩, begin have : ∀ c, aleph_idx c < o := λ c, (e _).2 ⟨_, rfl⟩, refine ordinal.induction_on o _ this, introsI α r _ h, let s := sup.{u u} (λ a:α, inv_fun aleph_idx (ordinal.typein r a)), apply not_le_of_gt (lt_succ_self s), have I : injective aleph_idx := aleph_idx.initial_seg.to_embedding.injective, simpa only [typein_enum, left_inverse_inv_fun I (succ s)] using le_sup.{u u} (λ a, inv_fun aleph_idx (ordinal.typein r a)) (ordinal.enum r _ (h (succ s))), end @[simp] theorem aleph_idx.rel_iso_coe : (aleph_idx.rel_iso : cardinal → ordinal) = aleph_idx := rfl @[simp] theorem type_cardinal : @ordinal.type cardinal (<) _ = ordinal.univ.{u (u+1)} := by rw ordinal.univ_id; exact quotient.sound ⟨aleph_idx.rel_iso⟩ @[simp] theorem mk_cardinal : mk cardinal = univ.{u (u+1)} := by simpa only [card_type, card_univ] using congr_arg card type_cardinal /-- The `aleph'` function gives the cardinals listed by their ordinal index, and is the inverse of `aleph_idx`. `aleph' n = n`, `aleph' ω = ω`, `aleph' (ω + 1) = ℵ₁`, etc. In this version, we register additionally that this function is an order isomorphism between ordinals and cardinals. For the basic function version, see `aleph'`. -/ def aleph'.rel_iso := cardinal.aleph_idx.rel_iso.symm /-- The `aleph'` function gives the cardinals listed by their ordinal index, and is the inverse of `aleph_idx`. `aleph' n = n`, `aleph' ω = ω`, `aleph' (ω + 1) = ℵ₁`, etc. -/ def aleph' : ordinal → cardinal := aleph'.rel_iso @[simp] theorem aleph'.rel_iso_coe : (aleph'.rel_iso : ordinal → cardinal) = aleph' := rfl @[simp] theorem aleph'_lt {o₁ o₂ : ordinal.{u}} : aleph' o₁ < aleph' o₂ ↔ o₁ < o₂ := aleph'.rel_iso.map_rel_iff @[simp] theorem aleph'_le {o₁ o₂ : ordinal.{u}} : aleph' o₁ ≤ aleph' o₂ ↔ o₁ ≤ o₂ := le_iff_le_iff_lt_iff_lt.2 aleph'_lt @[simp] theorem aleph'_aleph_idx (c : cardinal.{u}) : aleph' c.aleph_idx = c := cardinal.aleph_idx.rel_iso.to_equiv.symm_apply_apply c @[simp] theorem aleph_idx_aleph' (o : ordinal.{u}) : (aleph' o).aleph_idx = o := cardinal.aleph_idx.rel_iso.to_equiv.apply_symm_apply o @[simp] theorem aleph'_zero : aleph' 0 = 0 := by rw [← le_zero, ← aleph'_aleph_idx 0, aleph'_le]; apply ordinal.zero_le @[simp] theorem aleph'_succ {o : ordinal.{u}} : aleph' o.succ = (aleph' o).succ := le_antisymm (cardinal.aleph_idx_le.1 $ by rw [aleph_idx_aleph', ordinal.succ_le, ← aleph'_lt, aleph'_aleph_idx]; apply cardinal.lt_succ_self) (cardinal.succ_le.2 $ aleph'_lt.2 $ ordinal.lt_succ_self _) @[simp] theorem aleph'_nat : ∀ n : ℕ, aleph' n = n | 0 := aleph'_zero | (n+1) := show aleph' (ordinal.succ n) = n.succ, by rw [aleph'_succ, aleph'_nat, nat_succ] theorem aleph'_le_of_limit {o : ordinal.{u}} (l : o.is_limit) {c} : aleph' o ≤ c ↔ ∀ o' < o, aleph' o' ≤ c := ⟨λ h o' h', le_trans (aleph'_le.2 $ le_of_lt h') h, λ h, begin rw [← aleph'_aleph_idx c, aleph'_le, ordinal.limit_le l], intros x h', rw [← aleph'_le, aleph'_aleph_idx], exact h _ h' end⟩ @[simp] theorem aleph'_omega : aleph' ordinal.omega = omega := eq_of_forall_ge_iff $ λ c, begin simp only [aleph'_le_of_limit omega_is_limit, ordinal.lt_omega, exists_imp_distrib, omega_le], exact forall_swap.trans (forall_congr $ λ n, by simp only [forall_eq, aleph'_nat]), end /-- `aleph'` and `aleph_idx` form an equivalence between `ordinal` and `cardinal` -/ @[simp] def aleph'_equiv : ordinal ≃ cardinal := ⟨aleph', aleph_idx, aleph_idx_aleph', aleph'_aleph_idx⟩ /-- The `aleph` function gives the infinite cardinals listed by their ordinal index. `aleph 0 = ω`, `aleph 1 = succ ω` is the first uncountable cardinal, and so on. -/ def aleph (o : ordinal) : cardinal := aleph' (ordinal.omega + o) @[simp] theorem aleph_lt {o₁ o₂ : ordinal.{u}} : aleph o₁ < aleph o₂ ↔ o₁ < o₂ := aleph'_lt.trans (ordinal.add_lt_add_iff_left _) @[simp] theorem aleph_le {o₁ o₂ : ordinal.{u}} : aleph o₁ ≤ aleph o₂ ↔ o₁ ≤ o₂ := le_iff_le_iff_lt_iff_lt.2 aleph_lt @[simp] theorem aleph_succ {o : ordinal.{u}} : aleph o.succ = (aleph o).succ := by rw [aleph, ordinal.add_succ, aleph'_succ]; refl @[simp] theorem aleph_zero : aleph 0 = omega := by simp only [aleph, add_zero, aleph'_omega] theorem omega_le_aleph' {o : ordinal} : omega ≤ aleph' o ↔ ordinal.omega ≤ o := by rw [← aleph'_omega, aleph'_le] theorem omega_le_aleph (o : ordinal) : omega ≤ aleph o := by rw [aleph, omega_le_aleph']; apply ordinal.le_add_right theorem ord_aleph_is_limit (o : ordinal) : is_limit (aleph o).ord := ord_is_limit $ omega_le_aleph _ theorem exists_aleph {c : cardinal} : omega ≤ c ↔ ∃ o, c = aleph o := ⟨λ h, ⟨aleph_idx c - ordinal.omega, by rw [aleph, ordinal.add_sub_cancel_of_le, aleph'_aleph_idx]; rwa [← omega_le_aleph', aleph'_aleph_idx]⟩, λ ⟨o, e⟩, e.symm ▸ omega_le_aleph _⟩ theorem aleph'_is_normal : is_normal (ord ∘ aleph') := ⟨λ o, ord_lt_ord.2 $ aleph'_lt.2 $ ordinal.lt_succ_self _, λ o l a, by simp only [ord_le, aleph'_le_of_limit l]⟩ theorem aleph_is_normal : is_normal (ord ∘ aleph) := aleph'_is_normal.trans $ add_is_normal ordinal.omega /-! ### Properties of `mul` -/ /-- If `α` is an infinite type, then `α × α` and `α` have the same cardinality. -/ theorem mul_eq_self {c : cardinal} (h : omega ≤ c) : c * c = c := begin refine le_antisymm _ (by simpa only [mul_one] using mul_le_mul_left c (le_trans (le_of_lt one_lt_omega) h)), -- the only nontrivial part is `c * c ≤ c`. We prove it inductively. refine acc.rec_on (cardinal.wf.apply c) (λ c _, quotient.induction_on c $ λ α IH ol, _) h, -- consider the minimal well-order `r` on `α` (a type with cardinality `c`). rcases ord_eq α with ⟨r, wo, e⟩, resetI, letI := linear_order_of_STO' r, haveI : is_well_order α (<) := wo, -- Define an order `s` on `α × α` by writing `(a, b) < (c, d)` if `max a b < max c d`, or -- the max are equal and `a < c`, or the max are equal and `a = c` and `b < d`. let g : α × α → α := λ p, max p.1 p.2, let f : α × α ↪ ordinal × (α × α) := ⟨λ p:α×α, (typein (<) (g p), p), λ p q, congr_arg prod.snd⟩, let s := f ⁻¹'o (prod.lex (<) (prod.lex (<) (<))), -- this is a well order on `α × α`. haveI : is_well_order _ s := (rel_embedding.preimage _ _).is_well_order, /- it suffices to show that this well order is smaller than `r` if it were larger, then `r` would be a strict prefix of `s`. It would be contained in `β × β` for some `β` of cardinality `< c`. By the inductive assumption, this set has the same cardinality as `β` (or it is finite if `β` is finite), so it is `< c`, which is a contradiction. -/ suffices : type s ≤ type r, {exact card_le_card this}, refine le_of_forall_lt (λ o h, _), rcases typein_surj s h with ⟨p, rfl⟩, rw [← e, lt_ord], refine lt_of_le_of_lt (_ : _ ≤ card (typein (<) (g p)).succ * card (typein (<) (g p)).succ) _, { have : {q|s q p} ⊆ (insert (g p) {x | x < (g p)}).prod (insert (g p) {x | x < (g p)}), { intros q h, simp only [s, embedding.coe_fn_mk, order.preimage, typein_lt_typein, prod.lex_def, typein_inj] at h, exact max_le_iff.1 (le_iff_lt_or_eq.2 $ h.imp_right and.left) }, suffices H : (insert (g p) {x | r x (g p)} : set α) ≃ ({x | r x (g p)} ⊕ punit), { exact ⟨(set.embedding_of_subset _ _ this).trans ((equiv.set.prod _ _).trans (H.prod_congr H)).to_embedding⟩ }, refine (equiv.set.insert _).trans ((equiv.refl _).sum_congr punit_equiv_punit), apply @irrefl _ r }, cases lt_or_ge (card (typein (<) (g p)).succ) omega with qo qo, { exact lt_of_lt_of_le (mul_lt_omega qo qo) ol }, { suffices, {exact lt_of_le_of_lt (IH _ this qo) this}, rw ← lt_ord, apply (ord_is_limit ol).2, rw [mk_def, e], apply typein_lt_type } end end using_ordinals /-- If `α` and `β` are infinite types, then the cardinality of `α × β` is the maximum of the cardinalities of `α` and `β`. -/ theorem mul_eq_max {a b : cardinal} (ha : omega ≤ a) (hb : omega ≤ b) : a * b = max a b := le_antisymm (mul_eq_self (le_trans ha (le_max_left a b)) ▸ mul_le_mul (le_max_left _ _) (le_max_right _ _)) $ max_le (by simpa only [mul_one] using mul_le_mul_left a (le_trans (le_of_lt one_lt_omega) hb)) (by simpa only [one_mul] using mul_le_mul_right b (le_trans (le_of_lt one_lt_omega) ha)) theorem mul_lt_of_lt {a b c : cardinal} (hc : omega ≤ c) (h1 : a < c) (h2 : b < c) : a * b < c := lt_of_le_of_lt (mul_le_mul (le_max_left a b) (le_max_right a b)) $ (lt_or_le (max a b) omega).elim (λ h, lt_of_lt_of_le (mul_lt_omega h h) hc) (λ h, by rw mul_eq_self h; exact max_lt h1 h2) lemma mul_le_max_of_omega_le_left {a b : cardinal} (h : omega ≤ a) : a * b ≤ max a b := begin convert mul_le_mul (le_max_left a b) (le_max_right a b), rw [mul_eq_self], refine le_trans h (le_max_left a b) end lemma mul_eq_max_of_omega_le_left {a b : cardinal} (h : omega ≤ a) (h' : b ≠ 0) : a * b = max a b := begin apply le_antisymm, apply mul_le_max_of_omega_le_left h, cases le_or_gt omega b with hb hb, rw [mul_eq_max h hb], have : b ≤ a, exact le_trans (le_of_lt hb) h, rw [max_eq_left this], convert mul_le_mul_left _ (one_le_iff_ne_zero.mpr h'), rw [mul_one], end lemma mul_eq_left {a b : cardinal} (ha : omega ≤ a) (hb : b ≤ a) (hb' : b ≠ 0) : a * b = a := by { rw [mul_eq_max_of_omega_le_left ha hb', max_eq_left hb] } lemma mul_eq_right {a b : cardinal} (hb : omega ≤ b) (ha : a ≤ b) (ha' : a ≠ 0) : a * b = b := by { rw [mul_comm, mul_eq_left hb ha ha'] } lemma le_mul_left {a b : cardinal} (h : b ≠ 0) : a ≤ b * a := by { convert mul_le_mul_right _ (one_le_iff_ne_zero.mpr h), rw [one_mul] } lemma le_mul_right {a b : cardinal} (h : b ≠ 0) : a ≤ a * b := by { rw [mul_comm], exact le_mul_left h } lemma mul_eq_left_iff {a b : cardinal} : a * b = a ↔ ((max omega b ≤ a ∧ b ≠ 0) ∨ b = 1 ∨ a = 0) := begin rw [max_le_iff], split, { intro h, cases (le_or_lt omega a) with ha ha, { have : a ≠ 0, { rintro rfl, exact not_lt_of_le ha omega_pos }, left, use ha, { rw [← not_lt], intro hb, apply ne_of_gt _ h, refine lt_of_lt_of_le hb (le_mul_left this) }, { rintro rfl, apply this, rw [_root_.mul_zero] at h, subst h }}, right, by_cases h2a : a = 0, { right, exact h2a }, have hb : b ≠ 0, { rintro rfl, apply h2a, rw [mul_zero] at h, subst h }, left, rw [← h, mul_lt_omega_iff, lt_omega, lt_omega] at ha, rcases ha with rfl|rfl|⟨⟨n, rfl⟩, ⟨m, rfl⟩⟩, contradiction, contradiction, rw [← ne] at h2a, rw [← one_le_iff_ne_zero] at h2a hb, norm_cast at h2a hb h ⊢, apply le_antisymm _ hb, rw [← not_lt], intro h2b, apply ne_of_gt _ h, rw [gt], conv_lhs { rw [← mul_one n] }, rwa [mul_lt_mul_left], apply nat.lt_of_succ_le h2a }, { rintro (⟨⟨ha, hab⟩, hb⟩|rfl|rfl), { rw [mul_eq_max_of_omega_le_left ha hb, max_eq_left hab] }, all_goals {simp}} end /-! ### Properties of `add` -/ /-- If `α` is an infinite type, then `α ⊕ α` and `α` have the same cardinality. -/ theorem add_eq_self {c : cardinal} (h : omega ≤ c) : c + c = c := le_antisymm (by simpa only [nat.cast_bit0, nat.cast_one, mul_eq_self h, two_mul] using mul_le_mul_right c (le_trans (le_of_lt $ nat_lt_omega 2) h)) (le_add_left c c) /-- If `α` is an infinite type, then the cardinality of `α ⊕ β` is the maximum of the cardinalities of `α` and `β`. -/ theorem add_eq_max {a b : cardinal} (ha : omega ≤ a) : a + b = max a b := le_antisymm (add_eq_self (le_trans ha (le_max_left a b)) ▸ add_le_add (le_max_left _ _) (le_max_right _ _)) $ max_le (le_add_right _ _) (le_add_left _ _) theorem add_lt_of_lt {a b c : cardinal} (hc : omega ≤ c) (h1 : a < c) (h2 : b < c) : a + b < c := lt_of_le_of_lt (add_le_add (le_max_left a b) (le_max_right a b)) $ (lt_or_le (max a b) omega).elim (λ h, lt_of_lt_of_le (add_lt_omega h h) hc) (λ h, by rw add_eq_self h; exact max_lt h1 h2) lemma eq_of_add_eq_of_omega_le {a b c : cardinal} (h : a + b = c) (ha : a < c) (hc : omega ≤ c) : b = c := begin apply le_antisymm, { rw [← h], apply cardinal.le_add_left }, rw[← not_lt], intro hb, have : a + b < c := add_lt_of_lt hc ha hb, simpa [h, lt_irrefl] using this end lemma add_eq_left {a b : cardinal} (ha : omega ≤ a) (hb : b ≤ a) : a + b = a := by { rw [add_eq_max ha, max_eq_left hb] } lemma add_eq_right {a b : cardinal} (hb : omega ≤ b) (ha : a ≤ b) : a + b = b := by { rw [add_comm, add_eq_left hb ha] } lemma add_eq_left_iff {a b : cardinal} : a + b = a ↔ (max omega b ≤ a ∨ b = 0) := begin rw [max_le_iff], split, { intro h, cases (le_or_lt omega a) with ha ha, { left, use ha, rw [← not_lt], intro hb, apply ne_of_gt _ h, exact lt_of_lt_of_le hb (le_add_left b a) }, right, rw [← h, add_lt_omega_iff, lt_omega, lt_omega] at ha, rcases ha with ⟨⟨n, rfl⟩, ⟨m, rfl⟩⟩, norm_cast at h ⊢, rw [← add_right_inj, h, add_zero] }, { rintro (⟨h1, h2⟩|h3), rw [add_eq_max h1, max_eq_left h2], rw [h3, add_zero] } end lemma add_eq_right_iff {a b : cardinal} : a + b = b ↔ (max omega a ≤ b ∨ a = 0) := by { rw [add_comm, add_eq_left_iff] } lemma add_one_eq {a : cardinal} (ha : omega ≤ a) : a + 1 = a := have 1 ≤ a, from le_trans (le_of_lt one_lt_omega) ha, add_eq_left ha this protected lemma eq_of_add_eq_add_left {a b c : cardinal} (h : a + b = a + c) (ha : a < omega) : b = c := begin cases le_or_lt omega b with hb hb, { have : a < b := lt_of_lt_of_le ha hb, rw [add_eq_right hb (le_of_lt this), eq_comm] at h, rw [eq_of_add_eq_of_omega_le h this hb] }, { have hc : c < omega, { rw [← not_le], intro hc, apply lt_irrefl omega, apply lt_of_le_of_lt (le_trans hc (le_add_left _ a)), rw [← h], apply add_lt_omega ha hb }, rw [lt_omega] at *, rcases ha with ⟨n, rfl⟩, rcases hb with ⟨m, rfl⟩, rcases hc with ⟨k, rfl⟩, norm_cast at h ⊢, apply add_left_cancel h } end protected lemma eq_of_add_eq_add_right {a b c : cardinal} (h : a + b = c + b) (hb : b < omega) : a = c := by { rw [add_comm a b, add_comm c b] at h, exact cardinal.eq_of_add_eq_add_left h hb } /-! ### Properties about power -/ theorem pow_le {κ μ : cardinal.{u}} (H1 : omega ≤ κ) (H2 : μ < omega) : κ ^ μ ≤ κ := let ⟨n, H3⟩ := lt_omega.1 H2 in H3.symm ▸ (quotient.induction_on κ (λ α H1, nat.rec_on n (le_of_lt $ lt_of_lt_of_le (by rw [nat.cast_zero, power_zero]; from one_lt_omega) H1) (λ n ih, trans_rel_left _ (by rw [nat.cast_succ, power_add, power_one]; from mul_le_mul_right _ ih) (mul_eq_self H1))) H1) lemma power_self_eq {c : cardinal} (h : omega ≤ c) : c ^ c = 2 ^ c := begin apply le_antisymm, { apply le_trans (power_le_power_right $ le_of_lt $ cantor c), rw [power_mul, mul_eq_self h] }, { convert power_le_power_right (le_trans (le_of_lt $ nat_lt_omega 2) h), apply nat.cast_two.symm } end lemma power_nat_le {c : cardinal.{u}} {n : ℕ} (h : omega ≤ c) : c ^ (n : cardinal.{u}) ≤ c := pow_le h (nat_lt_omega n) lemma powerlt_omega {c : cardinal} (h : omega ≤ c) : c ^< omega = c := begin apply le_antisymm, { rw [powerlt_le], intro c', rw [lt_omega], rintro ⟨n, rfl⟩, apply power_nat_le h }, convert le_powerlt one_lt_omega, rw [power_one] end lemma powerlt_omega_le (c : cardinal) : c ^< omega ≤ max c omega := begin cases le_or_gt omega c, { rw [powerlt_omega h], apply le_max_left }, rw [powerlt_le], intros c' hc', refine le_trans (le_of_lt $ power_lt_omega h hc') (le_max_right _ _) end /-! ### Computing cardinality of various types -/ theorem mk_list_eq_mk {α : Type u} (H1 : omega ≤ mk α) : mk (list α) = mk α := eq.symm $ le_antisymm ⟨⟨λ x, [x], λ x y H, (list.cons.inj H).1⟩⟩ $ calc mk (list α) = sum (λ n : ℕ, mk α ^ (n : cardinal.{u})) : mk_list_eq_sum_pow α ... ≤ sum (λ n : ℕ, mk α) : sum_le_sum _ _ $ λ n, pow_le H1 $ nat_lt_omega n ... = sum (λ n : ulift.{u} ℕ, mk α) : quotient.sound ⟨@sigma_congr_left _ _ (λ _, quotient.out (mk α)) equiv.ulift.symm⟩ ... = omega * mk α : sum_const _ _ ... = max (omega) (mk α) : mul_eq_max (le_refl _) H1 ... = mk α : max_eq_right H1 theorem mk_finset_eq_mk {α : Type u} (h : omega ≤ mk α) : mk (finset α) = mk α := eq.symm $ le_antisymm (mk_le_of_injective (λ x y, finset.singleton_inj.1)) $ calc mk (finset α) ≤ mk (list α) : mk_le_of_surjective list.to_finset_surjective ... = mk α : mk_list_eq_mk h lemma mk_bounded_set_le_of_omega_le (α : Type u) (c : cardinal) (hα : omega ≤ mk α) : mk {t : set α // mk t ≤ c} ≤ mk α ^ c := begin refine le_trans _ (by rw [←add_one_eq hα]), refine quotient.induction_on c _, clear c, intro β, fapply mk_le_of_surjective, { intro f, use sum.inl ⁻¹' range f, refine le_trans (mk_preimage_of_injective _ _ (λ x y, sum.inl.inj)) _, apply mk_range_le }, rintro ⟨s, ⟨g⟩⟩, use λ y, if h : ∃(x : s), g x = y then sum.inl (classical.some h).val else sum.inr ⟨⟩, apply subtype.eq, ext, split, { rintro ⟨y, h⟩, dsimp only at h, by_cases h' : ∃ (z : s), g z = y, { rw [dif_pos h'] at h, cases sum.inl.inj h, exact (classical.some h').2 }, { rw [dif_neg h'] at h, cases h }}, { intro h, have : ∃(z : s), g z = g ⟨x, h⟩, exact ⟨⟨x, h⟩, rfl⟩, use g ⟨x, h⟩, dsimp only, rw [dif_pos this], congr', suffices : classical.some this = ⟨x, h⟩, exact congr_arg subtype.val this, apply g.2, exact classical.some_spec this } end lemma mk_bounded_set_le (α : Type u) (c : cardinal) : mk {t : set α // mk t ≤ c} ≤ max (mk α) omega ^ c := begin transitivity mk {t : set (ulift.{u} nat ⊕ α) // mk t ≤ c}, { refine ⟨embedding.subtype_map _ _⟩, apply embedding.image, use sum.inr, apply sum.inr.inj, intros s hs, exact le_trans mk_image_le hs }, refine le_trans (mk_bounded_set_le_of_omega_le (ulift.{u} nat ⊕ α) c (le_add_right omega (mk α))) _, rw [max_comm, ←add_eq_max]; refl end lemma mk_bounded_subset_le {α : Type u} (s : set α) (c : cardinal.{u}) : mk {t : set α // t ⊆ s ∧ mk t ≤ c} ≤ max (mk s) omega ^ c := begin refine le_trans _ (mk_bounded_set_le s c), refine ⟨embedding.cod_restrict _ _ _⟩, use λ t, coe ⁻¹' t.1, { rintros ⟨t, ht1, ht2⟩ ⟨t', h1t', h2t'⟩ h, apply subtype.eq, dsimp only at h ⊢, refine (preimage_eq_preimage' _ _).1 h; rw [subtype.range_coe]; assumption }, rintro ⟨t, h1t, h2t⟩, exact le_trans (mk_preimage_of_injective _ _ subtype.val_injective) h2t end /-! ### Properties of `compl` -/ lemma mk_compl_of_omega_le {α : Type*} (s : set α) (h : omega ≤ #α) (h2 : #s < #α) : #(sᶜ : set α) = #α := by { refine eq_of_add_eq_of_omega_le _ h2 h, exact mk_sum_compl s } lemma mk_compl_finset_of_omega_le {α : Type*} (s : finset α) (h : omega ≤ #α) : #((↑s)ᶜ : set α) = #α := by { apply mk_compl_of_omega_le _ h, exact lt_of_lt_of_le (finset_card_lt_omega s) h } lemma mk_compl_eq_mk_compl_infinite {α : Type*} {s t : set α} (h : omega ≤ #α) (hs : #s < #α) (ht : #t < #α) : #(sᶜ : set α) = #(tᶜ : set α) := by { rw [mk_compl_of_omega_le s h hs, mk_compl_of_omega_le t h ht] } lemma mk_compl_eq_mk_compl_finite_lift {α : Type u} {β : Type v} {s : set α} {t : set β} (hα : #α < omega) (h1 : lift.{u (max v w)} (#α) = lift.{v (max u w)} (#β)) (h2 : lift.{u (max v w)} (#s) = lift.{v (max u w)} (#t)) : lift.{u (max v w)} (#(sᶜ : set α)) = lift.{v (max u w)} (#(tᶜ : set β)) := begin have hα' := hα, have h1' := h1, rw [← mk_sum_compl s, ← mk_sum_compl t] at h1, rw [← mk_sum_compl s, add_lt_omega_iff] at hα, lift #s to ℕ using hα.1 with n hn, lift #(sᶜ : set α) to ℕ using hα.2 with m hm, have : #(tᶜ : set β) < omega, { refine lt_of_le_of_lt (mk_subtype_le _) _, rw [← lift_lt, lift_omega, ← h1', ← lift_omega.{u (max v w)}, lift_lt], exact hα' }, lift #(tᶜ : set β) to ℕ using this with k hk, simp [nat_eq_lift_eq_iff] at h2, rw [nat_eq_lift_eq_iff.{v (max u w)}] at h2, simp [h2.symm] at h1 ⊢, norm_cast at h1, simp at h1, exact h1 end lemma mk_compl_eq_mk_compl_finite {α β : Type u} {s : set α} {t : set β} (hα : #α < omega) (h1 : #α = #β) (h : #s = #t) : #(sᶜ : set α) = #(tᶜ : set β) := by { rw [← lift_inj], apply mk_compl_eq_mk_compl_finite_lift hα; rw [lift_inj]; assumption } lemma mk_compl_eq_mk_compl_finite_same {α : Type*} {s t : set α} (hα : #α < omega) (h : #s = #t) : #(sᶜ : set α) = #(tᶜ : set α) := mk_compl_eq_mk_compl_finite hα rfl h /-! ### Extending an injection to an equiv -/ theorem extend_function {α β : Type*} {s : set α} (f : s ↪ β) (h : nonempty ((sᶜ : set α) ≃ ((range f)ᶜ : set β))) : ∃ (g : α ≃ β), ∀ x : s, g x = f x := begin intros, have := h, cases this with g, let h : α ≃ β := (set.sum_compl (s : set α)).symm.trans ((sum_congr (equiv.set.range f f.2) g).trans (set.sum_compl (range f))), refine ⟨h, _⟩, rintro ⟨x, hx⟩, simp [set.sum_compl_symm_apply_of_mem, hx] end theorem extend_function_finite {α β : Type*} {s : set α} (f : s ↪ β) (hs : #α < omega) (h : nonempty (α ≃ β)) : ∃ (g : α ≃ β), ∀ x : s, g x = f x := begin apply extend_function f, have := h, cases this with g, rw [← lift_mk_eq] at h, rw [←lift_mk_eq, mk_compl_eq_mk_compl_finite_lift hs h], rw [mk_range_eq_lift], exact f.2 end theorem extend_function_of_lt {α β : Type*} {s : set α} (f : s ↪ β) (hs : #s < #α) (h : nonempty (α ≃ β)) : ∃ (g : α ≃ β), ∀ x : s, g x = f x := begin cases (le_or_lt omega (#α)) with hα hα, { apply extend_function f, have := h, cases this with g, rw [← lift_mk_eq] at h, cases cardinal.eq.mp (mk_compl_of_omega_le s hα hs) with g2, cases cardinal.eq.mp (mk_compl_of_omega_le (range f) _ _) with g3, { constructor, exact g2.trans (g.trans g3.symm) }, { rw [← lift_le, ← h], refine le_trans _ (lift_le.mpr hα), simp }, rwa [← lift_lt, ← h, mk_range_eq_lift, lift_lt], exact f.2 }, { exact extend_function_finite f hα h } end section bit /-! This section proves inequalities for `bit0` and `bit1`, enabling `simp` to solve inequalities for numeral cardinals. The complexity of the resulting algorithm is not good, as in some cases `simp` reduces an inequality to a disjunction of two situations, depending on whether a cardinal is finite or infinite. Since the evaluation of the branches is not lazy, this is bad. It is good enough for practical situations, though. For specific numbers, these inequalities could also be deduced from the corresponding inequalities of natural numbers using `norm_cast`: ``` example : (37 : cardinal) < 42 := by { norm_cast, norm_num } ``` -/ @[simp] lemma bit0_ne_zero (a : cardinal) : ¬bit0 a = 0 ↔ ¬a = 0 := by simp [bit0] @[simp] lemma bit1_ne_zero (a : cardinal) : ¬bit1 a = 0 := by simp [bit1] @[simp] lemma zero_lt_bit0 (a : cardinal) : 0 < bit0 a ↔ 0 < a := by { rw ←not_iff_not, simp [bit0], } @[simp] lemma zero_lt_bit1 (a : cardinal) : 0 < bit1 a := lt_of_lt_of_le zero_lt_one (le_add_left _ _) @[simp] lemma one_le_bit0 (a : cardinal) : 1 ≤ bit0 a ↔ 0 < a := ⟨λ h, (zero_lt_bit0 a).mp (lt_of_lt_of_le zero_lt_one h), λ h, le_trans (one_le_iff_pos.mpr h) (le_add_left a a)⟩ @[simp] lemma one_le_bit1 (a : cardinal) : 1 ≤ bit1 a := le_add_left _ _ theorem bit0_eq_self {c : cardinal} (h : omega ≤ c) : bit0 c = c := add_eq_self h @[simp] theorem bit0_lt_omega {c : cardinal} : bit0 c < omega ↔ c < omega := by simp [bit0, add_lt_omega_iff] @[simp] theorem omega_le_bit0 {c : cardinal} : omega ≤ bit0 c ↔ omega ≤ c := by { rw ← not_iff_not, simp } @[simp] theorem bit1_eq_self_iff {c : cardinal} : bit1 c = c ↔ omega ≤ c := begin by_cases h : omega ≤ c, { simp only [bit1, bit0_eq_self h, h, eq_self_iff_true, add_one_of_omega_le] }, { simp only [h, iff_false], apply ne_of_gt, rcases lt_omega.1 (not_le.1 h) with ⟨n, rfl⟩, norm_cast, dsimp [bit1, bit0], omega } end @[simp] theorem bit1_lt_omega {c : cardinal} : bit1 c < omega ↔ c < omega := by simp [bit1, bit0, add_lt_omega_iff, one_lt_omega] @[simp] theorem omega_le_bit1 {c : cardinal} : omega ≤ bit1 c ↔ omega ≤ c := by { rw ← not_iff_not, simp } @[simp] lemma bit0_le_bit0 {a b : cardinal} : bit0 a ≤ bit0 b ↔ a ≤ b := begin by_cases ha : omega ≤ a; by_cases hb : omega ≤ b, { rw [bit0_eq_self ha, bit0_eq_self hb] }, { rw bit0_eq_self ha, have I1 : ¬ (a ≤ b), { assume h, apply hb, exact le_trans ha h }, have I2 : ¬ (a ≤ bit0 b), { assume h, have A : bit0 b < omega, by simpa using hb, exact lt_irrefl _ (lt_of_lt_of_le (lt_of_lt_of_le A ha) h) }, simp [I1, I2] }, { rw [bit0_eq_self hb], simp only [not_le] at ha, have I1 : a ≤ b := le_of_lt (lt_of_lt_of_le ha hb), have I2 : bit0 a ≤ b := le_trans (le_of_lt (bit0_lt_omega.2 ha)) hb, simp [I1, I2] }, { simp at ha hb, rcases lt_omega.1 ha with ⟨m, rfl⟩, rcases lt_omega.1 hb with ⟨n, rfl⟩, norm_cast, simp } end @[simp] lemma bit0_le_bit1 {a b : cardinal} : bit0 a ≤ bit1 b ↔ a ≤ b := begin by_cases ha : omega ≤ a; by_cases hb : omega ≤ b, { rw [bit0_eq_self ha, bit1_eq_self_iff.2 hb], }, { rw bit0_eq_self ha, have I1 : ¬ (a ≤ b), { assume h, apply hb, exact le_trans ha h }, have I2 : ¬ (a ≤ bit1 b), { assume h, have A : bit1 b < omega, by simpa using hb, exact lt_irrefl _ (lt_of_lt_of_le (lt_of_lt_of_le A ha) h) }, simp [I1, I2] }, { rw [bit1_eq_self_iff.2 hb], simp only [not_le] at ha, have I1 : a ≤ b := le_of_lt (lt_of_lt_of_le ha hb), have I2 : bit0 a ≤ b := le_trans (le_of_lt (bit0_lt_omega.2 ha)) hb, simp [I1, I2] }, { simp at ha hb, rcases lt_omega.1 ha with ⟨m, rfl⟩, rcases lt_omega.1 hb with ⟨n, rfl⟩, norm_cast, simp } end @[simp] lemma bit1_le_bit1 {a b : cardinal} : bit1 a ≤ bit1 b ↔ a ≤ b := begin split, { assume h, apply bit0_le_bit1.1 (le_trans ((bit0 a).le_add_right 1) h) }, { assume h, calc a + a + 1 ≤ a + b + 1 : add_le_add_right 1 (add_le_add_left a h) ... ≤ b + b + 1 : add_le_add_right 1 (add_le_add_right b h) } end @[simp] lemma bit1_le_bit0 {a b : cardinal} : bit1 a ≤ bit0 b ↔ (a < b ∨ (a ≤ b ∧ omega ≤ a)) := begin by_cases ha : omega ≤ a; by_cases hb : omega ≤ b, { simp only [bit1_eq_self_iff.mpr ha, bit0_eq_self hb, ha, and_true], refine ⟨λ h, or.inr h, λ h, _⟩, cases h, { exact le_of_lt h }, { exact h } }, { rw bit1_eq_self_iff.2 ha, have I1 : ¬ (a ≤ b), { assume h, apply hb, exact le_trans ha h }, have I2 : ¬ (a ≤ bit0 b), { assume h, have A : bit0 b < omega, by simpa using hb, exact lt_irrefl _ (lt_of_lt_of_le (lt_of_lt_of_le A ha) h) }, simp [I1, I2, le_of_not_ge I1] }, { rw [bit0_eq_self hb], simp only [not_le] at ha, have I1 : a < b := lt_of_lt_of_le ha hb, have I2 : bit1 a ≤ b := le_trans (le_of_lt (bit1_lt_omega.2 ha)) hb, simp [I1, I2] }, { simp at ha hb, rcases lt_omega.1 ha with ⟨m, rfl⟩, rcases lt_omega.1 hb with ⟨n, rfl⟩, norm_cast, simp [not_le.mpr ha], } end @[simp] lemma bit0_lt_bit0 {a b : cardinal} : bit0 a < bit0 b ↔ a < b := begin by_cases ha : omega ≤ a; by_cases hb : omega ≤ b, { rw [bit0_eq_self ha, bit0_eq_self hb] }, { rw bit0_eq_self ha, have I1 : ¬ (a < b), { assume h, apply hb, exact le_trans ha (le_of_lt h) }, have I2 : ¬ (a < bit0 b), { assume h, have A : bit0 b < omega, by simpa using hb, exact lt_irrefl _ (lt_trans (lt_of_lt_of_le A ha) h) }, simp [I1, I2] }, { rw [bit0_eq_self hb], simp only [not_le] at ha, have I1 : a < b := lt_of_lt_of_le ha hb, have I2 : bit0 a < b := lt_of_lt_of_le (bit0_lt_omega.2 ha) hb, simp [I1, I2] }, { simp at ha hb, rcases lt_omega.1 ha with ⟨m, rfl⟩, rcases lt_omega.1 hb with ⟨n, rfl⟩, norm_cast, simp } end @[simp] lemma bit1_lt_bit0 {a b : cardinal} : bit1 a < bit0 b ↔ a < b := begin by_cases ha : omega ≤ a; by_cases hb : omega ≤ b, { rw [bit1_eq_self_iff.2 ha, bit0_eq_self hb], }, { rw bit1_eq_self_iff.2 ha, have I1 : ¬ (a < b), { assume h, apply hb, exact le_of_lt (lt_of_le_of_lt ha h) }, have I2 : ¬ (a < bit0 b), { assume h, have A : bit0 b < omega, by simpa using hb, exact lt_irrefl _ (lt_trans (lt_of_lt_of_le A ha) h) }, simp [I1, I2] }, { rw [bit0_eq_self hb], simp only [not_le] at ha, have I1 : a < b := (lt_of_lt_of_le ha hb), have I2 : bit1 a < b := lt_of_lt_of_le (bit1_lt_omega.2 ha) hb, simp [I1, I2] }, { simp at ha hb, rcases lt_omega.1 ha with ⟨m, rfl⟩, rcases lt_omega.1 hb with ⟨n, rfl⟩, norm_cast, simp } end @[simp] lemma bit1_lt_bit1 {a b : cardinal} : bit1 a < bit1 b ↔ a < b := begin by_cases ha : omega ≤ a; by_cases hb : omega ≤ b, { rw [bit1_eq_self_iff.2 ha, bit1_eq_self_iff.2 hb], }, { rw bit1_eq_self_iff.2 ha, have I1 : ¬ (a < b), { assume h, apply hb, exact le_of_lt (lt_of_le_of_lt ha h) }, have I2 : ¬ (a < bit1 b), { assume h, have A : bit1 b < omega, by simpa using hb, exact lt_irrefl _ (lt_trans (lt_of_lt_of_le A ha) h) }, simp [I1, I2] }, { rw [bit1_eq_self_iff.2 hb], simp only [not_le] at ha, have I1 : a < b := (lt_of_lt_of_le ha hb), have I2 : bit1 a < b := lt_of_lt_of_le (bit1_lt_omega.2 ha) hb, simp [I1, I2] }, { simp at ha hb, rcases lt_omega.1 ha with ⟨m, rfl⟩, rcases lt_omega.1 hb with ⟨n, rfl⟩, norm_cast, simp } end @[simp] lemma bit0_lt_bit1 {a b : cardinal} : bit0 a < bit1 b ↔ (a < b ∨ (a ≤ b ∧ a < omega)) := begin by_cases ha : omega ≤ a; by_cases hb : omega ≤ b, { simp [bit0_eq_self ha, bit1_eq_self_iff.2 hb, not_lt.mpr ha] }, { rw bit0_eq_self ha, have I1 : ¬ (a < b), { assume h, apply hb, exact le_of_lt (lt_of_le_of_lt ha h) }, have I2 : ¬ (a < bit1 b), { assume h, have A : bit1 b < omega, by simpa using hb, exact lt_irrefl _ (lt_trans (lt_of_lt_of_le A ha) h) }, simp [I1, I2, not_lt.mpr ha] }, { rw [bit1_eq_self_iff.2 hb], simp only [not_le] at ha, have I1 : a < b := (lt_of_lt_of_le ha hb), have I2 : bit0 a < b := lt_of_lt_of_le (bit0_lt_omega.2 ha) hb, simp [I1, I2] }, { simp at ha hb, rcases lt_omega.1 ha with ⟨m, rfl⟩, rcases lt_omega.1 hb with ⟨n, rfl⟩, norm_cast, simp only [ha, and_true, nat.bit0_lt_bit1_iff], refine ⟨λ h, or.inr h, λ h, _⟩, cases h, { exact le_of_lt h }, { exact h } } end lemma one_lt_two : (1 : cardinal) < 2 := -- This strategy works generally to prove inequalities between numerals in `cardinality`. by { norm_cast, norm_num } @[simp] lemma one_lt_bit0 {a : cardinal} : 1 < bit0 a ↔ 0 < a := by simp [← bit1_zero] @[simp] lemma one_lt_bit1 (a : cardinal) : 1 < bit1 a ↔ 0 < a := by simp [← bit1_zero] @[simp] lemma one_le_one : (1 : cardinal) ≤ 1 := le_refl _ end bit end cardinal
c1e7d376303ffe11c6f639b0559eba44c78b98fa
c45b34bfd44d8607a2e8762c926e3cfaa7436201
/uexp/src/uexp/cosette_tactics.lean
4d6ceefc030828de65e238416a40ba35bcd0983b
[ "BSD-2-Clause" ]
permissive
Shamrock-Frost/Cosette
b477c442c07e45082348a145f19ebb35a7f29392
24cbc4adebf627f13f5eac878f04ffa20d1209af
refs/heads/master
1,619,721,304,969
1,526,082,841,000
1,526,082,841,000
121,695,605
1
0
null
1,518,737,210,000
1,518,737,210,000
null
UTF-8
Lean
false
false
14,455
lean
import system.io import .u_semiring import .cosette_lemmas open nat io open list io section cosette_tactics def list.swap_ith_forward {α : Type} {f : Type → Type} [alternative f] : nat → list α → f (list α) | 0 (x::y::zs) := pure $ y :: x :: zs | (nat.succ n) (x::xs) := list.cons x <$> list.swap_ith_forward n xs | _ _ := failure lemma swap_gives_result_if_index_in_range {α : Type} : ∀ (ls : list α) i, i + 2 < list.length ls → { ls' : list α // list.swap_ith_forward i ls = some ls' } := begin intros ls i h, revert ls, induction i with j ih; intros; cases ls with x ys, { exfalso, cases h }, { cases ys with y zs, { exfalso, cases h, cases h_a }, { existsi (y :: x :: zs), refl } }, { exfalso, cases h }, { cases ih ys _ with ys' h', existsi x :: ys', unfold list.swap_ith_forward, rw h', refl, apply nat.lt_of_succ_lt_succ, assumption } end meta def expr.swap_free_vars (i : nat) (j : nat) : expr → expr | (expr.var n) := if n = i then expr.var j else if n = j then expr.var i else expr.var n | (expr.app f x) := expr.app (expr.swap_free_vars f) (expr.swap_free_vars x) | (expr.lam n bi ty body) := let ty' := expr.swap_free_vars ty, body' := expr.swap_free_vars body in expr.lam n bi ty' body' | (expr.pi n bi ty body) := let ty' := expr.swap_free_vars ty, body' := expr.swap_free_vars body in expr.pi n bi ty' body' | (expr.elet n ty val body) := let ty' := expr.swap_free_vars ty, val' := expr.swap_free_vars val, body' := expr.swap_free_vars body in expr.elet n ty' val' body' | ex := ex -- substitute variable and also lift de bruijn index meta def expr.subst_var (target: expr) : expr → expr := λ e, if e = target then (expr.var 0) else match e with | (expr.var n) := expr.var (n+1) | (expr.app f x) := expr.app (expr.subst_var f) (expr.subst_var x) | (expr.lam n bi ty body) := expr.lam n bi (expr.subst_var ty) (expr.subst_var body) | (expr.pi n bi ty body) := expr.pi n bi (expr.subst_var ty) (expr.subst_var body) | (expr.elet n ty val body) := let ty' := expr.subst_var ty, val' := expr.subst_var val, body' := expr.subst_var body in expr.elet n ty' val' body' | ex := ex end -- substitute variable without lift de bruijn index meta def expr.subst_var' (target: expr) (replacement: expr) : expr → expr := λ e, if e = target then replacement else match e with | (expr.var n) := expr.var n | (expr.app f x) := expr.app (expr.subst_var' f) (expr.subst_var' x) | (expr.lam n bi ty body) := expr.lam n bi (expr.subst_var' ty) (expr.subst_var' body) | (expr.pi n bi ty body) := expr.pi n bi (expr.subst_var' ty) (expr.subst_var' body) | (expr.elet n ty val body) := let ty' := expr.subst_var' ty, val' := expr.subst_var' val, body' := expr.subst_var' body in expr.elet n ty' val' body' | ex := ex end def move_nth_to_kth {α : Type} {m : Type → Type} [alternative m] [monad m] (final initial : ℕ) (ls : list α) : m (list α) := list.append (ls.take initial) <$> nat.repeat (λ n (ls' : m (list α)), ls' >>= list.swap_ith_forward (final - n - 1)) (final - initial) (return $ ls.drop initial) universes u v w def congr_arg₂ {α : Sort u} {β : Sort v} {γ : Sort w} {a₁ a₂ : α} {b₁ b₂ : β} (f : α → β → γ) : a₁ = a₂ → b₁ = b₂ → f a₁ b₁ = f a₂ b₂ := begin intros, apply congr, { apply congr_arg, assumption }, { assumption } end -- repeat tacitic t exactly n times meta def repeat_n (n: nat) (t: tactic unit) : tactic unit := nat.repeat (λ n next, t >> next) n $ return () -- check if an expr is in the list meta def expr_in : expr → list expr → bool := (λ e l, match l with | [] := ff | (h :: t) := if h=e then tt else (expr_in e t) end) meta def get_eq_sides : tactic (expr × expr) := tactic.target >>= λ e, match e with | `(%%a = %%b) := return (a, b) | _ := tactic.failed end meta def get_lhs : tactic expr := prod.fst <$> get_eq_sides meta def get_rhs : tactic expr := prod.snd <$> get_eq_sides meta def solved_or_continue (next: tactic unit) : tactic unit := do tactic.try tactic.reflexivity, ok ← list.empty <$> tactic.get_goals, if ok then return () else next meta def print_goals : tactic unit := do goals ← tactic.get_goals, tactic.trace goals meta def repeat_or_sol (f: ℕ → tactic unit) : ℕ → tactic unit | 0 := (f 0) | (nat.succ n) := do repeat_or_sol n, ok ← list.empty <$> tactic.get_goals, if ok then return () else (f n) meta def beta_reduction (e: expr): tactic unit := do reduced ← tactic.head_beta e, n ← tactic.mk_fresh_name, tactic.to_expr ``(%%e=%%reduced) >>= tactic.assert n, tactic.reflexivity, eq_lemma ← tactic.resolve_name n >>= tactic.to_expr, tactic.rewrite_target eq_lemma, tactic.clear eq_lemma -- this assume that expr is a right associative product private meta def ra_product_to_repr' : expr → list expr | `(%%a * %%b) := a :: ra_product_to_repr' b | e := [e] -- this assume that expr is a right associative product meta def ra_product_to_repr (e: expr) : tactic (list expr) := return $ ra_product_to_repr' e meta def repr_to_product : list expr → tactic expr | [x] := return x | (h::t) := do te ← repr_to_product t, tactic.to_expr ``(%%h * %%te) | [] := tactic.to_expr ``(usr.one) -- this doesn't assume any form of the product expr private meta def product_to_repr' : expr → list expr | `(%%a * %%b) := (product_to_repr' a) ++ (product_to_repr' b) | x := [x] meta def product_to_repr (e: expr) : tactic (list expr) := return $ product_to_repr' e meta def is_ueq : expr → bool | `(_ ≃ _) := tt | _ := ff meta def get_ueqs (l: list expr) : list expr := list.filter (λ e, is_ueq e = tt) l meta def get_non_ueqs (l: list expr) : list expr := list.filter (λ e, is_ueq e = ff) l -- assuming lhs is in the form of a*b*c meta def get_lhs_repr1 : tactic (list expr) := tactic.target >>= λ e, match e with | `(%%a * _ * _ = %%_) := ra_product_to_repr a | _ := tactic.failed end -- assuming lhs is in the form of a*b*c meta def get_lhs_repr2 : tactic (list expr) := tactic.target >>= λ e, match e with | `(_ * %%a * _ = _) := ra_product_to_repr a | _ := tactic.failed end -- assuming lhs is in the form of a*b*c meta def get_lhs_repr3 : tactic (list expr) := tactic.target >>= λ e, match e with | `(_ * _ * %%a = _) := ra_product_to_repr a | _ := tactic.failed end meta def get_lhs_expr3 : tactic expr := tactic.target >>= λ e, match e with | `(_ * _ * %%a = _) := return a | _ := tactic.failed end -- swap i-th element in a product forward meta def swap_element_forward (i: nat) (l: list expr) : tactic unit := do swapped_list ← list.swap_ith_forward i l, origin_expr ← repr_to_product l, swapped_expr ← repr_to_product swapped_list, eq_lemma ← tactic.to_expr ``(%%origin_expr = %%swapped_expr), eq_lemma_name ← tactic.mk_fresh_name, tactic.assert eq_lemma_name eq_lemma, repeat_n i $ (tactic.to_expr ``(congr_arg (has_mul.mul _)) >>= tactic.apply >> return ()), tactic.applyc `prod_symm_assoc <|> tactic.applyc `mul_comm, eq_lemma ← tactic.resolve_name eq_lemma_name >>= tactic.to_expr, tactic.rewrite_target eq_lemma, tactic.clear eq_lemma -- suppose i > j meta def forward_i_to_j (i : nat) (j: nat) : tactic unit := let loop : nat → tactic unit → tactic unit := λ iter_num next_iter, do next_iter, repr ← get_lhs_repr1, swap_element_forward (i - iter_num -1) repr in nat.repeat loop (i - j) $ return () -- the first nat is the size of body, the second nat is iteration meta def repeat_if_progress (f: ℕ → ℕ → (tactic ℕ)) : ℕ → ℕ → (tactic ℕ) | (s) 0 := return 0 | (s) (nat.succ n) := do s' ← f s (s - n - 1), repeat_if_progress s' n meta structure usr_sigma_repr := (var_schemas : list expr) (body : expr) meta instance sigma_repr_format : has_to_format usr_sigma_repr := ⟨λ sig, format.cbrace $ "var_schemas := " ++ to_fmt sig.var_schemas ++ "," ++ " body := " ++ to_fmt sig.body⟩ meta def sigma_expr_to_sigma_repr : expr → usr_sigma_repr | `(usr.sig (λ t : Tuple %%s, %%a)) := match sigma_expr_to_sigma_repr a with | ⟨var_schemas, inner⟩ := ⟨s :: var_schemas, inner⟩ end | e := ⟨[], e⟩ -- This needs to be a tactic so we can resolve `Tuple and `usr.sig meta def sigma_repr_to_sigma_expr : usr_sigma_repr → tactic expr | ⟨[], body⟩ := return body | ⟨t::ts, body⟩ := do body' ← sigma_repr_to_sigma_expr ⟨ts, body⟩, n ← tactic.get_unused_name `x, ty ← tactic.to_expr ``(Tuple %%t), let lam : expr := expr.lam n binder_info.default ty body', tactic.to_expr ``(usr.sig %%lam) meta def get_lhs_sigma_repr : tactic usr_sigma_repr := tactic.target >>= λ e, match e with | `(%%a = %%b) := return $ sigma_expr_to_sigma_repr a | _ := tactic.failed end meta def sigma_repr_to_closed_body_expr : usr_sigma_repr → tactic (expr × list name) | ⟨schemas, body⟩ := do lconsts ← list.mfoldr (λ (t : expr) (lconsts : list (expr × name)), do n ← tactic.mk_fresh_name, n' ← tactic.mk_fresh_name, ty ← tactic.to_expr ``(Tuple %%t), let local_const := expr.local_const n n' binder_info.default ty, return $ (local_const, n) :: lconsts) [] $ list.reverse schemas, let ⟨lconsts', names⟩ := lconsts.unzip, return (expr.instantiate_vars body lconsts', names) private meta def get_types_of_local_consts (ns : list name) : expr → list (nat × expr) | (expr.app f x) := list.union (get_types_of_local_consts f) $ get_types_of_local_consts x | (expr.lam n bi ty body) := list.union (get_types_of_local_consts ty) $ get_types_of_local_consts body | (expr.pi n bi ty body) := list.union (get_types_of_local_consts ty) $ get_types_of_local_consts body | (expr.elet n ty val body) := list.union (get_types_of_local_consts ty) $ list.union (get_types_of_local_consts val) $ get_types_of_local_consts body | (expr.local_const n _ _ ty) := let idx : option nat := list.rec none (λ n' ns res, if n = n' then some 0 else nat.succ <$> res) ns in match idx with | some i := [(i, ty)] | none := [] end | _ := [] meta def closed_sigma_repr_to_sigma_repr (body : expr) (names : list name) : tactic usr_sigma_repr := do schemas ← monad.sequence $ list.map (λ p : nat × expr, match p with | (_, `(Tuple %%s)) := return s | _ := tactic.failed end) $ list.qsort (λ x y : nat × expr, x.fst ≥ y.fst) $ get_types_of_local_consts names body, return $ usr_sigma_repr.mk schemas $ expr.abstract_locals body $ list.reverse names meta def forward_i_to_j_in_sig (i: nat) (j: nat) : tactic unit := do lr ← get_lhs_sigma_repr, match lr with |⟨xs, body⟩ := do le ← product_to_repr body, le' ← move_nth_to_kth i j le, body' ← repr_to_product le', origin ← get_lhs, new ← sigma_repr_to_sigma_expr ⟨xs, body'⟩, eq_lemma ← tactic.to_expr ``(%%origin = %%new), lemma_name ← tactic.mk_fresh_name, tactic.assert lemma_name eq_lemma, repeat_n (list.length xs) $ tactic.applyc `congr_arg >> tactic.funext, tactic.ac_refl, eq_lemma_name ← tactic.resolve_name lemma_name >>= tactic.to_expr, tactic.rewrite_target eq_lemma_name, tactic.clear eq_lemma_name end meta def sig_body_size : tactic ℕ := do lr ← get_lhs_sigma_repr, match lr with |⟨xs, body⟩ := do le ← product_to_repr body, return $ list.length le end meta def split_pairs : tactic unit := do `[repeat {rw eq_pair <|> rw eq_pair'}, try {dsimp}] meta def get_table_and_column (e : expr) : option (expr × expr) := let fn := expr.get_app_fn e in do match fn with | (expr.const n _) := if n = `isKey then match list.reverse $ expr.get_app_args e with | (rel::col::_) := some (rel, col) | _ := none end else none | _ := none end meta structure key_constraint := (name : expr) (table : expr) (column : expr) meta instance key_constraint_to_format : has_to_format key_constraint := ⟨λ kc, format.cbrace $ "name := " ++ to_fmt kc.name ++ "," ++ " table := " ++ to_fmt kc.table ++ "," ++ " column := " ++ to_fmt kc.column⟩ meta def find_keys : tactic (list key_constraint) := do hyps ← tactic.local_context, hyp_types ← monad.mapm tactic.infer_type hyps, return $ list.filter_map (λ (name_and_type : expr × expr), match name_and_type with | (key_name, key_type) := match get_table_and_column key_type with | some (rel, col) := some $ key_constraint.mk key_name rel col | none := none end end) $ list.zip hyps hyp_types meta def try_me : tactic unit := do ks ← find_keys, tactic.trace ks meta def unfold_all_denotations := `[ repeat { unfold denoteSQL <|> unfold denotePred <|> unfold denoteProj <|> unfold denoteExpr <|> unfold groupBy <|> unfold combineGroupByProj <|> unfold pair <|> unfold plainGroupByProj <|> unfold aggregatorGroupByProj} ] end cosette_tactics
ab92e7168867e729db9e3349d14cea92c8b51db2
4fa161becb8ce7378a709f5992a594764699e268
/src/topology/instances/real.lean
1e07deee3013b4bbf5d971f99df521120ed7d060
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
14,879
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 The real numbers ℝ. They are constructed as the topological completion of ℚ. With the following steps: (1) prove that ℚ forms a uniform space. (2) subtraction and addition are uniform continuous functions in this space (3) for multiplication and inverse this only holds on bounded subsets (4) ℝ is defined as separated Cauchy filters over ℚ (the separation requires a quotient construction) (5) extend the uniform continuous functions along the completion (6) proof field properties using the principle of extension of identities TODO generalizations: * topological groups & rings * order topologies * Archimedean fields -/ import topology.metric_space.basic import topology.algebra.uniform_group import topology.algebra.ring noncomputable theory open classical set filter topological_space metric open_locale classical open_locale topological_space universes u v w variables {α : Type u} {β : Type v} {γ : Type w} instance : metric_space ℚ := metric_space.induced coe rat.cast_injective real.metric_space theorem rat.dist_eq (x y : ℚ) : dist x y = abs (x - y) := rfl @[norm_cast, simp] lemma rat.dist_cast (x y : ℚ) : dist (x : ℝ) y = dist x y := rfl section low_prio -- we want to ignore this instance for the next declaration local attribute [instance, priority 10] int.uniform_space instance : metric_space ℤ := begin letI M := metric_space.induced coe int.cast_injective real.metric_space, refine @metric_space.replace_uniformity _ int.uniform_space M (le_antisymm refl_le_uniformity $ λ r ru, mem_uniformity_dist.2 ⟨1, zero_lt_one, λ a b h, mem_principal_sets.1 ru $ dist_le_zero.1 (_ : (abs (a - b) : ℝ) ≤ 0)⟩), have : (abs (↑a - ↑b) : ℝ) < 1 := h, have : abs (a - b) < 1, by norm_cast at this; assumption, have : abs (a - b) ≤ 0 := (@int.lt_add_one_iff _ 0).mp this, norm_cast, assumption end end low_prio theorem int.dist_eq (x y : ℤ) : dist x y = abs (x - y) := rfl @[norm_cast, simp] theorem int.dist_cast_real (x y : ℤ) : dist (x : ℝ) y = dist x y := rfl @[norm_cast, simp] theorem int.dist_cast_rat (x y : ℤ) : dist (x : ℚ) y = dist x y := by rw [← int.dist_cast_real, ← rat.dist_cast]; congr' 1; norm_cast theorem uniform_continuous_of_rat : uniform_continuous (coe : ℚ → ℝ) := uniform_continuous_comap theorem uniform_embedding_of_rat : uniform_embedding (coe : ℚ → ℝ) := uniform_embedding_comap rat.cast_injective theorem dense_embedding_of_rat : dense_embedding (coe : ℚ → ℝ) := uniform_embedding_of_rat.dense_embedding $ λ x, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε,ε0, hε⟩ := mem_nhds_iff.1 ht in let ⟨q, h⟩ := exists_rat_near x ε0 in ⟨_, hε (mem_ball'.2 h), q, rfl⟩ theorem embedding_of_rat : embedding (coe : ℚ → ℝ) := dense_embedding_of_rat.to_embedding theorem continuous_of_rat : continuous (coe : ℚ → ℝ) := uniform_continuous_of_rat.continuous theorem real.uniform_continuous_add : uniform_continuous (λp : ℝ × ℝ, p.1 + p.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ h₁ h₂⟩ -- TODO(Mario): Find a way to use rat_add_continuous_lemma theorem rat.uniform_continuous_add : uniform_continuous (λp : ℚ × ℚ, p.1 + p.2) := uniform_embedding_of_rat.to_uniform_inducing.uniform_continuous_iff.2 $ by simp [(∘)]; exact real.uniform_continuous_add.comp ((uniform_continuous_of_rat.comp uniform_continuous_fst).prod_mk (uniform_continuous_of_rat.comp uniform_continuous_snd)) theorem real.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℝ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [real.dist_eq] using h⟩ theorem rat.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℚ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [rat.dist_eq] using h⟩ instance : uniform_add_group ℝ := uniform_add_group.mk' real.uniform_continuous_add real.uniform_continuous_neg instance : uniform_add_group ℚ := uniform_add_group.mk' rat.uniform_continuous_add rat.uniform_continuous_neg -- short-circuit type class inference instance : topological_add_group ℝ := by apply_instance instance : topological_add_group ℚ := by apply_instance instance : order_topology ℚ := induced_order_topology _ (λ x y, rat.cast_lt) (@exists_rat_btwn _ _ _) lemma real.is_topological_basis_Ioo_rat : @is_topological_basis ℝ _ (⋃(a b : ℚ) (h : a < b), {Ioo a b}) := is_topological_basis_of_open_of_nhds (by simp [is_open_Ioo] {contextual:=tt}) (assume a v hav hv, let ⟨l, u, hl, hu, h⟩ := (mem_nhds_unbounded (no_top _) (no_bot _)).mp (mem_nhds_sets hv hav), ⟨q, hlq, hqa⟩ := exists_rat_btwn hl, ⟨p, hap, hpu⟩ := exists_rat_btwn hu in ⟨Ioo q p, by simp; exact ⟨q, p, rat.cast_lt.1 $ lt_trans hqa hap, rfl⟩, ⟨hqa, hap⟩, assume a' ⟨hqa', ha'p⟩, h _ (lt_trans hlq hqa') (lt_trans ha'p hpu)⟩) instance : second_countable_topology ℝ := ⟨⟨(⋃(a b : ℚ) (h : a < b), {Ioo a b}), by simp [countable_Union, countable_Union_Prop], real.is_topological_basis_Ioo_rat.2.2⟩⟩ /- TODO(Mario): Prove that these are uniform isomorphisms instead of uniform embeddings lemma uniform_embedding_add_rat {r : ℚ} : uniform_embedding (λp:ℚ, p + r) := _ lemma uniform_embedding_mul_rat {q : ℚ} (hq : q ≠ 0) : uniform_embedding ((*) q) := _ -/ lemma real.uniform_continuous_inv (s : set ℝ) {r : ℝ} (r0 : 0 < r) (H : ∀ x ∈ s, r ≤ abs x) : uniform_continuous (λp:s, p.1⁻¹) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abs ε0 r0 in ⟨δ, δ0, λ a b h, Hδ (H _ a.2) (H _ b.2) h⟩ lemma real.uniform_continuous_abs : uniform_continuous (abs : ℝ → ℝ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b, lt_of_le_of_lt (abs_abs_sub_abs_le_abs_sub _ _)⟩ lemma real.continuous_abs : continuous (abs : ℝ → ℝ) := real.uniform_continuous_abs.continuous lemma rat.uniform_continuous_abs : uniform_continuous (abs : ℚ → ℚ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b h, lt_of_le_of_lt (by simpa [rat.dist_eq] using abs_abs_sub_abs_le_abs_sub _ _) h⟩ lemma rat.continuous_abs : continuous (abs : ℚ → ℚ) := rat.uniform_continuous_abs.continuous lemma real.tendsto_inv {r : ℝ} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (𝓝 r) (𝓝 r⁻¹) := by rw ← abs_pos_iff at r0; exact tendsto_of_uniform_continuous_subtype (real.uniform_continuous_inv {x | abs r / 2 < abs x} (half_pos r0) (λ x h, le_of_lt h)) (mem_nhds_sets (real.continuous_abs _ $ is_open_lt' (abs r / 2)) (half_lt_self r0)) lemma real.continuous_inv : continuous (λa:{r:ℝ // r ≠ 0}, a.val⁻¹) := continuous_iff_continuous_at.mpr $ assume ⟨r, hr⟩, tendsto.comp (real.tendsto_inv hr) (continuous_iff_continuous_at.mp continuous_subtype_val _) lemma real.continuous.inv [topological_space α] {f : α → ℝ} (h : ∀a, f a ≠ 0) (hf : continuous f) : continuous (λa, (f a)⁻¹) := show continuous ((has_inv.inv ∘ @subtype.val ℝ (λr, r ≠ 0)) ∘ λa, ⟨f a, h a⟩), from real.continuous_inv.comp (continuous_subtype_mk _ hf) lemma real.uniform_continuous_mul_const {x : ℝ} : uniform_continuous ((*) x) := metric.uniform_continuous_iff.2 $ λ ε ε0, begin cases no_top (abs x) with y xy, have y0 := lt_of_le_of_lt (abs_nonneg _) xy, refine ⟨_, div_pos ε0 y0, λ a b h, _⟩, rw [real.dist_eq, ← mul_sub, abs_mul, ← mul_div_cancel' ε (ne_of_gt y0)], exact mul_lt_mul' (le_of_lt xy) h (abs_nonneg _) y0 end lemma real.uniform_continuous_mul (s : set (ℝ × ℝ)) {r₁ r₂ : ℝ} (H : ∀ x ∈ s, abs (x : ℝ × ℝ).1 < r₁ ∧ abs x.2 < r₂) : uniform_continuous (λp:s, p.1.1 * p.1.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ (H _ a.2).1 (H _ b.2).2 h₁ h₂⟩ protected lemma real.continuous_mul : continuous (λp : ℝ × ℝ, p.1 * p.2) := continuous_iff_continuous_at.2 $ λ ⟨a₁, a₂⟩, tendsto_of_uniform_continuous_subtype (real.uniform_continuous_mul ({x | abs x < abs a₁ + 1}.prod {x | abs x < abs a₂ + 1}) (λ x, id)) (mem_nhds_sets (is_open_prod (real.continuous_abs _ $ is_open_gt' (abs a₁ + 1)) (real.continuous_abs _ $ is_open_gt' (abs a₂ + 1))) ⟨lt_add_one (abs a₁), lt_add_one (abs a₂)⟩) instance : topological_ring ℝ := { continuous_mul := real.continuous_mul, ..real.topological_add_group } instance : topological_semiring ℝ := by apply_instance -- short-circuit type class inference lemma rat.continuous_mul : continuous (λp : ℚ × ℚ, p.1 * p.2) := embedding_of_rat.continuous_iff.2 $ by simp [(∘)]; exact real.continuous_mul.comp ((continuous_of_rat.comp continuous_fst).prod_mk (continuous_of_rat.comp continuous_snd)) instance : topological_ring ℚ := { continuous_mul := rat.continuous_mul, ..rat.topological_add_group } theorem real.ball_eq_Ioo (x ε : ℝ) : ball x ε = Ioo (x - ε) (x + ε) := set.ext $ λ y, by rw [mem_ball, real.dist_eq, abs_sub_lt_iff, sub_lt_iff_lt_add', and_comm, sub_lt]; refl theorem real.Ioo_eq_ball (x y : ℝ) : Ioo x y = ball ((x + y) / 2) ((y - x) / 2) := by rw [real.ball_eq_Ioo, ← sub_div, add_comm, ← sub_add, add_sub_cancel', add_self_div_two, ← add_div, add_assoc, add_sub_cancel'_right, add_self_div_two] lemma real.totally_bounded_Ioo (a b : ℝ) : totally_bounded (Ioo a b) := metric.totally_bounded_iff.2 $ λ ε ε0, begin rcases exists_nat_gt ((b - a) / ε) with ⟨n, ba⟩, rw [div_lt_iff' ε0, sub_lt_iff_lt_add'] at ba, let s := (λ i:ℕ, a + ε * i) '' {i:ℕ | i < n}, refine ⟨s, finite_image _ ⟨set.fintype_lt_nat _⟩, λ x h, _⟩, rcases h with ⟨ax, xb⟩, let i : ℕ := ⌊(x - a) / ε⌋.to_nat, have : (i : ℤ) = ⌊(x - a) / ε⌋ := int.to_nat_of_nonneg (floor_nonneg.2 $ le_of_lt (div_pos (sub_pos.2 ax) ε0)), simp, use i, split, { rw [← int.coe_nat_lt, this], refine int.cast_lt.1 (lt_of_le_of_lt (floor_le _) _), rw [int.cast_coe_nat, div_lt_iff' ε0, sub_lt_iff_lt_add'], exact lt_trans xb ba }, { rw [real.dist_eq, ← int.cast_coe_nat, this, abs_of_nonneg, ← sub_sub, sub_lt_iff_lt_add'], { have := lt_floor_add_one ((x - a) / ε), rwa [div_lt_iff' ε0, mul_add, mul_one] at this }, { have := floor_le ((x - a) / ε), rwa [sub_nonneg, ← le_sub_iff_add_le', ← le_div_iff' ε0] } } end lemma real.totally_bounded_ball (x ε : ℝ) : totally_bounded (ball x ε) := by rw real.ball_eq_Ioo; apply real.totally_bounded_Ioo lemma real.totally_bounded_Ico (a b : ℝ) : totally_bounded (Ico a b) := let ⟨c, ac⟩ := no_bot a in totally_bounded_subset (by exact λ x ⟨h₁, h₂⟩, ⟨lt_of_lt_of_le ac h₁, h₂⟩) (real.totally_bounded_Ioo c b) lemma real.totally_bounded_Icc (a b : ℝ) : totally_bounded (Icc a b) := let ⟨c, bc⟩ := no_top b in totally_bounded_subset (by exact λ x ⟨h₁, h₂⟩, ⟨h₁, lt_of_le_of_lt h₂ bc⟩) (real.totally_bounded_Ico a c) lemma rat.totally_bounded_Icc (a b : ℚ) : totally_bounded (Icc a b) := begin have := totally_bounded_preimage uniform_embedding_of_rat (real.totally_bounded_Icc a b), rwa (set.ext (λ q, _) : Icc _ _ = _), simp end instance : complete_space ℝ := begin apply complete_of_cauchy_seq_tendsto, intros u hu, let c : cau_seq ℝ abs := ⟨u, cauchy_seq_iff'.1 hu⟩, refine ⟨c.lim, λ s h, _⟩, rcases metric.mem_nhds_iff.1 h with ⟨ε, ε0, hε⟩, have := c.equiv_lim ε ε0, simp only [mem_map, mem_at_top_sets, mem_set_of_eq], refine this.imp (λ N hN n hn, hε (hN n hn)) end lemma tendsto_coe_nat_real_at_top_iff {f : α → ℕ} {l : filter α} : tendsto (λ n, (f n : ℝ)) l at_top ↔ tendsto f l at_top := tendsto_at_top_embedding (assume a₁ a₂, nat.cast_le) $ assume r, let ⟨n, hn⟩ := exists_nat_gt r in ⟨n, le_of_lt hn⟩ lemma tendsto_coe_nat_real_at_top_at_top : tendsto (coe : ℕ → ℝ) at_top at_top := tendsto_coe_nat_real_at_top_iff.2 tendsto_id lemma tendsto_coe_int_real_at_top_iff {f : α → ℤ} {l : filter α} : tendsto (λ n, (f n : ℝ)) l at_top ↔ tendsto f l at_top := tendsto_at_top_embedding (assume a₁ a₂, int.cast_le) $ assume r, let ⟨n, hn⟩ := exists_nat_gt r in ⟨(n:ℤ), le_of_lt $ by rwa [int.cast_coe_nat]⟩ lemma tendsto_coe_int_real_at_top_at_top : tendsto (coe : ℤ → ℝ) at_top at_top := tendsto_coe_int_real_at_top_iff.2 tendsto_id section lemma closure_of_rat_image_lt {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q < x}) = {r | ↑q ≤ r} := subset.antisymm ((closure_subset_iff_subset_of_is_closed (is_closed_ge' _)).2 (image_subset_iff.2 $ λ p h, le_of_lt $ (@rat.cast_lt ℝ _ _ _).2 h)) $ λ x hx, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε, ε0, hε⟩ := metric.mem_nhds_iff.1 ht in let ⟨p, h₁, h₂⟩ := exists_rat_btwn ((lt_add_iff_pos_right x).2 ε0) in ⟨_, hε (show abs _ < _, by rwa [abs_of_nonneg (le_of_lt $ sub_pos.2 h₁), sub_lt_iff_lt_add']), p, rat.cast_lt.1 (@lt_of_le_of_lt ℝ _ _ _ _ hx h₁), rfl⟩ /- TODO(Mario): Put these back only if needed later lemma closure_of_rat_image_le_eq {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q ≤ x}) = {r | ↑q ≤ r} := _ lemma closure_of_rat_image_le_le_eq {a b : ℚ} (hab : a ≤ b) : closure (of_rat '' {q:ℚ | a ≤ q ∧ q ≤ b}) = {r:ℝ | of_rat a ≤ r ∧ r ≤ of_rat b} := _-/ lemma compact_Icc {a b : ℝ} : compact (Icc a b) := compact_of_totally_bounded_is_closed (real.totally_bounded_Icc a b) (is_closed_inter (is_closed_ge' a) (is_closed_le' b)) instance : proper_space ℝ := { compact_ball := λx r, by rw closed_ball_Icc; apply compact_Icc } lemma real.bounded_iff_bdd_below_bdd_above {s : set ℝ} : bounded s ↔ bdd_below s ∧ bdd_above s := ⟨begin assume bdd, rcases (bounded_iff_subset_ball 0).1 bdd with ⟨r, hr⟩, -- hr : s ⊆ closed_ball 0 r rw closed_ball_Icc at hr, -- hr : s ⊆ Icc (0 - r) (0 + r) exact ⟨⟨-r, λy hy, by simpa using (hr hy).1⟩, ⟨r, λy hy, by simpa using (hr hy).2⟩⟩ end, begin rintros ⟨⟨m, hm⟩, ⟨M, hM⟩⟩, have I : s ⊆ Icc m M := λx hx, ⟨hm hx, hM hx⟩, have : Icc m M = closed_ball ((m+M)/2) ((M-m)/2) := by rw closed_ball_Icc; congr; ring, rw this at I, exact bounded.subset I bounded_closed_ball end⟩ end
030a92d5e48466ba928de3b0c2cf9ac34ee7874d
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/vector3.lean
2563fdd40ca7942319d3bcc2e4ff814984ac79e4
[ "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
565
lean
namespace Ex open nat inductive vector (A : Type) : nat → Type | vnil : vector nat.zero | vcons : Π {n : nat}, A → vector n → vector (succ n) namespace vector theorem vcons.inj₁ {A : Type} {n : nat} (a₁ a₂ : A) (v₁ v₂ : vector A n) : vcons a₁ v₁ = vcons a₂ v₂ → a₁ = a₂ := assume h, vector.no_confusion h (λ n h t, h) theorem vcons.inj₂ {A : Type} {n : nat} (a₁ a₂ : A) (v₁ v₂ : vector A n) : vcons a₁ v₁ = vcons a₂ v₂ → v₁ == v₂ := assume h, vector.no_confusion h (λ n h t, t) end vector end Ex
119c9225c349ae1ba5f3574036c646e545aa2d7b
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/category/fold.lean
6aba0502bf0ed34e7a7fac3dd10d09d410a2cd29
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
14,610
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Sean Leather List folds generalized to `traversable`. Informally, we can think of `foldl` as a special case of `traverse` where we do not care about the reconstructed data structure and, in a state monad, we care about the final state. The obvious way to define `foldl` would be to use the state monad but it is nicer to reason about a more abstract interface with `fold_map` as a primitive and `fold_map_hom` as a defining property. def fold_map {α ω} [has_one ω] [has_mul ω] (f : α → ω) : t α → ω := ... lemma fold_map_hom (α β) [monoid α] [monoid β] (f : α → β) [is_monoid_hom f] (g : γ → α) (x : t γ) : f (fold_map g x) = fold_map (f ∘ g) x := ... `fold_map` uses a monoid ω to accumulate a value for every element of a data structure and `fold_map_hom` uses a monoid homomorphism to substitute the monoid used by `fold_map`. The two are sufficient to define `foldl`, `foldr` and `to_list`. `to_list` permits the formulation of specifications in terms of operations on lists. Each fold function can be defined using a specialized monoid. `to_list` uses a free monoid represented as a list with concatenation while `foldl` uses endofunctions together with function composition. The definition through monoids uses `traverse` together with the applicative functor `const m` (where `m` is the monoid). As an implementation, `const` guarantees that no resource is spent on reconstructing the structure during traversal. A special class could be defined for `foldable`, similarly to Haskell, but the author cannot think of instances of `foldable` that are not also `traversable`. -/ import tactic.squeeze import algebra.group import data.list.basic import category.traversable.instances category.traversable.lemmas import category_theory.category category_theory.types category_theory.opposites category_theory.instances.kleisli import category.applicative universes u v open ulift category_theory namespace monoid variables {m : Type u → Type u} [monad m] variables {α β : Type u} /-- For a list, foldl f x [y₀,y₁] reduces as follows calc foldl f x [y₀,y₁] = foldl f (f x y₀) [y₁] : rfl ... = foldl f (f (f x y₀) y₁) [] : rfl ... = f (f x y₀) y₁ : rfl with f : α → β → α x : α [y₀,y₁] : list β We can view the above as a composition of functions: ... = f (f x y₀) y₁ : rfl ... = flip f y₁ (flip f y₀ x) : rfl ... = (flip f y₁ ∘ flip f y₀) x : rfl We can use traverse and const to construct this composition: calc const.run (traverse (λ y, const.mk' (flip f y)) [y₀,y₁]) x = const.run ((::) <$> const.mk' (flip f y₀) <*> traverse (λ y, const.mk' (flip f y)) [y₁]) x ... = const.run ((::) <$> const.mk' (flip f y₀) <*> ( (::) <$> const.mk' (flip f y₁) <*> traverse (λ y, const.mk' (flip f y)) [] )) x ... = const.run ((::) <$> const.mk' (flip f y₀) <*> ( (::) <$> const.mk' (flip f y₁) <*> pure [] )) x ... = const.run ( ((::) <$> const.mk' (flip f y₁) <*> pure []) ∘ ((::) <$> const.mk' (flip f y₀)) ) x ... = const.run ( const.mk' (flip f y₁) ∘ const.mk' (flip f y₀) ) x ... = const.run ( flip f y₁ ∘ flip f y₀ ) x ... = f (f x y₀) y₁ And this is how `const` turns a monoid into an applicative functor and how the monoid of endofunctions define `foldl`. -/ @[reducible] def foldl (α : Type u) : Type u := End α def foldl.mk (f : α → α) : foldl α := f def foldl.of_free_monoid (f : β → α → β) (xs : free_monoid α) : monoid.foldl β := flip (list.foldl f) xs @[reducible] def foldr (α : Type u) : Type u := (End α)ᵒᵖ def foldr.mk (f : α → α) : foldr α := op f def foldr.get (x : foldr α) : α → α := unop x def foldr.of_free_monoid (f : α → β → β) (xs : free_monoid α) : monoid.foldr β := op $ flip (list.foldr f) xs @[reducible] def mfoldl (m : Type u → Type u) [monad m] (α : Type u) : Type u := End $ Kleisli.mk m α def mfoldl.mk (f : α → m α) : mfoldl m α := f def mfoldl.of_free_monoid (f : β → α → m β) (xs : free_monoid α) : monoid.mfoldl m β := flip (list.mfoldl f) xs @[reducible] def mfoldr (m : Type u → Type u) [monad m] (α : Type u) : Type u := (End $ Kleisli.mk m α)ᵒᵖ def mfoldr.mk (f : α → m α) : mfoldr m α := op f def mfoldr.get (x : mfoldr m α) : α → m α := unop x def mfoldr.of_free_monoid (f : α → β → m β) (xs : free_monoid α) : monoid.mfoldr m β := op $ flip (list.mfoldr f) xs end monoid namespace traversable open monoid functor section defs variables {α β : Type u} {t : Type u → Type u} [traversable t] def fold_map {α ω} [has_one ω] [has_mul ω] (f : α → ω) : t α → ω := traverse (const.mk' ∘ f) def foldl (f : α → β → α) (x : α) (xs : t β) : α := fold_map (foldl.mk ∘ flip f) xs x def foldr (f : α → β → β) (x : β) (xs : t α) : β := unop (fold_map (foldr.mk ∘ f) xs) x /-- Conceptually, `to_list` collects all the elements of a collection in a list. This idea is formalized by `lemma to_list_spec (x : t α) : to_list x = fold_map free_monoid.mk x`. The definition of `to_list` is based on `foldl` and `list.cons` for speed. It is faster than using `fold_map free_monoid.mk` because, by using `foldl` and `list.cons`, each insertion is done in constant time. As a consequence, `to_list` performs in linear. On the other hand, `fold_map free_monoid.mk` creates a singleton list around each element and concatenates all the resulting lists. In `xs ++ ys`, concatenation takes a time proportional to `length xs`. Since the order in which concatenation is evaluated is unspecified, nothing prevents each element of the traversable to be appended at the end `xs ++ [x]` which would yield a `O(n²)` run time. -/ def to_list : t α → list α := list.reverse ∘ foldl (flip list.cons) [] def length (xs : t α) : ℕ := down $ foldl (λ l _, up $ l.down + 1) (up 0) xs variables {m : Type u → Type u} [monad m] def mfoldl (f : α → β → m α) (x : α) (xs : t β) : m α := fold_map (mfoldl.mk ∘ flip f) xs x def mfoldr (f : α → β → m β) (x : β) (xs : t α) : m β := unop (fold_map (mfoldr.mk ∘ f) xs) x end defs section applicative_transformation variables {α β γ : Type u} open function (hiding const) is_monoid_hom def map_fold [monoid α] [monoid β] (f : α → β) [is_monoid_hom f] : applicative_transformation (const α) (const β) := { app := λ x, f, preserves_seq' := by { intros, simp only [map_mul f], }, preserves_pure' := by { intros, simp only [map_one f] } } def free.mk : α → free_monoid α := list.ret def free.map (f : α → β) : free_monoid α → free_monoid β := list.map f lemma free.map_eq_map (f : α → β) (xs : list α) : f <$> xs = free.map f xs := rfl instance (f : α → β) : is_monoid_hom (free.map f) := { map_mul := λ x y, by simp only [free.map, list.map_append, free_add_monoid.add_def], map_one := by simp only [free.map, list.map, free_add_monoid.zero_def] } instance fold_foldl (f : β → α → β) : is_monoid_hom (foldl.of_free_monoid f) := { map_one := rfl, map_mul := by { intros, unfold_projs, simp only [foldl.of_free_monoid, flip, list.foldl_append], } } lemma foldr.unop_of_free_monoid (f : α → β → β) (xs : free_monoid α) (a : β) : unop (foldr.of_free_monoid f xs) a = list.foldr f a xs := rfl instance fold_foldr (f : α → β → β) : is_monoid_hom (foldr.of_free_monoid f) := { map_one := rfl, map_mul := by { intros, apply unop_inj, ext, simp only [foldr.of_free_monoid,flip,free_add_monoid.add_def, list.foldr_append], refl } } variables (m : Type u → Type u) [monad m] [is_lawful_monad m] instance fold_mfoldl (f : β → α → m β) : is_monoid_hom (mfoldl.of_free_monoid f) := { map_one := rfl, map_mul := by { intros, unfold_projs, simp only [mfoldl.of_free_monoid,flip, list.mfoldl_append] } } @[simp] lemma mfoldr.unop_of_free_monoid (f : α → β → m β) (xs : free_monoid α) (a : β) : unop (mfoldr.of_free_monoid f xs) a = list.mfoldr f a xs := rfl instance fold_mfoldr (f : α → β → m β) : is_monoid_hom (mfoldr.of_free_monoid f) := { map_one := rfl, map_mul := by { intros, apply unop_inj, ext, simp only [list.mfoldr_append, mfoldr.unop_of_free_monoid, free_add_monoid.add_def], apply bind_ext_congr, simp only [mfoldr.unop_of_free_monoid, eq_self_iff_true, forall_true_iff], } } variables {t : Type u → Type u} [traversable t] [is_lawful_traversable t] open is_lawful_traversable lemma fold_map_hom [monoid α] [monoid β] (f : α → β) [is_monoid_hom f] (g : γ → α) (x : t γ) : f (fold_map g x) = fold_map (f ∘ g) x := calc f (fold_map g x) = f (traverse (const.mk' ∘ g) x) : rfl ... = (map_fold f).app _ (traverse (const.mk' ∘ g) x) : rfl ... = traverse ((map_fold f).app _ ∘ (const.mk' ∘ g)) x : naturality (map_fold f) _ _ ... = fold_map (f ∘ g) x : rfl lemma fold_map_hom_free [monoid β] (f : free_monoid α → β) [is_monoid_hom f] (x : t α) : f (fold_map free.mk x) = fold_map (f ∘ free.mk) x := fold_map_hom _ _ x variable {m} lemma fold_mfoldl_cons (f : α → β → m α) (x : β) (y : α) : list.mfoldl f y (free.mk x) = f y x := by simp only [free.mk, list.ret, list.mfoldl, bind_pure] lemma fold_mfoldr_cons (f : β → α → m α) (x : β) (y : α) : list.mfoldr f y (free.mk x) = f x y := by simp only [free.mk, list.ret, list.mfoldr, pure_bind] end applicative_transformation section equalities open is_lawful_traversable list (cons) variables {α β γ : Type u} variables {t : Type u → Type u} [traversable t] [is_lawful_traversable t] @[simp] lemma foldl.of_free_monoid_comp_free_mk (f : α → β → α) : foldl.of_free_monoid f ∘ free.mk = foldl.mk ∘ flip f := rfl @[simp] lemma foldr.of_free_monoid_comp_free_mk (f : β → α → α) : foldr.of_free_monoid f ∘ free.mk = foldr.mk ∘ f := rfl @[simp] lemma mfoldl.of_free_monoid_comp_free_mk {m} [monad m] [is_lawful_monad m] (f : α → β → m α) : mfoldl.of_free_monoid f ∘ free.mk = mfoldl.mk ∘ flip f := by { ext, simp only [(∘), mfoldl.of_free_monoid, mfoldl.mk, flip, fold_mfoldl_cons] } @[simp] lemma mfoldr.of_free_monoid_comp_free_mk {m} [monad m] [is_lawful_monad m] (f : β → α → m α) : mfoldr.of_free_monoid f ∘ free.mk = mfoldr.mk ∘ f := by { ext, apply unop_inj, ext, simp only [(∘),mfoldr.of_free_monoid,mfoldr.mk,flip,fold_mfoldr_cons] } lemma to_list_spec (xs : t α) : to_list xs = (fold_map free.mk xs : free_monoid _) := eq.symm $ calc fold_map free.mk xs = (fold_map free.mk xs).reverse.reverse : by simp only [list.reverse_reverse] ... = (list.foldr cons [] (fold_map free.mk xs).reverse).reverse : by simp only [list.foldr_eta] ... = (foldl.of_free_monoid (flip cons) (fold_map free.mk xs) []).reverse : by simp only [flip,list.foldr_reverse,foldl.of_free_monoid] ... = to_list xs : by { rw fold_map_hom_free (foldl.of_free_monoid (flip cons)), simp only [to_list, foldl, list.reverse_inj, foldl.of_free_monoid_comp_free_mk], all_goals { apply_instance } } lemma fold_map_map [monoid γ] (f : α → β) (g : β → γ) (xs : t α) : fold_map g (f <$> xs) = fold_map (g ∘ f) xs := by simp only [fold_map,traverse_map] lemma foldl_to_list (f : α → β → α) (xs : t β) (x : α) : foldl f x xs = list.foldl f x (to_list xs) := by { change _ = foldl.of_free_monoid _ _ _, simp only [foldl, to_list_spec, fold_map_hom_free (foldl.of_free_monoid f), foldl.of_free_monoid_comp_free_mk] } lemma foldr_to_list (f : α → β → β) (xs : t α) (x : β) : foldr f x xs = list.foldr f x (to_list xs) := by { rw ← foldr.unop_of_free_monoid, simp only [foldr, to_list_spec, fold_map_hom_free (foldr.of_free_monoid f), foldr.of_free_monoid_comp_free_mk] } lemma to_list_map (f : α → β) (xs : t α) : to_list (f <$> xs) = f <$> to_list xs := by simp only [to_list_spec,free.map_eq_map,fold_map_hom (free.map f), fold_map_map]; refl @[simp] theorem foldl_map (g : β → γ) (f : α → γ → α) (a : α) (l : t β) : foldl f a (g <$> l) = foldl (λ x y, f x (g y)) a l := by simp only [foldl, fold_map_map, (∘), flip] @[simp] theorem foldr_map (g : β → γ) (f : γ → α → α) (a : α) (l : t β) : foldr f a (g <$> l) = foldr (f ∘ g) a l := by simp only [foldr, fold_map_map, (∘), flip] @[simp] theorem to_list_eq_self {xs : list α} : to_list xs = xs := begin simp only [to_list_spec, fold_map, traverse], induction xs, case list.nil { refl }, case list.cons : _ _ ih { unfold list.traverse list.ret, rw ih, refl } end theorem length_to_list {xs : t α} : length xs = list.length (to_list xs) := begin unfold length, rw foldl_to_list, generalize : to_list xs = ys, let f := λ (n : ℕ) (a : α), n + 1, transitivity list.foldl f 0 ys, { generalize : 0 = n, induction ys with _ _ ih generalizing n, { simp only [list.foldl_nil] }, { simp only [list.foldl, ih (n+1)] } }, { induction ys with _ tl ih, { simp only [list.length, list.foldl_nil] }, { simp only [list.foldl, list.length], transitivity list.foldl f 0 tl + 1, { exact eq.symm (list.foldl_hom (+1) f f 0 (λ _ _, rfl) _) }, { rw ih } } } end variables {m : Type u → Type u} [monad m] [is_lawful_monad m] lemma mfoldl_to_list {f : α → β → m α} {x : α} {xs : t β} : mfoldl f x xs = list.mfoldl f x (to_list xs) := by { change _ = mfoldl.of_free_monoid f (to_list xs) x, simp only [mfoldl, to_list_spec, fold_map_hom_free (mfoldl.of_free_monoid f),mfoldl.of_free_monoid_comp_free_mk] } lemma mfoldr_to_list (f : α → β → m β) (x : β) (xs : t α) : mfoldr f x xs = list.mfoldr f x (to_list xs) := by { change _ = unop (mfoldr.of_free_monoid f (to_list xs)) x, simp only [mfoldr, to_list_spec, fold_map_hom_free (mfoldr.of_free_monoid f),mfoldr.of_free_monoid_comp_free_mk] } @[simp] theorem mfoldl_map (g : β → γ) (f : α → γ → m α) (a : α) (l : t β) : mfoldl f a (g <$> l) = mfoldl (λ x y, f x (g y)) a l := by simp only [mfoldl, fold_map_map, (∘), flip] @[simp] theorem mfoldr_map (g : β → γ) (f : γ → α → m α) (a : α) (l : t β) : mfoldr f a (g <$> l) = mfoldr (f ∘ g) a l := by simp only [mfoldr, fold_map_map, (∘), flip] end equalities end traversable
77c0a925b8f82e42b623fef436c27af120551754
5ec8f5218a7c8e87dd0d70dc6b715b36d61a8d61
/word.lean
1cb5cab090156e9c9d46fad293ce0e804304838b
[]
no_license
mbrodersen/kremlin
f9f2f9dd77b9744fe0ffd5f70d9fa0f1f8bd8cec
d4665929ce9012e93a0b05fc7063b96256bab86f
refs/heads/master
1,624,057,268,130
1,496,957,084,000
1,496,957,084,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
37,044
lean
import .lib /- * Parameterization by the word size, in bits. -/ namespace word section variable (n : ℕ) def wordsize : ℕ := n def modulus : ℕ := 2^wordsize n def half_modulus : ℕ := 2^(wordsize n - 1) def max_unsigned : ℕ := modulus n - 1 def max_signed : ℕ := half_modulus n - 1 def min_signed : ℤ := - half_modulus n theorem modulus_pos : modulus n > 0 := nat.pos_pow_of_pos _ dec_trivial theorem succ_max_unsigned : nat.succ (max_unsigned n) = modulus n := nat.succ_pred_eq_of_pos (modulus_pos _) end end word /- * Representation of machine integers -/ /- A machine integer (type [word]) is represented as an arbitrary-precision natural number (type [nat]) plus a proof that it is less than [modulus]. -/ def word (n) := fin (word.modulus n) namespace word def repr {w} (x : ℤ) : word w := ⟨x.nat_mod (modulus w), sorry'⟩ instance coe_int_word {w} : has_coe ℤ (word w) := ⟨repr⟩ /- The [unsigned] and [signed] functions return the Coq integer corresponding to the given machine integer, interpreted as unsigned or signed respectively. -/ def unsigned {w} (n : word w) : ℕ := n.1 section parameter {wordsize : ℕ} local notation `modulus` := modulus wordsize local notation `half_modulus` := half_modulus wordsize local notation `max_unsigned` := max_unsigned wordsize local notation `max_signed` := max_signed wordsize local notation `min_signed` := min_signed wordsize local notation `word` := word wordsize local notation `repr` := @repr wordsize local notation `unsigned` := @unsigned wordsize def signed (n : word) : ℤ := let x := unsigned n in if x < half_modulus then x else x - modulus instance coe_word_int : has_coe word ℤ := ⟨signed⟩ /- Conversely, [repr] takes a Coq integer and returns the corresponding machine integer. The argument is treated modulo [modulus]. -/ def in_srange (x : ℤ) : bool := min_signed ≤ x ∧ x < half_modulus def in_urange (x : ℕ) : bool := x < modulus def iwordsize := repr wordsize instance : has_zero word := ⟨repr 0⟩ instance : has_one word := ⟨repr 1⟩ instance eq_dec : decidable_eq word := by tactic.mk_dec_eq_instance /- * Arithmetic and logical operations over machine integers -/ def ltu (x y : word) : Prop := unsigned x < unsigned y def leu (x y : word) : Prop := unsigned x ≤ unsigned y instance : has_lt word := ⟨λx y, signed x < signed y⟩ instance : has_le word := ⟨λx y, signed x ≤ signed y⟩ protected def neg (x : word) : word := repr (-unsigned x) instance : has_neg word := ⟨word.neg⟩ protected def add (x y : word) : word := repr (unsigned x + unsigned y) protected def mul (x y : word) : word := repr (unsigned x * unsigned y) instance : has_add word := ⟨word.add⟩ instance : has_mul word := ⟨word.mul⟩ def divs (x y : word) : word := repr (int.quot (signed x) (signed y)) def mods (x y : word) : word := repr (int.rem (signed x) (signed y)) instance : has_div word := ⟨divs⟩ instance : has_mod word := ⟨mods⟩ def divu (x y : word) : word := repr (unsigned x / unsigned y : ℕ) def modu (x y : word) : word := repr (unsigned x % unsigned y : ℕ) /- Bitwise boolean operations. -/ protected def and (x y : word) : word := repr (int.land (unsigned x) (unsigned y)) protected def or (x y : word) : word := repr (int.lor (unsigned x) (unsigned y)) protected def xor (x y : word) : word := repr (int.lxor (unsigned x) (unsigned y)) protected def not (x : word) : word := repr (int.lnot (unsigned x)) /- Shifts and rotates. -/ def shl (x y : word) : word := repr (int.shiftl (unsigned x) (unsigned y)) def shru (x y : word) : word := repr (int.shiftr (unsigned x) (unsigned y)) def shr (x y : word) : word := repr (int.shiftr (signed x) (unsigned y)) def rol (x y : word) : word := let n := unsigned y % wordsize in repr (int.lor (int.shiftl (unsigned x) n) (int.shiftr (unsigned x) (wordsize - n))) def ror (x y : word) : word := let n := unsigned y % wordsize in repr (int.lor (int.shiftr (unsigned x) n) (int.shiftl (unsigned x) (wordsize - n))) def rolm (x a m : word) : word := word.and (rol x a) m /- Viewed as signed divisions by powers of two, [shrx] rounds towards zero, while [shr] rounds towards minus infinity. -/ def shrx (x y : word) : word := x / shl 1 y /- High half of full multiply. -/ def mulhu (x y : word) : word := repr ((unsigned x * unsigned y) / modulus) def mulhs (x y : word) : word := repr ((signed x * signed y) / modulus) instance coe_bool_word : has_coe bool word := ⟨λb, cond b 1 0⟩ /- Condition flags -/ def negative (x : word) : word := to_bool (x < 0) def add_carry (x y cin : word) : word := to_bool (unsigned x + unsigned y + unsigned cin ≥ modulus) def add_overflow (x y cin : word) : word := bnot $ in_srange (signed x + signed y + signed cin) def sub_borrow (x y bin : word) : word := to_bool (unsigned x - unsigned y - unsigned bin < 0) def sub_overflow (x y bin : word) : word := bnot $ in_srange (signed x - signed y - signed bin) /- [shr_carry x y] is 1 if [x] is negative and at least one 1 bit is shifted away. -/ def shr_carry (x y : word) : word := to_bool (x < 0 ∧ and x (shl 1 y + -1) ≠ 0) /- Zero and sign extensions -/ def zero_ext (n : ℕ) (x : word) : word := repr (unsigned x % 2^n) def sign_ext (n : ℕ+) (x : word) : word := let modulus' := 2^n.1, y := unsigned x % modulus' in repr (if y < modulus'/2 then y else y - modulus') /- Decomposition of a number as a sum of powers of two. -/ def one_bits (x : word) : list word := (num.one_bits (unsigned x)).map (λx:ℕ, repr x) /- Recognition of powers of two. -/ def is_power2 (x : word) : option word := match num.one_bits (unsigned x) with | (i :: []) := some (repr i) | _ := none end /- Comparisons. -/ instance decidable_lt : @decidable_rel word (<) := by apply_instance instance decidable_le : @decidable_rel word (≤) := by apply_instance instance decidable_ltu : decidable_rel ltu := by delta ltu; apply_instance instance decidable_leu : decidable_rel leu := by delta leu; apply_instance def cmp : comparison → word → word → bool | Ceq x y := x = y | Cne x y := x ≠ y | Clt x y := x < y | Cle x y := x ≤ y | Cgt x y := y < x | Cge x y := y ≤ x def cmpu : comparison → word → word → bool | Ceq x y := x = y | Cne x y := x ≠ y | Clt x y := ltu x y | Cle x y := bnot (ltu y x) | Cgt x y := ltu y x | Cge x y := bnot (ltu x y) def is_false (x : word) : Prop := x = 0 def is_true (x : word) : Prop := x ≠ 0 def notbool (x : word) : word := to_bool (x = 0) /- x86-style extended division and modulus -/ def divmodu2 (nhi nlo : word) (d : word) : option (word × word) := if d = 0 then none else let q := unsigned nhi * modulus + unsigned nlo / unsigned d in if q < modulus then some (repr q, repr (unsigned nhi * modulus + unsigned nlo % unsigned d)) else none def divmods2 (nhi nlo : word) (d : word) : option (word × word) := if d = 0 then none else let q := int.quot (signed nhi * modulus + unsigned nlo) (signed d) in if in_srange q then some (repr q, repr (int.rem (signed nhi * modulus + unsigned nlo) (signed d))) else none /- Encode and decode from an integer -/ def words_of_int : ℕ → ℤ → list word | 0 x := [] | (m + 1) x := repr x :: words_of_int m (x / modulus) def nat_of_words : list word → ℕ | [] := 0 | (b :: l') := unsigned b + nat_of_words l' * modulus /- * Properties of integers and integer arithmetic -/ /- Relative positions, from greatest to smallest: << max_unsigned max_signed 2*wordsize-1 wordsize 0 min_signed >> -/ theorem half_modulus_pos : half_modulus > 0 := nat.pos_pow_of_pos _ dec_trivial theorem min_signed_neg : min_signed < 0 := sorry' theorem max_signed_pos : max_signed ≥ 0 := sorry' theorem two_wordsize_max_unsigned : 2 * wordsize - 1 ≤ max_unsigned := sorry' theorem max_signed_unsigned : max_signed < max_unsigned := sorry' @[simp] lemma unsigned_repr_eq (x) : unsigned (repr x) = x.nat_mod modulus := sorry' lemma signed_repr_eq (x) : signed (repr x) = if x.nat_mod modulus < half_modulus then x.nat_mod modulus else x.nat_mod modulus - modulus := sorry' lemma mod_eq_of_repr_eq {x y} (h : repr x = repr y) : x.nat_mod modulus = y.nat_mod modulus := let t := congr_arg unsigned h in by simp at t; simp [t] theorem unsigned_range (i) : unsigned i < modulus := sorry' theorem unsigned_range_2 (i) : unsigned i ≤ max_unsigned := sorry' theorem min_signed_range (i) : min_signed ≤ signed i := sorry' theorem max_signed_range (i) : signed i ≤ max_signed := sorry' @[simp] theorem repr_unsigned (i) : repr (unsigned i) = i := sorry' @[simp] theorem repr_signed (i) : repr (signed i) = i := sorry' theorem unsigned_repr {z} (h : z ≤ max_unsigned) : unsigned (repr z) = z := sorry' theorem signed_repr {z} : min_signed ≤ z → z ≤ max_signed → signed (repr z) = z := sorry' theorem signed_eq_unsigned (x) : unsigned x ≤ max_signed → signed x = unsigned x := sorry' theorem signed_positive (x) : 0 ≤ signed x ↔ unsigned x ≤ max_signed := sorry' /- ** Properties of zero, one, minus one -/ theorem unsigned_zero : unsigned 0 = 0 := sorry' theorem unsigned_mone : unsigned (-1) = modulus - 1 := sorry' theorem signed_zero : signed 0 = 0 := sorry' theorem signed_mone : signed (-1) = -1 := sorry' theorem unsigned_repr_wordsize : unsigned iwordsize = wordsize := sorry' /- ** Properties of equality -/ theorem eq_signed (x y) : x = y ↔ signed x = signed y := sorry' theorem eq_unsigned (x y) : x = y ↔ unsigned x = unsigned y := sorry' /- ** Properties of addition -/ theorem add_unsigned (x y) : x + y = repr (unsigned x + unsigned y) := sorry' theorem add_signed (x y) : x + y = repr (signed x + signed y) := sorry' theorem add_comm (x y : word) : x + y = y + x := sorry' theorem add_zero (x : word) : x + 0 = x := sorry' theorem add_assoc (x y z : word) : (x + y) + z = x + (y + z) := sorry' theorem add_left_neg (x : word) : -x + x = 0 := sorry' theorem unsigned_add_carry (x y) : unsigned (x + y) = unsigned x + unsigned y - unsigned (add_carry x y 0) * modulus := sorry' theorem unsigned_add_either (x y) : unsigned (x + y) = unsigned x + unsigned y ∨ (unsigned (x + y) : ℤ) = unsigned x + unsigned y - modulus := sorry' /- ** Properties of negation -/ theorem neg_repr (z) : -(repr z) = repr (-z) := sorry' /- ** Properties of multiplication -/ theorem mul_comm (x y : word) : x * y = y * x := sorry' theorem mul_one (x : word) : x * 1 = x := sorry' theorem mul_assoc (x y z : word) : (x * y) * z = x * (y * z) := sorry' theorem right_distrib (x y z : word) : (x + y) * z = x * z + y * z := sorry' theorem mul_signed (x y) : x * y = repr (signed x * signed y) := sorry' instance comm_ring : comm_ring word := { add := (+), add_assoc := add_assoc, zero := 0, zero_add := λx, by rw [add_comm, add_zero], add_zero := add_zero, neg := has_neg.neg, add_left_neg := add_left_neg, add_comm := add_comm, mul := (*), mul_assoc := mul_assoc, one := 1, one_mul := λx, by rw [mul_comm, mul_one], mul_one := mul_one, left_distrib := λx y z, by rw [mul_comm, right_distrib, mul_comm y x, mul_comm z x]; refl, right_distrib := right_distrib, mul_comm := mul_comm } /- ** Properties of subtraction -/ theorem sub_unsigned (x y) : x - y = repr (unsigned x - unsigned y) := sorry' theorem sub_signed (x y) : x - y = repr (signed x - signed y) := sorry' theorem unsigned_sub_borrow (x y) : unsigned (x - y) = unsigned x - unsigned y + unsigned (sub_borrow x y 0) * modulus := sorry' /- ** Properties of division and modulus -/ lemma divu_add_modu (x y) : y ≠ 0 → divu x y * y + modu x y = x := sorry' theorem modu_divu (x y) : y ≠ 0 → modu x y = x - divu x y * y := sorry' lemma mods_divs_Euclid (x y : word) : x / y * y + x % y = x := sorry' theorem mods_divs (x y : word) : x % y = x - x / y * y := sorry' theorem divu_one (x) : divu x 1 = x := sorry' theorem modu_one (x) : modu x 1 = 0 := sorry' theorem divs_mone (x : word) : x / (-1) = -x := sorry' theorem mods_mone (x : word) : x % (-1) = 0 := sorry' theorem divmodu2_divu_modu (n d) : d ≠ 0 → divmodu2 0 n d = some (divu n d, modu n d) := sorry' lemma unsigned_signed (n) : (unsigned n : ℤ) = if n < 0 then signed n + modulus else signed n := sorry' theorem divmods2_divs_mods (n d) : d ≠ 0 → n ≠ repr min_signed ∨ d ≠ -1 → divmods2 (if n < 0 then -1 else 0) n d = some (divs n d, mods n d) := sorry' /- ** Bit-level properties -/ /- ** Bit-level reasoning over type [int] -/ def test_bit (x : word) (i : ℕ) : bool := int.test_bit (unsigned x) i lemma test_bit_repr (x i) : i < wordsize → test_bit (repr x) i = int.test_bit x i := sorry' lemma same_bits_eq (x y) : (∀ i < wordsize, test_bit x i = test_bit y i) → x = y := sorry' lemma bits_above (x i) : i ≥ wordsize → test_bit x i = ff := sorry' lemma bits_zero (i) : test_bit 0 i = ff := sorry' theorem bits_one (n) : test_bit 1 n = to_bool (n = 0) := sorry' lemma bits_mone (i) : i < wordsize → test_bit (-1) i := sorry' lemma sign_bit_of_unsigned (x) : test_bit x (wordsize - 1) = to_bool (unsigned x ≥ half_modulus) := sorry' lemma bits_signed (x i) : int.test_bit (signed x) i = test_bit x (if i < wordsize then i else wordsize - 1) := sorry' lemma bits_le (x y) : (∀ i < wordsize, test_bit x i → test_bit y i) → unsigned x ≤ unsigned y := sorry' /- ** Properties of bitwise and, or, xor -/ @[simp] lemma bits_and (x y i) : i < wordsize → test_bit (word.and x y) i = test_bit x i && test_bit y i := sorry' @[simp] lemma bits_or (x y i) : i < wordsize → test_bit (word.or x y) i = test_bit x i || test_bit y i := sorry' @[simp] lemma bits_xor (x y i) : i < wordsize → test_bit (word.xor x y) i = bxor (test_bit x i) (test_bit y i) := sorry' @[simp] lemma bits_not (x i) : i < wordsize → test_bit (word.not x) i = bnot (test_bit x i) := sorry' theorem and_comm (x y) : word.and x y = word.and y x := sorry' theorem and_assoc (x y z) : word.and (word.and x y) z = word.and x (word.and y z) := sorry' @[simp] theorem and_zero (x) : word.and x 0 = 0 := sorry' @[simp] theorem zero_and (x) : word.and 0 x = 0 := sorry' @[simp] theorem and_mone (x) : word.and x (-1) = x := sorry' @[simp] theorem mone_and (x) : word.and (-1) x = x := sorry' @[simp] theorem and_self (x) : and x x = x := sorry' theorem or_comm (x y) : word.or x y = word.or y x := sorry' theorem or_assoc (x y z) : word.or (word.or x y) z = word.or x (word.or y z) := sorry' @[simp] theorem or_zero (x) : word.or x 0 = x := sorry' @[simp] theorem zero_or (x) : word.or 0 x = x := sorry' @[simp] theorem or_mone (x) : word.or x (-1) = -1 := sorry' @[simp] theorem or_self (x) : word.or x x = x := sorry' theorem and_or_left_distrib (x y z) : word.and x (word.or y z) = word.or (word.and x y) (word.and x z) := sorry' theorem and_or_right_distrib (x y z) : word.and (word.or x y) z = word.or (word.and x z) (word.and y z) := sorry' theorem or_and_left_distrib (x y z) : word.or x (word.and y z) = word.and (word.or x y) (word.or x z) := sorry' theorem or_and_right_distrib (x y z) : word.or (word.and x y) z = word.and (word.or x z) (word.or y z) := sorry' @[simp] theorem and_or_absorb (x y) : word.and x (word.or x y) = x := sorry' @[simp] theorem or_and_absorb (x y) : word.or x (word.and x y) = x := sorry' theorem xor_comm (x y) : word.xor x y = word.xor y x := sorry' theorem xor_assoc (x y z) : word.xor (word.xor x y) z = word.xor x (word.xor y z) := sorry' @[simp] theorem xor_zero (x) : word.xor x 0 = x := sorry' @[simp] theorem zero_xor (x) : word.xor 0 x = x := sorry' @[simp] theorem xor_self (x) : word.xor x x = 0 := sorry' @[simp] theorem xor_zero_one : word.xor 0 1 = 1 := zero_xor _ @[simp] theorem xor_one_one : word.xor 1 1 = 0 := xor_self _ theorem eq_of_xor_zero (x y) : word.xor x y = 0 → x = y := sorry' theorem and_xor_distrib (x y z) : word.and x (word.xor y z) = word.xor (word.and x y) (word.and x z) := sorry' theorem and_le (x y) : unsigned (word.and x y) ≤ unsigned x := sorry' theorem or_le (x y) : unsigned x ≤ unsigned (word.or x y) := sorry' /- Properties of bitwise complement.-/ theorem not_not (x) : word.not (word.not x) = x := sorry' theorem not_zero : word.not 0 = -1 := sorry' theorem not_mone : word.not (-1) = 0 := sorry' theorem not_or_and_not (x y) : word.not (word.or x y) = word.and (word.not x) (word.not y) := sorry' theorem not_and_or_not (x y) : word.not (word.and x y) = word.or (word.not x) (word.not y) := sorry' theorem and_not_self (x) : word.and x (word.not x) = 0 := sorry' theorem or_not_self (x) : word.or x (word.not x) = -1 := sorry' theorem xor_not_self (x) : word.xor x (word.not x) = -1 := sorry' lemma unsigned_not (x) : unsigned (word.not x) = max_unsigned - unsigned x := sorry' theorem not_neg (x) : word.not x = -x - 1 := sorry' theorem neg_not (x) : -x = word.not x + 1 := sorry' theorem sub_add_not (x y) : x - y = x + word.not y + 1 := sorry' theorem sub_add_not_3 (x y b) : b = 0 ∨ b = 1 → x - y - b = x + word.not y + word.xor b 1 := sorry' theorem sub_borrow_add_carry (x y b) : b = 0 ∨ b = 1 → sub_borrow x y b = word.xor (add_carry x (word.not y) (word.xor b 1)) 1 := sorry' /- Connections between [add] and bitwise logical operations. -/ lemma Z_add_is_or (i x y) : (∀ j ≤ i, int.test_bit x j && int.test_bit y j = ff) → int.test_bit (x + y) i = int.test_bit x i || int.test_bit y i := sorry' theorem add_is_or (x y) : word.and x y = 0 → x + y = word.or x y := sorry' theorem xor_is_or (x y) : word.and x y = 0 → word.xor x y = word.or x y := sorry' theorem add_is_xor (x y) : word.and x y = 0 → x + y = word.xor x y := sorry' theorem add_and (x y z) : word.and y z = 0 → word.and x y + word.and x z = word.and x (word.or y z) := sorry' /- ** Properties of shifts -/ @[simp] lemma bits_shl (x y i) : i < wordsize → test_bit (shl x y) i = if i < unsigned y then ff else test_bit x (i - unsigned y) := sorry' @[simp] lemma bits_shru (x y i) : i < wordsize → test_bit (shru x y) i = if i + unsigned y < wordsize then test_bit x (i + unsigned y) else ff := sorry' @[simp] lemma bits_shr (x y i) : i < wordsize → test_bit (shr x y) i = test_bit x (if i + unsigned y < wordsize then i + unsigned y else wordsize - 1) := sorry' @[simp] theorem shl_zero (x) : shl x 0 = x := sorry' lemma bitwise_binop_shl {f : word → word → word} {f' : bool → bool → bool} : (∀ x y i, i < wordsize → test_bit (f x y) i = f' (test_bit x i) (test_bit y i)) → f' ff ff = ff → ∀ x y n, f (shl x n) (shl y n) = shl (f x y) n := sorry' theorem and_shl : ∀ x y n, word.and (shl x n) (shl y n) = shl (word.and x y) n := bitwise_binop_shl bits_and rfl theorem or_shl : ∀ x y n, word.or (shl x n) (shl y n) = shl (word.or x y) n := bitwise_binop_shl bits_or rfl theorem xor_shl : ∀ x y n, word.xor (shl x n) (shl y n) = shl (word.xor x y) n := bitwise_binop_shl bits_xor rfl lemma ltu_inv (x y) : ltu x y → unsigned x < unsigned y := id lemma ltu_iwordsize_inv (x) : ltu x iwordsize → unsigned x < wordsize := sorry' theorem shl_shl (x y z) : ltu y iwordsize → ltu z iwordsize → ltu (y + z) iwordsize → shl (shl x y) z = shl x (y + z) := sorry' theorem shru_zero (x) : shru x 0 = x := sorry' lemma bitwise_binop_shru {f : word → word → word} {f' : bool → bool → bool} : (∀ x y i, i < wordsize → test_bit (f x y) i = f' (test_bit x i) (test_bit y i)) → f' ff ff = ff → ∀ x y n, f (shru x n) (shru y n) = shru (f x y) n := sorry' theorem and_shru : ∀ x y n, word.and (shru x n) (shru y n) = shru (word.and x y) n := bitwise_binop_shru bits_and rfl theorem or_shru : ∀ x y n, word.or (shru x n) (shru y n) = shru (word.or x y) n := bitwise_binop_shru bits_or rfl theorem xor_shru : ∀ x y n, word.xor (shru x n) (shru y n) = shru (word.xor x y) n := bitwise_binop_shru bits_xor rfl theorem shru_shru (x y z) : ltu y iwordsize → ltu z iwordsize → ltu (y + z) iwordsize → shru (shru x y) z = shru x (y + z) := sorry' theorem shr_zero (x) : shr x 0 = x := sorry' lemma bitwise_binop_shr {f : word → word → word} {f' : bool → bool → bool} : (∀ x y i, i < wordsize → test_bit (f x y) i = f' (test_bit x i) (test_bit y i)) → ∀ x y n, f (shr x n) (shr y n) = shr (f x y) n := sorry' theorem and_shr : ∀ x y n, word.and (shr x n) (shr y n) = shr (word.and x y) n := bitwise_binop_shr bits_and theorem or_shr : ∀ x y n, word.or (shr x n) (shr y n) = shr (word.or x y) n := bitwise_binop_shr bits_or theorem xor_shr : ∀ x y n, word.xor (shr x n) (shr y n) = shr (word.xor x y) n := bitwise_binop_shr bits_xor theorem shr_shr (x y z) : ltu y iwordsize → ltu z iwordsize → ltu (y + z) iwordsize → shr (shr x y) z = shr x (y + z) := sorry' theorem and_shr_shru (x y z) : word.and (shr x z) (shru y z) = shru (word.and x y) z := sorry' theorem shr_and_shru_and (x y z) : shru (shl z y) y = z → word.and (shr x y) z = word.and (shru x y) z := sorry' theorem shru_lt_zero (x) : shru x (repr (wordsize - 1)) = to_bool (x < 0) := sorry' theorem shr_lt_zero (x) : shr x (repr (wordsize - 1)) = -to_bool (x < 0) := sorry' /- ** Properties of rotations -/ @[simp] lemma bits_rol (x y i) : i < wordsize → test_bit (rol x y) i = test_bit x ((i - unsigned y) % wordsize) := sorry' @[simp] lemma bits_ror (x y i) : i < wordsize → test_bit (ror x y) i = test_bit x ((i + unsigned y) % wordsize) := sorry' theorem shl_rolm (x n) : ltu n iwordsize → shl x n = rolm x n (shl (-1) n) := sorry' theorem shru_rolm (x n) : ltu n iwordsize → shru x n = rolm x (iwordsize - n) (shru (-1) n) := sorry' theorem rol_zero (x) : rol x 0 = x := sorry' lemma bitwise_binop_rol {f : word → word → word} {f' : bool → bool → bool} : (∀ x y i, i < wordsize → test_bit (f x y) i = f' (test_bit x i) (test_bit y i)) → ∀ x y n, rol (f x y) n = f (rol x n) (rol y n) := sorry' theorem rol_and : ∀ x y n, rol (word.and x y) n = word.and (rol x n) (rol y n) := bitwise_binop_rol bits_and theorem rol_or : ∀ x y n, rol (word.or x y) n = word.or (rol x n) (rol y n) := bitwise_binop_rol bits_or theorem rol_xor : ∀ x y n, rol (word.xor x y) n = word.xor (rol x n) (rol y n) := bitwise_binop_rol bits_xor theorem rol_rol (x n m) : wordsize ∣ modulus → rol (rol x n) m = rol x (modu (n + m) iwordsize) := sorry' theorem rolm_zero (x m) : rolm x 0 m = word.and x m := sorry' theorem rolm_rolm (x n₁ m₁ n₂ m₂) : wordsize ∣ modulus → rolm (rolm x n₁ m₁) n₂ m₂ = rolm x (modu (n₁ + n₂) iwordsize) (word.and (rol m₁ n₂) m₂) := sorry' theorem or_rolm (x n m₁ m₂) : word.or (rolm x n m₁) (rolm x n m₂) = rolm x n (word.or m₁ m₂) := sorry' theorem ror_rol (x y) : ltu y iwordsize → ror x y = rol x (iwordsize - y) := sorry' theorem ror_rol_neg (x y) : wordsize ∣ modulus → ror x y = rol x (-y) := sorry' theorem or_ror (x y z) : ltu y iwordsize → ltu z iwordsize → y + z = iwordsize → ror x z = word.or (shl x y) (shru x z) := sorry' /- ** Properties of [Z_one_bits] and [is_power2]. -/ lemma is_power2_rng (n logn) : is_power2 n = some logn → unsigned logn < wordsize := sorry' theorem is_power2_range (n logn) : is_power2 n = some logn → ltu logn iwordsize := sorry' lemma is_power2_correct (n logn) : is_power2 n = some logn → unsigned n = 2^unsigned logn := sorry' theorem two_p_range (n) : n < wordsize → 2^n ≤ max_unsigned := sorry' lemma is_power2_two_p (n) : n < wordsize → is_power2 (repr (2^n)) = some (repr n) := sorry' /- ** Relation between bitwise operations and multiplications / divisions by powers of 2 -/ /- Left shifts and multiplications by powers of 2. -/ lemma Zshiftl_mul_two_p (x) (n : ℕ) : int.shiftl x n = x * 2^n := sorry' lemma shl_mul_two_p (x y) : shl x y = x * repr (2 ^ unsigned y) := sorry' theorem shl_mul (x y) : shl x y = x * shl 1 y := sorry' theorem mul_pow2 (x n logn) : is_power2 n = some logn → x * n = shl x logn := sorry' theorem shifted_or_is_add (x y n) : n < wordsize → unsigned y < 2^n → word.or (shl x (repr n)) y = repr (unsigned x * 2^n + unsigned y) := sorry' /- Unsigned right shifts and unsigned divisions by powers of 2. -/ lemma shru_div_two_p (x y) : shru x y = repr (unsigned x / 2^unsigned y) := sorry' theorem divu_pow2 (x n logn) : is_power2 n = some logn → divu x n = shru x logn := sorry' /- Signed right shifts and signed divisions by powers of 2. -/ lemma shr_div_two_p (x y) : shr x y = repr (signed x / 2^unsigned y) := sorry' theorem divs_pow2 (x n logn) : is_power2 n = some logn → x / n = shrx x logn := sorry' /- Unsigned modulus over [2^n] is masking with [2^n-1]. -/ theorem modu_and (x n logn) : is_power2 n = some logn → modu x n = word.and x (n - 1) := sorry' /- ** Properties of [shrx] (signed division by a power of 2) -/ lemma int.quot_div (x y) : y > 0 → int.quot x y = if x < 0 then (x + y - 1) / y else x / y := sorry' theorem shrx_shr (x y) : ltu y (repr (wordsize - 1)) → shrx x y = shr (if x < 0 then x + (shl 1 y - 1) else x) y := sorry' theorem shrx_shr_2 (x y) : ltu y (repr (wordsize - 1)) → shrx x y = shr (x + shru (shr x (repr (wordsize - 1))) (iwordsize - y)) y := sorry' lemma Zdiv_shift (x y) : y > 0 → (x + (y - 1)) / y = x / y + if x % y = 0 then 0 else 1 := sorry' theorem shrx_carry (x y) : ltu y (repr (wordsize - 1)) → shrx x y = shr x y + shr_carry x y := sorry' /- Connections between [shr] and [shru]. -/ lemma shr_shru_positive (x y) : signed x ≥ 0 → shr x y = shru x y := sorry' lemma and_positive (x y) : signed y ≥ 0 → signed (word.and x y) ≥ 0 := sorry' theorem shr_and_is_shru_and (x y z) : y ≥ 0 → shr (word.and x y) z = shru (word.and x y) z := sorry' @[simp] lemma bits_zero_ext (n x i) : test_bit (zero_ext n x) i = to_bool (i < n) && test_bit x i := sorry' @[simp] lemma bits_sign_ext (n x i) : i < wordsize → test_bit (sign_ext n x) i = test_bit x (if i < n then i else n - 1) := sorry' theorem zero_ext_above (n x) : n ≥ wordsize → zero_ext n x = x := sorry' theorem sign_ext_above (n : ℕ+) (x) : n.1 ≥ wordsize → sign_ext n x = x := sorry' theorem zero_ext_and (n x) : zero_ext n x = word.and x (repr (2^n - 1)) := sorry' theorem zero_ext_mod (n x) : n < wordsize → unsigned (zero_ext n x) = unsigned x % 2^n := sorry' theorem zero_ext_widen (x n n') : n ≤ n' → zero_ext n' (zero_ext n x) = zero_ext n x := sorry' theorem sign_ext_widen (x) (n n' : ℕ+) : n.1 ≤ n'.1 → sign_ext n' (sign_ext n x) = sign_ext n x := sorry' theorem sign_zero_ext_widen (x n) (n' : ℕ+) : n < n'.1 → sign_ext n' (zero_ext n x) = zero_ext n x := sorry' theorem zero_ext_narrow (x n n') : n ≤ n' → zero_ext n (zero_ext n' x) = zero_ext n x := sorry' theorem sign_ext_narrow (x) (n n' : ℕ+) : n.1 ≤ n'.1 → sign_ext n (sign_ext n' x) = sign_ext n x := sorry' theorem zero_sign_ext_narrow (x n) (n' : ℕ+) : n ≤ n'.1 → zero_ext n (sign_ext n' x) = zero_ext n x := sorry' theorem zero_ext_self (n x) : zero_ext n (zero_ext n x) = zero_ext n x := sorry' theorem sign_ext_self (n x) : sign_ext n (sign_ext n x) = sign_ext n x := sorry' theorem sign_ext_zero_ext (x n) : sign_ext n (zero_ext n x) = sign_ext n x := sorry' theorem zero_ext_sign_ext (x) (n : ℕ+) : zero_ext n (sign_ext n x) = zero_ext n x := sorry' theorem sign_ext_equal_if_zero_equal (n : ℕ+) (x y) : zero_ext n x = zero_ext n y → sign_ext n x = sign_ext n y := sorry' theorem zero_ext_shru_shl (n x) : 0 < n → n < wordsize → let y := repr (wordsize - n) in zero_ext n x = shru (shl x y) y := sorry' theorem sign_ext_shr_shl (n : ℕ+) (x) : n.1 < wordsize → let y := repr (wordsize - n) in sign_ext n x = shr (shl x y) y := sorry' /- [zero_ext n x] is the unique integer congruent to [x] modulo [2^n] in the range [0...2^n-1]. -/ lemma zero_ext_range (n x) : n < wordsize → unsigned (zero_ext n x) < 2^n := sorry' lemma eqmod_zero_ext (n x) : n < wordsize → unsigned (zero_ext n x) = unsigned x % 2^n := sorry' /- [sign_ext n x] is the unique integer congruent to [x] modulo [2^n] in the range [-2^(n-1)...2^(n-1) - 1]. -/ lemma sign_ext_range (x) (n : ℕ+) : n.1 < wordsize → -(2^(n-1) : ℤ) ≤ signed (sign_ext n x) ∧ signed (sign_ext n x) < 2^(n-1) := sorry' lemma eqmod_sign_ext' (x) (n : ℕ+) : n.1 < wordsize → unsigned (sign_ext n x) % 2^n = unsigned x % 2^n := sorry' lemma eqmod_sign_ext (x) (n : ℕ+) : n.1 < wordsize → signed (sign_ext n x) % 2^n = unsigned x % 2^n := sorry' /- ** Properties of [one_bits] (decomposition in sum of powers of two) -/ theorem one_bits_range (x i) : i ∈ one_bits x → ltu i iwordsize := sorry' def int_of_one_bits : list word → word | [] := 0 | (a :: l) := shl 1 a + int_of_one_bits l theorem one_bits_decomp (x) : int_of_one_bits (one_bits x) = x := sorry' /- ** Properties of comparisons -/ theorem negate_cmp (c x y) : cmp (negate_comparison c) x y = bnot (cmp c x y) := sorry' theorem negate_cmpu (c x y) : cmpu (negate_comparison c) x y = bnot (cmpu c x y) := sorry' theorem swap_cmp (c x y) : cmp (swap_comparison c) x y = cmp c y x := sorry' theorem swap_cmpu (c x y) : cmpu (swap_comparison c) x y = cmpu c y x := sorry' lemma translate_ltu (x y d) : unsigned x + unsigned d ≤ max_unsigned → unsigned y + unsigned d ≤ max_unsigned → ltu (x + d) (y + d) ↔ ltu x y := sorry' theorem translate_cmpu (c x y d) : unsigned x + unsigned d ≤ max_unsigned → unsigned y + unsigned d ≤ max_unsigned → cmpu c (x + d) (y + d) = cmpu c x y := sorry' lemma translate_lt (x y d) : in_srange (signed x + signed d) → in_srange (signed y + signed d) → x + d < y + d ↔ x < y := sorry' theorem translate_cmp (c x y d) : in_srange (signed x + signed d) → in_srange (signed y + signed d) → cmp c (x + d) (y + d) = cmp c x y := sorry' theorem notbool_isfalse_istrue (x) : is_false x → is_true (notbool x) := sorry' theorem notbool_istrue_isfalse (x) : is_true x → is_false (notbool x) := sorry' theorem ltu_range_test (x y) : ltu x y → unsigned y ≤ max_signed → 0 ≤ signed x ∧ signed x < unsigned y := sorry' theorem lt_sub_overflow (x y) : word.xor (sub_overflow x y 0) (negative (x - y)) = to_bool (x < y) := sorry' lemma signed_eq {x y} : x = y ↔ signed x = signed y := sorry' lemma unsigned_eq {x y} : x = y ↔ unsigned x = unsigned y := sorry' lemma leu_iff_ltu_or_eq (x y : word) : leu x y ↔ ltu x y ∨ x = y := iff.trans (@le_iff_lt_or_eq ℕ _ _ _) (or_congr iff.rfl unsigned_eq.symm) lemma le_iff_lt_or_eq (x y : word) : x ≤ y ↔ x < y ∨ x = y := iff.trans (@le_iff_lt_or_eq ℤ _ _ _) (or_congr iff.rfl signed_eq.symm) instance decidable_linear_order : decidable_linear_order word := { le := (≤), le_refl := λx, @le_refl ℤ _ _, le_trans := λx y z, @le_trans ℤ _ _ _ _, le_antisymm := λx y h1 h2, signed_eq.2 $ le_antisymm h1 h2, lt := (<), le_iff_lt_or_eq := le_iff_lt_or_eq, lt_irrefl := λx, @lt_irrefl ℤ _ _, le_total := λx y, @le_total ℤ _ _ _, decidable_lt := by apply_instance, decidable_le := by apply_instance, decidable_eq := by apply_instance } lemma ltu_not (x y) : ltu y x ↔ ¬ltu x y ∧ x ≠ y := sorry' /- Non-overlapping test -/ def no_overlap (ofs1 : word) (sz1 : ℕ) (ofs2 : word) (sz2 : ℕ) : bool := let x1 := unsigned ofs1, x2 := unsigned ofs2 in x1 + sz1 < modulus ∧ x2 + sz2 < modulus ∧ (x1 + sz1 ≤ x2 ∨ x2 + sz2 ≤ x1) instance (ofs1 sz1 ofs2 sz2) : decidable (no_overlap ofs1 sz1 ofs2 sz2) := by apply_instance lemma no_overlap_sound (ofs1 sz1 ofs2 sz2 base) : sz1 > 0 → sz2 > 0 → no_overlap ofs1 sz1 ofs2 sz2 → unsigned (base + ofs1) + sz1 ≤ unsigned (base + ofs2) ∨ unsigned (base + ofs2) + sz2 ≤ unsigned (base + ofs1) := sorry' /- Size of integers, in bits. -/ def size (x : word) : ℕ := nat.size (unsigned x) set_option type_context.unfold_lemmas true theorem size_zero : size 0 = 0 := congr_arg nat.size unsigned_zero theorem test_bit_size (x) : x > 0 → test_bit x (size x - 1) := sorry' theorem test_bit_size_lt (x i) : test_bit x i → i < size x := sorry' theorem size_le_wordsize (x) : size x ≤ wordsize := sorry' theorem bits_size_le (x n) (h : ∀ i < wordsize, test_bit x i → i < n) : size x ≤ n := sorry' theorem bits_size_eq (x n) : test_bit x (n - 1) → (∀ i < wordsize, test_bit x i → i < n) → size x = n := sorry' theorem lt_pow_size (x) : unsigned x < 2^size x := nat.lt_pow_size _ theorem size_le_of_lt_pow (x n) : unsigned x < 2^n → size x ≤ n := nat.size_le_of_lt_pow theorem size_and (a b) : size (word.and a b) ≤ min (size a) (size b) := sorry' theorem and_interval (a b) : unsigned (word.and a b) < 2^ min (size a) (size b) := sorry' theorem size_or (a b) : size (word.or a b) = max (size a) (size b) := sorry' theorem or_interval (a b) : unsigned (word.or a b) < 2^ max (size a) (size b) := sorry' theorem size_xor (a b) : size (word.xor a b) ≤ max (size a) (size b) := sorry' theorem xor_interval (a b) : unsigned (word.xor a b) < 2^ max (size a) (size b) := sorry' theorem wordsize_dvd_modulus (n) : wordsize = 2^n → wordsize ∣ modulus := sorry' @[simp] lemma length_words_of_int (n x) : (words_of_int n x).length = n := by revert x; induction n; simph [words_of_int] @[simp] lemma nat_of_words_of_int (n x) : nat_of_words (words_of_int n x) = x.nat_mod (2^(wordsize * n)) := sorry' lemma words_of_int_mod (n) {x y : ℤ} : x.nat_mod (2^(wordsize * n)) = y.nat_mod (2^(wordsize * n)) → words_of_int n x = words_of_int n y := sorry' lemma nat_of_words_append (l2 l1) : nat_of_words (l1 ++ l2) = nat_of_words l1 + nat_of_words l2 * 2^(wordsize * l1.length) := sorry' lemma nat_of_words_range (l) : nat_of_words l < 2^(wordsize * l.length) := sorry' lemma words_of_int_append {n2 x2 n1 x1} : x1 < 2^(wordsize * n1) → words_of_int (n1 + n2) (x1 + x2 * 2^(wordsize * n1)) = words_of_int n1 x1 ++ words_of_int n2 x2 := sorry' /- Theorems that depend on positive word size -/ parameter {wordsize_pos : wordsize > 0} theorem unsigned_one : unsigned 1 = 1 := sorry' theorem one_ne_zero : (1:word) ≠ 0 := sorry' theorem succ_leu_of_ltu {x y} (h : ltu x y) : leu (x + 1) y := begin change unsigned (repr (unsigned x + unsigned 1)) ≤ unsigned y, rw [unsigned_one, -int.coe_nat_add, word.unsigned_repr], exact h, exact nat.lt_of_lt_of_le h (unsigned_range_2 _), end theorem leu_pred_of_ltu {x y} (h : ltu x y) : leu x (y - 1) := begin change unsigned x ≤ unsigned (y - 1), rw [sub_unsigned, unsigned_one, -int.coe_nat_sub, unsigned_repr], exact nat.pred_le_pred h, exact le_trans (nat.sub_le _ _) (unsigned_range_2 _), exact lt_of_le_of_lt (nat.zero_le _) h end /- ** Properties of [modulus], [max_unsigned], etc. -/ theorem half_modulus_modulus : modulus = 2 * half_modulus := sorry' end def scoe {w w' : ℕ} (x : word w) : word w' := repr (signed x) def ucoe {w w' : ℕ} (x : word w) : word w' := repr (unsigned x) end word def uword (n) := word n namespace uword open word section parameter {w : ℕ+} local notation `uword` := uword w instance coe_uword_nat : has_coe uword ℕ := ⟨unsigned⟩ instance : has_zero uword := ⟨repr 0⟩ instance : has_one uword := ⟨repr 1⟩ instance eq_dec : decidable_eq uword := word.eq_dec instance : has_lt uword := ⟨ltu⟩ instance : has_le uword := ⟨leu⟩ instance : has_neg uword := ⟨word.neg⟩ instance : has_add uword := ⟨word.add⟩ instance : has_mul uword := ⟨word.mul⟩ instance : has_div uword := ⟨divu⟩ instance : has_mod uword := ⟨modu⟩ instance decidable_lt : @decidable_rel uword (<) := by apply_instance instance decidable_le : @decidable_rel uword (≤) := by apply_instance instance comm_ring : comm_ring uword := word.comm_ring instance decidable_linear_order : decidable_linear_order uword := { le := (≤), le_refl := λx, @le_refl ℕ _ _, le_trans := λx y z, @le_trans ℕ _ _ _ _, le_antisymm := λx y h1 h2, unsigned_eq.2 $ le_antisymm h1 h2, lt := (<), le_iff_lt_or_eq := leu_iff_ltu_or_eq, lt_irrefl := λx, @lt_irrefl ℕ _ _, le_total := λx y, @le_total ℕ _ _ _, decidable_lt := by apply_instance, decidable_le := by apply_instance, decidable_eq := by apply_instance } theorem succ_le_of_lt {x y : uword} : x < y → x + 1 ≤ y := word.succ_leu_of_ltu theorem le_pred_of_lt {x y : uword} : x < y → x ≤ y - 1 := word.leu_pred_of_ltu theorem zero_le (x : uword) : 0 ≤ x := show unsigned 0 ≤ _, by rw unsigned_zero; apply nat.zero_le end end uword
95ff1e43576ec5f50295e94baa584a765086de79
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/hom/group.lean
270b74b395dd956b3d3b84cd57f583cd9e15774a
[ "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
52,006
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Kevin Buzzard, Scott Morrison, Johan Commelin, Chris Hughes, Johannes Hölzl, Yury Kudryashov -/ import algebra.group.commute import algebra.group_with_zero.defs import data.fun_like.basic /-! # Monoid and group homomorphisms This file defines the bundled structures for monoid and group homomorphisms. Namely, we define `monoid_hom` (resp., `add_monoid_hom`) to be bundled homomorphisms between multiplicative (resp., additive) monoids or groups. We also define coercion to a function, and usual operations: composition, identity homomorphism, pointwise multiplication and pointwise inversion. This file also defines the lesser-used (and notation-less) homomorphism types which are used as building blocks for other homomorphisms: * `zero_hom` * `one_hom` * `add_hom` * `mul_hom` * `monoid_with_zero_hom` ## Notations * `→+`: Bundled `add_monoid` homs. Also use for `add_group` homs. * `→*`: Bundled `monoid` homs. Also use for `group` homs. * `→*₀`: Bundled `monoid_with_zero` homs. Also use for `group_with_zero` homs. * `→ₙ*`: Bundled `semigroup` homs. ## Implementation notes There's a coercion from bundled homs to fun, and the canonical notation is to use the bundled hom as a function via this coercion. There is no `group_hom` -- the idea is that `monoid_hom` is used. The constructor for `monoid_hom` needs a proof of `map_one` as well as `map_mul`; a separate constructor `monoid_hom.mk'` will construct group homs (i.e. monoid homs between groups) given only a proof that multiplication is preserved, Implicit `{}` brackets are often used instead of type class `[]` brackets. This is done when the instances can be inferred because they are implicit arguments to the type `monoid_hom`. When they can be inferred from the type it is faster to use this method than to use type class inference. Historically this file also included definitions of unbundled homomorphism classes; they were deprecated and moved to `deprecated/group`. ## Tags monoid_hom, add_monoid_hom -/ variables {M : Type*} {N : Type*} {P : Type*} -- monoids variables {G : Type*} {H : Type*} -- groups variables {F : Type*} -- homs -- for easy multiple inheritance set_option old_structure_cmd true section zero /-- `zero_hom M N` is the type of functions `M → N` that preserve zero. When possible, instead of parametrizing results over `(f : zero_hom M N)`, you should parametrize over `(F : Type*) [zero_hom_class F M N] (f : F)`. When you extend this structure, make sure to also extend `zero_hom_class`. -/ structure zero_hom (M : Type*) (N : Type*) [has_zero M] [has_zero N] := (to_fun : M → N) (map_zero' : to_fun 0 = 0) /-- `zero_hom_class F M N` states that `F` is a type of zero-preserving homomorphisms. You should extend this typeclass when you extend `zero_hom`. -/ class zero_hom_class (F : Type*) (M N : out_param $ Type*) [has_zero M] [has_zero N] extends fun_like F M (λ _, N) := (map_zero : ∀ (f : F), f 0 = 0) -- Instances and lemmas are defined below through `@[to_additive]`. end zero section add /-- `add_hom M N` is the type of functions `M → N` that preserve addition. When possible, instead of parametrizing results over `(f : add_hom M N)`, you should parametrize over `(F : Type*) [add_hom_class F M N] (f : F)`. When you extend this structure, make sure to extend `add_hom_class`. -/ structure add_hom (M : Type*) (N : Type*) [has_add M] [has_add N] := (to_fun : M → N) (map_add' : ∀ x y, to_fun (x + y) = to_fun x + to_fun y) /-- `add_hom_class F M N` states that `F` is a type of addition-preserving homomorphisms. You should declare an instance of this typeclass when you extend `add_hom`. -/ class add_hom_class (F : Type*) (M N : out_param $ Type*) [has_add M] [has_add N] extends fun_like F M (λ _, N) := (map_add : ∀ (f : F) (x y : M), f (x + y) = f x + f y) -- Instances and lemmas are defined below through `@[to_additive]`. end add section add_zero /-- `M →+ N` is the type of functions `M → N` that preserve the `add_zero_class` structure. `add_monoid_hom` is also used for group homomorphisms. When possible, instead of parametrizing results over `(f : M →+ N)`, you should parametrize over `(F : Type*) [add_monoid_hom_class F M N] (f : F)`. When you extend this structure, make sure to extend `add_monoid_hom_class`. -/ @[ancestor zero_hom add_hom] structure add_monoid_hom (M : Type*) (N : Type*) [add_zero_class M] [add_zero_class N] extends zero_hom M N, add_hom M N attribute [nolint doc_blame] add_monoid_hom.to_add_hom attribute [nolint doc_blame] add_monoid_hom.to_zero_hom infixr ` →+ `:25 := add_monoid_hom /-- `add_monoid_hom_class F M N` states that `F` is a type of `add_zero_class`-preserving homomorphisms. You should also extend this typeclass when you extend `add_monoid_hom`. -/ @[ancestor add_hom_class zero_hom_class] class add_monoid_hom_class (F : Type*) (M N : out_param $ Type*) [add_zero_class M] [add_zero_class N] extends add_hom_class F M N, zero_hom_class F M N -- Instances and lemmas are defined below through `@[to_additive]`. end add_zero section one variables [has_one M] [has_one N] /-- `one_hom M N` is the type of functions `M → N` that preserve one. When possible, instead of parametrizing results over `(f : one_hom M N)`, you should parametrize over `(F : Type*) [one_hom_class F M N] (f : F)`. When you extend this structure, make sure to also extend `one_hom_class`. -/ @[to_additive] structure one_hom (M : Type*) (N : Type*) [has_one M] [has_one N] := (to_fun : M → N) (map_one' : to_fun 1 = 1) /-- `one_hom_class F M N` states that `F` is a type of one-preserving homomorphisms. You should extend this typeclass when you extend `one_hom`. -/ @[to_additive] class one_hom_class (F : Type*) (M N : out_param $ Type*) [has_one M] [has_one N] extends fun_like F M (λ _, N) := (map_one : ∀ (f : F), f 1 = 1) @[to_additive] instance one_hom.one_hom_class : one_hom_class (one_hom M N) M N := { coe := one_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', map_one := one_hom.map_one' } @[simp, to_additive] lemma map_one [one_hom_class F M N] (f : F) : f 1 = 1 := one_hom_class.map_one f @[to_additive] lemma map_eq_one_iff [one_hom_class F M N] (f : F) (hf : function.injective f) {x : M} : f x = 1 ↔ x = 1 := hf.eq_iff' (map_one f) @[to_additive] lemma map_ne_one_iff {R S F : Type*} [has_one R] [has_one S] [one_hom_class F R S] (f : F) (hf : function.injective f) {x : R} : f x ≠ 1 ↔ x ≠ 1 := (map_eq_one_iff f hf).not @[to_additive] lemma ne_one_of_map {R S F : Type*} [has_one R] [has_one S] [one_hom_class F R S] {f : F} {x : R} (hx : f x ≠ 1) : x ≠ 1 := ne_of_apply_ne f $ ne_of_ne_of_eq hx (map_one f).symm @[to_additive] instance [one_hom_class F M N] : has_coe_t F (one_hom M N) := ⟨λ f, { to_fun := f, map_one' := map_one f }⟩ end one section mul variables [has_mul M] [has_mul N] /-- `M →ₙ* N` is the type of functions `M → N` that preserve multiplication. The `ₙ` in the notation stands for "non-unital" because it is intended to match the notation for `non_unital_alg_hom` and `non_unital_ring_hom`, so a `mul_hom` is a non-unital monoid hom. When possible, instead of parametrizing results over `(f : M →ₙ* N)`, you should parametrize over `(F : Type*) [mul_hom_class F M N] (f : F)`. When you extend this structure, make sure to extend `mul_hom_class`. -/ @[to_additive] structure mul_hom (M : Type*) (N : Type*) [has_mul M] [has_mul N] := (to_fun : M → N) (map_mul' : ∀ x y, to_fun (x * y) = to_fun x * to_fun y) infixr ` →ₙ* `:25 := mul_hom /-- `mul_hom_class F M N` states that `F` is a type of multiplication-preserving homomorphisms. You should declare an instance of this typeclass when you extend `mul_hom`. -/ @[to_additive] class mul_hom_class (F : Type*) (M N : out_param $ Type*) [has_mul M] [has_mul N] extends fun_like F M (λ _, N) := (map_mul : ∀ (f : F) (x y : M), f (x * y) = f x * f y) @[to_additive] instance mul_hom.mul_hom_class : mul_hom_class (M →ₙ* N) M N := { coe := mul_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', map_mul := mul_hom.map_mul' } @[simp, to_additive] lemma map_mul [mul_hom_class F M N] (f : F) (x y : M) : f (x * y) = f x * f y := mul_hom_class.map_mul f x y @[to_additive] instance [mul_hom_class F M N] : has_coe_t F (M →ₙ* N) := ⟨λ f, { to_fun := f, map_mul' := map_mul f }⟩ end mul section mul_one variables [mul_one_class M] [mul_one_class N] /-- `M →* N` is the type of functions `M → N` that preserve the `monoid` structure. `monoid_hom` is also used for group homomorphisms. When possible, instead of parametrizing results over `(f : M →+ N)`, you should parametrize over `(F : Type*) [monoid_hom_class F M N] (f : F)`. When you extend this structure, make sure to extend `monoid_hom_class`. -/ @[ancestor one_hom mul_hom, to_additive] structure monoid_hom (M : Type*) (N : Type*) [mul_one_class M] [mul_one_class N] extends one_hom M N, M →ₙ* N attribute [nolint doc_blame] monoid_hom.to_mul_hom attribute [nolint doc_blame] monoid_hom.to_one_hom infixr ` →* `:25 := monoid_hom /-- `monoid_hom_class F M N` states that `F` is a type of `monoid`-preserving homomorphisms. You should also extend this typeclass when you extend `monoid_hom`. -/ @[ancestor mul_hom_class one_hom_class, to_additive "`add_monoid_hom_class F M N` states that `F` is a type of `add_monoid`-preserving homomorphisms. You should also extend this typeclass when you extend `add_monoid_hom`."] class monoid_hom_class (F : Type*) (M N : out_param $ Type*) [mul_one_class M] [mul_one_class N] extends mul_hom_class F M N, one_hom_class F M N @[to_additive] instance monoid_hom.monoid_hom_class : monoid_hom_class (M →* N) M N := { coe := monoid_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', map_mul := monoid_hom.map_mul', map_one := monoid_hom.map_one' } @[to_additive] instance [monoid_hom_class F M N] : has_coe_t F (M →* N) := ⟨λ f, { to_fun := f, map_one' := map_one f, map_mul' := map_mul f }⟩ @[to_additive] lemma map_mul_eq_one [monoid_hom_class F M N] (f : F) {a b : M} (h : a * b = 1) : f a * f b = 1 := by rw [← map_mul, h, map_one] /-- Group homomorphisms preserve inverse. -/ @[simp, to_additive "Additive group homomorphisms preserve negation."] theorem map_inv [group G] [group H] [monoid_hom_class F G H] (f : F) (g : G) : f g⁻¹ = (f g)⁻¹ := eq_inv_of_mul_eq_one_left $ map_mul_eq_one f $ inv_mul_self g /-- Group homomorphisms preserve division. -/ @[simp, to_additive "Additive group homomorphisms preserve subtraction."] theorem map_mul_inv [group G] [group H] [monoid_hom_class F G H] (f : F) (g h : G) : f (g * h⁻¹) = f g * (f h)⁻¹ := by rw [map_mul, map_inv] /-- Group homomorphisms preserve division. -/ @[simp, to_additive "Additive group homomorphisms preserve subtraction."] lemma map_div [group G] [group H] [monoid_hom_class F G H] (f : F) (x y : G) : f (x / y) = f x / f y := by rw [div_eq_mul_inv, div_eq_mul_inv, map_mul_inv] @[to_additive] theorem map_div' [div_inv_monoid G] [div_inv_monoid H] [monoid_hom_class F G H] (f : F) (hf : ∀ x, f (x⁻¹) = (f x)⁻¹) (a b : G) : f (a / b) = f a / f b := by rw [div_eq_mul_inv, div_eq_mul_inv, map_mul, hf] -- to_additive puts the arguments in the wrong order, so generate an auxiliary lemma, then -- swap its arguments. @[to_additive map_nsmul.aux, simp] theorem map_pow [monoid G] [monoid H] [monoid_hom_class F G H] (f : F) (a : G) : ∀ (n : ℕ), f (a ^ n) = (f a) ^ n | 0 := by rw [pow_zero, pow_zero, map_one] | (n+1) := by rw [pow_succ, pow_succ, map_mul, map_pow] @[simp] theorem map_nsmul [add_monoid G] [add_monoid H] [add_monoid_hom_class F G H] (f : F) (n : ℕ) (a : G) : f (n • a) = n • (f a) := map_nsmul.aux f a n attribute [to_additive_reorder 8, to_additive] map_pow @[to_additive] theorem map_zpow' [div_inv_monoid G] [div_inv_monoid H] [monoid_hom_class F G H] (f : F) (hf : ∀ (x : G), f (x⁻¹) = (f x)⁻¹) (a : G) : ∀ n : ℤ, f (a ^ n) = (f a) ^ n | (n : ℕ) := by rw [zpow_coe_nat, map_pow, zpow_coe_nat] | -[1+n] := by rw [zpow_neg_succ_of_nat, hf, map_pow, ← zpow_neg_succ_of_nat] -- to_additive puts the arguments in the wrong order, so generate an auxiliary lemma, then -- swap its arguments. /-- Group homomorphisms preserve integer power. -/ @[to_additive map_zsmul.aux, simp] theorem map_zpow [group G] [group H] [monoid_hom_class F G H] (f : F) (g : G) (n : ℤ) : f (g ^ n) = (f g) ^ n := map_zpow' f (map_inv f) g n /-- Additive group homomorphisms preserve integer scaling. -/ theorem map_zsmul [add_group G] [add_group H] [add_monoid_hom_class F G H] (f : F) (n : ℤ) (g : G) : f (n • g) = n • f g := map_zsmul.aux f g n attribute [to_additive_reorder 8, to_additive] map_zpow end mul_one section mul_zero_one variables [mul_zero_one_class M] [mul_zero_one_class N] /-- `M →*₀ N` is the type of functions `M → N` that preserve the `monoid_with_zero` structure. `monoid_with_zero_hom` is also used for group homomorphisms. When possible, instead of parametrizing results over `(f : M →*₀ N)`, you should parametrize over `(F : Type*) [monoid_with_zero_hom_class F M N] (f : F)`. When you extend this structure, make sure to extend `monoid_with_zero_hom_class`. -/ @[ancestor zero_hom monoid_hom] structure monoid_with_zero_hom (M : Type*) (N : Type*) [mul_zero_one_class M] [mul_zero_one_class N] extends zero_hom M N, monoid_hom M N attribute [nolint doc_blame] monoid_with_zero_hom.to_monoid_hom attribute [nolint doc_blame] monoid_with_zero_hom.to_zero_hom infixr ` →*₀ `:25 := monoid_with_zero_hom /-- `monoid_with_zero_hom_class F M N` states that `F` is a type of `monoid_with_zero`-preserving homomorphisms. You should also extend this typeclass when you extend `monoid_with_zero_hom`. -/ class monoid_with_zero_hom_class (F : Type*) (M N : out_param $ Type*) [mul_zero_one_class M] [mul_zero_one_class N] extends monoid_hom_class F M N, zero_hom_class F M N instance monoid_with_zero_hom.monoid_with_zero_hom_class : monoid_with_zero_hom_class (M →*₀ N) M N := { coe := monoid_with_zero_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', map_mul := monoid_with_zero_hom.map_mul', map_one := monoid_with_zero_hom.map_one', map_zero := monoid_with_zero_hom.map_zero' } instance [monoid_with_zero_hom_class F M N] : has_coe_t F (M →*₀ N) := ⟨λ f, { to_fun := f, map_one' := map_one f, map_zero' := map_zero f, map_mul' := map_mul f }⟩ end mul_zero_one -- completely uninteresting lemmas about coercion to function, that all homs need section coes /-! Bundled morphisms can be down-cast to weaker bundlings -/ @[to_additive] instance monoid_hom.has_coe_to_one_hom {mM : mul_one_class M} {mN : mul_one_class N} : has_coe (M →* N) (one_hom M N) := ⟨monoid_hom.to_one_hom⟩ @[to_additive] instance monoid_hom.has_coe_to_mul_hom {mM : mul_one_class M} {mN : mul_one_class N} : has_coe (M →* N) (M →ₙ* N) := ⟨monoid_hom.to_mul_hom⟩ instance monoid_with_zero_hom.has_coe_to_monoid_hom {mM : mul_zero_one_class M} {mN : mul_zero_one_class N} : has_coe (M →*₀ N) (M →* N) := ⟨monoid_with_zero_hom.to_monoid_hom⟩ instance monoid_with_zero_hom.has_coe_to_zero_hom {mM : mul_zero_one_class M} {mN : mul_zero_one_class N} : has_coe (M →*₀ N) (zero_hom M N) := ⟨monoid_with_zero_hom.to_zero_hom⟩ /-! The simp-normal form of morphism coercion is `f.to_..._hom`. This choice is primarily because this is the way things were before the above coercions were introduced. Bundled morphisms defined elsewhere in Mathlib may choose `↑f` as their simp-normal form instead. -/ @[simp, to_additive] lemma monoid_hom.coe_eq_to_one_hom {mM : mul_one_class M} {mN : mul_one_class N} (f : M →* N) : (f : one_hom M N) = f.to_one_hom := rfl @[simp, to_additive] lemma monoid_hom.coe_eq_to_mul_hom {mM : mul_one_class M} {mN : mul_one_class N} (f : M →* N) : (f : M →ₙ* N) = f.to_mul_hom := rfl @[simp] lemma monoid_with_zero_hom.coe_eq_to_monoid_hom {mM : mul_zero_one_class M} {mN : mul_zero_one_class N} (f : M →*₀ N) : (f : M →* N) = f.to_monoid_hom := rfl @[simp] lemma monoid_with_zero_hom.coe_eq_to_zero_hom {mM : mul_zero_one_class M} {mN : mul_zero_one_class N} (f : M →*₀ N) : (f : zero_hom M N) = f.to_zero_hom := rfl -- Fallback `has_coe_to_fun` instances to help the elaborator @[to_additive] instance {mM : has_one M} {mN : has_one N} : has_coe_to_fun (one_hom M N) (λ _, M → N) := ⟨one_hom.to_fun⟩ @[to_additive] instance {mM : has_mul M} {mN : has_mul N} : has_coe_to_fun (M →ₙ* N) (λ _, M → N) := ⟨mul_hom.to_fun⟩ @[to_additive] instance {mM : mul_one_class M} {mN : mul_one_class N} : has_coe_to_fun (M →* N) (λ _, M → N) := ⟨monoid_hom.to_fun⟩ instance {mM : mul_zero_one_class M} {mN : mul_zero_one_class N} : has_coe_to_fun (M →*₀ N) (λ _, M → N) := ⟨monoid_with_zero_hom.to_fun⟩ -- these must come after the coe_to_fun definitions initialize_simps_projections zero_hom (to_fun → apply) initialize_simps_projections add_hom (to_fun → apply) initialize_simps_projections add_monoid_hom (to_fun → apply) initialize_simps_projections one_hom (to_fun → apply) initialize_simps_projections mul_hom (to_fun → apply) initialize_simps_projections monoid_hom (to_fun → apply) initialize_simps_projections monoid_with_zero_hom (to_fun → apply) @[simp, to_additive] lemma one_hom.to_fun_eq_coe [has_one M] [has_one N] (f : one_hom M N) : f.to_fun = f := rfl @[simp, to_additive] lemma mul_hom.to_fun_eq_coe [has_mul M] [has_mul N] (f : M →ₙ* N) : f.to_fun = f := rfl @[simp, to_additive] lemma monoid_hom.to_fun_eq_coe [mul_one_class M] [mul_one_class N] (f : M →* N) : f.to_fun = f := rfl @[simp] lemma monoid_with_zero_hom.to_fun_eq_coe [mul_zero_one_class M] [mul_zero_one_class N] (f : M →*₀ N) : f.to_fun = f := rfl @[simp, to_additive] lemma one_hom.coe_mk [has_one M] [has_one N] (f : M → N) (h1) : (one_hom.mk f h1 : M → N) = f := rfl @[simp, to_additive] lemma mul_hom.coe_mk [has_mul M] [has_mul N] (f : M → N) (hmul) : (mul_hom.mk f hmul : M → N) = f := rfl @[simp, to_additive] lemma monoid_hom.coe_mk [mul_one_class M] [mul_one_class N] (f : M → N) (h1 hmul) : (monoid_hom.mk f h1 hmul : M → N) = f := rfl @[simp] lemma monoid_with_zero_hom.coe_mk [mul_zero_one_class M] [mul_zero_one_class N] (f : M → N) (h0 h1 hmul) : (monoid_with_zero_hom.mk f h0 h1 hmul : M → N) = f := rfl @[simp, to_additive] lemma monoid_hom.to_one_hom_coe [mul_one_class M] [mul_one_class N] (f : M →* N) : (f.to_one_hom : M → N) = f := rfl @[simp, to_additive] lemma monoid_hom.to_mul_hom_coe [mul_one_class M] [mul_one_class N] (f : M →* N) : (f.to_mul_hom : M → N) = f := rfl @[simp] lemma monoid_with_zero_hom.to_zero_hom_coe [mul_zero_one_class M] [mul_zero_one_class N] (f : M →*₀ N) : (f.to_zero_hom : M → N) = f := rfl @[simp] lemma monoid_with_zero_hom.to_monoid_hom_coe [mul_zero_one_class M] [mul_zero_one_class N] (f : M →*₀ N) : (f.to_monoid_hom : M → N) = f := rfl @[ext, to_additive] lemma one_hom.ext [has_one M] [has_one N] ⦃f g : one_hom M N⦄ (h : ∀ x, f x = g x) : f = g := fun_like.ext _ _ h @[ext, to_additive] lemma mul_hom.ext [has_mul M] [has_mul N] ⦃f g : M →ₙ* N⦄ (h : ∀ x, f x = g x) : f = g := fun_like.ext _ _ h @[ext, to_additive] lemma monoid_hom.ext [mul_one_class M] [mul_one_class N] ⦃f g : M →* N⦄ (h : ∀ x, f x = g x) : f = g := fun_like.ext _ _ h @[ext] lemma monoid_with_zero_hom.ext [mul_zero_one_class M] [mul_zero_one_class N] ⦃f g : M →*₀ N⦄ (h : ∀ x, f x = g x) : f = g := fun_like.ext _ _ h section deprecated /-- Deprecated: use `fun_like.congr_fun` instead. -/ @[to_additive "Deprecated: use `fun_like.congr_fun` instead."] theorem one_hom.congr_fun [has_one M] [has_one N] {f g : one_hom M N} (h : f = g) (x : M) : f x = g x := fun_like.congr_fun h x /-- Deprecated: use `fun_like.congr_fun` instead. -/ @[to_additive "Deprecated: use `fun_like.congr_fun` instead."] theorem mul_hom.congr_fun [has_mul M] [has_mul N] {f g : M →ₙ* N} (h : f = g) (x : M) : f x = g x := fun_like.congr_fun h x /-- Deprecated: use `fun_like.congr_fun` instead. -/ @[to_additive "Deprecated: use `fun_like.congr_fun` instead."] theorem monoid_hom.congr_fun [mul_one_class M] [mul_one_class N] {f g : M →* N} (h : f = g) (x : M) : f x = g x := fun_like.congr_fun h x /-- Deprecated: use `fun_like.congr_fun` instead. -/ theorem monoid_with_zero_hom.congr_fun [mul_zero_one_class M] [mul_zero_one_class N] {f g : M →*₀ N} (h : f = g) (x : M) : f x = g x := fun_like.congr_fun h x /-- Deprecated: use `fun_like.congr_arg` instead. -/ @[to_additive "Deprecated: use `fun_like.congr_arg` instead."] theorem one_hom.congr_arg [has_one M] [has_one N] (f : one_hom M N) {x y : M} (h : x = y) : f x = f y := fun_like.congr_arg f h /-- Deprecated: use `fun_like.congr_arg` instead. -/ @[to_additive "Deprecated: use `fun_like.congr_arg` instead."] theorem mul_hom.congr_arg [has_mul M] [has_mul N] (f : M →ₙ* N) {x y : M} (h : x = y) : f x = f y := fun_like.congr_arg f h /-- Deprecated: use `fun_like.congr_arg` instead. -/ @[to_additive "Deprecated: use `fun_like.congr_arg` instead."] theorem monoid_hom.congr_arg [mul_one_class M] [mul_one_class N] (f : M →* N) {x y : M} (h : x = y) : f x = f y := fun_like.congr_arg f h /-- Deprecated: use `fun_like.congr_arg` instead. -/ theorem monoid_with_zero_hom.congr_arg [mul_zero_one_class M] [mul_zero_one_class N] (f : M →*₀ N) {x y : M} (h : x = y) : f x = f y := fun_like.congr_arg f h /-- Deprecated: use `fun_like.coe_injective` instead. -/ @[to_additive "Deprecated: use `fun_like.coe_injective` instead."] lemma one_hom.coe_inj [has_one M] [has_one N] ⦃f g : one_hom M N⦄ (h : (f : M → N) = g) : f = g := fun_like.coe_injective h /-- Deprecated: use `fun_like.coe_injective` instead. -/ @[to_additive "Deprecated: use `fun_like.coe_injective` instead."] lemma mul_hom.coe_inj [has_mul M] [has_mul N] ⦃f g : M →ₙ* N⦄ (h : (f : M → N) = g) : f = g := fun_like.coe_injective h /-- Deprecated: use `fun_like.coe_injective` instead. -/ @[to_additive "Deprecated: use `fun_like.coe_injective` instead."] lemma monoid_hom.coe_inj [mul_one_class M] [mul_one_class N] ⦃f g : M →* N⦄ (h : (f : M → N) = g) : f = g := fun_like.coe_injective h /-- Deprecated: use `fun_like.coe_injective` instead. -/ lemma monoid_with_zero_hom.coe_inj [mul_zero_one_class M] [mul_zero_one_class N] ⦃f g : M →*₀ N⦄ (h : (f : M → N) = g) : f = g := fun_like.coe_injective h /-- Deprecated: use `fun_like.ext_iff` instead. -/ @[to_additive "Deprecated: use `fun_like.ext_iff` instead."] lemma one_hom.ext_iff [has_one M] [has_one N] {f g : one_hom M N} : f = g ↔ ∀ x, f x = g x := fun_like.ext_iff /-- Deprecated: use `fun_like.ext_iff` instead. -/ @[to_additive] lemma mul_hom.ext_iff [has_mul M] [has_mul N] {f g : M →ₙ* N} : f = g ↔ ∀ x, f x = g x := fun_like.ext_iff /-- Deprecated: use `fun_like.ext_iff` instead. -/ @[to_additive] lemma monoid_hom.ext_iff [mul_one_class M] [mul_one_class N] {f g : M →* N} : f = g ↔ ∀ x, f x = g x := fun_like.ext_iff /-- Deprecated: use `fun_like.ext_iff` instead. -/ lemma monoid_with_zero_hom.ext_iff [mul_zero_one_class M] [mul_zero_one_class N] {f g : M →*₀ N} : f = g ↔ ∀ x, f x = g x := fun_like.ext_iff end deprecated @[simp, to_additive] lemma one_hom.mk_coe [has_one M] [has_one N] (f : one_hom M N) (h1) : one_hom.mk f h1 = f := one_hom.ext $ λ _, rfl @[simp, to_additive] lemma mul_hom.mk_coe [has_mul M] [has_mul N] (f : M →ₙ* N) (hmul) : mul_hom.mk f hmul = f := mul_hom.ext $ λ _, rfl @[simp, to_additive] lemma monoid_hom.mk_coe [mul_one_class M] [mul_one_class N] (f : M →* N) (h1 hmul) : monoid_hom.mk f h1 hmul = f := monoid_hom.ext $ λ _, rfl @[simp] lemma monoid_with_zero_hom.mk_coe [mul_zero_one_class M] [mul_zero_one_class N] (f : M →*₀ N) (h0 h1 hmul) : monoid_with_zero_hom.mk f h0 h1 hmul = f := monoid_with_zero_hom.ext $ λ _, rfl end coes /-- Copy of a `one_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ @[to_additive "Copy of a `zero_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities."] protected def one_hom.copy {hM : has_one M} {hN : has_one N} (f : one_hom M N) (f' : M → N) (h : f' = f) : one_hom M N := { to_fun := f', map_one' := h.symm ▸ f.map_one' } /-- Copy of a `mul_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ @[to_additive "Copy of an `add_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities."] protected def mul_hom.copy {hM : has_mul M} {hN : has_mul N} (f : M →ₙ* N) (f' : M → N) (h : f' = f) : M →ₙ* N := { to_fun := f', map_mul' := h.symm ▸ f.map_mul' } /-- Copy of a `monoid_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ @[to_additive "Copy of an `add_monoid_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities."] protected def monoid_hom.copy {hM : mul_one_class M} {hN : mul_one_class N} (f : M →* N) (f' : M → N) (h : f' = f) : M →* N := { ..f.to_one_hom.copy f' h, ..f.to_mul_hom.copy f' h } /-- Copy of a `monoid_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def monoid_with_zero_hom.copy {hM : mul_zero_one_class M} {hN : mul_zero_one_class N} (f : M →*₀ N) (f' : M → N) (h : f' = f) : M →* N := { ..f.to_zero_hom.copy f' h, ..f.to_monoid_hom.copy f' h } @[to_additive] protected lemma one_hom.map_one [has_one M] [has_one N] (f : one_hom M N) : f 1 = 1 := f.map_one' /-- If `f` is a monoid homomorphism then `f 1 = 1`. -/ @[to_additive] protected lemma monoid_hom.map_one [mul_one_class M] [mul_one_class N] (f : M →* N) : f 1 = 1 := f.map_one' protected lemma monoid_with_zero_hom.map_one [mul_zero_one_class M] [mul_zero_one_class N] (f : M →*₀ N) : f 1 = 1 := f.map_one' /-- If `f` is an additive monoid homomorphism then `f 0 = 0`. -/ add_decl_doc add_monoid_hom.map_zero protected lemma monoid_with_zero_hom.map_zero [mul_zero_one_class M] [mul_zero_one_class N] (f : M →*₀ N) : f 0 = 0 := f.map_zero' @[to_additive] protected lemma mul_hom.map_mul [has_mul M] [has_mul N] (f : M →ₙ* N) (a b : M) : f (a * b) = f a * f b := f.map_mul' a b /-- If `f` is a monoid homomorphism then `f (a * b) = f a * f b`. -/ @[to_additive] protected lemma monoid_hom.map_mul [mul_one_class M] [mul_one_class N] (f : M →* N) (a b : M) : f (a * b) = f a * f b := f.map_mul' a b protected lemma monoid_with_zero_hom.map_mul [mul_zero_one_class M] [mul_zero_one_class N] (f : M →*₀ N) (a b : M) : f (a * b) = f a * f b := f.map_mul' a b /-- If `f` is an additive monoid homomorphism then `f (a + b) = f a + f b`. -/ add_decl_doc add_monoid_hom.map_add namespace monoid_hom variables {mM : mul_one_class M} {mN : mul_one_class N} {mP : mul_one_class P} variables [group G] [comm_group H] [monoid_hom_class F M N] include mM mN /-- Given a monoid homomorphism `f : M →* N` and an element `x : M`, if `x` has a right inverse, then `f x` has a right inverse too. For elements invertible on both sides see `is_unit.map`. -/ @[to_additive "Given an add_monoid homomorphism `f : M →+ N` and an element `x : M`, if `x` has a right inverse, then `f x` has a right inverse too."] lemma map_exists_right_inv (f : F) {x : M} (hx : ∃ y, x * y = 1) : ∃ y, f x * y = 1 := let ⟨y, hy⟩ := hx in ⟨f y, map_mul_eq_one f hy⟩ /-- Given a monoid homomorphism `f : M →* N` and an element `x : M`, if `x` has a left inverse, then `f x` has a left inverse too. For elements invertible on both sides see `is_unit.map`. -/ @[to_additive "Given an add_monoid homomorphism `f : M →+ N` and an element `x : M`, if `x` has a left inverse, then `f x` has a left inverse too. For elements invertible on both sides see `is_add_unit.map`."] lemma map_exists_left_inv (f : F) {x : M} (hx : ∃ y, y * x = 1) : ∃ y, y * f x = 1 := let ⟨y, hy⟩ := hx in ⟨f y, map_mul_eq_one f hy⟩ end monoid_hom /-- Inversion on a commutative group, considered as a monoid homomorphism. -/ @[to_additive "Inversion on a commutative additive group, considered as an additive monoid homomorphism."] def comm_group.inv_monoid_hom {G : Type*} [comm_group G] : G →* G := { to_fun := has_inv.inv, map_one' := inv_one, map_mul' := mul_inv } /-- The identity map from a type with 1 to itself. -/ @[to_additive, simps] def one_hom.id (M : Type*) [has_one M] : one_hom M M := { to_fun := λ x, x, map_one' := rfl, } /-- The identity map from a type with multiplication to itself. -/ @[to_additive, simps] def mul_hom.id (M : Type*) [has_mul M] : M →ₙ* M := { to_fun := λ x, x, map_mul' := λ _ _, rfl, } /-- The identity map from a monoid to itself. -/ @[to_additive, simps] def monoid_hom.id (M : Type*) [mul_one_class M] : M →* M := { to_fun := λ x, x, map_one' := rfl, map_mul' := λ _ _, rfl, } /-- The identity map from a monoid_with_zero to itself. -/ @[simps] def monoid_with_zero_hom.id (M : Type*) [mul_zero_one_class M] : M →*₀ M := { to_fun := λ x, x, map_zero' := rfl, map_one' := rfl, map_mul' := λ _ _, rfl, } /-- The identity map from an type with zero to itself. -/ add_decl_doc zero_hom.id /-- The identity map from an type with addition to itself. -/ add_decl_doc add_hom.id /-- The identity map from an additive monoid to itself. -/ add_decl_doc add_monoid_hom.id /-- Composition of `one_hom`s as a `one_hom`. -/ @[to_additive] def one_hom.comp [has_one M] [has_one N] [has_one P] (hnp : one_hom N P) (hmn : one_hom M N) : one_hom M P := { to_fun := hnp ∘ hmn, map_one' := by simp, } /-- Composition of `mul_hom`s as a `mul_hom`. -/ @[to_additive] def mul_hom.comp [has_mul M] [has_mul N] [has_mul P] (hnp : N →ₙ* P) (hmn : M →ₙ* N) : M →ₙ* P := { to_fun := hnp ∘ hmn, map_mul' := by simp, } /-- Composition of monoid morphisms as a monoid morphism. -/ @[to_additive] def monoid_hom.comp [mul_one_class M] [mul_one_class N] [mul_one_class P] (hnp : N →* P) (hmn : M →* N) : M →* P := { to_fun := hnp ∘ hmn, map_one' := by simp, map_mul' := by simp, } /-- Composition of `monoid_with_zero_hom`s as a `monoid_with_zero_hom`. -/ def monoid_with_zero_hom.comp [mul_zero_one_class M] [mul_zero_one_class N] [mul_zero_one_class P] (hnp : N →*₀ P) (hmn : M →*₀ N) : M →*₀ P := { to_fun := hnp ∘ hmn, map_zero' := by simp, map_one' := by simp, map_mul' := by simp, } /-- Composition of `zero_hom`s as a `zero_hom`. -/ add_decl_doc zero_hom.comp /-- Composition of `add_hom`s as a `add_hom`. -/ add_decl_doc add_hom.comp /-- Composition of additive monoid morphisms as an additive monoid morphism. -/ add_decl_doc add_monoid_hom.comp @[simp, to_additive] lemma one_hom.coe_comp [has_one M] [has_one N] [has_one P] (g : one_hom N P) (f : one_hom M N) : ⇑(g.comp f) = g ∘ f := rfl @[simp, to_additive] lemma mul_hom.coe_comp [has_mul M] [has_mul N] [has_mul P] (g : N →ₙ* P) (f : M →ₙ* N) : ⇑(g.comp f) = g ∘ f := rfl @[simp, to_additive] lemma monoid_hom.coe_comp [mul_one_class M] [mul_one_class N] [mul_one_class P] (g : N →* P) (f : M →* N) : ⇑(g.comp f) = g ∘ f := rfl @[simp] lemma monoid_with_zero_hom.coe_comp [mul_zero_one_class M] [mul_zero_one_class N] [mul_zero_one_class P] (g : N →*₀ P) (f : M →*₀ N) : ⇑(g.comp f) = g ∘ f := rfl @[to_additive] lemma one_hom.comp_apply [has_one M] [has_one N] [has_one P] (g : one_hom N P) (f : one_hom M N) (x : M) : g.comp f x = g (f x) := rfl @[to_additive] lemma mul_hom.comp_apply [has_mul M] [has_mul N] [has_mul P] (g : N →ₙ* P) (f : M →ₙ* N) (x : M) : g.comp f x = g (f x) := rfl @[to_additive] lemma monoid_hom.comp_apply [mul_one_class M] [mul_one_class N] [mul_one_class P] (g : N →* P) (f : M →* N) (x : M) : g.comp f x = g (f x) := rfl lemma monoid_with_zero_hom.comp_apply [mul_zero_one_class M] [mul_zero_one_class N] [mul_zero_one_class P] (g : N →*₀ P) (f : M →*₀ N) (x : M) : g.comp f x = g (f x) := rfl /-- Composition of monoid homomorphisms is associative. -/ @[to_additive] lemma one_hom.comp_assoc {Q : Type*} [has_one M] [has_one N] [has_one P] [has_one Q] (f : one_hom M N) (g : one_hom N P) (h : one_hom P Q) : (h.comp g).comp f = h.comp (g.comp f) := rfl @[to_additive] lemma mul_hom.comp_assoc {Q : Type*} [has_mul M] [has_mul N] [has_mul P] [has_mul Q] (f : M →ₙ* N) (g : N →ₙ* P) (h : P →ₙ* Q) : (h.comp g).comp f = h.comp (g.comp f) := rfl @[to_additive] lemma monoid_hom.comp_assoc {Q : Type*} [mul_one_class M] [mul_one_class N] [mul_one_class P] [mul_one_class Q] (f : M →* N) (g : N →* P) (h : P →* Q) : (h.comp g).comp f = h.comp (g.comp f) := rfl lemma monoid_with_zero_hom.comp_assoc {Q : Type*} [mul_zero_one_class M] [mul_zero_one_class N] [mul_zero_one_class P] [mul_zero_one_class Q] (f : M →*₀ N) (g : N →*₀ P) (h : P →*₀ Q) : (h.comp g).comp f = h.comp (g.comp f) := rfl @[to_additive] lemma one_hom.cancel_right [has_one M] [has_one N] [has_one P] {g₁ g₂ : one_hom N P} {f : one_hom M N} (hf : function.surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, one_hom.ext $ hf.forall.2 (one_hom.ext_iff.1 h), λ h, h ▸ rfl⟩ @[to_additive] lemma mul_hom.cancel_right [has_mul M] [has_mul N] [has_mul P] {g₁ g₂ : N →ₙ* P} {f : M →ₙ* N} (hf : function.surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, mul_hom.ext $ hf.forall.2 (mul_hom.ext_iff.1 h), λ h, h ▸ rfl⟩ @[to_additive] lemma monoid_hom.cancel_right [mul_one_class M] [mul_one_class N] [mul_one_class P] {g₁ g₂ : N →* P} {f : M →* N} (hf : function.surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, monoid_hom.ext $ hf.forall.2 (monoid_hom.ext_iff.1 h), λ h, h ▸ rfl⟩ lemma monoid_with_zero_hom.cancel_right [mul_zero_one_class M] [mul_zero_one_class N] [mul_zero_one_class P] {g₁ g₂ : N →*₀ P} {f : M →*₀ N} (hf : function.surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, monoid_with_zero_hom.ext $ hf.forall.2 (monoid_with_zero_hom.ext_iff.1 h), λ h, h ▸ rfl⟩ @[to_additive] lemma one_hom.cancel_left [has_one M] [has_one N] [has_one P] {g : one_hom N P} {f₁ f₂ : one_hom M N} (hg : function.injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, one_hom.ext $ λ x, hg $ by rw [← one_hom.comp_apply, h, one_hom.comp_apply], λ h, h ▸ rfl⟩ @[to_additive] lemma mul_hom.cancel_left [has_mul M] [has_mul N] [has_mul P] {g : N →ₙ* P} {f₁ f₂ : M →ₙ* N} (hg : function.injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, mul_hom.ext $ λ x, hg $ by rw [← mul_hom.comp_apply, h, mul_hom.comp_apply], λ h, h ▸ rfl⟩ @[to_additive] lemma monoid_hom.cancel_left [mul_one_class M] [mul_one_class N] [mul_one_class P] {g : N →* P} {f₁ f₂ : M →* N} (hg : function.injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, monoid_hom.ext $ λ x, hg $ by rw [← monoid_hom.comp_apply, h, monoid_hom.comp_apply], λ h, h ▸ rfl⟩ lemma monoid_with_zero_hom.cancel_left [mul_zero_one_class M] [mul_zero_one_class N] [mul_zero_one_class P] {g : N →*₀ P} {f₁ f₂ : M →*₀ N} (hg : function.injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, monoid_with_zero_hom.ext $ λ x, hg $ by rw [ ← monoid_with_zero_hom.comp_apply, h, monoid_with_zero_hom.comp_apply], λ h, h ▸ rfl⟩ @[to_additive] lemma monoid_hom.to_one_hom_injective [mul_one_class M] [mul_one_class N] : function.injective (monoid_hom.to_one_hom : (M →* N) → one_hom M N) := λ f g h, monoid_hom.ext $ one_hom.ext_iff.mp h @[to_additive] lemma monoid_hom.to_mul_hom_injective [mul_one_class M] [mul_one_class N] : function.injective (monoid_hom.to_mul_hom : (M →* N) → M →ₙ* N) := λ f g h, monoid_hom.ext $ mul_hom.ext_iff.mp h lemma monoid_with_zero_hom.to_monoid_hom_injective [mul_zero_one_class M] [mul_zero_one_class N] : function.injective (monoid_with_zero_hom.to_monoid_hom : (M →*₀ N) → M →* N) := λ f g h, monoid_with_zero_hom.ext $ monoid_hom.ext_iff.mp h lemma monoid_with_zero_hom.to_zero_hom_injective [mul_zero_one_class M] [mul_zero_one_class N] : function.injective (monoid_with_zero_hom.to_zero_hom : (M →*₀ N) → zero_hom M N) := λ f g h, monoid_with_zero_hom.ext $ zero_hom.ext_iff.mp h @[simp, to_additive] lemma one_hom.comp_id [has_one M] [has_one N] (f : one_hom M N) : f.comp (one_hom.id M) = f := one_hom.ext $ λ x, rfl @[simp, to_additive] lemma mul_hom.comp_id [has_mul M] [has_mul N] (f : M →ₙ* N) : f.comp (mul_hom.id M) = f := mul_hom.ext $ λ x, rfl @[simp, to_additive] lemma monoid_hom.comp_id [mul_one_class M] [mul_one_class N] (f : M →* N) : f.comp (monoid_hom.id M) = f := monoid_hom.ext $ λ x, rfl @[simp] lemma monoid_with_zero_hom.comp_id [mul_zero_one_class M] [mul_zero_one_class N] (f : M →*₀ N) : f.comp (monoid_with_zero_hom.id M) = f := monoid_with_zero_hom.ext $ λ x, rfl @[simp, to_additive] lemma one_hom.id_comp [has_one M] [has_one N] (f : one_hom M N) : (one_hom.id N).comp f = f := one_hom.ext $ λ x, rfl @[simp, to_additive] lemma mul_hom.id_comp [has_mul M] [has_mul N] (f : M →ₙ* N) : (mul_hom.id N).comp f = f := mul_hom.ext $ λ x, rfl @[simp, to_additive] lemma monoid_hom.id_comp [mul_one_class M] [mul_one_class N] (f : M →* N) : (monoid_hom.id N).comp f = f := monoid_hom.ext $ λ x, rfl @[simp] lemma monoid_with_zero_hom.id_comp [mul_zero_one_class M] [mul_zero_one_class N] (f : M →*₀ N) : (monoid_with_zero_hom.id N).comp f = f := monoid_with_zero_hom.ext $ λ x, rfl @[to_additive add_monoid_hom.map_nsmul] protected theorem monoid_hom.map_pow [monoid M] [monoid N] (f : M →* N) (a : M) (n : ℕ) : f (a ^ n) = (f a) ^ n := map_pow f a n @[to_additive] protected theorem monoid_hom.map_zpow' [div_inv_monoid M] [div_inv_monoid N] (f : M →* N) (hf : ∀ x, f (x⁻¹) = (f x)⁻¹) (a : M) (n : ℤ) : f (a ^ n) = (f a) ^ n := map_zpow' f hf a n section End namespace monoid variables (M) [mul_one_class M] /-- The monoid of endomorphisms. -/ protected def End := M →* M namespace End instance : monoid (monoid.End M) := { mul := monoid_hom.comp, one := monoid_hom.id M, mul_assoc := λ _ _ _, monoid_hom.comp_assoc _ _ _, mul_one := monoid_hom.comp_id, one_mul := monoid_hom.id_comp } instance : inhabited (monoid.End M) := ⟨1⟩ instance : has_coe_to_fun (monoid.End M) (λ _, M → M) := ⟨monoid_hom.to_fun⟩ end End @[simp] lemma coe_one : ((1 : monoid.End M) : M → M) = id := rfl @[simp] lemma coe_mul (f g) : ((f * g : monoid.End M) : M → M) = f ∘ g := rfl end monoid namespace add_monoid variables (A : Type*) [add_zero_class A] /-- The monoid of endomorphisms. -/ protected def End := A →+ A namespace End instance : monoid (add_monoid.End A) := { mul := add_monoid_hom.comp, one := add_monoid_hom.id A, mul_assoc := λ _ _ _, add_monoid_hom.comp_assoc _ _ _, mul_one := add_monoid_hom.comp_id, one_mul := add_monoid_hom.id_comp } instance : inhabited (add_monoid.End A) := ⟨1⟩ instance : has_coe_to_fun (add_monoid.End A) (λ _, A → A) := ⟨add_monoid_hom.to_fun⟩ end End @[simp] lemma coe_one : ((1 : add_monoid.End A) : A → A) = id := rfl @[simp] lemma coe_mul (f g) : ((f * g : add_monoid.End A) : A → A) = f ∘ g := rfl end add_monoid end End /-- `1` is the homomorphism sending all elements to `1`. -/ @[to_additive] instance [has_one M] [has_one N] : has_one (one_hom M N) := ⟨⟨λ _, 1, rfl⟩⟩ /-- `1` is the multiplicative homomorphism sending all elements to `1`. -/ @[to_additive] instance [has_mul M] [mul_one_class N] : has_one (M →ₙ* N) := ⟨⟨λ _, 1, λ _ _, (one_mul 1).symm⟩⟩ /-- `1` is the monoid homomorphism sending all elements to `1`. -/ @[to_additive] instance [mul_one_class M] [mul_one_class N] : has_one (M →* N) := ⟨⟨λ _, 1, rfl, λ _ _, (one_mul 1).symm⟩⟩ /-- `0` is the homomorphism sending all elements to `0`. -/ add_decl_doc zero_hom.has_zero /-- `0` is the additive homomorphism sending all elements to `0`. -/ add_decl_doc add_hom.has_zero /-- `0` is the additive monoid homomorphism sending all elements to `0`. -/ add_decl_doc add_monoid_hom.has_zero @[simp, to_additive] lemma one_hom.one_apply [has_one M] [has_one N] (x : M) : (1 : one_hom M N) x = 1 := rfl @[simp, to_additive] lemma monoid_hom.one_apply [mul_one_class M] [mul_one_class N] (x : M) : (1 : M →* N) x = 1 := rfl @[simp, to_additive] lemma one_hom.one_comp [has_one M] [has_one N] [has_one P] (f : one_hom M N) : (1 : one_hom N P).comp f = 1 := rfl @[simp, to_additive] lemma one_hom.comp_one [has_one M] [has_one N] [has_one P] (f : one_hom N P) : f.comp (1 : one_hom M N) = 1 := by { ext, simp only [one_hom.map_one, one_hom.coe_comp, function.comp_app, one_hom.one_apply] } @[to_additive] instance [has_one M] [has_one N] : inhabited (one_hom M N) := ⟨1⟩ @[to_additive] instance [has_mul M] [mul_one_class N] : inhabited (M →ₙ* N) := ⟨1⟩ @[to_additive] instance [mul_one_class M] [mul_one_class N] : inhabited (M →* N) := ⟨1⟩ -- unlike the other homs, `monoid_with_zero_hom` does not have a `1` or `0` instance [mul_zero_one_class M] : inhabited (M →*₀ M) := ⟨monoid_with_zero_hom.id M⟩ namespace mul_hom /-- Given two mul morphisms `f`, `g` to a commutative semigroup, `f * g` is the mul morphism sending `x` to `f x * g x`. -/ @[to_additive] instance [has_mul M] [comm_semigroup N] : has_mul (M →ₙ* N) := ⟨λ f g, { to_fun := λ m, f m * g m, map_mul' := begin intros, show f (x * y) * g (x * y) = f x * g x * (f y * g y), rw [f.map_mul, g.map_mul, ←mul_assoc, ←mul_assoc, mul_right_comm (f x)], end }⟩ /-- Given two additive morphisms `f`, `g` to an additive commutative semigroup, `f + g` is the additive morphism sending `x` to `f x + g x`. -/ add_decl_doc add_hom.has_add @[simp, to_additive] lemma mul_apply {M N} {mM : has_mul M} {mN : comm_semigroup N} (f g : M →ₙ* N) (x : M) : (f * g) x = f x * g x := rfl @[to_additive] lemma mul_comp [has_mul M] [has_mul N] [comm_semigroup P] (g₁ g₂ : N →ₙ* P) (f : M →ₙ* N) : (g₁ * g₂).comp f = g₁.comp f * g₂.comp f := rfl @[to_additive] lemma comp_mul [has_mul M] [comm_semigroup N] [comm_semigroup P] (g : N →ₙ* P) (f₁ f₂ : M →ₙ* N) : g.comp (f₁ * f₂) = g.comp f₁ * g.comp f₂ := by { ext, simp only [mul_apply, function.comp_app, map_mul, coe_comp] } end mul_hom namespace monoid_hom variables [mM : mul_one_class M] [mN : mul_one_class N] [mP : mul_one_class P] variables [group G] [comm_group H] /-- Given two monoid morphisms `f`, `g` to a commutative monoid, `f * g` is the monoid morphism sending `x` to `f x * g x`. -/ @[to_additive] instance {M N} {mM : mul_one_class M} [comm_monoid N] : has_mul (M →* N) := ⟨λ f g, { to_fun := λ m, f m * g m, map_one' := show f 1 * g 1 = 1, by simp, map_mul' := begin intros, show f (x * y) * g (x * y) = f x * g x * (f y * g y), rw [f.map_mul, g.map_mul, ←mul_assoc, ←mul_assoc, mul_right_comm (f x)], end }⟩ /-- Given two additive monoid morphisms `f`, `g` to an additive commutative monoid, `f + g` is the additive monoid morphism sending `x` to `f x + g x`. -/ add_decl_doc add_monoid_hom.has_add @[simp, to_additive] lemma mul_apply {M N} {mM : mul_one_class M} {mN : comm_monoid N} (f g : M →* N) (x : M) : (f * g) x = f x * g x := rfl @[simp, to_additive] lemma one_comp [mul_one_class M] [mul_one_class N] [mul_one_class P] (f : M →* N) : (1 : N →* P).comp f = 1 := rfl @[simp, to_additive] lemma comp_one [mul_one_class M] [mul_one_class N] [mul_one_class P] (f : N →* P) : f.comp (1 : M →* N) = 1 := by { ext, simp only [map_one, coe_comp, function.comp_app, one_apply] } @[to_additive] lemma mul_comp [mul_one_class M] [mul_one_class N] [comm_monoid P] (g₁ g₂ : N →* P) (f : M →* N) : (g₁ * g₂).comp f = g₁.comp f * g₂.comp f := rfl @[to_additive] lemma comp_mul [mul_one_class M] [comm_monoid N] [comm_monoid P] (g : N →* P) (f₁ f₂ : M →* N) : g.comp (f₁ * f₂) = g.comp f₁ * g.comp f₂ := by { ext, simp only [mul_apply, function.comp_app, map_mul, coe_comp] } /-- If two homomorphism from a group to a monoid are equal at `x`, then they are equal at `x⁻¹`. -/ @[to_additive "If two homomorphism from an additive group to an additive monoid are equal at `x`, then they are equal at `-x`." ] lemma eq_on_inv {G} [group G] [monoid M] [monoid_hom_class F G M] {f g : F} {x : G} (h : f x = g x) : f x⁻¹ = g x⁻¹ := left_inv_eq_right_inv (map_mul_eq_one f $ inv_mul_self x) $ h.symm ▸ map_mul_eq_one g $ mul_inv_self x /-- Group homomorphisms preserve inverse. -/ @[to_additive] protected theorem map_inv {G H} [group G] [group H] (f : G →* H) (g : G) : f g⁻¹ = (f g)⁻¹ := map_inv f g /-- Group homomorphisms preserve integer power. -/ @[to_additive "Additive group homomorphisms preserve integer scaling."] protected theorem map_zpow {G H} [group G] [group H] (f : G →* H) (g : G) (n : ℤ) : f (g ^ n) = (f g) ^ n := map_zpow f g n /-- Group homomorphisms preserve division. -/ @[to_additive "Additive group homomorphisms preserve subtraction."] protected theorem map_div {G H} [group G] [group H] (f : G →* H) (g h : G) : f (g / h) = f g / f h := map_div f g h /-- Group homomorphisms preserve division. -/ @[to_additive] protected theorem map_mul_inv {G H} [group G] [group H] (f : G →* H) (g h : G) : f (g * h⁻¹) = (f g) * (f h)⁻¹ := map_mul_inv f g h /-- A homomorphism from a group to a monoid is injective iff its kernel is trivial. For the iff statement on the triviality of the kernel, see `injective_iff_map_eq_one'`. -/ @[to_additive "A homomorphism from an additive group to an additive monoid is injective iff its kernel is trivial. For the iff statement on the triviality of the kernel, see `injective_iff_map_eq_zero'`."] lemma _root_.injective_iff_map_eq_one {G H} [group G] [mul_one_class H] [monoid_hom_class F G H] (f : F) : function.injective f ↔ (∀ a, f a = 1 → a = 1) := ⟨λ h x, (map_eq_one_iff f h).mp, λ h x y hxy, mul_inv_eq_one.1 $ h _ $ by rw [map_mul, hxy, ← map_mul, mul_inv_self, map_one]⟩ /-- A homomorphism from a group to a monoid is injective iff its kernel is trivial, stated as an iff on the triviality of the kernel. For the implication, see `injective_iff_map_eq_one`. -/ @[to_additive "A homomorphism from an additive group to an additive monoid is injective iff its kernel is trivial, stated as an iff on the triviality of the kernel. For the implication, see `injective_iff_map_eq_zero`."] lemma _root_.injective_iff_map_eq_one' {G H} [group G] [mul_one_class H] [monoid_hom_class F G H] (f : F) : function.injective f ↔ (∀ a, f a = 1 ↔ a = 1) := (injective_iff_map_eq_one f).trans $ forall_congr $ λ a, ⟨λ h, ⟨h, λ H, H.symm ▸ map_one f⟩, iff.mp⟩ include mM /-- Makes a group homomorphism from a proof that the map preserves multiplication. -/ @[to_additive "Makes an additive group homomorphism from a proof that the map preserves addition.", simps {fully_applied := ff}] def mk' (f : M → G) (map_mul : ∀ a b : M, f (a * b) = f a * f b) : M →* G := { to_fun := f, map_mul' := map_mul, map_one' := mul_left_eq_self.1 $ by rw [←map_mul, mul_one] } omit mM /-- Makes a group homomorphism from a proof that the map preserves right division `λ x y, x * y⁻¹`. See also `monoid_hom.of_map_div` for a version using `λ x y, x / y`. -/ @[to_additive "Makes an additive group homomorphism from a proof that the map preserves the operation `λ a b, a + -b`. See also `add_monoid_hom.of_map_sub` for a version using `λ a b, a - b`."] def of_map_mul_inv {H : Type*} [group H] (f : G → H) (map_div : ∀ a b : G, f (a * b⁻¹) = f a * (f b)⁻¹) : G →* H := mk' f $ λ x y, calc f (x * y) = f x * (f $ 1 * 1⁻¹ * y⁻¹)⁻¹ : by simp only [one_mul, inv_one, ← map_div, inv_inv] ... = f x * f y : by { simp only [map_div], simp only [mul_right_inv, one_mul, inv_inv] } @[simp, to_additive] lemma coe_of_map_mul_inv {H : Type*} [group H] (f : G → H) (map_div : ∀ a b : G, f (a * b⁻¹) = f a * (f b)⁻¹) : ⇑(of_map_mul_inv f map_div) = f := rfl /-- Define a morphism of additive groups given a map which respects ratios. -/ @[to_additive /-"Define a morphism of additive groups given a map which respects difference."-/] def of_map_div {H : Type*} [group H] (f : G → H) (hf : ∀ x y, f (x / y) = f x / f y) : G →* H := of_map_mul_inv f (by simpa only [div_eq_mul_inv] using hf) @[simp, to_additive] lemma coe_of_map_div {H : Type*} [group H] (f : G → H) (hf : ∀ x y, f (x / y) = f x / f y) : ⇑(of_map_div f hf) = f := rfl /-- If `f` is a monoid homomorphism to a commutative group, then `f⁻¹` is the homomorphism sending `x` to `(f x)⁻¹`. -/ @[to_additive] instance {M G} [mul_one_class M] [comm_group G] : has_inv (M →* G) := ⟨λ f, mk' (λ g, (f g)⁻¹) $ λ a b, by rw [←mul_inv, f.map_mul]⟩ /-- If `f` is an additive monoid homomorphism to an additive commutative group, then `-f` is the homomorphism sending `x` to `-(f x)`. -/ add_decl_doc add_monoid_hom.has_neg @[simp, to_additive] lemma inv_apply {M G} {mM : mul_one_class M} {gG : comm_group G} (f : M →* G) (x : M) : f⁻¹ x = (f x)⁻¹ := rfl @[simp, to_additive] lemma inv_comp {M N A} {mM : mul_one_class M} {gN : mul_one_class N} {gA : comm_group A} (φ : N →* A) (ψ : M →* N) : φ⁻¹.comp ψ = (φ.comp ψ)⁻¹ := by { ext, simp only [function.comp_app, inv_apply, coe_comp] } @[simp, to_additive] lemma comp_inv {M A B} {mM : mul_one_class M} {mA : comm_group A} {mB : comm_group B} (φ : A →* B) (ψ : M →* A) : φ.comp ψ⁻¹ = (φ.comp ψ)⁻¹ := by { ext, simp only [function.comp_app, inv_apply, map_inv, coe_comp] } /-- If `f` and `g` are monoid homomorphisms to a commutative group, then `f / g` is the homomorphism sending `x` to `(f x) / (g x)`. -/ @[to_additive] instance {M G} [mul_one_class M] [comm_group G] : has_div (M →* G) := ⟨λ f g, mk' (λ x, f x / g x) $ λ a b, by simp [div_eq_mul_inv, mul_assoc, mul_left_comm, mul_comm]⟩ /-- If `f` and `g` are monoid homomorphisms to an additive commutative group, then `f - g` is the homomorphism sending `x` to `(f x) - (g x)`. -/ add_decl_doc add_monoid_hom.has_sub @[simp, to_additive] lemma div_apply {M G} {mM : mul_one_class M} {gG : comm_group G} (f g : M →* G) (x : M) : (f / g) x = f x / g x := rfl end monoid_hom /-- Given two monoid with zero morphisms `f`, `g` to a commutative monoid, `f * g` is the monoid with zero morphism sending `x` to `f x * g x`. -/ instance {M N} {hM : mul_zero_one_class M} [comm_monoid_with_zero N] : has_mul (M →*₀ N) := ⟨λ f g, { to_fun := λ a, f a * g a, map_zero' := by rw [map_zero, zero_mul], ..(f * g : M →* N) }⟩ section commute variables [has_mul M] [has_mul N] {a x y : M} @[simp, to_additive] protected lemma semiconj_by.map [mul_hom_class F M N] (h : semiconj_by a x y) (f : F) : semiconj_by (f a) (f x) (f y) := by simpa only [semiconj_by, map_mul] using congr_arg f h @[simp, to_additive] protected lemma commute.map [mul_hom_class F M N] (h : commute x y) (f : F) : commute (f x) (f y) := h.map f end commute
3baf6bf58803635b2283e2227849aa9c4f16c6fd
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/category_theory/graded_object.lean
cf65de92f756eba5929754c23df7e641e67f7ee6
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
7,171
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.shift import category_theory.concrete_category /-! # The category of graded objects For any type `β`, a `β`-graded object over some category `C` is just a function `β → C` into the objects of `C`. We define the category structure on these. We describe the `comap` functors obtained by precomposing with functions `β → γ`. As a consequence a fixed element (e.g. `1`) in an additive group `β` provides a shift functor on `β`-graded objects When `C` has coproducts we construct the `total` functor `graded_object β C ⥤ C`, show that it is faithful, and deduce that when `C` is concrete so is `graded_object β C`. -/ open category_theory.limits namespace category_theory universes w v u /-- A type synonym for `β → C`, used for `β`-graded objects in a category `C`. -/ def graded_object (β : Type w) (C : Type u) : Type (max w u) := β → C -- Satisfying the inhabited linter... instance inhabited_graded_object (β : Type w) (C : Type u) [inhabited C] : inhabited (graded_object β C) := ⟨λ b, inhabited.default C⟩ /-- A type synonym for `β → C`, used for `β`-graded objects in a category `C` with a shift functor given by translation by `s`. -/ @[nolint unused_arguments] -- `s` is here to distinguish type synonyms asking for different shifts abbreviation graded_object_with_shift {β : Type w} [add_comm_group β] (s : β) (C : Type u) : Type (max w u) := graded_object β C namespace graded_object variables {C : Type u} [category.{v} C] instance category_of_graded_objects (β : Type w) : category.{(max w v)} (graded_object β C) := { hom := λ X Y, Π b : β, X b ⟶ Y b, id := λ X b, 𝟙 (X b), comp := λ X Y Z f g b, f b ≫ g b, } @[simp] lemma id_apply {β : Type w} (X : graded_object β C) (b : β) : ((𝟙 X) : Π b, X b ⟶ X b) b = 𝟙 (X b) := rfl @[simp] lemma comp_apply {β : Type w} {X Y Z : graded_object β C} (f : X ⟶ Y) (g : Y ⟶ Z) (b : β) : ((f ≫ g) : Π b, X b ⟶ Z b) b = f b ≫ g b := rfl section variable (C) /-- Pull back a graded object along a change-of-grading function. -/ @[simps] def comap {β γ : Type w} (f : β → γ) : (graded_object γ C) ⥤ (graded_object β C) := { obj := λ X, X ∘ f, map := λ X Y g b, g (f b) } /-- The natural isomorphism between pulling back a grading along the identity function, and the identity functor. -/ @[simps] def comap_id (β : Type w) : comap C (id : β → β) ≅ 𝟭 (graded_object β C) := { hom := { app := λ X, 𝟙 X }, inv := { app := λ X, 𝟙 X } }. /-- The natural isomorphism comparing between pulling back along two successive functions, and pulling back along their composition -/ @[simps] def comap_comp {β γ δ : Type w} (f : β → γ) (g : γ → δ) : comap C g ⋙ comap C f ≅ comap C (g ∘ f) := { hom := { app := λ X b, 𝟙 (X (g (f b))) }, inv := { app := λ X b, 𝟙 (X (g (f b))) } } /-- The natural isomorphism comparing between pulling back along two propositionally equal functions. -/ @[simps] def comap_eq {β γ : Type w} {f g : β → γ} (h : f = g) : comap C f ≅ comap C g := { hom := { app := λ X b, eq_to_hom begin dsimp [comap], subst h, end }, inv := { app := λ X b, eq_to_hom begin dsimp [comap], subst h, end }, } @[simp] lemma comap_eq_symm {β γ : Type w} {f g : β → γ} (h : f = g) : comap_eq C h.symm = (comap_eq C h).symm := by tidy @[simp] lemma comap_eq_trans {β γ : Type w} {f g h : β → γ} (k : f = g) (l : g = h) : comap_eq C (k.trans l) = comap_eq C k ≪≫ comap_eq C l := begin ext X b, simp, end /-- The equivalence between β-graded objects and γ-graded objects, given an equivalence between β and γ. -/ @[simps] def comap_equiv {β γ : Type w} (e : β ≃ γ) : (graded_object β C) ≌ (graded_object γ C) := { functor := comap C (e.symm : γ → β), inverse := comap C (e : β → γ), counit_iso := (comap_comp C _ _).trans (comap_eq C (by { ext, simp } )), unit_iso := (comap_eq C (by { ext, simp} )).trans (comap_comp _ _ _).symm, functor_unit_iso_comp' := λ X, begin ext b, dsimp, simp, end, } end instance has_shift {β : Type*} [add_comm_group β] (s : β) : has_shift (graded_object_with_shift s C) := { shift := comap_equiv C { to_fun := λ b, b-s, inv_fun := λ b, b+s, left_inv := λ x, (by simp), right_inv := λ x, (by simp), } } @[simp] lemma shift_functor_obj_apply {β : Type*} [add_comm_group β] (s : β) (X : β → C) (t : β) : (shift (graded_object_with_shift s C)).functor.obj X t = X (t + s) := rfl @[simp] lemma shift_functor_map_apply {β : Type*} [add_comm_group β] (s : β) {X Y : graded_object_with_shift s C} (f : X ⟶ Y) (t : β) : (shift (graded_object_with_shift s C)).functor.map f t = f (t + s) := rfl instance has_zero_morphisms [has_zero_morphisms C] (β : Type w) : has_zero_morphisms.{(max w v)} (graded_object β C) := { has_zero := λ X Y, { zero := λ b, 0 } } @[simp] lemma zero_apply [has_zero_morphisms C] (β : Type w) (X Y : graded_object β C) (b : β) : (0 : X ⟶ Y) b = 0 := rfl section local attribute [instance] has_zero_object.has_zero instance has_zero_object [has_zero_object C] [has_zero_morphisms C] (β : Type w) : has_zero_object.{(max w v)} (graded_object β C) := { zero := λ b, (0 : C), unique_to := λ X, ⟨⟨λ b, 0⟩, λ f, (by ext)⟩, unique_from := λ X, ⟨⟨λ b, 0⟩, λ f, (by ext)⟩, } end end graded_object namespace graded_object -- The universes get a little hairy here, so we restrict the universe level for the grading to 0. -- Since we're typically interested in grading by ℤ or a finite group, this should be okay. -- If you're grading by things in higher universes, have fun! variables (β : Type) variables (C : Type u) [category.{v} C] variables [has_coproducts C] /-- The total object of a graded object is the coproduct of the graded components. -/ def total : graded_object β C ⥤ C := { obj := λ X, ∐ (λ i : ulift.{v} β, X i.down), map := λ X Y f, limits.sigma.map (λ i, f i.down) }. variables [has_zero_morphisms C] /-- The `total` functor taking a graded object to the coproduct of its graded components is faithful. To prove this, we need to know that the coprojections into the coproduct are monomorphisms, which follows from the fact we have zero morphisms and decidable equality for the grading. -/ instance : faithful (total β C) := { map_injective' := λ X Y f g w, begin classical, ext i, replace w := sigma.ι (λ i : ulift β, X i.down) ⟨i⟩ ≫= w, erw [colimit.ι_map, colimit.ι_map] at w, exact mono.right_cancellation _ _ w, end } end graded_object namespace graded_object variables (β : Type) variables (C : Type (u+1)) [large_category C] [concrete_category C] [has_coproducts C] [has_zero_morphisms C] instance : concrete_category (graded_object β C) := { forget := total β C ⋙ forget C } instance : has_forget₂ (graded_object β C) C := { forget₂ := total β C } end graded_object end category_theory
b1480b209357cd3d8986a3c4646aeb9d6a6c9d97
94637389e03c919023691dcd05bd4411b1034aa5
/src/zzz_junk/lang/imp_test.lean
49d39d6863ab8937bb9ba0996617503e81f66147
[]
no_license
kevinsullivan/complogic-s21
7c4eef2105abad899e46502270d9829d913e8afc
99039501b770248c8ceb39890be5dfe129dc1082
refs/heads/master
1,682,985,669,944
1,621,126,241,000
1,621,126,241,000
335,706,272
0
38
null
1,618,325,669,000
1,612,374,118,000
Lean
UTF-8
Lean
false
false
1,528
lean
import .imp import .var_test -- a little program: X gets overwritten def program : cmd := X = [7]; Y = [8]; Z = [9]; X = [10] -- verify that post state is as expected def post_env := c_eval program init_env example : post_env.nat_var_interp X = 10 := rfl example : post_env.nat_var_interp Y = 8 := rfl example : post_env.nat_var_interp Z = 9 := rfl /- Claim and prove logically that in "program" post state, X = 10. -/ theorem t1 : ∀ (post : env), c_sem program init_env post → post.nat_var_interp X = 10 := begin assume post, assume h, cases h, cases h_ᾰ_1, rw <- h_ᾰ_1_ᾰ, cases h_is, apply rfl, end -- Exam: fix this proof example : ∀ (post : env), c_sem program init_env post → post.nat_var_interp Z = 9 := begin assume post, assume h, unfold program at h, cases h, cases h_ᾰ, cases h_ᾰ_ᾰ_1, cases h_ᾰ_1, rw <- h_ᾰ_1_ᾰ, rw <- h_ᾰ_ᾰ_1_ᾰ, unfold Z, apply rfl, -- YOU FIX end -- open cmd def p2 : cmd := ifelse [tt] (X=[1]) (X=[2]) def p3 : cmd := ifelse [ff] (X=[1]) (X=[2]) -- computational testing example : (c_eval p2 init_env).nat_var_interp X = 1 := rfl example : (c_eval p3 init_env).nat_var_interp X = 2 := rfl -- logical verification example : ∀ (e e' : env), c_sem p2 e e' → e'.nat_var_interp X = 1 := begin unfold p2, intros, cases ᾰ, cases ᾰ_ᾰ, -- impossible case cases ᾰ_ᾰ_1, rw <- ᾰ_ᾰ_1_ᾰ, cases e, exact rfl, end
51d344ef2cec99fe8c3bb584277e9fdb5a2b7ede
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/linear_algebra/adic_completion.lean
7548f11f3764de79e6912b919a43512de2fe1b6d
[ "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
9,989
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.geom_sum import linear_algebra.smodeq import ring_theory.jacobson_ideal /-! # Completion of a module with respect to an ideal. In this file we define the notions of Hausdorff, precomplete, and complete for an `R`-module `M` with respect to an ideal `I`: ## Main definitions - `is_Hausdorff I M`: this says that the intersection of `I^n M` is `0`. - `is_precomplete I M`: this says that every Cauchy sequence converges. - `is_adic_complete I M`: this says that `M` is Hausdorff and precomplete. - `Hausdorffification I M`: this is the universal Hausdorff module with a map from `M`. - `completion I M`: if `I` is finitely generated, then this is the universal complete module (TODO) with a map from `M`. This map is injective iff `M` is Hausdorff and surjective iff `M` is precomplete. -/ open submodule variables {R : Type*} [comm_ring R] (I : ideal R) variables (M : Type*) [add_comm_group M] [module R M] variables {N : Type*} [add_comm_group N] [module R N] /-- A module `M` is Hausdorff with respect to an ideal `I` if `⋂ I^n M = 0`. -/ class is_Hausdorff : Prop := (haus' : ∀ x : M, (∀ n : ℕ, x ≡ 0 [SMOD (I ^ n • ⊤ : submodule R M)]) → x = 0) /-- A module `M` is precomplete with respect to an ideal `I` if every Cauchy sequence converges. -/ class is_precomplete : Prop := (prec' : ∀ f : ℕ → M, (∀ {m n}, m ≤ n → f m ≡ f n [SMOD (I ^ m • ⊤ : submodule R M)]) → ∃ L : M, ∀ n, f n ≡ L [SMOD (I ^ n • ⊤ : submodule R M)]) /-- A module `M` is `I`-adically complete if it is Hausdorff and precomplete. -/ class is_adic_complete extends is_Hausdorff I M, is_precomplete I M : Prop variables {I M} theorem is_Hausdorff.haus (h : is_Hausdorff I M) : ∀ x : M, (∀ n : ℕ, x ≡ 0 [SMOD (I ^ n • ⊤ : submodule R M)]) → x = 0 := is_Hausdorff.haus' theorem is_Hausdorff_iff : is_Hausdorff I M ↔ ∀ x : M, (∀ n : ℕ, x ≡ 0 [SMOD (I ^ n • ⊤ : submodule R M)]) → x = 0 := ⟨is_Hausdorff.haus, λ h, ⟨h⟩⟩ theorem is_precomplete.prec (h : is_precomplete I M) {f : ℕ → M} : (∀ {m n}, m ≤ n → f m ≡ f n [SMOD (I ^ m • ⊤ : submodule R M)]) → ∃ L : M, ∀ n, f n ≡ L [SMOD (I ^ n • ⊤ : submodule R M)] := is_precomplete.prec' _ theorem is_precomplete_iff : is_precomplete I M ↔ ∀ f : ℕ → M, (∀ {m n}, m ≤ n → f m ≡ f n [SMOD (I ^ m • ⊤ : submodule R M)]) → ∃ L : M, ∀ n, f n ≡ L [SMOD (I ^ n • ⊤ : submodule R M)] := ⟨λ h, h.1, λ h, ⟨h⟩⟩ variables (I M) /-- The Hausdorffification of a module with respect to an ideal. -/ @[reducible] def Hausdorffification : Type* := M ⧸ (⨅ n : ℕ, I ^ n • ⊤ : submodule R M) /-- The completion of a module with respect to an ideal. This is not necessarily Hausdorff. In fact, this is only complete if the ideal is finitely generated. -/ def adic_completion : submodule R (Π n : ℕ, (M ⧸ (I ^ n • ⊤ : submodule R M))) := { carrier := { f | ∀ {m n} (h : m ≤ n), liftq _ (mkq _) (by { rw ker_mkq, exact smul_mono (ideal.pow_le_pow h) le_rfl }) (f n) = f m }, zero_mem' := λ m n hmn, by rw [pi.zero_apply, pi.zero_apply, linear_map.map_zero], add_mem' := λ f g hf hg m n hmn, by rw [pi.add_apply, pi.add_apply, linear_map.map_add, hf hmn, hg hmn], smul_mem' := λ c f hf m n hmn, by rw [pi.smul_apply, pi.smul_apply, linear_map.map_smul, hf hmn] } namespace is_Hausdorff instance bot : is_Hausdorff (⊥ : ideal R) M := ⟨λ x hx, by simpa only [pow_one ⊥, bot_smul, smodeq.bot] using hx 1⟩ variables {M} protected theorem subsingleton (h : is_Hausdorff (⊤ : ideal R) M) : subsingleton M := ⟨λ x y, eq_of_sub_eq_zero $ h.haus (x - y) $ λ n, by { rw [ideal.top_pow, top_smul], exact smodeq.top }⟩ variables (M) @[priority 100] instance of_subsingleton [subsingleton M] : is_Hausdorff I M := ⟨λ x _, subsingleton.elim _ _⟩ variables {I M} theorem infi_pow_smul (h : is_Hausdorff I M) : (⨅ n : ℕ, I ^ n • ⊤ : submodule R M) = ⊥ := eq_bot_iff.2 $ λ x hx, (mem_bot _).2 $ h.haus x $ λ n, smodeq.zero.2 $ (mem_infi $ λ n : ℕ, I ^ n • ⊤).1 hx n end is_Hausdorff namespace Hausdorffification /-- The canonical linear map to the Hausdorffification. -/ def of : M →ₗ[R] Hausdorffification I M := mkq _ variables {I M} @[elab_as_eliminator] lemma induction_on {C : Hausdorffification I M → Prop} (x : Hausdorffification I M) (ih : ∀ x, C (of I M x)) : C x := quotient.induction_on' x ih variables (I M) instance : is_Hausdorff I (Hausdorffification I M) := ⟨λ x, quotient.induction_on' x $ λ x hx, (quotient.mk_eq_zero _).2 $ (mem_infi _).2 $ λ n, begin have := comap_map_mkq (⨅ n : ℕ, I ^ n • ⊤ : submodule R M) (I ^ n • ⊤), simp only [sup_of_le_right (infi_le (λ n, (I ^ n • ⊤ : submodule R M)) n)] at this, rw [← this, map_smul'', mem_comap, map_top, range_mkq, ← smodeq.zero], exact hx n end⟩ variables {M} [h : is_Hausdorff I N] include h /-- universal property of Hausdorffification: any linear map to a Hausdorff module extends to a unique map from the Hausdorffification. -/ def lift (f : M →ₗ[R] N) : Hausdorffification I M →ₗ[R] N := liftq _ f $ map_le_iff_le_comap.1 $ h.infi_pow_smul ▸ le_infi (λ n, le_trans (map_mono $ infi_le _ n) $ by { rw map_smul'', exact smul_mono le_rfl le_top }) theorem lift_of (f : M →ₗ[R] N) (x : M) : lift I f (of I M x) = f x := rfl theorem lift_comp_of (f : M →ₗ[R] N) : (lift I f).comp (of I M) = f := linear_map.ext $ λ _, rfl /-- Uniqueness of lift. -/ theorem lift_eq (f : M →ₗ[R] N) (g : Hausdorffification I M →ₗ[R] N) (hg : g.comp (of I M) = f) : g = lift I f := linear_map.ext $ λ x, induction_on x $ λ x, by rw [lift_of, ← hg, linear_map.comp_apply] end Hausdorffification namespace is_precomplete instance bot : is_precomplete (⊥ : ideal R) M := begin refine ⟨λ f hf, ⟨f 1, λ n, _⟩⟩, cases n, { rw [pow_zero, ideal.one_eq_top, top_smul], exact smodeq.top }, specialize hf (nat.le_add_left 1 n), rw [pow_one, bot_smul, smodeq.bot] at hf, rw hf end instance top : is_precomplete (⊤ : ideal R) M := ⟨λ f hf, ⟨0, λ n, by { rw [ideal.top_pow, top_smul], exact smodeq.top }⟩⟩ @[priority 100] instance of_subsingleton [subsingleton M] : is_precomplete I M := ⟨λ f hf, ⟨0, λ n, by rw subsingleton.elim (f n) 0⟩⟩ end is_precomplete namespace adic_completion /-- The canonical linear map to the completion. -/ def of : M →ₗ[R] adic_completion I M := { to_fun := λ x, ⟨λ n, mkq _ x, λ m n hmn, rfl⟩, map_add' := λ x y, rfl, map_smul' := λ c x, rfl } @[simp] lemma of_apply (x : M) (n : ℕ) : (of I M x).1 n = mkq _ x := rfl /-- Linearly evaluating a sequence in the completion at a given input. -/ def eval (n : ℕ) : adic_completion I M →ₗ[R] (M ⧸ (I ^ n • ⊤ : submodule R M)) := { to_fun := λ f, f.1 n, map_add' := λ f g, rfl, map_smul' := λ c f, rfl } @[simp] lemma coe_eval (n : ℕ) : (eval I M n : adic_completion I M → (M ⧸ (I ^ n • ⊤ : submodule R M))) = λ f, f.1 n := rfl lemma eval_apply (n : ℕ) (f : adic_completion I M) : eval I M n f = f.1 n := rfl lemma eval_of (n : ℕ) (x : M) : eval I M n (of I M x) = mkq _ x := rfl @[simp] lemma eval_comp_of (n : ℕ) : (eval I M n).comp (of I M) = mkq _ := rfl @[simp] lemma range_eval (n : ℕ) : (eval I M n).range = ⊤ := linear_map.range_eq_top.2 $ λ x, quotient.induction_on' x $ λ x, ⟨of I M x, rfl⟩ variables {I M} @[ext] lemma ext {x y : adic_completion I M} (h : ∀ n, eval I M n x = eval I M n y) : x = y := subtype.eq $ funext h variables (I M) instance : is_Hausdorff I (adic_completion I M) := ⟨λ x hx, ext $ λ n, smul_induction_on (smodeq.zero.1 $ hx n) (λ r hr x _, ((eval I M n).map_smul r x).symm ▸ quotient.induction_on' (eval I M n x) (λ x, smodeq.zero.2 $ smul_mem_smul hr mem_top)) (λ _ _ ih1 ih2, by rw [linear_map.map_add, ih1, ih2, linear_map.map_zero, add_zero])⟩ end adic_completion namespace is_adic_complete instance bot : is_adic_complete (⊥ : ideal R) M := {} protected theorem subsingleton (h : is_adic_complete (⊤ : ideal R) M) : subsingleton M := h.1.subsingleton @[priority 100] instance of_subsingleton [subsingleton M] : is_adic_complete I M := {} open_locale big_operators open finset lemma le_jacobson_bot [is_adic_complete I R] : I ≤ (⊥ : ideal R).jacobson := begin intros x hx, rw [← ideal.neg_mem_iff, ideal.mem_jacobson_bot], intros y, rw add_comm, let f : ℕ → R := λ n, ∑ i in range n, (x * y) ^ i, have hf : ∀ m n, m ≤ n → f m ≡ f n [SMOD I ^ m • (⊤ : submodule R R)], { intros m n h, simp only [f, algebra.id.smul_eq_mul, ideal.mul_top, smodeq.sub_mem], rw [← add_tsub_cancel_of_le h, finset.sum_range_add, ← sub_sub, sub_self, zero_sub, neg_mem_iff], apply submodule.sum_mem, intros n hn, rw [mul_pow, pow_add, mul_assoc], exact ideal.mul_mem_right _ (I ^ m) (ideal.pow_mem_pow hx m) }, obtain ⟨L, hL⟩ := is_precomplete.prec to_is_precomplete hf, { rw is_unit_iff_exists_inv, use L, rw [← sub_eq_zero, neg_mul], apply is_Hausdorff.haus (to_is_Hausdorff : is_Hausdorff I R), intros n, specialize hL n, rw [smodeq.sub_mem, algebra.id.smul_eq_mul, ideal.mul_top] at ⊢ hL, rw sub_zero, suffices : (1 - x * y) * (f n) - 1 ∈ I ^ n, { convert (ideal.sub_mem _ this (ideal.mul_mem_left _ (1 + - (x * y)) hL)) using 1, ring }, cases n, { simp only [ideal.one_eq_top, pow_zero] }, { dsimp [f], rw [← neg_sub _ (1:R), neg_mul, mul_geom_sum, neg_sub, sub_sub, add_comm, ← sub_sub, sub_self, zero_sub, neg_mem_iff, mul_pow], exact ideal.mul_mem_right _ (I ^ _) (ideal.pow_mem_pow hx _), } }, end end is_adic_complete
a799b9c53b8ee8e80e5a98809955da93efdb491b
e94d3f31e48d06d252ee7307fe71efe1d500f274
/hott/init/path.hlean
86f668f8615565a59d391e6d0bb42a35d590abe0
[ "Apache-2.0" ]
permissive
GallagherCommaJack/lean
e4471240a069d82f97cb361d2bf1a029de3f4256
226f8bafeb9baaa5a2ac58000c83d6beb29991e2
refs/heads/master
1,610,725,100,482
1,459,194,829,000
1,459,195,377,000
55,377,224
0
0
null
1,459,731,701,000
1,459,731,700,000
null
UTF-8
Lean
false
false
28,449
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Jakob von Raumer, Floris van Doorn Ported from Coq HoTT -/ prelude import .function .tactic open function eq /- Path equality -/ namespace eq variables {A B C : Type} {P : A → Type} {a a' x y z t : A} {b b' : B} --notation a = b := eq a b notation x = y `:>`:50 A:49 := @eq A x y definition idp [reducible] [constructor] {a : A} := refl a definition idpath [reducible] [constructor] (a : A) := refl a -- unbased path induction definition rec' [reducible] [unfold 6] {P : Π (a b : A), (a = b) → Type} (H : Π (a : A), P a a idp) {a b : A} (p : a = b) : P a b p := eq.rec (H a) p definition rec_on' [reducible] [unfold 5] {P : Π (a b : A), (a = b) → Type} {a b : A} (p : a = b) (H : Π (a : A), P a a idp) : P a b p := eq.rec (H a) p /- Concatenation and inverse -/ definition concat [trans] [unfold 6] (p : x = y) (q : y = z) : x = z := by induction q; exact p definition inverse [symm] [unfold 4] (p : x = y) : y = x := by induction p; reflexivity infix ⬝ := concat postfix ⁻¹ := inverse --a second notation for the inverse, which is not overloaded postfix [parsing_only] `⁻¹ᵖ`:std.prec.max_plus := inverse /- The 1-dimensional groupoid structure -/ -- The identity path is a right unit. definition con_idp [unfold_full] (p : x = y) : p ⬝ idp = p := idp -- The identity path is a right unit. definition idp_con [unfold 4] (p : x = y) : idp ⬝ p = p := by induction p; reflexivity -- Concatenation is associative. definition con.assoc' (p : x = y) (q : y = z) (r : z = t) : p ⬝ (q ⬝ r) = (p ⬝ q) ⬝ r := by induction r; reflexivity definition con.assoc (p : x = y) (q : y = z) (r : z = t) : (p ⬝ q) ⬝ r = p ⬝ (q ⬝ r) := by induction r; reflexivity -- The left inverse law. definition con.right_inv [unfold 4] (p : x = y) : p ⬝ p⁻¹ = idp := by induction p; reflexivity -- The right inverse law. definition con.left_inv [unfold 4] (p : x = y) : p⁻¹ ⬝ p = idp := by induction p; reflexivity /- Several auxiliary theorems about canceling inverses across associativity. These are somewhat redundant, following from earlier theorems. -/ definition inv_con_cancel_left (p : x = y) (q : y = z) : p⁻¹ ⬝ (p ⬝ q) = q := by induction q; induction p; reflexivity definition con_inv_cancel_left (p : x = y) (q : x = z) : p ⬝ (p⁻¹ ⬝ q) = q := by induction q; induction p; reflexivity definition con_inv_cancel_right (p : x = y) (q : y = z) : (p ⬝ q) ⬝ q⁻¹ = p := by induction q; reflexivity definition inv_con_cancel_right (p : x = z) (q : y = z) : (p ⬝ q⁻¹) ⬝ q = p := by induction q; reflexivity -- Inverse distributes over concatenation definition con_inv (p : x = y) (q : y = z) : (p ⬝ q)⁻¹ = q⁻¹ ⬝ p⁻¹ := by induction q; induction p; reflexivity definition inv_con_inv_left (p : y = x) (q : y = z) : (p⁻¹ ⬝ q)⁻¹ = q⁻¹ ⬝ p := by induction q; induction p; reflexivity -- universe metavariables definition inv_con_inv_right (p : x = y) (q : z = y) : (p ⬝ q⁻¹)⁻¹ = q ⬝ p⁻¹ := by induction q; induction p; reflexivity definition inv_con_inv_inv (p : y = x) (q : z = y) : (p⁻¹ ⬝ q⁻¹)⁻¹ = q ⬝ p := by induction q; induction p; reflexivity -- Inverse is an involution. definition inv_inv (p : x = y) : p⁻¹⁻¹ = p := by induction p; reflexivity -- auxiliary definition used by 'cases' tactic definition elim_inv_inv {A : Type} {a b : A} {C : a = b → Type} (H₁ : a = b) (H₂ : C (H₁⁻¹⁻¹)) : C H₁ := eq.rec_on (inv_inv H₁) H₂ /- Theorems for moving things around in equations -/ definition con_eq_of_eq_inv_con {p : x = z} {q : y = z} {r : y = x} : p = r⁻¹ ⬝ q → r ⬝ p = q := begin induction r, intro h, exact !idp_con ⬝ h ⬝ !idp_con end definition con_eq_of_eq_con_inv [unfold 5] {p : x = z} {q : y = z} {r : y = x} : r = q ⬝ p⁻¹ → r ⬝ p = q := by induction p; exact id definition inv_con_eq_of_eq_con {p : x = z} {q : y = z} {r : x = y} : p = r ⬝ q → r⁻¹ ⬝ p = q := by induction r; intro h; exact !idp_con ⬝ h ⬝ !idp_con definition con_inv_eq_of_eq_con [unfold 5] {p : z = x} {q : y = z} {r : y = x} : r = q ⬝ p → r ⬝ p⁻¹ = q := by induction p; exact id definition eq_con_of_inv_con_eq {p : x = z} {q : y = z} {r : y = x} : r⁻¹ ⬝ q = p → q = r ⬝ p := by induction r; intro h; exact !idp_con⁻¹ ⬝ h ⬝ !idp_con⁻¹ definition eq_con_of_con_inv_eq [unfold 5] {p : x = z} {q : y = z} {r : y = x} : q ⬝ p⁻¹ = r → q = r ⬝ p := by induction p; exact id definition eq_inv_con_of_con_eq {p : x = z} {q : y = z} {r : x = y} : r ⬝ q = p → q = r⁻¹ ⬝ p := by induction r; intro h; exact !idp_con⁻¹ ⬝ h ⬝ !idp_con⁻¹ definition eq_con_inv_of_con_eq [unfold 5] {p : z = x} {q : y = z} {r : y = x} : q ⬝ p = r → q = r ⬝ p⁻¹ := by induction p; exact id definition eq_of_con_inv_eq_idp [unfold 5] {p q : x = y} : p ⬝ q⁻¹ = idp → p = q := by induction q; exact id definition eq_of_inv_con_eq_idp {p q : x = y} : q⁻¹ ⬝ p = idp → p = q := by induction q; intro h; exact !idp_con⁻¹ ⬝ h definition eq_inv_of_con_eq_idp' [unfold 5] {p : x = y} {q : y = x} : p ⬝ q = idp → p = q⁻¹ := by induction q; exact id definition eq_inv_of_con_eq_idp {p : x = y} {q : y = x} : q ⬝ p = idp → p = q⁻¹ := by induction q; intro h; exact !idp_con⁻¹ ⬝ h definition eq_of_idp_eq_inv_con {p q : x = y} : idp = p⁻¹ ⬝ q → p = q := by induction p; intro h; exact h ⬝ !idp_con definition eq_of_idp_eq_con_inv [unfold 4] {p q : x = y} : idp = q ⬝ p⁻¹ → p = q := by induction p; exact id definition inv_eq_of_idp_eq_con [unfold 4] {p : x = y} {q : y = x} : idp = q ⬝ p → p⁻¹ = q := by induction p; exact id definition inv_eq_of_idp_eq_con' {p : x = y} {q : y = x} : idp = p ⬝ q → p⁻¹ = q := by induction p; intro h; exact h ⬝ !idp_con definition con_inv_eq_idp [unfold 6] {p q : x = y} (r : p = q) : p ⬝ q⁻¹ = idp := by cases r; apply con.right_inv definition inv_con_eq_idp [unfold 6] {p q : x = y} (r : p = q) : q⁻¹ ⬝ p = idp := by cases r; apply con.left_inv definition con_eq_idp {p : x = y} {q : y = x} (r : p = q⁻¹) : p ⬝ q = idp := by cases q; exact r definition idp_eq_inv_con {p q : x = y} (r : p = q) : idp = p⁻¹ ⬝ q := by cases r; exact !con.left_inv⁻¹ definition idp_eq_con_inv {p q : x = y} (r : p = q) : idp = q ⬝ p⁻¹ := by cases r; exact !con.right_inv⁻¹ definition idp_eq_con {p : x = y} {q : y = x} (r : p⁻¹ = q) : idp = q ⬝ p := by cases p; exact r definition eq_idp_of_con_right {p : x = x} {q : x = y} (r : p ⬝ q = q) : p = idp := by cases q; exact r definition eq_idp_of_con_left {p : x = x} {q : y = x} (r : q ⬝ p = q) : p = idp := by cases q; exact (idp_con p)⁻¹ ⬝ r definition idp_eq_of_con_right {p : x = x} {q : x = y} (r : q = p ⬝ q) : idp = p := by cases q; exact r definition idp_eq_of_con_left {p : x = x} {q : y = x} (r : q = q ⬝ p) : idp = p := by cases q; exact r ⬝ idp_con p /- Transport -/ definition transport [subst] [reducible] [unfold 5] (P : A → Type) {x y : A} (p : x = y) (u : P x) : P y := by induction p; exact u -- This idiom makes the operation right associative. infixr ` ▸ ` := transport _ definition cast [reducible] [unfold 3] {A B : Type} (p : A = B) (a : A) : B := p ▸ a definition cast_def [reducible] [unfold_full] {A B : Type} (p : A = B) (a : A) : cast p a = p ▸ a := idp definition tr_rev [reducible] [unfold 6] (P : A → Type) {x y : A} (p : x = y) (u : P y) : P x := p⁻¹ ▸ u definition ap [unfold 6] ⦃A B : Type⦄ (f : A → B) {x y:A} (p : x = y) : f x = f y := by induction p; reflexivity abbreviation ap01 [parsing_only] := ap definition homotopy [reducible] (f g : Πx, P x) : Type := Πx : A, f x = g x infix ~ := homotopy protected definition homotopy.refl [refl] [reducible] [unfold_full] (f : Πx, P x) : f ~ f := λ x, idp protected definition homotopy.symm [symm] [reducible] [unfold_full] {f g : Πx, P x} (H : f ~ g) : g ~ f := λ x, (H x)⁻¹ protected definition homotopy.trans [trans] [reducible] [unfold_full] {f g h : Πx, P x} (H1 : f ~ g) (H2 : g ~ h) : f ~ h := λ x, H1 x ⬝ H2 x definition homotopy_of_eq {f g : Πx, P x} (H1 : f = g) : f ~ g := H1 ▸ homotopy.refl f definition apd10 [unfold 5] {f g : Πx, P x} (H : f = g) : f ~ g := λx, by induction H; reflexivity --the next theorem is useful if you want to write "apply (apd10' a)" definition apd10' [unfold 6] {f g : Πx, P x} (a : A) (H : f = g) : f a = g a := by induction H; reflexivity --apd10 is also ap evaluation definition apd10_eq_ap_eval {f g : Πx, P x} (H : f = g) (a : A) : apd10 H a = ap (λs : Πx, P x, s a) H := by induction H; reflexivity definition ap10 [reducible] [unfold 5] {f g : A → B} (H : f = g) : f ~ g := apd10 H definition ap11 {f g : A → B} (H : f = g) {x y : A} (p : x = y) : f x = g y := by induction H; exact ap f p definition apd [unfold 6] (f : Πa, P a) {x y : A} (p : x = y) : p ▸ f x = f y := by induction p; reflexivity definition ap011 [unfold 9] (f : A → B → C) (Ha : a = a') (Hb : b = b') : f a b = f a' b' := by cases Ha; exact ap (f a) Hb /- More theorems for moving things around in equations -/ definition tr_eq_of_eq_inv_tr {P : A → Type} {x y : A} {p : x = y} {u : P x} {v : P y} : u = p⁻¹ ▸ v → p ▸ u = v := by induction p; exact id definition inv_tr_eq_of_eq_tr {P : A → Type} {x y : A} {p : y = x} {u : P x} {v : P y} : u = p ▸ v → p⁻¹ ▸ u = v := by induction p; exact id definition eq_inv_tr_of_tr_eq {P : A → Type} {x y : A} {p : x = y} {u : P x} {v : P y} : p ▸ u = v → u = p⁻¹ ▸ v := by induction p; exact id definition eq_tr_of_inv_tr_eq {P : A → Type} {x y : A} {p : y = x} {u : P x} {v : P y} : p⁻¹ ▸ u = v → u = p ▸ v := by induction p; exact id /- Functoriality of functions -/ -- Here we prove that functions behave like functors between groupoids, and that [ap] itself is -- functorial. -- Functions take identity paths to identity paths definition ap_idp [unfold_full] (x : A) (f : A → B) : ap f idp = idp :> (f x = f x) := idp -- Functions commute with concatenation. definition ap_con [unfold 8] (f : A → B) {x y z : A} (p : x = y) (q : y = z) : ap f (p ⬝ q) = ap f p ⬝ ap f q := by induction q; reflexivity definition con_ap_con_eq_con_ap_con_ap (f : A → B) {w x y z : A} (r : f w = f x) (p : x = y) (q : y = z) : r ⬝ ap f (p ⬝ q) = (r ⬝ ap f p) ⬝ ap f q := by induction q; induction p; reflexivity definition ap_con_con_eq_ap_con_ap_con (f : A → B) {w x y z : A} (p : x = y) (q : y = z) (r : f z = f w) : ap f (p ⬝ q) ⬝ r = ap f p ⬝ (ap f q ⬝ r) := by induction q; induction p; apply con.assoc -- Functions commute with path inverses. definition ap_inv' [unfold 6] (f : A → B) {x y : A} (p : x = y) : (ap f p)⁻¹ = ap f p⁻¹ := by induction p; reflexivity definition ap_inv [unfold 6] (f : A → B) {x y : A} (p : x = y) : ap f p⁻¹ = (ap f p)⁻¹ := by induction p; reflexivity -- [ap] itself is functorial in the first argument. definition ap_id [unfold 4] (p : x = y) : ap id p = p := by induction p; reflexivity definition ap_compose [unfold 8] (g : B → C) (f : A → B) {x y : A} (p : x = y) : ap (g ∘ f) p = ap g (ap f p) := by induction p; reflexivity -- Sometimes we don't have the actual function [compose]. definition ap_compose' [unfold 8] (g : B → C) (f : A → B) {x y : A} (p : x = y) : ap (λa, g (f a)) p = ap g (ap f p) := by induction p; reflexivity -- The action of constant maps. definition ap_constant [unfold 5] (p : x = y) (z : B) : ap (λu, z) p = idp := by induction p; reflexivity -- Naturality of [ap]. -- see also natural_square in cubical.square definition ap_con_eq_con_ap {f g : A → B} (p : f ~ g) {x y : A} (q : x = y) : ap f q ⬝ p y = p x ⬝ ap g q := by induction q; apply idp_con -- Naturality of [ap] at identity. definition ap_con_eq_con {f : A → A} (p : Πx, f x = x) {x y : A} (q : x = y) : ap f q ⬝ p y = p x ⬝ q := by induction q; apply idp_con definition con_ap_eq_con {f : A → A} (p : Πx, x = f x) {x y : A} (q : x = y) : p x ⬝ ap f q = q ⬝ p y := by induction q; exact !idp_con⁻¹ -- Naturality of [ap] with constant function definition ap_con_eq {f : A → B} {b : B} (p : Πx, f x = b) {x y : A} (q : x = y) : ap f q ⬝ p y = p x := by induction q; apply idp_con -- Naturality with other paths hanging around. definition con_ap_con_con_eq_con_con_ap_con {f g : A → B} (p : f ~ g) {x y : A} (q : x = y) {w z : B} (r : w = f x) (s : g y = z) : (r ⬝ ap f q) ⬝ (p y ⬝ s) = (r ⬝ p x) ⬝ (ap g q ⬝ s) := by induction s; induction q; reflexivity definition con_ap_con_eq_con_con_ap {f g : A → B} (p : f ~ g) {x y : A} (q : x = y) {w : B} (r : w = f x) : (r ⬝ ap f q) ⬝ p y = (r ⬝ p x) ⬝ ap g q := by induction q; reflexivity -- TODO: try this using the simplifier, and compare proofs definition ap_con_con_eq_con_ap_con {f g : A → B} (p : f ~ g) {x y : A} (q : x = y) {z : B} (s : g y = z) : ap f q ⬝ (p y ⬝ s) = p x ⬝ (ap g q ⬝ s) := begin induction s, induction q, apply idp_con end definition con_ap_con_con_eq_con_con_con {f : A → A} (p : f ~ id) {x y : A} (q : x = y) {w z : A} (r : w = f x) (s : y = z) : (r ⬝ ap f q) ⬝ (p y ⬝ s) = (r ⬝ p x) ⬝ (q ⬝ s) := by induction s; induction q; reflexivity definition con_con_ap_con_eq_con_con_con {g : A → A} (p : id ~ g) {x y : A} (q : x = y) {w z : A} (r : w = x) (s : g y = z) : (r ⬝ p x) ⬝ (ap g q ⬝ s) = (r ⬝ q) ⬝ (p y ⬝ s) := by induction s; induction q; reflexivity definition con_ap_con_eq_con_con {f : A → A} (p : f ~ id) {x y : A} (q : x = y) {w : A} (r : w = f x) : (r ⬝ ap f q) ⬝ p y = (r ⬝ p x) ⬝ q := by induction q; reflexivity definition ap_con_con_eq_con_con {f : A → A} (p : f ~ id) {x y : A} (q : x = y) {z : A} (s : y = z) : ap f q ⬝ (p y ⬝ s) = p x ⬝ (q ⬝ s) := by induction s; induction q; apply idp_con definition con_con_ap_eq_con_con {g : A → A} (p : id ~ g) {x y : A} (q : x = y) {w : A} (r : w = x) : (r ⬝ p x) ⬝ ap g q = (r ⬝ q) ⬝ p y := begin cases q, exact idp end definition con_ap_con_eq_con_con' {g : A → A} (p : id ~ g) {x y : A} (q : x = y) {z : A} (s : g y = z) : p x ⬝ (ap g q ⬝ s) = q ⬝ (p y ⬝ s) := by induction s; induction q; exact !idp_con⁻¹ /- Action of [apd10] and [ap10] on paths -/ -- Application of paths between functions preserves the groupoid structure definition apd10_idp (f : Πx, P x) (x : A) : apd10 (refl f) x = idp := idp definition apd10_con {f f' f'' : Πx, P x} (h : f = f') (h' : f' = f'') (x : A) : apd10 (h ⬝ h') x = apd10 h x ⬝ apd10 h' x := by induction h; induction h'; reflexivity definition apd10_inv {f g : Πx : A, P x} (h : f = g) (x : A) : apd10 h⁻¹ x = (apd10 h x)⁻¹ := by induction h; reflexivity definition ap10_idp {f : A → B} (x : A) : ap10 (refl f) x = idp := idp definition ap10_con {f f' f'' : A → B} (h : f = f') (h' : f' = f'') (x : A) : ap10 (h ⬝ h') x = ap10 h x ⬝ ap10 h' x := apd10_con h h' x definition ap10_inv {f g : A → B} (h : f = g) (x : A) : ap10 h⁻¹ x = (ap10 h x)⁻¹ := apd10_inv h x -- [ap10] also behaves nicely on paths produced by [ap] definition ap_ap10 (f g : A → B) (h : B → C) (p : f = g) (a : A) : ap h (ap10 p a) = ap10 (ap (λ f', h ∘ f') p) a:= by induction p; reflexivity /- Transport and the groupoid structure of paths -/ definition idp_tr {P : A → Type} {x : A} (u : P x) : idp ▸ u = u := idp definition con_tr [unfold 7] {P : A → Type} {x y z : A} (p : x = y) (q : y = z) (u : P x) : p ⬝ q ▸ u = q ▸ p ▸ u := by induction q; reflexivity definition tr_inv_tr {P : A → Type} {x y : A} (p : x = y) (z : P y) : p ▸ p⁻¹ ▸ z = z := (con_tr p⁻¹ p z)⁻¹ ⬝ ap (λr, transport P r z) (con.left_inv p) definition inv_tr_tr {P : A → Type} {x y : A} (p : x = y) (z : P x) : p⁻¹ ▸ p ▸ z = z := (con_tr p p⁻¹ z)⁻¹ ⬝ ap (λr, transport P r z) (con.right_inv p) definition con_tr_lemma {P : A → Type} {x y z w : A} (p : x = y) (q : y = z) (r : z = w) (u : P x) : ap (λe, e ▸ u) (con.assoc' p q r) ⬝ (con_tr (p ⬝ q) r u) ⬝ ap (transport P r) (con_tr p q u) = (con_tr p (q ⬝ r) u) ⬝ (con_tr q r (p ▸ u)) :> ((p ⬝ (q ⬝ r)) ▸ u = r ▸ q ▸ p ▸ u) := by induction r; induction q; induction p; reflexivity -- Here is another coherence lemma for transport. definition tr_inv_tr_lemma {P : A → Type} {x y : A} (p : x = y) (z : P x) : tr_inv_tr p (transport P p z) = ap (transport P p) (inv_tr_tr p z) := by induction p; reflexivity /- some properties for apd -/ definition apd_idp (x : A) (f : Πx, P x) : apd f idp = idp :> (f x = f x) := idp definition apd_con (f : Πx, P x) {x y z : A} (p : x = y) (q : y = z) : apd f (p ⬝ q) = con_tr p q (f x) ⬝ ap (transport P q) (apd f p) ⬝ apd f q := by cases p; cases q; apply idp definition apd_inv (f : Πx, P x) {x y : A} (p : x = y) : apd f p⁻¹ = (eq_inv_tr_of_tr_eq (apd f p))⁻¹ := by cases p; apply idp -- Dependent transport in a doubly dependent type. definition transportD [unfold 6] {P : A → Type} (Q : Πa, P a → Type) {a a' : A} (p : a = a') (b : P a) (z : Q a b) : Q a' (p ▸ b) := by induction p; exact z -- In Coq the variables P, Q and b are explicit, but in Lean we can probably have them implicit -- using the following notation notation p ` ▸D `:65 x:64 := transportD _ p _ x -- Transporting along higher-dimensional paths definition transport2 [unfold 7] (P : A → Type) {x y : A} {p q : x = y} (r : p = q) (z : P x) : p ▸ z = q ▸ z := ap (λp', p' ▸ z) r notation p ` ▸2 `:65 x:64 := transport2 _ p _ x -- An alternative definition. definition tr2_eq_ap10 (Q : A → Type) {x y : A} {p q : x = y} (r : p = q) (z : Q x) : transport2 Q r z = ap10 (ap (transport Q) r) z := by induction r; reflexivity definition tr2_con {P : A → Type} {x y : A} {p1 p2 p3 : x = y} (r1 : p1 = p2) (r2 : p2 = p3) (z : P x) : transport2 P (r1 ⬝ r2) z = transport2 P r1 z ⬝ transport2 P r2 z := by induction r1; induction r2; reflexivity definition tr2_inv (Q : A → Type) {x y : A} {p q : x = y} (r : p = q) (z : Q x) : transport2 Q r⁻¹ z = (transport2 Q r z)⁻¹ := by induction r; reflexivity definition transportD2 [unfold 7] {B C : A → Type} (D : Π(a:A), B a → C a → Type) {x1 x2 : A} (p : x1 = x2) (y : B x1) (z : C x1) (w : D x1 y z) : D x2 (p ▸ y) (p ▸ z) := by induction p; exact w notation p ` ▸D2 `:65 x:64 := transportD2 _ p _ _ x definition ap_tr_con_tr2 (P : A → Type) {x y : A} {p q : x = y} {z w : P x} (r : p = q) (s : z = w) : ap (transport P p) s ⬝ transport2 P r w = transport2 P r z ⬝ ap (transport P q) s := by induction r; exact !idp_con⁻¹ definition fn_tr_eq_tr_fn {P Q : A → Type} {x y : A} (p : x = y) (f : Πx, P x → Q x) (z : P x) : f y (p ▸ z) = p ▸ f x z := by induction p; reflexivity /- Transporting in particular fibrations -/ /- From the Coq HoTT library: One frequently needs lemmas showing that transport in a certain dependent type is equal to some more explicitly defined operation, defined according to the structure of that dependent type. For most dependent types, we prove these lemmas in the appropriate file in the types/ subdirectory. Here we consider only the most basic cases. -/ -- Transporting in a constant fibration. definition tr_constant (p : x = y) (z : B) : transport (λx, B) p z = z := by induction p; reflexivity definition tr2_constant {p q : x = y} (r : p = q) (z : B) : tr_constant p z = transport2 (λu, B) r z ⬝ tr_constant q z := by induction r; exact !idp_con⁻¹ -- Transporting in a pulled back fibration. definition tr_compose (P : B → Type) (f : A → B) (p : x = y) (z : P (f x)) : transport (P ∘ f) p z = transport P (ap f p) z := by induction p; reflexivity definition ap_precompose (f : A → B) (g g' : B → C) (p : g = g') : ap (λh, h ∘ f) p = transport (λh : B → C, g ∘ f = h ∘ f) p idp := by induction p; reflexivity definition apd10_ap_precompose (f : A → B) (g g' : B → C) (p : g = g') : apd10 (ap (λh : B → C, h ∘ f) p) = λa, apd10 p (f a) := by induction p; reflexivity definition apd10_ap_precompose_dependent {C : B → Type} (f : A → B) {g g' : Πb : B, C b} (p : g = g') : apd10 (ap (λ(h : (Πb : B, C b))(a : A), h (f a)) p) = λa, apd10 p (f a) := by induction p; reflexivity definition apd10_ap_postcompose (f : B → C) (g g' : A → B) (p : g = g') : apd10 (ap (λh : A → B, f ∘ h) p) = λa, ap f (apd10 p a) := by induction p; reflexivity -- A special case of [tr_compose] which seems to come up a lot. definition tr_eq_cast_ap {P : A → Type} {x y} (p : x = y) (u : P x) : p ▸ u = cast (ap P p) u := by induction p; reflexivity definition tr_eq_cast_ap_fn {P : A → Type} {x y} (p : x = y) : transport P p = cast (ap P p) := by induction p; reflexivity /- The behavior of [ap] and [apd] -/ -- In a constant fibration, [apd] reduces to [ap], modulo [transport_const]. definition apd_eq_tr_constant_con_ap (f : A → B) (p : x = y) : apd f p = tr_constant p (f x) ⬝ ap f p := by induction p; reflexivity /- The 2-dimensional groupoid structure -/ -- Horizontal composition of 2-dimensional paths. definition concat2 [unfold 9 10] {p p' : x = y} {q q' : y = z} (h : p = p') (h' : q = q') : p ⬝ q = p' ⬝ q' := ap011 concat h h' -- 2-dimensional path inversion definition inverse2 [unfold 6] {p q : x = y} (h : p = q) : p⁻¹ = q⁻¹ := ap inverse h infixl ` ◾ `:75 := concat2 postfix [parsing_only] `⁻²`:(max+10) := inverse2 --this notation is abusive, should we use it? /- Whiskering -/ definition whisker_left [unfold 8] (p : x = y) {q r : y = z} (h : q = r) : p ⬝ q = p ⬝ r := idp ◾ h definition whisker_right [unfold 7] {p q : x = y} (h : p = q) (r : y = z) : p ⬝ r = q ⬝ r := h ◾ idp -- Unwhiskering, a.k.a. cancelling definition cancel_left {x y z : A} (p : x = y) {q r : y = z} : (p ⬝ q = p ⬝ r) → (q = r) := λs, !inv_con_cancel_left⁻¹ ⬝ whisker_left p⁻¹ s ⬝ !inv_con_cancel_left definition cancel_right {x y z : A} {p q : x = y} (r : y = z) : (p ⬝ r = q ⬝ r) → (p = q) := λs, !con_inv_cancel_right⁻¹ ⬝ whisker_right s r⁻¹ ⬝ !con_inv_cancel_right -- Whiskering and identity paths. definition whisker_right_idp {p q : x = y} (h : p = q) : whisker_right h idp = h := by induction h; induction p; reflexivity definition whisker_right_idp_left [unfold_full] (p : x = y) (q : y = z) : whisker_right idp q = idp :> (p ⬝ q = p ⬝ q) := idp definition whisker_left_idp_right [unfold_full] (p : x = y) (q : y = z) : whisker_left p idp = idp :> (p ⬝ q = p ⬝ q) := idp definition whisker_left_idp {p q : x = y} (h : p = q) : (idp_con p)⁻¹ ⬝ whisker_left idp h ⬝ idp_con q = h := by induction h; induction p; reflexivity definition whisker_left_idp2 {A : Type} {a : A} (p : idp = idp :> a = a) : whisker_left idp p = p := begin refine _ ⬝ whisker_left_idp p, exact !idp_con⁻¹ end definition con2_idp [unfold_full] {p q : x = y} (h : p = q) : h ◾ idp = whisker_right h idp :> (p ⬝ idp = q ⬝ idp) := idp definition idp_con2 [unfold_full] {p q : x = y} (h : p = q) : idp ◾ h = whisker_left idp h :> (idp ⬝ p = idp ⬝ q) := idp definition inverse2_concat2 {p p' : x = y} (h : p = p') : h⁻² ◾ h = con.left_inv p ⬝ (con.left_inv p')⁻¹ := by induction h; induction p; reflexivity -- The interchange law for concatenation. definition con2_con_con2 {p p' p'' : x = y} {q q' q'' : y = z} (a : p = p') (b : p' = p'') (c : q = q') (d : q' = q'') : (a ◾ c) ⬝ (b ◾ d) = (a ⬝ b) ◾ (c ⬝ d) := by induction d; induction c; induction b;induction a; reflexivity definition concat2_eq_rl {A : Type} {x y z : A} {p p' : x = y} {q q' : y = z} (a : p = p') (b : q = q') : a ◾ b = whisker_right a q ⬝ whisker_left p' b := by induction b; induction a; reflexivity definition concat2_eq_lf {A : Type} {x y z : A} {p p' : x = y} {q q' : y = z} (a : p = p') (b : q = q') : a ◾ b = whisker_left p b ⬝ whisker_right a q' := by induction b; induction a; reflexivity definition whisker_right_con_whisker_left {x y z : A} {p p' : x = y} {q q' : y = z} (a : p = p') (b : q = q') : (whisker_right a q) ⬝ (whisker_left p' b) = (whisker_left p b) ⬝ (whisker_right a q') := by induction b; induction a; reflexivity -- Structure corresponding to the coherence equations of a bicategory. -- The "pentagonator": the 3-cell witnessing the associativity pentagon. definition pentagon {v w x y z : A} (p : v = w) (q : w = x) (r : x = y) (s : y = z) : whisker_left p (con.assoc' q r s) ⬝ con.assoc' p (q ⬝ r) s ⬝ whisker_right (con.assoc' p q r) s = con.assoc' p q (r ⬝ s) ⬝ con.assoc' (p ⬝ q) r s := by induction s;induction r;induction q;induction p;reflexivity -- The 3-cell witnessing the left unit triangle. definition triangulator (p : x = y) (q : y = z) : con.assoc' p idp q ⬝ whisker_right (con_idp p) q = whisker_left p (idp_con q) := by induction q; induction p; reflexivity definition eckmann_hilton {x:A} (p q : idp = idp :> x = x) : p ⬝ q = q ⬝ p := begin refine (whisker_right_idp p ◾ whisker_left_idp2 q)⁻¹ ⬝ _, refine !whisker_right_con_whisker_left ⬝ _, refine !whisker_left_idp2 ◾ !whisker_right_idp end definition concat_eq_concat2 {A : Type} {a : A} (p q : idp = idp :> a = a) : p ⬝ q = p ◾ q := begin refine (whisker_right_idp p ◾ whisker_left_idp2 q)⁻¹ ⬝ _, exact !concat2_eq_rl⁻¹ end definition inverse_eq_inverse2 {A : Type} {a : A} (p : idp = idp :> a = a) : p⁻¹ = p⁻² := begin apply eq.cancel_right p, refine !con.left_inv ⬝ _, refine _ ⬝ !concat_eq_concat2⁻¹, exact !inverse2_concat2⁻¹, end -- The action of functions on 2-dimensional paths definition ap02 [unfold 8] [reducible] (f : A → B) {x y : A} {p q : x = y} (r : p = q) : ap f p = ap f q := ap (ap f) r definition ap02_con (f : A → B) {x y : A} {p p' p'' : x = y} (r : p = p') (r' : p' = p'') : ap02 f (r ⬝ r') = ap02 f r ⬝ ap02 f r' := by induction r; induction r'; reflexivity definition ap02_con2 (f : A → B) {x y z : A} {p p' : x = y} {q q' :y = z} (r : p = p') (s : q = q') : ap02 f (r ◾ s) = ap_con f p q ⬝ (ap02 f r ◾ ap02 f s) ⬝ (ap_con f p' q')⁻¹ := by induction r; induction s; induction q; induction p; reflexivity definition apd02 [unfold 8] {p q : x = y} (f : Π x, P x) (r : p = q) : apd f p = transport2 P r (f x) ⬝ apd f q := by induction r; exact !idp_con⁻¹ -- And now for a lemma whose statement is much longer than its proof. definition apd02_con {P : A → Type} (f : Π x:A, P x) {x y : A} {p1 p2 p3 : x = y} (r1 : p1 = p2) (r2 : p2 = p3) : apd02 f (r1 ⬝ r2) = apd02 f r1 ⬝ whisker_left (transport2 P r1 (f x)) (apd02 f r2) ⬝ con.assoc' _ _ _ ⬝ (whisker_right (tr2_con r1 r2 (f x))⁻¹ (apd f p3)) := by induction r2; induction r1; induction p1; reflexivity end eq
0d4a20e42cdd3f665984585ed12929d1afdc46c3
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/analysis/special_functions/pow.lean
f523eb18d6da0101038682fad9bc2ed2b5262bc5
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
48,285
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Sébastien Gouëzel -/ import analysis.special_functions.trigonometric import analysis.calculus.extend_deriv /-! # Power function on `ℂ`, `ℝ` and `ℝ⁺` We construct the power functions `x ^ y` where `x` and `y` are complex numbers, or `x` and `y` are real numbers, or `x` is a nonnegative real and `y` is real, and prove their basic properties. -/ noncomputable theory open_locale classical real topological_space nnreal namespace complex /-- The complex power function `x^y`, given by `x^y = exp(y log x)` (where `log` is the principal determination of the logarithm), unless `x = 0` where one sets `0^0 = 1` and `0^y = 0` for `y ≠ 0`. -/ noncomputable def cpow (x y : ℂ) : ℂ := if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) noncomputable instance : has_pow ℂ ℂ := ⟨cpow⟩ @[simp] lemma cpow_eq_pow (x y : ℂ) : cpow x y = x ^ y := rfl lemma cpow_def (x y : ℂ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := rfl @[simp] lemma cpow_zero (x : ℂ) : x ^ (0 : ℂ) = 1 := by simp [cpow_def] @[simp] lemma cpow_eq_zero_iff (x y : ℂ) : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := by { simp only [cpow_def], split_ifs; simp [*, exp_ne_zero] } @[simp] lemma zero_cpow {x : ℂ} (h : x ≠ 0) : (0 : ℂ) ^ x = 0 := by simp [cpow_def, *] @[simp] lemma cpow_one (x : ℂ) : x ^ (1 : ℂ) = x := if hx : x = 0 then by simp [hx, cpow_def] else by rw [cpow_def, if_neg (one_ne_zero : (1 : ℂ) ≠ 0), if_neg hx, mul_one, exp_log hx] @[simp] lemma one_cpow (x : ℂ) : (1 : ℂ) ^ x = 1 := by rw cpow_def; split_ifs; simp [one_ne_zero, *] at * lemma cpow_add {x : ℂ} (y z : ℂ) (hx : x ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := by simp [cpow_def]; split_ifs; simp [*, exp_add, mul_add] at * lemma cpow_mul {x y : ℂ} (z : ℂ) (h₁ : -π < (log x * y).im) (h₂ : (log x * y).im ≤ π) : x ^ (y * z) = (x ^ y) ^ z := begin simp [cpow_def], split_ifs; simp [*, exp_ne_zero, log_exp h₁ h₂, mul_assoc] at * end lemma cpow_neg (x y : ℂ) : x ^ -y = (x ^ y)⁻¹ := by simp [cpow_def]; split_ifs; simp [exp_neg] lemma cpow_neg_one (x : ℂ) : x ^ (-1 : ℂ) = x⁻¹ := by simpa using cpow_neg x 1 @[simp] lemma cpow_nat_cast (x : ℂ) : ∀ (n : ℕ), x ^ (n : ℂ) = x ^ n | 0 := by simp | (n + 1) := if hx : x = 0 then by simp only [hx, pow_succ, complex.zero_cpow (nat.cast_ne_zero.2 (nat.succ_ne_zero _)), zero_mul] else by simp [cpow_add, hx, pow_add, cpow_nat_cast n] @[simp] lemma cpow_int_cast (x : ℂ) : ∀ (n : ℤ), x ^ (n : ℂ) = x ^ n | (n : ℕ) := by simp; refl | -[1+ n] := by rw fpow_neg_succ_of_nat; simp only [int.neg_succ_of_nat_coe, int.cast_neg, complex.cpow_neg, inv_eq_one_div, int.cast_coe_nat, cpow_nat_cast] lemma cpow_nat_inv_pow (x : ℂ) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℂ)) ^ n = x := have (log x * (↑n)⁻¹).im = (log x).im / n, by rw [div_eq_mul_inv, ← of_real_nat_cast, ← of_real_inv, mul_im, of_real_re, of_real_im]; simp, have h : -π < (log x * (↑n)⁻¹).im ∧ (log x * (↑n)⁻¹).im ≤ π, from (le_total (log x).im 0).elim (λ h, ⟨calc -π < (log x).im : by simp [log, neg_pi_lt_arg] ... ≤ ((log x).im * 1) / n : le_div_of_mul_le (nat.cast_pos.2 hn) (mul_le_mul_of_nonpos_left (by rw ← nat.cast_one; exact nat.cast_le.2 hn) h) ... = (log x * (↑n)⁻¹).im : by simp [this], this.symm ▸ le_trans (div_nonpos_of_nonpos_of_pos h (nat.cast_pos.2 hn)) (le_of_lt real.pi_pos)⟩) (λ h, ⟨this.symm ▸ lt_of_lt_of_le (neg_neg_of_pos real.pi_pos) (div_nonneg h (nat.cast_pos.2 hn)), calc (log x * (↑n)⁻¹).im = (1 * (log x).im) / n : by simp [this] ... ≤ (log x).im : (div_le_of_le_mul (nat.cast_pos.2 hn) (mul_le_mul_of_nonneg_right (by rw ← nat.cast_one; exact nat.cast_le.2 hn) h)) ... ≤ _ : by simp [log, arg_le_pi]⟩), by rw [← cpow_nat_cast, ← cpow_mul _ h.1 h.2, inv_mul_cancel (show (n : ℂ) ≠ 0, from nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 hn)), cpow_one] end complex namespace real /-- The real power function `x^y`, defined as the real part of the complex power function. For `x > 0`, it is equal to `exp(y log x)`. For `x = 0`, one sets `0^0=1` and `0^y=0` for `y ≠ 0`. For `x < 0`, the definition is somewhat arbitary as it depends on the choice of a complex determination of the logarithm. With our conventions, it is equal to `exp (y log x) cos (πy)`. -/ noncomputable def rpow (x y : ℝ) := ((x : ℂ) ^ (y : ℂ)).re noncomputable instance : has_pow ℝ ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x y : ℝ) : rpow x y = x ^ y := rfl lemma rpow_def (x y : ℝ) : x ^ y = ((x : ℂ) ^ (y : ℂ)).re := rfl lemma rpow_def_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := by simp only [rpow_def, complex.cpow_def]; split_ifs; simp [*, (complex.of_real_log hx).symm, -complex.of_real_mul, (complex.of_real_mul _ _).symm, complex.exp_of_real_re] at * lemma rpow_def_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : x ^ y = exp (log x * y) := by rw [rpow_def_of_nonneg (le_of_lt hx), if_neg (ne_of_gt hx)] lemma rpow_eq_zero_iff_of_nonneg {x y : ℝ} (hx : 0 ≤ x) : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := by { simp only [rpow_def_of_nonneg hx], split_ifs; simp [*, exp_ne_zero] } open_locale real lemma rpow_def_of_neg {x : ℝ} (hx : x < 0) (y : ℝ) : x ^ y = exp (log x * y) * cos (y * π) := begin rw [rpow_def, complex.cpow_def, if_neg], have : complex.log x * y = ↑(log(-x) * y) + ↑(y * π) * complex.I, simp only [complex.log, abs_of_neg hx, complex.arg_of_real_of_neg hx, complex.abs_of_real, complex.of_real_mul], ring, { rw [this, complex.exp_add_mul_I, ← complex.of_real_exp, ← complex.of_real_cos, ← complex.of_real_sin, mul_add, ← complex.of_real_mul, ← mul_assoc, ← complex.of_real_mul, complex.add_re, complex.of_real_re, complex.mul_re, complex.I_re, complex.of_real_im, real.log_neg_eq_log], ring }, { rw complex.of_real_eq_zero, exact ne_of_lt hx } end lemma rpow_def_of_nonpos {x : ℝ} (hx : x ≤ 0) (y : ℝ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) * cos (y * π) := by split_ifs; simp [rpow_def, *]; exact rpow_def_of_neg (lt_of_le_of_ne hx h) _ lemma rpow_pos_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : 0 < x ^ y := by rw rpow_def_of_pos hx; apply exp_pos lemma abs_rpow_le_abs_rpow (x y : ℝ) : abs (x ^ y) ≤ abs (x) ^ y := abs_le_of_le_of_neg_le begin cases lt_trichotomy 0 x, { rw abs_of_pos h }, cases h, { simp [h.symm] }, rw [rpow_def_of_neg h, rpow_def_of_pos (abs_pos_of_neg h), log_abs], calc exp (log x * y) * cos (y * π) ≤ exp (log x * y) * 1 : mul_le_mul_of_nonneg_left (cos_le_one _) (le_of_lt $ exp_pos _) ... = _ : mul_one _ end begin cases lt_trichotomy 0 x, { rw abs_of_pos h, have : 0 < x^y := rpow_pos_of_pos h _, linarith }, cases h, { simp only [h.symm, abs_zero, rpow_def_of_nonneg], split_ifs, repeat {norm_num} }, rw [rpow_def_of_neg h, rpow_def_of_pos (abs_pos_of_neg h), log_abs], calc -(exp (log x * y) * cos (y * π)) = exp (log x * y) * (-cos (y * π)) : by ring ... ≤ exp (log x * y) * 1 : mul_le_mul_of_nonneg_left (neg_le.2 $ neg_one_le_cos _) (le_of_lt $ exp_pos _) ... = exp (log x * y) : mul_one _ end end real namespace complex lemma of_real_cpow {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : ((x ^ y : ℝ) : ℂ) = (x : ℂ) ^ (y : ℂ) := by simp [real.rpow_def_of_nonneg hx, complex.cpow_def]; split_ifs; simp [complex.of_real_log hx] @[simp] lemma abs_cpow_real (x : ℂ) (y : ℝ) : abs (x ^ (y : ℂ)) = x.abs ^ y := begin rw [real.rpow_def_of_nonneg (abs_nonneg _), complex.cpow_def], split_ifs; simp [*, abs_of_nonneg (le_of_lt (real.exp_pos _)), complex.log, complex.exp_add, add_mul, mul_right_comm _ I, exp_mul_I, abs_cos_add_sin_mul_I, (complex.of_real_mul _ _).symm, -complex.of_real_mul] at * end @[simp] lemma abs_cpow_inv_nat (x : ℂ) (n : ℕ) : abs (x ^ (n⁻¹ : ℂ)) = x.abs ^ (n⁻¹ : ℝ) := by rw ← abs_cpow_real; simp [-abs_cpow_real] end complex namespace real variables {x y z : ℝ} @[simp] lemma rpow_zero (x : ℝ) : x ^ (0 : ℝ) = 1 := by simp [rpow_def] @[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : ℝ) ^ x = 0 := by simp [rpow_def, *] @[simp] lemma rpow_one (x : ℝ) : x ^ (1 : ℝ) = x := by simp [rpow_def] @[simp] lemma one_rpow (x : ℝ) : (1 : ℝ) ^ x = 1 := by simp [rpow_def] lemma zero_rpow_le_one (x : ℝ) : (0 : ℝ) ^ x ≤ 1 := by { by_cases h : x = 0; simp [h, zero_le_one] } lemma zero_rpow_nonneg (x : ℝ) : 0 ≤ (0 : ℝ) ^ x := by { by_cases h : x = 0; simp [h, zero_le_one] } lemma rpow_nonneg_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : 0 ≤ x ^ y := by rw [rpow_def_of_nonneg hx]; split_ifs; simp only [zero_le_one, le_refl, le_of_lt (exp_pos _)] lemma rpow_add {x : ℝ} (hx : 0 < x) (y z : ℝ) : x ^ (y + z) = x ^ y * x ^ z := by simp only [rpow_def_of_pos hx, mul_add, exp_add] lemma rpow_add' {x : ℝ} (hx : 0 ≤ x) {y z : ℝ} (h : y + z ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := begin rcases le_iff_eq_or_lt.1 hx with H|pos, { simp only [← H, h, rpow_eq_zero_iff_of_nonneg, true_and, zero_rpow, eq_self_iff_true, ne.def, not_false_iff, zero_eq_mul], by_contradiction F, push_neg at F, apply h, simp [F] }, { exact rpow_add pos _ _ } end /-- For `0 ≤ x`, the only problematic case in the equality `x ^ y * x ^ z = x ^ (y + z)` is for `x = 0` and `y + z = 0`, where the right hand side is `1` while the left hand side can vanish. The inequality is always true, though, and given in this lemma. -/ lemma le_rpow_add {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ y * x ^ z ≤ x ^ (y + z) := begin rcases le_iff_eq_or_lt.1 hx with H|pos, { by_cases h : y + z = 0, { simp only [H.symm, h, rpow_zero], calc (0 : ℝ) ^ y * 0 ^ z ≤ 1 * 1 : mul_le_mul (zero_rpow_le_one y) (zero_rpow_le_one z) (zero_rpow_nonneg z) zero_le_one ... = 1 : by simp }, { simp [rpow_add', ← H, h] } }, { simp [rpow_add pos] } end lemma rpow_mul {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := by rw [← complex.of_real_inj, complex.of_real_cpow (rpow_nonneg_of_nonneg hx _), complex.of_real_cpow hx, complex.of_real_mul, complex.cpow_mul, complex.of_real_cpow hx]; simp only [(complex.of_real_mul _ _).symm, (complex.of_real_log hx).symm, complex.of_real_im, neg_lt_zero, pi_pos, le_of_lt pi_pos] lemma rpow_neg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := by simp only [rpow_def_of_nonneg hx]; split_ifs; simp [*, exp_neg] at * lemma rpow_sub {x : ℝ} (hx : 0 < x) (y z : ℝ) : x ^ (y - z) = x ^ y / x ^ z := by simp only [sub_eq_add_neg, rpow_add hx, rpow_neg (le_of_lt hx), div_eq_mul_inv] lemma rpow_sub' {x : ℝ} (hx : 0 ≤ x) {y z : ℝ} (h : y - z ≠ 0) : x ^ (y - z) = x ^ y / x ^ z := by simp only [sub_eq_add_neg, rpow_add' hx h, rpow_neg hx, div_eq_mul_inv] @[simp] lemma rpow_nat_cast (x : ℝ) (n : ℕ) : x ^ (n : ℝ) = x ^ n := by simp only [rpow_def, (complex.of_real_pow _ _).symm, complex.cpow_nat_cast, complex.of_real_nat_cast, complex.of_real_re] @[simp] lemma rpow_int_cast (x : ℝ) (n : ℤ) : x ^ (n : ℝ) = x ^ n := by simp only [rpow_def, (complex.of_real_fpow _ _).symm, complex.cpow_int_cast, complex.of_real_int_cast, complex.of_real_re] lemma rpow_neg_one (x : ℝ) : x ^ (-1 : ℝ) = x⁻¹ := begin suffices H : x ^ ((-1 : ℤ) : ℝ) = x⁻¹, by exact_mod_cast H, simp only [rpow_int_cast, fpow_one, fpow_neg], end lemma mul_rpow {x y z : ℝ} (h : 0 ≤ x) (h₁ : 0 ≤ y) : (x*y)^z = x^z * y^z := begin iterate 3 { rw real.rpow_def_of_nonneg }, split_ifs; simp * at *, { have hx : 0 < x, cases lt_or_eq_of_le h with h₂ h₂, exact h₂, exfalso, apply h_2, exact eq.symm h₂, have hy : 0 < y, cases lt_or_eq_of_le h₁ with h₂ h₂, exact h₂, exfalso, apply h_3, exact eq.symm h₂, rw [log_mul (ne_of_gt hx) (ne_of_gt hy), add_mul, exp_add]}, { exact h₁}, { exact h}, { exact mul_nonneg h h₁}, end lemma inv_rpow (hx : 0 ≤ x) (y : ℝ) : (x⁻¹)^y = (x^y)⁻¹ := begin by_cases hy0 : y = 0, { simp [*] }, by_cases hx0 : x = 0, { simp [*] }, simp only [real.rpow_def_of_nonneg hx, real.rpow_def_of_nonneg (inv_nonneg.2 hx), if_false, hx0, mt inv_eq_zero.1 hx0, log_inv, ← neg_mul_eq_neg_mul, exp_neg] end lemma div_rpow (hx : 0 ≤ x) (hy : 0 ≤ y) (z : ℝ) : (x / y) ^ z = x^z / y^z := by simp only [div_eq_mul_inv, mul_rpow hx (inv_nonneg.2 hy), inv_rpow hy] lemma one_le_rpow (h : 1 ≤ x) (h₁ : 0 ≤ z) : 1 ≤ x^z := begin rw real.rpow_def_of_nonneg, split_ifs with h₂ h₃, { refl}, { simp [*, not_le_of_gt zero_lt_one] at *}, { have hx : 0 < x, exact lt_of_lt_of_le zero_lt_one h, rw [←log_le_log zero_lt_one hx, log_one] at h, have pos : 0 ≤ log x * z, exact mul_nonneg h h₁, rwa [←exp_le_exp, exp_zero] at pos}, { exact le_trans zero_le_one h}, end lemma rpow_lt_rpow (hx : 0 ≤ x) (hxy : x < y) (hz : 0 < z) : x^z < y^z := begin rw le_iff_eq_or_lt at hx, cases hx, { rw [← hx, zero_rpow (ne_of_gt hz)], exact rpow_pos_of_pos (by rwa ← hx at hxy) _ }, rw [rpow_def_of_pos hx, rpow_def_of_pos (lt_trans hx hxy), exp_lt_exp], exact mul_lt_mul_of_pos_right (log_lt_log hx hxy) hz end lemma rpow_le_rpow {x y z: ℝ} (h : 0 ≤ x) (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := begin rcases eq_or_lt_of_le h₁ with rfl|h₁', { refl }, rcases eq_or_lt_of_le h₂ with rfl|h₂', { simp }, exact le_of_lt (rpow_lt_rpow h h₁' h₂') end lemma rpow_lt_rpow_iff (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 < z) : x ^ z < y ^ z ↔ x < y := ⟨lt_imp_lt_of_le_imp_le $ λ h, rpow_le_rpow hy h (le_of_lt hz), λ h, rpow_lt_rpow hx h hz⟩ lemma rpow_le_rpow_iff (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 < z) : x ^ z ≤ y ^ z ↔ x ≤ y := le_iff_le_iff_lt_iff_lt.2 $ rpow_lt_rpow_iff hy hx hz lemma rpow_lt_rpow_of_exponent_lt (hx : 1 < x) (hyz : y < z) : x^y < x^z := begin repeat {rw [rpow_def_of_pos (lt_trans zero_lt_one hx)]}, rw exp_lt_exp, exact mul_lt_mul_of_pos_left hyz (log_pos hx), end lemma rpow_le_rpow_of_exponent_le (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := begin repeat {rw [rpow_def_of_pos (lt_of_lt_of_le zero_lt_one hx)]}, rw exp_le_exp, exact mul_le_mul_of_nonneg_left hyz (log_nonneg hx), end lemma rpow_lt_rpow_of_exponent_gt (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := begin repeat {rw [rpow_def_of_pos hx0]}, rw exp_lt_exp, exact mul_lt_mul_of_neg_left hyz (log_neg hx0 hx1), end lemma rpow_le_rpow_of_exponent_ge (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := begin repeat {rw [rpow_def_of_pos hx0]}, rw exp_le_exp, exact mul_le_mul_of_nonpos_left hyz (log_nonpos (le_of_lt hx0) hx1), end lemma rpow_le_one {x z : ℝ} (hx : 0 ≤ x) (hx2 : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 := by rw ←one_rpow z; apply rpow_le_rpow; assumption lemma one_lt_rpow (hx : 1 < x) (hz : 0 < z) : 1 < x^z := by { rw ← one_rpow z, exact rpow_lt_rpow zero_le_one hx hz } lemma rpow_lt_one (hx : 0 < x) (hx1 : x < 1) (hz : 0 < z) : x^z < 1 := by { rw ← one_rpow z, exact rpow_lt_rpow (le_of_lt hx) hx1 hz } lemma pow_nat_rpow_nat_inv {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) : (x ^ n) ^ (n⁻¹ : ℝ) = x := have hn0 : (n : ℝ) ≠ 0, by simpa [nat.pos_iff_ne_zero] using hn, by rw [← rpow_nat_cast, ← rpow_mul hx, mul_inv_cancel hn0, rpow_one] lemma rpow_nat_inv_pow_nat {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℝ)) ^ n = x := have hn0 : (n : ℝ) ≠ 0, by simpa [nat.pos_iff_ne_zero] using hn, by rw [← rpow_nat_cast, ← rpow_mul hx, inv_mul_cancel hn0, rpow_one] section prove_rpow_is_continuous lemma continuous_rpow_aux1 : continuous (λp : {p:ℝ×ℝ // 0 < p.1}, p.val.1 ^ p.val.2) := suffices h : continuous (λ p : {p:ℝ×ℝ // 0 < p.1 }, exp (log p.val.1 * p.val.2)), by { convert h, ext p, rw rpow_def_of_pos p.2 }, continuous_exp.comp $ (show continuous ((λp:{p:ℝ//0 < p}, log (p.val)) ∘ (λp:{p:ℝ×ℝ//0<p.fst}, ⟨p.val.1, p.2⟩)), from continuous_log'.comp $ continuous_subtype_mk _ $ continuous_fst.comp continuous_subtype_val).mul (continuous_snd.comp $ continuous_subtype_val.comp continuous_id) lemma continuous_rpow_aux2 : continuous (λ p : {p:ℝ×ℝ // p.1 < 0}, p.val.1 ^ p.val.2) := suffices h : continuous (λp:{p:ℝ×ℝ // p.1 < 0}, exp (log (-p.val.1) * p.val.2) * cos (p.val.2 * π)), by { convert h, ext p, rw [rpow_def_of_neg p.2, log_neg_eq_log] }, (continuous_exp.comp $ (show continuous $ (λp:{p:ℝ//0<p}, log (p.val))∘(λp:{p:ℝ×ℝ//p.1<0}, ⟨-p.val.1, neg_pos_of_neg p.2⟩), from continuous_log'.comp $ continuous_subtype_mk _ $ continuous_neg.comp $ continuous_fst.comp continuous_subtype_val).mul (continuous_snd.comp $ continuous_subtype_val.comp continuous_id)).mul (continuous_cos.comp $ (continuous_snd.comp $ continuous_subtype_val.comp continuous_id).mul continuous_const) lemma continuous_at_rpow_of_ne_zero (hx : x ≠ 0) (y : ℝ) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := begin cases lt_trichotomy 0 x, exact continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux1 _ h) (mem_nhds_sets (by { convert is_open_prod (is_open_lt' (0:ℝ)) is_open_univ, ext, finish }) h), cases h, { exact absurd h.symm hx }, exact continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux2 _ h) (mem_nhds_sets (by { convert is_open_prod (is_open_gt' (0:ℝ)) is_open_univ, ext, finish }) h) end lemma continuous_rpow_aux3 : continuous (λ p : {p:ℝ×ℝ // 0 < p.2}, p.val.1 ^ p.val.2) := continuous_iff_continuous_at.2 $ λ ⟨(x₀, y₀), hy₀⟩, begin by_cases hx₀ : x₀ = 0, { simp only [continuous_at, hx₀, zero_rpow (ne_of_gt hy₀), metric.tendsto_nhds_nhds], assume ε ε0, rcases exists_pos_rat_lt (half_pos hy₀) with ⟨q, q_pos, q_lt⟩, let q := (q:ℝ), replace q_pos : 0 < q := rat.cast_pos.2 q_pos, let δ := min (min q (ε ^ (1 / q))) (1/2), have δ0 : 0 < δ := lt_min (lt_min q_pos (rpow_pos_of_pos ε0 _)) (by norm_num), have : δ ≤ q := le_trans (min_le_left _ _) (min_le_left _ _), have : δ ≤ ε ^ (1 / q) := le_trans (min_le_left _ _) (min_le_right _ _), have : δ < 1 := lt_of_le_of_lt (min_le_right _ _) (by norm_num), use δ, use δ0, rintros ⟨⟨x, y⟩, hy⟩, simp only [subtype.dist_eq, real.dist_eq, prod.dist_eq, sub_zero, subtype.coe_mk], assume h, rw max_lt_iff at h, cases h with xδ yy₀, have qy : q < y, calc q < y₀ / 2 : q_lt ... = y₀ - y₀ / 2 : (sub_half _).symm ... ≤ y₀ - δ : by linarith ... < y : sub_lt_of_abs_sub_lt_left yy₀, calc abs(x^y) ≤ abs(x)^y : abs_rpow_le_abs_rpow _ _ ... < δ ^ y : rpow_lt_rpow (abs_nonneg _) xδ hy ... < δ ^ q : by { refine rpow_lt_rpow_of_exponent_gt _ _ _, repeat {linarith} } ... ≤ (ε ^ (1 / q)) ^ q : by { refine rpow_le_rpow _ _ _, repeat {linarith} } ... = ε : by { rw [← rpow_mul, div_mul_cancel, rpow_one], exact ne_of_gt q_pos, linarith }}, { exact (continuous_within_at_iff_continuous_at_restrict (λp:ℝ×ℝ, p.1^p.2) _).1 (continuous_at_rpow_of_ne_zero hx₀ _).continuous_within_at } end lemma continuous_at_rpow_of_pos (hy : 0 < y) (x : ℝ) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux3 _ hy) (mem_nhds_sets (by { convert is_open_prod is_open_univ (is_open_lt' (0:ℝ)), ext, finish }) hy) lemma continuous_at_rpow {x y : ℝ} (h : x ≠ 0 ∨ 0 < y) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := by { cases h, exact continuous_at_rpow_of_ne_zero h _, exact continuous_at_rpow_of_pos h x } variables {α : Type*} [topological_space α] {f g : α → ℝ} /-- `real.rpow` is continuous at all points except for the lower half of the y-axis. In other words, the function `λp:ℝ×ℝ, p.1^p.2` is continuous at `(x, y)` if `x ≠ 0` or `y > 0`. Multiple forms of the claim is provided in the current section. -/ lemma continuous_rpow (h : ∀a, f a ≠ 0 ∨ 0 < g a) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_iff_continuous_at.2 $ λ a, begin show continuous_at ((λp:ℝ×ℝ, p.1^p.2) ∘ (λa, (f a, g a))) a, refine continuous_at.comp _ (continuous_iff_continuous_at.1 (hf.prod_mk hg) _), { replace h := h a, cases h, { exact continuous_at_rpow_of_ne_zero h _ }, { exact continuous_at_rpow_of_pos h _ }}, end lemma continuous_rpow_of_ne_zero (h : ∀a, f a ≠ 0) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inl $ h a) hf hg lemma continuous_rpow_of_pos (h : ∀a, 0 < g a) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inr $ h a) hf hg end prove_rpow_is_continuous section prove_rpow_is_differentiable lemma has_deriv_at_rpow_of_pos {x : ℝ} (h : 0 < x) (p : ℝ) : has_deriv_at (λ x, x^p) (p * x^(p-1)) x := begin have : has_deriv_at (λ x, exp (log x * p)) (p * x^(p-1)) x, { convert (has_deriv_at_exp _).comp x ((has_deriv_at_log (ne_of_gt h)).mul_const p) using 1, field_simp [rpow_def_of_pos h, mul_sub, exp_sub, exp_log h, ne_of_gt h], ring }, apply this.congr_of_mem_nhds, have : set.Ioi (0 : ℝ) ∈ 𝓝 x := mem_nhds_sets is_open_Ioi h, exact filter.eventually_of_mem this (λ y hy, rpow_def_of_pos hy _) end lemma has_deriv_at_rpow_of_neg {x : ℝ} (h : x < 0) (p : ℝ) : has_deriv_at (λ x, x^p) (p * x^(p-1)) x := begin have : has_deriv_at (λ x, exp (log x * p) * cos (p * π)) (p * x^(p-1)) x, { convert ((has_deriv_at_exp _).comp x ((has_deriv_at_log (ne_of_lt h)).mul_const p)).mul_const _ using 1, field_simp [rpow_def_of_neg h, mul_sub, exp_sub, sub_mul, cos_sub, exp_log_of_neg h, ne_of_lt h], ring }, apply this.congr_of_mem_nhds, have : set.Iio (0 : ℝ) ∈ 𝓝 x := mem_nhds_sets is_open_Iio h, exact filter.eventually_of_mem this (λ y hy, rpow_def_of_neg hy _) end lemma has_deriv_at_rpow {x : ℝ} (h : x ≠ 0) (p : ℝ) : has_deriv_at (λ x, x^p) (p * x^(p-1)) x := begin rcases lt_trichotomy x 0 with H|H|H, { exact has_deriv_at_rpow_of_neg H p }, { exact (h H).elim }, { exact has_deriv_at_rpow_of_pos H p }, end lemma has_deriv_at_rpow_zero_of_one_le {p : ℝ} (h : 1 ≤ p) : has_deriv_at (λ x, x^p) (p * (0 : ℝ)^(p-1)) 0 := begin apply has_deriv_at_of_has_deriv_at_of_ne (λ x hx, has_deriv_at_rpow hx p), { exact (continuous_rpow_of_pos (λ _, (lt_of_lt_of_le zero_lt_one h)) continuous_id continuous_const).continuous_at }, { rcases le_iff_eq_or_lt.1 h with rfl|h, { simp [continuous_const.continuous_at] }, { exact (continuous_const.mul (continuous_rpow_of_pos (λ _, sub_pos_of_lt h) continuous_id continuous_const)).continuous_at } } end lemma has_deriv_at_rpow_of_one_le (x : ℝ) {p : ℝ} (h : 1 ≤ p) : has_deriv_at (λ x, x^p) (p * x^(p-1)) x := begin by_cases hx : x = 0, { rw hx, exact has_deriv_at_rpow_zero_of_one_le h }, { exact has_deriv_at_rpow hx p } end end prove_rpow_is_differentiable section sqrt lemma sqrt_eq_rpow : sqrt = λx:ℝ, x ^ (1/(2:ℝ)) := begin funext, by_cases h : 0 ≤ x, { rw [← mul_self_inj_of_nonneg, mul_self_sqrt h, ← pow_two, ← rpow_nat_cast, ← rpow_mul h], norm_num, exact sqrt_nonneg _, exact rpow_nonneg_of_nonneg h _ }, { replace h : x < 0 := lt_of_not_ge h, have : 1 / (2:ℝ) * π = π / (2:ℝ), ring, rw [sqrt_eq_zero_of_nonpos (le_of_lt h), rpow_def_of_neg h, this, cos_pi_div_two, mul_zero] } end lemma continuous_sqrt : continuous sqrt := by rw sqrt_eq_rpow; exact continuous_rpow_of_pos (λa, by norm_num) continuous_id continuous_const end sqrt end real section differentiability open real variables {f : ℝ → ℝ} {x f' : ℝ} {s : set ℝ} (p : ℝ) /- Differentiability statements for the power of a function, when the function does not vanish and the exponent is arbitrary-/ lemma has_deriv_within_at.rpow (hf : has_deriv_within_at f f' s x) (hx : f x ≠ 0) : has_deriv_within_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) s x := begin convert (has_deriv_at_rpow hx p).comp_has_deriv_within_at x hf using 1, ring end lemma has_deriv_at.rpow (hf : has_deriv_at f f' x) (hx : f x ≠ 0) : has_deriv_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) x := begin rw ← has_deriv_within_at_univ at *, exact hf.rpow p hx end lemma differentiable_within_at.rpow (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) : differentiable_within_at ℝ (λx, (f x)^p) s x := (hf.has_deriv_within_at.rpow p hx).differentiable_within_at @[simp] lemma differentiable_at.rpow (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : differentiable_at ℝ (λx, (f x)^p) x := (hf.has_deriv_at.rpow p hx).differentiable_at lemma differentiable_on.rpow (hf : differentiable_on ℝ f s) (hx : ∀ x ∈ s, f x ≠ 0) : differentiable_on ℝ (λx, (f x)^p) s := λx h, (hf x h).rpow p (hx x h) @[simp] lemma differentiable.rpow (hf : differentiable ℝ f) (hx : ∀ x, f x ≠ 0) : differentiable ℝ (λx, (f x)^p) := λx, (hf x).rpow p (hx x) lemma deriv_within_rpow (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, (f x)^p) s x = (deriv_within f s x) * p * (f x)^(p-1) := (hf.has_deriv_within_at.rpow p hx).deriv_within hxs @[simp] lemma deriv_rpow (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : deriv (λx, (f x)^p) x = (deriv f x) * p * (f x)^(p-1) := (hf.has_deriv_at.rpow p hx).deriv /- Differentiability statements for the power of a function, when the function may vanish but the exponent is at least one. -/ variable {p} lemma has_deriv_within_at.rpow_of_one_le (hf : has_deriv_within_at f f' s x) (hp : 1 ≤ p) : has_deriv_within_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) s x := begin convert (has_deriv_at_rpow_of_one_le (f x) hp).comp_has_deriv_within_at x hf using 1, ring end lemma has_deriv_at.rpow_of_one_le (hf : has_deriv_at f f' x) (hp : 1 ≤ p) : has_deriv_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) x := begin rw ← has_deriv_within_at_univ at *, exact hf.rpow_of_one_le hp end lemma differentiable_within_at.rpow_of_one_le (hf : differentiable_within_at ℝ f s x) (hp : 1 ≤ p) : differentiable_within_at ℝ (λx, (f x)^p) s x := (hf.has_deriv_within_at.rpow_of_one_le hp).differentiable_within_at @[simp] lemma differentiable_at.rpow_of_one_le (hf : differentiable_at ℝ f x) (hp : 1 ≤ p) : differentiable_at ℝ (λx, (f x)^p) x := (hf.has_deriv_at.rpow_of_one_le hp).differentiable_at lemma differentiable_on.rpow_of_one_le (hf : differentiable_on ℝ f s) (hp : 1 ≤ p) : differentiable_on ℝ (λx, (f x)^p) s := λx h, (hf x h).rpow_of_one_le hp @[simp] lemma differentiable.rpow_of_one_le (hf : differentiable ℝ f) (hp : 1 ≤ p) : differentiable ℝ (λx, (f x)^p) := λx, (hf x).rpow_of_one_le hp lemma deriv_within_rpow_of_one_le (hf : differentiable_within_at ℝ f s x) (hp : 1 ≤ p) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, (f x)^p) s x = (deriv_within f s x) * p * (f x)^(p-1) := (hf.has_deriv_within_at.rpow_of_one_le hp).deriv_within hxs @[simp] lemma deriv_rpow_of_one_le (hf : differentiable_at ℝ f x) (hp : 1 ≤ p) : deriv (λx, (f x)^p) x = (deriv f x) * p * (f x)^(p-1) := (hf.has_deriv_at.rpow_of_one_le hp).deriv /- Differentiability statements for the square root of a function, when the function does not vanish -/ lemma has_deriv_within_at.sqrt (hf : has_deriv_within_at f f' s x) (hx : f x ≠ 0) : has_deriv_within_at (λ y, sqrt (f y)) (f' / (2 * sqrt (f x))) s x := begin simp only [sqrt_eq_rpow], convert hf.rpow (1/2) hx, rcases lt_trichotomy (f x) 0 with H|H|H, { have A : (f x)^((1:ℝ)/2) = 0, { rw rpow_def_of_neg H, have : cos (1/2 * π) = 0, by { convert cos_pi_div_two using 2, ring }, rw [this], simp }, have B : f x ^ ((1:ℝ) / 2 - 1) = 0, { rw rpow_def_of_neg H, have : cos (π/2 - π) = 0, by simp [cos_sub], have : cos (((1:ℝ)/2 - 1) * π) = 0, by { convert this using 2, ring }, rw this, simp }, rw [A, B], simp }, { exact (hx H).elim }, { have A : 0 < (f x)^((1:ℝ)/2) := rpow_pos_of_pos H _, have B : (f x) ^ (-(1:ℝ)) = (f x)^(-((1:ℝ)/2)) * (f x)^(-((1:ℝ)/2)), { rw [← rpow_add H], congr, norm_num }, rw [sub_eq_add_neg, rpow_add H, B, rpow_neg (le_of_lt H)], field_simp [hx, ne_of_gt A], ring } end lemma has_deriv_at.sqrt (hf : has_deriv_at f f' x) (hx : f x ≠ 0) : has_deriv_at (λ y, sqrt (f y)) (f' / (2 * sqrt(f x))) x := begin rw ← has_deriv_within_at_univ at *, exact hf.sqrt hx end lemma differentiable_within_at.sqrt (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) : differentiable_within_at ℝ (λx, sqrt (f x)) s x := (hf.has_deriv_within_at.sqrt hx).differentiable_within_at @[simp] lemma differentiable_at.sqrt (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : differentiable_at ℝ (λx, sqrt (f x)) x := (hf.has_deriv_at.sqrt hx).differentiable_at lemma differentiable_on.sqrt (hf : differentiable_on ℝ f s) (hx : ∀ x ∈ s, f x ≠ 0) : differentiable_on ℝ (λx, sqrt (f x)) s := λx h, (hf x h).sqrt (hx x h) @[simp] lemma differentiable.sqrt (hf : differentiable ℝ f) (hx : ∀ x, f x ≠ 0) : differentiable ℝ (λx, sqrt (f x)) := λx, (hf x).sqrt (hx x) lemma deriv_within_sqrt (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, sqrt (f x)) s x = (deriv_within f s x) / (2 * sqrt (f x)) := (hf.has_deriv_within_at.sqrt hx).deriv_within hxs @[simp] lemma deriv_sqrt (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : deriv (λx, sqrt (f x)) x = (deriv f x) / (2 * sqrt (f x)) := (hf.has_deriv_at.sqrt hx).deriv end differentiability namespace nnreal /-- The nonnegative real power function `x^y`, defined for `x : ℝ≥0` and `y : ℝ ` as the restriction of the real power function. For `x > 0`, it is equal to `exp (y log x)`. For `x = 0`, one sets `0 ^ 0 = 1` and `0 ^ y = 0` for `y ≠ 0`. -/ noncomputable def rpow (x : ℝ≥0) (y : ℝ) : ℝ≥0 := ⟨(x : ℝ) ^ y, real.rpow_nonneg_of_nonneg x.2 y⟩ noncomputable instance : has_pow ℝ≥0 ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x : ℝ≥0) (y : ℝ) : rpow x y = x ^ y := rfl @[simp, norm_cast] lemma coe_rpow (x : ℝ≥0) (y : ℝ) : ((x ^ y : ℝ≥0) : ℝ) = (x : ℝ) ^ y := rfl @[simp] lemma rpow_zero (x : ℝ≥0) : x ^ (0 : ℝ) = 1 := nnreal.eq $ real.rpow_zero _ @[simp] lemma rpow_eq_zero_iff {x : ℝ≥0} {y : ℝ} : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := begin rw [← nnreal.coe_eq, coe_rpow, ← nnreal.coe_eq_zero], exact real.rpow_eq_zero_iff_of_nonneg x.2 end @[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : ℝ≥0) ^ x = 0 := nnreal.eq $ real.zero_rpow h @[simp] lemma rpow_one (x : ℝ≥0) : x ^ (1 : ℝ) = x := nnreal.eq $ real.rpow_one _ @[simp] lemma one_rpow (x : ℝ) : (1 : ℝ≥0) ^ x = 1 := nnreal.eq $ real.one_rpow _ lemma rpow_add {x : ℝ≥0} (hx : x ≠ 0) (y z : ℝ) : x ^ (y + z) = x ^ y * x ^ z := nnreal.eq $ real.rpow_add (zero_lt_iff_ne_zero.2 hx) _ _ lemma rpow_add' (x : ℝ≥0) {y z : ℝ} (h : y + z ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := nnreal.eq $ real.rpow_add' x.2 h lemma rpow_mul (x : ℝ≥0) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := nnreal.eq $ real.rpow_mul x.2 y z lemma rpow_neg (x : ℝ≥0) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := nnreal.eq $ real.rpow_neg x.2 _ lemma rpow_neg_one (x : ℝ≥0) : x ^ (-1 : ℝ) = x ⁻¹ := by simp [rpow_neg] lemma rpow_sub {x : ℝ≥0} (hx : x ≠ 0) (y z : ℝ) : x ^ (y - z) = x ^ y / x ^ z := nnreal.eq $ real.rpow_sub (zero_lt_iff_ne_zero.2 hx) y z lemma rpow_sub' (x : ℝ≥0) {y z : ℝ} (h : y - z ≠ 0) : x ^ (y - z) = x ^ y / x ^ z := nnreal.eq $ real.rpow_sub' x.2 h lemma inv_rpow (x : ℝ≥0) (y : ℝ) : (x⁻¹) ^ y = (x ^ y)⁻¹ := nnreal.eq $ real.inv_rpow x.2 y lemma div_rpow (x y : ℝ≥0) (z : ℝ) : (x / y) ^ z = x ^ z / y ^ z := nnreal.eq $ real.div_rpow x.2 y.2 z @[simp, norm_cast] lemma rpow_nat_cast (x : ℝ≥0) (n : ℕ) : x ^ (n : ℝ) = x ^ n := nnreal.eq $ by simpa only [coe_rpow, coe_pow] using real.rpow_nat_cast x n lemma mul_rpow {x y : ℝ≥0} {z : ℝ} : (x*y)^z = x^z * y^z := nnreal.eq $ real.mul_rpow x.2 y.2 lemma one_le_rpow {x : ℝ≥0} {z : ℝ} (h : 1 ≤ x) (h₁ : 0 ≤ z) : 1 ≤ x^z := real.one_le_rpow h h₁ lemma rpow_le_rpow {x y : ℝ≥0} {z: ℝ} (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := real.rpow_le_rpow x.2 h₁ h₂ lemma rpow_lt_rpow {x y : ℝ≥0} {z: ℝ} (h₁ : x < y) (h₂ : 0 < z) : x^z < y^z := real.rpow_lt_rpow x.2 h₁ h₂ lemma rpow_lt_rpow_iff {x y : ℝ≥0} {z : ℝ} (hz : 0 < z) : x ^ z < y ^ z ↔ x < y := real.rpow_lt_rpow_iff x.2 y.2 hz lemma rpow_le_rpow_iff {x y : ℝ≥0} {z : ℝ} (hz : 0 < z) : x ^ z ≤ y ^ z ↔ x ≤ y := real.rpow_le_rpow_iff x.2 y.2 hz lemma rpow_lt_rpow_of_exponent_lt {x : ℝ≥0} {y z : ℝ} (hx : 1 < x) (hyz : y < z) : x^y < x^z := real.rpow_lt_rpow_of_exponent_lt hx hyz lemma rpow_le_rpow_of_exponent_le {x : ℝ≥0} {y z : ℝ} (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := real.rpow_le_rpow_of_exponent_le hx hyz lemma rpow_lt_rpow_of_exponent_gt {x : ℝ≥0} {y z : ℝ} (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := real.rpow_lt_rpow_of_exponent_gt hx0 hx1 hyz lemma rpow_le_rpow_of_exponent_ge {x : ℝ≥0} {y z : ℝ} (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := real.rpow_le_rpow_of_exponent_ge hx0 hx1 hyz lemma rpow_le_one {x : ℝ≥0} {z : ℝ} (hx2 : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 := real.rpow_le_one x.2 hx2 hz lemma one_lt_rpow {x : ℝ≥0} {z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z := real.one_lt_rpow hx hz lemma rpow_lt_one {x : ℝ≥0} {z : ℝ} (hx : 0 < x) (hx1 : x < 1) (hz : 0 < z) : x^z < 1 := real.rpow_lt_one hx hx1 hz lemma pow_nat_rpow_nat_inv (x : ℝ≥0) {n : ℕ} (hn : 0 < n) : (x ^ n) ^ (n⁻¹ : ℝ) = x := by { rw [← nnreal.coe_eq, coe_rpow, nnreal.coe_pow], exact real.pow_nat_rpow_nat_inv x.2 hn } lemma rpow_nat_inv_pow_nat (x : ℝ≥0) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℝ)) ^ n = x := by { rw [← nnreal.coe_eq, nnreal.coe_pow, coe_rpow], exact real.rpow_nat_inv_pow_nat x.2 hn } lemma continuous_at_rpow {x : ℝ≥0} {y : ℝ} (h : x ≠ 0 ∨ 0 < y) : continuous_at (λp:ℝ≥0×ℝ, p.1^p.2) (x, y) := begin have : (λp:ℝ≥0×ℝ, p.1^p.2) = nnreal.of_real ∘ (λp:ℝ×ℝ, p.1^p.2) ∘ (λp:ℝ≥0 × ℝ, (p.1.1, p.2)), { ext p, rw [coe_rpow, nnreal.coe_of_real _ (real.rpow_nonneg_of_nonneg p.1.2 _)], refl }, rw this, refine nnreal.continuous_of_real.continuous_at.comp (continuous_at.comp _ _), { apply real.continuous_at_rpow, simp at h, rw ← (nnreal.coe_eq_zero x) at h, exact h }, { exact ((continuous_subtype_val.comp continuous_fst).prod_mk continuous_snd).continuous_at } end end nnreal open filter lemma filter.tendsto.nnrpow {α : Type*} {f : filter α} {u : α → ℝ≥0} {v : α → ℝ} {x : ℝ≥0} {y : ℝ} (hx : tendsto u f (𝓝 x)) (hy : tendsto v f (𝓝 y)) (h : x ≠ 0 ∨ 0 < y) : tendsto (λ a, (u a) ^ (v a)) f (𝓝 (x ^ y)) := tendsto.comp (nnreal.continuous_at_rpow h) (tendsto.prod_mk_nhds hx hy) namespace ennreal /-- The real power function `x^y` on extended nonnegative reals, defined for `x : ennreal` and `y : ℝ` as the restriction of the real power function if `0 < x < ⊤`, and with the natural values for `0` and `⊤` (i.e., `0 ^ x = 0` for `x > 0`, `1` for `x = 0` and `⊤` for `x < 0`, and `⊤ ^ x = 1 / 0 ^ x`). -/ noncomputable def rpow : ennreal → ℝ → ennreal | (some x) y := if x = 0 ∧ y < 0 then ⊤ else (x ^ y : ℝ≥0) | none y := if 0 < y then ⊤ else if y = 0 then 1 else 0 noncomputable instance : has_pow ennreal ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x : ennreal) (y : ℝ) : rpow x y = x ^ y := rfl @[simp] lemma rpow_zero {x : ennreal} : x ^ (0 : ℝ) = 1 := by cases x; { dsimp only [(^), rpow], simp [lt_irrefl] } lemma top_rpow_def (y : ℝ) : (⊤ : ennreal) ^ y = if 0 < y then ⊤ else if y = 0 then 1 else 0 := rfl @[simp] lemma top_rpow_of_pos {y : ℝ} (h : 0 < y) : (⊤ : ennreal) ^ y = ⊤ := by simp [top_rpow_def, h] @[simp] lemma top_rpow_of_neg {y : ℝ} (h : y < 0) : (⊤ : ennreal) ^ y = 0 := by simp [top_rpow_def, asymm h, ne_of_lt h] @[simp] lemma zero_rpow_of_pos {y : ℝ} (h : 0 < y) : (0 : ennreal) ^ y = 0 := begin rw [← ennreal.coe_zero, ← ennreal.some_eq_coe], dsimp only [(^), rpow], simp [h, asymm h, ne_of_gt h], end @[simp] lemma zero_rpow_of_neg {y : ℝ} (h : y < 0) : (0 : ennreal) ^ y = ⊤ := begin rw [← ennreal.coe_zero, ← ennreal.some_eq_coe], dsimp only [(^), rpow], simp [h, ne_of_gt h], end lemma zero_rpow_def (y : ℝ) : (0 : ennreal) ^ y = if 0 < y then 0 else if y = 0 then 1 else ⊤ := begin rcases lt_trichotomy 0 y with H|rfl|H, { simp [H, ne_of_gt, zero_rpow_of_pos, lt_irrefl] }, { simp [lt_irrefl] }, { simp [H, asymm H, ne_of_lt, zero_rpow_of_neg] } end @[norm_cast] lemma coe_rpow_of_ne_zero {x : ℝ≥0} (h : x ≠ 0) (y : ℝ) : (x : ennreal) ^ y = (x ^ y : ℝ≥0) := begin rw [← ennreal.some_eq_coe], dsimp only [(^), rpow], simp [h] end @[norm_cast] lemma coe_rpow_of_nonneg (x : ℝ≥0) {y : ℝ} (h : 0 ≤ y) : (x : ennreal) ^ y = (x ^ y : ℝ≥0) := begin by_cases hx : x = 0, { rcases le_iff_eq_or_lt.1 h with H|H, { simp [hx, H.symm] }, { simp [hx, zero_rpow_of_pos H, nnreal.zero_rpow (ne_of_gt H)] } }, { exact coe_rpow_of_ne_zero hx _ } end @[simp] lemma rpow_one (x : ennreal) : x ^ (1 : ℝ) = x := by cases x; dsimp only [(^), rpow]; simp [zero_lt_one, not_lt_of_le zero_le_one] @[simp] lemma one_rpow (x : ℝ) : (1 : ennreal) ^ x = 1 := by { rw [← coe_one, coe_rpow_of_ne_zero one_ne_zero], simp } @[simp] lemma rpow_eq_zero_iff {x : ennreal} {y : ℝ} : x ^ y = 0 ↔ (x = 0 ∧ 0 < y) ∨ (x = ⊤ ∧ y < 0) := begin cases x, { rcases lt_trichotomy y 0 with H|H|H; simp [H, top_rpow_of_neg, top_rpow_of_pos, le_of_lt] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with H|H|H; simp [h, H, zero_rpow_of_neg, zero_rpow_of_pos, le_of_lt] }, { simp [coe_rpow_of_ne_zero h, h] } } end @[simp] lemma rpow_eq_top_iff {x : ennreal} {y : ℝ} : x ^ y = ⊤ ↔ (x = 0 ∧ y < 0) ∨ (x = ⊤ ∧ 0 < y) := begin cases x, { rcases lt_trichotomy y 0 with H|H|H; simp [H, top_rpow_of_neg, top_rpow_of_pos, le_of_lt] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with H|H|H; simp [h, H, zero_rpow_of_neg, zero_rpow_of_pos, le_of_lt] }, { simp [coe_rpow_of_ne_zero h, h] } } end lemma rpow_add {x : ennreal} (y z : ℝ) (hx : x ≠ 0) (h'x : x ≠ ⊤) : x ^ (y + z) = x ^ y * x ^ z := begin cases x, { exact (h'x rfl).elim }, have : x ≠ 0 := λ h, by simpa [h] using hx, simp [coe_rpow_of_ne_zero this, nnreal.rpow_add this] end lemma rpow_neg (x : ennreal) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := begin cases x, { rcases lt_trichotomy y 0 with H|H|H; simp [top_rpow_of_pos, top_rpow_of_neg, H, neg_pos.mpr] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with H|H|H; simp [h, zero_rpow_of_pos, zero_rpow_of_neg, H, neg_pos.mpr] }, { have A : x ^ y ≠ 0, by simp [h], simp [coe_rpow_of_ne_zero h, ← coe_inv A, nnreal.rpow_neg] } } end lemma rpow_neg_one (x : ennreal) : x ^ (-1 : ℝ) = x ⁻¹ := by simp [rpow_neg] lemma rpow_mul (x : ennreal) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := begin cases x, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [Hy, Hz, zero_rpow_of_neg, zero_rpow_of_pos, top_rpow_of_neg, top_rpow_of_pos, mul_pos_of_neg_of_neg, mul_neg_of_neg_of_pos, mul_neg_of_pos_of_neg] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [h, Hy, Hz, zero_rpow_of_neg, zero_rpow_of_pos, top_rpow_of_neg, top_rpow_of_pos, mul_pos_of_neg_of_neg, mul_neg_of_neg_of_pos, mul_neg_of_pos_of_neg] }, { have : x ^ y ≠ 0, by simp [h], simp [coe_rpow_of_ne_zero h, coe_rpow_of_ne_zero this, nnreal.rpow_mul] } } end @[simp, norm_cast] lemma rpow_nat_cast (x : ennreal) (n : ℕ) : x ^ (n : ℝ) = x ^ n := begin cases x, { cases n; simp [top_rpow_of_pos (nat.cast_add_one_pos _), top_pow (nat.succ_pos _)] }, { simp [coe_rpow_of_nonneg _ (nat.cast_nonneg n)] } end @[norm_cast] lemma coe_mul_rpow (x y : ℝ≥0) (z : ℝ) : ((x : ennreal) * y) ^ z = x^z * y^z := begin rcases lt_trichotomy z 0 with H|H|H, { by_cases hx : x = 0; by_cases hy : y = 0, { simp [hx, hy, zero_rpow_of_neg, H] }, { have : (y : ennreal) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hy], simp [hx, hy, zero_rpow_of_neg, H, with_top.top_mul this] }, { have : (x : ennreal) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hx], simp [hx, hy, zero_rpow_of_neg H, with_top.mul_top this] }, { rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul, coe_rpow_of_ne_zero hx, coe_rpow_of_ne_zero hy], simp [hx, hy] } }, { simp [H] }, { by_cases hx : x = 0; by_cases hy : y = 0, { simp [hx, hy, zero_rpow_of_pos, H] }, { have : (y : ennreal) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hy], simp [hx, hy, zero_rpow_of_pos H, with_top.top_mul this] }, { have : (x : ennreal) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hx], simp [hx, hy, zero_rpow_of_pos H, with_top.mul_top this] }, { rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul, coe_rpow_of_ne_zero hx, coe_rpow_of_ne_zero hy], simp [hx, hy] } }, end lemma mul_rpow_of_ne_top {x y : ennreal} (hx : x ≠ ⊤) (hy : y ≠ ⊤) (z : ℝ) : (x * y) ^ z = x^z * y^z := begin lift x to ℝ≥0 using hx, lift y to ℝ≥0 using hy, exact coe_mul_rpow x y z end lemma mul_rpow_of_ne_zero {x y : ennreal} (hx : x ≠ 0) (hy : y ≠ 0) (z : ℝ) : (x * y) ^ z = x ^ z * y ^ z := begin rcases lt_trichotomy z 0 with H|H|H, { cases x; cases y, { simp [hx, hy, top_rpow_of_neg, H] }, { have : y ≠ 0, by simpa using hy, simp [hx, hy, top_rpow_of_neg, H, rpow_eq_zero_iff, this] }, { have : x ≠ 0, by simpa using hx, simp [hx, hy, top_rpow_of_neg, H, rpow_eq_zero_iff, this] }, { have hx' : x ≠ 0, by simpa using hx, have hy' : y ≠ 0, by simpa using hy, simp only [some_eq_coe], rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul, coe_rpow_of_ne_zero hx', coe_rpow_of_ne_zero hy'], simp [hx', hy'] } }, { simp [H] }, { cases x; cases y, { simp [hx, hy, top_rpow_of_pos, H] }, { have : y ≠ 0, by simpa using hy, simp [hx, hy, top_rpow_of_pos, H, rpow_eq_zero_iff, this] }, { have : x ≠ 0, by simpa using hx, simp [hx, hy, top_rpow_of_pos, H, rpow_eq_zero_iff, this] }, { have hx' : x ≠ 0, by simpa using hx, have hy' : y ≠ 0, by simpa using hy, simp only [some_eq_coe], rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul, coe_rpow_of_ne_zero hx', coe_rpow_of_ne_zero hy'], simp [hx', hy'] } } end lemma mul_rpow_of_nonneg (x y : ennreal) {z : ℝ} (hz : 0 ≤ z) : (x * y) ^ z = x ^ z * y ^ z := begin rcases le_iff_eq_or_lt.1 hz with H|H, { simp [← H] }, by_cases h : x = 0 ∨ y = 0, { cases h; simp [h, zero_rpow_of_pos H] }, push_neg at h, exact mul_rpow_of_ne_zero h.1 h.2 z end lemma one_le_rpow {x : ennreal} {z : ℝ} (h : 1 ≤ x) (h₁ : 0 ≤ z) : 1 ≤ x^z := begin cases x, { rcases le_iff_eq_or_lt.1 h₁ with H|H, { simp [← H, le_refl] }, { simp [top_rpow_of_pos H] } }, { simp only [one_le_coe_iff, some_eq_coe] at h, simp [coe_rpow_of_nonneg _ h₁, nnreal.one_le_rpow h h₁] } end lemma rpow_le_rpow {x y : ennreal} {z : ℝ} (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := begin rcases le_iff_eq_or_lt.1 h₂ with H|H, { simp [← H, le_refl] }, cases y, { simp [top_rpow_of_pos H] }, cases x, { exact (not_top_le_coe h₁).elim }, simp at h₁, simp [coe_rpow_of_nonneg _ h₂, nnreal.rpow_le_rpow h₁ h₂] end lemma rpow_lt_rpow {x y : ennreal} {z : ℝ} (h₁ : x < y) (h₂ : 0 < z) : x^z < y^z := begin cases x, { exact (not_top_lt h₁).elim }, cases y, { simp [top_rpow_of_pos h₂, coe_rpow_of_nonneg _ (le_of_lt h₂)] }, simp at h₁, simp [coe_rpow_of_nonneg _ (le_of_lt h₂), nnreal.rpow_lt_rpow h₁ h₂] end lemma rpow_lt_rpow_of_exponent_lt {x : ennreal} {y z : ℝ} (hx : 1 < x) (hx' : x ≠ ⊤) (hyz : y < z) : x^y < x^z := begin lift x to ℝ≥0 using hx', rw [one_lt_coe_iff] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_trans zero_lt_one hx)), nnreal.rpow_lt_rpow_of_exponent_lt hx hyz] end lemma rpow_le_rpow_of_exponent_le {x : ennreal} {y z : ℝ} (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := begin cases x, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [Hy, Hz, top_rpow_of_neg, top_rpow_of_pos, le_refl]; linarith }, { simp only [one_le_coe_iff, some_eq_coe] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_of_lt_of_le zero_lt_one hx)), nnreal.rpow_le_rpow_of_exponent_le hx hyz] } end lemma rpow_lt_rpow_of_exponent_gt {x : ennreal} {y z : ℝ} (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_lt_of_le hx1 le_top), simp at hx0 hx1, simp [coe_rpow_of_ne_zero (ne_of_gt hx0), nnreal.rpow_lt_rpow_of_exponent_gt hx0 hx1 hyz] end lemma rpow_le_rpow_of_exponent_ge {x : ennreal} {y z : ℝ} (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_le_of_lt hx1 coe_lt_top), by_cases h : x = 0, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [Hy, Hz, h, zero_rpow_of_neg, zero_rpow_of_pos, le_refl]; linarith }, { simp at hx1, simp [coe_rpow_of_ne_zero h, nnreal.rpow_le_rpow_of_exponent_ge (bot_lt_iff_ne_bot.mpr h) hx1 hyz] } end lemma rpow_le_one {x : ennreal} {z : ℝ} (hx2 : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 := begin lift x to ℝ≥0 using ne_of_lt (lt_of_le_of_lt hx2 coe_lt_top), simp at hx2, simp [coe_rpow_of_nonneg _ hz, nnreal.rpow_le_one hx2 hz] end lemma one_lt_rpow {x : ennreal} {z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z := begin cases x, { simp [top_rpow_of_pos hz], exact coe_lt_top }, { simp at hx, simp [coe_rpow_of_nonneg _ (le_of_lt hz), nnreal.one_lt_rpow hx hz] } end lemma rpow_lt_one {x : ennreal} {z : ℝ} (hx1 : x < 1) (hz : 0 < z) : x^z < 1 := begin by_cases h : x = 0, { simp [h, zero_rpow_of_pos hz, ennreal.zero_lt_one] }, { lift x to ℝ≥0 using ne_of_lt (lt_of_lt_of_le hx1 le_top), simp at h hx1, have : 0 < x := bot_lt_iff_ne_bot.mpr h, simp [coe_rpow_of_nonneg _ (le_of_lt hz), nnreal.rpow_lt_one this hx1 hz] } end lemma to_real_rpow (x : ennreal) (z : ℝ) : (x.to_real) ^ z = (x ^ z).to_real := begin rcases lt_trichotomy z 0 with H|H|H, { cases x, { simp [H, ne_of_lt] }, by_cases hx : x = 0, { simp [hx, H, ne_of_lt] }, { simp [coe_rpow_of_ne_zero hx] } }, { simp [H] }, { cases x, { simp [H, ne_of_gt] }, simp [coe_rpow_of_nonneg _ (le_of_lt H)] } end end ennreal
716373f3dbaf385ce783d511ab90bf495db811f1
618003631150032a5676f229d13a079ac875ff77
/src/control/equiv_functor/instances.lean
f7a829ed2155559ab4e4f03437a8deb65da5b059
[ "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
527
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Scott Morrison -/ import tactic.equiv_rw /-! # `equiv_functor` instances We derive some `equiv_functor` instances, to enable `equiv_rw` to rewrite under these functions. -/ open equiv instance equiv_functor_unique : equiv_functor unique := { map := λ α β e, equiv.unique_congr e, } instance equiv_functor_perm : equiv_functor perm := { map := λ α β e p, (e.symm.trans p).trans e }
9b684025616561df78c0354f43bfc0b302bf644e
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/transport.lean
9c727401bc73f5652d8aff6868ef5d4828cc426e
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
2,072
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Simon Hudon, Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.equiv_rw import Mathlib.PostPort namespace Mathlib /-! ## The `transport` tactic `transport` attempts to move an `s : S α` expression across an equivalence `e : α ≃ β` to solve a goal of the form `S β`, by building the new object field by field, taking each field of `s` and rewriting it along `e` using the `equiv_rw` tactic. We try to ensure good definitional properties, so that, for example, when we transport a `monoid α` to a `monoid β`, the new multiplication is definitionally `λ x y, e (e.symm a * e.symm b)`. -/ namespace tactic /-- Given `s : S α` for some structure `S` depending on a type `α`, and an equivalence `e : α ≃ β`, try to produce an `S β`, by transporting data and axioms across `e` using `equiv_rw`. -/ namespace interactive /-- Given a goal `⊢ S β` for some type class `S`, and an equivalence `e : α ≃ β`. `transport using e` will look for a hypothesis `s : S α`, and attempt to close the goal by transporting `s` across the equivalence `e`. ```lean example {α : Type} [ring α] {β : Type} (e : α ≃ β) : ring β := by transport using e. ``` You can specify the object to transport using `transport s using e`. `transport` works by attempting to copy each of the operations and axiom fields of `s`, rewriting them using `equiv_rw e` and defining a new structure using these rewritten fields. If it fails to fill in all the new fields, `transport` will produce new subgoals. It's probably best to think about which missing `simp` lemmas would have allowed `transport` to finish, rather than solving these goals by hand. (This may require looking at the implementation of `tranport` to understand its algorithm; there are several examples of "transport-by-hand" at the end of `test/equiv_rw.lean`, which `transport` is an abstraction of.) -/
a81d850f1b5d17967210aecf12fc1ee80a821a62
9dc8cecdf3c4634764a18254e94d43da07142918
/src/set_theory/game/pgame.lean
e9bf0c246ede70fc3d0fb61d66f8cef9f4b05de3
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
59,846
lean
/- Copyright (c) 2019 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Mario Carneiro, Isabel Longbottom, Scott Morrison -/ import data.fin.basic import data.list.basic import logic.relation /-! # Combinatorial (pre-)games. The basic theory of combinatorial games, following Conway's book `On Numbers and Games`. We construct "pregames", define an ordering and arithmetic operations on them, then show that the operations descend to "games", defined via the equivalence relation `p ≈ q ↔ p ≤ q ∧ q ≤ p`. The surreal numbers will be built as a quotient of a subtype of pregames. A pregame (`pgame` below) is axiomatised via an inductive type, whose sole constructor takes two types (thought of as indexing the possible moves for the players Left and Right), and a pair of functions out of these types to `pgame` (thought of as describing the resulting game after making a move). Combinatorial games themselves, as a quotient of pregames, are constructed in `game.lean`. ## Conway induction By construction, the induction principle for pregames is exactly "Conway induction". That is, to prove some predicate `pgame → Prop` holds for all pregames, it suffices to prove that for every pregame `g`, if the predicate holds for every game resulting from making a move, then it also holds for `g`. While it is often convenient to work "by induction" on pregames, in some situations this becomes awkward, so we also define accessor functions `pgame.left_moves`, `pgame.right_moves`, `pgame.move_left` and `pgame.move_right`. There is a relation `pgame.subsequent p q`, saying that `p` can be reached by playing some non-empty sequence of moves starting from `q`, an instance `well_founded subsequent`, and a local tactic `pgame_wf_tac` which is helpful for discharging proof obligations in inductive proofs relying on this relation. ## Order properties Pregames have both a `≤` and a `<` relation, satisfying the usual properties of a `preorder`. The relation `0 < x` means that `x` can always be won by Left, while `0 ≤ x` means that `x` can be won by Left as the second player. It turns out to be quite convenient to define various relations on top of these. We define the "less or fuzzy" relation `x ⧏ y` as `¬ y ≤ x`, the equivalence relation `x ≈ y` as `x ≤ y ∧ y ≤ x`, and the fuzzy relation `x ∥ y` as `x ⧏ y ∧ y ⧏ x`. If `0 ⧏ x`, then `x` can be won by Left as the first player. If `x ≈ 0`, then `x` can be won by the second player. If `x ∥ 0`, then `x` can be won by the first player. Statements like `zero_le_lf`, `zero_lf_le`, etc. unfold these definitions. The theorems `le_def` and `lf_def` give a recursive characterisation of each relation in terms of themselves two moves later. The theorems `zero_le`, `zero_lf`, etc. also take into account that `0` has no moves. Later, games will be defined as the quotient by the `≈` relation; that is to say, the `antisymmetrization` of `pgame`. ## Algebraic structures We next turn to defining the operations necessary to make games into a commutative additive group. Addition is defined for $x = \{xL | xR\}$ and $y = \{yL | yR\}$ by $x + y = \{xL + y, x + yL | xR + y, x + yR\}$. Negation is defined by $\{xL | xR\} = \{-xR | -xL\}$. The order structures interact in the expected way with addition, so we have ``` theorem le_iff_sub_nonneg {x y : pgame} : x ≤ y ↔ 0 ≤ y - x := sorry theorem lt_iff_sub_pos {x y : pgame} : x < y ↔ 0 < y - x := sorry ``` We show that these operations respect the equivalence relation, and hence descend to games. At the level of games, these operations satisfy all the laws of a commutative group. To prove the necessary equivalence relations at the level of pregames, we introduce the notion of a `relabelling` of a game, and show, for example, that there is a relabelling between `x + (y + z)` and `(x + y) + z`. ## Future work * The theory of dominated and reversible positions, and unique normal form for short games. * Analysis of basic domineering positions. * Hex. * Temperature. * The development of surreal numbers, based on this development of combinatorial games, is still quite incomplete. ## References The material here is all drawn from * [Conway, *On numbers and games*][conway2001] An interested reader may like to formalise some of the material from * [Andreas Blass, *A game semantics for linear logic*][MR1167694] * [André Joyal, *Remarques sur la théorie des jeux à deux personnes*][joyal1997] -/ open function relation universes u /-! ### Pre-game moves -/ /-- The type of pre-games, before we have quotiented by equivalence (`pgame.setoid`). In ZFC, a combinatorial game is constructed from two sets of combinatorial games that have been constructed at an earlier stage. To do this in type theory, we say that a pre-game is built inductively from two families of pre-games indexed over any type in Type u. The resulting type `pgame.{u}` lives in `Type (u+1)`, reflecting that it is a proper class in ZFC. -/ inductive pgame : Type (u+1) | mk : ∀ α β : Type u, (α → pgame) → (β → pgame) → pgame namespace pgame /-- The indexing type for allowable moves by Left. -/ def left_moves : pgame → Type u | (mk l _ _ _) := l /-- The indexing type for allowable moves by Right. -/ def right_moves : pgame → Type u | (mk _ r _ _) := r /-- The new game after Left makes an allowed move. -/ def move_left : Π (g : pgame), left_moves g → pgame | (mk l _ L _) := L /-- The new game after Right makes an allowed move. -/ def move_right : Π (g : pgame), right_moves g → pgame | (mk _ r _ R) := R @[simp] lemma left_moves_mk {xl xr xL xR} : (⟨xl, xr, xL, xR⟩ : pgame).left_moves = xl := rfl @[simp] lemma move_left_mk {xl xr xL xR} : (⟨xl, xr, xL, xR⟩ : pgame).move_left = xL := rfl @[simp] lemma right_moves_mk {xl xr xL xR} : (⟨xl, xr, xL, xR⟩ : pgame).right_moves = xr := rfl @[simp] lemma move_right_mk {xl xr xL xR} : (⟨xl, xr, xL, xR⟩ : pgame).move_right = xR := rfl /-- Construct a pre-game from list of pre-games describing the available moves for Left and Right. -/ -- TODO define this at the level of games, as well, and perhaps also for finsets of games. def of_lists (L R : list pgame.{u}) : pgame.{u} := mk (ulift (fin L.length)) (ulift (fin R.length)) (λ i, L.nth_le i.down i.down.is_lt) (λ j, R.nth_le j.down j.down.prop) lemma left_moves_of_lists (L R : list pgame) : (of_lists L R).left_moves = ulift (fin L.length) := rfl lemma right_moves_of_lists (L R : list pgame) : (of_lists L R).right_moves = ulift (fin R.length) := rfl /-- Converts a number into a left move for `of_lists`. -/ def to_of_lists_left_moves {L R : list pgame} : fin L.length ≃ (of_lists L R).left_moves := ((equiv.cast (left_moves_of_lists L R).symm).trans equiv.ulift).symm /-- Converts a number into a right move for `of_lists`. -/ def to_of_lists_right_moves {L R : list pgame} : fin R.length ≃ (of_lists L R).right_moves := ((equiv.cast (right_moves_of_lists L R).symm).trans equiv.ulift).symm theorem of_lists_move_left {L R : list pgame} (i : fin L.length) : (of_lists L R).move_left (to_of_lists_left_moves i) = L.nth_le i i.is_lt := rfl @[simp] theorem of_lists_move_left' {L R : list pgame} (i : (of_lists L R).left_moves) : (of_lists L R).move_left i = L.nth_le (to_of_lists_left_moves.symm i) (to_of_lists_left_moves.symm i).is_lt := rfl theorem of_lists_move_right {L R : list pgame} (i : fin R.length) : (of_lists L R).move_right (to_of_lists_right_moves i) = R.nth_le i i.is_lt := rfl @[simp] theorem of_lists_move_right' {L R : list pgame} (i : (of_lists L R).right_moves) : (of_lists L R).move_right i = R.nth_le (to_of_lists_right_moves.symm i) (to_of_lists_right_moves.symm i).is_lt := rfl /-- A variant of `pgame.rec_on` expressed in terms of `pgame.move_left` and `pgame.move_right`. Both this and `pgame.rec_on` describe Conway induction on games. -/ @[elab_as_eliminator] def move_rec_on {C : pgame → Sort*} (x : pgame) (IH : ∀ (y : pgame), (∀ i, C (y.move_left i)) → (∀ j, C (y.move_right j)) → C y) : C x := x.rec_on $ λ yl yr yL yR, IH (mk yl yr yL yR) /-- `is_option x y` means that `x` is either a left or right option for `y`. -/ @[mk_iff] inductive is_option : pgame → pgame → Prop | move_left {x : pgame} (i : x.left_moves) : is_option (x.move_left i) x | move_right {x : pgame} (i : x.right_moves) : is_option (x.move_right i) x theorem is_option.mk_left {xl xr : Type u} (xL : xl → pgame) (xR : xr → pgame) (i : xl) : (xL i).is_option (mk xl xr xL xR) := @is_option.move_left (mk _ _ _ _) i theorem is_option.mk_right {xl xr : Type u} (xL : xl → pgame) (xR : xr → pgame) (i : xr) : (xR i).is_option (mk xl xr xL xR) := @is_option.move_right (mk _ _ _ _) i theorem wf_is_option : well_founded is_option := ⟨λ x, move_rec_on x $ λ x IHl IHr, acc.intro x $ λ y h, begin induction h with _ i _ j, { exact IHl i }, { exact IHr j } end⟩ /-- `subsequent x y` says that `x` can be obtained by playing some nonempty sequence of moves from `y`. It is the transitive closure of `is_option`. -/ def subsequent : pgame → pgame → Prop := trans_gen is_option instance : is_trans _ subsequent := trans_gen.is_trans @[trans] theorem subsequent.trans {x y z} : subsequent x y → subsequent y z → subsequent x z := trans_gen.trans theorem wf_subsequent : well_founded subsequent := wf_is_option.trans_gen instance : has_well_founded pgame := ⟨_, wf_subsequent⟩ lemma subsequent.move_left {x : pgame} (i : x.left_moves) : subsequent (x.move_left i) x := trans_gen.single (is_option.move_left i) lemma subsequent.move_right {x : pgame} (j : x.right_moves) : subsequent (x.move_right j) x := trans_gen.single (is_option.move_right j) lemma subsequent.mk_left {xl xr} (xL : xl → pgame) (xR : xr → pgame) (i : xl) : subsequent (xL i) (mk xl xr xL xR) := @subsequent.move_left (mk _ _ _ _) i lemma subsequent.mk_right {xl xr} (xL : xl → pgame) (xR : xr → pgame) (j : xr) : subsequent (xR j) (mk xl xr xL xR) := @subsequent.move_right (mk _ _ _ _) j /-- A local tactic for proving well-foundedness of recursive definitions involving pregames. -/ meta def pgame_wf_tac := `[solve_by_elim [psigma.lex.left, psigma.lex.right, subsequent.move_left, subsequent.move_right, subsequent.mk_left, subsequent.mk_right, subsequent.trans] { max_depth := 6 }] /-! ### Basic pre-games -/ /-- The pre-game `zero` is defined by `0 = { | }`. -/ instance : has_zero pgame := ⟨⟨pempty, pempty, pempty.elim, pempty.elim⟩⟩ @[simp] lemma zero_left_moves : left_moves 0 = pempty := rfl @[simp] lemma zero_right_moves : right_moves 0 = pempty := rfl instance is_empty_zero_left_moves : is_empty (left_moves 0) := pempty.is_empty instance is_empty_zero_right_moves : is_empty (right_moves 0) := pempty.is_empty instance : inhabited pgame := ⟨0⟩ /-- The pre-game `one` is defined by `1 = { 0 | }`. -/ instance : has_one pgame := ⟨⟨punit, pempty, λ _, 0, pempty.elim⟩⟩ @[simp] lemma one_left_moves : left_moves 1 = punit := rfl @[simp] lemma one_move_left (x) : move_left 1 x = 0 := rfl @[simp] lemma one_right_moves : right_moves 1 = pempty := rfl instance unique_one_left_moves : unique (left_moves 1) := punit.unique instance is_empty_one_right_moves : is_empty (right_moves 1) := pempty.is_empty /-! ### Pre-game order relations -/ /-- Define simultaneously by mutual induction the `≤` relation and its swapped converse `⧏` on pre-games. The ZFC definition says that `x = {xL | xR}` is less or equal to `y = {yL | yR}` if `∀ x₁ ∈ xL, x₁ ⧏ y` and `∀ y₂ ∈ yR, x ⧏ y₂`, where `x ⧏ y` means `¬ y ≤ x`. This is a tricky induction because it only decreases one side at a time, and it also swaps the arguments in the definition of `≤`. The solution is to define `x ≤ y` and `x ⧏ y` simultaneously. -/ def le_lf : Π (x y : pgame.{u}), Prop × Prop | (mk xl xr xL xR) (mk yl yr yL yR) := -- the orderings of the clauses here are carefully chosen so that -- and.left/or.inl refer to moves by Left, and -- and.right/or.inr refer to moves by Right. ((∀ i, (le_lf (xL i) ⟨yl, yr, yL, yR⟩).2) ∧ ∀ j, (le_lf ⟨xl, xr, xL, xR⟩ (yR j)).2, (∃ i, (le_lf ⟨xl, xr, xL, xR⟩ (yL i)).1) ∨ ∃ j, (le_lf (xR j) ⟨yl, yr, yL, yR⟩).1) using_well_founded { dec_tac := pgame_wf_tac } /-- The less or equal relation on pre-games. If `0 ≤ x`, then Left can win `x` as the second player. -/ instance : has_le pgame := ⟨λ x y, (le_lf x y).1⟩ /-- The less or fuzzy relation on pre-games. If `0 ⧏ x`, then Left can win `x` as the first player. -/ def lf (x y : pgame) : Prop := (le_lf x y).2 localized "infix (name := pgame.lf) ` ⧏ `:50 := pgame.lf" in pgame /-- Definition of `x ≤ y` on pre-games built using the constructor. -/ @[simp] theorem mk_le_mk {xl xr xL xR yl yr yL yR} : mk xl xr xL xR ≤ mk yl yr yL yR ↔ (∀ i, xL i ⧏ mk yl yr yL yR) ∧ ∀ j, mk xl xr xL xR ⧏ yR j := show (le_lf _ _).1 ↔ _, by { rw le_lf, refl } /-- Definition of `x ≤ y` on pre-games, in terms of `⧏` -/ theorem le_iff_forall_lf {x y : pgame} : x ≤ y ↔ (∀ i, x.move_left i ⧏ y) ∧ ∀ j, x ⧏ y.move_right j := by { cases x, cases y, exact mk_le_mk } theorem le_of_forall_lf {x y : pgame} (h₁ : ∀ i, x.move_left i ⧏ y) (h₂ : ∀ j, x ⧏ y.move_right j) : x ≤ y := le_iff_forall_lf.2 ⟨h₁, h₂⟩ /-- Definition of `x ⧏ y` on pre-games built using the constructor. -/ @[simp] theorem mk_lf_mk {xl xr xL xR yl yr yL yR} : mk xl xr xL xR ⧏ mk yl yr yL yR ↔ (∃ i, mk xl xr xL xR ≤ yL i) ∨ ∃ j, xR j ≤ mk yl yr yL yR := show (le_lf _ _).2 ↔ _, by { rw le_lf, refl } /-- Definition of `x ⧏ y` on pre-games, in terms of `≤` -/ theorem lf_iff_exists_le {x y : pgame} : x ⧏ y ↔ (∃ i, x ≤ y.move_left i) ∨ ∃ j, x.move_right j ≤ y := by { cases x, cases y, exact mk_lf_mk } private theorem not_le_lf {x y : pgame} : (¬ x ≤ y ↔ y ⧏ x) ∧ (¬ x ⧏ y ↔ y ≤ x) := begin induction x with xl xr xL xR IHxl IHxr generalizing y, induction y with yl yr yL yR IHyl IHyr, simp only [mk_le_mk, mk_lf_mk, IHxl, IHxr, IHyl, IHyr, not_and_distrib, not_or_distrib, not_forall, not_exists, and_comm, or_comm, iff_self, and_self] end @[simp] protected theorem not_le {x y : pgame} : ¬ x ≤ y ↔ y ⧏ x := not_le_lf.1 @[simp] theorem not_lf {x y : pgame} : ¬ x ⧏ y ↔ y ≤ x := not_le_lf.2 theorem _root_.has_le.le.not_gf {x y : pgame} : x ≤ y → ¬ y ⧏ x := not_lf.2 theorem lf.not_ge {x y : pgame} : x ⧏ y → ¬ y ≤ x := pgame.not_le.2 theorem le_or_gf (x y : pgame) : x ≤ y ∨ y ⧏ x := by { rw ←pgame.not_le, apply em } theorem move_left_lf_of_le {x y : pgame} (h : x ≤ y) (i) : x.move_left i ⧏ y := (le_iff_forall_lf.1 h).1 i alias move_left_lf_of_le ← _root_.has_le.le.move_left_lf theorem lf_move_right_of_le {x y : pgame} (h : x ≤ y) (j) : x ⧏ y.move_right j := (le_iff_forall_lf.1 h).2 j alias lf_move_right_of_le ← _root_.has_le.le.lf_move_right theorem lf_of_move_right_le {x y : pgame} {j} (h : x.move_right j ≤ y) : x ⧏ y := lf_iff_exists_le.2 $ or.inr ⟨j, h⟩ theorem lf_of_le_move_left {x y : pgame} {i} (h : x ≤ y.move_left i) : x ⧏ y := lf_iff_exists_le.2 $ or.inl ⟨i, h⟩ theorem lf_of_le_mk {xl xr xL xR y} : mk xl xr xL xR ≤ y → ∀ i, xL i ⧏ y := move_left_lf_of_le theorem lf_of_mk_le {x yl yr yL yR} : x ≤ mk yl yr yL yR → ∀ j, x ⧏ yR j := lf_move_right_of_le theorem mk_lf_of_le {xl xr y j} (xL) {xR : xr → pgame} : xR j ≤ y → mk xl xr xL xR ⧏ y := @lf_of_move_right_le (mk _ _ _ _) y j theorem lf_mk_of_le {x yl yr} {yL : yl → pgame} (yR) {i} : x ≤ yL i → x ⧏ mk yl yr yL yR := @lf_of_le_move_left x (mk _ _ _ _) i /- We prove that `x ≤ y → y ≤ z ← x ≤ z` inductively, by also simultaneously proving its cyclic reorderings. This auxiliary lemma is used during said induction. -/ private theorem le_trans_aux {x y z : pgame} (h₁ : ∀ {i}, y ≤ z → z ≤ x.move_left i → y ≤ x.move_left i) (h₂ : ∀ {j}, z.move_right j ≤ x → x ≤ y → z.move_right j ≤ y) (hxy : x ≤ y) (hyz : y ≤ z) : x ≤ z := le_of_forall_lf (λ i, pgame.not_le.1 $ λ h, (h₁ hyz h).not_gf $ hxy.move_left_lf i) (λ j, pgame.not_le.1 $ λ h, (h₂ h hxy).not_gf $ hyz.lf_move_right j) instance : has_lt pgame := ⟨λ x y, x ≤ y ∧ x ⧏ y⟩ instance : preorder pgame := { le_refl := λ x, begin induction x with _ _ _ _ IHl IHr, exact le_of_forall_lf (λ i, lf_of_le_move_left (IHl i)) (λ i, lf_of_move_right_le (IHr i)) end, le_trans := begin suffices : ∀ {x y z : pgame}, (x ≤ y → y ≤ z → x ≤ z) ∧ (y ≤ z → z ≤ x → y ≤ x) ∧ (z ≤ x → x ≤ y → z ≤ y), from λ x y z, this.1, intros x y z, induction x with xl xr xL xR IHxl IHxr generalizing y z, induction y with yl yr yL yR IHyl IHyr generalizing z, induction z with zl zr zL zR IHzl IHzr, exact ⟨le_trans_aux (λ i, (IHxl i).2.1) (λ j, (IHzr j).2.2), le_trans_aux (λ i, (IHyl i).2.2) (λ j, (IHxr j).1), le_trans_aux (λ i, (IHzl i).1) (λ j, (IHyr j).2.1)⟩ end, lt_iff_le_not_le := λ x y, by { rw pgame.not_le, refl }, ..pgame.has_le, ..pgame.has_lt } theorem lt_iff_le_and_lf {x y : pgame} : x < y ↔ x ≤ y ∧ x ⧏ y := iff.rfl theorem lt_of_le_of_lf {x y : pgame} (h₁ : x ≤ y) (h₂ : x ⧏ y) : x < y := ⟨h₁, h₂⟩ theorem lf_of_lt {x y : pgame} (h : x < y) : x ⧏ y := h.2 alias lf_of_lt ← _root_.has_lt.lt.lf theorem lf_irrefl (x : pgame) : ¬ x ⧏ x := le_rfl.not_gf instance : is_irrefl _ (⧏) := ⟨lf_irrefl⟩ @[trans] theorem lf_of_le_of_lf {x y z : pgame} (h₁ : x ≤ y) (h₂ : y ⧏ z) : x ⧏ z := by { rw ←pgame.not_le at h₂ ⊢, exact λ h₃, h₂ (h₃.trans h₁) } @[trans] theorem lf_of_lf_of_le {x y z : pgame} (h₁ : x ⧏ y) (h₂ : y ≤ z) : x ⧏ z := by { rw ←pgame.not_le at h₁ ⊢, exact λ h₃, h₁ (h₂.trans h₃) } alias lf_of_le_of_lf ← _root_.has_le.le.trans_lf alias lf_of_lf_of_le ← lf.trans_le @[trans] theorem lf_of_lt_of_lf {x y z : pgame} (h₁ : x < y) (h₂ : y ⧏ z) : x ⧏ z := h₁.le.trans_lf h₂ @[trans] theorem lf_of_lf_of_lt {x y z : pgame} (h₁ : x ⧏ y) (h₂ : y < z) : x ⧏ z := h₁.trans_le h₂.le alias lf_of_lt_of_lf ← _root_.has_lt.lt.trans_lf alias lf_of_lf_of_lt ← lf.trans_lt theorem move_left_lf {x : pgame} : ∀ i, x.move_left i ⧏ x := le_rfl.move_left_lf theorem lf_move_right {x : pgame} : ∀ j, x ⧏ x.move_right j := le_rfl.lf_move_right theorem lf_mk {xl xr} (xL : xl → pgame) (xR : xr → pgame) (i) : xL i ⧏ mk xl xr xL xR := @move_left_lf (mk _ _ _ _) i theorem mk_lf {xl xr} (xL : xl → pgame) (xR : xr → pgame) (j) : mk xl xr xL xR ⧏ xR j := @lf_move_right (mk _ _ _ _) j /-- This special case of `pgame.le_of_forall_lf` is useful when dealing with surreals, where `<` is preferred over `⧏`. -/ theorem le_of_forall_lt {x y : pgame} (h₁ : ∀ i, x.move_left i < y) (h₂ : ∀ j, x < y.move_right j) : x ≤ y := le_of_forall_lf (λ i, (h₁ i).lf) (λ i, (h₂ i).lf) /-- The definition of `x ≤ y` on pre-games, in terms of `≤` two moves later. -/ theorem le_def {x y : pgame} : x ≤ y ↔ (∀ i, (∃ i', x.move_left i ≤ y.move_left i') ∨ ∃ j, (x.move_left i).move_right j ≤ y) ∧ ∀ j, (∃ i, x ≤ (y.move_right j).move_left i) ∨ ∃ j', x.move_right j' ≤ y.move_right j := by { rw le_iff_forall_lf, conv { to_lhs, simp only [lf_iff_exists_le] } } /-- The definition of `x ⧏ y` on pre-games, in terms of `⧏` two moves later. -/ theorem lf_def {x y : pgame} : x ⧏ y ↔ (∃ i, (∀ i', x.move_left i' ⧏ y.move_left i) ∧ ∀ j, x ⧏ (y.move_left i).move_right j) ∨ ∃ j, (∀ i, (x.move_right j).move_left i ⧏ y) ∧ ∀ j', x.move_right j ⧏ y.move_right j' := by { rw lf_iff_exists_le, conv { to_lhs, simp only [le_iff_forall_lf] } } /-- The definition of `0 ≤ x` on pre-games, in terms of `0 ⧏`. -/ theorem zero_le_lf {x : pgame} : 0 ≤ x ↔ ∀ j, 0 ⧏ x.move_right j := by { rw le_iff_forall_lf, simp } /-- The definition of `x ≤ 0` on pre-games, in terms of `⧏ 0`. -/ theorem le_zero_lf {x : pgame} : x ≤ 0 ↔ ∀ i, x.move_left i ⧏ 0 := by { rw le_iff_forall_lf, simp } /-- The definition of `0 ⧏ x` on pre-games, in terms of `0 ≤`. -/ theorem zero_lf_le {x : pgame} : 0 ⧏ x ↔ ∃ i, 0 ≤ x.move_left i := by { rw lf_iff_exists_le, simp } /-- The definition of `x ⧏ 0` on pre-games, in terms of `≤ 0`. -/ theorem lf_zero_le {x : pgame} : x ⧏ 0 ↔ ∃ j, x.move_right j ≤ 0 := by { rw lf_iff_exists_le, simp } /-- The definition of `0 ≤ x` on pre-games, in terms of `0 ≤` two moves later. -/ theorem zero_le {x : pgame} : 0 ≤ x ↔ ∀ j, ∃ i, 0 ≤ (x.move_right j).move_left i := by { rw le_def, simp } /-- The definition of `x ≤ 0` on pre-games, in terms of `≤ 0` two moves later. -/ theorem le_zero {x : pgame} : x ≤ 0 ↔ ∀ i, ∃ j, (x.move_left i).move_right j ≤ 0 := by { rw le_def, simp } /-- The definition of `0 ⧏ x` on pre-games, in terms of `0 ⧏` two moves later. -/ theorem zero_lf {x : pgame} : 0 ⧏ x ↔ ∃ i, ∀ j, 0 ⧏ (x.move_left i).move_right j := by { rw lf_def, simp } /-- The definition of `x ⧏ 0` on pre-games, in terms of `⧏ 0` two moves later. -/ theorem lf_zero {x : pgame} : x ⧏ 0 ↔ ∃ j, ∀ i, (x.move_right j).move_left i ⧏ 0 := by { rw lf_def, simp } @[simp] theorem zero_le_of_is_empty_right_moves (x : pgame) [is_empty x.right_moves] : 0 ≤ x := zero_le.2 is_empty_elim @[simp] theorem le_zero_of_is_empty_left_moves (x : pgame) [is_empty x.left_moves] : x ≤ 0 := le_zero.2 is_empty_elim /-- Given a game won by the right player when they play second, provide a response to any move by left. -/ noncomputable def right_response {x : pgame} (h : x ≤ 0) (i : x.left_moves) : (x.move_left i).right_moves := classical.some $ (le_zero.1 h) i /-- Show that the response for right provided by `right_response` preserves the right-player-wins condition. -/ lemma right_response_spec {x : pgame} (h : x ≤ 0) (i : x.left_moves) : (x.move_left i).move_right (right_response h i) ≤ 0 := classical.some_spec $ (le_zero.1 h) i /-- Given a game won by the left player when they play second, provide a response to any move by right. -/ noncomputable def left_response {x : pgame} (h : 0 ≤ x) (j : x.right_moves) : (x.move_right j).left_moves := classical.some $ (zero_le.1 h) j /-- Show that the response for left provided by `left_response` preserves the left-player-wins condition. -/ lemma left_response_spec {x : pgame} (h : 0 ≤ x) (j : x.right_moves) : 0 ≤ (x.move_right j).move_left (left_response h j) := classical.some_spec $ (zero_le.1 h) j /-- The equivalence relation on pre-games. Two pre-games `x`, `y` are equivalent if `x ≤ y` and `y ≤ x`. If `x ≈ 0`, then the second player can always win `x`. -/ def equiv (x y : pgame) : Prop := x ≤ y ∧ y ≤ x localized "infix (name := pgame.equiv) ` ≈ ` := pgame.equiv" in pgame instance : is_equiv _ (≈) := { refl := λ x, ⟨le_rfl, le_rfl⟩, trans := λ x y z ⟨xy, yx⟩ ⟨yz, zy⟩, ⟨xy.trans yz, zy.trans yx⟩, symm := λ x y, and.symm } theorem equiv.le {x y : pgame} (h : x ≈ y) : x ≤ y := h.1 theorem equiv.ge {x y : pgame} (h : x ≈ y) : y ≤ x := h.2 @[refl, simp] theorem equiv_rfl {x} : x ≈ x := refl x theorem equiv_refl (x) : x ≈ x := refl x @[symm] protected theorem equiv.symm {x y} : x ≈ y → y ≈ x := symm @[trans] protected theorem equiv.trans {x y z} : x ≈ y → y ≈ z → x ≈ z := trans protected theorem equiv_comm {x y} : x ≈ y ↔ y ≈ x := comm theorem equiv_of_eq {x y} (h : x = y) : x ≈ y := by subst h @[trans] theorem le_of_le_of_equiv {x y z} (h₁ : x ≤ y) (h₂ : y ≈ z) : x ≤ z := h₁.trans h₂.1 @[trans] theorem le_of_equiv_of_le {x y z} (h₁ : x ≈ y) : y ≤ z → x ≤ z := h₁.1.trans theorem lf.not_equiv {x y} (h : x ⧏ y) : ¬ x ≈ y := λ h', h.not_ge h'.2 theorem lf.not_equiv' {x y} (h : x ⧏ y) : ¬ y ≈ x := λ h', h.not_ge h'.1 theorem lf.not_gt {x y} (h : x ⧏ y) : ¬ y < x := λ h', h.not_ge h'.le theorem le_congr_imp {x₁ y₁ x₂ y₂} (hx : x₁ ≈ x₂) (hy : y₁ ≈ y₂) (h : x₁ ≤ y₁) : x₂ ≤ y₂ := hx.2.trans (h.trans hy.1) theorem le_congr {x₁ y₁ x₂ y₂} (hx : x₁ ≈ x₂) (hy : y₁ ≈ y₂) : x₁ ≤ y₁ ↔ x₂ ≤ y₂ := ⟨le_congr_imp hx hy, le_congr_imp hx.symm hy.symm⟩ theorem le_congr_left {x₁ x₂ y} (hx : x₁ ≈ x₂) : x₁ ≤ y ↔ x₂ ≤ y := le_congr hx equiv_rfl theorem le_congr_right {x y₁ y₂} (hy : y₁ ≈ y₂) : x ≤ y₁ ↔ x ≤ y₂ := le_congr equiv_rfl hy theorem lf_congr {x₁ y₁ x₂ y₂} (hx : x₁ ≈ x₂) (hy : y₁ ≈ y₂) : x₁ ⧏ y₁ ↔ x₂ ⧏ y₂ := pgame.not_le.symm.trans $ (not_congr (le_congr hy hx)).trans pgame.not_le theorem lf_congr_imp {x₁ y₁ x₂ y₂} (hx : x₁ ≈ x₂) (hy : y₁ ≈ y₂) : x₁ ⧏ y₁ → x₂ ⧏ y₂ := (lf_congr hx hy).1 theorem lf_congr_left {x₁ x₂ y} (hx : x₁ ≈ x₂) : x₁ ⧏ y ↔ x₂ ⧏ y := lf_congr hx equiv_rfl theorem lf_congr_right {x y₁ y₂} (hy : y₁ ≈ y₂) : x ⧏ y₁ ↔ x ⧏ y₂ := lf_congr equiv_rfl hy @[trans] theorem lf_of_lf_of_equiv {x y z} (h₁ : x ⧏ y) (h₂ : y ≈ z) : x ⧏ z := lf_congr_imp equiv_rfl h₂ h₁ @[trans] theorem lf_of_equiv_of_lf {x y z} (h₁ : x ≈ y) : y ⧏ z → x ⧏ z := lf_congr_imp h₁.symm equiv_rfl @[trans] theorem lt_of_lt_of_equiv {x y z} (h₁ : x < y) (h₂ : y ≈ z) : x < z := h₁.trans_le h₂.1 @[trans] theorem lt_of_equiv_of_lt {x y z} (h₁ : x ≈ y) : y < z → x < z := h₁.1.trans_lt theorem lt_congr_imp {x₁ y₁ x₂ y₂} (hx : x₁ ≈ x₂) (hy : y₁ ≈ y₂) (h : x₁ < y₁) : x₂ < y₂ := hx.2.trans_lt (h.trans_le hy.1) theorem lt_congr {x₁ y₁ x₂ y₂} (hx : x₁ ≈ x₂) (hy : y₁ ≈ y₂) : x₁ < y₁ ↔ x₂ < y₂ := ⟨lt_congr_imp hx hy, lt_congr_imp hx.symm hy.symm⟩ theorem lt_congr_left {x₁ x₂ y} (hx : x₁ ≈ x₂) : x₁ < y ↔ x₂ < y := lt_congr hx equiv_rfl theorem lt_congr_right {x y₁ y₂} (hy : y₁ ≈ y₂) : x < y₁ ↔ x < y₂ := lt_congr equiv_rfl hy theorem lt_or_equiv_of_le {x y : pgame} (h : x ≤ y) : x < y ∨ x ≈ y := and_or_distrib_left.mp ⟨h, (em $ y ≤ x).swap.imp_left pgame.not_le.1⟩ theorem lf_or_equiv_or_gf (x y : pgame) : x ⧏ y ∨ x ≈ y ∨ y ⧏ x := begin by_cases h : x ⧏ y, { exact or.inl h }, { right, cases (lt_or_equiv_of_le (pgame.not_lf.1 h)) with h' h', { exact or.inr h'.lf }, { exact or.inl h'.symm } } end theorem equiv_congr_left {y₁ y₂} : y₁ ≈ y₂ ↔ ∀ x₁, x₁ ≈ y₁ ↔ x₁ ≈ y₂ := ⟨λ h x₁, ⟨λ h', h'.trans h, λ h', h'.trans h.symm⟩, λ h, (h y₁).1 $ equiv_rfl⟩ theorem equiv_congr_right {x₁ x₂} : x₁ ≈ x₂ ↔ ∀ y₁, x₁ ≈ y₁ ↔ x₂ ≈ y₁ := ⟨λ h y₁, ⟨λ h', h.symm.trans h', λ h', h.trans h'⟩, λ h, (h x₂).2 $ equiv_rfl⟩ theorem equiv_of_mk_equiv {x y : pgame} (L : x.left_moves ≃ y.left_moves) (R : x.right_moves ≃ y.right_moves) (hl : ∀ i, x.move_left i ≈ y.move_left (L i)) (hr : ∀ j, x.move_right j ≈ y.move_right (R j)) : x ≈ y := begin fsplit; rw le_def, { exact ⟨λ i, or.inl ⟨_, (hl i).1⟩, λ j, or.inr ⟨_, by simpa using (hr (R.symm j)).1⟩⟩ }, { exact ⟨λ i, or.inl ⟨_, by simpa using (hl (L.symm i)).2⟩, λ j, or.inr ⟨_, (hr j).2⟩⟩ } end /-- The fuzzy, confused, or incomparable relation on pre-games. If `x ∥ 0`, then the first player can always win `x`. -/ def fuzzy (x y : pgame) : Prop := x ⧏ y ∧ y ⧏ x localized "infix (name := pgame.fuzzy) ` ∥ `:50 := pgame.fuzzy" in pgame @[symm] theorem fuzzy.swap {x y : pgame} : x ∥ y → y ∥ x := and.swap instance : is_symm _ (∥) := ⟨λ x y, fuzzy.swap⟩ theorem fuzzy.swap_iff {x y : pgame} : x ∥ y ↔ y ∥ x := ⟨fuzzy.swap, fuzzy.swap⟩ theorem fuzzy_irrefl (x : pgame) : ¬ x ∥ x := λ h, lf_irrefl x h.1 instance : is_irrefl _ (∥) := ⟨fuzzy_irrefl⟩ theorem lf_iff_lt_or_fuzzy {x y : pgame} : x ⧏ y ↔ x < y ∨ x ∥ y := by { simp only [lt_iff_le_and_lf, fuzzy, ←pgame.not_le], tauto! } theorem lf_of_fuzzy {x y : pgame} (h : x ∥ y) : x ⧏ y := lf_iff_lt_or_fuzzy.2 (or.inr h) alias lf_of_fuzzy ← fuzzy.lf theorem lt_or_fuzzy_of_lf {x y : pgame} : x ⧏ y → x < y ∨ x ∥ y := lf_iff_lt_or_fuzzy.1 theorem fuzzy.not_equiv {x y : pgame} (h : x ∥ y) : ¬ x ≈ y := λ h', h'.1.not_gf h.2 theorem fuzzy.not_equiv' {x y : pgame} (h : x ∥ y) : ¬ y ≈ x := λ h', h'.2.not_gf h.2 theorem not_fuzzy_of_le {x y : pgame} (h : x ≤ y) : ¬ x ∥ y := λ h', h'.2.not_ge h theorem not_fuzzy_of_ge {x y : pgame} (h : y ≤ x) : ¬ x ∥ y := λ h', h'.1.not_ge h theorem equiv.not_fuzzy {x y : pgame} (h : x ≈ y) : ¬ x ∥ y := not_fuzzy_of_le h.1 theorem equiv.not_fuzzy' {x y : pgame} (h : x ≈ y) : ¬ y ∥ x := not_fuzzy_of_le h.2 theorem fuzzy_congr {x₁ y₁ x₂ y₂ : pgame} (hx : x₁ ≈ x₂) (hy : y₁ ≈ y₂) : x₁ ∥ y₁ ↔ x₂ ∥ y₂ := show _ ∧ _ ↔ _ ∧ _, by rw [lf_congr hx hy, lf_congr hy hx] theorem fuzzy_congr_imp {x₁ y₁ x₂ y₂ : pgame} (hx : x₁ ≈ x₂) (hy : y₁ ≈ y₂) : x₁ ∥ y₁ → x₂ ∥ y₂ := (fuzzy_congr hx hy).1 theorem fuzzy_congr_left {x₁ x₂ y} (hx : x₁ ≈ x₂) : x₁ ∥ y ↔ x₂ ∥ y := fuzzy_congr hx equiv_rfl theorem fuzzy_congr_right {x y₁ y₂} (hy : y₁ ≈ y₂) : x ∥ y₁ ↔ x ∥ y₂ := fuzzy_congr equiv_rfl hy @[trans] theorem fuzzy_of_fuzzy_of_equiv {x y z} (h₁ : x ∥ y) (h₂ : y ≈ z) : x ∥ z := (fuzzy_congr_right h₂).1 h₁ @[trans] theorem fuzzy_of_equiv_of_fuzzy {x y z} (h₁ : x ≈ y) (h₂ : y ∥ z) : x ∥ z := (fuzzy_congr_left h₁).2 h₂ /-- Exactly one of the following is true (although we don't prove this here). -/ theorem lt_or_equiv_or_gt_or_fuzzy (x y : pgame) : x < y ∨ x ≈ y ∨ y < x ∨ x ∥ y := begin cases le_or_gf x y with h₁ h₁; cases le_or_gf y x with h₂ h₂, { right, left, exact ⟨h₁, h₂⟩ }, { left, exact ⟨h₁, h₂⟩ }, { right, right, left, exact ⟨h₂, h₁⟩ }, { right, right, right, exact ⟨h₂, h₁⟩ } end theorem lt_or_equiv_or_gf (x y : pgame) : x < y ∨ x ≈ y ∨ y ⧏ x := begin rw [lf_iff_lt_or_fuzzy, fuzzy.swap_iff], exact lt_or_equiv_or_gt_or_fuzzy x y end /-! ### Relabellings -/ /-- `restricted x y` says that Left always has no more moves in `x` than in `y`, and Right always has no more moves in `y` than in `x` -/ inductive restricted : pgame.{u} → pgame.{u} → Type (u+1) | mk : Π {x y : pgame} (L : x.left_moves → y.left_moves) (R : y.right_moves → x.right_moves), (∀ i, restricted (x.move_left i) (y.move_left (L i))) → (∀ j, restricted (x.move_right (R j)) (y.move_right j)) → restricted x y /-- The identity restriction. -/ @[refl] def restricted.refl : Π (x : pgame), restricted x x | x := ⟨_, _, λ i, restricted.refl _, λ j, restricted.refl _⟩ using_well_founded { dec_tac := pgame_wf_tac } instance (x : pgame) : inhabited (restricted x x) := ⟨restricted.refl _⟩ /-- Transitivity of restriction. -/ def restricted.trans : Π {x y z : pgame} (r : restricted x y) (s : restricted y z), restricted x z | x y z ⟨L₁, R₁, hL₁, hR₁⟩ ⟨L₂, R₂, hL₂, hR₂⟩ := ⟨_, _, λ i, (hL₁ i).trans (hL₂ _), λ j, (hR₁ _).trans (hR₂ j)⟩ theorem restricted.le : Π {x y : pgame} (r : restricted x y), x ≤ y | x y ⟨L, R, hL, hR⟩ := le_def.2 ⟨λ i, or.inl ⟨L i, (hL i).le⟩, λ i, or.inr ⟨R i, (hR i).le⟩⟩ /-- `relabelling x y` says that `x` and `y` are really the same game, just dressed up differently. Specifically, there is a bijection between the moves for Left in `x` and in `y`, and similarly for Right, and under these bijections we inductively have `relabelling`s for the consequent games. -/ inductive relabelling : pgame.{u} → pgame.{u} → Type (u+1) | mk : Π {x y : pgame} (L : x.left_moves ≃ y.left_moves) (R : x.right_moves ≃ y.right_moves), (∀ i, relabelling (x.move_left i) (y.move_left (L i))) → (∀ j, relabelling (x.move_right j) (y.move_right (R j))) → relabelling x y localized "infix (name := pgame.relabelling) ` ≡r `:50 := pgame.relabelling" in pgame namespace relabelling variables {x y : pgame.{u}} /-- A constructor for relabellings swapping the equivalences. -/ def mk' (L : y.left_moves ≃ x.left_moves) (R : y.right_moves ≃ x.right_moves) (hL : ∀ i, x.move_left (L i) ≡r y.move_left i) (hR : ∀ j, x.move_right (R j) ≡r y.move_right j) : x ≡r y := ⟨L.symm, R.symm, λ i, by simpa using hL (L.symm i), λ j, by simpa using hR (R.symm j)⟩ /-- The equivalence between left moves of `x` and `y` given by the relabelling. -/ def left_moves_equiv : Π (r : x ≡r y), x.left_moves ≃ y.left_moves | ⟨L, R, hL, hR⟩ := L @[simp] theorem mk_left_moves_equiv {x y L R hL hR} : (@relabelling.mk x y L R hL hR).left_moves_equiv = L := rfl @[simp] theorem mk'_left_moves_equiv {x y L R hL hR} : (@relabelling.mk' x y L R hL hR).left_moves_equiv = L.symm := rfl /-- The equivalence between right moves of `x` and `y` given by the relabelling. -/ def right_moves_equiv : Π (r : x ≡r y), x.right_moves ≃ y.right_moves | ⟨L, R, hL, hR⟩ := R @[simp] theorem mk_right_moves_equiv {x y L R hL hR} : (@relabelling.mk x y L R hL hR).right_moves_equiv = R := rfl @[simp] theorem mk'_right_moves_equiv {x y L R hL hR} : (@relabelling.mk' x y L R hL hR).right_moves_equiv = R.symm := rfl /-- A left move of `x` is a relabelling of a left move of `y`. -/ def move_left : ∀ (r : x ≡r y) (i : x.left_moves), x.move_left i ≡r y.move_left (r.left_moves_equiv i) | ⟨L, R, hL, hR⟩ := hL /-- A left move of `y` is a relabelling of a left move of `x`. -/ def move_left_symm : ∀ (r : x ≡r y) (i : y.left_moves), x.move_left (r.left_moves_equiv.symm i) ≡r y.move_left i | ⟨L, R, hL, hR⟩ i := by simpa using hL (L.symm i) /-- A right move of `x` is a relabelling of a right move of `y`. -/ def move_right : ∀ (r : x ≡r y) (i : x.right_moves), x.move_right i ≡r y.move_right (r.right_moves_equiv i) | ⟨L, R, hL, hR⟩ := hR /-- A right move of `y` is a relabelling of a right move of `x`. -/ def move_right_symm : ∀ (r : x ≡r y) (i : y.right_moves), x.move_right (r.right_moves_equiv.symm i) ≡r y.move_right i | ⟨L, R, hL, hR⟩ i := by simpa using hR (R.symm i) /-- If `x` is a relabelling of `y`, then `x` is a restriction of `y`. -/ def restricted : Π {x y : pgame} (r : x ≡r y), restricted x y | x y r := ⟨_, _, λ i, (r.move_left i).restricted, λ j, (r.move_right_symm j).restricted⟩ using_well_founded { dec_tac := pgame_wf_tac } /-! It's not the case that `restricted x y → restricted y x → x ≡r y`, but if we insisted that the maps in a restriction were injective, then one could use Schröder-Bernstein for do this. -/ /-- The identity relabelling. -/ @[refl] def refl : Π (x : pgame), x ≡r x | x := ⟨equiv.refl _, equiv.refl _, λ i, refl _, λ j, refl _⟩ using_well_founded { dec_tac := pgame_wf_tac } instance (x : pgame) : inhabited (x ≡r x) := ⟨refl _⟩ /-- Flip a relabelling. -/ @[symm] def symm : Π {x y : pgame}, x ≡r y → y ≡r x | x y ⟨L, R, hL, hR⟩ := mk' L R (λ i, (hL i).symm) (λ j, (hR j).symm) theorem le (r : x ≡r y) : x ≤ y := r.restricted.le theorem ge (r : x ≡r y) : y ≤ x := r.symm.restricted.le /-- A relabelling lets us prove equivalence of games. -/ theorem equiv (r : x ≡r y) : x ≈ y := ⟨r.le, r.ge⟩ /-- Transitivity of relabelling. -/ @[trans] def trans : Π {x y z : pgame}, x ≡r y → y ≡r z → x ≡r z | x y z ⟨L₁, R₁, hL₁, hR₁⟩ ⟨L₂, R₂, hL₂, hR₂⟩ := ⟨L₁.trans L₂, R₁.trans R₂, λ i, (hL₁ i).trans (hL₂ _), λ j, (hR₁ j).trans (hR₂ _)⟩ /-- Any game without left or right moves is a relabelling of 0. -/ def is_empty (x : pgame) [is_empty x.left_moves] [is_empty x.right_moves] : x ≡r 0 := ⟨equiv.equiv_pempty _, equiv.equiv_of_is_empty _ _, is_empty_elim, is_empty_elim⟩ end relabelling theorem equiv.is_empty (x : pgame) [is_empty x.left_moves] [is_empty x.right_moves] : x ≈ 0 := (relabelling.is_empty x).equiv instance {x y : pgame} : has_coe (x ≡r y) (x ≈ y) := ⟨relabelling.equiv⟩ /-- Replace the types indexing the next moves for Left and Right by equivalent types. -/ def relabel {x : pgame} {xl' xr'} (el : xl' ≃ x.left_moves) (er : xr' ≃ x.right_moves) : pgame := ⟨xl', xr', x.move_left ∘ el, x.move_right ∘ er⟩ @[simp] lemma relabel_move_left' {x : pgame} {xl' xr'} (el : xl' ≃ x.left_moves) (er : xr' ≃ x.right_moves) (i : xl') : move_left (relabel el er) i = x.move_left (el i) := rfl @[simp] lemma relabel_move_left {x : pgame} {xl' xr'} (el : xl' ≃ x.left_moves) (er : xr' ≃ x.right_moves) (i : x.left_moves) : move_left (relabel el er) (el.symm i) = x.move_left i := by simp @[simp] lemma relabel_move_right' {x : pgame} {xl' xr'} (el : xl' ≃ x.left_moves) (er : xr' ≃ x.right_moves) (j : xr') : move_right (relabel el er) j = x.move_right (er j) := rfl @[simp] lemma relabel_move_right {x : pgame} {xl' xr'} (el : xl' ≃ x.left_moves) (er : xr' ≃ x.right_moves) (j : x.right_moves) : move_right (relabel el er) (er.symm j) = x.move_right j := by simp /-- The game obtained by relabelling the next moves is a relabelling of the original game. -/ def relabel_relabelling {x : pgame} {xl' xr'} (el : xl' ≃ x.left_moves) (er : xr' ≃ x.right_moves) : x ≡r relabel el er := relabelling.mk' el er (λ i, by simp) (λ j, by simp) /-! ### Negation -/ /-- The negation of `{L | R}` is `{-R | -L}`. -/ def neg : pgame → pgame | ⟨l, r, L, R⟩ := ⟨r, l, λ i, neg (R i), λ i, neg (L i)⟩ instance : has_neg pgame := ⟨neg⟩ @[simp] lemma neg_def {xl xr xL xR} : -(mk xl xr xL xR) = mk xr xl (λ j, -(xR j)) (λ i, -(xL i)) := rfl instance : has_involutive_neg pgame := { neg_neg := λ x, begin induction x with xl xr xL xR ihL ihR, simp_rw [neg_def, ihL, ihR], exact ⟨rfl, rfl, heq.rfl, heq.rfl⟩, end, ..pgame.has_neg } @[simp] protected lemma neg_zero : -(0 : pgame) = 0 := begin dsimp [has_zero.zero, has_neg.neg, neg], congr; funext i; cases i end @[simp] lemma neg_of_lists (L R : list pgame) : -of_lists L R = of_lists (R.map (λ x, -x)) (L.map (λ x, -x)) := begin simp only [of_lists, neg_def, list.length_map, list.nth_le_map', eq_self_iff_true, true_and], split, all_goals { apply hfunext, { simp }, { intros a a' ha, congr' 2, have : ∀ {m n} (h₁ : m = n) {b : ulift (fin m)} {c : ulift (fin n)} (h₂ : b == c), (b.down : ℕ) = ↑c.down, { rintros m n rfl b c rfl, refl }, exact this (list.length_map _ _).symm ha } } end theorem is_option_neg {x y : pgame} : is_option x (-y) ↔ is_option (-x) y := begin rw [is_option_iff, is_option_iff, or_comm], cases y, apply or_congr; { apply exists_congr, intro, rw ← neg_eq_iff_neg_eq, exact eq_comm }, end @[simp] theorem is_option_neg_neg {x y : pgame} : is_option (-x) (-y) ↔ is_option x y := by rw [is_option_neg, neg_neg] theorem left_moves_neg : ∀ x : pgame, (-x).left_moves = x.right_moves | ⟨_, _, _, _⟩ := rfl theorem right_moves_neg : ∀ x : pgame, (-x).right_moves = x.left_moves | ⟨_, _, _, _⟩ := rfl /-- Turns a right move for `x` into a left move for `-x` and vice versa. Even though these types are the same (not definitionally so), this is the preferred way to convert between them. -/ def to_left_moves_neg {x : pgame} : x.right_moves ≃ (-x).left_moves := equiv.cast (left_moves_neg x).symm /-- Turns a left move for `x` into a right move for `-x` and vice versa. Even though these types are the same (not definitionally so), this is the preferred way to convert between them. -/ def to_right_moves_neg {x : pgame} : x.left_moves ≃ (-x).right_moves := equiv.cast (right_moves_neg x).symm lemma move_left_neg {x : pgame} (i) : (-x).move_left (to_left_moves_neg i) = -x.move_right i := by { cases x, refl } @[simp] lemma move_left_neg' {x : pgame} (i) : (-x).move_left i = -x.move_right (to_left_moves_neg.symm i) := by { cases x, refl } lemma move_right_neg {x : pgame} (i) : (-x).move_right (to_right_moves_neg i) = -(x.move_left i) := by { cases x, refl } @[simp] lemma move_right_neg' {x : pgame} (i) : (-x).move_right i = -x.move_left (to_right_moves_neg.symm i) := by { cases x, refl } lemma move_left_neg_symm {x : pgame} (i) : x.move_left (to_right_moves_neg.symm i) = -(-x).move_right i := by simp lemma move_left_neg_symm' {x : pgame} (i) : x.move_left i = -(-x).move_right (to_right_moves_neg i) := by simp lemma move_right_neg_symm {x : pgame} (i) : x.move_right (to_left_moves_neg.symm i) = -(-x).move_left i := by simp lemma move_right_neg_symm' {x : pgame} (i) : x.move_right i = -(-x).move_left (to_left_moves_neg i) := by simp /-- If `x` has the same moves as `y`, then `-x` has the sames moves as `-y`. -/ def relabelling.neg_congr : ∀ {x y : pgame}, x ≡r y → -x ≡r -y | ⟨xl, xr, xL, xR⟩ ⟨yl, yr, yL, yR⟩ ⟨L, R, hL, hR⟩ := ⟨R, L, λ j, (hR j).neg_congr, λ i, (hL i).neg_congr⟩ private theorem neg_le_lf_neg_iff : Π {x y : pgame.{u}}, (-y ≤ -x ↔ x ≤ y) ∧ (-y ⧏ -x ↔ x ⧏ y) | (mk xl xr xL xR) (mk yl yr yL yR) := begin simp_rw [neg_def, mk_le_mk, mk_lf_mk, ← neg_def], split, { rw and_comm, apply and_congr; exact forall_congr (λ _, neg_le_lf_neg_iff.2) }, { rw or_comm, apply or_congr; exact exists_congr (λ _, neg_le_lf_neg_iff.1) }, end using_well_founded { dec_tac := pgame_wf_tac } @[simp] theorem neg_le_neg_iff {x y : pgame} : -y ≤ -x ↔ x ≤ y := neg_le_lf_neg_iff.1 @[simp] theorem neg_lf_neg_iff {x y : pgame} : -y ⧏ -x ↔ x ⧏ y := neg_le_lf_neg_iff.2 @[simp] theorem neg_lt_neg_iff {x y : pgame} : -y < -x ↔ x < y := by rw [lt_iff_le_and_lf, lt_iff_le_and_lf, neg_le_neg_iff, neg_lf_neg_iff] @[simp] theorem neg_equiv_neg_iff {x y : pgame} : -x ≈ -y ↔ x ≈ y := by rw [equiv, equiv, neg_le_neg_iff, neg_le_neg_iff, and.comm] @[simp] theorem neg_fuzzy_neg_iff {x y : pgame} : -x ∥ -y ↔ x ∥ y := by rw [fuzzy, fuzzy, neg_lf_neg_iff, neg_lf_neg_iff, and.comm] theorem neg_le_iff {x y : pgame} : -y ≤ x ↔ -x ≤ y := by rw [←neg_neg x, neg_le_neg_iff, neg_neg] theorem neg_lf_iff {x y : pgame} : -y ⧏ x ↔ -x ⧏ y := by rw [←neg_neg x, neg_lf_neg_iff, neg_neg] theorem neg_lt_iff {x y : pgame} : -y < x ↔ -x < y := by rw [←neg_neg x, neg_lt_neg_iff, neg_neg] theorem neg_equiv_iff {x y : pgame} : -x ≈ y ↔ x ≈ -y := by rw [←neg_neg y, neg_equiv_neg_iff, neg_neg] theorem neg_fuzzy_iff {x y : pgame} : -x ∥ y ↔ x ∥ -y := by rw [←neg_neg y, neg_fuzzy_neg_iff, neg_neg] theorem le_neg_iff {x y : pgame} : y ≤ -x ↔ x ≤ -y := by rw [←neg_neg x, neg_le_neg_iff, neg_neg] theorem lf_neg_iff {x y : pgame} : y ⧏ -x ↔ x ⧏ -y := by rw [←neg_neg x, neg_lf_neg_iff, neg_neg] theorem lt_neg_iff {x y : pgame} : y < -x ↔ x < -y := by rw [←neg_neg x, neg_lt_neg_iff, neg_neg] @[simp] theorem neg_le_zero_iff {x : pgame} : -x ≤ 0 ↔ 0 ≤ x := by rw [neg_le_iff, pgame.neg_zero] @[simp] theorem zero_le_neg_iff {x : pgame} : 0 ≤ -x ↔ x ≤ 0 := by rw [le_neg_iff, pgame.neg_zero] @[simp] theorem neg_lf_zero_iff {x : pgame} : -x ⧏ 0 ↔ 0 ⧏ x := by rw [neg_lf_iff, pgame.neg_zero] @[simp] theorem zero_lf_neg_iff {x : pgame} : 0 ⧏ -x ↔ x ⧏ 0 := by rw [lf_neg_iff, pgame.neg_zero] @[simp] theorem neg_lt_zero_iff {x : pgame} : -x < 0 ↔ 0 < x := by rw [neg_lt_iff, pgame.neg_zero] @[simp] theorem zero_lt_neg_iff {x : pgame} : 0 < -x ↔ x < 0 := by rw [lt_neg_iff, pgame.neg_zero] @[simp] theorem neg_equiv_zero_iff {x : pgame} : -x ≈ 0 ↔ x ≈ 0 := by rw [neg_equiv_iff, pgame.neg_zero] @[simp] theorem neg_fuzzy_zero_iff {x : pgame} : -x ∥ 0 ↔ x ∥ 0 := by rw [neg_fuzzy_iff, pgame.neg_zero] @[simp] theorem zero_equiv_neg_iff {x : pgame} : 0 ≈ -x ↔ 0 ≈ x := by rw [←neg_equiv_iff, pgame.neg_zero] @[simp] theorem zero_fuzzy_neg_iff {x : pgame} : 0 ∥ -x ↔ 0 ∥ x := by rw [←neg_fuzzy_iff, pgame.neg_zero] /-! ### Addition and subtraction -/ /-- The sum of `x = {xL | xR}` and `y = {yL | yR}` is `{xL + y, x + yL | xR + y, x + yR}`. -/ instance : has_add pgame.{u} := ⟨λ x y, begin induction x with xl xr xL xR IHxl IHxr generalizing y, induction y with yl yr yL yR IHyl IHyr, have y := mk yl yr yL yR, refine ⟨xl ⊕ yl, xr ⊕ yr, sum.rec _ _, sum.rec _ _⟩, { exact λ i, IHxl i y }, { exact IHyl }, { exact λ i, IHxr i y }, { exact IHyr } end⟩ /-- The pre-game `((0+1)+⋯)+1`. -/ instance : has_nat_cast pgame := ⟨nat.unary_cast⟩ @[simp] protected theorem nat_succ (n : ℕ) : ((n + 1 : ℕ) : pgame) = n + 1 := rfl instance is_empty_left_moves_add (x y : pgame.{u}) [is_empty x.left_moves] [is_empty y.left_moves] : is_empty (x + y).left_moves := begin unfreezingI { cases x, cases y }, apply is_empty_sum.2 ⟨_, _⟩, assumption' end instance is_empty_right_moves_add (x y : pgame.{u}) [is_empty x.right_moves] [is_empty y.right_moves] : is_empty (x + y).right_moves := begin unfreezingI { cases x, cases y }, apply is_empty_sum.2 ⟨_, _⟩, assumption' end /-- `x + 0` has exactly the same moves as `x`. -/ def add_zero_relabelling : Π (x : pgame.{u}), x + 0 ≡r x | ⟨xl, xr, xL, xR⟩ := begin refine ⟨equiv.sum_empty xl pempty, equiv.sum_empty xr pempty, _, _⟩; rintro (⟨i⟩|⟨⟨⟩⟩); apply add_zero_relabelling end /-- `x + 0` is equivalent to `x`. -/ lemma add_zero_equiv (x : pgame.{u}) : x + 0 ≈ x := (add_zero_relabelling x).equiv /-- `0 + x` has exactly the same moves as `x`. -/ def zero_add_relabelling : Π (x : pgame.{u}), 0 + x ≡r x | ⟨xl, xr, xL, xR⟩ := begin refine ⟨equiv.empty_sum pempty xl, equiv.empty_sum pempty xr, _, _⟩; rintro (⟨⟨⟩⟩|⟨i⟩); apply zero_add_relabelling end /-- `0 + x` is equivalent to `x`. -/ lemma zero_add_equiv (x : pgame.{u}) : 0 + x ≈ x := (zero_add_relabelling x).equiv theorem left_moves_add : ∀ (x y : pgame.{u}), (x + y).left_moves = (x.left_moves ⊕ y.left_moves) | ⟨_, _, _, _⟩ ⟨_, _, _, _⟩ := rfl theorem right_moves_add : ∀ (x y : pgame.{u}), (x + y).right_moves = (x.right_moves ⊕ y.right_moves) | ⟨_, _, _, _⟩ ⟨_, _, _, _⟩ := rfl /-- Converts a left move for `x` or `y` into a left move for `x + y` and vice versa. Even though these types are the same (not definitionally so), this is the preferred way to convert between them. -/ def to_left_moves_add {x y : pgame} : x.left_moves ⊕ y.left_moves ≃ (x + y).left_moves := equiv.cast (left_moves_add x y).symm /-- Converts a right move for `x` or `y` into a right move for `x + y` and vice versa. Even though these types are the same (not definitionally so), this is the preferred way to convert between them. -/ def to_right_moves_add {x y : pgame} : x.right_moves ⊕ y.right_moves ≃ (x + y).right_moves := equiv.cast (right_moves_add x y).symm @[simp] lemma mk_add_move_left_inl {xl xr yl yr} {xL xR yL yR} {i} : (mk xl xr xL xR + mk yl yr yL yR).move_left (sum.inl i) = (mk xl xr xL xR).move_left i + (mk yl yr yL yR) := rfl @[simp] lemma add_move_left_inl {x : pgame} (y : pgame) (i) : (x + y).move_left (to_left_moves_add (sum.inl i)) = x.move_left i + y := by { cases x, cases y, refl } @[simp] lemma mk_add_move_right_inl {xl xr yl yr} {xL xR yL yR} {i} : (mk xl xr xL xR + mk yl yr yL yR).move_right (sum.inl i) = (mk xl xr xL xR).move_right i + (mk yl yr yL yR) := rfl @[simp] lemma add_move_right_inl {x : pgame} (y : pgame) (i) : (x + y).move_right (to_right_moves_add (sum.inl i)) = x.move_right i + y := by { cases x, cases y, refl } @[simp] lemma mk_add_move_left_inr {xl xr yl yr} {xL xR yL yR} {i} : (mk xl xr xL xR + mk yl yr yL yR).move_left (sum.inr i) = (mk xl xr xL xR) + (mk yl yr yL yR).move_left i := rfl @[simp] lemma add_move_left_inr (x : pgame) {y : pgame} (i) : (x + y).move_left (to_left_moves_add (sum.inr i)) = x + y.move_left i := by { cases x, cases y, refl } @[simp] lemma mk_add_move_right_inr {xl xr yl yr} {xL xR yL yR} {i} : (mk xl xr xL xR + mk yl yr yL yR).move_right (sum.inr i) = (mk xl xr xL xR) + (mk yl yr yL yR).move_right i := rfl @[simp] lemma add_move_right_inr (x : pgame) {y : pgame} (i) : (x + y).move_right (to_right_moves_add (sum.inr i)) = x + y.move_right i := by { cases x, cases y, refl } lemma left_moves_add_cases {x y : pgame} (k) {P : (x + y).left_moves → Prop} (hl : ∀ i, P $ to_left_moves_add (sum.inl i)) (hr : ∀ i, P $ to_left_moves_add (sum.inr i)) : P k := begin rw ←to_left_moves_add.apply_symm_apply k, cases to_left_moves_add.symm k with i i, { exact hl i }, { exact hr i } end lemma right_moves_add_cases {x y : pgame} (k) {P : (x + y).right_moves → Prop} (hl : ∀ j, P $ to_right_moves_add (sum.inl j)) (hr : ∀ j, P $ to_right_moves_add (sum.inr j)) : P k := begin rw ←to_right_moves_add.apply_symm_apply k, cases to_right_moves_add.symm k with i i, { exact hl i }, { exact hr i } end instance is_empty_nat_right_moves : ∀ n : ℕ, is_empty (right_moves n) | 0 := pempty.is_empty | (n + 1) := begin haveI := is_empty_nat_right_moves n, rw [pgame.nat_succ, right_moves_add], apply_instance end /-- If `w` has the same moves as `x` and `y` has the same moves as `z`, then `w + y` has the same moves as `x + z`. -/ def relabelling.add_congr : ∀ {w x y z : pgame.{u}}, w ≡r x → y ≡r z → w + y ≡r x + z | ⟨wl, wr, wL, wR⟩ ⟨xl, xr, xL, xR⟩ ⟨yl, yr, yL, yR⟩ ⟨zl, zr, zL, zR⟩ ⟨L₁, R₁, hL₁, hR₁⟩ ⟨L₂, R₂, hL₂, hR₂⟩ := begin let Hwx : ⟨wl, wr, wL, wR⟩ ≡r ⟨xl, xr, xL, xR⟩ := ⟨L₁, R₁, hL₁, hR₁⟩, let Hyz : ⟨yl, yr, yL, yR⟩ ≡r ⟨zl, zr, zL, zR⟩ := ⟨L₂, R₂, hL₂, hR₂⟩, refine ⟨equiv.sum_congr L₁ L₂, equiv.sum_congr R₁ R₂, _, _⟩; rintro (i|j), { exact (hL₁ i).add_congr Hyz }, { exact Hwx.add_congr (hL₂ j) }, { exact (hR₁ i).add_congr Hyz }, { exact Hwx.add_congr (hR₂ j) } end using_well_founded { dec_tac := pgame_wf_tac } instance : has_sub pgame := ⟨λ x y, x + -y⟩ @[simp] theorem sub_zero (x : pgame) : x - 0 = x + 0 := show x + -0 = x + 0, by rw pgame.neg_zero /-- If `w` has the same moves as `x` and `y` has the same moves as `z`, then `w - y` has the same moves as `x - z`. -/ def relabelling.sub_congr {w x y z : pgame} (h₁ : w ≡r x) (h₂ : y ≡r z) : w - y ≡r x - z := h₁.add_congr h₂.neg_congr /-- `-(x + y)` has exactly the same moves as `-x + -y`. -/ def neg_add_relabelling : Π (x y : pgame), -(x + y) ≡r -x + -y | ⟨xl, xr, xL, xR⟩ ⟨yl, yr, yL, yR⟩ := begin refine ⟨equiv.refl _, equiv.refl _, _, _⟩, all_goals { exact λ j, sum.cases_on j (λ j, neg_add_relabelling _ _) (λ j, neg_add_relabelling ⟨xl, xr, xL, xR⟩ _) } end using_well_founded { dec_tac := pgame_wf_tac } theorem neg_add_le {x y : pgame} : -(x + y) ≤ -x + -y := (neg_add_relabelling x y).le /-- `x + y` has exactly the same moves as `y + x`. -/ def add_comm_relabelling : Π (x y : pgame.{u}), x + y ≡r y + x | (mk xl xr xL xR) (mk yl yr yL yR) := begin refine ⟨equiv.sum_comm _ _, equiv.sum_comm _ _, _, _⟩; rintros (_|_); { dsimp [left_moves_add, right_moves_add], apply add_comm_relabelling } end using_well_founded { dec_tac := pgame_wf_tac } theorem add_comm_le {x y : pgame} : x + y ≤ y + x := (add_comm_relabelling x y).le theorem add_comm_equiv {x y : pgame} : x + y ≈ y + x := (add_comm_relabelling x y).equiv /-- `(x + y) + z` has exactly the same moves as `x + (y + z)`. -/ def add_assoc_relabelling : Π (x y z : pgame.{u}), x + y + z ≡r x + (y + z) | ⟨xl, xr, xL, xR⟩ ⟨yl, yr, yL, yR⟩ ⟨zl, zr, zL, zR⟩ := begin refine ⟨equiv.sum_assoc _ _ _, equiv.sum_assoc _ _ _, _, _⟩, all_goals { rintro (⟨i|i⟩|i) <|> rintro (j|⟨j|j⟩), { apply add_assoc_relabelling }, { apply add_assoc_relabelling ⟨xl, xr, xL, xR⟩ }, { apply add_assoc_relabelling ⟨xl, xr, xL, xR⟩ ⟨yl, yr, yL, yR⟩ } } end using_well_founded { dec_tac := pgame_wf_tac } theorem add_assoc_equiv {x y z : pgame} : (x + y) + z ≈ x + (y + z) := (add_assoc_relabelling x y z).equiv theorem add_left_neg_le_zero : ∀ (x : pgame), -x + x ≤ 0 | ⟨xl, xr, xL, xR⟩ := le_zero.2 $ λ i, begin cases i, { -- If Left played in -x, Right responds with the same move in x. refine ⟨@to_right_moves_add _ ⟨_, _, _, _⟩ (sum.inr i), _⟩, convert @add_left_neg_le_zero (xR i), apply add_move_right_inr }, { -- If Left in x, Right responds with the same move in -x. dsimp, refine ⟨@to_right_moves_add ⟨_, _, _, _⟩ _ (sum.inl i), _⟩, convert @add_left_neg_le_zero (xL i), apply add_move_right_inl } end theorem zero_le_add_left_neg (x : pgame) : 0 ≤ -x + x := begin rw [←neg_le_neg_iff, pgame.neg_zero], exact neg_add_le.trans (add_left_neg_le_zero _) end theorem add_left_neg_equiv (x : pgame) : -x + x ≈ 0 := ⟨add_left_neg_le_zero x, zero_le_add_left_neg x⟩ theorem add_right_neg_le_zero (x : pgame) : x + -x ≤ 0 := add_comm_le.trans (add_left_neg_le_zero x) theorem zero_le_add_right_neg (x : pgame) : 0 ≤ x + -x := (zero_le_add_left_neg x).trans add_comm_le theorem add_right_neg_equiv (x : pgame) : x + -x ≈ 0 := ⟨add_right_neg_le_zero x, zero_le_add_right_neg x⟩ theorem sub_self_equiv : ∀ x, x - x ≈ 0 := add_right_neg_equiv private lemma add_le_add_right' : ∀ {x y z : pgame} (h : x ≤ y), x + z ≤ y + z | (mk xl xr xL xR) (mk yl yr yL yR) (mk zl zr zL zR) := λ h, begin refine le_def.2 ⟨λ i, _, λ i, _⟩; cases i, { rw le_def at h, cases h, rcases h_left i with ⟨i', ih⟩ | ⟨j, jh⟩, { exact or.inl ⟨to_left_moves_add (sum.inl i'), add_le_add_right' ih⟩ }, { refine or.inr ⟨to_right_moves_add (sum.inl j), _⟩, convert add_le_add_right' jh, apply add_move_right_inl } }, { exact or.inl ⟨@to_left_moves_add _ ⟨_, _, _, _⟩ (sum.inr i), add_le_add_right' h⟩ }, { rw le_def at h, cases h, rcases h_right i with ⟨i, ih⟩ | ⟨j', jh⟩, { refine or.inl ⟨to_left_moves_add (sum.inl i), _⟩, convert add_le_add_right' ih, apply add_move_left_inl }, { exact or.inr ⟨to_right_moves_add (sum.inl j'), add_le_add_right' jh⟩ } }, { exact or.inr ⟨@to_right_moves_add _ ⟨_, _, _, _⟩ (sum.inr i), add_le_add_right' h⟩ } end using_well_founded { dec_tac := pgame_wf_tac } instance covariant_class_swap_add_le : covariant_class pgame pgame (swap (+)) (≤) := ⟨λ x y z, add_le_add_right'⟩ instance covariant_class_add_le : covariant_class pgame pgame (+) (≤) := ⟨λ x y z h, (add_comm_le.trans (add_le_add_right h x)).trans add_comm_le⟩ theorem add_lf_add_right {y z : pgame} (h : y ⧏ z) (x) : y + x ⧏ z + x := suffices z + x ≤ y + x → z ≤ y, by { rw ←pgame.not_le at ⊢ h, exact mt this h }, λ w, calc z ≤ z + 0 : (add_zero_relabelling _).symm.le ... ≤ z + (x + -x) : add_le_add_left (zero_le_add_right_neg x) _ ... ≤ z + x + -x : (add_assoc_relabelling _ _ _).symm.le ... ≤ y + x + -x : add_le_add_right w _ ... ≤ y + (x + -x) : (add_assoc_relabelling _ _ _).le ... ≤ y + 0 : add_le_add_left (add_right_neg_le_zero x) _ ... ≤ y : (add_zero_relabelling _).le theorem add_lf_add_left {y z : pgame} (h : y ⧏ z) (x) : x + y ⧏ x + z := by { rw lf_congr add_comm_equiv add_comm_equiv, apply add_lf_add_right h } instance covariant_class_swap_add_lt : covariant_class pgame pgame (swap (+)) (<) := ⟨λ x y z h, ⟨add_le_add_right h.1 x, add_lf_add_right h.2 x⟩⟩ instance covariant_class_add_lt : covariant_class pgame pgame (+) (<) := ⟨λ x y z h, ⟨add_le_add_left h.1 x, add_lf_add_left h.2 x⟩⟩ theorem add_lf_add_of_lf_of_le {w x y z : pgame} (hwx : w ⧏ x) (hyz : y ≤ z) : w + y ⧏ x + z := lf_of_lf_of_le (add_lf_add_right hwx y) (add_le_add_left hyz x) theorem add_lf_add_of_le_of_lf {w x y z : pgame} (hwx : w ≤ x) (hyz : y ⧏ z) : w + y ⧏ x + z := lf_of_le_of_lf (add_le_add_right hwx y) (add_lf_add_left hyz x) theorem add_congr {w x y z : pgame} (h₁ : w ≈ x) (h₂ : y ≈ z) : w + y ≈ x + z := ⟨(add_le_add_left h₂.1 w).trans (add_le_add_right h₁.1 z), (add_le_add_left h₂.2 x).trans (add_le_add_right h₁.2 y)⟩ theorem add_congr_left {x y z : pgame} (h : x ≈ y) : x + z ≈ y + z := add_congr h equiv_rfl theorem add_congr_right {x y z : pgame} : y ≈ z → x + y ≈ x + z := add_congr equiv_rfl theorem sub_congr {w x y z : pgame} (h₁ : w ≈ x) (h₂ : y ≈ z) : w - y ≈ x - z := add_congr h₁ (neg_equiv_neg_iff.2 h₂) theorem sub_congr_left {x y z : pgame} (h : x ≈ y) : x - z ≈ y - z := sub_congr h equiv_rfl theorem sub_congr_right {x y z : pgame} : y ≈ z → x - y ≈ x - z := sub_congr equiv_rfl theorem le_iff_sub_nonneg {x y : pgame} : x ≤ y ↔ 0 ≤ y - x := ⟨λ h, (zero_le_add_right_neg x).trans (add_le_add_right h _), λ h, calc x ≤ 0 + x : (zero_add_relabelling x).symm.le ... ≤ y - x + x : add_le_add_right h _ ... ≤ y + (-x + x) : (add_assoc_relabelling _ _ _).le ... ≤ y + 0 : add_le_add_left (add_left_neg_le_zero x) _ ... ≤ y : (add_zero_relabelling y).le⟩ theorem lf_iff_sub_zero_lf {x y : pgame} : x ⧏ y ↔ 0 ⧏ y - x := ⟨λ h, (zero_le_add_right_neg x).trans_lf (add_lf_add_right h _), λ h, calc x ≤ 0 + x : (zero_add_relabelling x).symm.le ... ⧏ y - x + x : add_lf_add_right h _ ... ≤ y + (-x + x) : (add_assoc_relabelling _ _ _).le ... ≤ y + 0 : add_le_add_left (add_left_neg_le_zero x) _ ... ≤ y : (add_zero_relabelling y).le⟩ theorem lt_iff_sub_pos {x y : pgame} : x < y ↔ 0 < y - x := ⟨λ h, lt_of_le_of_lt (zero_le_add_right_neg x) (add_lt_add_right h _), λ h, calc x ≤ 0 + x : (zero_add_relabelling x).symm.le ... < y - x + x : add_lt_add_right h _ ... ≤ y + (-x + x) : (add_assoc_relabelling _ _ _).le ... ≤ y + 0 : add_le_add_left (add_left_neg_le_zero x) _ ... ≤ y : (add_zero_relabelling y).le⟩ /-! ### Special pre-games -/ /-- The pre-game `star`, which is fuzzy with zero. -/ def star : pgame.{u} := ⟨punit, punit, λ _, 0, λ _, 0⟩ @[simp] theorem star_left_moves : star.left_moves = punit := rfl @[simp] theorem star_right_moves : star.right_moves = punit := rfl @[simp] theorem star_move_left (x) : star.move_left x = 0 := rfl @[simp] theorem star_move_right (x) : star.move_right x = 0 := rfl instance unique_star_left_moves : unique star.left_moves := punit.unique instance unique_star_right_moves : unique star.right_moves := punit.unique theorem star_fuzzy_zero : star ∥ 0 := ⟨by { rw lf_zero, use default, rintros ⟨⟩ }, by { rw zero_lf, use default, rintros ⟨⟩ }⟩ @[simp] theorem neg_star : -star = star := by simp [star] @[simp] theorem zero_lt_one : (0 : pgame) < 1 := lt_of_le_of_lf (zero_le_of_is_empty_right_moves 1) (zero_lf_le.2 ⟨default, le_rfl⟩) instance : zero_le_one_class pgame := ⟨zero_lt_one.le⟩ @[simp] theorem zero_lf_one : (0 : pgame) ⧏ 1 := zero_lt_one.lf end pgame
25128938e8adb7b3ba672eddb30e429458d9a2c9
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Data/Json/FromToJson.lean
58dd8811dc35f915507416f3b2a8e72ebee36111
[ "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,312
lean
/- Copyright (c) 2019 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Marc Huisinga -/ import Lean.Data.Json.Basic import Lean.Data.Json.Printer namespace Lean universe u class FromJson (α : Type u) where fromJson? : Json → Except String α export FromJson (fromJson?) class ToJson (α : Type u) where toJson : α → Json export ToJson (toJson) instance : FromJson Json := ⟨Except.ok⟩ instance : ToJson Json := ⟨id⟩ instance : FromJson JsonNumber := ⟨Json.getNum?⟩ instance : ToJson JsonNumber := ⟨Json.num⟩ -- looks like id, but there are coercions happening instance : FromJson Bool := ⟨Json.getBool?⟩ instance : ToJson Bool := ⟨fun b => b⟩ instance : FromJson Nat := ⟨Json.getNat?⟩ instance : ToJson Nat := ⟨fun n => n⟩ instance : FromJson Int := ⟨Json.getInt?⟩ instance : ToJson Int := ⟨fun n => Json.num n⟩ instance : FromJson String := ⟨Json.getStr?⟩ instance : ToJson String := ⟨fun s => s⟩ instance : FromJson System.FilePath := ⟨fun j => System.FilePath.mk <$> Json.getStr? j⟩ instance : ToJson System.FilePath := ⟨fun p => p.toString⟩ instance [FromJson α] : FromJson (Array α) where fromJson? | Json.arr a => a.mapM fromJson? | j => throw s!"expected JSON array, got '{j}'" instance [ToJson α] : ToJson (Array α) := ⟨fun a => Json.arr (a.map toJson)⟩ instance [FromJson α] : FromJson (List α) where fromJson? j := (fromJson? j (α := Array α)).map Array.toList instance [ToJson α] : ToJson (List α) where toJson xs := toJson xs.toArray instance [FromJson α] : FromJson (Option α) where fromJson? | Json.null => Except.ok none | j => some <$> fromJson? j instance [ToJson α] : ToJson (Option α) := ⟨fun | none => Json.null | some a => toJson a⟩ instance [FromJson α] [FromJson β] : FromJson (α × β) where fromJson? | Json.arr #[ja, jb] => do let a ← fromJson? ja let b ← fromJson? jb return (a, b) | j => throw s!"expected pair, got '{j}'" instance [ToJson α] [ToJson β] : ToJson (α × β) where toJson := fun (a, b) => Json.arr #[toJson a, toJson b] instance : FromJson Name where fromJson? j := do let s ← j.getStr? if s == "[anonymous]" then return Name.anonymous else let some n ← Syntax.decodeNameLit ("`" ++ s) | throw s!"expected a `Name`, got '{j}'" return n instance : ToJson Name where toJson n := toString n /- Note that `USize`s and `UInt64`s are stored as strings because JavaScript cannot represent 64-bit numbers. -/ def bignumFromJson? (j : Json) : Except String Nat := do let s ← j.getStr? let some v ← Syntax.decodeNatLitVal? s -- TODO maybe this should be in Std | throw s!"expected a string-encoded number, got '{j}'" return v def bignumToJson (n : Nat) : Json := toString n instance : FromJson USize where fromJson? j := do let n ← bignumFromJson? j if n ≥ USize.size then throw "value '{j}' is too large for `USize`" return USize.ofNat n instance : ToJson USize where toJson v := bignumToJson (USize.toNat v) instance : FromJson UInt64 where fromJson? j := do let n ← bignumFromJson? j if n ≥ UInt64.size then throw "value '{j}' is too large for `UInt64`" return UInt64.ofNat n instance : ToJson UInt64 where toJson v := bignumToJson (UInt64.toNat v) namespace Json instance : FromJson Structured := ⟨fun | arr a => Structured.arr a | obj o => Structured.obj o | j => throw s!"expected structured object, got '{j}'"⟩ instance : ToJson Structured := ⟨fun | Structured.arr a => arr a | Structured.obj o => obj o⟩ def toStructured? [ToJson α] (v : α) : Except String Structured := fromJson? (toJson v) def getObjValAs? (j : Json) (α : Type u) [FromJson α] (k : String) : Except String α := fromJson? <| j.getObjValD k def opt [ToJson α] (k : String) : Option α → List (String × Json) | none => [] | some o => [⟨k, toJson o⟩] /-- Parses a JSON-encoded `structure` or `inductive` constructor. Used mostly by `deriving FromJson`. -/ def parseTagged (json : Json) (tag : String) (nFields : Nat) (fieldNames? : Option (Array Name)) : Except String (Array Json) := if nFields == 0 then match getStr? json with | Except.ok s => if s == tag then Except.ok #[] else throw s!"incorrect tag: {s} ≟ {tag}" | Except.error err => Except.error err else match getObjVal? json tag with | Except.ok payload => match fieldNames? with | some fieldNames => do let mut fields := #[] for fieldName in fieldNames do fields := fields.push (←getObjVal? payload fieldName.getString!) Except.ok fields | none => if nFields == 1 then Except.ok #[payload] else match getArr? payload with | Except.ok fields => if fields.size == nFields then Except.ok fields else Except.error s!"incorrect number of fields: {fields.size} ≟ {nFields}" | Except.error err => Except.error err | Except.error err => Except.error err end Json end Lean
43327265b48ff0cddcf1c60a94325f44493e9b7a
4727251e0cd73359b15b664c3170e5d754078599
/src/geometry/manifold/mfderiv.lean
6435272cf0b0c453859c07174b685cd669206345
[ "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
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.tangent_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 ∈ cont_diff_groupoid ∞ I := has_groupoid.compatible _ (chart_mem_atlas H x) h, have A : 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)) ∈ cont_diff_groupoid ∞ I := has_groupoid.compatible _ h (chart_mem_atlas H _), have A : 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 [continuous_linear_map.coe_coe, basic_smooth_vector_bundle_core.chart, h, tangent_bundle_core, basic_smooth_vector_bundle_core.to_topological_vector_bundle_core, chart_at, sigma.mk.inj_iff] 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_vector_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_vector_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_vector_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_vector_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_vector_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
f2f36fb9a7569aa347089437269aba77303bacb6
ed9ca7f44f366ca3a04272f939b2275961f36c59
/src/for_mathlib/quotient.lean
6bddc187127844c83db3ad64218f96ed9d31d09f
[ "Apache-2.0" ]
permissive
wh941231/lean-perfectoid-spaces
e88fb5d76746009242349f276cd0920285d8beb9
43954f64ce4afdf4fa39e2aeef8ec43826b24f2a
refs/heads/master
1,653,641,928,775
1,588,499,720,000
1,588,499,720,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,171
lean
import data.set.basic import data.quot import order.order_iso variables {α : Type*} {β : Type*} [s : setoid α] namespace setoid def comap (t : setoid β) (f : α → β) : setoid α := { r := _, iseqv := preimage_equivalence f t.iseqv } end setoid namespace quotient lemma prod_preimage_eq_image (g : quotient s → β) {h : α → β} (Hh : h = g ∘ quotient.mk) (r : set (β × β)) : {x : quotient s × quotient s | (g x.1, g x.2) ∈ r} = (λ a : α × α, (⟦a.1⟧, ⟦a.2⟧)) '' ((λ a : α × α, (h a.1, h a.2)) ⁻¹' r) := Hh.symm ▸ set.ext (λ ⟨a₁, a₂⟩, ⟨quotient.induction_on₂ a₁ a₂ (λ a₁ a₂ h, ⟨(a₁, a₂), h, rfl⟩), λ ⟨⟨b₁, b₂⟩, h₁, h₂⟩, show (g a₁, g a₂) ∈ r, from have h₃ : ⟦b₁⟧ = a₁ ∧ ⟦b₂⟧ = a₂ := prod.ext_iff.1 h₂, h₃.1 ▸ h₃.2 ▸ h₁⟩) end quotient lemma quot_mk_quotient_mk {α :Type*} [setoid α] (a : α) : quot.mk setoid.r a = ⟦a⟧ := rfl noncomputable def habitant_of_quotient_habitant {α : Type*} {s : setoid α} (x : quotient s) : α := (classical.inhabited_of_nonempty $ (nonempty_quotient_iff s).1 ⟨x⟩).default
be5771d7574e8a9bf34f250a8da36fb6d7fb5e48
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/analysis/normed_space/mazur_ulam.lean
547949c58ee359a909bcbaf2ce9c4a887ced8bc4
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,862
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import topology.instances.real_vector_space import analysis.normed_space.affine_isometry import linear_algebra.affine_space.midpoint /-! # Mazur-Ulam Theorem Mazur-Ulam theorem states that an isometric bijection between two normed affine spaces over `ℝ` is affine. We formalize it in three definitions: * `isometric.to_real_linear_isometry_equiv_of_map_zero` : given `E ≃ᵢ F` sending `0` to `0`, returns `E ≃ₗᵢ[ℝ] F` with the same `to_fun` and `inv_fun`; * `isometric.to_real_linear_isometry_equiv` : given `f : E ≃ᵢ F`, returns a linear isometry equivalence `g : E ≃ₗᵢ[ℝ] F` with `g x = f x - f 0`. * `isometric.to_real_affine_isometry_equiv` : given `f : PE ≃ᵢ PF`, returns an affine isometry equivalence `g : PE ≃ᵃⁱ[ℝ] PF` whose underlying `isometric` is `f` The formalization is based on [Jussi Väisälä, *A Proof of the Mazur-Ulam Theorem*][Vaisala_2003]. ## Tags isometry, affine map, linear map -/ variables {E PE : Type*} [normed_group E] [normed_space ℝ E] [metric_space PE] [normed_add_torsor E PE] {F PF : Type*} [normed_group F] [normed_space ℝ F] [metric_space PF] [normed_add_torsor F PF] open set affine_map affine_isometry_equiv noncomputable theory namespace isometric include E /-- If an isometric self-homeomorphism of a normed vector space over `ℝ` fixes `x` and `y`, then it fixes the midpoint of `[x, y]`. This is a lemma for a more general Mazur-Ulam theorem, see below. -/ lemma midpoint_fixed {x y : PE} : ∀ e : PE ≃ᵢ PE, e x = x → e y = y → e (midpoint ℝ x y) = midpoint ℝ x y := begin set z := midpoint ℝ x y, -- Consider the set of `e : E ≃ᵢ E` such that `e x = x` and `e y = y` set s := { e : PE ≃ᵢ PE | e x = x ∧ e y = y }, haveI : nonempty s := ⟨⟨isometric.refl PE, rfl, rfl⟩⟩, -- On the one hand, `e` cannot send the midpoint `z` of `[x, y]` too far have h_bdd : bdd_above (range $ λ e : s, dist (e z) z), { refine ⟨dist x z + dist x z, forall_range_iff.2 $ subtype.forall.2 _⟩, rintro e ⟨hx, hy⟩, calc dist (e z) z ≤ dist (e z) x + dist x z : dist_triangle (e z) x z ... = dist (e x) (e z) + dist x z : by rw [hx, dist_comm] ... = dist x z + dist x z : by erw [e.dist_eq x z] }, -- On the other hand, consider the map `f : (E ≃ᵢ E) → (E ≃ᵢ E)` -- sending each `e` to `R ∘ e⁻¹ ∘ R ∘ e`, where `R` is the point reflection in the -- midpoint `z` of `[x, y]`. set R : PE ≃ᵢ PE := (point_reflection ℝ z).to_isometric, set f : (PE ≃ᵢ PE) → (PE ≃ᵢ PE) := λ e, ((e.trans R).trans e.symm).trans R, -- Note that `f` doubles the value of ``dist (e z) z` have hf_dist : ∀ e, dist (f e z) z = 2 * dist (e z) z, { intro e, dsimp [f], rw [dist_point_reflection_fixed, ← e.dist_eq, e.apply_symm_apply, dist_point_reflection_self_real, dist_comm] }, -- Also note that `f` maps `s` to itself have hf_maps_to : maps_to f s s, { rintros e ⟨hx, hy⟩, split; simp [hx, hy, e.symm_apply_eq.2 hx.symm, e.symm_apply_eq.2 hy.symm], }, -- Therefore, `dist (e z) z = 0` for all `e ∈ s`. set c := ⨆ e : s, dist ((e : PE ≃ᵢ PE) z) z, have : c ≤ c / 2, { apply csupr_le, rintros ⟨e, he⟩, simp only [subtype.coe_mk, le_div_iff' (@zero_lt_two ℝ _ _), ← hf_dist], exact le_csupr h_bdd ⟨f e, hf_maps_to he⟩ }, replace : c ≤ 0, { linarith }, refine λ e hx hy, dist_le_zero.1 (le_trans _ this), exact le_csupr h_bdd ⟨e, hx, hy⟩ end include F /-- A bijective isometry sends midpoints to midpoints. -/ lemma map_midpoint (f : PE ≃ᵢ PF) (x y : PE) : f (midpoint ℝ x y) = midpoint ℝ (f x) (f y) := begin set e : PE ≃ᵢ PE := ((f.trans $ (point_reflection ℝ $ midpoint ℝ (f x) (f y)).to_isometric).trans f.symm).trans (point_reflection ℝ $ midpoint ℝ x y).to_isometric, have hx : e x = x, by simp, have hy : e y = y, by simp, have hm := e.midpoint_fixed hx hy, simp only [e, trans_apply] at hm, rwa [← eq_symm_apply, to_isometric_symm, point_reflection_symm, coe_to_isometric, coe_to_isometric, point_reflection_self, symm_apply_eq, point_reflection_fixed_iff] at hm end /-! Since `f : PE ≃ᵢ PF` sends midpoints to midpoints, it is an affine map. We define a conversion to a `continuous_linear_equiv` first, then a conversion to an `affine_map`. -/ /-- **Mazur-Ulam Theorem**: if `f` is an isometric bijection between two normed vector spaces over `ℝ` and `f 0 = 0`, then `f` is a linear isometry equivalence. -/ def to_real_linear_isometry_equiv_of_map_zero (f : E ≃ᵢ F) (h0 : f 0 = 0) : E ≃ₗᵢ[ℝ] F := { norm_map' := λ x, show ∥f x∥ = ∥x∥, by simp only [← dist_zero_right, ← h0, f.dist_eq], .. ((add_monoid_hom.of_map_midpoint ℝ ℝ f h0 f.map_midpoint).to_real_linear_map f.continuous), .. f } @[simp] lemma coe_to_real_linear_equiv_of_map_zero (f : E ≃ᵢ F) (h0 : f 0 = 0) : ⇑(f.to_real_linear_isometry_equiv_of_map_zero h0) = f := rfl @[simp] lemma coe_to_real_linear_equiv_of_map_zero_symm (f : E ≃ᵢ F) (h0 : f 0 = 0) : ⇑(f.to_real_linear_isometry_equiv_of_map_zero h0).symm = f.symm := rfl /-- **Mazur-Ulam Theorem**: if `f` is an isometric bijection between two normed vector spaces over `ℝ`, then `x ↦ f x - f 0` is a linear isometry equivalence. -/ def to_real_linear_isometry_equiv (f : E ≃ᵢ F) : E ≃ₗᵢ[ℝ] F := (f.trans (isometric.add_right (f 0)).symm).to_real_linear_isometry_equiv_of_map_zero (by simpa only [sub_eq_add_neg] using sub_self (f 0)) @[simp] lemma to_real_linear_equiv_apply (f : E ≃ᵢ F) (x : E) : (f.to_real_linear_isometry_equiv : E → F) x = f x - f 0 := (sub_eq_add_neg (f x) (f 0)).symm @[simp] lemma to_real_linear_isometry_equiv_symm_apply (f : E ≃ᵢ F) (y : F) : (f.to_real_linear_isometry_equiv.symm : F → E) y = f.symm (y + f 0) := rfl /-- **Mazur-Ulam Theorem**: if `f` is an isometric bijection between two normed add-torsors over normed vector spaces over `ℝ`, then `f` is an affine isometry equivalence. -/ def to_real_affine_isometry_equiv (f : PE ≃ᵢ PF) : PE ≃ᵃⁱ[ℝ] PF := affine_isometry_equiv.mk' f (((vadd_const ℝ (classical.arbitrary PE)).to_isometric.trans $ f.trans (vadd_const ℝ (f $ classical.arbitrary PE)).to_isometric.symm).to_real_linear_isometry_equiv) (classical.arbitrary PE) (λ p, by simp) @[simp] lemma coe_fn_to_real_affine_isometry_equiv (f : PE ≃ᵢ PF) : ⇑f.to_real_affine_isometry_equiv = f := rfl @[simp] lemma coe_to_real_affine_isometry_equiv (f : PE ≃ᵢ PF) : f.to_real_affine_isometry_equiv.to_isometric = f := by { ext, refl } end isometric
794167ac807f538f75f56273a1a101783957729c
0d107d7abd6ae235d586830f8e09b1b30e7eef0b
/src/square_perfect/Solution.lean
3a0c67f35eb3447ef0dec98a99f0f266086000e8
[]
no_license
ukikagi/codewars-lean
6b9a83ebbb159e7eebf8551b745a1c4d450e747f
1912f2a4e25e917abfce70d65c0469cfac19dc93
refs/heads/master
1,672,948,190,244
1,603,361,004,000
1,603,795,841,000
303,746,208
0
0
null
null
null
null
UTF-8
Lean
false
false
127
lean
import .Preloaded import tactic theorem expand : ∀ n : ℕ, (n + 1) ^ 2 = n ^ 2 + 2 * n + 1 := begin intro n, ring end
95991dc700aa9f3e7c2522c72d0feeae6322edbb
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/box_integral/partition/additive.lean
e93a40af017267b091237c1279b7e8315d001158
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
9,839
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.box_integral.partition.split import analysis.normed_space.operator_norm import data.set.intervals.proj_Icc /-! # Box additive functions We say that a function `f : box ι → M` from boxes in `ℝⁿ` to a commutative additive monoid `M` is *box additive* on subboxes of `I₀ : with_top (box ι)` if for any box `J`, `↑J ≤ I₀`, and a partition `π` of `J`, `f J = ∑ J' in π.boxes, f J'`. We use `I₀ : with_top (box ι)` instead of `I₀ : box ι` to use the same definition for functions box additive on subboxes of a box and for functions box additive on all boxes. Examples of box-additive functions include the measure of a box and the integral of a fixed integrable function over a box. In this file we define box-additive functions and prove that a function such that `f J = f (J ∩ {x | x i < y}) + f (J ∩ {x | y ≤ x i})` is box-additive. ### Tags rectangular box, additive function -/ noncomputable theory open_locale classical big_operators open function set namespace box_integral variables {ι M : Type*} {n : ℕ} /-- A function on `box ι` is called box additive if for every box `J` and a partition `π` of `J` we have `f J = ∑ Ji in π.boxes, f Ji`. A function is called box additive on subboxes of `I : box ι` if the same property holds for `J ≤ I`. We formalize these two notions in the same definition using `I : with_bot (box ι)`: the value `I = ⊤` corresponds to functions box additive on the whole space. -/ structure box_additive_map (ι M : Type*) [add_comm_monoid M] (I : with_top (box ι)) := (to_fun : box ι → M) (sum_partition_boxes' : ∀ J : box ι, ↑J ≤ I → ∀ π : prepartition J, π.is_partition → ∑ Ji in π.boxes, to_fun Ji = to_fun J) localized "notation (name := box_integral.box_additive_map.top) ι ` →ᵇᵃ `:25 M := box_integral.box_additive_map ι M ⊤" in box_integral localized "notation (name := box_integral.box_additive_map) ι ` →ᵇᵃ[`:25 I `] ` M := box_integral.box_additive_map ι M I" in box_integral namespace box_additive_map open box prepartition finset variables {N : Type*} [add_comm_monoid M] [add_comm_monoid N] {I₀ : with_top (box ι)} {I J : box ι} {i : ι} instance : has_coe_to_fun (ι →ᵇᵃ[I₀] M) (λ _, box ι → M) := ⟨to_fun⟩ initialize_simps_projections box_integral.box_additive_map (to_fun → apply) @[simp] lemma to_fun_eq_coe (f : ι →ᵇᵃ[I₀] M) : f.to_fun = f := rfl @[simp] lemma coe_mk (f h) : ⇑(mk f h : ι →ᵇᵃ[I₀] M) = f := rfl lemma coe_injective : injective (λ (f : ι →ᵇᵃ[I₀] M) x, f x) := by { rintro ⟨f, hf⟩ ⟨g, hg⟩ (rfl : f = g), refl } @[simp] lemma coe_inj {f g : ι →ᵇᵃ[I₀] M} : (f : box ι → M) = g ↔ f = g := coe_injective.eq_iff lemma sum_partition_boxes (f : ι →ᵇᵃ[I₀] M) (hI : ↑I ≤ I₀) {π : prepartition I} (h : π.is_partition) : ∑ J in π.boxes, f J = f I := f.sum_partition_boxes' I hI π h @[simps { fully_applied := ff }] instance : has_zero (ι →ᵇᵃ[I₀] M) := ⟨⟨0, λ I hI π hπ, sum_const_zero⟩⟩ instance : inhabited (ι →ᵇᵃ[I₀] M) := ⟨0⟩ instance : has_add (ι →ᵇᵃ[I₀] M) := ⟨λ f g, ⟨f + g, λ I hI π hπ, by simp only [pi.add_apply, sum_add_distrib, sum_partition_boxes _ hI hπ]⟩⟩ instance {R} [monoid R] [distrib_mul_action R M] : has_smul R (ι →ᵇᵃ[I₀] M) := ⟨λ r f, ⟨r • f, λ I hI π hπ, by simp only [pi.smul_apply, ←smul_sum, sum_partition_boxes _ hI hπ]⟩⟩ instance : add_comm_monoid (ι →ᵇᵃ[I₀] M) := function.injective.add_comm_monoid _ coe_injective rfl (λ _ _, rfl) (λ _ _, rfl) @[simp] lemma map_split_add (f : ι →ᵇᵃ[I₀] M) (hI : ↑I ≤ I₀) (i : ι) (x : ℝ) : (I.split_lower i x).elim 0 f + (I.split_upper i x).elim 0 f = f I := by rw [← f.sum_partition_boxes hI (is_partition_split I i x), sum_split_boxes] /-- If `f` is box-additive on subboxes of `I₀`, then it is box-additive on subboxes of any `I ≤ I₀`. -/ @[simps] def restrict (f : ι →ᵇᵃ[I₀] M) (I : with_top (box ι)) (hI : I ≤ I₀) : ι →ᵇᵃ[I] M := ⟨f, λ J hJ, f.2 J (hJ.trans hI)⟩ /-- If `f : box ι → M` is box additive on partitions of the form `split I i x`, then it is box additive. -/ def of_map_split_add [fintype ι] (f : box ι → M) (I₀ : with_top (box ι)) (hf : ∀ I : box ι, ↑I ≤ I₀ → ∀ {i x}, x ∈ Ioo (I.lower i) (I.upper i) → (I.split_lower i x).elim 0 f + (I.split_upper i x).elim 0 f = f I) : ι →ᵇᵃ[I₀] M := begin refine ⟨f, _⟩, replace hf : ∀ I : box ι, ↑I ≤ I₀ → ∀ s, ∑ J in (split_many I s).boxes, f J = f I, { intros I hI s, induction s using finset.induction_on with a s ha ihs, { simp }, rw [split_many_insert, inf_split, ← ihs, bUnion_boxes, sum_bUnion_boxes], refine finset.sum_congr rfl (λ J' hJ', _), by_cases h : a.2 ∈ Ioo (J'.lower a.1) (J'.upper a.1), { rw sum_split_boxes, exact hf _ ((with_top.coe_le_coe.2 $ le_of_mem _ hJ').trans hI) h }, { rw [split_of_not_mem_Ioo h, top_boxes, finset.sum_singleton] } }, intros I hI π hπ, have Hle : ∀ J ∈ π, ↑J ≤ I₀, from λ J hJ, (with_top.coe_le_coe.2 $ π.le_of_mem hJ).trans hI, rcases hπ.exists_split_many_le with ⟨s, hs⟩, rw [← hf _ hI, ← inf_of_le_right hs, inf_split_many, bUnion_boxes, sum_bUnion_boxes], exact finset.sum_congr rfl (λ J hJ, (hf _ (Hle _ hJ) _).symm) end /-- If `g : M → N` is an additive map and `f` is a box additive map, then `g ∘ f` is a box additive map. -/ @[simps { fully_applied := ff }] def map (f : ι →ᵇᵃ[I₀] M) (g : M →+ N) : ι →ᵇᵃ[I₀] N := { to_fun := g ∘ f, sum_partition_boxes' := λ I hI π hπ, by rw [← g.map_sum, f.sum_partition_boxes hI hπ] } /-- If `f` is a box additive function on subboxes of `I` and `π₁`, `π₂` are two prepartitions of `I` that cover the same part of `I`, then `∑ J in π₁.boxes, f J = ∑ J in π₂.boxes, f J`. -/ lemma sum_boxes_congr [finite ι] (f : ι →ᵇᵃ[I₀] M) (hI : ↑I ≤ I₀) {π₁ π₂ : prepartition I} (h : π₁.Union = π₂.Union) : ∑ J in π₁.boxes, f J = ∑ J in π₂.boxes, f J := begin rcases exists_split_many_inf_eq_filter_of_finite {π₁, π₂} ((finite_singleton _).insert _) with ⟨s, hs⟩, simp only [inf_split_many] at hs, rcases ⟨hs _ (or.inl rfl), hs _ (or.inr rfl)⟩ with ⟨h₁, h₂⟩, clear hs, rw h at h₁, calc ∑ J in π₁.boxes, f J = ∑ J in π₁.boxes, ∑ J' in (split_many J s).boxes, f J' : finset.sum_congr rfl (λ J hJ, (f.sum_partition_boxes _ (is_partition_split_many _ _)).symm) ... = ∑ J in (π₁.bUnion (λ J, split_many J s)).boxes, f J : (sum_bUnion_boxes _ _ _).symm ... = ∑ J in (π₂.bUnion (λ J, split_many J s)).boxes, f J : by rw [h₁, h₂] ... = ∑ J in π₂.boxes, ∑ J' in (split_many J s).boxes, f J' : sum_bUnion_boxes _ _ _ ... = ∑ J in π₂.boxes, f J : finset.sum_congr rfl (λ J hJ, (f.sum_partition_boxes _ (is_partition_split_many _ _))), exacts [(with_top.coe_le_coe.2 $ π₁.le_of_mem hJ).trans hI, (with_top.coe_le_coe.2 $ π₂.le_of_mem hJ).trans hI] end section to_smul variables {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] /-- If `f` is a box-additive map, then so is the map sending `I` to the scalar multiplication by `f I` as a continuous linear map from `E` to itself. -/ def to_smul (f : ι →ᵇᵃ[I₀] ℝ) : ι →ᵇᵃ[I₀] (E →L[ℝ] E) := f.map (continuous_linear_map.lsmul ℝ ℝ).to_linear_map.to_add_monoid_hom @[simp] lemma to_smul_apply (f : ι →ᵇᵃ[I₀] ℝ) (I : box ι) (x : E) : f.to_smul I x = f I • x := rfl end to_smul /-- Given a box `I₀` in `ℝⁿ⁺¹`, `f x : box (fin n) → G` is a family of functions indexed by a real `x` and for `x ∈ [I₀.lower i, I₀.upper i]`, `f x` is box-additive on subboxes of the `i`-th face of `I₀`, then `λ J, f (J.upper i) (J.face i) - f (J.lower i) (J.face i)` is box-additive on subboxes of `I₀`. -/ @[simps] def {u} upper_sub_lower {G : Type u} [add_comm_group G] (I₀ : box (fin (n + 1))) (i : fin (n + 1)) (f : ℝ → box (fin n) → G) (fb : Icc (I₀.lower i) (I₀.upper i) → fin n →ᵇᵃ[I₀.face i] G) (hf : ∀ x (hx : x ∈ Icc (I₀.lower i) (I₀.upper i)) J, f x J = fb ⟨x, hx⟩ J) : fin (n + 1) →ᵇᵃ[I₀] G := of_map_split_add (λ J : box (fin (n + 1)), f (J.upper i) (J.face i) - f (J.lower i) (J.face i)) I₀ begin intros J hJ j, rw with_top.coe_le_coe at hJ, refine i.succ_above_cases _ _ j, { intros x hx, simp only [box.split_lower_def hx, box.split_upper_def hx, update_same, ← with_bot.some_eq_coe, option.elim, box.face, (∘), update_noteq (fin.succ_above_ne _ _)], abel }, { clear j, intros j x hx, have : (J.face i : with_top (box (fin n))) ≤ I₀.face i, from with_top.coe_le_coe.2 (face_mono hJ i), rw [le_iff_Icc, @box.Icc_eq_pi _ I₀] at hJ, rw [hf _ (hJ J.upper_mem_Icc _ trivial), hf _ (hJ J.lower_mem_Icc _ trivial), ← (fb _).map_split_add this j x, ← (fb _).map_split_add this j x], have hx' : x ∈ Ioo ((J.face i).lower j) ((J.face i).upper j) := hx, simp only [box.split_lower_def hx, box.split_upper_def hx, box.split_lower_def hx', box.split_upper_def hx', ← with_bot.some_eq_coe, option.elim, box.face_mk, update_noteq (fin.succ_above_ne _ _).symm, sub_add_sub_comm, update_comp_eq_of_injective _ i.succ_above.injective j x, ← hf], simp only [box.face] } end end box_additive_map end box_integral
ed2b6f011db673f3edf1463ea6b5c63a0f6b9410
7b02c598aa57070b4cf4fbfe2416d0479220187f
/homotopy/realprojective.hlean
69306714d6b660c7e26e10c1f8c004b73ceedcb1
[ "Apache-2.0" ]
permissive
jdchristensen/Spectral
50d4f0ddaea1484d215ef74be951da6549de221d
6ded2b94d7ae07c4098d96a68f80a9cd3d433eb8
refs/heads/master
1,611,555,010,649
1,496,724,191,000
1,496,724,191,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,050
hlean
-- Based on Buchholtz-Rijke: Real projective spaces in HoTT -- Author: Ulrik Buchholtz import homotopy.join open eq nat susp pointed pmap sigma is_equiv equiv fiber is_trunc trunc trunc_index is_conn sphere_index bool unit join pushout definition of_is_contr (A : Type) : is_contr A → A := @center A definition sigma_unit_left' [constructor] (B : unit → Type) : (Σx, B x) ≃ B star := begin fapply equiv.MK, { intro w, induction w with u b, induction u, exact b }, { intro b, exact ⟨ star, b ⟩ }, { intro b, reflexivity }, { intro w, induction w with u b, induction u, reflexivity } end definition sigma_eq_equiv' {A : Type} (B : A → Type) (a₁ a₂ : A) (b₁ : B a₁) (b₂ : B a₂) : (⟨a₁, b₁⟩ = ⟨a₂, b₂⟩) ≃ (Σ(p : a₁ = a₂), p ▸ b₁ = b₂) := calc (⟨a₁, b₁⟩ = ⟨a₂, b₂⟩) ≃ Σ(p : a₁ = a₂), b₁ =[p] b₂ : sigma_eq_equiv ... ≃ Σ(p : a₁ = a₂), p ▸ b₁ = b₂ : by apply sigma_equiv_sigma_right; intro e; apply pathover_equiv_tr_eq definition dec_eq_is_prop [instance] (A : Type) : is_prop (decidable_eq A) := begin apply is_prop.mk, intros h k, apply eq_of_homotopy, intro a, apply eq_of_homotopy, intro b, apply decidable.rec_on (h a b), { intro p, apply decidable.rec_on (k a b), { intro q, apply ap decidable.inl, apply is_set.elim }, { intro q, exact absurd p q } }, { intro p, apply decidable.rec_on (k a b), { intro q, exact absurd q p }, { intro q, apply ap decidable.inr, apply is_prop.elim } } end definition dec_eq_bool : decidable_eq bool := begin intro a, induction a: intro b: induction b, { exact decidable.inl idp }, { exact decidable.inr ff_ne_tt }, { exact decidable.inr (λ p, ff_ne_tt p⁻¹) }, { exact decidable.inl idp } end definition lemma_II_4 {A B : Type₀} (a : A) (b : B) (e f : A ≃ B) (p : e a = b) (q : f a = b) : (⟨e, p⟩ = ⟨f, q⟩) ≃ Σ (h : e ~ f), p = h a ⬝ q := calc (⟨e, p⟩ = ⟨f, q⟩) ≃ Σ (h : e = f), h ▸ p = q : sigma_eq_equiv' ... ≃ Σ (h : e ~ f), p = h a ⬝ q : begin apply sigma_equiv_sigma ((equiv_eq_char e f) ⬝e eq_equiv_homotopy), intro h, induction h, esimp, change (p = q) ≃ (p = idp ⬝ q), rewrite idp_con end -- the type of two-element types structure BoolType := (carrier : Type₀) (bool_eq_carrier : ∥ bool = carrier ∥) attribute BoolType.carrier [coercion] -- the basepoint definition pointed_BoolType [instance] : pointed BoolType := pointed.mk (BoolType.mk bool (tr idp)) definition pBoolType : pType := pType.mk BoolType pt definition BoolType.sigma_char : BoolType ≃ { X : Type₀ | ∥ bool = X ∥ } := begin fapply equiv.MK: intro Xf: induction Xf with X f, { exact ⟨ X, f ⟩ }, { exact BoolType.mk X f }, { esimp }, { esimp } end definition BoolType.eq_equiv_equiv (A B : BoolType) : (A = B) ≃ (A ≃ B) := calc (A = B) ≃ (BoolType.sigma_char A = BoolType.sigma_char B) : eq_equiv_fn_eq_of_equiv ... ≃ (BoolType.carrier A = BoolType.carrier B) : begin induction A with A p, induction B with B q, symmetry, esimp, apply equiv_subtype end ... ≃ (A ≃ B) : eq_equiv_equiv A B definition lemma_II_3 {A B : BoolType} (a : A) (b : B) : (⟨A, a⟩ = ⟨B, b⟩) ≃ Σ (e : A ≃ B), e a = b := calc (⟨A, a⟩ = ⟨B, b⟩) ≃ Σ (e : A = B), e ▸ a = b : sigma_eq_equiv' ... ≃ Σ (e : A ≃ B), e a = b : begin apply sigma_equiv_sigma (BoolType.eq_equiv_equiv A B), intro e, induction e, unfold BoolType.eq_equiv_equiv, induction A with A p, esimp end definition theorem_II_2_lemma_1 (e : bool ≃ bool) (p : e tt = tt) : e ff = ff := sum.elim (dichotomy (e ff)) (λ q, q) begin intro q, apply empty.elim, apply ff_ne_tt, apply to_inv (eq_equiv_fn_eq_of_equiv e ff tt), exact q ⬝ p⁻¹, end definition theorem_II_2_lemma_2 (e : bool ≃ bool) (p : e tt = ff) : e ff = tt := sum.elim (dichotomy (e ff)) begin intro q, apply empty.elim, apply ff_ne_tt, apply to_inv (eq_equiv_fn_eq_of_equiv e ff tt), exact q ⬝ p⁻¹ end begin intro q, exact q end definition theorem_II_2 : is_contr (Σ (X : BoolType), X) := begin fapply is_contr.mk, { exact sigma.mk pt tt }, { intro w, induction w with Xf x, induction Xf with X f, apply to_inv (lemma_II_3 tt x), apply of_is_contr, induction f with f, induction f, induction x, { apply is_contr.mk ⟨ equiv_bnot, idp ⟩, intro w, induction w with e p, symmetry, apply to_inv (lemma_II_4 tt ff e equiv_bnot p idp), fapply sigma.mk, { intro b, induction b, { exact theorem_II_2_lemma_2 e p }, { exact p } }, { reflexivity } }, { apply is_contr.mk ⟨ erfl, idp ⟩, intro w, induction w with e p, symmetry, apply to_inv (lemma_II_4 tt tt e erfl p idp), fapply sigma.mk, { intro b, induction b, { exact theorem_II_2_lemma_1 e p }, { exact p } }, { reflexivity } } } end definition corollary_II_6 : Π A : BoolType, (pt = A) ≃ A := @total_space_method BoolType pt BoolType.carrier theorem_II_2 idp definition is_conn_BoolType [instance] : is_conn 0 BoolType := begin apply is_contr.mk (tr pt), intro X, induction X with X, induction X with X p, induction p with p, induction p, reflexivity end definition bool_type_dec_eq : Π (A : BoolType), decidable_eq A := @is_conn.is_conn.elim -1 pBoolType is_conn_BoolType (λ A : BoolType, decidable_eq A) _ dec_eq_bool definition alpha (A : BoolType) (x y : A) : bool := decidable.rec_on (bool_type_dec_eq A x y) (λ p, tt) (λ q, ff) definition alpha_inv (a b : bool) : alpha pt a (alpha pt a b) = b := begin induction a: induction b: esimp end definition is_equiv_alpha [instance] : Π {A : BoolType} (a : A), is_equiv (alpha A a) := begin apply @is_conn.elim -1 pBoolType is_conn_BoolType (λ A : BoolType, Π a : A, is_equiv (alpha A a)), intro a, exact adjointify (alpha pt a) (alpha pt a) (alpha_inv a) (alpha_inv a) end definition alpha_equiv (A : BoolType) (a : A) : A ≃ bool := equiv.mk (alpha A a) (is_equiv_alpha a) definition alpha_symm : Π (A : BoolType) (x y : A), alpha A x y = alpha A y x := begin apply @is_conn.elim -1 pBoolType is_conn_BoolType (λ A : BoolType, Π x y : A, alpha A x y = alpha A y x), intros x y, induction x: induction y: esimp end -- we define the type of types together with a line bundle structure two_cover := (carrier : Type₀) (cov : carrier → Type₀) (cov_eq : Π x : carrier, ∥ bool = cov x ∥ ) open two_cover definition empty_two_cover : two_cover := two_cover.mk empty empty.elim (empty.rec _) open sigma.ops definition two_cover_step (X : two_cover) : two_cover := begin fapply two_cover.mk, { exact pushout (@sigma.pr1 (carrier X) (cov X)) (λ x, star) }, { fapply pushout.elim_type, { intro x, exact cov X x }, { intro u, exact BoolType.carrier pt }, { intro w, exact alpha_equiv (BoolType.mk (cov X w.1) (cov_eq X w.1)) w.2 } }, { fapply pushout.rec, { intro x, exact cov_eq X x }, { intro u, exact tr idp }, { intro w, apply is_prop.elimo } } end definition realprojective_two_cover : ℕ₋₁ → two_cover := sphere_index.rec empty_two_cover (λ x, two_cover_step) definition realprojective : ℕ₋₁ → Type₀ := λ n, carrier (realprojective_two_cover n) definition realprojective_cov [reducible] (n : ℕ₋₁) : realprojective n → BoolType := λ x, BoolType.mk (cov (realprojective_two_cover n) x) (cov_eq (realprojective_two_cover n) x) definition theorem_III_3_u [reducible] (n : ℕ₋₁) : (Σ (w : Σ x, realprojective_cov n x), realprojective_cov n w.1) ≃ (Σ x, realprojective_cov n x) × bool := calc (Σ (w : Σ x, realprojective_cov n x), realprojective_cov n w.1) ≃ (Σ (w : Σ x, realprojective_cov n x), realprojective_cov n w.1) : sigma_assoc_comm_equiv ... ≃ Σ (w : Σ x, realprojective_cov n x), bool : @sigma_equiv_sigma_right (Σ x : realprojective n, realprojective_cov n x) (λ w, realprojective_cov n w.1) (λ w, bool) (λ w, alpha_equiv (realprojective_cov n w.1) w.2) ... ≃ (Σ x, realprojective_cov n x) × bool : equiv_prod definition theorem_III_3 (n : ℕ₋₁) : sphere n ≃ sigma (realprojective_cov n) := begin induction n with n IH, { symmetry, apply sigma_empty_left }, { apply equiv.trans (join.bool (sphere n))⁻¹ᵉ, apply equiv.trans (join.equiv_closed erfl IH), symmetry, refine equiv.trans _ !join.symm, apply equiv.trans !pushout.flattening, esimp, fapply pushout.equiv, { unfold function.compose, exact theorem_III_3_u n}, { reflexivity }, { exact sigma_unit_left' (λ u, bool) }, { unfold function.compose, esimp, intro w, induction w with w z, induction w with x y, reflexivity }, { unfold function.compose, esimp, intro w, induction w with w z, induction w with x y, exact alpha_symm (realprojective_cov n x) y z } } end
ca47ea739330338dbd4087bcd49b1023c3c9ee15
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/stage0/src/Lean/Parser.lean
d4aef2b861de5a0a8741420dc2b8773afbfebc18
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
7,221
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.Basic import Lean.Parser.Level import Lean.Parser.Term import Lean.Parser.Tactic import Lean.Parser.Command import Lean.Parser.Module import Lean.Parser.Syntax import Lean.Parser.Do namespace Lean namespace Parser open Lean.PrettyPrinter open Lean.PrettyPrinter.Parenthesizer open Lean.PrettyPrinter.Formatter builtin_initialize register_parser_alias "ws" checkWsBefore { stackSz? := some 0 } register_parser_alias "noWs" checkNoWsBefore { stackSz? := some 0 } register_parser_alias "linebreak" checkLinebreakBefore { stackSz? := some 0 } register_parser_alias (kind := numLitKind) "num" numLit register_parser_alias (kind := strLitKind) "str" strLit register_parser_alias (kind := charLitKind) "char" charLit register_parser_alias (kind := nameLitKind) "name" nameLit register_parser_alias (kind := scientificLitKind) "scientific" scientificLit register_parser_alias (kind := identKind) "ident" ident register_parser_alias "colGt" checkColGt { stackSz? := some 0 } register_parser_alias "colGe" checkColGe { stackSz? := some 0 } register_parser_alias "colEq" checkColEq { stackSz? := some 0 } register_parser_alias "lineEq" checkLineEq { stackSz? := some 0 } register_parser_alias lookahead { stackSz? := some 0 } register_parser_alias atomic { stackSz? := none } register_parser_alias many register_parser_alias many1 register_parser_alias manyIndent register_parser_alias many1Indent register_parser_alias optional { autoGroupArgs := false } register_parser_alias withPosition { stackSz? := none } register_parser_alias (kind := interpolatedStrKind) interpolatedStr register_parser_alias orelse register_parser_alias andthen { stackSz? := none } registerAlias "notFollowedBy" ``notFollowedBy (notFollowedBy · "element") Parenthesizer.registerAlias "notFollowedBy" notFollowedBy.parenthesizer Formatter.registerAlias "notFollowedBy" notFollowedBy.formatter end Parser namespace PrettyPrinter namespace Parenthesizer -- Close the mutual recursion loop; see corresponding `[extern]` in the parenthesizer. @[export lean_mk_antiquot_parenthesizer] def mkAntiquot.parenthesizer (name : String) (kind : SyntaxNodeKind) (anonymous := true) (isPseudoKind := true) : Parenthesizer := Parser.mkAntiquot.parenthesizer name kind anonymous isPseudoKind -- The parenthesizer auto-generated these instances correctly, but tagged them with the wrong kind, since the actual kind -- (e.g. `ident`) is not equal to the parser name `Lean.Parser.Term.ident`. @[builtinParenthesizer ident] def ident.parenthesizer : Parenthesizer := Parser.Term.ident.parenthesizer @[builtinParenthesizer num] def numLit.parenthesizer : Parenthesizer := Parser.Term.num.parenthesizer @[builtinParenthesizer scientific] def scientificLit.parenthesizer : Parenthesizer := Parser.Term.scientific.parenthesizer @[builtinParenthesizer char] def charLit.parenthesizer : Parenthesizer := Parser.Term.char.parenthesizer @[builtinParenthesizer str] def strLit.parenthesizer : Parenthesizer := Parser.Term.str.parenthesizer open Lean.Parser @[export lean_pretty_printer_parenthesizer_interpret_parser_descr] unsafe def interpretParserDescr : ParserDescr → CoreM Parenthesizer | ParserDescr.const n => getConstAlias parenthesizerAliasesRef n | ParserDescr.unary n d => return (← getUnaryAlias parenthesizerAliasesRef n) (← interpretParserDescr d) | ParserDescr.binary n d₁ d₂ => return (← getBinaryAlias parenthesizerAliasesRef n) (← interpretParserDescr d₁) (← interpretParserDescr d₂) | ParserDescr.node k prec d => return leadingNode.parenthesizer k prec (← interpretParserDescr d) | ParserDescr.nodeWithAntiquot _ k d => return node.parenthesizer k (← interpretParserDescr d) | ParserDescr.sepBy p sep psep trail => return sepBy.parenthesizer (← interpretParserDescr p) sep (← interpretParserDescr psep) trail | ParserDescr.sepBy1 p sep psep trail => return sepBy1.parenthesizer (← interpretParserDescr p) sep (← interpretParserDescr psep) trail | ParserDescr.trailingNode k prec lhsPrec d => return trailingNode.parenthesizer k prec lhsPrec (← interpretParserDescr d) | ParserDescr.symbol tk => return symbol.parenthesizer tk | ParserDescr.nonReservedSymbol tk includeIdent => return nonReservedSymbol.parenthesizer tk includeIdent | ParserDescr.parser constName => combinatorParenthesizerAttribute.runDeclFor constName | ParserDescr.cat catName prec => return categoryParser.parenthesizer catName prec end Parenthesizer namespace Formatter @[export lean_mk_antiquot_formatter] def mkAntiquot.formatter (name : String) (kind : SyntaxNodeKind) (anonymous := true) (isPseudoKind := true) : Formatter := Parser.mkAntiquot.formatter name kind anonymous isPseudoKind @[builtinFormatter ident] def ident.formatter : Formatter := Parser.Term.ident.formatter @[builtinFormatter num] def numLit.formatter : Formatter := Parser.Term.num.formatter @[builtinFormatter scientific] def scientificLit.formatter : Formatter := Parser.Term.scientific.formatter @[builtinFormatter char] def charLit.formatter : Formatter := Parser.Term.char.formatter @[builtinFormatter str] def strLit.formatter : Formatter := Parser.Term.str.formatter open Lean.Parser @[export lean_pretty_printer_formatter_interpret_parser_descr] unsafe def interpretParserDescr : ParserDescr → CoreM Formatter | ParserDescr.const n => getConstAlias formatterAliasesRef n | ParserDescr.unary n d => return (← getUnaryAlias formatterAliasesRef n) (← interpretParserDescr d) | ParserDescr.binary n d₁ d₂ => return (← getBinaryAlias formatterAliasesRef n) (← interpretParserDescr d₁) (← interpretParserDescr d₂) | ParserDescr.node k _ d => return node.formatter k (← interpretParserDescr d) | ParserDescr.nodeWithAntiquot _ k d => return node.formatter k (← interpretParserDescr d) | ParserDescr.sepBy p sep psep trail => return sepBy.formatter (← interpretParserDescr p) sep (← interpretParserDescr psep) trail | ParserDescr.sepBy1 p sep psep trail => return sepBy1.formatter (← interpretParserDescr p) sep (← interpretParserDescr psep) trail | ParserDescr.trailingNode k prec lhsPrec d => return trailingNode.formatter k prec lhsPrec (← interpretParserDescr d) | ParserDescr.symbol tk => return symbol.formatter tk | ParserDescr.nonReservedSymbol tk _ => return nonReservedSymbol.formatter tk | ParserDescr.parser constName => combinatorFormatterAttribute.runDeclFor constName | ParserDescr.cat catName _ => return categoryParser.formatter catName end Formatter end PrettyPrinter end Lean
765bc94208ea9a09fd3227108e2d7360c27be02b
6094e25ea0b7699e642463b48e51b2ead6ddc23f
/library/data/set/function.lean
bc718d1f802f12f7ac3ad7b6899e08a4ee68c834
[ "Apache-2.0" ]
permissive
gbaz/lean
a7835c4e3006fbbb079e8f8ffe18aacc45adebfb
a501c308be3acaa50a2c0610ce2e0d71becf8032
refs/heads/master
1,611,198,791,433
1,451,339,111,000
1,451,339,111,000
48,713,797
0
0
null
1,451,338,939,000
1,451,338,939,000
null
UTF-8
Lean
false
false
9,429
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Andrew Zipperer, Haitao Zhang Functions between subsets of finite types. -/ import .basic open function eq.ops namespace set variables {X Y Z : Type} /- maps to -/ definition maps_to [reducible] (f : X → Y) (a : set X) (b : set Y) : Prop := ∀⦃x⦄, x ∈ a → f x ∈ b theorem maps_to_of_eq_on {f1 f2 : X → Y} {a : set X} {b : set Y} (eq_on_a : eq_on f1 f2 a) (maps_to_f1 : maps_to f1 a b) : maps_to f2 a b := take x, assume xa : x ∈ a, have H : f1 x ∈ b, from maps_to_f1 xa, show f2 x ∈ b, from eq_on_a xa ▸ H theorem maps_to_compose {g : Y → Z} {f : X → Y} {a : set X} {b : set Y} {c : set Z} (H1 : maps_to g b c) (H2 : maps_to f a b) : maps_to (g ∘ f) a c := take x, assume H : x ∈ a, H1 (H2 H) theorem maps_to_univ_univ (f : X → Y) : maps_to f univ univ := take x, assume H, trivial theorem image_subset_of_maps_to {f : X → Y} {a : set X} {b : set Y} (mfab : maps_to f a b) {c : set X} (csuba : c ⊆ a) : f '[c] ⊆ b := take y, suppose y ∈ f '[c], obtain x [(xc : x ∈ c) (yeq : f x = y)], from this, have x ∈ a, from csuba `x ∈ c`, have f x ∈ b, from mfab this, show y ∈ b, from yeq ▸ this /- injectivity -/ definition inj_on [reducible] (f : X → Y) (a : set X) : Prop := ∀⦃x1 x2 : X⦄, x1 ∈ a → x2 ∈ a → f x1 = f x2 → x1 = x2 theorem inj_on_empty (f : X → Y) : inj_on f ∅ := take x₁ x₂, assume H₁ H₂ H₃, false.elim H₁ theorem inj_on_of_eq_on {f1 f2 : X → Y} {a : set X} (eq_f1_f2 : eq_on f1 f2 a) (inj_f1 : inj_on f1 a) : inj_on f2 a := take x1 x2 : X, assume ax1 : x1 ∈ a, assume ax2 : x2 ∈ a, assume H : f2 x1 = f2 x2, have H' : f1 x1 = f1 x2, from eq_f1_f2 ax1 ⬝ H ⬝ (eq_f1_f2 ax2)⁻¹, show x1 = x2, from inj_f1 ax1 ax2 H' theorem inj_on_compose {g : Y → Z} {f : X → Y} {a : set X} {b : set Y} (fab : maps_to f a b) (Hg : inj_on g b) (Hf: inj_on f a) : inj_on (g ∘ f) a := take x1 x2 : X, assume x1a : x1 ∈ a, assume x2a : x2 ∈ a, have fx1b : f x1 ∈ b, from fab x1a, have fx2b : f x2 ∈ b, from fab x2a, assume H1 : g (f x1) = g (f x2), have H2 : f x1 = f x2, from Hg fx1b fx2b H1, show x1 = x2, from Hf x1a x2a H2 theorem inj_on_of_inj_on_of_subset {f : X → Y} {a b : set X} (H1 : inj_on f b) (H2 : a ⊆ b) : inj_on f a := take x1 x2 : X, assume (x1a : x1 ∈ a) (x2a : x2 ∈ a), assume H : f x1 = f x2, show x1 = x2, from H1 (H2 x1a) (H2 x2a) H lemma injective_iff_inj_on_univ {f : X → Y} : injective f ↔ inj_on f univ := iff.intro (assume H, take x₁ x₂, assume ax₁ ax₂, H x₁ x₂) (assume H : inj_on f univ, take x₁ x₂ Heq, show x₁ = x₂, from H trivial trivial Heq) /- surjectivity -/ definition surj_on [reducible] (f : X → Y) (a : set X) (b : set Y) : Prop := b ⊆ f '[a] theorem surj_on_of_eq_on {f1 f2 : X → Y} {a : set X} {b : set Y} (eq_f1_f2 : eq_on f1 f2 a) (surj_f1 : surj_on f1 a b) : surj_on f2 a b := take y, assume H : y ∈ b, obtain x (H1 : x ∈ a ∧ f1 x = y), from surj_f1 H, have H2 : x ∈ a, from and.left H1, have H3 : f2 x = y, from (eq_f1_f2 H2)⁻¹ ⬝ and.right H1, exists.intro x (and.intro H2 H3) theorem surj_on_compose {g : Y → Z} {f : X → Y} {a : set X} {b : set Y} {c : set Z} (Hg : surj_on g b c) (Hf: surj_on f a b) : surj_on (g ∘ f) a c := take z, assume zc : z ∈ c, obtain y (H1 : y ∈ b ∧ g y = z), from Hg zc, obtain x (H2 : x ∈ a ∧ f x = y), from Hf (and.left H1), show ∃x, x ∈ a ∧ g (f x) = z, from exists.intro x (and.intro (and.left H2) (calc g (f x) = g y : {and.right H2} ... = z : and.right H1)) lemma surjective_iff_surj_on_univ {f : X → Y} : surjective f ↔ surj_on f univ univ := iff.intro (assume H, take y, assume Hy, obtain x Hx, from H y, mem_image trivial Hx) (assume H, take y, obtain x H1x H2x, from H y trivial, exists.intro x H2x) /- bijectivity -/ definition bij_on [reducible] (f : X → Y) (a : set X) (b : set Y) : Prop := maps_to f a b ∧ inj_on f a ∧ surj_on f a b theorem bij_on_of_eq_on {f1 f2 : X → Y} {a : set X} {b : set Y} (eqf : eq_on f1 f2 a) (H : bij_on f1 a b) : bij_on f2 a b := match H with and.intro Hmap (and.intro Hinj Hsurj) := and.intro (maps_to_of_eq_on eqf Hmap) (and.intro (inj_on_of_eq_on eqf Hinj) (surj_on_of_eq_on eqf Hsurj)) end theorem bij_on_compose {g : Y → Z} {f : X → Y} {a : set X} {b : set Y} {c : set Z} (Hg : bij_on g b c) (Hf: bij_on f a b) : bij_on (g ∘ f) a c := match Hg with and.intro Hgmap (and.intro Hginj Hgsurj) := match Hf with and.intro Hfmap (and.intro Hfinj Hfsurj) := and.intro (maps_to_compose Hgmap Hfmap) (and.intro (inj_on_compose Hfmap Hginj Hfinj) (surj_on_compose Hgsurj Hfsurj)) end end lemma bijective_iff_bij_on_univ {f : X → Y} : bijective f ↔ bij_on f univ univ := iff.intro (assume H, obtain Hinj Hsurj, from H, and.intro (maps_to_univ_univ f) (and.intro (iff.mp !injective_iff_inj_on_univ Hinj) (iff.mp !surjective_iff_surj_on_univ Hsurj))) (assume H, obtain Hmaps Hinj Hsurj, from H, (and.intro (iff.mpr !injective_iff_inj_on_univ Hinj) (iff.mpr !surjective_iff_surj_on_univ Hsurj))) /- left inverse -/ -- g is a left inverse to f on a definition left_inv_on [reducible] (g : Y → X) (f : X → Y) (a : set X) : Prop := ∀₀ x ∈ a, g (f x) = x theorem left_inv_on_of_eq_on_left {g1 g2 : Y → X} {f : X → Y} {a : set X} {b : set Y} (fab : maps_to f a b) (eqg : eq_on g1 g2 b) (H : left_inv_on g1 f a) : left_inv_on g2 f a := take x, assume xa : x ∈ a, calc g2 (f x) = g1 (f x) : (eqg (fab xa))⁻¹ ... = x : H xa theorem left_inv_on_of_eq_on_right {g : Y → X} {f1 f2 : X → Y} {a : set X} (eqf : eq_on f1 f2 a) (H : left_inv_on g f1 a) : left_inv_on g f2 a := take x, assume xa : x ∈ a, calc g (f2 x) = g (f1 x) : {(eqf xa)⁻¹} ... = x : H xa theorem inj_on_of_left_inv_on {g : Y → X} {f : X → Y} {a : set X} (H : left_inv_on g f a) : inj_on f a := take x1 x2, assume x1a : x1 ∈ a, assume x2a : x2 ∈ a, assume H1 : f x1 = f x2, calc x1 = g (f x1) : H x1a ... = g (f x2) : H1 ... = x2 : H x2a theorem left_inv_on_compose {f' : Y → X} {g' : Z → Y} {g : Y → Z} {f : X → Y} {a : set X} {b : set Y} (fab : maps_to f a b) (Hf : left_inv_on f' f a) (Hg : left_inv_on g' g b) : left_inv_on (f' ∘ g') (g ∘ f) a := take x : X, assume xa : x ∈ a, have fxb : f x ∈ b, from fab xa, calc f' (g' (g (f x))) = f' (f x) : Hg fxb ... = x : Hf xa /- right inverse -/ -- g is a right inverse to f on a definition right_inv_on [reducible] (g : Y → X) (f : X → Y) (b : set Y) : Prop := left_inv_on f g b theorem right_inv_on_of_eq_on_left {g1 g2 : Y → X} {f : X → Y} {a : set X} {b : set Y} (eqg : eq_on g1 g2 b) (H : right_inv_on g1 f b) : right_inv_on g2 f b := left_inv_on_of_eq_on_right eqg H theorem right_inv_on_of_eq_on_right {g : Y → X} {f1 f2 : X → Y} {a : set X} {b : set Y} (gba : maps_to g b a) (eqf : eq_on f1 f2 a) (H : right_inv_on g f1 b) : right_inv_on g f2 b := left_inv_on_of_eq_on_left gba eqf H theorem surj_on_of_right_inv_on {g : Y → X} {f : X → Y} {a : set X} {b : set Y} (gba : maps_to g b a) (H : right_inv_on g f b) : surj_on f a b := take y, assume yb : y ∈ b, have gya : g y ∈ a, from gba yb, have H1 : f (g y) = y, from H yb, exists.intro (g y) (and.intro gya H1) theorem right_inv_on_compose {f' : Y → X} {g' : Z → Y} {g : Y → Z} {f : X → Y} {c : set Z} {b : set Y} (g'cb : maps_to g' c b) (Hf : right_inv_on f' f b) (Hg : right_inv_on g' g c) : right_inv_on (f' ∘ g') (g ∘ f) c := left_inv_on_compose g'cb Hg Hf theorem right_inv_on_of_inj_on_of_left_inv_on {f : X → Y} {g : Y → X} {a : set X} {b : set Y} (fab : maps_to f a b) (gba : maps_to g b a) (injf : inj_on f a) (lfg : left_inv_on f g b) : right_inv_on f g a := take x, assume xa : x ∈ a, have H : f (g (f x)) = f x, from lfg (fab xa), injf (gba (fab xa)) xa H theorem eq_on_of_left_inv_of_right_inv {g1 g2 : Y → X} {f : X → Y} {a : set X} {b : set Y} (g2ba : maps_to g2 b a) (Hg1 : left_inv_on g1 f a) (Hg2 : right_inv_on g2 f b) : eq_on g1 g2 b := take y, assume yb : y ∈ b, calc g1 y = g1 (f (g2 y)) : {(Hg2 yb)⁻¹} ... = g2 y : Hg1 (g2ba yb) theorem left_inv_on_of_surj_on_right_inv_on {f : X → Y} {g : Y → X} {a : set X} {b : set Y} (surjf : surj_on f a b) (rfg : right_inv_on f g a) : left_inv_on f g b := take y, assume yb : y ∈ b, obtain x (xa : x ∈ a) (Hx : f x = y), from surjf yb, calc f (g y) = f (g (f x)) : Hx ... = f x : rfg xa ... = y : Hx /- inverses -/ -- g is an inverse to f viewed as a map from a to b definition inv_on [reducible] (g : Y → X) (f : X → Y) (a : set X) (b : set Y) : Prop := left_inv_on g f a ∧ right_inv_on g f b theorem bij_on_of_inv_on {g : Y → X} {f : X → Y} {a : set X} {b : set Y} (fab : maps_to f a b) (gba : maps_to g b a) (H : inv_on g f a b) : bij_on f a b := and.intro fab (and.intro (inj_on_of_left_inv_on (and.left H)) (surj_on_of_right_inv_on gba (and.right H))) end set
f59fdfcbf262a474f4c85202549bcb9af0a2e3e8
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/measure_theory/measure/hausdorff.lean
2dc564ba8aa829728505920a20a83be6a37282c7
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
43,625
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import topology.metric_space.metric_separated import measure_theory.constructions.borel_space import measure_theory.measure.lebesgue import analysis.special_functions.pow import topology.metric_space.holder import data.equiv.list /-! # Hausdorff measure and metric (outer) measures In this file we define the `d`-dimensional Hausdorff measure on an (extended) metric space `X` and the Hausdorff dimension of a set in an (extended) metric space. Let `μ d δ` be the maximal outer measure such that `μ d δ s ≤ (emetric.diam s) ^ d` for every set of diameter less than `δ`. Then the Hausdorff measure `μH[d] s` of `s` is defined as `⨆ δ > 0, μ d δ s`. By Caratheodory theorem `measure_theory.outer_measure.is_metric.borel_le_caratheodory`, this is a Borel measure on `X`. The value of `μH[d]`, `d > 0`, on a set `s` (measurable or not) is given by ``` μH[d] s = ⨆ (r : ℝ≥0∞) (hr : 0 < r), ⨅ (t : ℕ → set X) (hts : s ⊆ ⋃ n, t n) (ht : ∀ n, emetric.diam (t n) ≤ r), ∑' n, emetric.diam (t n) ^ d ``` For every set `s` for any `d < d'` we have either `μH[d] s = ∞` or `μH[d'] s = 0`, see `measure_theory.measure.hausdorff_measure_zero_or_top`. In `topology.metric_space.hausdorff_dimension` we use this fact to define the Hausdorff dimension `dimH` of a set in an (extended) metric space. We also define two generalizations of the Hausdorff measure. In one generalization (see `measure_theory.measure.mk_metric`) we take any function `m (diam s)` instead of `(diam s) ^ d`. In an even more general definition (see `measure_theory.measure.mk_metric'`) we use any function of `m : set X → ℝ≥0∞`. Some authors start with a partial function `m` defined only on some sets `s : set X` (e.g., only on balls or only on measurable sets). This is equivalent to our definition applied to `measure_theory.extend m`. We also define a predicate `measure_theory.outer_measure.is_metric` which says that an outer measure is additive on metric separated pairs of sets: `μ (s ∪ t) = μ s + μ t` provided that `⨅ (x ∈ s) (y ∈ t), edist x y ≠ 0`. This is the property required for the Caratheodory theorem `measure_theory.outer_measure.is_metric.borel_le_caratheodory`, so we prove this theorem for any metric outer measure, then prove that outer measures constructed using `mk_metric'` are metric outer measures. ## Main definitions * `measure_theory.outer_measure.is_metric`: an outer measure `μ` is called *metric* if `μ (s ∪ t) = μ s + μ t` for any two metric separated sets `s` and `t`. A metric outer measure in a Borel extended metric space is guaranteed to satisfy the Caratheodory condition, see `measure_theory.outer_measure.is_metric.borel_le_caratheodory`. * `measure_theory.outer_measure.mk_metric'` and its particular case `measure_theory.outer_measure.mk_metric`: a construction of an outer measure that is guaranteed to be metric. Both constructions are generalizations of the Hausdorff measure. The same measures interpreted as Borel measures are called `measure_theory.measure.mk_metric'` and `measure_theory.measure.mk_metric`. * `measure_theory.measure.hausdorff_measure` a.k.a. `μH[d]`: the `d`-dimensional Hausdorff measure. There are many definitions of the Hausdorff measure that differ from each other by a multiplicative constant. We put `μH[d] s = ⨆ r > 0, ⨅ (t : ℕ → set X) (hts : s ⊆ ⋃ n, t n) (ht : ∀ n, emetric.diam (t n) ≤ r), ∑' n, ⨆ (ht : ¬set.subsingleton (t n)), (emetric.diam (t n)) ^ d`, see `measure_theory.measure.hausdorff_measure_apply'`. In the most interesting case `0 < d` one can omit the `⨆ (ht : ¬set.subsingleton (t n))` part. ## Main statements ### Basic properties * `measure_theory.outer_measure.is_metric.borel_le_caratheodory`: if `μ` is a metric outer measure on an extended metric space `X` (that is, it is additive on pairs of metric separated sets), then every Borel set is Caratheodory measurable (hence, `μ` defines an actual `measure_theory.measure`). See also `measure_theory.measure.mk_metric`. * `measure_theory.measure.hausdorff_measure_mono`: `μH[d] s` is an antitone function of `d`. * `measure_theory.measure.hausdorff_measure_zero_or_top`: if `d₁ < d₂`, then for any `s`, either `μH[d₂] s = 0` or `μH[d₁] s = ∞`. Together with the previous lemma, this means that `μH[d] s` is equal to infinity on some ray `(-∞, D)` and is equal to zero on `(D, +∞)`, where `D` is a possibly infinite number called the *Hausdorff dimension* of `s`; `μH[D] s` can be zero, infinity, or anything in between. * `measure_theory.measure.no_atoms_hausdorff`: Hausdorff measure has no atoms. ### Hausdorff measure in `ℝⁿ` * `measure_theory.hausdorff_measure_pi_real`: for a nonempty `ι`, `μH[card ι]` on `ι → ℝ` equals Lebesgue measure. ## Notations We use the following notation localized in `measure_theory`. - `μH[d]` : `measure_theory.measure.hausdorff_measure d` ## Implementation notes There are a few similar constructions called the `d`-dimensional Hausdorff measure. E.g., some sources only allow coverings by balls and use `r ^ d` instead of `(diam s) ^ d`. While these construction lead to different Hausdorff measures, they lead to the same notion of the Hausdorff dimension. Some sources define the `0`-dimensional Hausdorff measure to be the counting measure. We define it to be zero on subsingletons because this way we can have a `measure.has_no_atoms (measure.hausdorff_measure d)` instance. ## TODO * prove that `1`-dimensional Hausdorff measure on `ℝ` equals `volume`; * prove a similar statement for `ℝ × ℝ`. ## References * [Herbert Federer, Geometric Measure Theory, Chapter 2.10][Federer1996] ## Tags Hausdorff measure, measure, metric measure -/ open_locale nnreal ennreal topological_space big_operators open emetric set function filter encodable finite_dimensional topological_space noncomputable theory variables {ι X Y : Type*} [emetric_space X] [emetric_space Y] namespace measure_theory namespace outer_measure /-! ### Metric outer measures In this section we define metric outer measures and prove Caratheodory theorem: a metric outer measure has the Caratheodory property. -/ /-- We say that an outer measure `μ` in an (e)metric space is *metric* if `μ (s ∪ t) = μ s + μ t` for any two metric separated sets `s`, `t`. -/ def is_metric (μ : outer_measure X) : Prop := ∀ (s t : set X), is_metric_separated s t → μ (s ∪ t) = μ s + μ t namespace is_metric variables {μ : outer_measure X} /-- A metric outer measure is additive on a finite set of pairwise metric separated sets. -/ lemma finset_Union_of_pairwise_separated (hm : is_metric μ) {I : finset ι} {s : ι → set X} (hI : ∀ (i ∈ I) (j ∈ I), i ≠ j → is_metric_separated (s i) (s j)) : μ (⋃ i ∈ I, s i) = ∑ i in I, μ (s i) := begin classical, induction I using finset.induction_on with i I hiI ihI hI, { simp }, simp only [finset.mem_insert] at hI, rw [finset.set_bUnion_insert, hm, ihI, finset.sum_insert hiI], exacts [λ i hi j hj hij, (hI i (or.inr hi) j (or.inr hj) hij), is_metric_separated.finset_Union_right (λ j hj, hI i (or.inl rfl) j (or.inr hj) (ne_of_mem_of_not_mem hj hiI).symm)] end /-- Caratheodory theorem. If `m` is a metric outer measure, then every Borel measurable set `t` is Caratheodory measurable: for any (not necessarily measurable) set `s` we have `μ (s ∩ t) + μ (s \ t) = μ s`. -/ lemma borel_le_caratheodory (hm : is_metric μ) : borel X ≤ μ.caratheodory := begin rw [borel_eq_generate_from_is_closed], refine measurable_space.generate_from_le (λ t ht, μ.is_caratheodory_iff_le.2 $ λ s, _), set S : ℕ → set X := λ n, {x ∈ s | (↑n)⁻¹ ≤ inf_edist x t}, have n0 : ∀ {n : ℕ}, (n⁻¹ : ℝ≥0∞) ≠ 0, from λ n, ennreal.inv_ne_zero.2 ennreal.coe_nat_ne_top, have Ssep : ∀ n, is_metric_separated (S n) t, from λ n, ⟨n⁻¹, n0, λ x hx y hy, hx.2.trans $ inf_edist_le_edist_of_mem hy⟩, have Ssep' : ∀ n, is_metric_separated (S n) (s ∩ t), from λ n, (Ssep n).mono subset.rfl (inter_subset_right _ _), have S_sub : ∀ n, S n ⊆ s \ t, from λ n, subset_inter (inter_subset_left _ _) (Ssep n).subset_compl_right, have hSs : ∀ n, μ (s ∩ t) + μ (S n) ≤ μ s, from λ n, calc μ (s ∩ t) + μ (S n) = μ (s ∩ t ∪ S n) : eq.symm $ hm _ _ $ (Ssep' n).symm ... ≤ μ (s ∩ t ∪ s \ t) : by { mono*, exact le_rfl } ... = μ s : by rw [inter_union_diff], have Union_S : (⋃ n, S n) = s \ t, { refine subset.antisymm (Union_subset S_sub) _, rintro x ⟨hxs, hxt⟩, rw mem_iff_inf_edist_zero_of_closed ht at hxt, rcases ennreal.exists_inv_nat_lt hxt with ⟨n, hn⟩, exact mem_Union.2 ⟨n, hxs, hn.le⟩ }, /- Now we have `∀ n, μ (s ∩ t) + μ (S n) ≤ μ s` and we need to prove `μ (s ∩ t) + μ (⋃ n, S n) ≤ μ s`. We can't pass to the limit because `μ` is only an outer measure. -/ by_cases htop : μ (s \ t) = ∞, { rw [htop, ennreal.add_top, ← htop], exact μ.mono (diff_subset _ _) }, suffices : μ (⋃ n, S n) ≤ ⨆ n, μ (S n), calc μ (s ∩ t) + μ (s \ t) = μ (s ∩ t) + μ (⋃ n, S n) : by rw Union_S ... ≤ μ (s ∩ t) + ⨆ n, μ (S n) : add_le_add le_rfl this ... = ⨆ n, μ (s ∩ t) + μ (S n) : ennreal.add_supr ... ≤ μ s : supr_le hSs, /- It suffices to show that `∑' k, μ (S (k + 1) \ S k) ≠ ∞`. Indeed, if we have this, then for all `N` we have `μ (⋃ n, S n) ≤ μ (S N) + ∑' k, m (S (N + k + 1) \ S (N + k))` and the second term tends to zero, see `outer_measure.Union_nat_of_monotone_of_tsum_ne_top` for details. -/ have : ∀ n, S n ⊆ S (n + 1), from λ n x hx, ⟨hx.1, le_trans (ennreal.inv_le_inv.2 $ ennreal.coe_nat_le_coe_nat.2 n.le_succ) hx.2⟩, refine (μ.Union_nat_of_monotone_of_tsum_ne_top this _).le, clear this, /- While the sets `S (k + 1) \ S k` are not pairwise metric separated, the sets in each subsequence `S (2 * k + 1) \ S (2 * k)` and `S (2 * k + 2) \ S (2 * k)` are metric separated, so `m` is additive on each of those sequences. -/ rw [← tsum_even_add_odd ennreal.summable ennreal.summable, ennreal.add_ne_top], suffices : ∀ a, (∑' (k : ℕ), μ (S (2 * k + 1 + a) \ S (2 * k + a))) ≠ ∞, from ⟨by simpa using this 0, by simpa using this 1⟩, refine λ r, ne_top_of_le_ne_top htop _, rw [← Union_S, ennreal.tsum_eq_supr_nat, supr_le_iff], intro n, rw [← hm.finset_Union_of_pairwise_separated], { exact μ.mono (Union_subset $ λ i, Union_subset $ λ hi x hx, mem_Union.2 ⟨_, hx.1⟩) }, suffices : ∀ i j, i < j → is_metric_separated (S (2 * i + 1 + r)) (s \ S (2 * j + r)), from λ i _ j _ hij, hij.lt_or_lt.elim (λ h, (this i j h).mono (inter_subset_left _ _) (λ x hx, ⟨hx.1.1, hx.2⟩)) (λ h, (this j i h).symm.mono (λ x hx, ⟨hx.1.1, hx.2⟩) (inter_subset_left _ _)), intros i j hj, have A : ((↑(2 * j + r))⁻¹ : ℝ≥0∞) < (↑(2 * i + 1 + r))⁻¹, by { rw [ennreal.inv_lt_inv, ennreal.coe_nat_lt_coe_nat], linarith }, refine ⟨(↑(2 * i + 1 + r))⁻¹ - (↑(2 * j + r))⁻¹, by simpa using A, λ x hx y hy, _⟩, have : inf_edist y t < (↑(2 * j + r))⁻¹, from not_le.1 (λ hle, hy.2 ⟨hy.1, hle⟩), rcases exists_edist_lt_of_inf_edist_lt this with ⟨z, hzt, hyz⟩, have hxz : (↑(2 * i + 1 + r))⁻¹ ≤ edist x z, from le_inf_edist.1 hx.2 _ hzt, apply ennreal.le_of_add_le_add_right hyz.ne_top, refine le_trans _ (edist_triangle _ _ _), refine (add_le_add le_rfl hyz.le).trans (eq.trans_le _ hxz), rw [ennreal.sub_add_cancel_of_le A.le] end lemma le_caratheodory [measurable_space X] [borel_space X] (hm : is_metric μ) : ‹measurable_space X› ≤ μ.caratheodory := by { rw @borel_space.measurable_eq X _ _, exact hm.borel_le_caratheodory } end is_metric /-! ### Constructors of metric outer measures In this section we provide constructors `measure_theory.outer_measure.mk_metric'` and `measure_theory.outer_measure.mk_metric` and prove that these outer measures are metric outer measures. We also prove basic lemmas about `map`/`comap` of these measures. -/ /-- Auxiliary definition for `outer_measure.mk_metric'`: given a function on sets `m : set X → ℝ≥0∞`, returns the maximal outer measure `μ` such that `μ s ≤ m s` for any set `s` of diameter at most `r`.-/ def mk_metric'.pre (m : set X → ℝ≥0∞) (r : ℝ≥0∞) : outer_measure X := bounded_by $ extend (λ s (hs : diam s ≤ r), m s) /-- Given a function `m : set X → ℝ≥0∞`, `mk_metric' m` is the supremum of `mk_metric'.pre m r` over `r > 0`. Equivalently, it is the limit of `mk_metric'.pre m r` as `r` tends to zero from the right. -/ def mk_metric' (m : set X → ℝ≥0∞) : outer_measure X := ⨆ r > 0, mk_metric'.pre m r /-- Given a function `m : ℝ≥0∞ → ℝ≥0∞` and `r > 0`, let `μ r` be the maximal outer measure such that `μ s = 0` on subsingletons and `μ s ≤ m (emetric.diam s)` whenever `emetric.diam s < r`. Then `mk_metric m = ⨆ r > 0, μ r`. We add `⨆ (hs : ¬s.subsingleton)` to ensure that in the case `m x = x ^ d` the definition gives the expected result for `d = 0`. -/ def mk_metric (m : ℝ≥0∞ → ℝ≥0∞) : outer_measure X := mk_metric' (λ s, ⨆ (hs : ¬s.subsingleton), m (diam s)) namespace mk_metric' variables {m : set X → ℝ≥0∞} {r : ℝ≥0∞} {μ : outer_measure X} {s : set X} lemma le_pre : μ ≤ pre m r ↔ ∀ s : set X, diam s ≤ r → μ s ≤ m s := by simp only [pre, le_bounded_by, extend, le_infi_iff] lemma pre_le (hs : diam s ≤ r) : pre m r s ≤ m s := (bounded_by_le _).trans $ infi_le _ hs lemma mono_pre (m : set X → ℝ≥0∞) {r r' : ℝ≥0∞} (h : r ≤ r') : pre m r' ≤ pre m r := le_pre.2 $ λ s hs, pre_le (hs.trans h) lemma mono_pre_nat (m : set X → ℝ≥0∞) : monotone (λ k : ℕ, pre m k⁻¹) := λ k l h, le_pre.2 $ λ s hs, pre_le (hs.trans $ by simpa) lemma tendsto_pre (m : set X → ℝ≥0∞) (s : set X) : tendsto (λ r, pre m r s) (𝓝[Ioi 0] 0) (𝓝 $ mk_metric' m s) := begin rw [← map_coe_Ioi_at_bot, tendsto_map'_iff], simp only [mk_metric', outer_measure.supr_apply, supr_subtype'], exact tendsto_at_bot_supr (λ r r' hr, mono_pre _ hr _) end lemma tendsto_pre_nat (m : set X → ℝ≥0∞) (s : set X) : tendsto (λ n : ℕ, pre m n⁻¹ s) at_top (𝓝 $ mk_metric' m s) := begin refine (tendsto_pre m s).comp (tendsto_inf.2 ⟨ennreal.tendsto_inv_nat_nhds_zero, _⟩), refine tendsto_principal.2 (eventually_of_forall $ λ n, _), simp end lemma eq_supr_nat (m : set X → ℝ≥0∞) : mk_metric' m = ⨆ n : ℕ, mk_metric'.pre m n⁻¹ := begin ext1 s, rw supr_apply, refine tendsto_nhds_unique (mk_metric'.tendsto_pre_nat m s) (tendsto_at_top_supr $ λ k l hkl, mk_metric'.mono_pre_nat m hkl s) end /-- `measure_theory.outer_measure.mk_metric'.pre m r` is a trimmed measure provided that `m (closure s) = m s` for any set `s`. -/ lemma trim_pre [measurable_space X] [opens_measurable_space X] (m : set X → ℝ≥0∞) (hcl : ∀ s, m (closure s) = m s) (r : ℝ≥0∞) : (pre m r).trim = pre m r := begin refine le_antisymm (le_pre.2 $ λ s hs, _) (le_trim _), rw trim_eq_infi, refine (infi_le_of_le (closure s) $ infi_le_of_le subset_closure $ infi_le_of_le measurable_set_closure ((pre_le _).trans_eq (hcl _))), rwa diam_closure end end mk_metric' /-- An outer measure constructed using `outer_measure.mk_metric'` is a metric outer measure. -/ lemma mk_metric'_is_metric (m : set X → ℝ≥0∞) : (mk_metric' m).is_metric := begin rintros s t ⟨r, r0, hr⟩, refine tendsto_nhds_unique_of_eventually_eq (mk_metric'.tendsto_pre _ _) ((mk_metric'.tendsto_pre _ _).add (mk_metric'.tendsto_pre _ _)) _, rw [← pos_iff_ne_zero] at r0, filter_upwards [Ioo_mem_nhds_within_Ioi ⟨le_rfl, r0⟩], rintro ε ⟨ε0, εr⟩, refine bounded_by_union_of_top_of_nonempty_inter _, rintro u ⟨x, hxs, hxu⟩ ⟨y, hyt, hyu⟩, have : ε < diam u, from εr.trans_le ((hr x hxs y hyt).trans $ edist_le_diam_of_mem hxu hyu), exact infi_eq_top.2 (λ h, (this.not_le h).elim) end /-- If `c ∉ {0, ∞}` and `m₁ d ≤ c * m₂ d` for `0 < d < ε` for some `ε > 0` (we use `≤ᶠ[𝓝[Ioi 0]]` to state this), then `mk_metric m₁ hm₁ ≤ c • mk_metric m₂ hm₂`. -/ lemma mk_metric_mono_smul {m₁ m₂ : ℝ≥0∞ → ℝ≥0∞} {c : ℝ≥0∞} (hc : c ≠ ∞) (h0 : c ≠ 0) (hle : m₁ ≤ᶠ[𝓝[Ioi 0] 0] c • m₂) : (mk_metric m₁ : outer_measure X) ≤ c • mk_metric m₂ := begin classical, rcases (mem_nhds_within_Ioi_iff_exists_Ioo_subset' ennreal.zero_lt_one).1 hle with ⟨r, hr0, hr⟩, refine λ s, le_of_tendsto_of_tendsto (mk_metric'.tendsto_pre _ s) (ennreal.tendsto.const_mul (mk_metric'.tendsto_pre _ s) (or.inr hc)) (mem_of_superset (Ioo_mem_nhds_within_Ioi ⟨le_rfl, hr0⟩) (λ r' hr', _)), simp only [mem_set_of_eq, mk_metric'.pre], rw [← smul_apply, smul_bounded_by hc], refine le_bounded_by.2 (λ t, (bounded_by_le _).trans _) _, simp only [smul_eq_mul, pi.smul_apply, extend, infi_eq_if], split_ifs with ht ht, { refine supr_le (λ ht₁, _), rw [supr_eq_if, if_pos ht₁], refine hr ⟨_, ht.trans_lt hr'.2⟩, exact pos_iff_ne_zero.2 (mt diam_eq_zero_iff.1 ht₁) }, { simp [h0] } end /-- If `m₁ d ≤ m₂ d` for `0 < d < ε` for some `ε > 0` (we use `≤ᶠ[𝓝[Ioi 0]]` to state this), then `mk_metric m₁ hm₁ ≤ mk_metric m₂ hm₂`-/ lemma mk_metric_mono {m₁ m₂ : ℝ≥0∞ → ℝ≥0∞} (hle : m₁ ≤ᶠ[𝓝[Ioi 0] 0] m₂) : (mk_metric m₁ : outer_measure X) ≤ mk_metric m₂ := by { convert mk_metric_mono_smul ennreal.one_ne_top ennreal.zero_lt_one.ne' _; simp * } lemma isometry_comap_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) {f : X → Y} (hf : isometry f) (H : monotone (λ d : {d : ℝ≥0∞ | d ≠ 0}, m d) ∨ surjective f) : comap f (mk_metric m) = mk_metric m := begin simp only [mk_metric, mk_metric', mk_metric'.pre, induced_outer_measure, comap_supr], refine supr_congr id surjective_id (λ ε, supr_congr id surjective_id $ λ hε, _), rw comap_bounded_by _ (H.imp (λ h_mono, _) id), { congr' with s : 1, apply extend_congr, { simp [hf.ediam_image] }, { intros, simp [hf.injective.subsingleton_image_iff, hf.ediam_image] } }, { refine λ s t hst, infi_le_infi2 (λ ht, ⟨(diam_mono hst).trans ht, supr_le $ λ hs, _⟩), have ht : ¬(t : set Y).subsingleton, from λ ht, hs (ht.mono hst), refine (@h_mono ⟨_, mt diam_eq_zero_iff.1 hs⟩ ⟨_, mt diam_eq_zero_iff.1 ht⟩ (diam_mono hst)).trans _, exact le_supr (λ h : ¬(t : set Y).subsingleton, m (diam (t : set Y))) ht } end lemma isometry_map_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) {f : X → Y} (hf : isometry f) (H : monotone (λ d : {d : ℝ≥0∞ | d ≠ 0}, m d) ∨ surjective f) : map f (mk_metric m) = restrict (range f) (mk_metric m) := by rw [← isometry_comap_mk_metric _ hf H, map_comap] lemma isometric_comap_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) (f : X ≃ᵢ Y) : comap f (mk_metric m) = mk_metric m := isometry_comap_mk_metric _ f.isometry (or.inr f.surjective) lemma isometric_map_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) (f : X ≃ᵢ Y) : map f (mk_metric m) = mk_metric m := by rw [← isometric_comap_mk_metric _ f, map_comap_of_surjective f.surjective] lemma trim_mk_metric [measurable_space X] [borel_space X] (m : ℝ≥0∞ → ℝ≥0∞) : (mk_metric m : outer_measure X).trim = mk_metric m := begin simp only [mk_metric, mk_metric'.eq_supr_nat, trim_supr], congr' 1 with n : 1, refine mk_metric'.trim_pre _ (λ s, _) _, simp end lemma le_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) (μ : outer_measure X) (hμ : ∀ x, μ {x} = 0) (r : ℝ≥0∞) (h0 : 0 < r) (hr : ∀ s, diam s ≤ r → ¬s.subsingleton → μ s ≤ m (diam s)) : μ ≤ mk_metric m := le_bsupr_of_le r h0 $ mk_metric'.le_pre.2 $ λ s hs, begin by_cases h : s.subsingleton, exacts [h.induction_on (μ.empty'.trans_le (zero_le _)) (λ x, ((hμ x).trans_le (zero_le _))), le_supr_of_le h (hr _ hs h)] end end outer_measure /-! ### Metric measures In this section we use `measure_theory.outer_measure.to_measure` and theorems about `measure_theory.outer_measure.mk_metric'`/`measure_theory.outer_measure.mk_metric` to define `measure_theory.measure.mk_metric'`/`measure_theory.measure.mk_metric`. We also restate some lemmas about metric outer measures for metric measures. -/ namespace measure variables [measurable_space X] [borel_space X] /-- Given a function `m : set X → ℝ≥0∞`, `mk_metric' m` is the supremum of `μ r` over `r > 0`, where `μ r` is the maximal outer measure `μ` such that `μ s ≤ m s` for all `s`. While each `μ r` is an *outer* measure, the supremum is a measure. -/ def mk_metric' (m : set X → ℝ≥0∞) : measure X := (outer_measure.mk_metric' m).to_measure (outer_measure.mk_metric'_is_metric _).le_caratheodory /-- Given a function `m : ℝ≥0∞ → ℝ≥0∞`, `mk_metric m` is the supremum of `μ r` over `r > 0`, where `μ r` is the maximal outer measure `μ` such that `μ s ≤ m s` for all sets `s` that contain at least two points. While each `mk_metric'.pre` is an *outer* measure, the supremum is a measure. -/ def mk_metric (m : ℝ≥0∞ → ℝ≥0∞) : measure X := (outer_measure.mk_metric m).to_measure (outer_measure.mk_metric'_is_metric _).le_caratheodory @[simp] lemma mk_metric'_to_outer_measure (m : set X → ℝ≥0∞) : (mk_metric' m).to_outer_measure = (outer_measure.mk_metric' m).trim := rfl @[simp] lemma mk_metric_to_outer_measure (m : ℝ≥0∞ → ℝ≥0∞) : (mk_metric m : measure X).to_outer_measure = outer_measure.mk_metric m := outer_measure.trim_mk_metric m end measure lemma outer_measure.coe_mk_metric [measurable_space X] [borel_space X] (m : ℝ≥0∞ → ℝ≥0∞) : ⇑(outer_measure.mk_metric m : outer_measure X) = measure.mk_metric m := by rw [← measure.mk_metric_to_outer_measure, coe_to_outer_measure] namespace measure variables [measurable_space X] [borel_space X] /-- If `c ∉ {0, ∞}` and `m₁ d ≤ c * m₂ d` for `0 < d < ε` for some `ε > 0` (we use `≤ᶠ[𝓝[Ioi 0]]` to state this), then `mk_metric m₁ hm₁ ≤ c • mk_metric m₂ hm₂`. -/ lemma mk_metric_mono_smul {m₁ m₂ : ℝ≥0∞ → ℝ≥0∞} {c : ℝ≥0∞} (hc : c ≠ ∞) (h0 : c ≠ 0) (hle : m₁ ≤ᶠ[𝓝[Ioi 0] 0] c • m₂) : (mk_metric m₁ : measure X) ≤ c • mk_metric m₂ := begin intros s hs, rw [← outer_measure.coe_mk_metric, coe_smul, ← outer_measure.coe_mk_metric], exact outer_measure.mk_metric_mono_smul hc h0 hle s end /-- If `m₁ d ≤ m₂ d` for `0 < d < ε` for some `ε > 0` (we use `≤ᶠ[𝓝[Ioi 0]]` to state this), then `mk_metric m₁ hm₁ ≤ mk_metric m₂ hm₂`-/ lemma mk_metric_mono {m₁ m₂ : ℝ≥0∞ → ℝ≥0∞} (hle : m₁ ≤ᶠ[𝓝[Ioi 0] 0] m₂) : (mk_metric m₁ : measure X) ≤ mk_metric m₂ := by { convert mk_metric_mono_smul ennreal.one_ne_top ennreal.zero_lt_one.ne' _; simp * } /-- A formula for `measure_theory.measure.mk_metric`. -/ lemma mk_metric_apply (m : ℝ≥0∞ → ℝ≥0∞) (s : set X) : mk_metric m s = ⨆ (r : ℝ≥0∞) (hr : 0 < r), ⨅ (t : ℕ → set X) (hts : s ⊆ ⋃ n, t n) (ht : ∀ n, diam (t n) ≤ r), ∑' n, ⨆ (ht : ¬(t n).subsingleton), m (diam (t n)) := begin -- We mostly unfold the definitions but we need to switch the order of `∑'` and `⨅` -- and merge `(t n).nonempty` with `¬subsingleton (t n)` classical, simp only [← outer_measure.coe_mk_metric, outer_measure.mk_metric, outer_measure.mk_metric', outer_measure.supr_apply, outer_measure.mk_metric'.pre, outer_measure.bounded_by_apply, extend], refine supr_congr (λ r, r) surjective_id (λ r, supr_congr_Prop iff.rfl $ λ hr, infi_congr _ surjective_id $ λ t, infi_congr_Prop iff.rfl $ λ ht, _), by_cases htr : ∀ n, diam (t n) ≤ r, { rw [infi_eq_if, if_pos htr], congr' 1 with n : 1, simp only [infi_eq_if, htr n, id, if_true, supr_and'], refine supr_congr_Prop (and_iff_right_of_imp $ λ h, _) (λ _, rfl), contrapose! h, rw [not_nonempty_iff_eq_empty.1 h], exact subsingleton_empty }, { rw [infi_eq_if, if_neg htr], push_neg at htr, rcases htr with ⟨n, hn⟩, refine ennreal.tsum_eq_top_of_eq_top ⟨n, _⟩, rw [supr_eq_if, if_pos, infi_eq_if, if_neg], exact hn.not_le, rcases diam_pos_iff.1 ((zero_le r).trans_lt hn) with ⟨x, hx, -⟩, exact ⟨x, hx⟩ } end lemma le_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) (μ : measure X) [has_no_atoms μ] (ε : ℝ≥0∞) (h₀ : 0 < ε) (h : ∀ s : set X, diam s ≤ ε → ¬s.subsingleton → μ s ≤ m (diam s)) : μ ≤ mk_metric m := begin rw [← to_outer_measure_le, mk_metric_to_outer_measure], exact outer_measure.le_mk_metric m μ.to_outer_measure measure_singleton ε h₀ h end /-- To bound the Hausdorff measure (or, more generally, for a measure defined using `measure_theory.measure.mk_metric`) of a set, one may use coverings with maximum diameter tending to `0`, indexed by any sequence of encodable types. -/ lemma mk_metric_le_liminf_tsum {β : Type*} {ι : β → Type*} [∀ n, encodable (ι n)] (s : set X) {l : filter β} (r : β → ℝ≥0∞) (hr : tendsto r l (𝓝 0)) (t : Π (n : β), ι n → set X) (ht : ∀ᶠ n in l, ∀ i, diam (t n i) ≤ r n) (hst : ∀ᶠ n in l, s ⊆ ⋃ i, t n i) (m : ℝ≥0∞ → ℝ≥0∞) : mk_metric m s ≤ liminf l (λ n, ∑' i, m (diam (t n i))) := begin simp only [mk_metric_apply], refine bsupr_le (λ ε hε, _), refine le_of_forall_le_of_dense (λ c hc, _), rcases ((frequently_lt_of_liminf_lt (by apply_auto_param) hc).and_eventually ((hr.eventually (gt_mem_nhds hε)).and (ht.and hst))).exists with ⟨n, hn, hrn, htn, hstn⟩, set u : ℕ → set X := λ j, ⋃ b ∈ decode₂ (ι n) j, t n b, refine binfi_le_of_le u (by rwa Union_decode₂) _, refine infi_le_of_le (λ j, _) _, { rw emetric.diam_Union_mem_option, exact bsupr_le (λ _ _, (htn _).trans hrn.le) }, { calc (∑' (j : ℕ), ⨆ (ht : ¬(u j).subsingleton), m (diam (u j))) = _ : tsum_Union_decode₂ (λ t : set X, ⨆ (h : ¬t.subsingleton), m (diam t)) (by simp) _ ... ≤ _ : ennreal.tsum_le_tsum (λ b, supr_le $ λ htb, le_rfl) ... ≤ c : hn.le } end /-- To bound the Hausdorff measure (or, more generally, for a measure defined using `measure_theory.measure.mk_metric`) of a set, one may use coverings with maximum diameter tending to `0`, indexed by any sequence of finite types. -/ lemma mk_metric_le_liminf_sum {β : Type*} {ι : β → Type*} [hι : ∀ n, fintype (ι n)] (s : set X) {l : filter β} (r : β → ℝ≥0∞) (hr : tendsto r l (𝓝 0)) (t : Π (n : β), ι n → set X) (ht : ∀ᶠ n in l, ∀ i, diam (t n i) ≤ r n) (hst : ∀ᶠ n in l, s ⊆ ⋃ i, t n i) (m : ℝ≥0∞ → ℝ≥0∞) : mk_metric m s ≤ liminf l (λ n, ∑ i, m (diam (t n i))) := begin haveI : ∀ n, encodable (ι n), from λ n, fintype.encodable _, simpa only [tsum_fintype] using mk_metric_le_liminf_tsum s r hr t ht hst m, end /-! ### Hausdorff measure and Hausdorff dimension -/ /-- Hausdorff measure on an (e)metric space. -/ def hausdorff_measure (d : ℝ) : measure X := mk_metric (λ r, r ^ d) localized "notation `μH[` d `]` := measure_theory.measure.hausdorff_measure d" in measure_theory lemma le_hausdorff_measure (d : ℝ) (μ : measure X) [has_no_atoms μ] (ε : ℝ≥0∞) (h₀ : 0 < ε) (h : ∀ s : set X, diam s ≤ ε → ¬s.subsingleton → μ s ≤ diam s ^ d) : μ ≤ μH[d] := le_mk_metric _ μ ε h₀ h /-- A formula for `μH[d] s` that works for all `d`. In case of a positive `d` a simpler formula is available as `measure_theory.measure.hausdorff_measure_apply`. -/ lemma hausdorff_measure_apply' (d : ℝ) (s : set X) : μH[d] s = ⨆ (r : ℝ≥0∞) (hr : 0 < r), ⨅ (t : ℕ → set X) (hts : s ⊆ ⋃ n, t n) (ht : ∀ n, diam (t n) ≤ r), ∑' n, ⨆ (ht : ¬(t n).subsingleton), (diam (t n)) ^ d := mk_metric_apply _ _ /-- A formula for `μH[d] s` that works for all positive `d`. -/ lemma hausdorff_measure_apply {d : ℝ} (hd : 0 < d) (s : set X) : μH[d] s = ⨆ (r : ℝ≥0∞) (hr : 0 < r), ⨅ (t : ℕ → set X) (hts : s ⊆ ⋃ n, t n) (ht : ∀ n, diam (t n) ≤ r), ∑' n, diam (t n) ^ d := begin classical, rw hausdorff_measure_apply', -- I wish `congr'` was able to generate this refine supr_congr id surjective_id (λ r, supr_congr_Prop iff.rfl $ λ hr, infi_congr id surjective_id $ λ t, infi_congr_Prop iff.rfl $ λ hts, infi_congr_Prop iff.rfl $ λ ht, tsum_congr $ λ n, _), rw [supr_eq_if], split_ifs with ht', { erw [diam_eq_zero_iff.2 ht', ennreal.zero_rpow_of_pos hd, ennreal.bot_eq_zero] }, { refl } end /-- To bound the Hausdorff measure of a set, one may use coverings with maximum diameter tending to `0`, indexed by any sequence of encodable types. -/ lemma hausdorff_measure_le_liminf_tsum {β : Type*} {ι : β → Type*} [hι : ∀ n, encodable (ι n)] (d : ℝ) (s : set X) {l : filter β} (r : β → ℝ≥0∞) (hr : tendsto r l (𝓝 0)) (t : Π (n : β), ι n → set X) (ht : ∀ᶠ n in l, ∀ i, diam (t n i) ≤ r n) (hst : ∀ᶠ n in l, s ⊆ ⋃ i, t n i) : μH[d] s ≤ liminf l (λ n, ∑' i, diam (t n i) ^ d) := mk_metric_le_liminf_tsum s r hr t ht hst _ /-- To bound the Hausdorff measure of a set, one may use coverings with maximum diameter tending to `0`, indexed by any sequence of finite types. -/ lemma hausdorff_measure_le_liminf_sum {β : Type*} {ι : β → Type*} [hι : ∀ n, fintype (ι n)] (d : ℝ) (s : set X) {l : filter β} (r : β → ℝ≥0∞) (hr : tendsto r l (𝓝 0)) (t : Π (n : β), ι n → set X) (ht : ∀ᶠ n in l, ∀ i, diam (t n i) ≤ r n) (hst : ∀ᶠ n in l, s ⊆ ⋃ i, t n i) : μH[d] s ≤ liminf l (λ n, ∑ i, diam (t n i) ^ d) := mk_metric_le_liminf_sum s r hr t ht hst _ /-- If `d₁ < d₂`, then for any set `s` we have either `μH[d₂] s = 0`, or `μH[d₁] s = ∞`. -/ lemma hausdorff_measure_zero_or_top {d₁ d₂ : ℝ} (h : d₁ < d₂) (s : set X) : μH[d₂] s = 0 ∨ μH[d₁] s = ∞ := begin by_contra H, push_neg at H, suffices : ∀ (c : ℝ≥0), c ≠ 0 → μH[d₂] s ≤ c * μH[d₁] s, { rcases ennreal.exists_nnreal_pos_mul_lt H.2 H.1 with ⟨c, hc0, hc⟩, exact hc.not_le (this c (pos_iff_ne_zero.1 hc0)) }, intros c hc, refine le_iff'.1 (mk_metric_mono_smul ennreal.coe_ne_top (by exact_mod_cast hc) _) s, have : 0 < (c ^ (d₂ - d₁)⁻¹ : ℝ≥0∞), { rw [ennreal.coe_rpow_of_ne_zero hc, pos_iff_ne_zero, ne.def, ennreal.coe_eq_zero, nnreal.rpow_eq_zero_iff], exact mt and.left hc }, filter_upwards [Ioo_mem_nhds_within_Ioi ⟨le_rfl, this⟩], rintro r ⟨hr₀, hrc⟩, lift r to ℝ≥0 using ne_top_of_lt hrc, rw [pi.smul_apply, smul_eq_mul, ← ennreal.div_le_iff_le_mul (or.inr ennreal.coe_ne_top) (or.inr $ mt ennreal.coe_eq_zero.1 hc), ← ennreal.rpow_sub _ _ hr₀.ne' ennreal.coe_ne_top], refine (ennreal.rpow_lt_rpow hrc (sub_pos.2 h)).le.trans _, rw [← ennreal.rpow_mul, inv_mul_cancel (sub_pos.2 h).ne', ennreal.rpow_one], exact le_rfl end /-- Hausdorff measure `μH[d] s` is monotone in `d`. -/ lemma hausdorff_measure_mono {d₁ d₂ : ℝ} (h : d₁ ≤ d₂) (s : set X) : μH[d₂] s ≤ μH[d₁] s := begin rcases h.eq_or_lt with rfl|h, { exact le_rfl }, cases hausdorff_measure_zero_or_top h s with hs hs, { rw hs, exact zero_le _ }, { rw hs, exact le_top } end instance no_atoms_hausdorff (d : ℝ) : has_no_atoms (hausdorff_measure d : measure X) := begin refine ⟨λ x, _⟩, rw [← nonpos_iff_eq_zero, hausdorff_measure_apply'], refine bsupr_le (λ ε ε0, binfi_le_of_le (λ n, {x}) _ (infi_le_of_le (λ n, _) _)), { exact subset_Union (λ n, {x} : ℕ → set X) 0 }, { simp only [emetric.diam_singleton, zero_le] }, { simp } end end measure open_locale measure_theory open measure /-! ### Hausdorff measure and Lebesgue measure -/ /-- In the space `ι → ℝ`, Hausdorff measure coincides exactly with Lebesgue measure. -/ @[simp] theorem hausdorff_measure_pi_real {ι : Type*} [fintype ι] [nonempty ι] : (μH[fintype.card ι] : measure (ι → ℝ)) = volume := begin classical, -- it suffices to check that the two measures coincide on products of rational intervals refine (pi_eq_generate_from (λ i, real.borel_eq_generate_from_Ioo_rat.symm) (λ i, real.is_pi_system_Ioo_rat) (λ i, real.finite_spanning_sets_in_Ioo_rat _) _).symm, simp only [mem_Union, mem_singleton_iff], -- fix such a product `s` of rational intervals, of the form `Π (a i, b i)`. intros s hs, choose a b H using hs, obtain rfl : s = λ i, Ioo (a i) (b i), from funext (λ i, (H i).2), replace H := λ i, (H i).1, apply le_antisymm _, -- first check that `volume s ≤ μH s` { have Hle : volume ≤ (μH[fintype.card ι] : measure (ι → ℝ)), { refine le_hausdorff_measure _ _ ∞ ennreal.coe_lt_top (λ s h₁ h₂, _), rw [ennreal.rpow_nat_cast], exact real.volume_pi_le_diam_pow s }, rw [← volume_pi_pi (λ i, Ioo (a i : ℝ) (b i)) (λ i, measurable_set_Ioo)], exact measure.le_iff'.1 Hle _ }, /- For the other inequality `μH s ≤ volume s`, we use a covering of `s` by sets of small diameter `1/n`, namely cubes with left-most point of the form `a i + f i / n` with `f i` ranging between `0` and `⌈(b i - a i) * n⌉`. Their number is asymptotic to `n^d * Π (b i - a i)`. -/ have I : ∀ i, 0 ≤ (b i : ℝ) - a i := λ i, by simpa only [sub_nonneg, rat.cast_le] using (H i).le, let γ := λ (n : ℕ), (Π (i : ι), fin ⌈((b i : ℝ) - a i) * n⌉₊), let t : Π (n : ℕ), γ n → set (ι → ℝ) := λ n f, set.pi univ (λ i, Icc (a i + f i / n) (a i + (f i + 1) / n)), have A : tendsto (λ (n : ℕ), 1/(n : ℝ≥0∞)) at_top (𝓝 0), by simp only [one_div, ennreal.tendsto_inv_nat_nhds_zero], have B : ∀ᶠ n in at_top, ∀ (i : γ n), diam (t n i) ≤ 1 / n, { apply eventually_at_top.2 ⟨1, λ n hn, _⟩, assume f, apply diam_pi_le_of_le (λ b, _), simp only [real.ediam_Icc, add_div, ennreal.of_real_div_of_pos (nat.cast_pos.mpr hn), le_refl, add_sub_add_left_eq_sub, add_sub_cancel', ennreal.of_real_one, ennreal.of_real_coe_nat] }, have C : ∀ᶠ n in at_top, set.pi univ (λ (i : ι), Ioo (a i : ℝ) (b i)) ⊆ ⋃ (i : γ n), t n i, { apply eventually_at_top.2 ⟨1, λ n hn, _⟩, have npos : (0 : ℝ) < n := nat.cast_pos.2 hn, assume x hx, simp only [mem_Ioo, mem_univ_pi] at hx, simp only [mem_Union, mem_Ioo, mem_univ_pi, coe_coe], let f : γ n := λ i, ⟨⌊(x i - a i) * n⌋₊, begin apply nat.floor_lt_ceil_of_lt_of_pos, { refine (mul_lt_mul_right npos).2 _, simp only [(hx i).right, sub_lt_sub_iff_right] }, { refine mul_pos _ npos, simpa only [rat.cast_lt, sub_pos] using H i } end⟩, refine ⟨f, λ i, ⟨_, _⟩⟩, { calc (a i : ℝ) + ⌊(x i - a i) * n⌋₊ / n ≤ (a i : ℝ) + ((x i - a i) * n) / n : begin refine add_le_add le_rfl ((div_le_div_right npos).2 _), exact nat.floor_le (mul_nonneg (sub_nonneg.2 (hx i).1.le) npos.le), end ... = x i : by field_simp [npos.ne'] }, { calc x i = (a i : ℝ) + ((x i - a i) * n) / n : by field_simp [npos.ne'] ... ≤ (a i : ℝ) + (⌊(x i - a i) * n⌋₊ + 1) / n : add_le_add le_rfl ((div_le_div_right npos).2 (nat.lt_floor_add_one _).le) } }, calc μH[fintype.card ι] (set.pi univ (λ (i : ι), Ioo (a i : ℝ) (b i))) ≤ liminf at_top (λ (n : ℕ), ∑ (i : γ n), diam (t n i) ^ ↑(fintype.card ι)) : hausdorff_measure_le_liminf_sum _ (set.pi univ (λ i, Ioo (a i : ℝ) (b i))) (λ (n : ℕ), 1/(n : ℝ≥0∞)) A t B C ... ≤ liminf at_top (λ (n : ℕ), ∑ (i : γ n), (1/n) ^ (fintype.card ι)) : begin refine liminf_le_liminf _ (by is_bounded_default), filter_upwards [B], assume n hn, apply finset.sum_le_sum (λ i _, _), rw ennreal.rpow_nat_cast, exact pow_le_pow_of_le_left' (hn i) _, end ... = liminf at_top (λ (n : ℕ), ∏ (i : ι), (⌈((b i : ℝ) - a i) * n⌉₊ : ℝ≥0∞) / n) : begin simp only [finset.card_univ, nat.cast_prod, one_mul, fintype.card_fin, finset.sum_const, nsmul_eq_mul, fintype.card_pi, div_eq_mul_inv, finset.prod_mul_distrib, finset.prod_const] end ... = ∏ (i : ι), volume (Ioo (a i : ℝ) (b i)) : begin simp only [real.volume_Ioo], apply tendsto.liminf_eq, refine ennreal.tendsto_finset_prod_of_ne_top _ (λ i hi, _) (λ i hi, _), { apply tendsto.congr' _ ((ennreal.continuous_of_real.tendsto _).comp ((tendsto_nat_ceil_mul_div_at_top (I i)).comp tendsto_coe_nat_at_top_at_top)), apply eventually_at_top.2 ⟨1, λ n hn, _⟩, simp only [ennreal.of_real_div_of_pos (nat.cast_pos.mpr hn), comp_app, ennreal.of_real_coe_nat] }, { simp only [ennreal.of_real_ne_top, ne.def, not_false_iff] } end end end measure_theory /-! ### Hausdorff measure, Hausdorff dimension, and Hölder or Lipschitz continuous maps -/ open_locale measure_theory open measure_theory measure_theory.measure variables [measurable_space X] [borel_space X] [measurable_space Y] [borel_space Y] namespace holder_on_with variables {C r : ℝ≥0} {f : X → Y} {s t : set X} /-- If `f : X → Y` is Hölder continuous on `s` with a positive exponent `r`, then `μH[d] (f '' s) ≤ C ^ d * μH[r * d] s`. -/ lemma hausdorff_measure_image_le (h : holder_on_with C r f s) (hr : 0 < r) {d : ℝ} (hd : 0 ≤ d) : μH[d] (f '' s) ≤ C ^ d * μH[r * d] s := begin -- We start with the trivial case `C = 0` rcases (zero_le C).eq_or_lt with rfl|hC0, { have : (f '' s).subsingleton, by simpa [diam_eq_zero_iff] using h.ediam_image_le, rw this.measure_zero, exact zero_le _ }, { have hCd0 : (C : ℝ≥0∞) ^ d ≠ 0, by simp [hC0.ne'], have hCd : (C : ℝ≥0∞) ^ d ≠ ∞, by simp [hd], simp only [hausdorff_measure_apply', ennreal.mul_supr, ennreal.mul_infi_of_ne hCd0 hCd, ← ennreal.tsum_mul_left], refine supr_le (λ R, supr_le $ λ hR, _), have : tendsto (λ d : ℝ≥0∞, (C : ℝ≥0∞) * d ^ (r : ℝ)) (𝓝 0) (𝓝 0), from ennreal.tendsto_const_mul_rpow_nhds_zero_of_pos ennreal.coe_ne_top hr, rcases ennreal.nhds_zero_basis_Iic.eventually_iff.1 (this.eventually (gt_mem_nhds hR)) with ⟨δ, δ0, H⟩, refine le_supr_of_le δ (le_supr_of_le δ0 $ le_binfi $ λ t hst, le_infi $ λ htδ, _), refine binfi_le_of_le (λ n, f '' (t n ∩ s)) _ (infi_le_of_le (λ n, _) _), { rw [← image_Union, ← Union_inter], exact image_subset _ (subset_inter hst subset.rfl) }, { exact (h.ediam_image_inter_le (t n)).trans (H (htδ n)).le }, { refine ennreal.tsum_le_tsum (λ n, supr_le $ λ hft, le_supr_of_le (λ ht, hft $ (ht.mono (inter_subset_left _ _)).image f) _), rw [ennreal.rpow_mul, ← ennreal.mul_rpow_of_nonneg _ _ hd], exact ennreal.rpow_le_rpow (h.ediam_image_inter_le _) hd } } end end holder_on_with namespace lipschitz_on_with variables {K : ℝ≥0} {f : X → Y} {s t : set X} /-- If `f : X → Y` is `K`-Lipschitz on `s`, then `μH[d] (f '' s) ≤ K ^ d * μH[d] s`. -/ lemma hausdorff_measure_image_le (h : lipschitz_on_with K f s) {d : ℝ} (hd : 0 ≤ d) : μH[d] (f '' s) ≤ K ^ d * μH[d] s := by simpa only [nnreal.coe_one, one_mul] using h.holder_on_with.hausdorff_measure_image_le zero_lt_one hd end lipschitz_on_with namespace lipschitz_with variables {K : ℝ≥0} {f : X → Y} /-- If `f` is a `K`-Lipschitz map, then it increases the Hausdorff `d`-measures of sets at most by the factor of `K ^ d`.-/ lemma hausdorff_measure_image_le (h : lipschitz_with K f) {d : ℝ} (hd : 0 ≤ d) (s : set X) : μH[d] (f '' s) ≤ K ^ d * μH[d] s := (h.lipschitz_on_with s).hausdorff_measure_image_le hd end lipschitz_with /-! ### Antilipschitz maps do not decrease Hausdorff measures and dimension -/ namespace antilipschitz_with variables {f : X → Y} {K : ℝ≥0} {d : ℝ} lemma hausdorff_measure_preimage_le (hf : antilipschitz_with K f) (hd : 0 ≤ d) (s : set Y) : μH[d] (f ⁻¹' s) ≤ K ^ d * μH[d] s := begin rcases eq_or_ne K 0 with rfl|h0, { haveI : subsingleton X := hf.subsingleton, have : (f ⁻¹' s).subsingleton, from subsingleton_univ.mono (subset_univ _), rw this.measure_zero, exact zero_le _ }, have hKd0 : (K : ℝ≥0∞) ^ d ≠ 0, by simp [h0], have hKd : (K : ℝ≥0∞) ^ d ≠ ∞, by simp [hd], simp only [hausdorff_measure_apply', ennreal.mul_supr, ennreal.mul_infi_of_ne hKd0 hKd, ← ennreal.tsum_mul_left], refine bsupr_le (λ ε ε0, _), refine le_bsupr_of_le (ε / K) (by simp [ε0.ne']) _, refine le_binfi (λ t hst, le_infi $ λ htε, _), replace hst : f ⁻¹' s ⊆ _ := preimage_mono hst, rw preimage_Union at hst, refine binfi_le_of_le _ hst (infi_le_of_le (λ n, _) _), { exact (hf.ediam_preimage_le _).trans (ennreal.mul_le_of_le_div' $ htε n) }, { refine ennreal.tsum_le_tsum (λ n, supr_le $ λ H, le_supr_of_le (λ h, H $ h.preimage hf.injective) _), rw [← ennreal.mul_rpow_of_nonneg _ _ hd], exact ennreal.rpow_le_rpow (hf.ediam_preimage_le _) hd } end lemma le_hausdorff_measure_image (hf : antilipschitz_with K f) (hd : 0 ≤ d) (s : set X) : μH[d] s ≤ K ^ d * μH[d] (f '' s) := calc μH[d] s ≤ μH[d] (f ⁻¹' (f '' s)) : measure_mono (subset_preimage_image _ _) ... ≤ K ^ d * μH[d] (f '' s) : hf.hausdorff_measure_preimage_le hd (f '' s) end antilipschitz_with /-! ### Isometries preserve the Hausdorff measure and Hausdorff dimension -/ namespace isometry variables {f : X → Y} {d : ℝ} lemma hausdorff_measure_image (hf : isometry f) (hd : 0 ≤ d ∨ surjective f) (s : set X) : μH[d] (f '' s) = μH[d] s := begin simp only [hausdorff_measure, ← outer_measure.coe_mk_metric, ← outer_measure.comap_apply], rw [outer_measure.isometry_comap_mk_metric _ hf (hd.imp_left _)], exact λ hd x y hxy, ennreal.rpow_le_rpow hxy hd end lemma hausdorff_measure_preimage (hf : isometry f) (hd : 0 ≤ d ∨ surjective f) (s : set Y) : μH[d] (f ⁻¹' s) = μH[d] (s ∩ range f) := by rw [← hf.hausdorff_measure_image hd, image_preimage_eq_inter_range] lemma map_hausdorff_measure (hf : isometry f) (hd : 0 ≤ d ∨ surjective f) : measure.map f μH[d] = (μH[d]).restrict (range f) := begin ext1 s hs, rw [map_apply hf.continuous.measurable hs, restrict_apply hs, hf.hausdorff_measure_preimage hd] end end isometry namespace isometric @[simp] lemma hausdorff_measure_image (e : X ≃ᵢ Y) (d : ℝ) (s : set X) : μH[d] (e '' s) = μH[d] s := e.isometry.hausdorff_measure_image (or.inr e.surjective) s @[simp] lemma hausdorff_measure_preimage (e : X ≃ᵢ Y) (d : ℝ) (s : set Y) : μH[d] (e ⁻¹' s) = μH[d] s := by rw [← e.image_symm, e.symm.hausdorff_measure_image] end isometric
d1fe22e7a5825856b8290a721162f3e588ee0d6d
8e31b9e0d8cec76b5aa1e60a240bbd557d01047c
/scratch/simplex_nonverified.lean
64b49220e4a7ade9e18399e2582284ca3ba165e5
[]
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
12,705
lean
import data.matrix data.rat.basic linear_algebra.basis data.fintype import linear_algebra.determinant .misc order.pilex order.lexicographic .list_sup import data.list.min_max .fin_find open matrix fintype finset variables {m n : ℕ} variables (A : matrix (fin m) (fin n) ℚ) local notation `rvec`:2000 n := matrix (fin 1) (fin n) ℚ local notation `cvec`:2000 m := matrix (fin m) (fin 1) ℚ -- def column (j : fin n) : cvec m := λ i _, A i j -- def row (i : fin m) : rvec n := λ _ j, A i j variables (b : cvec m) (c : cvec n) def cvec.ordered_comm_group : ordered_comm_group (cvec n) := matrix.ordered_comm_group local attribute [instance] cvec.ordered_comm_group def cvec.decidable_le : decidable_rel ((≤) : (cvec n) → (cvec n) → Prop) := matrix.decidable_le local attribute [instance] cvec.decidable_le --instance : partial_order (matrix (fin m) (fin n) ℚ) := pi.partial_order constant matrix.has_inv : has_inv (matrix (fin n) (fin n) ℚ) local notation M `⬝` N := M.mul N local postfix `ᵀ` : 1500 := transpose def is_feasible (x : cvec n) : Prop := 0 ≤ x ∧ A ⬝ x = b instance (x : cvec n) : decidable (is_feasible A b x) := by dunfold is_feasible; apply_instance def is_optimal (x : cvec n) : Prop := is_feasible A b x ∧ ∀ y, is_feasible A b y → cᵀ ⬝ y ≤ cᵀ ⬝ x def is_invertible' (M : matrix (fin m) (fin n) ℚ) : Prop := ∃ h : m = n, by rw h at M; exact det M ≠ 0 instance is_invertible'.decidable : decidable_pred (@is_invertible' m n) := λ _, by unfold is_invertible'; apply_instance def comatrix (M : matrix (fin n) (fin n) ℚ) : matrix (fin n) (fin n) ℚ := begin cases n, { exact fin.elim0 }, { exact λ i j, (-1) ^ (i + j : ℕ) * det (minor M (λ i' : fin n, if i'.1 < i.1 then i'.cast_le sorry else i'.succ) (λ j' : fin n, if j'.1 < j.1 then j'.cast_le sorry else j'.succ)) } end def inverse (M : matrix (fin m) (fin n) ℚ) : matrix (fin n) (fin m) ℚ := if h : m = n then by subst h; exact (det M)⁻¹ • (comatrix M)ᵀ else 0 def rvec.to_list {n : ℕ} (x : rvec n) : list ℚ := (vector.of_fn (x 0)).1 def lex_rvec : linear_order (rvec m) := @pilex.linear_order _ _ _ (is_well_order.wf _) (λ _, pilex.linear_order (is_well_order.wf _)) def lex_rvec_decidable_linear_order : decidable_linear_order (rvec m) := { decidable_le := λ x y, decidable_of_iff (list.lex (<) (rvec.to_list x) (rvec.to_list y) ∨ x = y) sorry, ..lex_rvec } local attribute [instance] lex_rvec_decidable_linear_order def lex_ordered_comm_group_rvec : ordered_comm_group (rvec m) := @pilex.ordered_comm_group _ _ _ (λ _, pilex.ordered_comm_group) -- local attribute [instance] lex_ordered_comm_group_rvec -- lex_rvec_decidable_linear_order def pert_rat (m : ℕ) : Type := ℚ × rvec m instance : decidable_eq (pert_rat m) := by unfold pert_rat; apply_instance instance : add_comm_group (pert_rat m) := prod.add_comm_group instance : module ℚ (pert_rat m) := prod.module instance : decidable_linear_order (pert_rat m) := by letI := @lex_rvec_decidable_linear_order m; exact { decidable_le := @prod.lex.decidable _ _ _ _ _ _ _ (lex_rvec_decidable_linear_order).decidable_le, ..lex_linear_order } instance pert_rat.decidable_le (i j : pert_rat m) : decidable (i ≤ j) := @decidable_linear_order.decidable_le _ pert_rat.decidable_linear_order i j instance has_repr_fin_fun {n : ℕ} {α : Type*} [has_repr α] : has_repr (fin n → α) := ⟨λ f, repr (vector.of_fn f).to_list⟩ instance {m n} : has_repr (matrix (fin m) (fin n) ℚ) := has_repr_fin_fun instance : has_repr (pert_rat m) := prod.has_repr def pivot (A : matrix (fin m) (fin n) ℚ) (c : rvec n) (b : cvec m) (B : array m (fin n)) (NB : array (n - m) (fin n)) (i : fin (n - m)) (j : fin m) : array m (fin n) × -- basis array (n - m) (fin n) × -- non basis matrix (fin m) (fin (n - m)) ℚ × -- A_bar (rvec m) × -- c_B (rvec (n - m)) × --c_N (cvec m) × --b_bar matrix (fin m) (fin m) ℚ -- pert := let NBi : fin n := NB.read i in let Bj : fin n := B.read j in let NB' := NB.write i Bj in let B' := B.write j NBi in let A_B'_inverse := inverse (minor A id B'.read) in ⟨B', NB', A_B'_inverse ⬝ minor A id NB'.read, minor c id B'.read, minor c id NB'.read, A_B'_inverse ⬝ b, A_B'_inverse⟩ lemma true_well_founded {α : Type*} : well_founded (λ (_ _ : α), true) := sorry def simplex [inhabited (fin m)] (A : matrix (fin m) (fin n) ℚ) (c : rvec n) (b : cvec m) : Π (B : array m (fin n)) (NB : array (n - m) (fin n)) (A_bar : matrix (fin m) (fin (n - m)) ℚ) (c_B : rvec m) (c_N : rvec (n - m)) (b_bar : cvec m) (pert : (matrix (fin m) (fin m) ℚ)) (pivots : ℕ), ℕ × option (array m (fin n) × -- basis array (n - m) (fin n) × -- non basis matrix (fin m) (fin (n - m)) ℚ × -- A_bar (rvec m) × -- c_B (rvec (n - m)) × --c_N (cvec m) × --b_bar matrix (fin m) (fin m) ℚ) -- pert) | B NB A_bar c_B c_N b_bar pert pivots := let reduced_cost := c_N - c_B ⬝ A_bar in let i' := (list.fin_range (n - m)).find (λ i, 0 < column reduced_cost (fin 1) i) in match i' with | none := (pivots, some (B, NB, A_bar, c_B, c_N, b_bar, pert)) | some i := let ratio_pert : fin m → pert_rat m := λ j : fin m, (A_bar j i)⁻¹ • (b_bar j 0, row' pert (fin 1) j) in let l := (list.fin_range m).filter (λ j, 0 < ratio_pert j) in match l with | [] := (pivots + 1, none) | (a::l) := let j : fin m := list.argmin ratio_pert (a :: l) in let ⟨B', NB', A_bar', c_B', c_N', b_bar', pert'⟩ := pivot A c b B NB i j in have wf : true, from trivial, simplex B' NB' A_bar' c_B' c_N' b_bar' pert' (pivots + 1) end end using_well_founded {rel_tac := λ _ _, `[exact ⟨_, true_well_founded⟩], dec_tac := tactic.assumption} instance read_dec_pred (a : array m (fin n)) (i : fin n) : decidable_pred (λ (k : fin m), array.read a k = i) := by apply_instance instance array.mem_decidable {α : Type*} [decidable_eq α] (x : array m α) : decidable_pred (λ a : α, @array.mem m α a x) := by dunfold array.mem; apply_instance def find_optimal_solution_from_starting_basis [inhabited (fin m)] (A : matrix (fin m) (fin n) ℚ) (c : rvec n) (b : cvec m) (B : array m (fin n)) : ℕ × option (cvec n) := let NB : array (n - m) (fin n) := vector.to_array ⟨(list.fin_range n).filter (λ i, ¬ B.mem i), sorry⟩ in let A_B := minor A id B.read in let A_N := minor A id NB.read in let pert := inverse A_B in let A_bar := pert ⬝ A_N in let c_B := minor c id B.read in let c_N := minor c id NB.read in let b_bar := pert ⬝ b in match simplex A c b B NB A_bar c_B c_N b_bar pert 0 with | (pivots, none) := (pivots, none) | (pivots, some ⟨B', NB', A_bar', c_B', c_N', b_bar', pert'⟩) := prod.mk pivots $ some (λ i _, match @fin.find _ (λ k, B'.read k = i) (read_dec_pred _ _) with | none := 0 | some k := b_bar' k 0 end) end /- test code -/ instance {m : ℕ} : inhabited (fin m.succ) := ⟨0⟩ def list.to_matrix (m :ℕ) (n : ℕ) (l : list (list ℚ)) : matrix (fin m) (fin n) ℚ := λ i j, (l.nth_le i sorry).nth_le j sorry def found_solution_is_feasible [inhabited (fin m)] (A : matrix (fin m) (fin n) ℚ) (c : rvec n) (b : cvec m) (B : array m (fin n)) : bool := match find_optimal_solution_from_starting_basis A c b B with | (_, none) := tt | (_, some x) := (A ⬝ x = b ∧ 0 ≤ x : bool) end def is_optimal_bool [inhabited (fin m)] (A : matrix (fin m) (fin n) ℚ) (c : rvec n) (b : cvec m) (B : array m (fin n)) : bool := let NB : array (n - m) (fin n) := vector.to_array ⟨(list.fin_range n).filter (λ i, ¬ B.mem i), sorry⟩ in let A_B := minor A id B.read in let A_N := minor A id NB.read in let pert := inverse A_B in let A_bar := pert ⬝ A_N in let c_B := minor c id B.read in let c_N := minor c id NB.read in let b_bar := pert ⬝ b in match simplex A c b B NB A_N c_B c_N b_bar pert 0 with | (_, none) := tt | (_, some ⟨B', NB', A_bar', c_B', c_N', b_bar', pert'⟩) := c_N' - c_B' ⬝ A_bar' ≤ 0 end def is_feasible_basis [inhabited (fin m)] (A : matrix (fin m) (fin n) ℚ) (c : rvec n) (b : cvec m) (B : array m (fin n)) : Prop := let A_B := minor A id B.read in let NB : array (n - m) (fin n) := vector.to_array ⟨(list.fin_range n).filter (λ i, ¬ B.mem i), sorry⟩ in let A_N := minor A id NB.read in let pert := inverse A_B in let A_bar := pert ⬝ A_N in let c_B := minor c id B.read in let c_N := minor c id NB.read in let b_bar := pert ⬝ b in let x : cvec n := λ i _, match @fin.find _ (λ k, B.read k = i) (read_dec_pred _ _) with | none := 0 | some k := b_bar k 0 end in (0 : cvec n) ≤ x ∧ A ⬝ x = b ∧ det A_B ≠ 0 def finishing_basis [inhabited (fin m)] (A : matrix (fin m) (fin n) ℚ) (c : rvec n) (b : cvec m) (B : array m (fin n)) : option (array m (fin n)) := let NB : array (n - m) (fin n) := vector.to_array ⟨(list.fin_range n).filter (λ i, ¬ B.mem i), sorry⟩ in let A_B := minor A id B.read in let A_N := minor A id NB.read in let pert := inverse A_B in let A_bar := pert ⬝ A_N in let c_B := minor c id B.read in let c_N := minor c id NB.read in let b_bar := pert ⬝ b in option.map prod.fst (simplex A c b B NB A_N c_B c_N b_bar pert 0).2 def test [inhabited (fin m)] (A : matrix (fin m) (fin n) ℚ) (c : rvec n) (b : cvec m) (B : array m (fin n)) := let NB : array (n - m) (fin n) := vector.to_array ⟨(list.fin_range n).filter (λ i, ¬ B.mem i), sorry⟩ in let A_B := minor A id B.read in let A_N := minor A id NB.read in let pert := inverse A_B in let A_bar := pert ⬝ A_N in let c_B := minor c id B.read in let c_N := minor c id NB.read in let b_bar := pert ⬝ b in let reduced_cost := c_N - c_B ⬝ A_bar in let b_pert : fin m → pert_rat m := λ j : fin m, (A_bar j ⟨0, sorry⟩)⁻¹ • (b_bar j 0, row' pert (fin 1) j) in let reduced_cost := c_N - c_B ⬝ A_bar in let i' := (list.fin_range (n - m)).find (λ i, 0 < column reduced_cost (fin 1) i) in match i' with | none := sorry | some i := let ratio_pert : fin m → pert_rat m := λ j : fin m, (A_bar j i)⁻¹ • (b_bar j 0, row' pert (fin 1) j) in let l := (list.fin_range m).filter (λ j, 0 < ratio_pert j) in ratio_pert end --simplex A c b B NB A_N c_B c_N b_bar pert def objective_function_value (c : rvec n) (x : cvec n) := c ⬝ x -- (list.fin_range (n - m)).find (λ i, 0 < column reduced_cost (fin 1) i) -- pivot A c b B NB instance [inhabited (fin m)] (A : matrix (fin m) (fin n) ℚ) (c : rvec n) (b : cvec m) (B : array m (fin n)) : decidable (is_feasible_basis A c b B) := by dunfold is_feasible_basis; apply_instance def X' : pert_rat 2 := (0, X) --#eval X #eval X' #eval (0 = X' : bool) -- def ex.A := list.to_matrix 3 4 [[12,-1,1,1], -- [1,1.45,1,0], -- [1,2,0,1]] -- def ex.c : rvec 4 := λ _ i, (list.nth_le [1, 1.2, 1, 1.3] i sorry) -- --#eval ex.c -- def ex.b : cvec 3 := (λ i _, (list.nth_le [2, 2, 4] i sorry)) -- --#eval ex.b -- def ex.B : array 3 (fin 4) := list.to_array [0, 1, 3] -- def ex.NB : array 1 (fin 4) := list.to_array [2] -- def ex.A := list.to_matrix 2 5 [[1,1,0,1,0], [0,1,-1,0,1]] -- def ex.b : cvec 2 := (λ i _, (list.nth_le [8,0] i sorry)) -- --#eval ex.b -- def ex.c : rvec 5 := λ _ i, (list.nth_le [1, 1, 1, 0, 0] i sorry) -- --#eval ex.c -- def ex.B : array 2 (fin 5) := list.to_array [3,4] def ex.A := list.to_matrix 3 7 [[1/4, - 8, - 1, 9, 1, 0, 0], [1/2, -12, -1/2, 3, 0, 1, 0], [ 0, 0, 1, 0, 0, 0, 1]] def ex.b : cvec 3 := (λ i _, list.nth_le [0,0,1] i sorry) --#eval ex.b def ex.c : rvec 7 := λ _ i, (list.nth_le [3/4, -20, 1/2, -6, 0, 0, 0] i sorry) --#eval ex.c def ex.B : array 3 (fin 7) := list.to_array [4,5,6] -- #eval (found_solution_is_feasible ex.A ex.c ex.b ex.B) #eval (find_optimal_solution_from_starting_basis ex.A ex.c ex.b ex.B) --set_option trace.fun_info true #eval (is_optimal_bool ex.A ex.c ex.b ex.B) -- (some [[2064/445]]) -- (some [[6401/1895]]) #eval (is_feasible_basis ex.A ex.c ex.b ex.B : bool) -- #eval (show matrix _ _ ℚ, from minor ex.A id ex.B.read) * -- inverse (show matrix _ _ ℚ, from minor ex.A id ex.B.read ) -- #eval ((1 : matrix (fin 1) (fin 1) ℚ) - (minor ex.c id ex.B.read) ⬝ -- inverse (minor ex.A id ex.B.read) ⬝ -- (minor ex.A id ex.NB.read)) #eval finishing_basis ex.A ex.c ex.b ex.B #eval test ex.A ex.c ex.b ex.B #eval (let x : cvec 4 := λ i _, list.nth_le [0, 80/89, 62/89, 196/89] i sorry in let A := list.to_matrix 3 4 [[12, -1, 1, 1], [1, 1.45, 1, 0], [1, 2, 0, 1]] in A ⬝ x )
a8c2358d0af047bbbd00b04b32cff108495953d6
e151e9053bfd6d71740066474fc500a087837323
/src/hott/types/W.lean
d4879c0543fe5bdc91849e40467052c2fb01094b
[ "Apache-2.0" ]
permissive
daniel-carranza/hott3
15bac2d90589dbb952ef15e74b2837722491963d
913811e8a1371d3a5751d7d32ff9dec8aa6815d9
refs/heads/master
1,610,091,349,670
1,596,222,336,000
1,596,222,336,000
241,957,822
0
0
Apache-2.0
1,582,222,839,000
1,582,222,838,000
null
UTF-8
Lean
false
false
5,912
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Theorems about W-types (well-founded trees) -/ import .sigma .pi universes u v w hott_theory namespace hott open decidable open hott.eq hott.equiv hott.is_equiv sigma inductive Wtype {A : Type u} (B : A → Type v) : Type (max u v) | sup : Π (a : A), (B a → Wtype) → Wtype namespace Wtype notation `W` binders `, ` r:(scoped B, Wtype B) := r variables {A A' : Type u} {B B' : A → Type v} {C : Π(a : A), B a → Type _} {a a' : A} {f : B a → W a, B a} {f' : B a' → W a, B a} {w w' : W(a : A), B a} @[hott] protected def fst (w : W(a : A), B a) : A := by induction w with a f; exact a @[hott] protected def snd (w : W(a : A), B a) : B w.fst → W(a : A), B a := by induction w with a f; exact f @[hott] protected def eta (w : W a, B a) : sup w.fst w.snd = w := by induction w; exact idp @[hott] def sup_eq_sup (p : a = a') (q : f =[p; λa, B a → W a, B a] f') : sup a f = sup a' f' := by induction q; exact idp @[hott] def Wtype_eq (p : Wtype.fst w = Wtype.fst w') (q : Wtype.snd w =[p;λ a, B a → W(a : A), B a] Wtype.snd w') : w = w' := by induction w; induction w';exact (sup_eq_sup p q) @[hott] def Wtype_eq_fst (p : w = w') : w.fst = w'.fst := by induction p;exact idp @[hott] def Wtype_eq_snd (p : w = w') : w.snd =[Wtype_eq_fst p; λ a, B a → W(a : A), B a] w'.snd := by induction p;exact idpo namespace ops postfix `..fst`:(max+1) := Wtype_eq_fst postfix `..snd`:(max+1) := Wtype_eq_snd end ops open ops open sigma @[hott] def sup_path_W (p : w.fst = w'.fst) (q : w.snd =[p; λ a, B a → W(a : A), B a] w'.snd) : @dpair (w.fst=w'.fst) (λp, w.snd =[p; λ a, B a → W(a : A), B a] w'.snd) (Wtype_eq p q)..fst (Wtype_eq p q)..snd = ⟨p, q⟩ := begin induction w with a f, induction w' with a' f', dsimp [Wtype.fst] at p, dsimp [Wtype.snd] at q, hinduction q using pathover.rec, refl end @[hott] def fst_path_W (p : w.fst = w'.fst) (q : w.snd =[p; λ a, B a → W(a : A), B a] w'.snd) : (Wtype_eq p q)..fst = p := (sup_path_W _ _)..1 @[hott] def snd_path_W (p : w.fst = w'.fst) (q : w.snd =[p; λ a, B a → W(a : A), B a] w'.snd) : (Wtype_eq p q)..snd =[fst_path_W p q; λp, w.snd =[p; λ a, B a → W(a : A), B a] w'.snd] q := (sup_path_W _ _)..2 @[hott] def eta_path_W (p : w = w') : Wtype_eq (p..fst) (p..snd) = p := by induction p; induction w; exact idp @[hott] def transport_fst_path_W {B' : A → Type _} (p : w.fst = w'.fst) (q : w.snd =[p; λ a, B a → W(a : A), B a] w'.snd) : transport (λ(x:W a, B a), B' x.fst) (Wtype_eq p q) = transport B' p := begin induction w with a f, induction w' with a f', dsimp [Wtype.fst] at p, dsimp [Wtype.snd] at q, hinduction q using pathover.rec, refl end @[hott] def path_W_uncurried (pq : Σ(p : w.fst = w'.fst), w.snd =[p; λ a, B a → W(a : A), B a] w'.snd) : w = w' := by induction pq with p q; exact (Wtype_eq p q) @[hott] def sup_path_W_uncurried (pq : Σ(p : w.fst = w'.fst), w.snd =[p; λ a, B a → W(a : A), B a] w'.snd) : @dpair (w.fst = w'.fst) (λp, w.snd =[p; λ a, B a → W(a : A), B a] w'.snd) (path_W_uncurried pq)..fst (path_W_uncurried pq)..snd = pq := by induction pq with p q; exact (sup_path_W p q) @[hott] def fst_path_W_uncurried (pq : Σ(p : w.fst = w'.fst), w.snd =[p; λ a, B a → W(a : A), B a] w'.snd) : (path_W_uncurried pq)..fst = pq.fst := (sup_path_W_uncurried _)..1 @[hott] def snd_path_W_uncurried (pq : Σ(p : w.fst = w'.fst), w.snd =[p; λ a, B a → W(a : A), B a] w'.snd) : (path_W_uncurried pq)..snd =[fst_path_W_uncurried pq; λ p, w.snd =[p; λ a, B a → W(a : A), B a] w'.snd] pq.snd := (sup_path_W_uncurried _)..2 @[hott] def eta_path_W_uncurried (p : w = w') : path_W_uncurried ⟨p..fst, p..snd⟩ = p := eta_path_W _ @[hott] def transport_fst_path_W_uncurried {B' : A → Type _} (pq : Σ(p : w.fst = w'.fst), w.snd =[p; λ a, B a → W(a : A), B a] w'.snd) : transport (λ(x:W a, B a), B' x.fst) (@path_W_uncurried A B w w' pq) = transport B' pq.fst := by induction pq with p q; exact (transport_fst_path_W p q) @[hott] def isequiv_path_W /-[instance]-/ (w w' : W a, B a) : is_equiv (path_W_uncurried : (Σ(p : w.fst = w'.fst), w.snd =[p; λ a, B a → W(a : A), B a] w'.snd) → w = w') := adjointify path_W_uncurried (λp, ⟨p..fst, p..snd⟩) eta_path_W_uncurried sup_path_W_uncurried @[hott] def equiv_path_W (w w' : W a, B a) : (Σ(p : w.fst = w'.fst), w.snd =[p; λ a, B a → W(a : A), B a] w'.snd) ≃ (w = w') := equiv.mk path_W_uncurried (isequiv_path_W _ _) @[hott] def double_induction_on {P : (W a, B a) → (W a, B a) → Type _} (w w' : W a, B a) (H : ∀ (a a' : A) (f : B a → W a, B a) (f' : B a' → W a, B a), (∀ (b : B a) (b' : B a'), P (f b) (f' b')) → P (sup a f) (sup a' f')) : P w w' := begin revert w', induction w with a f IH, intro w', induction w' with a' f', apply H, intros b b', apply IH end /- truncatedness -/ open is_trunc pi hott.sigma hott.pi local attribute [instance] is_trunc_pi_eq @[hott, instance] def is_trunc_W (n : trunc_index) [HA : is_trunc (n.+1) A] : is_trunc (n.+1) (W a, B a) := begin fapply is_trunc_succ_intro, intros w w', eapply (double_induction_on w w'), intros a a' f f' IH, apply is_trunc_equiv_closed, apply equiv_path_W, dsimp [Wtype.fst,Wtype.snd], letI HD : Π (p : a = a'), is_trunc n (f =[p; λ (a : A), B a → Wtype B] f'), intro p, induction p, apply is_trunc_equiv_closed_rev, apply pathover_idp, apply_instance, applyI is_trunc_sigma, end end Wtype end hott
edcc7c0d5a9096b2fe412da9b0fd20b6dd2b7ec6
4727251e0cd73359b15b664c3170e5d754078599
/counterexamples/pseudoelement.lean
5b2c551cacfcd396e15519b3d80bb94c5e3a5bd1
[ "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,407
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 category_theory.abelian.pseudoelements /-! # Pseudoelements and pullbacks Borceux claims in Proposition 1.9.5 that the pseudoelement constructed in `category_theory.abelian.pseudoelement.pseudo_pullback` is unique. We show here that this claim is false. This means in particular that we cannot have an extensionality principle for pullbacks in terms of pseudoelements. ## Implementation details The construction, suggested in https://mathoverflow.net/a/419951/7845, is the following. We work in the category of `Module ℤ` and we consider the special case of `ℚ ⊞ ℚ` (that is the pullback over the terminal object). We consider the pseudoelements associated to `x : ℚ ⟶ ℚ ⊞ ℚ` given by `t ↦ (t, 2 * t)` and `y : ℚ ⟶ ℚ ⊞ ℚ` given by `t ↦ (t, t)`. ## Main results * `category_theory.abelian.pseudoelement.exist_ne_and_fst_eq_fst_and_snd_eq_snd` : there are two pseudoelements `x y : ℚ ⊞ ℚ` such that `x ≠ y`, `biprod.fst x = biprod.fst y` and `biprod.snd x = biprod.snd y`. ## References * [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2] -/ open category_theory.abelian category_theory category_theory.limits Module linear_map noncomputable theory namespace category_theory.abelian.pseudoelement /-- `x` is given by `t ↦ (t, 2 * t)`. -/ def x : over ((of ℤ ℚ) ⊞ (of ℤ ℚ)) := begin constructor, exact biprod.lift (of_hom id) (of_hom (2 * id)), end /-- `y` is given by `t ↦ (t, t)`. -/ def y : over ((of ℤ ℚ) ⊞ (of ℤ ℚ)) := begin constructor, exact biprod.lift (of_hom id) (of_hom id), end /-- `biprod.fst ≫ x` is pseudoequal to `biprod.fst y`. -/ lemma fst_x_pseudo_eq_fst_y : pseudo_equal _ (app biprod.fst x) (app biprod.fst y) := begin refine ⟨of ℤ ℚ, (of_hom id), (of_hom id), category_struct.id.epi (of ℤ ℚ), _, _⟩, { exact (Module.epi_iff_surjective _).2 (λ a, ⟨(a : ℚ), by simp⟩) }, { dsimp [x, y], simp } end /-- `biprod.snd ≫ x` is pseudoequal to `biprod.snd y`. -/ lemma snd_x_pseudo_eq_snd_y : pseudo_equal _ (app biprod.snd x) (app biprod.snd y) := begin refine ⟨of ℤ ℚ, (of_hom id), 2 • (of_hom id), category_struct.id.epi (of ℤ ℚ), _, _⟩, { refine (Module.epi_iff_surjective _).2 (λ a, ⟨(a/2 : ℚ), _⟩), simp only [two_smul, add_apply, of_hom_apply, id_coe, id.def], convert add_halves' _, change char_zero ℚ, apply_instance }, { dsimp [x, y], exact concrete_category.hom_ext _ _ (λ a, by simpa) } end /-- `x` is not pseudoequal to `y`. -/ lemma x_not_pseudo_eq : ¬(pseudo_equal _ x y) := begin intro h, replace h := Module.eq_range_of_pseudoequal h, dsimp [x, y] at h, let φ := (biprod.lift (of_hom (id : ℚ →ₗ[ℤ] ℚ)) (of_hom (2 * id))), have mem_range := mem_range_self φ (1 : ℚ), rw h at mem_range, obtain ⟨a, ha⟩ := mem_range, rw [← Module.id_apply (φ (1 : ℚ)), ← biprod.total, ← linear_map.comp_apply, ← comp_def, preadditive.comp_add] at ha, let π₁ := (biprod.fst : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _), have ha₁ := congr_arg π₁ ha, simp only [← linear_map.comp_apply, ← comp_def] at ha₁, simp only [biprod.lift_fst, of_hom_apply, id_coe, id.def, preadditive.add_comp, category.assoc, biprod.inl_fst, category.comp_id, biprod.inr_fst, limits.comp_zero, add_zero] at ha₁, let π₂ := (biprod.snd : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _), have ha₂ := congr_arg π₂ ha, simp only [← linear_map.comp_apply, ← comp_def] at ha₂, have : (2 : ℚ →ₗ[ℤ] ℚ) 1 = 1 + 1 := rfl, simp only [ha₁, this, biprod.lift_snd, of_hom_apply, id_coe, id.def, preadditive.add_comp, category.assoc, biprod.inl_snd, limits.comp_zero, biprod.inr_snd, category.comp_id, zero_add, mul_apply, self_eq_add_left] at ha₂, exact @one_ne_zero ℚ _ _ ha₂, end local attribute [instance] pseudoelement.setoid open_locale pseudoelement /-- `biprod.fst ⟦x⟧ = biprod.fst ⟦y⟧`. -/ lemma fst_mk_x_eq_fst_mk_y : (biprod.fst : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) ⟦x⟧ = (biprod.fst : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) ⟦y⟧ := by simpa only [abelian.pseudoelement.pseudo_apply_mk, quotient.eq] using fst_x_pseudo_eq_fst_y /-- `biprod.snd ⟦x⟧ = biprod.snd ⟦y⟧`. -/ lemma snd_mk_x_eq_snd_mk_y : (biprod.snd : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) ⟦x⟧ = (biprod.snd : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) ⟦y⟧ := by simpa only [abelian.pseudoelement.pseudo_apply_mk, quotient.eq] using snd_x_pseudo_eq_snd_y /-- `⟦x⟧ ≠ ⟦y⟧`. -/ lemma mk_x_ne_mk_y : ⟦x⟧ ≠ ⟦y⟧ := λ h, x_not_pseudo_eq $ quotient.eq.1 h /-- There are two pseudoelements `x y : ℚ ⊞ ℚ` such that `x ≠ y`, `biprod.fst x = biprod.fst y` and `biprod.snd x = biprod.snd y`. -/ lemma exist_ne_and_fst_eq_fst_and_snd_eq_snd : ∃ x y : (of ℤ ℚ) ⊞ (of ℤ ℚ), x ≠ y ∧ (biprod.fst : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) x = (biprod.fst : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) y ∧ (biprod.snd : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) x = (biprod.snd : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) y:= ⟨⟦x⟧, ⟦y⟧, mk_x_ne_mk_y, fst_mk_x_eq_fst_mk_y, snd_mk_x_eq_snd_mk_y⟩ end category_theory.abelian.pseudoelement
40ba38a7f67bd3e49162e97bdf9274271e451236
d6124c8dbe5661dcc5b8c9da0a56fbf1f0480ad6
/Papyrus/Script/Value.lean
e9372c816caa5b0ce944f0951663ee52de740d4f
[ "Apache-2.0" ]
permissive
xubaiw/lean4-papyrus
c3fbbf8ba162eb5f210155ae4e20feb2d32c8182
02e82973a5badda26fc0f9fd15b3d37e2eb309e0
refs/heads/master
1,691,425,756,824
1,632,122,825,000
1,632,123,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,308
lean
import Lean.Parser import Papyrus.Script.Type import Papyrus.Script.ParserUtil import Papyrus.Script.AddressSpace import Papyrus.IR.ConstantRefs import Papyrus.Builders namespace Papyrus.Script open Builder Lean Parser -- # Category declare_syntax_cat llvmValue (behavior := symbol) def valueParser (rbp : Nat := 0) := categoryParser `llvmValue rbp -- # Expansion def expandValueAsRef (stx : Syntax) : MacroM Syntax := expandMacros stx def expandValueAsRefArrow (stx : Syntax) : MacroM Syntax := do `(← $(← expandValueAsRef stx)) scoped macro "llvm " x:llvmValue : term => expandValueAsRef x -- # Special Macros macro "%" x:ident : llvmValue => x macro "value" "(" x:term ")" : llvmValue => x macro (priority := low) x:ident : llvmValue => x -------------------------------------------------------------------------------- -- # Constants -------------------------------------------------------------------------------- -- ## Category declare_syntax_cat llvmConst (behavior := symbol) def constParser (rbp : Nat := 0) := categoryParser `llvmConst rbp -- ## Expansion def expandConstantAsRef (stx : Syntax) : MacroM Syntax := expandMacros stx def expandConstantAsRefArrow (stx : Syntax) : MacroM Syntax := do `(← $(← expandConstantAsRef stx)) macro c:llvmConst : llvmValue => expandConstantAsRef c -- ## Constant Global String Pointers macro s:strLit addrspace?:optional(addrspace) "*" : llvmConst => do ``(stringPtr $s $(← expandOptAddrspace addrspace?)) -- ## Integer Constants @[runParserAttributeHooks] def constIntLit := leading_parser intTypeLit >> (numLit <|> negNumLit) def expandConstIntLitAsRef : Macro | `(constIntLit| $t:intTypeLit $n:numLit) => do ``(ConstantIntRef.ofNat $(← expandIntTypeLitAsNatLit t) $n) | `(constIntLit| $t:intTypeLit $n:negNumLit) => do ``(ConstantIntRef.ofInt $(← expandIntTypeLitAsNatLit t) $(← expandNegNumLit n)) | stx => Macro.throwErrorAt stx "ill-formed constant int literal" macro x:constIntLit : llvmConst => expandConstIntLitAsRef x -- ## Boolean Constants macro x:"true" : llvmConst => mkCIdentFrom x ``ConstantIntRef.getTrue macro x:"false" : llvmConst => mkCIdentFrom x ``ConstantIntRef.getFalse -- ## Constant Expressions @[runParserAttributeHooks] def constPtrToInt := leading_parser nonReservedSymbol "ptrtoint " true >> "(" >> constParser >> nonReservedSymbol " to " true >> typeParser >> ")" def expandConstPtrToIntAsRef : Macro | `(constPtrToInt| ptrtoint ($c:llvmConst to $ty:llvmType)) => do let ty ← expandTypeAsRefArrow ty let c ← expandConstantAsRefArrow c ``(ConstantExprRef.getPtrToInt $c $ty) | stx => Macro.throwErrorAt stx "ill-formed constant ptrtoint expression" macro x:constPtrToInt : llvmConst => expandConstPtrToIntAsRef x @[runParserAttributeHooks] def constIntToPtr := leading_parser nonReservedSymbol "inttoptr " true >> "(" >> constParser >> nonReservedSymbol " to " true >> typeParser >> ")" def expandConstIntToPtrAsRef : Macro | `(constIntToPtr| inttoptr ($c:llvmConst to $ty:llvmType)) => do let ty ← expandTypeAsRefArrow ty let c ← expandConstantAsRefArrow c ``(ConstantExprRef.getIntToPtr $c $ty) | stx => Macro.throwErrorAt stx "ill-formed constant inttoptr expression" macro x:constIntToPtr : llvmConst => expandConstIntToPtrAsRef x
b410bc4bdbe39c1e0c76b87797f75e2885a1a568
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/ring_theory/unique_factorization_domain.lean
5681daa455d08acc6bf1b4662ef84d620824d40b
[]
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
38,164
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, Aaron Anderson -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.gcd_monoid import Mathlib.ring_theory.integral_domain import Mathlib.ring_theory.noetherian import Mathlib.PostPort universes u_2 l u_1 u namespace Mathlib /-- # Unique factorization ## Main Definitions * `wf_dvd_monoid` holds for `monoid`s for which a strict divisibility relation is well-founded. * `unique_factorization_monoid` holds for `wf_dvd_monoid`s where `irreducible` is equivalent to `prime` ## To do * set up the complete lattice structure on `factor_set`. -/ /-- Well-foundedness of the strict version of |, which is equivalent to the descending chain condition on divisibility and to the ascending chain condition on principal ideals in an integral domain. -/ class wf_dvd_monoid (α : Type u_2) [comm_monoid_with_zero α] where well_founded_dvd_not_unit : well_founded dvd_not_unit protected instance is_noetherian_ring.wf_dvd_monoid {α : Type u_1} [integral_domain α] [is_noetherian_ring α] : wf_dvd_monoid α := wf_dvd_monoid.mk (eq.mpr ((fun (r r_1 : α → α → Prop) (e_1 : r = r_1) => congr_arg well_founded e_1) dvd_not_unit (inv_image gt fun (a : α) => ideal.span (singleton a)) (funext fun (x : α) => funext fun (x_1 : α) => propext (iff.symm ideal.span_singleton_lt_span_singleton))) (inv_image.wf (fun (a : α) => ideal.span (singleton a)) (well_founded_submodule_gt α α))) namespace wf_dvd_monoid theorem of_wf_dvd_monoid_associates {α : Type u_1} [comm_monoid_with_zero α] (h : wf_dvd_monoid (associates α)) : wf_dvd_monoid α := sorry protected instance wf_dvd_monoid_associates {α : Type u_1} [comm_monoid_with_zero α] [wf_dvd_monoid α] : wf_dvd_monoid (associates α) := mk (iff.mp (surjective.well_founded_iff associates.mk_surjective fun (a b : α) => eq.mpr (id (Eq._oldrec (Eq.refl (dvd_not_unit a b ↔ dvd_not_unit (associates.mk a) (associates.mk b))) (propext associates.mk_dvd_not_unit_mk_iff))) (iff.refl (dvd_not_unit a b))) well_founded_dvd_not_unit) theorem well_founded_associates {α : Type u_1} [comm_monoid_with_zero α] [wf_dvd_monoid α] : well_founded Less := subrelation.wf (fun (x y : associates α) => associates.dvd_not_unit_of_lt) well_founded_dvd_not_unit theorem exists_irreducible_factor {α : Type u_1} [comm_monoid_with_zero α] [wf_dvd_monoid α] {a : α} (ha : ¬is_unit a) (ha0 : a ≠ 0) : ∃ (i : α), irreducible i ∧ i ∣ a := sorry theorem induction_on_irreducible {α : Type u_1} [comm_monoid_with_zero α] [wf_dvd_monoid α] {P : α → Prop} (a : α) (h0 : P 0) (hu : ∀ (u : α), is_unit u → P u) (hi : ∀ (a i : α), a ≠ 0 → irreducible i → P a → P (i * a)) : P a := sorry theorem exists_factors {α : Type u_1} [comm_monoid_with_zero α] [wf_dvd_monoid α] (a : α) : a ≠ 0 → ∃ (f : multiset α), (∀ (b : α), b ∈ f → irreducible b) ∧ associated (multiset.prod f) a := sorry end wf_dvd_monoid theorem wf_dvd_monoid.of_well_founded_associates {α : Type u_1} [comm_cancel_monoid_with_zero α] (h : well_founded Less) : wf_dvd_monoid α := sorry theorem wf_dvd_monoid.iff_well_founded_associates {α : Type u_1} [comm_cancel_monoid_with_zero α] : wf_dvd_monoid α ↔ well_founded Less := { mp := wf_dvd_monoid.well_founded_associates, mpr := wf_dvd_monoid.of_well_founded_associates } /-- unique factorization monoids. These are defined as `comm_cancel_monoid_with_zero`s with well-founded strict divisibility relations, but this is equivalent to more familiar definitions: Each element (except zero) is uniquely represented as a multiset of irreducible factors. Uniqueness is only up to associated elements. Each element (except zero) is non-uniquely represented as a multiset of prime factors. To define a UFD using the definition in terms of multisets of irreducible factors, use the definition `of_exists_unique_irreducible_factors` To define a UFD using the definition in terms of multisets of prime factors, use the definition `of_exists_prime_factors` -/ class unique_factorization_monoid (α : Type u_2) [comm_cancel_monoid_with_zero α] extends wf_dvd_monoid α where irreducible_iff_prime : ∀ {a : α}, irreducible a ↔ prime a protected instance ufm_of_gcd_of_wf_dvd_monoid {α : Type u_1} [nontrivial α] [comm_cancel_monoid_with_zero α] [wf_dvd_monoid α] [gcd_monoid α] : unique_factorization_monoid α := unique_factorization_monoid.mk fun (_x : α) => gcd_monoid.irreducible_iff_prime protected instance associates.ufm {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] : unique_factorization_monoid (associates α) := unique_factorization_monoid.mk (eq.mpr (id (Eq._oldrec (Eq.refl (∀ {a : associates α}, irreducible a ↔ prime a)) (Eq.symm (propext associates.irreducible_iff_prime_iff)))) unique_factorization_monoid.irreducible_iff_prime) namespace unique_factorization_monoid theorem exists_prime_factors {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] (a : α) : a ≠ 0 → ∃ (f : multiset α), (∀ (b : α), b ∈ f → prime b) ∧ associated (multiset.prod f) a := sorry theorem induction_on_prime {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] {P : α → Prop} (a : α) (h₁ : P 0) (h₂ : ∀ (x : α), is_unit x → P x) (h₃ : ∀ (a p : α), a ≠ 0 → prime p → P a → P (p * a)) : P a := sorry theorem factors_unique {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] {f : multiset α} {g : multiset α} : (∀ (x : α), x ∈ f → irreducible x) → (∀ (x : α), x ∈ g → irreducible x) → associated (multiset.prod f) (multiset.prod g) → multiset.rel associated f g := sorry end unique_factorization_monoid theorem prime_factors_unique {α : Type u_1} [comm_cancel_monoid_with_zero α] {f : multiset α} {g : multiset α} : (∀ (x : α), x ∈ f → prime x) → (∀ (x : α), x ∈ g → prime x) → associated (multiset.prod f) (multiset.prod g) → multiset.rel associated f g := sorry /-- If an irreducible has a prime factorization, then it is an associate of one of its prime factors. -/ theorem prime_factors_irreducible {α : Type u_1} [comm_cancel_monoid_with_zero α] {a : α} {f : multiset α} (ha : irreducible a) (pfa : (∀ (b : α), b ∈ f → prime b) ∧ associated (multiset.prod f) a) : ∃ (p : α), associated a p ∧ f = p ::ₘ 0 := sorry theorem wf_dvd_monoid.of_exists_prime_factors {α : Type u_1} [comm_cancel_monoid_with_zero α] (pf : ∀ (a : α), a ≠ 0 → ∃ (f : multiset α), (∀ (b : α), b ∈ f → prime b) ∧ associated (multiset.prod f) a) : wf_dvd_monoid α := sorry theorem irreducible_iff_prime_of_exists_prime_factors {α : Type u_1} [comm_cancel_monoid_with_zero α] (pf : ∀ (a : α), a ≠ 0 → ∃ (f : multiset α), (∀ (b : α), b ∈ f → prime b) ∧ associated (multiset.prod f) a) {p : α} : irreducible p ↔ prime p := sorry theorem unique_factorization_monoid.of_exists_prime_factors {α : Type u_1} [comm_cancel_monoid_with_zero α] (pf : ∀ (a : α), a ≠ 0 → ∃ (f : multiset α), (∀ (b : α), b ∈ f → prime b) ∧ associated (multiset.prod f) a) : unique_factorization_monoid α := unique_factorization_monoid.mk fun (_x : α) => irreducible_iff_prime_of_exists_prime_factors pf theorem unique_factorization_monoid.iff_exists_prime_factors {α : Type u_1} [comm_cancel_monoid_with_zero α] : unique_factorization_monoid α ↔ ∀ (a : α), a ≠ 0 → ∃ (f : multiset α), (∀ (b : α), b ∈ f → prime b) ∧ associated (multiset.prod f) a := { mp := fun (h : unique_factorization_monoid α) => unique_factorization_monoid.exists_prime_factors, mpr := unique_factorization_monoid.of_exists_prime_factors } theorem irreducible_iff_prime_of_exists_unique_irreducible_factors {α : Type u_1} [comm_cancel_monoid_with_zero α] (eif : ∀ (a : α), a ≠ 0 → ∃ (f : multiset α), (∀ (b : α), b ∈ f → irreducible b) ∧ associated (multiset.prod f) a) (uif : ∀ (f g : multiset α), (∀ (x : α), x ∈ f → irreducible x) → (∀ (x : α), x ∈ g → irreducible x) → associated (multiset.prod f) (multiset.prod g) → multiset.rel associated f g) (p : α) : irreducible p ↔ prime p := sorry theorem unique_factorization_monoid.of_exists_unique_irreducible_factors {α : Type u_1} [comm_cancel_monoid_with_zero α] (eif : ∀ (a : α), a ≠ 0 → ∃ (f : multiset α), (∀ (b : α), b ∈ f → irreducible b) ∧ associated (multiset.prod f) a) (uif : ∀ (f g : multiset α), (∀ (x : α), x ∈ f → irreducible x) → (∀ (x : α), x ∈ g → irreducible x) → associated (multiset.prod f) (multiset.prod g) → multiset.rel associated f g) : unique_factorization_monoid α := sorry namespace unique_factorization_monoid /-- Noncomputably determines the multiset of prime factors. -/ def factors {α : Type u_1} [comm_cancel_monoid_with_zero α] [DecidableEq α] [nontrivial α] [normalization_monoid α] [unique_factorization_monoid α] (a : α) : multiset α := dite (a = 0) (fun (h : a = 0) => 0) fun (h : ¬a = 0) => multiset.map (⇑normalize) (classical.some (exists_prime_factors a h)) theorem factors_prod {α : Type u_1} [comm_cancel_monoid_with_zero α] [DecidableEq α] [nontrivial α] [normalization_monoid α] [unique_factorization_monoid α] {a : α} (ane0 : a ≠ 0) : associated (multiset.prod (factors a)) a := sorry theorem prime_of_factor {α : Type u_1} [comm_cancel_monoid_with_zero α] [DecidableEq α] [nontrivial α] [normalization_monoid α] [unique_factorization_monoid α] {a : α} (x : α) : x ∈ factors a → prime x := sorry theorem irreducible_of_factor {α : Type u_1} [comm_cancel_monoid_with_zero α] [DecidableEq α] [nontrivial α] [normalization_monoid α] [unique_factorization_monoid α] {a : α} (x : α) : x ∈ factors a → irreducible x := fun (h : x ∈ factors a) => irreducible_of_prime (prime_of_factor x h) theorem normalize_factor {α : Type u_1} [comm_cancel_monoid_with_zero α] [DecidableEq α] [nontrivial α] [normalization_monoid α] [unique_factorization_monoid α] {a : α} (x : α) : x ∈ factors a → coe_fn normalize x = x := sorry theorem factors_irreducible {α : Type u_1} [comm_cancel_monoid_with_zero α] [DecidableEq α] [nontrivial α] [normalization_monoid α] [unique_factorization_monoid α] {a : α} (ha : irreducible a) : factors a = coe_fn normalize a ::ₘ 0 := sorry theorem exists_mem_factors_of_dvd {α : Type u_1} [comm_cancel_monoid_with_zero α] [DecidableEq α] [nontrivial α] [normalization_monoid α] [unique_factorization_monoid α] {a : α} {p : α} (ha0 : a ≠ 0) (hp : irreducible p) : p ∣ a → ∃ (q : α), ∃ (H : q ∈ factors a), associated p q := sorry @[simp] theorem factors_zero {α : Type u_1} [comm_cancel_monoid_with_zero α] [DecidableEq α] [nontrivial α] [normalization_monoid α] [unique_factorization_monoid α] : factors 0 = 0 := dif_pos rfl @[simp] theorem factors_one {α : Type u_1} [comm_cancel_monoid_with_zero α] [DecidableEq α] [nontrivial α] [normalization_monoid α] [unique_factorization_monoid α] : factors 1 = 0 := sorry @[simp] theorem factors_mul {α : Type u_1} [comm_cancel_monoid_with_zero α] [DecidableEq α] [nontrivial α] [normalization_monoid α] [unique_factorization_monoid α] {x : α} {y : α} (hx : x ≠ 0) (hy : y ≠ 0) : factors (x * y) = factors x + factors y := sorry @[simp] theorem factors_pow {α : Type u_1} [comm_cancel_monoid_with_zero α] [DecidableEq α] [nontrivial α] [normalization_monoid α] [unique_factorization_monoid α] {x : α} (n : ℕ) : factors (x ^ n) = n •ℕ factors x := sorry theorem dvd_iff_factors_le_factors {α : Type u_1} [comm_cancel_monoid_with_zero α] [DecidableEq α] [nontrivial α] [normalization_monoid α] [unique_factorization_monoid α] {x : α} {y : α} (hx : x ≠ 0) (hy : y ≠ 0) : x ∣ y ↔ factors x ≤ factors y := sorry end unique_factorization_monoid namespace unique_factorization_monoid /-- Noncomputably defines a `normalization_monoid` structure on a `unique_factorization_monoid`. -/ protected def normalization_monoid {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [unique_factorization_monoid α] : normalization_monoid α := normalization_monoid_of_monoid_hom_right_inverse (monoid_hom.mk (fun (a : associates α) => ite (a = 0) 0 (multiset.prod (multiset.map (classical.some sorry) (factors a)))) sorry sorry) sorry protected instance normalization_monoid.inhabited {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [unique_factorization_monoid α] : Inhabited (normalization_monoid α) := { default := unique_factorization_monoid.normalization_monoid } end unique_factorization_monoid namespace unique_factorization_monoid theorem no_factors_of_no_prime_factors {R : Type u_2} [comm_cancel_monoid_with_zero R] [unique_factorization_monoid R] {a : R} {b : R} (ha : a ≠ 0) (h : ∀ {d : R}, d ∣ a → d ∣ b → ¬prime d) {d : R} : d ∣ a → d ∣ b → is_unit d := sorry /-- Euclid's lemma: if `a ∣ b * c` and `a` and `c` have no common prime factors, `a ∣ b`. Compare `is_coprime.dvd_of_dvd_mul_left`. -/ theorem dvd_of_dvd_mul_left_of_no_prime_factors {R : Type u_2} [comm_cancel_monoid_with_zero R] [unique_factorization_monoid R] {a : R} {b : R} {c : R} (ha : a ≠ 0) : (∀ {d : R}, d ∣ a → d ∣ c → ¬prime d) → a ∣ b * c → a ∣ b := sorry /-- Euclid's lemma: if `a ∣ b * c` and `a` and `b` have no common prime factors, `a ∣ c`. Compare `is_coprime.dvd_of_dvd_mul_right`. -/ theorem dvd_of_dvd_mul_right_of_no_prime_factors {R : Type u_2} [comm_cancel_monoid_with_zero R] [unique_factorization_monoid R] {a : R} {b : R} {c : R} (ha : a ≠ 0) (no_factors : ∀ {d : R}, d ∣ a → d ∣ b → ¬prime d) : a ∣ b * c → a ∣ c := sorry /-- If `a ≠ 0, b` are elements of a unique factorization domain, then dividing out their common factor `c'` gives `a'` and `b'` with no factors in common. -/ theorem exists_reduced_factors {R : Type u_2} [comm_cancel_monoid_with_zero R] [unique_factorization_monoid R] (a : R) (H : a ≠ 0) (b : R) : ∃ (a' : R), ∃ (b' : R), ∃ (c' : R), (∀ {d : R}, d ∣ a' → d ∣ b' → is_unit d) ∧ c' * a' = a ∧ c' * b' = b := sorry theorem exists_reduced_factors' {R : Type u_2} [comm_cancel_monoid_with_zero R] [unique_factorization_monoid R] (a : R) (b : R) (hb : b ≠ 0) : ∃ (a' : R), ∃ (b' : R), ∃ (c' : R), (∀ {d : R}, d ∣ a' → d ∣ b' → is_unit d) ∧ c' * a' = a ∧ c' * b' = b := sorry theorem le_multiplicity_iff_repeat_le_factors {R : Type u_2} [comm_cancel_monoid_with_zero R] [unique_factorization_monoid R] [nontrivial R] [normalization_monoid R] [DecidableEq R] [DecidableRel has_dvd.dvd] {a : R} {b : R} {n : ℕ} (ha : irreducible a) (hb : b ≠ 0) : ↑n ≤ multiplicity a b ↔ multiset.repeat (coe_fn normalize a) n ≤ factors b := sorry theorem multiplicity_eq_count_factors {R : Type u_2} [comm_cancel_monoid_with_zero R] [unique_factorization_monoid R] [nontrivial R] [normalization_monoid R] [DecidableEq R] [DecidableRel has_dvd.dvd] {a : R} {b : R} (ha : irreducible a) (hb : b ≠ 0) : multiplicity a b = ↑(multiset.count (coe_fn normalize a) (factors b)) := sorry end unique_factorization_monoid namespace associates /-- `factor_set α` representation elements of unique factorization domain as multisets. `multiset α` produced by `factors` are only unique up to associated elements, while the multisets in `factor_set α` are unqiue by equality and restricted to irreducible elements. This gives us a representation of each element as a unique multisets (or the added ⊤ for 0), which has a complete lattice struture. Infimum is the greatest common divisor and supremum is the least common multiple. -/ def factor_set (α : Type u) [comm_cancel_monoid_with_zero α] := with_top (multiset (Subtype fun (a : associates α) => irreducible a)) theorem factor_set.coe_add {α : Type u_1} [comm_cancel_monoid_with_zero α] {a : multiset (Subtype fun (a : associates α) => irreducible a)} {b : multiset (Subtype fun (a : associates α) => irreducible a)} : ↑(a + b) = ↑a + ↑b := sorry theorem factor_set.sup_add_inf_eq_add {α : Type u_1} [comm_cancel_monoid_with_zero α] [DecidableEq (associates α)] (a : factor_set α) (b : factor_set α) : a ⊔ b + a ⊓ b = a + b := sorry /-- Evaluates the product of a `factor_set` to be the product of the corresponding multiset, or `0` if there is none. -/ def factor_set.prod {α : Type u_1} [comm_cancel_monoid_with_zero α] : factor_set α → associates α := sorry @[simp] theorem prod_top {α : Type u_1} [comm_cancel_monoid_with_zero α] : factor_set.prod ⊤ = 0 := rfl @[simp] theorem prod_coe {α : Type u_1} [comm_cancel_monoid_with_zero α] {s : multiset (Subtype fun (a : associates α) => irreducible a)} : factor_set.prod ↑s = multiset.prod (multiset.map coe s) := rfl @[simp] theorem prod_add {α : Type u_1} [comm_cancel_monoid_with_zero α] (a : factor_set α) (b : factor_set α) : factor_set.prod (a + b) = factor_set.prod a * factor_set.prod b := sorry theorem prod_mono {α : Type u_1} [comm_cancel_monoid_with_zero α] {a : factor_set α} {b : factor_set α} : a ≤ b → factor_set.prod a ≤ factor_set.prod b := sorry /-- `bcount p s` is the multiplicity of `p` in the factor_set `s` (with bundled `p`)-/ def bcount {α : Type u_1} [comm_cancel_monoid_with_zero α] [DecidableEq (associates α)] (p : Subtype fun (a : associates α) => irreducible a) : factor_set α → ℕ := sorry /-- `count p s` is the multiplicity of the irreducible `p` in the factor_set `s`. If `p` is not irreducible, `count p s` is defined to be `0`. -/ def count {α : Type u_1} [comm_cancel_monoid_with_zero α] [dec_irr : (p : associates α) → Decidable (irreducible p)] [DecidableEq (associates α)] (p : associates α) : factor_set α → ℕ := dite (irreducible p) (fun (hp : irreducible p) => bcount { val := p, property := hp }) fun (hp : ¬irreducible p) => 0 @[simp] theorem count_some {α : Type u_1} [comm_cancel_monoid_with_zero α] [dec_irr : (p : associates α) → Decidable (irreducible p)] [DecidableEq (associates α)] {p : associates α} (hp : irreducible p) (s : multiset (Subtype fun (a : associates α) => irreducible a)) : count p (some s) = multiset.count { val := p, property := hp } s := sorry @[simp] theorem count_zero {α : Type u_1} [comm_cancel_monoid_with_zero α] [dec_irr : (p : associates α) → Decidable (irreducible p)] [DecidableEq (associates α)] {p : associates α} (hp : irreducible p) : count p 0 = 0 := sorry theorem count_reducible {α : Type u_1} [comm_cancel_monoid_with_zero α] [dec_irr : (p : associates α) → Decidable (irreducible p)] [DecidableEq (associates α)] {p : associates α} (hp : ¬irreducible p) : count p = 0 := dif_neg hp /-- membership in a factor_set (bundled version) -/ def bfactor_set_mem {α : Type u_1} [comm_cancel_monoid_with_zero α] : (Subtype fun (a : associates α) => irreducible a) → factor_set α → Prop := sorry /-- `factor_set_mem p s` is the predicate that the irreducible `p` is a member of `s : factor_set α`. If `p` is not irreducible, `p` is not a member of any `factor_set`. -/ def factor_set_mem {α : Type u_1} [comm_cancel_monoid_with_zero α] [dec_irr : (p : associates α) → Decidable (irreducible p)] (p : associates α) (s : factor_set α) := dite (irreducible p) (fun (hp : irreducible p) => bfactor_set_mem { val := p, property := hp } s) fun (hp : ¬irreducible p) => False protected instance factor_set.has_mem {α : Type u_1} [comm_cancel_monoid_with_zero α] [dec_irr : (p : associates α) → Decidable (irreducible p)] : has_mem (associates α) (factor_set α) := has_mem.mk factor_set_mem @[simp] theorem factor_set_mem_eq_mem {α : Type u_1} [comm_cancel_monoid_with_zero α] [dec_irr : (p : associates α) → Decidable (irreducible p)] (p : associates α) (s : factor_set α) : factor_set_mem p s = (p ∈ s) := rfl theorem mem_factor_set_top {α : Type u_1} [comm_cancel_monoid_with_zero α] [dec_irr : (p : associates α) → Decidable (irreducible p)] {p : associates α} {hp : irreducible p} : p ∈ ⊤ := id (id (eq.mpr (id (dif_pos hp)) trivial)) theorem mem_factor_set_some {α : Type u_1} [comm_cancel_monoid_with_zero α] [dec_irr : (p : associates α) → Decidable (irreducible p)] {p : associates α} {hp : irreducible p} {l : multiset (Subtype fun (a : associates α) => irreducible a)} : p ∈ ↑l ↔ { val := p, property := hp } ∈ l := sorry theorem reducible_not_mem_factor_set {α : Type u_1} [comm_cancel_monoid_with_zero α] [dec_irr : (p : associates α) → Decidable (irreducible p)] {p : associates α} (hp : ¬irreducible p) (s : factor_set α) : ¬p ∈ s := sorry theorem unique' {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] {p : multiset (associates α)} {q : multiset (associates α)} : (∀ (a : associates α), a ∈ p → irreducible a) → (∀ (a : associates α), a ∈ q → irreducible a) → multiset.prod p = multiset.prod q → p = q := sorry theorem prod_le_prod_iff_le {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] {p : multiset (associates α)} {q : multiset (associates α)} (hp : ∀ (a : associates α), a ∈ p → irreducible a) (hq : ∀ (a : associates α), a ∈ q → irreducible a) : multiset.prod p ≤ multiset.prod q ↔ p ≤ q := sorry /-- This returns the multiset of irreducible factors as a `factor_set`, a multiset of irreducible associates `with_top`. -/ def factors' {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] (a : α) : multiset (Subtype fun (a : associates α) => irreducible a) := multiset.pmap (fun (a : α) (ha : irreducible a) => { val := associates.mk a, property := sorry }) (unique_factorization_monoid.factors a) sorry @[simp] theorem map_subtype_coe_factors' {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] {a : α} : multiset.map coe (factors' a) = multiset.map associates.mk (unique_factorization_monoid.factors a) := sorry theorem factors'_cong {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] {a : α} {b : α} (ha : a ≠ 0) (hb : b ≠ 0) (h : associated a b) : factors' a = factors' b := sorry /-- This returns the multiset of irreducible factors of an associate as a `factor_set`, a multiset of irreducible associates `with_top`. -/ def factors {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] [dec' : DecidableEq (associates α)] (a : associates α) : factor_set α := dite (a = 0) (fun (h : a = 0) => ⊤) fun (h : ¬a = 0) => quotient.hrec_on a (fun (x : α) (h : ¬quotient.mk x = 0) => some (factors' x)) sorry h @[simp] theorem factors_0 {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] [dec' : DecidableEq (associates α)] : factors 0 = ⊤ := dif_pos rfl @[simp] theorem factors_mk {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] [dec' : DecidableEq (associates α)] (a : α) (h : a ≠ 0) : factors (associates.mk a) = ↑(factors' a) := dif_neg (mt (iff.mp mk_eq_zero) h) theorem prod_factors {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] [dec' : DecidableEq (associates α)] (s : factor_set α) : factors (factor_set.prod s) = s := sorry @[simp] theorem factors_prod {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] [dec' : DecidableEq (associates α)] (a : associates α) : factor_set.prod (factors a) = a := sorry theorem eq_of_factors_eq_factors {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] [dec' : DecidableEq (associates α)] {a : associates α} {b : associates α} (h : factors a = factors b) : a = b := sorry theorem eq_of_prod_eq_prod {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] {a : factor_set α} {b : factor_set α} (h : factor_set.prod a = factor_set.prod b) : a = b := sorry @[simp] theorem factors_mul {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] [dec' : DecidableEq (associates α)] (a : associates α) (b : associates α) : factors (a * b) = factors a + factors b := sorry theorem factors_mono {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] [dec' : DecidableEq (associates α)] {a : associates α} {b : associates α} : a ≤ b → factors a ≤ factors b := sorry theorem factors_le {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] [dec' : DecidableEq (associates α)] {a : associates α} {b : associates α} : factors a ≤ factors b ↔ a ≤ b := sorry theorem prod_le {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] {a : factor_set α} {b : factor_set α} : factor_set.prod a ≤ factor_set.prod b ↔ a ≤ b := sorry protected instance has_sup {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] [dec' : DecidableEq (associates α)] : has_sup (associates α) := has_sup.mk fun (a b : associates α) => factor_set.prod (factors a ⊔ factors b) protected instance has_inf {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] [dec' : DecidableEq (associates α)] : has_inf (associates α) := has_inf.mk fun (a b : associates α) => factor_set.prod (factors a ⊓ factors b) protected instance bounded_lattice {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] [dec' : DecidableEq (associates α)] : bounded_lattice (associates α) := bounded_lattice.mk has_sup.sup partial_order.le partial_order.lt sorry sorry sorry sorry sorry sorry has_inf.inf sorry sorry sorry order_top.top sorry order_bot.bot sorry theorem sup_mul_inf {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] [dec' : DecidableEq (associates α)] (a : associates α) (b : associates α) : (a ⊔ b) * (a ⊓ b) = a * b := sorry theorem dvd_of_mem_factors {α : Type u_1} [comm_cancel_monoid_with_zero α] [dec_irr : (p : associates α) → Decidable (irreducible p)] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] [dec' : DecidableEq (associates α)] {a : associates α} {p : associates α} {hp : irreducible p} (hm : p ∈ factors a) : p ∣ a := sorry theorem dvd_of_mem_factors' {α : Type u_1} [comm_cancel_monoid_with_zero α] [dec_irr : (p : associates α) → Decidable (irreducible p)] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] {a : α} {p : associates α} {hp : irreducible p} {hz : a ≠ 0} (h_mem : { val := p, property := hp } ∈ factors' a) : p ∣ associates.mk a := dvd_of_mem_factors (eq.mpr (id (Eq._oldrec (Eq.refl (p ∈ factors (associates.mk a))) (factors_mk a hz))) (iff.mpr mem_factor_set_some h_mem)) theorem mem_factors'_of_dvd {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] {a : α} {p : α} (ha0 : a ≠ 0) (hp : irreducible p) (hd : p ∣ a) : { val := associates.mk p, property := iff.mpr (irreducible_mk p) hp } ∈ factors' a := sorry theorem mem_factors'_iff_dvd {α : Type u_1} [comm_cancel_monoid_with_zero α] [dec_irr : (p : associates α) → Decidable (irreducible p)] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] {a : α} {p : α} (ha0 : a ≠ 0) (hp : irreducible p) : { val := associates.mk p, property := iff.mpr (irreducible_mk p) hp } ∈ factors' a ↔ p ∣ a := sorry theorem mem_factors_of_dvd {α : Type u_1} [comm_cancel_monoid_with_zero α] [dec_irr : (p : associates α) → Decidable (irreducible p)] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] [dec' : DecidableEq (associates α)] {a : α} {p : α} (ha0 : a ≠ 0) (hp : irreducible p) (hd : p ∣ a) : associates.mk p ∈ factors (associates.mk a) := eq.mpr (id (Eq._oldrec (Eq.refl (associates.mk p ∈ factors (associates.mk a))) (factors_mk a ha0))) (iff.mpr mem_factor_set_some (mem_factors'_of_dvd ha0 hp hd)) theorem mem_factors_iff_dvd {α : Type u_1} [comm_cancel_monoid_with_zero α] [dec_irr : (p : associates α) → Decidable (irreducible p)] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] [dec' : DecidableEq (associates α)] {a : α} {p : α} (ha0 : a ≠ 0) (hp : irreducible p) : associates.mk p ∈ factors (associates.mk a) ↔ p ∣ a := sorry theorem exists_prime_dvd_of_not_inf_one {α : Type u_1} [comm_cancel_monoid_with_zero α] [dec_irr : (p : associates α) → Decidable (irreducible p)] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] [dec' : DecidableEq (associates α)] {a : α} {b : α} (ha : a ≠ 0) (hb : b ≠ 0) (h : associates.mk a ⊓ associates.mk b ≠ 1) : ∃ (p : α), prime p ∧ p ∣ a ∧ p ∣ b := sorry theorem coprime_iff_inf_one {α : Type u_1} [comm_cancel_monoid_with_zero α] [dec_irr : (p : associates α) → Decidable (irreducible p)] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] [dec' : DecidableEq (associates α)] {a : α} {b : α} (ha0 : a ≠ 0) (hb0 : b ≠ 0) : associates.mk a ⊓ associates.mk b = 1 ↔ ∀ {d : α}, d ∣ a → d ∣ b → ¬prime d := sorry theorem factors_prime_pow {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] [dec' : DecidableEq (associates α)] {p : associates α} (hp : irreducible p) (k : ℕ) : factors (p ^ k) = some (multiset.repeat { val := p, property := hp } k) := sorry theorem prime_pow_dvd_iff_le {α : Type u_1} [comm_cancel_monoid_with_zero α] [dec_irr : (p : associates α) → Decidable (irreducible p)] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] [dec' : DecidableEq (associates α)] {m : associates α} {p : associates α} (h₁ : m ≠ 0) (h₂ : irreducible p) {k : ℕ} : p ^ k ≤ m ↔ k ≤ count p (factors m) := sorry theorem le_of_count_ne_zero {α : Type u_1} [comm_cancel_monoid_with_zero α] [dec_irr : (p : associates α) → Decidable (irreducible p)] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] [dec' : DecidableEq (associates α)] {m : associates α} {p : associates α} (h0 : m ≠ 0) (hp : irreducible p) : count p (factors m) ≠ 0 → p ≤ m := sorry theorem count_mul {α : Type u_1} [comm_cancel_monoid_with_zero α] [dec_irr : (p : associates α) → Decidable (irreducible p)] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] [dec' : DecidableEq (associates α)] {a : associates α} (ha : a ≠ 0) {b : associates α} (hb : b ≠ 0) {p : associates α} (hp : irreducible p) : count p (factors (a * b)) = count p (factors a) + count p (factors b) := sorry theorem count_of_coprime {α : Type u_1} [comm_cancel_monoid_with_zero α] [dec_irr : (p : associates α) → Decidable (irreducible p)] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] [dec' : DecidableEq (associates α)] {a : associates α} (ha : a ≠ 0) {b : associates α} (hb : b ≠ 0) (hab : ∀ (d : associates α), d ∣ a → d ∣ b → ¬prime d) {p : associates α} (hp : irreducible p) : count p (factors a) = 0 ∨ count p (factors b) = 0 := sorry theorem count_mul_of_coprime {α : Type u_1} [comm_cancel_monoid_with_zero α] [dec_irr : (p : associates α) → Decidable (irreducible p)] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] [dec' : DecidableEq (associates α)] {a : associates α} (ha : a ≠ 0) {b : associates α} (hb : b ≠ 0) {p : associates α} (hp : irreducible p) (hab : ∀ (d : associates α), d ∣ a → d ∣ b → ¬prime d) : count p (factors a) = 0 ∨ count p (factors a) = count p (factors (a * b)) := sorry theorem count_mul_of_coprime' {α : Type u_1} [comm_cancel_monoid_with_zero α] [dec_irr : (p : associates α) → Decidable (irreducible p)] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] [dec' : DecidableEq (associates α)] {a : associates α} (ha : a ≠ 0) {b : associates α} (hb : b ≠ 0) {p : associates α} (hp : irreducible p) (hab : ∀ (d : associates α), d ∣ a → d ∣ b → ¬prime d) : count p (factors (a * b)) = count p (factors a) ∨ count p (factors (a * b)) = count p (factors b) := sorry theorem dvd_count_of_dvd_count_mul {α : Type u_1} [comm_cancel_monoid_with_zero α] [dec_irr : (p : associates α) → Decidable (irreducible p)] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] [dec' : DecidableEq (associates α)] {a : associates α} {b : associates α} (ha : a ≠ 0) (hb : b ≠ 0) {p : associates α} (hp : irreducible p) (hab : ∀ (d : associates α), d ∣ a → d ∣ b → ¬prime d) {k : ℕ} (habk : k ∣ count p (factors (a * b))) : k ∣ count p (factors a) := sorry @[simp] theorem factors_one {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] [dec' : DecidableEq (associates α)] : factors 1 = 0 := eq_of_prod_eq_prod (eq.mpr (id (Eq._oldrec (Eq.refl (factor_set.prod (factors 1) = factor_set.prod 0)) (factors_prod 1))) multiset.prod_zero) @[simp] theorem pow_factors {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] [dec' : DecidableEq (associates α)] {a : associates α} {k : ℕ} : factors (a ^ k) = k •ℕ factors a := sorry theorem count_pow {α : Type u_1} [comm_cancel_monoid_with_zero α] [dec_irr : (p : associates α) → Decidable (irreducible p)] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] [dec' : DecidableEq (associates α)] {a : associates α} (ha : a ≠ 0) {p : associates α} (hp : irreducible p) (k : ℕ) : count p (factors (a ^ k)) = k * count p (factors a) := sorry theorem dvd_count_pow {α : Type u_1} [comm_cancel_monoid_with_zero α] [dec_irr : (p : associates α) → Decidable (irreducible p)] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] [dec' : DecidableEq (associates α)] {a : associates α} (ha : a ≠ 0) {p : associates α} (hp : irreducible p) (k : ℕ) : k ∣ count p (factors (a ^ k)) := eq.mpr (id (Eq._oldrec (Eq.refl (k ∣ count p (factors (a ^ k)))) (count_pow ha hp k))) (dvd_mul_right k (count p (factors a))) theorem is_pow_of_dvd_count {α : Type u_1} [comm_cancel_monoid_with_zero α] [dec_irr : (p : associates α) → Decidable (irreducible p)] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] [dec : DecidableEq α] [dec' : DecidableEq (associates α)] {a : associates α} (ha : a ≠ 0) {k : ℕ} (hk : ∀ (p : associates α), irreducible p → k ∣ count p (factors a)) : ∃ (b : associates α), a = b ^ k := sorry theorem eq_pow_of_mul_eq_pow {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] [nontrivial α] [normalization_monoid α] {a : associates α} {b : associates α} {c : associates α} (ha : a ≠ 0) (hb : b ≠ 0) (hab : ∀ (d : associates α), d ∣ a → d ∣ b → ¬prime d) {k : ℕ} (h : a * b = c ^ k) : ∃ (d : associates α), a = d ^ k := sorry end associates /-- `to_gcd_monoid` constructs a GCD monoid out of a normalization on a unique factorization domain. -/ def unique_factorization_monoid.to_gcd_monoid (α : Type u_1) [comm_cancel_monoid_with_zero α] [nontrivial α] [unique_factorization_monoid α] [normalization_monoid α] [DecidableEq (associates α)] [DecidableEq α] : gcd_monoid α := gcd_monoid.mk norm_unit norm_unit_zero norm_unit_mul norm_unit_coe_units (fun (a b : α) => associates.out (associates.mk a ⊓ associates.mk b)) (fun (a b : α) => associates.out (associates.mk a ⊔ associates.mk b)) sorry sorry sorry sorry sorry sorry sorry
a4170c54586ec1fe139828aa380ab09fcba6dd95
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Meta/Match/Basic.lean
16dd830117d7bcab32a38c40210e9b5e780b4f78
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
14,578
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Check import Lean.Meta.CollectFVars import Lean.Meta.Match.MatcherInfo import Lean.Meta.Match.CaseArraySizes namespace Lean.Meta.Match def mkNamedPattern (x h p : Expr) : MetaM Expr := mkAppM ``namedPattern #[x, p, h] def isNamedPattern (e : Expr) : Bool := let e := e.consumeMData e.getAppNumArgs == 4 && e.getAppFn.consumeMData.isConstOf ``namedPattern def isNamedPattern? (e : Expr) : Option Expr := let e := e.consumeMData if e.getAppNumArgs == 4 && e.getAppFn.consumeMData.isConstOf ``namedPattern then some e else none inductive Pattern : Type where | inaccessible (e : Expr) : Pattern | var (fvarId : FVarId) : Pattern | ctor (ctorName : Name) (us : List Level) (params : List Expr) (fields : List Pattern) : Pattern | val (e : Expr) : Pattern | arrayLit (type : Expr) (xs : List Pattern) : Pattern | as (varId : FVarId) (p : Pattern) (hId : FVarId) : Pattern deriving Inhabited namespace Pattern partial def toMessageData : Pattern → MessageData | inaccessible e => m!".({e})" | var varId => mkFVar varId | ctor ctorName _ _ [] => ctorName | ctor ctorName _ _ pats => m!"({ctorName}{pats.foldl (fun (msg : MessageData) pat => msg ++ " " ++ toMessageData pat) Format.nil})" | val e => e | arrayLit _ pats => m!"#[{MessageData.joinSep (pats.map toMessageData) ", "}]" | as varId p _ => m!"{mkFVar varId}@{toMessageData p}" partial def toExpr (p : Pattern) (annotate := false) : MetaM Expr := visit p where visit (p : Pattern) := do match p with | inaccessible e => if annotate then pure (mkInaccessible e) else pure e | var fvarId => pure $ mkFVar fvarId | val e => pure e | as fvarId p hId => -- TODO if annotate then mkNamedPattern (mkFVar fvarId) (mkFVar hId) (← visit p) else visit p | arrayLit type xs => let xs ← xs.mapM visit mkArrayLit type xs | ctor ctorName us params fields => let fields ← fields.mapM visit pure $ mkAppN (mkConst ctorName us) (params ++ fields).toArray /-- Apply the free variable substitution `s` to the given pattern -/ partial def applyFVarSubst (s : FVarSubst) : Pattern → Pattern | inaccessible e => inaccessible $ s.apply e | ctor n us ps fs => ctor n us (ps.map s.apply) $ fs.map (applyFVarSubst s) | val e => val $ s.apply e | arrayLit t xs => arrayLit (s.apply t) $ xs.map (applyFVarSubst s) | var fvarId => match s.find? fvarId with | some e => inaccessible e | none => var fvarId | as fvarId p hId => match s.find? fvarId with | none => as fvarId (applyFVarSubst s p) hId | some _ => applyFVarSubst s p def replaceFVarId (fvarId : FVarId) (v : Expr) (p : Pattern) : Pattern := let s : FVarSubst := {} p.applyFVarSubst (s.insert fvarId v) partial def hasExprMVar : Pattern → Bool | inaccessible e => e.hasExprMVar | ctor _ _ ps fs => ps.any (·.hasExprMVar) || fs.any hasExprMVar | val e => e.hasExprMVar | as _ p _ => hasExprMVar p | arrayLit t xs => t.hasExprMVar || xs.any hasExprMVar | _ => false partial def collectFVars (p : Pattern) : StateRefT CollectFVars.State MetaM Unit := do match p with | inaccessible e => e.collectFVars | ctor _ _ ps fs => ps.forM fun p => p.collectFVars fs.forM collectFVars | val e => e.collectFVars | arrayLit t xs => t.collectFVars; xs.forM collectFVars | as fvarId₁ p fvarId₂ => modify (·.add fvarId₁ |>.add fvarId₂); p.collectFVars | var fvarId => modify (·.add fvarId) end Pattern partial def instantiatePatternMVars : Pattern → MetaM Pattern | Pattern.inaccessible e => return Pattern.inaccessible (← instantiateMVars e) | Pattern.val e => return Pattern.val (← instantiateMVars e) | Pattern.ctor n us ps fields => return Pattern.ctor n us (← ps.mapM instantiateMVars) (← fields.mapM instantiatePatternMVars) | Pattern.as x p h => return Pattern.as x (← instantiatePatternMVars p) h | Pattern.arrayLit t xs => return Pattern.arrayLit (← instantiateMVars t) (← xs.mapM instantiatePatternMVars) | p => return p structure AltLHS where ref : Syntax fvarDecls : List LocalDecl -- Free variables used in the patterns. patterns : List Pattern -- We use `List Pattern` since we have nary match-expressions. def AltLHS.collectFVars (altLHS: AltLHS) : StateRefT CollectFVars.State MetaM Unit := do altLHS.fvarDecls.forM fun fvarDecl => fvarDecl.collectFVars altLHS.patterns.forM fun p => p.collectFVars def instantiateAltLHSMVars (altLHS : AltLHS) : MetaM AltLHS := return { altLHS with fvarDecls := (← altLHS.fvarDecls.mapM instantiateLocalDeclMVars), patterns := (← altLHS.patterns.mapM instantiatePatternMVars) } /-- `Match` alternative -/ structure Alt where /-- `Syntax` object for providing position information -/ ref : Syntax /-- Orginal alternative index. Alternatives can be split, this index is the original position of the alternative that generated this one. -/ idx : Nat /-- Right-hand-side of the alternative. -/ rhs : Expr /-- Alternative pattern variables. -/ fvarDecls : List LocalDecl /-- Alternative patterns. -/ patterns : List Pattern /-- Pending constraints `lhs ≋ rhs` that need to be solved before the alternative is considered acceptable. We generate them when processing inaccessible patterns. Note that `lhs` and `rhs` often have different types. After we perform additional case analysis, their types become definitionally equal. -/ cnstrs : List (Expr × Expr) deriving Inhabited namespace Alt partial def toMessageData (alt : Alt) : MetaM MessageData := do withExistingLocalDecls alt.fvarDecls do let msg := alt.fvarDecls.map fun d => m!"{d.toExpr}:({d.type})" let mut msg := m!"{msg} |- {alt.patterns.map Pattern.toMessageData} => {alt.rhs}" for (lhs, rhs) in alt.cnstrs do msg := m!"{msg}\n | {lhs} ≋ {rhs}" addMessageContext msg def applyFVarSubst (s : FVarSubst) (alt : Alt) : Alt := { alt with patterns := alt.patterns.map fun p => p.applyFVarSubst s, fvarDecls := alt.fvarDecls.map fun d => d.applyFVarSubst s, rhs := alt.rhs.applyFVarSubst s cnstrs := alt.cnstrs.map fun (lhs, rhs) => (lhs.applyFVarSubst s, rhs.applyFVarSubst s) } def replaceFVarId (fvarId : FVarId) (v : Expr) (alt : Alt) : Alt := { alt with patterns := alt.patterns.map fun p => p.replaceFVarId fvarId v, rhs := alt.rhs.replaceFVarId fvarId v fvarDecls := let decls := alt.fvarDecls.filter fun d => d.fvarId != fvarId decls.map (·.replaceFVarId fvarId v) cnstrs := alt.cnstrs.map fun (lhs, rhs) => (lhs.replaceFVarId fvarId v, rhs.replaceFVarId fvarId v) } /-- Return `true` if `fvarId` is one of the alternative pattern variables -/ def isLocalDecl (fvarId : FVarId) (alt : Alt) : Bool := alt.fvarDecls.any fun d => d.fvarId == fvarId /-- Similar to `checkAndReplaceFVarId`, but ensures type of `v` is definitionally equal to type of `fvarId`. This extra check is necessary when performing dependent elimination and inaccessible terms have been used. For example, consider the following code fragment: ``` inductive Vec (α : Type u) : Nat → Type u where | nil : Vec α 0 | cons {n} (head : α) (tail : Vec α n) : Vec α (n+1) inductive VecPred {α : Type u} (P : α → Prop) : {n : Nat} → Vec α n → Prop where | nil : VecPred P Vec.nil | cons {n : Nat} {head : α} {tail : Vec α n} : P head → VecPred P tail → VecPred P (Vec.cons head tail) theorem ex {α : Type u} (P : α → Prop) : {n : Nat} → (v : Vec α (n+1)) → VecPred P v → Exists P | _, Vec.cons head _, VecPred.cons h (w : VecPred P Vec.nil) => ⟨head, h⟩ ``` Recall that `_` in a pattern can be elaborated into pattern variable or an inaccessible term. The elaborator uses an inaccessible term when typing constraints restrict its value. Thus, in the example above, the `_` at `Vec.cons head _` becomes the inaccessible pattern `.(Vec.nil)` because the type ascription `(w : VecPred P Vec.nil)` propagates typing constraints that restrict its value to be `Vec.nil`. After elaboration the alternative becomes: ``` | .(0), @Vec.cons .(α) .(0) head .(Vec.nil), @VecPred.cons .(α) .(P) .(0) .(head) .(Vec.nil) h w => ⟨head, h⟩ ``` where ``` (head : α), (h: P head), (w : VecPred P Vec.nil) ``` Then, when we process this alternative in this module, the following check will detect that `w` has type `VecPred P Vec.nil`, when it is supposed to have type `VecPred P tail`. Note that if we had written ``` theorem ex {α : Type u} (P : α → Prop) : {n : Nat} → (v : Vec α (n+1)) → VecPred P v → Exists P | _, Vec.cons head Vec.nil, VecPred.cons h (w : VecPred P Vec.nil) => ⟨head, h⟩ ``` we would get the easier to digest error message ``` missing cases: _, (Vec.cons _ _ (Vec.cons _ _ _)), _ ``` -/ def checkAndReplaceFVarId (fvarId : FVarId) (v : Expr) (alt : Alt) : MetaM Alt := do match alt.fvarDecls.find? fun (fvarDecl : LocalDecl) => fvarDecl.fvarId == fvarId with | none => throwErrorAt alt.ref "unknown free pattern variable" | some fvarDecl => do let vType ← inferType v unless (← isDefEqGuarded fvarDecl.type vType) do withExistingLocalDecls alt.fvarDecls do let (expectedType, givenType) ← addPPExplicitToExposeDiff vType fvarDecl.type throwErrorAt alt.ref "type mismatch during dependent match-elimination at pattern variable '{mkFVar fvarDecl.fvarId}' with type{indentExpr givenType}\nexpected type{indentExpr expectedType}" return replaceFVarId fvarId v alt end Alt inductive Example where | var : FVarId → Example | underscore : Example | ctor : Name → List Example → Example | val : Expr → Example | arrayLit : List Example → Example namespace Example partial def replaceFVarId (fvarId : FVarId) (ex : Example) : Example → Example | var x => if x == fvarId then ex else var x | ctor n exs => ctor n $ exs.map (replaceFVarId fvarId ex) | arrayLit exs => arrayLit $ exs.map (replaceFVarId fvarId ex) | ex => ex partial def applyFVarSubst (s : FVarSubst) : Example → Example | var fvarId => match s.get fvarId with | Expr.fvar fvarId' => var fvarId' | _ => underscore | ctor n exs => ctor n $ exs.map (applyFVarSubst s) | arrayLit exs => arrayLit $ exs.map (applyFVarSubst s) | ex => ex partial def varsToUnderscore : Example → Example | var _ => underscore | ctor n exs => ctor n $ exs.map varsToUnderscore | arrayLit exs => arrayLit $ exs.map varsToUnderscore | ex => ex partial def toMessageData : Example → MessageData | var fvarId => mkFVar fvarId | ctor ctorName [] => mkConst ctorName | ctor ctorName exs => m!"({mkConst ctorName}{exs.foldl (fun msg pat => m!"{msg} {toMessageData pat}") Format.nil})" | arrayLit exs => "#" ++ MessageData.ofList (exs.map toMessageData) | val e => e | underscore => "_" end Example def examplesToMessageData (cex : List Example) : MessageData := MessageData.joinSep (cex.map (Example.toMessageData ∘ Example.varsToUnderscore)) ", " structure Problem where mvarId : MVarId vars : List Expr alts : List Alt examples : List Example deriving Inhabited def withGoalOf {α} (p : Problem) (x : MetaM α) : MetaM α := p.mvarId.withContext x def Problem.toMessageData (p : Problem) : MetaM MessageData := withGoalOf p do let alts ← p.alts.mapM Alt.toMessageData let vars ← p.vars.mapM fun x => do let xType ← inferType x; pure m!"{x}:({xType})" return m!"remaining variables: {vars}\nalternatives:{indentD (MessageData.joinSep alts Format.line)}\nexamples:{examplesToMessageData p.examples}\n" abbrev CounterExample := List Example def counterExampleToMessageData (cex : CounterExample) : MessageData := examplesToMessageData cex def counterExamplesToMessageData (cexs : List CounterExample) : MessageData := MessageData.joinSep (cexs.map counterExampleToMessageData) Format.line structure MatcherResult where matcher : Expr -- The matcher. It is not just `Expr.const matcherName` because the type of the major premises may contain free variables. counterExamples : List CounterExample unusedAltIdxs : List Nat addMatcher : MetaM Unit /-- Convert a expression occurring as the argument of a `match` motive application back into a `Pattern` For example, we can use this method to convert `x::y::xs` at ``` ... (motive : List Nat → Sort u_1) (xs : List Nat) (h_1 : (x y : Nat) → (xs : List Nat) → motive (x :: y :: xs)) ... ``` into a pattern object -/ partial def toPattern (e : Expr) : MetaM Pattern := do match inaccessible? e with | some t => return Pattern.inaccessible t | none => match e.arrayLit? with | some (α, lits) => return Pattern.arrayLit α (← lits.mapM toPattern) | none => if let some e := isNamedPattern? e then let p ← toPattern <| e.getArg! 2 match e.getArg! 1, e.getArg! 3 with | Expr.fvar x, Expr.fvar h => return Pattern.as x p h | _, _ => throwError "unexpected occurrence of auxiliary declaration 'namedPattern'" else if isMatchValue e then return Pattern.val e else if e.isFVar then return Pattern.var e.fvarId! else let newE ← whnf e if newE != e then toPattern newE else matchConstCtor e.getAppFn (fun _ => throwError "unexpected pattern{indentExpr e}") fun v us => do let args := e.getAppArgs unless args.size == v.numParams + v.numFields do throwError "unexpected pattern{indentExpr e}" let params := args.extract 0 v.numParams let fields := args.extract v.numParams args.size let fields ← fields.mapM toPattern return Pattern.ctor v.name us params.toList fields.toList end Lean.Meta.Match
8b10f16af553978cafd1c9d75da60c02f176ef7e
00de0c30dd1b090ed139f65c82ea6deb48c3f4c2
/src/category_theory/adjunction/basic.lean
82c75b27a77321af937377cb23699c58467419de
[ "Apache-2.0" ]
permissive
paulvanwamelen/mathlib
4b9c5c19eec71b475f3dd515cd8785f1c8515f26
79e296bdc9f83b9447dc1b81730d36f63a99f72d
refs/heads/master
1,667,766,172,625
1,590,239,595,000
1,590,239,595,000
266,392,625
0
0
Apache-2.0
1,590,257,277,000
1,590,257,277,000
null
UTF-8
Lean
false
false
10,900
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Johan Commelin -/ import category_theory.equivalence import data.equiv.basic namespace category_theory open category universes v₁ v₂ v₃ u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation local attribute [elab_simple] whisker_left whisker_right variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] /-- `F ⊣ G` represents the data of an adjunction between two functors `F : C ⥤ D` and `G : D ⥤ C`. `F` is the left adjoint and `G` is the right adjoint. -/ structure adjunction (F : C ⥤ D) (G : D ⥤ C) := (hom_equiv : Π (X Y), (F.obj X ⟶ Y) ≃ (X ⟶ G.obj Y)) (unit : 𝟭 C ⟶ F.comp G) (counit : G.comp F ⟶ 𝟭 D) (hom_equiv_unit' : Π {X Y f}, (hom_equiv X Y) f = (unit : _ ⟶ _).app X ≫ G.map f . obviously) (hom_equiv_counit' : Π {X Y g}, (hom_equiv X Y).symm g = F.map g ≫ counit.app Y . obviously) infix ` ⊣ `:15 := adjunction class is_left_adjoint (left : C ⥤ D) := (right : D ⥤ C) (adj : left ⊣ right) class is_right_adjoint (right : D ⥤ C) := (left : C ⥤ D) (adj : left ⊣ right) def left_adjoint (R : D ⥤ C) [is_right_adjoint R] : C ⥤ D := is_right_adjoint.left R def right_adjoint (L : C ⥤ D) [is_left_adjoint L] : D ⥤ C := is_left_adjoint.right L namespace adjunction restate_axiom hom_equiv_unit' restate_axiom hom_equiv_counit' attribute [simp, priority 10] hom_equiv_unit hom_equiv_counit section variables {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {X' X : C} {Y Y' : D} @[simp, priority 10] lemma hom_equiv_naturality_left_symm (f : X' ⟶ X) (g : X ⟶ G.obj Y) : (adj.hom_equiv X' Y).symm (f ≫ g) = F.map f ≫ (adj.hom_equiv X Y).symm g := by rw [hom_equiv_counit, F.map_comp, assoc, adj.hom_equiv_counit.symm] @[simp] lemma hom_equiv_naturality_left (f : X' ⟶ X) (g : F.obj X ⟶ Y) : (adj.hom_equiv X' Y) (F.map f ≫ g) = f ≫ (adj.hom_equiv X Y) g := by rw [← equiv.eq_symm_apply]; simp [-hom_equiv_unit] @[simp, priority 10] lemma hom_equiv_naturality_right (f : F.obj X ⟶ Y) (g : Y ⟶ Y') : (adj.hom_equiv X Y') (f ≫ g) = (adj.hom_equiv X Y) f ≫ G.map g := by rw [hom_equiv_unit, G.map_comp, ← assoc, ←hom_equiv_unit] @[simp] lemma hom_equiv_naturality_right_symm (f : X ⟶ G.obj Y) (g : Y ⟶ Y') : (adj.hom_equiv X Y').symm (f ≫ G.map g) = (adj.hom_equiv X Y).symm f ≫ g := by rw [equiv.symm_apply_eq]; simp [-hom_equiv_counit] @[simp] lemma left_triangle : (whisker_right adj.unit F) ≫ (whisker_left F adj.counit) = nat_trans.id _ := begin ext, dsimp, erw [← adj.hom_equiv_counit, equiv.symm_apply_eq, adj.hom_equiv_unit], simp end @[simp] lemma right_triangle : (whisker_left G adj.unit) ≫ (whisker_right adj.counit G) = nat_trans.id _ := begin ext, dsimp, erw [← adj.hom_equiv_unit, ← equiv.eq_symm_apply, adj.hom_equiv_counit], simp end @[simp, reassoc] lemma left_triangle_components : F.map (adj.unit.app X) ≫ adj.counit.app (F.obj X) = 𝟙 (F.obj X) := congr_arg (λ (t : nat_trans _ (𝟭 C ⋙ F)), t.app X) adj.left_triangle @[simp, reassoc] lemma right_triangle_components {Y : D} : adj.unit.app (G.obj Y) ≫ G.map (adj.counit.app Y) = 𝟙 (G.obj Y) := congr_arg (λ (t : nat_trans _ (G ⋙ 𝟭 C)), t.app Y) adj.right_triangle @[simp, reassoc] lemma counit_naturality {X Y : D} (f : X ⟶ Y) : F.map (G.map f) ≫ (adj.counit).app Y = (adj.counit).app X ≫ f := adj.counit.naturality f @[simp, reassoc] lemma unit_naturality {X Y : C} (f : X ⟶ Y) : (adj.unit).app X ≫ G.map (F.map f) = f ≫ (adj.unit).app Y := (adj.unit.naturality f).symm lemma hom_equiv_apply_eq {A : C} {B : D} (f : F.obj A ⟶ B) (g : A ⟶ G.obj B) : adj.hom_equiv A B f = g ↔ f = (adj.hom_equiv A B).symm g := ⟨λ h, by {cases h, simp}, λ h, by {cases h, simp}⟩ lemma eq_hom_equiv_apply {A : C} {B : D} (f : F.obj A ⟶ B) (g : A ⟶ G.obj B) : g = adj.hom_equiv A B f ↔ (adj.hom_equiv A B).symm g = f := ⟨λ h, by {cases h, simp}, λ h, by {cases h, simp}⟩ end end adjunction namespace adjunction structure core_hom_equiv (F : C ⥤ D) (G : D ⥤ C) := (hom_equiv : Π (X Y), (F.obj X ⟶ Y) ≃ (X ⟶ G.obj Y)) (hom_equiv_naturality_left_symm' : Π {X' X Y} (f : X' ⟶ X) (g : X ⟶ G.obj Y), (hom_equiv X' Y).symm (f ≫ g) = F.map f ≫ (hom_equiv X Y).symm g . obviously) (hom_equiv_naturality_right' : Π {X Y Y'} (f : F.obj X ⟶ Y) (g : Y ⟶ Y'), (hom_equiv X Y') (f ≫ g) = (hom_equiv X Y) f ≫ G.map g . obviously) namespace core_hom_equiv restate_axiom hom_equiv_naturality_left_symm' restate_axiom hom_equiv_naturality_right' attribute [simp, priority 10] hom_equiv_naturality_left_symm hom_equiv_naturality_right variables {F : C ⥤ D} {G : D ⥤ C} (adj : core_hom_equiv F G) {X' X : C} {Y Y' : D} @[simp] lemma hom_equiv_naturality_left (f : X' ⟶ X) (g : F.obj X ⟶ Y) : (adj.hom_equiv X' Y) (F.map f ≫ g) = f ≫ (adj.hom_equiv X Y) g := by rw [← equiv.eq_symm_apply]; simp @[simp] lemma hom_equiv_naturality_right_symm (f : X ⟶ G.obj Y) (g : Y ⟶ Y') : (adj.hom_equiv X Y').symm (f ≫ G.map g) = (adj.hom_equiv X Y).symm f ≫ g := by rw [equiv.symm_apply_eq]; simp end core_hom_equiv structure core_unit_counit (F : C ⥤ D) (G : D ⥤ C) := (unit : 𝟭 C ⟶ F.comp G) (counit : G.comp F ⟶ 𝟭 D) (left_triangle' : whisker_right unit F ≫ (functor.associator F G F).hom ≫ whisker_left F counit = nat_trans.id (𝟭 C ⋙ F) . obviously) (right_triangle' : whisker_left G unit ≫ (functor.associator G F G).inv ≫ whisker_right counit G = nat_trans.id (G ⋙ 𝟭 C) . obviously) namespace core_unit_counit restate_axiom left_triangle' restate_axiom right_triangle' attribute [simp] left_triangle right_triangle end core_unit_counit variables {F : C ⥤ D} {G : D ⥤ C} def mk_of_hom_equiv (adj : core_hom_equiv F G) : F ⊣ G := { unit := { app := λ X, (adj.hom_equiv X (F.obj X)) (𝟙 (F.obj X)), naturality' := begin intros, erw [← adj.hom_equiv_naturality_left, ← adj.hom_equiv_naturality_right], dsimp, simp end }, counit := { app := λ Y, (adj.hom_equiv _ _).inv_fun (𝟙 (G.obj Y)), naturality' := begin intros, erw [← adj.hom_equiv_naturality_left_symm, ← adj.hom_equiv_naturality_right_symm], dsimp, simp end }, hom_equiv_unit' := λ X Y f, by erw [← adj.hom_equiv_naturality_right]; simp, hom_equiv_counit' := λ X Y f, by erw [← adj.hom_equiv_naturality_left_symm]; simp, .. adj } def mk_of_unit_counit (adj : core_unit_counit F G) : F ⊣ G := { hom_equiv := λ X Y, { to_fun := λ f, adj.unit.app X ≫ G.map f, inv_fun := λ g, F.map g ≫ adj.counit.app Y, left_inv := λ f, begin change F.map (_ ≫ _) ≫ _ = _, rw [F.map_comp, assoc, ←functor.comp_map, adj.counit.naturality, ←assoc], convert id_comp f, have t := congr_arg (λ t : nat_trans _ _, t.app _) adj.left_triangle, dsimp at t, simp only [id_comp] at t, exact t, end, right_inv := λ g, begin change _ ≫ G.map (_ ≫ _) = _, rw [G.map_comp, ←assoc, ←functor.comp_map, ←adj.unit.naturality, assoc], convert comp_id g, have t := congr_arg (λ t : nat_trans _ _, t.app _) adj.right_triangle, dsimp at t, simp only [id_comp] at t, exact t, end }, .. adj } def id : 𝟭 C ⊣ 𝟭 C := { hom_equiv := λ X Y, equiv.refl _, unit := 𝟙 _, counit := 𝟙 _ } section variables {E : Type u₃} [ℰ : category.{v₃} E] (H : D ⥤ E) (I : E ⥤ D) def comp (adj₁ : F ⊣ G) (adj₂ : H ⊣ I) : F ⋙ H ⊣ I ⋙ G := { hom_equiv := λ X Z, equiv.trans (adj₂.hom_equiv _ _) (adj₁.hom_equiv _ _), unit := adj₁.unit ≫ (whisker_left F $ whisker_right adj₂.unit G) ≫ (functor.associator _ _ _).inv, counit := (functor.associator _ _ _).hom ≫ (whisker_left I $ whisker_right adj₁.counit H) ≫ adj₂.counit } end section construct_left -- Construction of a left adjoint. In order to construct a left -- adjoint to a functor G : D → C, it suffices to give the object part -- of a functor F : C → D together with isomorphisms Hom(FX, Y) ≃ -- Hom(X, GY) natural in Y. The action of F on morphisms can be -- constructed from this data. variables {F_obj : C → D} {G} variables (e : Π X Y, (F_obj X ⟶ Y) ≃ (X ⟶ G.obj Y)) variables (he : Π X Y Y' g h, e X Y' (h ≫ g) = e X Y h ≫ G.map g) include he private lemma he' {X Y Y'} (f g) : (e X Y').symm (f ≫ G.map g) = (e X Y).symm f ≫ g := by intros; rw [equiv.symm_apply_eq, he]; simp def left_adjoint_of_equiv : C ⥤ D := { obj := F_obj, map := λ X X' f, (e X (F_obj X')).symm (f ≫ e X' (F_obj X') (𝟙 _)), map_comp' := λ X X' X'' f f', begin rw [equiv.symm_apply_eq, he, equiv.apply_symm_apply], conv { to_rhs, rw [assoc, ←he, id_comp, equiv.apply_symm_apply] }, simp end } def adjunction_of_equiv_left : left_adjoint_of_equiv e he ⊣ G := mk_of_hom_equiv { hom_equiv := e, hom_equiv_naturality_left_symm' := begin intros, erw [← he' e he, ← equiv.apply_eq_iff_eq], simp [(he _ _ _ _ _).symm] end } end construct_left section construct_right -- Construction of a right adjoint, analogous to the above. variables {F} {G_obj : D → C} variables (e : Π X Y, (F.obj X ⟶ Y) ≃ (X ⟶ G_obj Y)) variables (he : Π X' X Y f g, e X' Y (F.map f ≫ g) = f ≫ e X Y g) include he private lemma he' {X' X Y} (f g) : F.map f ≫ (e X Y).symm g = (e X' Y).symm (f ≫ g) := by intros; rw [equiv.eq_symm_apply, he]; simp def right_adjoint_of_equiv : D ⥤ C := { obj := G_obj, map := λ Y Y' g, (e (G_obj Y) Y') ((e (G_obj Y) Y).symm (𝟙 _) ≫ g), map_comp' := λ Y Y' Y'' g g', begin rw [← equiv.eq_symm_apply, ← he' e he, equiv.symm_apply_apply], conv { to_rhs, rw [← assoc, he' e he, comp_id, equiv.symm_apply_apply] }, simp end } def adjunction_of_equiv_right : F ⊣ right_adjoint_of_equiv e he := mk_of_hom_equiv { hom_equiv := e, hom_equiv_naturality_left_symm' := by intros; rw [equiv.symm_apply_eq, he]; simp, hom_equiv_naturality_right' := begin intros X Y Y' g h, erw [←he, equiv.apply_eq_iff_eq, ←assoc, he' e he, comp_id, equiv.symm_apply_apply] end } end construct_right end adjunction open adjunction namespace equivalence def to_adjunction (e : C ≌ D) : e.functor ⊣ e.inverse := mk_of_unit_counit ⟨e.unit, e.counit, by { ext, dsimp, simp only [id_comp], exact e.functor_unit_comp _, }, by { ext, dsimp, simp only [id_comp], exact e.unit_inverse_comp _, }⟩ end equivalence namespace functor def adjunction (E : C ⥤ D) [is_equivalence E] : E ⊣ E.inv := (E.as_equivalence).to_adjunction end functor end category_theory
ac2902a70ead45e15c8e24bfedcea47d38dc6e30
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/data/real/nnreal.lean
97c376a9e5a87a5dd224019716b3f9f9637c7c39
[ "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
32,196
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import algebra.linear_ordered_comm_group_with_zero import algebra.big_operators.ring import data.real.basic import algebra.indicator_function import algebra.algebra.basic /-! # Nonnegative real numbers In this file we define `nnreal` (notation: `ℝ≥0`) to be the type of non-negative real numbers, a.k.a. the interval `[0, ∞)`. We also define the following operations and structures on `ℝ≥0`: * the order on `ℝ≥0` is the restriction of the order on `ℝ`; these relations define a conditionally complete linear order with a bottom element, `conditionally_complete_linear_order_bot`; * `a + b` and `a * b` are the restrictions of addition and multiplication of real numbers to `ℝ≥0`; these operations together with `0 = ⟨0, _⟩` and `1 = ⟨1, _⟩` turn `ℝ≥0` into a linear ordered archimedean commutative semifield; we have no typeclass for this in `mathlib` yet, so we define the following instances instead: - `linear_ordered_semiring ℝ≥0`; - `comm_semiring ℝ≥0`; - `canonically_ordered_comm_semiring ℝ≥0`; - `linear_ordered_comm_group_with_zero ℝ≥0`; - `archimedean ℝ≥0`. * `real.to_nnreal x` is defined as `⟨max x 0, _⟩`, i.e. `↑(real.to_nnreal x) = x` when `0 ≤ x` and `↑(real.to_nnreal x) = 0` otherwise. We also define an instance `can_lift ℝ ℝ≥0`. This instance can be used by the `lift` tactic to replace `x : ℝ` and `hx : 0 ≤ x` in the proof context with `x : ℝ≥0` while replacing all occurences of `x` with `↑x`. This tactic also works for a function `f : α → ℝ` with a hypothesis `hf : ∀ x, 0 ≤ f x`. ## Notations This file defines `ℝ≥0` as a localized notation for `nnreal`. -/ noncomputable theory open_locale classical big_operators /-- Nonnegative real numbers. -/ def nnreal := {r : ℝ // 0 ≤ r} localized "notation ` ℝ≥0 ` := nnreal" in nnreal namespace nnreal instance : has_coe ℝ≥0 ℝ := ⟨subtype.val⟩ /- Simp lemma to put back `n.val` into the normal form given by the coercion. -/ @[simp] lemma val_eq_coe (n : ℝ≥0) : n.val = n := rfl instance : can_lift ℝ ℝ≥0 := { coe := coe, cond := λ r, 0 ≤ r, prf := λ x hx, ⟨⟨x, hx⟩, rfl⟩ } protected lemma eq {n m : ℝ≥0} : (n : ℝ) = (m : ℝ) → n = m := subtype.eq protected lemma eq_iff {n m : ℝ≥0} : (n : ℝ) = (m : ℝ) ↔ n = m := iff.intro nnreal.eq (congr_arg coe) lemma ne_iff {x y : ℝ≥0} : (x : ℝ) ≠ (y : ℝ) ↔ x ≠ y := not_iff_not_of_iff $ nnreal.eq_iff /-- Reinterpret a real number `r` as a non-negative real number. Returns `0` if `r < 0`. -/ def _root_.real.to_nnreal (r : ℝ) : ℝ≥0 := ⟨max r 0, le_max_right _ _⟩ lemma _root_.real.coe_to_nnreal (r : ℝ) (hr : 0 ≤ r) : (real.to_nnreal r : ℝ) = r := max_eq_left hr lemma _root_.real.le_coe_to_nnreal (r : ℝ) : r ≤ real.to_nnreal r := le_max_left r 0 lemma coe_nonneg (r : ℝ≥0) : (0 : ℝ) ≤ r := r.2 @[norm_cast] theorem coe_mk (a : ℝ) (ha) : ((⟨a, ha⟩ : ℝ≥0) : ℝ) = a := rfl instance : has_zero ℝ≥0 := ⟨⟨0, le_refl 0⟩⟩ instance : has_one ℝ≥0 := ⟨⟨1, zero_le_one⟩⟩ instance : has_add ℝ≥0 := ⟨λa b, ⟨a + b, add_nonneg a.2 b.2⟩⟩ instance : has_sub ℝ≥0 := ⟨λa b, real.to_nnreal (a - b)⟩ instance : has_mul ℝ≥0 := ⟨λa b, ⟨a * b, mul_nonneg a.2 b.2⟩⟩ instance : has_inv ℝ≥0 := ⟨λa, ⟨(a.1)⁻¹, inv_nonneg.2 a.2⟩⟩ instance : has_div ℝ≥0 := ⟨λa b, ⟨a / b, div_nonneg a.2 b.2⟩⟩ instance : has_le ℝ≥0 := ⟨λ r s, (r:ℝ) ≤ s⟩ instance : has_bot ℝ≥0 := ⟨0⟩ instance : inhabited ℝ≥0 := ⟨0⟩ protected lemma coe_injective : function.injective (coe : ℝ≥0 → ℝ) := subtype.coe_injective @[simp, norm_cast] protected lemma coe_eq {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) = r₂ ↔ r₁ = r₂ := nnreal.coe_injective.eq_iff @[simp, norm_cast] protected lemma coe_zero : ((0 : ℝ≥0) : ℝ) = 0 := rfl @[simp, norm_cast] protected lemma coe_one : ((1 : ℝ≥0) : ℝ) = 1 := rfl @[simp, norm_cast] protected lemma coe_add (r₁ r₂ : ℝ≥0) : ((r₁ + r₂ : ℝ≥0) : ℝ) = r₁ + r₂ := rfl @[simp, norm_cast] protected lemma coe_mul (r₁ r₂ : ℝ≥0) : ((r₁ * r₂ : ℝ≥0) : ℝ) = r₁ * r₂ := rfl @[simp, norm_cast] protected lemma coe_inv (r : ℝ≥0) : ((r⁻¹ : ℝ≥0) : ℝ) = r⁻¹ := rfl @[simp, norm_cast] protected lemma coe_div (r₁ r₂ : ℝ≥0) : ((r₁ / r₂ : ℝ≥0) : ℝ) = r₁ / r₂ := rfl @[simp, norm_cast] protected lemma coe_bit0 (r : ℝ≥0) : ((bit0 r : ℝ≥0) : ℝ) = bit0 r := rfl @[simp, norm_cast] protected lemma coe_bit1 (r : ℝ≥0) : ((bit1 r : ℝ≥0) : ℝ) = bit1 r := rfl @[simp, norm_cast] protected lemma coe_sub {r₁ r₂ : ℝ≥0} (h : r₂ ≤ r₁) : ((r₁ - r₂ : ℝ≥0) : ℝ) = r₁ - r₂ := max_eq_left $ le_sub.2 $ by simp [show (r₂ : ℝ) ≤ r₁, from h] -- TODO: setup semifield! @[simp, norm_cast] protected lemma coe_eq_zero (r : ℝ≥0) : ↑r = (0 : ℝ) ↔ r = 0 := by rw [← nnreal.coe_zero, nnreal.coe_eq] @[simp, norm_cast] protected lemma coe_eq_one (r : ℝ≥0) : ↑r = (1 : ℝ) ↔ r = 1 := by rw [← nnreal.coe_one, nnreal.coe_eq] lemma coe_ne_zero {r : ℝ≥0} : (r : ℝ) ≠ 0 ↔ r ≠ 0 := by norm_cast instance : comm_semiring ℝ≥0 := { zero := 0, add := (+), one := 1, mul := (*), .. nnreal.coe_injective.comm_semiring _ rfl rfl (λ _ _, rfl) (λ _ _, rfl) } /-- Coercion `ℝ≥0 → ℝ` as a `ring_hom`. -/ def to_real_hom : ℝ≥0 →+* ℝ := ⟨coe, nnreal.coe_one, nnreal.coe_mul, nnreal.coe_zero, nnreal.coe_add⟩ @[simp] lemma coe_to_real_hom : ⇑to_real_hom = coe := rfl section actions /-- A `mul_action` over `ℝ` restricts to a `mul_action` over `ℝ≥0`. -/ instance {M : Type*} [mul_action ℝ M] : mul_action ℝ≥0 M := mul_action.comp_hom M to_real_hom.to_monoid_hom lemma smul_def {M : Type*} [mul_action ℝ M] (c : ℝ≥0) (x : M) : c • x = (c : ℝ) • x := rfl instance {M N : Type*} [mul_action ℝ M] [mul_action ℝ N] [has_scalar M N] [is_scalar_tower ℝ M N] : is_scalar_tower ℝ≥0 M N := { smul_assoc := λ r, (smul_assoc (r : ℝ) : _)} instance smul_comm_class_left {M N : Type*} [mul_action ℝ N] [has_scalar M N] [smul_comm_class ℝ M N] : smul_comm_class ℝ≥0 M N := { smul_comm := λ r, (smul_comm (r : ℝ) : _)} instance smul_comm_class_right {M N : Type*} [mul_action ℝ N] [has_scalar M N] [smul_comm_class M ℝ N] : smul_comm_class M ℝ≥0 N := { smul_comm := λ m r, (smul_comm m (r : ℝ) : _)} /-- A `distrib_mul_action` over `ℝ` restricts to a `distrib_mul_action` over `ℝ≥0`. -/ instance {M : Type*} [add_monoid M] [distrib_mul_action ℝ M] : distrib_mul_action ℝ≥0 M := distrib_mul_action.comp_hom M to_real_hom.to_monoid_hom /-- A `module` over `ℝ` restricts to a `module` over `ℝ≥0`. -/ instance {M : Type*} [add_comm_monoid M] [module ℝ M] : module ℝ≥0 M := module.comp_hom M to_real_hom /-- An `algebra` over `ℝ` restricts to an `algebra` over `ℝ≥0`. -/ instance {A : Type*} [semiring A] [algebra ℝ A] : algebra ℝ≥0 A := { smul := (•), commutes' := λ r x, by simp [algebra.commutes], smul_def' := λ r x, by simp [←algebra.smul_def (r : ℝ) x, smul_def], to_ring_hom := ((algebra_map ℝ A).comp (to_real_hom : ℝ≥0 →+* ℝ)) } -- verify that the above produces instances we might care about example : algebra ℝ≥0 ℝ := by apply_instance example : distrib_mul_action (units ℝ≥0) ℝ := by apply_instance end actions instance : comm_group_with_zero ℝ≥0 := { zero := 0, mul := (*), one := 1, inv := has_inv.inv, div := (/), .. nnreal.coe_injective.comm_group_with_zero _ rfl rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) } @[simp, norm_cast] lemma coe_indicator {α} (s : set α) (f : α → ℝ≥0) (a : α) : ((s.indicator f a : ℝ≥0) : ℝ) = s.indicator (λ x, f x) a := (to_real_hom : ℝ≥0 →+ ℝ).map_indicator _ _ _ @[simp, norm_cast] lemma coe_pow (r : ℝ≥0) (n : ℕ) : ((r^n : ℝ≥0) : ℝ) = r^n := to_real_hom.map_pow r n @[norm_cast] lemma coe_list_sum (l : list ℝ≥0) : ((l.sum : ℝ≥0) : ℝ) = (l.map coe).sum := to_real_hom.map_list_sum l @[norm_cast] lemma coe_list_prod (l : list ℝ≥0) : ((l.prod : ℝ≥0) : ℝ) = (l.map coe).prod := to_real_hom.map_list_prod l @[norm_cast] lemma coe_multiset_sum (s : multiset ℝ≥0) : ((s.sum : ℝ≥0) : ℝ) = (s.map coe).sum := to_real_hom.map_multiset_sum s @[norm_cast] lemma coe_multiset_prod (s : multiset ℝ≥0) : ((s.prod : ℝ≥0) : ℝ) = (s.map coe).prod := to_real_hom.map_multiset_prod s @[norm_cast] lemma coe_sum {α} {s : finset α} {f : α → ℝ≥0} : ↑(∑ a in s, f a) = ∑ a in s, (f a : ℝ) := to_real_hom.map_sum _ _ lemma _root_.real.to_nnreal_sum_of_nonneg {α} {s : finset α} {f : α → ℝ} (hf : ∀ a, a ∈ s → 0 ≤ f a) : real.to_nnreal (∑ a in s, f a) = ∑ a in s, real.to_nnreal (f a) := begin rw [←nnreal.coe_eq, nnreal.coe_sum, real.coe_to_nnreal _ (finset.sum_nonneg hf)], exact finset.sum_congr rfl (λ x hxs, by rw real.coe_to_nnreal _ (hf x hxs)), end @[norm_cast] lemma coe_prod {α} {s : finset α} {f : α → ℝ≥0} : ↑(∏ a in s, f a) = ∏ a in s, (f a : ℝ) := to_real_hom.map_prod _ _ lemma _root_.real.to_nnreal_prod_of_nonneg {α} {s : finset α} {f : α → ℝ} (hf : ∀ a, a ∈ s → 0 ≤ f a) : real.to_nnreal (∏ a in s, f a) = ∏ a in s, real.to_nnreal (f a) := begin rw [←nnreal.coe_eq, nnreal.coe_prod, real.coe_to_nnreal _ (finset.prod_nonneg hf)], exact finset.prod_congr rfl (λ x hxs, by rw real.coe_to_nnreal _ (hf x hxs)), end @[norm_cast] lemma nsmul_coe (r : ℝ≥0) (n : ℕ) : ↑(n • r) = n • (r:ℝ) := to_real_hom.to_add_monoid_hom.map_nsmul _ _ @[simp, norm_cast] protected lemma coe_nat_cast (n : ℕ) : (↑(↑n : ℝ≥0) : ℝ) = n := to_real_hom.map_nat_cast n instance : linear_order ℝ≥0 := linear_order.lift (coe : ℝ≥0 → ℝ) nnreal.coe_injective @[simp, norm_cast] protected lemma coe_le_coe {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) ≤ r₂ ↔ r₁ ≤ r₂ := iff.rfl @[simp, norm_cast] protected lemma coe_lt_coe {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) < r₂ ↔ r₁ < r₂ := iff.rfl @[simp, norm_cast] protected lemma coe_pos {r : ℝ≥0} : (0 : ℝ) < r ↔ 0 < r := iff.rfl protected lemma coe_mono : monotone (coe : ℝ≥0 → ℝ) := λ _ _, nnreal.coe_le_coe.2 protected lemma _root_.real.to_nnreal_mono : monotone real.to_nnreal := λ x y h, max_le_max h (le_refl 0) @[simp] lemma _root_.real.to_nnreal_coe {r : ℝ≥0} : real.to_nnreal r = r := nnreal.eq $ max_eq_left r.2 @[simp] lemma mk_coe_nat (n : ℕ) : @eq ℝ≥0 (⟨(n : ℝ), n.cast_nonneg⟩ : ℝ≥0) n := nnreal.eq (nnreal.coe_nat_cast n).symm @[simp] lemma to_nnreal_coe_nat (n : ℕ) : real.to_nnreal n = n := nnreal.eq $ by simp [real.coe_to_nnreal] /-- `real.to_nnreal` and `coe : ℝ≥0 → ℝ` form a Galois insertion. -/ protected def gi : galois_insertion real.to_nnreal coe := galois_insertion.monotone_intro nnreal.coe_mono real.to_nnreal_mono real.le_coe_to_nnreal (λ _, real.to_nnreal_coe) instance : order_bot ℝ≥0 := { bot := ⊥, bot_le := assume ⟨a, h⟩, h, .. nnreal.linear_order } instance : canonically_linear_ordered_add_monoid ℝ≥0 := { add_le_add_left := assume a b h c, nnreal.coe_le_coe.mp $ (add_le_add_left (nnreal.coe_le_coe.mpr h) c), le_iff_exists_add := assume ⟨a, ha⟩ ⟨b, hb⟩, iff.intro (assume h : a ≤ b, ⟨⟨b - a, le_sub_iff_add_le.2 $ (zero_add _).le.trans h⟩, nnreal.eq $ show b = a + (b - a), from (add_sub_cancel'_right _ _).symm⟩) (assume ⟨⟨c, hc⟩, eq⟩, eq.symm ▸ show a ≤ a + c, from (le_add_iff_nonneg_right a).2 hc), ..nnreal.comm_semiring, ..nnreal.order_bot, ..nnreal.linear_order } instance : linear_ordered_add_comm_monoid ℝ≥0 := { .. nnreal.comm_semiring, .. nnreal.canonically_linear_ordered_add_monoid } instance : distrib_lattice ℝ≥0 := by apply_instance instance : semilattice_inf_bot ℝ≥0 := { .. nnreal.order_bot, .. nnreal.distrib_lattice } instance : semilattice_sup_bot ℝ≥0 := { .. nnreal.order_bot, .. nnreal.distrib_lattice } instance : linear_ordered_semiring ℝ≥0 := { add_left_cancel := assume a b c h, nnreal.eq $ @add_left_cancel ℝ _ a b c (nnreal.eq_iff.2 h), le_of_add_le_add_left := assume a b c, @le_of_add_le_add_left ℝ _ _ _ a b c, mul_lt_mul_of_pos_left := assume a b c, @mul_lt_mul_of_pos_left ℝ _ a b c, mul_lt_mul_of_pos_right := assume a b c, @mul_lt_mul_of_pos_right ℝ _ a b c, zero_le_one := @zero_le_one ℝ _, exists_pair_ne := ⟨0, 1, ne_of_lt (@zero_lt_one ℝ _ _)⟩, .. nnreal.canonically_linear_ordered_add_monoid, .. nnreal.comm_semiring } instance : ordered_comm_semiring ℝ≥0 := { .. nnreal.linear_ordered_semiring, .. nnreal.comm_semiring } instance : linear_ordered_comm_group_with_zero ℝ≥0 := { mul_le_mul_left := assume a b h c, mul_le_mul (le_refl c) h (zero_le a) (zero_le c), zero_le_one := zero_le 1, .. nnreal.linear_ordered_semiring, .. nnreal.comm_group_with_zero } instance : canonically_ordered_comm_semiring ℝ≥0 := { .. nnreal.canonically_linear_ordered_add_monoid, .. nnreal.comm_semiring, .. (show no_zero_divisors ℝ≥0, by apply_instance), .. nnreal.comm_group_with_zero } instance : densely_ordered ℝ≥0 := ⟨assume a b (h : (a : ℝ) < b), let ⟨c, hac, hcb⟩ := exists_between h in ⟨⟨c, le_trans a.property $ le_of_lt $ hac⟩, hac, hcb⟩⟩ instance : no_top_order ℝ≥0 := ⟨assume a, let ⟨b, hb⟩ := no_top (a:ℝ) in ⟨⟨b, le_trans a.property $ le_of_lt $ hb⟩, hb⟩⟩ lemma bdd_above_coe {s : set ℝ≥0} : bdd_above ((coe : ℝ≥0 → ℝ) '' s) ↔ bdd_above s := iff.intro (assume ⟨b, hb⟩, ⟨real.to_nnreal b, assume ⟨y, hy⟩ hys, show y ≤ max b 0, from le_max_of_le_left $ hb $ set.mem_image_of_mem _ hys⟩) (assume ⟨b, hb⟩, ⟨b, assume y ⟨x, hx, eq⟩, eq ▸ hb hx⟩) lemma bdd_below_coe (s : set ℝ≥0) : bdd_below ((coe : ℝ≥0 → ℝ) '' s) := ⟨0, assume r ⟨q, _, eq⟩, eq ▸ q.2⟩ instance : conditionally_complete_linear_order_bot ℝ≥0 := { cSup_empty := (function.funext_iff.1 (@subset_Sup_def ℝ (set.Ici (0 : ℝ)) _ ⟨(0 : ℝ≥0)⟩) ∅).trans $ nnreal.eq $ by simp, .. nnreal.order_bot, .. @ord_connected_subset_conditionally_complete_linear_order ℝ (set.Ici (0 : ℝ)) _ ⟨(0 : ℝ≥0)⟩ _ } lemma coe_Sup (s : set ℝ≥0) : (↑(Sup s) : ℝ) = Sup ((coe : ℝ≥0 → ℝ) '' s) := eq.symm $ @subset_Sup_of_within ℝ (set.Ici 0) _ ⟨(0 : ℝ≥0)⟩ s $ real.Sup_nonneg _ $ λ y ⟨x, _, hy⟩, hy ▸ x.2 lemma coe_Inf (s : set ℝ≥0) : (↑(Inf s) : ℝ) = Inf ((coe : ℝ≥0 → ℝ) '' s) := eq.symm $ @subset_Inf_of_within ℝ (set.Ici 0) _ ⟨(0 : ℝ≥0)⟩ s $ real.Inf_nonneg _ $ λ y ⟨x, _, hy⟩, hy ▸ x.2 instance : archimedean ℝ≥0 := ⟨ assume x y pos_y, let ⟨n, hr⟩ := archimedean.arch (x:ℝ) (pos_y : (0 : ℝ) < y) in ⟨n, show (x:ℝ) ≤ (n • y : ℝ≥0), by simp [*, -nsmul_eq_mul, nsmul_coe]⟩ ⟩ lemma le_of_forall_pos_le_add {a b : ℝ≥0} (h : ∀ε, 0 < ε → a ≤ b + ε) : a ≤ b := le_of_forall_le_of_dense $ assume x hxb, begin rcases le_iff_exists_add.1 (le_of_lt hxb) with ⟨ε, rfl⟩, exact h _ ((lt_add_iff_pos_right b).1 hxb) end -- TODO: generalize to some ordered add_monoids, based on #6145 lemma le_of_add_le_left {a b c : ℝ≥0} (h : a + b ≤ c) : a ≤ c := by { refine le_trans _ h, simp } lemma le_of_add_le_right {a b c : ℝ≥0} (h : a + b ≤ c) : b ≤ c := by { refine le_trans _ h, simp } lemma lt_iff_exists_rat_btwn (a b : ℝ≥0) : a < b ↔ (∃q:ℚ, 0 ≤ q ∧ a < real.to_nnreal q ∧ real.to_nnreal q < b) := iff.intro (assume (h : (↑a:ℝ) < (↑b:ℝ)), let ⟨q, haq, hqb⟩ := exists_rat_btwn h in have 0 ≤ (q : ℝ), from le_trans a.2 $ le_of_lt haq, ⟨q, rat.cast_nonneg.1 this, by simp [real.coe_to_nnreal _ this, nnreal.coe_lt_coe.symm, haq, hqb]⟩) (assume ⟨q, _, haq, hqb⟩, lt_trans haq hqb) lemma bot_eq_zero : (⊥ : ℝ≥0) = 0 := rfl lemma mul_sup (a b c : ℝ≥0) : a * (b ⊔ c) = (a * b) ⊔ (a * c) := begin cases le_total b c with h h, { simp [sup_eq_max, max_eq_right h, max_eq_right (mul_le_mul_of_nonneg_left h (zero_le a))] }, { simp [sup_eq_max, max_eq_left h, max_eq_left (mul_le_mul_of_nonneg_left h (zero_le a))] }, end lemma mul_finset_sup {α} {f : α → ℝ≥0} {s : finset α} (r : ℝ≥0) : r * s.sup f = s.sup (λa, r * f a) := begin refine s.induction_on _ _, { simp [bot_eq_zero] }, { assume a s has ih, simp [has, ih, mul_sup], } end lemma finset_sup_div {α} {f : α → ℝ≥0} {s : finset α} (r : ℝ≥0) : s.sup f / r = s.sup (λ a, f a / r) := by simp only [div_eq_inv_mul, mul_finset_sup] @[simp, norm_cast] lemma coe_max (x y : ℝ≥0) : ((max x y : ℝ≥0) : ℝ) = max (x : ℝ) (y : ℝ) := by { delta max, split_ifs; refl } @[simp, norm_cast] lemma coe_min (x y : ℝ≥0) : ((min x y : ℝ≥0) : ℝ) = min (x : ℝ) (y : ℝ) := by { delta min, split_ifs; refl } @[simp] lemma zero_le_coe {q : ℝ≥0} : 0 ≤ (q : ℝ) := q.2 end nnreal namespace real section to_nnreal @[simp] lemma to_nnreal_zero : real.to_nnreal 0 = 0 := by simp [real.to_nnreal]; refl @[simp] lemma to_nnreal_one : real.to_nnreal 1 = 1 := by simp [real.to_nnreal, max_eq_left (zero_le_one : (0 :ℝ) ≤ 1)]; refl @[simp] lemma to_nnreal_pos {r : ℝ} : 0 < real.to_nnreal r ↔ 0 < r := by simp [real.to_nnreal, nnreal.coe_lt_coe.symm, lt_irrefl] @[simp] lemma to_nnreal_eq_zero {r : ℝ} : real.to_nnreal r = 0 ↔ r ≤ 0 := by simpa [-to_nnreal_pos] using (not_iff_not.2 (@to_nnreal_pos r)) lemma to_nnreal_of_nonpos {r : ℝ} : r ≤ 0 → real.to_nnreal r = 0 := to_nnreal_eq_zero.2 @[simp] lemma coe_to_nnreal' (r : ℝ) : (real.to_nnreal r : ℝ) = max r 0 := rfl @[simp] lemma to_nnreal_le_to_nnreal_iff {r p : ℝ} (hp : 0 ≤ p) : real.to_nnreal r ≤ real.to_nnreal p ↔ r ≤ p := by simp [nnreal.coe_le_coe.symm, real.to_nnreal, hp] @[simp] lemma to_nnreal_lt_to_nnreal_iff' {r p : ℝ} : real.to_nnreal r < real.to_nnreal p ↔ r < p ∧ 0 < p := by simp [nnreal.coe_lt_coe.symm, real.to_nnreal, lt_irrefl] lemma to_nnreal_lt_to_nnreal_iff {r p : ℝ} (h : 0 < p) : real.to_nnreal r < real.to_nnreal p ↔ r < p := to_nnreal_lt_to_nnreal_iff'.trans (and_iff_left h) lemma to_nnreal_lt_to_nnreal_iff_of_nonneg {r p : ℝ} (hr : 0 ≤ r) : real.to_nnreal r < real.to_nnreal p ↔ r < p := to_nnreal_lt_to_nnreal_iff'.trans ⟨and.left, λ h, ⟨h, lt_of_le_of_lt hr h⟩⟩ @[simp] lemma to_nnreal_add {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) : real.to_nnreal (r + p) = real.to_nnreal r + real.to_nnreal p := nnreal.eq $ by simp [real.to_nnreal, hr, hp, add_nonneg] lemma to_nnreal_add_to_nnreal {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) : real.to_nnreal r + real.to_nnreal p = real.to_nnreal (r + p) := (real.to_nnreal_add hr hp).symm lemma to_nnreal_le_to_nnreal {r p : ℝ} (h : r ≤ p) : real.to_nnreal r ≤ real.to_nnreal p := real.to_nnreal_mono h lemma to_nnreal_add_le {r p : ℝ} : real.to_nnreal (r + p) ≤ real.to_nnreal r + real.to_nnreal p := nnreal.coe_le_coe.1 $ max_le (add_le_add (le_max_left _ _) (le_max_left _ _)) nnreal.zero_le_coe lemma to_nnreal_le_iff_le_coe {r : ℝ} {p : ℝ≥0} : real.to_nnreal r ≤ p ↔ r ≤ ↑p := nnreal.gi.gc r p lemma le_to_nnreal_iff_coe_le {r : ℝ≥0} {p : ℝ} (hp : 0 ≤ p) : r ≤ real.to_nnreal p ↔ ↑r ≤ p := by rw [← nnreal.coe_le_coe, real.coe_to_nnreal p hp] lemma le_to_nnreal_iff_coe_le' {r : ℝ≥0} {p : ℝ} (hr : 0 < r) : r ≤ real.to_nnreal p ↔ ↑r ≤ p := (le_or_lt 0 p).elim le_to_nnreal_iff_coe_le $ λ hp, by simp only [(hp.trans_le r.coe_nonneg).not_le, to_nnreal_eq_zero.2 hp.le, hr.not_le] lemma to_nnreal_lt_iff_lt_coe {r : ℝ} {p : ℝ≥0} (ha : 0 ≤ r) : real.to_nnreal r < p ↔ r < ↑p := by rw [← nnreal.coe_lt_coe, real.coe_to_nnreal r ha] lemma lt_to_nnreal_iff_coe_lt {r : ℝ≥0} {p : ℝ} : r < real.to_nnreal p ↔ ↑r < p := begin cases le_total 0 p, { rw [← nnreal.coe_lt_coe, real.coe_to_nnreal p h] }, { rw [to_nnreal_eq_zero.2 h], split, { intro, have := not_lt_of_le (zero_le r), contradiction }, { intro rp, have : ¬(p ≤ 0) := not_le_of_lt (lt_of_le_of_lt (nnreal.coe_nonneg _) rp), contradiction } } end @[simp] lemma to_nnreal_bit0 {r : ℝ} (hr : 0 ≤ r) : real.to_nnreal (bit0 r) = bit0 (real.to_nnreal r) := real.to_nnreal_add hr hr @[simp] lemma to_nnreal_bit1 {r : ℝ} (hr : 0 ≤ r) : real.to_nnreal (bit1 r) = bit1 (real.to_nnreal r) := (real.to_nnreal_add (by simp [hr]) zero_le_one).trans (by simp [to_nnreal_one, bit1, hr]) end to_nnreal end real open real namespace nnreal section mul lemma mul_eq_mul_left {a b c : ℝ≥0} (h : a ≠ 0) : (a * b = a * c ↔ b = c) := begin rw [← nnreal.eq_iff, ← nnreal.eq_iff, nnreal.coe_mul, nnreal.coe_mul], split, { exact mul_left_cancel' (mt (@nnreal.eq_iff a 0).1 h) }, { assume h, rw [h] } end lemma _root_.real.to_nnreal_mul {p q : ℝ} (hp : 0 ≤ p) : real.to_nnreal (p * q) = real.to_nnreal p * real.to_nnreal q := begin cases le_total 0 q with hq hq, { apply nnreal.eq, simp [real.to_nnreal, hp, hq, max_eq_left, mul_nonneg] }, { have hpq := mul_nonpos_of_nonneg_of_nonpos hp hq, rw [to_nnreal_eq_zero.2 hq, to_nnreal_eq_zero.2 hpq, mul_zero] } end end mul section pow lemma pow_mono_decr_exp {a : ℝ≥0} (m n : ℕ) (mn : m ≤ n) (a1 : a ≤ 1) : a ^ n ≤ a ^ m := begin rcases le_iff_exists_add.mp mn with ⟨k, rfl⟩, rw [← mul_one (a ^ m), pow_add], refine mul_le_mul rfl.le (pow_le_one _ (zero_le a) a1) _ _; exact pow_nonneg (zero_le _) _, end end pow section sub lemma sub_def {r p : ℝ≥0} : r - p = real.to_nnreal (r - p) := rfl lemma sub_eq_zero {r p : ℝ≥0} (h : r ≤ p) : r - p = 0 := nnreal.eq $ max_eq_right $ sub_le_iff_le_add.2 $ by simpa [nnreal.coe_le_coe] using h @[simp] lemma sub_self {r : ℝ≥0} : r - r = 0 := sub_eq_zero $ le_refl r @[simp] lemma sub_zero {r : ℝ≥0} : r - 0 = r := by rw [sub_def, nnreal.coe_zero, sub_zero, real.to_nnreal_coe] lemma sub_pos {r p : ℝ≥0} : 0 < r - p ↔ p < r := to_nnreal_pos.trans $ sub_pos.trans $ nnreal.coe_lt_coe protected lemma sub_lt_self {r p : ℝ≥0} : 0 < r → 0 < p → r - p < r := assume hr hp, begin cases le_total r p, { rwa [sub_eq_zero h] }, { rw [← nnreal.coe_lt_coe, nnreal.coe_sub h], exact sub_lt_self _ hp } end @[simp] lemma sub_le_iff_le_add {r p q : ℝ≥0} : r - p ≤ q ↔ r ≤ q + p := match le_total p r with | or.inl h := by rw [← nnreal.coe_le_coe, ← nnreal.coe_le_coe, nnreal.coe_sub h, nnreal.coe_add, sub_le_iff_le_add] | or.inr h := have r ≤ p + q, from le_add_right h, by simpa [nnreal.coe_le_coe, nnreal.coe_le_coe, sub_eq_zero h, add_comm] end @[simp] lemma sub_le_self {r p : ℝ≥0} : r - p ≤ r := sub_le_iff_le_add.2 $ le_add_right $ le_refl r lemma add_sub_cancel {r p : ℝ≥0} : (p + r) - r = p := nnreal.eq $ by rw [nnreal.coe_sub, nnreal.coe_add, add_sub_cancel]; exact le_add_self lemma add_sub_cancel' {r p : ℝ≥0} : (r + p) - r = p := by rw [add_comm, add_sub_cancel] lemma sub_add_eq_max {r p : ℝ≥0} : (r - p) + p = max r p := nnreal.eq $ by rw [sub_def, nnreal.coe_add, coe_max, real.to_nnreal, coe_mk, ← max_add_add_right, zero_add, sub_add_cancel] lemma add_sub_eq_max {r p : ℝ≥0} : p + (r - p) = max p r := by rw [add_comm, sub_add_eq_max, max_comm] @[simp] lemma sub_add_cancel_of_le {a b : ℝ≥0} (h : b ≤ a) : (a - b) + b = a := by rw [sub_add_eq_max, max_eq_left h] lemma sub_sub_cancel_of_le {r p : ℝ≥0} (h : r ≤ p) : p - (p - r) = r := by rw [nnreal.sub_def, nnreal.sub_def, real.coe_to_nnreal _ $ sub_nonneg.2 h, sub_sub_cancel, real.to_nnreal_coe] lemma lt_sub_iff_add_lt {p q r : ℝ≥0} : p < q - r ↔ p + r < q := begin split, { assume H, have : (((q - r) : ℝ≥0) : ℝ) = (q : ℝ) - (r : ℝ) := nnreal.coe_sub (le_of_lt (sub_pos.1 (lt_of_le_of_lt (zero_le _) H))), rwa [← nnreal.coe_lt_coe, this, lt_sub_iff_add_lt, ← nnreal.coe_add] at H }, { assume H, have : r ≤ q := le_trans (le_add_self) (le_of_lt H), rwa [← nnreal.coe_lt_coe, nnreal.coe_sub this, lt_sub_iff_add_lt, ← nnreal.coe_add] } end lemma sub_lt_iff_lt_add {a b c : ℝ≥0} (h : b ≤ a) : a - b < c ↔ a < b + c := by simp only [←nnreal.coe_lt_coe, nnreal.coe_sub h, nnreal.coe_add, sub_lt_iff_lt_add'] lemma sub_eq_iff_eq_add {a b c : ℝ≥0} (h : b ≤ a) : a - b = c ↔ a = c + b := by rw [←nnreal.eq_iff, nnreal.coe_sub h, ←nnreal.eq_iff, nnreal.coe_add, sub_eq_iff_eq_add] end sub section inv lemma sum_div {ι} (s : finset ι) (f : ι → ℝ≥0) (b : ℝ≥0) : (∑ i in s, f i) / b = ∑ i in s, (f i / b) := by simp only [div_eq_mul_inv, finset.sum_mul] @[simp] lemma inv_pos {r : ℝ≥0} : 0 < r⁻¹ ↔ 0 < r := by simp [pos_iff_ne_zero] lemma div_pos {r p : ℝ≥0} (hr : 0 < r) (hp : 0 < p) : 0 < r / p := by simpa only [div_eq_mul_inv] using mul_pos hr (inv_pos.2 hp) protected lemma mul_inv {r p : ℝ≥0} : (r * p)⁻¹ = p⁻¹ * r⁻¹ := nnreal.eq $ mul_inv_rev' _ _ lemma div_self_le (r : ℝ≥0) : r / r ≤ 1 := if h : r = 0 then by simp [h] else by rw [div_self h] @[simp] lemma inv_le {r p : ℝ≥0} (h : r ≠ 0) : r⁻¹ ≤ p ↔ 1 ≤ r * p := by rw [← mul_le_mul_left (pos_iff_ne_zero.2 h), mul_inv_cancel h] lemma inv_le_of_le_mul {r p : ℝ≥0} (h : 1 ≤ r * p) : r⁻¹ ≤ p := by by_cases r = 0; simp [*, inv_le] @[simp] lemma le_inv_iff_mul_le {r p : ℝ≥0} (h : p ≠ 0) : (r ≤ p⁻¹ ↔ r * p ≤ 1) := by rw [← mul_le_mul_left (pos_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm] @[simp] lemma lt_inv_iff_mul_lt {r p : ℝ≥0} (h : p ≠ 0) : (r < p⁻¹ ↔ r * p < 1) := by rw [← mul_lt_mul_left (pos_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm] lemma mul_le_iff_le_inv {a b r : ℝ≥0} (hr : r ≠ 0) : r * a ≤ b ↔ a ≤ r⁻¹ * b := have 0 < r, from lt_of_le_of_ne (zero_le r) hr.symm, by rw [← @mul_le_mul_left _ _ a _ r this, ← mul_assoc, mul_inv_cancel hr, one_mul] lemma le_div_iff_mul_le {a b r : ℝ≥0} (hr : r ≠ 0) : a ≤ b / r ↔ a * r ≤ b := by rw [div_eq_inv_mul, ← mul_le_iff_le_inv hr, mul_comm] lemma div_le_iff {a b r : ℝ≥0} (hr : r ≠ 0) : a / r ≤ b ↔ a ≤ b * r := @div_le_iff ℝ _ a r b $ pos_iff_ne_zero.2 hr lemma div_le_iff' {a b r : ℝ≥0} (hr : r ≠ 0) : a / r ≤ b ↔ a ≤ r * b := @div_le_iff' ℝ _ a r b $ pos_iff_ne_zero.2 hr lemma div_le_of_le_mul {a b c : ℝ≥0} (h : a ≤ b * c) : a / c ≤ b := if h0 : c = 0 then by simp [h0] else (div_le_iff h0).2 h lemma div_le_of_le_mul' {a b c : ℝ≥0} (h : a ≤ b * c) : a / b ≤ c := div_le_of_le_mul $ mul_comm b c ▸ h lemma le_div_iff {a b r : ℝ≥0} (hr : r ≠ 0) : a ≤ b / r ↔ a * r ≤ b := @le_div_iff ℝ _ a b r $ pos_iff_ne_zero.2 hr lemma le_div_iff' {a b r : ℝ≥0} (hr : r ≠ 0) : a ≤ b / r ↔ r * a ≤ b := @le_div_iff' ℝ _ a b r $ pos_iff_ne_zero.2 hr lemma div_lt_iff {a b r : ℝ≥0} (hr : r ≠ 0) : a / r < b ↔ a < b * r := lt_iff_lt_of_le_iff_le (le_div_iff hr) lemma div_lt_iff' {a b r : ℝ≥0} (hr : r ≠ 0) : a / r < b ↔ a < r * b := lt_iff_lt_of_le_iff_le (le_div_iff' hr) lemma lt_div_iff {a b r : ℝ≥0} (hr : r ≠ 0) : a < b / r ↔ a * r < b := lt_iff_lt_of_le_iff_le (div_le_iff hr) lemma lt_div_iff' {a b r : ℝ≥0} (hr : r ≠ 0) : a < b / r ↔ r * a < b := lt_iff_lt_of_le_iff_le (div_le_iff' hr) lemma mul_lt_of_lt_div {a b r : ℝ≥0} (h : a < b / r) : a * r < b := begin refine (lt_div_iff $ λ hr, false.elim _).1 h, subst r, simpa using h end lemma div_le_div_left_of_le {a b c : ℝ≥0} (b0 : 0 < b) (c0 : 0 < c) (cb : c ≤ b) : a / b ≤ a / c := begin by_cases a0 : a = 0, { rw [a0, zero_div, zero_div] }, { cases a with a ha, replace a0 : 0 < a := lt_of_le_of_ne ha (ne_of_lt (zero_lt_iff.mpr a0)), exact (div_le_div_left a0 b0 c0).mpr cb } end lemma div_le_div_left {a b c : ℝ≥0} (a0 : 0 < a) (b0 : 0 < b) (c0 : 0 < c) : a / b ≤ a / c ↔ c ≤ b := by rw [nnreal.div_le_iff b0.ne.symm, div_mul_eq_mul_div, nnreal.le_div_iff_mul_le c0.ne.symm, mul_le_mul_left a0] lemma le_of_forall_lt_one_mul_le {x y : ℝ≥0} (h : ∀a<1, a * x ≤ y) : x ≤ y := le_of_forall_ge_of_dense $ assume a ha, have hx : x ≠ 0 := pos_iff_ne_zero.1 (lt_of_le_of_lt (zero_le _) ha), have hx' : x⁻¹ ≠ 0, by rwa [(≠), inv_eq_zero], have a * x⁻¹ < 1, by rwa [← lt_inv_iff_mul_lt hx', inv_inv'], have (a * x⁻¹) * x ≤ y, from h _ this, by rwa [mul_assoc, inv_mul_cancel hx, mul_one] at this lemma div_add_div_same (a b c : ℝ≥0) : a / c + b / c = (a + b) / c := eq.symm $ right_distrib a b (c⁻¹) lemma half_pos {a : ℝ≥0} (h : 0 < a) : 0 < a / 2 := div_pos h zero_lt_two lemma add_halves (a : ℝ≥0) : a / 2 + a / 2 = a := nnreal.eq (add_halves a) lemma half_lt_self {a : ℝ≥0} (h : a ≠ 0) : a / 2 < a := by rw [← nnreal.coe_lt_coe, nnreal.coe_div]; exact half_lt_self (bot_lt_iff_ne_bot.2 h) lemma two_inv_lt_one : (2⁻¹:ℝ≥0) < 1 := by simpa using half_lt_self zero_ne_one.symm lemma div_lt_one_of_lt {a b : ℝ≥0} (h : a < b) : a / b < 1 := begin rwa [div_lt_iff, one_mul], exact ne_of_gt (lt_of_le_of_lt (zero_le _) h) end @[field_simps] lemma div_add_div (a : ℝ≥0) {b : ℝ≥0} (c : ℝ≥0) {d : ℝ≥0} (hb : b ≠ 0) (hd : d ≠ 0) : a / b + c / d = (a * d + b * c) / (b * d) := begin rw ← nnreal.eq_iff, simp only [nnreal.coe_add, nnreal.coe_div, nnreal.coe_mul], exact div_add_div _ _ (coe_ne_zero.2 hb) (coe_ne_zero.2 hd) end @[field_simps] lemma add_div' (a b c : ℝ≥0) (hc : c ≠ 0) : b + a / c = (b * c + a) / c := by simpa using div_add_div b a one_ne_zero hc @[field_simps] lemma div_add' (a b c : ℝ≥0) (hc : c ≠ 0) : a / c + b = (a + b * c) / c := by rwa [add_comm, add_div', add_comm] lemma _root_.real.to_nnreal_inv {x : ℝ} : real.to_nnreal x⁻¹ = (real.to_nnreal x)⁻¹ := begin by_cases hx : 0 ≤ x, { nth_rewrite 0 ← real.coe_to_nnreal x hx, rw [←nnreal.coe_inv, real.to_nnreal_coe], }, { have hx' := le_of_not_ge hx, rw [to_nnreal_eq_zero.mpr hx', inv_zero, to_nnreal_eq_zero.mpr (inv_nonpos.mpr hx')], }, end lemma _root_.real.to_nnreal_div {x y : ℝ} (hx : 0 ≤ x) : real.to_nnreal (x / y) = real.to_nnreal x / real.to_nnreal y := by rw [div_eq_mul_inv, div_eq_mul_inv, ← real.to_nnreal_inv, ← real.to_nnreal_mul hx] lemma _root_.real.to_nnreal_div' {x y : ℝ} (hy : 0 ≤ y) : real.to_nnreal (x / y) = real.to_nnreal x / real.to_nnreal y := by rw [div_eq_inv_mul, div_eq_inv_mul, real.to_nnreal_mul (inv_nonneg.2 hy), real.to_nnreal_inv] end inv @[simp] lemma abs_eq (x : ℝ≥0) : abs (x : ℝ) = x := abs_of_nonneg x.property end nnreal namespace real /-- The absolute value on `ℝ` as a map to `ℝ≥0`. -/ @[pp_nodot] def nnabs : monoid_with_zero_hom ℝ ℝ≥0 := { to_fun := λ x, ⟨abs x, abs_nonneg x⟩, map_zero' := by { ext, simp }, map_one' := by { ext, simp }, map_mul' := λ x y, by { ext, simp [abs_mul] } } @[norm_cast, simp] lemma coe_nnabs (x : ℝ) : (nnabs x : ℝ) = abs x := by simp [nnabs] @[simp] lemma nnabs_of_nonneg {x : ℝ} (h : 0 ≤ x) : nnabs x = to_nnreal x := by { ext, simp [coe_to_nnreal x h, abs_of_nonneg h] } lemma coe_to_nnreal_le (x : ℝ) : (to_nnreal x : ℝ) ≤ abs x := max_le (le_abs_self _) (abs_nonneg _) lemma cast_nat_abs_eq_nnabs_cast (n : ℤ) : (n.nat_abs : ℝ≥0) = nnabs n := by { ext, rw [nnreal.coe_nat_cast, int.cast_nat_abs, real.coe_nnabs] } end real
fa00582d4400302f57155c4b3bf11a54b00c3696
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/countable/small.lean
95d88c7fb94b3377b0b90563fd08ec7e54613456
[ "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
492
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import logic.small.basic import data.countable.defs /-! # All countable types are small. That is, any countable type is equivalent to a type in any universe. -/ universes w v @[priority 100] instance small_of_countable (α : Type v) [countable α] : small.{w} α := let ⟨f, hf⟩ := exists_injective_nat α in small_of_injective hf
61f0ceaf27488d8c4240e74b0bf51c9563d3579d
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/order/category/omega_complete_partial_order.lean
87b1c7890b9515172b3fec5b184beee3935a40a3
[ "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
3,972
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import order.omega_complete_partial_order import order.category.Preorder import category_theory.limits.shapes.products import category_theory.limits.shapes.equalizers import category_theory.limits.constructions.limits_of_products_and_equalizers /-! # 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 : Type (u+1) := 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 section open category_theory.limits namespace has_products /-- The pi-type gives a cone for a product. -/ def product {J : Type v} (f : J → ωCPO.{v}) : fan f := fan.mk (of (Π j, f j)) (λ j, continuous_hom.of_mono (pi.monotone_apply j : _) (λ c, rfl)) /-- The pi-type is a limit cone for the product. -/ def is_product (J : Type v) (f : J → ωCPO) : is_limit (product f) := { lift := λ s, ⟨λ t j, s.π.app j t, λ x y h j, (s.π.app j).monotone h, λ x, funext (λ j, (s.π.app j).continuous x)⟩, uniq' := λ s m w, begin ext t j, change m t j = s.π.app j t, rw ← w j, refl, end }. instance (J : Type v) (f : J → ωCPO.{v}) : has_product f := has_limit.mk ⟨_, is_product _ f⟩ end has_products instance omega_complete_partial_order_equalizer {α β : Type*} [omega_complete_partial_order α] [omega_complete_partial_order β] (f g : α →𝒄 β) : omega_complete_partial_order {a : α // f a = g a} := omega_complete_partial_order.subtype _ $ λ c hc, begin rw [f.continuous, g.continuous], congr' 1, ext, apply hc _ ⟨_, rfl⟩, end namespace has_equalizers /-- The equalizer inclusion function as a `continuous_hom`. -/ def equalizer_ι {α β : Type*} [omega_complete_partial_order α] [omega_complete_partial_order β] (f g : α →𝒄 β) : {a : α // f a = g a} →𝒄 α := continuous_hom.of_mono (preorder_hom.subtype.val _) (λ c, rfl) /-- A construction of the equalizer fork. -/ def equalizer {X Y : ωCPO.{v}} (f g : X ⟶ Y) : fork f g := @fork.of_ι _ _ _ _ _ _ (ωCPO.of {a // f a = g a}) (equalizer_ι f g) (continuous_hom.ext _ _ (λ x, x.2)) /-- The equalizer fork is a limit. -/ def is_equalizer {X Y : ωCPO.{v}} (f g : X ⟶ Y) : is_limit (equalizer f g) := fork.is_limit.mk' _ $ λ s, ⟨{ to_fun := λ x, ⟨s.ι x, by apply continuous_hom.congr_fun s.condition⟩, monotone' := λ x y h, s.ι.monotone h, cont := λ x, subtype.ext (s.ι.continuous x) }, by { ext, refl }, λ m hm, begin ext, apply continuous_hom.congr_fun hm, end⟩ end has_equalizers instance : has_products ωCPO.{v} := λ J, { has_limit := λ F, has_limit_of_iso discrete.nat_iso_functor.symm } instance {X Y : ωCPO.{v}} (f g : X ⟶ Y) : has_limit (parallel_pair f g) := has_limit.mk ⟨_, has_equalizers.is_equalizer f g⟩ instance : has_equalizers ωCPO.{v} := has_equalizers_of_has_limit_parallel_pair _ instance : has_limits ωCPO.{v} := limits_from_equalizers_and_products end end ωCPO
45a9c6ef44a8bf9f83c75b8ba8355c2451ead72f
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/src/Init/Lean/Meta/Tactic/Rewrite.lean
a5c8f7c795db0d0c916e1547ec407a70a49e09e2
[ "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,503
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Lean.Meta.AppBuilder import Init.Lean.Meta.KAbstract import Init.Lean.Meta.Check import Init.Lean.Meta.Tactic.Apply namespace Lean namespace Meta structure RewriteResult := (eNew : Expr) (eqPrf : Expr) (newGoals : List MVarId) def rewriteCore (mvarId : MVarId) (e : Expr) (heq : Expr) (symm : Bool := false) (occs : Occurrences := Occurrences.all) : MetaM RewriteResult := withMVarContext mvarId $ do checkNotAssigned mvarId `rewrite; heqType ← inferType heq; (newMVars, binderInfos, heqType) ← forallMetaTelescopeReducing heqType; let heq := mkAppN heq newMVars; let continue (heq heqType : Expr) : MetaM RewriteResult := match heqType.eq? with | none => throwTacticEx `rewrite mvarId ("equality of iff proof expected") | some (α, lhs, rhs) => let continue (heq heqType lhs rhs : Expr) : MetaM RewriteResult := do { when lhs.getAppFn.isMVar $ throwTacticEx `rewrite mvarId ("pattern is a metavariable"); e ← instantiateMVars e; eAbst ← kabstract e lhs occs; unless eAbst.hasLooseBVars $ throwTacticEx `rewrite mvarId ("did not find instance of the pattern in the target expression"); -- construct rewrite proof let eNew := eAbst.instantiate1 rhs; eNew ← instantiateMVars eNew; eEqE ← mkEq e e; let eEqEAbst := mkApp eEqE.appFn! eAbst; let motive := Lean.mkLambda `_a BinderInfo.default α eEqEAbst; unlessM (isTypeCorrect motive) $ throwTacticEx `rewrite mvarId ("motive is not type correct"); eqRefl ← mkEqRefl e; eqPrf ← mkEqNDRec motive eqRefl heq; postprocessAppMVars `rewrite mvarId newMVars binderInfos; newMVars ← newMVars.filterM $ fun mvar => not <$> isExprMVarAssigned mvar.mvarId!; pure { eNew := eNew, eqPrf := eqPrf, newGoals := newMVars.toList.map Expr.mvarId! } }; match symm with | false => continue heq heqType lhs rhs | true => do { heq ← mkEqSymm heq; heqType ← mkEq rhs lhs; continue heq heqType rhs lhs }; match heqType.iff? with | some (lhs, rhs) => do heqType ← mkEq lhs rhs; let heq := mkApp3 (mkConst `propext) lhs rhs heq; continue heq heqType | none => continue heq heqType end Meta end Lean
a813e8c57d4eeded38fdd7caf2cd56b10caee4b1
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/hole_issue2.lean
bf522579606987da60b6b86a8e4531af8fa55da0
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
1,817
lean
constant bag_setoid : ∀ A, setoid (list A) attribute [instance] bag_setoid definition bag (A : Type) : Type := quotient (bag_setoid A) constant subcount : ∀ {A}, list A → list A → bool constant list.count : ∀ {A}, A → list A → nat constant all_of_subcount_eq_tt : ∀ {A} {l₁ l₂ : list A}, subcount l₁ l₂ = tt → ∀ a, list.count a l₁ ≤ list.count a l₂ constant ex_of_subcount_eq_ff : ∀ {A} {l₁ l₂ : list A}, subcount l₁ l₂ = ff → ∃ a, ¬ list.count a l₁ ≤ list.count a l₂ noncomputable definition count {A} (a : A) (b : bag A) : nat := quotient.lift_on b (λ l, list.count a l) (λ l₁ l₂ h, sorry) definition subbag {A} (b₁ b₂ : bag A) := ∀ a, count a b₁ ≤ count a b₂ infix ⊆ := subbag noncomputable definition decidable_subbag_1 {A} (b₁ b₂ : bag A) : decidable (b₁ ⊆ b₂) := quotient.rec_on_subsingleton₂ b₁ b₂ (λ l₁ l₂, match subcount l₁ l₂, rfl : ∀ (b : _), subcount l₁ l₂ = b → _ with | tt, H := is_true (all_of_subcount_eq_tt H) | ff, H := is_false (λ h, exists.elim (ex_of_subcount_eq_ff H) (λ w hw, _)) end) noncomputable definition decidable_subbag_2 {A} (b₁ b₂ : bag A) : decidable (b₁ ⊆ b₂) := quotient.rec_on_subsingleton₂ b₁ b₂ (λ l₁ l₂, match subcount l₁ l₂, rfl : ∀ (b : _), subcount l₁ l₂ = b → _ with | tt, H := is_true (all_of_subcount_eq_tt H) | ff, H := is_false (λ h, exists.elim (ex_of_subcount_eq_ff H) _) end) noncomputable definition decidable_subbag_3 {A} (b₁ b₂ : bag A) : decidable (b₁ ⊆ b₂) := quotient.rec_on_subsingleton₂ b₁ b₂ (λ l₁ l₂, match subcount l₁ l₂, rfl : ∀ (b : _), subcount l₁ l₂ = b → _ with | tt, H := is_true (all_of_subcount_eq_tt H) | ff, H := is_false (λ h, _) end)
8ac703fa5e24386a0adc5da0cb0841d1098e4506
9d00e4b237465921fb33aa10eed92a2495ca2e46
/biImplRules.lean
3907bc6eacdbc8c6313871a8d365c72961f93ace
[]
no_license
Bpalkmim/LeanNatD
7756abf1ed7b0e7a3e3b9d16ad756018f5c70c7c
2e73bb44e44b955839e7a0874cd7013fbfb9c4e3
refs/heads/master
1,610,999,141,530
1,475,515,895,000
1,475,515,895,000
69,893,600
0
0
null
null
null
null
UTF-8
Lean
false
false
1,928
lean
namespace biImplRules -- Requer o namespace de implicação open implRules print " " print "Provas com BI_IMPL - início" print " " constant bi_impl : Prop → Prop → Prop constants A B : Prop -- Definições constant bi_impl_intro {X Y : Prop} : (Π x : Proof X, Proof Y) → Proof Y → (Π x : Proof Y, Proof X) → Proof X → Proof (bi_impl X Y) constant bi_impl_elim_leftmost_left {X Y : Prop} : Proof (bi_impl X Y) → Proof X → Proof X constant bi_impl_elim_leftmost_right {X Y : Prop} : Proof (bi_impl X Y) → Proof X → Proof Y constant bi_impl_elim_rightmost_left {X Y : Prop} : Proof (bi_impl X Y) → Proof Y → Proof X constant bi_impl_elim_rightmost_right {X Y : Prop} : Proof (bi_impl X Y) → Proof Y → Proof Y -- Termos úteis variable a : Proof A variable b : Proof B variable aIMPb : Proof (implies A B) variable bIMPa : Proof (implies B A) variable aBIIMPLb : Proof (bi_impl A B) variable concl : Π x : Proof (bi_impl A B), Proof (bi_impl B A) -- Testes iniciais check @bi_impl_intro check @bi_impl_elim_leftmost_left check @bi_impl_elim_leftmost_right check @bi_impl_elim_rightmost_left check @bi_impl_elim_rightmost_right check bi_impl_intro (impl_elim aIMPb) b (impl_elim bIMPa) a check bi_impl_elim_leftmost_left aBIIMPLb a check bi_impl_elim_leftmost_right aBIIMPLb a check bi_impl_elim_rightmost_left aBIIMPLb b check bi_impl_elim_rightmost_right aBIIMPLb b print "------" -- Testes parciais check bi_impl_elim_leftmost_right aBIIMPLb check bi_impl_elim_rightmost_left aBIIMPLb check bi_impl_intro (bi_impl_elim_rightmost_left aBIIMPLb ) a (bi_impl_elim_leftmost_right aBIIMPLb ) b print "------" -- Teste final (A ↔ B) → (B ↔ A) check impl_intro concl (bi_impl_intro (bi_impl_elim_rightmost_left aBIIMPLb ) a (bi_impl_elim_leftmost_right aBIIMPLb ) b ) print " " print "Provas com BI_IMPL - fim" print " " end biImplRules
305236f17913ebfdf6c2560abe7f860178168d72
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/geometry/manifold/partition_of_unity.lean
e345b485faf25f2e20e1f1610a2a342049cc6c08
[ "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
27,581
lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import geometry.manifold.algebra.structures import geometry.manifold.bump_function import topology.metric_space.partition_of_unity import topology.shrinking_lemma /-! # Smooth partition of unity > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define two structures, `smooth_bump_covering` and `smooth_partition_of_unity`. Both structures describe coverings of a set by a locally finite family of supports of smooth functions with some additional properties. The former structure is mostly useful as an intermediate step in the construction of a smooth partition of unity but some proofs that traditionally deal with a partition of unity can use a `smooth_bump_covering` as well. Given a real manifold `M` and its subset `s`, a `smooth_bump_covering ι I M s` is a collection of `smooth_bump_function`s `f i` indexed by `i : ι` such that * the center of each `f i` belongs to `s`; * the family of sets `support (f i)` is locally finite; * for each `x ∈ s`, there exists `i : ι` such that `f i =ᶠ[𝓝 x] 1`. In the same settings, a `smooth_partition_of_unity ι I M s` is a collection of smooth nonnegative functions `f i : C^∞⟮I, M; 𝓘(ℝ), ℝ⟯`, `i : ι`, such that * the family of sets `support (f i)` is locally finite; * for each `x ∈ s`, the sum `∑ᶠ i, f i x` equals one; * for each `x`, the sum `∑ᶠ i, f i x` is less than or equal to one. We say that `f : smooth_bump_covering ι I M s` is *subordinate* to a map `U : M → set M` if for each index `i`, we have `tsupport (f i) ⊆ U (f i).c`. This notion is a bit more general than being subordinate to an open covering of `M`, because we make no assumption about the way `U x` depends on `x`. We prove that on a smooth finitely dimensional real manifold with `σ`-compact Hausdorff topology, for any `U : M → set M` such that `∀ x ∈ s, U x ∈ 𝓝 x` there exists a `smooth_bump_covering ι I M s` subordinate to `U`. Then we use this fact to prove a similar statement about smooth partitions of unity, see `smooth_partition_of_unity.exists_is_subordinate`. Finally, we use existence of a partition of unity to prove lemma `exists_smooth_forall_mem_convex_of_local` that allows us to construct a globally defined smooth function from local functions. ## TODO * Build a framework for to transfer local definitions to global using partition of unity and use it to define, e.g., the integral of a differential form over a manifold. Lemma `exists_smooth_forall_mem_convex_of_local` is a first step in this direction. ## Tags smooth bump function, partition of unity -/ universes uι uE uH uM uF open function filter finite_dimensional set open_locale topology manifold classical filter big_operators noncomputable theory variables {ι : Type uι} {E : Type uE} [normed_add_comm_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {F : Type uF} [normed_add_comm_group F] [normed_space ℝ F] {H : Type uH} [topological_space H] (I : model_with_corners ℝ E H) {M : Type uM} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] /-! ### Covering by supports of smooth bump functions In this section we define `smooth_bump_covering ι I M s` to be a collection of `smooth_bump_function`s such that their supports is a locally finite family of sets and for each `x ∈ s` some function `f i` from the collection is equal to `1` in a neighborhood of `x`. A covering of this type is useful to construct a smooth partition of unity and can be used instead of a partition of unity in some proofs. We prove that on a smooth finite dimensional real manifold with `σ`-compact Hausdorff topology, for any `U : M → set M` such that `∀ x ∈ s, U x ∈ 𝓝 x` there exists a `smooth_bump_covering ι I M s` subordinate to `U`. Then we use this fact to prove a version of the Whitney embedding theorem: any compact real manifold can be embedded into `ℝ^n` for large enough `n`. -/ variables (ι M) /-- We say that a collection of `smooth_bump_function`s is a `smooth_bump_covering` of a set `s` if * `(f i).c ∈ s` for all `i`; * the family `λ i, support (f i)` is locally finite; * for each point `x ∈ s` there exists `i` such that `f i =ᶠ[𝓝 x] 1`; in other words, `x` belongs to the interior of `{y | f i y = 1}`; If `M` is a finite dimensional real manifold which is a `σ`-compact Hausdorff topological space, then for every covering `U : M → set M`, `∀ x, U x ∈ 𝓝 x`, there exists a `smooth_bump_covering` subordinate to `U`, see `smooth_bump_covering.exists_is_subordinate`. This covering can be used, e.g., to construct a partition of unity and to prove the weak Whitney embedding theorem. -/ @[nolint has_nonempty_instance] structure smooth_bump_covering (s : set M := univ) := (c : ι → M) (to_fun : Π i, smooth_bump_function I (c i)) (c_mem' : ∀ i, c i ∈ s) (locally_finite' : locally_finite (λ i, support (to_fun i))) (eventually_eq_one' : ∀ x ∈ s, ∃ i, to_fun i =ᶠ[𝓝 x] 1) /-- We say that that a collection of functions form a smooth partition of unity on a set `s` if * all functions are infinitely smooth and nonnegative; * the family `λ i, support (f i)` is locally finite; * for all `x ∈ s` the sum `∑ᶠ i, f i x` equals one; * for all `x`, the sum `∑ᶠ i, f i x` is less than or equal to one. -/ structure smooth_partition_of_unity (s : set M := univ) := (to_fun : ι → C^∞⟮I, M; 𝓘(ℝ), ℝ⟯) (locally_finite' : locally_finite (λ i, support (to_fun i))) (nonneg' : ∀ i x, 0 ≤ to_fun i x) (sum_eq_one' : ∀ x ∈ s, ∑ᶠ i, to_fun i x = 1) (sum_le_one' : ∀ x, ∑ᶠ i, to_fun i x ≤ 1) variables {ι I M} namespace smooth_partition_of_unity variables {s : set M} (f : smooth_partition_of_unity ι I M s) {n : ℕ∞} instance {s : set M} : has_coe_to_fun (smooth_partition_of_unity ι I M s) (λ _, ι → C^∞⟮I, M; 𝓘(ℝ), ℝ⟯) := ⟨smooth_partition_of_unity.to_fun⟩ protected lemma locally_finite : locally_finite (λ i, support (f i)) := f.locally_finite' lemma nonneg (i : ι) (x : M) : 0 ≤ f i x := f.nonneg' i x lemma sum_eq_one {x} (hx : x ∈ s) : ∑ᶠ i, f i x = 1 := f.sum_eq_one' x hx lemma sum_le_one (x : M) : ∑ᶠ i, f i x ≤ 1 := f.sum_le_one' x /-- Reinterpret a smooth partition of unity as a continuous partition of unity. -/ def to_partition_of_unity : partition_of_unity ι M s := { to_fun := λ i, f i, .. f } lemma smooth_sum : smooth I 𝓘(ℝ) (λ x, ∑ᶠ i, f i x) := smooth_finsum (λ i, (f i).smooth) f.locally_finite lemma le_one (i : ι) (x : M) : f i x ≤ 1 := f.to_partition_of_unity.le_one i x lemma sum_nonneg (x : M) : 0 ≤ ∑ᶠ i, f i x := f.to_partition_of_unity.sum_nonneg x lemma cont_mdiff_smul {g : M → F} {i} (hg : ∀ x ∈ tsupport (f i), cont_mdiff_at I 𝓘(ℝ, F) n g x) : cont_mdiff I 𝓘(ℝ, F) n (λ x, f i x • g x) := cont_mdiff_of_support $ λ x hx, ((f i).cont_mdiff.cont_mdiff_at.of_le le_top).smul $ hg x $ tsupport_smul_subset_left _ _ hx lemma smooth_smul {g : M → F} {i} (hg : ∀ x ∈ tsupport (f i), smooth_at I 𝓘(ℝ, F) g x) : smooth I 𝓘(ℝ, F) (λ x, f i x • g x) := f.cont_mdiff_smul hg /-- If `f` is a smooth partition of unity on a set `s : set M` and `g : ι → M → F` is a family of functions such that `g i` is $C^n$ smooth at every point of the topological support of `f i`, then the sum `λ x, ∑ᶠ i, f i x • g i x` is smooth on the whole manifold. -/ lemma cont_mdiff_finsum_smul {g : ι → M → F} (hg : ∀ i (x ∈ tsupport (f i)), cont_mdiff_at I 𝓘(ℝ, F) n (g i) x) : cont_mdiff I 𝓘(ℝ, F) n (λ x, ∑ᶠ i, f i x • g i x) := cont_mdiff_finsum (λ i, f.cont_mdiff_smul (hg i)) $ f.locally_finite.subset $ λ i, support_smul_subset_left _ _ /-- If `f` is a smooth partition of unity on a set `s : set M` and `g : ι → M → F` is a family of functions such that `g i` is smooth at every point of the topological support of `f i`, then the sum `λ x, ∑ᶠ i, f i x • g i x` is smooth on the whole manifold. -/ lemma smooth_finsum_smul {g : ι → M → F} (hg : ∀ i (x ∈ tsupport (f i)), smooth_at I 𝓘(ℝ, F) (g i) x) : smooth I 𝓘(ℝ, F) (λ x, ∑ᶠ i, f i x • g i x) := f.cont_mdiff_finsum_smul hg lemma finsum_smul_mem_convex {g : ι → M → F} {t : set F} {x : M} (hx : x ∈ s) (hg : ∀ i, f i x ≠ 0 → g i x ∈ t) (ht : convex ℝ t) : ∑ᶠ i, f i x • g i x ∈ t := ht.finsum_mem (λ i, f.nonneg _ _) (f.sum_eq_one hx) hg /-- A smooth partition of unity `f i` is subordinate to a family of sets `U i` indexed by the same type if for each `i` the closure of the support of `f i` is a subset of `U i`. -/ def is_subordinate (f : smooth_partition_of_unity ι I M s) (U : ι → set M) := ∀ i, tsupport (f i) ⊆ U i variables {f} {U : ι → set M} @[simp] lemma is_subordinate_to_partition_of_unity : f.to_partition_of_unity.is_subordinate U ↔ f.is_subordinate U := iff.rfl alias is_subordinate_to_partition_of_unity ↔ _ is_subordinate.to_partition_of_unity /-- If `f` is a smooth partition of unity on a set `s : set M` subordinate to a family of open sets `U : ι → set M` and `g : ι → M → F` is a family of functions such that `g i` is $C^n$ smooth on `U i`, then the sum `λ x, ∑ᶠ i, f i x • g i x` is $C^n$ smooth on the whole manifold. -/ lemma is_subordinate.cont_mdiff_finsum_smul {g : ι → M → F} (hf : f.is_subordinate U) (ho : ∀ i, is_open (U i)) (hg : ∀ i, cont_mdiff_on I 𝓘(ℝ, F) n (g i) (U i)) : cont_mdiff I 𝓘(ℝ, F) n (λ x, ∑ᶠ i, f i x • g i x) := f.cont_mdiff_finsum_smul $ λ i x hx, (hg i).cont_mdiff_at $ (ho i).mem_nhds (hf i hx) /-- If `f` is a smooth partition of unity on a set `s : set M` subordinate to a family of open sets `U : ι → set M` and `g : ι → M → F` is a family of functions such that `g i` is smooth on `U i`, then the sum `λ x, ∑ᶠ i, f i x • g i x` is smooth on the whole manifold. -/ lemma is_subordinate.smooth_finsum_smul {g : ι → M → F} (hf : f.is_subordinate U) (ho : ∀ i, is_open (U i)) (hg : ∀ i, smooth_on I 𝓘(ℝ, F) (g i) (U i)) : smooth I 𝓘(ℝ, F) (λ x, ∑ᶠ i, f i x • g i x) := hf.cont_mdiff_finsum_smul ho hg end smooth_partition_of_unity namespace bump_covering -- Repeat variables to drop [finite_dimensional ℝ E] and [smooth_manifold_with_corners I M] lemma smooth_to_partition_of_unity {E : Type uE} [normed_add_comm_group E] [normed_space ℝ E] {H : Type uH} [topological_space H] {I : model_with_corners ℝ E H} {M : Type uM} [topological_space M] [charted_space H M] {s : set M} (f : bump_covering ι M s) (hf : ∀ i, smooth I 𝓘(ℝ) (f i)) (i : ι) : smooth I 𝓘(ℝ) (f.to_partition_of_unity i) := (hf i).mul $ smooth_finprod_cond (λ j _, smooth_const.sub (hf j)) $ by { simp only [mul_support_one_sub], exact f.locally_finite } variables {s : set M} /-- A `bump_covering` such that all functions in this covering are smooth generates a smooth partition of unity. In our formalization, not every `f : bump_covering ι M s` with smooth functions `f i` is a `smooth_bump_covering`; instead, a `smooth_bump_covering` is a covering by supports of `smooth_bump_function`s. So, we define `bump_covering.to_smooth_partition_of_unity`, then reuse it in `smooth_bump_covering.to_smooth_partition_of_unity`. -/ def to_smooth_partition_of_unity (f : bump_covering ι M s) (hf : ∀ i, smooth I 𝓘(ℝ) (f i)) : smooth_partition_of_unity ι I M s := { to_fun := λ i, ⟨f.to_partition_of_unity i, f.smooth_to_partition_of_unity hf i⟩, .. f.to_partition_of_unity } @[simp] lemma to_smooth_partition_of_unity_to_partition_of_unity (f : bump_covering ι M s) (hf : ∀ i, smooth I 𝓘(ℝ) (f i)) : (f.to_smooth_partition_of_unity hf).to_partition_of_unity = f.to_partition_of_unity := rfl @[simp] lemma coe_to_smooth_partition_of_unity (f : bump_covering ι M s) (hf : ∀ i, smooth I 𝓘(ℝ) (f i)) (i : ι) : ⇑(f.to_smooth_partition_of_unity hf i) = f.to_partition_of_unity i := rfl lemma is_subordinate.to_smooth_partition_of_unity {f : bump_covering ι M s} {U : ι → set M} (h : f.is_subordinate U) (hf : ∀ i, smooth I 𝓘(ℝ) (f i)) : (f.to_smooth_partition_of_unity hf).is_subordinate U := h.to_partition_of_unity end bump_covering namespace smooth_bump_covering variables {s : set M} {U : M → set M} (fs : smooth_bump_covering ι I M s) {I} instance : has_coe_to_fun (smooth_bump_covering ι I M s) (λ x, Π (i : ι), smooth_bump_function I (x.c i)) := ⟨to_fun⟩ @[simp] lemma coe_mk (c : ι → M) (to_fun : Π i, smooth_bump_function I (c i)) (h₁ h₂ h₃) : ⇑(mk c to_fun h₁ h₂ h₃ : smooth_bump_covering ι I M s) = to_fun := rfl /-- We say that `f : smooth_bump_covering ι I M s` is *subordinate* to a map `U : M → set M` if for each index `i`, we have `tsupport (f i) ⊆ U (f i).c`. This notion is a bit more general than being subordinate to an open covering of `M`, because we make no assumption about the way `U x` depends on `x`. -/ def is_subordinate {s : set M} (f : smooth_bump_covering ι I M s) (U : M → set M) := ∀ i, tsupport (f i) ⊆ U (f.c i) lemma is_subordinate.support_subset {fs : smooth_bump_covering ι I M s} {U : M → set M} (h : fs.is_subordinate U) (i : ι) : support (fs i) ⊆ U (fs.c i) := subset.trans subset_closure (h i) variable (I) /-- Let `M` be a smooth manifold with corners modelled on a finite dimensional real vector space. Suppose also that `M` is a Hausdorff `σ`-compact topological space. Let `s` be a closed set in `M` and `U : M → set M` be a collection of sets such that `U x ∈ 𝓝 x` for every `x ∈ s`. Then there exists a smooth bump covering of `s` that is subordinate to `U`. -/ lemma exists_is_subordinate [t2_space M] [sigma_compact_space M] (hs : is_closed s) (hU : ∀ x ∈ s, U x ∈ 𝓝 x) : ∃ (ι : Type uM) (f : smooth_bump_covering ι I M s), f.is_subordinate U := begin -- First we deduce some missing instances haveI : locally_compact_space H := I.locally_compact, haveI : locally_compact_space M := charted_space.locally_compact H M, haveI : normal_space M := normal_of_paracompact_t2, -- Next we choose a covering by supports of smooth bump functions have hB := λ x hx, smooth_bump_function.nhds_basis_support I (hU x hx), rcases refinement_of_locally_compact_sigma_compact_of_nhds_basis_set hs hB with ⟨ι, c, f, hf, hsub', hfin⟩, choose hcs hfU using hf, /- Then we use the shrinking lemma to get a covering by smaller open -/ rcases exists_subset_Union_closed_subset hs (λ i, (f i).is_open_support) (λ x hx, hfin.point_finite x) hsub' with ⟨V, hsV, hVc, hVf⟩, choose r hrR hr using λ i, (f i).exists_r_pos_lt_subset_ball (hVc i) (hVf i), refine ⟨ι, ⟨c, λ i, (f i).update_r (r i) (hrR i), hcs, _, λ x hx, _⟩, λ i, _⟩, { simpa only [smooth_bump_function.support_update_r] }, { refine (mem_Union.1 $ hsV hx).imp (λ i hi, _), exact ((f i).update_r _ _).eventually_eq_one_of_dist_lt ((f i).support_subset_source $ hVf _ hi) (hr i hi).2 }, { simpa only [coe_mk, smooth_bump_function.support_update_r, tsupport] using hfU i } end variables {I M} protected lemma locally_finite : locally_finite (λ i, support (fs i)) := fs.locally_finite' protected lemma point_finite (x : M) : {i | fs i x ≠ 0}.finite := fs.locally_finite.point_finite x lemma mem_chart_at_source_of_eq_one {i : ι} {x : M} (h : fs i x = 1) : x ∈ (chart_at H (fs.c i)).source := (fs i).support_subset_source $ by simp [h] lemma mem_ext_chart_at_source_of_eq_one {i : ι} {x : M} (h : fs i x = 1) : x ∈ (ext_chart_at I (fs.c i)).source := by { rw ext_chart_at_source, exact fs.mem_chart_at_source_of_eq_one h } /-- Index of a bump function such that `fs i =ᶠ[𝓝 x] 1`. -/ def ind (x : M) (hx : x ∈ s) : ι := (fs.eventually_eq_one' x hx).some lemma eventually_eq_one (x : M) (hx : x ∈ s) : fs (fs.ind x hx) =ᶠ[𝓝 x] 1 := (fs.eventually_eq_one' x hx).some_spec lemma apply_ind (x : M) (hx : x ∈ s) : fs (fs.ind x hx) x = 1 := (fs.eventually_eq_one x hx).eq_of_nhds lemma mem_support_ind (x : M) (hx : x ∈ s) : x ∈ support (fs $ fs.ind x hx) := by simp [fs.apply_ind x hx] lemma mem_chart_at_ind_source (x : M) (hx : x ∈ s) : x ∈ (chart_at H (fs.c (fs.ind x hx))).source := fs.mem_chart_at_source_of_eq_one (fs.apply_ind x hx) lemma mem_ext_chart_at_ind_source (x : M) (hx : x ∈ s) : x ∈ (ext_chart_at I (fs.c (fs.ind x hx))).source := fs.mem_ext_chart_at_source_of_eq_one (fs.apply_ind x hx) /-- The index type of a `smooth_bump_covering` of a compact manifold is finite. -/ protected def fintype [compact_space M] : fintype ι := fs.locally_finite.fintype_of_compact $ λ i, (fs i).nonempty_support variable [t2_space M] /-- Reinterpret a `smooth_bump_covering` as a continuous `bump_covering`. Note that not every `f : bump_covering ι M s` with smooth functions `f i` is a `smooth_bump_covering`. -/ def to_bump_covering : bump_covering ι M s := { to_fun := λ i, ⟨fs i, (fs i).continuous⟩, locally_finite' := fs.locally_finite, nonneg' := λ i x, (fs i).nonneg, le_one' := λ i x, (fs i).le_one, eventually_eq_one' := fs.eventually_eq_one' } @[simp] lemma is_subordinate_to_bump_covering {f : smooth_bump_covering ι I M s} {U : M → set M} : f.to_bump_covering.is_subordinate (λ i, U (f.c i)) ↔ f.is_subordinate U := iff.rfl alias is_subordinate_to_bump_covering ↔ _ is_subordinate.to_bump_covering /-- Every `smooth_bump_covering` defines a smooth partition of unity. -/ def to_smooth_partition_of_unity : smooth_partition_of_unity ι I M s := fs.to_bump_covering.to_smooth_partition_of_unity (λ i, (fs i).smooth) lemma to_smooth_partition_of_unity_apply (i : ι) (x : M) : fs.to_smooth_partition_of_unity i x = fs i x * ∏ᶠ j (hj : well_ordering_rel j i), (1 - fs j x) := rfl lemma to_smooth_partition_of_unity_eq_mul_prod (i : ι) (x : M) (t : finset ι) (ht : ∀ j, well_ordering_rel j i → fs j x ≠ 0 → j ∈ t) : fs.to_smooth_partition_of_unity i x = fs i x * ∏ j in t.filter (λ j, well_ordering_rel j i), (1 - fs j x) := fs.to_bump_covering.to_partition_of_unity_eq_mul_prod i x t ht lemma exists_finset_to_smooth_partition_of_unity_eventually_eq (i : ι) (x : M) : ∃ t : finset ι, fs.to_smooth_partition_of_unity i =ᶠ[𝓝 x] fs i * ∏ j in t.filter (λ j, well_ordering_rel j i), (1 - fs j) := fs.to_bump_covering.exists_finset_to_partition_of_unity_eventually_eq i x lemma to_smooth_partition_of_unity_zero_of_zero {i : ι} {x : M} (h : fs i x = 0) : fs.to_smooth_partition_of_unity i x = 0 := fs.to_bump_covering.to_partition_of_unity_zero_of_zero h lemma support_to_smooth_partition_of_unity_subset (i : ι) : support (fs.to_smooth_partition_of_unity i) ⊆ support (fs i) := fs.to_bump_covering.support_to_partition_of_unity_subset i lemma is_subordinate.to_smooth_partition_of_unity {f : smooth_bump_covering ι I M s} {U : M → set M} (h : f.is_subordinate U) : f.to_smooth_partition_of_unity.is_subordinate (λ i, U (f.c i)) := h.to_bump_covering.to_partition_of_unity lemma sum_to_smooth_partition_of_unity_eq (x : M) : ∑ᶠ i, fs.to_smooth_partition_of_unity i x = 1 - ∏ᶠ i, (1 - fs i x) := fs.to_bump_covering.sum_to_partition_of_unity_eq x end smooth_bump_covering variable (I) /-- Given two disjoint closed sets in a Hausdorff σ-compact finite dimensional manifold, there exists an infinitely smooth function that is equal to `0` on one of them and is equal to one on the other. -/ lemma exists_smooth_zero_one_of_closed [t2_space M] [sigma_compact_space M] {s t : set M} (hs : is_closed s) (ht : is_closed t) (hd : disjoint s t) : ∃ f : C^∞⟮I, M; 𝓘(ℝ), ℝ⟯, eq_on f 0 s ∧ eq_on f 1 t ∧ ∀ x, f x ∈ Icc (0 : ℝ) 1 := begin have : ∀ x ∈ t, sᶜ ∈ 𝓝 x, from λ x hx, hs.is_open_compl.mem_nhds (disjoint_right.1 hd hx), rcases smooth_bump_covering.exists_is_subordinate I ht this with ⟨ι, f, hf⟩, set g := f.to_smooth_partition_of_unity, refine ⟨⟨_, g.smooth_sum⟩, λ x hx, _, λ x, g.sum_eq_one, λ x, ⟨g.sum_nonneg x, g.sum_le_one x⟩⟩, suffices : ∀ i, g i x = 0, by simp only [this, cont_mdiff_map.coe_fn_mk, finsum_zero, pi.zero_apply], refine λ i, f.to_smooth_partition_of_unity_zero_of_zero _, exact nmem_support.1 (subset_compl_comm.1 (hf.support_subset i) hx) end namespace smooth_partition_of_unity /-- A `smooth_partition_of_unity` that consists of a single function, uniformly equal to one, defined as an example for `inhabited` instance. -/ def single (i : ι) (s : set M) : smooth_partition_of_unity ι I M s := (bump_covering.single i s).to_smooth_partition_of_unity $ λ j, begin rcases eq_or_ne j i with rfl|h, { simp only [smooth_one, continuous_map.coe_one, bump_covering.coe_single, pi.single_eq_same] }, { simp only [smooth_zero, bump_covering.coe_single, pi.single_eq_of_ne h, continuous_map.coe_zero] } end instance [inhabited ι] (s : set M) : inhabited (smooth_partition_of_unity ι I M s) := ⟨single I default s⟩ variables [t2_space M] [sigma_compact_space M] /-- If `X` is a paracompact normal topological space and `U` is an open covering of a closed set `s`, then there exists a `bump_covering ι X s` that is subordinate to `U`. -/ lemma exists_is_subordinate {s : set M} (hs : is_closed s) (U : ι → set M) (ho : ∀ i, is_open (U i)) (hU : s ⊆ ⋃ i, U i) : ∃ f : smooth_partition_of_unity ι I M s, f.is_subordinate U := begin haveI : locally_compact_space H := I.locally_compact, haveI : locally_compact_space M := charted_space.locally_compact H M, haveI : normal_space M := normal_of_paracompact_t2, rcases bump_covering.exists_is_subordinate_of_prop (smooth I 𝓘(ℝ)) _ hs U ho hU with ⟨f, hf, hfU⟩, { exact ⟨f.to_smooth_partition_of_unity hf, hfU.to_smooth_partition_of_unity hf⟩ }, { intros s t hs ht hd, rcases exists_smooth_zero_one_of_closed I hs ht hd with ⟨f, hf⟩, exact ⟨f, f.smooth, hf⟩ } end end smooth_partition_of_unity variables [sigma_compact_space M] [t2_space M] {t : M → set F} {n : ℕ∞} /-- Let `M` be a σ-compact Hausdorff finite dimensional topological manifold. Let `t : M → set F` be a family of convex sets. Suppose that for each point `x : M` there exists a neighborhood `U ∈ 𝓝 x` and a function `g : M → F` such that `g` is $C^n$ smooth on `U` and `g y ∈ t y` for all `y ∈ U`. Then there exists a $C^n$ smooth function `g : C^∞⟮I, M; 𝓘(ℝ, F), F⟯` such that `g x ∈ t x` for all `x`. See also `exists_smooth_forall_mem_convex_of_local` and `exists_smooth_forall_mem_convex_of_local_const`. -/ lemma exists_cont_mdiff_forall_mem_convex_of_local (ht : ∀ x, convex ℝ (t x)) (Hloc : ∀ x : M, ∃ (U ∈ 𝓝 x) (g : M → F), cont_mdiff_on I 𝓘(ℝ, F) n g U ∧ ∀ y ∈ U, g y ∈ t y) : ∃ g : C^n⟮I, M; 𝓘(ℝ, F), F⟯, ∀ x, g x ∈ t x := begin choose U hU g hgs hgt using Hloc, obtain ⟨f, hf⟩ := smooth_partition_of_unity.exists_is_subordinate I is_closed_univ (λ x, interior (U x)) (λ x, is_open_interior) (λ x hx, mem_Union.2 ⟨x, mem_interior_iff_mem_nhds.2 (hU x)⟩), refine ⟨⟨λ x, ∑ᶠ i, f i x • g i x, hf.cont_mdiff_finsum_smul (λ i, is_open_interior) $ λ i, (hgs i).mono interior_subset⟩, λ x, f.finsum_smul_mem_convex (mem_univ x) (λ i hi, hgt _ _ _) (ht _)⟩, exact interior_subset (hf _ $ subset_closure hi) end /-- Let `M` be a σ-compact Hausdorff finite dimensional topological manifold. Let `t : M → set F` be a family of convex sets. Suppose that for each point `x : M` there exists a neighborhood `U ∈ 𝓝 x` and a function `g : M → F` such that `g` is smooth on `U` and `g y ∈ t y` for all `y ∈ U`. Then there exists a smooth function `g : C^∞⟮I, M; 𝓘(ℝ, F), F⟯` such that `g x ∈ t x` for all `x`. See also `exists_cont_mdiff_forall_mem_convex_of_local` and `exists_smooth_forall_mem_convex_of_local_const`. -/ lemma exists_smooth_forall_mem_convex_of_local (ht : ∀ x, convex ℝ (t x)) (Hloc : ∀ x : M, ∃ (U ∈ 𝓝 x) (g : M → F), smooth_on I 𝓘(ℝ, F) g U ∧ ∀ y ∈ U, g y ∈ t y) : ∃ g : C^∞⟮I, M; 𝓘(ℝ, F), F⟯, ∀ x, g x ∈ t x := exists_cont_mdiff_forall_mem_convex_of_local I ht Hloc /-- Let `M` be a σ-compact Hausdorff finite dimensional topological manifold. Let `t : M → set F` be a family of convex sets. Suppose that for each point `x : M` there exists a vector `c : F` such that for all `y` in a neighborhood of `x` we have `c ∈ t y`. Then there exists a smooth function `g : C^∞⟮I, M; 𝓘(ℝ, F), F⟯` such that `g x ∈ t x` for all `x`. See also `exists_cont_mdiff_forall_mem_convex_of_local` and `exists_smooth_forall_mem_convex_of_local`. -/ lemma exists_smooth_forall_mem_convex_of_local_const (ht : ∀ x, convex ℝ (t x)) (Hloc : ∀ x : M, ∃ c : F, ∀ᶠ y in 𝓝 x, c ∈ t y) : ∃ g : C^∞⟮I, M; 𝓘(ℝ, F), F⟯, ∀ x, g x ∈ t x := exists_smooth_forall_mem_convex_of_local I ht $ λ x, let ⟨c, hc⟩ := Hloc x in ⟨_, hc, λ _, c, smooth_on_const, λ y, id⟩ /-- Let `M` be a smooth σ-compact manifold with extended distance. Let `K : ι → set M` be a locally finite family of closed sets, let `U : ι → set M` be a family of open sets such that `K i ⊆ U i` for all `i`. Then there exists a positive smooth function `δ : M → ℝ≥0` such that for any `i` and `x ∈ K i`, we have `emetric.closed_ball x (δ x) ⊆ U i`. -/ lemma emetric.exists_smooth_forall_closed_ball_subset {M} [emetric_space M] [charted_space H M] [smooth_manifold_with_corners I M] [sigma_compact_space M] {K : ι → set M} {U : ι → set M} (hK : ∀ i, is_closed (K i)) (hU : ∀ i, is_open (U i)) (hKU : ∀ i, K i ⊆ U i) (hfin : locally_finite K) : ∃ δ : C^∞⟮I, M; 𝓘(ℝ, ℝ), ℝ⟯, (∀ x, 0 < δ x) ∧ ∀ i (x ∈ K i), emetric.closed_ball x (ennreal.of_real (δ x)) ⊆ U i := by simpa only [mem_inter_iff, forall_and_distrib, mem_preimage, mem_Inter, @forall_swap ι M] using exists_smooth_forall_mem_convex_of_local_const I emetric.exists_forall_closed_ball_subset_aux₂ (emetric.exists_forall_closed_ball_subset_aux₁ hK hU hKU hfin) /-- Let `M` be a smooth σ-compact manifold with a metric. Let `K : ι → set M` be a locally finite family of closed sets, let `U : ι → set M` be a family of open sets such that `K i ⊆ U i` for all `i`. Then there exists a positive smooth function `δ : M → ℝ≥0` such that for any `i` and `x ∈ K i`, we have `metric.closed_ball x (δ x) ⊆ U i`. -/ lemma metric.exists_smooth_forall_closed_ball_subset {M} [metric_space M] [charted_space H M] [smooth_manifold_with_corners I M] [sigma_compact_space M] {K : ι → set M} {U : ι → set M} (hK : ∀ i, is_closed (K i)) (hU : ∀ i, is_open (U i)) (hKU : ∀ i, K i ⊆ U i) (hfin : locally_finite K) : ∃ δ : C^∞⟮I, M; 𝓘(ℝ, ℝ), ℝ⟯, (∀ x, 0 < δ x) ∧ ∀ i (x ∈ K i), metric.closed_ball x (δ x) ⊆ U i := begin rcases emetric.exists_smooth_forall_closed_ball_subset I hK hU hKU hfin with ⟨δ, hδ0, hδ⟩, refine ⟨δ, hδ0, λ i x hx, _⟩, rw [← metric.emetric_closed_ball (hδ0 _).le], exact hδ i x hx end
a734ab386e28f13f17cbc09596b58666708b29ab
618003631150032a5676f229d13a079ac875ff77
/src/analysis/special_functions/pow.lean
ea490ff51a409af8e4a329dd62172e17af740ba7
[ "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
24,694
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Sébastien Gouëzel -/ import analysis.special_functions.trigonometric /-! # Power function on `ℂ`, `ℝ` and `ℝ⁺` We construct the power functions `x ^ y` where `x` and `y` are complex numbers, or `x` and `y` are real numbers, or `x` is a nonnegative real and `y` is real, and prove their basic properties. -/ noncomputable theory open_locale classical real topological_space namespace complex /-- The complex power function `x^y`, given by `x^y = exp(y log x)` (where `log` is the principal determination of the logarithm), unless `x = 0` where one sets `0^0 = 1` and `0^y = 0` for `y ≠ 0`. -/ noncomputable def cpow (x y : ℂ) : ℂ := if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) noncomputable instance : has_pow ℂ ℂ := ⟨cpow⟩ @[simp] lemma cpow_eq_pow (x y : ℂ) : cpow x y = x ^ y := rfl lemma cpow_def (x y : ℂ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := rfl @[simp] lemma cpow_zero (x : ℂ) : x ^ (0 : ℂ) = 1 := by simp [cpow_def] @[simp] lemma cpow_eq_zero_iff (x y : ℂ) : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := by { simp only [cpow_def], split_ifs; simp [*, exp_ne_zero] } @[simp] lemma zero_cpow {x : ℂ} (h : x ≠ 0) : (0 : ℂ) ^ x = 0 := by simp [cpow_def, *] @[simp] lemma cpow_one (x : ℂ) : x ^ (1 : ℂ) = x := if hx : x = 0 then by simp [hx, cpow_def] else by rw [cpow_def, if_neg (one_ne_zero : (1 : ℂ) ≠ 0), if_neg hx, mul_one, exp_log hx] @[simp] lemma one_cpow (x : ℂ) : (1 : ℂ) ^ x = 1 := by rw cpow_def; split_ifs; simp [one_ne_zero, *] at * lemma cpow_add {x : ℂ} (y z : ℂ) (hx : x ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := by simp [cpow_def]; split_ifs; simp [*, exp_add, mul_add] at * lemma cpow_mul {x y : ℂ} (z : ℂ) (h₁ : -π < (log x * y).im) (h₂ : (log x * y).im ≤ π) : x ^ (y * z) = (x ^ y) ^ z := begin simp [cpow_def], split_ifs; simp [*, exp_ne_zero, log_exp h₁ h₂, mul_assoc] at * end lemma cpow_neg (x y : ℂ) : x ^ -y = (x ^ y)⁻¹ := by simp [cpow_def]; split_ifs; simp [exp_neg] @[simp] lemma cpow_nat_cast (x : ℂ) : ∀ (n : ℕ), x ^ (n : ℂ) = x ^ n | 0 := by simp | (n + 1) := if hx : x = 0 then by simp only [hx, pow_succ, complex.zero_cpow (nat.cast_ne_zero.2 (nat.succ_ne_zero _)), zero_mul] else by simp [cpow_def, hx, mul_comm, mul_add, exp_add, pow_succ, (cpow_nat_cast n).symm, exp_log hx] @[simp] lemma cpow_int_cast (x : ℂ) : ∀ (n : ℤ), x ^ (n : ℂ) = x ^ n | (n : ℕ) := by simp; refl | -[1+ n] := by rw fpow_neg_succ_of_nat; simp only [int.neg_succ_of_nat_coe, int.cast_neg, complex.cpow_neg, inv_eq_one_div, int.cast_coe_nat, cpow_nat_cast] lemma cpow_nat_inv_pow (x : ℂ) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℂ)) ^ n = x := have (log x * (↑n)⁻¹).im = (log x).im / n, by rw [div_eq_mul_inv, ← of_real_nat_cast, ← of_real_inv, mul_im, of_real_re, of_real_im]; simp, have h : -π < (log x * (↑n)⁻¹).im ∧ (log x * (↑n)⁻¹).im ≤ π, from (le_total (log x).im 0).elim (λ h, ⟨calc -π < (log x).im : by simp [log, neg_pi_lt_arg] ... ≤ ((log x).im * 1) / n : le_div_of_mul_le (nat.cast_pos.2 hn) (mul_le_mul_of_nonpos_left (by rw ← nat.cast_one; exact nat.cast_le.2 hn) h) ... = (log x * (↑n)⁻¹).im : by simp [this], this.symm ▸ le_trans (div_nonpos_of_nonpos_of_pos h (nat.cast_pos.2 hn)) (le_of_lt real.pi_pos)⟩) (λ h, ⟨this.symm ▸ lt_of_lt_of_le (neg_neg_of_pos real.pi_pos) (div_nonneg h (nat.cast_pos.2 hn)), calc (log x * (↑n)⁻¹).im = (1 * (log x).im) / n : by simp [this] ... ≤ (log x).im : (div_le_of_le_mul (nat.cast_pos.2 hn) (mul_le_mul_of_nonneg_right (by rw ← nat.cast_one; exact nat.cast_le.2 hn) h)) ... ≤ _ : by simp [log, arg_le_pi]⟩), by rw [← cpow_nat_cast, ← cpow_mul _ h.1 h.2, inv_mul_cancel (show (n : ℂ) ≠ 0, from nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 hn)), cpow_one] end complex namespace real /-- The real power function `x^y`, defined as the real part of the complex power function. For `x > 0`, it is equal to `exp(y log x)`. For `x = 0`, one sets `0^0=1` and `0^y=0` for `y ≠ 0`. For `x < 0`, the definition is somewhat arbitary as it depends on the choice of a complex determination of the logarithm. With our conventions, it is equal to `exp (y log x) cos (πy)`. -/ noncomputable def rpow (x y : ℝ) := ((x : ℂ) ^ (y : ℂ)).re noncomputable instance : has_pow ℝ ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x y : ℝ) : rpow x y = x ^ y := rfl lemma rpow_def (x y : ℝ) : x ^ y = ((x : ℂ) ^ (y : ℂ)).re := rfl lemma rpow_def_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := by simp only [rpow_def, complex.cpow_def]; split_ifs; simp [*, (complex.of_real_log hx).symm, -complex.of_real_mul, (complex.of_real_mul _ _).symm, complex.exp_of_real_re] at * lemma rpow_def_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : x ^ y = exp (log x * y) := by rw [rpow_def_of_nonneg (le_of_lt hx), if_neg (ne_of_gt hx)] lemma rpow_eq_zero_iff_of_nonneg {x y : ℝ} (hx : 0 ≤ x) : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := by { simp only [rpow_def_of_nonneg hx], split_ifs; simp [*, exp_ne_zero] } open_locale real lemma rpow_def_of_neg {x : ℝ} (hx : x < 0) (y : ℝ) : x ^ y = exp (log x * y) * cos (y * π) := begin rw [rpow_def, complex.cpow_def, if_neg], have : complex.log x * y = ↑(log(-x) * y) + ↑(y * π) * complex.I, simp only [complex.log, abs_of_neg hx, complex.arg_of_real_of_neg hx, complex.abs_of_real, complex.of_real_mul], ring, { rw [this, complex.exp_add_mul_I, ← complex.of_real_exp, ← complex.of_real_cos, ← complex.of_real_sin, mul_add, ← complex.of_real_mul, ← mul_assoc, ← complex.of_real_mul, complex.add_re, complex.of_real_re, complex.mul_re, complex.I_re, complex.of_real_im, real.log_neg_eq_log], ring }, { rw complex.of_real_eq_zero, exact ne_of_lt hx } end lemma rpow_def_of_nonpos {x : ℝ} (hx : x ≤ 0) (y : ℝ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) * cos (y * π) := by split_ifs; simp [rpow_def, *]; exact rpow_def_of_neg (lt_of_le_of_ne hx h) _ lemma rpow_pos_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : 0 < x ^ y := by rw rpow_def_of_pos hx; apply exp_pos lemma abs_rpow_le_abs_rpow (x y : ℝ) : abs (x ^ y) ≤ abs (x) ^ y := abs_le_of_le_of_neg_le begin cases lt_trichotomy 0 x, { rw abs_of_pos h }, cases h, { simp [h.symm] }, rw [rpow_def_of_neg h, rpow_def_of_pos (abs_pos_of_neg h), log_abs], calc exp (log x * y) * cos (y * π) ≤ exp (log x * y) * 1 : mul_le_mul_of_nonneg_left (cos_le_one _) (le_of_lt $ exp_pos _) ... = _ : mul_one _ end begin cases lt_trichotomy 0 x, { rw abs_of_pos h, have : 0 < x^y := rpow_pos_of_pos h _, linarith }, cases h, { simp only [h.symm, abs_zero, rpow_def_of_nonneg], split_ifs, repeat {norm_num} }, rw [rpow_def_of_neg h, rpow_def_of_pos (abs_pos_of_neg h), log_abs], calc -(exp (log x * y) * cos (y * π)) = exp (log x * y) * (-cos (y * π)) : by ring ... ≤ exp (log x * y) * 1 : mul_le_mul_of_nonneg_left (neg_le.2 $ neg_one_le_cos _) (le_of_lt $ exp_pos _) ... = exp (log x * y) : mul_one _ end end real namespace complex lemma of_real_cpow {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : ((x ^ y : ℝ) : ℂ) = (x : ℂ) ^ (y : ℂ) := by simp [real.rpow_def_of_nonneg hx, complex.cpow_def]; split_ifs; simp [complex.of_real_log hx] @[simp] lemma abs_cpow_real (x : ℂ) (y : ℝ) : abs (x ^ (y : ℂ)) = x.abs ^ y := begin rw [real.rpow_def_of_nonneg (abs_nonneg _), complex.cpow_def], split_ifs; simp [*, abs_of_nonneg (le_of_lt (real.exp_pos _)), complex.log, complex.exp_add, add_mul, mul_right_comm _ I, exp_mul_I, abs_cos_add_sin_mul_I, (complex.of_real_mul _ _).symm, -complex.of_real_mul] at * end @[simp] lemma abs_cpow_inv_nat (x : ℂ) (n : ℕ) : abs (x ^ (n⁻¹ : ℂ)) = x.abs ^ (n⁻¹ : ℝ) := by rw ← abs_cpow_real; simp [-abs_cpow_real] end complex namespace real variables {x y z : ℝ} @[simp] lemma rpow_zero (x : ℝ) : x ^ (0 : ℝ) = 1 := by simp [rpow_def] @[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : ℝ) ^ x = 0 := by simp [rpow_def, *] @[simp] lemma rpow_one (x : ℝ) : x ^ (1 : ℝ) = x := by simp [rpow_def] @[simp] lemma one_rpow (x : ℝ) : (1 : ℝ) ^ x = 1 := by simp [rpow_def] lemma rpow_nonneg_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : 0 ≤ x ^ y := by rw [rpow_def_of_nonneg hx]; split_ifs; simp only [zero_le_one, le_refl, le_of_lt (exp_pos _)] lemma rpow_add {x : ℝ} (y z : ℝ) (hx : 0 < x) : x ^ (y + z) = x ^ y * x ^ z := by simp only [rpow_def_of_pos hx, mul_add, exp_add] lemma rpow_mul {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := by rw [← complex.of_real_inj, complex.of_real_cpow (rpow_nonneg_of_nonneg hx _), complex.of_real_cpow hx, complex.of_real_mul, complex.cpow_mul, complex.of_real_cpow hx]; simp only [(complex.of_real_mul _ _).symm, (complex.of_real_log hx).symm, complex.of_real_im, neg_lt_zero, pi_pos, le_of_lt pi_pos] lemma rpow_neg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := by simp only [rpow_def_of_nonneg hx]; split_ifs; simp [*, exp_neg] at * @[simp] lemma rpow_nat_cast (x : ℝ) (n : ℕ) : x ^ (n : ℝ) = x ^ n := by simp only [rpow_def, (complex.of_real_pow _ _).symm, complex.cpow_nat_cast, complex.of_real_nat_cast, complex.of_real_re] @[simp] lemma rpow_int_cast (x : ℝ) (n : ℤ) : x ^ (n : ℝ) = x ^ n := by simp only [rpow_def, (complex.of_real_fpow _ _).symm, complex.cpow_int_cast, complex.of_real_int_cast, complex.of_real_re] lemma mul_rpow {x y z : ℝ} (h : 0 ≤ x) (h₁ : 0 ≤ y) : (x*y)^z = x^z * y^z := begin iterate 3 { rw real.rpow_def_of_nonneg }, split_ifs; simp * at *, { have hx : 0 < x, cases lt_or_eq_of_le h with h₂ h₂, exact h₂, exfalso, apply h_2, exact eq.symm h₂, have hy : 0 < y, cases lt_or_eq_of_le h₁ with h₂ h₂, exact h₂, exfalso, apply h_3, exact eq.symm h₂, rw [log_mul (ne_of_gt hx) (ne_of_gt hy), add_mul, exp_add]}, { exact h₁}, { exact h}, { exact mul_nonneg h h₁}, end lemma one_le_rpow {x z : ℝ} (h : 1 ≤ x) (h₁ : 0 ≤ z) : 1 ≤ x^z := begin rw real.rpow_def_of_nonneg, split_ifs with h₂ h₃, { refl}, { simp [*, not_le_of_gt zero_lt_one] at *}, { have hx : 0 < x, exact lt_of_lt_of_le zero_lt_one h, rw [←log_le_log zero_lt_one hx, log_one] at h, have pos : 0 ≤ log x * z, exact mul_nonneg h h₁, rwa [←exp_le_exp, exp_zero] at pos}, { exact le_trans zero_le_one h}, end lemma rpow_le_rpow {x y z: ℝ} (h : 0 ≤ x) (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := begin rw le_iff_eq_or_lt at h h₂, cases h₂, { rw [←h₂, rpow_zero, rpow_zero]}, { cases h, { rw [←h, zero_rpow], rw real.rpow_def_of_nonneg, split_ifs, { exact zero_le_one}, { refl}, { exact le_of_lt (exp_pos (log y * z))}, { rwa ←h at h₁}, { exact ne.symm (ne_of_lt h₂)}}, { have one_le : 1 ≤ y / x, rw one_le_div_iff_le h, exact h₁, have one_le_pow : 1 ≤ (y / x)^z, exact one_le_rpow one_le (le_of_lt h₂), rw [←mul_div_cancel y (ne.symm (ne_of_lt h)), mul_comm, mul_div_assoc], rw [mul_rpow (le_of_lt h) (le_trans zero_le_one one_le), mul_comm], exact (le_mul_of_ge_one_left (rpow_nonneg_of_nonneg (le_of_lt h) z) one_le_pow) } } end lemma rpow_lt_rpow (hx : 0 ≤ x) (hxy : x < y) (hz : 0 < z) : x^z < y^z := begin rw le_iff_eq_or_lt at hx, cases hx, { rw [← hx, zero_rpow (ne_of_gt hz)], exact rpow_pos_of_pos (by rwa ← hx at hxy) _ }, rw [rpow_def_of_pos hx, rpow_def_of_pos (lt_trans hx hxy), exp_lt_exp], exact mul_lt_mul_of_pos_right (log_lt_log hx hxy) hz end lemma rpow_lt_rpow_of_exponent_lt (hx : 1 < x) (hyz : y < z) : x^y < x^z := begin repeat {rw [rpow_def_of_pos (lt_trans zero_lt_one hx)]}, rw exp_lt_exp, exact mul_lt_mul_of_pos_left hyz (log_pos hx), end lemma rpow_le_rpow_of_exponent_le (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := begin repeat {rw [rpow_def_of_pos (lt_of_lt_of_le zero_lt_one hx)]}, rw exp_le_exp, exact mul_le_mul_of_nonneg_left hyz (log_nonneg hx), end lemma rpow_lt_rpow_of_exponent_gt (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := begin repeat {rw [rpow_def_of_pos hx0]}, rw exp_lt_exp, exact mul_lt_mul_of_neg_left hyz (log_neg hx0 hx1), end lemma rpow_le_rpow_of_exponent_ge (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := begin repeat {rw [rpow_def_of_pos hx0]}, rw exp_le_exp, exact mul_le_mul_of_nonpos_left hyz (log_nonpos (le_of_lt hx0) hx1), end lemma rpow_le_one {x e : ℝ} (he : 0 ≤ e) (hx : 0 ≤ x) (hx2 : x ≤ 1) : x^e ≤ 1 := by rw ←one_rpow e; apply rpow_le_rpow; assumption lemma one_lt_rpow (hx : 1 < x) (hz : 0 < z) : 1 < x^z := by { rw ← one_rpow z, exact rpow_lt_rpow zero_le_one hx hz } lemma rpow_lt_one (hx : 0 < x) (hx1 : x < 1) (hz : 0 < z) : x^z < 1 := by { rw ← one_rpow z, exact rpow_lt_rpow (le_of_lt hx) hx1 hz } lemma pow_nat_rpow_nat_inv {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) : (x ^ n) ^ (n⁻¹ : ℝ) = x := have hn0 : (n : ℝ) ≠ 0, by simpa [nat.pos_iff_ne_zero] using hn, by rw [← rpow_nat_cast, ← rpow_mul hx, mul_inv_cancel hn0, rpow_one] lemma rpow_nat_inv_pow_nat {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℝ)) ^ n = x := have hn0 : (n : ℝ) ≠ 0, by simpa [nat.pos_iff_ne_zero] using hn, by rw [← rpow_nat_cast, ← rpow_mul hx, inv_mul_cancel hn0, rpow_one] section prove_rpow_is_continuous lemma continuous_rpow_aux1 : continuous (λp : {p:ℝ×ℝ // 0 < p.1}, p.val.1 ^ p.val.2) := suffices h : continuous (λ p : {p:ℝ×ℝ // 0 < p.1 }, exp (log p.val.1 * p.val.2)), by { convert h, ext p, rw rpow_def_of_pos p.2 }, continuous_exp.comp $ (show continuous ((λp:{p:ℝ//0 < p}, log (p.val)) ∘ (λp:{p:ℝ×ℝ//0<p.fst}, ⟨p.val.1, p.2⟩)), from continuous_log'.comp $ continuous_subtype_mk _ $ continuous_fst.comp continuous_subtype_val).mul (continuous_snd.comp $ continuous_subtype_val.comp continuous_id) lemma continuous_rpow_aux2 : continuous (λ p : {p:ℝ×ℝ // p.1 < 0}, p.val.1 ^ p.val.2) := suffices h : continuous (λp:{p:ℝ×ℝ // p.1 < 0}, exp (log (-p.val.1) * p.val.2) * cos (p.val.2 * π)), by { convert h, ext p, rw [rpow_def_of_neg p.2, log_neg_eq_log] }, (continuous_exp.comp $ (show continuous $ (λp:{p:ℝ//0<p}, log (p.val))∘(λp:{p:ℝ×ℝ//p.1<0}, ⟨-p.val.1, neg_pos_of_neg p.2⟩), from continuous_log'.comp $ continuous_subtype_mk _ $ continuous_neg.comp $ continuous_fst.comp continuous_subtype_val).mul (continuous_snd.comp $ continuous_subtype_val.comp continuous_id)).mul (continuous_cos.comp $ (continuous_snd.comp $ continuous_subtype_val.comp continuous_id).mul continuous_const) lemma continuous_at_rpow_of_ne_zero (hx : x ≠ 0) (y : ℝ) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := begin cases lt_trichotomy 0 x, exact continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux1 _ h) (mem_nhds_sets (by { convert is_open_prod (is_open_lt' (0:ℝ)) is_open_univ, ext, finish }) h), cases h, { exact absurd h.symm hx }, exact continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux2 _ h) (mem_nhds_sets (by { convert is_open_prod (is_open_gt' (0:ℝ)) is_open_univ, ext, finish }) h) end lemma continuous_rpow_aux3 : continuous (λ p : {p:ℝ×ℝ // 0 < p.2}, p.val.1 ^ p.val.2) := continuous_iff_continuous_at.2 $ λ ⟨(x₀, y₀), hy₀⟩, begin by_cases hx₀ : x₀ = 0, { simp only [continuous_at, hx₀, zero_rpow (ne_of_gt hy₀), metric.tendsto_nhds_nhds], assume ε ε0, rcases exists_pos_rat_lt (half_pos hy₀) with ⟨q, q_pos, q_lt⟩, let q := (q:ℝ), replace q_pos : 0 < q := rat.cast_pos.2 q_pos, let δ := min (min q (ε ^ (1 / q))) (1/2), have δ0 : 0 < δ := lt_min (lt_min q_pos (rpow_pos_of_pos ε0 _)) (by norm_num), have : δ ≤ q := le_trans (min_le_left _ _) (min_le_left _ _), have : δ ≤ ε ^ (1 / q) := le_trans (min_le_left _ _) (min_le_right _ _), have : δ < 1 := lt_of_le_of_lt (min_le_right _ _) (by norm_num), use δ, use δ0, rintros ⟨⟨x, y⟩, hy⟩, simp only [subtype.dist_eq, real.dist_eq, prod.dist_eq, sub_zero, subtype.coe_mk], assume h, rw max_lt_iff at h, cases h with xδ yy₀, have qy : q < y, calc q < y₀ / 2 : q_lt ... = y₀ - y₀ / 2 : (sub_half _).symm ... ≤ y₀ - δ : by linarith ... < y : sub_lt_of_abs_sub_lt_left yy₀, calc abs(x^y) ≤ abs(x)^y : abs_rpow_le_abs_rpow _ _ ... < δ ^ y : rpow_lt_rpow (abs_nonneg _) xδ hy ... < δ ^ q : by { refine rpow_lt_rpow_of_exponent_gt _ _ _, repeat {linarith} } ... ≤ (ε ^ (1 / q)) ^ q : by { refine rpow_le_rpow _ _ _, repeat {linarith} } ... = ε : by { rw [← rpow_mul, div_mul_cancel, rpow_one], exact ne_of_gt q_pos, linarith }}, { exact (continuous_within_at_iff_continuous_at_restrict (λp:ℝ×ℝ, p.1^p.2) _).1 (continuous_at_rpow_of_ne_zero hx₀ _).continuous_within_at } end lemma continuous_at_rpow_of_pos (hy : 0 < y) (x : ℝ) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux3 _ hy) (mem_nhds_sets (by { convert is_open_prod is_open_univ (is_open_lt' (0:ℝ)), ext, finish }) hy) lemma continuous_at_rpow {x y : ℝ} (h : x ≠ 0 ∨ 0 < y) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := by { cases h, exact continuous_at_rpow_of_ne_zero h _, exact continuous_at_rpow_of_pos h x } variables {α : Type*} [topological_space α] {f g : α → ℝ} /-- `real.rpow` is continuous at all points except for the lower half of the y-axis. In other words, the function `λp:ℝ×ℝ, p.1^p.2` is continuous at `(x, y)` if `x ≠ 0` or `y > 0`. Multiple forms of the claim is provided in the current section. -/ lemma continuous_rpow (h : ∀a, f a ≠ 0 ∨ 0 < g a) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_iff_continuous_at.2 $ λ a, begin show continuous_at ((λp:ℝ×ℝ, p.1^p.2) ∘ (λa, (f a, g a))) a, refine continuous_at.comp _ (continuous_iff_continuous_at.1 (hf.prod_mk hg) _), { replace h := h a, cases h, { exact continuous_at_rpow_of_ne_zero h _ }, { exact continuous_at_rpow_of_pos h _ }}, end lemma continuous_rpow_of_ne_zero (h : ∀a, f a ≠ 0) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inl $ h a) hf hg lemma continuous_rpow_of_pos (h : ∀a, 0 < g a) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inr $ h a) hf hg end prove_rpow_is_continuous section sqrt lemma sqrt_eq_rpow : sqrt = λx:ℝ, x ^ (1/(2:ℝ)) := begin funext, by_cases h : 0 ≤ x, { rw [← mul_self_inj_of_nonneg, mul_self_sqrt h, ← pow_two, ← rpow_nat_cast, ← rpow_mul h], norm_num, exact sqrt_nonneg _, exact rpow_nonneg_of_nonneg h _ }, { replace h : x < 0 := lt_of_not_ge h, have : 1 / (2:ℝ) * π = π / (2:ℝ), ring, rw [sqrt_eq_zero_of_nonpos (le_of_lt h), rpow_def_of_neg h, this, cos_pi_div_two, mul_zero] } end lemma continuous_sqrt : continuous sqrt := by rw sqrt_eq_rpow; exact continuous_rpow_of_pos (λa, by norm_num) continuous_id continuous_const end sqrt end real namespace nnreal /-- The nonnegative real power function `x^y`, defined for `x : nnreal` and `y : ℝ ` as the restriction of the real power function. For `x > 0`, it is equal to `exp (y log x)`. For `x = 0`, one sets `0 ^ 0 = 1` and `0 ^ y = 0` for `y ≠ 0`. -/ noncomputable def rpow (x : nnreal) (y : ℝ) : nnreal := ⟨(x : ℝ) ^ y, real.rpow_nonneg_of_nonneg x.2 y⟩ noncomputable instance : has_pow nnreal ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x : nnreal) (y : ℝ) : rpow x y = x ^ y := rfl @[simp, norm_cast] lemma coe_rpow (x : nnreal) (y : ℝ) : ((x ^ y : nnreal) : ℝ) = (x : ℝ) ^ y := rfl @[simp] lemma rpow_zero (x : nnreal) : x ^ (0 : ℝ) = 1 := by { rw ← nnreal.coe_eq, exact real.rpow_zero _ } @[simp] lemma rpow_eq_zero_iff {x : nnreal} {y : ℝ} : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := begin rw [← nnreal.coe_eq, coe_rpow, ← nnreal.coe_eq_zero], exact real.rpow_eq_zero_iff_of_nonneg x.2 end @[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : nnreal) ^ x = 0 := by { rw ← nnreal.coe_eq, exact real.zero_rpow h } @[simp] lemma rpow_one (x : nnreal) : x ^ (1 : ℝ) = x := by { rw ← nnreal.coe_eq, exact real.rpow_one _ } @[simp] lemma one_rpow (x : ℝ) : (1 : nnreal) ^ x = 1 := by { rw ← nnreal.coe_eq, exact real.one_rpow _ } lemma rpow_add {x : nnreal} (y z : ℝ) (hx : 0 < x) : x ^ (y + z) = x ^ y * x ^ z := by { rw ← nnreal.coe_eq, exact real.rpow_add _ _ hx } lemma rpow_mul (x : nnreal) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := by { rw ← nnreal.coe_eq, exact real.rpow_mul x.2 y z } lemma rpow_neg (x : nnreal) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := by { rw ← nnreal.coe_eq, exact real.rpow_neg x.2 _ } @[simp] lemma rpow_nat_cast (x : nnreal) (n : ℕ) : x ^ (n : ℝ) = x ^ n := by { rw [← nnreal.coe_eq, nnreal.coe_pow], exact real.rpow_nat_cast (x : ℝ) n } lemma mul_rpow {x y : nnreal} {z : ℝ} : (x*y)^z = x^z * y^z := by { rw ← nnreal.coe_eq, exact real.mul_rpow x.2 y.2 } lemma one_le_rpow {x : nnreal} {z : ℝ} (h : 1 ≤ x) (h₁ : 0 ≤ z) : 1 ≤ x^z := real.one_le_rpow h h₁ lemma rpow_le_rpow {x y : nnreal} {z: ℝ} (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := real.rpow_le_rpow x.2 h₁ h₂ lemma rpow_lt_rpow {x y : nnreal} {z: ℝ} (h₁ : x < y) (h₂ : 0 < z) : x^z < y^z := real.rpow_lt_rpow x.2 h₁ h₂ lemma rpow_lt_rpow_of_exponent_lt {x : nnreal} {y z : ℝ} (hx : 1 < x) (hyz : y < z) : x^y < x^z := real.rpow_lt_rpow_of_exponent_lt hx hyz lemma rpow_le_rpow_of_exponent_le {x : nnreal} {y z : ℝ} (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := real.rpow_le_rpow_of_exponent_le hx hyz lemma rpow_lt_rpow_of_exponent_gt {x : nnreal} {y z : ℝ} (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := real.rpow_lt_rpow_of_exponent_gt hx0 hx1 hyz lemma rpow_le_rpow_of_exponent_ge {x : nnreal} {y z : ℝ} (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := real.rpow_le_rpow_of_exponent_ge hx0 hx1 hyz lemma rpow_le_one {x : nnreal} {e : ℝ} (he : 0 ≤ e) (hx2 : x ≤ 1) : x^e ≤ 1 := real.rpow_le_one he x.2 hx2 lemma one_lt_rpow {x : nnreal} {z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z := real.one_lt_rpow hx hz lemma rpow_lt_one {x : nnreal} {z : ℝ} (hx : 0 < x) (hx1 : x < 1) (hz : 0 < z) : x^z < 1 := real.rpow_lt_one hx hx1 hz lemma pow_nat_rpow_nat_inv (x : nnreal) {n : ℕ} (hn : 0 < n) : (x ^ n) ^ (n⁻¹ : ℝ) = x := by { rw [← nnreal.coe_eq, coe_rpow, nnreal.coe_pow], exact real.pow_nat_rpow_nat_inv x.2 hn } lemma rpow_nat_inv_pow_nat (x : nnreal) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℝ)) ^ n = x := by { rw [← nnreal.coe_eq, nnreal.coe_pow, coe_rpow], exact real.rpow_nat_inv_pow_nat x.2 hn } lemma continuous_at_rpow {x : nnreal} {y : ℝ} (h : x ≠ 0 ∨ 0 < y) : continuous_at (λp:nnreal×ℝ, p.1^p.2) (x, y) := begin have : (λp:nnreal×ℝ, p.1^p.2) = nnreal.of_real ∘ (λp:ℝ×ℝ, p.1^p.2) ∘ (λp:nnreal × ℝ, (p.1.1, p.2)), { ext p, rw [← nnreal.coe_eq, coe_rpow, nnreal.coe_of_real _ (real.rpow_nonneg_of_nonneg p.1.2 _)], refl }, rw this, refine nnreal.continuous_of_real.continuous_at.comp (continuous_at.comp _ _), { apply real.continuous_at_rpow, simp at h, rw ← (nnreal.coe_eq_zero x) at h, exact h }, { exact ((continuous_subtype_val.comp continuous_fst).prod_mk continuous_snd).continuous_at } end end nnreal open filter lemma filter.tendsto.nnrpow {α : Type*} {f : filter α} {u : α → nnreal} {v : α → ℝ} {x : nnreal} {y : ℝ} (hx : tendsto u f (𝓝 x)) (hy : tendsto v f (𝓝 y)) (h : x ≠ 0 ∨ 0 < y) : tendsto (λ a, (u a) ^ (v a)) f (𝓝 (x ^ y)) := tendsto.comp (nnreal.continuous_at_rpow h) (tendsto.prod_mk_nhds hx hy)
f7e5d86c999a59df5db9bddef065df17dc6f060b
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/run/multiTargetCasesInductionIssue.lean
507d9919bc495931df05a0fc3a0e6d73bca1dac3
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
1,660
lean
def Vec (α : Type u) (n : Nat) : Type u := { a : List α // a.length = n } def Vec.nil : Vec α 0 := ⟨[], rfl⟩ def Vec.cons (a : α) (as : Vec α n) : Vec α (n+1) := ⟨a :: as.val, by simp [as.property]⟩ set_option pp.analyze false def Vec.casesOn (motive : (n : Nat) → Vec α n → Sort v) (n : Nat) (as : Vec α n) (nil : motive 0 Vec.nil) (cons : (n : Nat) → (a : α) → (as : Vec α n) → (ih : motive n as) → motive (n+1) (Vec.cons a as)) : motive n as := let rec go (n : Nat) (as : List α) (h : as.length = n) : motive n ⟨as, h⟩ := match n, as, h with | 0, [], _ => nil | n+1, a::as, h => have : as.length = n := by injection h; assumption have ih : motive n ⟨as, this⟩ := go n as this cons n a ⟨as, this⟩ ih match as with | ⟨as, h⟩ => go n as h example (n : Nat) (a : α) (as : Vec α n) : Vec.cons a (Vec.cons a as) = Vec.cons a (Vec.cons a as) := by induction n+2, Vec.cons a (Vec.cons a as) using Vec.casesOn case nil => constructor case cons n a as ih => trace_state constructor #print "-----" example (n : Nat) (a : α) (as : Vec α n) : Vec.cons a (Vec.cons a as) = Vec.cons a (Vec.cons a as) := by cases n+2, Vec.cons a (Vec.cons a as) using Vec.casesOn case nil => constructor case cons n a as ih => trace_state constructor #print "-----" example (n : Nat) (a : α) (as : Vec α n) : Vec.cons a (Vec.cons a as) = Vec.cons a (Vec.cons a as) := by cases h₁ : n+2, h₂ : Vec.cons a (Vec.cons a as) using Vec.casesOn case nil => constructor case cons n' a' as' ih => trace_state constructor
8c414531cebcbfcba38fac6abc308b2aadb9f387
63abd62053d479eae5abf4951554e1064a4c45b4
/src/algebra/group/hom.lean
e4171d1509df70d9f35ca9087c580dc669a56c57
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
25,484
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Kevin Buzzard, Scott Morrison, Johan Commelin, Chris Hughes, Johannes Hölzl, Yury Kudryashov -/ import algebra.group.commute /-! # monoid and group homomorphisms This file defines the bundled structures for monoid and group homomorphisms. Namely, we define `monoid_hom` (resp., `add_monoid_hom`) to be bundled homomorphisms between multiplicative (resp., additive) monoids or groups. We also define coercion to a function, and usual operations: composition, identity homomorphism, pointwise multiplication and pointwise inversion. ## Notations * `→*` for bundled monoid homs (also use for group homs) * `→+` for bundled add_monoid homs (also use for add_group homs) ## implementation notes There's a coercion from bundled homs to fun, and the canonical notation is to use the bundled hom as a function via this coercion. There is no `group_hom` -- the idea is that `monoid_hom` is used. The constructor for `monoid_hom` needs a proof of `map_one` as well as `map_mul`; a separate constructor `monoid_hom.mk'` will construct group homs (i.e. monoid homs between groups) given only a proof that multiplication is preserved, Implicit `{}` brackets are often used instead of type class `[]` brackets. This is done when the instances can be inferred because they are implicit arguments to the type `monoid_hom`. When they can be inferred from the type it is faster to use this method than to use type class inference. Historically this file also included definitions of unbundled homomorphism classes; they were deprecated and moved to `deprecated/group`. ## Tags monoid_hom, add_monoid_hom -/ variables {M : Type*} {N : Type*} {P : Type*} -- monoids {G : Type*} {H : Type*} -- groups -- for easy multiple inheritance set_option old_structure_cmd true /-- Homomorphism that preserves zero -/ structure zero_hom (M : Type*) (N : Type*) [has_zero M] [has_zero N] := (to_fun : M → N) (map_zero' : to_fun 0 = 0) /-- Homomorphism that preserves addition -/ structure add_hom (M : Type*) (N : Type*) [has_add M] [has_add N] := (to_fun : M → N) (map_add' : ∀ x y, to_fun (x + y) = to_fun x + to_fun y) /-- Bundled add_monoid homomorphisms; use this for bundled add_group homomorphisms too. -/ structure add_monoid_hom (M : Type*) (N : Type*) [add_monoid M] [add_monoid N] extends zero_hom M N, add_hom M N attribute [nolint doc_blame] add_monoid_hom.to_add_hom attribute [nolint doc_blame] add_monoid_hom.to_zero_hom infixr ` →+ `:25 := add_monoid_hom /-- Homomorphism that preserves one -/ @[to_additive] structure one_hom (M : Type*) (N : Type*) [has_one M] [has_one N] := (to_fun : M → N) (map_one' : to_fun 1 = 1) /-- Homomorphism that preserves multiplication -/ @[to_additive] structure mul_hom (M : Type*) (N : Type*) [has_mul M] [has_mul N] := (to_fun : M → N) (map_mul' : ∀ x y, to_fun (x * y) = to_fun x * to_fun y) /-- Bundled monoid homomorphisms; use this for bundled group homomorphisms too. -/ @[to_additive] structure monoid_hom (M : Type*) (N : Type*) [monoid M] [monoid N] extends one_hom M N, mul_hom M N attribute [nolint doc_blame] monoid_hom.to_mul_hom attribute [nolint doc_blame] monoid_hom.to_one_hom infixr ` →* `:25 := monoid_hom -- completely uninteresting lemmas about coercion to function, that all homs need section coes @[to_additive] instance {mM : has_one M} {mN : has_one N} : has_coe_to_fun (one_hom M N) := ⟨_, one_hom.to_fun⟩ @[to_additive] instance {mM : has_mul M} {mN : has_mul N} : has_coe_to_fun (mul_hom M N) := ⟨_, mul_hom.to_fun⟩ @[to_additive] instance {mM : monoid M} {mN : monoid N} : has_coe_to_fun (M →* N) := ⟨_, monoid_hom.to_fun⟩ -- these must come after the coe_to_fun definitions initialize_simps_projections zero_hom (to_fun → apply) initialize_simps_projections add_hom (to_fun → apply) initialize_simps_projections add_monoid_hom (to_fun → apply) initialize_simps_projections one_hom (to_fun → apply) initialize_simps_projections mul_hom (to_fun → apply) initialize_simps_projections monoid_hom (to_fun → apply) @[simp, to_additive] lemma one_hom.to_fun_eq_coe [has_one M] [has_one N] (f : one_hom M N) : f.to_fun = f := rfl @[simp, to_additive] lemma mul_hom.to_fun_eq_coe [has_mul M] [has_mul N] (f : mul_hom M N) : f.to_fun = f := rfl @[simp, to_additive] lemma monoid_hom.to_fun_eq_coe [monoid M] [monoid N] (f : M →* N) : f.to_fun = f := rfl @[simp, to_additive] lemma one_hom.coe_mk [has_one M] [has_one N] (f : M → N) (h1) : ⇑(one_hom.mk f h1) = f := rfl @[simp, to_additive] lemma mul_hom.coe_mk [has_mul M] [has_mul N] (f : M → N) (hmul) : ⇑(mul_hom.mk f hmul) = f := rfl @[simp, to_additive] lemma monoid_hom.coe_mk [monoid M] [monoid N] (f : M → N) (h1 hmul) : ⇑(monoid_hom.mk f h1 hmul) = f := rfl @[to_additive] theorem one_hom.congr_fun [has_one M] [has_one N] {f g : one_hom M N} (h : f = g) (x : M) : f x = g x := congr_arg (λ h : one_hom M N, h x) h @[to_additive] theorem mul_hom.congr_fun [has_mul M] [has_mul N] {f g : mul_hom M N} (h : f = g) (x : M) : f x = g x := congr_arg (λ h : mul_hom M N, h x) h @[to_additive] theorem monoid_hom.congr_fun [monoid M] [monoid N] {f g : M →* N} (h : f = g) (x : M) : f x = g x := congr_arg (λ h : M →* N, h x) h @[to_additive] theorem one_hom.congr_arg [has_one M] [has_one N] (f : one_hom M N) {x y : M} (h : x = y) : f x = f y := congr_arg (λ x : M, f x) h @[to_additive] theorem mul_hom.congr_arg [has_mul M] [has_mul N] (f : mul_hom M N) {x y : M} (h : x = y) : f x = f y := congr_arg (λ x : M, f x) h @[to_additive] theorem monoid_hom.congr_arg [monoid M] [monoid N] (f : M →* N) {x y : M} (h : x = y) : f x = f y := congr_arg (λ x : M, f x) h @[to_additive] lemma one_hom.coe_inj [has_one M] [has_one N] ⦃f g : one_hom M N⦄ (h : (f : M → N) = g) : f = g := by cases f; cases g; cases h; refl @[to_additive] lemma mul_hom.coe_inj [has_mul M] [has_mul N] ⦃f g : mul_hom M N⦄ (h : (f : M → N) = g) : f = g := by cases f; cases g; cases h; refl @[to_additive] lemma monoid_hom.coe_inj [monoid M] [monoid N] ⦃f g : M →* N⦄ (h : (f : M → N) = g) : f = g := by cases f; cases g; cases h; refl @[ext, to_additive] lemma one_hom.ext [has_one M] [has_one N] ⦃f g : one_hom M N⦄ (h : ∀ x, f x = g x) : f = g := one_hom.coe_inj (funext h) @[ext, to_additive] lemma mul_hom.ext [has_mul M] [has_mul N] ⦃f g : mul_hom M N⦄ (h : ∀ x, f x = g x) : f = g := mul_hom.coe_inj (funext h) @[ext, to_additive] lemma monoid_hom.ext [monoid M] [monoid N] ⦃f g : M →* N⦄ (h : ∀ x, f x = g x) : f = g := monoid_hom.coe_inj (funext h) attribute [ext] zero_hom.ext add_hom.ext add_monoid_hom.ext @[to_additive] lemma one_hom.ext_iff [has_one M] [has_one N] {f g : one_hom M N} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, one_hom.ext h⟩ @[to_additive] lemma mul_hom.ext_iff [has_mul M] [has_mul N] {f g : mul_hom M N} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, mul_hom.ext h⟩ @[to_additive] lemma monoid_hom.ext_iff [monoid M] [monoid N] {f g : M →* N} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, monoid_hom.ext h⟩ end coes @[simp, to_additive] lemma one_hom.map_one [has_one M] [has_one N] (f : one_hom M N) : f 1 = 1 := f.map_one' /-- If `f` is a monoid homomorphism then `f 1 = 1`. -/ @[simp, to_additive] lemma monoid_hom.map_one [monoid M] [monoid N] (f : M →* N) : f 1 = 1 := f.map_one' /-- If `f` is an additive monoid homomorphism then `f 0 = 0`. -/ add_decl_doc add_monoid_hom.map_zero @[simp, to_additive] lemma mul_hom.map_mul [has_mul M] [has_mul N] (f : mul_hom M N) (a b : M) : f (a * b) = f a * f b := f.map_mul' a b /-- If `f` is a monoid homomorphism then `f (a * b) = f a * f b`. -/ @[simp, to_additive] lemma monoid_hom.map_mul [monoid M] [monoid N] (f : M →* N) (a b : M) : f (a * b) = f a * f b := f.map_mul' a b /-- If `f` is an additive monoid homomorphism then `f (a + b) = f a + f b`. -/ add_decl_doc add_monoid_hom.map_add namespace monoid_hom variables {mM : monoid M} {mN : monoid N} {mP : monoid P} variables [group G] [comm_group H] include mM mN @[to_additive] lemma map_mul_eq_one (f : M →* N) {a b : M} (h : a * b = 1) : f a * f b = 1 := by rw [← f.map_mul, h, f.map_one] /-- Given a monoid homomorphism `f : M →* N` and an element `x : M`, if `x` has a right inverse, then `f x` has a right inverse too. For elements invertible on both sides see `is_unit.map`. -/ @[to_additive "Given an add_monoid homomorphism `f : M →+ N` and an element `x : M`, if `x` has a right inverse, then `f x` has a right inverse too."] lemma map_exists_right_inv (f : M →* N) {x : M} (hx : ∃ y, x * y = 1) : ∃ y, f x * y = 1 := let ⟨y, hy⟩ := hx in ⟨f y, f.map_mul_eq_one hy⟩ /-- Given a monoid homomorphism `f : M →* N` and an element `x : M`, if `x` has a left inverse, then `f x` has a left inverse too. For elements invertible on both sides see `is_unit.map`. -/ @[to_additive "Given an add_monoid homomorphism `f : M →+ N` and an element `x : M`, if `x` has a left inverse, then `f x` has a left inverse too. For elements invertible on both sides see `is_add_unit.map`."] lemma map_exists_left_inv (f : M →* N) {x : M} (hx : ∃ y, y * x = 1) : ∃ y, y * f x = 1 := let ⟨y, hy⟩ := hx in ⟨f y, f.map_mul_eq_one hy⟩ end monoid_hom /-- The identity map from a type with 1 to itself. -/ @[to_additive] def one_hom.id (M : Type*) [has_one M] : one_hom M M := { to_fun := id, map_one' := rfl, } /-- The identity map from a type with multiplication to itself. -/ @[to_additive] def mul_hom.id (M : Type*) [has_mul M] : mul_hom M M := { to_fun := id, map_mul' := λ _ _, rfl, } /-- The identity map from a monoid to itself. -/ @[to_additive] def monoid_hom.id (M : Type*) [monoid M] : M →* M := { to_fun := id, map_one' := rfl, map_mul' := λ _ _, rfl, } /-- The identity map from an type with zero to itself. -/ add_decl_doc zero_hom.id /-- The identity map from an type with addition to itself. -/ add_decl_doc add_hom.id /-- The identity map from an additive monoid to itself. -/ add_decl_doc add_monoid_hom.id @[simp, to_additive] lemma one_hom.id_apply {M : Type*} [has_one M] (x : M) : one_hom.id M x = x := rfl @[simp, to_additive] lemma mul_hom.id_apply {M : Type*} [has_mul M] (x : M) : mul_hom.id M x = x := rfl @[simp, to_additive] lemma monoid_hom.id_apply {M : Type*} [monoid M] (x : M) : monoid_hom.id M x = x := rfl /-- Composition of `one_hom`s as a `one_hom`. -/ @[to_additive] def one_hom.comp [has_one M] [has_one N] [has_one P] (hnp : one_hom N P) (hmn : one_hom M N) : one_hom M P := { to_fun := hnp ∘ hmn, map_one' := by simp, } /-- Composition of `mul_hom`s as a `mul_hom`. -/ @[to_additive] def mul_hom.comp [has_mul M] [has_mul N] [has_mul P] (hnp : mul_hom N P) (hmn : mul_hom M N) : mul_hom M P := { to_fun := hnp ∘ hmn, map_mul' := by simp, } /-- Composition of monoid morphisms as a monoid morphism. -/ @[to_additive] def monoid_hom.comp [monoid M] [monoid N] [monoid P] (hnp : N →* P) (hmn : M →* N) : M →* P := { to_fun := hnp ∘ hmn, map_one' := by simp, map_mul' := by simp, } /-- Composition of `zero_hom`s as a `zero_hom`. -/ add_decl_doc zero_hom.comp /-- Composition of `add_hom`s as a `add_hom`. -/ add_decl_doc add_hom.comp /-- Composition of additive monoid morphisms as an additive monoid morphism. -/ add_decl_doc add_monoid_hom.comp @[simp, to_additive] lemma one_hom.coe_comp [has_one M] [has_one N] [has_one P] (g : one_hom N P) (f : one_hom M N) : ⇑(g.comp f) = g ∘ f := rfl @[simp, to_additive] lemma mul_hom.coe_comp [has_mul M] [has_mul N] [has_mul P] (g : mul_hom N P) (f : mul_hom M N) : ⇑(g.comp f) = g ∘ f := rfl @[simp, to_additive] lemma monoid_hom.coe_comp [monoid M] [monoid N] [monoid P] (g : N →* P) (f : M →* N) : ⇑(g.comp f) = g ∘ f := rfl @[to_additive] lemma one_hom.comp_apply [has_one M] [has_one N] [has_one P] (g : one_hom N P) (f : one_hom M N) (x : M) : g.comp f x = g (f x) := rfl @[to_additive] lemma mul_hom.comp_apply [has_mul M] [has_mul N] [has_mul P] (g : mul_hom N P) (f : mul_hom M N) (x : M) : g.comp f x = g (f x) := rfl @[to_additive] lemma monoid_hom.comp_apply [monoid M] [monoid N] [monoid P] (g : N →* P) (f : M →* N) (x : M) : g.comp f x = g (f x) := rfl /-- Composition of monoid homomorphisms is associative. -/ @[to_additive] lemma one_hom.comp_assoc {Q : Type*} [has_one M] [has_one N] [has_one P] [has_one Q] (f : one_hom M N) (g : one_hom N P) (h : one_hom P Q) : (h.comp g).comp f = h.comp (g.comp f) := rfl @[to_additive] lemma mul_hom.comp_assoc {Q : Type*} [has_mul M] [has_mul N] [has_mul P] [has_mul Q] (f : mul_hom M N) (g : mul_hom N P) (h : mul_hom P Q) : (h.comp g).comp f = h.comp (g.comp f) := rfl @[to_additive] lemma monoid_hom.comp_assoc {Q : Type*} [monoid M] [monoid N] [monoid P] [monoid Q] (f : M →* N) (g : N →* P) (h : P →* Q) : (h.comp g).comp f = h.comp (g.comp f) := rfl @[to_additive] lemma one_hom.cancel_right [has_one M] [has_one N] [has_one P] {g₁ g₂ : one_hom N P} {f : one_hom M N} (hf : function.surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, one_hom.ext $ (forall_iff_forall_surj hf).1 (one_hom.ext_iff.1 h), λ h, h ▸ rfl⟩ @[to_additive] lemma mul_hom.cancel_right [has_mul M] [has_mul N] [has_mul P] {g₁ g₂ : mul_hom N P} {f : mul_hom M N} (hf : function.surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, mul_hom.ext $ (forall_iff_forall_surj hf).1 (mul_hom.ext_iff.1 h), λ h, h ▸ rfl⟩ @[to_additive] lemma monoid_hom.cancel_right [monoid M] [monoid N] [monoid P] {g₁ g₂ : N →* P} {f : M →* N} (hf : function.surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, monoid_hom.ext $ (forall_iff_forall_surj hf).1 (monoid_hom.ext_iff.1 h), λ h, h ▸ rfl⟩ @[to_additive] lemma one_hom.cancel_left [has_one M] [has_one N] [has_one P] {g : one_hom N P} {f₁ f₂ : one_hom M N} (hg : function.injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, one_hom.ext $ λ x, hg $ by rw [← one_hom.comp_apply, h, one_hom.comp_apply], λ h, h ▸ rfl⟩ @[to_additive] lemma mul_hom.cancel_left [has_one M] [has_one N] [has_one P] {g : one_hom N P} {f₁ f₂ : one_hom M N} (hg : function.injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, one_hom.ext $ λ x, hg $ by rw [← one_hom.comp_apply, h, one_hom.comp_apply], λ h, h ▸ rfl⟩ @[to_additive] lemma monoid_hom.cancel_left [monoid M] [monoid N] [monoid P] {g : N →* P} {f₁ f₂ : M →* N} (hg : function.injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, monoid_hom.ext $ λ x, hg $ by rw [← monoid_hom.comp_apply, h, monoid_hom.comp_apply], λ h, h ▸ rfl⟩ @[simp, to_additive] lemma one_hom.comp_id [has_one M] [has_one N] (f : one_hom M N) : f.comp (one_hom.id M) = f := one_hom.ext $ λ x, rfl @[simp, to_additive] lemma mul_hom.comp_id [has_mul M] [has_mul N] (f : mul_hom M N) : f.comp (mul_hom.id M) = f := mul_hom.ext $ λ x, rfl @[simp, to_additive] lemma monoid_hom.comp_id [monoid M] [monoid N] (f : M →* N) : f.comp (monoid_hom.id M) = f := monoid_hom.ext $ λ x, rfl @[simp, to_additive] lemma one_hom.id_comp [has_one M] [has_one N] (f : one_hom M N) : (one_hom.id N).comp f = f := one_hom.ext $ λ x, rfl @[simp, to_additive] lemma mul_hom.id_comp [has_mul M] [has_mul N] (f : mul_hom M N) : (mul_hom.id N).comp f = f := mul_hom.ext $ λ x, rfl @[simp, to_additive] lemma monoid_hom.id_comp [monoid M] [monoid N] (f : M →* N) : (monoid_hom.id N).comp f = f := monoid_hom.ext $ λ x, rfl section End namespace monoid variables (M) [monoid M] /-- The monoid of endomorphisms. -/ protected def End := M →* M namespace End instance : monoid (monoid.End M) := { mul := monoid_hom.comp, one := monoid_hom.id M, mul_assoc := λ _ _ _, monoid_hom.comp_assoc _ _ _, mul_one := monoid_hom.comp_id, one_mul := monoid_hom.id_comp } instance : inhabited (monoid.End M) := ⟨1⟩ instance : has_coe_to_fun (monoid.End M) := ⟨_, monoid_hom.to_fun⟩ end End @[simp] lemma coe_one : ((1 : monoid.End M) : M → M) = id := rfl @[simp] lemma coe_mul (f g) : ((f * g : monoid.End M) : M → M) = f ∘ g := rfl end monoid namespace add_monoid variables (A : Type*) [add_monoid A] /-- The monoid of endomorphisms. -/ protected def End := A →+ A namespace End instance : monoid (add_monoid.End A) := { mul := add_monoid_hom.comp, one := add_monoid_hom.id A, mul_assoc := λ _ _ _, add_monoid_hom.comp_assoc _ _ _, mul_one := add_monoid_hom.comp_id, one_mul := add_monoid_hom.id_comp } instance : inhabited (add_monoid.End A) := ⟨1⟩ instance : has_coe_to_fun (add_monoid.End A) := ⟨_, add_monoid_hom.to_fun⟩ end End @[simp] lemma coe_one : ((1 : add_monoid.End A) : A → A) = id := rfl @[simp] lemma coe_mul (f g) : ((f * g : add_monoid.End A) : A → A) = f ∘ g := rfl end add_monoid end End /-- `1` is the homomorphism sending all elements to `1`. -/ @[to_additive] instance [has_one M] [has_one N] : has_one (one_hom M N) := ⟨⟨λ _, 1, rfl⟩⟩ /-- `1` is the multiplicative homomorphism sending all elements to `1`. -/ @[to_additive] instance [has_mul M] [monoid N] : has_one (mul_hom M N) := ⟨⟨λ _, 1, λ _ _, (one_mul 1).symm⟩⟩ /-- `1` is the monoid homomorphism sending all elements to `1`. -/ @[to_additive] instance [monoid M] [monoid N] : has_one (M →* N) := ⟨⟨λ _, 1, rfl, λ _ _, (one_mul 1).symm⟩⟩ /-- `0` is the homomorphism sending all elements to `0`. -/ add_decl_doc zero_hom.has_zero /-- `0` is the additive homomorphism sending all elements to `0`. -/ add_decl_doc add_hom.has_zero /-- `0` is the additive monoid homomorphism sending all elements to `0`. -/ add_decl_doc add_monoid_hom.has_zero @[simp, to_additive] lemma one_hom.one_apply [has_one M] [has_one N] (x : M) : (1 : one_hom M N) x = 1 := rfl @[simp, to_additive] lemma monoid_hom.one_apply [monoid M] [monoid N] (x : M) : (1 : M →* N) x = 1 := rfl @[to_additive] instance [has_one M] [has_one N] : inhabited (one_hom M N) := ⟨1⟩ @[to_additive] instance [has_mul M] [monoid N] : inhabited (mul_hom M N) := ⟨1⟩ @[to_additive] instance [monoid M] [monoid N] : inhabited (M →* N) := ⟨1⟩ namespace monoid_hom variables [mM : monoid M] [mN : monoid N] [mP : monoid P] variables [group G] [comm_group H] /-- Given two monoid morphisms `f`, `g` to a commutative monoid, `f * g` is the monoid morphism sending `x` to `f x * g x`. -/ @[to_additive] instance {M N} {mM : monoid M} [comm_monoid N] : has_mul (M →* N) := ⟨λ f g, { to_fun := λ m, f m * g m, map_one' := show f 1 * g 1 = 1, by simp, map_mul' := begin intros, show f (x * y) * g (x * y) = f x * g x * (f y * g y), rw [f.map_mul, g.map_mul, ←mul_assoc, ←mul_assoc, mul_right_comm (f x)], end }⟩ /-- Given two additive monoid morphisms `f`, `g` to an additive commutative monoid, `f + g` is the additive monoid morphism sending `x` to `f x + g x`. -/ add_decl_doc add_monoid_hom.has_add @[simp, to_additive] lemma mul_apply {M N} {mM : monoid M} {mN : comm_monoid N} (f g : M →* N) (x : M) : (f * g) x = f x * g x := rfl /-- (M →* N) is a comm_monoid if N is commutative. -/ @[to_additive] instance {M N} [monoid M] [comm_monoid N] : comm_monoid (M →* N) := { mul := (*), mul_assoc := by intros; ext; apply mul_assoc, one := 1, one_mul := by intros; ext; apply one_mul, mul_one := by intros; ext; apply mul_one, mul_comm := by intros; ext; apply mul_comm } /-- `flip` arguments of `f : M →* N →* P` -/ @[to_additive "`flip` arguments of `f : M →+ N →+ P`"] def flip {mM : monoid M} {mN : monoid N} {mP : comm_monoid P} (f : M →* N →* P) : N →* M →* P := { to_fun := λ y, ⟨λ x, f x y, by rw [f.map_one, one_apply], λ x₁ x₂, by rw [f.map_mul, mul_apply]⟩, map_one' := ext $ λ x, (f x).map_one, map_mul' := λ y₁ y₂, ext $ λ x, (f x).map_mul y₁ y₂ } @[simp, to_additive] lemma flip_apply {mM : monoid M} {mN : monoid N} {mP : comm_monoid P} (f : M →* N →* P) (x : M) (y : N) : f.flip y x = f x y := rfl /-- Evaluation of a `monoid_hom` at a point as a monoid homomorphism. See also `monoid_hom.apply` for the evaluation of any function at a point. -/ @[to_additive "Evaluation of an `add_monoid_hom` at a point as an additive monoid homomorphism. See also `add_monoid_hom.apply` for the evaluation of any function at a point."] def eval [monoid M] [comm_monoid N] : M →* (M →* N) →* N := (monoid_hom.id (M →* N)).flip @[simp, to_additive] lemma eval_apply [monoid M] [comm_monoid N] (x : M) (f : M →* N) : eval x f = f x := rfl /-- If two homomorphism from a group to a monoid are equal at `x`, then they are equal at `x⁻¹`. -/ @[to_additive "If two homomorphism from an additive group to an additive monoid are equal at `x`, then they are equal at `-x`." ] lemma eq_on_inv {G} [group G] [monoid M] {f g : G →* M} {x : G} (h : f x = g x) : f x⁻¹ = g x⁻¹ := left_inv_eq_right_inv (f.map_mul_eq_one $ inv_mul_self x) $ h.symm ▸ g.map_mul_eq_one $ mul_inv_self x /-- Group homomorphisms preserve inverse. -/ @[simp, to_additive] theorem map_inv {G H} [group G] [group H] (f : G →* H) (g : G) : f g⁻¹ = (f g)⁻¹ := eq_inv_of_mul_eq_one $ f.map_mul_eq_one $ inv_mul_self g /-- Group homomorphisms preserve division. -/ @[simp, to_additive] theorem map_mul_inv {G H} [group G] [group H] (f : G →* H) (g h : G) : f (g * h⁻¹) = (f g) * (f h)⁻¹ := by rw [f.map_mul, f.map_inv] /-- A homomorphism from a group to a monoid is injective iff its kernel is trivial. -/ @[to_additive] lemma injective_iff {G H} [group G] [monoid H] (f : G →* H) : function.injective f ↔ (∀ a, f a = 1 → a = 1) := ⟨λ h x hfx, h $ hfx.trans f.map_one.symm, λ h x y hxy, mul_inv_eq_one.1 $ h _ $ by rw [f.map_mul, hxy, ← f.map_mul, mul_inv_self, f.map_one]⟩ include mM /-- Makes a group homomomorphism from a proof that the map preserves multiplication. -/ @[to_additive] def mk' (f : M → G) (map_mul : ∀ a b : M, f (a * b) = f a * f b) : M →* G := { to_fun := f, map_mul' := map_mul, map_one' := mul_self_iff_eq_one.1 $ by rw [←map_mul, mul_one] } /-- Makes an additive group homomomorphism from a proof that the map preserves multiplication. -/ add_decl_doc add_monoid_hom.mk' @[simp, to_additive] lemma coe_mk' {f : M → G} (map_mul : ∀ a b : M, f (a * b) = f a * f b) : ⇑(mk' f map_mul) = f := rfl omit mM /-- Makes a group homomorphism from a proof that the map preserves right division `λ x y, x * y⁻¹`. -/ @[to_additive "Makes an additive group homomorphism from a proof that the map preserves the operation `λ a b, a + -b`. See also `add_monoid_hom.of_map_sub` for a version using `λ a b, a - b`."] def of_map_mul_inv {H : Type*} [group H] (f : G → H) (map_div : ∀ a b : G, f (a * b⁻¹) = f a * (f b)⁻¹) : G →* H := mk' f $ λ x y, calc f (x * y) = f x * (f $ 1 * 1⁻¹ * y⁻¹)⁻¹ : by simp only [one_mul, one_inv, ← map_div, inv_inv] ... = f x * f y : by { simp only [map_div], simp only [mul_right_inv, one_mul, inv_inv] } @[simp, to_additive] lemma coe_of_map_mul_inv {H : Type*} [group H] (f : G → H) (map_div : ∀ a b : G, f (a * b⁻¹) = f a * (f b)⁻¹) : ⇑(of_map_mul_inv f map_div) = f := rfl /-- If `f` is a monoid homomorphism to a commutative group, then `f⁻¹` is the homomorphism sending `x` to `(f x)⁻¹`. -/ @[to_additive] instance {M G} [monoid M] [comm_group G] : has_inv (M →* G) := ⟨λ f, mk' (λ g, (f g)⁻¹) $ λ a b, by rw [←mul_inv, f.map_mul]⟩ /-- If `f` is an additive monoid homomorphism to an additive commutative group, then `-f` is the homomorphism sending `x` to `-(f x)`. -/ add_decl_doc add_monoid_hom.has_neg @[simp, to_additive] lemma inv_apply {M G} {mM : monoid M} {gG : comm_group G} (f : M →* G) (x : M) : f⁻¹ x = (f x)⁻¹ := rfl /-- If `G` is a commutative group, then `M →* G` a commutative group too. -/ @[to_additive] instance {M G} [monoid M] [comm_group G] : comm_group (M →* G) := { inv := has_inv.inv, mul_left_inv := by intros; ext; apply mul_left_inv, ..monoid_hom.comm_monoid } /-- If `G` is an additive commutative group, then `M →+ G` an additive commutative group too. -/ add_decl_doc add_monoid_hom.add_comm_group end monoid_hom namespace add_monoid_hom variables [add_group G] [add_group H] /-- Additive group homomorphisms preserve subtraction. -/ @[simp] theorem map_sub (f : G →+ H) (g h : G) : f (g - h) = (f g) - (f h) := f.map_add_neg g h /-- Define a morphism of additive groups given a map which respects difference. -/ def of_map_sub (f : G → H) (hf : ∀ x y, f (x - y) = f x - f y) : G →+ H := of_map_add_neg f hf @[simp] lemma coe_of_map_sub (f : G → H) (hf : ∀ x y, f (x - y) = f x - f y) : ⇑(of_map_sub f hf) = f := rfl end add_monoid_hom section commute variables [monoid M] [monoid N] {a x y : M} @[simp, to_additive] protected lemma semiconj_by.map (h : semiconj_by a x y) (f : M →* N) : semiconj_by (f a) (f x) (f y) := by simpa only [semiconj_by, f.map_mul] using congr_arg f h @[simp, to_additive] protected lemma commute.map (h : commute x y) (f : M →* N) : commute (f x) (f y) := h.map f end commute
7af35dba4f0ec56905026141a74d08afeba27e35
75c54c8946bb4203e0aaf196f918424a17b0de99
/old/zfc_consistent.lean
bd0d8113a86cf10088c47477d1be564cea8f0432
[ "Apache-2.0" ]
permissive
urkud/flypitch
261e2a45f1038130178575406df8aea78255ba77
2250f5eda14b6ef9fc3e4e1f4a9ac4005634de5c
refs/heads/master
1,653,266,469,246
1,577,819,679,000
1,577,819,679,000
259,862,235
1
0
Apache-2.0
1,588,147,244,000
1,588,147,244,000
null
UTF-8
Lean
false
false
7,315
lean
/- Copyright (c) 2019 The Flypitch Project. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jesse Han, Floris van Doorn -/ import .zfc open fol open zfc local infix `∈'`:100 := bounded_formula_of_relation ZFC_el local notation h :: t := dvector.cons h t local notation `[` l:(foldr `, ` (h t, dvector.cons h t) dvector.nil `]`:0) := l def L_ZFC_structure_of_Set : Structure L_ZFC := begin refine ⟨Set,_,_⟩, {intros n f, repeat{cases f}}, {intros n r v, cases r, cases v, cases v_xs, exact v_x ∈ v_xs_x} end local notation `Set'` := L_ZFC_structure_of_Set instance has_mem_Set'_Set' : (has_mem Set' Set') := ⟨Set.mem⟩ instance has_mem_Set_Set' : has_mem Set.{0} Set' := ⟨Set.mem⟩ instance has_emptyc_Set' : has_emptyc Set' := ⟨Set.empty⟩ lemma empty_subset : ∀ x: Set', Set.empty ⊆ x := by tidy lemma Set'_Set : ↥Set' = Set := by refl @[simp]lemma Set'_Set_2 {p : (by exact ↥Set') → Prop} : (λ x, p x) = λ x : Set, p x := by refl lemma Set'_has_mem : has_mem ↥Set' ↥Set' := ⟨ Set.mem ⟩ local notation h :: t := dvector.cons h t local notation `[` l:(foldr `, ` (h t, dvector.cons h t) dvector.nil `]`) := l example : Set' ⊨ (∃' is_emptyset) := begin unfold is_emptyset, simp[realize_sentence_ex], refine ⟨∅, _⟩, tidy end @[simp]lemma Set'_rel_mem {x y : Set} : (Structure.rel_map Set' ZFC_rel.ϵ ( [x,y] ) ) = (x ∈ y) := by tidy @[simp] lemma Set'_mem_mem {n : ℕ} {x y : bounded_term L_ZFC n} {v : dvector ↥Set' n} : realize_bounded_formula v (x ∈' y) dvector.nil = ((realize_bounded_term v x dvector.nil) ∈ (realize_bounded_term v y dvector.nil)) := begin simp [ZFC_el, bounded_formula_of_relation, realize_bounded_formula, bd_apps_rel] end @[simp] lemma realize_term_remove_irrel {n : ℕ} {L : Language} {S : Structure L} {v : dvector ↥S (n+1)} {j : fin n} {k : ℕ} {p : k > j} : realize_bounded_term v ((lift_bounded_term_at (bd_var j : bounded_term L n) 1 k) ) dvector.nil = realize_bounded_term (dvector.remove_mth k v) (bd_var j) dvector.nil := begin sorry end set_option trace.check true @[simp]lemma Set'_realize_subset_2 : ∀ x y : Set, @realize_bounded_formula L_ZFC Set' 2 0 (x :: y :: dvector.nil) subset dvector.nil = Set.subset x y:= begin simp only [subset, Set'_mem_mem, fol.realize_bounded_formula, fol.realize_bounded_term, dvector.nth], intros, conv {to_lhs, change ∀ z, z ∈ x → z ∈ y}, rw [Set.subset] end set_option trace.app_builder true @[simp]lemma Set'_realize_is_empty : ∀ x, (@realize_bounded_formula L_ZFC Set' _ _ ([x]) is_emptyset dvector.nil ↔ x = ∅) := begin intro x, unfold is_emptyset, simp only [not_exists, fol.realize_bounded_formula_ex, Set'_mem_mem, fol.realize_bounded_formula, fol.realize_bounded_formula_not, fol.realize_bounded_term], symmetry, apply Set.eq_empty end @[simp]lemma Set'_realize_empty : @realize_bounded_formula L_ZFC Set' 1 0 (Set.empty :: dvector.nil) is_emptyset dvector.nil := by rw[Set'_realize_is_empty]; refl -- set_option trace.simplify.rewrite true lemma Set'_models_extensionality : axiom_of_extensionality ∈ Th Set' := begin simp [Th, axiom_of_extensionality, fin.val, has_one.one, fin.of_nat], intros x y, intro h, apply Set.ext, intro z, revert h, intro h, have := h z, exact this end lemma Set'_models_union : axiom_of_union ∈ Th Set' := begin simp only [Th, axiom_of_union, small], intro x, conv {congr, skip, congr, congr, congr, skip, change (∃' (&1 ∈' &0 ⊓ &0 ∈' &3) : bounded_formula L_ZFC 3)}, simp, change ∃ U, ∀ z, z ∈ U ↔ ∃ w, z ∈ w ∧ w ∈ x, refine ⟨⋃ x, _⟩, intro z, rw[@Set.mem_Union x z], finish end lemma Set'_models_powerset : axiom_of_powerset ∈ Th Set' := begin simp only [Th, axiom_of_powerset, small, fol.realize_bounded_formula_ex, fol.realize_bounded_formula, realize_bounded_formula_biimp, set.mem_set_of_eq], intros, refine ⟨Set.powerset x, _⟩, intro y, change y ∈ Set.powerset x ↔ Set.subset y x, exact Set.mem_powerset, end lemma Set'_models_choice : axiom_of_choice ∈ Th Set' := sorry lemma Set'_models_infinity : axiom_of_infinity ∈ Th Set' := begin simp [has_mem.mem, set.mem, Th, set_of, axiom_of_infinity,satisfied_in], refine ⟨Set.omega, _⟩, refine ⟨_,_⟩, refine ⟨Set.empty,_⟩, refine ⟨Set'_realize_empty, by {change Set.empty ∈ Set.omega, exact Set.omega_zero}⟩, intros, refine ⟨Set.insert x x, _⟩, refine ⟨_,@Set.omega_succ x a⟩, exact (iff.mpr Set.mem_insert (or.inl (refl x))) end lemma Set'_models_infinity' : axiom_of_infinity' ∈ Th Set' := begin simp [has_mem.mem, set.mem, Th, set_of, axiom_of_infinity' ,satisfied_in,realize_cast_bounded_formula], refine ⟨Set.omega, _⟩, intro x, refine ⟨_,_⟩, {intro H_x, change Set.mem x _, change _ ∈ Set.omega, suffices : x = Set.empty, by rw[this]; apply Set.omega_zero, exact H_x}, intro y, conv in (dvector.nth _ _ _) {change x}, conv in (dvector.nth _ _ _) {change y}, change Set.mem y Set.omega → _, intro H, exact ⟨Set.insert y y, ⟨iff.mpr Set.mem_insert (or.inl (by refl)), @Set.omega_succ y H⟩⟩ end lemma Set'_models_shallow_infinity : Set_axiom_of_infinity := begin unfold Set_axiom_of_infinity Set_is_emptyset, refine ⟨Set.omega, _⟩, split, {refine ⟨∅, ⟨_, Set.omega_zero⟩⟩, apply Set.mem_empty}, {intros z H, refine ⟨Set.insert z z, ⟨iff.mpr Set.mem_insert (or.inl (by refl)), @Set.omega_succ z H⟩⟩}, end lemma shallow_infinity_iff_shallow_infinity' : Set_axiom_of_infinity ↔ Set_axiom_of_infinity' := sorry lemma Set'_infinity_shallow_infinity : Set'[axiom_of_infinity] ↔ Set_axiom_of_infinity := sorry lemma Set'_infinity'_shallow_infinity' : Set'[axiom_of_infinity'] ↔ Set_axiom_of_infinity' := sorry example : axiom_of_infinity ∈ Th(Set') := Set'_infinity_shallow_infinity.mpr Set'_models_shallow_infinity example : axiom_of_infinity' ∈ Th(Set') := Set'_infinity'_shallow_infinity'.mpr $ shallow_infinity_iff_shallow_infinity'.mp Set'_models_shallow_infinity @[simp]lemma Set'_functional_rw : ∀ c : bounded_formula L_ZFC 2, @realize_bounded_formula L_ZFC Set' 0 0 dvector.nil (functional c) dvector.nil = ∀ x : Set, ∃ y : Set, ∀ w, @realize_bounded_formula L_ZFC Set' 3 0 ([w,y,x]) ( (c ↑' 1 # 1) ⇔ &0 ≃ &1) dvector.nil := begin intros c, ext1, simp at *, rw [functional, realize_bounded_formula], simp [realize_bounded_formula_ex], refl end lemma Set'_functional : ∀ c, @realize_bounded_formula L_ZFC Set' 0 0 dvector.nil (functional c) dvector.nil → Set → Set := begin intro c, rw[Set'_functional_rw], intros h s, sorry end lemma Set'_models_replacement: ∀ c : bounded_formula L_ZFC 2, axiom_of_replacement c ∈ Th Set' := begin intro c, simp only [has_mem.mem,set.mem,Th,set_of,axiom_of_replacement], intros a x, sorry end lemma Set_extends_ZFC : ZFC ⊆ Th Set' := begin intros f hf, cases hf with zf choice, repeat{cases zf}, exact Set'_models_infinity, exact Set'_models_powerset, exact Set'_models_union, exact Set'_models_extensionality, dsimp at zf_h, cases zf_h with a b, subst b, revert zf_w, simp, exact Set'_models_replacement, repeat{cases choice}, exact Set'_models_choice end
490298aa652a75f5791e79e15dcee98e8cb50cb6
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/polynomial/algebra_map.lean
bc0ea04ec0ae6ca42bcc925dce4ead122ba07c23
[ "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
11,497
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.eval import algebra.algebra.tower /-! # Theory of univariate polynomials We show that `polynomial A` is an R-algebra when `A` is an R-algebra. We promote `eval₂` to an algebra hom in `aeval`. -/ noncomputable theory open finset open_locale big_operators namespace polynomial universes u v w z variables {R : Type u} {S : Type v} {T : Type w} {A : Type z} {a b : R} {n : ℕ} section comm_semiring variables [comm_semiring R] {p q r : polynomial R} variables [semiring A] [algebra R A] /-- Note that this instance also provides `algebra R (polynomial R)`. -/ instance algebra_of_algebra : algebra R (polynomial A) := { smul_def' := λ r p, begin rcases p, simp only [C, monomial, monomial_fun, ring_hom.coe_mk, ring_hom.to_fun_eq_coe, function.comp_app, ring_hom.coe_comp, smul_to_finsupp, mul_to_finsupp], exact algebra.smul_def' _ _, end, commutes' := λ r p, begin rcases p, simp only [C, monomial, monomial_fun, ring_hom.coe_mk, ring_hom.to_fun_eq_coe, function.comp_app, ring_hom.coe_comp, mul_to_finsupp], convert algebra.commutes' r p, end, .. C.comp (algebra_map R A) } lemma algebra_map_apply (r : R) : algebra_map R (polynomial A) r = C (algebra_map R A r) := rfl /-- When we have `[comm_ring R]`, the function `C` is the same as `algebra_map R (polynomial R)`. (But note that `C` is defined when `R` is not necessarily commutative, in which case `algebra_map` is not available.) -/ lemma C_eq_algebra_map {R : Type*} [comm_semiring R] (r : R) : C r = algebra_map R (polynomial R) r := rfl variable (R) /-- Algebra isomorphism between `polynomial R` and `add_monoid_algebra R ℕ`. This is just an implementation detail, but it can be useful to transfer results from `finsupp` to polynomials. -/ @[simps] def to_finsupp_iso_alg : polynomial R ≃ₐ[R] add_monoid_algebra R ℕ := { commutes' := λ r, begin simp only [add_monoid_algebra.coe_algebra_map, algebra.id.map_eq_self, function.comp_app], rw [←C_eq_algebra_map, ←monomial_zero_left, ring_equiv.to_fun_eq_coe, to_finsupp_iso_monomial], end, ..to_finsupp_iso R } variable {R} instance [nontrivial A] : nontrivial (subalgebra R (polynomial A)) := ⟨⟨⊥, ⊤, begin rw [ne.def, set_like.ext_iff, not_forall], refine ⟨X, _⟩, simp only [algebra.mem_bot, not_exists, set.mem_range, iff_true, algebra.mem_top, algebra_map_apply, not_forall], intro x, rw [ext_iff, not_forall], refine ⟨1, _⟩, simp [coeff_C], end⟩⟩ @[simp] lemma alg_hom_eval₂_algebra_map {R A B : Type*} [comm_ring R] [ring A] [ring B] [algebra R A] [algebra R B] (p : polynomial R) (f : A →ₐ[R] B) (a : A) : f (eval₂ (algebra_map R A) a p) = eval₂ (algebra_map R B) (f a) p := begin dsimp [eval₂, sum], simp only [f.map_sum, f.map_mul, f.map_pow, ring_hom.eq_int_cast, ring_hom.map_int_cast, alg_hom.commutes], end @[simp] lemma eval₂_algebra_map_X {R A : Type*} [comm_ring R] [ring A] [algebra R A] (p : polynomial R) (f : polynomial R →ₐ[R] A) : eval₂ (algebra_map R A) (f X) p = f p := begin conv_rhs { rw [←polynomial.sum_C_mul_X_eq p], }, dsimp [eval₂, sum], simp only [f.map_sum, f.map_mul, f.map_pow, ring_hom.eq_int_cast, ring_hom.map_int_cast], simp [polynomial.C_eq_algebra_map], end @[simp] lemma ring_hom_eval₂_algebra_map_int {R S : Type*} [ring R] [ring S] (p : polynomial ℤ) (f : R →+* S) (r : R) : f (eval₂ (algebra_map ℤ R) r p) = eval₂ (algebra_map ℤ S) (f r) p := alg_hom_eval₂_algebra_map p f.to_int_alg_hom r @[simp] lemma eval₂_algebra_map_int_X {R : Type*} [ring R] (p : polynomial ℤ) (f : polynomial ℤ →+* R) : eval₂ (algebra_map ℤ R) (f X) p = f p := -- Unfortunately `f.to_int_alg_hom` doesn't work here, as typeclasses don't match up correctly. eval₂_algebra_map_X p { commutes' := λ n, by simp, .. f } end comm_semiring section aeval variables [comm_semiring R] {p q : polynomial R} variables [semiring A] [algebra R A] variables {B : Type*} [semiring B] [algebra R B] variables (x : A) /-- Given a valuation `x` of the variable in an `R`-algebra `A`, `aeval R A x` is the unique `R`-algebra homomorphism from `R[X]` to `A` sending `X` to `x`. -/ def aeval : polynomial R →ₐ[R] A := { commutes' := λ r, eval₂_C _ _, ..eval₂_ring_hom' (algebra_map R A) x (λ a, algebra.commutes _ _) } variables {R A} @[ext] lemma alg_hom_ext {f g : polynomial R →ₐ[R] A} (h : f X = g X) : f = g := begin ext p, rw [← sum_monomial_eq p], simp [sum, f.map_sum, g.map_sum, monomial_eq_smul_X, h], end theorem aeval_def (p : polynomial R) : aeval x p = eval₂ (algebra_map R A) x p := rfl @[simp] lemma aeval_zero : aeval x (0 : polynomial R) = 0 := alg_hom.map_zero (aeval x) @[simp] lemma aeval_X : aeval x (X : polynomial R) = x := eval₂_X _ x @[simp] lemma aeval_C (r : R) : aeval x (C r) = algebra_map R A r := eval₂_C _ x @[simp] lemma aeval_monomial {n : ℕ} {r : R} : aeval x (monomial n r) = (algebra_map _ _ r) * x^n := eval₂_monomial _ _ @[simp] lemma aeval_X_pow {n : ℕ} : aeval x ((X : polynomial R)^n) = x^n := eval₂_X_pow _ _ @[simp] lemma aeval_add : aeval x (p + q) = aeval x p + aeval x q := alg_hom.map_add _ _ _ @[simp] lemma aeval_one : aeval x (1 : polynomial R) = 1 := alg_hom.map_one _ @[simp] lemma aeval_bit0 : aeval x (bit0 p) = bit0 (aeval x p) := alg_hom.map_bit0 _ _ @[simp] lemma aeval_bit1 : aeval x (bit1 p) = bit1 (aeval x p) := alg_hom.map_bit1 _ _ @[simp] lemma aeval_nat_cast (n : ℕ) : aeval x (n : polynomial R) = n := alg_hom.map_nat_cast _ _ lemma aeval_mul : aeval x (p * q) = aeval x p * aeval x q := alg_hom.map_mul _ _ _ lemma aeval_comp {A : Type*} [comm_semiring A] [algebra R A] (x : A) : aeval x (p.comp q) = (aeval (aeval x q) p) := eval₂_comp (algebra_map R A) @[simp] lemma aeval_map {A : Type*} [comm_semiring A] [algebra R A] [algebra A B] [is_scalar_tower R A B] (b : B) (p : polynomial R) : aeval b (p.map (algebra_map R A)) = aeval b p := by rw [aeval_def, eval₂_map, ←is_scalar_tower.algebra_map_eq, ←aeval_def] theorem eval_unique (φ : polynomial R →ₐ[R] A) (p) : φ p = eval₂ (algebra_map R A) (φ X) p := begin apply polynomial.induction_on p, { intro r, rw eval₂_C, exact φ.commutes r }, { intros f g ih1 ih2, rw [φ.map_add, ih1, ih2, eval₂_add] }, { intros n r ih, rw [pow_succ', ← mul_assoc, φ.map_mul, eval₂_mul_noncomm (algebra_map R A) _ (λ k, algebra.commutes _ _), eval₂_X, ih] } end theorem aeval_alg_hom (f : A →ₐ[R] B) (x : A) : aeval (f x) = f.comp (aeval x) := alg_hom.ext $ λ p, by rw [eval_unique (f.comp (aeval x)), alg_hom.comp_apply, aeval_X, aeval_def] theorem aeval_alg_hom_apply (f : A →ₐ[R] B) (x : A) (p : polynomial R) : aeval (f x) p = f (aeval x p) := alg_hom.ext_iff.1 (aeval_alg_hom f x) p theorem aeval_alg_equiv (f : A ≃ₐ[R] B) (x : A) : aeval (f x) = (f : A →ₐ[R] B).comp (aeval x) := aeval_alg_hom (f : A →ₐ[R] B) x theorem aeval_alg_equiv_apply (f : A ≃ₐ[R] B) (x : A) (p : polynomial R) : aeval (f x) p = f (aeval x p) := aeval_alg_hom_apply (f : A →ₐ[R] B) x p lemma aeval_algebra_map_apply (x : R) (p : polynomial R) : aeval (algebra_map R A x) p = algebra_map R A (p.eval x) := aeval_alg_hom_apply (algebra.of_id R A) x p @[simp] lemma coe_aeval_eq_eval (r : R) : (aeval r : polynomial R → R) = eval r := rfl @[simp] lemma aeval_fn_apply {X : Type*} (g : polynomial R) (f : X → R) (x : X) : ((aeval f) g) x = aeval (f x) g := (aeval_alg_hom_apply (pi.eval_alg_hom _ _ x) f g).symm @[norm_cast] lemma aeval_subalgebra_coe (g : polynomial R) {A : Type*} [semiring A] [algebra R A] (s : subalgebra R A) (f : s) : (aeval f g : A) = aeval (f : A) g := (aeval_alg_hom_apply s.val f g).symm lemma coeff_zero_eq_aeval_zero (p : polynomial R) : p.coeff 0 = aeval 0 p := by simp [coeff_zero_eq_eval_zero] section comm_semiring variables [comm_semiring S] {f : R →+* S} lemma aeval_eq_sum_range [algebra R S] {p : polynomial R} (x : S) : aeval x p = ∑ i in finset.range (p.nat_degree + 1), p.coeff i • x ^ i := by { simp_rw algebra.smul_def, exact eval₂_eq_sum_range (algebra_map R S) x } lemma aeval_eq_sum_range' [algebra R S] {p : polynomial R} {n : ℕ} (hn : p.nat_degree < n) (x : S) : aeval x p = ∑ i in finset.range n, p.coeff i • x ^ i := by { simp_rw algebra.smul_def, exact eval₂_eq_sum_range' (algebra_map R S) hn x } lemma is_root_of_eval₂_map_eq_zero (hf : function.injective f) {r : R} : eval₂ f (f r) p = 0 → p.is_root r := begin intro h, apply hf, rw [←eval₂_hom, h, f.map_zero], end lemma is_root_of_aeval_algebra_map_eq_zero [algebra R S] {p : polynomial R} (inj : function.injective (algebra_map R S)) {r : R} (hr : aeval (algebra_map R S r) p = 0) : p.is_root r := is_root_of_eval₂_map_eq_zero inj hr end comm_semiring section comm_ring variables [comm_ring S] {f : R →+* S} lemma dvd_term_of_dvd_eval_of_dvd_terms {z p : S} {f : polynomial S} (i : ℕ) (dvd_eval : p ∣ f.eval z) (dvd_terms : ∀ (j ≠ i), p ∣ f.coeff j * z ^ j) : p ∣ f.coeff i * z ^ i := begin by_cases hf : f = 0, { simp [hf] }, by_cases hi : i ∈ f.support, { rw [eval, eval₂, sum] at dvd_eval, rw [←finset.insert_erase hi, finset.sum_insert (finset.not_mem_erase _ _)] at dvd_eval, refine (dvd_add_left _).mp dvd_eval, apply finset.dvd_sum, intros j hj, exact dvd_terms j (finset.ne_of_mem_erase hj) }, { convert dvd_zero p, rw not_mem_support_iff at hi, simp [hi] } end lemma dvd_term_of_is_root_of_dvd_terms {r p : S} {f : polynomial S} (i : ℕ) (hr : f.is_root r) (h : ∀ (j ≠ i), p ∣ f.coeff j * r ^ j) : p ∣ f.coeff i * r ^ i := dvd_term_of_dvd_eval_of_dvd_terms i (eq.symm hr ▸ dvd_zero p) h end comm_ring end aeval section ring variables [ring R] /-- The evaluation map is not generally multiplicative when the coefficient ring is noncommutative, but nevertheless any polynomial of the form `p * (X - monomial 0 r)` is sent to zero when evaluated at `r`. This is the key step in our proof of the Cayley-Hamilton theorem. -/ lemma eval_mul_X_sub_C {p : polynomial R} (r : R) : (p * (X - C r)).eval r = 0 := begin simp only [eval, eval₂, ring_hom.id_apply], have bound := calc (p * (X - C r)).nat_degree ≤ p.nat_degree + (X - C r).nat_degree : nat_degree_mul_le ... ≤ p.nat_degree + 1 : add_le_add_left nat_degree_X_sub_C_le _ ... < p.nat_degree + 2 : lt_add_one _, rw sum_over_range' _ _ (p.nat_degree + 2) bound, swap, { simp, }, rw sum_range_succ', conv_lhs { congr, apply_congr, skip, rw [coeff_mul_X_sub_C, sub_mul, mul_assoc, ←pow_succ], }, simp [sum_range_sub', coeff_monomial], end theorem not_is_unit_X_sub_C [nontrivial R] {r : R} : ¬ is_unit (X - C r) := λ ⟨⟨_, g, hfg, hgf⟩, rfl⟩, @zero_ne_one R _ _ $ by erw [← eval_mul_X_sub_C, hgf, eval_one] end ring lemma aeval_endomorphism {M : Type*} [comm_ring R] [add_comm_group M] [module R M] (f : M →ₗ[R] M) (v : M) (p : polynomial R) : aeval f p v = p.sum (λ n b, b • (f ^ n) v) := begin rw [aeval_def, eval₂], exact (finset.sum_hom p.support (λ h : M →ₗ[R] M, h v)).symm end end polynomial
b7a1c65b8bc9801aef563aa36c4543168e463529
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/control/alternative_auto.lean
4cf17d6ed0faafd0ca575767d37cfa6d9bba4b95
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,406
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 -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.logic import Mathlib.Lean3Lib.init.control.applicative universes u v l namespace Mathlib class has_orelse (f : Type u → Type v) where orelse : {α : Type u} → f α → f α → f α infixr:2 " <|> " => Mathlib.has_orelse.orelse class alternative (f : Type u → Type v) extends has_orelse f, Applicative f where failure : {α : Type u} → f α def failure {f : Type u → Type v} [alternative f] {α : Type u} : f α := alternative.failure /-- If the condition `p` is decided to be false, then fail, otherwise, return unit. -/ def guard {f : Type → Type v} [alternative f] (p : Prop) [Decidable p] : f Unit := ite p (pure Unit.unit) failure def assert {f : Type → Type v} [alternative f] (p : Prop) [Decidable p] : f (Inhabited p) := dite p (fun (h : p) => pure { default := h }) fun (h : ¬p) => failure /- Later we define a coercion from bool to Prop, but this version will still be useful. Given (t : tactic bool), we can write t >>= guardb -/ def guardb {f : Type → Type v} [alternative f] : Bool → f Unit := sorry def optional {f : Type u → Type v} [alternative f] {α : Type u} (x : f α) : f (Option α) := some <$> x <|> pure none end Mathlib
4564376cdbea42474853ac551057caf40ddd863d
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/int/range.lean
e0b60dd231060602d588f9828a228de776f13851
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
2,062
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kenny Lau -/ import data.list.range import data.int.order.basic /-! # Intervals in ℤ This file defines integer ranges. `range m n` is the set of integers greater than `m` and strictly less than `n`. ## Note This could be unified with `data.list.intervals`. See the TODOs there. -/ namespace int local attribute [semireducible] int.nonneg /-- List enumerating `[m, n)`. This is the ℤ variant of `list.Ico`. -/ def range (m n : ℤ) : list ℤ := (list.range (to_nat (n-m))).map $ λ r, m+r theorem mem_range_iff {m n r : ℤ} : r ∈ range m n ↔ m ≤ r ∧ r < n := ⟨λ H, let ⟨s, h1, h2⟩ := list.mem_map.1 H in h2 ▸ ⟨le_add_of_nonneg_right trivial, add_lt_of_lt_sub_left $ match n-m, h1 with | (k:ℕ), h1 := by rwa [list.mem_range, to_nat_coe_nat, ← coe_nat_lt] at h1 end⟩, λ ⟨h1, h2⟩, list.mem_map.2 ⟨to_nat (r-m), list.mem_range.2 $ by rw [← coe_nat_lt, to_nat_of_nonneg (sub_nonneg_of_le h1), to_nat_of_nonneg (sub_nonneg_of_le (le_of_lt (lt_of_le_of_lt h1 h2)))]; exact sub_lt_sub_right h2 _, show m + _ = _, by rw [to_nat_of_nonneg (sub_nonneg_of_le h1), add_sub_cancel'_right]⟩⟩ instance decidable_le_lt (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m ≤ r → r < n → P r) := decidable_of_iff (∀ r ∈ range m n, P r) $ by simp only [mem_range_iff, and_imp] instance decidable_le_le (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m ≤ r → r ≤ n → P r) := decidable_of_iff (∀ r ∈ range m (n+1), P r) $ by simp only [mem_range_iff, and_imp, lt_add_one_iff] instance decidable_lt_lt (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m < r → r < n → P r) := int.decidable_le_lt P _ _ instance decidable_lt_le (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m < r → r ≤ n → P r) := int.decidable_le_le P _ _ end int
6b4da3f4cf736cffda74a3b0a564dda50b5af7e3
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Widget/UserWidget.lean
d2d07fbf804344e85fd2dd5cfd37865f0f9ef945
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
6,799
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: E.W.Ayers -/ import Lean.Elab.Eval import Lean.Server.Rpc.RequestHandling open Lean namespace Lean.Widget /-- A custom piece of code that is run on the editor client. The editor can use the `Lean.Widget.getWidgetSource` RPC method to get this object. See the [manual entry](doc/widgets.md) above this declaration for more information on how to use the widgets system. -/ structure WidgetSource where /-- Sourcetext of the code to run.-/ sourcetext : String deriving Inhabited, ToJson, FromJson /-- Use this structure and the `@[widget]` attribute to define your own widgets. ```lean @[widget] def rubiks : UserWidgetDefinition := { name := "Rubiks cube app" javascript := include_str ... } ``` -/ structure UserWidgetDefinition where /-- Pretty name of user widget to display to the user. -/ name : String /-- An ESmodule that exports a react component to render. -/ javascript: String deriving Inhabited, ToJson, FromJson structure UserWidget where id : Name /-- Pretty name of widget to display to the user.-/ name : String javascriptHash: UInt64 deriving Inhabited, ToJson, FromJson private abbrev WidgetSourceRegistry := SimplePersistentEnvExtension (UInt64 × Name) (RBMap UInt64 Name compare) -- Mapping widgetSourceId to hash of sourcetext builtin_initialize userWidgetRegistry : MapDeclarationExtension UserWidget ← mkMapDeclarationExtension `widgetRegistry builtin_initialize widgetSourceRegistry : WidgetSourceRegistry ← registerSimplePersistentEnvExtension { name := `widgetSourceRegistry addImportedFn := fun xss => xss.foldl (Array.foldl (fun s n => s.insert n.1 n.2)) ∅ addEntryFn := fun s n => s.insert n.1 n.2 toArrayFn := fun es => es.toArray } private unsafe def getUserWidgetDefinitionUnsafe (decl : Name) : CoreM UserWidgetDefinition := evalConstCheck UserWidgetDefinition ``UserWidgetDefinition decl @[implementedBy getUserWidgetDefinitionUnsafe] private opaque getUserWidgetDefinition (decl : Name) : CoreM UserWidgetDefinition private def attributeImpl : AttributeImpl where name := `widget descr := "Mark a string as static code that can be loaded by a widget handler." applicationTime := AttributeApplicationTime.afterCompilation add decl _stx _kind := do let env ← getEnv let defn ← getUserWidgetDefinition decl let javascriptHash := hash defn.javascript let env := userWidgetRegistry.insert env decl {id := decl, name := defn.name, javascriptHash} let env := widgetSourceRegistry.addEntry env (javascriptHash, decl) setEnv <| env builtin_initialize registerBuiltinAttribute attributeImpl /-- Input for `getWidgetSource` RPC. -/ structure GetWidgetSourceParams where /-- The hash of the sourcetext to retrieve. -/ hash: UInt64 pos : Lean.Lsp.Position deriving ToJson, FromJson open Server RequestM in @[serverRpcMethod] def getWidgetSource (args : GetWidgetSourceParams) : RequestM (RequestTask WidgetSource) := do let doc ← readDoc let pos := doc.meta.text.lspPosToUtf8Pos args.pos let notFound := throwThe RequestError ⟨.invalidParams, s!"No registered user-widget with hash {args.hash}"⟩ withWaitFindSnap doc (notFoundX := notFound) (fun s => s.endPos >= pos || (widgetSourceRegistry.getState s.env).contains args.hash) fun snap => do if let some id := widgetSourceRegistry.getState snap.env |>.find? args.hash then runCoreM snap do return {sourcetext := (← getUserWidgetDefinition id).javascript} else notFound open Lean Elab /-- Try to retrieve the `UserWidgetInfo` at a particular position. -/ def widgetInfosAt? (text : FileMap) (t : InfoTree) (hoverPos : String.Pos) : List UserWidgetInfo := t.deepestNodes fun | _ctx, i@(Info.ofUserWidgetInfo wi), _cs => do if let (some pos, some tailPos) := (i.pos?, i.tailPos?) then let trailSize := i.stx.getTrailingSize -- show info at EOF even if strictly outside token + trail let atEOF := tailPos.byteIdx + trailSize == text.source.endPos.byteIdx guard <| pos ≤ hoverPos ∧ (hoverPos.byteIdx < tailPos.byteIdx + trailSize || atEOF) return wi else failure | _, _, _ => none /-- UserWidget accompanied by component props. -/ structure UserWidgetInstance extends UserWidget where /-- Arguments to be fed to the widget's main component. -/ props : Json /-- The location of the widget instance in the Lean file. -/ range? : Option Lsp.Range deriving ToJson, FromJson /-- Output of `getWidgets` RPC.-/ structure GetWidgetsResponse where widgets : Array UserWidgetInstance deriving ToJson, FromJson open Lean Server RequestM in /-- Get the `UserWidget`s present at a particular position. -/ @[serverRpcMethod] def getWidgets (args : Lean.Lsp.Position) : RequestM (RequestTask (GetWidgetsResponse)) := do let doc ← readDoc let filemap := doc.meta.text let pos := filemap.lspPosToUtf8Pos args withWaitFindSnap doc (·.endPos >= pos) (notFoundX := return ⟨∅⟩) fun snap => do let env := snap.env let ws := widgetInfosAt? filemap snap.infoTree pos let ws ← ws.toArray.mapM (fun (w : UserWidgetInfo) => do let some widget := userWidgetRegistry.find? env w.widgetId | throw <| RequestError.mk .invalidParams s!"No registered user-widget with id {w.widgetId}" return { widget with props := w.props range? := String.Range.toLspRange filemap <$> Syntax.getRange? w.stx }) return {widgets := ws} /-- Save a user-widget instance to the infotree. The given `widgetId` should be the declaration name of the widget definition. -/ def saveWidgetInfo [Monad m] [MonadEnv m] [MonadError m] [MonadInfoTree m] (widgetId : Name) (props : Json) (stx : Syntax): m Unit := do let info := Info.ofUserWidgetInfo { widgetId := widgetId props := props stx := stx } pushInfoLeaf info /-! # Widget command -/ /-- Use `#widget <widgetname> <props>` to display a widget. Useful for debugging widgets. -/ syntax (name := widgetCmd) "#widget " ident term : command open Lean Lean.Meta Lean.Elab Lean.Elab.Term in private unsafe def evalJsonUnsafe (stx : Syntax) : TermElabM Json := Lean.Elab.Term.evalTerm Json (mkConst ``Json) stx @[implementedBy evalJsonUnsafe] private opaque evalJson (stx : Syntax) : TermElabM Json open Elab Command in @[commandElab widgetCmd] def elabWidgetCmd : CommandElab := fun | stx@`(#widget $id:ident $props) => do let props : Json ← runTermElabM fun _ => evalJson props saveWidgetInfo id.getId props stx | _ => throwUnsupportedSyntax end Lean.Widget
2dd19e71c60b6a29b58fa58ce85982f093df663b
82e44445c70db0f03e30d7be725775f122d72f3e
/src/category_theory/adjunction/lifting.lean
c821a9f9c2e2125dd34dbf01692eca1dc81456bf
[ "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
11,725
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.shapes.equalizers import category_theory.limits.shapes.reflexive import category_theory.adjunction import category_theory.monad.adjunction import category_theory.monad.coequalizer /-! # Adjoint lifting This file gives two constructions for building left adjoints: the adjoint triangle theorem and the adjoint lifting theorem. The adjoint triangle theorem says that given a functor `U : B ⥤ C` with a left adjoint `F` such that `ε_X : FUX ⟶ X` is a regular epi. Then for any category `A` with coequalizers of reflexive pairs, a functor `R : A ⥤ B` has a left adjoint if (and only if) the composite `R ⋙ U` does. Note that the condition on `U` regarding `ε_X` is automatically satisfied in the case when `U` is a monadic functor, giving the corollary: `monadic_adjoint_triangle_lift`, i.e. if `U` is monadic, `A` has reflexive coequalizers then `R : A ⥤ B` has a left adjoint provided `R ⋙ U` does. The adjoint lifting theorem says that given a commutative square of functors (up to isomorphism): Q A → B U ↓ ↓ V C → D R where `U` and `V` are monadic and `A` has reflexive coequalizers, then if `R` has a left adjoint then `Q` has a left adjoint. ## Implementation It is more convenient to prove this theorem by assuming we are given the explicit adjunction rather than just a functor known to be a right adjoint. In docstrings, we write `(η, ε)` for the unit and counit of the adjunction `adj₁ : F ⊣ U` and `(ι, δ)` for the unit and counit of the adjunction `adj₂ : F' ⊣ R ⋙ U`. ## TODO Dualise to lift right adjoints through comonads (by reversing 1-cells) and dualise to lift right adjoints through monads (by reversing 2-cells), and the combination. ## References * https://ncatlab.org/nlab/show/adjoint+triangle+theorem * https://ncatlab.org/nlab/show/adjoint+lifting+theorem * Adjoint Lifting Theorems for Categories of Algebras (PT Johnstone, 1975) * A unified approach to the lifting of adjoints (AJ Power, 1988) -/ namespace category_theory open category limits universes v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄ variables {A : Type u₁} {B : Type u₂} {C : Type u₃} variables [category.{v₁} A] [category.{v₂} B] [category.{v₃} C] -- Hide implementation details in this namespace namespace lift_adjoint variables {U : B ⥤ C} {F : C ⥤ B} (R : A ⥤ B) (F' : C ⥤ A) variables (adj₁ : F ⊣ U) (adj₂ : F' ⊣ R ⋙ U) /-- To show that `ε_X` is a coequalizer for `(FUε_X, ε_FUX)`, it suffices to assume it's always a coequalizer of something (i.e. a regular epi). -/ def counit_coequalises [∀ (X : B), regular_epi (adj₁.counit.app X)] (X : B) : is_colimit (cofork.of_π (adj₁.counit.app X) (adj₁.counit_naturality _)) := cofork.is_colimit.mk' _ $ λ s, begin refine ⟨(regular_epi.desc' (adj₁.counit.app X) s.π _).1, _, _⟩, { rw ← cancel_epi (adj₁.counit.app (regular_epi.W (adj₁.counit.app X))), rw ← adj₁.counit_naturality_assoc, dsimp only [functor.comp_obj], rw [← s.condition, ← F.map_comp_assoc, ← U.map_comp, regular_epi.w, U.map_comp, F.map_comp_assoc, s.condition, ← adj₁.counit_naturality_assoc] }, { apply (regular_epi.desc' (adj₁.counit.app X) s.π _).2 }, { intros m hm, rw ← cancel_epi (adj₁.counit.app X), apply hm.trans (regular_epi.desc' (adj₁.counit.app X) s.π _).2.symm } end include adj₁ adj₂ /-- (Implementation) To construct the left adjoint, we use the coequalizer of `F' U ε_Y` with the composite `F' U F U X ⟶ F' U F U R F U' X ⟶ F' U R F' U X ⟶ F' U X` where the first morphism is `F' U F ι_UX`, the second is `F' U ε_RF'UX`, and the third is `δ_F'UX`. We will show that this coequalizer exists and that it forms the object map for a left adjoint to `R`. -/ def other_map (X) : F'.obj (U.obj (F.obj (U.obj X))) ⟶ F'.obj (U.obj X) := F'.map (U.map (F.map (adj₂.unit.app _) ≫ adj₁.counit.app _)) ≫ adj₂.counit.app _ /-- `(F'Uε_X, other_map X)` is a reflexive pair: in particular if `A` has reflexive coequalizers then it has a coequalizer. -/ instance (X : B) : is_reflexive_pair (F'.map (U.map (adj₁.counit.app X))) (other_map _ _ adj₁ adj₂ X) := is_reflexive_pair.mk' (F'.map (adj₁.unit.app (U.obj X))) (by {rw [← F'.map_comp, adj₁.right_triangle_components], apply F'.map_id }) begin dsimp [other_map], rw [← F'.map_comp_assoc, U.map_comp, adj₁.unit_naturality_assoc, adj₁.right_triangle_components, comp_id, adj₂.left_triangle_components] end variables [has_reflexive_coequalizers A] /-- Construct the object part of the desired left adjoint as the coequalizer of `F'Uε_Y` with `other_map`. -/ noncomputable def construct_left_adjoint_obj (Y : B) : A := coequalizer (F'.map (U.map (adj₁.counit.app Y))) (other_map _ _ adj₁ adj₂ Y) /-- The homset equivalence which helps show that `R` is a right adjoint. -/ @[simps {rhs_md := semireducible}] noncomputable def construct_left_adjoint_equiv [∀ (X : B), regular_epi (adj₁.counit.app X)] (Y : A) (X : B) : (construct_left_adjoint_obj _ _ adj₁ adj₂ X ⟶ Y) ≃ (X ⟶ R.obj Y) := calc (construct_left_adjoint_obj _ _ adj₁ adj₂ X ⟶ Y) ≃ {f : F'.obj (U.obj X) ⟶ Y // F'.map (U.map (adj₁.counit.app X)) ≫ f = other_map _ _ adj₁ adj₂ _ ≫ f} : cofork.is_colimit.hom_iso (colimit.is_colimit _) _ ... ≃ {g : U.obj X ⟶ U.obj (R.obj Y) // U.map (F.map g ≫ adj₁.counit.app _) = U.map (adj₁.counit.app _) ≫ g} : begin apply (adj₂.hom_equiv _ _).subtype_equiv _, intro f, rw [← (adj₂.hom_equiv _ _).injective.eq_iff, eq_comm, adj₂.hom_equiv_naturality_left, other_map, assoc, adj₂.hom_equiv_naturality_left, ← adj₂.counit_naturality, adj₂.hom_equiv_naturality_left, adj₂.hom_equiv_unit, adj₂.right_triangle_components, comp_id, functor.comp_map, ← U.map_comp, assoc, ← adj₁.counit_naturality, adj₂.hom_equiv_unit, adj₂.hom_equiv_unit, F.map_comp, assoc], refl, end ... ≃ {z : F.obj (U.obj X) ⟶ R.obj Y // _} : begin apply (adj₁.hom_equiv _ _).symm.subtype_equiv, intro g, rw [← (adj₁.hom_equiv _ _).symm.injective.eq_iff, adj₁.hom_equiv_counit, adj₁.hom_equiv_counit, adj₁.hom_equiv_counit, F.map_comp, assoc, U.map_comp, F.map_comp, assoc, adj₁.counit_naturality, adj₁.counit_naturality_assoc], apply eq_comm, end ... ≃ (X ⟶ R.obj Y) : (cofork.is_colimit.hom_iso (counit_coequalises adj₁ X) _).symm /-- Construct the left adjoint to `R`, with object map `construct_left_adjoint_obj`. -/ noncomputable def construct_left_adjoint [∀ (X : B), regular_epi (adj₁.counit.app X)] : B ⥤ A := begin refine adjunction.left_adjoint_of_equiv (λ X Y, construct_left_adjoint_equiv R _ adj₁ adj₂ Y X) _, intros X Y Y' g h, rw [construct_left_adjoint_equiv_apply, construct_left_adjoint_equiv_apply, function.comp_app, function.comp_app, equiv.trans_apply, equiv.trans_apply, equiv.trans_apply, equiv.trans_apply, equiv.symm_apply_eq, subtype.ext_iff, cofork.is_colimit.hom_iso_natural, equiv.apply_symm_apply, equiv.subtype_equiv_apply, equiv.subtype_equiv_apply, equiv.subtype_equiv_apply, equiv.subtype_equiv_apply, subtype.coe_mk, subtype.coe_mk, subtype.coe_mk, subtype.coe_mk, ← adj₁.hom_equiv_naturality_right_symm, cofork.is_colimit.hom_iso_natural, adj₂.hom_equiv_naturality_right, functor.comp_map], end end lift_adjoint /-- The adjoint triangle theorem: Suppose `U : B ⥤ C` has a left adjoint `F` such that each counit `ε_X : FUX ⟶ X` is a regular epimorphism. Then if a category `A` has coequalizers of reflexive pairs, then a functor `R : A ⥤ B` has a left adjoint if the composite `R ⋙ U` does. Note the converse is true (with weaker assumptions), by `adjunction.comp`. See https://ncatlab.org/nlab/show/adjoint+triangle+theorem -/ noncomputable def adjoint_triangle_lift {U : B ⥤ C} {F : C ⥤ B} (R : A ⥤ B) (adj₁ : F ⊣ U) [Π (X : B), regular_epi (adj₁.counit.app X)] [has_reflexive_coequalizers A] [is_right_adjoint (R ⋙ U)] : is_right_adjoint R := { left := lift_adjoint.construct_left_adjoint R _ adj₁ (adjunction.of_right_adjoint _), adj := adjunction.adjunction_of_equiv_left _ _ } /-- If `R ⋙ U` has a left adjoint, the domain of `R` has reflexive coequalizers and `U` is a monadic functor, then `R` has a left adjoint. This is a special case of `adjoint_triangle_lift` which is often more useful in practice. -/ noncomputable def monadic_adjoint_triangle_lift (U : B ⥤ C) [monadic_right_adjoint U] {R : A ⥤ B} [has_reflexive_coequalizers A] [is_right_adjoint (R ⋙ U)] : is_right_adjoint R := begin let R' : A ⥤ _ := R ⋙ monad.comparison (adjunction.of_right_adjoint U), suffices : is_right_adjoint R', { let : is_right_adjoint (R' ⋙ (monad.comparison (adjunction.of_right_adjoint U)).inv), { resetI, apply_instance }, { let : R' ⋙ (monad.comparison (adjunction.of_right_adjoint U)).inv ≅ R := (iso_whisker_left R (monad.comparison _).as_equivalence.unit_iso.symm : _) ≪≫ R.right_unitor, exactI adjunction.right_adjoint_of_nat_iso this } }, let : is_right_adjoint (R' ⋙ monad.forget (adjunction.of_right_adjoint U).to_monad) := adjunction.right_adjoint_of_nat_iso (iso_whisker_left R (monad.comparison_forget (adjunction.of_right_adjoint U)).symm : _), letI : Π X, regular_epi ((monad.adj (adjunction.of_right_adjoint U).to_monad).counit.app X), { intro X, simp only [monad.adj_counit], exact ⟨_, _, _, _, monad.beck_algebra_coequalizer X⟩ }, exact adjoint_triangle_lift R' (monad.adj _), end variables {D : Type u₄} variables [category.{v₄} D] /-- Suppose we have a commutative square of functors Q A → B U ↓ ↓ V C → D R where `U` has a left adjoint, `A` has reflexive coequalizers and `V` has a left adjoint such that each component of the counit is a regular epi. Then `Q` has a left adjoint if `R` has a left adjoint. See https://ncatlab.org/nlab/show/adjoint+lifting+theorem -/ noncomputable def adjoint_square_lift (Q : A ⥤ B) (V : B ⥤ D) (U : A ⥤ C) (R : C ⥤ D) (comm : U ⋙ R ≅ Q ⋙ V) [is_right_adjoint U] [is_right_adjoint V] [is_right_adjoint R] [∀ X, regular_epi ((adjunction.of_right_adjoint V).counit.app X)] [has_reflexive_coequalizers A] : is_right_adjoint Q := begin let := adjunction.right_adjoint_of_nat_iso comm, exactI adjoint_triangle_lift Q (adjunction.of_right_adjoint V), end /-- Suppose we have a commutative square of functors Q A → B U ↓ ↓ V C → D R where `U` has a left adjoint, `A` has reflexive coequalizers and `V` is monadic. Then `Q` has a left adjoint if `R` has a left adjoint. See https://ncatlab.org/nlab/show/adjoint+lifting+theorem -/ noncomputable def monadic_adjoint_square_lift (Q : A ⥤ B) (V : B ⥤ D) (U : A ⥤ C) (R : C ⥤ D) (comm : U ⋙ R ≅ Q ⋙ V) [is_right_adjoint U] [monadic_right_adjoint V] [is_right_adjoint R] [has_reflexive_coequalizers A] : is_right_adjoint Q := begin let := adjunction.right_adjoint_of_nat_iso comm, exactI monadic_adjoint_triangle_lift V, end end category_theory
a7aec0d8fdd9fa1c0f3a341f49a63337f9032452
8eeb99d0fdf8125f5d39a0ce8631653f588ee817
/src/data/complex/basic.lean
f9395e4e5b64ac3b39917f6fbd2dfdb159dbc106
[ "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
20,437
lean
/- Copyright (c) 2017 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Mario Carneiro -/ import data.real.basic open_locale big_operators /-! # The complex numbers The complex numbers are modelled as ℝ^2 in the obvious way. -/ /-! ### Definition and basic arithmmetic -/ /-- Complex numbers consist of two `real`s: a real part `re` and an imaginary part `im`. -/ structure complex : Type := (re : ℝ) (im : ℝ) notation `ℂ` := complex namespace complex noncomputable instance : decidable_eq ℂ := classical.dec_eq _ /-- The equivalence between the complex numbers and `ℝ × ℝ`. -/ def equiv_real_prod : ℂ ≃ (ℝ × ℝ) := { to_fun := λ z, ⟨z.re, z.im⟩, inv_fun := λ p, ⟨p.1, p.2⟩, left_inv := λ ⟨x, y⟩, rfl, right_inv := λ ⟨x, y⟩, rfl } @[simp] theorem equiv_real_prod_apply (z : ℂ) : equiv_real_prod z = (z.re, z.im) := rfl theorem equiv_real_prod_symm_re (x y : ℝ) : (equiv_real_prod.symm (x, y)).re = x := rfl theorem equiv_real_prod_symm_im (x y : ℝ) : (equiv_real_prod.symm (x, y)).im = y := rfl @[simp] theorem eta : ∀ z : ℂ, complex.mk z.re z.im = z | ⟨a, b⟩ := rfl @[ext] theorem ext : ∀ {z w : ℂ}, z.re = w.re → z.im = w.im → z = w | ⟨zr, zi⟩ ⟨_, _⟩ rfl rfl := rfl theorem ext_iff {z w : ℂ} : z = w ↔ z.re = w.re ∧ z.im = w.im := ⟨λ H, by simp [H], and.rec ext⟩ instance : has_coe ℝ ℂ := ⟨λ r, ⟨r, 0⟩⟩ @[simp, norm_cast] lemma of_real_re (r : ℝ) : (r : ℂ).re = r := rfl @[simp, norm_cast] lemma of_real_im (r : ℝ) : (r : ℂ).im = 0 := rfl @[simp, norm_cast] theorem of_real_inj {z w : ℝ} : (z : ℂ) = w ↔ z = w := ⟨congr_arg re, congr_arg _⟩ instance : has_zero ℂ := ⟨(0 : ℝ)⟩ instance : inhabited ℂ := ⟨0⟩ @[simp] lemma zero_re : (0 : ℂ).re = 0 := rfl @[simp] lemma zero_im : (0 : ℂ).im = 0 := rfl @[simp, norm_cast] lemma of_real_zero : ((0 : ℝ) : ℂ) = 0 := rfl @[simp] theorem of_real_eq_zero {z : ℝ} : (z : ℂ) = 0 ↔ z = 0 := of_real_inj theorem of_real_ne_zero {z : ℝ} : (z : ℂ) ≠ 0 ↔ z ≠ 0 := not_congr of_real_eq_zero instance : has_one ℂ := ⟨(1 : ℝ)⟩ @[simp] lemma one_re : (1 : ℂ).re = 1 := rfl @[simp] lemma one_im : (1 : ℂ).im = 0 := rfl @[simp, norm_cast] lemma of_real_one : ((1 : ℝ) : ℂ) = 1 := rfl instance : has_add ℂ := ⟨λ z w, ⟨z.re + w.re, z.im + w.im⟩⟩ @[simp] lemma add_re (z w : ℂ) : (z + w).re = z.re + w.re := rfl @[simp] lemma add_im (z w : ℂ) : (z + w).im = z.im + w.im := rfl @[simp] lemma bit0_re (z : ℂ) : (bit0 z).re = bit0 z.re := rfl @[simp] lemma bit1_re (z : ℂ) : (bit1 z).re = bit1 z.re := rfl @[simp] lemma bit0_im (z : ℂ) : (bit0 z).im = bit0 z.im := eq.refl _ @[simp] lemma bit1_im (z : ℂ) : (bit1 z).im = bit0 z.im := add_zero _ @[simp, norm_cast] lemma of_real_add (r s : ℝ) : ((r + s : ℝ) : ℂ) = r + s := ext_iff.2 $ by simp @[simp, norm_cast] lemma of_real_bit0 (r : ℝ) : ((bit0 r : ℝ) : ℂ) = bit0 r := ext_iff.2 $ by simp [bit0] @[simp, norm_cast] lemma of_real_bit1 (r : ℝ) : ((bit1 r : ℝ) : ℂ) = bit1 r := ext_iff.2 $ by simp [bit1] instance : has_neg ℂ := ⟨λ z, ⟨-z.re, -z.im⟩⟩ @[simp] lemma neg_re (z : ℂ) : (-z).re = -z.re := rfl @[simp] lemma neg_im (z : ℂ) : (-z).im = -z.im := rfl @[simp, norm_cast] lemma of_real_neg (r : ℝ) : ((-r : ℝ) : ℂ) = -r := ext_iff.2 $ by simp instance : has_mul ℂ := ⟨λ z w, ⟨z.re * w.re - z.im * w.im, z.re * w.im + z.im * w.re⟩⟩ @[simp] lemma mul_re (z w : ℂ) : (z * w).re = z.re * w.re - z.im * w.im := rfl @[simp] lemma mul_im (z w : ℂ) : (z * w).im = z.re * w.im + z.im * w.re := rfl @[simp, norm_cast] lemma of_real_mul (r s : ℝ) : ((r * s : ℝ) : ℂ) = r * s := ext_iff.2 $ by simp lemma smul_re (r : ℝ) (z : ℂ) : (↑r * z).re = r * z.re := by simp lemma smul_im (r : ℝ) (z : ℂ) : (↑r * z).im = r * z.im := by simp lemma of_real_smul (r : ℝ) (z : ℂ) : (↑r * z) = ⟨r * z.re, r * z.im⟩ := ext (smul_re _ _) (smul_im _ _) /-! ### The imaginary unit, `I` -/ /-- The imaginary unit. -/ def I : ℂ := ⟨0, 1⟩ @[simp] lemma I_re : I.re = 0 := rfl @[simp] lemma I_im : I.im = 1 := rfl @[simp] lemma I_mul_I : I * I = -1 := ext_iff.2 $ by simp lemma I_mul (z : ℂ) : I * z = ⟨-z.im, z.re⟩ := ext_iff.2 $ by simp lemma I_ne_zero : (I : ℂ) ≠ 0 := mt (congr_arg im) zero_ne_one.symm lemma mk_eq_add_mul_I (a b : ℝ) : complex.mk a b = a + b * I := ext_iff.2 $ by simp @[simp] lemma re_add_im (z : ℂ) : (z.re : ℂ) + z.im * I = z := ext_iff.2 $ by simp /-! ### Commutative ring instance and lemmas -/ instance : comm_ring ℂ := by refine { zero := 0, add := (+), neg := has_neg.neg, one := 1, mul := (*), ..}; { intros, apply ext_iff.2; split; simp; ring } instance re.is_add_group_hom : is_add_group_hom complex.re := { map_add := complex.add_re } instance im.is_add_group_hom : is_add_group_hom complex.im := { map_add := complex.add_im } /-! ### Complex conjugation -/ /-- The complex conjugate. -/ def conj : ℂ →+* ℂ := begin refine_struct { to_fun := λ z : ℂ, (⟨z.re, -z.im⟩ : ℂ), .. }; { intros, ext; simp [add_comm], }, end @[simp] lemma conj_re (z : ℂ) : (conj z).re = z.re := rfl @[simp] lemma conj_im (z : ℂ) : (conj z).im = -z.im := rfl @[simp] lemma conj_of_real (r : ℝ) : conj r = r := ext_iff.2 $ by simp [conj] @[simp] lemma conj_I : conj I = -I := ext_iff.2 $ by simp @[simp] lemma conj_bit0 (z : ℂ) : conj (bit0 z) = bit0 (conj z) := ext_iff.2 $ by simp [bit0] @[simp] lemma conj_bit1 (z : ℂ) : conj (bit1 z) = bit1 (conj z) := ext_iff.2 $ by simp [bit0] @[simp] lemma conj_neg_I : conj (-I) = I := ext_iff.2 $ by simp @[simp] lemma conj_conj (z : ℂ) : conj (conj z) = z := ext_iff.2 $ by simp lemma conj_involutive : function.involutive conj := conj_conj lemma conj_bijective : function.bijective conj := conj_involutive.bijective lemma conj_inj {z w : ℂ} : conj z = conj w ↔ z = w := conj_bijective.1.eq_iff @[simp] lemma conj_eq_zero {z : ℂ} : conj z = 0 ↔ z = 0 := by simpa using @conj_inj z 0 lemma eq_conj_iff_real {z : ℂ} : conj z = z ↔ ∃ r : ℝ, z = r := ⟨λ h, ⟨z.re, ext rfl $ eq_zero_of_neg_eq (congr_arg im h)⟩, λ ⟨h, e⟩, by rw [e, conj_of_real]⟩ lemma eq_conj_iff_re {z : ℂ} : conj z = z ↔ (z.re : ℂ) = z := eq_conj_iff_real.trans ⟨by rintro ⟨r, rfl⟩; simp, λ h, ⟨_, h.symm⟩⟩ /-! ### Norm squared -/ /-- The norm squared function. -/ @[pp_nodot] def norm_sq (z : ℂ) : ℝ := z.re * z.re + z.im * z.im @[simp] lemma norm_sq_of_real (r : ℝ) : norm_sq r = r * r := by simp [norm_sq] @[simp] lemma norm_sq_zero : norm_sq 0 = 0 := by simp [norm_sq] @[simp] lemma norm_sq_one : norm_sq 1 = 1 := by simp [norm_sq] @[simp] lemma norm_sq_I : norm_sq I = 1 := by simp [norm_sq] lemma norm_sq_nonneg (z : ℂ) : 0 ≤ norm_sq z := add_nonneg (mul_self_nonneg _) (mul_self_nonneg _) @[simp] lemma norm_sq_eq_zero {z : ℂ} : norm_sq z = 0 ↔ z = 0 := ⟨λ h, ext (eq_zero_of_mul_self_add_mul_self_eq_zero h) (eq_zero_of_mul_self_add_mul_self_eq_zero $ (add_comm _ _).trans h), λ h, h.symm ▸ norm_sq_zero⟩ @[simp] lemma norm_sq_pos {z : ℂ} : 0 < norm_sq z ↔ z ≠ 0 := by rw [lt_iff_le_and_ne, ne, eq_comm]; simp [norm_sq_nonneg] @[simp] lemma norm_sq_neg (z : ℂ) : norm_sq (-z) = norm_sq z := by simp [norm_sq] @[simp] lemma norm_sq_conj (z : ℂ) : norm_sq (conj z) = norm_sq z := by simp [norm_sq] @[simp] lemma norm_sq_mul (z w : ℂ) : norm_sq (z * w) = norm_sq z * norm_sq w := by dsimp [norm_sq]; ring lemma norm_sq_add (z w : ℂ) : norm_sq (z + w) = norm_sq z + norm_sq w + 2 * (z * conj w).re := by dsimp [norm_sq]; ring lemma re_sq_le_norm_sq (z : ℂ) : z.re * z.re ≤ norm_sq z := le_add_of_nonneg_right (mul_self_nonneg _) lemma im_sq_le_norm_sq (z : ℂ) : z.im * z.im ≤ norm_sq z := le_add_of_nonneg_left (mul_self_nonneg _) theorem mul_conj (z : ℂ) : z * conj z = norm_sq z := ext_iff.2 $ by simp [norm_sq, mul_comm, sub_eq_neg_add, add_comm] theorem add_conj (z : ℂ) : z + conj z = (2 * z.re : ℝ) := ext_iff.2 $ by simp [two_mul] /-- The coercion `ℝ → ℂ` as a `ring_hom`. -/ def of_real : ℝ →+* ℂ := ⟨coe, of_real_one, of_real_mul, of_real_zero, of_real_add⟩ @[simp] lemma of_real_eq_coe (r : ℝ) : of_real r = r := rfl @[simp] lemma I_sq : I ^ 2 = -1 := by rw [pow_two, I_mul_I] @[simp] lemma sub_re (z w : ℂ) : (z - w).re = z.re - w.re := rfl @[simp] lemma sub_im (z w : ℂ) : (z - w).im = z.im - w.im := rfl @[simp, norm_cast] lemma of_real_sub (r s : ℝ) : ((r - s : ℝ) : ℂ) = r - s := ext_iff.2 $ by simp @[simp, norm_cast] lemma of_real_pow (r : ℝ) (n : ℕ) : ((r ^ n : ℝ) : ℂ) = r ^ n := by induction n; simp [*, of_real_mul, pow_succ] theorem sub_conj (z : ℂ) : z - conj z = (2 * z.im : ℝ) * I := ext_iff.2 $ by simp [two_mul, sub_eq_add_neg] lemma norm_sq_sub (z w : ℂ) : norm_sq (z - w) = norm_sq z + norm_sq w - 2 * (z * conj w).re := by rw [sub_eq_add_neg, norm_sq_add]; simp [-mul_re, add_comm, add_left_comm, sub_eq_add_neg] /-! ### Inversion -/ noncomputable instance : has_inv ℂ := ⟨λ z, conj z * ((norm_sq z)⁻¹:ℝ)⟩ theorem inv_def (z : ℂ) : z⁻¹ = conj z * ((norm_sq z)⁻¹:ℝ) := rfl @[simp] lemma inv_re (z : ℂ) : (z⁻¹).re = z.re / norm_sq z := by simp [inv_def, division_def] @[simp] lemma inv_im (z : ℂ) : (z⁻¹).im = -z.im / norm_sq z := by simp [inv_def, division_def] @[simp, norm_cast] lemma of_real_inv (r : ℝ) : ((r⁻¹ : ℝ) : ℂ) = r⁻¹ := ext_iff.2 $ begin simp, by_cases r = 0, { simp [h] }, { rw [← div_div_eq_div_mul, div_self h, one_div] }, end protected lemma inv_zero : (0⁻¹ : ℂ) = 0 := by rw [← of_real_zero, ← of_real_inv, inv_zero] protected theorem mul_inv_cancel {z : ℂ} (h : z ≠ 0) : z * z⁻¹ = 1 := by rw [inv_def, ← mul_assoc, mul_conj, ← of_real_mul, mul_inv_cancel (mt norm_sq_eq_zero.1 h), of_real_one] /-! ### Field instance and lemmas -/ noncomputable instance : field ℂ := { inv := has_inv.inv, exists_pair_ne := ⟨0, 1, mt (congr_arg re) zero_ne_one⟩, mul_inv_cancel := @complex.mul_inv_cancel, inv_zero := complex.inv_zero, ..complex.comm_ring } lemma div_re (z w : ℂ) : (z / w).re = z.re * w.re / norm_sq w + z.im * w.im / norm_sq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg] lemma div_im (z w : ℂ) : (z / w).im = z.im * w.re / norm_sq w - z.re * w.im / norm_sq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg, add_comm] @[simp, norm_cast] lemma of_real_div (r s : ℝ) : ((r / s : ℝ) : ℂ) = r / s := of_real.map_div r s @[simp, norm_cast] lemma of_real_fpow (r : ℝ) (n : ℤ) : ((r ^ n : ℝ) : ℂ) = (r : ℂ) ^ n := of_real.map_fpow r n @[simp] lemma div_I (z : ℂ) : z / I = -(z * I) := (div_eq_iff_mul_eq I_ne_zero).2 $ by simp [mul_assoc] @[simp] lemma inv_I : I⁻¹ = -I := by simp [inv_eq_one_div] @[simp] lemma norm_sq_inv (z : ℂ) : norm_sq z⁻¹ = (norm_sq z)⁻¹ := if h : z = 0 then by simp [h] else mul_right_cancel' (mt norm_sq_eq_zero.1 h) $ by rw [← norm_sq_mul]; simp [h, -norm_sq_mul] @[simp] lemma norm_sq_div (z w : ℂ) : norm_sq (z / w) = norm_sq z / norm_sq w := by rw [division_def, norm_sq_mul, norm_sq_inv]; refl /-! ### Cast lemmas -/ @[simp, norm_cast] theorem of_real_nat_cast (n : ℕ) : ((n : ℝ) : ℂ) = n := of_real.map_nat_cast n @[simp, norm_cast] lemma nat_cast_re (n : ℕ) : (n : ℂ).re = n := by rw [← of_real_nat_cast, of_real_re] @[simp, norm_cast] lemma nat_cast_im (n : ℕ) : (n : ℂ).im = 0 := by rw [← of_real_nat_cast, of_real_im] @[simp, norm_cast] theorem of_real_int_cast (n : ℤ) : ((n : ℝ) : ℂ) = n := of_real.map_int_cast n @[simp, norm_cast] lemma int_cast_re (n : ℤ) : (n : ℂ).re = n := by rw [← of_real_int_cast, of_real_re] @[simp, norm_cast] lemma int_cast_im (n : ℤ) : (n : ℂ).im = 0 := by rw [← of_real_int_cast, of_real_im] @[simp, norm_cast] theorem of_real_rat_cast (n : ℚ) : ((n : ℝ) : ℂ) = n := of_real.map_rat_cast n @[simp, norm_cast] lemma rat_cast_re (q : ℚ) : (q : ℂ).re = q := by rw [← of_real_rat_cast, of_real_re] @[simp, norm_cast] lemma rat_cast_im (q : ℚ) : (q : ℂ).im = 0 := by rw [← of_real_rat_cast, of_real_im] /-! ### Characteristic zero -/ instance char_zero_complex : char_zero ℂ := add_group.char_zero_of_inj_zero $ λ n h, by rwa [← of_real_nat_cast, of_real_eq_zero, nat.cast_eq_zero] at h theorem re_eq_add_conj (z : ℂ) : (z.re : ℂ) = (z + conj z) / 2 := by rw [add_conj]; simp; rw [mul_div_cancel_left (z.re:ℂ) two_ne_zero'] /-! ### Absolute value -/ /-- The complex absolute value function, defined as the square root of the norm squared. -/ @[pp_nodot] noncomputable def abs (z : ℂ) : ℝ := (norm_sq z).sqrt local notation `abs'` := _root_.abs @[simp, norm_cast] lemma abs_of_real (r : ℝ) : abs r = abs' r := by simp [abs, norm_sq_of_real, real.sqrt_mul_self_eq_abs] lemma abs_of_nonneg {r : ℝ} (h : 0 ≤ r) : abs r = r := (abs_of_real _).trans (abs_of_nonneg h) lemma abs_of_nat (n : ℕ) : complex.abs n = n := calc complex.abs n = complex.abs (n:ℝ) : by rw [of_real_nat_cast] ... = _ : abs_of_nonneg (nat.cast_nonneg n) lemma mul_self_abs (z : ℂ) : abs z * abs z = norm_sq z := real.mul_self_sqrt (norm_sq_nonneg _) @[simp] lemma abs_zero : abs 0 = 0 := by simp [abs] @[simp] lemma abs_one : abs 1 = 1 := by simp [abs] @[simp] lemma abs_I : abs I = 1 := by simp [abs] @[simp] lemma abs_two : abs 2 = 2 := calc abs 2 = abs (2 : ℝ) : by rw [of_real_bit0, of_real_one] ... = (2 : ℝ) : abs_of_nonneg (by norm_num) lemma abs_nonneg (z : ℂ) : 0 ≤ abs z := real.sqrt_nonneg _ @[simp] lemma abs_eq_zero {z : ℂ} : abs z = 0 ↔ z = 0 := (real.sqrt_eq_zero $ norm_sq_nonneg _).trans norm_sq_eq_zero lemma abs_ne_zero {z : ℂ} : abs z ≠ 0 ↔ z ≠ 0 := not_congr abs_eq_zero @[simp] lemma abs_conj (z : ℂ) : abs (conj z) = abs z := by simp [abs] @[simp] lemma abs_mul (z w : ℂ) : abs (z * w) = abs z * abs w := by rw [abs, norm_sq_mul, real.sqrt_mul (norm_sq_nonneg _)]; refl lemma abs_re_le_abs (z : ℂ) : abs' z.re ≤ abs z := by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg z.re) (abs_nonneg _), abs_mul_abs_self, mul_self_abs]; apply re_sq_le_norm_sq lemma abs_im_le_abs (z : ℂ) : abs' z.im ≤ abs z := by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg z.im) (abs_nonneg _), abs_mul_abs_self, mul_self_abs]; apply im_sq_le_norm_sq lemma re_le_abs (z : ℂ) : z.re ≤ abs z := (abs_le.1 (abs_re_le_abs _)).2 lemma im_le_abs (z : ℂ) : z.im ≤ abs z := (abs_le.1 (abs_im_le_abs _)).2 lemma abs_add (z w : ℂ) : abs (z + w) ≤ abs z + abs w := (mul_self_le_mul_self_iff (abs_nonneg _) (add_nonneg (abs_nonneg _) (abs_nonneg _))).2 $ begin rw [mul_self_abs, add_mul_self_eq, mul_self_abs, mul_self_abs, add_right_comm, norm_sq_add, add_le_add_iff_left, mul_assoc, mul_le_mul_left (@zero_lt_two ℝ _)], simpa [-mul_re] using re_le_abs (z * conj w) end instance : is_absolute_value abs := { abv_nonneg := abs_nonneg, abv_eq_zero := λ _, abs_eq_zero, abv_add := abs_add, abv_mul := abs_mul } open is_absolute_value @[simp] lemma abs_abs (z : ℂ) : abs' (abs z) = abs z := _root_.abs_of_nonneg (abs_nonneg _) @[simp] lemma abs_pos {z : ℂ} : 0 < abs z ↔ z ≠ 0 := abv_pos abs @[simp] lemma abs_neg : ∀ z, abs (-z) = abs z := abv_neg abs lemma abs_sub : ∀ z w, abs (z - w) = abs (w - z) := abv_sub abs lemma abs_sub_le : ∀ a b c, abs (a - c) ≤ abs (a - b) + abs (b - c) := abv_sub_le abs @[simp] theorem abs_inv : ∀ z, abs z⁻¹ = (abs z)⁻¹ := abv_inv abs @[simp] theorem abs_div : ∀ z w, abs (z / w) = abs z / abs w := abv_div abs lemma abs_abs_sub_le_abs_sub : ∀ z w, abs' (abs z - abs w) ≤ abs (z - w) := abs_abv_sub_le_abv_sub abs lemma abs_le_abs_re_add_abs_im (z : ℂ) : abs z ≤ abs' z.re + abs' z.im := by simpa [re_add_im] using abs_add z.re (z.im * I) lemma abs_re_div_abs_le_one (z : ℂ) : abs' (z.re / z.abs) ≤ 1 := if hz : z = 0 then by simp [hz, zero_le_one] else by { simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, abs_re_le_abs] } lemma abs_im_div_abs_le_one (z : ℂ) : abs' (z.im / z.abs) ≤ 1 := if hz : z = 0 then by simp [hz, zero_le_one] else by { simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, abs_im_le_abs] } @[simp, norm_cast] lemma abs_cast_nat (n : ℕ) : abs (n : ℂ) = n := by rw [← of_real_nat_cast, abs_of_nonneg (nat.cast_nonneg n)] lemma norm_sq_eq_abs (x : ℂ) : norm_sq x = abs x ^ 2 := by rw [abs, pow_two, real.mul_self_sqrt (norm_sq_nonneg _)] /-! ### Cauchy sequences -/ theorem is_cau_seq_re (f : cau_seq ℂ abs) : is_cau_seq abs' (λ n, (f n).re) := λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij, lt_of_le_of_lt (by simpa using abs_re_le_abs (f j - f i)) (H _ ij) theorem is_cau_seq_im (f : cau_seq ℂ abs) : is_cau_seq abs' (λ n, (f n).im) := λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij, lt_of_le_of_lt (by simpa using abs_im_le_abs (f j - f i)) (H _ ij) /-- The real part of a complex Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cau_seq_re (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_re f⟩ /-- The imaginary part of a complex Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cau_seq_im (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_im f⟩ lemma is_cau_seq_abs {f : ℕ → ℂ} (hf : is_cau_seq abs f) : is_cau_seq abs' (abs ∘ f) := λ ε ε0, let ⟨i, hi⟩ := hf ε ε0 in ⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩ /-- The limit of a Cauchy sequence of complex numbers. -/ noncomputable def lim_aux (f : cau_seq ℂ abs) : ℂ := ⟨cau_seq.lim (cau_seq_re f), cau_seq.lim (cau_seq_im f)⟩ theorem equiv_lim_aux (f : cau_seq ℂ abs) : f ≈ cau_seq.const abs (lim_aux f) := λ ε ε0, (exists_forall_ge_and (cau_seq.equiv_lim ⟨_, is_cau_seq_re f⟩ _ (half_pos ε0)) (cau_seq.equiv_lim ⟨_, is_cau_seq_im f⟩ _ (half_pos ε0))).imp $ λ i H j ij, begin cases H _ ij with H₁ H₂, apply lt_of_le_of_lt (abs_le_abs_re_add_abs_im _), dsimp [lim_aux] at *, have := add_lt_add H₁ H₂, rwa add_halves at this, end noncomputable instance : cau_seq.is_complete ℂ abs := ⟨λ f, ⟨lim_aux f, equiv_lim_aux f⟩⟩ open cau_seq lemma lim_eq_lim_im_add_lim_re (f : cau_seq ℂ abs) : lim f = ↑(lim (cau_seq_re f)) + ↑(lim (cau_seq_im f)) * I := lim_eq_of_equiv_const $ calc f ≈ _ : equiv_lim_aux f ... = cau_seq.const abs (↑(lim (cau_seq_re f)) + ↑(lim (cau_seq_im f)) * I) : cau_seq.ext (λ _, complex.ext (by simp [lim_aux, cau_seq_re]) (by simp [lim_aux, cau_seq_im])) lemma lim_re (f : cau_seq ℂ abs) : lim (cau_seq_re f) = (lim f).re := by rw [lim_eq_lim_im_add_lim_re]; simp lemma lim_im (f : cau_seq ℂ abs) : lim (cau_seq_im f) = (lim f).im := by rw [lim_eq_lim_im_add_lim_re]; simp lemma is_cau_seq_conj (f : cau_seq ℂ abs) : is_cau_seq abs (λ n, conj (f n)) := λ ε ε0, let ⟨i, hi⟩ := f.2 ε ε0 in ⟨i, λ j hj, by rw [← conj.map_sub, abs_conj]; exact hi j hj⟩ /-- The complex conjugate of a complex Cauchy sequence, as a complex Cauchy sequence. -/ noncomputable def cau_seq_conj (f : cau_seq ℂ abs) : cau_seq ℂ abs := ⟨_, is_cau_seq_conj f⟩ lemma lim_conj (f : cau_seq ℂ abs) : lim (cau_seq_conj f) = conj (lim f) := complex.ext (by simp [cau_seq_conj, (lim_re _).symm, cau_seq_re]) (by simp [cau_seq_conj, (lim_im _).symm, cau_seq_im, (lim_neg _).symm]; refl) /-- The absolute value of a complex Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cau_seq_abs (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_abs f.2⟩ lemma lim_abs (f : cau_seq ℂ abs) : lim (cau_seq_abs f) = abs (lim f) := lim_eq_of_equiv_const (λ ε ε0, let ⟨i, hi⟩ := equiv_lim f ε ε0 in ⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩) @[simp, norm_cast] lemma of_real_prod {α : Type*} (s : finset α) (f : α → ℝ) : ((∏ i in s, f i : ℝ) : ℂ) = ∏ i in s, (f i : ℂ) := ring_hom.map_prod of_real _ _ @[simp, norm_cast] lemma of_real_sum {α : Type*} (s : finset α) (f : α → ℝ) : ((∑ i in s, f i : ℝ) : ℂ) = ∑ i in s, (f i : ℂ) := ring_hom.map_sum of_real _ _ end complex
39d3298996f256de22498bab44d4fe060195c913
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Meta/Eval.lean
a93853130ae7617f04ebd341228465afb461363d
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
1,279
lean
/- Copyright (c) 2022 Sebastian Ullrich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich, Leonardo de Moura -/ import Lean.Meta.Check namespace Lean.Meta unsafe def evalExprCore (α) (value : Expr) (checkType : Expr → MetaM Unit) (safety := DefinitionSafety.safe) : MetaM α := withoutModifyingEnv do let name ← mkFreshUserName `_tmp let type ← inferType value checkType type let decl := Declaration.defnDecl { name, levelParams := [], type value, hints := ReducibilityHints.opaque, safety } addAndCompile decl evalConst α name unsafe def evalExpr' (α) (typeName : Name) (value : Expr) (safety := DefinitionSafety.safe) : MetaM α := evalExprCore (safety := safety) α value fun type => do let type ← whnfD type unless type.isConstOf typeName do throwError "unexpected type at evalExpr{indentExpr type}" unsafe def evalExpr (α) (expectedType : Expr) (value : Expr) (safety := DefinitionSafety.safe) : MetaM α := evalExprCore (safety := safety) α value fun type => do unless ← isDefEq type expectedType do throwError "unexpected type at `evalExpr` {← mkHasTypeButIsExpectedMsg type expectedType}" end Lean.Meta
117e95639d7fd07d3e2e1697d67f9d542c874983
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/adjunction/basic.lean
0df5be9436e539a0e528de2813ede0c634abbfe9
[ "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
19,644
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Johan Commelin, Bhavik Mehta -/ import category_theory.equivalence /-! # Adjunctions between functors `F ⊣ G` represents the data of an adjunction between two functors `F : C ⥤ D` and `G : D ⥤ C`. `F` is the left adjoint and `G` is the right adjoint. We provide various useful constructors: * `mk_of_hom_equiv` * `mk_of_unit_counit` * `left_adjoint_of_equiv` / `right_adjoint_of equiv` construct a left/right adjoint of a given functor given the action on objects and the relevant equivalence of morphism spaces. * `adjunction_of_equiv_left` / `adjunction_of_equiv_right` witness that these constructions give adjunctions. There are also typeclasses `is_left_adjoint` / `is_right_adjoint`, carrying data witnessing that a given functor is a left or right adjoint. Given `[is_left_adjoint F]`, a right adjoint of `F` can be constructed as `right_adjoint F`. `adjunction.comp` composes adjunctions. `to_equivalence` upgrades an adjunction to an equivalence, given witnesses that the unit and counit are pointwise isomorphisms. Conversely `equivalence.to_adjunction` recovers the underlying adjunction from an equivalence. -/ namespace category_theory open category -- declare the `v`'s first; see `category_theory.category` for an explanation universes v₁ v₂ v₃ u₁ u₂ u₃ local attribute [elab_simple] whisker_left whisker_right variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] /-- `F ⊣ G` represents the data of an adjunction between two functors `F : C ⥤ D` and `G : D ⥤ C`. `F` is the left adjoint and `G` is the right adjoint. To construct an `adjunction` between two functors, it's often easier to instead use the constructors `mk_of_hom_equiv` or `mk_of_unit_counit`. To construct a left adjoint, there are also constructors `left_adjoint_of_equiv` and `adjunction_of_equiv_left` (as well as their duals) which can be simpler in practice. Uniqueness of adjoints is shown in `category_theory.adjunction.opposites`. See <https://stacks.math.columbia.edu/tag/0037>. -/ structure adjunction (F : C ⥤ D) (G : D ⥤ C) := (hom_equiv : Π (X Y), (F.obj X ⟶ Y) ≃ (X ⟶ G.obj Y)) (unit : 𝟭 C ⟶ F.comp G) (counit : G.comp F ⟶ 𝟭 D) (hom_equiv_unit' : Π {X Y f}, (hom_equiv X Y) f = (unit : _ ⟶ _).app X ≫ G.map f . obviously) (hom_equiv_counit' : Π {X Y g}, (hom_equiv X Y).symm g = F.map g ≫ counit.app Y . obviously) infix ` ⊣ `:15 := adjunction /-- A class giving a chosen right adjoint to the functor `left`. -/ class is_left_adjoint (left : C ⥤ D) := (right : D ⥤ C) (adj : left ⊣ right) /-- A class giving a chosen left adjoint to the functor `right`. -/ class is_right_adjoint (right : D ⥤ C) := (left : C ⥤ D) (adj : left ⊣ right) /-- Extract the left adjoint from the instance giving the chosen adjoint. -/ def left_adjoint (R : D ⥤ C) [is_right_adjoint R] : C ⥤ D := is_right_adjoint.left R /-- Extract the right adjoint from the instance giving the chosen adjoint. -/ def right_adjoint (L : C ⥤ D) [is_left_adjoint L] : D ⥤ C := is_left_adjoint.right L /-- The adjunction associated to a functor known to be a left adjoint. -/ def adjunction.of_left_adjoint (left : C ⥤ D) [is_left_adjoint left] : adjunction left (right_adjoint left) := is_left_adjoint.adj /-- The adjunction associated to a functor known to be a right adjoint. -/ def adjunction.of_right_adjoint (right : C ⥤ D) [is_right_adjoint right] : adjunction (left_adjoint right) right := is_right_adjoint.adj namespace adjunction restate_axiom hom_equiv_unit' restate_axiom hom_equiv_counit' attribute [simp, priority 10] hom_equiv_unit hom_equiv_counit section variables {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {X' X : C} {Y Y' : D} lemma hom_equiv_id (X : C) : adj.hom_equiv X _ (𝟙 _) = adj.unit.app X := by simp lemma hom_equiv_symm_id (X : D) : (adj.hom_equiv _ X).symm (𝟙 _) = adj.counit.app X := by simp @[simp, priority 10] lemma hom_equiv_naturality_left_symm (f : X' ⟶ X) (g : X ⟶ G.obj Y) : (adj.hom_equiv X' Y).symm (f ≫ g) = F.map f ≫ (adj.hom_equiv X Y).symm g := by rw [hom_equiv_counit, F.map_comp, assoc, adj.hom_equiv_counit.symm] @[simp] lemma hom_equiv_naturality_left (f : X' ⟶ X) (g : F.obj X ⟶ Y) : (adj.hom_equiv X' Y) (F.map f ≫ g) = f ≫ (adj.hom_equiv X Y) g := by rw [← equiv.eq_symm_apply]; simp [-hom_equiv_unit] @[simp, priority 10] lemma hom_equiv_naturality_right (f : F.obj X ⟶ Y) (g : Y ⟶ Y') : (adj.hom_equiv X Y') (f ≫ g) = (adj.hom_equiv X Y) f ≫ G.map g := by rw [hom_equiv_unit, G.map_comp, ← assoc, ←hom_equiv_unit] @[simp] lemma hom_equiv_naturality_right_symm (f : X ⟶ G.obj Y) (g : Y ⟶ Y') : (adj.hom_equiv X Y').symm (f ≫ G.map g) = (adj.hom_equiv X Y).symm f ≫ g := by rw [equiv.symm_apply_eq]; simp [-hom_equiv_counit] @[simp] lemma left_triangle : (whisker_right adj.unit F) ≫ (whisker_left F adj.counit) = nat_trans.id _ := begin ext, dsimp, erw [← adj.hom_equiv_counit, equiv.symm_apply_eq, adj.hom_equiv_unit], simp end @[simp] lemma right_triangle : (whisker_left G adj.unit) ≫ (whisker_right adj.counit G) = nat_trans.id _ := begin ext, dsimp, erw [← adj.hom_equiv_unit, ← equiv.eq_symm_apply, adj.hom_equiv_counit], simp end @[simp, reassoc] lemma left_triangle_components : F.map (adj.unit.app X) ≫ adj.counit.app (F.obj X) = 𝟙 (F.obj X) := congr_arg (λ (t : nat_trans _ (𝟭 C ⋙ F)), t.app X) adj.left_triangle @[simp, reassoc] lemma right_triangle_components {Y : D} : adj.unit.app (G.obj Y) ≫ G.map (adj.counit.app Y) = 𝟙 (G.obj Y) := congr_arg (λ (t : nat_trans _ (G ⋙ 𝟭 C)), t.app Y) adj.right_triangle @[simp, reassoc] lemma counit_naturality {X Y : D} (f : X ⟶ Y) : F.map (G.map f) ≫ (adj.counit).app Y = (adj.counit).app X ≫ f := adj.counit.naturality f @[simp, reassoc] lemma unit_naturality {X Y : C} (f : X ⟶ Y) : (adj.unit).app X ≫ G.map (F.map f) = f ≫ (adj.unit).app Y := (adj.unit.naturality f).symm lemma hom_equiv_apply_eq {A : C} {B : D} (f : F.obj A ⟶ B) (g : A ⟶ G.obj B) : adj.hom_equiv A B f = g ↔ f = (adj.hom_equiv A B).symm g := ⟨λ h, by {cases h, simp}, λ h, by {cases h, simp}⟩ lemma eq_hom_equiv_apply {A : C} {B : D} (f : F.obj A ⟶ B) (g : A ⟶ G.obj B) : g = adj.hom_equiv A B f ↔ (adj.hom_equiv A B).symm g = f := ⟨λ h, by {cases h, simp}, λ h, by {cases h, simp}⟩ end end adjunction namespace adjunction /-- This is an auxiliary data structure useful for constructing adjunctions. See `adjunction.mk_of_hom_equiv`. This structure won't typically be used anywhere else. -/ @[nolint has_nonempty_instance] structure core_hom_equiv (F : C ⥤ D) (G : D ⥤ C) := (hom_equiv : Π (X Y), (F.obj X ⟶ Y) ≃ (X ⟶ G.obj Y)) (hom_equiv_naturality_left_symm' : Π {X' X Y} (f : X' ⟶ X) (g : X ⟶ G.obj Y), (hom_equiv X' Y).symm (f ≫ g) = F.map f ≫ (hom_equiv X Y).symm g . obviously) (hom_equiv_naturality_right' : Π {X Y Y'} (f : F.obj X ⟶ Y) (g : Y ⟶ Y'), (hom_equiv X Y') (f ≫ g) = (hom_equiv X Y) f ≫ G.map g . obviously) namespace core_hom_equiv restate_axiom hom_equiv_naturality_left_symm' restate_axiom hom_equiv_naturality_right' attribute [simp, priority 10] hom_equiv_naturality_left_symm hom_equiv_naturality_right variables {F : C ⥤ D} {G : D ⥤ C} (adj : core_hom_equiv F G) {X' X : C} {Y Y' : D} @[simp] lemma hom_equiv_naturality_left (f : X' ⟶ X) (g : F.obj X ⟶ Y) : (adj.hom_equiv X' Y) (F.map f ≫ g) = f ≫ (adj.hom_equiv X Y) g := by rw [← equiv.eq_symm_apply]; simp @[simp] lemma hom_equiv_naturality_right_symm (f : X ⟶ G.obj Y) (g : Y ⟶ Y') : (adj.hom_equiv X Y').symm (f ≫ G.map g) = (adj.hom_equiv X Y).symm f ≫ g := by rw [equiv.symm_apply_eq]; simp end core_hom_equiv /-- This is an auxiliary data structure useful for constructing adjunctions. See `adjunction.mk_of_unit_counit`. This structure won't typically be used anywhere else. -/ @[nolint has_nonempty_instance] structure core_unit_counit (F : C ⥤ D) (G : D ⥤ C) := (unit : 𝟭 C ⟶ F.comp G) (counit : G.comp F ⟶ 𝟭 D) (left_triangle' : whisker_right unit F ≫ (functor.associator F G F).hom ≫ whisker_left F counit = nat_trans.id (𝟭 C ⋙ F) . obviously) (right_triangle' : whisker_left G unit ≫ (functor.associator G F G).inv ≫ whisker_right counit G = nat_trans.id (G ⋙ 𝟭 C) . obviously) namespace core_unit_counit restate_axiom left_triangle' restate_axiom right_triangle' attribute [simp] left_triangle right_triangle end core_unit_counit variables {F : C ⥤ D} {G : D ⥤ C} /-- Construct an adjunction between `F` and `G` out of a natural bijection between each `F.obj X ⟶ Y` and `X ⟶ G.obj Y`. -/ @[simps] def mk_of_hom_equiv (adj : core_hom_equiv F G) : F ⊣ G := { unit := { app := λ X, (adj.hom_equiv X (F.obj X)) (𝟙 (F.obj X)), naturality' := begin intros, erw [← adj.hom_equiv_naturality_left, ← adj.hom_equiv_naturality_right], dsimp, simp -- See note [dsimp, simp]. end }, counit := { app := λ Y, (adj.hom_equiv _ _).inv_fun (𝟙 (G.obj Y)), naturality' := begin intros, erw [← adj.hom_equiv_naturality_left_symm, ← adj.hom_equiv_naturality_right_symm], dsimp, simp end }, hom_equiv_unit' := λ X Y f, by erw [← adj.hom_equiv_naturality_right]; simp, hom_equiv_counit' := λ X Y f, by erw [← adj.hom_equiv_naturality_left_symm]; simp, .. adj } /-- Construct an adjunction between functors `F` and `G` given a unit and counit for the adjunction satisfying the triangle identities. -/ @[simps] def mk_of_unit_counit (adj : core_unit_counit F G) : F ⊣ G := { hom_equiv := λ X Y, { to_fun := λ f, adj.unit.app X ≫ G.map f, inv_fun := λ g, F.map g ≫ adj.counit.app Y, left_inv := λ f, begin change F.map (_ ≫ _) ≫ _ = _, rw [F.map_comp, assoc, ←functor.comp_map, adj.counit.naturality, ←assoc], convert id_comp f, have t := congr_arg (λ t : nat_trans _ _, t.app _) adj.left_triangle, dsimp at t, simp only [id_comp] at t, exact t, end, right_inv := λ g, begin change _ ≫ G.map (_ ≫ _) = _, rw [G.map_comp, ←assoc, ←functor.comp_map, ←adj.unit.naturality, assoc], convert comp_id g, have t := congr_arg (λ t : nat_trans _ _, t.app _) adj.right_triangle, dsimp at t, simp only [id_comp] at t, exact t, end }, .. adj } /-- The adjunction between the identity functor on a category and itself. -/ def id : 𝟭 C ⊣ 𝟭 C := { hom_equiv := λ X Y, equiv.refl _, unit := 𝟙 _, counit := 𝟙 _ } -- Satisfy the inhabited linter. instance : inhabited (adjunction (𝟭 C) (𝟭 C)) := ⟨id⟩ /-- If F and G are naturally isomorphic functors, establish an equivalence of hom-sets. -/ @[simps] def equiv_homset_left_of_nat_iso {F F' : C ⥤ D} (iso : F ≅ F') {X : C} {Y : D} : (F.obj X ⟶ Y) ≃ (F'.obj X ⟶ Y) := { to_fun := λ f, iso.inv.app _ ≫ f, inv_fun := λ g, iso.hom.app _ ≫ g, left_inv := λ f, by simp, right_inv := λ g, by simp } /-- If G and H are naturally isomorphic functors, establish an equivalence of hom-sets. -/ @[simps] def equiv_homset_right_of_nat_iso {G G' : D ⥤ C} (iso : G ≅ G') {X : C} {Y : D} : (X ⟶ G.obj Y) ≃ (X ⟶ G'.obj Y) := { to_fun := λ f, f ≫ iso.hom.app _, inv_fun := λ g, g ≫ iso.inv.app _, left_inv := λ f, by simp, right_inv := λ g, by simp } /-- Transport an adjunction along an natural isomorphism on the left. -/ def of_nat_iso_left {F G : C ⥤ D} {H : D ⥤ C} (adj : F ⊣ H) (iso : F ≅ G) : G ⊣ H := adjunction.mk_of_hom_equiv { hom_equiv := λ X Y, (equiv_homset_left_of_nat_iso iso.symm).trans (adj.hom_equiv X Y) } /-- Transport an adjunction along an natural isomorphism on the right. -/ def of_nat_iso_right {F : C ⥤ D} {G H : D ⥤ C} (adj : F ⊣ G) (iso : G ≅ H) : F ⊣ H := adjunction.mk_of_hom_equiv { hom_equiv := λ X Y, (adj.hom_equiv X Y).trans (equiv_homset_right_of_nat_iso iso) } /-- Transport being a right adjoint along a natural isomorphism. -/ def right_adjoint_of_nat_iso {F G : C ⥤ D} (h : F ≅ G) [r : is_right_adjoint F] : is_right_adjoint G := { left := r.left, adj := of_nat_iso_right r.adj h } /-- Transport being a left adjoint along a natural isomorphism. -/ def left_adjoint_of_nat_iso {F G : C ⥤ D} (h : F ≅ G) [r : is_left_adjoint F] : is_left_adjoint G := { right := r.right, adj := of_nat_iso_left r.adj h } section variables {E : Type u₃} [ℰ : category.{v₃} E] {H : D ⥤ E} {I : E ⥤ D} /-- Composition of adjunctions. See <https://stacks.math.columbia.edu/tag/0DV0>. -/ def comp (adj₁ : F ⊣ G) (adj₂ : H ⊣ I) : F ⋙ H ⊣ I ⋙ G := { hom_equiv := λ X Z, equiv.trans (adj₂.hom_equiv _ _) (adj₁.hom_equiv _ _), unit := adj₁.unit ≫ (whisker_left F $ whisker_right adj₂.unit G) ≫ (functor.associator _ _ _).inv, counit := (functor.associator _ _ _).hom ≫ (whisker_left I $ whisker_right adj₁.counit H) ≫ adj₂.counit } /-- If `F` and `G` are left adjoints then `F ⋙ G` is a left adjoint too. -/ instance left_adjoint_of_comp {E : Type u₃} [ℰ : category.{v₃} E] (F : C ⥤ D) (G : D ⥤ E) [Fl : is_left_adjoint F] [Gl : is_left_adjoint G] : is_left_adjoint (F ⋙ G) := { right := Gl.right ⋙ Fl.right, adj := Fl.adj.comp Gl.adj } /-- If `F` and `G` are right adjoints then `F ⋙ G` is a right adjoint too. -/ instance right_adjoint_of_comp {E : Type u₃} [ℰ : category.{v₃} E] {F : C ⥤ D} {G : D ⥤ E} [Fr : is_right_adjoint F] [Gr : is_right_adjoint G] : is_right_adjoint (F ⋙ G) := { left := Gr.left ⋙ Fr.left, adj := Gr.adj.comp Fr.adj } end section construct_left -- Construction of a left adjoint. In order to construct a left -- adjoint to a functor G : D → C, it suffices to give the object part -- of a functor F : C → D together with isomorphisms Hom(FX, Y) ≃ -- Hom(X, GY) natural in Y. The action of F on morphisms can be -- constructed from this data. variables {F_obj : C → D} {G} variables (e : Π X Y, (F_obj X ⟶ Y) ≃ (X ⟶ G.obj Y)) variables (he : ∀ X Y Y' g h, e X Y' (h ≫ g) = e X Y h ≫ G.map g) include he private lemma he' {X Y Y'} (f g) : (e X Y').symm (f ≫ G.map g) = (e X Y).symm f ≫ g := by intros; rw [equiv.symm_apply_eq, he]; simp /-- Construct a left adjoint functor to `G`, given the functor's value on objects `F_obj` and a bijection `e` between `F_obj X ⟶ Y` and `X ⟶ G.obj Y` satisfying a naturality law `he : ∀ X Y Y' g h, e X Y' (h ≫ g) = e X Y h ≫ G.map g`. Dual to `right_adjoint_of_equiv`. -/ @[simps] def left_adjoint_of_equiv : C ⥤ D := { obj := F_obj, map := λ X X' f, (e X (F_obj X')).symm (f ≫ e X' (F_obj X') (𝟙 _)), map_comp' := λ X X' X'' f f', begin rw [equiv.symm_apply_eq, he, equiv.apply_symm_apply], conv { to_rhs, rw [assoc, ←he, id_comp, equiv.apply_symm_apply] }, simp end } /-- Show that the functor given by `left_adjoint_of_equiv` is indeed left adjoint to `G`. Dual to `adjunction_of_equiv_right`. -/ @[simps] def adjunction_of_equiv_left : left_adjoint_of_equiv e he ⊣ G := mk_of_hom_equiv { hom_equiv := e, hom_equiv_naturality_left_symm' := begin intros, erw [← he' e he, ← equiv.apply_eq_iff_eq], simp [(he _ _ _ _ _).symm] end } end construct_left section construct_right -- Construction of a right adjoint, analogous to the above. variables {F} {G_obj : D → C} variables (e : Π X Y, (F.obj X ⟶ Y) ≃ (X ⟶ G_obj Y)) variables (he : ∀ X' X Y f g, e X' Y (F.map f ≫ g) = f ≫ e X Y g) include he private lemma he' {X' X Y} (f g) : F.map f ≫ (e X Y).symm g = (e X' Y).symm (f ≫ g) := by intros; rw [equiv.eq_symm_apply, he]; simp /-- Construct a right adjoint functor to `F`, given the functor's value on objects `G_obj` and a bijection `e` between `F.obj X ⟶ Y` and `X ⟶ G_obj Y` satisfying a naturality law `he : ∀ X Y Y' g h, e X' Y (F.map f ≫ g) = f ≫ e X Y g`. Dual to `left_adjoint_of_equiv`. -/ @[simps] def right_adjoint_of_equiv : D ⥤ C := { obj := G_obj, map := λ Y Y' g, (e (G_obj Y) Y') ((e (G_obj Y) Y).symm (𝟙 _) ≫ g), map_comp' := λ Y Y' Y'' g g', begin rw [← equiv.eq_symm_apply, ← he' e he, equiv.symm_apply_apply], conv { to_rhs, rw [← assoc, he' e he, comp_id, equiv.symm_apply_apply] }, simp end } /-- Show that the functor given by `right_adjoint_of_equiv` is indeed right adjoint to `F`. Dual to `adjunction_of_equiv_left`. -/ @[simps] def adjunction_of_equiv_right : F ⊣ right_adjoint_of_equiv e he := mk_of_hom_equiv { hom_equiv := e, hom_equiv_naturality_left_symm' := by intros; rw [equiv.symm_apply_eq, he]; simp, hom_equiv_naturality_right' := begin intros X Y Y' g h, erw [←he, equiv.apply_eq_iff_eq, ←assoc, he' e he, comp_id, equiv.symm_apply_apply] end } end construct_right /-- If the unit and counit of a given adjunction are (pointwise) isomorphisms, then we can upgrade the adjunction to an equivalence. -/ @[simps] noncomputable def to_equivalence (adj : F ⊣ G) [∀ X, is_iso (adj.unit.app X)] [∀ Y, is_iso (adj.counit.app Y)] : C ≌ D := { functor := F, inverse := G, unit_iso := nat_iso.of_components (λ X, as_iso (adj.unit.app X)) (by simp), counit_iso := nat_iso.of_components (λ Y, as_iso (adj.counit.app Y)) (by simp) } /-- If the unit and counit for the adjunction corresponding to a right adjoint functor are (pointwise) isomorphisms, then the functor is an equivalence of categories. -/ @[simps] noncomputable def is_right_adjoint_to_is_equivalence [is_right_adjoint G] [∀ X, is_iso ((adjunction.of_right_adjoint G).unit.app X)] [∀ Y, is_iso ((adjunction.of_right_adjoint G).counit.app Y)] : is_equivalence G := is_equivalence.of_equivalence_inverse (adjunction.of_right_adjoint G).to_equivalence end adjunction open adjunction namespace equivalence /-- The adjunction given by an equivalence of categories. (To obtain the opposite adjunction, simply use `e.symm.to_adjunction`. -/ def to_adjunction (e : C ≌ D) : e.functor ⊣ e.inverse := mk_of_unit_counit ⟨e.unit, e.counit, by { ext, dsimp, simp only [id_comp], exact e.functor_unit_comp _, }, by { ext, dsimp, simp only [id_comp], exact e.unit_inverse_comp _, }⟩ @[simp] lemma as_equivalence_to_adjunction_unit {e : C ≌ D} : e.functor.as_equivalence.to_adjunction.unit = e.unit := rfl @[simp] lemma as_equivalence_to_adjunction_counit {e : C ≌ D} : e.functor.as_equivalence.to_adjunction.counit = e.counit := rfl end equivalence namespace functor /-- An equivalence `E` is left adjoint to its inverse. -/ def adjunction (E : C ⥤ D) [is_equivalence E] : E ⊣ E.inv := (E.as_equivalence).to_adjunction /-- If `F` is an equivalence, it's a left adjoint. -/ @[priority 10] instance left_adjoint_of_equivalence {F : C ⥤ D} [is_equivalence F] : is_left_adjoint F := { right := _, adj := functor.adjunction F } @[simp] lemma right_adjoint_of_is_equivalence {F : C ⥤ D} [is_equivalence F] : right_adjoint F = inv F := rfl /-- If `F` is an equivalence, it's a right adjoint. -/ @[priority 10] instance right_adjoint_of_equivalence {F : C ⥤ D} [is_equivalence F] : is_right_adjoint F := { left := _, adj := functor.adjunction F.inv } @[simp] lemma left_adjoint_of_is_equivalence {F : C ⥤ D} [is_equivalence F] : left_adjoint F = inv F := rfl end functor end category_theory
b8d442b7372e8ff1955e3835ec9a5c4cad02013c
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/Deriving/BEq.lean
a3963f056b6e95c4fc6c8f8175b900f553eb437b
[ "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
5,069
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Transform import Lean.Elab.Deriving.Basic import Lean.Elab.Deriving.Util namespace Lean.Elab.Deriving.BEq open Lean.Parser.Term open Meta def mkBEqHeader (indVal : InductiveVal) : TermElabM Header := do mkHeader `BEq 2 indVal def mkMatch (header : Header) (indVal : InductiveVal) (auxFunName : Name) : TermElabM Term := do let discrs ← mkDiscrs header indVal let alts ← mkAlts `(match $[$discrs],* with $alts:matchAlt*) where mkElseAlt : TermElabM (TSyntax ``matchAltExpr) := do let mut patterns := #[] -- add `_` pattern for indices for _ in [:indVal.numIndices] do patterns := patterns.push (← `(_)) patterns := patterns.push (← `(_)) patterns := patterns.push (← `(_)) let altRhs ← `(false) `(matchAltExpr| | $[$patterns:term],* => $altRhs:term) mkAlts : TermElabM (Array (TSyntax ``matchAlt)) := do let mut alts := #[] for ctorName in indVal.ctors do let ctorInfo ← getConstInfoCtor ctorName let alt ← forallTelescopeReducing ctorInfo.type fun xs type => do let type ← Core.betaReduce type -- we 'beta-reduce' to eliminate "artificial" dependencies let mut patterns := #[] -- add `_` pattern for indices for _ in [:indVal.numIndices] do patterns := patterns.push (← `(_)) let mut ctorArgs1 := #[] let mut ctorArgs2 := #[] let mut rhs ← `(true) -- add `_` for inductive parameters, they are inaccessible for _ in [:indVal.numParams] do ctorArgs1 := ctorArgs1.push (← `(_)) ctorArgs2 := ctorArgs2.push (← `(_)) for i in [:ctorInfo.numFields] do let x := xs[indVal.numParams + i]! if type.containsFVar x.fvarId! then -- If resulting type depends on this field, we don't need to compare ctorArgs1 := ctorArgs1.push (← `(_)) ctorArgs2 := ctorArgs2.push (← `(_)) else let a := mkIdent (← mkFreshUserName `a) let b := mkIdent (← mkFreshUserName `b) ctorArgs1 := ctorArgs1.push a ctorArgs2 := ctorArgs2.push b if (← inferType x).isAppOf indVal.name then rhs ← `($rhs && $(mkIdent auxFunName):ident $a:ident $b:ident) else rhs ← `($rhs && $a:ident == $b:ident) patterns := patterns.push (← `(@$(mkIdent ctorName):ident $ctorArgs1:term*)) patterns := patterns.push (← `(@$(mkIdent ctorName):ident $ctorArgs2:term*)) `(matchAltExpr| | $[$patterns:term],* => $rhs:term) alts := alts.push alt alts := alts.push (← mkElseAlt) return alts def mkAuxFunction (ctx : Context) (i : Nat) : TermElabM Command := do let auxFunName := ctx.auxFunNames[i]! let indVal := ctx.typeInfos[i]! let header ← mkBEqHeader indVal let mut body ← mkMatch header indVal auxFunName if ctx.usePartial then let letDecls ← mkLocalInstanceLetDecls ctx `BEq header.argNames body ← mkLet letDecls body let binders := header.binders if ctx.usePartial then `(private partial def $(mkIdent auxFunName):ident $binders:bracketedBinder* : Bool := $body:term) else `(private def $(mkIdent auxFunName):ident $binders:bracketedBinder* : Bool := $body:term) def mkMutualBlock (ctx : Context) : TermElabM Syntax := do let mut auxDefs := #[] for i in [:ctx.typeInfos.size] do auxDefs := auxDefs.push (← mkAuxFunction ctx i) `(mutual set_option match.ignoreUnusedAlts true $auxDefs:command* end) private def mkBEqInstanceCmds (declNames : Array Name) : TermElabM (Array Syntax) := do let ctx ← mkContext "beq" declNames[0]! let cmds := #[← mkMutualBlock ctx] ++ (← mkInstanceCmds ctx `BEq declNames) trace[Elab.Deriving.beq] "\n{cmds}" return cmds private def mkBEqEnumFun (ctx : Context) (name : Name) : TermElabM Syntax := do let auxFunName := ctx.auxFunNames[0]! `(private def $(mkIdent auxFunName):ident (x y : $(mkIdent name)) : Bool := x.toCtorIdx == y.toCtorIdx) private def mkBEqEnumCmd (name : Name): TermElabM (Array Syntax) := do let ctx ← mkContext "beq" name let cmds := #[← mkBEqEnumFun ctx name] ++ (← mkInstanceCmds ctx `BEq #[name]) trace[Elab.Deriving.beq] "\n{cmds}" return cmds open Command def mkBEqInstanceHandler (declNames : Array Name) : CommandElabM Bool := do if declNames.size == 1 && (← isEnumType declNames[0]!) then let cmds ← liftTermElabM <| mkBEqEnumCmd declNames[0]! cmds.forM elabCommand return true else if (← declNames.allM isInductive) && declNames.size > 0 then let cmds ← liftTermElabM <| mkBEqInstanceCmds declNames cmds.forM elabCommand return true else return false builtin_initialize registerDerivingHandler `BEq mkBEqInstanceHandler registerTraceClass `Elab.Deriving.beq end Lean.Elab.Deriving.BEq
ddef61d29492ba8b6e11b13b090917ee0d36b013
d31b9f832ff922a603f76cf32e0f3aa822640508
/src/hott/init/meta/induction.lean
77717753f4e348209313fe7048876aeda951da7e
[ "Apache-2.0" ]
permissive
javra/hott3
6e7a9e72a991a2fae32e5764982e521dca617b16
cd51f2ab2aa48c1246a188f9b525b30f76c3d651
refs/heads/master
1,585,819,679,148
1,531,232,382,000
1,536,682,965,000
154,294,022
0
0
Apache-2.0
1,540,284,376,000
1,540,284,375,000
null
UTF-8
Lean
false
false
18,293
lean
/- Copyright (c) 2017 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn A tactic to infer truncatedness better than type-class inference. -/ import .basic_tactics namespace expr /-- gives the arity of the type, i.e. the number of pi's in the expression -/ meta def arity : expr → ℕ | (pi _ _ _ b) := arity b + 1 | e := 0 end expr namespace list universes u v variables {α : Type u} {β : Type v} def replace_position : list α → ℕ → α → list α | [] n x := [] | (_::xs) 0 x := x::xs | (x'::xs) (k+1) x := x'::replace_position xs k x def position_aux : list α → (ℕ → α → bool) → ℕ → list ℕ | [] f n := [] | (x::xs) f n := let ps := position_aux xs f (n+1) in if f n x then n::ps else ps /-- gives a list of positions where f returns true. f is applied to the position and the element in that position -/ def position (l : list α) (f : ℕ → α → bool) : list ℕ := list.position_aux l f 0 def gen_position_aux : list α → (ℕ → α → list α → bool) → ℕ → list ℕ | [] f n := [] | (x::xs) f n := let ps := gen_position_aux xs f (n+1) in if f n x xs then n::ps else ps /-- gives a list of positions where f returns true. f is applied to the position, the element in that position, and the tail of the list -/ def gen_position (l : list α) (f : ℕ → α → list α → bool) : list ℕ := list.gen_position_aux l f 0 def any_indexed_aux : list α → (ℕ → α → bool) → ℕ → bool | [] f n := ff | (x::xs) f n := f n x || any_indexed_aux xs f (n+1) def any_indexed : list α → (ℕ → α → bool) → bool := λxs f, any_indexed_aux xs f 0 def all_indexed_aux : list α → (ℕ → α → bool) → ℕ → bool | [] f n := tt | (x::xs) f n := f n x && all_indexed_aux xs f (n+1) def all_indexed : list α → (ℕ → α → bool) → bool := λxs f, all_indexed_aux xs f 0 def map_indexed_aux : list α → (ℕ → α → β) → ℕ → list β | [] f n := [] | (x::xs) f n := f n x::map_indexed_aux xs f (n+1) /-- maps the function to both the position and the element in that position -/ def map_indexed : list α → (ℕ → α → β) → list β := λxs f, map_indexed_aux xs f 0 /-- Splits the list at position n. Pads the first output list by x₀'s to ensure it has length n. -/ def split_pad (x₀ : α) : ℕ → list α → list α × list α | 0 xs := ([], xs) | (n+1) [] := (repeat x₀ (n+1), []) | (n+1) (x::xs) := let (ys, zs) := split_pad n xs in (x::ys, zs) /-- Splits the first list into a list of lists with lengths indicated by the second list. If the first list is too long, the remainder is ignored. If the list is too short, the result is padded by the element `x₀` -/ def splits_pad (x₀ : α) : list α → list ℕ → list (list α) | xs [] := [] | xs (n::ns) := let (ys, zs) := split_pad x₀ n xs in ys::splits_pad zs ns end list namespace option universes u v w variables {α : Type u} {β : Type v} def any : option α → (α → bool) → bool | (some x) f := f x | none f := ff def all : option α → (α → bool) → bool | (some x) f := f x | none f := tt end option namespace tactic open environment lean.parser expr pexpr sum variable {elab : bool} declare_trace hinduction private meta def mtac (t : tactic unit) : tactic unit := when_tracing `hinduction t private meta def mtrace (msg : format) : tactic unit := mtac $ trace msg private meta def mfail {α : Type _} (msg : format) : tactic α := mtrace msg >> fail msg structure induction_info := (nargs : ℕ) /- the number of arguments of the recursor -/ (motive : ℕ) /- the head of the conclusion of the recursor -/ (minor_premises : list ℕ) /- the hypotheses depending on the motive which are not type class instances -/ (minor_premise_arity : list ℕ) /- the arity of these -/ (type_class_premises : list ℕ) /- the hypotheses depending on the motive which are type class instances -/ (major_premise : ℕ) (target : name) /- the head of the major premise -/ (dependent : bool) /- whether the major premise occurs in the conclusion -/ (indices : list ℕ) /- The indices are the variables to which the motive is applied in the conclusion, excluding the major premise -/ (indices_in_major_premise : list ℕ) /- Position where the indices occur in the type of the major premise. If a index occurs more than once, then only the first occurrence is recorded. In this case, when applying the recursor, we don't check that the same variable occurs in these places, if that is not the case, we might get a confusing error message -/ (params : list ℕ) /- the parameters are the other arguments of the induction principle -/ (params_in_major_premise : list ℕ) /- Position where the parameters occurs in the type of the major premise. See remarks from indices -/ /- gets the information for the `hinduction` tactic. If add_dec is true then this data is stored for future use -/ meta def get_induction_info (nm : name) (add_dec : bool := tt) : tactic expr := do let info_name := mk_str_name nm "_ind_info", env ← get_env, if env.contains info_name then declaration.value <$> env.get info_name >>= return else do t ← mk_const nm >>= infer_type, let (_, binders, args, c) := destruct_pis t, let len_args : ℕ := args.length, var mot ← return $ get_app_fn c | fail "Conclusion doesn't have a variable as head", let motive := len_args - mot - 1, /- the minor premises are all arguments whose type depends on the motive -/ let pre_min_prem := args.position $ λn e, to_bool (n > motive) && e.has_var_idx (n - motive - 1), let (type_class_prem, min_prem) := pre_min_prem.partition (λk, (binders.nth k).iget = binder_info.inst_implicit), let min_prem_arity := min_prem.map $ λk, (args.nth k).iget.arity, /- l₁ is the list of arguments where minor premises are replaced by none -/ let l₁ := args.map_indexed $ λn e, if min_prem.mem n then none else some e, /- l₂ is the list of "major premises": the list of non-minor premises which do not occur in a later argument which is not a minor premise, which are not the motive and do not occur in the motive -/ let l₂ := l₁.gen_position $ λn' oe' es, to_bool (oe' ≠ none ∧ n' ≠ motive ∧ (n' < motive ∨ (oe'.any $ λe', bnot $ e'.has_var_idx (n' - motive - 1)))) && (es.all_indexed $ λn oe, bnot $ oe.any $ λe, e.has_var_idx n), [maj_prem] ← return l₂ | (if l₂ = [] then fail $ to_fmt "No major premise found. Positions of minor premises: " ++ to_fmt (min_prem.map (+1)) else fail $ to_fmt "Multiple major premises found at positions " ++ to_fmt (l₂.map (+1)) ++ ". Side conditions or mutual induction is not supported. Positions of minor premises: " ++ to_fmt min_prem), tmaj ← args.nth maj_prem, const tgt _ ← return $ get_app_fn tmaj | fail $ to_fmt "Invalid type of major premise (at position " ++ to_fmt (maj_prem+1) ++ "). The head is not a constant or definition.", when (min_prem.any $ λk, to_bool (k > maj_prem) && (args.nth k).iget.has_var_idx (k - maj_prem - 1)) $ fail $ to_fmt "Some minor premises depend on major premise. Minor premises: " ++ to_fmt (min_prem.map (+1)) ++ ", major premise: " ++ to_fmt (maj_prem+1), let dep := c.has_var_idx (len_args - maj_prem - 1), let mot_args := get_app_args c, indices_or_maj_prem ← mot_args.mmap (λe, do var ve ← return e | fail "Motive is applied to arguments which are not variables.", return $ len_args - ve - 1), maj_prem_arg_vars ← (get_app_args tmaj).mmap (λe, try_core $ do var ve ← head_eta e, return ve), mtrace $ to_fmt maj_prem_arg_vars, let indices := if dep then indices_or_maj_prem.init else indices_or_maj_prem, indices_in_major_premise ← indices.mmap (λn, do let l := maj_prem_arg_vars.position $ λpos var, to_bool $ var = some (maj_prem - n - 1), mpos::_ ← return l | fail $ to_fmt "The index at position " ++ to_fmt (n+1) ++ " is not an argument of the major premise.", return $ mpos), let params := (list.range len_args).filter $ λk, k ≠ motive ∧ k ≠ maj_prem ∧ ¬pre_min_prem.mem k ∧ ¬indices.mem k, params_in_major_premise ← params.mmap (λn, do let l := maj_prem_arg_vars.position $ λpos var, to_bool $ var = some (maj_prem - n - 1), mpos::_ ← return l | fail $ to_fmt "The parameter at position " ++ to_fmt (n+1) ++ " is not an argument of the major premise.", return $ mpos), let e := `(induction_info.mk %%(reflect len_args) %%(reflect motive) %%(reflect min_prem) %%(reflect min_prem_arity) %%(reflect type_class_prem) %%(reflect maj_prem) %%(reflect tgt) %%(reflect dep) %%(reflect indices) %%(reflect indices_in_major_premise) %%(reflect params) %%(reflect params_in_major_premise)), add_decl $ mk_definition info_name [] `(induction_info) e, return e /- this attribute which makes the definition an induction principle or the `hinduction` tactic -/ @[user_attribute] meta def induction_attribute : user_attribute := { name := `induction, descr := "HoTT attribute for induction principles", after_set := some $ λ n _ _, get_induction_info n >> skip } /- This attribute generates the induction data, but does not make this definition a standard induction principle. This means you can only use it by writing `hinduction ... using ...`. If this attribute is not given, the induction data has to be generated every call of the induction principle -/ @[user_attribute] meta def induction_using_attribute : user_attribute := { name := `induction_using, descr := "HoTT attribute for induction principles, which are not enabled by default", after_set := some $ λ n _ _, get_induction_info n >> skip } meta def get_rec_info (nm : name) : expr := expr.const (mk_str_name nm "_ind_info") [] /- to do: [later] add support for let-expressions (in revert_kdeps) -/ /- t is the type of h, possiby unfolded -/ meta def hinduction_core (h t : expr) (rec : name) (ns : list name) (info : expr) : tactic unit := focus1 $ do induction_info.mk nargs motive_pos _/-minor_premise position-/ mp_ar _/-type class premises-/ maj_prem_pos _/-target-/ dep index_pos index_pos_maj params_pos params_pos_maj ← eval_expr induction_info info, let t_args := get_app_args t, indices : list expr ← index_pos_maj.mmap $ λk, (do e ← whnf (t_args.nth k).iget, local_const _ _ _ _ ← return e | pp e >>= λmsg, mfail (to_fmt "Invalid recursor application with indices. There is an index which doesn't occur as variable in the type of major premise.\nSolution: generalize expression\n" ++ msg), return e), mtrace $ to_fmt "indices: " ++ to_fmt indices, let params : list expr := params_pos_maj.map $ λk, (t_args.nth k).iget, reverts : list ℕ ← indices.mmap $ λe, (do revs ← kdependencies e, revert_lst $ revs.filter (λx, x ≠ h ∧ ¬indices.mem x)), mtrace $ to_fmt "reverts: " ++ to_fmt (list.foldr nat.add 0 reverts), t ← target, crec ← mk_explicit <$> to_pexpr <$> mk_const rec, let indices_plus := if dep then indices.append [h] else indices, mot ← bind_lambdas indices_plus t, pp t >>= λm, mtrace $ to_fmt "target: " ++ m, pp mot >>= λm, mtrace $ to_fmt "motive: " ++ m, let mot' := to_pexpr mot, /- a list with placeholders, with the major premise and motive filled in-/ let flist : list pexpr := ((list.repeat mk_placeholder nargs).replace_position maj_prem_pos (to_pexpr h)).replace_position motive_pos mot', /- also fill in the indices -/ let flist₂ : list pexpr := (list.zip index_pos indices).foldl (λe ⟨n, e'⟩, e.replace_position n $ to_pexpr e') flist, /- also fill in the parameters -/ let flist₃ : list pexpr := (list.zip params_pos params).foldl (λe ⟨n, e'⟩, e.replace_position n $ to_pexpr e') flist, flist₃.mmap pp >>= λe, (mtrace $ to_fmt "List of arguments: " ++ to_fmt e), let fapp : pexpr := flist₃.foldl app crec, -- mtrace $ to_fmt "Raw format of the application: " ++ to_raw_fmt fapp, efapp ← (to_expr ``(%%fapp : %%t)).do_on_failure $ λmsg, (let msg' : format := "Induction tactic failed. Recursor is not applicable.\n" ++ msg in mtrace msg' >> return msg'), type_check efapp <|> pp efapp >>= λm, mfail $ to_fmt "Incorrect recursor application.\nRecursors with indices might still be buggy.\n" ++ "Possible solution: reduce the type of indices with dsimp.\n" ++ m, mtrace $ to_fmt "Elaborated application: " ++ to_fmt efapp, exact efapp, (all_goals $ clear h) <|> mfail ("Couldn't clear major premise from context after applying the induction principle.\n" ++ "Possible solution: generalize all let-expressions where the major premise occurs."), (all_goals $ indices.reverse.mmap' clear) <|> mfail "Couldn't clear indices from context after applying the induction principle.", ng ← num_goals, guard (mp_ar.length = ng) <|> mfail "Unreachable(?) code: wrong number of minor premises", let names := ns.splits_pad `_ mp_ar, focus $ names.map $ λnms, intro_lst nms >> skip, (all_goals $ reverts.mmap' intron) <|> mfail "Couldn't reintroduce hypotheses which depend on indices." -- to do: only do this if minor premise has as conclusion the motive /- t is the type of h, possiby unfolded, ht is the head of t, dept is whether the target depends on h -/ meta def hinduction_using (h t : expr) (ht : name) (dept : bool) (nm : name) (ns' : list name) : tactic (unit ⊕ option (unit → format)) := do rec_info ← get_induction_info nm ff <|> mfail (to_fmt "Invalid recursor " ++ to_fmt nm), tgt ← eval_expr name $ expr.app `(induction_info.target) rec_info, is_dept_rec ← eval_expr bool $ expr.app `(induction_info.dependent) rec_info, guard (tgt = ht) <|> mfail (to_fmt "Recursor " ++ to_fmt nm ++ " is not applicable. The head of the induction variable is " ++ to_fmt ht ++ ", but the target of the induction principle is " ++ to_fmt tgt), if bnot dept || is_dept_rec then skip else mfail (to_fmt "Invalid recursor. " ++ to_fmt nm ++ " is not recursive"), try_core_msg $ hinduction_core h t nm ns' rec_info /- t is the type of h, possiby unfolded -/ meta def hinduction (h t : expr) (rec : option name) (ns' : list name) : tactic unit := do const ht _ ← return $ get_app_fn t | mfail $ to_fmt "Invalid major premise " ++ to_fmt h ++ ". The head of its type is not a constant or definition.", dept ← target >>= λtgt, kdepends_on tgt h, match rec with | some nm := extract $ hinduction_using h t ht dept nm ns' | none := do ns₂ ← attribute.get_instances `induction, -- to do: use rb_map to filter induction principles more quickly!? let hrec := mk_str_name ht "rec", env ← get_env, ns ← if env.contains hrec then (has_attribute `induction hrec >> return ns₂) <|> return (ns₂ ++ [hrec]) else return ns₂, ns.mfirst_msg $ λnm, mtrace (to_fmt "Trying " ++ to_fmt nm) >> hinduction_using h t ht dept nm ns' end /-- tries to apply hinduction, but if it fails, applies whnf to the type of h and tries again -/ meta def hinduction_whnf (h : expr) (rec : option name) (ns' : list name) : tactic unit := do t ← infer_type h, (hinduction h t rec ns').orelse_plus $ do t' ← whnf t, if t = t' then return none else mtrace "Applying whnf to major premsie" >> some <$> hinduction h t' rec ns' meta def hinduction_or_induction (h : expr) (rec : option name) (ns : list name) : tactic unit := hinduction_whnf h rec ns <|> induction' h ns rec /- If h is a local constant, reverts all local constants which have h in their type. Otherwise, generalizes h to local constant h' and adds equality H : h' = h, where H is the head of ns (if non-empty). Then applies tactic tac. tac is only applied to a local constant which doesn't occur in the type of other local constants. After tac is executed, introduces generalized hypotheses. -/ meta def ind_generalize (h : expr) (ns : list name := []) (tac : expr → list name → tactic unit) : tactic unit := match h with | (local_const _ _ _ _) := do n ← revert_kdeps h, tac h ns, all_goals $ try $ intron n -- to do: only do this if minor premise has as conclusion the motive | _ := /- The block "generalize major premise args" in the induction tactic is for inductive families only(?) and only rarely useful -/ do x ← mk_fresh_name, /- to do: let the user decide whether to use ginduction or induction here -/ let (nm, nms) := (match ns with | [] := (`_h, []) | nm :: nms := (nm, nms) end : name × list name), hgeneralize (some nm) (to_pexpr h) x, t ← get_local x, pt ← get_local nm, revert pt, tac t nms, all_goals $ try $ intro1 end namespace interactive open expr interactive.types lean.parser tactic interactive local postfix `?`:9001 := optional local postfix *:9001 := many /- To do: allow hinduction 1 and maybe hinduction to a variable yet to be intro'd -/ /- to do: eta-reduce (and maybe more reductions) to variables, so that `(λx, B x)` is recognized as parameter `B` -/ /-- Applies induction to p. Works also for HoTT-induction principles which may not eliminate into Prop. -/ meta def hinduction (p : parse texpr) (rec_name : parse using_ident) (ids : parse with_ident_list) (revert : parse $ (tk "generalizing" *> ident*)?) : tactic unit := focus1 $ do e ← i_to_expr p, rec : option name ← rec_name.mmap resolve_constant, n ← mmap tactic.get_local (revert.get_or_else []) >>= revert_lst, ind_generalize e ids $ λe' ns', tactic.hinduction_whnf e' rec ns', all_goals $ intron n -- to do: only do this if minor premise has as conclusion the motive /-- Similar to hinduction, but tries the usual induction principle first if hinduction fails -/ meta def hinduction_plus (p : parse texpr) (rec_name : parse using_ident) (ids : parse with_ident_list) (revert : parse $ (tk "generalizing" *> ident*)?) : tactic unit := focus1 $ do e ← i_to_expr p, rec : option name ← rec_name.mmap resolve_constant, n ← mmap tactic.get_local (revert.get_or_else []) >>= revert_lst, ind_generalize e ids $ λe' ns', tactic.hinduction_or_induction e' rec ns', all_goals $ intron n -- to do: only do this if minor premise has as conclusion the motive end interactive end tactic
db6e23610e5119a49d6586cd69a62ae7f9c71fcc
92b50235facfbc08dfe7f334827d47281471333b
/library/theories/combinatorics/choose.lean
298d9eefe2db8ad6c73a8d8c243c8058bf252365
[ "Apache-2.0" ]
permissive
htzh/lean
24f6ed7510ab637379ec31af406d12584d31792c
d70c79f4e30aafecdfc4a60b5d3512199200ab6e
refs/heads/master
1,607,677,731,270
1,437,089,952,000
1,437,089,952,000
37,078,816
0
0
null
1,433,780,956,000
1,433,780,955,000
null
UTF-8
Lean
false
false
4,050
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Binomial coefficients, "n choose k". -/ import data.nat.div data.nat.fact open decidable namespace nat /- choose -/ definition choose : ℕ → ℕ → ℕ | 0 0 := 1 | 0 (succ k) := 0 | (succ n) 0 := 1 | (succ n) (succ k) := choose n (succ k) + choose n k theorem choose_zero_right (n : ℕ) : choose n 0 = 1 := nat.cases_on n rfl (take m, rfl) theorem choose_zero_succ (k : ℕ) : choose 0 (succ k) = 0 := rfl theorem choose_succ_succ (n k : ℕ) : choose (succ n) (succ k) = choose n (succ k) + choose n k := rfl theorem choose_eq_zero_of_lt {n : ℕ} : ∀{k : ℕ}, n < k → choose n k = 0 := nat.induction_on n (take k, assume H : 0 < k, obtain k' (H : k = succ k'), from exists_eq_succ_of_pos H, by rewrite H) (take n', assume IH: ∀ k, n' < k → choose n' k = 0, take k, assume H : succ n' < k, obtain k' (keq : k = succ k'), from exists_eq_succ_of_lt H, assert H' : n' < k', by rewrite keq at H; apply lt_of_succ_lt_succ H, by rewrite [keq, choose_succ_succ, IH _ H', IH _ (lt.trans H' !lt_succ_self)]) theorem choose_self (n : ℕ) : choose n n = 1 := begin induction n with [n, ih], {apply rfl}, rewrite [choose_succ_succ, ih, choose_eq_zero_of_lt !lt_succ_self] end theorem choose_succ_self (n : ℕ) : choose (succ n) n = succ n := begin induction n with [n, ih], {apply rfl}, rewrite [choose_succ_succ, ih, choose_self, add.comm] end theorem choose_one_right (n : ℕ) : choose n 1 = n := begin induction n with [n, ih], {apply rfl}, rewrite [choose_succ_succ, ih, choose_zero_right] end theorem choose_pos {n : ℕ} : ∀ {k : ℕ}, k ≤ n → choose n k > 0 := begin induction n with [n, ih], {intros [k, H], have kz : k = 0, from eq_of_le_of_ge H !zero_le, rewrite [kz, choose_zero_right]; apply zero_lt_one}, intro k, cases k with k, {intro H, rewrite [choose_zero_right], apply zero_lt_one}, assume H : succ k ≤ succ n, assert H' : k ≤ n, from le_of_succ_le_succ H, by rewrite [choose_succ_succ]; apply add_pos_right (ih H') end -- A key identity. The proof is subtle. theorem succ_mul_choose_eq (n : ℕ) : ∀ k, succ n * (choose n k) = choose (succ n) (succ k) * succ k := begin induction n with [n, ih], {intro k, cases k with k', {rewrite [*choose_self, one_mul, mul_one]}, {have H : 1 < succ (succ k'), from succ_lt_succ !zero_lt_succ, rewrite [one_mul, choose_zero_succ, choose_eq_zero_of_lt H, zero_mul]}}, intro k, cases k with k', {rewrite [choose_zero_right, choose_one_right]}, rewrite [choose_succ_succ (succ n), mul.right_distrib, -ih (succ k')], rewrite [choose_succ_succ at {1}, mul.left_distrib, *succ_mul (succ n), mul_succ, -ih k'], rewrite [*add.assoc, add.left_comm (choose n _)] end theorem choose_mul_fact_mul_fact {n : ℕ} : ∀ {k : ℕ}, k ≤ n → choose n k * fact k * fact (n - k) = fact n := begin induction n using nat.strong_induction_on with [n, ih], cases n with n, {intro k H, have kz : k = 0, from eq_zero_of_le_zero H, rewrite [kz]}, intro k, intro H, -- k ≤ n, cases k with k, {rewrite [choose_zero_right, fact_zero, *one_mul]}, have kle : k ≤ n, from le_of_succ_le_succ H, show choose (succ n) (succ k) * fact (succ k) * fact (succ n - succ k) = fact (succ n), from begin rewrite [succ_sub_succ, fact_succ, -mul.assoc, -succ_mul_choose_eq], rewrite [fact_succ n, -ih n !lt_succ_self kle, *mul.assoc] end end theorem choose_def_alt {n k : ℕ} (H : k ≤ n) : choose n k = fact n div (fact k * fact (n -k)) := eq.symm (div_eq_of_eq_mul_left (mul_pos !fact_pos !fact_pos) (by rewrite [-mul.assoc, choose_mul_fact_mul_fact H])) theorem fact_mul_fact_dvd_fact {n k : ℕ} (H : k ≤ n) : fact k * fact (n - k) ∣ fact n := by rewrite [-choose_mul_fact_mul_fact H, mul.assoc]; apply dvd_mul_left end nat
f0573e65381323127faca1ac66499f3f99416af1
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/elabAsElim.lean
1b1352bd977f632afe9bd81316151d2405438d88
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
2,535
lean
inductive Vec (α : Type u) : Nat → Type u | nil : Vec α 0 | cons : α → Vec α n → Vec α (n+1) def f1 (xs : Vec α n) : Nat := Vec.casesOn xs 0 fun _ _ => 1 def f2 (xs : Vec α n) : Nat := xs.casesOn 0 -- Error insufficient number of arguments def f3 (x : Nat) : Nat → (Nat → Nat) → Nat := x.casesOn def f4 (xs : List Nat) : xs ≠ [] → xs.length > 0 := xs.casesOn (by intros; contradiction) (by intros; simp_arith) def f5 (xs : List Nat) (h : xs ≠ []) : xs.length > 0 := xs.casesOn (by intros; contradiction) (by intros; simp_arith) h def f6 (x : Nat) := 2 * x.casesOn 0 id example : f6 (x+1) = 2*x := rfl def f7 (xs : Vec α n) : Nat := xs.casesOn (a := 10) 0 -- Error unused named args def f8 (xs : List Nat) : xs ≠ [] → xs.length > 0 := @List.casesOn _ (fun xs => xs ≠ [] → xs.length > 0) xs (by dsimp; intros; contradiction) (by dsimp; intros; simp_arith) def f5' (xs : List Nat) (h : xs ≠ []) : xs.length > 0 := xs.casesOn (fun h => absurd rfl h) (fun _ _ _ => Nat.zero_lt_succ ..) h example (h₁ : a = b) (h₂ : b = c) : a = c := Eq.rec h₂ h₁.symm @[elab_as_elim] theorem subst {p : (b : α) → a = b → Prop} (h₁ : a = b) (h₂ : p a rfl) : p b h₁ := by cases h₁ assumption example (h₁ : a = b) (h₂ : b = c) : a = c := subst h₁.symm h₂ theorem not_or_not : (¬p ∨ ¬q) → ¬(p ∧ q) := λ h ⟨hp, hq⟩ => h.rec (λ h1 => h1 hp) (λ h2 => h2 hq) structure Point where x : Nat theorem PointExt_lean4 (p : Point) : forall (q : Point) (h1 : Point.x p = Point.x q), p = q := Point.recOn p <| fun z1 q => Point.recOn q $ fun z2 (hA : Point.x (Point.mk z1) = Point.x (Point.mk z2)) => congrArg Point.mk hA inductive pos_num : Type | one : pos_num | bit1 : pos_num → pos_num | bit0 : pos_num → pos_num inductive num : Type | zero : num | pos : pos_num → num inductive znum : Type | zero : znum | pos : pos_num → znum | neg : pos_num → znum def pos_num.pred' : pos_num → num | one => .zero | bit0 n => num.pos (num.casesOn (pred' n) one bit1) | bit1 n => num.pos (bit0 n) protected def znum.bit1 : znum → znum | zero => pos .one | pos n => pos (pos_num.bit1 n) | neg n => neg (num.casesOn (pos_num.pred' n) .one pos_num.bit1) example (h : False) : a = c := h.rec example (h : False) : a = c := h.elim noncomputable def f : Nat → Nat := Nat.rec 0 (fun x _ => x) example : ∀ x, x ≥ 0 := Nat.rec (Nat.le_refl 0) (fun _ ih => Nat.le_succ_of_le ih)
2edafecda947b35f5a8574af0770e22c2d398596
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/byCasesMetaM.lean
b28e8dd5f3873cfeba6432832e2f1e1e646c4872
[ "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
537
lean
import Lean axiom ex (p q : Prop) (h : p ∧ q) : q ∧ q open Lean in open Lean.Meta in def test : MetaM Unit := do let type := (← getConstInfo ``ex).type let mvar ← mkFreshExprMVar type let (#[p, q, h], mvarId) ← introNP mvar.mvarId! 3 | throwError "unexpected" trace[Meta.debug] "{MessageData.ofGoal mvarId}" let (s₁, s₂) ← byCases mvarId (mkFVar p) `hAux trace[Meta.debug] "{MessageData.ofGoal s₁.mvarId}\n------\n{MessageData.ofGoal s₂.mvarId}" return () set_option trace.Meta.debug true #eval test
b9624db3feb6d1c30560d2632f50609b6b7aec50
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/tests/lean/decimals.lean
26c0504b3f53b05e7224d20c0522593c27849dd5
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
241
lean
#check 1.2 #check 1.2 + 2.3 #check 1.0 #eval 1.2 + 2.3 #check 1. #check 3.1416 theorem ex : 31416e-4 = 3.1416 := rfl #eval 3.4e-100 * 1e98 #eval 12.3e90 * 1E-90 #eval 3.00e-100 * 1e100 #eval 3.00e-100 * 1.e100 #eval 3.00e-100 * 1.0e100
cc170cef362b9ba960e2ae0cb655317a8878f215
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/locally_convex/weak_dual.lean
5d601abe1bc309b803344ffac06e371f33b80dcb
[ "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
5,440
lean
/- Copyright (c) 2022 Moritz Doll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Moritz Doll -/ import topology.algebra.module.weak_dual import analysis.normed.field.basic import analysis.locally_convex.with_seminorms /-! # Weak Dual in Topological Vector Spaces We prove that the weak topology induced by a bilinear form `B : E →ₗ[𝕜] F →ₗ[𝕜] 𝕜` is locally convex and we explicit give a neighborhood basis in terms of the family of seminorms `λ x, ‖B x y‖` for `y : F`. ## Main definitions * `linear_map.to_seminorm`: turn a linear form `f : E →ₗ[𝕜] 𝕜` into a seminorm `λ x, ‖f x‖`. * `linear_map.to_seminorm_family`: turn a bilinear form `B : E →ₗ[𝕜] F →ₗ[𝕜] 𝕜` into a map `F → seminorm 𝕜 E`. ## Main statements * `linear_map.has_basis_weak_bilin`: the seminorm balls of `B.to_seminorm_family` form a neighborhood basis of `0` in the weak topology. * `linear_map.to_seminorm_family.with_seminorms`: the topology of a weak space is induced by the family of seminorm `B.to_seminorm_family`. * `weak_bilin.locally_convex_space`: a spaced endowed with a weak topology is locally convex. ## References * [Bourbaki, *Topological Vector Spaces*][bourbaki1987] ## Tags weak dual, seminorm -/ variables {𝕜 E F ι : Type*} open_locale topology section bilin_form namespace linear_map variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E] [add_comm_group F] [module 𝕜 F] /-- Construct a seminorm from a linear form `f : E →ₗ[𝕜] 𝕜` over a normed field `𝕜` by `λ x, ‖f x‖` -/ def to_seminorm (f : E →ₗ[𝕜] 𝕜) : seminorm 𝕜 E := (norm_seminorm 𝕜 𝕜).comp f lemma coe_to_seminorm {f : E →ₗ[𝕜] 𝕜} : ⇑f.to_seminorm = λ x, ‖f x‖ := rfl @[simp] lemma to_seminorm_apply {f : E →ₗ[𝕜] 𝕜} {x : E} : f.to_seminorm x = ‖f x‖ := rfl lemma to_seminorm_ball_zero {f : E →ₗ[𝕜] 𝕜} {r : ℝ} : seminorm.ball f.to_seminorm 0 r = { x : E | ‖f x‖ < r} := by simp only [seminorm.ball_zero_eq, to_seminorm_apply] lemma to_seminorm_comp (f : F →ₗ[𝕜] 𝕜) (g : E →ₗ[𝕜] F) : f.to_seminorm.comp g = (f.comp g).to_seminorm := by { ext, simp only [seminorm.comp_apply, to_seminorm_apply, coe_comp] } /-- Construct a family of seminorms from a bilinear form. -/ def to_seminorm_family (B : E →ₗ[𝕜] F →ₗ[𝕜] 𝕜) : seminorm_family 𝕜 E F := λ y, (B.flip y).to_seminorm @[simp] lemma to_seminorm_family_apply {B : E →ₗ[𝕜] F →ₗ[𝕜] 𝕜} {x y} : (B.to_seminorm_family y) x = ‖B x y‖ := rfl end linear_map end bilin_form section topology variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E] [add_comm_group F] [module 𝕜 F] variables [nonempty ι] variables {B : E →ₗ[𝕜] F →ₗ[𝕜] 𝕜} lemma linear_map.has_basis_weak_bilin (B : E →ₗ[𝕜] F →ₗ[𝕜] 𝕜) : (𝓝 (0 : weak_bilin B)).has_basis B.to_seminorm_family.basis_sets id := begin let p := B.to_seminorm_family, rw [nhds_induced, nhds_pi], simp only [map_zero, linear_map.zero_apply], have h := @metric.nhds_basis_ball 𝕜 _ 0, have h' := filter.has_basis_pi (λ (i : F), h), have h'' := filter.has_basis.comap (λ x y, B x y) h', refine h''.to_has_basis _ _, { rintros (U : set F × (F → ℝ)) hU, cases hU with hU₁ hU₂, simp only [id.def], let U' := hU₁.to_finset, by_cases hU₃ : U.fst.nonempty, { have hU₃' : U'.nonempty := hU₁.to_finset_nonempty.mpr hU₃, refine ⟨(U'.sup p).ball 0 $ U'.inf' hU₃' U.snd, p.basis_sets_mem _ $ (finset.lt_inf'_iff _).2 $ λ y hy, hU₂ y $ (hU₁.mem_to_finset).mp hy, λ x hx y hy, _⟩, simp only [set.mem_preimage, set.mem_pi, mem_ball_zero_iff], rw seminorm.mem_ball_zero at hx, rw ←linear_map.to_seminorm_family_apply, have hyU' : y ∈ U' := (set.finite.mem_to_finset hU₁).mpr hy, have hp : p y ≤ U'.sup p := finset.le_sup hyU', refine lt_of_le_of_lt (hp x) (lt_of_lt_of_le hx _), exact finset.inf'_le _ hyU' }, rw set.not_nonempty_iff_eq_empty.mp hU₃, simp only [set.empty_pi, set.preimage_univ, set.subset_univ, and_true], exact Exists.intro ((p 0).ball 0 1) (p.basis_sets_singleton_mem 0 one_pos) }, rintros U (hU : U ∈ p.basis_sets), rw seminorm_family.basis_sets_iff at hU, rcases hU with ⟨s, r, hr, hU⟩, rw hU, refine ⟨(s, λ _, r), ⟨by simp only [s.finite_to_set], λ y hy, hr⟩, λ x hx, _⟩, simp only [set.mem_preimage, set.mem_pi, finset.mem_coe, mem_ball_zero_iff] at hx, simp only [id.def, seminorm.mem_ball, sub_zero], refine seminorm.finset_sup_apply_lt hr (λ y hy, _), rw linear_map.to_seminorm_family_apply, exact hx y hy, end lemma linear_map.weak_bilin_with_seminorms (B : E →ₗ[𝕜] F →ₗ[𝕜] 𝕜) : with_seminorms (linear_map.to_seminorm_family B : F → seminorm 𝕜 (weak_bilin B)) := seminorm_family.with_seminorms_of_has_basis _ B.has_basis_weak_bilin end topology section locally_convex variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E] [add_comm_group F] [module 𝕜 F] variables [nonempty ι] [normed_space ℝ 𝕜] [module ℝ E] [is_scalar_tower ℝ 𝕜 E] instance {B : E →ₗ[𝕜] F →ₗ[𝕜] 𝕜} : locally_convex_space ℝ (weak_bilin B) := (B.weak_bilin_with_seminorms).to_locally_convex_space end locally_convex
c7fb0268d123c9f2cf7db8de16f58b56e4554dc6
290f65d8de0088e3098f612884d54e5b714d7862
/src/affine_algebraic_set/union.lean
8f06c0cd6f85bf955e07d63e643fd42aa8d4a478
[ "Apache-2.0" ]
permissive
auhlmann/M4P33
ec775fd53610427b35f59ef84d469c30511de24e
dc2586aa3a8e0d916fc0795df592a996c89c85bb
refs/heads/master
1,607,862,664,432
1,579,796,968,000
1,579,796,968,000
234,415,945
0
0
Apache-2.0
1,579,210,321,000
1,579,210,320,000
null
UTF-8
Lean
false
false
7,376
lean
/- Algebraic geometry lecture 1: The union of two algebraic sets is an algebraic set. Kevin Buzzard -/ import affine_algebraic_set.basic -- the basic theory of affine algebraic sets. /- # The union of two affine algebraic sets is affine. Let k be a field and let n be a natural number. We prove the following theorem in this file: Theorem. If V and W are two affine algebraic subsets of kⁿ then their union V ∪ W is also an affine algebraic subset of kⁿ. Lean version: `def union (V W : affine_algebraic_set k n) : affine_algebraic_set k n` Maths proof: if V is cut out by the set S ⊆ k[X_1,X_2,…,X_n] and W is cut out by T, then we claim V ∪ W is cut out by the set ST := { s*t | s ∈ S and t ∈ T}. To prove that the set cut out by ST equals V ∪ W, we prove both inclusions separately. One inclusion is very easy. If x ∈ V ∪ W then either every element of S vanishes at x or every element of T vanishes on x, and either way every element of ST vanishes at x. Conversely, if x vanishes at every element of ST, then we want to prove that x ∈ V ∪ W. If x is in V then we're done. If not, then this means that there exists some s ∈ S with s(x) ≠ 0. Then for every t ∈ T, we have s(x)t(x)=st(x)=0, and hence t(x)=0, which implies that x is in W. ## Implementation notes I defined an affine algebraic set to be the zeros of an arbitrary set of functions, as opposed to just a finite set. We will see later on that these definitions are equivalent. If V is an affine algebraic set, then V is a pair. The first element of the pair is a subset V.carrier ⊆ kⁿ, but we will call this set V as well (there is a coercion from affine algebraic sets to subsets of kⁿ). The second element of the pair is the proof that there exists a subset S of k[X_1,X_2,...,X_n] such that V is cut out by S, by which I mean that V is the set of x ∈ k^n which vanish at each element of S. ## References Martin Orr's lecture notes at https://homepages.warwick.ac.uk/staff/Martin.Orr/2017-8/alg-geom/ ## Tags algebraic geometry, algebraic variety -/ -- end of docstring; code starts here. -- We're proving theorems about affine algebraic sets so the names of the theorems -- should start with "affine_algebraic_set". namespace affine_algebraic_set -- let k be a field variables {k : Type*} [discrete_field k] -- and let n be a natural number variable {n : ℕ} -- We're working with multivariable polynomials, so let's get access to their notation open mv_polynomial -- Now here's a basic fact about affine algebraic sets. /-- The union of two algebraic subsets of kⁿ is an algebraic subset-/ def union (V W : affine_algebraic_set k n) : affine_algebraic_set k n := { carrier := V ∪ W, -- the underlying set is the union of the two sets defining V and W is_algebraic' := -- We now need to prove that the union of V and W is cut out by some set of polynomials. begin -- Now here's the bad news. -- Lean notation for kⁿ is `fin n → k`. -- Lean notation for k[X₁, X₂, ..., Xₙ] is `mv_polynomial (fin n) k`. -- Lean notation for the subsets of X is `set X` -- Let's state what we're trying to prove, using Lean's notation. show ∃ (U : set (mv_polynomial (fin n) k)), -- such that (V : set _) ∪ W = ⋂ f ∈ U, zeros f, -- say S is the set that defines V cases V.is_algebraic with S hS, -- and T is the set that defines W -- (slightly fancier way) rcases W.is_algebraic with ⟨T, hT⟩, -- Now reduce to an unwieldy precise statement about zeros of polynomials rw [hS, hT], -- Our goal is now to come up with a set U such that -- the zeros of U are exactly the union of the zeros of S and of T. -- Here's how to do it. use {u | ∃ (s ∈ S) (t ∈ T), u = s * t}, -- The goal in maths is now -- ⋂ (s ∈ S) zeros(s) ∪ ⋂ (t ∈ T) zeros(t) = ⋂ (u ∈ ST) zeros(u). -- Lean manages to make quite a mess of its display of this. -- To prove that the affine algebraic set cut out by this collection of polynomials -- is precisely the set V ∪ W, we check both inclusions. apply set.subset.antisymm, { -- Here's the easier of the two inclusions. -- say x ∈ V ∪ W, intros x hx, -- it's either in V or W. cases hx with hxV hxW, { -- Say x ∈ V -- We know that x vanishes at every element of S. rw set.mem_Inter at hxV, -- We want to prove x vanishes at every polynomial of the form s * t -- with s ∈ S and t ∈ T. rw set.mem_Inter, -- so let's take an element u of the form s * t rintro u, -- Let's now notice that the goal has got completely out of hand, and -- simplify it back to ∀ s ∈ S and ∀ t ∈ T, (s * t)(x) = 0. suffices : ∀ s ∈ S, ∀ t ∈ T, u = s * t → u.eval x = 0, {rw [set.mem_Inter], rintros ⟨s, hsS, t, htT, rfl⟩, exact this s hsS t htT rfl}, rintro s hs t ht rfl, -- we need to show st(x)=0. -- Because x ∈ V, we have s(x)=0. have hx := set.mem_Inter.1 (hxV s) hs, change s.eval x = 0 at hx, -- It suffices to show s(x)*t(x)=0 rw eval_mul, -- but s(x) = 0, rw hx, -- and now it's obvious apply zero_mul, }, { -- This is the case x ∈ W and it's essentially completely the same as the x ∈ V argument so I won't -- comment it. Some sort of argument with the `wlog` tactic might be able to do this. rw set.mem_Inter at hxW ⊢, rintro u, suffices : ∀ s ∈ S, ∀ t ∈ T, u = s * t → u.eval x = 0, {rw [set.mem_Inter], rintros ⟨s, hsS, t, htT, rfl⟩, exact this s hsS t htT rfl}, rintro s hs t ht rfl, have hx := hxW t, rw set.mem_Inter at hx, replace hx : eval x t = 0 := hx ht, rw eval_mul, rw hx, simp, } }, { -- This is the harder way; we need to check that if x vanishes on every element of S*T, -- then x ∈ V or x ∈ W. intros x hx, have hx' : ∀ u s : mv_polynomial (fin n) k, s ∈ S → ∀ t ∈ T, u = s * t → u.eval x = 0, simpa using hx, classical, -- We now proudly assume the law of the excluded middle. -- If x ∈ V then the result is easy... by_cases hx2 : x ∈ (V : set _), left, rwa ←hS, -- ...so we can assume assume x ∉ V, -- and hence that there's s ∈ S such that s(x) ≠ 0 rw [hS, set.mem_Inter, not_forall] at hx2, cases hx2 with s hs, have hs2 : s ∈ S ∧ ¬eval x s = 0, simpa using hs, cases hs2 with hsS hns, -- we now show x ∈ W right, rw set.mem_Inter, -- Say t ∈ T intro t, -- We want to prove that t(x) = 0. suffices : t ∈ T → eval x t = 0, simpa, intro ht, -- Now by assumption, x vanishes on s * t. replace hx' := hx' (s * t) s hsS t ht rfl, -- so s(x) * t(x) = 0 rw eval_mul at hx', -- so either s(x) or t(x) = 0, but we chose s such that s(x) ≠ 0. cases mul_eq_zero.1 hx' with hxs hxt, -- So the case s(x) = 0 is a contradiction contradiction, -- and t(x) = 0 is what we wanted to prove assumption } end } end affine_algebraic_set
2d8b03a8939858e4a090638ed831846081b1d033
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/covariant_and_contravariant.lean
5a904bd7f3a5a12c8397ad97f9e60e40f2194053
[ "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
13,550
lean
/- Copyright (c) 2021 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import algebra.group.defs import order.basic import order.monotone /-! # Covariants and contravariants This file contains general lemmas and instances to work with the interactions between a relation and an action on a Type. The intended application is the splitting of the ordering from the algebraic assumptions on the operations in the `ordered_[...]` hierarchy. The strategy is to introduce two more flexible typeclasses, `covariant_class` and `contravariant_class`: * `covariant_class` models the implication `a ≤ b → c * a ≤ c * b` (multiplication is monotone), * `contravariant_class` models the implication `a * b < a * c → b < c`. Since `co(ntra)variant_class` takes as input the operation (typically `(+)` or `(*)`) and the order relation (typically `(≤)` or `(<)`), these are the only two typeclasses that I have used. The general approach is to formulate the lemma that you are interested in and prove it, with the `ordered_[...]` typeclass of your liking. After that, you convert the single typeclass, say `[ordered_cancel_monoid M]`, into three typeclasses, e.g. `[left_cancel_semigroup M] [partial_order M] [covariant_class M M (function.swap (*)) (≤)]` and have a go at seeing if the proof still works! Note that it is possible to combine several co(ntra)variant_class assumptions together. Indeed, the usual ordered typeclasses arise from assuming the pair `[covariant_class M M (*) (≤)] [contravariant_class M M (*) (<)]` on top of order/algebraic assumptions. A formal remark is that normally `covariant_class` uses the `(≤)`-relation, while `contravariant_class` uses the `(<)`-relation. This need not be the case in general, but seems to be the most common usage. In the opposite direction, the implication ```lean [semigroup α] [partial_order α] [contravariant_class α α (*) (≤)] => left_cancel_semigroup α ``` holds -- note the `co*ntra*` assumption on the `(≤)`-relation. # Formalization notes We stick to the convention of using `function.swap (*)` (or `function.swap (+)`), for the typeclass assumptions, since `function.swap` is slightly better behaved than `flip`. However, sometimes as a **non-typeclass** assumption, we prefer `flip (*)` (or `flip (+)`), as it is easier to use. -/ -- TODO: convert `has_exists_mul_of_le`, `has_exists_add_of_le`? -- TODO: relationship with `con/add_con` -- TODO: include equivalence of `left_cancel_semigroup` with -- `semigroup partial_order contravariant_class α α (*) (≤)`? -- TODO : use ⇒, as per Eric's suggestion? See -- https://leanprover.zulipchat.com/#narrow/stream/116395-maths/topic/ordered.20stuff/near/236148738 -- for a discussion. open function section variants variables {M N : Type*} (μ : M → N → N) (r : N → N → Prop) variables (M N) /-- `covariant` is useful to formulate succintly statements about the interactions between an action of a Type on another one and a relation on the acted-upon Type. See the `covariant_class` doc-string for its meaning. -/ def covariant : Prop := ∀ (m) {n₁ n₂}, r n₁ n₂ → r (μ m n₁) (μ m n₂) /-- `contravariant` is useful to formulate succintly statements about the interactions between an action of a Type on another one and a relation on the acted-upon Type. See the `contravariant_class` doc-string for its meaning. -/ def contravariant : Prop := ∀ (m) {n₁ n₂}, r (μ m n₁) (μ m n₂) → r n₁ n₂ /-- Given an action `μ` of a Type `M` on a Type `N` and a relation `r` on `N`, informally, the `covariant_class` says that "the action `μ` preserves the relation `r`." More precisely, the `covariant_class` is a class taking two Types `M N`, together with an "action" `μ : M → N → N` and a relation `r : N → N → Prop`. Its unique field `elim` is the assertion that for all `m ∈ M` and all elements `n₁, n₂ ∈ N`, if the relation `r` holds for the pair `(n₁, n₂)`, then, the relation `r` also holds for the pair `(μ m n₁, μ m n₂)`, obtained from `(n₁, n₂)` by acting upon it by `m`. If `m : M` and `h : r n₁ n₂`, then `covariant_class.elim m h : r (μ m n₁) (μ m n₂)`. -/ @[protect_proj] class covariant_class : Prop := (elim : covariant M N μ r) /-- Given an action `μ` of a Type `M` on a Type `N` and a relation `r` on `N`, informally, the `contravariant_class` says that "if the result of the action `μ` on a pair satisfies the relation `r`, then the initial pair satisfied the relation `r`." More precisely, the `contravariant_class` is a class taking two Types `M N`, together with an "action" `μ : M → N → N` and a relation `r : N → N → Prop`. Its unique field `elim` is the assertion that for all `m ∈ M` and all elements `n₁, n₂ ∈ N`, if the relation `r` holds for the pair `(μ m n₁, μ m n₂)` obtained from `(n₁, n₂)` by acting upon it by `m`, then, the relation `r` also holds for the pair `(n₁, n₂)`. If `m : M` and `h : r (μ m n₁) (μ m n₂)`, then `contravariant_class.elim m h : r n₁ n₂`. -/ @[protect_proj] class contravariant_class : Prop := (elim : contravariant M N μ r) lemma rel_iff_cov [covariant_class M N μ r] [contravariant_class M N μ r] (m : M) {a b : N} : r (μ m a) (μ m b) ↔ r a b := ⟨contravariant_class.elim _, covariant_class.elim _⟩ section flip variables {M N μ r} lemma covariant.flip (h : covariant M N μ r) : covariant M N μ (flip r) := λ a b c hbc, h a hbc lemma contravariant.flip (h : contravariant M N μ r) : contravariant M N μ (flip r) := λ a b c hbc, h a hbc end flip section covariant variables {M N μ r} [covariant_class M N μ r] lemma act_rel_act_of_rel (m : M) {a b : N} (ab : r a b) : r (μ m a) (μ m b) := covariant_class.elim _ ab @[to_additive] lemma group.covariant_iff_contravariant [group N] : covariant N N (*) r ↔ contravariant N N (*) r := begin refine ⟨λ h a b c bc, _, λ h a b c bc, _⟩, { rw [← inv_mul_cancel_left a b, ← inv_mul_cancel_left a c], exact h a⁻¹ bc }, { rw [← inv_mul_cancel_left a b, ← inv_mul_cancel_left a c] at bc, exact h a⁻¹ bc } end @[to_additive] lemma group.covconv [group N] [covariant_class N N (*) r] : contravariant_class N N (*) r := ⟨group.covariant_iff_contravariant.mp covariant_class.elim⟩ section is_trans variables [is_trans N r] (m n : M) {a b c d : N} /- Lemmas with 3 elements. -/ lemma act_rel_of_rel_of_act_rel (ab : r a b) (rl : r (μ m b) c) : r (μ m a) c := trans (act_rel_act_of_rel m ab) rl lemma rel_act_of_rel_of_rel_act (ab : r a b) (rr : r c (μ m a)) : r c (μ m b) := trans rr (act_rel_act_of_rel _ ab) end is_trans end covariant /- Lemma with 4 elements. -/ section M_eq_N variables {M N μ r} {mu : N → N → N} [is_trans N r] [covariant_class N N mu r] [covariant_class N N (swap mu) r] {a b c d : N} lemma act_rel_act_of_rel_of_rel (ab : r a b) (cd : r c d) : r (mu a c) (mu b d) := trans (act_rel_act_of_rel c ab : _) (act_rel_act_of_rel b cd) end M_eq_N section contravariant variables {M N μ r} [contravariant_class M N μ r] lemma rel_of_act_rel_act (m : M) {a b : N} (ab : r (μ m a) (μ m b)) : r a b := contravariant_class.elim _ ab section is_trans variables [is_trans N r] (m n : M) {a b c d : N} /- Lemmas with 3 elements. -/ lemma act_rel_of_act_rel_of_rel_act_rel (ab : r (μ m a) b) (rl : r (μ m b) (μ m c)) : r (μ m a) c := trans ab (rel_of_act_rel_act m rl) lemma rel_act_of_act_rel_act_of_rel_act (ab : r (μ m a) (μ m b)) (rr : r b (μ m c)) : r a (μ m c) := trans (rel_of_act_rel_act m ab) rr end is_trans end contravariant section monotone variables {α : Type*} {M N μ} [preorder α] [preorder N] variable {f : N → α} /-- The partial application of a constant to a covariant operator is monotone. -/ lemma covariant.monotone_of_const [covariant_class M N μ (≤)] (m : M) : monotone (μ m) := λ a b ha, covariant_class.elim m ha /-- A monotone function remains monotone when composed with the partial application of a covariant operator. E.g., `∀ (m : ℕ), monotone f → monotone (λ n, f (m + n))`. -/ lemma monotone.covariant_of_const [covariant_class M N μ (≤)] (hf : monotone f) (m : M) : monotone (λ n, f (μ m n)) := hf.comp $ covariant.monotone_of_const m /-- Same as `monotone.covariant_of_const`, but with the constant on the other side of the operator. E.g., `∀ (m : ℕ), monotone f → monotone (λ n, f (n + m))`. -/ lemma monotone.covariant_of_const' {μ : N → N → N} [covariant_class N N (swap μ) (≤)] (hf : monotone f) (m : N) : monotone (λ n, f (μ n m)) := hf.comp $ covariant.monotone_of_const m /-- Dual of `monotone.covariant_of_const` -/ lemma antitone.covariant_of_const [covariant_class M N μ (≤)] (hf : antitone f) (m : M) : antitone (λ n, f (μ m n)) := hf.comp_monotone $ covariant.monotone_of_const m /-- Dual of `monotone.covariant_of_const'` -/ lemma antitone.covariant_of_const' {μ : N → N → N} [covariant_class N N (swap μ) (≤)] (hf : antitone f) (m : N) : antitone (λ n, f (μ n m)) := hf.comp_monotone $ covariant.monotone_of_const m end monotone lemma covariant_le_of_covariant_lt [partial_order N] : covariant M N μ (<) → covariant M N μ (≤) := begin refine λ h a b c bc, _, rcases le_iff_eq_or_lt.mp bc with rfl | bc, { exact rfl.le }, { exact (h _ bc).le } end lemma contravariant_lt_of_contravariant_le [partial_order N] : contravariant M N μ (≤) → contravariant M N μ (<) := begin refine λ h a b c bc, lt_iff_le_and_ne.mpr ⟨h a bc.le, _⟩, rintro rfl, exact lt_irrefl _ bc, end lemma covariant_le_iff_contravariant_lt [linear_order N] : covariant M N μ (≤) ↔ contravariant M N μ (<) := ⟨ λ h a b c bc, not_le.mp (λ k, not_le.mpr bc (h _ k)), λ h a b c bc, not_lt.mp (λ k, not_lt.mpr bc (h _ k))⟩ lemma covariant_lt_iff_contravariant_le [linear_order N] : covariant M N μ (<) ↔ contravariant M N μ (≤) := ⟨ λ h a b c bc, not_lt.mp (λ k, not_lt.mpr bc (h _ k)), λ h a b c bc, not_le.mp (λ k, not_le.mpr bc (h _ k))⟩ @[to_additive] lemma covariant_flip_mul_iff [comm_semigroup N] : covariant N N (flip (*)) (r) ↔ covariant N N (*) (r) := by rw is_symm_op.flip_eq @[to_additive] lemma contravariant_flip_mul_iff [comm_semigroup N] : contravariant N N (flip (*)) (r) ↔ contravariant N N (*) (r) := by rw is_symm_op.flip_eq @[to_additive] instance contravariant_mul_lt_of_covariant_mul_le [has_mul N] [linear_order N] [covariant_class N N (*) (≤)] : contravariant_class N N (*) (<) := { elim := (covariant_le_iff_contravariant_lt N N (*)).mp covariant_class.elim } @[to_additive] instance covariant_mul_lt_of_contravariant_mul_le [has_mul N] [linear_order N] [contravariant_class N N (*) (≤)] : covariant_class N N (*) (<) := { elim := (covariant_lt_iff_contravariant_le N N (*)).mpr contravariant_class.elim } @[to_additive] instance covariant_swap_mul_le_of_covariant_mul_le [comm_semigroup N] [has_le N] [covariant_class N N (*) (≤)] : covariant_class N N (swap (*)) (≤) := { elim := (covariant_flip_mul_iff N (≤)).mpr covariant_class.elim } @[to_additive] instance contravariant_swap_mul_le_of_contravariant_mul_le [comm_semigroup N] [has_le N] [contravariant_class N N (*) (≤)] : contravariant_class N N (swap (*)) (≤) := { elim := (contravariant_flip_mul_iff N (≤)).mpr contravariant_class.elim } @[to_additive] instance contravariant_swap_mul_lt_of_contravariant_mul_lt [comm_semigroup N] [has_lt N] [contravariant_class N N (*) (<)] : contravariant_class N N (swap (*)) (<) := { elim := (contravariant_flip_mul_iff N (<)).mpr contravariant_class.elim } @[to_additive] instance covariant_swap_mul_lt_of_covariant_mul_lt [comm_semigroup N] [has_lt N] [covariant_class N N (*) (<)] : covariant_class N N (swap (*)) (<) := { elim := (covariant_flip_mul_iff N (<)).mpr covariant_class.elim } @[to_additive] instance left_cancel_semigroup.covariant_mul_lt_of_covariant_mul_le [left_cancel_semigroup N] [partial_order N] [covariant_class N N (*) (≤)] : covariant_class N N (*) (<) := { elim := λ a b c bc, by { cases lt_iff_le_and_ne.mp bc with bc cb, exact lt_iff_le_and_ne.mpr ⟨covariant_class.elim a bc, (mul_ne_mul_right a).mpr cb⟩ } } @[to_additive] instance right_cancel_semigroup.covariant_swap_mul_lt_of_covariant_swap_mul_le [right_cancel_semigroup N] [partial_order N] [covariant_class N N (swap (*)) (≤)] : covariant_class N N (swap (*)) (<) := { elim := λ a b c bc, by { cases lt_iff_le_and_ne.mp bc with bc cb, exact lt_iff_le_and_ne.mpr ⟨covariant_class.elim a bc, (mul_ne_mul_left a).mpr cb⟩ } } @[to_additive] instance left_cancel_semigroup.contravariant_mul_le_of_contravariant_mul_lt [left_cancel_semigroup N] [partial_order N] [contravariant_class N N (*) (<)] : contravariant_class N N (*) (≤) := { elim := λ a b c bc, by { cases le_iff_eq_or_lt.mp bc with h h, { exact ((mul_right_inj a).mp h).le }, { exact (contravariant_class.elim _ h).le } } } @[to_additive] instance right_cancel_semigroup.contravariant_swap_mul_le_of_contravariant_swap_mul_lt [right_cancel_semigroup N] [partial_order N] [contravariant_class N N (swap (*)) (<)] : contravariant_class N N (swap (*)) (≤) := { elim := λ a b c bc, by { cases le_iff_eq_or_lt.mp bc with h h, { exact ((mul_left_inj a).mp h).le }, { exact (contravariant_class.elim _ h).le } } } end variants
d31ca153d49161d7bf61d1df3c3723b6ea1b441d
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/deprecated/subring.lean
4ba040b26d7a065f321d72c923b3e34e9e80ec32
[ "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
8,209
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import deprecated.subgroup import deprecated.group universes u v open group variables {R : Type u} [ring R] /-- `S` is a subring: a set containing 1 and closed under multiplication, addition and and additive inverse. -/ class is_subring (S : set R) extends is_add_subgroup S, is_submonoid S : Prop. instance subset.ring {S : set R} [is_subring S] : ring S := { left_distrib := λ x y z, subtype.eq $ left_distrib x.1 y.1 z.1, right_distrib := λ x y z, subtype.eq $ right_distrib x.1 y.1 z.1, .. subtype.add_comm_group, .. subtype.monoid } instance subtype.ring {S : set R} [is_subring S] : ring (subtype S) := subset.ring namespace ring_hom instance is_subring_preimage {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) (s : set S) [is_subring s] : is_subring (f ⁻¹' s) := {} instance is_subring_image {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) (s : set R) [is_subring s] : is_subring (f '' s) := {} instance is_subring_set_range {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) : is_subring (set.range f) := {} end ring_hom /-- Restrict the codomain of a ring homomorphism to a subring that includes the range. -/ def ring_hom.cod_restrict {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) (s : set S) [is_subring s] (h : ∀ x, f x ∈ s) : R →+* s := { to_fun := λ x, ⟨f x, h x⟩, map_add' := λ x y, subtype.eq $ f.map_add x y, map_zero' := subtype.eq f.map_zero, map_mul' := λ x y, subtype.eq $ f.map_mul x y, map_one' := subtype.eq f.map_one } /-- Coersion `S → R` as a ring homormorphism-/ def is_subring.subtype (S : set R) [is_subring S] : S →+* R := ⟨coe, rfl, λ _ _, rfl, rfl, λ _ _, rfl⟩ @[simp] lemma is_subring.coe_subtype {S : set R} [is_subring S] : ⇑(is_subring.subtype S) = coe := rfl variables {cR : Type u} [comm_ring cR] instance subset.comm_ring {S : set cR} [is_subring S] : comm_ring S := { mul_comm := λ x y, subtype.eq $ mul_comm x.1 y.1, .. subset.ring } instance subtype.comm_ring {S : set cR} [is_subring S] : comm_ring (subtype S) := subset.comm_ring instance subring.domain {D : Type*} [integral_domain D] (S : set D) [is_subring S] : integral_domain S := { exists_pair_ne := ⟨0, 1, mt subtype.ext_iff_val.1 zero_ne_one⟩, eq_zero_or_eq_zero_of_mul_eq_zero := λ ⟨x, hx⟩ ⟨y, hy⟩, by { simp only [subtype.ext_iff_val, subtype.coe_mk], exact eq_zero_or_eq_zero_of_mul_eq_zero }, .. subset.comm_ring } instance is_subring.inter (S₁ S₂ : set R) [is_subring S₁] [is_subring S₂] : is_subring (S₁ ∩ S₂) := { } instance is_subring.Inter {ι : Sort*} (S : ι → set R) [h : ∀ y : ι, is_subring (S y)] : is_subring (set.Inter S) := { } lemma is_subring_Union_of_directed {ι : Type*} [hι : nonempty ι] (s : ι → set R) [∀ i, is_subring (s i)] (directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) : is_subring (⋃i, s i) := { to_is_add_subgroup := is_add_subgroup_Union_of_directed s directed, to_is_submonoid := is_submonoid_Union_of_directed s directed } namespace ring def closure (s : set R) := add_group.closure (monoid.closure s) variable {s : set R} local attribute [reducible] closure theorem exists_list_of_mem_closure {a : R} (h : a ∈ closure s) : (∃ L : list (list R), (∀ l ∈ L, ∀ x ∈ l, x ∈ s ∨ x = (-1:R)) ∧ (L.map list.prod).sum = a) := add_group.in_closure.rec_on h (λ x hx, match x, monoid.exists_list_of_mem_closure hx with | _, ⟨L, h1, rfl⟩ := ⟨[L], list.forall_mem_singleton.2 (λ r hr, or.inl (h1 r hr)), zero_add _⟩ end) ⟨[], list.forall_mem_nil _, rfl⟩ (λ b _ ih, match b, ih with | _, ⟨L1, h1, rfl⟩ := ⟨L1.map (list.cons (-1)), λ L2 h2, match L2, list.mem_map.1 h2 with | _, ⟨L3, h3, rfl⟩ := list.forall_mem_cons.2 ⟨or.inr rfl, h1 L3 h3⟩ end, by simp only [list.map_map, (∘), list.prod_cons, neg_one_mul]; exact list.rec_on L1 neg_zero.symm (λ hd tl ih, by rw [list.map_cons, list.sum_cons, ih, list.map_cons, list.sum_cons, neg_add])⟩ end) (λ r1 r2 hr1 hr2 ih1 ih2, match r1, r2, ih1, ih2 with | _, _, ⟨L1, h1, rfl⟩, ⟨L2, h2, rfl⟩ := ⟨L1 ++ L2, list.forall_mem_append.2 ⟨h1, h2⟩, by rw [list.map_append, list.sum_append]⟩ end) @[elab_as_eliminator] protected theorem in_closure.rec_on {C : R → Prop} {x : R} (hx : x ∈ closure s) (h1 : C 1) (hneg1 : C (-1)) (hs : ∀ z ∈ s, ∀ n, C n → C (z * n)) (ha : ∀ {x y}, C x → C y → C (x + y)) : C x := begin have h0 : C 0 := add_neg_self (1:R) ▸ ha h1 hneg1, rcases exists_list_of_mem_closure hx with ⟨L, HL, rfl⟩, clear hx, induction L with hd tl ih, { exact h0 }, rw list.forall_mem_cons at HL, suffices : C (list.prod hd), { rw [list.map_cons, list.sum_cons], exact ha this (ih HL.2) }, replace HL := HL.1, clear ih tl, suffices : ∃ L : list R, (∀ x ∈ L, x ∈ s) ∧ (list.prod hd = list.prod L ∨ list.prod hd = -list.prod L), { rcases this with ⟨L, HL', HP | HP⟩, { rw HP, clear HP HL hd, induction L with hd tl ih, { exact h1 }, rw list.forall_mem_cons at HL', rw list.prod_cons, exact hs _ HL'.1 _ (ih HL'.2) }, rw HP, clear HP HL hd, induction L with hd tl ih, { exact hneg1 }, rw [list.prod_cons, neg_mul_eq_mul_neg], rw list.forall_mem_cons at HL', exact hs _ HL'.1 _ (ih HL'.2) }, induction hd with hd tl ih, { exact ⟨[], list.forall_mem_nil _, or.inl rfl⟩ }, rw list.forall_mem_cons at HL, rcases ih HL.2 with ⟨L, HL', HP | HP⟩; cases HL.1 with hhd hhd, { exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inl $ by rw [list.prod_cons, list.prod_cons, HP]⟩ }, { exact ⟨L, HL', or.inr $ by rw [list.prod_cons, hhd, neg_one_mul, HP]⟩ }, { exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inr $ by rw [list.prod_cons, list.prod_cons, HP, neg_mul_eq_mul_neg]⟩ }, { exact ⟨L, HL', or.inl $ by rw [list.prod_cons, hhd, HP, neg_one_mul, neg_neg]⟩ } end instance : is_subring (closure s) := { one_mem := add_group.mem_closure is_submonoid.one_mem, mul_mem := λ a b ha hb, add_group.in_closure.rec_on hb (λ b hb, add_group.in_closure.rec_on ha (λ a ha, add_group.subset_closure (is_submonoid.mul_mem ha hb)) ((zero_mul b).symm ▸ is_add_submonoid.zero_mem) (λ a ha hab, (neg_mul_eq_neg_mul a b) ▸ is_add_subgroup.neg_mem hab) (λ a c ha hc hab hcb, (add_mul a c b).symm ▸ is_add_submonoid.add_mem hab hcb)) ((mul_zero a).symm ▸ is_add_submonoid.zero_mem) (λ b hb hab, (neg_mul_eq_mul_neg a b) ▸ is_add_subgroup.neg_mem hab) (λ b c hb hc hab hac, (mul_add a b c).symm ▸ is_add_submonoid.add_mem hab hac), .. add_group.closure.is_add_subgroup _ } theorem mem_closure {a : R} : a ∈ s → a ∈ closure s := add_group.mem_closure ∘ @monoid.subset_closure _ _ _ _ theorem subset_closure : s ⊆ closure s := λ _, mem_closure theorem closure_subset {t : set R} [is_subring t] : s ⊆ t → closure s ⊆ t := add_group.closure_subset ∘ monoid.closure_subset theorem closure_subset_iff (s t : set R) [is_subring t] : closure s ⊆ t ↔ s ⊆ t := (add_group.closure_subset_iff _ t).trans ⟨set.subset.trans monoid.subset_closure, monoid.closure_subset⟩ theorem closure_mono {s t : set R} (H : s ⊆ t) : closure s ⊆ closure t := closure_subset $ set.subset.trans H subset_closure lemma image_closure {S : Type*} [ring S] (f : R →+* S) (s : set R) : f '' closure s = closure (f '' s) := le_antisymm begin rintros _ ⟨x, hx, rfl⟩, apply in_closure.rec_on hx; intros, { rw [f.map_one], apply is_submonoid.one_mem }, { rw [f.map_neg, f.map_one], apply is_add_subgroup.neg_mem, apply is_submonoid.one_mem }, { rw [f.map_mul], apply is_submonoid.mul_mem; solve_by_elim [subset_closure, set.mem_image_of_mem] }, { rw [f.map_add], apply is_add_submonoid.add_mem, assumption' }, end (closure_subset $ set.image_subset _ subset_closure) end ring
303cd12a685cd7e3bfb05bff52984a3f231ad244
9dc8cecdf3c4634764a18254e94d43da07142918
/src/category_theory/limits/yoneda.lean
8e691accd57e26412bfaadb81d27421ab1daca18
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
5,278
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import category_theory.limits.functor_category /-! # Limit properties relating to the (co)yoneda embedding. We calculate the colimit of `Y ↦ (X ⟶ Y)`, which is just `punit`. (This is used in characterising cofinal functors.) We also show the (co)yoneda embeddings preserve limits and jointly reflect them. -/ open opposite open category_theory open category_theory.limits universes w v u namespace category_theory namespace coyoneda variables {C : Type v} [small_category C] /-- The colimit cocone over `coyoneda.obj X`, with cocone point `punit`. -/ @[simps] def colimit_cocone (X : Cᵒᵖ) : cocone (coyoneda.obj X) := { X := punit, ι := { app := by tidy, } } /-- The proposed colimit cocone over `coyoneda.obj X` is a colimit cocone. -/ @[simps] def colimit_cocone_is_colimit (X : Cᵒᵖ) : is_colimit (colimit_cocone X) := { desc := λ s x, s.ι.app (unop X) (𝟙 _), fac' := λ s Y, by { ext f, convert congr_fun (s.w f).symm (𝟙 (unop X)), simp, }, uniq' := λ s m w, by { ext ⟨⟩, rw ← w, simp, } } instance (X : Cᵒᵖ) : has_colimit (coyoneda.obj X) := has_colimit.mk { cocone := _, is_colimit := colimit_cocone_is_colimit X } /-- The colimit of `coyoneda.obj X` is isomorphic to `punit`. -/ noncomputable def colimit_coyoneda_iso (X : Cᵒᵖ) : colimit (coyoneda.obj X) ≅ punit := colimit.iso_colimit_cocone { cocone := _, is_colimit := colimit_cocone_is_colimit X } end coyoneda variables {C : Type u} [category.{v} C] open limits /-- The yoneda embedding `yoneda.obj X : Cᵒᵖ ⥤ Type v` for `X : C` preserves limits. -/ instance yoneda_preserves_limits (X : C) : preserves_limits (yoneda.obj X) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ K, { preserves := λ c t, { lift := λ s x, quiver.hom.unop (t.lift ⟨op X, λ j, (s.π.app j x).op, λ j₁ j₂ α, _⟩), fac' := λ s j, funext $ λ x, quiver.hom.op_inj (t.fac _ _), uniq' := λ s m w, funext $ λ x, begin refine quiver.hom.op_inj (t.uniq ⟨op X, _, _⟩ _ (λ j, _)), { dsimp, simp [← s.w α] }, -- See library note [dsimp, simp] { exact quiver.hom.unop_inj (congr_fun (w j) x) }, end } } } } /-- The coyoneda embedding `coyoneda.obj X : C ⥤ Type v` for `X : Cᵒᵖ` preserves limits. -/ instance coyoneda_preserves_limits (X : Cᵒᵖ) : preserves_limits (coyoneda.obj X) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ K, { preserves := λ c t, { lift := λ s x, t.lift ⟨unop X, λ j, s.π.app j x, λ j₁ j₂ α, by { dsimp, simp [← s.w α]}⟩, -- See library note [dsimp, simp] fac' := λ s j, funext $ λ x, t.fac _ _, uniq' := λ s m w, funext $ λ x, begin refine (t.uniq ⟨unop X, _⟩ _ (λ j, _)), exact congr_fun (w j) x, end } } } } /-- The yoneda embeddings jointly reflect limits. -/ def yoneda_jointly_reflects_limits (J : Type w) [small_category J] (K : J ⥤ Cᵒᵖ) (c : cone K) (t : Π (X : C), is_limit ((yoneda.obj X).map_cone c)) : is_limit c := let s' : Π (s : cone K), cone (K ⋙ yoneda.obj s.X.unop) := λ s, ⟨punit, λ j _, (s.π.app j).unop, λ j₁ j₂ α, funext $ λ _, quiver.hom.op_inj (s.w α).symm⟩ in { lift := λ s, ((t s.X.unop).lift (s' s) punit.star).op, fac' := λ s j, quiver.hom.unop_inj (congr_fun ((t s.X.unop).fac (s' s) j) punit.star), uniq' := λ s m w, begin apply quiver.hom.unop_inj, suffices : (λ (x : punit), m.unop) = (t s.X.unop).lift (s' s), { apply congr_fun this punit.star }, apply (t _).uniq (s' s) _ (λ j, _), ext, exact quiver.hom.op_inj (w j), end } /-- The coyoneda embeddings jointly reflect limits. -/ def coyoneda_jointly_reflects_limits (J : Type w) [small_category J] (K : J ⥤ C) (c : cone K) (t : Π (X : Cᵒᵖ), is_limit ((coyoneda.obj X).map_cone c)) : is_limit c := let s' : Π (s : cone K), cone (K ⋙ coyoneda.obj (op s.X)) := λ s, ⟨punit, λ j _, s.π.app j, λ j₁ j₂ α, funext $ λ _, (s.w α).symm⟩ in { lift := λ s, (t (op s.X)).lift (s' s) punit.star, fac' := λ s j, congr_fun ((t _).fac (s' s) j) punit.star, uniq' := λ s m w, begin suffices : (λ (x : punit), m) = (t _).lift (s' s), { apply congr_fun this punit.star }, apply (t _).uniq (s' s) _ (λ j, _), ext, exact (w j), end } variables {D : Type u} [small_category D] instance yoneda_functor_preserves_limits : preserves_limits (@yoneda D _) := begin apply preserves_limits_of_evaluation, intro K, change preserves_limits (coyoneda.obj K), apply_instance end instance coyoneda_functor_preserves_limits : preserves_limits (@coyoneda D _) := begin apply preserves_limits_of_evaluation, intro K, change preserves_limits (yoneda.obj K), apply_instance end instance yoneda_functor_reflects_limits : reflects_limits (@yoneda D _) := limits.fully_faithful_reflects_limits _ instance coyoneda_functor_reflects_limits : reflects_limits (@coyoneda D _) := limits.fully_faithful_reflects_limits _ end category_theory
8ca2e101cf88749171a5a61891d83418af8be8b9
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/monoidal/functor_auto.lean
45186a1845f060069a404c1545eac3e3c7884248
[]
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
12,714
lean
/- Copyright (c) 2018 Michael Jendrusch. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Jendrusch, Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.monoidal.category import Mathlib.PostPort universes v₁ v₂ u₁ u₂ l u₃ v₃ namespace Mathlib /-! # (Lax) monoidal functors A lax monoidal functor `F` between monoidal categories `C` and `D` is a functor between the underlying categories equipped with morphisms * `ε : 𝟙_ D ⟶ F.obj (𝟙_ C)` (called the unit morphism) * `μ X Y : (F.obj X) ⊗ (F.obj Y) ⟶ F.obj (X ⊗ Y)` (called the tensorator, or strength). satisfying various axioms. A monoidal functor is a lax monoidal functor for which `ε` and `μ` are isomorphisms. We show that the composition of (lax) monoidal functors gives a (lax) monoidal functor. See also `category_theory.monoidal.functorial` for a typeclass decorating an object-level function with the additional data of a monoidal functor. This is useful when stating that a pre-existing functor is monoidal. See `category_theory.monoidal.natural_transformation` for monoidal natural transformations. We show in `category_theory.monoidal.Mon_` that lax monoidal functors take monoid objects to monoid objects. ## Future work * Oplax monoidal functors. ## References See https://stacks.math.columbia.edu/tag/0FFL. -/ namespace category_theory /-- A lax monoidal functor is a functor `F : C ⥤ D` between monoidal categories, equipped with morphisms `ε : 𝟙 _D ⟶ F.obj (𝟙_ C)` and `μ X Y : F.obj X ⊗ F.obj Y ⟶ F.obj (X ⊗ Y)`, satisfying the the appropriate coherences. -/ -- unit morphism structure lax_monoidal_functor (C : Type u₁) [category C] [monoidal_category C] (D : Type u₂) [category D] [monoidal_category D] extends C ⥤ D where ε : 𝟙_ ⟶ functor.obj _to_functor 𝟙_ μ : (X Y : C) → functor.obj _to_functor X ⊗ functor.obj _to_functor Y ⟶ functor.obj _to_functor (X ⊗ Y) μ_natural' : autoParam (∀ {X Y X' Y' : C} (f : X ⟶ Y) (g : X' ⟶ Y'), (functor.map _to_functor f ⊗ functor.map _to_functor g) ≫ μ Y Y' = μ X X' ≫ functor.map _to_functor (f ⊗ g)) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) associativity' : autoParam (∀ (X Y Z : C), (μ X Y ⊗ 𝟙) ≫ μ (X ⊗ Y) Z ≫ functor.map _to_functor (iso.hom α_) = iso.hom α_ ≫ (𝟙 ⊗ μ Y Z) ≫ μ X (Y ⊗ Z)) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) left_unitality' : autoParam (∀ (X : C), iso.hom λ_ = (ε ⊗ 𝟙) ≫ μ 𝟙_ X ≫ functor.map _to_functor (iso.hom λ_)) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) right_unitality' : autoParam (∀ (X : C), iso.hom ρ_ = (𝟙 ⊗ ε) ≫ μ X 𝟙_ ≫ functor.map _to_functor (iso.hom ρ_)) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) -- tensorator -- associativity of the tensorator -- unitality @[simp] theorem lax_monoidal_functor.μ_natural {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] [monoidal_category D] (c : lax_monoidal_functor C D) {X : C} {Y : C} {X' : C} {Y' : C} (f : X ⟶ Y) (g : X' ⟶ Y') : (functor.map (lax_monoidal_functor.to_functor c) f ⊗ functor.map (lax_monoidal_functor.to_functor c) g) ≫ lax_monoidal_functor.μ c Y Y' = lax_monoidal_functor.μ c X X' ≫ functor.map (lax_monoidal_functor.to_functor c) (f ⊗ g) := sorry @[simp] theorem lax_monoidal_functor.μ_natural_assoc {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] [monoidal_category D] (c : lax_monoidal_functor C D) {X : C} {Y : C} {X' : C} {Y' : C} (f : X ⟶ Y) (g : X' ⟶ Y') : ∀ {X'_1 : D} (f' : functor.obj (lax_monoidal_functor.to_functor c) (Y ⊗ Y') ⟶ X'_1), (functor.map (lax_monoidal_functor.to_functor c) f ⊗ functor.map (lax_monoidal_functor.to_functor c) g) ≫ lax_monoidal_functor.μ c Y Y' ≫ f' = lax_monoidal_functor.μ c X X' ≫ functor.map (lax_monoidal_functor.to_functor c) (f ⊗ g) ≫ f' := sorry @[simp] theorem lax_monoidal_functor.left_unitality {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] [monoidal_category D] (c : lax_monoidal_functor C D) (X : C) : iso.hom λ_ = (lax_monoidal_functor.ε c ⊗ 𝟙) ≫ lax_monoidal_functor.μ c 𝟙_ X ≫ functor.map (lax_monoidal_functor.to_functor c) (iso.hom λ_) := sorry @[simp] theorem lax_monoidal_functor.right_unitality {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] [monoidal_category D] (c : lax_monoidal_functor C D) (X : C) : iso.hom ρ_ = (𝟙 ⊗ lax_monoidal_functor.ε c) ≫ lax_monoidal_functor.μ c X 𝟙_ ≫ functor.map (lax_monoidal_functor.to_functor c) (iso.hom ρ_) := sorry @[simp] theorem lax_monoidal_functor.associativity {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] [monoidal_category D] (c : lax_monoidal_functor C D) (X : C) (Y : C) (Z : C) : (lax_monoidal_functor.μ c X Y ⊗ 𝟙) ≫ lax_monoidal_functor.μ c (X ⊗ Y) Z ≫ functor.map (lax_monoidal_functor.to_functor c) (iso.hom α_) = iso.hom α_ ≫ (𝟙 ⊗ lax_monoidal_functor.μ c Y Z) ≫ lax_monoidal_functor.μ c X (Y ⊗ Z) := sorry -- When `rewrite_search` lands, add @[search] attributes to -- lax_monoidal_functor.μ_natural lax_monoidal_functor.left_unitality -- lax_monoidal_functor.right_unitality lax_monoidal_functor.associativity /-- A monoidal functor is a lax monoidal functor for which the tensorator and unitor as isomorphisms. See https://stacks.math.columbia.edu/tag/0FFL. -/ structure monoidal_functor (C : Type u₁) [category C] [monoidal_category C] (D : Type u₂) [category D] [monoidal_category D] extends lax_monoidal_functor C D where ε_is_iso : autoParam (is_iso (lax_monoidal_functor.ε _to_lax_monoidal_functor)) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.tactic.apply_instance") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "tactic") "apply_instance") []) μ_is_iso : autoParam ((X Y : C) → is_iso (lax_monoidal_functor.μ _to_lax_monoidal_functor X Y)) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.tactic.apply_instance") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "tactic") "apply_instance") []) /-- The unit morphism of a (strong) monoidal functor as an isomorphism. -/ def monoidal_functor.ε_iso {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] [monoidal_category D] (F : monoidal_functor C D) : 𝟙_ ≅ functor.obj (lax_monoidal_functor.to_functor (monoidal_functor.to_lax_monoidal_functor F)) 𝟙_ := as_iso (lax_monoidal_functor.ε (monoidal_functor.to_lax_monoidal_functor F)) /-- The tensorator of a (strong) monoidal functor as an isomorphism. -/ def monoidal_functor.μ_iso {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] [monoidal_category D] (F : monoidal_functor C D) (X : C) (Y : C) : functor.obj (lax_monoidal_functor.to_functor (monoidal_functor.to_lax_monoidal_functor F)) X ⊗ functor.obj (lax_monoidal_functor.to_functor (monoidal_functor.to_lax_monoidal_functor F)) Y ≅ functor.obj (lax_monoidal_functor.to_functor (monoidal_functor.to_lax_monoidal_functor F)) (X ⊗ Y) := as_iso (lax_monoidal_functor.μ (monoidal_functor.to_lax_monoidal_functor F) X Y) namespace lax_monoidal_functor /-- The identity lax monoidal functor. -/ @[simp] theorem id_ε (C : Type u₁) [category C] [monoidal_category C] : ε (id C) = 𝟙 := Eq.refl (ε (id C)) protected instance inhabited (C : Type u₁) [category C] [monoidal_category C] : Inhabited (lax_monoidal_functor C C) := { default := id C } end lax_monoidal_functor namespace monoidal_functor theorem map_tensor {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] [monoidal_category D] (F : monoidal_functor C D) {X : C} {Y : C} {X' : C} {Y' : C} (f : X ⟶ Y) (g : X' ⟶ Y') : functor.map (lax_monoidal_functor.to_functor (to_lax_monoidal_functor F)) (f ⊗ g) = inv (lax_monoidal_functor.μ (to_lax_monoidal_functor F) X X') ≫ (functor.map (lax_monoidal_functor.to_functor (to_lax_monoidal_functor F)) f ⊗ functor.map (lax_monoidal_functor.to_functor (to_lax_monoidal_functor F)) g) ≫ lax_monoidal_functor.μ (to_lax_monoidal_functor F) Y Y' := sorry theorem map_left_unitor {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] [monoidal_category D] (F : monoidal_functor C D) (X : C) : functor.map (lax_monoidal_functor.to_functor (to_lax_monoidal_functor F)) (iso.hom λ_) = inv (lax_monoidal_functor.μ (to_lax_monoidal_functor F) 𝟙_ X) ≫ (inv (lax_monoidal_functor.ε (to_lax_monoidal_functor F)) ⊗ 𝟙) ≫ iso.hom λ_ := sorry theorem map_right_unitor {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] [monoidal_category D] (F : monoidal_functor C D) (X : C) : functor.map (lax_monoidal_functor.to_functor (to_lax_monoidal_functor F)) (iso.hom ρ_) = inv (lax_monoidal_functor.μ (to_lax_monoidal_functor F) X 𝟙_) ≫ (𝟙 ⊗ inv (lax_monoidal_functor.ε (to_lax_monoidal_functor F))) ≫ iso.hom ρ_ := sorry /-- The tensorator as a natural isomorphism. -/ def μ_nat_iso {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] [monoidal_category D] (F : monoidal_functor C D) : functor.prod (lax_monoidal_functor.to_functor (to_lax_monoidal_functor F)) (lax_monoidal_functor.to_functor (to_lax_monoidal_functor F)) ⋙ monoidal_category.tensor D ≅ monoidal_category.tensor C ⋙ lax_monoidal_functor.to_functor (to_lax_monoidal_functor F) := nat_iso.of_components (fun (X : C × C) => μ_iso F (prod.fst X) (prod.snd X)) sorry /-- The identity monoidal functor. -/ def id (C : Type u₁) [category C] [monoidal_category C] : monoidal_functor C C := mk (lax_monoidal_functor.mk (functor.mk (functor.obj 𝟭) (functor.map 𝟭)) 𝟙 fun (X Y : C) => 𝟙) protected instance inhabited (C : Type u₁) [category C] [monoidal_category C] : Inhabited (monoidal_functor C C) := { default := id C } end monoidal_functor namespace lax_monoidal_functor -- The proofs here are horrendous; rewrite_search helps a lot. /-- The composition of two lax monoidal functors is again lax monoidal. -/ @[simp] theorem comp_ε {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] [monoidal_category D] {E : Type u₃} [category E] [monoidal_category E] (F : lax_monoidal_functor C D) (G : lax_monoidal_functor D E) : ε (comp F G) = ε G ≫ functor.map (to_functor G) (ε F) := Eq.refl (ε (comp F G)) infixr:80 " ⊗⋙ " => Mathlib.category_theory.lax_monoidal_functor.comp end lax_monoidal_functor namespace monoidal_functor /-- The composition of two monoidal functors is again monoidal. -/ def comp {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] [monoidal_category D] {E : Type u₃} [category E] [monoidal_category E] (F : monoidal_functor C D) (G : monoidal_functor D E) : monoidal_functor C E := mk (lax_monoidal_functor.mk (lax_monoidal_functor.to_functor (to_lax_monoidal_functor F ⊗⋙ to_lax_monoidal_functor G)) (lax_monoidal_functor.ε (to_lax_monoidal_functor F ⊗⋙ to_lax_monoidal_functor G)) (lax_monoidal_functor.μ (to_lax_monoidal_functor F ⊗⋙ to_lax_monoidal_functor G))) infixr:80 " ⊗⋙ " => Mathlib.category_theory.monoidal_functor.comp end Mathlib
9fb983bcfa575aff167059da95d97356509f0a38
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/linear_algebra/exterior_algebra/basic.lean
c0d133a7281947178d736f285c4d9b98d3dd2e70
[ "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
10,938
lean
/- Copyright (c) 2020 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhangir Azerbayev, Adam Topaz, Eric Wieser -/ import linear_algebra.clifford_algebra.basic import linear_algebra.alternating /-! # Exterior Algebras We construct the exterior algebra of a module `M` over a commutative semiring `R`. ## Notation The exterior algebra of the `R`-module `M` is denoted as `exterior_algebra R M`. It is endowed with the structure of an `R`-algebra. Given a linear morphism `f : M → A` from a module `M` to another `R`-algebra `A`, such that `cond : ∀ m : M, f m * f m = 0`, there is a (unique) lift of `f` to an `R`-algebra morphism, which is denoted `exterior_algebra.lift R f cond`. The canonical linear map `M → exterior_algebra R M` is denoted `exterior_algebra.ι R`. ## Theorems The main theorems proved ensure that `exterior_algebra R M` satisfies the universal property of the exterior algebra. 1. `ι_comp_lift` is fact that the composition of `ι R` with `lift R f cond` agrees with `f`. 2. `lift_unique` ensures the uniqueness of `lift R f cond` with respect to 1. ## Definitions * `ι_multi` is the `alternating_map` corresponding to the wedge product of `ι R m` terms. ## Implementation details The exterior algebra of `M` is constructed as simply `clifford_algebra (0 : quadratic_form R M)`, as this avoids us having to duplicate API. -/ universes u1 u2 u3 variables (R : Type u1) [comm_ring R] variables (M : Type u2) [add_comm_group M] [module R M] /-- The exterior algebra of an `R`-module `M`. -/ @[reducible] def exterior_algebra := clifford_algebra (0 : quadratic_form R M) namespace exterior_algebra variables {M} /-- The canonical linear map `M →ₗ[R] exterior_algebra R M`. -/ @[reducible] def ι : M →ₗ[R] exterior_algebra R M := by exact clifford_algebra.ι _ variables {R} /-- As well as being linear, `ι m` squares to zero -/ @[simp] theorem ι_sq_zero (m : M) : (ι R m) * (ι R m) = 0 := (clifford_algebra.ι_sq_scalar _ m).trans $ map_zero _ variables {A : Type*} [semiring A] [algebra R A] @[simp] theorem comp_ι_sq_zero (g : exterior_algebra R M →ₐ[R] A) (m : M) : g (ι R m) * g (ι R m) = 0 := by rw [←alg_hom.map_mul, ι_sq_zero, alg_hom.map_zero] variables (R) /-- Given a linear map `f : M →ₗ[R] A` into an `R`-algebra `A`, which satisfies the condition: `cond : ∀ m : M, f m * f m = 0`, this is the canonical lift of `f` to a morphism of `R`-algebras from `exterior_algebra R M` to `A`. -/ @[simps symm_apply] def lift : {f : M →ₗ[R] A // ∀ m, f m * f m = 0} ≃ (exterior_algebra R M →ₐ[R] A) := equiv.trans (equiv.subtype_equiv (equiv.refl _) $ by simp) $ clifford_algebra.lift _ @[simp] theorem ι_comp_lift (f : M →ₗ[R] A) (cond : ∀ m, f m * f m = 0) : (lift R ⟨f, cond⟩).to_linear_map.comp (ι R) = f := clifford_algebra.ι_comp_lift f _ @[simp] theorem lift_ι_apply (f : M →ₗ[R] A) (cond : ∀ m, f m * f m = 0) (x) : lift R ⟨f, cond⟩ (ι R x) = f x := clifford_algebra.lift_ι_apply f _ x @[simp] theorem lift_unique (f : M →ₗ[R] A) (cond : ∀ m, f m * f m = 0) (g : exterior_algebra R M →ₐ[R] A) : g.to_linear_map.comp (ι R) = f ↔ g = lift R ⟨f, cond⟩ := clifford_algebra.lift_unique f _ _ variables {R M} @[simp] theorem lift_comp_ι (g : exterior_algebra R M →ₐ[R] A) : lift R ⟨g.to_linear_map.comp (ι R), comp_ι_sq_zero _⟩ = g := clifford_algebra.lift_comp_ι g /-- See note [partially-applied ext lemmas]. -/ @[ext] theorem hom_ext {f g : exterior_algebra R M →ₐ[R] A} (h : f.to_linear_map.comp (ι R) = g.to_linear_map.comp (ι R)) : f = g := clifford_algebra.hom_ext h /-- If `C` holds for the `algebra_map` of `r : R` into `exterior_algebra R M`, the `ι` of `x : M`, and is preserved under addition and muliplication, then it holds for all of `exterior_algebra R M`. -/ @[elab_as_eliminator] lemma induction {C : exterior_algebra R M → Prop} (h_grade0 : ∀ r, C (algebra_map R (exterior_algebra R M) r)) (h_grade1 : ∀ x, C (ι R x)) (h_mul : ∀ a b, C a → C b → C (a * b)) (h_add : ∀ a b, C a → C b → C (a + b)) (a : exterior_algebra R M) : C a := clifford_algebra.induction h_grade0 h_grade1 h_mul h_add a /-- The left-inverse of `algebra_map`. -/ def algebra_map_inv : exterior_algebra R M →ₐ[R] R := exterior_algebra.lift R ⟨(0 : M →ₗ[R] R), λ m, by simp⟩ variables (M) lemma algebra_map_left_inverse : function.left_inverse algebra_map_inv (algebra_map R $ exterior_algebra R M) := λ x, by simp [algebra_map_inv] @[simp] lemma algebra_map_inj (x y : R) : algebra_map R (exterior_algebra R M) x = algebra_map R (exterior_algebra R M) y ↔ x = y := (algebra_map_left_inverse M).injective.eq_iff @[simp] lemma algebra_map_eq_zero_iff (x : R) : algebra_map R (exterior_algebra R M) x = 0 ↔ x = 0 := map_eq_zero_iff (algebra_map _ _) (algebra_map_left_inverse _).injective @[simp] lemma algebra_map_eq_one_iff (x : R) : algebra_map R (exterior_algebra R M) x = 1 ↔ x = 1 := map_eq_one_iff (algebra_map _ _) (algebra_map_left_inverse _).injective lemma is_unit_algebra_map (r : R) : is_unit (algebra_map R (exterior_algebra R M) r) ↔ is_unit r := is_unit_map_of_left_inverse _ (algebra_map_left_inverse M) /-- Invertibility in the exterior algebra is the same as invertibility of the base ring. -/ @[simps] def invertible_algebra_map_equiv (r : R) : invertible (algebra_map R (exterior_algebra R M) r) ≃ invertible r := invertible_equiv_of_left_inverse _ _ _ (algebra_map_left_inverse M) variables {M} /-- The canonical map from `exterior_algebra R M` into `triv_sq_zero_ext R M` that sends `exterior_algebra.ι` to `triv_sq_zero_ext.inr`. -/ def to_triv_sq_zero_ext : exterior_algebra R M →ₐ[R] triv_sq_zero_ext R M := lift R ⟨triv_sq_zero_ext.inr_hom R M, λ m, triv_sq_zero_ext.inr_mul_inr R m m⟩ @[simp] lemma to_triv_sq_zero_ext_ι (x : M) : to_triv_sq_zero_ext (ι R x) = triv_sq_zero_ext.inr x := lift_ι_apply _ _ _ _ /-- The left-inverse of `ι`. As an implementation detail, we implement this using `triv_sq_zero_ext` which has a suitable algebra structure. -/ def ι_inv : exterior_algebra R M →ₗ[R] M := (triv_sq_zero_ext.snd_hom R M).comp to_triv_sq_zero_ext.to_linear_map lemma ι_left_inverse : function.left_inverse ι_inv (ι R : M → exterior_algebra R M) := λ x, by simp [ι_inv] variables (R) @[simp] lemma ι_inj (x y : M) : ι R x = ι R y ↔ x = y := ι_left_inverse.injective.eq_iff variables {R} @[simp] lemma ι_eq_zero_iff (x : M) : ι R x = 0 ↔ x = 0 := by rw [←ι_inj R x 0, linear_map.map_zero] @[simp] lemma ι_eq_algebra_map_iff (x : M) (r : R) : ι R x = algebra_map R _ r ↔ x = 0 ∧ r = 0 := begin refine ⟨λ h, _, _⟩, { have hf0 : to_triv_sq_zero_ext (ι R x) = (0, x), from to_triv_sq_zero_ext_ι _, rw [h, alg_hom.commutes] at hf0, have : r = 0 ∧ 0 = x := prod.ext_iff.1 hf0, exact this.symm.imp_left eq.symm, }, { rintro ⟨rfl, rfl⟩, rw [linear_map.map_zero, ring_hom.map_zero] } end @[simp] lemma ι_ne_one [nontrivial R] (x : M) : ι R x ≠ 1 := begin rw [←(algebra_map R (exterior_algebra R M)).map_one, ne.def, ι_eq_algebra_map_iff], exact one_ne_zero ∘ and.right, end /-- The generators of the exterior algebra are disjoint from its scalars. -/ lemma ι_range_disjoint_one : disjoint (linear_map.range (ι R : M →ₗ[R] exterior_algebra R M)) (1 : submodule R (exterior_algebra R M)) := begin rw submodule.disjoint_def, rintros _ ⟨x, hx⟩ ⟨r, (rfl : algebra_map _ _ _ = _)⟩, rw ι_eq_algebra_map_iff x at hx, rw [hx.2, ring_hom.map_zero] end @[simp] lemma ι_add_mul_swap (x y : M) : ι R x * ι R y + ι R y * ι R x = 0 := calc _ = ι R (x + y) * ι R (x + y) : by simp [mul_add, add_mul] ... = _ : ι_sq_zero _ lemma ι_mul_prod_list {n : ℕ} (f : fin n → M) (i : fin n) : (ι R $ f i) * (list.of_fn $ λ i, ι R $ f i).prod = 0 := begin induction n with n hn, { exact i.elim0, }, { rw [list.of_fn_succ, list.prod_cons, ←mul_assoc], by_cases h : i = 0, { rw [h, ι_sq_zero, zero_mul], }, { replace hn := congr_arg ((*) $ ι R $ f 0) (hn (λ i, f $ fin.succ i) (i.pred h)), simp only at hn, rw [fin.succ_pred, ←mul_assoc, mul_zero] at hn, refine (eq_zero_iff_eq_zero_of_add_eq_zero _).mp hn, rw [← add_mul, ι_add_mul_swap, zero_mul], } } end variables (R) /-- The product of `n` terms of the form `ι R m` is an alternating map. This is a special case of `multilinear_map.mk_pi_algebra_fin`, and the exterior algebra version of `tensor_algebra.tprod`. -/ def ι_multi (n : ℕ) : alternating_map R M (exterior_algebra R M) (fin n) := let F := (multilinear_map.mk_pi_algebra_fin R n (exterior_algebra R M)).comp_linear_map (λ i, ι R) in { map_eq_zero_of_eq' := λ f x y hfxy hxy, begin rw [multilinear_map.comp_linear_map_apply, multilinear_map.mk_pi_algebra_fin_apply], wlog h : x < y := lt_or_gt_of_ne hxy using x y, clear hxy, induction n with n hn generalizing x y, { exact x.elim0, }, { rw [list.of_fn_succ, list.prod_cons], by_cases hx : x = 0, -- one of the repeated terms is on the left { rw hx at hfxy h, rw [hfxy, ←fin.succ_pred y (ne_of_lt h).symm], exact ι_mul_prod_list (f ∘ fin.succ) _, }, -- ignore the left-most term and induct on the remaining ones, decrementing indices { convert mul_zero _, refine hn (λ i, f $ fin.succ i) (x.pred hx) (y.pred (ne_of_lt $ lt_of_le_of_lt x.zero_le h).symm) (fin.pred_lt_pred_iff.mpr h) _, simp only [fin.succ_pred], exact hfxy, } } end, to_fun := F, ..F} variables {R} lemma ι_multi_apply {n : ℕ} (v : fin n → M) : ι_multi R n v = (list.of_fn $ λ i, ι R (v i)).prod := rfl @[simp] lemma ι_multi_zero_apply (v : fin 0 → M) : ι_multi R 0 v = 1 := rfl @[simp] lemma ι_multi_succ_apply {n : ℕ} (v : fin n.succ → M) : ι_multi R _ v = ι R (v 0) * ι_multi R _ (matrix.vec_tail v):= (congr_arg list.prod (list.of_fn_succ _)).trans list.prod_cons lemma ι_multi_succ_curry_left {n : ℕ} (m : M) : (ι_multi R n.succ).curry_left m = (linear_map.mul_left R (ι R m)).comp_alternating_map (ι_multi R n) := alternating_map.ext $ λ v, (ι_multi_succ_apply _).trans $ begin simp_rw matrix.tail_cons, refl, end end exterior_algebra namespace tensor_algebra variables {R M} /-- The canonical image of the `tensor_algebra` in the `exterior_algebra`, which maps `tensor_algebra.ι R x` to `exterior_algebra.ι R x`. -/ def to_exterior : tensor_algebra R M →ₐ[R] exterior_algebra R M := tensor_algebra.lift R (exterior_algebra.ι R : M →ₗ[R] exterior_algebra R M) @[simp] lemma to_exterior_ι (m : M) : (tensor_algebra.ι R m).to_exterior = exterior_algebra.ι R m := by simp [to_exterior] end tensor_algebra
ac206f3fdb3e8c15b6315563277a8220840331ae
5ec8f5218a7c8e87dd0d70dc6b715b36d61a8d61
/errors.lean
bb68682170623533f7331163bceea02408025cc7
[]
no_license
mbrodersen/kremlin
f9f2f9dd77b9744fe0ffd5f70d9fa0f1f8bd8cec
d4665929ce9012e93a0b05fc7063b96256bab86f
refs/heads/master
1,624,057,268,130
1,496,957,084,000
1,496,957,084,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
663
lean
import data.num.basic namespace errors inductive errcode : Type | MSG: string -> errcode | CTX: pos_num -> errcode /- a top-level identifier -/ | POS: pos_num -> errcode /- a positive integer, e.g. a PC -/ export errcode (MSG CTX POS) def errmsg: Type := list errcode def msg (s: string) : errmsg := [MSG s] inductive res (A : Type) : Type | OK {} : A -> res | error {} : errmsg -> res export res (OK error) def res.bind {A B : Type} : res A → (A → res B) → res B | (OK a) f := f a | (error e) _ := error e instance : monad res := { pure := @OK, bind := @res.bind, id_map := sorry, pure_bind := sorry, bind_assoc := sorry } end errors
d2ef0bcdbd6f57f947e1cdc3b6a1543464d30d51
9028d228ac200bbefe3a711342514dd4e4458bff
/src/tactic/omega/eq_elim.lean
7245b7bcced20832668bf86eb512e006235e53bf
[ "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
14,706
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek -/ /- Correctness lemmas for equality elimination. See 5.5 of <http://www.decision-procedures.org/> for details. -/ import tactic.omega.clause open list.func namespace omega def symdiv (i j : int) : int := if (2 * (i % j)) < j then i / j else (i / j) + 1 def symmod (i j : int) : int := if (2 * (i % j)) < j then i % j else (i % j) - j local attribute [semireducible] int.lt lemma symmod_add_one_self {i : int} : 0 < i → symmod i (i+1) = -1 := begin intro h1, unfold symmod, rw [int.mod_eq_of_lt (le_of_lt h1) (lt_add_one _), if_neg], simp only [add_comm, add_neg_cancel_left, neg_add_rev, sub_eq_add_neg], have h2 : 2 * i = (1 + 1) * i := rfl, simpa only [h2, add_mul, one_mul, add_lt_add_iff_left, not_lt] using h1 end lemma mul_symdiv_eq {i j : int} : j * (symdiv i j) = i - (symmod i j) := begin unfold symdiv, unfold symmod, by_cases h1 : (2 * (i % j)) < j, { repeat {rw if_pos h1}, rw [int.mod_def, sub_sub_cancel] }, { repeat {rw if_neg h1}, rw [int.mod_def, sub_sub, sub_sub_cancel, mul_add, mul_one] } end lemma symmod_eq {i j : int} : symmod i j = i - j * (symdiv i j) := by rw [mul_symdiv_eq, sub_sub_cancel] /-- (sgm v b as n) is the new value assigned to the nth variable after a single step of equality elimination using valuation v, term ⟨b, as⟩, and variable index n. If v satisfies the initial constraint set, then (v ⟨n ↦ sgm v b as n⟩) satisfies the new constraint set after equality elimination. -/ def sgm (v : nat → int) (b : int) (as : list int) (n : nat) := let a_n : int := get n as in let m : int := a_n + 1 in ((symmod b m) + (coeffs.val v (as.map (λ x, symmod x m)))) / m open_locale list.func def rhs : nat → int → list int → term | n b as := let m := get n as + 1 in ⟨(symmod b m), (as.map (λ x, symmod x m)) {n ↦ -m}⟩ lemma rhs_correct_aux {v : nat → int} {m : int} {as : list int} : ∀ {k}, ∃ d, (m * d + coeffs.val_between v (as.map (λ (x : ℤ), symmod x m)) 0 k = coeffs.val_between v as 0 k) | 0 := begin existsi (0 : int), simp only [add_zero, mul_zero, coeffs.val_between] end | (k+1) := begin simp only [zero_add, coeffs.val_between, list.map], cases @rhs_correct_aux k with d h1, rw ← h1, by_cases hk : k < as.length, { rw [get_map hk, symmod_eq, sub_mul], existsi (d + (symdiv (get k as) m * v k)), ring }, { rw not_lt at hk, repeat {rw get_eq_default_of_le}, existsi d, rw add_assoc, exact hk, simp only [hk, list.length_map] } end open_locale omega lemma rhs_correct {v : nat → int} {b : int} {as : list int} (n : nat) : 0 < get n as → 0 = term.val v (b,as) → v n = term.val (v ⟨n ↦ sgm v b as n⟩) (rhs n b as) := begin intros h0 h1, let a_n := get n as, let m := a_n + 1, have h3 : m ≠ 0, { apply ne_of_gt, apply lt_trans h0, simp [a_n, m] }, have h2 : m * (sgm v b as n) = (symmod b m) + coeffs.val v (as.map (λ x, symmod x m)), { simp only [sgm, mul_comm m], rw [int.div_mul_cancel], have h4 : ∃ c, m * c + (symmod b (get n as + 1) + coeffs.val v (as.map (λ (x : ℤ), symmod x m))) = term.val v (b,as), { have h5: ∃ d, m * d + (coeffs.val v (as.map (λ x, symmod x m))) = coeffs.val v as, { simp only [coeffs.val, list.length_map], apply rhs_correct_aux }, cases h5 with d h5, rw symmod_eq, existsi (symdiv b m + d), unfold term.val, rw ← h5, simp only [term.val, mul_add, add_mul, m, a_n], ring }, cases h4 with c h4, rw [dvd_add_iff_right (dvd_mul_right m c), h4, ← h1], apply dvd_zero }, apply calc v n = -(m * sgm v b as n) + (symmod b m) + (coeffs.val_except n v (as.map (λ x, symmod x m))) : begin rw [h2, ← coeffs.val_except_add_eq n], have hn : n < as.length, { by_contra hc, rw not_lt at hc, rw (get_eq_default_of_le n hc) at h0, cases h0 }, rw get_map hn, simp only [a_n, m], rw [add_comm, symmod_add_one_self h0], ring end ... = term.val (v⟨n↦sgm v b as n⟩) (rhs n b as) : begin unfold rhs, unfold term.val, rw [← coeffs.val_except_add_eq n, get_set, update_eq], have h2 : ∀ a b c : int, a + b + c = b + (c + a) := by {intros, ring}, rw (h2 (- _)), apply fun_mono_2 rfl, apply fun_mono_2, { rw coeffs.val_except_update_set }, { simp only [m, a_n], ring } end end def sym_sym (m b : int) : int := symdiv b m + symmod b m def coeffs_reduce : nat → int → list int → term | n b as := let a := get n as in let m := a + 1 in (sym_sym m b, (as.map (sym_sym m)) {n ↦ -a}) lemma coeffs_reduce_correct {v : nat → int} {b : int} {as : list int} {n : nat} : 0 < get n as → 0 = term.val v (b,as) → 0 = term.val (v ⟨n ↦ sgm v b as n⟩) (coeffs_reduce n b as) := begin intros h1 h2, let a_n := get n as, let m := a_n + 1, have h3 : m ≠ 0, { apply ne_of_gt, apply lt_trans h1, simp only [m, lt_add_iff_pos_right] }, have h4 : 0 = (term.val (v⟨n↦sgm v b as n⟩) (coeffs_reduce n b as)) * m := calc 0 = term.val v (b,as) : h2 ... = b + coeffs.val_except n v as + a_n * ((rhs n b as).val (v⟨n ↦ sgm v b as n⟩)) : begin unfold term.val, rw [← coeffs.val_except_add_eq n, rhs_correct n h1 h2], simp only [a_n, add_assoc], end ... = -(m * a_n * sgm v b as n) + (b + a_n * (symmod b m)) + (coeffs.val_except n v as + a_n * coeffs.val_except n v (as.map (λ x, symmod x m))) : begin simp only [term.val, rhs, mul_add, m, a_n, add_assoc, add_right_inj, add_comm, add_left_comm], rw [← coeffs.val_except_add_eq n, get_set, update_eq, mul_add], apply fun_mono_2, { rw coeffs.val_except_eq_val_except update_eq_of_ne (get_set_eq_of_ne _) }, simp only [m], ring, end ... = -(m * a_n * sgm v b as n) + (b + a_n * (symmod b m)) + coeffs.val_except n v (as.map (λ a_i, a_i + a_n * (symmod a_i m))) : begin apply fun_mono_2 rfl, simp only [coeffs.val_except, mul_add], repeat {rw ← coeffs.val_between_map_mul}, have h4 : ∀ {a b c d : int}, a + b + (c + d) = (a + c) + (b + d), { intros, ring }, rw h4, have h5 : add as (list.map (has_mul.mul a_n) (list.map (λ (x : ℤ), symmod x (get n as + 1)) as)) = list.map (λ (a_i : ℤ), a_i + a_n * symmod a_i m) as, { rw [list.map_map, ←map_add_map], apply fun_mono_2, { have h5 : (λ x : int, x) = id, { rw function.funext_iff, intro x, refl }, rw [h5, list.map_id] }, { apply fun_mono_2 _ rfl, rw function.funext_iff, intro x, simp only [m] } }, simp only [list.length_map], repeat { rw [← coeffs.val_between_add, h5] }, end ... = -(m * a_n * sgm v b as n) + (m * sym_sym m b) + coeffs.val_except n v (as.map (λ a_i, m * sym_sym m a_i)) : begin repeat {rw add_assoc}, apply fun_mono_2, refl, rw ← add_assoc, have h4 : ∀ (x : ℤ), x + a_n * symmod x m = m * sym_sym m x, { intro x, have h5 : a_n = m - 1, { simp only [m], rw add_sub_cancel }, rw [h5, sub_mul, one_mul, add_sub, add_comm, add_sub_assoc, ← mul_symdiv_eq], simp only [sym_sym, mul_add, add_comm] }, apply fun_mono_2 (h4 _), apply coeffs.val_except_eq_val_except; intros x h5, refl, apply congr_arg, apply fun_mono_2 _ rfl, rw function.funext_iff, apply h4 end ... = (-(a_n * sgm v b as n) + (sym_sym m b) + coeffs.val_except n v (as.map (sym_sym m))) * m : begin simp only [add_mul _ _ m], apply fun_mono_2, ring, simp only [coeffs.val_except, add_mul _ _ m], apply fun_mono_2, { rw [mul_comm _ m, ← coeffs.val_between_map_mul, list.map_map] }, simp only [list.length_map, mul_comm _ m], rw [← coeffs.val_between_map_mul, list.map_map] end ... = (sym_sym m b + (coeffs.val_except n v (as.map (sym_sym m)) + (-a_n * sgm v b as n))) * m : by ring ... = (term.val (v ⟨n ↦ sgm v b as n⟩) (coeffs_reduce n b as)) * m : begin simp only [coeffs_reduce, term.val, m, a_n], rw [← coeffs.val_except_add_eq n, coeffs.val_except_update_set, get_set, update_eq] end, rw [← int.mul_div_cancel (term.val _ _) h3, ← h4, int.zero_div] end -- Requires : t1.coeffs[m] = 1 def cancel (m : nat) (t1 t2 : term) : term := term.add (t1.mul (-(get m (t2.snd)))) t2 def subst (n : nat) (t1 t2 : term) : term := term.add (t1.mul (get n t2.snd)) (t2.fst, t2.snd {n ↦ 0}) lemma subst_correct {v : nat → int} {b : int} {as : list int} {t : term} {n : nat} : 0 < get n as → 0 = term.val v (b,as) → term.val v t = term.val (v ⟨n ↦ sgm v b as n⟩) (subst n (rhs n b as) t) := begin intros h1 h2, simp only [subst, term.val, term.val_add, term.val_mul], rw ← rhs_correct _ h1 h2, cases t with b' as', simp only [term.val], have h3 : coeffs.val (v ⟨n ↦ sgm v b as n⟩) (as' {n ↦ 0}) = coeffs.val_except n v as', { rw [← coeffs.val_except_add_eq n, get_set, zero_mul, add_zero, coeffs.val_except_update_set] }, rw [h3, ← coeffs.val_except_add_eq n], ring end /-- The type of equality elimination rules. -/ @[derive has_reflect, derive inhabited] inductive ee : Type | drop : ee | nondiv : int → ee | factor : int → ee | neg : ee | reduce : nat → ee | cancel : nat → ee namespace ee def repr : ee → string | drop := "↓" | (nondiv i) := i.repr ++ "∤" | (factor i) := "/" ++ i.repr | neg := "-" | (reduce n) := "≻" ++ n.repr | (cancel n) := "+" ++ n.repr instance has_repr : has_repr ee := ⟨repr⟩ meta instance has_to_format : has_to_format ee := ⟨λ x, x.repr⟩ end ee /-- Apply a given sequence of equality elimination steps to a clause. -/ def eq_elim : list ee → clause → clause | [] ([], les) := ([],les) | [] ((_::_), les) := ([],[]) | (_::_) ([], les) := ([],[]) | (ee.drop::es) ((eq::eqs), les) := eq_elim es (eqs, les) | (ee.neg::es) ((eq::eqs), les) := eq_elim es ((eq.neg::eqs), les) | (ee.nondiv i::es) ((b,as)::eqs, les) := if ¬(i ∣ b) ∧ (∀ x ∈ as, i ∣ x) then ([],[⟨-1,[]⟩]) else ([],[]) | (ee.factor i::es) ((b,as)::eqs, les) := if (i ∣ b) ∧ (∀ x ∈ as, i ∣ x) then eq_elim es ((term.div i (b,as)::eqs), les) else ([],[]) | (ee.reduce n::es) ((b,as)::eqs, les) := if 0 < get n as then let eq' := coeffs_reduce n b as in let r := rhs n b as in let eqs' := eqs.map (subst n r) in let les' := les.map (subst n r) in eq_elim es ((eq'::eqs'), les') else ([],[]) | (ee.cancel m::es) ((eq::eqs), les) := eq_elim es ((eqs.map (cancel m eq)), (les.map (cancel m eq))) open tactic lemma sat_empty : clause.sat ([],[]) := ⟨λ _,0, ⟨dec_trivial, dec_trivial⟩⟩ lemma sat_eq_elim : ∀ {es : list ee} {c : clause}, c.sat → (eq_elim es c).sat | [] ([], les) h := h | (e::_) ([], les) h := by {cases e; simp only [eq_elim]; apply sat_empty} | [] ((_::_), les) h := sat_empty | (ee.drop::es) ((eq::eqs), les) h1 := begin apply (@sat_eq_elim es _ _), rcases h1 with ⟨v,h1,h2⟩, refine ⟨v, list.forall_mem_of_forall_mem_cons h1, h2⟩ end | (ee.neg::es) ((eq::eqs), les) h1 := begin simp only [eq_elim], apply sat_eq_elim, cases h1 with v h1, existsi v, cases h1 with hl hr, apply and.intro _ hr, rw list.forall_mem_cons at *, apply and.intro _ hl.right, rw term.val_neg, rw ← hl.left, refl end | (ee.nondiv i::es) ((b,as)::eqs, les) h1 := begin unfold eq_elim, by_cases h2 : (¬i ∣ b ∧ ∀ (x : ℤ), x ∈ as → i ∣ x), { exfalso, cases h1 with v h1, have h3 : 0 = b + coeffs.val v as := h1.left _ (or.inl rfl), have h4 : i ∣ coeffs.val v as := coeffs.dvd_val h2.right, have h5 : i ∣ b + coeffs.val v as := by { rw ← h3, apply dvd_zero }, rw ← dvd_add_iff_left h4 at h5, apply h2.left h5 }, rw if_neg h2, apply sat_empty end | (ee.factor i::es) ((b,as)::eqs, les) h1 := begin simp only [eq_elim], by_cases h2 : (i ∣ b) ∧ (∀ x ∈ as, i ∣ x), { rw if_pos h2, apply sat_eq_elim, cases h1 with v h1, existsi v, cases h1 with h3 h4, apply and.intro _ h4, rw list.forall_mem_cons at *, cases h3 with h5 h6, apply and.intro _ h6, rw [term.val_div h2.left h2.right, ← h5, int.zero_div] }, { rw if_neg h2, apply sat_empty } end | (ee.reduce n::es) ((b,as)::eqs, les) h1 := begin simp only [eq_elim], by_cases h2 : 0 < get n as, tactic.rotate 1, { rw if_neg h2, apply sat_empty }, rw if_pos h2, apply sat_eq_elim, cases h1 with v h1, existsi v ⟨n ↦ sgm v b as n⟩, cases h1 with h1 h3, rw list.forall_mem_cons at h1, cases h1 with h4 h5, constructor, { rw list.forall_mem_cons, constructor, { apply coeffs_reduce_correct h2 h4 }, { intros x h6, rw list.mem_map at h6, cases h6 with t h6, cases h6 with h6 h7, rw [← h7, ← subst_correct h2 h4], apply h5 _ h6 } }, { intros x h6, rw list.mem_map at h6, cases h6 with t h6, cases h6 with h6 h7, rw [← h7, ← subst_correct h2 h4], apply h3 _ h6 } end | (ee.cancel m::es) ((eq::eqs), les) h1 := begin unfold eq_elim, apply sat_eq_elim, cases h1 with v h1, existsi v, cases h1 with h1 h2, rw list.forall_mem_cons at h1, cases h1 with h1 h3, constructor; intros t h4; rw list.mem_map at h4; rcases h4 with ⟨s,h4,h5⟩; rw ← h5; simp only [term.val_add, term.val_mul, cancel]; rw [← h1, mul_zero, zero_add], { apply h3 _ h4 }, { apply h2 _ h4 } end /-- If the result of equality elimination is unsatisfiable, the original clause is unsatisfiable. -/ lemma unsat_of_unsat_eq_elim (ee : list ee) (c : clause) : (eq_elim ee c).unsat → c.unsat := by {intros h1 h2, apply h1, apply sat_eq_elim h2} end omega
4fd095ef75876c734bbe45ba486b6d03e98e80b7
ea5678cc400c34ff95b661fa26d15024e27ea8cd
/mods_and_fermat_little.lean
5741176f487b322c58358d36f027b25797fabfb3
[]
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
265
lean
theorem test1 :∀ y:ℕ, ∃ x:ℕ, x-2=y:=λ y,exists.intro (y+2) rfl #print classical.some noncomputable def test2 : ℕ → ℕ :=λ y, classical.some (test1 y) theorem test3 : ∀ y:ℕ,test2 y-2=y:=λ y,classical.some_spec (test1 y) Sort hello #check test3 7
7b26344205401920cb0401722754fd23d22ff379
0dc59d2b959c9b11a672f655b104d7d7d3e37660
/Lean4_filters/Set/Basic.lean
c3d2901e503454b08af443ceaf0d42b670bed977
[]
no_license
kbuzzard/lean4-filters
5aa17d95079ceb906622543209064151fa645e71
29f90055b7a2341c86d924954463c439bd128fb7
refs/heads/master
1,679,762,259,673
1,616,701,300,000
1,616,701,300,000
350,784,493
5
1
null
1,625,691,081,000
1,616,517,435,000
Lean
UTF-8
Lean
false
false
2,879
lean
import Lean4_filters.Lattice.Basic import Lean4_filters.Tactics.Basic class HasMem (α : outParam $ Type u) (β : Type v) where mem : α → β → Prop infix:50 " ∈ " => HasMem.mem def Set (α : Type u) := α → Prop namespace Set variable {α : Type u} instance : HasMem α (Set α) := ⟨λ a s => s a⟩ theorem ext {s t : Set α} (h : ∀ x, x ∈ s ↔ x ∈ t) : s = t := funext $ λ x=> propext $ h x instance : HasLessEq (Set α) := ⟨λ s t => ∀ {x : α}, x ∈ s → x ∈ t⟩ instance : PartialOrder (Set α) where refl := λ s x => id antisymm := λ s t hst hts => ext $ λ x => ⟨hst, hts⟩ trans := λ s t u hst htu x hxs => htu $ hst hxs instance : HasSup (Set α) := ⟨λ s t x => x ∈ s ∨ x ∈ t⟩ instance : HasInf (Set α) := ⟨λ s t x => x ∈ s ∧ x ∈ t⟩ instance : Lattice (Set α) where leSupLeft := λ a b x => Or.inl leSupRight := λ a b x => Or.inr supLe := λ a b c hac hbc x => Or.rec hac hbc infLeLeft := λ a b x hx => hx.1 infLeRight := λ a b x hx => hx.2 leInf := λ a b c hab hac x hx => ⟨hab hx, hac hx⟩ example : Lattice (Set α) where leSupLeft := by intros a b x hx; left; exact hx; leSupRight := by intros a b x; intro hx; right; exact hx; supLe := by intros a b c hac hbc x hx; cases hx; apply hac; assumption apply hbc; assumption infLeLeft := by intros a b x hx; cases hx with ha hb; exact ha; infLeRight := by intros _ _ _ hx; cases hx with ha hb; exact hb; leInf := by intro a b c hab hac x hx; split; exact hab hx; exact hac hx; def univ : Set α := λ _ => True def empty : Set α := λ _ => False def setOf (p : α → Prop) : Set α := p declare_syntax_cat index syntax ident : index syntax ident ":" term : index syntax ident "∈" term : index -- Notation for sets syntax "{" index "|" term "}" : term macro_rules | `({ $x:ident : $t | $p }) => `(setOf (λ ($x:ident : $t) => $p)) | `({ $x:ident | $p }) => `(setOf (λ ($x:ident) => $p)) | `({ $x:ident ∈ $s | $p }) => `(setOf (λ $x => $x ∈ $s → $p)) -- Notation for ∀ x ∈ s, p and ∃ x ∈ s, p syntax "∀" index "," term : term syntax "∃" index "," term : term macro_rules | `(∀ $x:ident ∈ $s, $p) => `(∀ $x:ident, $x ∈ $s → $p) | `(∃ $x:ident ∈ $s, $p) => `(∃ $x:ident, $x ∈ $s ∧ $p) def map (f : α → β) (s : Set α) : Set β := {b : β | ∃ a ∈ s, f a = b } def comap (f : α → β) (t : Set β) : Set α := {a : α | f a ∈ t } infix:80 " '' " => Set.map infix:80 " ⁻¹ " => Set.comap theorem gc {α β} (f : α → β) : galoisConnection (map f) (comap f) := by intros s t; split_iffs; { intro h x hxs; apply h; refine ⟨x, hxs, rfl⟩ }; { intro h x hx; let ⟨a, has, h2⟩ := hx; rw ← h2; exact h has } end Set
c91dcde430dab3821f5da7aa4955cdee51779f62
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/data/finset/locally_finite.lean
4fa683f8e82d447fcfe0722594131693aa9653e5
[ "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
10,238
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Yaël Dillies -/ import order.locally_finite /-! # Intervals as finsets This file provides basic results about all the `finset.Ixx`, which are defined in `order.locally_finite`. ## TODO This file was originally only about `finset.Ico a b` where `a b : ℕ`. No care has yet been taken to generalize these lemmas properly and many lemmas about `Icc`, `Ioc`, `Ioo` are missing. In general, what's to do is taking the lemmas in `data.x.intervals` and abstract away the concrete structure. -/ namespace finset variables {α : Type*} section preorder variables [preorder α] [locally_finite_order α] {a b : α} @[simp] lemma nonempty_Icc : (Icc a b).nonempty ↔ a ≤ b := by rw [←coe_nonempty, coe_Icc, set.nonempty_Icc] @[simp] lemma nonempty_Ico : (Ico a b).nonempty ↔ a < b := by rw [←coe_nonempty, coe_Ico, set.nonempty_Ico] @[simp] lemma nonempty_Ioc : (Ioc a b).nonempty ↔ a < b := by rw [←coe_nonempty, coe_Ioc, set.nonempty_Ioc] @[simp] lemma nonempty_Ioo [densely_ordered α] : (Ioo a b).nonempty ↔ a < b := by rw [←coe_nonempty, coe_Ioo, set.nonempty_Ioo] @[simp] lemma Icc_eq_empty_iff : Icc a b = ∅ ↔ ¬a ≤ b := by rw [←coe_eq_empty, coe_Icc, set.Icc_eq_empty_iff] @[simp] lemma Ico_eq_empty_iff : Ico a b = ∅ ↔ ¬a < b := by rw [←coe_eq_empty, coe_Ico, set.Ico_eq_empty_iff] @[simp] lemma Ioc_eq_empty_iff : Ioc a b = ∅ ↔ ¬a < b := by rw [←coe_eq_empty, coe_Ioc, set.Ioc_eq_empty_iff] @[simp] lemma Ioo_eq_empty_iff [densely_ordered α] : Ioo a b = ∅ ↔ ¬a < b := by rw [←coe_eq_empty, coe_Ioo, set.Ioo_eq_empty_iff] alias Icc_eq_empty_iff ↔ _ finset.Icc_eq_empty alias Ico_eq_empty_iff ↔ _ finset.Ico_eq_empty alias Ioc_eq_empty_iff ↔ _ finset.Ioc_eq_empty @[simp] lemma Ioo_eq_empty (h : ¬a < b) : Ioo a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x hx, h ((mem_Ioo.1 hx).1.trans (mem_Ioo.1 hx).2) @[simp] lemma Icc_eq_empty_of_lt (h : b < a) : Icc a b = ∅ := Icc_eq_empty h.not_le @[simp] lemma Ico_eq_empty_of_le (h : b ≤ a) : Ico a b = ∅ := Ico_eq_empty h.not_lt @[simp] lemma Ioc_eq_empty_of_le (h : b ≤ a) : Ioc a b = ∅ := Ioc_eq_empty h.not_lt @[simp] lemma Ioo_eq_empty_of_le (h : b ≤ a) : Ioo a b = ∅ := Ioo_eq_empty h.not_lt variables (a) @[simp] lemma Ico_self : Ico a a = ∅ := by rw [←coe_eq_empty, coe_Ico, set.Ico_self] @[simp] lemma Ioc_self : Ioc a a = ∅ := by rw [←coe_eq_empty, coe_Ioc, set.Ioc_self] @[simp] lemma Ioo_self : Ioo a a = ∅ := by rw [←coe_eq_empty, coe_Ioo, set.Ioo_self] @[simp] lemma right_not_mem_Ico {a b : α} : b ∉ Ico a b := by { rw [mem_Ico, not_and], exact λ _, lt_irrefl _ } lemma Ico_filter_lt_of_le_left [decidable_rel ((<) : α → α → Prop)] {a b c : α} (hca : c ≤ a) : (Ico a b).filter (λ x, x < c) = ∅ := finset.filter_false_of_mem (λ x hx, (hca.trans (mem_Ico.1 hx).1).not_lt) lemma Ico_filter_lt_of_right_le [decidable_rel ((<) : α → α → Prop)] {a b c : α} (hbc : b ≤ c) : (Ico a b).filter (λ x, x < c) = Ico a b := finset.filter_true_of_mem (λ x hx, (mem_Ico.1 hx).2.trans_le hbc) lemma Ico_filter_lt_of_le_right [decidable_rel ((<) : α → α → Prop)] {a b c : α} (hcb : c ≤ b) : (Ico a b).filter (λ x, x < c) = Ico a c := begin ext x, rw [mem_filter, mem_Ico, mem_Ico, and.right_comm], exact and_iff_left_of_imp (λ h, h.2.trans_le hcb), end lemma Ico_filter_le_of_le_left [decidable_rel ((≤) : α → α → Prop)] {a b c : α} (hca : c ≤ a) : (Ico a b).filter (λ x, c ≤ x) = Ico a b := finset.filter_true_of_mem (λ x hx, hca.trans (mem_Ico.1 hx).1) lemma Ico_filter_le_of_right_le [decidable_rel ((≤) : α → α → Prop)] {a b : α} : (Ico a b).filter (λ x, b ≤ x) = ∅ := finset.filter_false_of_mem (λ x hx, (mem_Ico.1 hx).2.not_le) lemma Ico_filter_le_of_left_le [decidable_rel ((≤) : α → α → Prop)] {a b c : α} (hac : a ≤ c) : (Ico a b).filter (λ x, c ≤ x) = Ico c b := begin ext x, rw [mem_filter, mem_Ico, mem_Ico, and_comm, and.left_comm], exact and_iff_right_of_imp (λ h, hac.trans h.1), end end preorder section partial_order variables [partial_order α] [locally_finite_order α] {a b : α} @[simp] lemma Icc_self (a : α) : Icc a a = {a} := by rw [←coe_eq_singleton, coe_Icc, set.Icc_self] lemma Ico_insert_right [decidable_eq α] (h : a ≤ b) : insert b (Ico a b) = Icc a b := by rw [←coe_inj, coe_insert, coe_Icc, coe_Ico, set.insert_eq, set.union_comm, set.Ico_union_right h] lemma Ioo_insert_left [decidable_eq α] (h : a < b) : insert a (Ioo a b) = Ico a b := by rw [←coe_inj, coe_insert, coe_Ioo, coe_Ico, set.insert_eq, set.union_comm, set.Ioo_union_left h] @[simp] lemma Ico_inter_Ico_consecutive [decidable_eq α] (a b c : α) : Ico a b ∩ Ico b c = ∅ := begin refine eq_empty_of_forall_not_mem (λ x hx, _), rw [mem_inter, mem_Ico, mem_Ico] at hx, exact hx.1.2.not_le hx.2.1, end lemma Ico_disjoint_Ico_consecutive [decidable_eq α] (a b c : α) : disjoint (Ico a b) (Ico b c) := le_of_eq $ Ico_inter_Ico_consecutive a b c lemma Ico_filter_le_left [decidable_rel ((≤) : α → α → Prop)] {a b : α} (hab : a < b) : (Ico a b).filter (λ x, x ≤ a) = {a} := begin ext x, rw [mem_filter, mem_Ico, mem_singleton, and.right_comm, ←le_antisymm_iff, eq_comm], exact and_iff_left_of_imp (λ h, h.le.trans_lt hab), end end partial_order section linear_order variables [linear_order α] [locally_finite_order α] {a b : α} lemma Ico_subset_Ico_iff {a₁ b₁ a₂ b₂ : α} (h : a₁ < b₁) : Ico a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := by rw [←coe_subset, coe_Ico, coe_Ico, set.Ico_subset_Ico_iff h] lemma Ico_union_Ico_eq_Ico {a b c : α} (hab : a ≤ b) (hbc : b ≤ c) : Ico a b ∪ Ico b c = Ico a c := by rw [←coe_inj, coe_union, coe_Ico, coe_Ico, coe_Ico, set.Ico_union_Ico_eq_Ico hab hbc] lemma Ico_union_Ico' {a b c d : α} (hcb : c ≤ b) (had : a ≤ d) : Ico a b ∪ Ico c d = Ico (min a c) (max b d) := by rw [←coe_inj, coe_union, coe_Ico, coe_Ico, coe_Ico, set.Ico_union_Ico' hcb had] lemma Ico_union_Ico {a b c d : α} (h₁ : min a b ≤ max c d) (h₂ : min c d ≤ max a b) : Ico a b ∪ Ico c d = Ico (min a c) (max b d) := by rw [←coe_inj, coe_union, coe_Ico, coe_Ico, coe_Ico, set.Ico_union_Ico h₁ h₂] lemma Ico_inter_Ico {a b c d : α} : Ico a b ∩ Ico c d = Ico (max a c) (min b d) := by rw [←coe_inj, coe_inter, coe_Ico, coe_Ico, coe_Ico, ←inf_eq_min, ←sup_eq_max, set.Ico_inter_Ico] @[simp] lemma Ico_filter_lt (a b c : α) : (Ico a b).filter (λ x, x < c) = Ico a (min b c) := begin cases le_total b c, { rw [Ico_filter_lt_of_right_le h, min_eq_left h] }, { rw [Ico_filter_lt_of_le_right h, min_eq_right h] } end @[simp] lemma Ico_filter_le (a b c : α) : (Ico a b).filter (λ x, c ≤ x) = Ico (max a c) b := begin cases le_total a c, { rw [Ico_filter_le_of_left_le h, max_eq_right h] }, { rw [Ico_filter_le_of_le_left h, max_eq_left h] } end @[simp] lemma Ico_diff_Ico_left (a b c : α) : (Ico a b) \ (Ico a c) = Ico (max a c) b := begin cases le_total a c, { ext x, rw [mem_sdiff, mem_Ico, mem_Ico, mem_Ico, max_eq_right h, and.right_comm, not_and, not_lt], exact and_congr_left' ⟨λ hx, hx.2 hx.1, λ hx, ⟨h.trans hx, λ _, hx⟩⟩ }, { rw [Ico_eq_empty_of_le h, sdiff_empty, max_eq_left h] } end @[simp] lemma Ico_diff_Ico_right (a b c : α) : (Ico a b) \ (Ico c b) = Ico a (min b c) := begin cases le_total b c, { rw [Ico_eq_empty_of_le h, sdiff_empty, min_eq_left h] }, { ext x, rw [mem_sdiff, mem_Ico, mem_Ico, mem_Ico, min_eq_right h, and_assoc, not_and', not_le], exact and_congr_right' ⟨λ hx, hx.2 hx.1, λ hx, ⟨hx.trans_le h, λ _, hx⟩⟩ } end end linear_order section ordered_cancel_add_comm_monoid variables [ordered_cancel_add_comm_monoid α] [has_exists_add_of_le α] [decidable_eq α] [locally_finite_order α] lemma image_add_const_Icc (a b c : α) : (Icc a b).image ((+) c) = Icc (a + c) (b + c) := begin ext x, rw [mem_image, mem_Icc], split, { rintro ⟨y, hy, rfl⟩, rw mem_Icc at hy, rw add_comm c, exact ⟨add_le_add_right hy.1 c, add_le_add_right hy.2 c⟩ }, { intro hx, obtain ⟨y, hy⟩ := exists_add_of_le hx.1, rw [hy, add_right_comm] at hx, rw [eq_comm, add_right_comm, add_comm] at hy, exact ⟨a + y, mem_Icc.2 ⟨le_of_add_le_add_right hx.1, le_of_add_le_add_right hx.2⟩, hy⟩ } end lemma image_add_const_Ico (a b c : α) : (Ico a b).image ((+) c) = Ico (a + c) (b + c) := begin ext x, rw [mem_image, mem_Ico], split, { rintro ⟨y, hy, hx⟩, rw mem_Ico at hy, rw [←hx, add_comm c], exact ⟨add_le_add_right hy.1 c, add_lt_add_right hy.2 c⟩ }, { intro hx, obtain ⟨y, hy⟩ := exists_add_of_le hx.1, rw [hy, add_right_comm] at hx, rw [eq_comm, add_right_comm, add_comm] at hy, exact ⟨a + y, mem_Ico.2 ⟨le_of_add_le_add_right hx.1, lt_of_add_lt_add_right hx.2⟩, hy⟩ } end lemma image_add_const_Ioc (a b c : α) : (Ioc a b).image ((+) c) = Ioc (a + c) (b + c) := begin ext x, rw [mem_image, mem_Ioc], split, { rintro ⟨y, hy, rfl⟩, rw mem_Ioc at hy, rw add_comm c, exact ⟨add_lt_add_right hy.1 c, add_le_add_right hy.2 c⟩ }, { intro hx, obtain ⟨y, hy⟩ := exists_add_of_le hx.1.le, rw [hy, add_right_comm] at hx, rw [eq_comm, add_right_comm, add_comm] at hy, exact ⟨a + y, mem_Ioc.2 ⟨lt_of_add_lt_add_right hx.1, le_of_add_le_add_right hx.2⟩, hy⟩ } end lemma image_add_const_Ioo (a b c : α) : (Ioo a b).image ((+) c) = Ioo (a + c) (b + c) := begin ext x, rw [mem_image, mem_Ioo], split, { rintro ⟨y, hy, rfl⟩, rw mem_Ioo at hy, rw add_comm c, exact ⟨add_lt_add_right hy.1 c, add_lt_add_right hy.2 c⟩ }, { intro hx, obtain ⟨y, hy⟩ := exists_add_of_le hx.1.le, rw [hy, add_right_comm] at hx, rw [eq_comm, add_right_comm, add_comm] at hy, exact ⟨a + y, mem_Ioo.2 ⟨lt_of_add_lt_add_right hx.1, lt_of_add_lt_add_right hx.2⟩, hy⟩ } end end ordered_cancel_add_comm_monoid end finset
54b02b5f61b4ee6d3d20b1338d7c30edf25b32c6
bf532e3e865883a676110e756f800e0ddeb465be
/data/int/basic.lean
086e34e3676da841153cac0c7508f8e5dd39b37d
[ "Apache-2.0" ]
permissive
aqjune/mathlib
da42a97d9e6670d2efaa7d2aa53ed3585dafc289
f7977ff5a6bcf7e5c54eec908364ceb40dafc795
refs/heads/master
1,631,213,225,595
1,521,089,840,000
1,521,089,840,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
42,178
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad The integers, with addition, multiplication, and subtraction. -/ import data.nat.basic algebra.char_zero algebra.order_functions open nat namespace int instance : inhabited ℤ := ⟨0⟩ meta instance : has_to_format ℤ := ⟨λ z, int.rec_on z (λ k, ↑k) (λ k, "-("++↑k++"+1)")⟩ attribute [simp] int.coe_nat_add int.coe_nat_mul int.coe_nat_zero int.coe_nat_one int.coe_nat_succ @[simp] theorem coe_nat_mul_neg_succ (m n : ℕ) : (m : ℤ) * -[1+ n] = -(m * succ n) := rfl @[simp] theorem neg_succ_mul_coe_nat (m n : ℕ) : -[1+ m] * n = -(succ m * n) := rfl @[simp] theorem neg_succ_mul_neg_succ (m n : ℕ) : -[1+ m] * -[1+ n] = succ m * succ n := rfl theorem coe_nat_le {m n : ℕ} : (↑m : ℤ) ≤ ↑n ↔ m ≤ n := coe_nat_le_coe_nat_iff m n theorem coe_nat_lt {m n : ℕ} : (↑m : ℤ) < ↑n ↔ m < n := coe_nat_lt_coe_nat_iff m n theorem coe_nat_inj' {m n : ℕ} : (↑m : ℤ) = ↑n ↔ m = n := int.coe_nat_eq_coe_nat_iff m n @[simp] theorem coe_nat_pos {n : ℕ} : (0 : ℤ) < n ↔ 0 < n := by rw [← int.coe_nat_zero, coe_nat_lt] @[simp] theorem coe_nat_eq_zero {n : ℕ} : (n : ℤ) = 0 ↔ n = 0 := by rw [← int.coe_nat_zero, coe_nat_inj'] @[simp] theorem coe_nat_ne_zero {n : ℕ} : (n : ℤ) ≠ 0 ↔ n ≠ 0 := not_congr coe_nat_eq_zero /- succ and pred -/ /-- Immediate successor of an integer: `succ n = n + 1` -/ def succ (a : ℤ) := a + 1 /-- Immediate predecessor of an integer: `pred n = n - 1` -/ def pred (a : ℤ) := a - 1 theorem nat_succ_eq_int_succ (n : ℕ) : (nat.succ n : ℤ) = int.succ n := rfl theorem pred_succ (a : ℤ) : pred (succ a) = a := add_sub_cancel _ _ theorem succ_pred (a : ℤ) : succ (pred a) = a := sub_add_cancel _ _ theorem neg_succ (a : ℤ) : -succ a = pred (-a) := neg_add _ _ theorem succ_neg_succ (a : ℤ) : succ (-succ a) = -a := by rw [neg_succ, succ_pred] theorem neg_pred (a : ℤ) : -pred a = succ (-a) := by rw [eq_neg_of_eq_neg (neg_succ (-a)).symm, neg_neg] theorem pred_neg_pred (a : ℤ) : pred (-pred a) = -a := by rw [neg_pred, pred_succ] theorem pred_nat_succ (n : ℕ) : pred (nat.succ n) = n := pred_succ n theorem neg_nat_succ (n : ℕ) : -(nat.succ n : ℤ) = pred (-n) := neg_succ n theorem succ_neg_nat_succ (n : ℕ) : succ (-nat.succ n) = -n := succ_neg_succ n theorem lt_succ_self (a : ℤ) : a < succ a := lt_add_of_pos_right _ zero_lt_one theorem pred_self_lt (a : ℤ) : pred a < a := sub_lt_self _ zero_lt_one theorem add_one_le_iff {a b : ℤ} : a + 1 ≤ b ↔ a < b := iff.rfl theorem lt_add_one_iff {a b : ℤ} : a < b + 1 ↔ a ≤ b := @add_le_add_iff_right _ _ a b 1 theorem sub_one_le_iff {a b : ℤ} : a - 1 < b ↔ a ≤ b := sub_lt_iff_lt_add.trans lt_add_one_iff theorem le_sub_one_iff {a b : ℤ} : a ≤ b - 1 ↔ a < b := le_sub_iff_add_le protected lemma induction_on {p : ℤ → Prop} (i : ℤ) (hz : p 0) (hp : ∀i, p i → p (i + 1)) (hn : ∀i, p i → p (i - 1)) : p i := begin induction i, { induction i, { exact hz }, { exact hp _ i_ih } }, { have : ∀n:ℕ, p (- n), { intro n, induction n, { simp [hz] }, { have := hn _ n_ih, simpa } }, exact this (i + 1) } end /- / -/ theorem of_nat_div (m n : nat) : of_nat (m / n) = (of_nat m) / (of_nat n) := rfl theorem neg_succ_of_nat_div (m : nat) {b : ℤ} (H : b > 0) : -[1+m] / b = -(m / b + 1) := match b, eq_succ_of_zero_lt H with ._, ⟨n, rfl⟩ := rfl end @[simp] protected theorem div_neg : ∀ (a b : ℤ), a / -b = -(a / b) | (m : ℕ) 0 := show of_nat (m / 0) = -(m / 0 : ℕ), by rw nat.div_zero; refl | (m : ℕ) (n+1:ℕ) := rfl | 0 -[1+ n] := rfl | (m+1:ℕ) -[1+ n] := (neg_neg _).symm | -[1+ m] 0 := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl theorem div_of_neg_of_pos {a b : ℤ} (Ha : a < 0) (Hb : b > 0) : a / b = -((-a - 1) / b + 1) := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := by change (- -[1+ m] : ℤ) with (m+1 : ℤ); rw add_sub_cancel; refl end protected theorem div_nonneg {a b : ℤ} (Ha : a ≥ 0) (Hb : b ≥ 0) : a / b ≥ 0 := match a, b, eq_coe_of_zero_le Ha, eq_coe_of_zero_le Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := coe_zero_le _ end protected theorem div_nonpos {a b : ℤ} (Ha : a ≥ 0) (Hb : b ≤ 0) : a / b ≤ 0 := nonpos_of_neg_nonneg $ by rw [← int.div_neg]; exact int.div_nonneg Ha (neg_nonneg_of_nonpos Hb) theorem div_neg' {a b : ℤ} (Ha : a < 0) (Hb : b > 0) : a / b < 0 := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := neg_succ_lt_zero _ end @[simp] protected theorem zero_div : ∀ (b : ℤ), 0 / b = 0 | 0 := rfl | (n+1:ℕ) := rfl | -[1+ n] := rfl @[simp] protected theorem div_zero : ∀ (a : ℤ), a / 0 = 0 | 0 := rfl | (n+1:ℕ) := rfl | -[1+ n] := rfl @[simp] protected theorem div_one : ∀ (a : ℤ), a / 1 = a | 0 := rfl | (n+1:ℕ) := congr_arg of_nat (nat.div_one _) | -[1+ n] := congr_arg neg_succ_of_nat (nat.div_one _) theorem div_eq_zero_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a / b = 0 := match a, b, eq_coe_of_zero_le H1, eq_succ_of_zero_lt (lt_of_le_of_lt H1 H2), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.div_eq_of_lt $ lt_of_coe_nat_lt_coe_nat H2 end theorem div_eq_zero_of_lt_abs {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < abs b) : a / b = 0 := match b, abs b, abs_eq_nat_abs b, H2 with | (n : ℕ), ._, rfl, H2 := div_eq_zero_of_lt H1 H2 | -[1+ n], ._, rfl, H2 := neg_inj $ by rw [← int.div_neg]; exact div_eq_zero_of_lt H1 H2 end protected theorem add_mul_div_right (a b : ℤ) {c : ℤ} (H : c ≠ 0) : (a + b * c) / c = a / c + b := have ∀ {k n : ℕ} {a : ℤ}, (a + n * k.succ) / k.succ = a / k.succ + n, from λ k n a, match a with | (m : ℕ) := congr_arg of_nat $ nat.add_mul_div_right _ _ k.succ_pos | -[1+ m] := show ((n * k.succ:ℕ) - m.succ : ℤ) / k.succ = n - (m / k.succ + 1 : ℕ), begin cases lt_or_ge m (n*k.succ) with h h, { rw [← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.div_lt_iff_lt_mul _ _ k.succ_pos).2 h)], apply congr_arg of_nat, rw [mul_comm, nat.mul_sub_div], rwa mul_comm }, { change (↑(n * nat.succ k) - (m + 1) : ℤ) / ↑(nat.succ k) = ↑n - ((m / nat.succ k : ℕ) + 1), rw [← sub_sub, ← sub_sub, ← neg_sub (m:ℤ), ← neg_sub _ (n:ℤ), ← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.le_div_iff_mul_le _ _ k.succ_pos).2 h), ← neg_succ_of_nat_coe', ← neg_succ_of_nat_coe'], { apply congr_arg neg_succ_of_nat, rw [mul_comm, nat.sub_mul_div], rwa mul_comm } } end end, have ∀ {a b c : ℤ}, c > 0 → (a + b * c) / c = a / c + b, from λ a b c H, match c, eq_succ_of_zero_lt H, b with | ._, ⟨k, rfl⟩, (n : ℕ) := this | ._, ⟨k, rfl⟩, -[1+ n] := show (a - n.succ * k.succ) / k.succ = (a / k.succ) - n.succ, from eq_sub_of_add_eq $ by rw [← this, sub_add_cancel] end, match lt_trichotomy c 0 with | or.inl hlt := neg_inj $ by rw [← int.div_neg, neg_add, ← int.div_neg, ← neg_mul_neg]; apply this (neg_pos_of_neg hlt) | or.inr (or.inl heq) := absurd heq H | or.inr (or.inr hgt) := this hgt end protected theorem add_mul_div_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b ≠ 0) : (a + b * c) / b = a / b + c := by rw [mul_comm, int.add_mul_div_right _ _ H] @[simp] protected theorem mul_div_cancel (a : ℤ) {b : ℤ} (H : b ≠ 0) : a * b / b = a := by have := int.add_mul_div_right 0 a H; rwa [zero_add, int.zero_div, zero_add] at this @[simp] protected theorem mul_div_cancel_left {a : ℤ} (b : ℤ) (H : a ≠ 0) : a * b / a = b := by rw [mul_comm, int.mul_div_cancel _ H] @[simp] protected theorem div_self {a : ℤ} (H : a ≠ 0) : a / a = 1 := by have := int.mul_div_cancel 1 H; rwa one_mul at this /- mod -/ theorem of_nat_mod (m n : nat) : (m % n : ℤ) = of_nat (m % n) := rfl @[simp] theorem coe_nat_mod (m n : ℕ) : (↑(m % n) : ℤ) = ↑m % ↑n := rfl theorem neg_succ_of_nat_mod (m : ℕ) {b : ℤ} (bpos : b > 0) : -[1+m] % b = b - 1 - m % b := by rw [sub_sub, add_comm]; exact match b, eq_succ_of_zero_lt bpos with ._, ⟨n, rfl⟩ := rfl end @[simp] theorem mod_neg : ∀ (a b : ℤ), a % -b = a % b | (m : ℕ) n := @congr_arg ℕ ℤ _ _ (λ i, ↑(m % i)) (nat_abs_neg _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λ i, sub_nat_nat i (nat.succ (m % i))) (nat_abs_neg _) @[simp] theorem mod_abs (a b : ℤ) : a % (abs b) = a % b := abs_by_cases (λ i, a % i = a % b) rfl (mod_neg _ _) @[simp] theorem zero_mod (b : ℤ) : 0 % b = 0 := congr_arg of_nat $ nat.zero_mod _ @[simp] theorem mod_zero : ∀ (a : ℤ), a % 0 = a | (m : ℕ) := congr_arg of_nat $ nat.mod_zero _ | -[1+ m] := congr_arg neg_succ_of_nat $ nat.mod_zero _ @[simp] theorem mod_one : ∀ (a : ℤ), a % 1 = 0 | (m : ℕ) := congr_arg of_nat $ nat.mod_one _ | -[1+ m] := show (1 - (m % 1).succ : ℤ) = 0, by rw nat.mod_one; refl theorem mod_eq_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a % b = a := match a, b, eq_coe_of_zero_le H1, eq_coe_of_zero_le (le_trans H1 (le_of_lt H2)), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.mod_eq_of_lt (lt_of_coe_nat_lt_coe_nat H2) end theorem mod_nonneg : ∀ (a : ℤ) {b : ℤ}, b ≠ 0 → a % b ≥ 0 | (m : ℕ) n H := coe_zero_le _ | -[1+ m] n H := sub_nonneg_of_le $ coe_nat_le_coe_nat_of_le $ nat.mod_lt _ (nat_abs_pos_of_ne_zero H) theorem mod_lt_of_pos (a : ℤ) {b : ℤ} (H : b > 0) : a % b < b := match a, b, eq_succ_of_zero_lt H with | (m : ℕ), ._, ⟨n, rfl⟩ := coe_nat_lt_coe_nat_of_lt (nat.mod_lt _ (nat.succ_pos _)) | -[1+ m], ._, ⟨n, rfl⟩ := sub_lt_self _ (coe_nat_lt_coe_nat_of_lt $ nat.succ_pos _) end theorem mod_lt (a : ℤ) {b : ℤ} (H : b ≠ 0) : a % b < abs b := by rw [← mod_abs]; exact mod_lt_of_pos _ (abs_pos_of_ne_zero H) theorem mod_add_div_aux (m n : ℕ) : (n - (m % n + 1) - (n * (m / n) + n) : ℤ) = -[1+ m] := begin rw [← sub_sub, neg_succ_of_nat_coe, sub_sub (n:ℤ)], apply eq_neg_of_eq_neg, rw [neg_sub, sub_sub_self, add_right_comm], exact @congr_arg ℕ ℤ _ _ (λi, (i + 1 : ℤ)) (nat.mod_add_div _ _).symm end theorem mod_add_div : ∀ (a b : ℤ), a % b + b * (a / b) = a | (m : ℕ) 0 := congr_arg of_nat (nat.mod_add_div _ _) | (m : ℕ) (n+1:ℕ) := congr_arg of_nat (nat.mod_add_div _ _) | 0 -[1+ n] := rfl | (m+1:ℕ) -[1+ n] := show (_ + -(n+1) * -((m + 1) / (n + 1) : ℕ) : ℤ) = _, by rw [neg_mul_neg]; exact congr_arg of_nat (nat.mod_add_div _ _) | -[1+ m] 0 := by rw [mod_zero, int.div_zero]; refl | -[1+ m] (n+1:ℕ) := mod_add_div_aux m n.succ | -[1+ m] -[1+ n] := mod_add_div_aux m n.succ theorem mod_def (a b : ℤ) : a % b = a - b * (a / b) := eq_sub_of_add_eq (mod_add_div _ _) @[simp] theorem add_mul_mod_self {a b c : ℤ} : (a + b * c) % c = a % c := if cz : c = 0 then by rw [cz, mul_zero, add_zero] else by rw [mod_def, mod_def, int.add_mul_div_right _ _ cz, mul_add, mul_comm, add_sub_add_right_eq_sub] @[simp] theorem add_mul_mod_self_left (a b c : ℤ) : (a + b * c) % b = a % b := by rw [mul_comm, add_mul_mod_self] @[simp] theorem add_mod_self {a b : ℤ} : (a + b) % b = a % b := by have := add_mul_mod_self_left a b 1; rwa mul_one at this @[simp] theorem add_mod_self_left {a b : ℤ} : (a + b) % a = b % a := by rw [add_comm, add_mod_self] @[simp] theorem mod_add_mod (m n k : ℤ) : (m % n + k) % n = (m + k) % n := by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm; rwa [add_right_comm, mod_add_div] at this @[simp] theorem add_mod_mod (m n k : ℤ) : (m + n % k) % k = (m + n) % k := by rw [add_comm, mod_add_mod, add_comm] theorem add_mod_eq_add_mod_right {m n k : ℤ} (i : ℤ) (H : m % n = k % n) : (m + i) % n = (k + i) % n := by rw [← mod_add_mod, ← mod_add_mod k, H] theorem add_mod_eq_add_mod_left {m n k : ℤ} (i : ℤ) (H : m % n = k % n) : (i + m) % n = (i + k) % n := by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm] theorem mod_add_cancel_right {m n k : ℤ} (i) : (m + i) % n = (k + i) % n ↔ m % n = k % n := ⟨λ H, by have := add_mod_eq_add_mod_right (-i) H; rwa [add_neg_cancel_right, add_neg_cancel_right] at this, add_mod_eq_add_mod_right _⟩ theorem mod_add_cancel_left {m n k i : ℤ} : (i + m) % n = (i + k) % n ↔ m % n = k % n := by rw [add_comm, add_comm i, mod_add_cancel_right] theorem mod_sub_cancel_right {m n k : ℤ} (i) : (m - i) % n = (k - i) % n ↔ m % n = k % n := mod_add_cancel_right _ theorem mod_eq_mod_iff_mod_sub_eq_zero {m n k : ℤ} : m % n = k % n ↔ (m - k) % n = 0 := (mod_sub_cancel_right k).symm.trans $ by simp @[simp] theorem mul_mod_left (a b : ℤ) : (a * b) % b = 0 := by rw [← zero_add (a * b), add_mul_mod_self, zero_mod] @[simp] theorem mul_mod_right (a b : ℤ) : (a * b) % a = 0 := by rw [mul_comm, mul_mod_left] @[simp] theorem mod_self {a : ℤ} : a % a = 0 := by have := mul_mod_left 1 a; rwa one_mul at this /- properties of / and % -/ @[simp] theorem mul_div_mul_of_pos {a : ℤ} (b c : ℤ) (H : a > 0) : a * b / (a * c) = b / c := suffices ∀ (m k : ℕ) (b : ℤ), (m.succ * b / (m.succ * k) : ℤ) = b / k, from match a, eq_succ_of_zero_lt H, c, eq_coe_or_neg c with | ._, ⟨m, rfl⟩, ._, ⟨k, or.inl rfl⟩ := this _ _ _ | ._, ⟨m, rfl⟩, ._, ⟨k, or.inr rfl⟩ := by rw [← neg_mul_eq_mul_neg, int.div_neg, int.div_neg]; apply congr_arg has_neg.neg; apply this end, λ m k b, match b, k with | (n : ℕ), k := congr_arg of_nat (nat.mul_div_mul _ _ m.succ_pos) | -[1+ n], 0 := by rw [int.coe_nat_zero, mul_zero, int.div_zero, int.div_zero] | -[1+ n], k+1 := congr_arg neg_succ_of_nat $ show (m.succ * n + m) / (m.succ * k.succ) = n / k.succ, begin apply nat.div_eq_of_lt_le, { refine le_trans _ (nat.le_add_right _ _), rw [← nat.mul_div_mul _ _ m.succ_pos], apply nat.div_mul_le_self }, { change m.succ * n.succ ≤ _, rw [mul_left_comm], apply nat.mul_le_mul_left, apply (nat.div_lt_iff_lt_mul _ _ k.succ_pos).1, apply nat.lt_succ_self } end end @[simp] theorem mul_div_mul_of_pos_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b > 0) : a * b / (c * b) = a / c := by rw [mul_comm, mul_comm c, mul_div_mul_of_pos _ _ H] @[simp] theorem mul_mod_mul_of_pos {a : ℤ} (b c : ℤ) (H : a > 0) : a * b % (a * c) = a * (b % c) := by rw [mod_def, mod_def, mul_div_mul_of_pos _ _ H, mul_sub_left_distrib, mul_assoc] theorem lt_div_add_one_mul_self (a : ℤ) {b : ℤ} (H : b > 0) : a < (a / b + 1) * b := by rw [add_mul, one_mul, mul_comm]; apply lt_add_of_sub_left_lt; rw [← mod_def]; apply mod_lt_of_pos _ H theorem abs_div_le_abs : ∀ (a b : ℤ), abs (a / b) ≤ abs a := suffices ∀ (a : ℤ) (n : ℕ), abs (a / n) ≤ abs a, from λ a b, match b, eq_coe_or_neg b with | ._, ⟨n, or.inl rfl⟩ := this _ _ | ._, ⟨n, or.inr rfl⟩ := by rw [int.div_neg, abs_neg]; apply this end, λ a n, by rw [abs_eq_nat_abs, abs_eq_nat_abs]; exact coe_nat_le_coe_nat_of_le (match a, n with | (m : ℕ), n := nat.div_le_self _ _ | -[1+ m], 0 := nat.zero_le _ | -[1+ m], n+1 := nat.succ_le_succ (nat.div_le_self _ _) end) theorem div_le_self {a : ℤ} (b : ℤ) (Ha : a ≥ 0) : a / b ≤ a := by have := le_trans (le_abs_self _) (abs_div_le_abs a b); rwa [abs_of_nonneg Ha] at this theorem mul_div_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : b * (a / b) = a := by have := mod_add_div a b; rwa [H, zero_add] at this theorem div_mul_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : a / b * b = a := by rw [mul_comm, mul_div_cancel_of_mod_eq_zero H] /- dvd -/ theorem coe_nat_dvd {m n : ℕ} : (↑m : ℤ) ∣ ↑n ↔ m ∣ n := ⟨λ ⟨a, ae⟩, m.eq_zero_or_pos.elim (λm0, by simp [m0] at ae; simp [ae, m0]) (λm0l, by { cases eq_coe_of_zero_le (@nonneg_of_mul_nonneg_left ℤ _ m a (by simp [ae.symm]) (by simpa using m0l)) with k e, subst a, exact ⟨k, int.coe_nat_inj ae⟩ }), λ ⟨k, e⟩, dvd.intro k $ by rw [e, int.coe_nat_mul]⟩ theorem dvd_antisymm {a b : ℤ} (H1 : a ≥ 0) (H2 : b ≥ 0) : a ∣ b → b ∣ a → a = b := begin rw [← abs_of_nonneg H1, ← abs_of_nonneg H2, abs_eq_nat_abs, abs_eq_nat_abs], rw [coe_nat_dvd, coe_nat_dvd, coe_nat_inj'], apply nat.dvd_antisymm end theorem dvd_of_mod_eq_zero {a b : ℤ} (H : b % a = 0) : a ∣ b := ⟨b / a, (mul_div_cancel_of_mod_eq_zero H).symm⟩ theorem mod_eq_zero_of_dvd : ∀ {a b : ℤ}, a ∣ b → b % a = 0 | a ._ ⟨c, rfl⟩ := mul_mod_right _ _ theorem dvd_iff_mod_eq_zero (a b : ℤ) : a ∣ b ↔ b % a = 0 := ⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩ theorem nat_abs_dvd {a b : ℤ} : (a.nat_abs : ℤ) ∣ b ↔ a ∣ b := (nat_abs_eq a).elim (λ e, by rw ← e) (λ e, by rw [← neg_dvd_iff_dvd, ← e]) theorem dvd_nat_abs {a b : ℤ} : a ∣ b.nat_abs ↔ a ∣ b := (nat_abs_eq b).elim (λ e, by rw ← e) (λ e, by rw [← dvd_neg_iff_dvd, ← e]) instance decidable_dvd : @decidable_rel ℤ (∣) := assume a n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm protected theorem div_mul_cancel {a b : ℤ} (H : b ∣ a) : a / b * b = a := div_mul_cancel_of_mod_eq_zero (mod_eq_zero_of_dvd H) protected theorem mul_div_cancel' {a b : ℤ} (H : a ∣ b) : a * (b / a) = b := by rw [mul_comm, int.div_mul_cancel H] protected theorem mul_div_assoc (a : ℤ) : ∀ {b c : ℤ}, c ∣ b → (a * b) / c = a * (b / c) | ._ c ⟨d, rfl⟩ := if cz : c = 0 then by simp [cz] else by rw [mul_left_comm, int.mul_div_cancel_left _ cz, int.mul_div_cancel_left _ cz] theorem div_dvd_div : ∀ {a b c : ℤ} (H1 : a ∣ b) (H2 : b ∣ c), b / a ∣ c / a | a ._ ._ ⟨b, rfl⟩ ⟨c, rfl⟩ := if az : a = 0 then by simp [az] else by rw [int.mul_div_cancel_left _ az, mul_assoc, int.mul_div_cancel_left _ az]; apply dvd_mul_right protected theorem eq_mul_of_div_eq_right {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := by rw [← H2, int.mul_div_cancel' H1] protected theorem div_eq_of_eq_mul_right {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = b * c) : a / b = c := by rw [H2, int.mul_div_cancel_left _ H1] protected theorem div_eq_iff_eq_mul_right {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = b * c := ⟨int.eq_mul_of_div_eq_right H', int.div_eq_of_eq_mul_right H⟩ protected theorem div_eq_iff_eq_mul_left {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = c * b := by rw mul_comm; exact int.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_left {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := by rw [mul_comm, int.eq_mul_of_div_eq_right H1 H2] protected theorem div_eq_of_eq_mul_left {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = c * b) : a / b = c := int.div_eq_of_eq_mul_right H1 (by rw [mul_comm, H2]) theorem neg_div_of_dvd : ∀ {a b : ℤ} (H : b ∣ a), -a / b = -(a / b) | ._ b ⟨c, rfl⟩ := if bz : b = 0 then by simp [bz] else by rw [neg_mul_eq_mul_neg, int.mul_div_cancel_left _ bz, int.mul_div_cancel_left _ bz] theorem div_sign : ∀ a b, a / sign b = a * sign b | a (n+1:ℕ) := by unfold sign; simp | a 0 := by simp [sign] | a -[1+ n] := by simp [sign] @[simp] theorem sign_mul : ∀ a b, sign (a * b) = sign a * sign b | a 0 := by simp | 0 b := by simp | (m+1:ℕ) (n+1:ℕ) := rfl | (m+1:ℕ) -[1+ n] := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl protected theorem sign_eq_div_abs (a : ℤ) : sign a = a / (abs a) := if az : a = 0 then by simp [az] else (int.div_eq_of_eq_mul_left (mt eq_zero_of_abs_eq_zero az) (sign_mul_abs _).symm).symm theorem mul_sign : ∀ (i : ℤ), i * sign i = nat_abs i | (n+1:ℕ) := mul_one _ | 0 := mul_zero _ | -[1+ n] := mul_neg_one _ theorem le_of_dvd {a b : ℤ} (bpos : b > 0) (H : a ∣ b) : a ≤ b := match a, b, eq_succ_of_zero_lt bpos, H with | (m : ℕ), ._, ⟨n, rfl⟩, H := coe_nat_le_coe_nat_of_le $ nat.le_of_dvd n.succ_pos $ coe_nat_dvd.1 H | -[1+ m], ._, ⟨n, rfl⟩, _ := le_trans (le_of_lt $ neg_succ_lt_zero _) (coe_zero_le _) end theorem eq_one_of_dvd_one {a : ℤ} (H : a ≥ 0) (H' : a ∣ 1) : a = 1 := match a, eq_coe_of_zero_le H, H' with | ._, ⟨n, rfl⟩, H' := congr_arg coe $ nat.eq_one_of_dvd_one $ coe_nat_dvd.1 H' end theorem eq_one_of_mul_eq_one_right {a b : ℤ} (H : a ≥ 0) (H' : a * b = 1) : a = 1 := eq_one_of_dvd_one H ⟨b, H'.symm⟩ theorem eq_one_of_mul_eq_one_left {a b : ℤ} (H : b ≥ 0) (H' : a * b = 1) : b = 1 := eq_one_of_mul_eq_one_right H (by rw [mul_comm, H']) /- / and ordering -/ protected theorem div_mul_le (a : ℤ) {b : ℤ} (H : b ≠ 0) : a / b * b ≤ a := le_of_sub_nonneg $ by rw [mul_comm, ← mod_def]; apply mod_nonneg _ H protected theorem div_le_of_le_mul {a b c : ℤ} (H : c > 0) (H' : a ≤ b * c) : a / c ≤ b := le_of_mul_le_mul_right (le_trans (int.div_mul_le _ (ne_of_gt H)) H') H protected theorem mul_lt_of_lt_div {a b c : ℤ} (H : c > 0) (H3 : a < b / c) : a * c < b := lt_of_not_ge $ mt (int.div_le_of_le_mul H) (not_le_of_gt H3) protected theorem mul_le_of_le_div {a b c : ℤ} (H1 : c > 0) (H2 : a ≤ b / c) : a * c ≤ b := le_trans (mul_le_mul_of_nonneg_right H2 (le_of_lt H1)) (int.div_mul_le _ (ne_of_gt H1)) protected theorem le_div_of_mul_le {a b c : ℤ} (H1 : c > 0) (H2 : a * c ≤ b) : a ≤ b / c := le_of_lt_add_one $ lt_of_mul_lt_mul_right (lt_of_le_of_lt H2 (lt_div_add_one_mul_self _ H1)) (le_of_lt H1) protected theorem le_div_iff_mul_le {a b c : ℤ} (H : c > 0) : a ≤ b / c ↔ a * c ≤ b := ⟨int.mul_le_of_le_div H, int.le_div_of_mul_le H⟩ protected theorem div_le_div {a b c : ℤ} (H : c > 0) (H' : a ≤ b) : a / c ≤ b / c := int.le_div_of_mul_le H (le_trans (int.div_mul_le _ (ne_of_gt H)) H') protected theorem div_lt_of_lt_mul {a b c : ℤ} (H : c > 0) (H' : a < b * c) : a / c < b := lt_of_not_ge $ mt (int.mul_le_of_le_div H) (not_le_of_gt H') protected theorem lt_mul_of_div_lt {a b c : ℤ} (H1 : c > 0) (H2 : a / c < b) : a < b * c := lt_of_not_ge $ mt (int.le_div_of_mul_le H1) (not_le_of_gt H2) protected theorem div_lt_iff_lt_mul {a b c : ℤ} (H : c > 0) : a / c < b ↔ a < b * c := ⟨int.lt_mul_of_div_lt H, int.div_lt_of_lt_mul H⟩ protected theorem le_mul_of_div_le {a b c : ℤ} (H1 : b ≥ 0) (H2 : b ∣ a) (H3 : a / b ≤ c) : a ≤ c * b := by rw [← int.div_mul_cancel H2]; exact mul_le_mul_of_nonneg_right H3 H1 protected theorem lt_div_of_mul_lt {a b c : ℤ} (H1 : b ≥ 0) (H2 : b ∣ c) (H3 : a * b < c) : a < c / b := lt_of_not_ge $ mt (int.le_mul_of_div_le H1 H2) (not_le_of_gt H3) protected theorem lt_div_iff_mul_lt {a b : ℤ} (c : ℤ) (H : c > 0) (H' : c ∣ b) : a < b / c ↔ a * c < b := ⟨int.mul_lt_of_lt_div H, int.lt_div_of_mul_lt (le_of_lt H) H'⟩ theorem div_pos_of_pos_of_dvd {a b : ℤ} (H1 : a > 0) (H2 : b ≥ 0) (H3 : b ∣ a) : a / b > 0 := int.lt_div_of_mul_lt H2 H3 (by rwa zero_mul) theorem div_eq_div_of_mul_eq_mul {a b c d : ℤ} (H1 : b ∣ a) (H2 : d ∣ c) (H3 : b ≠ 0) (H4 : d ≠ 0) (H5 : a * d = b * c) : a / b = c / d := int.div_eq_of_eq_mul_right H3 $ by rw [← int.mul_div_assoc _ H2]; exact (int.div_eq_of_eq_mul_left H4 H5.symm).symm theorem of_nat_add_neg_succ_of_nat_of_lt {m n : ℕ} (h : m < n.succ) : of_nat m + -[1+n] = -[1+ n - m] := begin change sub_nat_nat _ _ = _, have h' : n.succ - m = (n - m).succ, apply succ_sub, apply le_of_lt_succ h, simp [*, sub_nat_nat] end theorem of_nat_add_neg_succ_of_nat_of_ge {m n : ℕ} (h : m ≥ n.succ) : of_nat m + -[1+n] = of_nat (m - n.succ) := begin change sub_nat_nat _ _ = _, have h' : n.succ - m = 0, apply sub_eq_zero_of_le h, simp [*, sub_nat_nat] end @[simp] theorem neg_add_neg (m n : ℕ) : -[1+m] + -[1+n] = -[1+nat.succ(m+n)] := rfl /- nat abs -/ attribute [simp] nat_abs nat_abs_of_nat nat_abs_zero nat_abs_one theorem nat_abs_add_le (a b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b := begin have, { refine (λ a b : ℕ, sub_nat_nat_elim a b.succ (λ m n i, n = b.succ → nat_abs i ≤ (m + b).succ) _ _ rfl); intros i n e, { subst e, rw [add_comm _ i, add_assoc], exact nat.le_add_right i (b.succ + b).succ }, { apply succ_le_succ, rw [← succ_inj e, ← add_assoc, add_comm], apply nat.le_add_right } }, cases a; cases b with b b; simp [nat_abs, nat.succ_add]; try {refl}; [skip, rw add_comm a b]; apply this end theorem nat_abs_neg_of_nat (n : nat) : nat_abs (neg_of_nat n) = n := by cases n; refl theorem nat_abs_mul (a b : ℤ) : nat_abs (a * b) = (nat_abs a) * (nat_abs b) := by cases a; cases b; simp [(*), int.mul, nat_abs_neg_of_nat] theorem neg_succ_of_nat_eq' (m : ℕ) : -[1+ m] = -m - 1 := by simp [neg_succ_of_nat_eq] /- to_nat -/ theorem to_nat_eq_max : ∀ (a : ℤ), (to_nat a : ℤ) = max a 0 | (n : ℕ) := (max_eq_left (coe_zero_le n)).symm | -[1+ n] := (max_eq_right (le_of_lt (neg_succ_lt_zero n))).symm @[simp] theorem to_nat_of_nonneg {a : ℤ} (h : 0 ≤ a) : (to_nat a : ℤ) = a := by rw [to_nat_eq_max, max_eq_left h] @[simp] theorem to_nat_coe_nat (n : ℕ) : to_nat ↑n = n := rfl theorem le_to_nat (a : ℤ) : a ≤ to_nat a := by rw [to_nat_eq_max]; apply le_max_left @[simp] theorem to_nat_le (a : ℤ) (n : ℕ) : to_nat a ≤ n ↔ a ≤ n := by rw [(coe_nat_le_coe_nat_iff _ _).symm, to_nat_eq_max, max_le_iff]; exact and_iff_left (coe_zero_le _) /- bitwise ops -/ @[simp] lemma bodd_zero : bodd 0 = ff := rfl @[simp] lemma bodd_one : bodd 1 = tt := rfl @[simp] lemma bodd_two : bodd 2 = ff := rfl @[simp] lemma bodd_sub_nat_nat (m n : ℕ) : bodd (sub_nat_nat m n) = bxor m.bodd n.bodd := by apply sub_nat_nat_elim m n (λ m n i, bodd i = bxor m.bodd n.bodd); intros i m; simp [bodd]; cases i.bodd; cases m.bodd; refl @[simp] lemma bodd_neg_of_nat (n : ℕ) : bodd (neg_of_nat n) = n.bodd := by cases n; simp; refl @[simp] lemma bodd_neg (n : ℤ) : bodd (-n) = bodd n := by cases n; unfold has_neg.neg; simp [int.coe_nat_eq, int.neg, bodd] @[simp] lemma bodd_add (m n : ℤ) : bodd (m + n) = bxor (bodd m) (bodd n) := by cases m with m m; cases n with n n; unfold has_add.add; simp [int.add, bodd]; cases m.bodd; cases n.bodd; refl @[simp] lemma bodd_mul (m n : ℤ) : bodd (m * n) = bodd m && bodd n := by cases m with m m; cases n with n n; unfold has_mul.mul; simp [int.mul, bodd]; cases m.bodd; cases n.bodd; refl theorem bodd_add_div2 : ∀ n, cond (bodd n) 1 0 + 2 * div2 n = n | (n : ℕ) := by rw [show (cond (bodd n) 1 0 : ℤ) = (cond (bodd n) 1 0 : ℕ), by cases bodd n; refl]; exact congr_arg of_nat n.bodd_add_div2 | -[1+ n] := begin refine eq.trans _ (congr_arg neg_succ_of_nat n.bodd_add_div2), dsimp [bodd], cases nat.bodd n; dsimp [cond, bnot, div2, int.mul], { change -[1+ 2 * nat.div2 n] = _, rw zero_add }, { rw [zero_add, add_comm], refl } end theorem div2_val : ∀ n, div2 n = n / 2 | (n : ℕ) := congr_arg of_nat n.div2_val | -[1+ n] := congr_arg neg_succ_of_nat n.div2_val lemma bit0_val (n : ℤ) : bit0 n = 2 * n := (two_mul _).symm lemma bit1_val (n : ℤ) : bit1 n = 2 * n + 1 := congr_arg (+(1:ℤ)) (bit0_val _) lemma bit_val (b n) : bit b n = 2 * n + cond b 1 0 := by { cases b, apply (bit0_val n).trans (add_zero _).symm, apply bit1_val } lemma bit_decomp (n : ℤ) : bit (bodd n) (div2 n) = n := (bit_val _ _).trans $ (add_comm _ _).trans $ bodd_add_div2 _ def {u} bit_cases_on {C : ℤ → Sort u} (n) (h : ∀ b n, C (bit b n)) : C n := by rw [← bit_decomp n]; apply h @[simp] lemma bit_zero : bit ff 0 = 0 := rfl @[simp] lemma bit_coe_nat (b) (n : ℕ) : bit b n = nat.bit b n := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bit_neg_succ (b) (n : ℕ) : bit b -[1+ n] = -[1+ nat.bit (bnot b) n] := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bodd_bit (b n) : bodd (bit b n) = b := by rw bit_val; simp; cases b; cases bodd n; refl @[simp] lemma div2_bit (b n) : div2 (bit b n) = n := begin rw [bit_val, div2_val, add_comm, int.add_mul_div_left, (_ : (_/2:ℤ) = 0), zero_add], cases b, all_goals {exact dec_trivial} end @[simp] lemma test_bit_zero (b) : ∀ n, test_bit (bit b n) 0 = b | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_zero | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_zero]; clear test_bit_zero; cases b; refl @[simp] lemma test_bit_succ (m b) : ∀ n, test_bit (bit b n) (nat.succ m) = test_bit n m | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_succ | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_succ] private meta def bitwise_tac : tactic unit := `[ funext m, funext n, cases m with m m; cases n with n n; try {refl}, all_goals { apply congr_arg of_nat <|> apply congr_arg neg_succ_of_nat, try {dsimp [nat.land, nat.ldiff, nat.lor]}, try {rw [ show nat.bitwise (λ a b, a && bnot b) n m = nat.bitwise (λ a b, b && bnot a) m n, from congr_fun (congr_fun (@nat.bitwise_swap (λ a b, b && bnot a) rfl) n) m]}, apply congr_arg (λ f, nat.bitwise f m n), funext a, funext b, cases a; cases b; refl }, all_goals {unfold nat.land nat.ldiff nat.lor} ] theorem bitwise_or : bitwise bor = lor := by bitwise_tac theorem bitwise_and : bitwise band = land := by bitwise_tac theorem bitwise_diff : bitwise (λ a b, a && bnot b) = ldiff := by bitwise_tac theorem bitwise_xor : bitwise bxor = lxor := by bitwise_tac @[simp] lemma bitwise_bit (f : bool → bool → bool) (a m b n) : bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) := begin cases m with m m; cases n with n n; repeat { rw [← int.coe_nat_eq] <|> rw bit_coe_nat <|> rw bit_neg_succ }; unfold bitwise nat_bitwise bnot; [ induction h : f ff ff, induction h : f ff tt, induction h : f tt ff, induction h : f tt tt ], all_goals { unfold cond, rw nat.bitwise_bit, repeat { rw bit_coe_nat <|> rw bit_neg_succ <|> rw bnot_bnot } }, all_goals { unfold bnot {fail_if_unchanged := ff}; rw h; refl } end @[simp] lemma lor_bit (a m b n) : lor (bit a m) (bit b n) = bit (a || b) (lor m n) := by rw [← bitwise_or, bitwise_bit] @[simp] lemma land_bit (a m b n) : land (bit a m) (bit b n) = bit (a && b) (land m n) := by rw [← bitwise_and, bitwise_bit] @[simp] lemma ldiff_bit (a m b n) : ldiff (bit a m) (bit b n) = bit (a && bnot b) (ldiff m n) := by rw [← bitwise_diff, bitwise_bit] @[simp] lemma lxor_bit (a m b n) : lxor (bit a m) (bit b n) = bit (bxor a b) (lxor m n) := by rw [← bitwise_xor, bitwise_bit] @[simp] lemma lnot_bit (b) : ∀ n, lnot (bit b n) = bit (bnot b) (lnot n) | (n : ℕ) := by simp [lnot] | -[1+ n] := by simp [lnot] @[simp] lemma test_bit_bitwise (f : bool → bool → bool) (m n k) : test_bit (bitwise f m n) k = f (test_bit m k) (test_bit n k) := begin induction k with k IH generalizing m n; apply bit_cases_on m; intros a m'; apply bit_cases_on n; intros b n'; rw bitwise_bit, { simp [test_bit_zero] }, { simp [test_bit_succ, IH] } end @[simp] lemma test_bit_lor (m n k) : test_bit (lor m n) k = test_bit m k || test_bit n k := by rw [← bitwise_or, test_bit_bitwise] @[simp] lemma test_bit_land (m n k) : test_bit (land m n) k = test_bit m k && test_bit n k := by rw [← bitwise_and, test_bit_bitwise] @[simp] lemma test_bit_ldiff (m n k) : test_bit (ldiff m n) k = test_bit m k && bnot (test_bit n k) := by rw [← bitwise_diff, test_bit_bitwise] @[simp] lemma test_bit_lxor (m n k) : test_bit (lxor m n) k = bxor (test_bit m k) (test_bit n k) := by rw [← bitwise_xor, test_bit_bitwise] @[simp] lemma test_bit_lnot : ∀ n k, test_bit (lnot n) k = bnot (test_bit n k) | (n : ℕ) k := by simp [lnot, test_bit] | -[1+ n] k := by simp [lnot, test_bit] lemma shiftl_add : ∀ (m : ℤ) (n : ℕ) (k : ℤ), shiftl m (n + k) = shiftl (shiftl m n) k | (m : ℕ) n (k:ℕ) := congr_arg of_nat (nat.shiftl_add _ _ _) | -[1+ m] n (k:ℕ) := congr_arg neg_succ_of_nat (nat.shiftl'_add _ _ _ _) | (m : ℕ) n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl ↑m i = nat.shiftr (nat.shiftl m n) k) (λ i n, congr_arg coe $ by rw [← nat.shiftl_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg coe $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl_sub, nat.sub_self]; refl) | -[1+ m] n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl -[1+ m] i = -[1+ nat.shiftr (nat.shiftl' tt m n) k]) (λ i n, congr_arg neg_succ_of_nat $ by rw [← nat.shiftl'_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg neg_succ_of_nat $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl'_sub, nat.sub_self]; refl) lemma shiftl_sub (m : ℤ) (n : ℕ) (k : ℤ) : shiftl m (n - k) = shiftr (shiftl m n) k := shiftl_add _ _ _ @[simp] lemma shiftl_neg (m n : ℤ) : shiftl m (-n) = shiftr m n := rfl @[simp] lemma shiftr_neg (m n : ℤ) : shiftr m (-n) = shiftl m n := by rw [← shiftl_neg, neg_neg] @[simp] lemma shiftl_coe_nat (m n : ℕ) : shiftl m n = nat.shiftl m n := rfl @[simp] lemma shiftr_coe_nat (m n : ℕ) : shiftr m n = nat.shiftr m n := by cases n; refl @[simp] lemma shiftl_neg_succ (m n : ℕ) : shiftl -[1+ m] n = -[1+ nat.shiftl' tt m n] := rfl @[simp] lemma shiftr_neg_succ (m n : ℕ) : shiftr -[1+ m] n = -[1+ nat.shiftr m n] := by cases n; refl lemma shiftr_add : ∀ (m : ℤ) (n k : ℕ), shiftr m (n + k) = shiftr (shiftr m n) k | (m : ℕ) n k := by rw [shiftr_coe_nat, shiftr_coe_nat, ← int.coe_nat_add, shiftr_coe_nat, nat.shiftr_add] | -[1+ m] n k := by rw [shiftr_neg_succ, shiftr_neg_succ, ← int.coe_nat_add, shiftr_neg_succ, nat.shiftr_add] lemma shiftl_eq_mul_pow : ∀ (m : ℤ) (n : ℕ), shiftl m n = m * 2 ^ n | (m : ℕ) n := congr_arg coe (nat.shiftl_eq_mul_pow _ _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λi, -i) (nat.shiftl'_tt_eq_mul_pow _ _) lemma shiftr_eq_div_pow : ∀ (m : ℤ) (n : ℕ), shiftr m n = m / 2 ^ n | (m : ℕ) n := by rw shiftr_coe_nat; exact congr_arg coe (nat.shiftr_eq_div_pow _ _) | -[1+ m] n := begin rw [shiftr_neg_succ, neg_succ_of_nat_div, nat.shiftr_eq_div_pow], refl, exact coe_nat_lt_coe_nat_of_lt (nat.pos_pow_of_pos _ dec_trivial) end lemma one_shiftl (n : ℕ) : shiftl 1 n = (2 ^ n : ℕ) := congr_arg coe (nat.one_shiftl _) @[simp] lemma zero_shiftl : ∀ n : ℤ, shiftl 0 n = 0 | (n : ℕ) := congr_arg coe (nat.zero_shiftl _) | -[1+ n] := congr_arg coe (nat.zero_shiftr _) @[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 := zero_shiftl _ /- Least upper bound property for integers -/ theorem exists_least_of_bdd {P : ℤ → Prop} [HP : decidable_pred P] (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → b ≤ z) (Hinh : ∃ z : ℤ, P z) : ∃ lb : ℤ, P lb ∧ (∀ z : ℤ, P z → lb ≤ z) := let ⟨b, Hb⟩ := Hbdd in have EX : ∃ n : ℕ, P (b + n), from let ⟨elt, Helt⟩ := Hinh in match elt, le.dest (Hb _ Helt), Helt with | ._, ⟨n, rfl⟩, Hn := ⟨n, Hn⟩ end, ⟨b + (nat.find EX : ℤ), nat.find_spec EX, λ z h, match z, le.dest (Hb _ h), h with | ._, ⟨n, rfl⟩, h := add_le_add_left (int.coe_nat_le.2 $ nat.find_min' _ h) _ end⟩ theorem exists_greatest_of_bdd {P : ℤ → Prop} [HP : decidable_pred P] (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → z ≤ b) (Hinh : ∃ z : ℤ, P z) : ∃ ub : ℤ, P ub ∧ (∀ z : ℤ, P z → z ≤ ub) := have Hbdd' : ∃ (b : ℤ), ∀ (z : ℤ), P (-z) → b ≤ z, from let ⟨b, Hb⟩ := Hbdd in ⟨-b, λ z h, neg_le.1 (Hb _ h)⟩, have Hinh' : ∃ z : ℤ, P (-z), from let ⟨elt, Helt⟩ := Hinh in ⟨-elt, by rw [neg_neg]; exact Helt⟩, let ⟨lb, Plb, al⟩ := exists_least_of_bdd Hbdd' Hinh' in ⟨-lb, Plb, λ z h, le_neg.1 $ al _ $ by rwa neg_neg⟩ /- cast (injection into groups with one) -/ @[simp] theorem nat_cast_eq_coe_nat : ∀ n, @coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ nat.cast_coe)) n = @coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ int.has_coe)) n | 0 := rfl | (n+1) := congr_arg (+(1:ℤ)) (nat_cast_eq_coe_nat n) section cast variables {α : Type*} section variables [has_zero α] [has_one α] [has_add α] [has_neg α] /-- Canonical homomorphism from the integers to any ring(-like) structure `α` -/ protected def cast : ℤ → α | (n : ℕ) := n | -[1+ n] := -(n+1) @[priority 0] instance cast_coe : has_coe ℤ α := ⟨int.cast⟩ @[simp] theorem cast_zero : ((0 : ℤ) : α) = 0 := rfl @[simp] theorem cast_of_nat (n : ℕ) : (of_nat n : α) = n := rfl @[simp] theorem cast_coe_nat (n : ℕ) : ((n : ℤ) : α) = n := rfl @[simp] theorem cast_coe_nat' (n : ℕ) : (@coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ nat.cast_coe)) n : α) = n := by simp @[simp] theorem cast_neg_succ_of_nat (n : ℕ) : (-[1+ n] : α) = -(n + 1) := rfl end @[simp] theorem cast_one [add_monoid α] [has_one α] [has_neg α] : ((1 : ℤ) : α) = 1 := nat.cast_one @[simp] theorem cast_sub_nat_nat [add_group α] [has_one α] (m n) : ((int.sub_nat_nat m n : ℤ) : α) = m - n := begin unfold sub_nat_nat, cases e : n - m, { simp [sub_nat_nat, e, nat.le_of_sub_eq_zero e] }, { rw [sub_nat_nat, cast_neg_succ_of_nat, ← nat.cast_succ, ← e, nat.cast_sub $ _root_.le_of_lt $ nat.lt_of_sub_eq_succ e, neg_sub] }, end @[simp] theorem cast_neg_of_nat [add_group α] [has_one α] : ∀ n, ((neg_of_nat n : ℤ) : α) = -n | 0 := neg_zero.symm | (n+1) := rfl @[simp] theorem cast_add [add_group α] [has_one α] : ∀ m n, ((m + n : ℤ) : α) = m + n | (m : ℕ) (n : ℕ) := nat.cast_add _ _ | (m : ℕ) -[1+ n] := cast_sub_nat_nat _ _ | -[1+ m] (n : ℕ) := (cast_sub_nat_nat _ _).trans $ sub_eq_of_eq_add $ show (n:α) = -(m+1) + n + (m+1), by rw [add_assoc, ← cast_succ, ← nat.cast_add, add_comm, nat.cast_add, cast_succ, neg_add_cancel_left] | -[1+ m] -[1+ n] := show -((m + n + 1 + 1 : ℕ) : α) = -(m + 1) + -(n + 1), by rw [← neg_add_rev, ← nat.cast_add_one, ← nat.cast_add_one, ← nat.cast_add]; apply congr_arg (λ x:ℕ, -(x:α)); simp @[simp] theorem cast_neg [add_group α] [has_one α] : ∀ n, ((-n : ℤ) : α) = -n | (n : ℕ) := cast_neg_of_nat _ | -[1+ n] := (neg_neg _).symm theorem cast_sub [add_group α] [has_one α] (m n) : ((m - n : ℤ) : α) = m - n := by simp @[simp] theorem cast_eq_zero [add_group α] [has_one α] [char_zero α] {n : ℤ} : (n : α) = 0 ↔ n = 0 := ⟨λ h, begin cases n, { exact congr_arg coe (nat.cast_eq_zero.1 h) }, { rw [cast_neg_succ_of_nat, neg_eq_zero, ← cast_succ, nat.cast_eq_zero] at h, contradiction } end, λ h, by rw [h, cast_zero]⟩ @[simp] theorem cast_inj [add_group α] [has_one α] [char_zero α] {m n : ℤ} : (m : α) = n ↔ m = n := by rw [← sub_eq_zero, ← cast_sub, cast_eq_zero, sub_eq_zero] theorem cast_injective [add_group α] [has_one α] [char_zero α] : function.injective (coe : ℤ → α) | m n := cast_inj.1 @[simp] theorem cast_ne_zero [add_group α] [has_one α] [char_zero α] {n : ℤ} : (n : α) ≠ 0 ↔ n ≠ 0 := not_congr cast_eq_zero @[simp] theorem cast_mul [ring α] : ∀ m n, ((m * n : ℤ) : α) = m * n | (m : ℕ) (n : ℕ) := nat.cast_mul _ _ | (m : ℕ) -[1+ n] := (cast_neg_of_nat _).trans $ show (-(m * (n + 1) : ℕ) : α) = m * -(n + 1), by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_mul_neg] | -[1+ m] (n : ℕ) := (cast_neg_of_nat _).trans $ show (-((m + 1) * n : ℕ) : α) = -(m + 1) * n, by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_neg_mul] | -[1+ m] -[1+ n] := show (((m + 1) * (n + 1) : ℕ) : α) = -(m + 1) * -(n + 1), by rw [nat.cast_mul, nat.cast_add_one, nat.cast_add_one, neg_mul_neg] theorem mul_cast_comm [ring α] (a : α) (n : ℤ) : a * n = n * a := by cases n; simp [nat.mul_cast_comm, left_distrib, right_distrib, *] @[simp] theorem cast_bit0 [ring α] (n : ℤ) : ((bit0 n : ℤ) : α) = bit0 n := cast_add _ _ @[simp] theorem cast_bit1 [ring α] (n : ℤ) : ((bit1 n : ℤ) : α) = bit1 n := by rw [bit1, cast_add, cast_one, cast_bit0]; refl theorem cast_nonneg [linear_ordered_ring α] : ∀ {n : ℤ}, (0 : α) ≤ n ↔ 0 ≤ n | (n : ℕ) := by simp | -[1+ n] := by simpa [not_le_of_gt (neg_succ_lt_zero n)] using show -(n:α) < 1, from lt_of_le_of_lt (by simp) zero_lt_one @[simp] theorem cast_le [linear_ordered_ring α] {m n : ℤ} : (m : α) ≤ n ↔ m ≤ n := by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg] @[simp] theorem cast_lt [linear_ordered_ring α] {m n : ℤ} : (m : α) < n ↔ m < n := by simpa [-cast_le] using not_congr (@cast_le α _ n m) @[simp] theorem cast_nonpos [linear_ordered_ring α] {n : ℤ} : (n : α) ≤ 0 ↔ n ≤ 0 := by rw [← cast_zero, cast_le] @[simp] theorem cast_pos [linear_ordered_ring α] {n : ℤ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] @[simp] theorem cast_lt_zero [linear_ordered_ring α] {n : ℤ} : (n : α) < 0 ↔ n < 0 := by rw [← cast_zero, cast_lt] theorem eq_cast [add_group α] [has_one α] (f : ℤ → α) (H1 : f 1 = 1) (Hadd : ∀ x y, f (x + y) = f x + f y) (n : ℤ) : f n = n := begin have H : ∀ (n : ℕ), f n = n := nat.eq_cast' (λ n, f n) H1 (λ x y, Hadd x y), cases n, {apply H}, apply eq_neg_of_add_eq_zero, rw [← nat.cast_zero, ← H 0, int.coe_nat_zero, ← show -[1+ n] + (↑n + 1) = 0, from neg_add_self (↑n+1), Hadd, show f (n+1) = n+1, from H (n+1)] end @[simp] theorem cast_id (n : ℤ) : ↑n = n := (eq_cast id rfl (λ _ _, rfl) n).symm @[simp] theorem cast_min [decidable_linear_ordered_comm_ring α] {a b : ℤ} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [h, min] @[simp] theorem cast_max [decidable_linear_ordered_comm_ring α] {a b : ℤ} : (↑(max a b) : α) = max a b := by by_cases a ≤ b; simp [h, max] @[simp] theorem cast_abs [decidable_linear_ordered_comm_ring α] {q : ℤ} : ((abs q : ℤ) : α) = abs q := by simp [abs] end cast end int
1db61ee4835fe6128f088523122329ad75276345
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/stage0/src/Init/Data/Array/Basic.lean
1c16673ed804ca3e8b4c7c22783b789ab138dd33
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
27,439
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.Nat.Basic import Init.Data.Fin.Basic import Init.Data.UInt import Init.Data.Repr import Init.Data.ToString.Basic import Init.Util universes u v w namespace Array variable {α : Type u} @[extern "lean_mk_array"] def mkArray {α : Type u} (n : Nat) (v : α) : Array α := { data := List.replicate n v } @[simp] theorem size_mkArray (n : Nat) (v : α) : (mkArray n v).size = n := List.length_replicate .. instance : EmptyCollection (Array α) := ⟨Array.empty⟩ instance : Inhabited (Array α) where default := Array.empty def isEmpty (a : Array α) : Bool := a.size = 0 def singleton (v : α) : Array α := mkArray 1 v /- Low-level version of `fget` which is as fast as a C array read. `Fin` values are represented as tag pointers in the Lean runtime. Thus, `fget` may be slightly slower than `uget`. -/ @[extern "lean_array_uget"] def uget (a : @& Array α) (i : USize) (h : i.toNat < a.size) : α := a.get ⟨i.toNat, h⟩ def back [Inhabited α] (a : Array α) : α := a.get! (a.size - 1) def get? (a : Array α) (i : Nat) : Option α := if h : i < a.size then some (a.get ⟨i, h⟩) else none def back? (a : Array α) : Option α := a.get? (a.size - 1) -- auxiliary declaration used in the equation compiler when pattern matching array literals. abbrev getLit {α : Type u} {n : Nat} (a : Array α) (i : Nat) (h₁ : a.size = n) (h₂ : i < n) : α := a.get ⟨i, h₁.symm ▸ h₂⟩ @[simp] theorem size_set (a : Array α) (i : Fin a.size) (v : α) : (set a i v).size = a.size := List.length_set .. @[simp] theorem size_push (a : Array α) (v : α) : (push a v).size = a.size + 1 := List.length_concat .. /- Low-level version of `fset` which is as fast as a C array fset. `Fin` values are represented as tag pointers in the Lean runtime. Thus, `fset` may be slightly slower than `uset`. -/ @[extern "lean_array_uset"] def uset (a : Array α) (i : USize) (v : α) (h : i.toNat < a.size) : Array α := a.set ⟨i.toNat, h⟩ v @[extern "lean_array_fswap"] def swap (a : Array α) (i j : @& Fin a.size) : Array α := let v₁ := a.get i let v₂ := a.get j let a' := a.set i v₂ a'.set (size_set a i v₂ ▸ j) v₁ @[extern "lean_array_swap"] def swap! (a : Array α) (i j : @& Nat) : Array α := if h₁ : i < a.size then if h₂ : j < a.size then swap a ⟨i, h₁⟩ ⟨j, h₂⟩ else panic! "index out of bounds" else panic! "index out of bounds" @[inline] def swapAt (a : Array α) (i : Fin a.size) (v : α) : α × Array α := let e := a.get i let a := a.set i v (e, a) @[inline] def swapAt! (a : Array α) (i : Nat) (v : α) : α × Array α := if h : i < a.size then swapAt a ⟨i, h⟩ v else have Inhabited α from ⟨v⟩ panic! ("index " ++ toString i ++ " out of bounds") @[extern "lean_array_pop"] def pop (a : Array α) : Array α := { data := a.data.dropLast } def shrink (a : Array α) (n : Nat) : Array α := let rec loop | 0, a => a | n+1, a => loop n a.pop loop (a.size - n) a @[inline] def modifyM [Monad m] [Inhabited α] (a : Array α) (i : Nat) (f : α → m α) : m (Array α) := do if h : i < a.size then let idx : Fin a.size := ⟨i, h⟩ let v := a.get idx let a' := a.set idx arbitrary let v ← f v pure <| a'.set (size_set a .. ▸ idx) v else pure a @[inline] def modify [Inhabited α] (a : Array α) (i : Nat) (f : α → α) : Array α := Id.run <| a.modifyM i f @[inline] def modifyOp [Inhabited α] (self : Array α) (idx : Nat) (f : α → α) : Array α := self.modify idx f /- We claim this unsafe implementation is correct because an array cannot have more than `usizeSz` elements in our runtime. This kind of low level trick can be removed with a little bit of compiler support. For example, if the compiler simplifies `as.size < usizeSz` to true. -/ @[inline] unsafe def forInUnsafe {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (b : β) (f : α → β → m (ForInStep β)) : m β := let sz := USize.ofNat as.size let rec @[specialize] loop (i : USize) (b : β) : m β := do if i < sz then let a := as.uget i lcProof match (← f a b) with | ForInStep.done b => pure b | ForInStep.yield b => loop (i+1) b else pure b loop 0 b -- Move? private theorem zeroLtOfLt : {a b : Nat} → a < b → 0 < b | 0, _, h => h | a+1, b, h => have a < b from Nat.ltTrans (Nat.ltSuccSelf _) h zeroLtOfLt this /- Reference implementation for `forIn` -/ @[implementedBy Array.forInUnsafe] protected def forIn {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (b : β) (f : α → β → m (ForInStep β)) : m β := let rec loop (i : Nat) (h : i ≤ as.size) (b : β) : m β := do match i, h with | 0, _ => pure b | i+1, h => have h' : i < as.size from Nat.ltOfLtOfLe (Nat.ltSuccSelf i) h have as.size - 1 < as.size from Nat.subLt (zeroLtOfLt h') (decide! : 0 < 1) have as.size - 1 - i < as.size from Nat.ltOfLeOfLt (Nat.subLe (as.size - 1) i) this match (← f (as.get ⟨as.size - 1 - i, this⟩) b) with | ForInStep.done b => pure b | ForInStep.yield b => loop i (Nat.leOfLt h') b loop as.size (Nat.leRefl _) b instance : ForIn m (Array α) α where forIn := Array.forIn /- See comment at forInUnsafe -/ @[inline] unsafe def foldlMUnsafe {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : β → α → m β) (init : β) (as : Array α) (start := 0) (stop := as.size) : m β := let rec @[specialize] fold (i : USize) (stop : USize) (b : β) : m β := do if i == stop then pure b else fold (i+1) stop (← f b (as.uget i lcProof)) if start < stop then if stop ≤ as.size then fold (USize.ofNat start) (USize.ofNat stop) init else pure init else pure init /- Reference implementation for `foldlM` -/ @[implementedBy foldlMUnsafe] def foldlM {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : β → α → m β) (init : β) (as : Array α) (start := 0) (stop := as.size) : m β := let fold (stop : Nat) (h : stop ≤ as.size) := let rec loop (i : Nat) (j : Nat) (b : β) : m β := do if hlt : j < stop then match i with | 0 => pure b | i'+1 => loop i' (j+1) (← f b (as.get ⟨j, Nat.ltOfLtOfLe hlt h⟩)) else pure b loop (stop - start) start init if h : stop ≤ as.size then fold stop h else fold as.size (Nat.leRefl _) /- See comment at forInUnsafe -/ @[inline] unsafe def foldrMUnsafe {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : α → β → m β) (init : β) (as : Array α) (start := as.size) (stop := 0) : m β := let rec @[specialize] fold (i : USize) (stop : USize) (b : β) : m β := do if i == stop then pure b else fold (i-1) stop (← f (as.uget (i-1) lcProof) b) if start ≤ as.size then if stop < start then fold (USize.ofNat start) (USize.ofNat stop) init else pure init else if stop < as.size then fold (USize.ofNat as.size) (USize.ofNat stop) init else pure init /- Reference implementation for `foldrM` -/ @[implementedBy foldrMUnsafe] def foldrM {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : α → β → m β) (init : β) (as : Array α) (start := as.size) (stop := 0) : m β := let rec fold (i : Nat) (h : i ≤ as.size) (b : β) : m β := do if i == stop then pure b else match i, h with | 0, _ => pure b | i+1, h => have i < as.size from Nat.ltOfLtOfLe (Nat.ltSuccSelf _) h fold i (Nat.leOfLt this) (← f (as.get ⟨i, this⟩) b) if h : start ≤ as.size then if stop < start then fold start h init else pure init else if stop < as.size then fold as.size (Nat.leRefl _) init else pure init /- See comment at forInUnsafe -/ @[inline] unsafe def mapMUnsafe {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : α → m β) (as : Array α) : m (Array β) := let sz := USize.ofNat as.size let rec @[specialize] map (i : USize) (r : Array NonScalar) : m (Array PNonScalar.{v}) := do if i < sz then let v := r.uget i lcProof let r := r.uset i arbitrary lcProof let vNew ← f (unsafeCast v) map (i+1) (r.uset i (unsafeCast vNew) lcProof) else pure (unsafeCast r) unsafeCast <| map 0 (unsafeCast as) /- Reference implementation for `mapM` -/ @[implementedBy mapMUnsafe] def mapM {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : α → m β) (as : Array α) : m (Array β) := as.foldlM (fun bs a => do let b ← f a; pure (bs.push b)) (mkEmpty as.size) @[inline] def mapIdxM {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : Fin as.size → α → m β) : m (Array β) := let rec @[specialize] map (i : Nat) (j : Nat) (inv : i + j = as.size) (bs : Array β) : m (Array β) := do match i, inv with | 0, _ => pure bs | i+1, inv => have j < as.size by rw [← inv, Nat.add_assoc, Nat.add_comm 1 j, Nat.add_left_comm]; apply Nat.leAddRight let idx : Fin as.size := ⟨j, this⟩ have i + (j + 1) = as.size by rw [← inv, Nat.add_comm j 1, Nat.add_assoc] map i (j+1) this (bs.push (← f idx (as.get idx))) map as.size 0 rfl (mkEmpty as.size) @[inline] def findSomeM? {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : α → m (Option β)) : m (Option β) := do for a in as do match (← f a) with | some b => return b | _ => pure ⟨⟩ return none @[inline] def findM? {α : Type} {m : Type → Type} [Monad m] (as : Array α) (p : α → m Bool) : m (Option α) := do for a in as do if (← p a) then return a return none @[inline] def findIdxM? [Monad m] (as : Array α) (p : α → m Bool) : m (Option Nat) := do let mut i := 0 for a in as do if (← p a) then return some i i := i + 1 return none @[inline] unsafe def anyMUnsafe {α : Type u} {m : Type → Type w} [Monad m] (p : α → m Bool) (as : Array α) (start := 0) (stop := as.size) : m Bool := let rec @[specialize] any (i : USize) (stop : USize) : m Bool := do if i == stop then pure false else if (← p (as.uget i lcProof)) then pure true else any (i+1) stop if start < stop then if stop ≤ as.size then any (USize.ofNat start) (USize.ofNat stop) else pure false else pure false @[implementedBy anyMUnsafe] def anyM {α : Type u} {m : Type → Type w} [Monad m] (p : α → m Bool) (as : Array α) (start := 0) (stop := as.size) : m Bool := let any (stop : Nat) (h : stop ≤ as.size) := let rec loop (i : Nat) (j : Nat) : m Bool := do if hlt : j < stop then match i with | 0 => pure false | i'+1 => if (← p (as.get ⟨j, Nat.ltOfLtOfLe hlt h⟩)) then pure true else loop i' (j+1) else pure false loop (stop - start) start if h : stop ≤ as.size then any stop h else any as.size (Nat.leRefl _) @[inline] def allM {α : Type u} {m : Type → Type w} [Monad m] (p : α → m Bool) (as : Array α) (start := 0) (stop := as.size) : m Bool := return !(← as.anyM fun v => return !(← p v)) @[inline] def findSomeRevM? {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : α → m (Option β)) : m (Option β) := let rec @[specialize] find : (i : Nat) → i ≤ as.size → m (Option β) | 0, h => pure none | i+1, h => do have i < as.size from Nat.ltOfLtOfLe (Nat.ltSuccSelf _) h let r ← f (as.get ⟨i, this⟩) match r with | some v => pure r | none => have i ≤ as.size from Nat.leOfLt this find i this find as.size (Nat.leRefl _) @[inline] def findRevM? {α : Type} {m : Type → Type w} [Monad m] (as : Array α) (p : α → m Bool) : m (Option α) := as.findSomeRevM? fun a => return if (← p a) then some a else none @[inline] def forM {α : Type u} {m : Type v → Type w} [Monad m] (f : α → m PUnit) (as : Array α) (start := 0) (stop := as.size) : m PUnit := as.foldlM (fun _ => f) ⟨⟩ start stop @[inline] def forRevM {α : Type u} {m : Type v → Type w} [Monad m] (f : α → m PUnit) (as : Array α) (start := as.size) (stop := 0) : m PUnit := as.foldrM (fun a _ => f a) ⟨⟩ start stop @[inline] def foldl {α : Type u} {β : Type v} (f : β → α → β) (init : β) (as : Array α) (start := 0) (stop := as.size) : β := Id.run <| as.foldlM f init start stop @[inline] def foldr {α : Type u} {β : Type v} (f : α → β → β) (init : β) (as : Array α) (start := as.size) (stop := 0) : β := Id.run <| as.foldrM f init start stop @[inline] def map {α : Type u} {β : Type v} (f : α → β) (as : Array α) : Array β := Id.run <| as.mapM f @[inline] def mapIdx {α : Type u} {β : Type v} (as : Array α) (f : Fin as.size → α → β) : Array β := Id.run <| as.mapIdxM f @[inline] def find? {α : Type} (as : Array α) (p : α → Bool) : Option α := Id.run <| as.findM? p @[inline] def findSome? {α : Type u} {β : Type v} (as : Array α) (f : α → Option β) : Option β := Id.run <| as.findSomeM? f @[inline] def findSome! {α : Type u} {β : Type v} [Inhabited β] (a : Array α) (f : α → Option β) : β := match findSome? a f with | some b => b | none => panic! "failed to find element" @[inline] def findSomeRev? {α : Type u} {β : Type v} (as : Array α) (f : α → Option β) : Option β := Id.run <| as.findSomeRevM? f @[inline] def findRev? {α : Type} (as : Array α) (p : α → Bool) : Option α := Id.run <| as.findRevM? p @[inline] def findIdx? {α : Type u} (as : Array α) (p : α → Bool) : Option Nat := let rec loop (i : Nat) (j : Nat) (inv : i + j = as.size) : Option Nat := if hlt : j < as.size then match i, inv with | 0, inv => by apply False.elim rw [Nat.zero_add] at inv rw [inv] at hlt exact absurd hlt (Nat.ltIrrefl _) | i+1, inv => if p (as.get ⟨j, hlt⟩) then some j else have i + (j+1) = as.size by rw [← inv, Nat.add_comm j 1, Nat.add_assoc] loop i (j+1) this else none loop as.size 0 rfl def getIdx? [BEq α] (a : Array α) (v : α) : Option Nat := a.findIdx? fun a => a == v @[inline] def any (as : Array α) (p : α → Bool) (start := 0) (stop := as.size) : Bool := Id.run <| as.anyM p start stop @[inline] def all (as : Array α) (p : α → Bool) (start := 0) (stop := as.size) : Bool := Id.run <| as.allM p start stop def contains [BEq α] (as : Array α) (a : α) : Bool := as.any fun b => a == b def elem [BEq α] (a : α) (as : Array α) : Bool := as.contains a -- TODO(Leo): justify termination using wf-rec, and use `swap` partial def reverse (as : Array α) : Array α := let n := as.size let mid := n / 2 let rec rev (as : Array α) (i : Nat) := if i < mid then rev (as.swap! i (n - i - 1)) (i+1) else as rev as 0 @[inline] def getEvenElems (as : Array α) : Array α := (·.2) <| as.foldl (init := (true, Array.empty)) fun (even, r) a => if even then (false, r.push a) else (true, r) @[export lean_array_to_list] def toList (as : Array α) : List α := as.foldr List.cons [] instance {α : Type u} [Repr α] : Repr (Array α) where reprPrec a _ := if a.size == 0 then "#[]" else Std.Format.bracketFill "#[" (@Std.Format.joinSep _ ⟨repr⟩ (toList a) ("," ++ Std.Format.line)) "]" instance [ToString α] : ToString (Array α) where toString a := "#" ++ toString a.toList protected def append (as : Array α) (bs : Array α) : Array α := bs.foldl (init := as) fun r v => r.push v instance : Append (Array α) := ⟨Array.append⟩ @[inline] def concatMapM [Monad m] (f : α → m (Array β)) (as : Array α) : m (Array β) := as.foldlM (init := empty) fun bs a => do return bs ++ (← f a) @[inline] def concatMap (f : α → Array β) (as : Array α) : Array β := as.foldl (init := empty) fun bs a => bs ++ f a end Array @[inlineIfReduce] def List.toArrayAux : List α → Array α → Array α | [], r => r | a::as, r => toArrayAux as (r.push a) @[inlineIfReduce] def List.redLength : List α → Nat | [] => 0 | _::as => as.redLength + 1 @[inline, matchPattern, export lean_list_to_array] def List.toArray (as : List α) : Array α := as.toArrayAux (Array.mkEmpty as.redLength) export Array (mkArray) syntax "#[" sepBy(term, ", ") "]" : term macro_rules | `(#[ $elems,* ]) => `(List.toArray [ $elems,* ]) namespace Array -- TODO(Leo): cleanup @[specialize] partial def isEqvAux (a b : Array α) (hsz : a.size = b.size) (p : α → α → Bool) (i : Nat) : Bool := if h : i < a.size then let aidx : Fin a.size := ⟨i, h⟩; let bidx : Fin b.size := ⟨i, hsz ▸ h⟩; match p (a.get aidx) (b.get bidx) with | true => isEqvAux a b hsz p (i+1) | false => false else true @[inline] def isEqv (a b : Array α) (p : α → α → Bool) : Bool := if h : a.size = b.size then isEqvAux a b h p 0 else false instance [BEq α] : BEq (Array α) := ⟨fun a b => isEqv a b BEq.beq⟩ @[inline] def filter (p : α → Bool) (as : Array α) (start := 0) (stop := as.size) : Array α := as.foldl (init := #[]) (start := start) (stop := stop) fun r a => if p a then r.push a else r @[inline] def filterM [Monad m] (p : α → m Bool) (as : Array α) (start := 0) (stop := as.size) : m (Array α) := as.foldlM (init := #[]) (start := start) (stop := stop) fun r a => do if (← p a) then r.push a else r @[specialize] def filterMapM [Monad m] (f : α → m (Option β)) (as : Array α) (start := 0) (stop := as.size) : m (Array β) := as.foldlM (init := #[]) (start := start) (stop := stop) fun bs a => do match (← f a) with | some b => pure (bs.push b) | none => pure bs @[inline] def filterMap (f : α → Option β) (as : Array α) (start := 0) (stop := as.size) : Array β := Id.run <| as.filterMapM f (start := start) (stop := stop) @[specialize] def getMax? (as : Array α) (lt : α → α → Bool) : Option α := if h : 0 < as.size then let a0 := as.get ⟨0, h⟩ some <| as.foldl (init := a0) (start := 1) fun best a => if lt best a then a else best else none @[inline] def partition (p : α → Bool) (as : Array α) : Array α × Array α := do let mut bs := #[] let mut cs := #[] for a in as do if p a then bs := bs.push a else cs := cs.push a return (bs, cs) theorem ext (a b : Array α) (h₁ : a.size = b.size) (h₂ : (i : Nat) → (hi₁ : i < a.size) → (hi₂ : i < b.size) → a.get ⟨i, hi₁⟩ = b.get ⟨i, hi₂⟩) : a = b := by let rec extAux (a b : List α) (h₁ : a.length = b.length) (h₂ : (i : Nat) → (hi₁ : i < a.length) → (hi₂ : i < b.length) → a.get i hi₁ = b.get i hi₂) : a = b := by induction a generalizing b with | nil => cases b with | nil => rfl | cons b bs => rw [List.length_cons] at h₁; injection h₁ | cons a as ih => cases b with | nil => rw [List.length_cons] at h₁; injection h₁ | cons b bs => have hz₁ : 0 < (a::as).length by rw [List.length_cons]; apply Nat.zeroLtSucc have hz₂ : 0 < (b::bs).length by rw [List.length_cons]; apply Nat.zeroLtSucc have headEq : a = b from h₂ 0 hz₁ hz₂ have h₁' : as.length = bs.length by rw [List.length_cons, List.length_cons] at h₁; injection h₁; assumption have h₂' : (i : Nat) → (hi₁ : i < as.length) → (hi₂ : i < bs.length) → as.get i hi₁ = bs.get i hi₂ by intro i hi₁ hi₂ have hi₁' : i+1 < (a::as).length by rw [List.length_cons]; apply Nat.succ_lt_succ; assumption have hi₂' : i+1 < (b::bs).length by rw [List.length_cons]; apply Nat.succ_lt_succ; assumption have (a::as).get (i+1) hi₁' = (b::bs).get (i+1) hi₂' from h₂ (i+1) hi₁' hi₂' apply this have tailEq : as = bs from ih bs h₁' h₂' rw [headEq, tailEq] cases a; cases b apply congrArg apply extAux assumption assumption theorem extLit {n : Nat} (a b : Array α) (hsz₁ : a.size = n) (hsz₂ : b.size = n) (h : (i : Nat) → (hi : i < n) → a.getLit i hsz₁ hi = b.getLit i hsz₂ hi) : a = b := Array.ext a b (hsz₁.trans hsz₂.symm) fun i hi₁ hi₂ => h i (hsz₁ ▸ hi₁) end Array -- CLEANUP the following code namespace Array partial def indexOfAux [BEq α] (a : Array α) (v : α) : Nat → Option (Fin a.size) | i => if h : i < a.size then let idx : Fin a.size := ⟨i, h⟩; if a.get idx == v then some idx else indexOfAux a v (i+1) else none def indexOf? [BEq α] (a : Array α) (v : α) : Option (Fin a.size) := indexOfAux a v 0 partial def eraseIdxAux : Nat → Array α → Array α | i, a => if h : i < a.size then let idx : Fin a.size := ⟨i, h⟩; let idx1 : Fin a.size := ⟨i - 1, by exact Nat.ltOfLeOfLt (Nat.predLe i) h⟩; eraseIdxAux (i+1) (a.swap idx idx1) else a.pop def feraseIdx (a : Array α) (i : Fin a.size) : Array α := eraseIdxAux (i.val + 1) a def eraseIdx (a : Array α) (i : Nat) : Array α := if i < a.size then eraseIdxAux (i+1) a else a @[simp] theorem size_swap (a : Array α) (i j : Fin a.size) : (a.swap i j).size = a.size := by show ((a.set i (a.get j)).set (size_set a i _ ▸ j) (a.get i)).size = a.size rw [size_set, size_set] @[simp] theorem size_pop (a : Array α) : a.pop.size = a.size - 1 := List.length_dropLast .. section /- Instance for justifying `partial` declaration. We should be able to delete it as soon as we restore support for well-founded recursion. -/ instance eraseIdxSzAuxInstance (a : Array α) : Inhabited { r : Array α // r.size = a.size - 1 } where default := ⟨a.pop, size_pop a⟩ partial def eraseIdxSzAux (a : Array α) : ∀ (i : Nat) (r : Array α), r.size = a.size → { r : Array α // r.size = a.size - 1 } | i, r, heq => if h : i < r.size then let idx : Fin r.size := ⟨i, h⟩; let idx1 : Fin r.size := ⟨i - 1, by exact Nat.ltOfLeOfLt (Nat.predLe i) h⟩; eraseIdxSzAux a (i+1) (r.swap idx idx1) ((size_swap r idx idx1).trans heq) else ⟨r.pop, (size_pop r).trans (heq ▸ rfl)⟩ end def eraseIdx' (a : Array α) (i : Fin a.size) : { r : Array α // r.size = a.size - 1 } := eraseIdxSzAux a (i.val + 1) a rfl def erase [BEq α] (as : Array α) (a : α) : Array α := match as.indexOf? a with | none => as | some i => as.feraseIdx i partial def insertAtAux (i : Nat) : Array α → Nat → Array α | as, j => if i == j then as else let as := as.swap! (j-1) j; insertAtAux i as (j-1) /-- Insert element `a` at position `i`. Pre: `i < as.size` -/ def insertAt (as : Array α) (i : Nat) (a : α) : Array α := if i > as.size then panic! "invalid index" else let as := as.push a; as.insertAtAux i as.size def toListLitAux (a : Array α) (n : Nat) (hsz : a.size = n) : ∀ (i : Nat), i ≤ a.size → List α → List α | 0, hi, acc => acc | (i+1), hi, acc => toListLitAux a n hsz i (Nat.leOfSuccLe hi) (a.getLit i hsz (Nat.ltOfLtOfEq (Nat.ltOfLtOfLe (Nat.ltSuccSelf i) hi) hsz) :: acc) def toArrayLit (a : Array α) (n : Nat) (hsz : a.size = n) : Array α := List.toArray <| toListLitAux a n hsz n (hsz ▸ Nat.leRefl _) [] theorem toArrayLitEq (a : Array α) (n : Nat) (hsz : a.size = n) : a = toArrayLit a n hsz := -- TODO: this is painful to prove without proper automation sorry /- First, we need to prove ∀ i j acc, i ≤ a.size → (toListLitAux a n hsz (i+1) hi acc).index j = if j < i then a.getLit j hsz _ else acc.index (j - i) by induction Base case is trivial (j : Nat) (acc : List α) (hi : 0 ≤ a.size) |- (toListLitAux a n hsz 0 hi acc).index j = if j < 0 then a.getLit j hsz _ else acc.index (j - 0) ... |- acc.index j = acc.index j Induction (j : Nat) (acc : List α) (hi : i+1 ≤ a.size) |- (toListLitAux a n hsz (i+1) hi acc).index j = if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1)) ... |- (toListLitAux a n hsz i hi' (a.getLit i hsz _ :: acc)).index j = if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1)) * by def ... |- if j < i then a.getLit j hsz _ else (a.getLit i hsz _ :: acc).index (j-i) * by induction hypothesis = if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1)) If j < i, then both are a.getLit j hsz _ If j = i, then lhs reduces else-branch to (a.getLit i hsz _) and rhs is then-brachn (a.getLit i hsz _) If j >= i + 1, we use - j - i >= 1 > 0 - (a::as).index k = as.index (k-1) If k > 0 - j - (i + 1) = (j - i) - 1 Then lhs = (a.getLit i hsz _ :: acc).index (j-i) = acc.index (j-i-1) = acc.index (j-(i+1)) = rhs With this proof, we have ∀ j, j < n → (toListLitAux a n hsz n _ []).index j = a.getLit j hsz _ We also need - (toListLitAux a n hsz n _ []).length = n - j < n -> (List.toArray as).getLit j _ _ = as.index j Then using Array.extLit, we have that a = List.toArray <| toListLitAux a n hsz n _ [] -/ partial def isPrefixOfAux [BEq α] (as bs : Array α) (hle : as.size ≤ bs.size) : Nat → Bool | i => if h : i < as.size then let a := as.get ⟨i, h⟩; let b := bs.get ⟨i, Nat.ltOfLtOfLe h hle⟩; if a == b then isPrefixOfAux as bs hle (i+1) else false else true /- Return true iff `as` is a prefix of `bs` -/ def isPrefixOf [BEq α] (as bs : Array α) : Bool := if h : as.size ≤ bs.size then isPrefixOfAux as bs h 0 else false private def allDiffAuxAux [BEq α] (as : Array α) (a : α) : forall (i : Nat), i < as.size → Bool | 0, h => true | i+1, h => have i < as.size from Nat.ltTrans (Nat.ltSuccSelf _) h; a != as.get ⟨i, this⟩ && allDiffAuxAux as a i this private partial def allDiffAux [BEq α] (as : Array α) : Nat → Bool | i => if h : i < as.size then allDiffAuxAux as (as.get ⟨i, h⟩) i h && allDiffAux as (i+1) else true def allDiff [BEq α] (as : Array α) : Bool := allDiffAux as 0 @[specialize] partial def zipWithAux (f : α → β → γ) (as : Array α) (bs : Array β) : Nat → Array γ → Array γ | i, cs => if h : i < as.size then let a := as.get ⟨i, h⟩; if h : i < bs.size then let b := bs.get ⟨i, h⟩; zipWithAux f as bs (i+1) <| cs.push <| f a b else cs else cs @[inline] def zipWith (as : Array α) (bs : Array β) (f : α → β → γ) : Array γ := zipWithAux f as bs 0 #[] def zip (as : Array α) (bs : Array β) : Array (α × β) := zipWith as bs Prod.mk end Array
538ed8089e8676b0bbfd024d293df29151c49908
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/run/secnot.lean
e3553de74c191530fe8fe702c1d139d562da1824
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
395
lean
import data.num section variable {A : Type} definition f (a b : A) := a infixl `◀`:65 := f variables a b : A check a ◀ b end inductive list (T : Type) : Type := nil {} : list T, cons : T → list T → list T namespace list section variable {T : Type} notation `[` l:(foldr `,` (h t, cons h t) nil) `]` := l check [10, 20, 30] end end list open list check [10, 20, 40] check 10 ◀ 20
4e6d544903d38313a0015d1c5decae3288c6174d
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/inst_error.lean
efb8c011ec0eb72d4fe7aa0810a80adc9dc86a2b
[ "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
74
lean
check λ (A : Type) (a : A) (b c : _), if a = b ∧ a = c then tt else ff