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
9e0d98d1cd229b2b70e8fffd0e09e7947573e34a
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/measure_theory/decomposition.lean
e0ec7e5064139db0c97316a259d87f3534d19606
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
8,719
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Hahn decomposition theorem TODO: * introduce finite measures (into nnreal) * show general for signed measures (into ℝ) -/ import measure_theory.measure_space local attribute [instance, priority 0] classical.prop_decidable namespace measure_theory open set lattice filter variables {α : Type*} [measurable_space α] {μ ν : measure α} -- suddenly this is necessary?! private lemma aux {m : ℕ} {γ d : ℝ} (h : γ - (1 / 2) ^ m < d) : γ - 2 * (1 / 2) ^ m + (1 / 2) ^ m ≤ d := by linarith lemma hahn_decomposition (hμ : μ univ < ⊤) (hν : ν univ < ⊤) : ∃s, is_measurable s ∧ (∀t, is_measurable t → t ⊆ s → ν t ≤ μ t) ∧ (∀t, is_measurable t → t ⊆ - s → μ t ≤ ν t) := begin let d : set α → ℝ := λs, ((μ s).to_nnreal : ℝ) - (ν s).to_nnreal, let c : set ℝ := d '' {s | is_measurable s }, let γ : ℝ := Sup c, have hμ : ∀s, μ s < ⊤ := assume s, lt_of_le_of_lt (measure_mono $ subset_univ _) hμ, have hν : ∀s, ν s < ⊤ := assume s, lt_of_le_of_lt (measure_mono $ subset_univ _) hν, have to_nnreal_μ : ∀s, ((μ s).to_nnreal : ennreal) = μ s := (assume s, ennreal.coe_to_nnreal $ ne_top_of_lt $ hμ _), have to_nnreal_ν : ∀s, ((ν s).to_nnreal : ennreal) = ν s := (assume s, ennreal.coe_to_nnreal $ ne_top_of_lt $ hν _), have d_empty : d ∅ = 0, { simp [d], rw [measure_empty, measure_empty], simp }, have d_split : ∀s t, is_measurable s → is_measurable t → d s = d (s \ t) + d (s ∩ t), { assume s t hs ht, simp only [d], rw [measure_eq_inter_diff hs ht, measure_eq_inter_diff hs ht, ennreal.to_nnreal_add (hμ _) (hμ _), ennreal.to_nnreal_add (hν _) (hν _), nnreal.coe_add, nnreal.coe_add], simp only [sub_eq_add_neg, neg_add], ac_refl }, have d_Union : ∀(s : ℕ → set α), (∀n, is_measurable (s n)) → monotone s → tendsto (λn, d (s n)) at_top (nhds (d (⋃n, s n))), { assume s hs hm, refine tendsto_sub _ _; refine (nnreal.tendsto_coe.2 $ (ennreal.tendsto_to_nnreal $ @ne_top_of_lt _ _ _ ⊤ _).comp $ tendsto_measure_Union hs hm), exact hμ _, exact hν _ }, have d_Inter : ∀(s : ℕ → set α), (∀n, is_measurable (s n)) → (∀n m, n ≤ m → s m ⊆ s n) → tendsto (λn, d (s n)) at_top (nhds (d (⋂n, s n))), { assume s hs hm, refine tendsto_sub _ _; refine (nnreal.tendsto_coe.2 $ (ennreal.tendsto_to_nnreal $ @ne_top_of_lt _ _ _ ⊤ _).comp $ tendsto_measure_Inter hs hm _), exact hμ _, exact ⟨0, hμ _⟩, exact hν _, exact ⟨0, hν _⟩ }, have bdd_c : bdd_above c, { use (μ univ).to_nnreal, rintros r ⟨s, hs, rfl⟩, refine le_trans (sub_le_self _ $ nnreal.coe_nonneg _) _, rw [← nnreal.coe_le, ← ennreal.coe_le_coe, to_nnreal_μ, to_nnreal_μ], exact measure_mono (subset_univ _) }, have c_nonempty : c ≠ ∅ := ne_empty_of_mem (mem_image_of_mem _ is_measurable.empty), have d_le_γ : ∀s, is_measurable s → d s ≤ γ := assume s hs, le_cSup bdd_c ⟨s, hs, rfl⟩, have : ∀n:ℕ, ∃s : set α, is_measurable s ∧ γ - (1/2)^n < d s, { assume n, have : γ - (1/2)^n < γ := sub_lt_self γ (pow_pos (half_pos zero_lt_one) n), rcases exists_lt_of_lt_cSup c_nonempty this with ⟨r, ⟨s, hs, rfl⟩, hlt⟩, exact ⟨s, hs, hlt⟩ }, rcases classical.axiom_of_choice this with ⟨e, he⟩, change ℕ → set α at e, have he₁ : ∀n, is_measurable (e n) := assume n, (he n).1, have he₂ : ∀n, γ - (1/2)^n < d (e n) := assume n, (he n).2, let f : ℕ → ℕ → set α := λn m, (finset.Ico n (m + 1)).inf e, have hf : ∀n m, is_measurable (f n m), { assume n m, simp only [f, finset.inf_eq_infi], exact is_measurable.bInter (countable_encodable _) (assume i _, he₁ _) }, have f_subset_f : ∀{a b c d}, a ≤ b → c ≤ d → f a d ⊆ f b c, { assume a b c d hab hcd, dsimp only [f], rw [finset.inf_eq_infi, finset.inf_eq_infi], refine bInter_subset_bInter_left _, simp, rintros j ⟨hbj, hjc⟩, exact ⟨le_trans hab hbj, lt_of_lt_of_le hjc $ add_le_add_right hcd 1⟩ }, have f_succ : ∀n m, n ≤ m → f n (m + 1) = f n m ∩ e (m + 1), { assume n m hnm, have : n ≤ m + 1 := le_of_lt (nat.succ_le_succ hnm), simp only [f], rw [finset.Ico.succ_top this, finset.inf_insert, set.inter_comm], refl }, have le_d_f : ∀n m, m ≤ n → γ - 2 * ((1 / 2) ^ m) + (1 / 2) ^ n ≤ d (f m n), { assume n m h, refine nat.le_induction _ _ n h, { have := he₂ m, simp only [f], rw [finset.Ico.succ_singleton, finset.inf_singleton], exact aux this }, { assume n (hmn : m ≤ n) ih, have : γ + (γ - 2 * (1 / 2)^m + (1 / 2) ^ (n + 1)) ≤ γ + d (f m (n + 1)), { calc γ + (γ - 2 * (1 / 2)^m + (1 / 2) ^ (n+1)) ≤ γ + (γ - 2 * (1 / 2)^m + ((1 / 2) ^ n - (1/2)^(n+1))) : begin refine add_le_add_left (add_le_add_left _ _) γ, simp only [pow_add, pow_one, le_sub_iff_add_le], linarith end ... = (γ - (1 / 2)^(n+1)) + (γ - 2 * (1 / 2)^m + (1 / 2)^n) : by simp only [sub_eq_add_neg]; ac_refl ... ≤ d (e (n + 1)) + d (f m n) : add_le_add (le_of_lt $ he₂ _) ih ... ≤ d (e (n + 1)) + d (f m n \ e (n + 1)) + d (f m (n + 1)) : by rw [f_succ _ _ hmn, d_split (f m n) (e (n + 1)) (hf _ _) (he₁ _), add_assoc] ... = d (e (n + 1) ∪ f m n) + d (f m (n + 1)) : begin rw [d_split (e (n + 1) ∪ f m n) (e (n + 1)), union_diff_left, union_inter_cancel_left], ac_refl, exact (he₁ _).union (hf _ _), exact (he₁ _) end ... ≤ γ + d (f m (n + 1)) : add_le_add_right (d_le_γ _ $ (he₁ _).union (hf _ _)) _ }, exact (add_le_add_iff_left γ).1 this } }, let s := ⋃ m, ⋂n, f m n, have γ_le_d_s : γ ≤ d s, { have hγ : tendsto (λm:ℕ, γ - 2 * (1/2)^m) at_top (nhds γ), { suffices : tendsto (λm:ℕ, γ - 2 * (1/2)^m) at_top (nhds (γ - 2 * 0)), { simpa }, exact (tendsto_sub tendsto_const_nhds $ tendsto_mul tendsto_const_nhds $ tendsto_pow_at_top_nhds_0_of_lt_1 (le_of_lt $ half_pos $ zero_lt_one) (half_lt_self zero_lt_one)) }, have hd : tendsto (λm, d (⋂n, f m n)) at_top (nhds (d (⋃ m, ⋂ n, f m n))), { refine d_Union _ _ _, { assume n, exact is_measurable.Inter (assume m, hf _ _) }, { exact assume n m hnm, subset_Inter (assume i, subset.trans (Inter_subset (f n) i) $ f_subset_f hnm $ le_refl _) } }, refine le_of_tendsto_of_tendsto (@at_top_ne_bot ℕ _ _) hγ hd (univ_mem_sets' $ assume m, _), change γ - 2 * (1 / 2) ^ m ≤ d (⋂ (n : ℕ), f m n), have : tendsto (λn, d (f m n)) at_top (nhds (d (⋂ n, f m n))), { refine d_Inter _ _ _, { assume n, exact hf _ _ }, { assume n m hnm, exact f_subset_f (le_refl _) hnm } }, refine ge_of_tendsto (@at_top_ne_bot ℕ _ _) this (mem_at_top_sets.2 ⟨m, assume n hmn, _⟩), change γ - 2 * (1 / 2) ^ m ≤ d (f m n), refine le_trans _ (le_d_f _ _ hmn), exact le_add_of_le_of_nonneg (le_refl _) (pow_nonneg (le_of_lt $ half_pos $ zero_lt_one) _) }, have hs : is_measurable s := is_measurable.Union (assume n, is_measurable.Inter (assume m, hf _ _)), refine ⟨s, hs, _, _⟩, { assume t ht hts, have : 0 ≤ d t := ((add_le_add_iff_left γ).1 $ calc γ + 0 ≤ d s : by rw [add_zero]; exact γ_le_d_s ... = d (s \ t) + d t : by rw [d_split _ _ hs ht, inter_eq_self_of_subset_right hts] ... ≤ γ + d t : add_le_add (d_le_γ _ (hs.diff ht)) (le_refl _)), rw [← to_nnreal_μ, ← to_nnreal_ν, ennreal.coe_le_coe, nnreal.coe_le], simpa only [d, le_sub_iff_add_le, zero_add] using this }, { assume t ht hts, have : d t ≤ 0, exact ((add_le_add_iff_left γ).1 $ calc γ + d t ≤ d s + d t : add_le_add γ_le_d_s (le_refl _) ... = d (s ∪ t) : begin rw [d_split _ _ (hs.union ht) ht, union_diff_right, union_inter_cancel_right, diff_eq_self.2], exact assume a ⟨hat, has⟩, hts hat has end ... ≤ γ + 0 : by rw [add_zero]; exact d_le_γ _ (hs.union ht)), rw [← to_nnreal_μ, ← to_nnreal_ν, ennreal.coe_le_coe, nnreal.coe_le], simpa only [d, sub_le_iff_le_add, zero_add] using this } end end measure_theory
50aec9595288b26a128ea2a8136e134811282e6f
48eee836fdb5c613d9a20741c17db44c8e12e61c
/src/algebra/theories/unital.lean
66acb8961579d60f5b7df9d1406070085b213dba
[ "Apache-2.0" ]
permissive
fgdorais/lean-universal
06430443a4abe51e303e602684c2977d1f5c0834
9259b0f7fb3aa83a9e0a7a3eaa44c262e42cc9b1
refs/heads/master
1,592,479,744,136
1,589,473,399,000
1,589,473,399,000
196,287,552
1
1
null
null
null
null
UTF-8
Lean
false
false
2,310
lean
-- Copyright © 2019 François G. Dorais. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. import .basic import .magma namespace algebra signature unital (α : Type*) := (op : α → α → α) (id : α) namespace unital_sig variables {α : Type*} (s : unital_sig α) @[signature_instance] definition to_magma : magma_sig α := { op := s.op } end unital_sig variables {α : Type*} (s : unital_sig α) local infix ∙ := s.op local notation `e` := s.id @[theory] class unital : Prop := intro :: (left_identity : identity.op_left_identity s.op s.id) (right_identity : identity.op_right_identity s.op s.id) namespace unital variable [i : unital s] include i instance to_magma : magma s.to_magma := magma.infer _ end unital @[theory] class cancel_unital : Prop := intro :: (left_cancellative : identity.op_left_cancellative s.op) (right_cancellative : identity.op_right_cancellative s.op) (left_identity : identity.op_left_identity s.op s.id) (right_identity : identity.op_right_identity s.op s.id) namespace cancel_unital variable [i : cancel_unital s] include i instance to_cancel_magma : cancel_magma s.to_magma := cancel_magma.infer _ end cancel_unital @[theory] class comm_unital : Prop := intro :: (commutative : identity.op_commutative s.op) (right_identity : identity.op_right_identity s.op s.id) namespace comm_unital variable [i : comm_unital s] include i @[identity_instance] theorem left_identity : identity.op_left_identity s.op s.id := λ x, show e ∙ x = x, from calc _ = x ∙ e : by rw op_commutative s.op ... = x : by rw op_right_identity s.op instance to_unital : unital s := unital.infer _ instance to_comm_magma : comm_magma s.to_magma := comm_magma.infer _ end comm_unital @[theory] class cancel_comm_unital : Prop := intro :: (commutative : identity.op_commutative s.op) (right_identity : identity.op_right_identity s.op s.id) (right_cancellative : identity.op_right_cancellative s.op) namespace cancel_comm_unital variables [i : cancel_comm_unital s] include i instance to_comm_unital : comm_unital s := comm_unital.infer _ instance to_cancel_comm_magma : cancel_comm_magma s.to_magma := cancel_comm_magma.infer _ instance to_cancel_unital : cancel_unital s := cancel_unital.infer _ end cancel_comm_unital end algebra
067a1ab4c3841d3a703e12d05fe735f0a1cd5af2
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/system/random/basic.lean
917e10012473036ab746953074fe1696cacde75f
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,944
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 algebra.group_power import control.uliftable import control.monad.basic import data.bitvec.basic import data.list.basic import data.set.intervals.basic import data.stream.basic import data.fin import tactic.cache import tactic.interactive import tactic.norm_num import system.io import system.random /-! # Rand Monad and Random Class This module provides tools for formulating computations guided by randomness and for defining objects that can be created randomly. ## Main definitions * `rand` monad for computations guided by randomness; * `random` class for objects that can be generated randomly; * `random` to generate one object; * `random_r` to generate one object inside a range; * `random_series` to generate an infinite series of objects; * `random_series_r` to generate an infinite series of objects inside a range; * `io.mk_generator` to create a new random number generator; * `io.run_rand` to run a randomized computation inside the `io` monad; * `tactic.run_rand` to run a randomized computation inside the `tactic` monad ## Local notation * `i .. j` : `Icc i j`, the set of values between `i` and `j` inclusively; ## Tags random monad io ## References * Similar library in Haskell: https://hackage.haskell.org/package/MonadRandom -/ open list io applicative universes u v w /-- A monad to generate random objects using the generator type `g` -/ @[reducible] def rand_g (g : Type) (α : Type u) : Type u := state (ulift.{u} g) α /-- A monad to generate random objects using the generator type `std_gen` -/ @[reducible] def rand := rand_g std_gen instance (g : Type) : uliftable (rand_g.{u} g) (rand_g.{v} g) := @state_t.uliftable' _ _ _ _ _ (equiv.ulift.trans.{u u u u u} equiv.ulift.symm) open ulift (hiding inhabited) /-- Generate one more `ℕ` -/ def rand_g.next {g : Type} [random_gen g] : rand_g g ℕ := ⟨ prod.map id up ∘ random_gen.next ∘ down ⟩ local infix ` .. `:41 := set.Icc open stream /-- `bounded_random α` gives us machinery to generate values of type `α` between certain bounds -/ class bounded_random (α : Type u) [preorder α] := (random_r : Π g [random_gen g] (x y : α), (x ≤ y) → rand_g g (x .. y)) /-- `random α` gives us machinery to generate values of type `α` -/ class random (α : Type u) := (random [] : Π (g : Type) [random_gen g], rand_g g α) /-- shift_31_left = 2^31; multiplying by it shifts the binary representation of a number left by 31 bits, dividing by it shifts it right by 31 bits -/ def shift_31_left : ℕ := by apply_normed 2^31 namespace rand open stream variables (α : Type u) variables (g : Type) [random_gen g] /-- create a new random number generator distinct from the one stored in the state -/ def split : rand_g g g := ⟨ prod.map id up ∘ random_gen.split ∘ down ⟩ variables {g} section random variables [random α] export random (random) /-- Generate a random value of type `α`. -/ def random : rand_g g α := random.random α g /-- generate an infinite series of random values of type `α` -/ def random_series : rand_g g (stream α) := do gen ← uliftable.up (split g), pure $ stream.corec_state (random.random α g) gen end random variables {α} /-- Generate a random value between `x` and `y` inclusive. -/ def random_r [preorder α] [bounded_random α] (x y : α) (h : x ≤ y) : rand_g g (x .. y) := bounded_random.random_r g x y h /-- generate an infinite series of random values of type `α` between `x` and `y` inclusive. -/ def random_series_r [preorder α] [bounded_random α] (x y : α) (h : x ≤ y) : rand_g g (stream (x .. y)) := do gen ← uliftable.up (split g), pure $ corec_state (bounded_random.random_r g x y h) gen end rand namespace io private def accum_char (w : ℕ) (c : char) : ℕ := c.to_nat + 256 * w /-- create and a seed a random number generator -/ def mk_generator : io std_gen := do seed ← io.rand 0 shift_31_left, return $ mk_std_gen seed variables {α : Type} /-- Run `cmd` using a randomly seeded random number generator -/ def run_rand (cmd : _root_.rand α) : io α := do g ← io.mk_generator, return $ (cmd.run ⟨g⟩).1 /-- Run `cmd` using the provided seed. -/ def run_rand_with (seed : ℕ) (cmd : _root_.rand α) : io α := return $ (cmd.run ⟨mk_std_gen seed⟩).1 section random variables [random α] /-- randomly generate a value of type α -/ def random : io α := io.run_rand (rand.random α) /-- randomly generate an infinite series of value of type α -/ def random_series : io (stream α) := io.run_rand (rand.random_series α) end random section bounded_random variables [preorder α] [bounded_random α] /-- randomly generate a value of type α between `x` and `y` -/ def random_r (x y : α) (p : x ≤ y) : io (x .. y) := io.run_rand (bounded_random.random_r _ x y p) /-- randomly generate an infinite series of value of type α between `x` and `y` -/ def random_series_r (x y : α) (h : x ≤ y) : io (stream $ x .. y) := io.run_rand (rand.random_series_r x y h) end bounded_random end io namespace tactic /-- create a seeded random number generator in the `tactic` monad -/ meta def mk_generator : tactic std_gen := do tactic.unsafe_run_io @io.mk_generator /-- run `cmd` using the a randomly seeded random number generator in the tactic monad -/ meta def run_rand {α : Type u} (cmd : rand α) : tactic α := do ⟨g⟩ ← tactic.up mk_generator, return (cmd.run ⟨g⟩).1 variables {α : Type u} section bounded_random variables [preorder α] [bounded_random α] /-- Generate a random value between `x` and `y` inclusive. -/ meta def random_r (x y : α) (h : x ≤ y) : tactic (x .. y) := run_rand (rand.random_r x y h) /-- Generate an infinite series of random values of type `α` between `x` and `y` inclusive. -/ meta def random_series_r (x y : α) (h : x ≤ y) : tactic (stream $ x .. y) := run_rand (rand.random_series_r x y h) end bounded_random section random variables [random α] /-- randomly generate a value of type α -/ meta def random : tactic α := run_rand (rand.random α) /-- randomly generate an infinite series of value of type α -/ meta def random_series : tactic (stream α) := run_rand (rand.random_series α) end random end tactic open nat (succ one_add mod_eq_of_lt zero_lt_succ add_one succ_le_succ) variables {g : Type} [random_gen g] open nat namespace fin variables {n : ℕ} [fact (0 < n)] /-- generate a `fin` randomly -/ protected def random : rand_g g (fin n) := ⟨ λ ⟨g⟩, prod.map of_nat' up $ rand_nat g 0 n ⟩ end fin open nat instance nat_bounded_random : bounded_random ℕ := { random_r := λ g inst x y hxy, do z ← @fin.random g inst (succ $ y - x) _, pure ⟨z.val + x, nat.le_add_left _ _, by rw ← nat.le_sub_right_iff_add_le hxy; apply le_of_succ_le_succ z.is_lt⟩ } /-- This `bounded_random` interval generates integers between `x` and `y` by first generating a natural number between `0` and `y - x` and shifting the result appropriately. -/ instance int_bounded_random : bounded_random ℤ := { random_r := λ g inst x y hxy, do ⟨z,h₀,h₁⟩ ← @bounded_random.random_r ℕ _ _ g inst 0 (int.nat_abs $ y - x) dec_trivial, pure ⟨z + x, int.le_add_of_nonneg_left (int.coe_nat_nonneg _), int.add_le_of_le_sub_right $ le_trans (int.coe_nat_le_coe_nat_of_le h₁) (le_of_eq $ int.of_nat_nat_abs_eq_of_nonneg (int.sub_nonneg_of_le hxy)) ⟩ } instance fin_random (n : ℕ) [fact (0 < n)] : random (fin n) := { random := λ g inst, @fin.random g inst _ _ } instance fin_bounded_random (n : ℕ) : bounded_random (fin n) := { random_r := λ g inst (x y : fin n) p, do ⟨r, h, h'⟩ ← @rand.random_r ℕ g inst _ _ x.val y.val p, pure ⟨⟨r,lt_of_le_of_lt h' y.is_lt⟩, h, h'⟩ } /-- A shortcut for creating a `random (fin n)` instance from a proof that `0 < n` rather than on matching on `fin (succ n)` -/ def random_fin_of_pos : ∀ {n : ℕ} (h : 0 < n), random (fin n) | (succ n) _ := fin_random _ | 0 h := false.elim (nat.not_lt_zero _ h) lemma bool_of_nat_mem_Icc_of_mem_Icc_to_nat (x y : bool) (n : ℕ) : n ∈ (x.to_nat .. y.to_nat) → bool.of_nat n ∈ (x .. y) := begin simp only [and_imp, set.mem_Icc], intros h₀ h₁, split; [ have h₂ := bool.of_nat_le_of_nat h₀, have h₂ := bool.of_nat_le_of_nat h₁ ]; rw bool.of_nat_to_nat at h₂; exact h₂, end instance : random bool := { random := λ g inst, (bool.of_nat ∘ subtype.val) <$> @bounded_random.random_r ℕ _ _ g inst 0 1 (nat.zero_le _) } instance : bounded_random bool := { random_r := λ g _inst x y p, subtype.map bool.of_nat (bool_of_nat_mem_Icc_of_mem_Icc_to_nat x y) <$> @bounded_random.random_r ℕ _ _ g _inst x.to_nat y.to_nat (bool.to_nat_le_to_nat p) } open_locale fin_fact /-- generate a random bit vector of length `n` -/ def bitvec.random (n : ℕ) : rand_g g (bitvec n) := bitvec.of_fin <$> rand.random (fin $ 2^n) /-- generate a random bit vector of length `n` -/ def bitvec.random_r {n : ℕ} (x y : bitvec n) (h : x ≤ y) : rand_g g (x .. y) := have h' : ∀ (a : fin (2 ^ n)), a ∈ (x.to_fin .. y.to_fin) → bitvec.of_fin a ∈ (x .. y), begin simp only [and_imp, set.mem_Icc], intros z h₀ h₁, replace h₀ := bitvec.of_fin_le_of_fin_of_le h₀, replace h₁ := bitvec.of_fin_le_of_fin_of_le h₁, rw bitvec.of_fin_to_fin at h₀ h₁, split; assumption, end, subtype.map bitvec.of_fin h' <$> rand.random_r x.to_fin y.to_fin (bitvec.to_fin_le_to_fin_of_le h) open nat instance random_bitvec (n : ℕ) : random (bitvec n) := { random := λ _ inst, @bitvec.random _ inst n } instance bounded_random_bitvec (n : ℕ) : bounded_random (bitvec n) := { random_r := λ _ inst x y p, @bitvec.random_r _ inst _ _ _ p }
128e95599e011a7bfd6433f3da920dbb87ed61ec
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/linear_algebra/nonsingular_inverse.lean
c1ead46a42652cd203ced11c3fea1e47f2498e6b
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,371
lean
/- Copyright (c) 2019 Tim Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baanen -/ import algebra.associated import linear_algebra.determinant import tactic.linarith import tactic.ring_exp /-! # Nonsingular inverses In this file, we define an inverse for square matrices of invertible determinant. For matrices that are not square or not of full rank, there is a more general notion of pseudoinverses which we do not consider here. The definition of inverse used in this file is the adjugate divided by the determinant. The adjugate is calculated with Cramer's rule, which we introduce first. The vectors returned by Cramer's rule are given by the linear map `cramer`, which sends a matrix `A` and vector `b` to the vector consisting of the determinant of replacing the `i`th column of `A` with `b` at index `i` (written as `(A.update_column i b).det`). Using Cramer's rule, we can compute for each matrix `A` the matrix `adjugate A`. The entries of the adjugate are the determinants of each minor of `A`. Instead of defining a minor to be `A` with row `i` and column `j` deleted, we replace the `i`th row of `A` with the `j`th basis vector; this has the same determinant as the minor but more importantly equals Cramer's rule applied to `A` and the `j`th basis vector, simplifying the subsequent proofs. We prove the adjugate behaves like `det A • A⁻¹`. Finally, we show that dividing the adjugate by `det A` (if possible), giving a matrix `nonsing_inv A`, will result in a multiplicative inverse to `A`. ## References * https://en.wikipedia.org/wiki/Cramer's_rule#Finding_inverse_matrix ## Tags matrix inverse, cramer, cramer's rule, adjugate -/ namespace matrix universes u v variables {n : Type u} [decidable_eq n] [fintype n] {α : Type v} [comm_ring α] open_locale matrix big_operators open equiv equiv.perm finset section cramer /-! ### `cramer` section Introduce the linear map `cramer` with values defined by `cramer_map`. After defining `cramer_map` and showing it is linear, we will restrict our proofs to using `cramer`. -/ variables (A : matrix n n α) (b : n → α) /-- `cramer_map A b i` is the determinant of the matrix `A` with column `i` replaced with `b`, and thus `cramer_map A b` is the vector output by Cramer's rule on `A` and `b`. If `A ⬝ x = b` has a unique solution in `x`, `cramer_map A` sends the vector `b` to `A.det • x`. Otherwise, the outcome of `cramer_map` is well-defined but not necessarily useful. -/ def cramer_map (i : n) : α := (A.update_column i b).det lemma cramer_map_is_linear (i : n) : is_linear_map α (λ b, cramer_map A b i) := { map_add := det_update_column_add _ _, map_smul := det_update_column_smul _ _ } lemma cramer_is_linear : is_linear_map α (cramer_map A) := begin split; intros; ext i, { apply (cramer_map_is_linear A i).1 }, { apply (cramer_map_is_linear A i).2 } end /-- `cramer A b i` is the determinant of the matrix `A` with column `i` replaced with `b`, and thus `cramer A b` is the vector output by Cramer's rule on `A` and `b`. If `A ⬝ x = b` has a unique solution in `x`, `cramer A` sends the vector `b` to `A.det • x`. Otherwise, the outcome of `cramer` is well-defined but not necessarily useful. -/ def cramer (A : matrix n n α) : (n → α) →ₗ[α] (n → α) := is_linear_map.mk' (cramer_map A) (cramer_is_linear A) lemma cramer_apply (i : n) : cramer A b i = (A.update_column i b).det := rfl lemma cramer_transpose_row_self (i : n) : Aᵀ.cramer (A i) = λ j, ite (i = j) A.det 0 := begin ext j, rw cramer_apply, by_cases h : i = j, { -- i = j: this entry should be `A.det` rw [update_column_transpose, det_transpose], simp [update_row, h], }, { -- i ≠ j: this entry should be 0 rw [if_neg h, update_column_transpose, det_transpose], apply det_zero_of_row_eq h, rw [update_row_self, update_row_ne], apply h } end /-- Use linearity of `cramer` to take it out of a summation. -/ lemma sum_cramer {β} (s : finset β) (f : β → n → α) : ∑ x in s, cramer A (f x) = cramer A (∑ x in s, f x) := (linear_map.map_sum (cramer A)).symm /-- Use linearity of `cramer` and vector evaluation to take `cramer A _ i` out of a summation. -/ lemma sum_cramer_apply {β} (s : finset β) (f : n → β → α) (i : n) : ∑ x in s, cramer A (λ j, f j x) i = cramer A (λ (j : n), ∑ x in s, f j x) i := calc ∑ x in s, cramer A (λ j, f j x) i = (∑ x in s, cramer A (λ j, f j x)) i : (finset.sum_apply i s _).symm ... = cramer A (λ (j : n), ∑ x in s, f j x) i : by { rw [sum_cramer, cramer_apply], congr' with j, apply finset.sum_apply } end cramer section adjugate /-! ### `adjugate` section Define the `adjugate` matrix and a few equations. These will hold for any matrix over a commutative ring, while the `inv` section is specifically for invertible matrices. -/ /-- The adjugate matrix is the transpose of the cofactor matrix. Typically, the cofactor matrix is defined by taking the determinant of minors, i.e. the matrix with a row and column removed. However, the proof of `mul_adjugate` becomes a lot easier if we define the minor as replacing a column with a basis vector, since it allows us to use facts about the `cramer` map. -/ def adjugate (A : matrix n n α) : matrix n n α := λ i, cramer Aᵀ (λ j, if i = j then 1 else 0) lemma adjugate_def (A : matrix n n α) : adjugate A = λ i, cramer Aᵀ (λ j, if i = j then 1 else 0) := rfl lemma adjugate_apply (A : matrix n n α) (i j : n) : adjugate A i j = (A.update_row j (λ j, if i = j then 1 else 0)).det := by { rw adjugate_def, simp only, rw [cramer_apply, update_column_transpose, det_transpose], } lemma adjugate_transpose (A : matrix n n α) : (adjugate A)ᵀ = adjugate (Aᵀ) := begin ext i j, rw [transpose_apply, adjugate_apply, adjugate_apply, update_row_transpose, det_transpose], rw [det_apply', det_apply'], apply finset.sum_congr rfl, intros σ _, congr' 1, by_cases i = σ j, { -- Everything except `(i , j)` (= `(σ j , j)`) is given by A, and the rest is a single `1`. congr; ext j', have := (@equiv.injective _ _ σ j j' : σ j = σ j' → j = j'), rw [update_row_apply, update_column_apply], finish }, { -- Otherwise, we need to show that there is a `0` somewhere in the product. have : (∏ j' : n, update_column A j (λ (i' : n), ite (i = i') 1 0) (σ j') j') = 0, { apply prod_eq_zero (mem_univ j), rw [update_column_self], exact if_neg h }, rw this, apply prod_eq_zero (mem_univ (σ⁻¹ i)), erw [apply_symm_apply σ i, update_row_self], apply if_neg, intro h', exact h ((symm_apply_eq σ).mp h'.symm) } end /-- Since the map `b ↦ cramer A b` is linear in `b`, it must be multiplication by some matrix. This matrix is `A.adjugate`. -/ lemma cramer_eq_adjugate_mul_vec (A : matrix n n α) (b : n → α) : cramer A b = A.adjugate.mul_vec b := begin nth_rewrite 1 ← A.transpose_transpose, rw [← adjugate_transpose, adjugate_def], have : b = ∑ i, (b i) • (λ j, if i = j then 1 else 0), { ext i, simp, }, rw this, ext k, simp [mul_vec, dot_product, mul_comm], end lemma mul_adjugate_apply (A : matrix n n α) (i j k) : A i k * adjugate A k j = cramer Aᵀ (λ j, if k = j then A i k else 0) j := begin erw [←smul_eq_mul, ←pi.smul_apply, ←linear_map.map_smul], congr' with l, rw [pi.smul_apply, smul_eq_mul, mul_boole], end lemma mul_adjugate (A : matrix n n α) : A ⬝ adjugate A = A.det • 1 := begin ext i j, rw [mul_apply, smul_apply, one_apply, mul_boole], simp [mul_adjugate_apply, sum_cramer_apply, cramer_transpose_row_self], end lemma adjugate_mul (A : matrix n n α) : adjugate A ⬝ A = A.det • 1 := calc adjugate A ⬝ A = (Aᵀ ⬝ (adjugate Aᵀ))ᵀ : by rw [←adjugate_transpose, ←transpose_mul, transpose_transpose] ... = A.det • 1 : by rw [mul_adjugate (Aᵀ), det_transpose, transpose_smul, transpose_one] /-- `det_adjugate_of_cancel` is an auxiliary lemma for computing `(adjugate A).det`, used in `det_adjugate_eq_one` and `det_adjugate_of_is_unit`. The formula for the determinant of the adjugate of an `n` by `n` matrix `A` is in general `(adjugate A).det = A.det ^ (n - 1)`, but the proof differs in several cases. This lemma `det_adjugate_of_cancel` covers the case that `det A` cancels on the left of the equation `A.det * b = A.det ^ n`. -/ lemma det_adjugate_of_cancel {A : matrix n n α} (h : ∀ b, A.det * b = A.det ^ fintype.card n → b = A.det ^ (fintype.card n - 1)) : (adjugate A).det = A.det ^ (fintype.card n - 1) := h (adjugate A).det (calc A.det * (adjugate A).det = (A ⬝ adjugate A).det : (det_mul _ _).symm ... = A.det ^ fintype.card n : by simp [mul_adjugate]) lemma adjugate_eq_one_of_card_eq_one {A : matrix n n α} (h : fintype.card n = 1) : adjugate A = 1 := begin haveI : subsingleton n := fintype.card_le_one_iff_subsingleton.mp h.le, ext i j, simp [subsingleton.elim i j, adjugate_apply, det_eq_elem_of_card_eq_one h j], end @[simp] lemma adjugate_zero (h : 1 < fintype.card n) : adjugate (0 : matrix n n α) = 0 := begin ext i j, obtain ⟨j', hj'⟩ : ∃ j', j' ≠ j := fintype.exists_ne_of_one_lt_card h j, apply det_eq_zero_of_column_eq_zero j', intro j'', simp [update_column_ne hj'], end lemma det_adjugate_eq_one {A : matrix n n α} (h : A.det = 1) : (adjugate A).det = 1 := calc (adjugate A).det = A.det ^ (fintype.card n - 1) : det_adjugate_of_cancel (λ b hb, by simpa [h] using hb) ... = 1 : by rw [h, one_pow] /-- `det_adjugate_of_is_unit` gives the formula for `(adjugate A).det` if `A.det` has an inverse. The formula for the determinant of the adjugate of an `n` by `n` matrix `A` is in general `(adjugate A).det = A.det ^ (n - 1)`, but the proof differs in several cases. This lemma `det_adjugate_of_is_unit` covers the case that `det A` has an inverse. -/ lemma det_adjugate_of_is_unit {A : matrix n n α} (h : is_unit A.det) : (adjugate A).det = A.det ^ (fintype.card n - 1) := begin rcases is_unit_iff_exists_inv'.mp h with ⟨a, ha⟩, by_cases card_lt_zero : fintype.card n ≤ 0, { have h : fintype.card n = 0 := by linarith, simp [det_eq_one_of_card_eq_zero h] }, have zero_lt_card : 0 < fintype.card n := by linarith, have n_nonempty : nonempty n := fintype.card_pos_iff.mp zero_lt_card, by_cases card_lt_one : fintype.card n ≤ 1, { have h : fintype.card n = 1 := by linarith, simp [h, adjugate_eq_one_of_card_eq_one h] }, have one_lt_card : 1 < fintype.card n := by linarith, have zero_lt_card_sub_one : 0 < fintype.card n - 1 := (nat.sub_lt_sub_right_iff (refl 1)).mpr one_lt_card, apply det_adjugate_of_cancel, intros b hb, calc b = a * (det A ^ (fintype.card n - 1 + 1)) : by rw [←one_mul b, ←ha, mul_assoc, hb, nat.sub_add_cancel zero_lt_card] ... = a * det A * det A ^ (fintype.card n - 1) : by ring_exp ... = det A ^ (fintype.card n - 1) : by rw [ha, one_mul] end end adjugate section inv /-! ### `inv` section Defines the matrix `nonsing_inv A` and proves it is the inverse matrix of a square matrix `A` as long as `det A` has a multiplicative inverse. -/ variables (A : matrix n n α) open_locale classical lemma is_unit_det_transpose (h : is_unit A.det) : is_unit Aᵀ.det := by { rw det_transpose, exact h, } /-- The inverse of a square matrix, when it is invertible (and zero otherwise).-/ noncomputable def nonsing_inv : matrix n n α := if h : is_unit A.det then (↑h.unit⁻¹ : α) • A.adjugate else 0 noncomputable instance : has_inv (matrix n n α) := ⟨matrix.nonsing_inv⟩ lemma nonsing_inv_apply (h : is_unit A.det) : A⁻¹ = (↑h.unit⁻¹ : α) • A.adjugate := by { change A.nonsing_inv = _, dunfold nonsing_inv, simp only [dif_pos, h], } lemma transpose_nonsing_inv (h : is_unit A.det) : (A⁻¹)ᵀ = (Aᵀ)⁻¹ := begin have h' := A.is_unit_det_transpose h, have dets_eq : (↑h.unit : α) = ↑h'.unit := by rw [h.unit_spec, h'.unit_spec, det_transpose], rw [A.nonsing_inv_apply h, Aᵀ.nonsing_inv_apply h', units.inv_unique dets_eq, A.adjugate_transpose.symm], refl, end /-- The `nonsing_inv` of `A` is a right inverse. -/ @[simp] lemma mul_nonsing_inv (h : is_unit A.det) : A ⬝ A⁻¹ = 1 := by rw [A.nonsing_inv_apply h, mul_smul, mul_adjugate, smul_smul, units.inv_mul_of_eq h.unit_spec, one_smul] /-- The `nonsing_inv` of `A` is a left inverse. -/ @[simp] lemma nonsing_inv_mul (h : is_unit A.det) : A⁻¹ ⬝ A = 1 := calc A⁻¹ ⬝ A = (Aᵀ ⬝ (Aᵀ)⁻¹)ᵀ : by { rw [transpose_mul, Aᵀ.transpose_nonsing_inv (A.is_unit_det_transpose h), transpose_transpose], } ... = 1ᵀ : by { rw Aᵀ.mul_nonsing_inv, exact A.is_unit_det_transpose h, } ... = 1 : transpose_one @[simp] lemma nonsing_inv_det (h : is_unit A.det) : A⁻¹.det * A.det = 1 := by rw [←det_mul, A.nonsing_inv_mul h, det_one] lemma is_unit_nonsing_inv_det (h : is_unit A.det) : is_unit A⁻¹.det := is_unit_of_mul_eq_one _ _ (A.nonsing_inv_det h) @[simp] lemma nonsing_inv_nonsing_inv (h : is_unit A.det) : (A⁻¹)⁻¹ = A := calc (A⁻¹)⁻¹ = 1 ⬝ (A⁻¹)⁻¹ : by rw matrix.one_mul ... = A ⬝ A⁻¹ ⬝ (A⁻¹)⁻¹ : by rw A.mul_nonsing_inv h ... = A : by { rw [matrix.mul_assoc, (A⁻¹).mul_nonsing_inv (A.is_unit_nonsing_inv_det h), matrix.mul_one], } /-- A matrix whose determinant is a unit is itself a unit. -/ noncomputable def nonsing_inv_unit (h : is_unit A.det) : units (matrix n n α) := { val := A, inv := A⁻¹, val_inv := by { rw matrix.mul_eq_mul, apply A.mul_nonsing_inv h, }, inv_val := by { rw matrix.mul_eq_mul, apply A.nonsing_inv_mul h, } } lemma is_unit_iff_is_unit_det : is_unit A ↔ is_unit A.det := begin split; intros h, { -- is_unit A → is_unit A.det suffices : ∃ (B : matrix n n α), A ⬝ B = 1, { rcases this with ⟨B, hB⟩, apply is_unit_of_mul_eq_one _ B.det, rw [←det_mul, hB, det_one], }, refine ⟨↑h.unit⁻¹, _⟩, conv_lhs { congr, rw ←h.unit_spec, }, exact h.unit.mul_inv, }, { -- is_unit A.det → is_unit A exact (A.nonsing_inv_unit h).is_unit, }, end lemma is_unit_det_of_left_inverse (B : matrix n n α) (h : B ⬝ A = 1) : is_unit A.det := ⟨{ val := A.det, inv := B.det, val_inv := by rw [mul_comm, ← det_mul, h, det_one], inv_val := by rw [← det_mul, h, det_one], }, rfl⟩ lemma is_unit_det_of_right_inverse (B : matrix n n α) (h : A ⬝ B = 1) : is_unit A.det := ⟨{ val := A.det, inv := B.det, val_inv := by rw [← det_mul, h, det_one], inv_val := by rw [mul_comm, ← det_mul, h, det_one], }, rfl⟩ lemma nonsing_inv_left_right (B : matrix n n α) (h : A ⬝ B = 1) : B ⬝ A = 1 := begin have h' : is_unit B.det := B.is_unit_det_of_left_inverse A h, calc B ⬝ A = (B ⬝ A) ⬝ (B ⬝ B⁻¹) : by simp only [h', matrix.mul_one, mul_nonsing_inv] ... = B ⬝ ((A ⬝ B) ⬝ B⁻¹) : by simp only [matrix.mul_assoc] ... = B ⬝ B⁻¹ : by simp only [h, matrix.one_mul] ... = 1 : mul_nonsing_inv B h', end lemma nonsing_inv_right_left (B : matrix n n α) (h : B ⬝ A = 1) : A ⬝ B = 1 := B.nonsing_inv_left_right A h end inv /- One form of Cramer's rule. -/ @[simp] lemma det_smul_inv_mul_vec_eq_cramer (A : matrix n n α) (b : n → α) (h : is_unit A.det) : A.det • A⁻¹.mul_vec b = cramer A b := begin rw [cramer_eq_adjugate_mul_vec, A.nonsing_inv_apply h, ← smul_mul_vec_assoc], conv_lhs { congr, congr, rw ← h.unit_spec, }, rw units.smul_inv_smul, end /- A stronger form of Cramer's rule that allows us to solve some instances of `A ⬝ x = b` even if the determinant is not a unit. A sufficient (but still not necessary) condition is that `A.det` divides `b`. -/ @[simp] lemma mul_vec_cramer (A : matrix n n α) (b : n → α) : A.mul_vec (cramer A b) = A.det • b := by rw [cramer_eq_adjugate_mul_vec, mul_vec_mul_vec, mul_adjugate, smul_mul_vec_assoc, mul_vec_one] end matrix
1005da51b9b3092100a70bf81bb067b49f55f506
49ffcd4736fa3bdcc1cdbb546d4c855d67c0f28a
/library/init/meta/pexpr.lean
17f94f2afab288de23a9513f9050f5e30b23f899
[ "Apache-2.0" ]
permissive
black13/lean
979e24d09e17b2fdf8ec74aac160583000086bc8
1a80ea9c8e28902cadbfb612896bcd45ba4ce697
refs/heads/master
1,626,839,620,164
1,509,113,016,000
1,509,122,889,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,624
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.expr universe u /-- Quoted expressions. They can be converted into expressions by using a tactic. -/ @[reducible] meta def pexpr := expr ff protected meta constant pexpr.of_expr : expr → pexpr meta constant pexpr.is_placeholder : pexpr → bool meta constant pexpr.mk_placeholder : pexpr meta constant pexpr.mk_field_macro : pexpr → name → pexpr meta constant pexpr.mk_explicit : pexpr → pexpr /-- Choice macros are used to implement overloading. -/ meta constant pexpr.is_choice_macro : pexpr → bool /-- Information about unelaborated structure instance expressions. -/ meta structure structure_instance_info := (struct : option name := none) (source : option pexpr := none) (field_names : list name) (field_values : list pexpr) /-- Create a structure instance expression. Note: If both `struct` and `source` are specified, the former will be ignored. -/ meta constant pexpr.mk_structure_instance : structure_instance_info → pexpr meta constant pexpr.get_structure_instance_info : pexpr → option structure_instance_info meta class has_to_pexpr (α : Sort u) := (to_pexpr : α → pexpr) meta def to_pexpr {α : Sort u} [has_to_pexpr α] : α → pexpr := has_to_pexpr.to_pexpr meta instance : has_to_pexpr pexpr := ⟨id⟩ meta instance : has_to_pexpr expr := ⟨pexpr.of_expr⟩ meta instance (α : Sort u) (a : α) : has_to_pexpr (reflected a) := ⟨pexpr.of_expr ∘ reflected.to_expr⟩
896f89222615b2f6e75e799dc8b439433d35abc0
94e33a31faa76775069b071adea97e86e218a8ee
/src/topology/metric_space/emetric_space.lean
e4e9477af35eceeb70f55c8d85d0ea9e2ecc26b5
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
46,994
lean
/- Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel -/ import data.nat.interval import data.real.ennreal import topology.uniform_space.pi import topology.uniform_space.uniform_convergence import topology.uniform_space.uniform_embedding /-! # Extended metric spaces This file is devoted to the definition and study of `emetric_spaces`, i.e., metric spaces in which the distance is allowed to take the value ∞. This extended distance is called `edist`, and takes values in `ℝ≥0∞`. Many definitions and theorems expected on emetric spaces are already introduced on uniform spaces and topological spaces. For example: open and closed sets, compactness, completeness, continuity and uniform continuity. The class `emetric_space` therefore extends `uniform_space` (and `topological_space`). Since a lot of elementary properties don't require `eq_of_edist_eq_zero` we start setting up the theory of `pseudo_emetric_space`, where we don't require `edist x y = 0 → x = y` and we specialize to `emetric_space` at the end. -/ open set filter classical noncomputable theory open_locale uniformity topological_space big_operators filter nnreal ennreal universes u v w variables {α : Type u} {β : Type v} /-- Characterizing uniformities associated to a (generalized) distance function `D` in terms of the elements of the uniformity. -/ theorem uniformity_dist_of_mem_uniformity [linear_order β] {U : filter (α × α)} (z : β) (D : α → α → β) (H : ∀ s, s ∈ U ↔ ∃ε>z, ∀{a b:α}, D a b < ε → (a, b) ∈ s) : U = ⨅ ε>z, 𝓟 {p:α×α | D p.1 p.2 < ε} := le_antisymm (le_infi $ λ ε, le_infi $ λ ε0, le_principal_iff.2 $ (H _).2 ⟨ε, ε0, λ a b, id⟩) (λ r ur, let ⟨ε, ε0, h⟩ := (H _).1 ur in mem_infi_of_mem ε $ mem_infi_of_mem ε0 $ mem_principal.2 $ λ ⟨a, b⟩, h) /-- `has_edist α` means that `α` is equipped with an extended distance. -/ class has_edist (α : Type*) := (edist : α → α → ℝ≥0∞) export has_edist (edist) /-- Creating a uniform space from an extended distance. -/ def uniform_space_of_edist (edist : α → α → ℝ≥0∞) (edist_self : ∀ x : α, edist x x = 0) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) : uniform_space α := uniform_space.of_core { uniformity := (⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε}), refl := le_infi $ assume ε, le_infi $ by simp [set.subset_def, id_rel, edist_self, (>)] {contextual := tt}, comp := le_infi $ assume ε, le_infi $ assume h, have (2 : ℝ≥0∞) = (2 : ℕ) := by simp, have A : 0 < ε / 2 := ennreal.div_pos_iff.2 ⟨ne_of_gt h, by { convert ennreal.nat_ne_top 2 }⟩, lift'_le (mem_infi_of_mem (ε / 2) $ mem_infi_of_mem A (subset.refl _)) $ have ∀ (a b c : α), edist a c < ε / 2 → edist c b < ε / 2 → edist a b < ε, from assume a b c hac hcb, calc edist a b ≤ edist a c + edist c b : edist_triangle _ _ _ ... < ε / 2 + ε / 2 : ennreal.add_lt_add hac hcb ... = ε : by rw [ennreal.add_halves], by simpa [comp_rel], symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h, tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [edist_comm] } -- the uniform structure is embedded in the emetric space structure -- to avoid instance diamond issues. See Note [forgetful inheritance]. /-- Extended (pseudo) metric spaces, with an extended distance `edist` possibly taking the value ∞ Each pseudo_emetric space induces a canonical `uniform_space` and hence a canonical `topological_space`. This is enforced in the type class definition, by extending the `uniform_space` structure. When instantiating a `pseudo_emetric_space` structure, the uniformity fields are not necessary, they will be filled in by default. There is a default value for the uniformity, that can be substituted in cases of interest, for instance when instantiating a `pseudo_emetric_space` structure on a product. Continuity of `edist` is proved in `topology.instances.ennreal` -/ class pseudo_emetric_space (α : Type u) extends has_edist α : Type u := (edist_self : ∀ x : α, edist x x = 0) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) (to_uniform_space : uniform_space α := uniform_space_of_edist edist edist_self edist_comm edist_triangle) (uniformity_edist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε} . control_laws_tac) attribute [priority 100, instance] pseudo_emetric_space.to_uniform_space /- Pseudoemetric spaces are less common than metric spaces. Therefore, we work in a dedicated namespace, while notions associated to metric spaces are mostly in the root namespace. -/ variables [pseudo_emetric_space α] export pseudo_emetric_space (edist_self edist_comm edist_triangle) attribute [simp] edist_self /-- Triangle inequality for the extended distance -/ theorem edist_triangle_left (x y z : α) : edist x y ≤ edist z x + edist z y := by rw edist_comm z; apply edist_triangle theorem edist_triangle_right (x y z : α) : edist x y ≤ edist x z + edist y z := by rw edist_comm y; apply edist_triangle lemma edist_triangle4 (x y z t : α) : edist x t ≤ edist x y + edist y z + edist z t := calc edist x t ≤ edist x z + edist z t : edist_triangle x z t ... ≤ (edist x y + edist y z) + edist z t : add_le_add_right (edist_triangle x y z) _ /-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/ lemma edist_le_Ico_sum_edist (f : ℕ → α) {m n} (h : m ≤ n) : edist (f m) (f n) ≤ ∑ i in finset.Ico m n, edist (f i) (f (i + 1)) := begin revert n, refine nat.le_induction _ _, { simp only [finset.sum_empty, finset.Ico_self, edist_self], -- TODO: Why doesn't Lean close this goal automatically? `exact le_rfl` fails too. exact le_refl (0:ℝ≥0∞) }, { assume n hn hrec, calc edist (f m) (f (n+1)) ≤ edist (f m) (f n) + edist (f n) (f (n+1)) : edist_triangle _ _ _ ... ≤ ∑ i in finset.Ico m n, _ + _ : add_le_add hrec le_rfl ... = ∑ i in finset.Ico m (n+1), _ : by rw [nat.Ico_succ_right_eq_insert_Ico hn, finset.sum_insert, add_comm]; simp } end /-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/ lemma edist_le_range_sum_edist (f : ℕ → α) (n : ℕ) : edist (f 0) (f n) ≤ ∑ i in finset.range n, edist (f i) (f (i + 1)) := nat.Ico_zero_eq_range ▸ edist_le_Ico_sum_edist f (nat.zero_le n) /-- A version of `edist_le_Ico_sum_edist` with each intermediate distance replaced with an upper estimate. -/ lemma edist_le_Ico_sum_of_edist_le {f : ℕ → α} {m n} (hmn : m ≤ n) {d : ℕ → ℝ≥0∞} (hd : ∀ {k}, m ≤ k → k < n → edist (f k) (f (k + 1)) ≤ d k) : edist (f m) (f n) ≤ ∑ i in finset.Ico m n, d i := le_trans (edist_le_Ico_sum_edist f hmn) $ finset.sum_le_sum $ λ k hk, hd (finset.mem_Ico.1 hk).1 (finset.mem_Ico.1 hk).2 /-- A version of `edist_le_range_sum_edist` with each intermediate distance replaced with an upper estimate. -/ lemma edist_le_range_sum_of_edist_le {f : ℕ → α} (n : ℕ) {d : ℕ → ℝ≥0∞} (hd : ∀ {k}, k < n → edist (f k) (f (k + 1)) ≤ d k) : edist (f 0) (f n) ≤ ∑ i in finset.range n, d i := nat.Ico_zero_eq_range ▸ edist_le_Ico_sum_of_edist_le (zero_le n) (λ _ _, hd) /-- Reformulation of the uniform structure in terms of the extended distance -/ theorem uniformity_pseudoedist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε} := pseudo_emetric_space.uniformity_edist theorem uniformity_basis_edist : (𝓤 α).has_basis (λ ε : ℝ≥0∞, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) := (@uniformity_pseudoedist α _).symm ▸ has_basis_binfi_principal (λ r hr p hp, ⟨min r p, lt_min hr hp, λ x hx, lt_of_lt_of_le hx (min_le_left _ _), λ x hx, lt_of_lt_of_le hx (min_le_right _ _)⟩) ⟨1, ennreal.zero_lt_one⟩ /-- Characterization of the elements of the uniformity in terms of the extended distance -/ theorem mem_uniformity_edist {s : set (α×α)} : s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, edist a b < ε → (a, b) ∈ s) := uniformity_basis_edist.mem_uniformity_iff /-- Given `f : β → ℝ≥0∞`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_edist`, `uniformity_basis_edist'`, `uniformity_basis_edist_nnreal`, and `uniformity_basis_edist_inv_nat`. -/ protected theorem emetric.mk_uniformity_basis {β : Type*} {p : β → Prop} {f : β → ℝ≥0∞} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 < f x}) := begin refine ⟨λ s, uniformity_basis_edist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, rcases hf ε ε₀ with ⟨i, hi, H⟩, exact ⟨i, hi, λ x hx, hε $ lt_of_lt_of_le hx H⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, H⟩ } end /-- Given `f : β → ℝ≥0∞`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then closed `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_edist_le` and `uniformity_basis_edist_le'`. -/ protected theorem emetric.mk_uniformity_basis_le {β : Type*} {p : β → Prop} {f : β → ℝ≥0∞} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 ≤ f x}) := begin refine ⟨λ s, uniformity_basis_edist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, rcases exists_between ε₀ with ⟨ε', hε'⟩, rcases hf ε' hε'.1 with ⟨i, hi, H⟩, exact ⟨i, hi, λ x hx, hε $ lt_of_le_of_lt (le_trans hx H) hε'.2⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, λ x hx, H (le_of_lt hx)⟩ } end theorem uniformity_basis_edist_le : (𝓤 α).has_basis (λ ε : ℝ≥0∞, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) := emetric.mk_uniformity_basis_le (λ _, id) (λ ε ε₀, ⟨ε, ε₀, le_refl ε⟩) theorem uniformity_basis_edist' (ε' : ℝ≥0∞) (hε' : 0 < ε') : (𝓤 α).has_basis (λ ε : ℝ≥0∞, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 < ε}) := emetric.mk_uniformity_basis (λ _, and.left) (λ ε ε₀, let ⟨δ, hδ⟩ := exists_between hε' in ⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩) theorem uniformity_basis_edist_le' (ε' : ℝ≥0∞) (hε' : 0 < ε') : (𝓤 α).has_basis (λ ε : ℝ≥0∞, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) := emetric.mk_uniformity_basis_le (λ _, and.left) (λ ε ε₀, let ⟨δ, hδ⟩ := exists_between hε' in ⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩) theorem uniformity_basis_edist_nnreal : (𝓤 α).has_basis (λ ε : ℝ≥0, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) := emetric.mk_uniformity_basis (λ _, ennreal.coe_pos.2) (λ ε ε₀, let ⟨δ, hδ⟩ := ennreal.lt_iff_exists_nnreal_btwn.1 ε₀ in ⟨δ, ennreal.coe_pos.1 hδ.1, le_of_lt hδ.2⟩) theorem uniformity_basis_edist_inv_nat : (𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | edist p.1 p.2 < (↑n)⁻¹}) := emetric.mk_uniformity_basis (λ n _, ennreal.inv_pos.2 $ ennreal.nat_ne_top n) (λ ε ε₀, let ⟨n, hn⟩ := ennreal.exists_inv_nat_lt (ne_of_gt ε₀) in ⟨n, trivial, le_of_lt hn⟩) theorem uniformity_basis_edist_inv_two_pow : (𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | edist p.1 p.2 < 2⁻¹ ^ n}) := emetric.mk_uniformity_basis (λ n _, ennreal.pow_pos (ennreal.inv_pos.2 ennreal.two_ne_top) _) (λ ε ε₀, let ⟨n, hn⟩ := ennreal.exists_inv_two_pow_lt (ne_of_gt ε₀) in ⟨n, trivial, le_of_lt hn⟩) /-- Fixed size neighborhoods of the diagonal belong to the uniform structure -/ theorem edist_mem_uniformity {ε:ℝ≥0∞} (ε0 : 0 < ε) : {p:α×α | edist p.1 p.2 < ε} ∈ 𝓤 α := mem_uniformity_edist.2 ⟨ε, ε0, λ a b, id⟩ namespace emetric @[priority 900] instance : is_countably_generated (𝓤 α) := is_countably_generated_of_seq ⟨_, uniformity_basis_edist_inv_nat.eq_infi⟩ /-- ε-δ characterization of uniform continuity on a set for pseudoemetric spaces -/ theorem uniform_continuous_on_iff [pseudo_emetric_space β] {f : α → β} {s : set α} : uniform_continuous_on f s ↔ ∀ ε > 0, ∃ δ > 0, ∀ {a b ∈ s}, edist a b < δ → edist (f a) (f b) < ε := uniformity_basis_edist.uniform_continuous_on_iff uniformity_basis_edist /-- ε-δ characterization of uniform continuity on pseudoemetric spaces -/ theorem uniform_continuous_iff [pseudo_emetric_space β] {f : α → β} : uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b:α}, edist a b < δ → edist (f a) (f b) < ε := uniformity_basis_edist.uniform_continuous_iff uniformity_basis_edist /-- ε-δ characterization of uniform embeddings on pseudoemetric spaces -/ theorem uniform_embedding_iff [pseudo_emetric_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ := uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl ⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (edist_mem_uniformity δ0), ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 tu in ⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩, λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_edist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in ⟨_, edist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩ /-- If a map between pseudoemetric spaces is a uniform embedding then the edistance between `f x` and `f y` is controlled in terms of the distance between `x` and `y`. -/ theorem controlled_of_uniform_embedding [pseudo_emetric_space β] {f : α → β} : uniform_embedding f → (∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, edist a b < δ → edist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ) := begin assume h, exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩, end /-- ε-δ characterization of Cauchy sequences on pseudoemetric spaces -/ protected lemma cauchy_iff {f : filter α} : cauchy f ↔ f ≠ ⊥ ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, edist x y < ε := by rw ← ne_bot_iff; exact uniformity_basis_edist.cauchy_iff /-- A very useful criterion to show that a space is complete is to show that all sequences which satisfy a bound of the form `edist (u n) (u m) < B N` for all `n m ≥ N` are converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to `0`, which makes it possible to use arguments of converging series, while this is impossible to do in general for arbitrary Cauchy sequences. -/ theorem complete_of_convergent_controlled_sequences (B : ℕ → ℝ≥0∞) (hB : ∀n, 0 < B n) (H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → edist (u n) (u m) < B N) → ∃x, tendsto u at_top (𝓝 x)) : complete_space α := uniform_space.complete_of_convergent_controlled_sequences (λ n, {p:α×α | edist p.1 p.2 < B n}) (λ n, edist_mem_uniformity $ hB n) H /-- A sequentially complete pseudoemetric space is complete. -/ theorem complete_of_cauchy_seq_tendsto : (∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α := uniform_space.complete_of_cauchy_seq_tendsto /-- Expressing locally uniform convergence on a set using `edist`. -/ lemma tendsto_locally_uniformly_on_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_locally_uniformly_on F f p s ↔ ∀ ε > 0, ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε := begin refine ⟨λ H ε hε, H _ (edist_mem_uniformity hε), λ H u hu x hx, _⟩, rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩, rcases H ε εpos x hx with ⟨t, ht, Ht⟩, exact ⟨t, ht, Ht.mono (λ n hs x hx, hε (hs x hx))⟩ end /-- Expressing uniform convergence on a set using `edist`. -/ lemma tendsto_uniformly_on_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_uniformly_on F f p s ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x ∈ s, edist (f x) (F n x) < ε := begin refine ⟨λ H ε hε, H _ (edist_mem_uniformity hε), λ H u hu, _⟩, rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩, exact (H ε εpos).mono (λ n hs x hx, hε (hs x hx)) end /-- Expressing locally uniform convergence using `edist`. -/ lemma tendsto_locally_uniformly_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_locally_uniformly F f p ↔ ∀ ε > 0, ∀ (x : β), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε := by simp only [← tendsto_locally_uniformly_on_univ, tendsto_locally_uniformly_on_iff, mem_univ, forall_const, exists_prop, nhds_within_univ] /-- Expressing uniform convergence using `edist`. -/ lemma tendsto_uniformly_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_uniformly F f p ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x, edist (f x) (F n x) < ε := by simp only [← tendsto_uniformly_on_univ, tendsto_uniformly_on_iff, mem_univ, forall_const] end emetric open emetric /-- Auxiliary function to replace the uniformity on a pseudoemetric space with a uniformity which is equal to the original one, but maybe not defeq. This is useful if one wants to construct a pseudoemetric space with a specified uniformity. See Note [forgetful inheritance] explaining why having definitionally the right uniformity is often important. -/ def pseudo_emetric_space.replace_uniformity {α} [U : uniform_space α] (m : pseudo_emetric_space α) (H : @uniformity _ U = @uniformity _ pseudo_emetric_space.to_uniform_space) : pseudo_emetric_space α := { edist := @edist _ m.to_has_edist, edist_self := edist_self, edist_comm := edist_comm, edist_triangle := edist_triangle, to_uniform_space := U, uniformity_edist := H.trans (@pseudo_emetric_space.uniformity_edist α _) } /-- The extended pseudometric induced by a function taking values in a pseudoemetric space. -/ def pseudo_emetric_space.induced {α β} (f : α → β) (m : pseudo_emetric_space β) : pseudo_emetric_space α := { edist := λ x y, edist (f x) (f y), edist_self := λ x, edist_self _, edist_comm := λ x y, edist_comm _ _, edist_triangle := λ x y z, edist_triangle _ _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_edist := begin apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, edist (f x) (f y)), refine λ s, mem_comap.trans _, split; intro H, { rcases H with ⟨r, ru, rs⟩, rcases mem_uniformity_edist.1 ru with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h }, { rcases H with ⟨ε, ε0, hε⟩, exact ⟨_, edist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ } end } /-- Pseudoemetric space instance on subsets of pseudoemetric spaces -/ instance {α : Type*} {p : α → Prop} [pseudo_emetric_space α] : pseudo_emetric_space (subtype p) := pseudo_emetric_space.induced coe ‹_› /-- The extended psuedodistance on a subset of a pseudoemetric space is the restriction of the original pseudodistance, by definition -/ theorem subtype.edist_eq {p : α → Prop} (x y : subtype p) : edist x y = edist (x : α) y := rfl namespace mul_opposite /-- Pseudoemetric space instance on the multiplicative opposite of a pseudoemetric space. -/ @[to_additive "Pseudoemetric space instance on the additive opposite of a pseudoemetric space."] instance {α : Type*} [pseudo_emetric_space α] : pseudo_emetric_space αᵐᵒᵖ := pseudo_emetric_space.induced unop ‹_› @[to_additive] theorem edist_unop (x y : αᵐᵒᵖ) : edist (unop x) (unop y) = edist x y := rfl @[to_additive] theorem edist_op (x y : α) : edist (op x) (op y) = edist x y := rfl end mul_opposite section ulift instance : pseudo_emetric_space (ulift α) := pseudo_emetric_space.induced ulift.down ‹_› lemma ulift.edist_eq (x y : ulift α) : edist x y = edist x.down y.down := rfl @[simp] lemma ulift.edist_up_up (x y : α) : edist (ulift.up x) (ulift.up y) = edist x y := rfl end ulift /-- The product of two pseudoemetric spaces, with the max distance, is an extended pseudometric spaces. We make sure that the uniform structure thus constructed is the one corresponding to the product of uniform spaces, to avoid diamond problems. -/ instance prod.pseudo_emetric_space_max [pseudo_emetric_space β] : pseudo_emetric_space (α × β) := { edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2), edist_self := λ x, by simp, edist_comm := λ x y, by simp [edist_comm], edist_triangle := λ x y z, max_le (le_trans (edist_triangle _ _ _) (add_le_add (le_max_left _ _) (le_max_left _ _))) (le_trans (edist_triangle _ _ _) (add_le_add (le_max_right _ _) (le_max_right _ _))), uniformity_edist := begin refine uniformity_prod.trans _, simp only [pseudo_emetric_space.uniformity_edist, comap_infi], rw ← infi_inf_eq, congr, funext, rw ← infi_inf_eq, congr, funext, simp [inf_principal, ext_iff, max_lt_iff] end, to_uniform_space := prod.uniform_space } lemma prod.edist_eq [pseudo_emetric_space β] (x y : α × β) : edist x y = max (edist x.1 y.1) (edist x.2 y.2) := rfl section pi open finset variables {π : β → Type*} [fintype β] /-- The product of a finite number of pseudoemetric spaces, with the max distance, is still a pseudoemetric space. This construction would also work for infinite products, but it would not give rise to the product topology. Hence, we only formalize it in the good situation of finitely many spaces. -/ instance pseudo_emetric_space_pi [∀b, pseudo_emetric_space (π b)] : pseudo_emetric_space (Πb, π b) := { edist := λ f g, finset.sup univ (λb, edist (f b) (g b)), edist_self := assume f, bot_unique $ finset.sup_le $ by simp, edist_comm := assume f g, by unfold edist; congr; funext a; exact edist_comm _ _, edist_triangle := assume f g h, begin simp only [finset.sup_le_iff], assume b hb, exact le_trans (edist_triangle _ (g b) _) (add_le_add (le_sup hb) (le_sup hb)) end, to_uniform_space := Pi.uniform_space _, uniformity_edist := begin simp only [Pi.uniformity, pseudo_emetric_space.uniformity_edist, comap_infi, gt_iff_lt, preimage_set_of_eq, comap_principal], rw infi_comm, congr, funext ε, rw infi_comm, congr, funext εpos, change 0 < ε at εpos, simp [set.ext_iff, εpos] end } lemma edist_pi_def [Π b, pseudo_emetric_space (π b)] (f g : Π b, π b) : edist f g = finset.sup univ (λb, edist (f b) (g b)) := rfl @[simp] lemma edist_pi_const [nonempty β] (a b : α) : edist (λ x : β, a) (λ _, b) = edist a b := finset.sup_const univ_nonempty (edist a b) lemma edist_le_pi_edist [Π b, pseudo_emetric_space (π b)] (f g : Π b, π b) (b : β) : edist (f b) (g b) ≤ edist f g := finset.le_sup (finset.mem_univ b) lemma edist_pi_le_iff [Π b, pseudo_emetric_space (π b)] {f g : Π b, π b} {d : ℝ≥0∞} : edist f g ≤ d ↔ ∀ b, edist (f b) (g b) ≤ d := finset.sup_le_iff.trans $ by simp only [finset.mem_univ, forall_const] end pi namespace emetric variables {x y z : α} {ε ε₁ ε₂ : ℝ≥0∞} {s : set α} /-- `emetric.ball x ε` is the set of all points `y` with `edist y x < ε` -/ def ball (x : α) (ε : ℝ≥0∞) : set α := {y | edist y x < ε} @[simp] theorem mem_ball : y ∈ ball x ε ↔ edist y x < ε := iff.rfl theorem mem_ball' : y ∈ ball x ε ↔ edist x y < ε := by rw [edist_comm, mem_ball] /-- `emetric.closed_ball x ε` is the set of all points `y` with `edist y x ≤ ε` -/ def closed_ball (x : α) (ε : ℝ≥0∞) := {y | edist y x ≤ ε} @[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ edist y x ≤ ε := iff.rfl theorem mem_closed_ball' : y ∈ closed_ball x ε ↔ edist x y ≤ ε := by rw [edist_comm, mem_closed_ball] @[simp] theorem closed_ball_top (x : α) : closed_ball x ∞ = univ := eq_univ_of_forall $ λ y, le_top theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε := assume y hy, le_of_lt hy theorem pos_of_mem_ball (hy : y ∈ ball x ε) : 0 < ε := lt_of_le_of_lt (zero_le _) hy theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε := show edist x x < ε, by rw edist_self; assumption theorem mem_closed_ball_self : x ∈ closed_ball x ε := show edist x x ≤ ε, by rw edist_self; exact bot_le theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε := by rw [mem_ball', mem_ball] theorem mem_closed_ball_comm : x ∈ closed_ball y ε ↔ y ∈ closed_ball x ε := by rw [mem_closed_ball', mem_closed_ball] theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ := λ y (yx : _ < ε₁), lt_of_lt_of_le yx h theorem closed_ball_subset_closed_ball (h : ε₁ ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball x ε₂ := λ y (yx : _ ≤ ε₁), le_trans yx h theorem ball_disjoint (h : ε₁ + ε₂ ≤ edist x y) : disjoint (ball x ε₁) (ball y ε₂) := λ z ⟨h₁, h₂⟩, (edist_triangle_left x y z).not_lt $ (ennreal.add_lt_add h₁ h₂).trans_le h theorem ball_subset (h : edist x y + ε₁ ≤ ε₂) (h' : edist x y ≠ ∞) : ball x ε₁ ⊆ ball y ε₂ := λ z zx, calc edist z y ≤ edist z x + edist x y : edist_triangle _ _ _ ... = edist x y + edist z x : add_comm _ _ ... < edist x y + ε₁ : ennreal.add_lt_add_left h' zx ... ≤ ε₂ : h theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε := begin have : 0 < ε - edist y x := by simpa using h, refine ⟨ε - edist y x, this, ball_subset _ (ne_top_of_lt h)⟩, exact (add_tsub_cancel_of_le (mem_ball.mp h).le).le end theorem ball_eq_empty_iff : ball x ε = ∅ ↔ ε = 0 := eq_empty_iff_forall_not_mem.trans ⟨λh, le_bot_iff.1 (le_of_not_gt (λ ε0, h _ (mem_ball_self ε0))), λε0 y h, not_lt_of_le (le_of_eq ε0) (pos_of_mem_ball h)⟩ /-- Relation “two points are at a finite edistance” is an equivalence relation. -/ def edist_lt_top_setoid : setoid α := { r := λ x y, edist x y < ⊤, iseqv := ⟨λ x, by { rw edist_self, exact ennreal.coe_lt_top }, λ x y h, by rwa edist_comm, λ x y z hxy hyz, lt_of_le_of_lt (edist_triangle x y z) (ennreal.add_lt_top.2 ⟨hxy, hyz⟩)⟩ } @[simp] lemma ball_zero : ball x 0 = ∅ := by rw [emetric.ball_eq_empty_iff] theorem nhds_basis_eball : (𝓝 x).has_basis (λ ε:ℝ≥0∞, 0 < ε) (ball x) := nhds_basis_uniformity uniformity_basis_edist theorem nhds_basis_closed_eball : (𝓝 x).has_basis (λ ε:ℝ≥0∞, 0 < ε) (closed_ball x) := nhds_basis_uniformity uniformity_basis_edist_le theorem nhds_eq : 𝓝 x = (⨅ε>0, 𝓟 (ball x ε)) := nhds_basis_eball.eq_binfi theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s := nhds_basis_eball.mem_iff theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s := by simp [is_open_iff_nhds, mem_nhds_iff] theorem is_open_ball : is_open (ball x ε) := is_open_iff.2 $ λ y, exists_ball_subset_ball theorem is_closed_ball_top : is_closed (ball x ⊤) := is_open_compl_iff.1 $ is_open_iff.2 $ λ y hy, ⟨⊤, ennreal.coe_lt_top, (ball_disjoint $ by { rw ennreal.top_add, exact le_of_not_lt hy }).subset_compl_right⟩ theorem ball_mem_nhds (x : α) {ε : ℝ≥0∞} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x := is_open_ball.mem_nhds (mem_ball_self ε0) theorem closed_ball_mem_nhds (x : α) {ε : ℝ≥0∞} (ε0 : 0 < ε) : closed_ball x ε ∈ 𝓝 x := mem_of_superset (ball_mem_nhds x ε0) ball_subset_closed_ball theorem ball_prod_same [pseudo_emetric_space β] (x : α) (y : β) (r : ℝ≥0∞) : ball x r ×ˢ ball y r = ball (x, y) r := ext $ λ z, max_lt_iff.symm theorem closed_ball_prod_same [pseudo_emetric_space β] (x : α) (y : β) (r : ℝ≥0∞) : closed_ball x r ×ˢ closed_ball y r = closed_ball (x, y) r := ext $ λ z, max_le_iff.symm /-- ε-characterization of the closure in pseudoemetric spaces -/ theorem mem_closure_iff : x ∈ closure s ↔ ∀ε>0, ∃y ∈ s, edist x y < ε := (mem_closure_iff_nhds_basis nhds_basis_eball).trans $ by simp only [mem_ball, edist_comm x] theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, edist (u x) a < ε := nhds_basis_eball.tendsto_right_iff theorem tendsto_at_top [nonempty β] [semilattice_sup β] {u : β → α} {a : α} : tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, edist (u n) a < ε := (at_top_basis.tendsto_iff nhds_basis_eball).trans $ by simp only [exists_prop, true_and, mem_Ici, mem_ball] theorem inseparable_iff : inseparable x y ↔ edist x y = 0 := by simp [inseparable_iff_mem_closure, mem_closure_iff, edist_comm, forall_lt_iff_le'] /-- In a pseudoemetric space, Cauchy sequences are characterized by the fact that, eventually, the pseudoedistance between its elements is arbitrarily small -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem cauchy_seq_iff [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, edist (u m) (u n) < ε := uniformity_basis_edist.cauchy_seq_iff /-- A variation around the emetric characterization of Cauchy sequences -/ theorem cauchy_seq_iff' [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>(0 : ℝ≥0∞), ∃N, ∀n≥N, edist (u n) (u N) < ε := uniformity_basis_edist.cauchy_seq_iff' /-- A variation of the emetric characterization of Cauchy sequences that deals with `ℝ≥0` upper bounds. -/ theorem cauchy_seq_iff_nnreal [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ ε : ℝ≥0, 0 < ε → ∃ N, ∀ n, N ≤ n → edist (u n) (u N) < ε := uniformity_basis_edist_nnreal.cauchy_seq_iff' theorem totally_bounded_iff {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t : set α, t.finite ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, H _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, ft, h⟩ := H ε ε0 in ⟨t, ft, h.trans $ Union₂_mono $ λ y yt z, hε⟩⟩ theorem totally_bounded_iff' {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t⊆s, set.finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, (totally_bounded_iff_subset.1 H) _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, _, ft, h⟩ := H ε ε0 in ⟨t, ft, h.trans $ Union₂_mono $ λ y yt z, hε⟩⟩ section compact /-- For a set `s` in a pseudo emetric space, if for every `ε > 0` there exists a countable set that is `ε`-dense in `s`, then there exists a countable subset `t ⊆ s` that is dense in `s`. -/ lemma subset_countable_closure_of_almost_dense_set (s : set α) (hs : ∀ ε > 0, ∃ t : set α, t.countable ∧ s ⊆ ⋃ x ∈ t, closed_ball x ε) : ∃ t ⊆ s, (t.countable ∧ s ⊆ closure t) := begin rcases s.eq_empty_or_nonempty with rfl|⟨x₀, hx₀⟩, { exact ⟨∅, empty_subset _, countable_empty, empty_subset _⟩ }, choose! T hTc hsT using (λ n : ℕ, hs n⁻¹ (by simp)), have : ∀ r x, ∃ y ∈ s, closed_ball x r ∩ s ⊆ closed_ball y (r * 2), { intros r x, rcases (closed_ball x r ∩ s).eq_empty_or_nonempty with he|⟨y, hxy, hys⟩, { refine ⟨x₀, hx₀, _⟩, rw he, exact empty_subset _ }, { refine ⟨y, hys, λ z hz, _⟩, calc edist z y ≤ edist z x + edist y x : edist_triangle_right _ _ _ ... ≤ r + r : add_le_add hz.1 hxy ... = r * 2 : (mul_two r).symm } }, choose f hfs hf, refine ⟨⋃ n : ℕ, (f n⁻¹) '' (T n), Union_subset $ λ n, image_subset_iff.2 (λ z hz, hfs _ _), countable_Union $ λ n, (hTc n).image _, _⟩, refine λ x hx, mem_closure_iff.2 (λ ε ε0, _), rcases ennreal.exists_inv_nat_lt (ennreal.half_pos ε0.lt.ne').ne' with ⟨n, hn⟩, rcases mem_Union₂.1 (hsT n hx) with ⟨y, hyn, hyx⟩, refine ⟨f n⁻¹ y, mem_Union.2 ⟨n, mem_image_of_mem _ hyn⟩, _⟩, calc edist x (f n⁻¹ y) ≤ n⁻¹ * 2 : hf _ _ ⟨hyx, hx⟩ ... < ε : ennreal.mul_lt_of_lt_div hn end /-- A compact set in a pseudo emetric space is separable, i.e., it is a subset of the closure of a countable set. -/ lemma subset_countable_closure_of_compact {s : set α} (hs : is_compact s) : ∃ t ⊆ s, (t.countable ∧ s ⊆ closure t) := begin refine subset_countable_closure_of_almost_dense_set s (λ ε hε, _), rcases totally_bounded_iff'.1 hs.totally_bounded ε hε with ⟨t, hts, htf, hst⟩, exact ⟨t, htf.countable, subset.trans hst $ Union₂_mono $ λ _ _, ball_subset_closed_ball⟩ end end compact section second_countable open _root_.topological_space variables (α) /-- A sigma compact pseudo emetric space has second countable topology. This is not an instance to avoid a loop with `sigma_compact_space_of_locally_compact_second_countable`. -/ lemma second_countable_of_sigma_compact [sigma_compact_space α] : second_countable_topology α := begin suffices : separable_space α, by exactI uniform_space.second_countable_of_separable α, choose T hTsub hTc hsubT using λ n, subset_countable_closure_of_compact (is_compact_compact_covering α n), refine ⟨⟨⋃ n, T n, countable_Union hTc, λ x, _⟩⟩, rcases Union_eq_univ_iff.1 (Union_compact_covering α) x with ⟨n, hn⟩, exact closure_mono (subset_Union _ n) (hsubT _ hn) end variable {α} lemma second_countable_of_almost_dense_set (hs : ∀ ε > 0, ∃ t : set α, t.countable ∧ (⋃ x ∈ t, closed_ball x ε) = univ) : second_countable_topology α := begin suffices : separable_space α, by exactI uniform_space.second_countable_of_separable α, rcases subset_countable_closure_of_almost_dense_set (univ : set α) (λ ε ε0, _) with ⟨t, -, htc, ht⟩, { exact ⟨⟨t, htc, λ x, ht (mem_univ x)⟩⟩ }, { rcases hs ε ε0 with ⟨t, htc, ht⟩, exact ⟨t, htc, univ_subset_iff.2 ht⟩ } end end second_countable section diam /-- The diameter of a set in a pseudoemetric space, named `emetric.diam` -/ def diam (s : set α) := ⨆ (x ∈ s) (y ∈ s), edist x y lemma diam_le_iff {d : ℝ≥0∞} : diam s ≤ d ↔ ∀ (x ∈ s) (y ∈ s), edist x y ≤ d := by simp only [diam, supr_le_iff] lemma diam_image_le_iff {d : ℝ≥0∞} {f : β → α} {s : set β} : diam (f '' s) ≤ d ↔ ∀ (x ∈ s) (y ∈ s), edist (f x) (f y) ≤ d := by simp only [diam_le_iff, ball_image_iff] lemma edist_le_of_diam_le {d} (hx : x ∈ s) (hy : y ∈ s) (hd : diam s ≤ d) : edist x y ≤ d := diam_le_iff.1 hd x hx y hy /-- If two points belong to some set, their edistance is bounded by the diameter of the set -/ lemma edist_le_diam_of_mem (hx : x ∈ s) (hy : y ∈ s) : edist x y ≤ diam s := edist_le_of_diam_le hx hy le_rfl /-- If the distance between any two points in a set is bounded by some constant, this constant bounds the diameter. -/ lemma diam_le {d : ℝ≥0∞} (h : ∀ (x ∈ s) (y ∈ s), edist x y ≤ d) : diam s ≤ d := diam_le_iff.2 h /-- The diameter of a subsingleton vanishes. -/ lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 := nonpos_iff_eq_zero.1 $ diam_le $ λ x hx y hy, (hs hx hy).symm ▸ edist_self y ▸ le_rfl /-- The diameter of the empty set vanishes -/ @[simp] lemma diam_empty : diam (∅ : set α) = 0 := diam_subsingleton subsingleton_empty /-- The diameter of a singleton vanishes -/ @[simp] lemma diam_singleton : diam ({x} : set α) = 0 := diam_subsingleton subsingleton_singleton lemma diam_Union_mem_option {ι : Type*} (o : option ι) (s : ι → set α) : diam (⋃ i ∈ o, s i) = ⨆ i ∈ o, diam (s i) := by cases o; simp lemma diam_insert : diam (insert x s) = max (⨆ y ∈ s, edist x y) (diam s) := eq_of_forall_ge_iff $ λ d, by simp only [diam_le_iff, ball_insert_iff, edist_self, edist_comm x, max_le_iff, supr_le_iff, zero_le, true_and, forall_and_distrib, and_self, ← and_assoc] lemma diam_pair : diam ({x, y} : set α) = edist x y := by simp only [supr_singleton, diam_insert, diam_singleton, ennreal.max_zero_right] lemma diam_triple : diam ({x, y, z} : set α) = max (max (edist x y) (edist x z)) (edist y z) := by simp only [diam_insert, supr_insert, supr_singleton, diam_singleton, ennreal.max_zero_right, ennreal.sup_eq_max] /-- The diameter is monotonous with respect to inclusion -/ lemma diam_mono {s t : set α} (h : s ⊆ t) : diam s ≤ diam t := diam_le $ λ x hx y hy, edist_le_diam_of_mem (h hx) (h hy) /-- The diameter of a union is controlled by the diameter of the sets, and the edistance between two points in the sets. -/ lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + edist x y + diam t := begin have A : ∀a ∈ s, ∀b ∈ t, edist a b ≤ diam s + edist x y + diam t := λa ha b hb, calc edist a b ≤ edist a x + edist x y + edist y b : edist_triangle4 _ _ _ _ ... ≤ diam s + edist x y + diam t : add_le_add (add_le_add (edist_le_diam_of_mem ha xs) le_rfl) (edist_le_diam_of_mem yt hb), refine diam_le (λa ha b hb, _), cases (mem_union _ _ _).1 ha with h'a h'a; cases (mem_union _ _ _).1 hb with h'b h'b, { calc edist a b ≤ diam s : edist_le_diam_of_mem h'a h'b ... ≤ diam s + (edist x y + diam t) : le_self_add ... = diam s + edist x y + diam t : (add_assoc _ _ _).symm }, { exact A a h'a b h'b }, { have Z := A b h'b a h'a, rwa [edist_comm] at Z }, { calc edist a b ≤ diam t : edist_le_diam_of_mem h'a h'b ... ≤ (diam s + edist x y) + diam t : le_add_self } end lemma diam_union' {t : set α} (h : (s ∩ t).nonempty) : diam (s ∪ t) ≤ diam s + diam t := let ⟨x, ⟨xs, xt⟩⟩ := h in by simpa using diam_union xs xt lemma diam_closed_ball {r : ℝ≥0∞} : diam (closed_ball x r) ≤ 2 * r := diam_le $ λa ha b hb, calc edist a b ≤ edist a x + edist b x : edist_triangle_right _ _ _ ... ≤ r + r : add_le_add ha hb ... = 2 * r : (two_mul r).symm lemma diam_ball {r : ℝ≥0∞} : diam (ball x r) ≤ 2 * r := le_trans (diam_mono ball_subset_closed_ball) diam_closed_ball lemma diam_pi_le_of_le {π : β → Type*} [fintype β] [∀ b, pseudo_emetric_space (π b)] {s : Π (b : β), set (π b)} {c : ℝ≥0∞} (h : ∀ b, diam (s b) ≤ c) : diam (set.pi univ s) ≤ c := begin apply diam_le (λ x hx y hy, edist_pi_le_iff.mpr _), rw [mem_univ_pi] at hx hy, exact λ b, diam_le_iff.1 (h b) (x b) (hx b) (y b) (hy b), end end diam end emetric --namespace /-- We now define `emetric_space`, extending `pseudo_emetric_space`. -/ class emetric_space (α : Type u) extends pseudo_emetric_space α : Type u := (eq_of_edist_eq_zero : ∀ {x y : α}, edist x y = 0 → x = y) variables {γ : Type w} [emetric_space γ] export emetric_space (eq_of_edist_eq_zero) /-- Characterize the equality of points by the vanishing of their extended distance -/ @[simp] theorem edist_eq_zero {x y : γ} : edist x y = 0 ↔ x = y := iff.intro eq_of_edist_eq_zero (assume : x = y, this ▸ edist_self _) @[simp] theorem zero_eq_edist {x y : γ} : 0 = edist x y ↔ x = y := iff.intro (assume h, eq_of_edist_eq_zero (h.symm)) (assume : x = y, this ▸ (edist_self _).symm) theorem edist_le_zero {x y : γ} : (edist x y ≤ 0) ↔ x = y := nonpos_iff_eq_zero.trans edist_eq_zero @[simp] theorem edist_pos {x y : γ} : 0 < edist x y ↔ x ≠ y := by simp [← not_le] /-- Two points coincide if their distance is `< ε` for all positive ε -/ theorem eq_of_forall_edist_le {x y : γ} (h : ∀ε > 0, edist x y ≤ ε) : x = y := eq_of_edist_eq_zero (eq_of_le_of_forall_le_of_dense bot_le h) /-- A map between emetric spaces is a uniform embedding if and only if the edistance between `f x` and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/ theorem uniform_embedding_iff' [emetric_space β] {f : γ → β} : uniform_embedding f ↔ (∀ ε > 0, ∃ δ > 0, ∀ {a b : γ}, edist a b < δ → edist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : γ}, edist (f a) (f b) < ε → edist a b < δ) := begin split, { assume h, exact ⟨emetric.uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩ }, { rintros ⟨h₁, h₂⟩, refine uniform_embedding_iff.2 ⟨_, emetric.uniform_continuous_iff.2 h₁, h₂⟩, assume x y hxy, have : edist x y ≤ 0, { refine le_of_forall_lt' (λδ δpos, _), rcases h₂ δ δpos with ⟨ε, εpos, hε⟩, have : edist (f x) (f y) < ε, by simpa [hxy], exact hε this }, simpa using this } end /-- An emetric space is separated -/ @[priority 100] -- see Note [lower instance priority] instance to_separated : separated_space γ := separated_def.2 $ λ x y h, eq_of_forall_edist_le $ λ ε ε0, le_of_lt (h _ (edist_mem_uniformity ε0)) /-- If a `pseudo_emetric_space` is a T₀ space, then it is an `emetric_space`. -/ def emetric.of_t0_pseudo_emetric_space (α : Type*) [pseudo_emetric_space α] [t0_space α] : emetric_space α := { eq_of_edist_eq_zero := λ x y hdist, inseparable.eq $ emetric.inseparable_iff.2 hdist, ..‹pseudo_emetric_space α› } /-- Auxiliary function to replace the uniformity on an emetric space with a uniformity which is equal to the original one, but maybe not defeq. This is useful if one wants to construct an emetric space with a specified uniformity. See Note [forgetful inheritance] explaining why having definitionally the right uniformity is often important. -/ def emetric_space.replace_uniformity {γ} [U : uniform_space γ] (m : emetric_space γ) (H : @uniformity _ U = @uniformity _ pseudo_emetric_space.to_uniform_space) : emetric_space γ := { edist := @edist _ m.to_has_edist, edist_self := edist_self, eq_of_edist_eq_zero := @eq_of_edist_eq_zero _ _, edist_comm := edist_comm, edist_triangle := edist_triangle, to_uniform_space := U, uniformity_edist := H.trans (@pseudo_emetric_space.uniformity_edist γ _) } /-- The extended metric induced by an injective function taking values in a emetric space. -/ def emetric_space.induced {γ β} (f : γ → β) (hf : function.injective f) (m : emetric_space β) : emetric_space γ := { edist := λ x y, edist (f x) (f y), edist_self := λ x, edist_self _, eq_of_edist_eq_zero := λ x y h, hf (edist_eq_zero.1 h), edist_comm := λ x y, edist_comm _ _, edist_triangle := λ x y z, edist_triangle _ _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_edist := begin apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, edist (f x) (f y)), refine λ s, mem_comap.trans _, split; intro H, { rcases H with ⟨r, ru, rs⟩, rcases mem_uniformity_edist.1 ru with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h }, { rcases H with ⟨ε, ε0, hε⟩, exact ⟨_, edist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ } end } /-- Emetric space instance on subsets of emetric spaces -/ instance {α : Type*} {p : α → Prop} [emetric_space α] : emetric_space (subtype p) := emetric_space.induced coe subtype.coe_injective ‹_› /-- Emetric space instance on the multiplicative opposite of an emetric space. -/ @[to_additive "Emetric space instance on the additive opposite of an emetric space."] instance {α : Type*} [emetric_space α] : emetric_space αᵐᵒᵖ := emetric_space.induced mul_opposite.unop mul_opposite.unop_injective ‹_› instance {α : Type*} [emetric_space α] : emetric_space (ulift α) := emetric_space.induced ulift.down ulift.down_injective ‹_› /-- The product of two emetric spaces, with the max distance, is an extended metric spaces. We make sure that the uniform structure thus constructed is the one corresponding to the product of uniform spaces, to avoid diamond problems. -/ instance prod.emetric_space_max [emetric_space β] : emetric_space (γ × β) := { eq_of_edist_eq_zero := λ x y h, begin cases max_le_iff.1 (le_of_eq h) with h₁ h₂, have A : x.fst = y.fst := edist_le_zero.1 h₁, have B : x.snd = y.snd := edist_le_zero.1 h₂, exact prod.ext_iff.2 ⟨A, B⟩ end, ..prod.pseudo_emetric_space_max } /-- Reformulation of the uniform structure in terms of the extended distance -/ theorem uniformity_edist : 𝓤 γ = ⨅ ε>0, 𝓟 {p:γ×γ | edist p.1 p.2 < ε} := pseudo_emetric_space.uniformity_edist section pi open finset variables {π : β → Type*} [fintype β] /-- The product of a finite number of emetric spaces, with the max distance, is still an emetric space. This construction would also work for infinite products, but it would not give rise to the product topology. Hence, we only formalize it in the good situation of finitely many spaces. -/ instance emetric_space_pi [∀b, emetric_space (π b)] : emetric_space (Πb, π b) := { eq_of_edist_eq_zero := assume f g eq0, begin have eq1 : sup univ (λ (b : β), edist (f b) (g b)) ≤ 0 := le_of_eq eq0, simp only [finset.sup_le_iff] at eq1, exact (funext $ assume b, edist_le_zero.1 $ eq1 b $ mem_univ b), end, ..pseudo_emetric_space_pi } end pi namespace emetric /-- A compact set in an emetric space is separable, i.e., it is the closure of a countable set. -/ lemma countable_closure_of_compact {s : set γ} (hs : is_compact s) : ∃ t ⊆ s, (t.countable ∧ s = closure t) := begin rcases subset_countable_closure_of_compact hs with ⟨t, hts, htc, hsub⟩, exact ⟨t, hts, htc, subset.antisymm hsub (closure_minimal hts hs.is_closed)⟩ end section diam variables {s : set γ} lemma diam_eq_zero_iff : diam s = 0 ↔ s.subsingleton := ⟨λ h x hx y hy, edist_le_zero.1 $ h ▸ edist_le_diam_of_mem hx hy, diam_subsingleton⟩ lemma diam_pos_iff : 0 < diam s ↔ ∃ (x ∈ s) (y ∈ s), x ≠ y := by simp only [pos_iff_ne_zero, ne.def, diam_eq_zero_iff, set.subsingleton, not_forall] end diam end emetric
f44e1ef967db30c421cdf9fcb61ab995ae704fc8
43390109ab88557e6090f3245c47479c123ee500
/src/Geometry/unordered_pairs.lean
a537015fdc22bda86cf10ace3a55314184f7f63e
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,334
lean
universe u private definition eqv {α : Type u} (p₁ p₂ : α × α) : Prop := (p₁.1 = p₂.1 ∧ p₁.2 = p₂.2) ∨ (p₁.1 = p₂.2 ∧ p₁.2 = p₂.1) local infix `~` := eqv open or private theorem eqv.refl {α : Type u} : ∀ p : α × α, p ~ p := assume p, inl ⟨rfl, rfl⟩ private theorem eqv.symm {α : Type u} : ∀ p₁ p₂ : α × α, p₁ ~ p₂ → p₂ ~ p₁ | (a₁, a₂) (b₁, b₂) (inl ⟨a₁b₁, a₂b₂⟩) := inl ⟨symm a₁b₁, symm a₂b₂⟩ | (a₁, a₂) (b₁, b₂) (inr ⟨a₁b₂, a₂b₁⟩) := inr ⟨symm a₂b₁, symm a₁b₂⟩ private theorem eqv.trans {α : Type u} : ∀ p₁ p₂ p₃ : α × α, p₁ ~ p₂ → p₂ ~ p₃ → p₁ ~ p₃ | (a₁, a₂) (b₁, b₂) (c₁, c₂) (inl ⟨a₁b₁, a₂b₂⟩) (inl ⟨b₁c₁, b₂c₂⟩) := inl ⟨trans a₁b₁ b₁c₁, trans a₂b₂ b₂c₂⟩ | (a₁, a₂) (b₁, b₂) (c₁, c₂) (inl ⟨a₁b₁, a₂b₂⟩) (inr ⟨b₁c₂, b₂c₁⟩) := inr ⟨trans a₁b₁ b₁c₂, trans a₂b₂ b₂c₁⟩ | (a₁, a₂) (b₁, b₂) (c₁, c₂) (inr ⟨a₁b₂, a₂b₁⟩) (inl ⟨b₁c₁, b₂c₂⟩) := inr ⟨trans a₁b₂ b₂c₂, trans a₂b₁ b₁c₁⟩ | (a₁, a₂) (b₁, b₂) (c₁, c₂) (inr ⟨a₁b₂, a₂b₁⟩) (inr ⟨b₁c₂, b₂c₁⟩) := inl ⟨trans a₁b₂ b₂c₁, trans a₂b₁ b₁c₂⟩ private theorem is_equivalence (α : Type u) : equivalence (@eqv α) := mk_equivalence (@eqv α) (@eqv.refl α) (@eqv.symm α) (@eqv.trans α) instance uprod.setoid (α : Type u) : setoid (α × α) := setoid.mk (@eqv α) (is_equivalence α) definition uprod (α : Type u) : Type u := quotient (uprod.setoid α) namespace uprod definition mk {α : Type u} (a₁ a₂ : α) : uprod α := ⟦(a₁, a₂)⟧ local notation `{` a₁ `,` a₂ `}` := mk a₁ a₂ theorem mk_eq_mk {α : Type} (a₁ a₂ : α) : {a₁, a₂} = {a₂, a₁} := quot.sound (inr ⟨rfl, rfl⟩) private definition mem_fn {α : Type} (a : α) : α × α → Prop | (a₁, a₂) := a = a₁ ∨ a = a₂ -- auxiliary lemma for proving mem_respects private lemma mem_swap {α : Type} {a : α} : ∀ {p : α × α}, mem_fn a p = mem_fn a (⟨p.2, p.1⟩) | (a₁, a₂) := propext (iff.intro (λ l : a = a₁ ∨ a = a₂, or.elim l (λ h₁, inr h₁) (λ h₂, inl h₂)) (λ r : a = a₂ ∨ a = a₁, or.elim r (λ h₁, inr h₁) (λ h₂, inl h₂))) private lemma mem_respects {α : Type} : ∀ {p₁ p₂ : α × α} (a : α), p₁ ~ p₂ → mem_fn a p₁ = mem_fn a p₂ | (a₁, a₂) (b₁, b₂) a (inl ⟨a₁b₁, a₂b₂⟩) := by { dsimp at a₁b₁, dsimp at a₂b₂, rw [a₁b₁, a₂b₂] } | (a₁, a₂) (b₁, b₂) a (inr ⟨a₁b₂, a₂b₁⟩) := by { dsimp at a₁b₂, dsimp at a₂b₁, rw [a₁b₂, a₂b₁], apply mem_swap } def mem {α : Type} (a : α) (u : uprod α) : Prop := quot.lift_on u (λ p, mem_fn a p) (λ p₁ p₂ e, mem_respects a e) local infix `∈` := mem theorem mem_mk_left {α : Type} (a b : α) : a ∈ {a, b} := inl rfl theorem mem_mk_right {α : Type} (a b : α) : b ∈ {a, b} := inr rfl theorem mem_or_mem_of_mem_mk {α : Type} {a b c : α} : c ∈ {a, b} → c = a ∨ c = b := λ h, h end uprod
e2e5cb3f7b8691d5835710d721d0c10f50b3ed16
63abd62053d479eae5abf4951554e1064a4c45b4
/src/topology/sequences.lean
99a5b146c90b91c8b6d5a618c875b5c63d3586ce
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
18,808
lean
/- Copyright (c) 2018 Jan-David Salchow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jan-David Salchow, Patrick Massot -/ import topology.bases import topology.subset_properties import topology.metric_space.basic /-! # Sequences in topological spaces In this file we define sequences in topological spaces and show how they are related to filters and the topology. In particular, we * define the sequential closure of a set and prove that it's contained in the closure, * define a type class "sequential_space" in which closure and sequential closure agree, * define sequential continuity and show that it coincides with continuity in sequential spaces, * provide an instance that shows that every first-countable (and in particular metric) space is a sequential space. * define sequential compactness, prove that compactness implies sequential compactness in first countable spaces, and prove they are equivalent for uniform spaces having a countable uniformity basis (in particular metric spaces). -/ open set filter open_locale topological_space variables {α : Type*} {β : Type*} local notation f ` ⟶ ` limit := tendsto f at_top (𝓝 limit) /-! ### Sequential closures, sequential continuity, and sequential spaces. -/ section topological_space variables [topological_space α] [topological_space β] /-- A sequence converges in the sence of topological spaces iff the associated statement for filter holds. -/ lemma topological_space.seq_tendsto_iff {x : ℕ → α} {limit : α} : tendsto x at_top (𝓝 limit) ↔ ∀ U : set α, limit ∈ U → is_open U → ∃ N, ∀ n ≥ N, (x n) ∈ U := (at_top_basis.tendsto_iff (nhds_basis_opens limit)).trans $ by simp only [and_imp, exists_prop, true_and, set.mem_Ici, ge_iff_le, id] /-- The sequential closure of a subset M ⊆ α of a topological space α is the set of all p ∈ α which arise as limit of sequences in M. -/ def sequential_closure (M : set α) : set α := {p | ∃ x : ℕ → α, (∀ n : ℕ, x n ∈ M) ∧ (x ⟶ p)} lemma subset_sequential_closure (M : set α) : M ⊆ sequential_closure M := assume p (_ : p ∈ M), show p ∈ sequential_closure M, from ⟨λ n, p, assume n, ‹p ∈ M›, tendsto_const_nhds⟩ /-- A set `s` is sequentially closed if for any converging sequence `x n` of elements of `s`, the limit belongs to `s` as well. -/ def is_seq_closed (s : set α) : Prop := s = sequential_closure s /-- A convenience lemma for showing that a set is sequentially closed. -/ lemma is_seq_closed_of_def {A : set α} (h : ∀(x : ℕ → α) (p : α), (∀ n : ℕ, x n ∈ A) → (x ⟶ p) → p ∈ A) : is_seq_closed A := show A = sequential_closure A, from subset.antisymm (subset_sequential_closure A) (show ∀ p, p ∈ sequential_closure A → p ∈ A, from (assume p ⟨x, _, _⟩, show p ∈ A, from h x p ‹∀ n : ℕ, ((x n) ∈ A)› ‹(x ⟶ p)›)) /-- The sequential closure of a set is contained in the closure of that set. The converse is not true. -/ lemma sequential_closure_subset_closure (M : set α) : sequential_closure M ⊆ closure M := assume p ⟨x, xM, xp⟩, mem_closure_of_tendsto xp (univ_mem_sets' xM) /-- A set is sequentially closed if it is closed. -/ lemma is_seq_closed_of_is_closed (M : set α) (_ : is_closed M) : is_seq_closed M := suffices sequential_closure M ⊆ M, from set.eq_of_subset_of_subset (subset_sequential_closure M) this, calc sequential_closure M ⊆ closure M : sequential_closure_subset_closure M ... = M : is_closed.closure_eq ‹is_closed M› /-- The limit of a convergent sequence in a sequentially closed set is in that set.-/ lemma mem_of_is_seq_closed {A : set α} (_ : is_seq_closed A) {x : ℕ → α} (_ : ∀ n, x n ∈ A) {limit : α} (_ : (x ⟶ limit)) : limit ∈ A := have limit ∈ sequential_closure A, from show ∃ x : ℕ → α, (∀ n : ℕ, x n ∈ A) ∧ (x ⟶ limit), from ⟨x, ‹∀ n, x n ∈ A›, ‹(x ⟶ limit)›⟩, eq.subst (eq.symm ‹is_seq_closed A›) ‹limit ∈ sequential_closure A› /-- The limit of a convergent sequence in a closed set is in that set.-/ lemma mem_of_is_closed_sequential {A : set α} (_ : is_closed A) {x : ℕ → α} (_ : ∀ n, x n ∈ A) {limit : α} (_ : x ⟶ limit) : limit ∈ A := mem_of_is_seq_closed (is_seq_closed_of_is_closed A ‹is_closed A›) ‹∀ n, x n ∈ A› ‹(x ⟶ limit)› /-- A sequential space is a space in which 'sequences are enough to probe the topology'. This can be formalised by demanding that the sequential closure and the closure coincide. The following statements show that other topological properties can be deduced from sequences in sequential spaces. -/ class sequential_space (α : Type*) [topological_space α] : Prop := (sequential_closure_eq_closure : ∀ M : set α, sequential_closure M = closure M) /-- In a sequential space, a set is closed iff it's sequentially closed. -/ lemma is_seq_closed_iff_is_closed [sequential_space α] {M : set α} : is_seq_closed M ↔ is_closed M := iff.intro (assume _, closure_eq_iff_is_closed.mp (eq.symm (calc M = sequential_closure M : by assumption ... = closure M : sequential_space.sequential_closure_eq_closure M))) (is_seq_closed_of_is_closed M) /-- In a sequential space, a point belongs to the closure of a set iff it is a limit of a sequence taking values in this set. -/ lemma mem_closure_iff_seq_limit [sequential_space α] {s : set α} {a : α} : a ∈ closure s ↔ ∃ x : ℕ → α, (∀ n : ℕ, x n ∈ s) ∧ (x ⟶ a) := by { rw ← sequential_space.sequential_closure_eq_closure, exact iff.rfl } /-- A function between topological spaces is sequentially continuous if it commutes with limit of convergent sequences. -/ def sequentially_continuous (f : α → β) : Prop := ∀ (x : ℕ → α), ∀ {limit : α}, (x ⟶ limit) → (f∘x ⟶ f limit) /- A continuous function is sequentially continuous. -/ lemma continuous.to_sequentially_continuous {f : α → β} (_ : continuous f) : sequentially_continuous f := assume x limit (_ : x ⟶ limit), have tendsto f (𝓝 limit) (𝓝 (f limit)), from continuous.tendsto ‹continuous f› limit, show (f ∘ x) ⟶ (f limit), from tendsto.comp this ‹(x ⟶ limit)› /-- In a sequential space, continuity and sequential continuity coincide. -/ lemma continuous_iff_sequentially_continuous {f : α → β} [sequential_space α] : continuous f ↔ sequentially_continuous f := iff.intro (assume _, ‹continuous f›.to_sequentially_continuous) (assume : sequentially_continuous f, show continuous f, from suffices h : ∀ {A : set β}, is_closed A → is_seq_closed (f ⁻¹' A), from continuous_iff_is_closed.mpr (assume A _, is_seq_closed_iff_is_closed.mp $ h ‹is_closed A›), assume A (_ : is_closed A), is_seq_closed_of_def $ assume (x : ℕ → α) p (_ : ∀ n, f (x n) ∈ A) (_ : x ⟶ p), have (f ∘ x) ⟶ (f p), from ‹sequentially_continuous f› x ‹(x ⟶ p)›, show f p ∈ A, from mem_of_is_closed_sequential ‹is_closed A› ‹∀ n, f (x n) ∈ A› ‹(f∘x ⟶ f p)›) end topological_space namespace topological_space namespace first_countable_topology variables [topological_space α] [first_countable_topology α] /-- Every first-countable space is sequential. -/ @[priority 100] -- see Note [lower instance priority] instance : sequential_space α := ⟨show ∀ M, sequential_closure M = closure M, from assume M, suffices closure M ⊆ sequential_closure M, from set.subset.antisymm (sequential_closure_subset_closure M) this, -- For every p ∈ closure M, we need to construct a sequence x in M that converges to p: assume (p : α) (hp : p ∈ closure M), -- Since we are in a first-countable space, the neighborhood filter around `p` has a decreasing -- basis `U` indexed by `ℕ`. let ⟨U, hU⟩ := (nhds_generated_countable p).exists_antimono_basis in -- Since `p ∈ closure M`, there is an element in each `M ∩ U i` have hp : ∀ (i : ℕ), ∃ (y : α), y ∈ M ∧ y ∈ U i, by simpa using (mem_closure_iff_nhds_basis hU.1).mp hp, begin -- The axiom of (countable) choice builds our sequence from the later fact choose u hu using hp, rw forall_and_distrib at hu, -- It clearly takes values in `M` use [u, hu.1], -- and converges to `p` because the basis is decreasing. apply hU.tendsto hu.2, end⟩ end first_countable_topology end topological_space section seq_compact open topological_space topological_space.first_countable_topology variables [topological_space α] /-- A set `s` is sequentially compact if every sequence taking values in `s` has a converging subsequence. -/ def is_seq_compact (s : set α) := ∀ ⦃u : ℕ → α⦄, (∀ n, u n ∈ s) → ∃ (x ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) /-- A space `α` is sequentially compact if every sequence in `α` has a converging subsequence. -/ class seq_compact_space (α : Type*) [topological_space α] : Prop := (seq_compact_univ : is_seq_compact (univ : set α)) lemma is_seq_compact.subseq_of_frequently_in {s : set α} (hs : is_seq_compact s) {u : ℕ → α} (hu : ∃ᶠ n in at_top, u n ∈ s) : ∃ (x ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) := let ⟨ψ, hψ, huψ⟩ := extraction_of_frequently_at_top hu, ⟨x, x_in, φ, hφ, h⟩ := hs huψ in ⟨x, x_in, ψ ∘ φ, hψ.comp hφ, h⟩ lemma seq_compact_space.tendsto_subseq [seq_compact_space α] (u : ℕ → α) : ∃ x (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) := let ⟨x, _, φ, mono, h⟩ := seq_compact_space.seq_compact_univ (by simp : ∀ n, u n ∈ univ) in ⟨x, φ, mono, h⟩ section first_countable_topology variables [first_countable_topology α] open topological_space.first_countable_topology lemma is_compact.is_seq_compact {s : set α} (hs : is_compact s) : is_seq_compact s := λ u u_in, let ⟨x, x_in, hx⟩ := @hs (map u at_top) _ (le_principal_iff.mpr (univ_mem_sets' u_in : _)) in ⟨x, x_in, tendsto_subseq hx⟩ lemma is_compact.tendsto_subseq' {s : set α} {u : ℕ → α} (hs : is_compact s) (hu : ∃ᶠ n in at_top, u n ∈ s) : ∃ (x ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) := hs.is_seq_compact.subseq_of_frequently_in hu lemma is_compact.tendsto_subseq {s : set α} {u : ℕ → α} (hs : is_compact s) (hu : ∀ n, u n ∈ s) : ∃ (x ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) := hs.is_seq_compact hu @[priority 100] -- see Note [lower instance priority] instance first_countable_topology.seq_compact_of_compact [compact_space α] : seq_compact_space α := ⟨compact_univ.is_seq_compact⟩ lemma compact_space.tendsto_subseq [compact_space α] (u : ℕ → α) : ∃ x (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) := seq_compact_space.tendsto_subseq u end first_countable_topology end seq_compact section uniform_space_seq_compact open_locale uniformity open uniform_space prod variables [uniform_space β] {s : set β} lemma lebesgue_number_lemma_seq {ι : Type*} {c : ι → set β} (hs : is_seq_compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) (hU : is_countably_generated (𝓤 β)) : ∃ V ∈ 𝓤 β, symmetric_rel V ∧ ∀ x ∈ s, ∃ i, ball x V ⊆ c i := begin classical, obtain ⟨V, hV, Vsymm⟩ : ∃ V : ℕ → set (β × β), (𝓤 β).has_antimono_basis (λ _, true) V ∧ ∀ n, swap ⁻¹' V n = V n, from uniform_space.has_seq_basis hU, clear hU, suffices : ∃ n, ∀ x ∈ s, ∃ i, ball x (V n) ⊆ c i, { cases this with n hn, exact ⟨V n, hV.to_has_basis.mem_of_mem trivial, Vsymm n, hn⟩ }, by_contradiction H, obtain ⟨x, x_in, hx⟩ : ∃ x : ℕ → β, (∀ n, x n ∈ s) ∧ ∀ n i, ¬ ball (x n) (V n) ⊆ c i, { push_neg at H, choose x hx using H, exact ⟨x, forall_and_distrib.mp hx⟩ }, clear H, obtain ⟨x₀, x₀_in, φ, φ_mono, hlim⟩ : ∃ (x₀ ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ (x ∘ φ ⟶ x₀), from hs x_in, clear hs, obtain ⟨i₀, x₀_in⟩ : ∃ i₀, x₀ ∈ c i₀, { rcases hc₂ x₀_in with ⟨_, ⟨i₀, rfl⟩, x₀_in_c⟩, exact ⟨i₀, x₀_in_c⟩ }, clear hc₂, obtain ⟨n₀, hn₀⟩ : ∃ n₀, ball x₀ (V n₀) ⊆ c i₀, { rcases (nhds_basis_uniformity hV.to_has_basis).mem_iff.mp (is_open_iff_mem_nhds.mp (hc₁ i₀) _ x₀_in) with ⟨n₀, _, h⟩, use n₀, rwa ← ball_eq_of_symmetry (Vsymm n₀) at h }, clear hc₁, obtain ⟨W, W_in, hWW⟩ : ∃ W ∈ 𝓤 β, W ○ W ⊆ V n₀, from comp_mem_uniformity_sets (hV.to_has_basis.mem_of_mem trivial), obtain ⟨N, x_φ_N_in, hVNW⟩ : ∃ N, x (φ N) ∈ ball x₀ W ∧ V (φ N) ⊆ W, { obtain ⟨N₁, h₁⟩ : ∃ N₁, ∀ n ≥ N₁, x (φ n) ∈ ball x₀ W, from tendsto_at_top'.mp hlim _ (mem_nhds_left x₀ W_in), obtain ⟨N₂, h₂⟩ : ∃ N₂, V (φ N₂) ⊆ W, { rcases hV.to_has_basis.mem_iff.mp W_in with ⟨N, _, hN⟩, use N, exact subset.trans (hV.decreasing trivial trivial $ φ_mono.id_le _) hN }, have : φ N₂ ≤ φ (max N₁ N₂), from φ_mono.le_iff_le.mpr (le_max_right _ _), exact ⟨max N₁ N₂, h₁ _ (le_max_left _ _), subset.trans (hV.decreasing trivial trivial this) h₂⟩ }, suffices : ball (x (φ N)) (V (φ N)) ⊆ c i₀, from hx (φ N) i₀ this, calc ball (x $ φ N) (V $ φ N) ⊆ ball (x $ φ N) W : preimage_mono hVNW ... ⊆ ball x₀ (V n₀) : ball_subset_of_comp_subset x_φ_N_in hWW ... ⊆ c i₀ : hn₀, end lemma is_seq_compact.totally_bounded (h : is_seq_compact s) : totally_bounded s := begin classical, apply totally_bounded_of_forall_symm, unfold is_seq_compact at h, contrapose! h, rcases h with ⟨V, V_in, V_symm, h⟩, simp_rw [not_subset] at h, have : ∀ (t : set β), finite t → ∃ a, a ∈ s ∧ a ∉ ⋃ y ∈ t, ball y V, { intros t ht, obtain ⟨a, a_in, H⟩ : ∃ a ∈ s, ∀ (x : β), x ∈ t → (x, a) ∉ V, by simpa [ht] using h t, use [a, a_in], intro H', obtain ⟨x, x_in, hx⟩ := mem_bUnion_iff.mp H', exact H x x_in hx }, cases seq_of_forall_finite_exists this with u hu, clear h this, simp [forall_and_distrib] at hu, cases hu with u_in hu, use [u, u_in], clear u_in, intros x x_in φ, intros hφ huφ, obtain ⟨N, hN⟩ : ∃ N, ∀ p q, p ≥ N → q ≥ N → (u (φ p), u (φ q)) ∈ V, from huφ.cauchy_seq.mem_entourage V_in, specialize hN N (N+1) (le_refl N) (nat.le_succ N), specialize hu (φ $ N+1) (φ N) (hφ $ lt_add_one N), exact hu hN, end protected lemma is_seq_compact.is_compact (h : is_countably_generated $ 𝓤 β) (hs : is_seq_compact s) : is_compact s := begin classical, rw compact_iff_finite_subcover, intros ι U Uop s_sub, rcases lebesgue_number_lemma_seq hs Uop s_sub h with ⟨V, V_in, Vsymm, H⟩, rcases totally_bounded_iff_subset.mp hs.totally_bounded V V_in with ⟨t,t_sub, tfin, ht⟩, have : ∀ x : t, ∃ (i : ι), ball x.val V ⊆ U i, { rintros ⟨x, x_in⟩, exact H x (t_sub x_in) }, choose i hi using this, haveI : fintype t := tfin.fintype, use finset.image i finset.univ, transitivity ⋃ y ∈ t, ball y V, { intros x x_in, specialize ht x_in, rw mem_bUnion_iff at *, simp_rw ball_eq_of_symmetry Vsymm, exact ht }, { apply bUnion_subset_bUnion, intros x x_in, exact ⟨i ⟨x, x_in⟩, finset.mem_image_of_mem _ (finset.mem_univ _), hi ⟨x, x_in⟩⟩ }, end protected lemma uniform_space.compact_iff_seq_compact (h : is_countably_generated $ 𝓤 β) : is_compact s ↔ is_seq_compact s := begin haveI := uniform_space.first_countable_topology h, exact ⟨λ H, H.is_seq_compact, λ H, H.is_compact h⟩ end lemma uniform_space.compact_space_iff_seq_compact_space (H : is_countably_generated $ 𝓤 β) : compact_space β ↔ seq_compact_space β := have key : is_compact univ ↔ is_seq_compact univ := uniform_space.compact_iff_seq_compact H, ⟨λ ⟨h⟩, ⟨key.mp h⟩, λ ⟨h⟩, ⟨key.mpr h⟩⟩ end uniform_space_seq_compact section metric_seq_compact variables [metric_space β] {s : set β} open metric /-- A version of Bolzano-Weistrass: in a metric space, is_compact s ↔ is_seq_compact s -/ lemma metric.compact_iff_seq_compact : is_compact s ↔ is_seq_compact s := uniform_space.compact_iff_seq_compact emetric.uniformity_has_countable_basis /-- A version of Bolzano-Weistrass: in a proper metric space (eg. $ℝ^n$), every bounded sequence has a converging subsequence. This version assumes only that the sequence is frequently in some bounded set. -/ lemma tendsto_subseq_of_frequently_bounded [proper_space β] (hs : bounded s) {u : ℕ → β} (hu : ∃ᶠ n in at_top, u n ∈ s) : ∃ b ∈ closure s, ∃ φ : ℕ → ℕ, strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 b) := begin have hcs : is_compact (closure s) := compact_iff_closed_bounded.mpr ⟨is_closed_closure, bounded_closure_of_bounded hs⟩, replace hcs : is_seq_compact (closure s), by rwa metric.compact_iff_seq_compact at hcs, have hu' : ∃ᶠ n in at_top, u n ∈ closure s, { apply frequently.mono hu, intro n, apply subset_closure }, exact hcs.subseq_of_frequently_in hu', end /-- A version of Bolzano-Weistrass: in a proper metric space (eg. $ℝ^n$), every bounded sequence has a converging subsequence. -/ lemma tendsto_subseq_of_bounded [proper_space β] (hs : bounded s) {u : ℕ → β} (hu : ∀ n, u n ∈ s) : ∃ b ∈ closure s, ∃ φ : ℕ → ℕ, strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 b) := tendsto_subseq_of_frequently_bounded hs $ frequently_of_forall hu lemma metric.compact_space_iff_seq_compact_space : compact_space β ↔ seq_compact_space β := uniform_space.compact_space_iff_seq_compact_space emetric.uniformity_has_countable_basis lemma seq_compact.lebesgue_number_lemma_of_metric {ι : Type*} {c : ι → set β} (hs : is_seq_compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ δ > 0, ∀ x ∈ s, ∃ i, ball x δ ⊆ c i := begin rcases lebesgue_number_lemma_seq hs hc₁ hc₂ emetric.uniformity_has_countable_basis with ⟨V, V_in, _, hV⟩, rcases uniformity_basis_dist.mem_iff.mp V_in with ⟨δ, δ_pos, h⟩, use [δ, δ_pos], intros x x_in, rcases hV x x_in with ⟨i, hi⟩, use i, have := ball_mono h x, rw ball_eq_ball' at this, exact subset.trans this hi, end end metric_seq_compact
59c46cc237070f347e2df177bcfa589d095e50ba
c777c32c8e484e195053731103c5e52af26a25d1
/src/algebra/continued_fractions/computation/approximations.lean
19ca7909b95c21fc3d281a2761578f27167c3cd5
[ "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
28,876
lean
/- Copyright (c) 2020 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import algebra.continued_fractions.computation.correctness_terminating import data.nat.fib import tactic.solve_by_elim /-! # Approximations for Continued Fraction Computations (`generalized_continued_fraction.of`) ## Summary This file contains useful approximations for the values involved in the continued fractions computation `generalized_continued_fraction.of`. In particular, we derive the so-called *determinant formula* for `generalized_continued_fraction.of`: `Aₙ * Bₙ₊₁ - Bₙ * Aₙ₊₁ = (-1)^(n + 1)`. Moreover, we derive some upper bounds for the error term when computing a continued fraction up a given position, i.e. bounds for the term `|v - (generalized_continued_fraction.of v).convergents n|`. The derived bounds will show us that the error term indeed gets smaller. As a corollary, we will be able to show that `(generalized_continued_fraction.of v).convergents` converges to `v` in `algebra.continued_fractions.computation.approximation_corollaries`. ## Main Theorems - `generalized_continued_fraction.of_part_num_eq_one`: shows that all partial numerators `aᵢ` are equal to one. - `generalized_continued_fraction.exists_int_eq_of_part_denom`: shows that all partial denominators `bᵢ` correspond to an integer. - `generalized_continued_fraction.one_le_of_nth_part_denom`: shows that `1 ≤ bᵢ`. - `generalized_continued_fraction.succ_nth_fib_le_of_nth_denom`: shows that the `n`th denominator `Bₙ` is greater than or equal to the `n + 1`th fibonacci number `nat.fib (n + 1)`. - `generalized_continued_fraction.le_of_succ_nth_denom`: shows that `bₙ * Bₙ ≤ Bₙ₊₁`, where `bₙ` is the `n`th partial denominator of the continued fraction. - `generalized_continued_fraction.abs_sub_convergents_le`: shows that `|v - Aₙ / Bₙ| ≤ 1 / (Bₙ * Bₙ₊₁)`, where `Aₙ` is the nth partial numerator. ## References - [*Hardy, GH and Wright, EM and Heath-Brown, Roger and Silverman, Joseph*][hardy2008introduction] - https://en.wikipedia.org/wiki/Generalized_continued_fraction#The_determinant_formula -/ namespace generalized_continued_fraction open generalized_continued_fraction (of) int variables {K : Type*} {v : K} {n : ℕ} [linear_ordered_field K] [floor_ring K] namespace int_fract_pair /-! We begin with some lemmas about the stream of `int_fract_pair`s, which presumably are not of great interest for the end user. -/ /-- Shows that the fractional parts of the stream are in `[0,1)`. -/ lemma nth_stream_fr_nonneg_lt_one {ifp_n : int_fract_pair K} (nth_stream_eq : int_fract_pair.stream v n = some ifp_n) : 0 ≤ ifp_n.fr ∧ ifp_n.fr < 1 := begin cases n, case nat.zero { have : int_fract_pair.of v = ifp_n, by injection nth_stream_eq, rw [←this, int_fract_pair.of], exact ⟨fract_nonneg _, fract_lt_one _⟩ }, case nat.succ { rcases (succ_nth_stream_eq_some_iff.elim_left nth_stream_eq) with ⟨_, _, _, ifp_of_eq_ifp_n⟩, rw [←ifp_of_eq_ifp_n, int_fract_pair.of], exact ⟨fract_nonneg _, fract_lt_one _⟩ } end /-- Shows that the fractional parts of the stream are nonnegative. -/ lemma nth_stream_fr_nonneg {ifp_n : int_fract_pair K} (nth_stream_eq : int_fract_pair.stream v n = some ifp_n) : 0 ≤ ifp_n.fr := (nth_stream_fr_nonneg_lt_one nth_stream_eq).left /-- Shows that the fractional parts of the stream are smaller than one. -/ lemma nth_stream_fr_lt_one {ifp_n : int_fract_pair K} (nth_stream_eq : int_fract_pair.stream v n = some ifp_n) : ifp_n.fr < 1 := (nth_stream_fr_nonneg_lt_one nth_stream_eq).right /-- Shows that the integer parts of the stream are at least one. -/ lemma one_le_succ_nth_stream_b {ifp_succ_n : int_fract_pair K} (succ_nth_stream_eq : int_fract_pair.stream v (n + 1) = some ifp_succ_n) : 1 ≤ ifp_succ_n.b := begin obtain ⟨ifp_n, nth_stream_eq, stream_nth_fr_ne_zero, ⟨-⟩⟩ : ∃ ifp_n, int_fract_pair.stream v n = some ifp_n ∧ ifp_n.fr ≠ 0 ∧ int_fract_pair.of ifp_n.fr⁻¹ = ifp_succ_n, from succ_nth_stream_eq_some_iff.elim_left succ_nth_stream_eq, suffices : 1 ≤ ifp_n.fr⁻¹, { rw_mod_cast [le_floor], assumption }, suffices : ifp_n.fr ≤ 1, { have h : 0 < ifp_n.fr, from lt_of_le_of_ne (nth_stream_fr_nonneg nth_stream_eq) stream_nth_fr_ne_zero.symm, apply one_le_inv h this }, simp only [le_of_lt (nth_stream_fr_lt_one nth_stream_eq)] end /-- Shows that the `n + 1`th integer part `bₙ₊₁` of the stream is smaller or equal than the inverse of the `n`th fractional part `frₙ` of the stream. This result is straight-forward as `bₙ₊₁` is defined as the floor of `1 / frₙ` -/ lemma succ_nth_stream_b_le_nth_stream_fr_inv {ifp_n ifp_succ_n : int_fract_pair K} (nth_stream_eq : int_fract_pair.stream v n = some ifp_n) (succ_nth_stream_eq : int_fract_pair.stream v (n + 1) = some ifp_succ_n) : (ifp_succ_n.b : K) ≤ ifp_n.fr⁻¹ := begin suffices : (⌊ifp_n.fr⁻¹⌋ : K) ≤ ifp_n.fr⁻¹, { cases ifp_n with _ ifp_n_fr, have : ifp_n_fr ≠ 0, { intro h, simpa [h, int_fract_pair.stream, nth_stream_eq] using succ_nth_stream_eq }, have : int_fract_pair.of ifp_n_fr⁻¹ = ifp_succ_n, { simpa [this, int_fract_pair.stream, nth_stream_eq, option.coe_def] using succ_nth_stream_eq }, rwa ←this }, exact (floor_le ifp_n.fr⁻¹) end end int_fract_pair /-! Next we translate above results about the stream of `int_fract_pair`s to the computed continued fraction `generalized_continued_fraction.of`. -/ /-- Shows that the integer parts of the continued fraction are at least one. -/ lemma of_one_le_nth_part_denom {b : K} (nth_part_denom_eq : (of v).partial_denominators.nth n = some b) : 1 ≤ b := begin obtain ⟨gp_n, nth_s_eq, ⟨-⟩⟩ : ∃ gp_n, (of v).s.nth n = some gp_n ∧ gp_n.b = b, from exists_s_b_of_part_denom nth_part_denom_eq, obtain ⟨ifp_n, succ_nth_stream_eq, ifp_n_b_eq_gp_n_b⟩ : ∃ ifp, int_fract_pair.stream v (n + 1) = some ifp ∧ (ifp.b : K) = gp_n.b, from int_fract_pair.exists_succ_nth_stream_of_gcf_of_nth_eq_some nth_s_eq, rw [←ifp_n_b_eq_gp_n_b], exact_mod_cast (int_fract_pair.one_le_succ_nth_stream_b succ_nth_stream_eq) end /-- Shows that the partial numerators `aᵢ` of the continued fraction are equal to one and the partial denominators `bᵢ` correspond to integers. -/ lemma of_part_num_eq_one_and_exists_int_part_denom_eq {gp : generalized_continued_fraction.pair K} (nth_s_eq : (of v).s.nth n = some gp) : gp.a = 1 ∧ ∃ (z : ℤ), gp.b = (z : K) := begin obtain ⟨ifp, stream_succ_nth_eq, -⟩ : ∃ ifp, int_fract_pair.stream v (n + 1) = some ifp ∧ _, from int_fract_pair.exists_succ_nth_stream_of_gcf_of_nth_eq_some nth_s_eq, have : gp = ⟨1, ifp.b⟩, by { have : (of v).s.nth n = some ⟨1, ifp.b⟩, from nth_of_eq_some_of_succ_nth_int_fract_pair_stream stream_succ_nth_eq, have : some gp = some ⟨1, ifp.b⟩, by rwa nth_s_eq at this, injection this }, simp [this], end /-- Shows that the partial numerators `aᵢ` are equal to one. -/ lemma of_part_num_eq_one {a : K} (nth_part_num_eq : (of v).partial_numerators.nth n = some a) : a = 1 := begin obtain ⟨gp, nth_s_eq, gp_a_eq_a_n⟩ : ∃ gp, (of v).s.nth n = some gp ∧ gp.a = a, from exists_s_a_of_part_num nth_part_num_eq, have : gp.a = 1, from (of_part_num_eq_one_and_exists_int_part_denom_eq nth_s_eq).left, rwa gp_a_eq_a_n at this end /-- Shows that the partial denominators `bᵢ` correspond to an integer. -/ lemma exists_int_eq_of_part_denom {b : K} (nth_part_denom_eq : (of v).partial_denominators.nth n = some b) : ∃ (z : ℤ), b = (z : K) := begin obtain ⟨gp, nth_s_eq, gp_b_eq_b_n⟩ : ∃ gp, (of v).s.nth n = some gp ∧ gp.b = b, from exists_s_b_of_part_denom nth_part_denom_eq, have : ∃ (z : ℤ), gp.b = (z : K), from (of_part_num_eq_one_and_exists_int_part_denom_eq nth_s_eq).right, rwa gp_b_eq_b_n at this end /-! One of our next goals is to show that `bₙ * Bₙ ≤ Bₙ₊₁`. For this, we first show that the partial denominators `Bₙ` are bounded from below by the fibonacci sequence `nat.fib`. This then implies that `0 ≤ Bₙ` and hence `Bₙ₊₂ = bₙ₊₁ * Bₙ₊₁ + Bₙ ≥ bₙ₊₁ * Bₙ₊₁ + 0 = bₙ₊₁ * Bₙ₊₁`. -/ -- open `nat` as we will make use of fibonacci numbers. open nat lemma fib_le_of_continuants_aux_b : (n ≤ 1 ∨ ¬(of v).terminated_at (n - 2)) → (fib n : K) ≤ ((of v).continuants_aux n).b := nat.strong_induction_on n begin clear n, assume n IH hyp, rcases n with _|_|n, { simp [fib_add_two, continuants_aux] }, -- case n = 0 { simp [fib_add_two, continuants_aux] }, -- case n = 1 { let g := of v, -- case 2 ≤ n have : ¬(n + 2 ≤ 1), by linarith, have not_terminated_at_n : ¬g.terminated_at n, from or.resolve_left hyp this, obtain ⟨gp, s_ppred_nth_eq⟩ : ∃ gp, g.s.nth n = some gp, from option.ne_none_iff_exists'.mp not_terminated_at_n, set pconts := g.continuants_aux (n + 1) with pconts_eq, set ppconts := g.continuants_aux n with ppconts_eq, -- use the recurrence of continuants_aux suffices : (fib n : K) + fib (n + 1) ≤ gp.a * ppconts.b + gp.b * pconts.b, by simpa [fib_add_two, add_comm, (continuants_aux_recurrence s_ppred_nth_eq ppconts_eq pconts_eq)], -- make use of the fact that gp.a = 1 suffices : (fib n : K) + fib (n + 1) ≤ ppconts.b + gp.b * pconts.b, by simpa [(of_part_num_eq_one $ part_num_eq_s_a s_ppred_nth_eq)], have not_terminated_at_pred_n : ¬g.terminated_at (n - 1), from mt (terminated_stable $ nat.sub_le n 1) not_terminated_at_n, have not_terminated_at_ppred_n : ¬terminated_at g (n - 2), from mt (terminated_stable (n - 1).pred_le) not_terminated_at_pred_n, -- use the IH to get the inequalities for `pconts` and `ppconts` have : (fib (n + 1) : K) ≤ pconts.b, from IH _ (nat.lt.base $ n + 1) (or.inr not_terminated_at_pred_n), have ppred_nth_fib_le_ppconts_B : (fib n : K) ≤ ppconts.b, from IH n (lt_trans (nat.lt.base n) $ nat.lt.base $ n + 1) (or.inr not_terminated_at_ppred_n), suffices : (fib (n + 1) : K) ≤ gp.b * pconts.b, solve_by_elim [add_le_add ppred_nth_fib_le_ppconts_B], -- finally use the fact that 1 ≤ gp.b to solve the goal suffices : 1 * (fib (n + 1) : K) ≤ gp.b * pconts.b, by rwa [one_mul] at this, have one_le_gp_b : (1 : K) ≤ gp.b, from of_one_le_nth_part_denom (part_denom_eq_s_b s_ppred_nth_eq), have : (0 : K) ≤ fib (n + 1), by exact_mod_cast (fib (n + 1)).zero_le, have : (0 : K) ≤ gp.b, from le_trans zero_le_one one_le_gp_b, mono } end /-- Shows that the `n`th denominator is greater than or equal to the `n + 1`th fibonacci number, that is `nat.fib (n + 1) ≤ Bₙ`. -/ lemma succ_nth_fib_le_of_nth_denom (hyp: n = 0 ∨ ¬(of v).terminated_at (n - 1)) : (fib (n + 1) : K) ≤ (of v).denominators n := begin rw [denom_eq_conts_b, nth_cont_eq_succ_nth_cont_aux], have : (n + 1) ≤ 1 ∨ ¬(of v).terminated_at (n - 1), by { cases n, case nat.zero : { exact (or.inl $ le_refl 1) }, case nat.succ : { exact or.inr (or.resolve_left hyp n.succ_ne_zero) } }, exact (fib_le_of_continuants_aux_b this) end /-! As a simple consequence, we can now derive that all denominators are nonnegative. -/ lemma zero_le_of_continuants_aux_b : 0 ≤ ((of v).continuants_aux n).b := begin let g := of v, induction n with n IH, case nat.zero: { refl }, case nat.succ: { cases (decidable.em $ g.terminated_at (n - 1)) with terminated not_terminated, { cases n, -- terminating case { simp [zero_le_one] }, { have : g.continuants_aux (n + 2) = g.continuants_aux (n + 1), from continuants_aux_stable_step_of_terminated terminated, simp only [this, IH] } }, { calc -- non-terminating case (0 : K) ≤ fib (n + 1) : by exact_mod_cast (n + 1).fib.zero_le ... ≤ ((of v).continuants_aux (n + 1)).b : fib_le_of_continuants_aux_b (or.inr not_terminated) } } end /-- Shows that all denominators are nonnegative. -/ lemma zero_le_of_denom : 0 ≤ (of v).denominators n := by { rw [denom_eq_conts_b, nth_cont_eq_succ_nth_cont_aux], exact zero_le_of_continuants_aux_b } lemma le_of_succ_succ_nth_continuants_aux_b {b : K} (nth_part_denom_eq : (of v).partial_denominators.nth n = some b) : b * ((of v).continuants_aux $ n + 1).b ≤ ((of v).continuants_aux $ n + 2).b := begin obtain ⟨gp_n, nth_s_eq, rfl⟩ : ∃ gp_n, (of v).s.nth n = some gp_n ∧ gp_n.b = b, from exists_s_b_of_part_denom nth_part_denom_eq, simp [of_part_num_eq_one (part_num_eq_s_a nth_s_eq), zero_le_of_continuants_aux_b, generalized_continued_fraction.continuants_aux_recurrence nth_s_eq rfl rfl] end /-- Shows that `bₙ * Bₙ ≤ Bₙ₊₁`, where `bₙ` is the `n`th partial denominator and `Bₙ₊₁` and `Bₙ` are the `n + 1`th and `n`th denominator of the continued fraction. -/ theorem le_of_succ_nth_denom {b : K} (nth_part_denom_eq : (of v).partial_denominators.nth n = some b) : b * (of v).denominators n ≤ (of v).denominators (n + 1) := begin rw [denom_eq_conts_b, nth_cont_eq_succ_nth_cont_aux], exact (le_of_succ_succ_nth_continuants_aux_b nth_part_denom_eq) end /-- Shows that the sequence of denominators is monotone, that is `Bₙ ≤ Bₙ₊₁`. -/ theorem of_denom_mono : (of v).denominators n ≤ (of v).denominators (n + 1) := begin let g := of v, cases (decidable.em $ g.partial_denominators.terminated_at n) with terminated not_terminated, { have : g.partial_denominators.nth n = none, by rwa stream.seq.terminated_at at terminated, have : g.terminated_at n, from terminated_at_iff_part_denom_none.elim_right (by rwa stream.seq.terminated_at at terminated), have : g.denominators (n + 1) = g.denominators n, from denominators_stable_of_terminated n.le_succ this, rw this }, { obtain ⟨b, nth_part_denom_eq⟩ : ∃ b, g.partial_denominators.nth n = some b, from option.ne_none_iff_exists'.mp not_terminated, have : 1 ≤ b, from of_one_le_nth_part_denom nth_part_denom_eq, calc g.denominators n ≤ b * g.denominators n : by simpa using (mul_le_mul_of_nonneg_right this zero_le_of_denom) ... ≤ g.denominators (n + 1) : le_of_succ_nth_denom nth_part_denom_eq } end section determinant /-! ### Determinant Formula Next we prove the so-called *determinant formula* for `generalized_continued_fraction.of`: `Aₙ * Bₙ₊₁ - Bₙ * Aₙ₊₁ = (-1)^(n + 1)`. -/ lemma determinant_aux (hyp: n = 0 ∨ ¬(of v).terminated_at (n - 1)) : ((of v).continuants_aux n).a * ((of v).continuants_aux (n + 1)).b - ((of v).continuants_aux n).b * ((of v).continuants_aux (n + 1)).a = (-1)^n := begin induction n with n IH, case nat.zero { simp [continuants_aux] }, case nat.succ { -- set up some shorthand notation let g := of v, let conts := continuants_aux g (n + 2), set pred_conts := continuants_aux g (n + 1) with pred_conts_eq, set ppred_conts := continuants_aux g n with ppred_conts_eq, let pA := pred_conts.a, let pB := pred_conts.b, let ppA := ppred_conts.a, let ppB := ppred_conts.b, -- let's change the goal to something more readable change pA * conts.b - pB * conts.a = (-1)^(n + 1), have not_terminated_at_n : ¬terminated_at g n, from or.resolve_left hyp n.succ_ne_zero, obtain ⟨gp, s_nth_eq⟩ : ∃ gp, g.s.nth n = some gp, from option.ne_none_iff_exists'.elim_left not_terminated_at_n, -- unfold the recurrence relation for `conts` once and simplify to derive the following suffices : pA * (ppB + gp.b * pB) - pB * (ppA + gp.b * pA) = (-1)^(n + 1), by { simp only [conts, (continuants_aux_recurrence s_nth_eq ppred_conts_eq pred_conts_eq)], have gp_a_eq_one : gp.a = 1, from of_part_num_eq_one (part_num_eq_s_a s_nth_eq), rw [gp_a_eq_one, this.symm], ring }, suffices : pA * ppB - pB * ppA = (-1)^(n + 1), calc pA * (ppB + gp.b * pB) - pB * (ppA + gp.b * pA) = pA * ppB + pA * gp.b * pB - pB * ppA - pB * gp.b * pA : by ring ... = pA * ppB - pB * ppA : by ring ... = (-1)^(n + 1) : by assumption, suffices : ppA * pB - ppB * pA = (-1)^n, by { have pow_succ_n : (-1 : K)^(n + 1) = (-1) * (-1)^n, from pow_succ (-1) n, rw [pow_succ_n, ←this], ring }, exact (IH $ or.inr $ mt (terminated_stable $ n.sub_le 1) not_terminated_at_n) } end /-- The determinant formula `Aₙ * Bₙ₊₁ - Bₙ * Aₙ₊₁ = (-1)^(n + 1)` -/ lemma determinant (not_terminated_at_n : ¬(of v).terminated_at n) : (of v).numerators n * (of v).denominators (n + 1) - (of v).denominators n * (of v).numerators (n + 1) = (-1)^(n + 1) := (determinant_aux $ or.inr $ not_terminated_at_n) end determinant section error_term /-! ### Approximation of Error Term Next we derive some approximations for the error term when computing a continued fraction up a given position, i.e. bounds for the term `|v - (generalized_continued_fraction.of v).convergents n|`. -/ /-- This lemma follows from the finite correctness proof, the determinant equality, and by simplifying the difference. -/ lemma sub_convergents_eq {ifp : int_fract_pair K} (stream_nth_eq : int_fract_pair.stream v n = some ifp) : let g := of v in let B := (g.continuants_aux (n + 1)).b in let pB := (g.continuants_aux n).b in v - g.convergents n = if ifp.fr = 0 then 0 else (-1)^n / (B * (ifp.fr⁻¹ * B + pB)) := begin -- set up some shorthand notation let g := of v, let conts := g.continuants_aux (n + 1), let pred_conts := g.continuants_aux n, have g_finite_correctness : v = generalized_continued_fraction.comp_exact_value pred_conts conts ifp.fr, from comp_exact_value_correctness_of_stream_eq_some stream_nth_eq, cases decidable.em (ifp.fr = 0) with ifp_fr_eq_zero ifp_fr_ne_zero, { suffices : v - g.convergents n = 0, by simpa [ifp_fr_eq_zero], replace g_finite_correctness : v = g.convergents n, by simpa [generalized_continued_fraction.comp_exact_value, ifp_fr_eq_zero] using g_finite_correctness, exact (sub_eq_zero.elim_right g_finite_correctness) }, { -- more shorthand notation let A := conts.a, let B := conts.b, let pA := pred_conts.a, let pB := pred_conts.b, -- first, let's simplify the goal as `ifp.fr ≠ 0` suffices : v - A / B = (-1)^n / (B * (ifp.fr⁻¹ * B + pB)), by simpa [ifp_fr_ne_zero], -- now we can unfold `g.comp_exact_value` to derive the following equality for `v` replace g_finite_correctness : v = (pA + ifp.fr⁻¹ * A) / (pB + ifp.fr⁻¹ * B), by simpa [generalized_continued_fraction.comp_exact_value, ifp_fr_ne_zero, next_continuants, next_numerator, next_denominator, add_comm] using g_finite_correctness, -- let's rewrite this equality for `v` in our goal suffices : (pA + ifp.fr⁻¹ * A) / (pB + ifp.fr⁻¹ * B) - A / B = (-1)^n / (B * (ifp.fr⁻¹ * B + pB)), by rwa g_finite_correctness, -- To continue, we need use the determinant equality. So let's derive the needed hypothesis. have n_eq_zero_or_not_terminated_at_pred_n : n = 0 ∨ ¬g.terminated_at (n - 1), by { cases n with n', { simp }, { have : int_fract_pair.stream v (n' + 1) ≠ none, by simp [stream_nth_eq], have : ¬g.terminated_at n', from (not_iff_not_of_iff of_terminated_at_n_iff_succ_nth_int_fract_pair_stream_eq_none) .elim_right this, exact (or.inr this) } }, have determinant_eq : pA * B - pB * A = (-1)^n, from determinant_aux n_eq_zero_or_not_terminated_at_pred_n, -- now all we got to do is to rewrite this equality in our goal and re-arrange terms; -- however, for this, we first have to derive quite a few tedious inequalities. have pB_ineq : (fib n : K) ≤ pB, by { have : n ≤ 1 ∨ ¬g.terminated_at (n - 2), by { cases n_eq_zero_or_not_terminated_at_pred_n with n_eq_zero not_terminated_at_pred_n, { simp [n_eq_zero] }, { exact (or.inr $ mt (terminated_stable (n - 1).pred_le) not_terminated_at_pred_n) } }, exact (fib_le_of_continuants_aux_b this) }, have B_ineq : (fib (n + 1) : K) ≤ B, by { have : n + 1 ≤ 1 ∨ ¬g.terminated_at (n + 1 - 2), by { cases n_eq_zero_or_not_terminated_at_pred_n with n_eq_zero not_terminated_at_pred_n, { simp [n_eq_zero, le_refl] }, { exact (or.inr not_terminated_at_pred_n) } }, exact (fib_le_of_continuants_aux_b this) }, have zero_lt_B : 0 < B, { have : 1 ≤ B, from le_trans (by exact_mod_cast fib_pos (lt_of_le_of_ne n.succ.zero_le n.succ_ne_zero.symm)) B_ineq, exact (lt_of_lt_of_le zero_lt_one this) }, have zero_ne_B : 0 ≠ B, from ne_of_lt zero_lt_B, have : 0 ≠ pB + ifp.fr⁻¹ * B, by { have : (0 : K) ≤ fib n, by exact_mod_cast (fib n).zero_le, -- 0 ≤ fib n ≤ pB have zero_le_pB : 0 ≤ pB, from le_trans this pB_ineq, have : 0 < ifp.fr⁻¹, by { suffices : 0 < ifp.fr, by rwa inv_pos, have : 0 ≤ ifp.fr, from int_fract_pair.nth_stream_fr_nonneg stream_nth_eq, change ifp.fr ≠ 0 at ifp_fr_ne_zero, exact lt_of_le_of_ne this ifp_fr_ne_zero.symm }, have : 0 < ifp.fr⁻¹ * B, from mul_pos this zero_lt_B, have : 0 < pB + ifp.fr⁻¹ * B, from add_pos_of_nonneg_of_pos zero_le_pB this, exact (ne_of_lt this) }, -- finally, let's do the rewriting calc (pA + ifp.fr⁻¹ * A) / (pB + ifp.fr⁻¹ * B) - A / B = ((pA + ifp.fr⁻¹ * A) * B - (pB + ifp.fr⁻¹ * B) * A) / ((pB + ifp.fr⁻¹ * B) * B) : by rw (div_sub_div _ _ this.symm zero_ne_B.symm) ... = (pA * B + ifp.fr⁻¹ * A * B - (pB * A + ifp.fr⁻¹ * B * A)) / _ : by repeat { rw [add_mul] } ... = (pA * B - pB * A) / ((pB + ifp.fr⁻¹ * B) * B) : by ring ... = (-1)^n / ((pB + ifp.fr⁻¹ * B) * B) : by rw determinant_eq ... = (-1)^n / (B * (ifp.fr⁻¹ * B + pB)) : by ac_refl } end /-- Shows that `|v - Aₙ / Bₙ| ≤ 1 / (Bₙ * Bₙ₊₁)` -/ theorem abs_sub_convergents_le (not_terminated_at_n : ¬(of v).terminated_at n) : |v - (of v).convergents n| ≤ 1 / (((of v).denominators n) * ((of v).denominators $ n + 1)) := begin -- shorthand notation let g := of v, let nextConts := g.continuants_aux (n + 2), set conts := continuants_aux g (n + 1) with conts_eq, set pred_conts := continuants_aux g n with pred_conts_eq, -- change the goal to something more readable change |v - convergents g n| ≤ 1 / (conts.b * nextConts.b), obtain ⟨gp, s_nth_eq⟩ : ∃ gp, g.s.nth n = some gp, from option.ne_none_iff_exists'.elim_left not_terminated_at_n, have gp_a_eq_one : gp.a = 1, from of_part_num_eq_one (part_num_eq_s_a s_nth_eq), -- unfold the recurrence relation for `nextConts.b` have nextConts_b_eq : nextConts.b = pred_conts.b + gp.b * conts.b, by simp [nextConts, (continuants_aux_recurrence s_nth_eq pred_conts_eq conts_eq), gp_a_eq_one, pred_conts_eq.symm, conts_eq.symm, add_comm], let denom := conts.b * (pred_conts.b + gp.b * conts.b), suffices : |v - g.convergents n| ≤ 1 / denom, by { rw [nextConts_b_eq], congr' 1 }, obtain ⟨ifp_succ_n, succ_nth_stream_eq, ifp_succ_n_b_eq_gp_b⟩ : ∃ ifp_succ_n, int_fract_pair.stream v (n + 1) = some ifp_succ_n ∧ (ifp_succ_n.b : K) = gp.b, from int_fract_pair.exists_succ_nth_stream_of_gcf_of_nth_eq_some s_nth_eq, obtain ⟨ifp_n, stream_nth_eq, stream_nth_fr_ne_zero, if_of_eq_ifp_succ_n⟩ : ∃ ifp_n, int_fract_pair.stream v n = some ifp_n ∧ ifp_n.fr ≠ 0 ∧ int_fract_pair.of ifp_n.fr⁻¹ = ifp_succ_n, from int_fract_pair.succ_nth_stream_eq_some_iff.elim_left succ_nth_stream_eq, let denom' := conts.b * (pred_conts.b + ifp_n.fr⁻¹ * conts.b), -- now we can use `sub_convergents_eq` to simplify our goal suffices : |(-1)^n / denom'| ≤ 1 / denom, by { have : v - g.convergents n = (-1)^n / denom', by { -- apply `sub_convergens_eq` and simplify the result have tmp, from sub_convergents_eq stream_nth_eq, delta at tmp, simp only [stream_nth_fr_ne_zero, conts_eq.symm, pred_conts_eq.symm] at tmp, rw tmp, simp only [denom'], ring_nf }, rwa this }, -- derive some tedious inequalities that we need to rewrite our goal have nextConts_b_ineq : (fib (n + 2) : K) ≤ (pred_conts.b + gp.b * conts.b), by { have : (fib (n + 2) : K) ≤ nextConts.b, from fib_le_of_continuants_aux_b (or.inr not_terminated_at_n), rwa [nextConts_b_eq] at this }, have conts_b_ineq : (fib (n + 1) : K) ≤ conts.b, by { have : ¬g.terminated_at (n - 1), from mt (terminated_stable n.pred_le) not_terminated_at_n, exact (fib_le_of_continuants_aux_b $ or.inr this) }, have zero_lt_conts_b : 0 < conts.b, by { have : (0 : K) < fib (n + 1), by exact_mod_cast (fib_pos (lt_of_le_of_ne n.succ.zero_le n.succ_ne_zero.symm)), exact (lt_of_lt_of_le this conts_b_ineq) }, -- `denom'` is positive, so we can remove `|⬝|` from our goal suffices : 1 / denom' ≤ 1 / denom, by { have : |(-1)^n / denom'| = 1 / denom', by { suffices : 1 / |denom'| = 1 / denom', by rwa [abs_div, (abs_neg_one_pow n)], have : 0 < denom', by { have : 0 ≤ pred_conts.b, by { have : (fib n : K) ≤ pred_conts.b, by { have : ¬g.terminated_at (n - 2), from mt (terminated_stable (n.sub_le 2)) not_terminated_at_n, exact (fib_le_of_continuants_aux_b $ or.inr this) }, exact le_trans (by exact_mod_cast (fib n).zero_le) this }, have : 0 < ifp_n.fr⁻¹, by { have zero_le_ifp_n_fract : 0 ≤ ifp_n.fr, from int_fract_pair.nth_stream_fr_nonneg stream_nth_eq, exact inv_pos.elim_right (lt_of_le_of_ne zero_le_ifp_n_fract stream_nth_fr_ne_zero.symm) }, any_goals { repeat { apply mul_pos <|> apply add_pos_of_nonneg_of_pos } }; assumption }, rwa (abs_of_pos this) }, rwa this }, suffices : 0 < denom ∧ denom ≤ denom', from div_le_div_of_le_left zero_le_one this.left this.right, split, { have : 0 < pred_conts.b + gp.b * conts.b, from lt_of_lt_of_le (by exact_mod_cast (fib_pos (lt_of_le_of_ne n.succ.succ.zero_le n.succ.succ_ne_zero.symm))) nextConts_b_ineq, solve_by_elim [mul_pos] }, { -- we can cancel multiplication by `conts.b` and addition with `pred_conts.b` suffices : gp.b * conts.b ≤ ifp_n.fr⁻¹ * conts.b, from ((mul_le_mul_left zero_lt_conts_b).elim_right $ (add_le_add_iff_left pred_conts.b).elim_right this), suffices : (ifp_succ_n.b : K) * conts.b ≤ ifp_n.fr⁻¹ * conts.b, by rwa [←ifp_succ_n_b_eq_gp_b], have : (ifp_succ_n.b : K) ≤ ifp_n.fr⁻¹, from int_fract_pair.succ_nth_stream_b_le_nth_stream_fr_inv stream_nth_eq succ_nth_stream_eq, have : 0 ≤ conts.b, from le_of_lt zero_lt_conts_b, mono } end /-- Shows that `|v - Aₙ / Bₙ| ≤ 1 / (bₙ * Bₙ * Bₙ)`. This bound is worse than the one shown in `gcf.abs_sub_convergents_le`, but sometimes it is easier to apply and sufficient for one's use case. -/ lemma abs_sub_convergents_le' {b : K} (nth_part_denom_eq : (of v).partial_denominators.nth n = some b) : |v - (of v).convergents n| ≤ 1 / (b * ((of v).denominators n) * ((of v).denominators n)) := begin have not_terminated_at_n : ¬(of v).terminated_at n, by simp [terminated_at_iff_part_denom_none, nth_part_denom_eq], refine (abs_sub_convergents_le not_terminated_at_n).trans _, -- One can show that `0 < (generalized_continued_fraction.of v).denominators n` but it's easier -- to consider the case `(generalized_continued_fraction.of v).denominators n = 0`. rcases zero_le_of_denom.eq_or_gt with (hB : (generalized_continued_fraction.of v).denominators n = 0) | hB, { simp only [hB, mul_zero, zero_mul, div_zero] }, { apply one_div_le_one_div_of_le, { have : 0 < b := zero_lt_one.trans_le (of_one_le_nth_part_denom nth_part_denom_eq), apply_rules [mul_pos] }, { conv_rhs { rw [mul_comm] }, exact mul_le_mul_of_nonneg_right (le_of_succ_nth_denom nth_part_denom_eq) hB.le } } end end error_term end generalized_continued_fraction
f501627116d4d9a6125794a0231371baec8a2de4
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/linear_algebra/multilinear.lean
3dd91ca4a43aad8a6496b2afbdc9f46fa3bb1a18
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
54,373
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 linear_algebra.basic import algebra.algebra.basic import data.fintype.sort /-! # Multilinear maps We define multilinear maps as maps from `Π(i : ι), M₁ i` to `M₂` which are linear in each coordinate. Here, `M₁ i` and `M₂` are modules over a ring `R`, and `ι` is an arbitrary type (although some statements will require it to be a fintype). This space, denoted by `multilinear_map R M₁ M₂`, inherits a module structure by pointwise addition and multiplication. ## Main definitions * `multilinear_map R M₁ M₂` is the space of multilinear maps from `Π(i : ι), M₁ i` to `M₂`. * `f.map_smul` is the multiplicativity of the multilinear map `f` along each coordinate. * `f.map_add` is the additivity of the multilinear map `f` along each coordinate. * `f.map_smul_univ` expresses the multiplicativity of `f` over all coordinates at the same time, writing `f (λi, c i • m i)` as `(∏ i, c i) • f m`. * `f.map_add_univ` expresses the additivity of `f` over all coordinates at the same time, writing `f (m + m')` as the sum over all subsets `s` of `ι` of `f (s.piecewise m m')`. * `f.map_sum` expresses `f (Σ_{j₁} g₁ j₁, ..., Σ_{jₙ} gₙ jₙ)` as the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all possible functions. We also register isomorphisms corresponding to currying or uncurrying variables, transforming a multilinear function `f` on `n+1` variables into a linear function taking values in multilinear functions in `n` variables, and into a multilinear function in `n` variables taking values in linear functions. These operations are called `f.curry_left` and `f.curry_right` respectively (with inverses `f.uncurry_left` and `f.uncurry_right`). These operations induce linear equivalences between spaces of multilinear functions in `n+1` variables and spaces of linear functions into multilinear functions in `n` variables (resp. multilinear functions in `n` variables taking values in linear functions), called respectively `multilinear_curry_left_equiv` and `multilinear_curry_right_equiv`. ## Implementation notes Expressing that a map is linear along the `i`-th coordinate when all other coordinates are fixed can be done in two (equivalent) different ways: * fixing a vector `m : Π(j : ι - i), M₁ j.val`, and then choosing separately the `i`-th coordinate * fixing a vector `m : Πj, M₁ j`, and then modifying its `i`-th coordinate The second way is more artificial as the value of `m` at `i` is not relevant, but it has the advantage of avoiding subtype inclusion issues. This is the definition we use, based on `function.update` that allows to change the value of `m` at `i`. -/ open function fin set open_locale big_operators universes u v v' v₁ v₂ v₃ w u' variables {R : Type u} {ι : Type u'} {n : ℕ} {M : fin n.succ → Type v} {M₁ : ι → Type v₁} {M₂ : Type v₂} {M₃ : Type v₃} {M' : Type v'} [decidable_eq ι] /-- Multilinear maps over the ring `R`, from `Πi, M₁ i` to `M₂` where `M₁ i` and `M₂` are modules over `R`. -/ structure multilinear_map (R : Type u) {ι : Type u'} (M₁ : ι → Type v) (M₂ : Type w) [decidable_eq ι] [semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [∀i, module R (M₁ i)] [module R M₂] := (to_fun : (Πi, M₁ i) → M₂) (map_add' : ∀(m : Πi, M₁ i) (i : ι) (x y : M₁ i), to_fun (update m i (x + y)) = to_fun (update m i x) + to_fun (update m i y)) (map_smul' : ∀(m : Πi, M₁ i) (i : ι) (c : R) (x : M₁ i), to_fun (update m i (c • x)) = c • to_fun (update m i x)) namespace multilinear_map section semiring variables [semiring R] [∀i, add_comm_monoid (M i)] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M'] [∀i, module R (M i)] [∀i, module R (M₁ i)] [module R M₂] [module R M₃] [module R M'] (f f' : multilinear_map R M₁ M₂) instance : has_coe_to_fun (multilinear_map R M₁ M₂) := ⟨_, to_fun⟩ initialize_simps_projections multilinear_map (to_fun → apply) @[simp] lemma to_fun_eq_coe : f.to_fun = f := rfl @[simp] lemma coe_mk (f : (Π i, M₁ i) → M₂) (h₁ h₂ ) : ⇑(⟨f, h₁, h₂⟩ : multilinear_map R M₁ M₂) = f := rfl theorem congr_fun {f g : multilinear_map R M₁ M₂} (h : f = g) (x : Π i, M₁ i) : f x = g x := congr_arg (λ h : multilinear_map R M₁ M₂, h x) h theorem congr_arg (f : multilinear_map R M₁ M₂) {x y : Π i, M₁ i} (h : x = y) : f x = f y := congr_arg (λ x : Π i, M₁ i, f x) h theorem coe_inj ⦃f g : multilinear_map R M₁ M₂⦄ (h : ⇑f = g) : f = g := by cases f; cases g; cases h; refl @[ext] theorem ext {f f' : multilinear_map R M₁ M₂} (H : ∀ x, f x = f' x) : f = f' := coe_inj (funext H) theorem ext_iff {f g : multilinear_map R M₁ M₂} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ @[simp] lemma map_add (m : Πi, M₁ i) (i : ι) (x y : M₁ i) : f (update m i (x + y)) = f (update m i x) + f (update m i y) := f.map_add' m i x y @[simp] lemma map_smul (m : Πi, M₁ i) (i : ι) (c : R) (x : M₁ i) : f (update m i (c • x)) = c • f (update m i x) := f.map_smul' m i c x lemma map_coord_zero {m : Πi, M₁ i} (i : ι) (h : m i = 0) : f m = 0 := begin have : (0 : R) • (0 : M₁ i) = 0, by simp, rw [← update_eq_self i m, h, ← this, f.map_smul, zero_smul] end @[simp] lemma map_update_zero (m : Πi, M₁ i) (i : ι) : f (update m i 0) = 0 := f.map_coord_zero i (update_same i 0 m) @[simp] lemma map_zero [nonempty ι] : f 0 = 0 := begin obtain ⟨i, _⟩ : ∃i:ι, i ∈ set.univ := set.exists_mem_of_nonempty ι, exact map_coord_zero f i rfl end instance : has_add (multilinear_map R M₁ M₂) := ⟨λf f', ⟨λx, f x + f' x, λm i x y, by simp [add_left_comm, add_assoc], λm i c x, by simp [smul_add]⟩⟩ @[simp] lemma add_apply (m : Πi, M₁ i) : (f + f') m = f m + f' m := rfl instance : has_zero (multilinear_map R M₁ M₂) := ⟨⟨λ _, 0, λm i x y, by simp, λm i c x, by simp⟩⟩ instance : inhabited (multilinear_map R M₁ M₂) := ⟨0⟩ @[simp] lemma zero_apply (m : Πi, M₁ i) : (0 : multilinear_map R M₁ M₂) m = 0 := rfl instance : add_comm_monoid (multilinear_map R M₁ M₂) := { zero := (0 : multilinear_map R M₁ M₂), add := (+), add_assoc := by intros; ext; simp [add_comm, add_left_comm], zero_add := by intros; ext; simp [add_comm, add_left_comm], add_zero := by intros; ext; simp [add_comm, add_left_comm], add_comm := by intros; ext; simp [add_comm, add_left_comm], nsmul := λ n f, ⟨λ m, n • f m, λm i x y, by simp [smul_add], λl i x d, by simp [←smul_comm x n] ⟩, nsmul_zero' := λ f, by { ext, simp }, nsmul_succ' := λ n f, by { ext, simp [add_smul, nat.succ_eq_one_add] } } @[simp] lemma sum_apply {α : Type*} (f : α → multilinear_map R M₁ M₂) (m : Πi, M₁ i) : ∀ {s : finset α}, (∑ a in s, f a) m = ∑ a in s, f a m := begin classical, apply finset.induction, { rw finset.sum_empty, simp }, { assume a s has H, rw finset.sum_insert has, simp [H, has] } end /-- If `f` is a multilinear map, then `f.to_linear_map m i` is the linear map obtained by fixing all coordinates but `i` equal to those of `m`, and varying the `i`-th coordinate. -/ def to_linear_map (m : Πi, M₁ i) (i : ι) : M₁ i →ₗ[R] M₂ := { to_fun := λx, f (update m i x), map_add' := λx y, by simp, map_smul' := λc x, by simp } /-- The cartesian product of two multilinear maps, as a multilinear map. -/ def prod (f : multilinear_map R M₁ M₂) (g : multilinear_map R M₁ M₃) : multilinear_map R M₁ (M₂ × M₃) := { to_fun := λ m, (f m, g m), map_add' := λ m i x y, by simp, map_smul' := λ m i c x, by simp } /-- Combine a family of multilinear maps with the same domain and codomains `M' i` into a multilinear map taking values in the space of functions `Π i, M' i`. -/ @[simps] def pi {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)] [Π i, module R (M' i)] (f : Π i, multilinear_map R M₁ (M' i)) : multilinear_map R M₁ (Π i, M' i) := { to_fun := λ m i, f i m, map_add' := λ m i x y, funext $ λ j, (f j).map_add _ _ _ _, map_smul' := λ m i c x, funext $ λ j, (f j).map_smul _ _ _ _ } /-- Given a multilinear map `f` on `n` variables (parameterized by `fin n`) and a subset `s` of `k` of these variables, one gets a new multilinear map on `fin k` by varying these variables, and fixing the other ones equal to a given value `z`. It is denoted by `f.restr s hk z`, where `hk` is a proof that the cardinality of `s` is `k`. The implicit identification between `fin k` and `s` that we use is the canonical (increasing) bijection. -/ def restr {k n : ℕ} (f : multilinear_map R (λ i : fin n, M') M₂) (s : finset (fin n)) (hk : s.card = k) (z : M') : multilinear_map R (λ i : fin k, M') M₂ := { to_fun := λ v, f (λ j, if h : j ∈ s then v ((s.order_iso_of_fin hk).symm ⟨j, h⟩) else z), map_add' := λ v i x y, by { erw [dite_comp_equiv_update, dite_comp_equiv_update, dite_comp_equiv_update], simp }, map_smul' := λ v i c x, by { erw [dite_comp_equiv_update, dite_comp_equiv_update], simp } } variable {R} /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the additivity of a multilinear map along the first variable. -/ lemma cons_add (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (x y : M 0) : f (cons (x+y) m) = f (cons x m) + f (cons y m) := by rw [← update_cons_zero x m (x+y), f.map_add, update_cons_zero, update_cons_zero] /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the multiplicativity of a multilinear map along the first variable. -/ lemma cons_smul (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (c : R) (x : M 0) : f (cons (c • x) m) = c • f (cons x m) := by rw [← update_cons_zero x m (c • x), f.map_smul, update_cons_zero] /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `snoc`, one can express directly the additivity of a multilinear map along the first variable. -/ lemma snoc_add (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.cast_succ) (x y : M (last n)) : f (snoc m (x+y)) = f (snoc m x) + f (snoc m y) := by rw [← update_snoc_last x m (x+y), f.map_add, update_snoc_last, update_snoc_last] /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the multiplicativity of a multilinear map along the first variable. -/ lemma snoc_smul (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.cast_succ) (c : R) (x : M (last n)) : f (snoc m (c • x)) = c • f (snoc m x) := by rw [← update_snoc_last x m (c • x), f.map_smul, update_snoc_last] section variables {M₁' : ι → Type*} [Π i, add_comm_monoid (M₁' i)] [Π i, module R (M₁' i)] /-- If `g` is a multilinear map and `f` is a collection of linear maps, then `g (f₁ m₁, ..., fₙ mₙ)` is again a multilinear map, that we call `g.comp_linear_map f`. -/ def comp_linear_map (g : multilinear_map R M₁' M₂) (f : Π i, M₁ i →ₗ[R] M₁' i) : multilinear_map R M₁ M₂ := { to_fun := λ m, g $ λ i, f i (m i), map_add' := λ m i x y, have ∀ j z, f j (update m i z j) = update (λ k, f k (m k)) i (f i z) j := λ j z, function.apply_update (λ k, f k) _ _ _ _, by simp [this], map_smul' := λ m i c x, have ∀ j z, f j (update m i z j) = update (λ k, f k (m k)) i (f i z) j := λ j z, function.apply_update (λ k, f k) _ _ _ _, by simp [this] } @[simp] lemma comp_linear_map_apply (g : multilinear_map R M₁' M₂) (f : Π i, M₁ i →ₗ[R] M₁' i) (m : Π i, M₁ i) : g.comp_linear_map f m = g (λ i, f i (m i)) := rfl end /-- If one adds to a vector `m'` another vector `m`, but only for coordinates in a finset `t`, then the image under a multilinear map `f` is the sum of `f (s.piecewise m m')` along all subsets `s` of `t`. This is mainly an auxiliary statement to prove the result when `t = univ`, given in `map_add_univ`, although it can be useful in its own right as it does not require the index set `ι` to be finite.-/ lemma map_piecewise_add (m m' : Πi, M₁ i) (t : finset ι) : f (t.piecewise (m + m') m') = ∑ s in t.powerset, f (s.piecewise m m') := begin revert m', refine finset.induction_on t (by simp) _, assume i t hit Hrec m', have A : (insert i t).piecewise (m + m') m' = update (t.piecewise (m + m') m') i (m i + m' i) := t.piecewise_insert _ _ _, have B : update (t.piecewise (m + m') m') i (m' i) = t.piecewise (m + m') m', { ext j, by_cases h : j = i, { rw h, simp [hit] }, { simp [h] } }, let m'' := update m' i (m i), have C : update (t.piecewise (m + m') m') i (m i) = t.piecewise (m + m'') m'', { ext j, by_cases h : j = i, { rw h, simp [m'', hit] }, { by_cases h' : j ∈ t; simp [h, hit, m'', h'] } }, rw [A, f.map_add, B, C, finset.sum_powerset_insert hit, Hrec, Hrec, add_comm], congr' 1, apply finset.sum_congr rfl (λs hs, _), have : (insert i s).piecewise m m' = s.piecewise m m'', { ext j, by_cases h : j = i, { rw h, simp [m'', finset.not_mem_of_mem_powerset_of_not_mem hs hit] }, { by_cases h' : j ∈ s; simp [h, m'', h'] } }, rw this end /-- Additivity of a multilinear map along all coordinates at the same time, writing `f (m + m')` as the sum of `f (s.piecewise m m')` over all sets `s`. -/ lemma map_add_univ [fintype ι] (m m' : Πi, M₁ i) : f (m + m') = ∑ s : finset ι, f (s.piecewise m m') := by simpa using f.map_piecewise_add m m' finset.univ section apply_sum variables {α : ι → Type*} (g : Π i, α i → M₁ i) (A : Π i, finset (α i)) open_locale classical open fintype finset /-- If `f` is multilinear, then `f (Σ_{j₁ ∈ A₁} g₁ j₁, ..., Σ_{jₙ ∈ Aₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ..., `r n ∈ Aₙ`. This follows from multilinearity by expanding successively with respect to each coordinate. Here, we give an auxiliary statement tailored for an inductive proof. Use instead `map_sum_finset`. -/ lemma map_sum_finset_aux [fintype ι] {n : ℕ} (h : ∑ i, (A i).card = n) : f (λ i, ∑ j in A i, g i j) = ∑ r in pi_finset A, f (λ i, g i (r i)) := begin induction n using nat.strong_induction_on with n IH generalizing A, -- If one of the sets is empty, then all the sums are zero by_cases Ai_empty : ∃ i, A i = ∅, { rcases Ai_empty with ⟨i, hi⟩, have : ∑ j in A i, g i j = 0, by convert sum_empty, rw f.map_coord_zero i this, have : pi_finset A = ∅, { apply finset.eq_empty_of_forall_not_mem (λ r hr, _), have : r i ∈ A i := mem_pi_finset.mp hr i, rwa hi at this }, convert sum_empty.symm }, push_neg at Ai_empty, -- Otherwise, if all sets are at most singletons, then they are exactly singletons and the result -- is again straightforward by_cases Ai_singleton : ∀ i, (A i).card ≤ 1, { have Ai_card : ∀ i, (A i).card = 1, { assume i, have pos : finset.card (A i) ≠ 0, by simp [finset.card_eq_zero, Ai_empty i], have : finset.card (A i) ≤ 1 := Ai_singleton i, exact le_antisymm this (nat.succ_le_of_lt (_root_.pos_iff_ne_zero.mpr pos)) }, have : ∀ (r : Π i, α i), r ∈ pi_finset A → f (λ i, g i (r i)) = f (λ i, ∑ j in A i, g i j), { assume r hr, unfold_coes, congr' with i, have : ∀ j ∈ A i, g i j = g i (r i), { assume j hj, congr, apply finset.card_le_one_iff.1 (Ai_singleton i) hj, exact mem_pi_finset.mp hr i }, simp only [finset.sum_congr rfl this, finset.mem_univ, finset.sum_const, Ai_card i, one_nsmul] }, simp only [sum_congr rfl this, Ai_card, card_pi_finset, prod_const_one, one_nsmul, finset.sum_const] }, -- Remains the interesting case where one of the `A i`, say `A i₀`, has cardinality at least 2. -- We will split into two parts `B i₀` and `C i₀` of smaller cardinality, let `B i = C i = A i` -- for `i ≠ i₀`, apply the inductive assumption to `B` and `C`, and add up the corresponding -- parts to get the sum for `A`. push_neg at Ai_singleton, obtain ⟨i₀, hi₀⟩ : ∃ i, 1 < (A i).card := Ai_singleton, obtain ⟨j₁, j₂, hj₁, hj₂, j₁_ne_j₂⟩ : ∃ j₁ j₂, (j₁ ∈ A i₀) ∧ (j₂ ∈ A i₀) ∧ j₁ ≠ j₂ := finset.one_lt_card_iff.1 hi₀, let B := function.update A i₀ (A i₀ \ {j₂}), let C := function.update A i₀ {j₂}, have B_subset_A : ∀ i, B i ⊆ A i, { assume i, by_cases hi : i = i₀, { rw hi, simp only [B, sdiff_subset, update_same]}, { simp only [hi, B, update_noteq, ne.def, not_false_iff, finset.subset.refl] } }, have C_subset_A : ∀ i, C i ⊆ A i, { assume i, by_cases hi : i = i₀, { rw hi, simp only [C, hj₂, finset.singleton_subset_iff, update_same] }, { simp only [hi, C, update_noteq, ne.def, not_false_iff, finset.subset.refl] } }, -- split the sum at `i₀` as the sum over `B i₀` plus the sum over `C i₀`, to use additivity. have A_eq_BC : (λ i, ∑ j in A i, g i j) = function.update (λ i, ∑ j in A i, g i j) i₀ (∑ j in B i₀, g i₀ j + ∑ j in C i₀, g i₀ j), { ext i, by_cases hi : i = i₀, { rw [hi], simp only [function.update_same], have : A i₀ = B i₀ ∪ C i₀, { simp only [B, C, function.update_same, finset.sdiff_union_self_eq_union], symmetry, simp only [hj₂, finset.singleton_subset_iff, union_eq_left_iff_subset] }, rw this, apply finset.sum_union, apply finset.disjoint_right.2 (λ j hj, _), have : j = j₂, by { dsimp [C] at hj, simpa using hj }, rw this, dsimp [B], simp only [mem_sdiff, eq_self_iff_true, not_true, not_false_iff, finset.mem_singleton, update_same, and_false] }, { simp [hi] } }, have Beq : function.update (λ i, ∑ j in A i, g i j) i₀ (∑ j in B i₀, g i₀ j) = (λ i, ∑ j in B i, g i j), { ext i, by_cases hi : i = i₀, { rw hi, simp only [update_same] }, { simp only [hi, B, update_noteq, ne.def, not_false_iff] } }, have Ceq : function.update (λ i, ∑ j in A i, g i j) i₀ (∑ j in C i₀, g i₀ j) = (λ i, ∑ j in C i, g i j), { ext i, by_cases hi : i = i₀, { rw hi, simp only [update_same] }, { simp only [hi, C, update_noteq, ne.def, not_false_iff] } }, -- Express the inductive assumption for `B` have Brec : f (λ i, ∑ j in B i, g i j) = ∑ r in pi_finset B, f (λ i, g i (r i)), { have : ∑ i, finset.card (B i) < ∑ i, finset.card (A i), { refine finset.sum_lt_sum (λ i hi, finset.card_le_of_subset (B_subset_A i)) ⟨i₀, finset.mem_univ _, _⟩, have : {j₂} ⊆ A i₀, by simp [hj₂], simp only [B, finset.card_sdiff this, function.update_same, finset.card_singleton], exact nat.pred_lt (ne_of_gt (lt_trans nat.zero_lt_one hi₀)) }, rw h at this, exact IH _ this B rfl }, -- Express the inductive assumption for `C` have Crec : f (λ i, ∑ j in C i, g i j) = ∑ r in pi_finset C, f (λ i, g i (r i)), { have : ∑ i, finset.card (C i) < ∑ i, finset.card (A i) := finset.sum_lt_sum (λ i hi, finset.card_le_of_subset (C_subset_A i)) ⟨i₀, finset.mem_univ _, by simp [C, hi₀]⟩, rw h at this, exact IH _ this C rfl }, have D : disjoint (pi_finset B) (pi_finset C), { have : disjoint (B i₀) (C i₀), by simp [B, C], exact pi_finset_disjoint_of_disjoint B C this }, have pi_BC : pi_finset A = pi_finset B ∪ pi_finset C, { apply finset.subset.antisymm, { assume r hr, by_cases hri₀ : r i₀ = j₂, { apply finset.mem_union_right, apply mem_pi_finset.2 (λ i, _), by_cases hi : i = i₀, { have : r i₀ ∈ C i₀, by simp [C, hri₀], convert this }, { simp [C, hi, mem_pi_finset.1 hr i] } }, { apply finset.mem_union_left, apply mem_pi_finset.2 (λ i, _), by_cases hi : i = i₀, { have : r i₀ ∈ B i₀, by simp [B, hri₀, mem_pi_finset.1 hr i₀], convert this }, { simp [B, hi, mem_pi_finset.1 hr i] } } }, { exact finset.union_subset (pi_finset_subset _ _ (λ i, B_subset_A i)) (pi_finset_subset _ _ (λ i, C_subset_A i)) } }, rw A_eq_BC, simp only [multilinear_map.map_add, Beq, Ceq, Brec, Crec, pi_BC], rw ← finset.sum_union D, end /-- If `f` is multilinear, then `f (Σ_{j₁ ∈ A₁} g₁ j₁, ..., Σ_{jₙ ∈ Aₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ..., `r n ∈ Aₙ`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ lemma map_sum_finset [fintype ι] : f (λ i, ∑ j in A i, g i j) = ∑ r in pi_finset A, f (λ i, g i (r i)) := f.map_sum_finset_aux _ _ rfl /-- If `f` is multilinear, then `f (Σ_{j₁} g₁ j₁, ..., Σ_{jₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions `r`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ lemma map_sum [fintype ι] [∀ i, fintype (α i)] : f (λ i, ∑ j, g i j) = ∑ r : Π i, α i, f (λ i, g i (r i)) := f.map_sum_finset g (λ i, finset.univ) lemma map_update_sum {α : Type*} (t : finset α) (i : ι) (g : α → M₁ i) (m : Π i, M₁ i): f (update m i (∑ a in t, g a)) = ∑ a in t, f (update m i (g a)) := begin induction t using finset.induction with a t has ih h, { simp }, { simp [finset.sum_insert has, ih] } end end apply_sum section restrict_scalar variables (R) {A : Type*} [semiring A] [has_scalar R A] [Π (i : ι), module A (M₁ i)] [module A M₂] [∀ i, is_scalar_tower R A (M₁ i)] [is_scalar_tower R A M₂] /-- Reinterpret an `A`-multilinear map as an `R`-multilinear map, if `A` is an algebra over `R` and their actions on all involved modules agree with the action of `R` on `A`. -/ def restrict_scalars (f : multilinear_map A M₁ M₂) : multilinear_map R M₁ M₂ := { to_fun := f, map_add' := f.map_add, map_smul' := λ m i, (f.to_linear_map m i).map_smul_of_tower } @[simp] lemma coe_restrict_scalars (f : multilinear_map A M₁ M₂) : ⇑(f.restrict_scalars R) = f := rfl end restrict_scalar section variables {ι₁ ι₂ ι₃ : Type*} [decidable_eq ι₁] [decidable_eq ι₂] [decidable_eq ι₃] /-- Transfer the arguments to a map along an equivalence between argument indices. The naming is derived from `finsupp.dom_congr`, noting that here the permutation applies to the domain of the domain. -/ @[simps apply] def dom_dom_congr (σ : ι₁ ≃ ι₂) (m : multilinear_map R (λ i : ι₁, M₂) M₃) : multilinear_map R (λ i : ι₂, M₂) M₃ := { to_fun := λ v, m (λ i, v (σ i)), map_add' := λ v i a b, by { simp_rw function.update_apply_equiv_apply v, rw m.map_add, }, map_smul' := λ v i a b, by { simp_rw function.update_apply_equiv_apply v, rw m.map_smul, }, } lemma dom_dom_congr_trans (σ₁ : ι₁ ≃ ι₂) (σ₂ : ι₂ ≃ ι₃) (m : multilinear_map R (λ i : ι₁, M₂) M₃) : m.dom_dom_congr (σ₁.trans σ₂) = (m.dom_dom_congr σ₁).dom_dom_congr σ₂ := rfl lemma dom_dom_congr_mul (σ₁ : equiv.perm ι₁) (σ₂ : equiv.perm ι₁) (m : multilinear_map R (λ i : ι₁, M₂) M₃) : m.dom_dom_congr (σ₂ * σ₁) = (m.dom_dom_congr σ₁).dom_dom_congr σ₂ := rfl /-- `multilinear_map.dom_dom_congr` as an equivalence. This is declared separately because it does not work with dot notation. -/ @[simps apply symm_apply] def dom_dom_congr_equiv (σ : ι₁ ≃ ι₂) : multilinear_map R (λ i : ι₁, M₂) M₃ ≃+ multilinear_map R (λ i : ι₂, M₂) M₃ := { to_fun := dom_dom_congr σ, inv_fun := dom_dom_congr σ.symm, left_inv := λ m, by {ext, simp}, right_inv := λ m, by {ext, simp}, map_add' := λ a b, by {ext, simp} } end end semiring end multilinear_map namespace linear_map variables [semiring R] [Πi, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M'] [∀i, module R (M₁ i)] [module R M₂] [module R M₃] [module R M'] /-- Composing a multilinear map with a linear map gives again a multilinear map. -/ def comp_multilinear_map (g : M₂ →ₗ[R] M₃) (f : multilinear_map R M₁ M₂) : multilinear_map R M₁ M₃ := { to_fun := g ∘ f, map_add' := λ m i x y, by simp, map_smul' := λ m i c x, by simp } @[simp] lemma coe_comp_multilinear_map (g : M₂ →ₗ[R] M₃) (f : multilinear_map R M₁ M₂) : ⇑(g.comp_multilinear_map f) = g ∘ f := rfl lemma comp_multilinear_map_apply (g : M₂ →ₗ[R] M₃) (f : multilinear_map R M₁ M₂) (m : Π i, M₁ i) : g.comp_multilinear_map f m = g (f m) := rfl variables {ι₁ ι₂ : Type*} [decidable_eq ι₁] [decidable_eq ι₂] @[simp] lemma comp_multilinear_map_dom_dom_congr (σ : ι₁ ≃ ι₂) (g : M₂ →ₗ[R] M₃) (f : multilinear_map R (λ i : ι₁, M') M₂) : (g.comp_multilinear_map f).dom_dom_congr σ = g.comp_multilinear_map (f.dom_dom_congr σ) := by { ext, simp } end linear_map namespace multilinear_map section comm_semiring variables [comm_semiring R] [∀i, add_comm_monoid (M₁ i)] [∀i, add_comm_monoid (M i)] [add_comm_monoid M₂] [∀i, module R (M i)] [∀i, module R (M₁ i)] [module R M₂] (f f' : multilinear_map R M₁ M₂) /-- If one multiplies by `c i` the coordinates in a finset `s`, then the image under a multilinear map is multiplied by `∏ i in s, c i`. This is mainly an auxiliary statement to prove the result when `s = univ`, given in `map_smul_univ`, although it can be useful in its own right as it does not require the index set `ι` to be finite. -/ lemma map_piecewise_smul (c : ι → R) (m : Πi, M₁ i) (s : finset ι) : f (s.piecewise (λi, c i • m i) m) = (∏ i in s, c i) • f m := begin refine s.induction_on (by simp) _, assume j s j_not_mem_s Hrec, have A : function.update (s.piecewise (λi, c i • m i) m) j (m j) = s.piecewise (λi, c i • m i) m, { ext i, by_cases h : i = j, { rw h, simp [j_not_mem_s] }, { simp [h] } }, rw [s.piecewise_insert, f.map_smul, A, Hrec], simp [j_not_mem_s, mul_smul] end /-- Multiplicativity of a multilinear map along all coordinates at the same time, writing `f (λi, c i • m i)` as `(∏ i, c i) • f m`. -/ lemma map_smul_univ [fintype ι] (c : ι → R) (m : Πi, M₁ i) : f (λi, c i • m i) = (∏ i, c i) • f m := by simpa using map_piecewise_smul f c m finset.univ section distrib_mul_action variables {R' A : Type*} [monoid R'] [semiring A] [Π i, module A (M₁ i)] [distrib_mul_action R' M₂] [module A M₂] [smul_comm_class A R' M₂] instance : has_scalar R' (multilinear_map A M₁ M₂) := ⟨λ c f, ⟨λ m, c • f m, λm i x y, by simp [smul_add], λl i x d, by simp [←smul_comm x c] ⟩⟩ @[simp] lemma smul_apply (f : multilinear_map A M₁ M₂) (c : R') (m : Πi, M₁ i) : (c • f) m = c • f m := rfl instance : distrib_mul_action R' (multilinear_map A M₁ M₂) := { one_smul := λ f, ext $ λ x, one_smul _ _, mul_smul := λ c₁ c₂ f, ext $ λ x, mul_smul _ _ _, smul_zero := λ r, ext $ λ x, smul_zero _, smul_add := λ r f₁ f₂, ext $ λ x, smul_add _ _ _ } end distrib_mul_action section module variables {R' A : Type*} [semiring R'] [semiring A] [Π i, module A (M₁ i)] [module A M₂] [add_comm_monoid M₃] [module R' M₃] [module A M₃] [smul_comm_class A R' M₃] /-- The space of multilinear maps over an algebra over `R` is a module over `R`, for the pointwise addition and scalar multiplication. -/ instance [module R' M₂] [smul_comm_class A R' M₂] : module R' (multilinear_map A M₁ M₂) := { add_smul := λ r₁ r₂ f, ext $ λ x, add_smul _ _ _, zero_smul := λ f, ext $ λ x, zero_smul _ _ } variables (M₂ M₃ R' A) /-- `multilinear_map.dom_dom_congr` as a `linear_equiv`. -/ @[simps apply symm_apply] def dom_dom_congr_linear_equiv {ι₁ ι₂} [decidable_eq ι₁] [decidable_eq ι₂] (σ : ι₁ ≃ ι₂) : multilinear_map A (λ i : ι₁, M₂) M₃ ≃ₗ[R'] multilinear_map A (λ i : ι₂, M₂) M₃ := { map_smul' := λ c f, by { ext, simp }, .. (dom_dom_congr_equiv σ : multilinear_map A (λ i : ι₁, M₂) M₃ ≃+ multilinear_map A (λ i : ι₂, M₂) M₃) } end module section dom_coprod open_locale tensor_product variables {ι₁ ι₂ ι₃ ι₄ : Type*} variables [decidable_eq ι₁] [decidable_eq ι₂][decidable_eq ι₃] [decidable_eq ι₄] variables {N₁ : Type*} [add_comm_monoid N₁] [module R N₁] variables {N₂ : Type*} [add_comm_monoid N₂] [module R N₂] variables {N : Type*} [add_comm_monoid N] [module R N] /-- Given two multilinear maps `(ι₁ → N) → N₁` and `(ι₂ → N) → N₂`, this produces the map `(ι₁ ⊕ ι₂ → N) → N₁ ⊗ N₂` by taking the coproduct of the domain and the tensor product of the codomain. This can be thought of as combining `equiv.sum_arrow_equiv_prod_arrow.symm` with `tensor_product.map`, noting that the two operations can't be separated as the intermediate result is not a `multilinear_map`. While this can be generalized to work for dependent `Π i : ι₁, N'₁ i` instead of `ι₁ → N`, doing so introduces `sum.elim N'₁ N'₂` types in the result which are difficult to work with and not defeq to the simple case defined here. See [this zulip thread]( https://leanprover.zulipchat.com/#narrow/stream/217875-Is-there.20code.20for.20X.3F/topic/Instances.20on.20.60sum.2Eelim.20A.20B.20i.60/near/218484619). -/ @[simps apply] def dom_coprod (a : multilinear_map R (λ _ : ι₁, N) N₁) (b : multilinear_map R (λ _ : ι₂, N) N₂) : multilinear_map R (λ _ : ι₁ ⊕ ι₂, N) (N₁ ⊗[R] N₂) := { to_fun := λ v, a (λ i, v (sum.inl i)) ⊗ₜ b (λ i, v (sum.inr i)), map_add' := λ v i p q, by cases i; simp [tensor_product.add_tmul, tensor_product.tmul_add], map_smul' := λ v i c p, by cases i; simp [tensor_product.smul_tmul', tensor_product.tmul_smul] } /-- A more bundled version of `multilinear_map.dom_coprod` that maps `((ι₁ → N) → N₁) ⊗ ((ι₂ → N) → N₂)` to `(ι₁ ⊕ ι₂ → N) → N₁ ⊗ N₂`. -/ def dom_coprod' : multilinear_map R (λ _ : ι₁, N) N₁ ⊗[R] multilinear_map R (λ _ : ι₂, N) N₂ →ₗ[R] multilinear_map R (λ _ : ι₁ ⊕ ι₂, N) (N₁ ⊗[R] N₂) := tensor_product.lift $ linear_map.mk₂ R (dom_coprod) (λ m₁ m₂ n, by { ext, simp only [dom_coprod_apply, tensor_product.add_tmul, add_apply] }) (λ c m n, by { ext, simp only [dom_coprod_apply, tensor_product.smul_tmul', smul_apply] }) (λ m n₁ n₂, by { ext, simp only [dom_coprod_apply, tensor_product.tmul_add, add_apply] }) (λ c m n, by { ext, simp only [dom_coprod_apply, tensor_product.tmul_smul, smul_apply] }) @[simp] lemma dom_coprod'_apply (a : multilinear_map R (λ _ : ι₁, N) N₁) (b : multilinear_map R (λ _ : ι₂, N) N₂) : dom_coprod' (a ⊗ₜ[R] b) = dom_coprod a b := rfl /-- When passed an `equiv.sum_congr`, `multilinear_map.dom_dom_congr` distributes over `multilinear_map.dom_coprod`. -/ lemma dom_coprod_dom_dom_congr_sum_congr (a : multilinear_map R (λ _ : ι₁, N) N₁) (b : multilinear_map R (λ _ : ι₂, N) N₂) (σa : ι₁ ≃ ι₃) (σb : ι₂ ≃ ι₄) : (a.dom_coprod b).dom_dom_congr (σa.sum_congr σb) = (a.dom_dom_congr σa).dom_coprod (b.dom_dom_congr σb) := rfl end dom_coprod section variables (R ι) (A : Type*) [comm_semiring A] [algebra R A] [fintype ι] /-- Given an `R`-algebra `A`, `mk_pi_algebra` is the multilinear map on `A^ι` associating to `m` the product of all the `m i`. See also `multilinear_map.mk_pi_algebra_fin` for a version that works with a non-commutative algebra `A` but requires `ι = fin n`. -/ protected def mk_pi_algebra : multilinear_map R (λ i : ι, A) A := { to_fun := λ m, ∏ i, m i, map_add' := λ m i x y, by simp [finset.prod_update_of_mem, add_mul], map_smul' := λ m i c x, by simp [finset.prod_update_of_mem] } variables {R A ι} @[simp] lemma mk_pi_algebra_apply (m : ι → A) : multilinear_map.mk_pi_algebra R ι A m = ∏ i, m i := rfl end section variables (R n) (A : Type*) [semiring A] [algebra R A] /-- Given an `R`-algebra `A`, `mk_pi_algebra_fin` is the multilinear map on `A^n` associating to `m` the product of all the `m i`. See also `multilinear_map.mk_pi_algebra` for a version that assumes `[comm_semiring A]` but works for `A^ι` with any finite type `ι`. -/ protected def mk_pi_algebra_fin : multilinear_map R (λ i : fin n, A) A := { to_fun := λ m, (list.of_fn m).prod, map_add' := begin intros m i x y, have : (list.fin_range n).index_of i < n, by simpa using list.index_of_lt_length.2 (list.mem_fin_range i), simp [list.of_fn_eq_map, (list.nodup_fin_range n).map_update, list.prod_update_nth, add_mul, this, mul_add, add_mul] end, map_smul' := begin intros m i c x, have : (list.fin_range n).index_of i < n, by simpa using list.index_of_lt_length.2 (list.mem_fin_range i), simp [list.of_fn_eq_map, (list.nodup_fin_range n).map_update, list.prod_update_nth, this] end } variables {R A n} @[simp] lemma mk_pi_algebra_fin_apply (m : fin n → A) : multilinear_map.mk_pi_algebra_fin R n A m = (list.of_fn m).prod := rfl lemma mk_pi_algebra_fin_apply_const (a : A) : multilinear_map.mk_pi_algebra_fin R n A (λ _, a) = a ^ n := by simp end /-- Given an `R`-multilinear map `f` taking values in `R`, `f.smul_right z` is the map sending `m` to `f m • z`. -/ def smul_right (f : multilinear_map R M₁ R) (z : M₂) : multilinear_map R M₁ M₂ := (linear_map.smul_right linear_map.id z).comp_multilinear_map f @[simp] lemma smul_right_apply (f : multilinear_map R M₁ R) (z : M₂) (m : Π i, M₁ i) : f.smul_right z m = f m • z := rfl variables (R ι) /-- The canonical multilinear map on `R^ι` when `ι` is finite, associating to `m` the product of all the `m i` (multiplied by a fixed reference element `z` in the target module). See also `mk_pi_algebra` for a more general version. -/ protected def mk_pi_ring [fintype ι] (z : M₂) : multilinear_map R (λ(i : ι), R) M₂ := (multilinear_map.mk_pi_algebra R ι R).smul_right z variables {R ι} @[simp] lemma mk_pi_ring_apply [fintype ι] (z : M₂) (m : ι → R) : (multilinear_map.mk_pi_ring R ι z : (ι → R) → M₂) m = (∏ i, m i) • z := rfl lemma mk_pi_ring_apply_one_eq_self [fintype ι] (f : multilinear_map R (λ(i : ι), R) M₂) : multilinear_map.mk_pi_ring R ι (f (λi, 1)) = f := begin ext m, have : m = (λi, m i • 1), by { ext j, simp }, conv_rhs { rw [this, f.map_smul_univ] }, refl end end comm_semiring section range_add_comm_group variables [semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_group M₂] [∀i, module R (M₁ i)] [module R M₂] (f g : multilinear_map R M₁ M₂) instance : has_neg (multilinear_map R M₁ M₂) := ⟨λ f, ⟨λ m, - f m, λm i x y, by simp [add_comm], λm i c x, by simp⟩⟩ @[simp] lemma neg_apply (m : Πi, M₁ i) : (-f) m = - (f m) := rfl instance : has_sub (multilinear_map R M₁ M₂) := ⟨λ f g, ⟨λ m, f m - g m, λ m i x y, by { simp only [map_add, sub_eq_add_neg, neg_add], cc }, λ m i c x, by { simp only [map_smul, smul_sub] }⟩⟩ @[simp] lemma sub_apply (m : Πi, M₁ i) : (f - g) m = f m - g m := rfl instance : add_comm_group (multilinear_map R M₁ M₂) := by refine { zero := (0 : multilinear_map R M₁ M₂), add := (+), neg := has_neg.neg, sub := has_sub.sub, sub_eq_add_neg := _, nsmul := λ n f, ⟨λ m, n • f m, λm i x y, by simp [smul_add], λl i x d, by simp [←smul_comm x n] ⟩, gsmul := λ n f, ⟨λ m, n • f m, λm i x y, by simp [smul_add], λl i x d, by simp [←smul_comm x n] ⟩, gsmul_zero' := _, gsmul_succ' := _, gsmul_neg' := _, .. multilinear_map.add_comm_monoid, .. }; intros; ext; simp [add_comm, add_left_comm, sub_eq_add_neg, add_smul, nat.succ_eq_add_one] end range_add_comm_group section add_comm_group variables [semiring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂] [∀i, module R (M₁ i)] [module R M₂] (f : multilinear_map R M₁ M₂) @[simp] lemma map_neg (m : Πi, M₁ i) (i : ι) (x : M₁ i) : f (update m i (-x)) = -f (update m i x) := eq_neg_of_add_eq_zero $ by rw [←map_add, add_left_neg, f.map_coord_zero i (update_same i 0 m)] @[simp] lemma map_sub (m : Πi, M₁ i) (i : ι) (x y : M₁ i) : f (update m i (x - y)) = f (update m i x) - f (update m i y) := by rw [sub_eq_add_neg, sub_eq_add_neg, map_add, map_neg] end add_comm_group section comm_semiring variables [comm_semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [∀i, module R (M₁ i)] [module R M₂] /-- When `ι` is finite, multilinear maps on `R^ι` with values in `M₂` are in bijection with `M₂`, as such a multilinear map is completely determined by its value on the constant vector made of ones. We register this bijection as a linear equivalence in `multilinear_map.pi_ring_equiv`. -/ protected def pi_ring_equiv [fintype ι] : M₂ ≃ₗ[R] (multilinear_map R (λ(i : ι), R) M₂) := { to_fun := λ z, multilinear_map.mk_pi_ring R ι z, inv_fun := λ f, f (λi, 1), map_add' := λ z z', by { ext m, simp [smul_add] }, map_smul' := λ c z, by { ext m, simp [smul_smul, mul_comm] }, left_inv := λ z, by simp, right_inv := λ f, f.mk_pi_ring_apply_one_eq_self } end comm_semiring end multilinear_map section currying /-! ### Currying We associate to a multilinear map in `n+1` variables (i.e., based on `fin n.succ`) two curried functions, named `f.curry_left` (which is a linear map on `E 0` taking values in multilinear maps in `n` variables) and `f.curry_right` (wich is a multilinear map in `n` variables taking values in linear maps on `E 0`). In both constructions, the variable that is singled out is `0`, to take advantage of the operations `cons` and `tail` on `fin n`. The inverse operations are called `uncurry_left` and `uncurry_right`. We also register linear equiv versions of these correspondences, in `multilinear_curry_left_equiv` and `multilinear_curry_right_equiv`. -/ open multilinear_map variables {R M M₂} [comm_semiring R] [∀i, add_comm_monoid (M i)] [add_comm_monoid M'] [add_comm_monoid M₂] [∀i, module R (M i)] [module R M'] [module R M₂] /-! #### Left currying -/ /-- Given a linear map `f` from `M 0` to multilinear maps on `n` variables, construct the corresponding multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (m 0) (tail m)`-/ def linear_map.uncurry_left (f : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) : multilinear_map R M M₂ := { to_fun := λm, f (m 0) (tail m), map_add' := λm i x y, begin by_cases h : i = 0, { subst i, rw [update_same, update_same, update_same, f.map_add, add_apply, tail_update_zero, tail_update_zero, tail_update_zero] }, { rw [update_noteq (ne.symm h), update_noteq (ne.symm h), update_noteq (ne.symm h)], revert x y, rw ← succ_pred i h, assume x y, rw [tail_update_succ, map_add, tail_update_succ, tail_update_succ] } end, map_smul' := λm i c x, begin by_cases h : i = 0, { subst i, rw [update_same, update_same, tail_update_zero, tail_update_zero, ← smul_apply, f.map_smul] }, { rw [update_noteq (ne.symm h), update_noteq (ne.symm h)], revert x, rw ← succ_pred i h, assume x, rw [tail_update_succ, tail_update_succ, map_smul] } end } @[simp] lemma linear_map.uncurry_left_apply (f : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) (m : Πi, M i) : f.uncurry_left m = f (m 0) (tail m) := rfl /-- Given a multilinear map `f` in `n+1` variables, split the first variable to obtain a linear map into multilinear maps in `n` variables, given by `x ↦ (m ↦ f (cons x m))`. -/ def multilinear_map.curry_left (f : multilinear_map R M M₂) : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂) := { to_fun := λx, { to_fun := λm, f (cons x m), map_add' := λm i y y', by simp, map_smul' := λm i y c, by simp }, map_add' := λx y, by { ext m, exact cons_add f m x y }, map_smul' := λc x, by { ext m, exact cons_smul f m c x } } @[simp] lemma multilinear_map.curry_left_apply (f : multilinear_map R M M₂) (x : M 0) (m : Π(i : fin n), M i.succ) : f.curry_left x m = f (cons x m) := rfl @[simp] lemma linear_map.curry_uncurry_left (f : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) : f.uncurry_left.curry_left = f := begin ext m x, simp only [tail_cons, linear_map.uncurry_left_apply, multilinear_map.curry_left_apply], rw cons_zero end @[simp] lemma multilinear_map.uncurry_curry_left (f : multilinear_map R M M₂) : f.curry_left.uncurry_left = f := by { ext m, simp, } variables (R M M₂) /-- The space of multilinear maps on `Π(i : fin (n+1)), M i` is canonically isomorphic to the space of linear maps from `M 0` to the space of multilinear maps on `Π(i : fin n), M i.succ `, by separating the first variable. We register this isomorphism as a linear isomorphism in `multilinear_curry_left_equiv R M M₂`. The direct and inverse maps are given by `f.uncurry_left` and `f.curry_left`. Use these unless you need the full framework of linear equivs. -/ def multilinear_curry_left_equiv : (M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) ≃ₗ[R] (multilinear_map R M M₂) := { to_fun := linear_map.uncurry_left, map_add' := λf₁ f₂, by { ext m, refl }, map_smul' := λc f, by { ext m, refl }, inv_fun := multilinear_map.curry_left, left_inv := linear_map.curry_uncurry_left, right_inv := multilinear_map.uncurry_curry_left } variables {R M M₂} /-! #### Right currying -/ /-- Given a multilinear map `f` in `n` variables to the space of linear maps from `M (last n)` to `M₂`, construct the corresponding multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (init m) (m (last n))`-/ def multilinear_map.uncurry_right (f : (multilinear_map R (λ(i : fin n), M i.cast_succ) (M (last n) →ₗ[R] M₂))) : multilinear_map R M M₂ := { to_fun := λm, f (init m) (m (last n)), map_add' := λm i x y, begin by_cases h : i.val < n, { have : last n ≠ i := ne.symm (ne_of_lt h), rw [update_noteq this, update_noteq this, update_noteq this], revert x y, rw [(cast_succ_cast_lt i h).symm], assume x y, rw [init_update_cast_succ, map_add, init_update_cast_succ, init_update_cast_succ, linear_map.add_apply] }, { revert x y, rw eq_last_of_not_lt h, assume x y, rw [init_update_last, init_update_last, init_update_last, update_same, update_same, update_same, linear_map.map_add] } end, map_smul' := λm i c x, begin by_cases h : i.val < n, { have : last n ≠ i := ne.symm (ne_of_lt h), rw [update_noteq this, update_noteq this], revert x, rw [(cast_succ_cast_lt i h).symm], assume x, rw [init_update_cast_succ, init_update_cast_succ, map_smul, linear_map.smul_apply] }, { revert x, rw eq_last_of_not_lt h, assume x, rw [update_same, update_same, init_update_last, init_update_last, linear_map.map_smul] } end } @[simp] lemma multilinear_map.uncurry_right_apply (f : (multilinear_map R (λ(i : fin n), M i.cast_succ) ((M (last n)) →ₗ[R] M₂))) (m : Πi, M i) : f.uncurry_right m = f (init m) (m (last n)) := rfl /-- Given a multilinear map `f` in `n+1` variables, split the last variable to obtain a multilinear map in `n` variables taking values in linear maps from `M (last n)` to `M₂`, given by `m ↦ (x ↦ f (snoc m x))`. -/ def multilinear_map.curry_right (f : multilinear_map R M M₂) : multilinear_map R (λ(i : fin n), M (fin.cast_succ i)) ((M (last n)) →ₗ[R] M₂) := { to_fun := λm, { to_fun := λx, f (snoc m x), map_add' := λx y, by rw f.snoc_add, map_smul' := λc x, by rw f.snoc_smul }, map_add' := λm i x y, begin ext z, change f (snoc (update m i (x + y)) z) = f (snoc (update m i x) z) + f (snoc (update m i y) z), rw [snoc_update, snoc_update, snoc_update, f.map_add] end, map_smul' := λm i c x, begin ext z, change f (snoc (update m i (c • x)) z) = c • f (snoc (update m i x) z), rw [snoc_update, snoc_update, f.map_smul] end } @[simp] lemma multilinear_map.curry_right_apply (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.cast_succ) (x : M (last n)) : f.curry_right m x = f (snoc m x) := rfl @[simp] lemma multilinear_map.curry_uncurry_right (f : (multilinear_map R (λ(i : fin n), M i.cast_succ) ((M (last n)) →ₗ[R] M₂))) : f.uncurry_right.curry_right = f := begin ext m x, simp only [snoc_last, multilinear_map.curry_right_apply, multilinear_map.uncurry_right_apply], rw init_snoc end @[simp] lemma multilinear_map.uncurry_curry_right (f : multilinear_map R M M₂) : f.curry_right.uncurry_right = f := by { ext m, simp } variables (R M M₂) /-- The space of multilinear maps on `Π(i : fin (n+1)), M i` is canonically isomorphic to the space of linear maps from the space of multilinear maps on `Π(i : fin n), M i.cast_succ` to the space of linear maps on `M (last n)`, by separating the last variable. We register this isomorphism as a linear isomorphism in `multilinear_curry_right_equiv R M M₂`. The direct and inverse maps are given by `f.uncurry_right` and `f.curry_right`. Use these unless you need the full framework of linear equivs. -/ def multilinear_curry_right_equiv : (multilinear_map R (λ(i : fin n), M i.cast_succ) ((M (last n)) →ₗ[R] M₂)) ≃ₗ[R] (multilinear_map R M M₂) := { to_fun := multilinear_map.uncurry_right, map_add' := λf₁ f₂, by { ext m, refl }, map_smul' := λc f, by { ext m, rw [smul_apply], refl }, inv_fun := multilinear_map.curry_right, left_inv := multilinear_map.curry_uncurry_right, right_inv := multilinear_map.uncurry_curry_right } namespace multilinear_map variables {ι' : Type*} [decidable_eq ι'] [decidable_eq (ι ⊕ ι')] {R M₂} /-- A multilinear map on `Π i : ι ⊕ ι', M'` defines a multilinear map on `Π i : ι, M'` taking values in the space of multilinear maps on `Π i : ι', M'`. -/ def curry_sum (f : multilinear_map R (λ x : ι ⊕ ι', M') M₂) : multilinear_map R (λ x : ι, M') (multilinear_map R (λ x : ι', M') M₂) := { to_fun := λ u, { to_fun := λ v, f (sum.elim u v), map_add' := λ v i x y, by simp only [← sum.update_elim_inr, f.map_add], map_smul' := λ v i c x, by simp only [← sum.update_elim_inr, f.map_smul] }, map_add' := λ u i x y, ext $ λ v, by simp only [multilinear_map.coe_mk, add_apply, ← sum.update_elim_inl, f.map_add], map_smul' := λ u i c x, ext $ λ v, by simp only [multilinear_map.coe_mk, smul_apply, ← sum.update_elim_inl, f.map_smul] } @[simp] lemma curry_sum_apply (f : multilinear_map R (λ x : ι ⊕ ι', M') M₂) (u : ι → M') (v : ι' → M') : f.curry_sum u v = f (sum.elim u v) := rfl /-- A multilinear map on `Π i : ι, M'` taking values in the space of multilinear maps on `Π i : ι', M'` defines a multilinear map on `Π i : ι ⊕ ι', M'`. -/ def uncurry_sum (f : multilinear_map R (λ x : ι, M') (multilinear_map R (λ x : ι', M') M₂)) : multilinear_map R (λ x : ι ⊕ ι', M') M₂ := { to_fun := λ u, f (u ∘ sum.inl) (u ∘ sum.inr), map_add' := λ u i x y, by cases i; simp only [map_add, add_apply, sum.update_inl_comp_inl, sum.update_inl_comp_inr, sum.update_inr_comp_inl, sum.update_inr_comp_inr], map_smul' := λ u i c x, by cases i; simp only [map_smul, smul_apply, sum.update_inl_comp_inl, sum.update_inl_comp_inr, sum.update_inr_comp_inl, sum.update_inr_comp_inr] } @[simp] lemma uncurry_sum_aux_apply (f : multilinear_map R (λ x : ι, M') (multilinear_map R (λ x : ι', M') M₂)) (u : ι ⊕ ι' → M') : f.uncurry_sum u = f (u ∘ sum.inl) (u ∘ sum.inr) := rfl variables (ι ι' R M₂ M') /-- Linear equivalence between the space of multilinear maps on `Π i : ι ⊕ ι', M'` and the space of multilinear maps on `Π i : ι, M'` taking values in the space of multilinear maps on `Π i : ι', M'`. -/ def curry_sum_equiv : multilinear_map R (λ x : ι ⊕ ι', M') M₂ ≃ₗ[R] multilinear_map R (λ x : ι, M') (multilinear_map R (λ x : ι', M') M₂) := { to_fun := curry_sum, inv_fun := uncurry_sum, left_inv := λ f, ext $ λ u, by simp, right_inv := λ f, by { ext, simp }, map_add' := λ f g, by { ext, refl }, map_smul' := λ c f, by { ext, refl } } variables {ι ι' R M₂ M'} @[simp] lemma coe_curry_sum_equiv : ⇑(curry_sum_equiv R ι M₂ M' ι') = curry_sum := rfl @[simp] lemma coe_curr_sum_equiv_symm : ⇑(curry_sum_equiv R ι M₂ M' ι').symm = uncurry_sum := rfl variables (R M₂ M') /-- If `s : finset (fin n)` is a finite set of cardinality `k` and its complement has cardinality `l`, then the space of multilinear maps on `λ i : fin n, M'` is isomorphic to the space of multilinear maps on `λ i : fin k, M'` taking values in the space of multilinear maps on `λ i : fin l, M'`. -/ def curry_fin_finset {k l n : ℕ} {s : finset (fin n)} [decidable_pred (s : set (fin n))] (hk : s.card = k) (hl : sᶜ.card = l) : multilinear_map R (λ x : fin n, M') M₂ ≃ₗ[R] multilinear_map R (λ x : fin k, M') (multilinear_map R (λ x : fin l, M') M₂) := (dom_dom_congr_linear_equiv M' M₂ R R (fin_sum_equiv_of_finset hk hl).symm).trans (curry_sum_equiv R (fin k) M₂ M' (fin l)) variables {R M₂ M'} @[simp] lemma curry_fin_finset_apply {k l n : ℕ} {s : finset (fin n)} [decidable_pred (s : set (fin n))] (hk : s.card = k) (hl : sᶜ.card = l) (f : multilinear_map R (λ x : fin n, M') M₂) (mk : fin k → M') (ml : fin l → M') : curry_fin_finset R M₂ M' hk hl f mk ml = f (λ i, sum.elim mk ml ((fin_sum_equiv_of_finset hk hl).symm i)) := rfl @[simp] lemma curry_fin_finset_symm_apply {k l n : ℕ} {s : finset (fin n)} [decidable_pred (s : set (fin n))] (hk : s.card = k) (hl : sᶜ.card = l) (f : multilinear_map R (λ x : fin k, M') (multilinear_map R (λ x : fin l, M') M₂)) (m : fin n → M') : (curry_fin_finset R M₂ M' hk hl).symm f m = f (λ i, m $ fin_sum_equiv_of_finset hk hl (sum.inl i)) (λ i, m $ fin_sum_equiv_of_finset hk hl (sum.inr i)) := rfl @[simp] lemma curry_fin_finset_symm_apply_piecewise_const {k l n : ℕ} {s : finset (fin n)} [decidable_pred (s : set (fin n))] (hk : s.card = k) (hl : sᶜ.card = l) (f : multilinear_map R (λ x : fin k, M') (multilinear_map R (λ x : fin l, M') M₂)) (x y : M') : (curry_fin_finset R M₂ M' hk hl).symm f (s.piecewise (λ _, x) (λ _, y)) = f (λ _, x) (λ _, y) := begin rw curry_fin_finset_symm_apply, congr, { ext i, rw [fin_sum_equiv_of_finset_inl, finset.piecewise_eq_of_mem], apply finset.order_emb_of_fin_mem }, { ext i, rw [fin_sum_equiv_of_finset_inr, finset.piecewise_eq_of_not_mem], exact finset.mem_compl.1 (finset.order_emb_of_fin_mem _ _ _) } end @[simp] lemma curry_fin_finset_symm_apply_const {k l n : ℕ} {s : finset (fin n)} [decidable_pred (s : set (fin n))] (hk : s.card = k) (hl : sᶜ.card = l) (f : multilinear_map R (λ x : fin k, M') (multilinear_map R (λ x : fin l, M') M₂)) (x : M') : (curry_fin_finset R M₂ M' hk hl).symm f (λ _, x) = f (λ _, x) (λ _, x) := rfl @[simp] lemma curry_fin_finset_apply_const {k l n : ℕ} {s : finset (fin n)} [decidable_pred (s : set (fin n))] (hk : s.card = k) (hl : sᶜ.card = l) (f : multilinear_map R (λ x : fin n, M') M₂) (x y : M') : curry_fin_finset R M₂ M' hk hl f (λ _, x) (λ _, y) = f (s.piecewise (λ _, x) (λ _, y)) := begin refine (curry_fin_finset_symm_apply_piecewise_const hk hl _ _ _).symm.trans _, -- `rw` fails rw linear_equiv.symm_apply_apply end end multilinear_map end currying section submodule variables {R M M₂} [ring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M'] [add_comm_monoid M₂] [∀i, module R (M₁ i)] [module R M'] [module R M₂] namespace multilinear_map /-- The pushforward of an indexed collection of submodule `p i ⊆ M₁ i` by `f : M₁ → M₂`. Note that this is not a submodule - it is not closed under addition. -/ def map [nonempty ι] (f : multilinear_map R M₁ M₂) (p : Π i, submodule R (M₁ i)) : sub_mul_action R M₂ := { carrier := f '' { v | ∀ i, v i ∈ p i}, smul_mem' := λ c _ ⟨x, hx, hf⟩, let ⟨i⟩ := ‹nonempty ι› in by { refine ⟨update x i (c • x i), λ j, if hij : j = i then _ else _, hf ▸ _⟩, { rw [hij, update_same], exact (p i).smul_mem _ (hx i) }, { rw [update_noteq hij], exact hx j }, { rw [f.map_smul, update_eq_self] } } } /-- The map is always nonempty. This lemma is needed to apply `sub_mul_action.zero_mem`. -/ lemma map_nonempty [nonempty ι] (f : multilinear_map R M₁ M₂) (p : Π i, submodule R (M₁ i)) : (map f p : set M₂).nonempty := ⟨f 0, 0, λ i, (p i).zero_mem, rfl⟩ /-- The range of a multilinear map, closed under scalar multiplication. -/ def range [nonempty ι] (f : multilinear_map R M₁ M₂) : sub_mul_action R M₂ := f.map (λ i, ⊤) end multilinear_map end submodule
5df98ac1d3a5579cb125798b9e3a164e446ee474
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/data/nat/fib.lean
6c5ac67cc3ec6ab04719ab7e50c14b5ea5c72acf
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,558
lean
/- Copyright (c) 2019 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import data.stream.basic import tactic import data.nat.gcd /-! # The Fibonacci Sequence ## Summary Definition of the Fibonacci sequence `F₀ = 0, F₁ = 1, Fₙ₊₂ = Fₙ + Fₙ₊₁`. ## Main Definitions - `fib` returns the stream of Fibonacci numbers. ## Main Statements - `fib_succ_succ` : shows that `fib` indeed satisfies the Fibonacci recurrence `Fₙ₊₂ = Fₙ + Fₙ₊₁.`. - `fib_gcd` : `fib n` is a strong divisibility sequence. ## Implementation Notes For efficiency purposes, the sequence is defined using `stream.iterate`. ## Tags fib, fibonacci -/ namespace nat /-- Auxiliary function used in the definition of `fib_aux_stream`. -/ private def fib_aux_step : (ℕ × ℕ) → (ℕ × ℕ) := λ p, ⟨p.snd, p.fst + p.snd⟩ /-- Auxiliary stream creating Fibonacci pairs `⟨Fₙ, Fₙ₊₁⟩`. -/ private def fib_aux_stream : stream (ℕ × ℕ) := stream.iterate fib_aux_step ⟨0, 1⟩ /-- Implementation of the fibonacci sequence satisfying `fib 0 = 0, fib 1 = 1, fib (n + 2) = fib n + fib (n + 1)`. *Note:* We use a stream iterator for better performance when compared to the naive recursive implementation. -/ @[pp_nodot] def fib (n : ℕ) : ℕ := (fib_aux_stream n).fst @[simp] lemma fib_zero : fib 0 = 0 := rfl @[simp] lemma fib_one : fib 1 = 1 := rfl @[simp] lemma fib_two : fib 2 = 1 := rfl private lemma fib_aux_stream_succ {n : ℕ} : fib_aux_stream (n + 1) = fib_aux_step (fib_aux_stream n) := begin change (stream.nth (n + 1) $ stream.iterate fib_aux_step ⟨0, 1⟩) = fib_aux_step (stream.nth n $ stream.iterate fib_aux_step ⟨0, 1⟩), rw [stream.nth_succ_iterate, stream.map_iterate, stream.nth_map] end /-- Shows that `fib` indeed satisfies the Fibonacci recurrence `Fₙ₊₂ = Fₙ + Fₙ₊₁.` -/ lemma fib_succ_succ {n : ℕ} : fib (n + 2) = fib n + fib (n + 1) := by simp only [fib, fib_aux_stream_succ, fib_aux_step] lemma fib_pos {n : ℕ} (n_pos : 0 < n) : 0 < fib n := begin induction n with n IH, case nat.zero { norm_num at n_pos }, case nat.succ { cases n, case nat.zero { simp [fib_succ_succ, zero_lt_one] }, case nat.succ { have : 0 ≤ fib n, by simp, exact (lt_add_of_nonneg_of_lt this $ IH n.succ_pos) }} end lemma fib_le_fib_succ {n : ℕ} : fib n ≤ fib (n + 1) := by { cases n; simp [fib_succ_succ] } @[mono] lemma fib_mono : monotone fib := monotone_of_monotone_nat $ λ _, fib_le_fib_succ lemma le_fib_self {n : ℕ} (five_le_n : 5 ≤ n) : n ≤ fib n := begin induction five_le_n with n five_le_n IH, { have : 5 = fib 5, by refl, -- 5 ≤ fib 5 exact le_of_eq this }, { -- n + 1 ≤ fib (n + 1) for 5 ≤ n cases n with n', -- rewrite n = succ n' to use fib.succ_succ { have : 5 = 0, from nat.le_zero_iff.elim_left five_le_n, contradiction }, rw fib_succ_succ, suffices : 1 + (n' + 1) ≤ fib n' + fib (n' + 1), by rwa [nat.succ_eq_add_one, add_comm], have : n' ≠ 0, by { intro h, have : 5 ≤ 1, by rwa h at five_le_n, norm_num at this }, have : 1 ≤ fib n', from nat.succ_le_of_lt (fib_pos $ pos_iff_ne_zero.mpr this), mono } end /-- Subsequent Fibonacci numbers are coprime, see https://proofwiki.org/wiki/Consecutive_Fibonacci_Numbers_are_Coprime -/ lemma fib_coprime_fib_succ (n : ℕ) : nat.coprime (fib n) (fib (n + 1)) := begin unfold coprime, induction n with n ih, { simp }, { convert ih using 1, rw [fib_succ_succ, succ_eq_add_one, gcd_rec, add_mod_right, gcd_comm (fib n), gcd_rec (fib (n + 1))], } end /-- See https://proofwiki.org/wiki/Fibonacci_Number_in_terms_of_Smaller_Fibonacci_Numbers -/ lemma fib_add (m n : ℕ) : fib m * fib n + fib (m + 1) * fib (n + 1) = fib (m + n + 1) := begin induction n with n ih generalizing m, { simp }, { intros, specialize ih (m + 1), rw [add_assoc m 1 n, add_comm 1 n] at ih, simp only [fib_succ_succ, ← ih], ring, } end lemma gcd_fib_add_self (m n : ℕ) : gcd (fib m) (fib (n + m)) = gcd (fib m) (fib n) := begin cases eq_zero_or_pos n, { rw h, simp }, replace h := nat.succ_pred_eq_of_pos h, rw [← h, succ_eq_add_one], calc gcd (fib m) (fib (n.pred + 1 + m)) = gcd (fib m) (fib (n.pred) * (fib m) + fib (n.pred + 1) * fib (m + 1)) : by { rw fib_add n.pred _, ring_nf } ... = gcd (fib m) (fib (n.pred + 1) * fib (m + 1)) : by rw [add_comm, gcd_add_mul_self (fib m) _ (fib (n.pred))] ... = gcd (fib m) (fib (n.pred + 1)) : coprime.gcd_mul_right_cancel_right (fib (n.pred + 1)) (coprime.symm (fib_coprime_fib_succ m)) end lemma gcd_fib_add_mul_self (m n : ℕ) : ∀ k, gcd (fib m) (fib (n + k * m)) = gcd (fib m) (fib n) | 0 := by simp | (k+1) := by rw [← gcd_fib_add_mul_self k, add_mul, ← add_assoc, one_mul, gcd_fib_add_self _ _] /-- `fib n` is a strong divisibility sequence, see https://proofwiki.org/wiki/GCD_of_Fibonacci_Numbers -/ lemma fib_gcd (m n : ℕ) : fib (gcd m n) = gcd (fib m) (fib n) := begin wlog h : m ≤ n using [n m, m n], exact le_total m n, { apply gcd.induction m n, { simp }, intros m n mpos h, rw ← gcd_rec m n at h, conv_rhs { rw ← mod_add_div' n m }, rwa [gcd_fib_add_mul_self m (n % m) (n / m), gcd_comm (fib m) _] }, rwa [gcd_comm, gcd_comm (fib m)] end lemma fib_dvd (m n : ℕ) (h : m ∣ n) : fib m ∣ fib n := by rwa [gcd_eq_left_iff_dvd, ← fib_gcd, gcd_eq_left_iff_dvd.mp] end nat
1f0515bcb9c37dd1869f68615709577aebe2efe7
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/tests/lean/run/def_brec3.lean
8621b27af7b8bba900cef61888dbc266a8ba8c18
[ "Apache-2.0" ]
permissive
pacchiano/lean
9324b33f3ac3b5c5647285160f9f6ea8d0d767dc
fdadada3a970377a6df8afcd629a6f2eab6e84e8
refs/heads/master
1,611,357,380,399
1,489,870,101,000
1,489,870,101,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
505
lean
open nat inductive bv : nat → Type | nil : bv 0 | cons : ∀ (n) (hd : bool) (tl : bv n), bv (succ n) open bv variable (f : bool → bool → bool) definition map2 : ∀ {n}, bv n → bv n → bv n | .0 nil nil := nil | .(n+1) (cons n b1 v1) (cons .n b2 v2) := cons n (f b1 b2) (map2 v1 v2) example : map2 f nil nil = nil := rfl example (n : nat) (b1 b2 : bool) (v1 v2 : bv n) : map2 f (cons n b1 v1) (cons n b2 v2) = cons n (f b1 b2) (map2 f v1 v2) := rfl #print map2
dbd7c1c7577bb97be2949e18f3aea981fa520c2d
f3be49eddff7edf577d3d3666e314d995f7a6357
/TBA/Exercises/Exercise2.lean
5b811fe79376e4417f8574733b8b0da0900c7882
[]
no_license
IPDSnelting/tba-2021
8b930bcd2f4aae44a2ddc86e72b77f84e6d46e82
b6390e55b768423d3266969e81d19290129c5914
refs/heads/master
1,686,754,693,583
1,625,135,602,000
1,625,136,365,000
355,124,341
50
7
null
1,625,133,762,000
1,617,699,824,000
Lean
UTF-8
Lean
false
false
2,494
lean
section variable (α : Type) (p q : α → Prop) (r : α → α → Prop) /- UNIVERSAL QUANTIFICATION -/ -- We can leave off `: α` if Lean can infer it (here via `p`/`q`) example : (∀ x, p x) → (∀ x, p x → q x) → (∀ x, q x) := _ -- The reverse direction of the slides example example : (∀ x, p x ∧ q x) → (∀ x, p x) ∧ (∀ x, q x) := _ -- TODO: Prove the corresponding forward/reverse lemma(s) for `∨` (that hold)! -- hint: input `∀` as `\all` -- We can bind multiple variables in a single `∀` example : (∀ x y, r x y) → (∀ y x, r x y) := _ /- EXISTENTIAL QUANTIFICATION -/ /- Interestingly, in contrast to the universal quantifier, the existential quantifier is not primitive but can be specified as an inductive type: ``` inductive Exists (p : α → Prop) : Prop where | intro (w : α) (h : p w) : Exists p ``` That is, `Exists.intro` takes/offers a "witness" and a proof that the predicate holds for the witness. Instead of `Exists (fun x => p x)`, we can also write `∃ x, p x` (input `∃` as `\ex`). -/ example : (∃ x, p x ∧ q x) → (∃ x, p x) ∧ (∃ x, q x) := _ example : ¬(∃ x, p x) → (∀ x, ¬ p x) := _ example : (∀ x, ¬ p x) → ¬(∃ x, p x) := _ example : (∃ x, ¬ p x) → ¬ (∀ x, p x) := _ section open Classical -- The following example can only be solved using the classical axioms -- This one is pretty tricky again, don't feel bad about skipping it -- hint: use the following helper theorem that can be derived from `em`: #check byContradiction -- hint: you may even need to use it more than once example : ¬(∀ x, p x) → (∃ x, ¬ p x) := _ end -- TODO: Decide for yourself what variables you need to model and prove the following -- important real-world observation, which is sometimes called "drinker paradox": -- "If there is at least one person in the pub, then there is someone in the pub such that, -- if (s)he is drinking, then everyone in the pub is drinking." -- hint: you can define "is in pub" either as a predicate variable on a "Person" type (`(Person : Type)`), -- or, more simply, directly as a type "Occupant" since we are not interested in persons outside the pub -- hint: you might need classical logic again section Drinker end Drinker /- EQUALITY -/ example : ∀ a b c : α, a = b → b = c → a = c := _ example : ∀ a : α, ∃ b : α, b = a := _ -- "`Eq` is the least reflexive relation" example : (∀ a, r a a) → (∀ a b, a = b → r a b) := _ end
41514ce2035834087b0e0678c58fe147f27e01d9
5ee26964f602030578ef0159d46145dd2e357ba5
/src/for_mathlib/sheaves/presheaf_of_rings.lean
d7495e1c0d61b600b1cf7f3b4c1057a6882dacec
[ "Apache-2.0" ]
permissive
fpvandoorn/lean-perfectoid-spaces
569b4006fdfe491ca8b58dd817bb56138ada761f
06cec51438b168837fc6e9268945735037fd1db6
refs/heads/master
1,590,154,571,918
1,557,685,392,000
1,557,685,392,000
186,363,547
0
0
Apache-2.0
1,557,730,933,000
1,557,730,933,000
null
UTF-8
Lean
false
false
1,538
lean
/- Presheaf of rings. https://stacks.math.columbia.edu/tag/006N Author: Ramon Fernandez Mir -/ import for_mathlib.sheaves.presheaf universes u v -- Definition of a presheaf of rings. structure presheaf_of_rings (α : Type u) [topological_space α] extends presheaf α := (Fring : ∀ (U), comm_ring (F U)) (res_is_ring_hom : ∀ (U V) (HVU : V ⊆ U), is_ring_hom (res U V HVU)) instance {α : Type u} [topological_space α] : has_coe (presheaf_of_rings α) (presheaf α) := ⟨λ F, F.to_presheaf⟩ attribute [instance] presheaf_of_rings.Fring attribute [instance] presheaf_of_rings.res_is_ring_hom instance presheaf_of_rings.comm_ring {α : Type u} [topological_space α] (F : presheaf_of_rings α) (U : topological_space.opens α) : comm_ring (F U) := F.Fring U namespace presheaf_of_rings variables {α : Type u} {β : Type v} [topological_space α] [topological_space β] -- Morphism of presheaf of rings. structure morphism (F G : presheaf_of_rings α) extends presheaf.morphism F.to_presheaf G.to_presheaf := (ring_homs : ∀ (U), is_ring_hom (map U)) infix `⟶`:80 := morphism def identity (F : presheaf_of_rings α) : F ⟶ F := { ring_homs := λ U, is_ring_hom.id, ..presheaf.id F.to_presheaf } -- Isomorphic presheaves of rings. structure iso (F G : presheaf_of_rings α) := (mor : F ⟶ G) (inv : G ⟶ F) (mor_inv_id : mor.to_morphism ⊚ inv.to_morphism = presheaf.id F.to_presheaf) (inv_mor_id : inv.to_morphism ⊚ mor.to_morphism = presheaf.id G.to_presheaf) end presheaf_of_rings
dd27a5c58fd1996488d014cbd5026166868d4c72
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Init/Data/Nat/Gcd.lean
fbfef6746a6f628f0bbdc898534275b81a3281f8
[ "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
945
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.Nat.Div namespace Nat private def gcdF (x : Nat) : (∀ x₁, x₁ < x → Nat → Nat) → Nat → Nat := match x with | 0 => fun _ y => y | succ x => fun f y => f (y % succ x) (mod_lt _ (zero_lt_succ _)) (succ x) @[extern "lean_nat_gcd"] def gcd (a b : @& Nat) : Nat := WellFounded.fix (measure id).wf gcdF a b @[simp] theorem gcd_zero_left (y : Nat) : gcd 0 y = y := rfl theorem gcd_succ (x y : Nat) : gcd (succ x) y = gcd (y % succ x) (succ x) := rfl @[simp] theorem gcd_one_left (n : Nat) : gcd 1 n = 1 := by rw [gcd_succ, mod_one] rfl @[simp] theorem gcd_zero_right (n : Nat) : gcd n 0 = n := by cases n <;> simp [gcd_succ] @[simp] theorem gcd_self (n : Nat) : gcd n n = n := by cases n <;> simp [gcd_succ] end Nat
2f6de9f4657f4d8894b55865999e89c8a351afbd
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/group_theory/subgroup/zpowers.lean
f3456efdf70d39e2fa7307985ff1256931ca09f9
[ "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
6,753
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 group_theory.subgroup.basic /-! # Subgroups generated by an element > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Tags subgroup, subgroups -/ variables {G : Type*} [group G] variables {A : Type*} [add_group A] variables {N : Type*} [group N] namespace subgroup /-- The subgroup generated by an element. -/ def zpowers (g : G) : subgroup G := subgroup.copy (zpowers_hom G g).range (set.range ((^) g : ℤ → G)) rfl @[simp] lemma mem_zpowers (g : G) : g ∈ zpowers g := ⟨1, zpow_one _⟩ @[norm_cast] lemma coe_zpowers (g : G) : ↑(zpowers g) = set.range (λ n : ℤ, g ^ n) := rfl lemma zpowers_eq_closure (g : G) : zpowers g = closure {g} := by { ext, exact mem_closure_singleton.symm } @[simp] lemma range_zpowers_hom (g : G) : (zpowers_hom G g).range = zpowers g := rfl lemma mem_zpowers_iff {g h : G} : h ∈ zpowers g ↔ ∃ (k : ℤ), g ^ k = h := iff.rfl @[simp] lemma zpow_mem_zpowers (g : G) (k : ℤ) : g^k ∈ zpowers g := mem_zpowers_iff.mpr ⟨k, rfl⟩ @[simp] lemma npow_mem_zpowers (g : G) (k : ℕ) : g^k ∈ zpowers g := (zpow_coe_nat g k) ▸ zpow_mem_zpowers g k @[simp] lemma forall_zpowers {x : G} {p : zpowers x → Prop} : (∀ g, p g) ↔ ∀ m : ℤ, p ⟨x ^ m, m, rfl⟩ := set.forall_subtype_range_iff @[simp] lemma exists_zpowers {x : G} {p : zpowers x → Prop} : (∃ g, p g) ↔ ∃ m : ℤ, p ⟨x ^ m, m, rfl⟩ := set.exists_subtype_range_iff lemma forall_mem_zpowers {x : G} {p : G → Prop} : (∀ g ∈ zpowers x, p g) ↔ ∀ m : ℤ, p (x ^ m) := set.forall_range_iff lemma exists_mem_zpowers {x : G} {p : G → Prop} : (∃ g ∈ zpowers x, p g) ↔ ∃ m : ℤ, p (x ^ m) := set.exists_range_iff instance (a : G) : countable (zpowers a) := ((zpowers_hom G a).range_restrict_surjective.comp multiplicative.of_add.surjective).countable end subgroup namespace add_subgroup /-- The subgroup generated by an element. -/ def zmultiples (a : A) : add_subgroup A := add_subgroup.copy (zmultiples_hom A a).range (set.range ((• a) : ℤ → A)) rfl @[simp] lemma range_zmultiples_hom (a : A) : (zmultiples_hom A a).range = zmultiples a := rfl attribute [to_additive add_subgroup.zmultiples] subgroup.zpowers attribute [to_additive add_subgroup.mem_zmultiples] subgroup.mem_zpowers attribute [to_additive add_subgroup.coe_zmultiples] subgroup.coe_zpowers attribute [to_additive add_subgroup.zmultiples_eq_closure] subgroup.zpowers_eq_closure attribute [to_additive add_subgroup.range_zmultiples_hom] subgroup.range_zpowers_hom attribute [to_additive add_subgroup.mem_zmultiples_iff] subgroup.mem_zpowers_iff attribute [to_additive add_subgroup.zsmul_mem_zmultiples] subgroup.zpow_mem_zpowers attribute [to_additive add_subgroup.nsmul_mem_zmultiples] subgroup.npow_mem_zpowers attribute [to_additive add_subgroup.forall_zmultiples] subgroup.forall_zpowers attribute [to_additive add_subgroup.forall_mem_zmultiples] subgroup.forall_mem_zpowers attribute [to_additive add_subgroup.exists_zmultiples] subgroup.exists_zpowers attribute [to_additive add_subgroup.exists_mem_zmultiples] subgroup.exists_mem_zpowers instance (a : A) : countable (zmultiples a) := (zmultiples_hom A a).range_restrict_surjective.countable section ring variables {R : Type*} [ring R] (r : R) (k : ℤ) @[simp] lemma int_cast_mul_mem_zmultiples : ↑(k : ℤ) * r ∈ zmultiples r := by simpa only [← zsmul_eq_mul] using zsmul_mem_zmultiples r k @[simp] lemma int_cast_mem_zmultiples_one : ↑(k : ℤ) ∈ zmultiples (1 : R) := mem_zmultiples_iff.mp ⟨k, by simp⟩ end ring end add_subgroup @[simp, to_additive map_zmultiples] lemma monoid_hom.map_zpowers (f : G →* N) (x : G) : (subgroup.zpowers x).map f = subgroup.zpowers (f x) := by rw [subgroup.zpowers_eq_closure, subgroup.zpowers_eq_closure, f.map_closure, set.image_singleton] lemma int.mem_zmultiples_iff {a b : ℤ} : b ∈ add_subgroup.zmultiples a ↔ a ∣ b := exists_congr (λ k, by rw [mul_comm, eq_comm, ← smul_eq_mul]) lemma of_mul_image_zpowers_eq_zmultiples_of_mul { x : G } : additive.of_mul '' ((subgroup.zpowers x) : set G) = add_subgroup.zmultiples (additive.of_mul x) := begin ext y, split, { rintro ⟨z, ⟨m, hm⟩, hz2⟩, use m, simp only, rwa [← of_mul_zpow, hm] }, { rintros ⟨n, hn⟩, refine ⟨x ^ n, ⟨n, rfl⟩, _⟩, rwa of_mul_zpow } end lemma of_add_image_zmultiples_eq_zpowers_of_add {x : A} : multiplicative.of_add '' ((add_subgroup.zmultiples x) : set A) = subgroup.zpowers (multiplicative.of_add x) := begin symmetry, rw equiv.eq_image_iff_symm_image_eq, exact of_mul_image_zpowers_eq_zmultiples_of_mul, end namespace subgroup variables {s : set G} {g : G} @[to_additive zmultiples_is_commutative] instance zpowers_is_commutative (g : G) : (zpowers g).is_commutative := ⟨⟨λ ⟨_, _, h₁⟩ ⟨_, _, h₂⟩, by rw [subtype.ext_iff, coe_mul, coe_mul, subtype.coe_mk, subtype.coe_mk, ←h₁, ←h₂, zpow_mul_comm]⟩⟩ @[simp, to_additive zmultiples_le] lemma zpowers_le {g : G} {H : subgroup G} : zpowers g ≤ H ↔ g ∈ H := by rw [zpowers_eq_closure, closure_le, set.singleton_subset_iff, set_like.mem_coe] alias zpowers_le ↔ _ zpowers_le_of_mem alias add_subgroup.zmultiples_le ↔ _ _root_.add_subgroup.zmultiples_le_of_mem attribute [to_additive zmultiples_le_of_mem] zpowers_le_of_mem @[simp, to_additive zmultiples_eq_bot] lemma zpowers_eq_bot {g : G} : zpowers g = ⊥ ↔ g = 1 := by rw [eq_bot_iff, zpowers_le, mem_bot] @[to_additive zmultiples_ne_bot] lemma zpowers_ne_bot : zpowers g ≠ ⊥ ↔ g ≠ 1 := zpowers_eq_bot.not @[simp, to_additive zmultiples_zero_eq_bot] lemma zpowers_one_eq_bot : subgroup.zpowers (1 : G) = ⊥ := subgroup.zpowers_eq_bot.mpr rfl @[to_additive] lemma centralizer_closure (S : set G) : centralizer (closure S : set G) = ⨅ g ∈ S, centralizer (zpowers g : set G) := le_antisymm (le_infi $ λ g, le_infi $ λ hg, centralizer_le $ set_like.coe_subset_coe.2 $ zpowers_le.2 $ subset_closure hg) $ le_centralizer_iff.1 $ (closure_le _).2 $ λ g, set_like.mem_coe.2 ∘ zpowers_le.1 ∘ le_centralizer_iff.1 ∘ infi_le_of_le g ∘ infi_le _ @[to_additive] lemma center_eq_infi (S : set G) (hS : closure S = ⊤) : center G = ⨅ g ∈ S, centralizer (zpowers g) := by rw [←centralizer_univ, ←coe_top, ←hS, centralizer_closure] @[to_additive] lemma center_eq_infi' (S : set G) (hS : closure S = ⊤) : center G = ⨅ g : S, centralizer (zpowers (g : G) : set G) := by rw [center_eq_infi S hS, ←infi_subtype''] end subgroup
f464fc0ca5f3738d4f45d929d1cb262827d923be
5e60919d574b821fabd9387be5589c0c4d3f3fe2
/src/language/unitb/parser.lean
f2238196ddac7f3bb1f12cd2c5d5b09c42e6360b
[]
no_license
unitb/unitb-pointers
3fc72b873377a12e3f677ccd30143fc001a56c63
c057420c1e72bba00181bc6db30cf369ef2bfd23
refs/heads/master
1,629,969,967,065
1,511,386,892,000
1,511,386,892,000
110,323,164
0
0
null
null
null
null
UTF-8
Lean
false
false
1,234
lean
import meta.declaration import meta.tactic import unitb.models.pointers.basic import language.unitb.obligations import language.unitb.semantics import language.unitb.syntax import language.unitb.scope import util.control.applicative import util.control.monad import util.data.generic universes u v w k namespace unitb.parser open lean lean.parser open interactive.types open interactive open list tactic applicative open tactic.interactive meta def expr.local_consts (e : expr) : list expr := e.fold [ ] (λ e i xs, if e.is_local_constant then e :: xs else xs) open lean (parser) monad (mmap₂) predicate @[user_command] meta def unitb_machine (meta_info : decl_meta_info) (_ : parse $ tk "machine") : parser unit := do n ← ident, updateex_env $ λ e₀, return $ e₀.add_namespace n, s ← variable_decl n, invs ← invariant_section s, init ← init_section s, sch ← event_section s, pos ← mk_proof_obligations s init invs, proof_section s pos, mk_machine_spec n sch, mk_machine_correctness n, tk "end" end unitb.parser precedence `initialization` : 0 precedence `invariants` : 0 precedence `events` : 0 precedence `when` : 0 precedence `proofs` : 0 notation when := _root_.when
fc5e72c08b9981bfccc3e89c06494e802c2e8359
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/tests/lean/run/macro.lean
c4b69e4da6ea2e21e4798035e9a688992b635abc
[ "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
1,205
lean
abbrev Set (α : Type) := α → Prop axiom setOf {α : Type} : (α → Prop) → Set α axiom mem {α : Type} : α → Set α → Prop axiom univ {α : Type} : Set α axiom Union {α : Type} : Set (Set α) → Set α syntax:100 term " ∈ " term:99 : term macro_rules | `($x ∈ $s) => `(mem $x $s) declare_syntax_cat index syntax term : index syntax term "≤" ident "<" term : index syntax ident ":" term : index syntax "{" index " | " term "}" : term macro_rules | `({$l:term ≤ $x:ident < $u | $p}) => `(setOf (fun $x:ident => $l ≤ $x:ident ∧ $x:ident < $u ∧ $p)) | `({$x:ident : $t | $p}) => `(setOf (fun ($x:ident : $t) => $p)) | `({$x:term ∈ $s | $p}) => `(setOf (fun $x => $x ∈ $s ∧ $p)) | `({$x:term ≤ $e | $p}) => `(setOf (fun $x => $x ≤ $e ∧ $p)) | `({$b:term | $r}) => `(setOf (fun $b => $r)) #check { 1 ≤ x < 10 | x ≠ 5 } #check { f : Nat → Nat | f 1 > 0 } syntax "⋃ " term ", " term : term macro_rules | `(⋃ $b, $r) => `(Union {$b:term | $r}) #check ⋃ x, x = x #check ⋃ (x : Set Unit), x = x #check ⋃ x ∈ univ, x = x syntax "#check2" term : command macro_rules | `(#check2 $e) => `(#check $e #check $e) #check2 1
e8cc6bc6e17ce81020dc96b6ed2a8f3860d3da1b
da3a76c514d38801bae19e8a9e496dc31f8e5866
/library/init/data/default.lean
edbab1e2c38ab419a9ec99d591b182aed92ee4d7
[ "Apache-2.0" ]
permissive
cipher1024/lean
270c1ac5781e6aee12f5c8d720d267563a164beb
f5cbdff8932dd30c6dd8eec68f3059393b4f8b3a
refs/heads/master
1,611,223,459,029
1,487,566,573,000
1,487,566,573,000
83,356,543
0
0
null
1,488,229,336,000
1,488,229,336,000
null
UTF-8
Lean
false
false
325
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.data.basic init.data.sigma init.data.nat init.data.char init.data.string import init.data.list init.data.sum init.data.subtype init.data.int
29a6eb9e3242009879b1af91a6b0e7272b89f2de
63abd62053d479eae5abf4951554e1064a4c45b4
/archive/imo/imo1962_q1.lean
7fd1d442e6c5d028d59f0d9dfdbd6896c9a7dff9
[ "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
5,435
lean
/- Copyright (c) 2020 Kevin Lacker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Lacker -/ import data.nat.digits /-! # IMO 1962 Q1 Find the smallest natural number $n$ which has the following properties: (a) Its decimal representation has 6 as the last digit. (b) If the last digit 6 is erased and placed in front of the remaining digits, the resulting number is four times as large as the original number $n$. Since Lean does not explicitly express problems of the form "find the smallest number satisfying X", we define the problem as a predicate, and then prove a particular number is the smallest member of a set satisfying it. -/ open nat def problem_predicate (n : ℕ) : Prop := (digits 10 n).head = 6 ∧ of_digits 10 ((digits 10 n).tail.concat 6) = 4 * n /-! First, it's inconvenient to work with digits, so let's simplify them out of the problem. -/ abbreviation problem_predicate' (c n : ℕ) : Prop := n = 10 * c + 6 ∧ 6 * 10 ^ (digits 10 c).length + c = 4 * n lemma without_digits {n : ℕ} (h1 : problem_predicate n) : ∃ c : ℕ, problem_predicate' c n := begin use n / 10, cases n, { have h2 : ¬ problem_predicate 0, by norm_num [problem_predicate], contradiction }, { rw [problem_predicate, digits_def' (dec_trivial : 2 ≤ 10) n.succ_pos, list.head, list.tail_cons, list.concat_eq_append] at h1, split, { rw [← h1.left, add_comm, mod_add_div (n+1) 10], }, { rw [← h1.right, of_digits_append, of_digits_digits, of_digits_singleton, add_comm, mul_comm], }, }, end /-! Now we can eliminate possibilities for `(digits 10 c).length` until we get to the one that works. -/ lemma case_0_digit {c n : ℕ} (h1 : (digits 10 c).length = 0) : ¬ problem_predicate' c n := begin intro h2, have h3 : 6 * 10 ^ 0 + c = 6 * 10 ^ (digits 10 c).length + c, by rw h1, have h4 : 6 * 10 ^ 0 + c = 4 * (10 * c + 6), by rw [h3, h2.right, h2.left], linarith, end lemma case_1_digit {c n : ℕ} (h1 : (digits 10 c).length = 1) : ¬ problem_predicate' c n := begin intro h2, have h3 : 6 * 10 ^ 1 + c = 6 * 10 ^ (digits 10 c).length + c, by rw h1, have h4 : 6 * 10 ^ 1 + c = 4 * (10 * c + 6), by rw [h3, h2.right, h2.left], have h6 : c > 0, by linarith, linarith, end lemma case_2_digit {c n : ℕ} (h1 : (digits 10 c).length = 2) : ¬ problem_predicate' c n := begin intro h2, have h3 : 6 * 10 ^ 2 + c = 6 * 10 ^ (digits 10 c).length + c, by rw h1, have h4 : 6 * 10 ^ 2 + c = 4 * (10 * c + 6), by rw [h3, h2.right, h2.left], have h5 : c > 14, by linarith, linarith end lemma case_3_digit {c n : ℕ} (h1 : (digits 10 c).length = 3) : ¬ problem_predicate' c n := begin intro h2, have h3 : 6 * 10 ^ 3 + c = 6 * 10 ^ (digits 10 c).length + c, by rw h1, have h4 : 6 * 10 ^ 3 + c = 4 * (10 * c + 6), by rw [h3, h2.right, h2.left], have h5 : c > 153, by linarith, linarith end lemma case_4_digit {c n : ℕ} (h1 : (digits 10 c).length = 4) : ¬ problem_predicate' c n := begin intro h2, have h3 : 6 * 10 ^ 4 + c = 6 * 10 ^ (digits 10 c).length + c, by rw h1, have h4 : 6 * 10 ^ 4 + c = 4 * (10 * c + 6), by rw [h3, h2.right, h2.left], have h5 : c > 1537, by linarith, linarith end /-- Putting this inline causes a deep recursion error, so we separate it out. -/ lemma helper_5_digit {c : ℤ} (h : 6 * 10 ^ 5 + c = 4 * (10 * c + 6)) : c = 15384 := by linarith lemma case_5_digit {c n : ℕ} (h1 : (digits 10 c).length = 5) (h2 : problem_predicate' c n) : c = 15384 := begin have h3 : 6 * 10 ^ 5 + c = 6 * 10 ^ (digits 10 c).length + c, by rw h1, have h4 : 6 * 10 ^ 5 + c = 4 * (10 * c + 6), by rw [h3, h2.right, h2.left], zify at *, exact helper_5_digit h4 end /-- `linarith` fails on numbers this large, so this lemma spells out some of the arithmetic that normally would be automated. -/ lemma case_more_digits {c n : ℕ} (h1 : (digits 10 c).length ≥ 6) (h2 : problem_predicate' c n) : n ≥ 153846 := begin have h3 : c ≠ 0, { intro h4, have h5 : (digits 10 c).length = 0, by simp [h4], exact case_0_digit h5 h2 }, have h6 : 2 ≤ 10, from dec_trivial, calc n ≥ 10 * c : le.intro h2.left.symm ... ≥ 10 ^ (digits 10 c).length : base_pow_length_digits_le 10 c h6 h3 ... ≥ 10 ^ 6 : (pow_le_iff_le_right h6).mpr h1 ... ≥ 153846 : by norm_num, end /-! Now we combine these cases to show that 153846 is the smallest solution. -/ lemma satisfied_by_153846 : problem_predicate 153846 := by norm_num [problem_predicate, digits_def', of_digits] lemma no_smaller_solutions (n : ℕ) (h1 : problem_predicate n) : n ≥ 153846 := begin cases without_digits h1 with c h2, have h3 : (digits 10 c).length < 6 ∨ (digits 10 c).length ≥ 6, by apply lt_or_ge, cases h3, case or.inr { exact case_more_digits h3 h2, }, case or.inl { interval_cases (digits 10 c).length with h, { exfalso, exact case_0_digit h h2 }, { exfalso, exact case_1_digit h h2 }, { exfalso, exact case_2_digit h h2 }, { exfalso, exact case_3_digit h h2 }, { exfalso, exact case_4_digit h h2 }, { have h4 : c = 15384, from case_5_digit h h2, have h5 : n = 10 * 15384 + 6, from h4 ▸ h2.left, norm_num at h5, exact h5.ge, }, }, end theorem imo1962_q1 : is_least {n | problem_predicate n} 153846 := ⟨satisfied_by_153846, no_smaller_solutions⟩
451e1d476afdb7924b250b3eebb32c9500e4f955
6b7c9c6393bac7cb1c64582a1c62597e24f5bb80
/src/tactic/autoname/default.lean
1acb2e7c89e70aeb6fde65a7eaa0665aee77ac4c
[ "Apache-2.0" ]
permissive
alreadydone/lean-gptf
56a7d9cbd9400af72fb143d60c8774b8cfbc09cb
b4ab1eb2da0178f3dcdc49771d9fed6b50e35d98
refs/heads/master
1,679,371,993,063
1,614,479,778,000
1,614,479,778,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
32
lean
import tactic.autoname.autoname
fa3cf688e5d6c9bcff8cb491effc949de5124cf1
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/geometry/euclidean/basic.lean
17e595e16e518b28f0406263df2b25511b2c7377
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
56,072
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers, Manuel Candales -/ import analysis.inner_product_space.projection import analysis.special_functions.trigonometric.inverse import algebra.quadratic_discriminant import linear_algebra.affine_space.finite_dimensional import analysis.calculus.conformal.normed_space /-! # Euclidean spaces This file makes some definitions and proves very basic geometrical results about real inner product spaces and Euclidean affine spaces. Results about real inner product spaces that involve the norm and inner product but not angles generally go in `analysis.normed_space.inner_product`. Results with longer proofs or more geometrical content generally go in separate files. ## Main definitions * `inner_product_geometry.angle` is the undirected angle between two vectors. * `euclidean_geometry.angle`, with notation `∠`, is the undirected angle determined by three points. * `euclidean_geometry.orthogonal_projection` is the orthogonal projection of a point onto an affine subspace. * `euclidean_geometry.reflection` is the reflection of a point in an affine subspace. ## Implementation notes To declare `P` as the type of points in a Euclidean affine space with `V` as the type of vectors, use `[inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P]`. This works better with `out_param` to make `V` implicit in most cases than having a separate type alias for Euclidean affine spaces. Rather than requiring Euclidean affine spaces to be finite-dimensional (as in the definition on Wikipedia), this is specified only for those theorems that need it. ## References * https://en.wikipedia.org/wiki/Euclidean_space -/ noncomputable theory open_locale big_operators open_locale classical open_locale real open_locale real_inner_product_space namespace inner_product_geometry /-! ### Geometrical results on real inner product spaces This section develops some geometrical definitions and results on real inner product spaces, where those definitions and results can most conveniently be developed in terms of vectors and then used to deduce corresponding results for Euclidean affine spaces. -/ variables {V : Type*} [inner_product_space ℝ V] /-- The undirected angle between two vectors. If either vector is 0, this is π/2. -/ def angle (x y : V) : ℝ := real.arccos (inner x y / (∥x∥ * ∥y∥)) lemma is_conformal_map.preserves_angle {E F : Type*} [inner_product_space ℝ E] [inner_product_space ℝ F] {f' : E →L[ℝ] F} (h : is_conformal_map f') (u v : E) : angle (f' u) (f' v) = angle u v := begin obtain ⟨c, hc, li, hcf⟩ := h, suffices : c * (c * inner u v) / (∥c∥ * ∥u∥ * (∥c∥ * ∥v∥)) = inner u v / (∥u∥ * ∥v∥), { simp [this, angle, hcf, norm_smul, inner_smul_left, inner_smul_right] }, by_cases hu : ∥u∥ = 0, { simp [norm_eq_zero.mp hu] }, by_cases hv : ∥v∥ = 0, { simp [norm_eq_zero.mp hv] }, have hc : ∥c∥ ≠ 0 := λ w, hc (norm_eq_zero.mp w), field_simp, have : c * c = ∥c∥ * ∥c∥ := by simp [real.norm_eq_abs, abs_mul_abs_self], convert congr_arg (λ x, x * ⟪u, v⟫ * ∥u∥ * ∥v∥) this using 1; ring, end /-- If a real differentiable map `f` is conformal at a point `x`, then it preserves the angles at that point. -/ lemma conformal_at.preserves_angle {E F : Type*} [inner_product_space ℝ E] [inner_product_space ℝ F] {f : E → F} {x : E} {f' : E →L[ℝ] F} (h : has_fderiv_at f f' x) (H : conformal_at f x) (u v : E) : angle (f' u) (f' v) = angle u v := let ⟨f₁, h₁, c⟩ := H in h₁.unique h ▸ is_conformal_map.preserves_angle c u v /-- The cosine of the angle between two vectors. -/ lemma cos_angle (x y : V) : real.cos (angle x y) = inner x y / (∥x∥ * ∥y∥) := real.cos_arccos (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1 (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2 /-- The angle between two vectors does not depend on their order. -/ lemma angle_comm (x y : V) : angle x y = angle y x := begin unfold angle, rw [real_inner_comm, mul_comm] end /-- The angle between the negation of two vectors. -/ @[simp] lemma angle_neg_neg (x y : V) : angle (-x) (-y) = angle x y := begin unfold angle, rw [inner_neg_neg, norm_neg, norm_neg] end /-- The angle between two vectors is nonnegative. -/ lemma angle_nonneg (x y : V) : 0 ≤ angle x y := real.arccos_nonneg _ /-- The angle between two vectors is at most π. -/ lemma angle_le_pi (x y : V) : angle x y ≤ π := real.arccos_le_pi _ /-- The angle between a vector and the negation of another vector. -/ lemma angle_neg_right (x y : V) : angle x (-y) = π - angle x y := begin unfold angle, rw [←real.arccos_neg, norm_neg, inner_neg_right, neg_div] end /-- The angle between the negation of a vector and another vector. -/ lemma angle_neg_left (x y : V) : angle (-x) y = π - angle x y := by rw [←angle_neg_neg, neg_neg, angle_neg_right] /-- The angle between the zero vector and a vector. -/ @[simp] lemma angle_zero_left (x : V) : angle 0 x = π / 2 := begin unfold angle, rw [inner_zero_left, zero_div, real.arccos_zero] end /-- The angle between a vector and the zero vector. -/ @[simp] lemma angle_zero_right (x : V) : angle x 0 = π / 2 := begin unfold angle, rw [inner_zero_right, zero_div, real.arccos_zero] end /-- The angle between a nonzero vector and itself. -/ @[simp] lemma angle_self {x : V} (hx : x ≠ 0) : angle x x = 0 := begin unfold angle, rw [←real_inner_self_eq_norm_sq, div_self (λ h, hx (inner_self_eq_zero.1 h)), real.arccos_one] end /-- The angle between a nonzero vector and its negation. -/ @[simp] lemma angle_self_neg_of_nonzero {x : V} (hx : x ≠ 0) : angle x (-x) = π := by rw [angle_neg_right, angle_self hx, sub_zero] /-- The angle between the negation of a nonzero vector and that vector. -/ @[simp] lemma angle_neg_self_of_nonzero {x : V} (hx : x ≠ 0) : angle (-x) x = π := by rw [angle_comm, angle_self_neg_of_nonzero hx] /-- The angle between a vector and a positive multiple of a vector. -/ @[simp] lemma angle_smul_right_of_pos (x y : V) {r : ℝ} (hr : 0 < r) : angle x (r • y) = angle x y := begin unfold angle, rw [inner_smul_right, norm_smul, real.norm_eq_abs, abs_of_nonneg (le_of_lt hr), ←mul_assoc, mul_comm _ r, mul_assoc, mul_div_mul_left _ _ (ne_of_gt hr)] end /-- The angle between a positive multiple of a vector and a vector. -/ @[simp] lemma angle_smul_left_of_pos (x y : V) {r : ℝ} (hr : 0 < r) : angle (r • x) y = angle x y := by rw [angle_comm, angle_smul_right_of_pos y x hr, angle_comm] /-- The angle between a vector and a negative multiple of a vector. -/ @[simp] lemma angle_smul_right_of_neg (x y : V) {r : ℝ} (hr : r < 0) : angle x (r • y) = angle x (-y) := by rw [←neg_neg r, neg_smul, angle_neg_right, angle_smul_right_of_pos x y (neg_pos_of_neg hr), angle_neg_right] /-- The angle between a negative multiple of a vector and a vector. -/ @[simp] lemma angle_smul_left_of_neg (x y : V) {r : ℝ} (hr : r < 0) : angle (r • x) y = angle (-x) y := by rw [angle_comm, angle_smul_right_of_neg y x hr, angle_comm] /-- The cosine of the angle between two vectors, multiplied by the product of their norms. -/ lemma cos_angle_mul_norm_mul_norm (x y : V) : real.cos (angle x y) * (∥x∥ * ∥y∥) = inner x y := begin rw [cos_angle, div_mul_cancel_of_imp], simp [or_imp_distrib] { contextual := tt }, end /-- The sine of the angle between two vectors, multiplied by the product of their norms. -/ lemma sin_angle_mul_norm_mul_norm (x y : V) : real.sin (angle x y) * (∥x∥ * ∥y∥) = real.sqrt (inner x x * inner y y - inner x y * inner x y) := begin unfold angle, rw [real.sin_arccos (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1 (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2, ←real.sqrt_mul_self (mul_nonneg (norm_nonneg x) (norm_nonneg y)), ←real.sqrt_mul' _ (mul_self_nonneg _), sq, real.sqrt_mul_self (mul_nonneg (norm_nonneg x) (norm_nonneg y)), real_inner_self_eq_norm_sq, real_inner_self_eq_norm_sq], by_cases h : (∥x∥ * ∥y∥) = 0, { rw [(show ∥x∥ * ∥x∥ * (∥y∥ * ∥y∥) = (∥x∥ * ∥y∥) * (∥x∥ * ∥y∥), by ring), h, mul_zero, mul_zero, zero_sub], cases eq_zero_or_eq_zero_of_mul_eq_zero h with hx hy, { rw norm_eq_zero at hx, rw [hx, inner_zero_left, zero_mul, neg_zero] }, { rw norm_eq_zero at hy, rw [hy, inner_zero_right, zero_mul, neg_zero] } }, { field_simp [h], ring_nf, ring_nf, } end /-- The angle between two vectors is zero if and only if they are nonzero and one is a positive multiple of the other. -/ lemma angle_eq_zero_iff {x y : V} : angle x y = 0 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), 0 < r ∧ y = r • x) := begin rw [angle, ← real_inner_div_norm_mul_norm_eq_one_iff, real.arccos_eq_zero, has_le.le.le_iff_eq, eq_comm], exact (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2 end /-- The angle between two vectors is π if and only if they are nonzero and one is a negative multiple of the other. -/ lemma angle_eq_pi_iff {x y : V} : angle x y = π ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r < 0 ∧ y = r • x) := begin rw [angle, ← real_inner_div_norm_mul_norm_eq_neg_one_iff, real.arccos_eq_pi, has_le.le.le_iff_eq], exact (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1 end /-- If the angle between two vectors is π, the angles between those vectors and a third vector add to π. -/ lemma angle_add_angle_eq_pi_of_angle_eq_pi {x y : V} (z : V) (h : angle x y = π) : angle x z + angle y z = π := begin rcases angle_eq_pi_iff.1 h with ⟨hx, ⟨r, ⟨hr, rfl⟩⟩⟩, rw [angle_smul_left_of_neg x z hr, angle_neg_left, add_sub_cancel'_right] end /-- Two vectors have inner product 0 if and only if the angle between them is π/2. -/ lemma inner_eq_zero_iff_angle_eq_pi_div_two (x y : V) : ⟪x, y⟫ = 0 ↔ angle x y = π / 2 := iff.symm $ by simp [angle, or_imp_distrib] { contextual := tt } /-- If the angle between two vectors is π, the inner product equals the negative product of the norms. -/ lemma inner_eq_neg_mul_norm_of_angle_eq_pi {x y : V} (h : angle x y = π) : ⟪x, y⟫ = - (∥x∥ * ∥y∥) := by simp [← cos_angle_mul_norm_mul_norm, h] /-- If the angle between two vectors is 0, the inner product equals the product of the norms. -/ lemma inner_eq_mul_norm_of_angle_eq_zero {x y : V} (h : angle x y = 0) : ⟪x, y⟫ = ∥x∥ * ∥y∥ := by simp [← cos_angle_mul_norm_mul_norm, h] /-- The inner product of two non-zero vectors equals the negative product of their norms if and only if the angle between the two vectors is π. -/ lemma inner_eq_neg_mul_norm_iff_angle_eq_pi {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : ⟪x, y⟫ = - (∥x∥ * ∥y∥) ↔ angle x y = π := begin refine ⟨λ h, _, inner_eq_neg_mul_norm_of_angle_eq_pi⟩, have h₁ : (∥x∥ * ∥y∥) ≠ 0 := (mul_pos (norm_pos_iff.mpr hx) (norm_pos_iff.mpr hy)).ne', rw [angle, h, neg_div, div_self h₁, real.arccos_neg_one], end /-- The inner product of two non-zero vectors equals the product of their norms if and only if the angle between the two vectors is 0. -/ lemma inner_eq_mul_norm_iff_angle_eq_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : ⟪x, y⟫ = ∥x∥ * ∥y∥ ↔ angle x y = 0 := begin refine ⟨λ h, _, inner_eq_mul_norm_of_angle_eq_zero⟩, have h₁ : (∥x∥ * ∥y∥) ≠ 0 := (mul_pos (norm_pos_iff.mpr hx) (norm_pos_iff.mpr hy)).ne', rw [angle, h, div_self h₁, real.arccos_one], end /-- If the angle between two vectors is π, the norm of their difference equals the sum of their norms. -/ lemma norm_sub_eq_add_norm_of_angle_eq_pi {x y : V} (h : angle x y = π) : ∥x - y∥ = ∥x∥ + ∥y∥ := begin rw ← sq_eq_sq (norm_nonneg (x - y)) (add_nonneg (norm_nonneg x) (norm_nonneg y)), rw [norm_sub_pow_two_real, inner_eq_neg_mul_norm_of_angle_eq_pi h], ring, end /-- If the angle between two vectors is 0, the norm of their sum equals the sum of their norms. -/ lemma norm_add_eq_add_norm_of_angle_eq_zero {x y : V} (h : angle x y = 0) : ∥x + y∥ = ∥x∥ + ∥y∥ := begin rw ← sq_eq_sq (norm_nonneg (x + y)) (add_nonneg (norm_nonneg x) (norm_nonneg y)), rw [norm_add_pow_two_real, inner_eq_mul_norm_of_angle_eq_zero h], ring, end /-- If the angle between two vectors is 0, the norm of their difference equals the absolute value of the difference of their norms. -/ lemma norm_sub_eq_abs_sub_norm_of_angle_eq_zero {x y : V} (h : angle x y = 0) : ∥x - y∥ = |∥x∥ - ∥y∥| := begin rw [← sq_eq_sq (norm_nonneg (x - y)) (abs_nonneg (∥x∥ - ∥y∥)), norm_sub_pow_two_real, inner_eq_mul_norm_of_angle_eq_zero h, sq_abs (∥x∥ - ∥y∥)], ring, end /-- The norm of the difference of two non-zero vectors equals the sum of their norms if and only the angle between the two vectors is π. -/ lemma norm_sub_eq_add_norm_iff_angle_eq_pi {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : ∥x - y∥ = ∥x∥ + ∥y∥ ↔ angle x y = π := begin refine ⟨λ h, _, norm_sub_eq_add_norm_of_angle_eq_pi⟩, rw ← inner_eq_neg_mul_norm_iff_angle_eq_pi hx hy, obtain ⟨hxy₁, hxy₂⟩ := ⟨norm_nonneg (x - y), add_nonneg (norm_nonneg x) (norm_nonneg y)⟩, rw [← sq_eq_sq hxy₁ hxy₂, norm_sub_pow_two_real] at h, calc inner x y = (∥x∥ ^ 2 + ∥y∥ ^ 2 - (∥x∥ + ∥y∥) ^ 2) / 2 : by linarith ... = -(∥x∥ * ∥y∥) : by ring, end /-- The norm of the sum of two non-zero vectors equals the sum of their norms if and only the angle between the two vectors is 0. -/ lemma norm_add_eq_add_norm_iff_angle_eq_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : ∥x + y∥ = ∥x∥ + ∥y∥ ↔ angle x y = 0 := begin refine ⟨λ h, _, norm_add_eq_add_norm_of_angle_eq_zero⟩, rw ← inner_eq_mul_norm_iff_angle_eq_zero hx hy, obtain ⟨hxy₁, hxy₂⟩ := ⟨norm_nonneg (x + y), add_nonneg (norm_nonneg x) (norm_nonneg y)⟩, rw [← sq_eq_sq hxy₁ hxy₂, norm_add_pow_two_real] at h, calc inner x y = ((∥x∥ + ∥y∥) ^ 2 - ∥x∥ ^ 2 - ∥y∥ ^ 2)/ 2 : by linarith ... = ∥x∥ * ∥y∥ : by ring, end /-- The norm of the difference of two non-zero vectors equals the absolute value of the difference of their norms if and only the angle between the two vectors is 0. -/ lemma norm_sub_eq_abs_sub_norm_iff_angle_eq_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : ∥x - y∥ = |∥x∥ - ∥y∥| ↔ angle x y = 0 := begin refine ⟨λ h, _, norm_sub_eq_abs_sub_norm_of_angle_eq_zero⟩, rw ← inner_eq_mul_norm_iff_angle_eq_zero hx hy, have h1 : ∥x - y∥ ^ 2 = (∥x∥ - ∥y∥) ^ 2, { rw h, exact sq_abs (∥x∥ - ∥y∥) }, rw norm_sub_pow_two_real at h1, calc inner x y = ((∥x∥ + ∥y∥) ^ 2 - ∥x∥ ^ 2 - ∥y∥ ^ 2)/ 2 : by linarith ... = ∥x∥ * ∥y∥ : by ring, end /-- The norm of the sum of two vectors equals the norm of their difference if and only if the angle between them is π/2. -/ lemma norm_add_eq_norm_sub_iff_angle_eq_pi_div_two (x y : V) : ∥x + y∥ = ∥x - y∥ ↔ angle x y = π / 2 := begin rw [← sq_eq_sq (norm_nonneg (x + y)) (norm_nonneg (x - y)), ← inner_eq_zero_iff_angle_eq_pi_div_two x y, norm_add_pow_two_real, norm_sub_pow_two_real], split; intro h; linarith, end end inner_product_geometry namespace euclidean_geometry /-! ### Geometrical results on Euclidean affine spaces This section develops some geometrical definitions and results on Euclidean affine spaces. -/ open inner_product_geometry variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] local notation `⟪`x`, `y`⟫` := @inner ℝ V _ x y include V /-- The undirected angle at `p2` between the line segments to `p1` and `p3`. If either of those points equals `p2`, this is π/2. Use `open_locale euclidean_geometry` to access the `∠ p1 p2 p3` notation. -/ def angle (p1 p2 p3 : P) : ℝ := angle (p1 -ᵥ p2 : V) (p3 -ᵥ p2) localized "notation `∠` := euclidean_geometry.angle" in euclidean_geometry /-- The angle at a point does not depend on the order of the other two points. -/ lemma angle_comm (p1 p2 p3 : P) : ∠ p1 p2 p3 = ∠ p3 p2 p1 := angle_comm _ _ /-- The angle at a point is nonnegative. -/ lemma angle_nonneg (p1 p2 p3 : P) : 0 ≤ ∠ p1 p2 p3 := angle_nonneg _ _ /-- The angle at a point is at most π. -/ lemma angle_le_pi (p1 p2 p3 : P) : ∠ p1 p2 p3 ≤ π := angle_le_pi _ _ /-- The angle ∠AAB at a point. -/ lemma angle_eq_left (p1 p2 : P) : ∠ p1 p1 p2 = π / 2 := begin unfold angle, rw vsub_self, exact angle_zero_left _ end /-- The angle ∠ABB at a point. -/ lemma angle_eq_right (p1 p2 : P) : ∠ p1 p2 p2 = π / 2 := by rw [angle_comm, angle_eq_left] /-- The angle ∠ABA at a point. -/ lemma angle_eq_of_ne {p1 p2 : P} (h : p1 ≠ p2) : ∠ p1 p2 p1 = 0 := angle_self (λ he, h (vsub_eq_zero_iff_eq.1 he)) /-- If the angle ∠ABC at a point is π, the angle ∠BAC is 0. -/ lemma angle_eq_zero_of_angle_eq_pi_left {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) : ∠ p2 p1 p3 = 0 := begin unfold angle at h, rw angle_eq_pi_iff at h, rcases h with ⟨hp1p2, ⟨r, ⟨hr, hpr⟩⟩⟩, unfold angle, rw angle_eq_zero_iff, rw [←neg_vsub_eq_vsub_rev, neg_ne_zero] at hp1p2, use [hp1p2, -r + 1, add_pos (neg_pos_of_neg hr) zero_lt_one], rw [add_smul, ←neg_vsub_eq_vsub_rev p1 p2, smul_neg], simp [←hpr] end /-- If the angle ∠ABC at a point is π, the angle ∠BCA is 0. -/ lemma angle_eq_zero_of_angle_eq_pi_right {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) : ∠ p2 p3 p1 = 0 := begin rw angle_comm at h, exact angle_eq_zero_of_angle_eq_pi_left h end /-- If ∠BCD = π, then ∠ABC = ∠ABD. -/ lemma angle_eq_angle_of_angle_eq_pi (p1 : P) {p2 p3 p4 : P} (h : ∠ p2 p3 p4 = π) : ∠ p1 p2 p3 = ∠ p1 p2 p4 := begin unfold angle at *, rcases angle_eq_pi_iff.1 h with ⟨hp2p3, ⟨r, ⟨hr, hpr⟩⟩⟩, rw [eq_comm], convert angle_smul_right_of_pos (p1 -ᵥ p2) (p3 -ᵥ p2) (add_pos (neg_pos_of_neg hr) zero_lt_one), rw [add_smul, ← neg_vsub_eq_vsub_rev p2 p3, smul_neg, neg_smul, ← hpr], simp end /-- If ∠BCD = π, then ∠ACB + ∠ACD = π. -/ lemma angle_add_angle_eq_pi_of_angle_eq_pi (p1 : P) {p2 p3 p4 : P} (h : ∠ p2 p3 p4 = π) : ∠ p1 p3 p2 + ∠ p1 p3 p4 = π := begin unfold angle at h, rw [angle_comm p1 p3 p2, angle_comm p1 p3 p4], unfold angle, exact angle_add_angle_eq_pi_of_angle_eq_pi _ h end /-- Vertical Angles Theorem: angles opposite each other, formed by two intersecting straight lines, are equal. -/ lemma angle_eq_angle_of_angle_eq_pi_of_angle_eq_pi {p1 p2 p3 p4 p5 : P} (hapc : ∠ p1 p5 p3 = π) (hbpd : ∠ p2 p5 p4 = π) : ∠ p1 p5 p2 = ∠ p3 p5 p4 := by linarith [angle_add_angle_eq_pi_of_angle_eq_pi p1 hbpd, angle_comm p4 p5 p1, angle_add_angle_eq_pi_of_angle_eq_pi p4 hapc, angle_comm p4 p5 p3] /-- If ∠ABC = π then dist A B ≠ 0. -/ lemma left_dist_ne_zero_of_angle_eq_pi {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) : dist p1 p2 ≠ 0 := begin by_contra heq, rw [dist_eq_zero] at heq, rw [heq, angle_eq_left] at h, exact real.pi_ne_zero (by linarith), end /-- If ∠ABC = π then dist C B ≠ 0. -/ lemma right_dist_ne_zero_of_angle_eq_pi {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) : dist p3 p2 ≠ 0 := left_dist_ne_zero_of_angle_eq_pi $ (angle_comm _ _ _).trans h /-- If ∠ABC = π, then (dist A C) = (dist A B) + (dist B C). -/ lemma dist_eq_add_dist_of_angle_eq_pi {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) : dist p1 p3 = dist p1 p2 + dist p3 p2 := begin rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, dist_eq_norm_vsub V, ← vsub_sub_vsub_cancel_right], exact norm_sub_eq_add_norm_of_angle_eq_pi h, end /-- If A ≠ B and C ≠ B then ∠ABC = π if and only if (dist A C) = (dist A B) + (dist B C). -/ lemma dist_eq_add_dist_iff_angle_eq_pi {p1 p2 p3 : P} (hp1p2 : p1 ≠ p2) (hp3p2 : p3 ≠ p2) : dist p1 p3 = dist p1 p2 + dist p3 p2 ↔ ∠ p1 p2 p3 = π := begin rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, dist_eq_norm_vsub V, ← vsub_sub_vsub_cancel_right], exact norm_sub_eq_add_norm_iff_angle_eq_pi ((λ he, hp1p2 (vsub_eq_zero_iff_eq.1 he))) (λ he, hp3p2 (vsub_eq_zero_iff_eq.1 he)), end /-- If ∠ABC = 0, then (dist A C) = abs ((dist A B) - (dist B C)). -/ lemma dist_eq_abs_sub_dist_of_angle_eq_zero {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = 0) : (dist p1 p3) = |(dist p1 p2) - (dist p3 p2)| := begin rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, dist_eq_norm_vsub V, ← vsub_sub_vsub_cancel_right], exact norm_sub_eq_abs_sub_norm_of_angle_eq_zero h, end /-- If A ≠ B and C ≠ B then ∠ABC = 0 if and only if (dist A C) = abs ((dist A B) - (dist B C)). -/ lemma dist_eq_abs_sub_dist_iff_angle_eq_zero {p1 p2 p3 : P} (hp1p2 : p1 ≠ p2) (hp3p2 : p3 ≠ p2) : (dist p1 p3) = |(dist p1 p2) - (dist p3 p2)| ↔ ∠ p1 p2 p3 = 0 := begin rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, dist_eq_norm_vsub V, ← vsub_sub_vsub_cancel_right], exact norm_sub_eq_abs_sub_norm_iff_angle_eq_zero ((λ he, hp1p2 (vsub_eq_zero_iff_eq.1 he))) (λ he, hp3p2 (vsub_eq_zero_iff_eq.1 he)), end /-- The midpoint of the segment AB is the same distance from A as it is from B. -/ lemma dist_left_midpoint_eq_dist_right_midpoint (p1 p2 : P) : dist p1 (midpoint ℝ p1 p2) = dist p2 (midpoint ℝ p1 p2) := by rw [dist_left_midpoint p1 p2, dist_right_midpoint p1 p2] /-- If M is the midpoint of the segment AB, then ∠AMB = π. -/ lemma angle_midpoint_eq_pi (p1 p2 : P) (hp1p2 : p1 ≠ p2) : ∠ p1 (midpoint ℝ p1 p2) p2 = π := have p2 -ᵥ midpoint ℝ p1 p2 = -(p1 -ᵥ midpoint ℝ p1 p2), by { rw neg_vsub_eq_vsub_rev, simp }, by simp [angle, this, hp1p2, -zero_lt_one] /-- If M is the midpoint of the segment AB and C is the same distance from A as it is from B then ∠CMA = π / 2. -/ lemma angle_left_midpoint_eq_pi_div_two_of_dist_eq {p1 p2 p3 : P} (h : dist p3 p1 = dist p3 p2) : ∠ p3 (midpoint ℝ p1 p2) p1 = π / 2 := begin let m : P := midpoint ℝ p1 p2, have h1 : p3 -ᵥ p1 = (p3 -ᵥ m) - (p1 -ᵥ m) := (vsub_sub_vsub_cancel_right p3 p1 m).symm, have h2 : p3 -ᵥ p2 = (p3 -ᵥ m) + (p1 -ᵥ m), { rw [left_vsub_midpoint, ← midpoint_vsub_right, vsub_add_vsub_cancel] }, rw [dist_eq_norm_vsub V p3 p1, dist_eq_norm_vsub V p3 p2, h1, h2] at h, exact (norm_add_eq_norm_sub_iff_angle_eq_pi_div_two (p3 -ᵥ m) (p1 -ᵥ m)).mp h.symm, end /-- If M is the midpoint of the segment AB and C is the same distance from A as it is from B then ∠CMB = π / 2. -/ lemma angle_right_midpoint_eq_pi_div_two_of_dist_eq {p1 p2 p3 : P} (h : dist p3 p1 = dist p3 p2) : ∠ p3 (midpoint ℝ p1 p2) p2 = π / 2 := by rw [midpoint_comm p1 p2, angle_left_midpoint_eq_pi_div_two_of_dist_eq h.symm] /-- The inner product of two vectors given with `weighted_vsub`, in terms of the pairwise distances. -/ lemma inner_weighted_vsub {ι₁ : Type*} {s₁ : finset ι₁} {w₁ : ι₁ → ℝ} (p₁ : ι₁ → P) (h₁ : ∑ i in s₁, w₁ i = 0) {ι₂ : Type*} {s₂ : finset ι₂} {w₂ : ι₂ → ℝ} (p₂ : ι₂ → P) (h₂ : ∑ i in s₂, w₂ i = 0) : inner (s₁.weighted_vsub p₁ w₁) (s₂.weighted_vsub p₂ w₂) = (-∑ i₁ in s₁, ∑ i₂ in s₂, w₁ i₁ * w₂ i₂ * (dist (p₁ i₁) (p₂ i₂) * dist (p₁ i₁) (p₂ i₂))) / 2 := begin rw [finset.weighted_vsub_apply, finset.weighted_vsub_apply, inner_sum_smul_sum_smul_of_sum_eq_zero _ h₁ _ h₂], simp_rw [vsub_sub_vsub_cancel_right], rcongr i₁ i₂; rw dist_eq_norm_vsub V (p₁ i₁) (p₂ i₂) end /-- The distance between two points given with `affine_combination`, in terms of the pairwise distances between the points in that combination. -/ lemma dist_affine_combination {ι : Type*} {s : finset ι} {w₁ w₂ : ι → ℝ} (p : ι → P) (h₁ : ∑ i in s, w₁ i = 1) (h₂ : ∑ i in s, w₂ i = 1) : dist (s.affine_combination p w₁) (s.affine_combination p w₂) * dist (s.affine_combination p w₁) (s.affine_combination p w₂) = (-∑ i₁ in s, ∑ i₂ in s, (w₁ - w₂) i₁ * (w₁ - w₂) i₂ * (dist (p i₁) (p i₂) * dist (p i₁) (p i₂))) / 2 := begin rw [dist_eq_norm_vsub V (s.affine_combination p w₁) (s.affine_combination p w₂), ←inner_self_eq_norm_sq, finset.affine_combination_vsub], have h : ∑ i in s, (w₁ - w₂) i = 0, { simp_rw [pi.sub_apply, finset.sum_sub_distrib, h₁, h₂, sub_self] }, exact inner_weighted_vsub p h p h end /-- Suppose that `c₁` is equidistant from `p₁` and `p₂`, and the same applies to `c₂`. Then the vector between `c₁` and `c₂` is orthogonal to that between `p₁` and `p₂`. (In two dimensions, this says that the diagonals of a kite are orthogonal.) -/ lemma inner_vsub_vsub_of_dist_eq_of_dist_eq {c₁ c₂ p₁ p₂ : P} (hc₁ : dist p₁ c₁ = dist p₂ c₁) (hc₂ : dist p₁ c₂ = dist p₂ c₂) : ⟪c₂ -ᵥ c₁, p₂ -ᵥ p₁⟫ = 0 := begin have h : ⟪(c₂ -ᵥ c₁) + (c₂ -ᵥ c₁), p₂ -ᵥ p₁⟫ = 0, { conv_lhs { congr, congr, rw ←vsub_sub_vsub_cancel_right c₂ c₁ p₁, skip, rw ←vsub_sub_vsub_cancel_right c₂ c₁ p₂ }, rw [←add_sub_comm, inner_sub_left], conv_lhs { congr, rw ←vsub_sub_vsub_cancel_right p₂ p₁ c₂, skip, rw ←vsub_sub_vsub_cancel_right p₂ p₁ c₁ }, rw [dist_comm p₁, dist_comm p₂, dist_eq_norm_vsub V _ p₁, dist_eq_norm_vsub V _ p₂, ←real_inner_add_sub_eq_zero_iff] at hc₁ hc₂, simp_rw [←neg_vsub_eq_vsub_rev c₁, ←neg_vsub_eq_vsub_rev c₂, sub_neg_eq_add, neg_add_eq_sub, hc₁, hc₂, sub_zero] }, simpa [inner_add_left, ←mul_two, (by norm_num : (2 : ℝ) ≠ 0)] using h end /-- The squared distance between points on a line (expressed as a multiple of a fixed vector added to a point) and another point, expressed as a quadratic. -/ lemma dist_smul_vadd_sq (r : ℝ) (v : V) (p₁ p₂ : P) : dist (r • v +ᵥ p₁) p₂ * dist (r • v +ᵥ p₁) p₂ = ⟪v, v⟫ * r * r + 2 * ⟪v, p₁ -ᵥ p₂⟫ * r + ⟪p₁ -ᵥ p₂, p₁ -ᵥ p₂⟫ := begin rw [dist_eq_norm_vsub V _ p₂, ←real_inner_self_eq_norm_sq, vadd_vsub_assoc, real_inner_add_add_self, real_inner_smul_left, real_inner_smul_left, real_inner_smul_right], ring end /-- The condition for two points on a line to be equidistant from another point. -/ lemma dist_smul_vadd_eq_dist {v : V} (p₁ p₂ : P) (hv : v ≠ 0) (r : ℝ) : dist (r • v +ᵥ p₁) p₂ = dist p₁ p₂ ↔ (r = 0 ∨ r = -2 * ⟪v, p₁ -ᵥ p₂⟫ / ⟪v, v⟫) := begin conv_lhs { rw [←mul_self_inj_of_nonneg dist_nonneg dist_nonneg, dist_smul_vadd_sq, ←sub_eq_zero, add_sub_assoc, dist_eq_norm_vsub V p₁ p₂, ←real_inner_self_eq_norm_sq, sub_self] }, have hvi : ⟪v, v⟫ ≠ 0, by simpa using hv, have hd : discrim ⟪v, v⟫ (2 * ⟪v, p₁ -ᵥ p₂⟫) 0 = (2 * inner v (p₁ -ᵥ p₂)) * (2 * inner v (p₁ -ᵥ p₂)), { rw discrim, ring }, rw [quadratic_eq_zero_iff hvi hd, add_left_neg, zero_div, neg_mul_eq_neg_mul, ←mul_sub_right_distrib, sub_eq_add_neg, ←mul_two, mul_assoc, mul_div_assoc, mul_div_mul_left, mul_div_assoc], norm_num end open affine_subspace finite_dimensional /-- Distances `r₁` `r₂` of `p` from two different points `c₁` `c₂` determine at most two points `p₁` `p₂` in a two-dimensional subspace containing those points (two circles intersect in at most two points). -/ lemma eq_of_dist_eq_of_dist_eq_of_mem_of_finrank_eq_two {s : affine_subspace ℝ P} [finite_dimensional ℝ s.direction] (hd : finrank ℝ s.direction = 2) {c₁ c₂ p₁ p₂ p : P} (hc₁s : c₁ ∈ s) (hc₂s : c₂ ∈ s) (hp₁s : p₁ ∈ s) (hp₂s : p₂ ∈ s) (hps : p ∈ s) {r₁ r₂ : ℝ} (hc : c₁ ≠ c₂) (hp : p₁ ≠ p₂) (hp₁c₁ : dist p₁ c₁ = r₁) (hp₂c₁ : dist p₂ c₁ = r₁) (hpc₁ : dist p c₁ = r₁) (hp₁c₂ : dist p₁ c₂ = r₂) (hp₂c₂ : dist p₂ c₂ = r₂) (hpc₂ : dist p c₂ = r₂) : p = p₁ ∨ p = p₂ := begin have ho : ⟪c₂ -ᵥ c₁, p₂ -ᵥ p₁⟫ = 0 := inner_vsub_vsub_of_dist_eq_of_dist_eq (hp₁c₁.trans hp₂c₁.symm) (hp₁c₂.trans hp₂c₂.symm), have hop : ⟪c₂ -ᵥ c₁, p -ᵥ p₁⟫ = 0 := inner_vsub_vsub_of_dist_eq_of_dist_eq (hp₁c₁.trans hpc₁.symm) (hp₁c₂.trans hpc₂.symm), let b : fin 2 → V := ![c₂ -ᵥ c₁, p₂ -ᵥ p₁], have hb : linear_independent ℝ b, { refine linear_independent_of_ne_zero_of_inner_eq_zero _ _, { intro i, fin_cases i; simp [b, hc.symm, hp.symm], }, { intros i j hij, fin_cases i; fin_cases j; try { exact false.elim (hij rfl) }, { exact ho }, { rw real_inner_comm, exact ho } } }, have hbs : submodule.span ℝ (set.range b) = s.direction, { refine eq_of_le_of_finrank_eq _ _, { rw [submodule.span_le, set.range_subset_iff], intro i, fin_cases i, { exact vsub_mem_direction hc₂s hc₁s }, { exact vsub_mem_direction hp₂s hp₁s } }, { rw [finrank_span_eq_card hb, fintype.card_fin, hd] } }, have hv : ∀ v ∈ s.direction, ∃ t₁ t₂ : ℝ, v = t₁ • (c₂ -ᵥ c₁) + t₂ • (p₂ -ᵥ p₁), { intros v hv, have hr : set.range b = {c₂ -ᵥ c₁, p₂ -ᵥ p₁}, { have hu : (finset.univ : finset (fin 2)) = {0, 1}, by dec_trivial, rw [←fintype.coe_image_univ, hu], simp, refl }, rw [←hbs, hr, submodule.mem_span_insert] at hv, rcases hv with ⟨t₁, v', hv', hv⟩, rw submodule.mem_span_singleton at hv', rcases hv' with ⟨t₂, rfl⟩, exact ⟨t₁, t₂, hv⟩ }, rcases hv (p -ᵥ p₁) (vsub_mem_direction hps hp₁s) with ⟨t₁, t₂, hpt⟩, simp only [hpt, inner_add_right, inner_smul_right, ho, mul_zero, add_zero, mul_eq_zero, inner_self_eq_zero, vsub_eq_zero_iff_eq, hc.symm, or_false] at hop, rw [hop, zero_smul, zero_add, ←eq_vadd_iff_vsub_eq] at hpt, subst hpt, have hp' : (p₂ -ᵥ p₁ : V) ≠ 0, { simp [hp.symm] }, have hp₂ : dist ((1 : ℝ) • (p₂ -ᵥ p₁) +ᵥ p₁) c₁ = r₁, { simp [hp₂c₁] }, rw [←hp₁c₁, dist_smul_vadd_eq_dist _ _ hp'] at hpc₁ hp₂, simp only [one_ne_zero, false_or] at hp₂, rw hp₂.symm at hpc₁, cases hpc₁; simp [hpc₁] end /-- Distances `r₁` `r₂` of `p` from two different points `c₁` `c₂` determine at most two points `p₁` `p₂` in two-dimensional space (two circles intersect in at most two points). -/ lemma eq_of_dist_eq_of_dist_eq_of_finrank_eq_two [finite_dimensional ℝ V] (hd : finrank ℝ V = 2) {c₁ c₂ p₁ p₂ p : P} {r₁ r₂ : ℝ} (hc : c₁ ≠ c₂) (hp : p₁ ≠ p₂) (hp₁c₁ : dist p₁ c₁ = r₁) (hp₂c₁ : dist p₂ c₁ = r₁) (hpc₁ : dist p c₁ = r₁) (hp₁c₂ : dist p₁ c₂ = r₂) (hp₂c₂ : dist p₂ c₂ = r₂) (hpc₂ : dist p c₂ = r₂) : p = p₁ ∨ p = p₂ := begin have hd' : finrank ℝ (⊤ : affine_subspace ℝ P).direction = 2, { rw [direction_top, finrank_top], exact hd }, exact eq_of_dist_eq_of_dist_eq_of_mem_of_finrank_eq_two hd' (mem_top ℝ V _) (mem_top ℝ V _) (mem_top ℝ V _) (mem_top ℝ V _) (mem_top ℝ V _) hc hp hp₁c₁ hp₂c₁ hpc₁ hp₁c₂ hp₂c₂ hpc₂ end variables {V} /-- The orthogonal projection of a point onto a nonempty affine subspace, whose direction is complete, as an unbundled function. This definition is only intended for use in setting up the bundled version `orthogonal_projection` and should not be used once that is defined. -/ def orthogonal_projection_fn (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : P := classical.some $ inter_eq_singleton_of_nonempty_of_is_compl (nonempty_subtype.mp ‹_›) (mk'_nonempty p s.directionᗮ) begin convert submodule.is_compl_orthogonal_of_is_complete (complete_space_coe_iff_is_complete.mp ‹_›), exact direction_mk' p s.directionᗮ end /-- The intersection of the subspace and the orthogonal subspace through the given point is the `orthogonal_projection_fn` of that point onto the subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma inter_eq_singleton_orthogonal_projection_fn {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : (s : set P) ∩ (mk' p s.directionᗮ) = {orthogonal_projection_fn s p} := classical.some_spec $ inter_eq_singleton_of_nonempty_of_is_compl (nonempty_subtype.mp ‹_›) (mk'_nonempty p s.directionᗮ) begin convert submodule.is_compl_orthogonal_of_is_complete (complete_space_coe_iff_is_complete.mp ‹_›), exact direction_mk' p s.directionᗮ end /-- The `orthogonal_projection_fn` lies in the given subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_mem {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : orthogonal_projection_fn s p ∈ s := begin rw [←mem_coe, ←set.singleton_subset_iff, ←inter_eq_singleton_orthogonal_projection_fn], exact set.inter_subset_left _ _ end /-- The `orthogonal_projection_fn` lies in the orthogonal subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_mem_orthogonal {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : orthogonal_projection_fn s p ∈ mk' p s.directionᗮ := begin rw [←mem_coe, ←set.singleton_subset_iff, ←inter_eq_singleton_orthogonal_projection_fn], exact set.inter_subset_right _ _ end /-- Subtracting `p` from its `orthogonal_projection_fn` produces a result in the orthogonal direction. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_vsub_mem_direction_orthogonal {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : orthogonal_projection_fn s p -ᵥ p ∈ s.directionᗮ := direction_mk' p s.directionᗮ ▸ vsub_mem_direction (orthogonal_projection_fn_mem_orthogonal p) (self_mem_mk' _ _) /-- The orthogonal projection of a point onto a nonempty affine subspace, whose direction is complete. The corresponding linear map (mapping a vector to the difference between the projections of two points whose difference is that vector) is the `orthogonal_projection` for real inner product spaces, onto the direction of the affine subspace being projected onto. -/ def orthogonal_projection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] : P →ᵃ[ℝ] s := { to_fun := λ p, ⟨orthogonal_projection_fn s p, orthogonal_projection_fn_mem p⟩, linear := orthogonal_projection s.direction, map_vadd' := λ p v, begin have hs : ((orthogonal_projection s.direction) v : V) +ᵥ orthogonal_projection_fn s p ∈ s := vadd_mem_of_mem_direction (orthogonal_projection s.direction v).2 (orthogonal_projection_fn_mem p), have ho : ((orthogonal_projection s.direction) v : V) +ᵥ orthogonal_projection_fn s p ∈ mk' (v +ᵥ p) s.directionᗮ, { rw [←vsub_right_mem_direction_iff_mem (self_mem_mk' _ _) _, direction_mk', vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_comm, add_sub_assoc], refine submodule.add_mem _ (orthogonal_projection_fn_vsub_mem_direction_orthogonal p) _, rw submodule.mem_orthogonal', intros w hw, rw [←neg_sub, inner_neg_left, orthogonal_projection_inner_eq_zero _ w hw, neg_zero], }, have hm : ((orthogonal_projection s.direction) v : V) +ᵥ orthogonal_projection_fn s p ∈ ({orthogonal_projection_fn s (v +ᵥ p)} : set P), { rw ←inter_eq_singleton_orthogonal_projection_fn (v +ᵥ p), exact set.mem_inter hs ho }, rw set.mem_singleton_iff at hm, ext, exact hm.symm end } @[simp] lemma orthogonal_projection_fn_eq {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : orthogonal_projection_fn s p = orthogonal_projection s p := rfl /-- The linear map corresponding to `orthogonal_projection`. -/ @[simp] lemma orthogonal_projection_linear {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] : (orthogonal_projection s).linear = _root_.orthogonal_projection s.direction := rfl /-- The intersection of the subspace and the orthogonal subspace through the given point is the `orthogonal_projection` of that point onto the subspace. -/ lemma inter_eq_singleton_orthogonal_projection {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : (s : set P) ∩ (mk' p s.directionᗮ) = {orthogonal_projection s p} := begin rw ←orthogonal_projection_fn_eq, exact inter_eq_singleton_orthogonal_projection_fn p end /-- The `orthogonal_projection` lies in the given subspace. -/ lemma orthogonal_projection_mem {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : ↑(orthogonal_projection s p) ∈ s := (orthogonal_projection s p).2 /-- The `orthogonal_projection` lies in the orthogonal subspace. -/ lemma orthogonal_projection_mem_orthogonal (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : ↑(orthogonal_projection s p) ∈ mk' p s.directionᗮ := orthogonal_projection_fn_mem_orthogonal p /-- Subtracting a point in the given subspace from the `orthogonal_projection` produces a result in the direction of the given subspace. -/ lemma orthogonal_projection_vsub_mem_direction {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p1 : P} (p2 : P) (hp1 : p1 ∈ s) : ↑(orthogonal_projection s p2 -ᵥ ⟨p1, hp1⟩ : s.direction) ∈ s.direction := (orthogonal_projection s p2 -ᵥ ⟨p1, hp1⟩ : s.direction).2 /-- Subtracting the `orthogonal_projection` from a point in the given subspace produces a result in the direction of the given subspace. -/ lemma vsub_orthogonal_projection_mem_direction {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p1 : P} (p2 : P) (hp1 : p1 ∈ s) : ↑((⟨p1, hp1⟩ : s) -ᵥ orthogonal_projection s p2 : s.direction) ∈ s.direction := ((⟨p1, hp1⟩ : s) -ᵥ orthogonal_projection s p2 : s.direction).2 /-- A point equals its orthogonal projection if and only if it lies in the subspace. -/ lemma orthogonal_projection_eq_self_iff {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p : P} : ↑(orthogonal_projection s p) = p ↔ p ∈ s := begin split, { exact λ h, h ▸ orthogonal_projection_mem p }, { intro h, have hp : p ∈ ((s : set P) ∩ mk' p s.directionᗮ) := ⟨h, self_mem_mk' p _⟩, rw [inter_eq_singleton_orthogonal_projection p] at hp, symmetry, exact hp } end @[simp] lemma orthogonal_projection_mem_subspace_eq_self {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : s) : orthogonal_projection s p = p := begin ext, rw orthogonal_projection_eq_self_iff, exact p.2 end /-- Orthogonal projection is idempotent. -/ @[simp] lemma orthogonal_projection_orthogonal_projection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : orthogonal_projection s (orthogonal_projection s p) = orthogonal_projection s p := begin ext, rw orthogonal_projection_eq_self_iff, exact orthogonal_projection_mem p, end lemma eq_orthogonal_projection_of_eq_subspace {s s' : affine_subspace ℝ P} [nonempty s] [nonempty s'] [complete_space s.direction] [complete_space s'.direction] (h : s = s') (p : P) : (orthogonal_projection s p : P) = (orthogonal_projection s' p : P) := begin change orthogonal_projection_fn s p = orthogonal_projection_fn s' p, congr, exact h end /-- The distance to a point's orthogonal projection is 0 iff it lies in the subspace. -/ lemma dist_orthogonal_projection_eq_zero_iff {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p : P} : dist p (orthogonal_projection s p) = 0 ↔ p ∈ s := by rw [dist_comm, dist_eq_zero, orthogonal_projection_eq_self_iff] /-- The distance between a point and its orthogonal projection is nonzero if it does not lie in the subspace. -/ lemma dist_orthogonal_projection_ne_zero_of_not_mem {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p : P} (hp : p ∉ s) : dist p (orthogonal_projection s p) ≠ 0 := mt dist_orthogonal_projection_eq_zero_iff.mp hp /-- Subtracting `p` from its `orthogonal_projection` produces a result in the orthogonal direction. -/ lemma orthogonal_projection_vsub_mem_direction_orthogonal (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : (orthogonal_projection s p : P) -ᵥ p ∈ s.directionᗮ := orthogonal_projection_fn_vsub_mem_direction_orthogonal p /-- Subtracting the `orthogonal_projection` from `p` produces a result in the orthogonal direction. -/ lemma vsub_orthogonal_projection_mem_direction_orthogonal (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : p -ᵥ orthogonal_projection s p ∈ s.directionᗮ := direction_mk' p s.directionᗮ ▸ vsub_mem_direction (self_mem_mk' _ _) (orthogonal_projection_mem_orthogonal s p) /-- Subtracting the `orthogonal_projection` from `p` produces a result in the kernel of the linear part of the orthogonal projection. -/ lemma orthogonal_projection_vsub_orthogonal_projection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : _root_.orthogonal_projection s.direction (p -ᵥ orthogonal_projection s p) = 0 := begin apply orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero, intros c hc, rw [← neg_vsub_eq_vsub_rev, inner_neg_right, (orthogonal_projection_vsub_mem_direction_orthogonal s p c hc), neg_zero] end /-- Adding a vector to a point in the given subspace, then taking the orthogonal projection, produces the original point if the vector was in the orthogonal direction. -/ lemma orthogonal_projection_vadd_eq_self {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p : P} (hp : p ∈ s) {v : V} (hv : v ∈ s.directionᗮ) : orthogonal_projection s (v +ᵥ p) = ⟨p, hp⟩ := begin have h := vsub_orthogonal_projection_mem_direction_orthogonal s (v +ᵥ p), rw [vadd_vsub_assoc, submodule.add_mem_iff_right _ hv] at h, refine (eq_of_vsub_eq_zero _).symm, ext, refine submodule.disjoint_def.1 s.direction.orthogonal_disjoint _ _ h, exact (_ : s.direction).2 end /-- Adding a vector to a point in the given subspace, then taking the orthogonal projection, produces the original point if the vector is a multiple of the result of subtracting a point's orthogonal projection from that point. -/ lemma orthogonal_projection_vadd_smul_vsub_orthogonal_projection {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p1 : P} (p2 : P) (r : ℝ) (hp : p1 ∈ s) : orthogonal_projection s (r • (p2 -ᵥ orthogonal_projection s p2 : V) +ᵥ p1) = ⟨p1, hp⟩ := orthogonal_projection_vadd_eq_self hp (submodule.smul_mem _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s _)) /-- The square of the distance from a point in `s` to `p2` equals the sum of the squares of the distances of the two points to the `orthogonal_projection`. -/ lemma dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p1 : P} (p2 : P) (hp1 : p1 ∈ s) : dist p1 p2 * dist p1 p2 = dist p1 (orthogonal_projection s p2) * dist p1 (orthogonal_projection s p2) + dist p2 (orthogonal_projection s p2) * dist p2 (orthogonal_projection s p2) := begin rw [pseudo_metric_space.dist_comm p2 _, dist_eq_norm_vsub V p1 _, dist_eq_norm_vsub V p1 _, dist_eq_norm_vsub V _ p2, ← vsub_add_vsub_cancel p1 (orthogonal_projection s p2) p2, norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero], exact submodule.inner_right_of_mem_orthogonal (vsub_orthogonal_projection_mem_direction p2 hp1) (orthogonal_projection_vsub_mem_direction_orthogonal s p2), end /-- The square of the distance between two points constructed by adding multiples of the same orthogonal vector to points in the same subspace. -/ lemma dist_sq_smul_orthogonal_vadd_smul_orthogonal_vadd {s : affine_subspace ℝ P} {p1 p2 : P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) (r1 r2 : ℝ) {v : V} (hv : v ∈ s.directionᗮ) : dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) * dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) = dist p1 p2 * dist p1 p2 + (r1 - r2) * (r1 - r2) * (∥v∥ * ∥v∥) := calc dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) * dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) = ∥(p1 -ᵥ p2) + (r1 - r2) • v∥ * ∥(p1 -ᵥ p2) + (r1 - r2) • v∥ : by { rw [dist_eq_norm_vsub V (r1 • v +ᵥ p1), vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, sub_smul], abel } ... = ∥p1 -ᵥ p2∥ * ∥p1 -ᵥ p2∥ + ∥(r1 - r2) • v∥ * ∥(r1 - r2) • v∥ : norm_add_sq_eq_norm_sq_add_norm_sq_real (submodule.inner_right_of_mem_orthogonal (vsub_mem_direction hp1 hp2) (submodule.smul_mem _ _ hv)) ... = ∥(p1 -ᵥ p2 : V)∥ * ∥(p1 -ᵥ p2 : V)∥ + |r1 - r2| * |r1 - r2| * ∥v∥ * ∥v∥ : by { rw [norm_smul, real.norm_eq_abs], ring } ... = dist p1 p2 * dist p1 p2 + (r1 - r2) * (r1 - r2) * (∥v∥ * ∥v∥) : by { rw [dist_eq_norm_vsub V p1, abs_mul_abs_self, mul_assoc] } /-- Reflection in an affine subspace, which is expected to be nonempty and complete. The word "reflection" is sometimes understood to mean specifically reflection in a codimension-one subspace, and sometimes more generally to cover operations such as reflection in a point. The definition here, of reflection in an affine subspace, is a more general sense of the word that includes both those common cases. -/ def reflection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] : P ≃ᵃⁱ[ℝ] P := affine_isometry_equiv.mk' (λ p, (↑(orthogonal_projection s p) -ᵥ p) +ᵥ orthogonal_projection s p) (_root_.reflection s.direction) ↑(classical.arbitrary s) begin intros p, let v := p -ᵥ ↑(classical.arbitrary s), let a : V := _root_.orthogonal_projection s.direction v, let b : P := ↑(classical.arbitrary s), have key : a +ᵥ b -ᵥ (v +ᵥ b) +ᵥ (a +ᵥ b) = a + a - v +ᵥ (b -ᵥ b +ᵥ b), { rw [← add_vadd, vsub_vadd_eq_vsub_sub, vsub_vadd, vadd_vsub], congr' 1, abel }, have : p = v +ᵥ ↑(classical.arbitrary s) := (vsub_vadd p ↑(classical.arbitrary s)).symm, simpa only [coe_vadd, reflection_apply, affine_map.map_vadd, orthogonal_projection_linear, orthogonal_projection_mem_subspace_eq_self, vadd_vsub, continuous_linear_map.coe_coe, continuous_linear_equiv.coe_coe, this] using key, end /-- The result of reflecting. -/ lemma reflection_apply (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : reflection s p = (↑(orthogonal_projection s p) -ᵥ p) +ᵥ orthogonal_projection s p := rfl lemma eq_reflection_of_eq_subspace {s s' : affine_subspace ℝ P} [nonempty s] [nonempty s'] [complete_space s.direction] [complete_space s'.direction] (h : s = s') (p : P) : (reflection s p : P) = (reflection s' p : P) := by unfreezingI { subst h } /-- Reflecting twice in the same subspace. -/ @[simp] lemma reflection_reflection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : reflection s (reflection s p) = p := begin have : ∀ a : s, ∀ b : V, (_root_.orthogonal_projection s.direction) b = 0 → reflection s (reflection s (b +ᵥ a)) = b +ᵥ a, { intros a b h, have : (a:P) -ᵥ (b +ᵥ a) = - b, { rw [vsub_vadd_eq_vsub_sub, vsub_self, zero_sub] }, simp [reflection, h, this] }, rw ← vsub_vadd p (orthogonal_projection s p), exact this (orthogonal_projection s p) _ (orthogonal_projection_vsub_orthogonal_projection s p), end /-- Reflection is its own inverse. -/ @[simp] lemma reflection_symm (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] : (reflection s).symm = reflection s := by { ext, rw ← (reflection s).injective.eq_iff, simp } /-- Reflection is involutive. -/ lemma reflection_involutive (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] : function.involutive (reflection s) := reflection_reflection s /-- A point is its own reflection if and only if it is in the subspace. -/ lemma reflection_eq_self_iff {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : reflection s p = p ↔ p ∈ s := begin rw [←orthogonal_projection_eq_self_iff, reflection_apply], split, { intro h, rw [←@vsub_eq_zero_iff_eq V, vadd_vsub_assoc, ←two_smul ℝ (↑(orthogonal_projection s p) -ᵥ p), smul_eq_zero] at h, norm_num at h, exact h }, { intro h, simp [h] } end /-- Reflecting a point in two subspaces produces the same result if and only if the point has the same orthogonal projection in each of those subspaces. -/ lemma reflection_eq_iff_orthogonal_projection_eq (s₁ s₂ : affine_subspace ℝ P) [nonempty s₁] [nonempty s₂] [complete_space s₁.direction] [complete_space s₂.direction] (p : P) : reflection s₁ p = reflection s₂ p ↔ (orthogonal_projection s₁ p : P) = orthogonal_projection s₂ p := begin rw [reflection_apply, reflection_apply], split, { intro h, rw [←@vsub_eq_zero_iff_eq V, vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_comm, add_sub_assoc, vsub_sub_vsub_cancel_right, ←two_smul ℝ ((orthogonal_projection s₁ p : P) -ᵥ orthogonal_projection s₂ p), smul_eq_zero] at h, norm_num at h, exact h }, { intro h, rw h } end /-- The distance between `p₁` and the reflection of `p₂` equals that between the reflection of `p₁` and `p₂`. -/ lemma dist_reflection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p₁ p₂ : P) : dist p₁ (reflection s p₂) = dist (reflection s p₁) p₂ := begin conv_lhs { rw ←reflection_reflection s p₁ }, exact (reflection s).dist_map _ _ end /-- A point in the subspace is equidistant from another point and its reflection. -/ lemma dist_reflection_eq_of_mem (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] {p₁ : P} (hp₁ : p₁ ∈ s) (p₂ : P) : dist p₁ (reflection s p₂) = dist p₁ p₂ := begin rw ←reflection_eq_self_iff p₁ at hp₁, convert (reflection s).dist_map p₁ p₂, rw hp₁ end /-- The reflection of a point in a subspace is contained in any larger subspace containing both the point and the subspace reflected in. -/ lemma reflection_mem_of_le_of_mem {s₁ s₂ : affine_subspace ℝ P} [nonempty s₁] [complete_space s₁.direction] (hle : s₁ ≤ s₂) {p : P} (hp : p ∈ s₂) : reflection s₁ p ∈ s₂ := begin rw [reflection_apply], have ho : ↑(orthogonal_projection s₁ p) ∈ s₂ := hle (orthogonal_projection_mem p), exact vadd_mem_of_mem_direction (vsub_mem_direction ho hp) ho end /-- Reflecting an orthogonal vector plus a point in the subspace produces the negation of that vector plus the point. -/ lemma reflection_orthogonal_vadd {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p : P} (hp : p ∈ s) {v : V} (hv : v ∈ s.directionᗮ) : reflection s (v +ᵥ p) = -v +ᵥ p := begin rw [reflection_apply, orthogonal_projection_vadd_eq_self hp hv, vsub_vadd_eq_vsub_sub], simp end /-- Reflecting a vector plus a point in the subspace produces the negation of that vector plus the point if the vector is a multiple of the result of subtracting a point's orthogonal projection from that point. -/ lemma reflection_vadd_smul_vsub_orthogonal_projection {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p₁ : P} (p₂ : P) (r : ℝ) (hp₁ : p₁ ∈ s) : reflection s (r • (p₂ -ᵥ orthogonal_projection s p₂) +ᵥ p₁) = -(r • (p₂ -ᵥ orthogonal_projection s p₂)) +ᵥ p₁ := reflection_orthogonal_vadd hp₁ (submodule.smul_mem _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s _)) omit V /-- A set of points is cospherical if they are equidistant from some point. In two dimensions, this is the same thing as being concyclic. -/ def cospherical (ps : set P) : Prop := ∃ (center : P) (radius : ℝ), ∀ p ∈ ps, dist p center = radius /-- The definition of `cospherical`. -/ lemma cospherical_def (ps : set P) : cospherical ps ↔ ∃ (center : P) (radius : ℝ), ∀ p ∈ ps, dist p center = radius := iff.rfl /-- A subset of a cospherical set is cospherical. -/ lemma cospherical_subset {ps₁ ps₂ : set P} (hs : ps₁ ⊆ ps₂) (hc : cospherical ps₂) : cospherical ps₁ := begin rcases hc with ⟨c, r, hcr⟩, exact ⟨c, r, λ p hp, hcr p (hs hp)⟩ end include V /-- The empty set is cospherical. -/ lemma cospherical_empty : cospherical (∅ : set P) := begin use add_torsor.nonempty.some, simp, end omit V /-- A single point is cospherical. -/ lemma cospherical_singleton (p : P) : cospherical ({p} : set P) := begin use p, simp end include V /-- Two points are cospherical. -/ lemma cospherical_insert_singleton (p₁ p₂ : P) : cospherical ({p₁, p₂} : set P) := begin use [(2⁻¹ : ℝ) • (p₂ -ᵥ p₁) +ᵥ p₁, (2⁻¹ : ℝ) * (dist p₂ p₁)], intro p, rw [set.mem_insert_iff, set.mem_singleton_iff], rintro ⟨_|_⟩, { rw [dist_eq_norm_vsub V p₁, vsub_vadd_eq_vsub_sub, vsub_self, zero_sub, norm_neg, norm_smul, dist_eq_norm_vsub V p₂], simp }, { rw [H, dist_eq_norm_vsub V p₂, vsub_vadd_eq_vsub_sub, dist_eq_norm_vsub V p₂], conv_lhs { congr, congr, rw ←one_smul ℝ (p₂ -ᵥ p₁ : V) }, rw [←sub_smul, norm_smul], norm_num } end /-- Any three points in a cospherical set are affinely independent. -/ lemma cospherical.affine_independent {s : set P} (hs : cospherical s) {p : fin 3 → P} (hps : set.range p ⊆ s) (hpi : function.injective p) : affine_independent ℝ p := begin rw affine_independent_iff_not_collinear, intro hc, rw collinear_iff_of_mem ℝ (set.mem_range_self (0 : fin 3)) at hc, rcases hc with ⟨v, hv⟩, rw set.forall_range_iff at hv, have hv0 : v ≠ 0, { intro h, have he : p 1 = p 0, by simpa [h] using hv 1, exact (dec_trivial : (1 : fin 3) ≠ 0) (hpi he) }, rcases hs with ⟨c, r, hs⟩, have hs' := λ i, hs (p i) (set.mem_of_mem_of_subset (set.mem_range_self _) hps), choose f hf using hv, have hsd : ∀ i, dist ((f i • v) +ᵥ p 0) c = r, { intro i, rw ←hf, exact hs' i }, have hf0 : f 0 = 0, { have hf0' := hf 0, rw [eq_comm, ←@vsub_eq_zero_iff_eq V, vadd_vsub, smul_eq_zero] at hf0', simpa [hv0] using hf0' }, have hfi : function.injective f, { intros i j h, have hi := hf i, rw [h, ←hf j] at hi, exact hpi hi }, simp_rw [←hsd 0, hf0, zero_smul, zero_vadd, dist_smul_vadd_eq_dist (p 0) c hv0] at hsd, have hfn0 : ∀ i, i ≠ 0 → f i ≠ 0 := λ i, (hfi.ne_iff' hf0).2, have hfn0' : ∀ i, i ≠ 0 → f i = (-2) * ⟪v, (p 0 -ᵥ c)⟫ / ⟪v, v⟫, { intros i hi, have hsdi := hsd i, simpa [hfn0, hi] using hsdi }, have hf12 : f 1 = f 2, { rw [hfn0' 1 dec_trivial, hfn0' 2 dec_trivial] }, exact (dec_trivial : (1 : fin 3) ≠ 2) (hfi hf12) end end euclidean_geometry
d0c0dc6ce55d7f36c97e3c4c941696eb461391b7
37a833c924892ee3ecb911484775a6d6ebb8984d
/src/category_theory/path_category.lean
edcbb581d600e4ef9136c9498e247ca6f04438d6
[]
no_license
silky/lean-category-theory
28126e80564a1f99e9c322d86b3f7d750da0afa1
0f029a2364975f56ac727d31d867a18c95c22fd8
refs/heads/master
1,589,555,811,646
1,554,673,665,000
1,554,673,665,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,256
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan and Scott Morrison import category_theory.graphs.category -- FIXME why do we need this here? @[obviously] meta def obviously_4 := tactic.tidy { tactics := extended_tidy_tactics } open category_theory open category_theory.graphs universes u₁ v₁ u₂ v₂ namespace category_theory.graphs def paths (C : Type u₂) := C instance paths_category (C : Type u₁) [graph.{u₁ v₁} C] : category.{u₁ (max u₁ v₁)} (paths C) := { hom := λ x y : C, path x y, id := λ x, path.nil x, comp := λ _ _ _ f g, concatenate_paths f g, comp_id' := begin tidy, induction f, -- PROJECT think about how to automate an inductive step. When can you be sure it's a good idea? obviously, end, assoc' := begin tidy, induction f, obviously, end }. instance paths_small_category (C : Type u₁) [graph.{u₁ u₁} C] : small_category (paths C) := graphs.paths_category C variables {C : Type u₂} [𝒞 : category.{u₂ v₂} C] {G : Type u₁} [𝒢 : graph.{u₁ v₁} G] include 𝒢 𝒞 @[simp] def path_to_morphism (H : graph_hom G C) : Π {X Y : G}, path X Y → ((H.onVertices X) ⟶ (H.onVertices Y)) | ._ ._ (path.nil Z) := 𝟙 (H.onVertices Z) | ._ ._ (@path.cons ._ _ _ _ _ e p) := (H.onEdges e) ≫ (path_to_morphism p) @[simp] lemma path_to_morphism.comp (H : graph_hom G C) {X Y Z : paths G} (f : X ⟶ Y) (g : Y ⟶ Z) : path_to_morphism H (f ≫ g) = path_to_morphism H f ≫ path_to_morphism H g := begin induction f, obviously, end end category_theory.graphs namespace category_theory.functor open category_theory.graphs variables {C : Type u₂} [𝒞 : category.{u₂ v₂} C] {G : Type u₁} [𝒢 : graph.{u₁ v₁} G] include 𝒢 𝒞 -- PROJECT obtain this as the left adjoint to the forgetful functor. @[simp] def of_graph_hom (H : graph_hom G C) : (paths G) ⥤ C := { obj := λ X, (H.onVertices X), map := λ _ _ f, (path_to_morphism H f) } end category_theory.functor
1eb546343f5e99bfd562049f6797e7071eb98a09
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/struct3.lean
073ecdda9c4a418a6d1910217e1c954c07a98c62
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
564
lean
new_frontend universes u v class HasBind2 (m : Type u → Type v) := (bind : ∀ {α β : Type u}, m α → (α → m β) → m β) set_option pp.all true class Monad2 (m : Type u → Type v) extends Applicative m, HasBind2 m : Type (max (u+1) v) := (map := fun f x => HasBind2.bind x (pure ∘ f)) (seq := fun f x => HasBind2.bind f fun y => Functor.map y x) (seqLeft := fun x y => HasBind2.bind x fun a => HasBind2.bind y fun _ => pure a) (seqRight := @fun β x y => HasBind2.bind x fun _ => y) -- Recall that `@` disables implicit lambda support
0f0a775c478582dcd45289fe97eb778b5167ae26
fe84e287c662151bb313504482b218a503b972f3
/src/algebra/power_mod.lean
52c11655dbbbf6648400a6d1d5ad3c44d298b9f2
[]
no_license
NeilStrickland/lean_lib
91e163f514b829c42fe75636407138b5c75cba83
6a9563de93748ace509d9db4302db6cd77d8f92c
refs/heads/master
1,653,408,198,261
1,652,996,419,000
1,652,996,419,000
181,006,067
4
1
null
null
null
null
UTF-8
Lean
false
false
5,475
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 monoid `M` and an element `g ∈ M` satisfying `gⁿ = 1`, we can interpret `gⁱ` for elements `i ∈ ℤ/n`. We give several different Lean versions of this idea. Some of them involve the type `zmod n`, which is Lean's implementation of `ℤ/n`. Others involve the relation `a ≡ b [MOD n]` on `ℕ`, or the relation `a ≡ b [ZMOD n]` on `ℤ`. -/ import data.fintype.basic algebra.group_power data.zmod.basic data.nat.modeq section pow_congr_monoid variables {n : ℕ} {M : Type*} [fact (0 < n)] [monoid M] {g : M} (hg : g ^ n = 1) include hg lemma pow_nat_mod (i : ℕ) : g ^ i = g ^ (i % n) := calc g ^ i = g ^ (i % (n : ℕ) + (n : ℕ) * (i / (n : ℕ))) : by rw [nat.mod_add_div i (n : ℕ)] ... = g ^ (i % (n : ℕ)) : by rw [pow_add, pow_mul, hg, one_pow, mul_one] lemma pow_nat_congr {i j : ℕ} (e : i ≡ j [MOD n]) : g ^ i = g ^ j := begin change i % n = j % n at e, rw [pow_nat_mod hg i, pow_nat_mod hg j, e] end end pow_congr_monoid section pow_congr_group variables {n : ℕ} {G : Type*} [group G] [fact (0 < n)] {g : G} (hg : g ^ (n : ℕ) = 1) include hg lemma gpow_exponent (m : ℤ) : (g ^ m) ^ (n : ℕ) = 1 := begin rw[← zpow_coe_nat, ← zpow_mul, mul_comm, zpow_mul, zpow_coe_nat, hg, one_zpow] end lemma inv_exponent : (g⁻¹) ^ (n : ℕ) = 1 := by rw [inv_pow, hg, inv_one] lemma gpow_nat_congr {i j : ℕ} (e : i ≡ j [MOD n]) : g ^ i = g ^ j := begin change i % n = j % n at e, rw [pow_nat_mod hg i, pow_nat_mod hg j, e] end lemma gpow_int_mod (i : ℤ) : g ^ i = g ^ (i % n) := by rw[← congr_arg ((^) g) (int.mod_add_div i n), zpow_add, zpow_mul, zpow_coe_nat, hg, one_zpow, mul_one] lemma gpow_int_mod' (h : n > 0) (i : ℤ) : g ^ i = g ^ (i % n).nat_abs := begin have := int.mod_nonneg i (ne_of_gt (int.coe_nat_pos.mpr h)), have : ((i % n).nat_abs : ℤ) = i % n := int.of_nat_nat_abs_eq_of_nonneg this, rw[gpow_int_mod hg, ← zpow_coe_nat, this] end lemma gpow_int_congr {i j : ℤ} (e : i ≡ j [ZMOD n]) : g ^ i = g ^ j := begin change i % n = j % n at e, rw [gpow_int_mod hg i, gpow_int_mod hg j, e] end end pow_congr_group variables (n : ℕ) [fact (0 < n)] section pow_mod variables {M : Type*} [monoid M] (g : M) instance : has_pow M (zmod n) := ⟨λ g i, g ^ i.val⟩ theorem pow_mod_eq (i : zmod n) : g ^ i = g ^ i.val := rfl @[simp] lemma one_pow_mod (i : zmod n) : (1 : M) ^ i = 1 := one_pow i.val @[simp] lemma pow_mod_zero : g ^ (0 : zmod n) = 1 := by rw[pow_mod_eq,zmod.val_zero,pow_zero] variable {n} lemma monoid_hom.map_pow_mod {N : Type*} [monoid N] (f : M →* N) (g : M) (i : zmod n) : f (g ^ i) = (f g) ^ i := f.map_pow g i.val variable (n) section with_exponent variables {n} {g} (hg : g ^ (n : ℕ) = 1) include hg lemma pow_exponent (m : ℕ) : (g ^ m) ^ (n : ℕ) = 1 := by rw [← pow_mul, mul_comm, pow_mul, hg, one_pow] lemma pow_mod_exponent (m : zmod n) : (g ^ m) ^ (n : ℕ) = 1 := pow_exponent hg m.val @[simp] lemma pow_mod_coe_nat (i : ℕ) : g ^ (i : zmod n) = g ^ i := by rw [pow_mod_eq, zmod.val_nat_cast, ← pow_nat_mod hg] @[simp] lemma pow_mod_one : g ^ (1 : zmod n) = g := begin have := pow_mod_coe_nat hg 1, rw [pow_one, nat.cast_one] at this, exact this end lemma pow_mod_add (i j : zmod n) : g ^ (i + j) = g ^ i * g ^ j := by rw [pow_mod_eq, pow_mod_eq, pow_mod_eq, ← pow_add, zmod.val_add, ← pow_nat_mod hg] lemma pow_mod_mul (i j : zmod n) : g ^ (i * j) = (g ^ i) ^ j := by rw [pow_mod_eq, pow_mod_eq, pow_mod_eq, ← pow_mul, zmod.val_mul, ← pow_nat_mod hg] end with_exponent end pow_mod section gpow_mod lemma zmod_cast_eq_cast_val (i : (zmod n)) : (i : ℤ) = (i.val : ℤ) := begin casesI n, { exfalso, exact nat.not_lt_zero 0 (fact.out _) }, { cases i with i₀ hi, change _ = int.of_nat i₀, dsimp[zmod.cast], rw[int.nat_cast_eq_coe_nat], } end variable {n} variables {G : Type*} [group G] {g : G} (hg : g ^ (n : ℕ) = 1) include hg lemma gpow_mod_eq_gpow (i : (zmod n)) : g ^ i = g ^ (i : ℤ) := begin change g ^ i.val = g ^ (i : ℤ), rw [← zpow_coe_nat g i.val], congr' 1, rw [← zmod_cast_eq_cast_val] end lemma gpow_mod_coe_int (i : ℤ) : g ^ (i : zmod n) = g ^ i := begin let j := i % n, let q := i / n, have : j + n * q = i := int.mod_add_div i n, rw[← this], rw [int.cast_add,int.cast_mul,int.cast_coe_nat,zmod.nat_cast_self, zpow_add,pow_mod_add,zero_mul,pow_mod_zero,mul_one, zpow_mul,zpow_coe_nat,hg,one_zpow,mul_one], have n_pos : 0 < n := fact.out _, have n_pos' : 0 < (n : ℤ) := by linarith, have n_nz : (n : ℤ) ≠ 0 := ne_of_gt n_pos', have j_nonneg : j ≥ 0 := int.mod_nonneg i n_nz, have j_is_lt : j < n := int.mod_lt_of_pos i n_pos', let j' := j.nat_abs, have : j = j' := int.eq_nat_abs_of_zero_le j_nonneg, rw this at j_is_lt ⊢, change g ^ (j' : zmod n).val = _, have j'_is_lt := int.coe_nat_lt.mp j_is_lt, rw [zpow_coe_nat, zmod.val_cast_of_lt j'_is_lt], exact hg end @[simp] lemma gpow_mod_neg (i : zmod n) : g ^ (- i) = (g ^ i)⁻¹ := eq_inv_iff_mul_eq_one.mpr $ by rw [← pow_mod_add hg, neg_add_self, pow_mod_zero] lemma gpow_mod_inv (i : zmod n) : g⁻¹ ^ i = g ^ (- i) := begin rw [gpow_mod_neg hg], apply eq_inv_iff_mul_eq_one.mpr, rw [pow_mod_eq, pow_mod_eq, inv_pow, mul_left_inv] end end gpow_mod
3559d43361ecd3ac9e21b6a6b2d83c3a72e4abfc
7cef822f3b952965621309e88eadf618da0c8ae9
/src/group_theory/free_abelian_group.lean
4cb7537a529484f6504c7114351736ef4d9d1592
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
11,333
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Free abelian groups as abelianization of free groups. -/ import algebra.pi_instances import group_theory.free_group import group_theory.abelianization universes u v variables (α : Type u) def free_abelian_group : Type u := additive $ abelianization $ free_group α instance : add_comm_group (free_abelian_group α) := @additive.add_comm_group _ $ abelianization.comm_group _ variable {α} namespace free_abelian_group def of (x : α) : free_abelian_group α := abelianization.of $ free_group.of x def lift {β : Type v} [add_comm_group β] (f : α → β) (x : free_abelian_group α) : β := @abelianization.lift _ _ (multiplicative β) _ (@free_group.to_group _ (multiplicative β) _ f) _ x namespace lift variables {β : Type v} [add_comm_group β] (f : α → β) open free_abelian_group instance is_add_group_hom : is_add_group_hom (lift f) := { map_add := λ x y, @is_mul_hom.map_mul _ (multiplicative β) _ _ _ (abelianization.lift.is_group_hom _).to_is_mul_hom x y } @[simp] protected lemma add (x y : free_abelian_group α) : lift f (x + y) = lift f x + lift f y := is_add_hom.map_add _ _ _ @[simp] protected lemma neg (x : free_abelian_group α) : lift f (-x) = -lift f x := is_add_group_hom.map_neg _ _ @[simp] protected lemma sub (x y : free_abelian_group α) : lift f (x - y) = lift f x - lift f y := by simp @[simp] protected lemma zero : lift f 0 = 0 := is_add_group_hom.map_zero _ @[simp] protected lemma of (x : α) : lift f (of x) = f x := by unfold of; unfold lift; simp protected theorem unique (g : free_abelian_group α → β) [is_add_group_hom g] (hg : ∀ x, g (of x) = f x) {x} : g x = lift f x := @abelianization.lift.unique (free_group α) _ (multiplicative β) _ _ _ g { map_mul := λ x y, is_add_hom.map_add g x y } (λ x, @free_group.to_group.unique α (multiplicative β) _ _ (g ∘ abelianization.of) { map_mul := λ m n, is_add_hom.map_add g (abelianization.of m) (abelianization.of n) } hg _) _ protected theorem ext (g h : free_abelian_group α → β) [is_add_group_hom g] [is_add_group_hom h] (H : ∀ x, g (of x) = h (of x)) {x} : g x = h x := (lift.unique (g ∘ of) g (λ _, rfl)).trans $ eq.symm $ lift.unique _ _ $ λ x, eq.symm $ H x lemma map_hom {α β γ} [add_comm_group β] [add_comm_group γ] (a : free_abelian_group α) (f : α → β) (g : β → γ) [is_add_group_hom g] : g (a.lift f) = a.lift (g ∘ f) := show (g ∘ lift f) a = a.lift (g ∘ f), begin apply @lift.unique, assume a, simp only [(∘), lift.of] end def universal : (α → β) ≃ { f : free_abelian_group α → β // is_add_group_hom f } := { to_fun := λ f, ⟨_, lift.is_add_group_hom f⟩, inv_fun := λ f, f.1 ∘ of, left_inv := λ f, funext $ λ x, lift.of f x, right_inv := λ f, subtype.eq $ funext $ λ x, eq.symm $ by letI := f.2; from lift.unique _ _ (λ _, rfl) } end lift local attribute [instance] quotient_group.left_rel normal_subgroup.to_is_subgroup @[elab_as_eliminator] protected theorem induction_on {C : free_abelian_group α → Prop} (z : free_abelian_group α) (C0 : C 0) (C1 : ∀ x, C $ of x) (Cn : ∀ x, C (of x) → C (-of x)) (Cp : ∀ x y, C x → C y → C (x + y)) : C z := quotient.induction_on z $ λ x, quot.induction_on x $ λ L, list.rec_on L C0 $ λ ⟨x, b⟩ tl ih, bool.rec_on b (Cp _ _ (Cn _ (C1 x)) ih) (Cp _ _ (C1 x) ih) theorem lift.add' {α β} [add_comm_group β] (a : free_abelian_group α) (f g : α → β) : a.lift (f + g) = (a.lift f) + (a.lift g) := begin refine free_abelian_group.induction_on a _ _ _ _, { simp only [lift.zero, zero_add] }, { assume x, simp only [lift.of, pi.add_apply] }, { assume x h, simp only [lift.neg, lift.of, pi.add_apply, neg_add] }, { assume x y hx hy, simp only [lift.add, hx, hy], ac_refl } end instance is_add_group_hom_lift' {α} (β) [add_comm_group β] (a : free_abelian_group α) : is_add_group_hom (λf, (a.lift f : β)) := { map_add := λ f g, lift.add' a f g } variables {β : Type u} instance : monad free_abelian_group.{u} := { pure := λ α, of, bind := λ α β x f, lift f x } @[elab_as_eliminator] protected theorem induction_on' {C : free_abelian_group α → Prop} (z : free_abelian_group α) (C0 : C 0) (C1 : ∀ x, C $ pure x) (Cn : ∀ x, C (pure x) → C (-pure x)) (Cp : ∀ x y, C x → C y → C (x + y)) : C z := free_abelian_group.induction_on z C0 C1 Cn Cp @[simp] lemma map_pure (f : α → β) (x : α) : f <$> (pure x : free_abelian_group α) = pure (f x) := lift.of _ _ @[simp] lemma map_zero (f : α → β) : f <$> (0 : free_abelian_group α) = 0 := lift.zero (of ∘ f) @[simp] lemma map_add (f : α → β) (x y : free_abelian_group α) : f <$> (x + y) = f <$> x + f <$> y := lift.add _ _ _ @[simp] lemma map_neg (f : α → β) (x : free_abelian_group α) : f <$> (-x) = -(f <$> x) := lift.neg _ _ @[simp] lemma map_sub (f : α → β) (x y : free_abelian_group α) : f <$> (x - y) = f <$> x - f <$> y := lift.sub _ _ _ @[simp] lemma pure_bind (f : α → free_abelian_group β) (x) : pure x >>= f = f x := lift.of _ _ @[simp] lemma zero_bind (f : α → free_abelian_group β) : 0 >>= f = 0 := lift.zero f @[simp] lemma add_bind (f : α → free_abelian_group β) (x y : free_abelian_group α) : x + y >>= f = (x >>= f) + (y >>= f) := lift.add _ _ _ @[simp] lemma neg_bind (f : α → free_abelian_group β) (x : free_abelian_group α) : -x >>= f = -(x >>= f) := lift.neg _ _ @[simp] lemma sub_bind (f : α → free_abelian_group β) (x y : free_abelian_group α) : x - y >>= f = (x >>= f) - (y >>= f) := lift.sub _ _ _ @[simp] lemma pure_seq (f : α → β) (x : free_abelian_group α) : pure f <*> x = f <$> x := pure_bind _ _ @[simp] lemma zero_seq (x : free_abelian_group α) : (0 : free_abelian_group (α → β)) <*> x = 0 := zero_bind _ @[simp] lemma add_seq (f g : free_abelian_group (α → β)) (x : free_abelian_group α) : f + g <*> x = (f <*> x) + (g <*> x) := add_bind _ _ _ @[simp] lemma neg_seq (f : free_abelian_group (α → β)) (x : free_abelian_group α) : -f <*> x = -(f <*> x) := neg_bind _ _ @[simp] lemma sub_seq (f g : free_abelian_group (α → β)) (x : free_abelian_group α) : f - g <*> x = (f <*> x) - (g <*> x) := sub_bind _ _ _ instance is_add_group_hom_seq (f : free_abelian_group (α → β)) : is_add_group_hom ((<*>) f) := { map_add := λ x y, show lift (<$> (x+y)) _ = _, by simp only [map_add]; exact @@is_add_hom.map_add _ _ _ (@@free_abelian_group.is_add_group_hom_lift' (free_abelian_group β) _ _).to_is_add_hom _ _ } @[simp] lemma seq_zero (f : free_abelian_group (α → β)) : f <*> 0 = 0 := is_add_group_hom.map_zero _ @[simp] lemma seq_add (f : free_abelian_group (α → β)) (x y : free_abelian_group α) : f <*> (x + y) = (f <*> x) + (f <*> y) := is_add_hom.map_add _ _ _ @[simp] lemma seq_neg (f : free_abelian_group (α → β)) (x : free_abelian_group α) : f <*> (-x) = -(f <*> x) := is_add_group_hom.map_neg _ _ @[simp] lemma seq_sub (f : free_abelian_group (α → β)) (x y : free_abelian_group α) : f <*> (x - y) = (f <*> x) - (f <*> y) := is_add_group_hom.map_sub _ _ _ instance : is_lawful_monad free_abelian_group.{u} := { id_map := λ α x, free_abelian_group.induction_on' x (map_zero id) (λ x, map_pure id x) (λ x ih, by rw [map_neg, ih]) (λ x y ihx ihy, by rw [map_add, ihx, ihy]), pure_bind := λ α β x f, pure_bind f x, bind_assoc := λ α β γ x f g, free_abelian_group.induction_on' x (by iterate 3 { rw zero_bind }) (λ x, by iterate 2 { rw pure_bind }) (λ x ih, by iterate 3 { rw neg_bind }; rw ih) (λ x y ihx ihy, by iterate 3 { rw add_bind }; rw [ihx, ihy]) } instance : is_comm_applicative free_abelian_group.{u} := { commutative_prod := λ α β x y, free_abelian_group.induction_on' x (by rw [map_zero, zero_seq, seq_zero]) (λ p, by rw [map_pure, pure_seq]; exact free_abelian_group.induction_on' y (by rw [map_zero, map_zero, zero_seq]) (λ q, by rw [map_pure, map_pure, pure_seq, map_pure]) (λ q ih, by rw [map_neg, map_neg, neg_seq, ih]) (λ y₁ y₂ ih1 ih2, by rw [map_add, map_add, add_seq, ih1, ih2])) (λ p ih, by rw [map_neg, neg_seq, seq_neg, ih]) (λ x₁ x₂ ih1 ih2, by rw [map_add, add_seq, seq_add, ih1, ih2]) } variable (α) instance [monoid α] : semigroup (free_abelian_group α) := { mul := λ x, lift $ λ x₂, lift (λ x₁, of $ x₁ * x₂) x, mul_assoc := λ x y z, begin unfold has_mul.mul, refine free_abelian_group.induction_on z rfl _ _ _, { intros L3, rw [lift.of, lift.of], refine free_abelian_group.induction_on y rfl _ _ _, { intros L2, iterate 3 { rw lift.of }, refine free_abelian_group.induction_on x rfl _ _ _, { intros L1, iterate 3 { rw lift.of }, congr' 1, exact mul_assoc _ _ _ }, { intros L1 ih, iterate 3 { rw lift.neg }, rw ih }, { intros x1 x2 ih1 ih2, iterate 3 { rw lift.add }, rw [ih1, ih2] } }, { intros L2 ih, iterate 4 { rw lift.neg }, rw ih }, { intros y1 y2 ih1 ih2, iterate 4 { rw lift.add }, rw [ih1, ih2] } }, { intros L3 ih, iterate 3 { rw lift.neg }, rw ih }, { intros z1 z2 ih1 ih2, iterate 2 { rw lift.add }, rw [ih1, ih2], exact (lift.add _ _ _).symm } end } instance [monoid α] : ring (free_abelian_group α) := { one := free_abelian_group.of 1, mul_one := λ x, begin unfold has_mul.mul semigroup.mul has_one.one, rw lift.of, refine free_abelian_group.induction_on x rfl _ _ _, { intros L, erw [lift.of], congr' 1, exact mul_one L }, { intros L ih, rw [lift.neg, ih] }, { intros x1 x2 ih1 ih2, rw [lift.add, ih1, ih2] } end, one_mul := λ x, begin unfold has_mul.mul semigroup.mul has_one.one, refine free_abelian_group.induction_on x rfl _ _ _, { intros L, rw [lift.of, lift.of], congr' 1, exact one_mul L }, { intros L ih, rw [lift.neg, ih] }, { intros x1 x2 ih1 ih2, rw [lift.add, ih1, ih2] } end, left_distrib := λ x y z, lift.add _ _ _, right_distrib := λ x y z, begin unfold has_mul.mul semigroup.mul, refine free_abelian_group.induction_on z rfl _ _ _, { intros L, iterate 3 { rw lift.of }, rw lift.add, refl }, { intros L ih, iterate 3 { rw lift.neg }, rw [ih, neg_add], refl }, { intros z1 z2 ih1 ih2, iterate 3 { rw lift.add }, rw [ih1, ih2], rw [add_assoc, add_assoc], congr' 1, apply add_left_comm } end, .. free_abelian_group.add_comm_group α, .. free_abelian_group.semigroup α } instance [comm_monoid α] : comm_ring (free_abelian_group α) := { mul_comm := λ x y, begin refine free_abelian_group.induction_on x (zero_mul y) _ _ _, { intros s, refine free_abelian_group.induction_on y (zero_mul _).symm _ _ _, { intros t, unfold has_mul.mul semigroup.mul ring.mul, iterate 4 { rw lift.of }, congr' 1, exact mul_comm _ _ }, { intros t ih, rw [mul_neg_eq_neg_mul_symm, ih, neg_mul_eq_neg_mul] }, { intros y1 y2 ih1 ih2, rw [mul_add, add_mul, ih1, ih2] } }, { intros s ih, rw [neg_mul_eq_neg_mul_symm, ih, neg_mul_eq_mul_neg] }, { intros x1 x2 ih1 ih2, rw [add_mul, mul_add, ih1, ih2] } end .. free_abelian_group.ring α } end free_abelian_group
f8cb052f526ba8ea57564711542ac700a7a936da
63abd62053d479eae5abf4951554e1064a4c45b4
/src/field_theory/finite/polynomial.lean
a4b00eccfe434bdc3aded80d19e5b12ac0a4b099
[ "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
7,505
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import field_theory.finite.basic import field_theory.mv_polynomial import data.mv_polynomial.expand import linear_algebra.basic /-! ## Polynomials over finite fields -/ namespace mv_polynomial variables {σ : Type*} /-- A polynomial over the integers is divisible by `n : ℕ` if and only if it is zero over `zmod n`. -/ lemma C_dvd_iff_zmod (n : ℕ) (φ : mv_polynomial σ ℤ) : C (n:ℤ) ∣ φ ↔ map (int.cast_ring_hom (zmod n)) φ = 0 := C_dvd_iff_map_hom_eq_zero _ _ (char_p.int_cast_eq_zero_iff (zmod n) n) _ section frobenius variables {p : ℕ} [fact p.prime] lemma frobenius_zmod (f : mv_polynomial σ (zmod p)) : frobenius _ p f = expand p f := begin apply induction_on f, { intro a, rw [expand_C, frobenius_def, ← C_pow, zmod.pow_card], }, { simp only [alg_hom.map_add, ring_hom.map_add], intros _ _ hf hg, rw [hf, hg] }, { simp only [expand_X, ring_hom.map_mul, alg_hom.map_mul], intros _ _ hf, rw [hf, frobenius_def], }, end lemma expand_zmod (f : mv_polynomial σ (zmod p)) : expand p f = f ^ p := (frobenius_zmod _).symm end frobenius end mv_polynomial namespace mv_polynomial noncomputable theory open_locale big_operators classical open set linear_map submodule variables {K : Type*} {σ : Type*} variables [field K] [fintype K] [fintype σ] def indicator (a : σ → K) : mv_polynomial σ K := ∏ n, (1 - (X n - C (a n))^(fintype.card K - 1)) lemma eval_indicator_apply_eq_one (a : σ → K) : eval a (indicator a) = 1 := have 0 < fintype.card K - 1, begin rw [← finite_field.card_units, fintype.card_pos_iff], exact ⟨1⟩ end, by simp only [indicator, (finset.univ.prod_hom (eval a)).symm, ring_hom.map_sub, is_ring_hom.map_one (eval a), is_monoid_hom.map_pow (eval a), eval_X, eval_C, sub_self, zero_pow this, sub_zero, finset.prod_const_one] lemma eval_indicator_apply_eq_zero (a b : σ → K) (h : a ≠ b) : eval a (indicator b) = 0 := have ∃i, a i ≠ b i, by rwa [(≠), function.funext_iff, not_forall] at h, begin rcases this with ⟨i, hi⟩, simp only [indicator, (finset.univ.prod_hom (eval a)).symm, ring_hom.map_sub, is_ring_hom.map_one (eval a), is_monoid_hom.map_pow (eval a), eval_X, eval_C, sub_self, finset.prod_eq_zero_iff], refine ⟨i, finset.mem_univ _, _⟩, rw [finite_field.pow_card_sub_one_eq_one, sub_self], rwa [(≠), sub_eq_zero], end lemma degrees_indicator (c : σ → K) : degrees (indicator c) ≤ ∑ s : σ, (fintype.card K - 1) •ℕ {s} := begin rw [indicator], refine le_trans (degrees_prod _ _) (finset.sum_le_sum $ assume s hs, _), refine le_trans (degrees_sub _ _) _, rw [degrees_one, ← bot_eq_zero, bot_sup_eq], refine le_trans (degrees_pow _ _) (nsmul_le_nsmul_of_le_right _ _), refine le_trans (degrees_sub _ _) _, rw [degrees_C, ← bot_eq_zero, sup_bot_eq], exact degrees_X _ end lemma indicator_mem_restrict_degree (c : σ → K) : indicator c ∈ restrict_degree σ K (fintype.card K - 1) := begin rw [mem_restrict_degree_iff_sup, indicator], assume n, refine le_trans (multiset.count_le_of_le _ $ degrees_indicator _) (le_of_eq _), rw [← finset.univ.sum_hom (multiset.count n)], simp only [is_add_monoid_hom.map_nsmul (multiset.count n), multiset.singleton_eq_singleton, nsmul_eq_mul, nat.cast_id], transitivity, refine finset.sum_eq_single n _ _, { assume b hb ne, rw [multiset.count_cons_of_ne ne.symm, multiset.count_zero, mul_zero] }, { assume h, exact (h $ finset.mem_univ _).elim }, { rw [multiset.count_cons_self, multiset.count_zero, mul_one] } end section variables (K σ) def evalₗ : mv_polynomial σ K →ₗ[K] (σ → K) → K := ⟨ λp e, eval e p, assume p q, (by { ext x, rw ring_hom.map_add, refl, }), assume a p, funext $ assume e, by rw [smul_eq_C_mul, ring_hom.map_mul, eval_C]; refl ⟩ end lemma evalₗ_apply (p : mv_polynomial σ K) (e : σ → K) : evalₗ K σ p e = eval e p := rfl lemma map_restrict_dom_evalₗ : (restrict_degree σ K (fintype.card K - 1)).map (evalₗ K σ) = ⊤ := begin refine top_unique (submodule.le_def'.2 $ assume e _, mem_map.2 _), refine ⟨∑ n : σ → K, e n • indicator n, _, _⟩, { exact sum_mem _ (assume c _, smul_mem _ _ (indicator_mem_restrict_degree _)) }, { ext n, simp only [linear_map.map_sum, @finset.sum_apply (σ → K) (λ_, K) _ _ _ _ _, pi.smul_apply, linear_map.map_smul], simp only [evalₗ_apply], transitivity, refine finset.sum_eq_single n _ _, { assume b _ h, rw [eval_indicator_apply_eq_zero _ _ h.symm, smul_zero] }, { assume h, exact (h $ finset.mem_univ n).elim }, { rw [eval_indicator_apply_eq_one, smul_eq_mul, mul_one] } } end end mv_polynomial namespace mv_polynomial open_locale classical open linear_map submodule universe u variables (σ : Type u) (K : Type u) [fintype σ] [field K] [fintype K] @[derive [add_comm_group, vector_space K, inhabited]] def R : Type u := restrict_degree σ K (fintype.card K - 1) noncomputable instance decidable_restrict_degree (m : ℕ) : decidable_pred (λn, n ∈ {n : σ →₀ ℕ | ∀i, n i ≤ m }) := by simp only [set.mem_set_of_eq]; apply_instance lemma dim_R : vector_space.dim K (R σ K) = fintype.card (σ → K) := calc vector_space.dim K (R σ K) = vector_space.dim K (↥{s : σ →₀ ℕ | ∀ (n : σ), s n ≤ fintype.card K - 1} →₀ K) : linear_equiv.dim_eq (finsupp.supported_equiv_finsupp {s : σ →₀ ℕ | ∀n:σ, s n ≤ fintype.card K - 1 }) ... = cardinal.mk {s : σ →₀ ℕ | ∀ (n : σ), s n ≤ fintype.card K - 1} : by rw [finsupp.dim_eq, dim_of_field, mul_one] ... = cardinal.mk {s : σ → ℕ | ∀ (n : σ), s n < fintype.card K } : begin refine quotient.sound ⟨equiv.subtype_congr finsupp.equiv_fun_on_fintype $ assume f, _⟩, refine forall_congr (assume n, nat.le_sub_right_iff_add_le _), exact fintype.card_pos_iff.2 ⟨0⟩ end ... = cardinal.mk (σ → {n // n < fintype.card K}) : quotient.sound ⟨@equiv.subtype_pi_equiv_pi σ (λ_, ℕ) (λs n, n < fintype.card K)⟩ ... = cardinal.mk (σ → fin (fintype.card K)) : quotient.sound ⟨equiv.arrow_congr (equiv.refl σ) (equiv.fin_equiv_subtype _).symm⟩ ... = cardinal.mk (σ → K) : begin refine (trunc.induction_on (fintype.equiv_fin K) $ assume (e : K ≃ fin (fintype.card K)), _), refine quotient.sound ⟨equiv.arrow_congr (equiv.refl σ) e.symm⟩ end ... = fintype.card (σ → K) : cardinal.fintype_card _ def evalᵢ : R σ K →ₗ[K] (σ → K) → K := ((evalₗ K σ).comp (restrict_degree σ K (fintype.card K - 1)).subtype) lemma range_evalᵢ : (evalᵢ σ K).range = ⊤ := begin rw [evalᵢ, linear_map.range_comp, range_subtype], exact map_restrict_dom_evalₗ end lemma ker_evalₗ : (evalᵢ σ K).ker = ⊥ := begin refine injective_of_surjective _ _ _ (range_evalᵢ _ _), { rw [dim_R], exact cardinal.nat_lt_omega _ }, { rw [dim_R, dim_fun, dim_of_field, mul_one] } end lemma eq_zero_of_eval_eq_zero (p : mv_polynomial σ K) (h : ∀v:σ → K, eval v p = 0) (hp : p ∈ restrict_degree σ K (fintype.card K - 1)) : p = 0 := let p' : R σ K := ⟨p, hp⟩ in have p' ∈ (evalᵢ σ K).ker := by { rw [mem_ker], ext v, exact h v }, show p'.1 = (0 : R σ K).1, begin rw [ker_evalₗ, mem_bot] at this, rw [this] end end mv_polynomial
6ebec2067ab4ba00613282729511bb16d67bb99f
7cef822f3b952965621309e88eadf618da0c8ae9
/src/category_theory/products/basic.lean
2ca66f8ff0205227f144fed5c8c27c2ced395894
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
5,504
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.equivalence import category_theory.eq_to_hom import tactic.interactive namespace category_theory universes v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄ -- declare the `v`'s first; see `category_theory.category` for an explanation section variables (C : Type u₁) [𝒞 : category.{v₁} C] (D : Type u₂) [𝒟 : category.{v₂} D] include 𝒞 𝒟 /-- `prod C D` gives the cartesian product of two categories. -/ instance prod : category.{max v₁ v₂} (C × D) := { hom := λ X Y, ((X.1) ⟶ (Y.1)) × ((X.2) ⟶ (Y.2)), id := λ X, ⟨ 𝟙 (X.1), 𝟙 (X.2) ⟩, comp := λ _ _ _ f g, (f.1 ≫ g.1, f.2 ≫ g.2) } -- rfl lemmas for category.prod @[simp] lemma prod_id (X : C) (Y : D) : 𝟙 (X, Y) = (𝟙 X, 𝟙 Y) := rfl @[simp] lemma prod_comp {P Q R : C} {S T U : D} (f : (P, S) ⟶ (Q, T)) (g : (Q, T) ⟶ (R, U)) : f ≫ g = (f.1 ≫ g.1, f.2 ≫ g.2) := rfl @[simp] lemma prod_id_fst (X : prod C D) : _root_.prod.fst (𝟙 X) = 𝟙 X.fst := rfl @[simp] lemma prod_id_snd (X : prod C D) : _root_.prod.snd (𝟙 X) = 𝟙 X.snd := rfl @[simp] lemma prod_comp_fst {X Y Z : prod C D} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).1 = f.1 ≫ g.1 := rfl @[simp] lemma prod_comp_snd {X Y Z : prod C D} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).2 = f.2 ≫ g.2 := rfl end section variables (C : Type u₁) [𝒞 : category.{v₁} C] (D : Type u₁) [𝒟 : category.{v₁} D] include 𝒞 𝒟 /-- `prod.category.uniform C D` is an additional instance specialised so both factors have the same universe levels. This helps typeclass resolution. -/ instance uniform_prod : category (C × D) := category_theory.prod C D end -- Next we define the natural functors into and out of product categories. For now this doesn't address the universal properties. namespace prod variables (C : Type u₁) [𝒞 : category.{v₁} C] (D : Type u₂) [𝒟 : category.{v₂} D] include 𝒞 𝒟 /-- `inl C Z` is the functor `X ↦ (X, Z)`. -/ -- Here and below we specify explicitly the projections to generate `@[simp]` lemmas for, -- as the default behaviour of `@[simps]` will generate projections all the way down to components of pairs. @[simps obj map] def inl (Z : D) : C ⥤ C × D := { obj := λ X, (X, Z), map := λ X Y f, (f, 𝟙 Z) } /-- `inr D Z` is the functor `X ↦ (Z, X)`. -/ @[simps obj map] def inr (Z : C) : D ⥤ C × D := { obj := λ X, (Z, X), map := λ X Y f, (𝟙 Z, f) } /-- `fst` is the functor `(X, Y) ↦ X`. -/ @[simps obj map] def fst : C × D ⥤ C := { obj := λ X, X.1, map := λ X Y f, f.1 } /-- `snd` is the functor `(X, Y) ↦ Y`. -/ @[simps obj map] def snd : C × D ⥤ D := { obj := λ X, X.2, map := λ X Y f, f.2 } @[simps obj map] def swap : C × D ⥤ D × C := { obj := λ X, (X.2, X.1), map := λ _ _ f, (f.2, f.1) } @[simps hom_app inv_app] def symmetry : swap C D ⋙ swap D C ≅ 𝟭 (C × D) := { hom := { app := λ X, 𝟙 X }, inv := { app := λ X, 𝟙 X } } def braiding : C × D ≌ D × C := equivalence.mk (swap C D) (swap D C) (nat_iso.of_components (λ X, eq_to_iso (by simp)) (by tidy)) (nat_iso.of_components (λ X, eq_to_iso (by simp)) (by tidy)) instance swap_is_equivalence : is_equivalence (swap C D) := (by apply_instance : is_equivalence (braiding C D).functor) end prod section variables (C : Type u₁) [𝒞 : category.{v₁} C] (D : Type u₂) [𝒟 : category.{v₂} D] include 𝒞 𝒟 @[simps] def evaluation : C ⥤ (C ⥤ D) ⥤ D := { obj := λ X, { obj := λ F, F.obj X, map := λ F G α, α.app X, }, map := λ X Y f, { app := λ F, F.map f, naturality' := λ F G α, eq.symm (α.naturality f) } } @[simps obj map] def evaluation_uncurried : C × (C ⥤ D) ⥤ D := { obj := λ p, p.2.obj p.1, map := λ x y f, (x.2.map f.1) ≫ (f.2.app y.1), map_comp' := λ X Y Z f g, begin cases g, cases f, cases Z, cases Y, cases X, simp only [prod_comp, nat_trans.comp_app, functor.map_comp, category.assoc], rw [←nat_trans.comp_app, nat_trans.naturality, nat_trans.comp_app, category.assoc, nat_trans.naturality], end } end variables {A : Type u₁} [𝒜 : category.{v₁} A] {B : Type u₂} [ℬ : category.{v₂} B] {C : Type u₃} [𝒞 : category.{v₃} C] {D : Type u₄} [𝒟 : category.{v₄} D] include 𝒜 ℬ 𝒞 𝒟 namespace functor /-- The cartesian product of two functors. -/ @[simps obj map] def prod (F : A ⥤ B) (G : C ⥤ D) : A × C ⥤ B × D := { obj := λ X, (F.obj X.1, G.obj X.2), map := λ _ _ f, (F.map f.1, G.map f.2) } /- Because of limitations in Lean 3's handling of notations, we do not setup a notation `F × G`. You can use `F.prod G` as a "poor man's infix", or just write `functor.prod F G`. -/ end functor namespace nat_trans /-- The cartesian product of two natural transformations. -/ @[simps app] def prod {F G : A ⥤ B} {H I : C ⥤ D} (α : F ⟶ G) (β : H ⟶ I) : F.prod H ⟶ G.prod I := { app := λ X, (α.app X.1, β.app X.2), naturality' := λ X Y f, begin cases X, cases Y, simp only [functor.prod_map, prod.mk.inj_iff, prod_comp], split; rw naturality end } /- Again, it is inadvisable in Lean 3 to setup a notation `α × β`; use instead `α.prod β` or `nat_trans.prod α β`. -/ end nat_trans end category_theory
924cc3e64b3ec62d25afec018d532c6b23f90032
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/archive/100-theorems-list/42_inverse_triangle_sum.lean
6e83289b02df5943977781c4abebf9ac9e12ff0a
[ "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
998
lean
/- Copyright (c) 2020. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jalex Stark, Yury Kudryashov -/ import data.real.basic /-! # Sum of the Reciprocals of the Triangular Numbers This file proves Theorem 42 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/). We interpret “triangular numbers” as naturals of the form $\frac{k(k+1)}{2}$ for natural `k`. We prove that the sum of the first `n` triangular numbers is equal to $2 - \frac2n$. ## Tags discrete_sum -/ open_locale big_operators open finset lemma inverse_triangle_sum : ∀ n, ∑ k in range n, (2 : ℚ) / (k * (k + 1)) = if n = 0 then 0 else 2 - (2 : ℚ) / n := begin refine sum_range_induction _ _ (if_pos rfl) _, rintro (_|n), { rw [if_neg, if_pos]; norm_num }, simp_rw [if_neg (nat.succ_ne_zero _), nat.succ_eq_add_one], have A : (n + 1 + 1 : ℚ) ≠ 0, by { norm_cast, norm_num }, push_cast, field_simp [nat.cast_add_one_ne_zero], ring end
0092ccae8fd9a45c1d191e738073b92653b9aff6
3446e92e64a5de7ed1f2109cfb024f83cd904c34
/src/game/world3/level2.lean
11b0b46eaa4f86ed3d99f38f46274e160c7e2d56
[]
no_license
kckennylau/natural_number_game
019f4a5f419c9681e65234ecd124c564f9a0a246
ad8c0adaa725975be8a9f978c8494a39311029be
refs/heads/master
1,598,784,137,722
1,571,905,156,000
1,571,905,156,000
218,354,686
0
0
null
1,572,373,319,000
1,572,373,318,000
null
UTF-8
Lean
false
false
720
lean
import game.world3.level1 -- hide import mynat.mul -- hide namespace mynat -- hide /- # Multiplication World ## Level 2: `mul_one` Currently our tools for multiplication are the following: * `mul_zero : ∀ m, m * 0 = 0` * `zero_mul : ∀ m, 0 * m = m` * `mul_succ : ∀ a b, a * succ b = a * b + b` We also have * `one_eq_succ_zero : 1 = succ(0)` which will be a useful thing to rewrite as we now begin to prove a couple of lemmas about how `1` behaves with respect to multiplication. -/ /- Lemma For any natural number $m$, we have $$ m * 1 = m. $$ -/ lemma mul_one (m : mynat) : m * 1 = m := begin [less_leaky] rw one_eq_succ_zero, rw mul_succ, rw mul_zero, exact zero_add m, end end mynat -- hide
87ab144900c7a04f1941500521aab62f84315fc4
5b0c53e5aaa0e60538d10f6b619a464aaf463815
/ch1.hlean
3439e8717999c16f2e2af0ff7a20b84069e41e61
[ "Apache-2.0" ]
permissive
bbentzen/hott-book-in-lean
f845a19ef09d48d2fb813624b4650d5832a47e10
9e262e633e653280b9cde5d287631fcec8501f64
refs/heads/master
1,586,430,679,994
1,519,975,089,000
1,519,975,089,000
50,330,220
1
0
null
null
null
null
UTF-8
Lean
false
false
5,342
hlean
/- Copyright (c) 2015 Bruno Bentzen. All rights reserved. Released under the Apache License 2.0 (see "License"); Theorems and exercises of the HoTT book (Chapter 1) -/ /- ************************************** -/ /- Ch.1 Type Theory -/ /- ************************************** -/ open eq variables {A B C D: Type} /- §1.4 Dependent function types (Π-Types) -/ definition swap (A B C: Type) : (A → B → C) → (B → A → C) := λ f b a, f a b -- /- §1.5 Product types -/ open prod unit notation `𝟭` := unit notation `⋆` := star -- Product uniqueness principle definition uppt (x : A × B) : x = (pr1 x, pr2 x) := prod.rec_on x (λ a b, refl _) -- /- §1.6 Dependent pair types (Σ-Types) -/ open sigma definition ac (A B : Type) (R : A → B → Type) : (Π (x : A), Σ (y : B), R x y ) → (Σ (f : A → B), Π (x : A), R x (f x)) := λ g, ⟨ λ x, pr1 (g x), λ x, pr2 (g x)⟩ definition magma : Type := Σ (A : Type), A → A → A definition pointedmagma : Type := (Σ (A : Type), A → A → A) × A -- /- §1.7 Coproduct types -/ open sum empty notation `𝟬` := empty -- /- §1.8 The type of booleans -/ open bool notation `𝟮` := bool definition upbool (x : 𝟮) : (x = ff) + (x = tt) := bool.rec_on x (inl (refl ff)) (inr (refl tt)) -- /- §1.9 The natural numbers -/ open nat definition double : Π (x : ℕ ), ℕ | double 0 := 0 | double (succ n) := succ (succ (double n)) definition add (m n : ℕ) : ℕ := nat.rec m (λ n add_n, succ (add_n)) n definition assoc (i j k : ℕ) : i + (j + k) = (i + j) + k := by induction k with k IH; reflexivity; apply (calc i + (j + (succ k)) = i + (succ (j + k)) : idp ... = succ (i + (j + k)) : idp ... = succ ((i + j) + k) : IH) /- §1.11 Proposition-as-types -/ definition dmorganpt: (A → 𝟬) × (B → 𝟬) → ( A + B ) → 𝟬 := λ p, prod.rec_on p (λ x y, (λ (z : A + B), sum.rec_on z (λ a, x a) (λ b, y b) ) ) definition dmorgansum: (A + B → 𝟬) → (A → 𝟬) × (B → 𝟬) := λ p, ( λ a, p (inl a) , λ b, p (inr b) ) example (P Q : A → Type) : (Π (x : A), P (x) × Q (x) ) → (Π (x : A), P (x)) × (Π (x : A), Q (x)) := λ p, ( λ x, pr1 (p x), λ x, pr2 (p x) ) definition leq (n m : ℕ) : Type₀ := Σ (k : ℕ), n + k = m notation n `≤` m := leq n m definition less (n m : ℕ) : Type₀ := Σ (k : ℕ), n + (succ k) = m notation n `<` m := less n m definition semigroup : Type := Σ (A : Type), A → A → A /- §1.12 Identity types -/ -- §1.12.1 Path induction -- For this section only, we define a 'path induction' version of equality inductive eq' {A : Type} : Π (x y : A), Type := | refl : Π (a : A), (eq' a a) -- §1.12.1 Equivalence of path induction and based path induction -- Path induction to Based path induction definition ind_eq_to_bind_eq {A : Type} {a : A} {C : Π (x : A), eq' a x → Type} {x : A} (p : eq' a x) (c : C a (eq'.refl a)) : C x p := (@eq'.rec_on A (λ x y p, Π (C : (Π (z : A), eq' x z → Type)), (C x (eq'.refl x)) → C y p)) a x p (λ a' C' c', c') C c -- Based path induction to Path induction definition bind_eq_to_ind_eq (f : Π (A : Type) (a : A) (C : Π (x : A), eq' a x → Type) (x : A) (p : eq' a x) (c : C a (eq'.refl a)), C x p) {A : Type} {C : Π (x y : A), eq' x y → Type} {x y : A} (p : eq' x y) (c : Π (a : A), C a a (eq'.refl a)) : C x y p := f A x (C x) y p (c x) -- §1.12.2 Disequality -- -- No formalizable content. -- /- Exercises -/ -- 1.1 Given functions f : A ! B and g : B ! C, define their composite g ∘ f : A → C. Show that we have h ∘ (g ∘ f) = (h ∘ g) ∘ f. definition comp (g : B → C) (f : A → B) : A → C := λ (x : A), g (f (x)) notation g `∘` f := comp g f definition comp_assoc (f : A → B) (g : B → C) (h : C → D) : h ∘ (g ∘ f) = (h ∘ g) ∘ f := idp -- -- 1.11 Show that for any type A, we have ¬¬¬A → ¬A. definition ndne : (((A → 𝟬) → 𝟬) → 𝟬) → (A → 𝟬) := λ p a, p ((λ a p, p a) a) -- -- 1.13 Using the proposition-as-types, derive the double negation of the principle of excluded middle, i.e. prove (not (not (P or not P))) definition dnlem : ((A + (A → 𝟬)) → 𝟬) → 𝟬 := λ p, (pr2 (dmorgansum p)) (pr1 (dmorgansum p)) -- -- 1.15 Show that the indiscernability of identicals follows from path induction example (a b : A) (P : A → Type) : a = b → P a → P b := λ p u, eq.rec_on p u -- /-- Other useful lemmas --/ definition id (A : Type) : A → A := λ (x : A), x definition ant [reducible] (m : ℕ) : ℕ := nat.rec 0 (λ m ant_m, m) m -- Interplay between transport and pathovers (used in ch 6) universe variables l i definition cancel_tr_pathover {A : Type.{l}} {x y : A} {P : A → Type.{i}} {p : x = y} {u : P x} {v : P y} (α : transport P p u = v) : tr_eq_of_pathover.{l i} (pathover_of_tr_eq α) = α := by cases p; cases α; apply idp definition apdo_to_apd {P : A → Type} {x y : A} (f : Π (x : A), P x) (p : x = y) : tr_eq_of_pathover (apdo f p) = apd f p := by induction p; unfold apdo -- notation a `=⟨`:50 p:0 `⟩`:0 b:50 := (transport _ p a) = b --
42d3e674898295b714622e392aeea7f06f7ac580
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/nat/choose/dvd.lean
11c3114090e97cbce0139742d9f239349f83b926
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
1,336
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Patrick Stevens -/ import data.nat.choose.basic import data.nat.prime /-! # Divisibility properties of binomial coefficients > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ namespace nat open_locale nat namespace prime lemma dvd_choose_add {p a b : ℕ} (hap : a < p) (hbp : b < p) (h : p ≤ a + b) (hp : prime p) : p ∣ choose (a + b) a := have h₁ : p ∣ (a + b)!, from hp.dvd_factorial.2 h, have h₂ : ¬p ∣ a!, from mt hp.dvd_factorial.1 (not_le_of_gt hap), have h₃ : ¬p ∣ b!, from mt hp.dvd_factorial.1 (not_le_of_gt hbp), by rw [← choose_mul_factorial_mul_factorial (le.intro rfl), mul_assoc, hp.dvd_mul, hp.dvd_mul, add_tsub_cancel_left a b] at h₁; exact h₁.resolve_right (not_or_distrib.2 ⟨h₂, h₃⟩) lemma dvd_choose_self {p k : ℕ} (hk : 0 < k) (hkp : k < p) (hp : prime p) : p ∣ choose p k := begin have r : k + (p - k) = p, by rw [← add_tsub_assoc_of_le (nat.le_of_lt hkp) k, add_tsub_cancel_left], have e : p ∣ choose (k + (p - k)) k, by exact dvd_choose_add hkp (nat.sub_lt (hk.trans hkp) hk) (by rw r) hp, rwa r at e, end end prime end nat
96b59bb8f5156429eb901d9992a36626a5594f2b
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/init/wf_k.lean
159e596ca14655f14cd669257192ccbf01a368fe
[ "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
749
lean
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Leonardo de Moura prelude import init.wf namespace well_founded -- This is an auxiliary definition that useful for generating a new "proof" for (well_founded R) -- that allows us to use well_founded.fix and execute the definitions up to k nested recursive -- calls without "computing" with the proofs in Hwf. definition intro_k {A : Type} {R : A → A → Prop} (Hwf : well_founded R) (k : nat) : well_founded R := well_founded.intro (nat.rec_on k (λ n : A, well_founded.apply Hwf n) (λ (k' : nat) (f : Πa, acc R a), (λ n : A, acc.intro n (λ y H, f y)))) end well_founded
a247a3f4b6b31d226a24c3e8c1a634d5309e95fa
46125763b4dbf50619e8846a1371029346f4c3db
/src/tactic/squeeze.lean
b68984149273a7a05c32634cee6c9a34c4abba66
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
4,678
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon -/ import category.traversable.basic import tactic.simpa open interactive interactive.types lean.parser meta def loc.to_string_aux : option name → string | none := "⊢" | (some x) := to_string x meta def loc.to_string : loc → string | (loc.ns []) := "" | (loc.ns [none]) := "" | (loc.ns ls) := string.join $ list.intersperse " " (" at" :: ls.map loc.to_string_aux) | loc.wildcard := " at *" namespace tactic namespace interactive /-- `erase_simp_args hs s` removes from `s` each name `n` such that `const n` is an element of `hs` -/ meta def erase_simp_args (hs : list simp_arg_type) (s : name_set) : tactic name_set := do -- TODO: when Lean 3.4 support is dropped, use `decode_simp_arg_list_with_symm` on the next line: (hs, _, _) ← decode_simp_arg_list hs, pure $ hs.foldr (λ (h : pexpr) (s : name_set), match h.get_app_fn h with | (expr.const n _) := s.erase n | _ := s end) s /-- Polyfill instance for Lean versions <3.5.1c -/ -- TODO: when Lean 3.4 support is dropped, this instance can be removed @[priority 1] meta instance : has_to_tactic_format simp_arg_type := ⟨λ a, match a with | (simp_arg_type.expr e) := i_to_expr_no_subgoals e >>= pp | (simp_arg_type.except n) := pure format!"-{n}" | _ := pure "*" -- should only be called on `simp_arg_type.all_hyps` end⟩ open list meta def record_lit : lean.parser pexpr := do tk "{", ls ← sep_by (skip_info (tk ",")) ( sum.inl <$> (tk ".." *> texpr) <|> sum.inr <$> (prod.mk <$> ident <* tk ":=" <*> texpr)), tk "}", let (srcs,fields) := partition_map id ls, let (names,values) := unzip fields, pure $ pexpr.mk_structure_instance { field_names := names, field_values := values, sources := srcs } meta def rec.to_tactic_format (e : pexpr) : tactic format := do r ← e.get_structure_instance_info, fs ← mzip_with (λ n v, do v ← to_expr v >>= pp, pure $ format!"{n} := {v}" ) r.field_names r.field_values, let ss := r.sources.map (λ s, format!" .. {s}"), let x : format := format.join $ list.intersperse ", " (fs ++ ss), pure format!" {{{x}}" local postfix `?`:9001 := optional meta def parse_config : option pexpr → tactic (simp_config_ext × format) | none := pure ({}, "") | (some cfg) := do e ← to_expr ``(%%cfg : simp_config_ext), fmt ← has_to_tactic_format.to_tactic_format cfg, prod.mk <$> eval_expr simp_config_ext e <*> rec.to_tactic_format cfg meta def auto_simp_lemma := [``eq_self_iff_true] meta def squeeze_simp (use_iota_eqn : parse (tk "!")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (locat : parse location) (cfg : parse record_lit?) : tactic unit := do g ← main_goal, (cfg',c) ← parse_config cfg, hs' ← hs.mmap pp, simp use_iota_eqn no_dflt hs attr_names locat cfg', g ← instantiate_mvars g, let vs := g.list_constant, vs ← vs.mfilter (succeeds ∘ has_attribute `simp) >>= name_set.mmap strip_prefix, let vs := auto_simp_lemma.foldl name_set.erase vs, vs ← erase_simp_args hs vs, let use_iota_eqn := if use_iota_eqn.is_some then "!" else "", let attrs := if attr_names.empty then "" else string.join (list.intersperse " " (" with" :: attr_names.map to_string)), let loc := loc.to_string locat, let args := hs' ++ vs.to_list.map to_fmt, trace format!"Try this: simp{use_iota_eqn} only {args}{attrs}{loc}{c}" meta def squeeze_simpa (use_iota_eqn : parse (tk "!")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (tgt : parse (tk "using" *> texpr)?) (cfg : parse record_lit?) : tactic unit := do g ← main_goal, (cfg',c) ← parse_config cfg, tgt' ← traverse (λ t, do t ← to_expr t >>= pp, pure format!" using {t}") tgt, simpa use_iota_eqn no_dflt hs attr_names tgt cfg', g ← instantiate_mvars g, let vs := g.list_constant, vs ← vs.mfilter (succeeds ∘ has_attribute `simp) >>= name_set.mmap strip_prefix, let vs := auto_simp_lemma.foldl name_set.erase vs, vs ← erase_simp_args hs vs, let use_iota_eqn := if use_iota_eqn.is_some then "!" else "", let attrs := if attr_names.empty then "" else string.join (list.intersperse " " (" with" :: attr_names.map to_string)), let tgt' := tgt'.get_or_else "", hs ← hs.mmap pp, let args := hs ++ vs.to_list.map to_fmt, trace format!"Try this: simpa{use_iota_eqn} only {args}{attrs}{tgt'}{c}" end interactive end tactic
8c3ae87cdb48a92784515951f3468de7ca86dbcf
94e33a31faa76775069b071adea97e86e218a8ee
/src/category_theory/limits/over.lean
261554a0a8ee295c0d1a9b3805b8bef78a62ebf2
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
4,982
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Reid Barton, Bhavik Mehta -/ import category_theory.over import category_theory.adjunction.opposites import category_theory.limits.preserves.basic import category_theory.limits.shapes.pullbacks import category_theory.limits.creates import category_theory.limits.comma /-! # Limits and colimits in the over and under categories Show that the forgetful functor `forget X : over X ⥤ C` creates colimits, and hence `over X` has any colimits that `C` has (as well as the dual that `forget X : under X ⟶ C` creates limits). Note that the folder `category_theory.limits.shapes.constructions.over` further shows that `forget X : over X ⥤ C` creates connected limits (so `over X` has connected limits), and that `over X` has `J`-indexed products if `C` has `J`-indexed wide pullbacks. TODO: If `C` has binary products, then `forget X : over X ⥤ C` has a right adjoint. -/ noncomputable theory universes v u -- morphism levels before object levels. See note [category_theory universes]. open category_theory category_theory.limits variables {J : Type v} [small_category J] variables {C : Type u} [category.{v} C] variable {X : C} namespace category_theory.over instance has_colimit_of_has_colimit_comp_forget (F : J ⥤ over X) [i : has_colimit (F ⋙ forget X)] : has_colimit F := @@costructured_arrow.has_colimit _ _ _ _ i _ instance [has_colimits_of_shape J C] : has_colimits_of_shape J (over X) := {} instance [has_colimits C] : has_colimits (over X) := ⟨infer_instance⟩ instance creates_colimits : creates_colimits (forget X) := costructured_arrow.creates_colimits -- We can automatically infer that the forgetful functor preserves and reflects colimits. example [has_colimits C] : preserves_colimits (forget X) := infer_instance example : reflects_colimits (forget X) := infer_instance section variables [has_pullbacks C] open tactic /-- When `C` has pullbacks, a morphism `f : X ⟶ Y` induces a functor `over Y ⥤ over X`, by pulling back a morphism along `f`. -/ @[simps] def pullback {X Y : C} (f : X ⟶ Y) : over Y ⥤ over X := { obj := λ g, over.mk (pullback.snd : pullback g.hom f ⟶ X), map := λ g h k, over.hom_mk (pullback.lift (pullback.fst ≫ k.left) pullback.snd (by simp [pullback.condition])) (by tidy) } /-- `over.map f` is left adjoint to `over.pullback f`. -/ def map_pullback_adj {A B : C} (f : A ⟶ B) : over.map f ⊣ pullback f := adjunction.mk_of_hom_equiv { hom_equiv := λ g h, { to_fun := λ X, over.hom_mk (pullback.lift X.left g.hom (over.w X)) (pullback.lift_snd _ _ _), inv_fun := λ Y, begin refine over.hom_mk _ _, refine Y.left ≫ pullback.fst, dsimp, rw [← over.w Y, category.assoc, pullback.condition, category.assoc], refl, end, left_inv := λ X, by { ext, dsimp, simp, }, right_inv := λ Y, begin ext, dsimp, simp only [pullback.lift_fst], dsimp, rw [pullback.lift_snd, ← over.w Y], refl, end } } /-- pullback (𝟙 A) : over A ⥤ over A is the identity functor. -/ def pullback_id {A : C} : pullback (𝟙 A) ≅ 𝟭 _ := adjunction.right_adjoint_uniq (map_pullback_adj _) (adjunction.id.of_nat_iso_left over.map_id.symm) /-- pullback commutes with composition (up to natural isomorphism). -/ def pullback_comp {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) : pullback (f ≫ g) ≅ pullback g ⋙ pullback f := adjunction.right_adjoint_uniq (map_pullback_adj _) (((map_pullback_adj _).comp (map_pullback_adj _)).of_nat_iso_left (over.map_comp _ _).symm) instance pullback_is_right_adjoint {A B : C} (f : A ⟶ B) : is_right_adjoint (pullback f) := ⟨_, map_pullback_adj f⟩ end end category_theory.over namespace category_theory.under instance has_limit_of_has_limit_comp_forget (F : J ⥤ under X) [i : has_limit (F ⋙ forget X)] : has_limit F := @@structured_arrow.has_limit _ _ _ _ i _ instance [has_limits_of_shape J C] : has_limits_of_shape J (under X) := {} instance [has_limits C] : has_limits (under X) := ⟨infer_instance⟩ instance creates_limits : creates_limits (forget X) := structured_arrow.creates_limits -- We can automatically infer that the forgetful functor preserves and reflects limits. example [has_limits C] : preserves_limits (forget X) := infer_instance example : reflects_limits (forget X) := infer_instance section variables [has_pushouts C] /-- When `C` has pushouts, a morphism `f : X ⟶ Y` induces a functor `under X ⥤ under Y`, by pushing a morphism forward along `f`. -/ @[simps] def pushout {X Y : C} (f : X ⟶ Y) : under X ⥤ under Y := { obj := λ g, under.mk (pushout.inr : Y ⟶ pushout g.hom f), map := λ g h k, under.hom_mk (pushout.desc (k.right ≫ pushout.inl) pushout.inr (by { simp [←pushout.condition], })) (by tidy) } end end category_theory.under
af14890fa536d86fc70c3441d470cbf5882d3c8c
952248371e69ccae722eb20bfe6815d8641554a8
/src/datatypes/proof.lean
cd84ac5555f1a96571bb85a69633473a36005a98
[]
no_license
robertylewis/lean_polya
5fd079031bf7114449d58d68ccd8c3bed9bcbc97
1da14d60a55ad6cd8af8017b1b64990fccb66ab7
refs/heads/master
1,647,212,226,179
1,558,108,354,000
1,558,108,354,000
89,933,264
1
2
null
1,560,964,118,000
1,493,650,551,000
Lean
UTF-8
Lean
false
false
7,961
lean
import .expr_form namespace polya meta inductive proof_sketch | mk (fact : string) (reason : string) (justifications : list proof_sketch) : proof_sketch namespace proof_sketch meta def justifications : proof_sketch → list proof_sketch | ⟨_, _, j⟩ := j meta def reason : proof_sketch → string | ⟨_, r, _⟩ := r end proof_sketch /- PROOF OBJECTS -/ /- TODO: rename as diseq.proof, eq.proof, sign.proof, ... ? -/ meta inductive diseq_proof : expr → expr → ℚ → Type | hyp : Π lhs rhs c, expr → diseq_proof lhs rhs c | sym : Π {lhs rhs c}, Π (dp : diseq_proof lhs rhs c), diseq_proof rhs lhs (1/c) meta mutual inductive eq_proof, ineq_proof, sign_proof, sum_form_proof with eq_proof : expr → expr → ℚ → Type | hyp : Π lhs rhs c, expr → eq_proof lhs rhs c | sym : Π {lhs rhs c}, Π (ep : eq_proof lhs rhs c), eq_proof rhs lhs (1/c) | of_opp_ineqs : Π {lhs rhs i}, Π c, ineq_proof lhs rhs i → ineq_proof lhs rhs (i.reverse) → eq_proof lhs rhs c | of_sum_form_proof : Π lhs rhs c {sf}, sum_form_proof ⟨sf, spec_comp.eq⟩ → eq_proof lhs rhs c | adhoc : Π lhs rhs c, tactic proof_sketch → tactic expr → eq_proof lhs rhs c with ineq_proof : expr → expr → ineq → Type | hyp : Π lhs rhs i, expr → ineq_proof lhs rhs i | sym : Π {lhs rhs i}, ineq_proof lhs rhs i → ineq_proof rhs lhs (i.reverse) | of_ineq_proof_and_diseq : Π {lhs rhs i c}, ineq_proof lhs rhs i → diseq_proof lhs rhs c → ineq_proof lhs rhs (i.strengthen) | of_ineq_proof_and_sign_lhs : Π {lhs rhs i c}, ineq_proof lhs rhs i → sign_proof lhs c → ineq_proof lhs rhs (i.strengthen) | of_ineq_proof_and_sign_rhs : Π {lhs rhs i c}, ineq_proof lhs rhs i → sign_proof rhs c → ineq_proof lhs rhs (i.strengthen) | zero_comp_of_sign_proof : Π {lhs c} rhs i, sign_proof lhs c → ineq_proof lhs rhs i | horiz_of_sign_proof : Π {rhs c} lhs i, sign_proof rhs c → ineq_proof lhs rhs i | of_sum_form_proof : Π lhs rhs i {sfc}, sum_form_proof sfc → ineq_proof lhs rhs i | adhoc : Π lhs rhs i, tactic proof_sketch → tactic expr → ineq_proof lhs rhs i with sign_proof : expr → gen_comp → Type | hyp : Π e c, expr → sign_proof e c | scaled_hyp : Π e c, expr → ℚ → sign_proof e c | ineq_lhs : Π c, Π {lhs rhs iqp}, ineq_proof lhs rhs iqp → sign_proof lhs c | ineq_rhs : Π c, Π {lhs rhs iqp}, ineq_proof lhs rhs iqp → sign_proof rhs c | eq_of_two_eqs_lhs : Π {lhs rhs eqp1 eqp2}, eq_proof lhs rhs eqp1 → eq_proof lhs rhs eqp2 → sign_proof lhs gen_comp.eq | eq_of_two_eqs_rhs : Π {lhs rhs eqp1 eqp2}, eq_proof lhs rhs eqp1 → eq_proof lhs rhs eqp2 → sign_proof rhs gen_comp.eq | diseq_of_diseq_zero : Π {lhs rhs}, diseq_proof lhs rhs 0 → sign_proof lhs gen_comp.ne | eq_of_eq_zero : Π {lhs rhs}, eq_proof lhs rhs 0 → sign_proof lhs gen_comp.eq | eq_of_le_of_ge : Π {e}, sign_proof e gen_comp.le → sign_proof e gen_comp.ge → sign_proof e gen_comp.eq | ineq_of_eq_and_ineq_lhs : Π {lhs rhs i c}, Π c', eq_proof lhs rhs c → ineq_proof lhs rhs i → sign_proof lhs c' | ineq_of_eq_and_ineq_rhs : Π {lhs rhs i c}, Π c', eq_proof lhs rhs c → ineq_proof lhs rhs i → sign_proof rhs c' | ineq_of_ineq_and_eq_zero_rhs : Π {lhs rhs i}, Π c, ineq_proof lhs rhs i → sign_proof lhs gen_comp.eq → sign_proof rhs c | diseq_of_strict_ineq : Π {e c}, sign_proof e c → sign_proof e gen_comp.ne | of_sum_form_proof : Π e c {sfc}, sum_form_proof sfc → sign_proof e c | adhoc : Π e c, tactic proof_sketch → tactic expr → sign_proof e c with sum_form_proof : sum_form_comp → Type | of_ineq_proof : Π {lhs rhs iq}, Π id : ineq_proof lhs rhs iq, sum_form_proof (sum_form_comp.of_ineq lhs rhs iq) | of_eq_proof : Π {lhs rhs c}, Π id : eq_proof lhs rhs c, sum_form_proof (sum_form_comp.of_eq lhs rhs c) | of_sign_proof : Π {e c}, Π id : sign_proof e c, sum_form_proof (sum_form_comp.of_sign e c) | of_add_factor_same_comp : Π {lhs rhs c1 c2}, Π m : ℚ, -- assumes m is positive sum_form_proof ⟨lhs, c1⟩ → sum_form_proof ⟨rhs, c2⟩ → sum_form_proof ⟨lhs.add_factor rhs m, spec_comp.strongest c1 c2⟩ | of_add_eq_factor_op_comp : Π {lhs rhs c1}, Π m : ℚ, -- assumes m is negative sum_form_proof ⟨lhs, c1⟩ → sum_form_proof ⟨rhs, spec_comp.eq⟩ → sum_form_proof ⟨lhs.add_factor rhs m, c1⟩ | of_scale : Π {sfc}, Π m, sum_form_proof sfc → sum_form_proof (sfc.scale m) | of_expr_def : Π (e : expr) (sf : sum_form), sum_form_proof ⟨sf, spec_comp.eq⟩ | fake : Π sd, sum_form_proof sd meta inductive prod_form_proof : prod_form_comp → Type | of_ineq_proof : Π {lhs rhs iq cl cr}, Π (id : ineq_proof lhs rhs iq) (spl : sign_proof lhs cl) (spr : sign_proof rhs cr), prod_form_proof (prod_form_comp.of_ineq lhs rhs cl cr iq) | of_eq_proof : Π {lhs rhs c}, Π (id : eq_proof lhs rhs c) (lhsne : sign_proof lhs gen_comp.ne), prod_form_proof (prod_form_comp.of_eq lhs rhs c) | of_expr_def : Π (e : expr) (pf : prod_form), prod_form_proof ⟨pf, spec_comp.eq⟩ | of_pow : Π {pfc}, Π z, prod_form_proof pfc → prod_form_proof (pfc.pow z) | of_mul : Π {lhs rhs c1 c2}, prod_form_proof ⟨lhs, c1⟩ → prod_form_proof ⟨rhs, c2⟩ → (list Σ e : expr, sign_proof e gen_comp.ne) → prod_form_proof ⟨lhs*rhs, spec_comp.strongest c1 c2⟩ | adhoc : Π pfc, tactic proof_sketch → tactic expr → prod_form_proof pfc | fake : Π pd, prod_form_proof pd namespace ineq_proof meta def to_format {lhs rhs c} : ineq_proof lhs rhs c → format | p := "proof" meta def to_format2 : Π {lhs rhs : expr} {iq : ineq}, ineq_proof lhs rhs iq → format | .(_) .(_) .(_) (hyp (lhs) (rhs) (iq) e) := "hyp" | .(_) .(_) .(_) (@sym lhs rhs c ip) := "sym" | .(_) .(_) .(_) (@of_ineq_proof_and_diseq lhs rhs iq c ip dp) := "of_ineq_proof_and_diseq" | .(_) .(_) .(_) (@of_ineq_proof_and_sign_lhs lhs rhs iq c ip sp) := "of_ineq_proof_and_sign_lhs" | .(_) .(_) .(_) (@of_ineq_proof_and_sign_rhs lhs rhs iq c ip sp) := "of_ineq_proof_and_sign_rhs" | .(_) .(_) .(_) (@zero_comp_of_sign_proof lhs c rhs iq sp) := "zero_comp_of_sign" | .(_) .(_) .(_) (@horiz_of_sign_proof rhs c lhs iq sp) := "horiz_of_sign" | .(_) .(_) .(_) (@of_sum_form_proof lhs rhs i _ sp) := "of_sum_form" | .(_) .(_) .(_) (adhoc _ _ _ _ t) := "adhoc" meta instance has_to_format (lhs rhs c) : has_to_format (ineq_proof lhs rhs c) := ⟨to_format2⟩ end ineq_proof namespace sign_proof meta def to_format : Π {e c}, sign_proof e c → format | (_) (_) (hyp _ _ _) := "hyp" | (_) (_) (scaled_hyp _ _ _ _) := "scaled_hyp" | (_) (_) (ineq_lhs _ _) := "ineq_lhs" | (_) (_) (ineq_rhs _ _) := "ineq_rhs" | (_) (_) (eq_of_two_eqs_rhs _ _) := "eq_of_two_eqs_rhs" | (_) (_) (eq_of_two_eqs_lhs _ _) := "eq_of_two_eqs_lhs" | (_) (_) (diseq_of_diseq_zero _) := "diseq_of_diseq_zero" | (_) (_) (eq_of_eq_zero _) := "eq_of_eq_zero" | (_) (_) (eq_of_le_of_ge _ _) := "eq_of_le_of_ge" | (_) (_) (ineq_of_eq_and_ineq_lhs _ _ _) := "ineq_of_eq_and_ineq_lhs" | (_) (_) (ineq_of_eq_and_ineq_rhs _ _ _) := "ineq_of_eq_and_ineq_rhs" | (_) (_) (ineq_of_ineq_and_eq_zero_rhs _ _ _) := "ineq_of_ineq_and_eq_zero_rhs" | (_) (_) (diseq_of_strict_ineq _) := "diseq_of_strict_ineq" | (_) (_) (of_sum_form_proof _ _ _) := "of_sum_form_proof" | (_) (_) (adhoc _ _ _ _) := "adhoc" meta instance has_to_format {e c} : has_to_format (sign_proof e c) := ⟨sign_proof.to_format⟩ end sign_proof namespace prod_form_proof meta def to_format {pfc} (pfp : prod_form_proof pfc) : format := begin cases pfp, exact "of_ineq_proof", exact "of_eq_proof", exact "of_expr_def", exact "of_pow", exact "of_mul", exact "adhoc", exact "fake" end meta instance has_to_format {pfc} : has_to_format (prod_form_proof pfc) := ⟨to_format⟩ end prod_form_proof namespace sum_form_comp -- is this needed? meta def of_ineq_proof {lhs rhs id} (ip : ineq_proof lhs rhs id) : sum_form_comp := sum_form_comp.of_ineq lhs rhs id end sum_form_comp end polya
0f40045e8aac86f84cda9a74d159acd75ac2462f
9028d228ac200bbefe3a711342514dd4e4458bff
/src/logic/embedding.lean
621429bc48dde16972a2538e8af35d356e2b0b1b
[ "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
9,306
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 -/ import data.equiv.basic import data.sigma.basic /-! # Injective functions -/ universes u v w x namespace function /-- `α ↪ β` is a bundled injective function. -/ @[nolint has_inhabited_instance] -- depending on cardinalities, an injective function may not exist structure embedding (α : Sort*) (β : Sort*) := (to_fun : α → β) (inj' : injective to_fun) infixr ` ↪ `:25 := embedding instance {α : Sort u} {β : Sort v} : has_coe_to_fun (α ↪ β) := ⟨_, embedding.to_fun⟩ end function /-- Convert an `α ≃ β` to `α ↪ β`. -/ @[simps] protected def equiv.to_embedding {α : Sort u} {β : Sort v} (f : α ≃ β) : α ↪ β := ⟨f, f.injective⟩ namespace function namespace embedding @[ext] lemma ext {α β} {f g : embedding α β} (h : ∀ x, f x = g x) : f = g := by cases f; cases g; simpa using funext h lemma ext_iff {α β} {f g : embedding α β} : (∀ x, f x = g x) ↔ f = g := ⟨ext, λ h _, by rw h⟩ @[simp] theorem to_fun_eq_coe {α β} (f : α ↪ β) : to_fun f = f := rfl @[simp] theorem coe_fn_mk {α β} (f : α → β) (i) : (@mk _ _ f i : α → β) = f := rfl theorem injective {α β} (f : α ↪ β) : injective f := f.inj' @[refl, simps {simp_rhs := tt}] protected def refl (α : Sort*) : α ↪ α := ⟨id, injective_id⟩ @[trans, simps {simp_rhs := tt}] protected def trans {α β γ} (f : α ↪ β) (g : β ↪ γ) : α ↪ γ := ⟨g ∘ f, g.injective.comp f.injective⟩ @[simp] lemma equiv_to_embedding_trans_symm_to_embedding {α β : Sort*} (e : α ≃ β) : e.to_embedding.trans e.symm.to_embedding = embedding.refl _ := by { ext, simp, } @[simp] lemma equiv_symm_to_embedding_trans_to_embedding {α β : Sort*} (e : α ≃ β) : e.symm.to_embedding.trans e.to_embedding = embedding.refl _ := by { ext, simp, } protected def congr {α : Sort u} {β : Sort v} {γ : Sort w} {δ : Sort x} (e₁ : α ≃ β) (e₂ : γ ≃ δ) (f : α ↪ γ) : (β ↪ δ) := (equiv.to_embedding e₁.symm).trans (f.trans e₂.to_embedding) /-- A right inverse `surj_inv` of a surjective function as an `embedding`. -/ protected noncomputable def of_surjective {α β} (f : β → α) (hf : surjective f) : α ↪ β := ⟨surj_inv hf, injective_surj_inv _⟩ /-- Convert a surjective `embedding` to an `equiv` -/ protected noncomputable def equiv_of_surjective {α β} (f : α ↪ β) (hf : surjective f) : α ≃ β := equiv.of_bijective f ⟨f.injective, hf⟩ protected def of_not_nonempty {α β} (hα : ¬ nonempty α) : α ↪ β := ⟨λa, (hα ⟨a⟩).elim, assume a, (hα ⟨a⟩).elim⟩ /-- Change the value of an embedding `f` at one point. If the prescribed image is already occupied by some `f a'`, then swap the values at these two points. -/ def set_value {α β} (f : α ↪ β) (a : α) (b : β) [∀ a', decidable (a' = a)] [∀ a', decidable (f a' = b)] : α ↪ β := ⟨λ a', if a' = a then b else if f a' = b then f a else f a', begin intros x y h, dsimp at h, split_ifs at h; try { substI b }; try { simp only [f.injective.eq_iff] at * }; cc end⟩ theorem set_value_eq {α β} (f : α ↪ β) (a : α) (b : β) [∀ a', decidable (a' = a)] [∀ a', decidable (f a' = b)] : set_value f a b a = b := by simp [set_value] /-- Embedding into `option` -/ protected def some {α} : α ↪ option α := ⟨some, option.some_injective α⟩ /-- Embedding of a `subtype`. -/ def subtype {α} (p : α → Prop) : subtype p ↪ α := ⟨coe, λ _ _, subtype.ext_val⟩ @[simp] lemma coe_subtype {α} (p : α → Prop) : ⇑(subtype p) = coe := rfl /-- Choosing an element `b : β` gives an embedding of `punit` into `β`. -/ def punit {β : Sort*} (b : β) : punit ↪ β := ⟨λ _, b, by { rintros ⟨⟩ ⟨⟩ _, refl, }⟩ /-- Fixing an element `b : β` gives an embedding `α ↪ α × β`. -/ def sectl (α : Sort*) {β : Sort*} (b : β) : α ↪ α × β := ⟨λ a, (a, b), λ a a' h, congr_arg prod.fst h⟩ /-- Fixing an element `a : α` gives an embedding `β ↪ α × β`. -/ def sectr {α : Sort*} (a : α) (β : Sort*): β ↪ α × β := ⟨λ b, (a, b), λ b b' h, congr_arg prod.snd h⟩ /-- Restrict the codomain of an embedding. -/ def cod_restrict {α β} (p : set β) (f : α ↪ β) (H : ∀ a, f a ∈ p) : α ↪ p := ⟨λ a, ⟨f a, H a⟩, λ a b h, f.injective (@congr_arg _ _ _ _ subtype.val h)⟩ @[simp] theorem cod_restrict_apply {α β} (p) (f : α ↪ β) (H a) : cod_restrict p f H a = ⟨f a, H a⟩ := rfl /-- If `e₁` and `e₂` are embeddings, then so is `prod.map e₁ e₂ : (a, b) ↦ (e₁ a, e₂ b)`. -/ def prod_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α × γ ↪ β × δ := ⟨prod.map e₁ e₂, e₁.injective.prod_map e₂.injective⟩ @[simp] lemma coe_prod_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : ⇑(e₁.prod_map e₂) = prod.map e₁ e₂ := rfl section sum open sum /-- If `e₁` and `e₂` are embeddings, then so is `sum.map e₁ e₂`. -/ def sum_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α ⊕ γ ↪ β ⊕ δ := ⟨sum.map e₁ e₂, assume s₁ s₂ h, match s₁, s₂, h with | inl a₁, inl a₂, h := congr_arg inl $ e₁.injective $ inl.inj h | inr b₁, inr b₂, h := congr_arg inr $ e₂.injective $ inr.inj h end⟩ @[simp] theorem coe_sum_map {α β γ δ} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : ⇑(sum_map e₁ e₂) = sum.map e₁ e₂ := rfl /-- The embedding of `α` into the sum `α ⊕ β`. -/ def inl {α β : Type*} : α ↪ α ⊕ β := ⟨sum.inl, λ a b, sum.inl.inj⟩ /-- The embedding of `β` into the sum `α ⊕ β`. -/ def inr {α β : Type*} : β ↪ α ⊕ β := ⟨sum.inr, λ a b, sum.inr.inj⟩ end sum section sigma variables {α α' : Type*} {β : α → Type*} {β' : α' → Type*} /-- `sigma.mk` as an `function.embedding`. -/ @[simps to_fun] def sigma_mk (a : α) : β a ↪ Σ x, β x := ⟨sigma.mk a, sigma_mk_injective⟩ /-- If `f : α ↪ α'` is an embedding and `g : Π a, β α ↪ β' (f α)` is a family of embeddings, then `sigma.map f g` is an embedding. -/ @[simps to_fun] def sigma_map (f : α ↪ α') (g : Π a, β a ↪ β' (f a)) : (Σ a, β a) ↪ Σ a', β' a' := ⟨sigma.map f (λ a, g a), f.injective.sigma_map (λ a, (g a).injective)⟩ end sigma def Pi_congr_right {α : Sort*} {β γ : α → Sort*} (e : ∀ a, β a ↪ γ a) : (Π a, β a) ↪ (Π a, γ a) := ⟨λf a, e a (f a), λ f₁ f₂ h, funext $ λ a, (e a).injective (congr_fun h a)⟩ def arrow_congr_left {α : Sort u} {β : Sort v} {γ : Sort w} (e : α ↪ β) : (γ → α) ↪ (γ → β) := Pi_congr_right (λ _, e) noncomputable def arrow_congr_right {α : Sort u} {β : Sort v} {γ : Sort w} [inhabited γ] (e : α ↪ β) : (α → γ) ↪ (β → γ) := by haveI := classical.prop_decidable; exact let f' : (α → γ) → (β → γ) := λf b, if h : ∃c, e c = b then f (classical.some h) else default γ in ⟨f', assume f₁ f₂ h, funext $ assume c, have ∃c', e c' = e c, from ⟨c, rfl⟩, have eq' : f' f₁ (e c) = f' f₂ (e c), from congr_fun h _, have eq_b : classical.some this = c, from e.injective $ classical.some_spec this, by simp [f', this, if_pos, eq_b] at eq'; assumption⟩ protected def subtype_map {α β} {p : α → Prop} {q : β → Prop} (f : α ↪ β) (h : ∀{{x}}, p x → q (f x)) : {x : α // p x} ↪ {y : β // q y} := ⟨subtype.map f h, subtype.map_injective h f.2⟩ open set /-- `set.image` as an embedding `set α ↪ set β`. -/ @[simps to_fun] protected def image {α β} (f : α ↪ β) : set α ↪ set β := ⟨image f, f.2.image_injective⟩ end embedding end function namespace equiv @[simp] lemma refl_to_embedding {α : Type*} : (equiv.refl α).to_embedding = function.embedding.refl α := rfl @[simp] lemma trans_to_embedding {α β γ : Type*} (e : α ≃ β) (f : β ≃ γ) : (e.trans f).to_embedding = e.to_embedding.trans f.to_embedding := rfl end equiv namespace set /-- The injection map is an embedding between subsets. -/ @[simps to_fun] def embedding_of_subset {α} (s t : set α) (h : s ⊆ t) : s ↪ t := ⟨λ x, ⟨x.1, h x.2⟩, λ ⟨x, hx⟩ ⟨y, hy⟩ h, by { congr, injection h }⟩ end set /-- The embedding of a left cancellative semigroup into itself by left multiplication by a fixed element. -/ @[to_additive "The embedding of a left cancellative additive semigroup into itself by left translation by a fixed element."] def mul_left_embedding {G : Type u} [left_cancel_semigroup G] (g : G) : G ↪ G := { to_fun := λ h, g * h, inj' := λ h h', (mul_right_inj g).mp, } /-- The embedding of a right cancellative semigroup into itself by right multiplication by a fixed element. -/ @[to_additive "The embedding of a right cancellative additive semigroup into itself by right translation by a fixed element."] def mul_right_embedding {G : Type u} [right_cancel_semigroup G] (g : G) : G ↪ G := { to_fun := λ h, h * g, inj' := λ h h', (mul_left_inj g).mp, } attribute [simps] mul_left_embedding add_left_embedding mul_right_embedding add_right_embedding
df68632a1fa8d3fe3d7d525e7519baa005ec0c5d
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/reserve_bugs.lean
71ec5f59b9b0b4971d141e19a997efd6e205a947
[ "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
481
lean
-- constant f : num → num constant g : num → num → num constant h : num → num → num reserve infixl `+`:65 reserve infixr `&`:70 reserve infixl `-`:65 reserve prefix `-`:100 local infixl `+` := g local infixl `-` := h local prefix `-` := f local infixr `&` := h set_option pp.notation false check -(1:num) + 2 check 1 & 2 & 3 & 4 check (1:num) - 2 - 3 - 4 infixr `~~`:60 := h infixl `!!`:60 := h check 1 ~~ 2 ~~ 3 ~~ 4 check 1 !! 2 !! 3 !! 4 check 1 ~~ 2 + 3 ~~ 4
9d7ddcd340019cdac32030b5fb0bef0bd66ad95e
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/analysis/filter.lean
d0cc1ec900a398e3f8ef66d9baf5a04c96249de6
[ "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
11,807
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Computational realization of filters (experimental). -/ import order.filter.cofinite open set filter /-- A `cfilter α σ` is a realization of a filter (base) on `α`, represented by a type `σ` together with operations for the top element and the binary inf operation. -/ structure cfilter (α σ : Type*) [partial_order α] := (f : σ → α) (pt : σ) (inf : σ → σ → σ) (inf_le_left : ∀ a b : σ, f (inf a b) ≤ f a) (inf_le_right : ∀ a b : σ, f (inf a b) ≤ f b) variables {α : Type*} {β : Type*} {σ : Type*} {τ : Type*} namespace cfilter section variables [partial_order α] (F : cfilter α σ) instance : has_coe_to_fun (cfilter α σ) := ⟨_, cfilter.f⟩ @[simp] theorem coe_mk (f pt inf h₁ h₂ a) : (@cfilter.mk α σ _ f pt inf h₁ h₂) a = f a := rfl /-- Map a cfilter to an equivalent representation type. -/ def of_equiv (E : σ ≃ τ) : cfilter α σ → cfilter α τ | ⟨f, p, g, h₁, h₂⟩ := { f := λ a, f (E.symm a), pt := E p, inf := λ a b, E (g (E.symm a) (E.symm b)), inf_le_left := λ a b, by simpa using h₁ (E.symm a) (E.symm b), inf_le_right := λ a b, by simpa using h₂ (E.symm a) (E.symm b) } @[simp] theorem of_equiv_val (E : σ ≃ τ) (F : cfilter α σ) (a : τ) : F.of_equiv E a = F (E.symm a) := by cases F; refl end /-- The filter represented by a `cfilter` is the collection of supersets of elements of the filter base. -/ def to_filter (F : cfilter (set α) σ) : filter α := { sets := {a | ∃ b, F b ⊆ a}, univ_sets := ⟨F.pt, subset_univ _⟩, sets_of_superset := λ x y ⟨b, h⟩ s, ⟨b, subset.trans h s⟩, inter_sets := λ x y ⟨a, h₁⟩ ⟨b, h₂⟩, ⟨F.inf a b, subset_inter (subset.trans (F.inf_le_left _ _) h₁) (subset.trans (F.inf_le_right _ _) h₂)⟩ } @[simp] theorem mem_to_filter_sets (F : cfilter (set α) σ) {a : set α} : a ∈ F.to_filter ↔ ∃ b, F b ⊆ a := iff.rfl end cfilter /-- A realizer for filter `f` is a cfilter which generates `f`. -/ structure filter.realizer (f : filter α) := (σ : Type*) (F : cfilter (set α) σ) (eq : F.to_filter = f) protected def cfilter.to_realizer (F : cfilter (set α) σ) : F.to_filter.realizer := ⟨σ, F, rfl⟩ namespace filter.realizer theorem mem_sets {f : filter α} (F : f.realizer) {a : set α} : a ∈ f ↔ ∃ b, F.F b ⊆ a := by cases F; subst f; simp -- Used because it has better definitional equalities than the eq.rec proof def of_eq {f g : filter α} (e : f = g) (F : f.realizer) : g.realizer := ⟨F.σ, F.F, F.eq.trans e⟩ /-- A filter realizes itself. -/ def of_filter (f : filter α) : f.realizer := ⟨f.sets, { f := subtype.val, pt := ⟨univ, univ_mem⟩, inf := λ ⟨x, h₁⟩ ⟨y, h₂⟩, ⟨_, inter_mem h₁ h₂⟩, inf_le_left := λ ⟨x, h₁⟩ ⟨y, h₂⟩, inter_subset_left x y, inf_le_right := λ ⟨x, h₁⟩ ⟨y, h₂⟩, inter_subset_right x y }, filter_eq $ set.ext $ λ x, set_coe.exists.trans exists_mem_subset_iff⟩ /-- Transfer a filter realizer to another realizer on a different base type. -/ def of_equiv {f : filter α} (F : f.realizer) (E : F.σ ≃ τ) : f.realizer := ⟨τ, F.F.of_equiv E, by refine eq.trans _ F.eq; exact filter_eq (set.ext $ λ x, ⟨λ ⟨s, h⟩, ⟨E.symm s, by simpa using h⟩, λ ⟨t, h⟩, ⟨E t, by simp [h]⟩⟩)⟩ @[simp] theorem of_equiv_σ {f : filter α} (F : f.realizer) (E : F.σ ≃ τ) : (F.of_equiv E).σ = τ := rfl @[simp] theorem of_equiv_F {f : filter α} (F : f.realizer) (E : F.σ ≃ τ) (s : τ) : (F.of_equiv E).F s = F.F (E.symm s) := by delta of_equiv; simp /-- `unit` is a realizer for the principal filter -/ protected def principal (s : set α) : (principal s).realizer := ⟨unit, { f := λ _, s, pt := (), inf := λ _ _, (), inf_le_left := λ _ _, le_refl _, inf_le_right := λ _ _, le_refl _ }, filter_eq $ set.ext $ λ x, ⟨λ ⟨_, s⟩, s, λ h, ⟨(), h⟩⟩⟩ @[simp] theorem principal_σ (s : set α) : (realizer.principal s).σ = unit := rfl @[simp] theorem principal_F (s : set α) (u : unit) : (realizer.principal s).F u = s := rfl /-- `unit` is a realizer for the top filter -/ protected def top : (⊤ : filter α).realizer := (realizer.principal _).of_eq principal_univ @[simp] theorem top_σ : (@realizer.top α).σ = unit := rfl @[simp] theorem top_F (u : unit) : (@realizer.top α).F u = univ := rfl /-- `unit` is a realizer for the bottom filter -/ protected def bot : (⊥ : filter α).realizer := (realizer.principal _).of_eq principal_empty @[simp] theorem bot_σ : (@realizer.bot α).σ = unit := rfl @[simp] theorem bot_F (u : unit) : (@realizer.bot α).F u = ∅ := rfl /-- Construct a realizer for `map m f` given a realizer for `f` -/ protected def map (m : α → β) {f : filter α} (F : f.realizer) : (map m f).realizer := ⟨F.σ, { f := λ s, image m (F.F s), pt := F.F.pt, inf := F.F.inf, inf_le_left := λ a b, image_subset _ (F.F.inf_le_left _ _), inf_le_right := λ a b, image_subset _ (F.F.inf_le_right _ _) }, filter_eq $ set.ext $ λ x, by simp [cfilter.to_filter]; rw F.mem_sets; refl ⟩ @[simp] theorem map_σ (m : α → β) {f : filter α} (F : f.realizer) : (F.map m).σ = F.σ := rfl @[simp] theorem map_F (m : α → β) {f : filter α} (F : f.realizer) (s) : (F.map m).F s = image m (F.F s) := rfl /-- Construct a realizer for `comap m f` given a realizer for `f` -/ protected def comap (m : α → β) {f : filter β} (F : f.realizer) : (comap m f).realizer := ⟨F.σ, { f := λ s, preimage m (F.F s), pt := F.F.pt, inf := F.F.inf, inf_le_left := λ a b, preimage_mono (F.F.inf_le_left _ _), inf_le_right := λ a b, preimage_mono (F.F.inf_le_right _ _) }, filter_eq $ set.ext $ λ x, by cases F; subst f; simp [cfilter.to_filter, mem_comap]; exact ⟨λ ⟨s, h⟩, ⟨_, ⟨s, subset.refl _⟩, h⟩, λ ⟨y, ⟨s, h⟩, h₂⟩, ⟨s, subset.trans (preimage_mono h) h₂⟩⟩⟩ /-- Construct a realizer for the sup of two filters -/ protected def sup {f g : filter α} (F : f.realizer) (G : g.realizer) : (f ⊔ g).realizer := ⟨F.σ × G.σ, { f := λ ⟨s, t⟩, F.F s ∪ G.F t, pt := (F.F.pt, G.F.pt), inf := λ ⟨a, a'⟩ ⟨b, b'⟩, (F.F.inf a b, G.F.inf a' b'), inf_le_left := λ ⟨a, a'⟩ ⟨b, b'⟩, union_subset_union (F.F.inf_le_left _ _) (G.F.inf_le_left _ _), inf_le_right := λ ⟨a, a'⟩ ⟨b, b'⟩, union_subset_union (F.F.inf_le_right _ _) (G.F.inf_le_right _ _) }, filter_eq $ set.ext $ λ x, by cases F; cases G; substs f g; simp [cfilter.to_filter]; exact ⟨λ ⟨s, t, h⟩, ⟨⟨s, subset.trans (subset_union_left _ _) h⟩, ⟨t, subset.trans (subset_union_right _ _) h⟩⟩, λ ⟨⟨s, h₁⟩, ⟨t, h₂⟩⟩, ⟨s, t, union_subset h₁ h₂⟩⟩⟩ /-- Construct a realizer for the inf of two filters -/ protected def inf {f g : filter α} (F : f.realizer) (G : g.realizer) : (f ⊓ g).realizer := ⟨F.σ × G.σ, { f := λ ⟨s, t⟩, F.F s ∩ G.F t, pt := (F.F.pt, G.F.pt), inf := λ ⟨a, a'⟩ ⟨b, b'⟩, (F.F.inf a b, G.F.inf a' b'), inf_le_left := λ ⟨a, a'⟩ ⟨b, b'⟩, inter_subset_inter (F.F.inf_le_left _ _) (G.F.inf_le_left _ _), inf_le_right := λ ⟨a, a'⟩ ⟨b, b'⟩, inter_subset_inter (F.F.inf_le_right _ _) (G.F.inf_le_right _ _) }, begin ext x, cases F; cases G; substs f g; simp [cfilter.to_filter], split, { rintro ⟨s : F_σ, t : G_σ, h⟩, apply mem_inf_of_inter _ _ h, use s, use t, }, { rintros ⟨s, ⟨a, ha⟩, t, ⟨b, hb⟩, rfl⟩, exact ⟨a, b, inter_subset_inter ha hb⟩ } end⟩ /-- Construct a realizer for the cofinite filter -/ protected def cofinite [decidable_eq α] : (@cofinite α).realizer := ⟨finset α, { f := λ s, {a | a ∉ s}, pt := ∅, inf := (∪), inf_le_left := λ s t a, mt (finset.mem_union_left _), inf_le_right := λ s t a, mt (finset.mem_union_right _) }, filter_eq $ set.ext $ λ x, ⟨λ ⟨s, h⟩, s.finite_to_set.subset (compl_subset_comm.1 h), λ ⟨fs⟩, by exactI ⟨xᶜ.to_finset, λ a (h : a ∉ xᶜ.to_finset), classical.by_contradiction $ λ h', h (mem_to_finset.2 h')⟩⟩⟩ /-- Construct a realizer for filter bind -/ protected def bind {f : filter α} {m : α → filter β} (F : f.realizer) (G : ∀ i, (m i).realizer) : (f.bind m).realizer := ⟨Σ s : F.σ, Π i ∈ F.F s, (G i).σ, { f := λ ⟨s, f⟩, ⋃ i ∈ F.F s, (G i).F (f i H), pt := ⟨F.F.pt, λ i H, (G i).F.pt⟩, inf := λ ⟨a, f⟩ ⟨b, f'⟩, ⟨F.F.inf a b, λ i h, (G i).F.inf (f i (F.F.inf_le_left _ _ h)) (f' i (F.F.inf_le_right _ _ h))⟩, inf_le_left := λ ⟨a, f⟩ ⟨b, f'⟩ x, show (x ∈ ⋃ (i : α) (H : i ∈ F.F (F.F.inf a b)), _) → x ∈ ⋃ i (H : i ∈ F.F a), ((G i).F) (f i H), by simp; exact λ i h₁ h₂, ⟨i, F.F.inf_le_left _ _ h₁, (G i).F.inf_le_left _ _ h₂⟩, inf_le_right := λ ⟨a, f⟩ ⟨b, f'⟩ x, show (x ∈ ⋃ (i : α) (H : i ∈ F.F (F.F.inf a b)), _) → x ∈ ⋃ i (H : i ∈ F.F b), ((G i).F) (f' i H), by simp; exact λ i h₁ h₂, ⟨i, F.F.inf_le_right _ _ h₁, (G i).F.inf_le_right _ _ h₂⟩ }, filter_eq $ set.ext $ λ x, by cases F with _ F _; subst f; simp [cfilter.to_filter, mem_bind]; exact ⟨λ ⟨s, f, h⟩, ⟨F s, ⟨s, subset.refl _⟩, λ i H, (G i).mem_sets.2 ⟨f i H, λ a h', h ⟨_, ⟨i, rfl⟩, _, ⟨H, rfl⟩, h'⟩⟩⟩, λ ⟨y, ⟨s, h⟩, f⟩, let ⟨f', h'⟩ := classical.axiom_of_choice (λ i:F s, (G i).mem_sets.1 (f i (h i.2))) in ⟨s, λ i h, f' ⟨i, h⟩, λ a ⟨_, ⟨i, rfl⟩, _, ⟨H, rfl⟩, m⟩, h' ⟨_, H⟩ m⟩⟩⟩ /-- Construct a realizer for indexed supremum -/ protected def Sup {f : α → filter β} (F : ∀ i, (f i).realizer) : (⨆ i, f i).realizer := let F' : (⨆ i, f i).realizer := ((realizer.bind realizer.top F).of_eq $ filter_eq $ set.ext $ by simp [filter.bind, eq_univ_iff_forall, supr_sets_eq]) in F'.of_equiv $ show (Σ u:unit, Π (i : α), true → (F i).σ) ≃ Π i, (F i).σ, from ⟨λ⟨_,f⟩ i, f i ⟨⟩, λ f, ⟨(), λ i _, f i⟩, λ ⟨⟨⟩, f⟩, by dsimp; congr; simp, λ f, rfl⟩ /-- Construct a realizer for the product of filters -/ protected def prod {f g : filter α} (F : f.realizer) (G : g.realizer) : (f.prod g).realizer := (F.comap _).inf (G.comap _) theorem le_iff {f g : filter α} (F : f.realizer) (G : g.realizer) : f ≤ g ↔ ∀ b : G.σ, ∃ a : F.σ, F.F a ≤ G.F b := ⟨λ H t, F.mem_sets.1 (H (G.mem_sets.2 ⟨t, subset.refl _⟩)), λ H x h, F.mem_sets.2 $ let ⟨s, h₁⟩ := G.mem_sets.1 h, ⟨t, h₂⟩ := H s in ⟨t, subset.trans h₂ h₁⟩⟩ theorem tendsto_iff (f : α → β) {l₁ : filter α} {l₂ : filter β} (L₁ : l₁.realizer) (L₂ : l₂.realizer) : tendsto f l₁ l₂ ↔ ∀ b, ∃ a, ∀ x ∈ L₁.F a, f x ∈ L₂.F b := (le_iff (L₁.map f) L₂).trans $ forall_congr $ λ b, exists_congr $ λ a, image_subset_iff theorem ne_bot_iff {f : filter α} (F : f.realizer) : f ≠ ⊥ ↔ ∀ a : F.σ, (F.F a).nonempty := begin classical, rw [not_iff_comm, ← le_bot_iff, F.le_iff realizer.bot, not_forall], simp only [set.not_nonempty_iff_eq_empty], exact ⟨λ ⟨x, e⟩ _, ⟨x, le_of_eq e⟩, λ h, let ⟨x, h⟩ := h () in ⟨x, le_bot_iff.1 h⟩⟩ end end filter.realizer
60f285eb993e2a21fa94a22b22c83851c426653e
b561a44b48979a98df50ade0789a21c79ee31288
/src/Lean/ParserCompiler.lean
36c47c460ef692b6754877f31f912936848ac175
[ "Apache-2.0" ]
permissive
3401ijk/lean4
97659c475ebd33a034fed515cb83a85f75ccfb06
a5b1b8de4f4b038ff752b9e607b721f15a9a4351
refs/heads/master
1,693,933,007,651
1,636,424,845,000
1,636,424,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,389
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.Util.ReplaceExpr import Lean.Meta.Basic import Lean.Meta.WHNF import Lean.ParserCompiler.Attribute import Lean.Parser.Extension /-! Gadgets for compiling parser declarations into other programs, such as pretty printers. -/ namespace Lean namespace ParserCompiler structure Context (α : Type) where varName : Name categoryAttr : KeyedDeclsAttribute α combinatorAttr : CombinatorAttribute def Context.tyName {α} (ctx : Context α) : Name := ctx.categoryAttr.defn.valueTypeName -- replace all references of `Parser` with `tyName` def replaceParserTy {α} (ctx : Context α) (e : Expr) : Expr := e.replace fun e => -- strip `optParam` let e := if e.isOptParam then e.appFn!.appArg! else e if e.isConstOf `Lean.Parser.Parser then mkConst ctx.tyName else none section open Meta variable {α} (ctx : Context α) (force : Bool := false) in /-- Translate an expression of type `Parser` into one of type `tyName`, tagging intermediary constants with `ctx.combinatorAttr`. If `force` is `false`, refuse to do so for imported constants. -/ partial def compileParserExpr (e : Expr) : MetaM Expr := do let e ← whnfCore e match e with | e@(Expr.lam _ _ _ _) => lambdaLetTelescope e fun xs b => compileParserExpr b >>= mkLambdaFVars xs | e@(Expr.fvar _ _) => pure e | _ => do let fn := e.getAppFn let Expr.const c _ _ ← pure fn | throwError "call of unknown parser at '{e}'" let args := e.getAppArgs -- call the translated `p` with (a prefix of) the arguments of `e`, recursing for arguments -- of type `ty` (i.e. formerly `Parser`) let mkCall (p : Name) := do let ty ← inferType (mkConst p) forallTelescope ty fun params _ => do let mut p := mkConst p let args := e.getAppArgs for i in [:Nat.min params.size args.size] do let param := params[i] let arg := args[i] let paramTy ← inferType param let resultTy ← forallTelescope paramTy fun _ b => pure b let arg ← if resultTy.isConstOf ctx.tyName then compileParserExpr arg else pure arg p := mkApp p arg pure p let env ← getEnv match ctx.combinatorAttr.getDeclFor? env c with | some p => mkCall p | none => let c' := c ++ ctx.varName let cinfo ← getConstInfo c let resultTy ← forallTelescope cinfo.type fun _ b => pure b if resultTy.isConstOf `Lean.Parser.TrailingParser || resultTy.isConstOf `Lean.Parser.Parser then do -- synthesize a new `[combinatorAttr c]` let some value ← pure cinfo.value? | throwError "don't know how to generate {ctx.varName} for non-definition '{e}'" unless (env.getModuleIdxFor? c).isNone || force do throwError "refusing to generate code for imported parser declaration '{c}'; use `@[runParserAttributeHooks]` on its definition instead." let value ← compileParserExpr $ replaceParserTy ctx value let ty ← forallTelescope cinfo.type fun params _ => params.foldrM (init := mkConst ctx.tyName) fun param ty => do let paramTy ← replaceParserTy ctx <$> inferType param pure $ mkForall `_ BinderInfo.default paramTy ty let decl := Declaration.defnDecl { name := c', levelParams := [], type := ty, value := value, hints := ReducibilityHints.opaque, safety := DefinitionSafety.safe } let env ← getEnv let env ← match env.addAndCompile {} decl with | Except.ok env => pure env | Except.error kex => do throwError (← (kex.toMessageData {}).toString) setEnv $ ctx.combinatorAttr.setDeclFor env c c' mkCall c' else -- if this is a generic function, e.g. `AndThen.andthen`, it's easier to just unfold it until we are -- back to parser combinators let some e' ← unfoldDefinition? e | throwError "don't know how to generate {ctx.varName} for non-parser combinator '{e}'" compileParserExpr e' end open Core /-- Compile the given declaration into a `[(builtin)categoryAttr declName]` -/ def compileCategoryParser {α} (ctx : Context α) (declName : Name) (builtin : Bool) : AttrM Unit := do -- This will also tag the declaration as a `[combinatorParenthesizer declName]` in case the parser is used by other parsers. -- Note that simply having `[(builtin)Parenthesizer]` imply `[combinatorParenthesizer]` is not ideal since builtin -- attributes are active only in the next stage, while `[combinatorParenthesizer]` is active immediately (since we never -- call them at compile time but only reference them). let (Expr.const c' _ _) ← (compileParserExpr ctx (mkConst declName) (force := false)).run' | unreachable! -- We assume that for tagged parsers, the kind is equal to the declaration name. This is automatically true for parsers -- using `leading_parser` or `syntax`. let kind := declName let attrName := if builtin then ctx.categoryAttr.defn.builtinName else ctx.categoryAttr.defn.name -- Create syntax node for a simple attribute of the form -- `def simple := leading_parser ident >> optional (ident <|> priorityParser)` let stx := mkNode `Lean.Parser.Attr.simple #[ mkIdent attrName, mkNullNode #[mkIdent kind] ] Attribute.add c' attrName stx variable {α} (ctx : Context α) in def compileEmbeddedParsers : ParserDescr → MetaM Unit | ParserDescr.const _ => pure () | ParserDescr.unary _ d => compileEmbeddedParsers d | ParserDescr.binary _ d₁ d₂ => compileEmbeddedParsers d₁ *> compileEmbeddedParsers d₂ | ParserDescr.parser constName => discard $ compileParserExpr ctx (mkConst constName) (force := false) | ParserDescr.node _ _ d => compileEmbeddedParsers d | ParserDescr.nodeWithAntiquot _ _ d => compileEmbeddedParsers d | ParserDescr.sepBy p _ psep _ => compileEmbeddedParsers p *> compileEmbeddedParsers psep | ParserDescr.sepBy1 p _ psep _ => compileEmbeddedParsers p *> compileEmbeddedParsers psep | ParserDescr.trailingNode _ _ _ d => compileEmbeddedParsers d | ParserDescr.symbol _ => pure () | ParserDescr.nonReservedSymbol _ _ => pure () | ParserDescr.cat _ _ => pure () /-- Precondition: `α` must match `ctx.tyName`. -/ unsafe def registerParserCompiler {α} (ctx : Context α) : IO Unit := do Parser.registerParserAttributeHook { postAdd := fun catName constName builtin => do let info ← getConstInfo constName if info.type.isConstOf `Lean.ParserDescr || info.type.isConstOf `Lean.TrailingParserDescr then let d ← evalConstCheck ParserDescr `Lean.ParserDescr constName <|> evalConstCheck TrailingParserDescr `Lean.TrailingParserDescr constName compileEmbeddedParsers ctx d |>.run' else if catName.isAnonymous then -- `[runBuiltinParserAttributeHooks]` => force compilation even if imported, do not apply `ctx.categoryAttr`. discard (compileParserExpr ctx (mkConst constName) (force := true)).run' else compileCategoryParser ctx constName builtin } end ParserCompiler end Lean
63e4c233c7aec376fddc3333911e2bd156ff0106
e514e8b939af519a1d5e9b30a850769d058df4e9
/src/tactic/rewrite_search/core/default.lean
d5fdd9ed93dcf501933b4083c27a33792d36bf12
[]
no_license
semorrison/lean-rewrite-search
dca317c5a52e170fb6ffc87c5ab767afb5e3e51a
e804b8f2753366b8957be839908230ee73f9e89f
refs/heads/master
1,624,051,754,485
1,614,160,817,000
1,614,160,817,000
162,660,605
0
1
null
null
null
null
UTF-8
Lean
false
false
92
lean
import .common import .types import .debug import .backtrack import .explain import .engine
f688f4509e396090c5681f00a6c98c041d6485b5
f1dc39e1c68f71465c8bf79910c4664d03824751
/tests/lean/run/mario_type_context.lean
560c24e30856f76feda841a2210cb3f409fc3bd5
[ "Apache-2.0" ]
permissive
kckennylau/lean-2
6504f45da07bc98b098d726b74130103be25885c
c9a9368bc0fd600d832bd56c5cb2124b8a523ef9
refs/heads/master
1,659,140,308,864
1,589,361,166,000
1,589,361,166,000
263,748,786
0
0
null
1,589,405,915,000
1,589,405,915,000
null
UTF-8
Lean
false
false
561
lean
-- see https://leanprover.zulipchat.com/#narrow/stream/116395-maths/topic/witt.20vectors/near/168407094 set_option profiler true open tactic def bar (α) [semiring α] : α := sorry lemma foo (α) [comm_ring α] (h : bar α = @bar α (@comm_semiring.to_semiring α _)) : true := by do h ← get_local `h, ht ← infer_type h, `(%%h1 = %%h2) ← return ht, ht' ← to_expr ``(%%h2 = %%h2), pr ← mk_app `eq.refl [ht], pr' ← mk_app `eq.refl [ht'], trace [ht, ht, pr', h], try_for 100 $ mk_mapp `eq.mp [ht, ht, pr', h], -- slow step admit
a18656bf4fe554fc4d69c11717c944e333cba0b2
56e5b79a7ab4f2c52e6eb94f76d8100a25273cf3
/src/tests/test_get_tsd.lean
2aaedfc7f9537591278583428f479a26eac0e2ff
[ "Apache-2.0" ]
permissive
DyeKuu/lean-tpe-public
3a9968f286ca182723ef7e7d97e155d8cb6b1e70
750ade767ab28037e80b7a80360d213a875038f8
refs/heads/master
1,682,842,633,115
1,621,330,793,000
1,621,330,793,000
368,475,816
0
0
Apache-2.0
1,621,330,745,000
1,621,330,744,000
null
UTF-8
Lean
false
false
2,100
lean
import system.io import utils -- import all -- uncomment as needed, depending on the `decls_file` import ..evaluation /-- checks that we can get and set the tactic_state_data from a list of files -/ meta def test_get_tsd (decls_file : string) : io unit := do { nm_strs ← (io.mk_file_handle decls_file io.mode.read >>= λ f, (string.split (λ c, c = '\n') <$> buffer.to_string <$> io.fs.read_to_end f)), -- io.put_str_ln' format!"NM STRS: {nm_strs}", (nms : list (name × list name)) ← (nm_strs.filter $ λ nm_str, string.length nm_str > 0).mmap $ λ nm_str, do { ((io.run_tactic' ∘ parse_decl_nm_and_open_ns) $ nm_str) }, io.put_str_ln' format!"[evaluation_harness_from_decls_file] GOT {nms.length} NAMES", for_ nms ( let body : (name × list name) → io unit := λ ⟨decl_nm, open_ns⟩, do { when (decl_nm.length > 0) $ do env₀ ← io.run_tactic' $ tactic.get_env, io.run_tactic' $ (do { tsd_result ← tactic.capture $ get_tsd_at_decl decl_nm, tsd ← match tsd_result with | (interaction_monad.result.success val state) := tactic.resume tsd_result *> pure val | exc@(interaction_monad.result.exception _ _ _) := tactic.trace format!"[test_get_tsd] SERIALIZATION FAILED ON {decl_nm} HELLO \n---{exc}\n---" *> tactic.fail exc end, rebuild_result ← tactic.capture (rebuild_tactic_state tsd), match rebuild_result with | (interaction_monad.result.success val state) := tactic.resume rebuild_result | exc := tactic.trace format!"[test_get_tsd] RECONSTRUCTION FAILED ON {decl_nm} GOODBYE \n---{exc}\n---" *> tactic.resume exc end, tactic.trace format!"REBUILT TSD FOR DECL: {decl_nm}" }) <|> pure (), io.run_tactic' $ tactic.set_env_core env₀ } in body ) } meta def main : io unit := do { args ← io.cmdline_args, decls_file ← lift_option $ args.nth 0 | io.fail "must supply decls_file as first argument", io.put_str_ln' format!"[test_get_tsd.main] ENTERING test_get_tsd {decls_file}", test_get_tsd decls_file }
fdfea0930d211522bcbeb64150b0e11c19c7b22c
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebra/lie/subalgebra.lean
0e8fa028c81d6f3e1bb5b66f8d6716f33ba34c56
[ "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
21,854
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.basic import ring_theory.noetherian /-! # Lie subalgebras This file defines Lie subalgebras of a Lie algebra and provides basic related definitions and results. ## Main definitions * `lie_subalgebra` * `lie_subalgebra.incl` * `lie_subalgebra.map` * `lie_hom.range` * `lie_equiv.of_injective` * `lie_equiv.of_eq` * `lie_equiv.of_subalgebra` * `lie_equiv.of_subalgebras` ## Tags lie algebra, lie subalgebra -/ universes u v w w₁ w₂ section lie_subalgebra variables (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] /-- A Lie subalgebra of a Lie algebra is submodule that is closed under the Lie bracket. This is a sufficient condition for the subset itself to form a Lie algebra. -/ structure lie_subalgebra extends submodule R L := (lie_mem' : ∀ {x y}, x ∈ carrier → y ∈ carrier → ⁅x, y⁆ ∈ carrier) attribute [nolint doc_blame] lie_subalgebra.to_submodule /-- The zero algebra is a subalgebra of any Lie algebra. -/ instance : has_zero (lie_subalgebra R L) := ⟨{ lie_mem' := λ x y hx hy, by { rw [((submodule.mem_bot R).1 hx), zero_lie], exact submodule.zero_mem (0 : submodule R L), }, ..(0 : submodule R L) }⟩ instance : inhabited (lie_subalgebra R L) := ⟨0⟩ instance : has_coe (lie_subalgebra R L) (submodule R L) := ⟨lie_subalgebra.to_submodule⟩ instance : has_mem L (lie_subalgebra R L) := ⟨λ x L', x ∈ (L' : set L)⟩ namespace lie_subalgebra /-- A Lie subalgebra forms a new Lie ring. -/ instance (L' : lie_subalgebra R L) : lie_ring L' := { bracket := λ x y, ⟨⁅x.val, y.val⁆, L'.lie_mem' x.property y.property⟩, lie_add := by { intros, apply set_coe.ext, apply lie_add, }, add_lie := by { intros, apply set_coe.ext, apply add_lie, }, lie_self := by { intros, apply set_coe.ext, apply lie_self, }, leibniz_lie := by { intros, apply set_coe.ext, apply leibniz_lie, } } section variables {R₁ : Type*} [semiring R₁] /-- A Lie subalgebra inherits module structures from `L`. -/ instance [has_scalar R₁ R] [module R₁ L] [is_scalar_tower R₁ R L] (L' : lie_subalgebra R L) : module R₁ L' := L'.to_submodule.module' instance [has_scalar R₁ R] [has_scalar R₁ᵐᵒᵖ R] [module R₁ L] [module R₁ᵐᵒᵖ L] [is_scalar_tower R₁ R L] [is_scalar_tower R₁ᵐᵒᵖ R L] [is_central_scalar R₁ L] (L' : lie_subalgebra R L) : is_central_scalar R₁ L' := L'.to_submodule.is_central_scalar instance [has_scalar R₁ R] [module R₁ L] [is_scalar_tower R₁ R L] (L' : lie_subalgebra R L) : is_scalar_tower R₁ R L' := L'.to_submodule.is_scalar_tower end /-- A Lie subalgebra forms a new Lie algebra. -/ instance (L' : lie_subalgebra R L) : lie_algebra R L' := { lie_smul := by { intros, apply set_coe.ext, apply lie_smul } } variables {R L} (L' : lie_subalgebra R L) @[simp] lemma zero_mem : (0 : L) ∈ L' := (L' : submodule R L).zero_mem lemma smul_mem (t : R) {x : L} (h : x ∈ L') : t • x ∈ L' := (L' : submodule R L).smul_mem t h lemma add_mem {x y : L} (hx : x ∈ L') (hy : y ∈ L') : (x + y : L) ∈ L' := (L' : submodule R L).add_mem hx hy lemma sub_mem {x y : L} (hx : x ∈ L') (hy : y ∈ L') : (x - y : L) ∈ L' := (L' : submodule R L).sub_mem hx hy @[simp] lemma neg_mem_iff {x : L} : -x ∈ L' ↔ x ∈ L' := L'.to_submodule.neg_mem_iff lemma lie_mem {x y : L} (hx : x ∈ L') (hy : y ∈ L') : (⁅x, y⁆ : L) ∈ L' := L'.lie_mem' hx hy @[simp] lemma mem_carrier {x : L} : x ∈ L'.carrier ↔ x ∈ (L' : set L) := iff.rfl @[simp] lemma mem_mk_iff (S : set L) (h₁ h₂ h₃ h₄) {x : L} : x ∈ (⟨⟨S, h₁, h₂, h₃⟩, h₄⟩ : lie_subalgebra R L) ↔ x ∈ S := iff.rfl @[simp] lemma mem_coe_submodule {x : L} : x ∈ (L' : submodule R L) ↔ x ∈ L' := iff.rfl lemma mem_coe {x : L} : x ∈ (L' : set L) ↔ x ∈ L' := iff.rfl @[simp, norm_cast] lemma coe_bracket (x y : L') : (↑⁅x, y⁆ : L) = ⁅(↑x : L), ↑y⁆ := rfl lemma ext_iff (x y : L') : x = y ↔ (x : L) = y := subtype.ext_iff lemma coe_zero_iff_zero (x : L') : (x : L) = 0 ↔ x = 0 := (ext_iff L' x 0).symm @[ext] lemma ext (L₁' L₂' : lie_subalgebra R L) (h : ∀ x, x ∈ L₁' ↔ x ∈ L₂') : L₁' = L₂' := by { cases L₁', cases L₂', simp only [], ext x, exact h x, } lemma ext_iff' (L₁' L₂' : lie_subalgebra R L) : L₁' = L₂' ↔ ∀ x, x ∈ L₁' ↔ x ∈ L₂' := ⟨λ h x, by rw h, ext L₁' L₂'⟩ @[simp] lemma mk_coe (S : set L) (h₁ h₂ h₃ h₄) : ((⟨⟨S, h₁, h₂, h₃⟩, h₄⟩ : lie_subalgebra R L) : set L) = S := rfl @[simp] lemma coe_to_submodule_mk (p : submodule R L) (h) : (({lie_mem' := h, ..p} : lie_subalgebra R L) : submodule R L) = p := by { cases p, refl, } lemma coe_injective : function.injective (coe : lie_subalgebra R L → set L) := by { rintro ⟨⟨⟩⟩ ⟨⟨⟩⟩ h, congr' } @[norm_cast] theorem coe_set_eq (L₁' L₂' : lie_subalgebra R L) : (L₁' : set L) = L₂' ↔ L₁' = L₂' := coe_injective.eq_iff lemma to_submodule_injective : function.injective (coe : lie_subalgebra R L → submodule R L) := λ L₁' L₂' h, by { rw set_like.ext'_iff at h, rw ← coe_set_eq, exact h, } @[simp] lemma coe_to_submodule_eq_iff (L₁' L₂' : lie_subalgebra R L) : (L₁' : submodule R L) = (L₂' : submodule R L) ↔ L₁' = L₂' := to_submodule_injective.eq_iff @[norm_cast] lemma coe_to_submodule : ((L' : submodule R L) : set L) = L' := rfl section lie_module variables {M : Type w} [add_comm_group M] [lie_ring_module L M] variables {N : Type w₁} [add_comm_group N] [lie_ring_module L N] [module R N] [lie_module R L N] /-- Given a Lie algebra `L` containing a Lie subalgebra `L' ⊆ L`, together with a Lie ring module `M` of `L`, we may regard `M` as a Lie ring module of `L'` by restriction. -/ instance : lie_ring_module L' M := { bracket := λ x m, ⁅(x : L), m⁆, add_lie := λ x y m, add_lie x y m, lie_add := λ x y m, lie_add x y m, leibniz_lie := λ x y m, leibniz_lie x y m, } @[simp] lemma coe_bracket_of_module (x : L') (m : M) : ⁅x, m⁆ = ⁅(x : L), m⁆ := rfl variables [module R M] [lie_module R L M] /-- Given a Lie algebra `L` containing a Lie subalgebra `L' ⊆ L`, together with a Lie module `M` of `L`, we may regard `M` as a Lie module of `L'` by restriction. -/ instance : lie_module R L' M := { smul_lie := λ t x m, by simp only [coe_bracket_of_module, smul_lie, submodule.coe_smul_of_tower], lie_smul := λ t x m, by simp only [coe_bracket_of_module, lie_smul], } /-- An `L`-equivariant map of Lie modules `M → N` is `L'`-equivariant for any Lie subalgebra `L' ⊆ L`. -/ def _root_.lie_module_hom.restrict_lie (f : M →ₗ⁅R,L⁆ N) (L' : lie_subalgebra R L) : M →ₗ⁅R,L'⁆ N := { map_lie' := λ x m, f.map_lie ↑x m, .. (f : M →ₗ[R] N)} @[simp] lemma _root_.lie_module_hom.coe_restrict_lie (f : M →ₗ⁅R,L⁆ N) : ⇑(f.restrict_lie L') = f := rfl end lie_module /-- The embedding of a Lie subalgebra into the ambient space as a morphism of Lie algebras. -/ def incl : L' →ₗ⁅R⁆ L := { map_lie' := λ x y, by { simp only [linear_map.to_fun_eq_coe, submodule.subtype_apply], refl, }, .. (L' : submodule R L).subtype, } @[simp] lemma coe_incl : ⇑L'.incl = coe := rfl /-- The embedding of a Lie subalgebra into the ambient space as a morphism of Lie modules. -/ def incl' : L' →ₗ⁅R,L'⁆ L := { map_lie' := λ x y, by simp only [coe_bracket_of_module, linear_map.to_fun_eq_coe, submodule.subtype_apply, coe_bracket], .. (L' : submodule R L).subtype, } @[simp] lemma coe_incl' : ⇑L'.incl' = coe := rfl end lie_subalgebra variables {R L} {L₂ : Type w} [lie_ring L₂] [lie_algebra R L₂] variables (f : L →ₗ⁅R⁆ L₂) namespace lie_hom /-- The range of a morphism of Lie algebras is a Lie subalgebra. -/ def range : lie_subalgebra R L₂ := { lie_mem' := λ x y, show x ∈ f.to_linear_map.range → y ∈ f.to_linear_map.range → ⁅x, y⁆ ∈ f.to_linear_map.range, by { repeat { rw linear_map.mem_range }, rintros ⟨x', hx⟩ ⟨y', hy⟩, refine ⟨⁅x', y'⁆, _⟩, rw [←hx, ←hy], change f ⁅x', y'⁆ = ⁅f x', f y'⁆, rw map_lie, }, ..(f : L →ₗ[R] L₂).range } @[simp] lemma range_coe : (f.range : set L₂) = set.range f := linear_map.range_coe ↑f @[simp] lemma mem_range (x : L₂) : x ∈ f.range ↔ ∃ (y : L), f y = x := linear_map.mem_range lemma mem_range_self (x : L) : f x ∈ f.range := linear_map.mem_range_self f x /-- We can restrict a morphism to a (surjective) map to its range. -/ def range_restrict : L →ₗ⁅R⁆ f.range := { map_lie' := λ x y, by { apply subtype.ext, exact f.map_lie x y, }, ..(f : L →ₗ[R] L₂).range_restrict, } @[simp] lemma range_restrict_apply (x : L) : f.range_restrict x = ⟨f x, f.mem_range_self x⟩ := rfl lemma surjective_range_restrict : function.surjective (f.range_restrict) := begin rintros ⟨y, hy⟩, erw mem_range at hy, obtain ⟨x, rfl⟩ := hy, use x, simp only [subtype.mk_eq_mk, range_restrict_apply], end end lie_hom lemma submodule.exists_lie_subalgebra_coe_eq_iff (p : submodule R L) : (∃ (K : lie_subalgebra R L), ↑K = p) ↔ ∀ (x y : L), x ∈ p → y ∈ p → ⁅x, y⁆ ∈ p := begin split, { rintros ⟨K, rfl⟩, exact K.lie_mem', }, { intros h, use { lie_mem' := h, ..p }, exact lie_subalgebra.coe_to_submodule_mk p _, }, end namespace lie_subalgebra variables (K K' : lie_subalgebra R L) (K₂ : lie_subalgebra R L₂) @[simp] lemma incl_range : K.incl.range = K := by { rw ← coe_to_submodule_eq_iff, exact (K : submodule R L).range_subtype, } /-- The image of a Lie subalgebra under a Lie algebra morphism is a Lie subalgebra of the codomain. -/ def map : lie_subalgebra R L₂ := { lie_mem' := λ x y hx hy, by { erw submodule.mem_map at hx, rcases hx with ⟨x', hx', hx⟩, rw ←hx, erw submodule.mem_map at hy, rcases hy with ⟨y', hy', hy⟩, rw ←hy, erw submodule.mem_map, exact ⟨⁅x', y'⁆, K.lie_mem hx' hy', f.map_lie x' y'⟩, }, ..((K : submodule R L).map (f : L →ₗ[R] L₂)) } @[simp] lemma mem_map (x : L₂) : x ∈ K.map f ↔ ∃ (y : L), y ∈ K ∧ f y = x := submodule.mem_map -- TODO Rename and state for homs instead of equivs. @[simp] lemma mem_map_submodule (e : L ≃ₗ⁅R⁆ L₂) (x : L₂) : x ∈ K.map (e : L →ₗ⁅R⁆ L₂) ↔ x ∈ (K : submodule R L).map (e : L →ₗ[R] L₂) := iff.rfl /-- The preimage of a Lie subalgebra under a Lie algebra morphism is a Lie subalgebra of the domain. -/ def comap : lie_subalgebra R L := { lie_mem' := λ x y hx hy, by { suffices : ⁅f x, f y⁆ ∈ K₂, by { simp [this], }, exact K₂.lie_mem hx hy, }, ..((K₂ : submodule R L₂).comap (f : L →ₗ[R] L₂)), } section lattice_structure open set instance : partial_order (lie_subalgebra R L) := { le := λ N N', ∀ ⦃x⦄, x ∈ N → x ∈ N', -- Overriding `le` like this gives a better defeq. ..partial_order.lift (coe : lie_subalgebra R L → set L) coe_injective } lemma le_def : K ≤ K' ↔ (K : set L) ⊆ K' := iff.rfl @[simp, norm_cast] lemma coe_submodule_le_coe_submodule : (K : submodule R L) ≤ K' ↔ K ≤ K' := iff.rfl instance : has_bot (lie_subalgebra R L) := ⟨0⟩ @[simp] lemma bot_coe : ((⊥ : lie_subalgebra R L) : set L) = {0} := rfl @[simp] lemma bot_coe_submodule : ((⊥ : lie_subalgebra R L) : submodule R L) = ⊥ := rfl @[simp] lemma mem_bot (x : L) : x ∈ (⊥ : lie_subalgebra R L) ↔ x = 0 := mem_singleton_iff instance : has_top (lie_subalgebra R L) := ⟨{ lie_mem' := λ x y hx hy, mem_univ ⁅x, y⁆, ..(⊤ : submodule R L) }⟩ @[simp] lemma top_coe : ((⊤ : lie_subalgebra R L) : set L) = univ := rfl @[simp] lemma top_coe_submodule : ((⊤ : lie_subalgebra R L) : submodule R L) = ⊤ := rfl @[simp] lemma mem_top (x : L) : x ∈ (⊤ : lie_subalgebra R L) := mem_univ x lemma _root_.lie_hom.range_eq_map : f.range = map f ⊤ := by { ext, simp } instance : has_inf (lie_subalgebra R L) := ⟨λ K K', { lie_mem' := λ x y hx hy, mem_inter (K.lie_mem hx.1 hy.1) (K'.lie_mem hx.2 hy.2), ..(K ⊓ K' : submodule R L) }⟩ instance : has_Inf (lie_subalgebra R L) := ⟨λ S, { lie_mem' := λ x y hx hy, by { simp only [submodule.mem_carrier, mem_Inter, submodule.Inf_coe, mem_set_of_eq, forall_apply_eq_imp_iff₂, exists_imp_distrib] at *, intros K hK, exact K.lie_mem (hx K hK) (hy K hK), }, ..Inf {(s : submodule R L) | s ∈ S} }⟩ @[simp] theorem inf_coe : (↑(K ⊓ K') : set L) = K ∩ K' := rfl @[simp] lemma Inf_coe_to_submodule (S : set (lie_subalgebra R L)) : (↑(Inf S) : submodule R L) = Inf {(s : submodule R L) | s ∈ S} := rfl @[simp] lemma Inf_coe (S : set (lie_subalgebra R L)) : (↑(Inf S) : set L) = ⋂ s ∈ S, (s : set L) := begin rw [← coe_to_submodule, Inf_coe_to_submodule, submodule.Inf_coe], ext x, simpa only [mem_Inter, mem_set_of_eq, forall_apply_eq_imp_iff₂, exists_imp_distrib], end lemma Inf_glb (S : set (lie_subalgebra R L)) : is_glb S (Inf S) := begin have h : ∀ (K K' : lie_subalgebra R L), (K : set L) ≤ K' ↔ K ≤ K', { intros, exact iff.rfl, }, apply is_glb.of_image h, simp only [Inf_coe], exact is_glb_binfi end /-- The set of Lie subalgebras of a Lie algebra form a complete lattice. We provide explicit values for the fields `bot`, `top`, `inf` to get more convenient definitions than we would otherwise obtain from `complete_lattice_of_Inf`. -/ instance : complete_lattice (lie_subalgebra R L) := { bot := ⊥, bot_le := λ N _ h, by { rw mem_bot at h, rw h, exact N.zero_mem', }, top := ⊤, le_top := λ _ _ _, trivial, inf := (⊓), le_inf := λ N₁ N₂ N₃ h₁₂ h₁₃ m hm, ⟨h₁₂ hm, h₁₃ hm⟩, inf_le_left := λ _ _ _, and.left, inf_le_right := λ _ _ _, and.right, ..complete_lattice_of_Inf _ Inf_glb } instance : add_comm_monoid (lie_subalgebra R L) := { add := (⊔), add_assoc := λ _ _ _, sup_assoc, zero := ⊥, zero_add := λ _, bot_sup_eq, add_zero := λ _, sup_bot_eq, add_comm := λ _ _, sup_comm, } @[simp] lemma add_eq_sup : K + K' = K ⊔ K' := rfl @[norm_cast, simp] lemma inf_coe_to_submodule : (↑(K ⊓ K') : submodule R L) = (K : submodule R L) ⊓ (K' : submodule R L) := rfl @[simp] lemma mem_inf (x : L) : x ∈ K ⊓ K' ↔ x ∈ K ∧ x ∈ K' := by rw [← mem_coe_submodule, ← mem_coe_submodule, ← mem_coe_submodule, inf_coe_to_submodule, submodule.mem_inf] lemma eq_bot_iff : K = ⊥ ↔ ∀ (x : L), x ∈ K → x = 0 := by { rw eq_bot_iff, exact iff.rfl, } -- TODO[gh-6025]: make this an instance once safe to do so lemma subsingleton_of_bot : subsingleton (lie_subalgebra R ↥(⊥ : lie_subalgebra R L)) := begin apply subsingleton_of_bot_eq_top, ext ⟨x, hx⟩, change x ∈ ⊥ at hx, rw submodule.mem_bot at hx, subst hx, simp only [true_iff, eq_self_iff_true, submodule.mk_eq_zero, mem_bot], end variables (R L) lemma well_founded_of_noetherian [is_noetherian R L] : well_founded ((>) : lie_subalgebra R L → lie_subalgebra R L → Prop) := let f : ((>) : lie_subalgebra R L → lie_subalgebra R L → Prop) →r ((>) : submodule R L → submodule R L → Prop) := { to_fun := coe, map_rel' := λ N N' h, h, } in rel_hom_class.well_founded f (is_noetherian_iff_well_founded.mp infer_instance) variables {R L K K' f} section nested_subalgebras variables (h : K ≤ K') /-- Given two nested Lie subalgebras `K ⊆ K'`, the inclusion `K ↪ K'` is a morphism of Lie algebras. -/ def hom_of_le : K →ₗ⁅R⁆ K' := { map_lie' := λ x y, rfl, ..submodule.of_le h } @[simp] lemma coe_hom_of_le (x : K) : (hom_of_le h x : L) = x := rfl lemma hom_of_le_apply (x : K) : hom_of_le h x = ⟨x.1, h x.2⟩ := rfl lemma hom_of_le_injective : function.injective (hom_of_le h) := λ x y, by simp only [hom_of_le_apply, imp_self, subtype.mk_eq_mk, set_like.coe_eq_coe, subtype.val_eq_coe] /-- Given two nested Lie subalgebras `K ⊆ K'`, we can view `K` as a Lie subalgebra of `K'`, regarded as Lie algebra in its own right. -/ def of_le : lie_subalgebra R K' := (hom_of_le h).range @[simp] lemma mem_of_le (x : K') : x ∈ of_le h ↔ (x : L) ∈ K := begin simp only [of_le, hom_of_le_apply, lie_hom.mem_range], split, { rintros ⟨y, rfl⟩, exact y.property, }, { intros h, use ⟨(x : L), h⟩, simp, }, end lemma of_le_eq_comap_incl : of_le h = K.comap K'.incl := by { ext, rw mem_of_le, refl, } end nested_subalgebras lemma map_le_iff_le_comap {K : lie_subalgebra R L} {K' : lie_subalgebra R L₂} : map f K ≤ K' ↔ K ≤ comap f K' := set.image_subset_iff lemma gc_map_comap : galois_connection (map f) (comap f) := λ K K', map_le_iff_le_comap end lattice_structure section lie_span variables (R L) (s : set L) /-- The Lie subalgebra of a Lie algebra `L` generated by a subset `s ⊆ L`. -/ def lie_span : lie_subalgebra R L := Inf {N | s ⊆ N} variables {R L s} lemma mem_lie_span {x : L} : x ∈ lie_span R L s ↔ ∀ K : lie_subalgebra R L, s ⊆ K → x ∈ K := by { change x ∈ (lie_span R L s : set L) ↔ _, erw Inf_coe, exact set.mem_Inter₂, } lemma subset_lie_span : s ⊆ lie_span R L s := by { intros m hm, erw mem_lie_span, intros K hK, exact hK hm, } lemma submodule_span_le_lie_span : submodule.span R s ≤ lie_span R L s := by { rw submodule.span_le, apply subset_lie_span, } lemma lie_span_le {K} : lie_span R L s ≤ K ↔ s ⊆ K := begin split, { exact set.subset.trans subset_lie_span, }, { intros hs m hm, rw mem_lie_span at hm, exact hm _ hs, }, end lemma lie_span_mono {t : set L} (h : s ⊆ t) : lie_span R L s ≤ lie_span R L t := by { rw lie_span_le, exact set.subset.trans h subset_lie_span, } lemma lie_span_eq : lie_span R L (K : set L) = K := le_antisymm (lie_span_le.mpr rfl.subset) subset_lie_span lemma coe_lie_span_submodule_eq_iff {p : submodule R L} : (lie_span R L (p : set L) : submodule R L) = p ↔ ∃ (K : lie_subalgebra R L), ↑K = p := begin rw p.exists_lie_subalgebra_coe_eq_iff, split; intros h, { intros x m hm, rw [← h, mem_coe_submodule], exact lie_mem _ (subset_lie_span hm), }, { rw [← coe_to_submodule_mk p h, coe_to_submodule, coe_to_submodule_eq_iff, lie_span_eq], }, end variables (R L) /-- `lie_span` forms a Galois insertion with the coercion from `lie_subalgebra` to `set`. -/ protected def gi : galois_insertion (lie_span R L : set L → lie_subalgebra R L) coe := { choice := λ s _, lie_span R L s, gc := λ s t, lie_span_le, le_l_u := λ s, subset_lie_span, choice_eq := λ s h, rfl } @[simp] lemma span_empty : lie_span R L (∅ : set L) = ⊥ := (lie_subalgebra.gi R L).gc.l_bot @[simp] lemma span_univ : lie_span R L (set.univ : set L) = ⊤ := eq_top_iff.2 $ set_like.le_def.2 $ subset_lie_span variables {L} lemma span_union (s t : set L) : lie_span R L (s ∪ t) = lie_span R L s ⊔ lie_span R L t := (lie_subalgebra.gi R L).gc.l_sup lemma span_Union {ι} (s : ι → set L) : lie_span R L (⋃ i, s i) = ⨆ i, lie_span R L (s i) := (lie_subalgebra.gi R L).gc.l_supr end lie_span end lie_subalgebra end lie_subalgebra namespace lie_equiv variables {R : Type u} {L₁ : Type v} {L₂ : Type w} variables [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_algebra R L₁] [lie_algebra R L₂] /-- An injective Lie algebra morphism is an equivalence onto its range. -/ noncomputable def of_injective (f : L₁ →ₗ⁅R⁆ L₂) (h : function.injective f) : L₁ ≃ₗ⁅R⁆ f.range := { map_lie' := λ x y, by { apply set_coe.ext, simpa, }, ..(linear_equiv.of_injective ↑f $ by rwa [lie_hom.coe_to_linear_map])} @[simp] lemma of_injective_apply (f : L₁ →ₗ⁅R⁆ L₂) (h : function.injective f) (x : L₁) : ↑(of_injective f h x) = f x := rfl variables (L₁' L₁'' : lie_subalgebra R L₁) (L₂' : lie_subalgebra R L₂) /-- Lie subalgebras that are equal as sets are equivalent as Lie algebras. -/ def of_eq (h : (L₁' : set L₁) = L₁'') : L₁' ≃ₗ⁅R⁆ L₁'' := { map_lie' := λ x y, by { apply set_coe.ext, simp, }, ..(linear_equiv.of_eq ↑L₁' ↑L₁'' (by {ext x, change x ∈ (L₁' : set L₁) ↔ x ∈ (L₁'' : set L₁), rw h, } )) } @[simp] lemma of_eq_apply (L L' : lie_subalgebra R L₁) (h : (L : set L₁) = L') (x : L) : (↑(of_eq L L' h x) : L₁) = x := rfl variables (e : L₁ ≃ₗ⁅R⁆ L₂) /-- An equivalence of Lie algebras restricts to an equivalence from any Lie subalgebra onto its image. -/ def lie_subalgebra_map : L₁'' ≃ₗ⁅R⁆ (L₁''.map e : lie_subalgebra R L₂) := { map_lie' := λ x y, by { apply set_coe.ext, exact lie_hom.map_lie (↑e : L₁ →ₗ⁅R⁆ L₂) ↑x ↑y, } ..(linear_equiv.submodule_map (e : L₁ ≃ₗ[R] L₂) ↑L₁'') } @[simp] lemma lie_subalgebra_map_apply (x : L₁'') : ↑(e.lie_subalgebra_map _ x) = e x := rfl /-- An equivalence of Lie algebras restricts to an equivalence from any Lie subalgebra onto its image. -/ def of_subalgebras (h : L₁'.map ↑e = L₂') : L₁' ≃ₗ⁅R⁆ L₂' := { map_lie' := λ x y, by { apply set_coe.ext, exact lie_hom.map_lie (↑e : L₁ →ₗ⁅R⁆ L₂) ↑x ↑y, }, ..(linear_equiv.of_submodules (e : L₁ ≃ₗ[R] L₂) ↑L₁' ↑L₂' (by { rw ←h, refl, })) } @[simp] lemma of_subalgebras_apply (h : L₁'.map ↑e = L₂') (x : L₁') : ↑(e.of_subalgebras _ _ h x) = e x := rfl @[simp] lemma of_subalgebras_symm_apply (h : L₁'.map ↑e = L₂') (x : L₂') : ↑((e.of_subalgebras _ _ h).symm x) = e.symm x := rfl end lie_equiv
9a29d42a829122ea1dbad771e326f7340062cc4c
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/topology/uniform_space/completion.lean
6806aa0c36ff3b64008801eac9a8d3713b0a1af6
[ "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
26,794
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl Hausdorff completions of uniform spaces. The goal is to construct a left-adjoint to the inclusion of complete Hausdorff uniform spaces into all uniform spaces. Any uniform space `α` gets a completion `completion α` and a morphism (ie. uniformly continuous map) `completion : α → completion α` which solves the universal mapping problem of factorizing morphisms from `α` to any complete Hausdorff uniform space `β`. It means any uniformly continuous `f : α → β` gives rise to a unique morphism `completion.extension f : completion α → β` such that `f = completion.extension f ∘ completion α`. Actually `completion.extension f` is defined for all maps from `α` to `β` but it has the desired properties only if `f` is uniformly continuous. Beware that `completion α` is not injective if `α` is not Hausdorff. But its image is always dense. The adjoint functor acting on morphisms is then constructed by the usual abstract nonsense. For every uniform spaces `α` and `β`, it turns `f : α → β` into a morphism `completion.map f : completion α → completion β` such that `coe ∘ f = (completion.map f) ∘ coe` provided `f` is uniformly continuous. This construction is compatible with composition. In this file we introduce the following concepts: * `Cauchy α` the uniform completion of the uniform space `α` (using Cauchy filters). These are not minimal filters. * `completion α := quotient (separation_setoid (Cauchy α))` the Hausdorff completion. This formalization is mostly based on N. Bourbaki: General Topology I. M. James: Topologies and Uniformities From a slightly different perspective in order to reuse material in topology.uniform_space.basic. -/ import data.set.basic import topology.uniform_space.uniform_embedding topology.uniform_space.separation noncomputable theory local attribute [instance] classical.prop_decidable open filter set universes u v w x local notation `𝓤` := uniformity /-- Space of Cauchy filters This is essentially the completion of a uniform space. The embeddings are the neighbourhood filters. This space is not minimal, the separated uniform space (i.e. quotiented on the intersection of all entourages) is necessary for this. -/ def Cauchy (α : Type u) [uniform_space α] : Type u := { f : filter α // cauchy f } namespace Cauchy section parameters {α : Type u} [uniform_space α] variables {β : Type v} {γ : Type w} variables [uniform_space β] [uniform_space γ] def gen (s : set (α × α)) : set (Cauchy α × Cauchy α) := {p | s ∈ filter.prod (p.1.val) (p.2.val) } lemma monotone_gen : monotone gen := monotone_set_of $ assume p, @monotone_mem_sets (α×α) (filter.prod (p.1.val) (p.2.val)) private lemma symm_gen : map prod.swap ((𝓤 α).lift' gen) ≤ (𝓤 α).lift' gen := calc map prod.swap ((𝓤 α).lift' gen) = (𝓤 α).lift' (λs:set (α×α), {p | s ∈ filter.prod (p.2.val) (p.1.val) }) : begin delta gen, simp [map_lift'_eq, monotone_set_of, monotone_mem_sets, function.comp, image_swap_eq_preimage_swap] end ... ≤ (𝓤 α).lift' gen : uniformity_lift_le_swap (monotone_comp (monotone_set_of $ assume p, @monotone_mem_sets (α×α) ((filter.prod ((p.2).val) ((p.1).val)))) monotone_principal) begin have h := λ(p:Cauchy α×Cauchy α), @filter.prod_comm _ _ (p.2.val) (p.1.val), simp [function.comp, h], exact le_refl _ end private lemma comp_rel_gen_gen_subset_gen_comp_rel {s t : set (α×α)} : comp_rel (gen s) (gen t) ⊆ (gen (comp_rel s t) : set (Cauchy α × Cauchy α)) := assume ⟨f, g⟩ ⟨h, h₁, h₂⟩, let ⟨t₁, (ht₁ : t₁ ∈ f.val), t₂, (ht₂ : t₂ ∈ h.val), (h₁ : set.prod t₁ t₂ ⊆ s)⟩ := mem_prod_iff.mp h₁ in let ⟨t₃, (ht₃ : t₃ ∈ h.val), t₄, (ht₄ : t₄ ∈ g.val), (h₂ : set.prod t₃ t₄ ⊆ t)⟩ := mem_prod_iff.mp h₂ in have t₂ ∩ t₃ ∈ h.val, from inter_mem_sets ht₂ ht₃, let ⟨x, xt₂, xt₃⟩ := inhabited_of_mem_sets (h.property.left) this in (filter.prod f.val g.val).sets_of_superset (prod_mem_prod ht₁ ht₄) (assume ⟨a, b⟩ ⟨(ha : a ∈ t₁), (hb : b ∈ t₄)⟩, ⟨x, h₁ (show (a, x) ∈ set.prod t₁ t₂, from ⟨ha, xt₂⟩), h₂ (show (x, b) ∈ set.prod t₃ t₄, from ⟨xt₃, hb⟩)⟩) private lemma comp_gen : ((𝓤 α).lift' gen).lift' (λs, comp_rel s s) ≤ (𝓤 α).lift' gen := calc ((𝓤 α).lift' gen).lift' (λs, comp_rel s s) = (𝓤 α).lift' (λs, comp_rel (gen s) (gen s)) : begin rw [lift'_lift'_assoc], exact monotone_gen, exact (monotone_comp_rel monotone_id monotone_id) end ... ≤ (𝓤 α).lift' (λs, gen $ comp_rel s s) : lift'_mono' $ assume s hs, comp_rel_gen_gen_subset_gen_comp_rel ... = ((𝓤 α).lift' $ λs:set(α×α), comp_rel s s).lift' gen : begin rw [lift'_lift'_assoc], exact (monotone_comp_rel monotone_id monotone_id), exact monotone_gen end ... ≤ (𝓤 α).lift' gen : lift'_mono comp_le_uniformity (le_refl _) instance : uniform_space (Cauchy α) := uniform_space.of_core { uniformity := (𝓤 α).lift' gen, refl := principal_le_lift' $ assume s hs ⟨a, b⟩ (a_eq_b : a = b), a_eq_b ▸ a.property.right hs, symm := symm_gen, comp := comp_gen } theorem mem_uniformity {s : set (Cauchy α × Cauchy α)} : s ∈ 𝓤 (Cauchy α) ↔ ∃ t ∈ 𝓤 α, gen t ⊆ s := mem_lift'_sets monotone_gen theorem mem_uniformity' {s : set (Cauchy α × Cauchy α)} : s ∈ 𝓤 (Cauchy α) ↔ ∃ t ∈ 𝓤 α, ∀ f g : Cauchy α, t ∈ filter.prod f.1 g.1 → (f, g) ∈ s := mem_uniformity.trans $ bex_congr $ λ t h, prod.forall /-- Embedding of `α` into its completion -/ def pure_cauchy (a : α) : Cauchy α := ⟨pure a, cauchy_pure⟩ lemma uniform_inducing_pure_cauchy : uniform_inducing (pure_cauchy : α → Cauchy α) := ⟨have (preimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) = id, from funext $ assume s, set.ext $ assume ⟨a₁, a₂⟩, by simp [preimage, gen, pure_cauchy, prod_principal_principal], calc comap (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ((𝓤 α).lift' gen) = (𝓤 α).lift' (preimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) : comap_lift'_eq monotone_gen ... = 𝓤 α : by simp [this]⟩ lemma uniform_embedding_pure_cauchy : uniform_embedding (pure_cauchy : α → Cauchy α) := { inj := assume a₁ a₂ h, have (pure_cauchy a₁).val = (pure_cauchy a₂).val, from congr_arg _ h, have {a₁} = ({a₂} : set α), from principal_eq_iff_eq.mp this, by simp at this; assumption, ..uniform_inducing_pure_cauchy } lemma pure_cauchy_dense : ∀x, x ∈ closure (range pure_cauchy) := assume f, have h_ex : ∀ s ∈ 𝓤 (Cauchy α), ∃y:α, (f, pure_cauchy y) ∈ s, from assume s hs, let ⟨t'', ht''₁, (ht''₂ : gen t'' ⊆ s)⟩ := (mem_lift'_sets monotone_gen).mp hs in let ⟨t', ht'₁, ht'₂⟩ := comp_mem_uniformity_sets ht''₁ in have t' ∈ filter.prod (f.val) (f.val), from f.property.right ht'₁, let ⟨t, ht, (h : set.prod t t ⊆ t')⟩ := mem_prod_same_iff.mp this in let ⟨x, (hx : x ∈ t)⟩ := inhabited_of_mem_sets f.property.left ht in have t'' ∈ filter.prod f.val (pure x), from mem_prod_iff.mpr ⟨t, ht, {y:α | (x, y) ∈ t'}, assume y, begin simp, intro h, simp [h], exact refl_mem_uniformity ht'₁ end, assume ⟨a, b⟩ ⟨(h₁ : a ∈ t), (h₂ : (x, b) ∈ t')⟩, ht'₂ $ prod_mk_mem_comp_rel (@h (a, x) ⟨h₁, hx⟩) h₂⟩, ⟨x, ht''₂ $ by dsimp [gen]; exact this⟩, begin simp [closure_eq_nhds, nhds_eq_uniformity, lift'_inf_principal_eq, set.inter_comm], exact (lift'_neq_bot_iff $ monotone_inter monotone_const monotone_preimage).mpr (assume s hs, let ⟨y, hy⟩ := h_ex s hs in have pure_cauchy y ∈ range pure_cauchy ∩ {y : Cauchy α | (f, y) ∈ s}, from ⟨mem_range_self y, hy⟩, ne_empty_of_mem this) end lemma dense_inducing_pure_cauchy : dense_inducing pure_cauchy := uniform_inducing_pure_cauchy.dense_inducing pure_cauchy_dense lemma dense_embedding_pure_cauchy : dense_embedding pure_cauchy := uniform_embedding_pure_cauchy.dense_embedding pure_cauchy_dense lemma nonempty_Cauchy_iff : nonempty (Cauchy α) ↔ nonempty α := begin split ; rintro ⟨c⟩, { have := eq_univ_iff_forall.1 dense_embedding_pure_cauchy.to_dense_inducing.closure_range c, have := mem_closure_iff.1 this _ is_open_univ trivial, rcases exists_mem_of_ne_empty this with ⟨_, ⟨_, a, _⟩⟩, exact ⟨a⟩ }, { exact ⟨pure_cauchy c⟩ } end section set_option eqn_compiler.zeta true instance : complete_space (Cauchy α) := complete_space_extension uniform_inducing_pure_cauchy pure_cauchy_dense $ assume f hf, let f' : Cauchy α := ⟨f, hf⟩ in have map pure_cauchy f ≤ (𝓤 $ Cauchy α).lift' (preimage (prod.mk f')), from le_lift' $ assume s hs, let ⟨t, ht₁, (ht₂ : gen t ⊆ s)⟩ := (mem_lift'_sets monotone_gen).mp hs in let ⟨t', ht', (h : set.prod t' t' ⊆ t)⟩ := mem_prod_same_iff.mp (hf.right ht₁) in have t' ⊆ { y : α | (f', pure_cauchy y) ∈ gen t }, from assume x hx, (filter.prod f (pure x)).sets_of_superset (prod_mem_prod ht' $ mem_pure hx) h, f.sets_of_superset ht' $ subset.trans this (preimage_mono ht₂), ⟨f', by simp [nhds_eq_uniformity]; assumption⟩ end instance [inhabited α] : inhabited (Cauchy α) := ⟨pure_cauchy $ default α⟩ instance [h : nonempty α] : nonempty (Cauchy α) := h.rec_on $ assume a, nonempty.intro $ Cauchy.pure_cauchy a section extend def extend (f : α → β) : (Cauchy α → β) := if uniform_continuous f then dense_inducing_pure_cauchy.extend f else λ x, f (classical.inhabited_of_nonempty $ nonempty_Cauchy_iff.1 ⟨x⟩).default variables [separated β] lemma extend_pure_cauchy {f : α → β} (hf : uniform_continuous f) (a : α) : extend f (pure_cauchy a) = f a := begin rw [extend, if_pos hf], exact uniformly_extend_of_ind uniform_inducing_pure_cauchy pure_cauchy_dense hf _ end variables [_root_.complete_space β] lemma uniform_continuous_extend {f : α → β} : uniform_continuous (extend f) := begin by_cases hf : uniform_continuous f, { rw [extend, if_pos hf], exact uniform_continuous_uniformly_extend uniform_inducing_pure_cauchy pure_cauchy_dense hf }, { rw [extend, if_neg hf], exact uniform_continuous_of_const (assume a b, by congr) } end end extend end theorem Cauchy_eq {α : Type*} [inhabited α] [uniform_space α] [complete_space α] [separated α] {f g : Cauchy α} : lim f.1 = lim g.1 ↔ (f, g) ∈ separation_rel (Cauchy α) := begin split, { intros e s hs, rcases Cauchy.mem_uniformity'.1 hs with ⟨t, tu, ts⟩, apply ts, rcases comp_mem_uniformity_sets tu with ⟨d, du, dt⟩, refine mem_prod_iff.2 ⟨_, le_nhds_lim_of_cauchy f.2 (mem_nhds_right (lim f.1) du), _, le_nhds_lim_of_cauchy g.2 (mem_nhds_left (lim g.1) du), λ x h, _⟩, cases x with a b, cases h with h₁ h₂, rw ← e at h₂, exact dt ⟨_, h₁, h₂⟩ }, { intros H, refine separated_def.1 (by apply_instance) _ _ (λ t tu, _), rcases mem_uniformity_is_closed tu with ⟨d, du, dc, dt⟩, refine H {p | (lim p.1.1, lim p.2.1) ∈ t} (Cauchy.mem_uniformity'.2 ⟨d, du, λ f g h, _⟩), rcases mem_prod_iff.1 h with ⟨x, xf, y, yg, h⟩, have limc : ∀ (f : Cauchy α) (x ∈ f.1), lim f.1 ∈ closure x, { intros f x xf, rw closure_eq_nhds, exact lattice.neq_bot_of_le_neq_bot f.2.1 (lattice.le_inf (le_nhds_lim_of_cauchy f.2) (le_principal_iff.2 xf)) }, have := (closure_subset_iff_subset_of_is_closed dc).2 h, rw closure_prod_eq at this, refine dt (this ⟨_, _⟩); dsimp; apply limc; assumption } end section local attribute [instance] uniform_space.separation_setoid lemma injective_separated_pure_cauchy {α : Type*} [uniform_space α] [s : separated α] : function.injective (λa:α, ⟦pure_cauchy a⟧) | a b h := separated_def.1 s _ _ $ assume s hs, let ⟨t, ht, hts⟩ := by rw [← (@uniform_embedding_pure_cauchy α _).comap_uniformity, filter.mem_comap_sets] at hs; exact hs in have (pure_cauchy a, pure_cauchy b) ∈ t, from quotient.exact h t ht, @hts (a, b) this end end Cauchy local attribute [instance] uniform_space.separation_setoid open Cauchy set namespace uniform_space variables (α : Type*) [uniform_space α] variables {β : Type*} [uniform_space β] variables {γ : Type*} [uniform_space γ] instance complete_space_separation [h : complete_space α] : complete_space (quotient (separation_setoid α)) := ⟨assume f, assume hf : cauchy f, have cauchy (f.comap (λx, ⟦x⟧)), from cauchy_comap comap_quotient_le_uniformity hf $ comap_neq_bot_of_surj hf.left $ assume b, quotient.exists_rep _, let ⟨x, (hx : f.comap (λx, ⟦x⟧) ≤ nhds x)⟩ := complete_space.complete this in ⟨⟦x⟧, calc f = map (λx, ⟦x⟧) (f.comap (λx, ⟦x⟧)) : (map_comap $ univ_mem_sets' $ assume b, quotient.exists_rep _).symm ... ≤ map (λx, ⟦x⟧) (nhds x) : map_mono hx ... ≤ _ : continuous_iff_continuous_at.mp uniform_continuous_quotient_mk.continuous _⟩⟩ /-- Hausdorff completion of `α` -/ def completion := quotient (separation_setoid $ Cauchy α) namespace completion @[priority 50] instance : uniform_space (completion α) := by dunfold completion ; apply_instance instance : complete_space (completion α) := by dunfold completion ; apply_instance instance : separated (completion α) := by dunfold completion ; apply_instance instance : t2_space (completion α) := separated_t2 instance : regular_space (completion α) := separated_regular lemma nonempty_completion_iff : nonempty (completion α) ↔ nonempty α := begin conv_rhs { rw ← nonempty_Cauchy_iff }, split ; rintro ⟨c⟩, { rcases quotient.exists_rep c with ⟨a, _⟩, exact ⟨a⟩ }, { exact ⟨⟦c⟧⟩ } end /-- Automatic coercion from `α` to its completion. Not always injective. -/ instance : has_coe α (completion α) := ⟨quotient.mk ∘ pure_cauchy⟩ protected lemma coe_eq : (coe : α → completion α) = quotient.mk ∘ pure_cauchy := rfl lemma uniform_continuous_coe : uniform_continuous (coe : α → completion α) := uniform_continuous.comp uniform_continuous_quotient_mk uniform_inducing_pure_cauchy.uniform_continuous lemma continuous_coe : continuous (coe : α → completion α) := uniform_continuous.continuous (uniform_continuous_coe α) lemma comap_coe_eq_uniformity : (𝓤 _).comap (λ(p:α×α), ((p.1 : completion α), (p.2 : completion α))) = 𝓤 α := begin have : (λx:α×α, ((x.1 : completion α), (x.2 : completion α))) = (λx:(Cauchy α)×(Cauchy α), (⟦x.1⟧, ⟦x.2⟧)) ∘ (λx:α×α, (pure_cauchy x.1, pure_cauchy x.2)), { ext ⟨a, b⟩; simp; refl }, rw [this, ← filter.comap_comap_comp], change filter.comap _ (filter.comap _ (𝓤 $ quotient $ separation_setoid $ Cauchy α)) = 𝓤 α, rw [comap_quotient_eq_uniformity, uniform_embedding_pure_cauchy.comap_uniformity] end lemma uniform_inducing_coe : uniform_inducing (coe : α → completion α) := ⟨comap_coe_eq_uniformity α⟩ lemma uniform_embedding_coe [separated α] : uniform_embedding (coe : α → completion α) := { comap_uniformity := comap_coe_eq_uniformity α, inj := injective_separated_pure_cauchy } variable {α} lemma dense : closure (range (coe : α → completion α)) = univ := by rw [completion.coe_eq, range_comp]; exact quotient_dense_of_dense pure_cauchy_dense lemma dense_inducing_coe : dense_inducing (coe : α → completion α) := { dense := (dense_range_iff_closure_eq _).2 dense, ..(uniform_inducing_coe α).inducing } lemma dense_embedding_coe [separated α]: dense_embedding (coe : α → completion α) := { inj := injective_separated_pure_cauchy, ..dense_inducing_coe } lemma dense₂ : closure (range (λx:α × β, ((x.1 : completion α), (x.2 : completion β)))) = univ := by rw [← set.prod_range_range_eq, closure_prod_eq, dense, dense, univ_prod_univ] lemma dense₃ : closure (range (λx:α × (β × γ), ((x.1 : completion α), ((x.2.1 : completion β), (x.2.2 : completion γ))))) = univ := let a : α → completion α := coe, bc := λp:β × γ, ((p.1 : completion β), (p.2 : completion γ)) in show closure (range (λx:α × (β × γ), (a x.1, bc x.2))) = univ, begin rw [← set.prod_range_range_eq, @closure_prod_eq _ _ _ _ (range a) (range bc), ← univ_prod_univ], congr, exact dense, exact dense₂ end @[elab_as_eliminator] lemma induction_on {p : completion α → Prop} (a : completion α) (hp : is_closed {a | p a}) (ih : ∀a:α, p a) : p a := is_closed_property dense hp ih a @[elab_as_eliminator] lemma induction_on₂ {p : completion α → completion β → Prop} (a : completion α) (b : completion β) (hp : is_closed {x : completion α × completion β | p x.1 x.2}) (ih : ∀(a:α) (b:β), p a b) : p a b := have ∀x : completion α × completion β, p x.1 x.2, from is_closed_property dense₂ hp $ assume ⟨a, b⟩, ih a b, this (a, b) @[elab_as_eliminator] lemma induction_on₃ {p : completion α → completion β → completion γ → Prop} (a : completion α) (b : completion β) (c : completion γ) (hp : is_closed {x : completion α × completion β × completion γ | p x.1 x.2.1 x.2.2}) (ih : ∀(a:α) (b:β) (c:γ), p a b c) : p a b c := have ∀x : completion α × completion β × completion γ, p x.1 x.2.1 x.2.2, from is_closed_property dense₃ hp $ assume ⟨a, b, c⟩, ih a b c, this (a, b, c) @[elab_as_eliminator] lemma induction_on₄ {δ : Type*} [uniform_space δ] {p : completion α → completion β → completion γ → completion δ → Prop} (a : completion α) (b : completion β) (c : completion γ) (d : completion δ) (hp : is_closed {x : (completion α × completion β) × (completion γ × completion δ) | p x.1.1 x.1.2 x.2.1 x.2.2}) (ih : ∀(a:α) (b:β) (c:γ) (d : δ), p ↑a ↑b ↑c ↑d) : p a b c d := let ab := λp:α × β, ((p.1 : completion α), (p.2 : completion β)), cd := λp:γ × δ, ((p.1 : completion γ), (p.2 : completion δ)) in have dense₄ : closure (range (λx:(α × β) × (γ × δ), (ab x.1, cd x.2))) = univ, begin rw [← set.prod_range_range_eq, @closure_prod_eq _ _ _ _ (range ab) (range cd), ← univ_prod_univ], congr, exact dense₂, exact dense₂ end, have ∀x:(completion α × completion β) × (completion γ × completion δ), p x.1.1 x.1.2 x.2.1 x.2.2, from is_closed_property dense₄ hp (assume p:(α×β)×(γ×δ), ih p.1.1 p.1.2 p.2.1 p.2.2), this ((a, b), (c, d)) lemma ext [t2_space β] {f g : completion α → β} (hf : continuous f) (hg : continuous g) (h : ∀a:α, f a = g a) : f = g := funext $ assume a, completion.induction_on a (is_closed_eq hf hg) h section extension variables {f : α → β} /-- "Extension" to the completion. It is defined for any map `f` but returns an arbitrary constant value if `f` is not uniformly continuous -/ protected def extension (f : α → β) : completion α → β := if uniform_continuous f then dense_inducing_coe.extend f else λ x, f (classical.inhabited_of_nonempty $ (nonempty_completion_iff α).1 ⟨x⟩).default variables [separated β] @[simp] lemma extension_coe (hf : uniform_continuous f) (a : α) : (completion.extension f) a = f a := begin rw [completion.extension, if_pos hf], exact dense_inducing_coe.extend_eq_of_cont hf.continuous a end variables [complete_space β] lemma uniform_continuous_extension : uniform_continuous (completion.extension f) := begin by_cases hf : uniform_continuous f, { rw [completion.extension, if_pos hf], exact uniform_continuous_uniformly_extend (uniform_inducing_coe α) ((dense_range_iff_closure_eq _).2 dense) hf }, { rw [completion.extension, if_neg hf], exact uniform_continuous_of_const (assume a b, by congr) } end lemma continuous_extension : continuous (completion.extension f) := uniform_continuous_extension.continuous lemma extension_unique (hf : uniform_continuous f) {g : completion α → β} (hg : uniform_continuous g) (h : ∀ a : α, f a = g (a : completion α)) : completion.extension f = g := begin apply completion.ext uniform_continuous_extension.continuous hg.continuous, simpa only [extension_coe hf] using h end @[simp] lemma extension_comp_coe {f : completion α → β} (hf : uniform_continuous f) : completion.extension (f ∘ coe) = f := funext $ λ x, completion.induction_on x (is_closed_eq continuous_extension hf.continuous) (λ y, completion.extension_coe (hf.comp $ uniform_continuous_coe α) y) end extension section map variables {f : α → β} /-- Completion functor acting on morphisms -/ protected def map (f : α → β) : completion α → completion β := completion.extension (coe ∘ f) lemma uniform_continuous_map : uniform_continuous (completion.map f) := uniform_continuous_extension lemma continuous_map : continuous (completion.map f) := uniform_continuous_extension.continuous @[simp] lemma map_coe (hf : uniform_continuous f) (a : α) : (completion.map f) a = f a := by rw [completion.map, extension_coe]; from (uniform_continuous_coe β).comp hf lemma map_unique {f : α → β} {g : completion α → completion β} (hg : uniform_continuous g) (h : ∀a:α, ↑(f a) = g a) : completion.map f = g := completion.ext continuous_map hg.continuous $ begin intro a, simp only [completion.map, (∘), h], rw [extension_coe (hg.comp (uniform_continuous_coe α))] end @[simp] lemma map_id : completion.map (@id α) = id := map_unique uniform_continuous_id (assume a, rfl) lemma extension_map [complete_space γ] [separated γ] {f : β → γ} {g : α → β} (hf : uniform_continuous f) (hg : uniform_continuous g) : completion.extension f ∘ completion.map g = completion.extension (f ∘ g) := completion.ext (continuous_extension.comp continuous_map) continuous_extension $ by intro a; simp only [hg, hf, hf.comp hg, (∘), map_coe, extension_coe] lemma map_comp {g : β → γ} {f : α → β} (hg : uniform_continuous g) (hf : uniform_continuous f) : completion.map g ∘ completion.map f = completion.map (g ∘ f) := extension_map ((uniform_continuous_coe _).comp hg) hf end map /- In this section we construct isomorphisms between the completion of a uniform space and the completion of its separation quotient -/ section separation_quotient_completion def completion_separation_quotient_equiv (α : Type u) [uniform_space α] : completion (separation_quotient α) ≃ completion α := begin refine ⟨completion.extension (separation_quotient.lift (coe : α → completion α)), completion.map quotient.mk, _, _⟩, { assume a, refine completion.induction_on a (is_closed_eq (continuous_map.comp continuous_extension) continuous_id) _, rintros ⟨a⟩, show completion.map quotient.mk (completion.extension (separation_quotient.lift coe) ↑⟦a⟧) = ↑⟦a⟧, rw [extension_coe (separation_quotient.uniform_continuous_lift _), separation_quotient.lift_mk (uniform_continuous_coe α), completion.map_coe uniform_continuous_quotient_mk] ; apply_instance }, { assume a, refine completion.induction_on a (is_closed_eq (continuous_extension.comp continuous_map) continuous_id) _, assume a, rw [map_coe uniform_continuous_quotient_mk, extension_coe (separation_quotient.uniform_continuous_lift _), separation_quotient.lift_mk (uniform_continuous_coe α) _] ; apply_instance } end lemma uniform_continuous_completion_separation_quotient_equiv : uniform_continuous ⇑(completion_separation_quotient_equiv α) := uniform_continuous_extension lemma uniform_continuous_completion_separation_quotient_equiv_symm : uniform_continuous ⇑(completion_separation_quotient_equiv α).symm := uniform_continuous_map end separation_quotient_completion section prod protected def prod {α β} [uniform_space α] [uniform_space β] : completion α × completion β → completion (α × β) := dense_inducing.extend (dense_inducing_coe.prod dense_inducing_coe) coe lemma uniform_continuous_prod : uniform_continuous (@completion.prod α β _ _) := uniform_continuous_uniformly_extend ((uniform_inducing_coe α).prod $ uniform_inducing_coe β) (eq_univ_iff_forall.1 dense₂) (uniform_continuous_coe _) @[move_cast] lemma prod_coe_coe (a : α) (b : β) : coe (a, b) = completion.prod ((a : completion α), (b : completion β)) := (dense_inducing.extend_eq_of_cont (dense_inducing_coe.prod dense_inducing_coe) (continuous_coe $ α × β) (a, b)).symm end prod section extension₂ variables (f : α → β → γ) open function protected def extension₂ (f : α → β → γ) : completion α → completion β → γ := curry $ completion.extension (uncurry' f) ∘ completion.prod variables [separated γ] {f} @[simp] lemma extension₂_coe_coe (hf : uniform_continuous $ uncurry' f) (a : α) (b : β) : completion.extension₂ f a b = f a b := by simpa [completion.extension₂, curry, (prod_coe_coe _ _).symm, extension_coe hf] variables [complete_space γ] (f) lemma uniform_continuous_extension₂ : uniform_continuous₂ (completion.extension₂ f) := begin rw [uniform_continuous₂_def, completion.extension₂, uncurry'_curry], exact uniform_continuous_extension.comp uniform_continuous_prod, end end extension₂ section map₂ open function protected def map₂ (f : α → β → γ) : completion α → completion β → completion γ := completion.extension₂ (coe ∘ f) lemma uniform_continuous_map₂ (f : α → β → γ) : uniform_continuous (uncurry' $ completion.map₂ f) := uniform_continuous_extension₂ _ lemma continuous_map₂ {δ} [topological_space δ] {f : α → β → γ} {a : δ → completion α} {b : δ → completion β} (ha : continuous a) (hb : continuous b) : continuous (λd:δ, completion.map₂ f (a d) (b d)) := ((uniform_continuous_map₂ f).continuous.comp (continuous.prod_mk ha hb) : _) lemma map₂_coe_coe (a : α) (b : β) (f : α → β → γ) (hf : uniform_continuous $ uncurry' f) : completion.map₂ f (a : completion α) (b : completion β) = f a b := completion.extension₂_coe_coe ((uniform_continuous_coe γ).comp hf) a b end map₂ end completion end uniform_space
f23ceed13a971fc1ceb15ae6eefa510679439bf4
bb31430994044506fa42fd667e2d556327e18dfe
/src/topology/uniform_space/compact.lean
68806ee7d7932f06c3e19c04aa157318e6853623
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
12,864
lean
/- Copyright (c) 2020 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Yury Kudryashov -/ import topology.uniform_space.uniform_convergence import topology.uniform_space.equicontinuity import topology.separation /-! # Compact separated uniform spaces ## Main statements * `compact_space_uniformity`: On a compact uniform space, the topology determines the uniform structure, entourages are exactly the neighborhoods of the diagonal. * `uniform_space_of_compact_t2`: every compact T2 topological structure is induced by a uniform structure. This uniform structure is described in the previous item. * **Heine-Cantor** theorem: continuous functions on compact uniform spaces with values in uniform spaces are automatically uniformly continuous. There are several variations, the main one is `compact_space.uniform_continuous_of_continuous`. ## Implementation notes The construction `uniform_space_of_compact_t2` is not declared as an instance, as it would badly loop. ## tags uniform space, uniform continuity, compact space -/ open_locale classical uniformity topological_space filter open filter uniform_space set variables {α β γ : Type*} [uniform_space α] [uniform_space β] /-! ### Uniformity on compact spaces -/ /-- On a compact uniform space, the topology determines the uniform structure, entourages are exactly the neighborhoods of the diagonal. -/ lemma nhds_set_diagonal_eq_uniformity [compact_space α] : 𝓝ˢ (diagonal α) = 𝓤 α := begin refine nhds_set_diagonal_le_uniformity.antisymm _, have : (𝓤 (α × α)).has_basis (λ U, U ∈ 𝓤 α) (λ U, (λ p : (α × α) × α × α, ((p.1.1, p.2.1), p.1.2, p.2.2)) ⁻¹' U ×ˢ U), { rw [uniformity_prod_eq_comap_prod], exact (𝓤 α).basis_sets.prod_self.comap _ }, refine (is_compact_diagonal.nhds_set_basis_uniformity this).ge_iff.2 (λ U hU, _), exact mem_of_superset hU (λ ⟨x, y⟩ hxy, mem_Union₂.2 ⟨(x, x), rfl, refl_mem_uniformity hU, hxy⟩) end /-- On a compact uniform space, the topology determines the uniform structure, entourages are exactly the neighborhoods of the diagonal. -/ lemma compact_space_uniformity [compact_space α] : 𝓤 α = ⨆ x, 𝓝 (x, x) := nhds_set_diagonal_eq_uniformity.symm.trans (nhds_set_diagonal _) lemma unique_uniformity_of_compact [t : topological_space γ] [compact_space γ] {u u' : uniform_space γ} (h : u.to_topological_space = t) (h' : u'.to_topological_space = t) : u = u' := begin apply uniform_space_eq, change uniformity _ = uniformity _, haveI : @compact_space γ u.to_topological_space, { rwa h }, haveI : @compact_space γ u'.to_topological_space, { rwa h' }, rw [compact_space_uniformity, compact_space_uniformity, h, h'] end /-- The unique uniform structure inducing a given compact topological structure. -/ def uniform_space_of_compact_t2 [topological_space γ] [compact_space γ] [t2_space γ] : uniform_space γ := { uniformity := ⨆ x, 𝓝 (x, x), refl := begin simp_rw [filter.principal_le_iff, mem_supr], rintros V V_in ⟨x, _⟩ ⟨⟩, exact mem_of_mem_nhds (V_in x), end, symm := begin refine le_of_eq _, rw filter.map_supr, congr' with x : 1, erw [nhds_prod_eq, ← prod_comm], end, comp := begin /- This is the difficult part of the proof. We need to prove that, for each neighborhood W of the diagonal Δ, W ○ W is still a neighborhood of the diagonal. -/ set 𝓝Δ := ⨆ x : γ, 𝓝 (x, x), -- The filter of neighborhoods of Δ set F := 𝓝Δ.lift' (λ (s : set (γ × γ)), s ○ s), -- Compositions of neighborhoods of Δ -- If this weren't true, then there would be V ∈ 𝓝Δ such that F ⊓ 𝓟 Vᶜ ≠ ⊥ rw le_iff_forall_inf_principal_compl, intros V V_in, by_contra H, haveI : ne_bot (F ⊓ 𝓟 Vᶜ) := ⟨H⟩, -- Hence compactness would give us a cluster point (x, y) for F ⊓ 𝓟 Vᶜ obtain ⟨⟨x, y⟩, hxy⟩ : ∃ (p : γ × γ), cluster_pt p (F ⊓ 𝓟 Vᶜ) := cluster_point_of_compact _, -- In particular (x, y) is a cluster point of 𝓟 Vᶜ, hence is not in the interior of V, -- and a fortiori not in Δ, so x ≠ y have clV : cluster_pt (x, y) (𝓟 $ Vᶜ) := hxy.of_inf_right, have : (x, y) ∉ interior V, { have : (x, y) ∈ closure (Vᶜ), by rwa mem_closure_iff_cluster_pt, rwa closure_compl at this }, have diag_subset : diagonal γ ⊆ interior V, { rw subset_interior_iff_nhds, rintros ⟨x, x⟩ ⟨⟩, exact (mem_supr.mp V_in : _) x }, have x_ne_y : x ≠ y, { intro h, apply this, apply diag_subset, simp [h] }, -- Since γ is compact and Hausdorff, it is normal, hence T₃. haveI : normal_space γ := normal_of_compact_t2, -- So there are closed neighboords V₁ and V₂ of x and y contained in disjoint open neighborhoods -- U₁ and U₂. obtain ⟨U₁, U₁_in, V₁, V₁_in, U₂, U₂_in₂, V₂, V₂_in, V₁_cl, V₂_cl, U₁_op, U₂_op, VU₁, VU₂, hU₁₂⟩ := disjoint_nested_nhds x_ne_y, -- We set U₃ := (V₁ ∪ V₂)ᶜ so that W := U₁ ×ˢ U₁ ∪ U₂ ×ˢ U₂ ∪ U₃ ×ˢ U₃ is an open -- neighborhood of Δ. let U₃ := (V₁ ∪ V₂)ᶜ, have U₃_op : is_open U₃ := is_open_compl_iff.mpr (is_closed.union V₁_cl V₂_cl), let W := U₁ ×ˢ U₁ ∪ U₂ ×ˢ U₂ ∪ U₃ ×ˢ U₃, have W_in : W ∈ 𝓝Δ, { rw mem_supr, intros x, apply is_open.mem_nhds (is_open.union (is_open.union _ _) _), { by_cases hx : x ∈ V₁ ∪ V₂, { left, cases hx with hx hx ; [left, right] ; split ; tauto }, { right, rw mem_prod, tauto }, }, all_goals { simp only [is_open.prod, *] } }, -- So W ○ W ∈ F by definition of F have : W ○ W ∈ F, by simpa only using mem_lift' W_in, -- And V₁ ×ˢ V₂ ∈ 𝓝 (x, y) have hV₁₂ : V₁ ×ˢ V₂ ∈ 𝓝 (x, y) := prod_mem_nhds V₁_in V₂_in, -- But (x, y) is also a cluster point of F so (V₁ ×ˢ V₂) ∩ (W ○ W) ≠ ∅ -- However the construction of W implies (V₁ ×ˢ V₂) ∩ (W ○ W) = ∅. -- Indeed assume for contradiction there is some (u, v) in the intersection. obtain ⟨⟨u, v⟩, ⟨u_in, v_in⟩, w, huw, hwv⟩ := cluster_pt_iff.mp (hxy.of_inf_left) hV₁₂ this, -- So u ∈ V₁, v ∈ V₂, and there exists some w such that (u, w) ∈ W and (w ,v) ∈ W. -- Because u is in V₁ which is disjoint from U₂ and U₃, (u, w) ∈ W forces (u, w) ∈ U₁ ×ˢ U₁. have uw_in : (u, w) ∈ U₁ ×ˢ U₁ := (huw.resolve_right $ λ h, (h.1 $ or.inl u_in)).resolve_right (λ h, hU₁₂.le_bot ⟨VU₁ u_in, h.1⟩), -- Similarly, because v ∈ V₂, (w ,v) ∈ W forces (w, v) ∈ U₂ ×ˢ U₂. have wv_in : (w, v) ∈ U₂ ×ˢ U₂ := (hwv.resolve_right $ λ h, (h.2 $ or.inr v_in)).resolve_left (λ h, hU₁₂.le_bot ⟨h.2, VU₂ v_in⟩), -- Hence w ∈ U₁ ∩ U₂ which is empty. -- So we have a contradiction exact hU₁₂.le_bot ⟨uw_in.2, wv_in.1⟩, end, is_open_uniformity := begin -- Here we need to prove the topology induced by the constructed uniformity is the -- topology we started with. suffices : ∀ x : γ, filter.comap (prod.mk x) (⨆ y, 𝓝 (y ,y)) = 𝓝 x, { intros s, change is_open s ↔ _, simp_rw [is_open_iff_mem_nhds, nhds_eq_comap_uniformity_aux, this] }, intros x, simp_rw [comap_supr, nhds_prod_eq, comap_prod, show prod.fst ∘ prod.mk x = λ y : γ, x, by ext ; simp, show prod.snd ∘ (prod.mk x) = (id : γ → γ), by ext ; refl, comap_id], rw [supr_split_single _ x, comap_const_of_mem (λ V, mem_of_mem_nhds)], suffices : ∀ y ≠ x, comap (λ (y : γ), x) (𝓝 y) ⊓ 𝓝 y ≤ 𝓝 x, by simpa, intros y hxy, simp [comap_const_of_not_mem (compl_singleton_mem_nhds hxy) (by simp)], end } /-! ### Heine-Cantor theorem -/ /-- Heine-Cantor: a continuous function on a compact uniform space is uniformly continuous. -/ lemma compact_space.uniform_continuous_of_continuous [compact_space α] {f : α → β} (h : continuous f) : uniform_continuous f := calc map (prod.map f f) (𝓤 α) = map (prod.map f f) (⨆ x, 𝓝 (x, x)) : by rw compact_space_uniformity ... = ⨆ x, map (prod.map f f) (𝓝 (x, x)) : by rw filter.map_supr ... ≤ ⨆ x, 𝓝 (f x, f x) : supr_mono (λ x, (h.prod_map h).continuous_at) ... ≤ ⨆ y, 𝓝 (y, y) : supr_comp_le (λ y, 𝓝 (y, y)) f ... ≤ 𝓤 β : supr_nhds_le_uniformity /-- Heine-Cantor: a continuous function on a compact set of a uniform space is uniformly continuous. -/ lemma is_compact.uniform_continuous_on_of_continuous {s : set α} {f : α → β} (hs : is_compact s) (hf : continuous_on f s) : uniform_continuous_on f s := begin rw uniform_continuous_on_iff_restrict, rw is_compact_iff_compact_space at hs, rw continuous_on_iff_continuous_restrict at hf, resetI, exact compact_space.uniform_continuous_of_continuous hf, end /-- If `s` is compact and `f` is continuous at all points of `s`, then `f` is "uniformly continuous at the set `s`", i.e. `f x` is close to `f y` whenever `x ∈ s` and `y` is close to `x` (even if `y` is not itself in `s`, so this is a stronger assertion than `uniform_continuous_on s`). -/ lemma is_compact.uniform_continuous_at_of_continuous_at {r : set (β × β)} {s : set α} (hs : is_compact s) (f : α → β) (hf : ∀ a ∈ s, continuous_at f a) (hr : r ∈ 𝓤 β) : {x : α × α | x.1 ∈ s → (f x.1, f x.2) ∈ r} ∈ 𝓤 α := begin obtain ⟨t, ht, htsymm, htr⟩ := comp_symm_mem_uniformity_sets hr, choose U hU T hT hb using λ a ha, exists_mem_nhds_ball_subset_of_mem_nhds ((hf a ha).preimage_mem_nhds $ mem_nhds_left _ ht), obtain ⟨fs, hsU⟩ := hs.elim_nhds_subcover' U hU, apply mem_of_superset ((bInter_finset_mem fs).2 $ λ a _, hT a a.2), rintro ⟨a₁, a₂⟩ h h₁, obtain ⟨a, ha, haU⟩ := set.mem_Union₂.1 (hsU h₁), apply htr, refine ⟨f a, htsymm.mk_mem_comm.1 (hb _ _ _ haU _), hb _ _ _ haU _⟩, exacts [mem_ball_self _ (hT a a.2), mem_Inter₂.1 h a ha], end lemma continuous.uniform_continuous_of_zero_at_infty {f : α → β} [has_zero β] (h_cont : continuous f) (h_zero : tendsto f (cocompact α) (𝓝 0)) : uniform_continuous f := uniform_continuous_def.2 $ λ r hr, begin obtain ⟨t, ht, htsymm, htr⟩ := comp_symm_mem_uniformity_sets hr, obtain ⟨s, hs, hst⟩ := mem_cocompact.1 (h_zero $ mem_nhds_left 0 ht), apply mem_of_superset (symmetrize_mem_uniformity $ hs.uniform_continuous_at_of_continuous_at f (λ _ _, h_cont.continuous_at) $ symmetrize_mem_uniformity hr), rintro ⟨b₁, b₂⟩ h, by_cases h₁ : b₁ ∈ s, { exact (h.1 h₁).1 }, by_cases h₂ : b₂ ∈ s, { exact (h.2 h₂).2 }, apply htr, exact ⟨0, htsymm.mk_mem_comm.1 (hst h₁), hst h₂⟩, end /-- A family of functions `α → β → γ` tends uniformly to its value at `x` if `α` is locally compact, `β` is compact and `f` is continuous on `U × (univ : set β)` for some neighborhood `U` of `x`. -/ lemma continuous_on.tendsto_uniformly [locally_compact_space α] [compact_space β] [uniform_space γ] {f : α → β → γ} {x : α} {U : set α} (hxU : U ∈ 𝓝 x) (h : continuous_on ↿f (U ×ˢ univ)) : tendsto_uniformly f (f x) (𝓝 x) := begin rcases locally_compact_space.local_compact_nhds _ _ hxU with ⟨K, hxK, hKU, hK⟩, have : uniform_continuous_on ↿f (K ×ˢ univ), from is_compact.uniform_continuous_on_of_continuous (hK.prod is_compact_univ) (h.mono $ prod_mono hKU subset.rfl), exact this.tendsto_uniformly hxK end /-- A continuous family of functions `α → β → γ` tends uniformly to its value at `x` if `α` is locally compact and `β` is compact. -/ lemma continuous.tendsto_uniformly [locally_compact_space α] [compact_space β] [uniform_space γ] (f : α → β → γ) (h : continuous ↿f) (x : α) : tendsto_uniformly f (f x) (𝓝 x) := h.continuous_on.tendsto_uniformly univ_mem section uniform_convergence /-- An equicontinuous family of functions defined on a compact uniform space is automatically uniformly equicontinuous. -/ lemma compact_space.uniform_equicontinuous_of_equicontinuous {ι : Type*} {F : ι → β → α} [compact_space β] (h : equicontinuous F) : uniform_equicontinuous F := begin rw equicontinuous_iff_continuous at h, rw uniform_equicontinuous_iff_uniform_continuous, exact compact_space.uniform_continuous_of_continuous h end end uniform_convergence
d336c14b308f2834feef12cb7d42733b649c6118
130c49f47783503e462c16b2eff31933442be6ff
/src/Lean/Server/Rpc/RequestHandling.lean
0a3c3b214a90c47f07c31cf42339bbc3a320310a
[ "Apache-2.0" ]
permissive
Hazel-Brown/lean4
8aa5860e282435ffc30dcdfccd34006c59d1d39c
79e6732fc6bbf5af831b76f310f9c488d44e7a16
refs/heads/master
1,689,218,208,951
1,629,736,869,000
1,629,736,896,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,566
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.Data.Lsp.Extra import Lean.Server.Requests import Lean.Server.Rpc.Basic namespace Lean.Server private structure RpcProcedure where wrapper : (sessionId : UInt64) → Json → RequestM (RequestTask Json) builtin_initialize rpcProcedures : IO.Ref (Std.PersistentHashMap Name RpcProcedure) ← IO.mkRef {} private def handleRpcCall (p : Lsp.RpcCallParams) : RequestM (RequestTask Json) := do let rc ← read let some proc ← (← rpcProcedures.get).find? p.method | throwThe RequestError { code := JsonRpc.ErrorCode.methodNotFound message := s!"No RPC method '{p.method}' bound" } proc.wrapper p.sessionId p.params builtin_initialize registerLspRequestHandler "$/lean/rpc/call" Lsp.RpcCallParams Json handleRpcCall def registerRpcCallHandler (method : Name) paramType respType {paramLspType} [RpcEncoding paramType paramLspType] [FromJson paramLspType] {respLspType} [RpcEncoding respType respLspType] [ToJson respLspType] (handler : paramType → RequestM (RequestTask respType)) : IO Unit := do if !(← IO.initializing) then throw <| IO.userError s!"Failed to register RPC call handler for '{method}': only possible during initialization" if (←rpcProcedures.get).contains method then throw <| IO.userError s!"Failed to register RPC call handler for '{method}': already registered" let wrapper seshId j := do let rc ← read let t ← RequestM.asTask do let paramsLsp ← parseRequestParams paramLspType j if seshId ≠ rc.rpcSesh.sessionId then throwThe RequestError { code := JsonRpc.ErrorCode.rpcNeedsReconnect message := s!"Outdated RPC session" } match (← @rpcDecode paramType paramLspType _ RequestM _ _ paramsLsp) with | Except.ok v => return v | Except.error e => throwThe RequestError { code := JsonRpc.ErrorCode.invalidParams message := s!"{e} in RPC call '{method}({j})'" } let t ← RequestM.bindTask t fun | Except.error e => throw e | Except.ok ps => handler ps RequestM.mapTask t fun | Except.error e => throw e | Except.ok ret => do let retLsp ← @rpcEncode respType respLspType _ RequestM _ _ ret return toJson retLsp rpcProcedures.modify fun ps => ps.insert method ⟨wrapper⟩ end Lean.Server
d653816abba95c19245283e9ba7e5ffcbb86c05e
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/calculus/extend_deriv.lean
b2c01107784caaad2733e697d3e767c3b8740064
[ "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
11,711
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.calculus.mean_value /-! # Extending differentiability to the boundary > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We investigate how differentiable functions inside a set extend to differentiable functions on the boundary. For this, it suffices that the function and its derivative admit limits there. A general version of this statement is given in `has_fderiv_at_boundary_of_tendsto_fderiv`. One-dimensional versions, in which one wants to obtain differentiability at the left endpoint or the right endpoint of an interval, are given in `has_deriv_at_interval_left_endpoint_of_tendsto_deriv` and `has_deriv_at_interval_right_endpoint_of_tendsto_deriv`. These versions are formulated in terms of the one-dimensional derivative `deriv ℝ f`. -/ variables {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] {F : Type*} [normed_add_comm_group F] [normed_space ℝ F] open filter set metric continuous_linear_map open_locale topology local attribute [mono] prod_mono /-- If a function `f` is differentiable in a convex open set and continuous on its closure, and its derivative converges to a limit `f'` at a point on the boundary, then `f` is differentiable there with derivative `f'`. -/ theorem has_fderiv_at_boundary_of_tendsto_fderiv {f : E → F} {s : set E} {x : E} {f' : E →L[ℝ] F} (f_diff : differentiable_on ℝ f s) (s_conv : convex ℝ s) (s_open : is_open s) (f_cont : ∀y ∈ closure s, continuous_within_at f s y) (h : tendsto (λy, fderiv ℝ f y) (𝓝[s] x) (𝓝 f')) : has_fderiv_within_at f f' (closure s) x := begin classical, -- one can assume without loss of generality that `x` belongs to the closure of `s`, as the -- statement is empty otherwise by_cases hx : x ∉ closure s, { rw ← closure_closure at hx, exact has_fderiv_within_at_of_not_mem_closure hx }, push_neg at hx, rw [has_fderiv_within_at, has_fderiv_at_filter, asymptotics.is_o_iff], /- One needs to show that `‖f y - f x - f' (y - x)‖ ≤ ε ‖y - x‖` for `y` close to `x` in `closure s`, where `ε` is an arbitrary positive constant. By continuity of the functions, it suffices to prove this for nearby points inside `s`. In a neighborhood of `x`, the derivative of `f` is arbitrarily close to `f'` by assumption. The mean value inequality completes the proof. -/ assume ε ε_pos, obtain ⟨δ, δ_pos, hδ⟩ : ∃ δ > 0, ∀ y ∈ s, dist y x < δ → ‖fderiv ℝ f y - f'‖ < ε, by simpa [dist_zero_right] using tendsto_nhds_within_nhds.1 h ε ε_pos, set B := ball x δ, suffices : ∀ y ∈ B ∩ (closure s), ‖f y - f x - (f' y - f' x)‖ ≤ ε * ‖y - x‖, from mem_nhds_within_iff.2 ⟨δ, δ_pos, λy hy, by simpa using this y hy⟩, suffices : ∀ p : E × E, p ∈ closure ((B ∩ s) ×ˢ (B ∩ s)) → ‖f p.2 - f p.1 - (f' p.2 - f' p.1)‖ ≤ ε * ‖p.2 - p.1‖, { rw closure_prod_eq at this, intros y y_in, apply this ⟨x, y⟩, have : B ∩ closure s ⊆ closure (B ∩ s), from is_open_ball.inter_closure, exact ⟨this ⟨mem_ball_self δ_pos, hx⟩, this y_in⟩ }, have key : ∀ p : E × E, p ∈ (B ∩ s) ×ˢ (B ∩ s) → ‖f p.2 - f p.1 - (f' p.2 - f' p.1)‖ ≤ ε * ‖p.2 - p.1‖, { rintros ⟨u, v⟩ ⟨u_in, v_in⟩, have conv : convex ℝ (B ∩ s) := (convex_ball _ _).inter s_conv, have diff : differentiable_on ℝ f (B ∩ s) := f_diff.mono (inter_subset_right _ _), have bound : ∀ z ∈ (B ∩ s), ‖fderiv_within ℝ f (B ∩ s) z - f'‖ ≤ ε, { intros z z_in, convert le_of_lt (hδ _ z_in.2 z_in.1), have op : is_open (B ∩ s) := is_open_ball.inter s_open, rw differentiable_at.fderiv_within _ (op.unique_diff_on z z_in), exact (diff z z_in).differentiable_at (is_open.mem_nhds op z_in) }, simpa using conv.norm_image_sub_le_of_norm_fderiv_within_le' diff bound u_in v_in }, rintros ⟨u, v⟩ uv_in, refine continuous_within_at.closure_le uv_in _ _ key, have f_cont' : ∀y ∈ closure s, continuous_within_at (f - f') s y, { intros y y_in, exact tendsto.sub (f_cont y y_in) (f'.cont.continuous_within_at) }, all_goals { -- common start for both continuity proofs have : (B ∩ s) ×ˢ (B ∩ s) ⊆ s ×ˢ s, by mono ; exact inter_subset_right _ _, obtain ⟨u_in, v_in⟩ : u ∈ closure s ∧ v ∈ closure s, by simpa [closure_prod_eq] using closure_mono this uv_in, apply continuous_within_at.mono _ this, simp only [continuous_within_at] }, rw nhds_within_prod_eq, { have : ∀ u v, f v - f u - (f' v - f' u) = f v - f' v - (f u - f' u) := by { intros, abel }, simp only [this], exact tendsto.comp continuous_norm.continuous_at ((tendsto.comp (f_cont' v v_in) tendsto_snd).sub $ tendsto.comp (f_cont' u u_in) tendsto_fst) }, { apply tendsto_nhds_within_of_tendsto_nhds, rw nhds_prod_eq, exact tendsto_const_nhds.mul (tendsto.comp continuous_norm.continuous_at $ tendsto_snd.sub tendsto_fst) }, end /-- If a function is differentiable on the right of a point `a : ℝ`, continuous at `a`, and its derivative also converges at `a`, then `f` is differentiable on the right at `a`. -/ lemma has_deriv_at_interval_left_endpoint_of_tendsto_deriv {s : set ℝ} {e : E} {a : ℝ} {f : ℝ → E} (f_diff : differentiable_on ℝ f s) (f_lim : continuous_within_at f s a) (hs : s ∈ 𝓝[>] a) (f_lim' : tendsto (λx, deriv f x) (𝓝[>] a) (𝓝 e)) : has_deriv_within_at f e (Ici a) a := begin /- This is a specialization of `has_fderiv_at_boundary_of_tendsto_fderiv`. To be in the setting of this theorem, we need to work on an open interval with closure contained in `s ∪ {a}`, that we call `t = (a, b)`. Then, we check all the assumptions of this theorem and we apply it. -/ obtain ⟨b, ab : a < b, sab : Ioc a b ⊆ s⟩ := mem_nhds_within_Ioi_iff_exists_Ioc_subset.1 hs, let t := Ioo a b, have ts : t ⊆ s := subset.trans Ioo_subset_Ioc_self sab, have t_diff : differentiable_on ℝ f t := f_diff.mono ts, have t_conv : convex ℝ t := convex_Ioo a b, have t_open : is_open t := is_open_Ioo, have t_closure : closure t = Icc a b := closure_Ioo ab.ne, have t_cont : ∀y ∈ closure t, continuous_within_at f t y, { rw t_closure, assume y hy, by_cases h : y = a, { rw h, exact f_lim.mono ts }, { have : y ∈ s := sab ⟨lt_of_le_of_ne hy.1 (ne.symm h), hy.2⟩, exact (f_diff.continuous_on y this).mono ts } }, have t_diff' : tendsto (λx, fderiv ℝ f x) (𝓝[t] a) (𝓝 (smul_right 1 e)), { simp only [deriv_fderiv.symm], exact tendsto.comp (is_bounded_bilinear_map_smul_right : is_bounded_bilinear_map ℝ _) .continuous_right.continuous_at (tendsto_nhds_within_mono_left Ioo_subset_Ioi_self f_lim'), }, -- now we can apply `has_fderiv_at_boundary_of_differentiable` have : has_deriv_within_at f e (Icc a b) a, { rw [has_deriv_within_at_iff_has_fderiv_within_at, ← t_closure], exact has_fderiv_at_boundary_of_tendsto_fderiv t_diff t_conv t_open t_cont t_diff' }, exact this.nhds_within (Icc_mem_nhds_within_Ici $ left_mem_Ico.2 ab) end /-- If a function is differentiable on the left of a point `a : ℝ`, continuous at `a`, and its derivative also converges at `a`, then `f` is differentiable on the left at `a`. -/ lemma has_deriv_at_interval_right_endpoint_of_tendsto_deriv {s : set ℝ} {e : E} {a : ℝ} {f : ℝ → E} (f_diff : differentiable_on ℝ f s) (f_lim : continuous_within_at f s a) (hs : s ∈ 𝓝[<] a) (f_lim' : tendsto (λx, deriv f x) (𝓝[<] a) (𝓝 e)) : has_deriv_within_at f e (Iic a) a := begin /- This is a specialization of `has_fderiv_at_boundary_of_differentiable`. To be in the setting of this theorem, we need to work on an open interval with closure contained in `s ∪ {a}`, that we call `t = (b, a)`. Then, we check all the assumptions of this theorem and we apply it. -/ obtain ⟨b, ba, sab⟩ : ∃ b ∈ Iio a, Ico b a ⊆ s := mem_nhds_within_Iio_iff_exists_Ico_subset.1 hs, let t := Ioo b a, have ts : t ⊆ s := subset.trans Ioo_subset_Ico_self sab, have t_diff : differentiable_on ℝ f t := f_diff.mono ts, have t_conv : convex ℝ t := convex_Ioo b a, have t_open : is_open t := is_open_Ioo, have t_closure : closure t = Icc b a := closure_Ioo (ne_of_lt ba), have t_cont : ∀y ∈ closure t, continuous_within_at f t y, { rw t_closure, assume y hy, by_cases h : y = a, { rw h, exact f_lim.mono ts }, { have : y ∈ s := sab ⟨hy.1, lt_of_le_of_ne hy.2 h⟩, exact (f_diff.continuous_on y this).mono ts } }, have t_diff' : tendsto (λx, fderiv ℝ f x) (𝓝[t] a) (𝓝 (smul_right 1 e)), { simp only [deriv_fderiv.symm], exact tendsto.comp (is_bounded_bilinear_map_smul_right : is_bounded_bilinear_map ℝ _) .continuous_right.continuous_at (tendsto_nhds_within_mono_left Ioo_subset_Iio_self f_lim'), }, -- now we can apply `has_fderiv_at_boundary_of_differentiable` have : has_deriv_within_at f e (Icc b a) a, { rw [has_deriv_within_at_iff_has_fderiv_within_at, ← t_closure], exact has_fderiv_at_boundary_of_tendsto_fderiv t_diff t_conv t_open t_cont t_diff' }, exact this.nhds_within (Icc_mem_nhds_within_Iic $ right_mem_Ioc.2 ba) end /-- If a real function `f` has a derivative `g` everywhere but at a point, and `f` and `g` are continuous at this point, then `g` is also the derivative of `f` at this point. -/ lemma has_deriv_at_of_has_deriv_at_of_ne {f g : ℝ → E} {x : ℝ} (f_diff : ∀ y ≠ x, has_deriv_at f (g y) y) (hf : continuous_at f x) (hg : continuous_at g x) : has_deriv_at f (g x) x := begin have A : has_deriv_within_at f (g x) (Ici x) x, { have diff : differentiable_on ℝ f (Ioi x) := λy hy, (f_diff y (ne_of_gt hy)).differentiable_at.differentiable_within_at, -- next line is the nontrivial bit of this proof, appealing to differentiability -- extension results. apply has_deriv_at_interval_left_endpoint_of_tendsto_deriv diff hf.continuous_within_at self_mem_nhds_within, have : tendsto g (𝓝[>] x) (𝓝 (g x)) := tendsto_inf_left hg, apply this.congr' _, apply mem_of_superset self_mem_nhds_within (λy hy, _), exact (f_diff y (ne_of_gt hy)).deriv.symm }, have B : has_deriv_within_at f (g x) (Iic x) x, { have diff : differentiable_on ℝ f (Iio x) := λy hy, (f_diff y (ne_of_lt hy)).differentiable_at.differentiable_within_at, -- next line is the nontrivial bit of this proof, appealing to differentiability -- extension results. apply has_deriv_at_interval_right_endpoint_of_tendsto_deriv diff hf.continuous_within_at self_mem_nhds_within, have : tendsto g (𝓝[<] x) (𝓝 (g x)) := tendsto_inf_left hg, apply this.congr' _, apply mem_of_superset self_mem_nhds_within (λy hy, _), exact (f_diff y (ne_of_lt hy)).deriv.symm }, simpa using B.union A end /-- If a real function `f` has a derivative `g` everywhere but at a point, and `f` and `g` are continuous at this point, then `g` is the derivative of `f` everywhere. -/ lemma has_deriv_at_of_has_deriv_at_of_ne' {f g : ℝ → E} {x : ℝ} (f_diff : ∀ y ≠ x, has_deriv_at f (g y) y) (hf : continuous_at f x) (hg : continuous_at g x) (y : ℝ) : has_deriv_at f (g y) y := begin rcases eq_or_ne y x with rfl|hne, { exact has_deriv_at_of_has_deriv_at_of_ne f_diff hf hg }, { exact f_diff y hne } end
ec8225c399ee32dc59065772cd4664b4f217a6e3
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/playground/pldi/array_map.lean
2cc438efe55ecb8f595f144f3e412c00d0aa5828
[ "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,066
lean
@[specialize] unsafe partial def umapAux {α β : Type} (f : α → β) : Nat → Array NonScalar → Array NonScalar | i, a => if h : i < a.size then let a := dbgTraceIfShared "array" a; let idx : Fin a.size := ⟨i, h⟩; let v : NonScalar := a.get idx; let a := a.set idx (arbitrary _); let newV := f (unsafeCast v); umapAux (i+1) (a.set idx (unsafeCast newV)) else a @[inline] unsafe partial def umap {α β : Type} (f : α → β) (as : Array α) : Array β := unsafeCast (umapAux f 0 (unsafeCast as)) @[implementedBy umap] def map {α β : Type} (f : α → β) (as : Array α) : Array β := as.foldl (fun bs a => bs.push (f a)) (Array.mkEmpty as.size) set_option compiler.extract_closed false -- set_option trace.compiler.ir.result true def tst1 : Array String := map (fun x => "val: " ++ toString x) #[1, 2, 3] #eval tst1 def tst2 : Array String := let xs := #[1, 2, 3]; map (fun x => "val1: " ++ toString x) xs ++ map (fun x => "val2: " ++ toString x) xs #eval tst2
b837c2542d657eb126b72c5769131852ef08d6a4
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/category_theory/elements.lean
7129cfdba7daa7c7bd83d72a6124ec18e8f48e1c
[ "Apache-2.0" ]
permissive
SAAluthwela/mathlib
62044349d72dd63983a8500214736aa7779634d3
83a4b8b990907291421de54a78988c024dc8a552
refs/heads/master
1,679,433,873,417
1,615,998,031,000
1,615,998,031,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,912
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.comma import category_theory.groupoid import category_theory.punit /-! # The category of elements This file defines the category of elements, also known as (a special case of) the Grothendieck construction. Given a functor `F : C ⥤ Type`, an object of `F.elements` is a pair `(X : C, x : F.obj X)`. A morphism `(X, x) ⟶ (Y, y)` is a morphism `f : X ⟶ Y` in `C`, so `F.map f` takes `x` to `y`. ## Implementation notes This construction is equivalent to a special case of a comma construction, so this is mostly just a more convenient API. We prove the equivalence in `category_theory.category_of_elements.comma_equivalence`. ## References * [Emily Riehl, *Category Theory in Context*, Section 2.4][riehl2017] * <https://en.wikipedia.org/wiki/Category_of_elements> * <https://ncatlab.org/nlab/show/category+of+elements> ## Tags category of elements, Grothendieck construction, comma category -/ namespace category_theory universes w v u variables {C : Type u} [category.{v} C] /-- The type of objects for the category of elements of a functor `F : C ⥤ Type` is a pair `(X : C, x : F.obj X)`. -/ @[nolint has_inhabited_instance] def functor.elements (F : C ⥤ Type w) := (Σ c : C, F.obj c) /-- The category structure on `F.elements`, for `F : C ⥤ Type`. A morphism `(X, x) ⟶ (Y, y)` is a morphism `f : X ⟶ Y` in `C`, so `F.map f` takes `x` to `y`. -/ instance category_of_elements (F : C ⥤ Type w) : category.{v} F.elements := { hom := λ p q, { f : p.1 ⟶ q.1 // (F.map f) p.2 = q.2 }, id := λ p, ⟨𝟙 p.1, by obviously⟩, comp := λ p q r f g, ⟨f.val ≫ g.val, by obviously⟩ } namespace category_of_elements @[ext] lemma ext (F : C ⥤ Type w) {x y : F.elements} (f g : x ⟶ y) (w : f.val = g.val) : f = g := subtype.ext_val w @[simp] lemma comp_val {F : C ⥤ Type w} {p q r : F.elements} {f : p ⟶ q} {g : q ⟶ r} : (f ≫ g).val = f.val ≫ g.val := rfl @[simp] lemma id_val {F : C ⥤ Type w} {p : F.elements} : (𝟙 p : p ⟶ p).val = 𝟙 p.1 := rfl end category_of_elements noncomputable instance groupoid_of_elements {G : Type u} [groupoid.{v} G] (F : G ⥤ Type w) : groupoid F.elements := { inv := λ p q f, ⟨inv f.val, calc F.map (inv f.val) q.2 = F.map (inv f.val) (F.map f.val p.2) : by rw f.2 ... = (F.map f.val ≫ F.map (inv f.val)) p.2 : by simp ... = p.2 : by {rw ←functor.map_comp, simp}⟩, } namespace category_of_elements variable (F : C ⥤ Type w) /-- The functor out of the category of elements which forgets the element. -/ @[simps] def π : F.elements ⥤ C := { obj := λ X, X.1, map := λ X Y f, f.val } /-- A natural transformation between functors induces a functor between the categories of elements. -/ @[simps] def map {F₁ F₂ : C ⥤ Type w} (α : F₁ ⟶ F₂) : F₁.elements ⥤ F₂.elements := { obj := λ t, ⟨t.1, α.app t.1 t.2⟩, map := λ t₁ t₂ k, ⟨k.1, by simpa [←k.2] using (functor_to_types.naturality _ _ α k.1 t₁.2).symm⟩ } @[simp] lemma map_π {F₁ F₂ : C ⥤ Type w} (α : F₁ ⟶ F₂) : map α ⋙ π F₂ = π F₁ := rfl /-- The forward direction of the equivalence `F.elements ≅ (*, F)`. -/ def to_comma : F.elements ⥤ comma (functor.from_punit punit) F := { obj := λ X, { left := punit.star, right := X.1, hom := λ _, X.2 }, map := λ X Y f, { right := f.val } } @[simp] lemma to_comma_obj (X) : (to_comma F).obj X = { left := punit.star, right := X.1, hom := λ _, X.2 } := rfl @[simp] lemma to_comma_map {X Y} (f : X ⟶ Y) : (to_comma F).map f = { right := f.val } := rfl /-- The reverse direction of the equivalence `F.elements ≅ (*, F)`. -/ def from_comma : comma (functor.from_punit punit) F ⥤ F.elements := { obj := λ X, ⟨X.right, X.hom (punit.star)⟩, map := λ X Y f, ⟨f.right, congr_fun f.w'.symm punit.star⟩ } @[simp] lemma from_comma_obj (X) : (from_comma F).obj X = ⟨X.right, X.hom (punit.star)⟩ := rfl @[simp] lemma from_comma_map {X Y} (f : X ⟶ Y) : (from_comma F).map f = ⟨f.right, congr_fun f.w'.symm punit.star⟩ := rfl /-- The equivalence between the category of elements `F.elements` and the comma category `(*, F)`. -/ def comma_equivalence : F.elements ≌ comma (functor.from_punit punit) F := equivalence.mk (to_comma F) (from_comma F) (nat_iso.of_components (λ X, eq_to_iso (by tidy)) (by tidy)) (nat_iso.of_components (λ X, { hom := { right := 𝟙 _ }, inv := { right := 𝟙 _ } }) (by tidy)) @[simp] lemma comma_equivalence_functor : (comma_equivalence F).functor = to_comma F := rfl @[simp] lemma comma_equivalence_inverse : (comma_equivalence F).inverse = from_comma F := rfl end category_of_elements end category_theory
8fc2ea78fa0fe9205d18e12e7250af87fdb7d13a
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/Lake/Config/TargetConfig.lean
b272f47209ac7628fbc496f4c8380fdb79942014
[ "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,407
lean
/- Copyright (c) 2022 Mac Malone. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mac Malone -/ import Lake.Build.Info import Lake.Build.Store namespace Lake /-- A custom target's declarative configuration. -/ structure TargetConfig (pkgName name : Name) : Type where /-- The target's build function. -/ build : (pkg : NPackage pkgName) → IndexBuildM (CustomData (pkgName, name)) /-- The target's resulting build job. -/ getJob : CustomData (pkgName, name) → BuildJob Unit deriving Inhabited /-- A smart constructor for target configurations that generate CLI targets. -/ @[inline] def mkTargetJobConfig (build : (pkg : NPackage pkgName) → IndexBuildM (BuildJob α)) [h : FamilyOut CustomData (pkgName, name) (BuildJob α)] : TargetConfig pkgName name where build := cast (by rw [← h.family_key_eq_type]) build getJob := fun data => discard <| ofFamily data /-- A dependently typed configuration based on its registered package and name. -/ structure TargetDecl where pkg : Name name : Name config : TargetConfig pkg name hydrate_opaque_type OpaqueTargetConfig TargetConfig pkgName name /-- Try to find a target configuration in the package with the given name . -/ def Package.findTargetConfig? (name : Name) (self : Package) : Option (TargetConfig self.name name) := self.opaqueTargetConfigs.find? name |>.map (·.get)
c3dc49c1c26d4d283dabe326027a09c7f3e0dd13
59b654f4ee2fef898a3487dc03554a569051b63a
/src/old/graph.lean
6b0577b790a056b991ef59a026fb0ca2407ed41f
[]
no_license
gunpinyo/twisted_cube_formalisation
180c9157478b66ec2b11ca47c8ff998a3e978a88
f78206ac495e84bd43a9b820fa10b6c94722e0ec
refs/heads/master
1,624,501,222,992
1,607,081,624,000
1,607,081,624,000
166,885,106
0
0
null
null
null
null
UTF-8
Lean
false
false
6,813
lean
import data.vector2 import utils import category structure graph : Type 1 := (nodes : Type) (edges : Type) (srctrg : bool → edges → nodes) -- `edge_ext` asserts that every graph we consider does not have multi-edge (edge_ext : ∀ e e' : edges, (∀ b, srctrg b e = srctrg b e') → e = e') namespace graph def source (G : graph) : G.edges → G.nodes := G.srctrg ff def target (G : graph) : G.edges → G.nodes := G.srctrg tt def eq {G G' : graph} (nodes_eq : G.nodes = G'.nodes) (edges_eq : G.edges = G'.edges) (srctrg_eq : G.srctrg == G'.srctrg) : G = G' := begin cases G with n e st, cases G' with n' e' st', cases nodes_eq, cases edges_eq, cases srctrg_eq, refl end @[class] def has_deceq_node (G : graph) : Type := decidable_eq G.nodes def to_rel (G : graph) : G.nodes → G.nodes → Prop := λ v v', ∃ e : G.edges, G.source e = v ∧ G.target e = v' @[class] def has_dec_rel (G : graph) : Type := decidable_rel G.to_rel -- TODO: define an instance of for `prism_graph` `cube_graph` `cube_graph_alt` -- in `generic_cube_graph.lean` end graph namespace graph_cat structure hom (G G' : graph) : Type := (nodes_map : G.nodes → G'.nodes) (edges_map : G.edges → G'.edges) (srctrg_map : ∀ (b : bool) (e : G.edges), nodes_map (G.srctrg b e) = G'.srctrg b (edges_map e)) def hom.eq {G G' : graph} {F F' : hom G G'} (nodes_map_eq : F.nodes_map = F'.nodes_map) (edges_map_eq : F.edges_map = F'.edges_map) : F = F' := begin cases F with nm em stm, cases F' with nm' em' stm', cases nodes_map_eq, cases edges_map_eq, refl end def id (G : graph) : hom G G := { nodes_map := id , edges_map := id , srctrg_map := λ _ _, rfl } def comp {G G' G'' : graph} (F : hom G G') (F' : hom G' G'') : hom G G'' := { nodes_map := F'.nodes_map ∘ F.nodes_map , edges_map := F'.edges_map ∘ F.edges_map , srctrg_map := λ b e, by {simp, rw F.srctrg_map, rw F'.srctrg_map} } def id_l {G G' : graph} (F : hom G G') : comp (id G) F = F := hom.eq rfl rfl def id_r {G G' : graph} (F : hom G G') : comp F (id G') = F := hom.eq rfl rfl def assoc {G G' G'' G''' : graph} (F : hom G G') (F' : hom G' G'') (F'' : hom G'' G''') : comp (comp F F') F'' = comp F (comp F' F'') := hom.eq rfl rfl end graph_cat def graph_cat : category := { obj := graph , hom := graph_cat.hom , id := graph_cat.id , comp := @graph_cat.comp , id_l := @graph_cat.id_l , id_r := @graph_cat.id_r , assoc := @graph_cat.assoc } namespace graph def reverse (G : graph) : graph := { nodes := G.nodes , edges := G.edges , srctrg := (λ b, G.srctrg (bnot b)) , edge_ext := λ e e' p, G.edge_ext e e' (begin intro b, let h := p (bnot b), simp at h, assumption end) } def singleton_reflexive : graph := { nodes := unit , edges := unit , srctrg := (λ _ _, ()) , edge_ext := λ e e' _, begin cases e, cases e', refl end } def path_graph (n : ℕ) : graph := { nodes := fin (n +1) , edges := fin n , srctrg := λ b e, match b with | ff := e.cast_succ | tt := e.succ end , edge_ext := begin induction n with n IH, { intro e, exact e.elim0 }, intros e e' p, cases e, cases e', cases e_val, { cases e'_val, {exact fin.eq_of_veq rfl}, replace p := p tt, simp [path_graph._match_1, fin.succ] at p, contradiction,}, cases e'_val, { replace p := p tt, simp [path_graph._match_1, fin.succ] at p, contradiction,}, let e := fin.mk_from_succ e_val e_is_lt, let e' := fin.mk_from_succ e'_val e'_is_lt, suffices : ∀ b, path_graph._match_1 n e b = path_graph._match_1 n e' b, { simp, exact fin.veq_of_eq (IH e e' this),}, intro b, replace p := p b, cases b, { simp [path_graph._match_1] at p |-, exact fin.eq_of_veq p}, { simp [path_graph._match_1] at p |-, replace p := fin.succ_injection p, simp at p, congr, exact fin.eq_of_veq p}, end } def path (G : graph) (len : ℕ) := graph_cat.hom (path_graph len) G def path.source {G : graph} {n : ℕ} (P : path G n) : G.nodes := P.nodes_map fin.zero def path.target {G : graph} {n : ℕ} (P : path G n) : G.nodes := P.nodes_map (fin.last n) def path.from_node (G : graph) (v : G.nodes) : path G 0 := { nodes_map := λ i, match i with | ⟨0, _⟩ := v | ⟨i +1, p⟩ := fin.elim_out_of_bound p end , edges_map := fin.elim0 , srctrg_map := λ b e, e.elim0 } def path.from_edge (G : graph) (e : G.edges) : path G 1 := { nodes_map := λ i, match i with | ⟨0, _⟩ := G.source e | ⟨1, _⟩ := G.target e | ⟨i +2, p⟩ := fin.elim_out_of_bound p end , edges_map := λ i, match i with | ⟨0, _⟩ := e | ⟨i +1, p⟩ := fin.elim_out_of_bound p end , srctrg_map := λ b e', match b, e' with | ff, ⟨0, _⟩ := begin -- TODO: currently here dsimp [path_graph, graph.srctrg], change fin.cast_succ ⟨0, _⟩ with ⟨0, _⟩ dsimp [fin.cast_succ, fin.cast_add, fin.cast_le, fin.cast_lt], simp [path.from_edge._match_1, path.from_edge._match_2, graph.srctrg], refl, end | tt, ⟨0, _⟩ := _ | _, ⟨i +1, p⟩ := fin.elim_out_of_bound p end } -- structure Hamiltonian_path (G : graph) (n : ℕ) := -- (path : path G n) -- (nodes_bij : function.bijective path.nodes_map) -- -- TODO: -- structure unique_Hamiltonian_path (G : graph) extends Hamiltonian_path G := -- (unique : subsingleton (Hamiltonian_path.mk len mor nodes_bij)) end graph
c2b0f45deec3a8c26cdb21cf468a85164f1792b9
6fbf10071e62af7238f2de8f9aa83d55d8763907
/hw/hw7.lean
75527de91b7a97b5121c215f35c5b96f240e435f
[]
no_license
HasanMukati/uva-cs-dm-s19
ee5aad4568a3ca330c2738ed579c30e1308b03b0
3e7177682acdb56a2d16914e0344c10335583dcf
refs/heads/master
1,596,946,213,130
1,568,221,949,000
1,568,221,949,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,350
lean
/- Read, and if you have already read, then re-read, the chapters in the notes on proofs of disjunctions and negations. We have added some new material, especially under negation elimination. In proofs of bi-implications, use comments to mark the start of the proofs of the implications in each direction. Label one as "forward" the other other as "backward." The collaboration policy for this homework is "no collaboration allowed." You may study and discuss the underlying concepts with anyone. You may provide proofs in the style of your choice: term-style, tactic style, or mixed. Yes, you can using tactic scripts within terms and terms within tactic scripts. You may use any tactics you know of. As a courtesy, we provide begin/end pairs, in case you should want to use them. Otherwise you may delete them. -/ /- 1. 15 points -/ example : ∀ (P Q : Prop), P ∧ Q → P ∨ Q := begin end /- 2. 15 points -/ example : ∀ (P Q R : Prop), (P ∨ Q) → (Q ∨ R) → ¬ Q → (P ∧ R) := begin end /- 3. 15 points -/ example : ∀ (P Q R : Prop), P ∧ (Q ∨ R) ↔ (P ∧ Q) ∨ (P ∧ R) := begin end /- 4. 10 points -/ example : ∀ (P Q R : Prop), P → Q → R → ¬ Q → (Q ∨ ¬ Q) := begin end open classical -- hint: you can now use em easily /- 4a. 5 points. Write *your own* proof of this conjecture. -/ example : ∀ (P Q : Prop), ¬ (P ∨ Q) ↔ ¬ P ∧ ¬ Q := begin end /- 4b. 5 points. Is this theorem classically true in neither, one, or both directions. Explain your answer in relation to your proof. Answer: -/ /- 5. 5 points. Write *your own proof* of this conjecture. -/ example : ∀ (P Q : Prop), ¬ (P ∧ Q) ↔ (¬ P ∨ ¬ Q) := begin end /- 6. 10 points -/ example : ∀ (P : Prop), (¬ ¬ P → P) ↔ (P ∨ ¬ P) := begin end /- 7. 5 points Tranlate the preceding proposition into English, referring explicitly to the principles of negation elimination and excluded middle. Write your sentence here: -/ /- 8. [10 points] -/ example : (∀ ( P Q : Prop ), (P → Q) ↔ (¬ Q → ¬ P)) → ∀ (Raining Wet : Prop), (¬ Wet → ¬ Raining) → (Raining → Wet) := begin end /- 9. [5 points] What is the name of the principle expressed by the premise, (P → Q) ↔ (¬ Q → ¬ P)), in the preceding problem? Answer here: -/
606f627e851112f6e9637738893c303cc97d0ed1
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/category_theory/limits/shapes/equalizers.lean
5abfbda99a2875422c1b5b2896047f4908c06812
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
5,242
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.eq_to_hom import category_theory.limits.cones open category_theory namespace category_theory.limits local attribute [tidy] tactic.case_bash universes v u @[derive decidable_eq] inductive walking_parallel_pair : Type v | zero | one open walking_parallel_pair inductive walking_parallel_pair_hom : walking_parallel_pair → walking_parallel_pair → Type v | left : walking_parallel_pair_hom zero one | right : walking_parallel_pair_hom zero one | id : Π X : walking_parallel_pair.{v}, walking_parallel_pair_hom X X open walking_parallel_pair_hom def walking_parallel_pair_hom.comp : Π (X Y Z : walking_parallel_pair) (f : walking_parallel_pair_hom X Y) (g : walking_parallel_pair_hom Y Z), walking_parallel_pair_hom X Z | _ _ _ (id _) h := h | _ _ _ left (id one) := left | _ _ _ right (id one) := right . instance walking_parallel_pair_hom_category : small_category.{v} walking_parallel_pair := { hom := walking_parallel_pair_hom, id := walking_parallel_pair_hom.id, comp := walking_parallel_pair_hom.comp } lemma walking_parallel_pair_hom_id (X : walking_parallel_pair.{v}) : walking_parallel_pair_hom.id X = 𝟙 X := rfl variables {C : Type u} [𝒞 : category.{v+1} C] include 𝒞 variables {X Y : C} def parallel_pair (f g : X ⟶ Y) : walking_parallel_pair.{v} ⥤ C := { obj := λ x, match x with | zero := X | one := Y end, map := λ x y h, match x, y, h with | _, _, (id _) := 𝟙 _ | _, _, left := f | _, _, right := g end }. @[simp] lemma parallel_pair_map_left (f g : X ⟶ Y) : (parallel_pair f g).map left = f := rfl @[simp] lemma parallel_pair_map_right (f g : X ⟶ Y) : (parallel_pair f g).map right = g := rfl @[simp] lemma parallel_pair_functor_obj {F : walking_parallel_pair.{v} ⥤ C} (j : walking_parallel_pair.{v}) : (parallel_pair (F.map left) (F.map right)).obj j = F.obj j := begin cases j; refl end abbreviation fork (f g : X ⟶ Y) := cone (parallel_pair f g) abbreviation cofork (f g : X ⟶ Y) := cocone (parallel_pair f g) variables {f g : X ⟶ Y} attribute [simp] walking_parallel_pair_hom_id def fork.of_ι {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) : fork f g := { X := P, π := { app := λ X, begin cases X, exact ι, exact ι ≫ f, end, naturality' := λ X Y f, begin cases X; cases Y; cases f; dsimp; simp, exact w end }} def cofork.of_π {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) : cofork f g := { X := P, ι := { app := λ X, begin cases X, exact f ≫ π, exact π, end, naturality' := λ X Y f, begin cases X; cases Y; cases f; dsimp; simp, exact eq.symm w end }} @[simp] lemma fork.of_ι_app_zero {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) : (fork.of_ι ι w).π.app zero = ι := rfl @[simp] lemma fork.of_ι_app_one {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) : (fork.of_ι ι w).π.app one = ι ≫ f := rfl def fork.ι (t : fork f g) := t.π.app zero def cofork.π (t : cofork f g) := t.ι.app one def fork.condition (t : fork f g) : (fork.ι t) ≫ f = (fork.ι t) ≫ g := begin erw [t.w left, ← t.w right], refl end def cofork.condition (t : cofork f g) : f ≫ (cofork.π t) = g ≫ (cofork.π t) := begin erw [t.w left, ← t.w right], refl end def cone.of_fork {F : walking_parallel_pair.{v} ⥤ C} (t : fork (F.map left) (F.map right)) : cone F := { X := t.X, π := { app := λ X, t.π.app X ≫ eq_to_hom (by tidy), naturality' := λ j j' g, begin cases j; cases j'; cases g; dsimp; simp, erw ← t.w left, refl, erw ← t.w right, refl, end } }. def cocone.of_cofork {F : walking_parallel_pair.{v} ⥤ C} (t : cofork (F.map left) (F.map right)) : cocone F := { X := t.X, ι := { app := λ X, eq_to_hom (by tidy) ≫ t.ι.app X, naturality' := λ j j' g, begin cases j; cases j'; cases g; dsimp; simp, erw ← t.w left, refl, erw ← t.w right, refl, end } }. @[simp] lemma cone.of_fork_π {F : walking_parallel_pair.{v} ⥤ C} (t : fork (F.map left) (F.map right)) (j) : (cone.of_fork t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl @[simp] lemma cocone.of_cofork_ι {F : walking_parallel_pair.{v} ⥤ C} (t : cofork (F.map left) (F.map right)) (j) : (cocone.of_cofork t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl def fork.of_cone {F : walking_parallel_pair.{v} ⥤ C} (t : cone F) : fork (F.map left) (F.map right) := { X := t.X, π := { app := λ X, t.π.app X ≫ eq_to_hom (by tidy) } } def cofork.of_cocone {F : walking_parallel_pair.{v} ⥤ C} (t : cocone F) : cofork (F.map left) (F.map right) := { X := t.X, ι := { app := λ X, eq_to_hom (by tidy) ≫ t.ι.app X } } @[simp] lemma fork.of_cone_π {F : walking_parallel_pair.{v} ⥤ C} (t : cone F) (j) : (fork.of_cone t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl @[simp] lemma cofork.of_cocone_ι {F : walking_parallel_pair.{v} ⥤ C} (t : cocone F) (j) : (cofork.of_cocone t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl end category_theory.limits
3a5f56b599da947c957c9010706820c1536ac463
6b2a480f27775cba4f3ae191b1c1387a29de586e
/group_rep1/Projection/test.lean
e2f5e62881bf78face6cda6c0a06cab8f4c906e6
[]
no_license
Or7ando/group_representation
a681de2e19d1930a1e1be573d6735a2f0b8356cb
9b576984f17764ebf26c8caa2a542d248f1b50d2
refs/heads/master
1,662,413,107,324
1,590,302,389,000
1,590,302,389,000
258,130,829
0
1
null
null
null
null
UTF-8
Lean
false
false
1,078
lean
import algebra.module import linear_algebra.basic --infix ` * ` := linear_map.comp universes u v variables {R : Type u}[comm_ring R]{M : Type v}[add_comm_group M] [module R M ] open linear_map def Projector (p : M →ₗ[R] M) := p * p = p /-- if `p² = p` then `(1-p)² = 1 - p - p +p² = ... = 1-p` -/ lemma Complementary (p : M →ₗ[R]M) [Projector p] : Projector (1 - p) := begin unfold Projector, rw mul_sub_left_distrib, iterate 2 { rw mul_sub_right_distrib,rw mul_one}, unfold Projector at *, rw _inst_4, rw one_mul, simp, end variables (p : M→ₗ[R]M) lemma ker_eq_im_complementary (hyp : Projector p ) : range p = ker (1-p) := begin apply submodule.ext, intros x, split, intros x_in_range, rw mem_range at x_in_range, rcases x_in_range with ⟨y,hyp_y⟩, rw mem_ker, rw ← hyp_y, simp, rw ← function.comp_apply ⇑p, unfold Projector at hyp, erw hyp, --- here do you have an idea to make the coersion of the composition easy ? end
8e0853f71734646bbb2c0892ac35e3f6bca45c7c
a4673261e60b025e2c8c825dfa4ab9108246c32e
/src/Lean/Elab/Do.lean
fa2aede4f4e2804291362b7512af277098d9b7c1
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
65,515
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Term import Lean.Elab.Binders import Lean.Elab.Quotation import Lean.Elab.Match namespace Lean.Elab.Term open Meta private def getDoSeqElems (doSeq : Syntax) : List Syntax := if doSeq.getKind == `Lean.Parser.Term.doSeqBracketed then doSeq[1].getArgs.toList.map fun arg => arg[0] else if doSeq.getKind == `Lean.Parser.Term.doSeqIndent then doSeq[0].getArgs.toList.map fun arg => arg[0] else [] private def getDoSeq (doStx : Syntax) : Syntax := doStx[1] @[builtinTermElab liftMethod] def elabLiftMethod : TermElab := fun stx _ => throwErrorAt stx "invalid use of `(<- ...)`, must be nested inside a 'do' expression" /-- Return true if we should not lift `(<- ...)` actions nested in the syntax nodes with the given kind. -/ private def liftMethodDelimiter (k : SyntaxNodeKind) : Bool := k == `Lean.Parser.Term.do || k == `Lean.Parser.Term.doSeqIndent || k == `Lean.Parser.Term.doSeqBracketed || k == `Lean.Parser.Term.quot || k == `Lean.Parser.Term.termReturn || k == `Lean.Parser.Term.termUnless || k == `Lean.Parser.Term.termTry || k == `Lean.Parser.Term.termFor private partial def hasLiftMethod : Syntax → Bool | Syntax.node k args => if liftMethodDelimiter k then false else if k == `Lean.Parser.Term.liftMethod then true else args.any hasLiftMethod | _ => false structure ExtractMonadResult := (m : Expr) (α : Expr) (hasBindInst : Expr) (expectedType : Expr) private def mkIdBindFor (type : Expr) : TermElabM ExtractMonadResult := do let u ← getDecLevel type let id := Lean.mkConst `Id [u] let idBindVal := Lean.mkConst `Id.hasBind [u] pure { m := id, hasBindInst := idBindVal, α := type, expectedType := mkApp id type } private def extractBind (expectedType? : Option Expr) : TermElabM ExtractMonadResult := do match expectedType? with | none => throwError "invalid do notation, expected type is not available" | some expectedType => let type ← withReducible $ whnf expectedType if type.getAppFn.isMVar then throwError "invalid do notation, expected type is not available" match type with | Expr.app m α _ => try let bindInstType ← mkAppM `Bind #[m] let bindInstVal ← synthesizeInst bindInstType pure { m := m, hasBindInst := bindInstVal, α := α, expectedType := expectedType } catch _ => mkIdBindFor type | _ => mkIdBindFor type namespace Do /- A `doMatch` alternative. `vars` is the array of variables declared by `patterns`. -/ structure Alt (σ : Type) := (ref : Syntax) (vars : Array Name) (patterns : Syntax) (rhs : σ) /- Auxiliary datastructure for representing a `do` code block, and compiling "reassignments" (e.g., `x := x + 1`). We convert `Code` into a `Syntax` term representing the: - `do`-block, or - the visitor argument for the `forIn` combinator. We say the following constructors are terminals: - `break`: for interrupting a `for x in s` - `continue`: for interrupting the current iteration of a `for x in s` - `return e`: for returning `e` as the result for the whole `do` computation block - `action a`: for executing action `a` as a terminal - `ite`: if-then-else - `match`: pattern matching - `jmp` a goto to a join-point We say the terminals `break`, `continue`, `action`, and `return` are "exit points" Note that, `return e` is not equivalent to `action (pure e)`. Here is an example: ``` def f (x : Nat) : IO Unit := do if x == 0 then return () IO.println "hello" ``` Executing `#eval f 0` will not print "hello". Now, consider ``` def g (x : Nat) : IO Unit := do if x == 0 then pure () IO.println "hello" ``` The `if` statement is essentially a noop, and "hello" is printed when we execute `g 0`. - `decl` represents all declaration-like `doElem`s (e.g., `let`, `have`, `let rec`). The field `stx` is the actual `doElem`, `vars` is the array of variables declared by it, and `cont` is the next instruction in the `do` code block. `vars` is an array since we have declarations such as `let (a, b) := s`. - `reassign` is an reassignment-like `doElem` (e.g., `x := x + 1`). - `joinpoint` is a join point declaration: an auxiliary `let`-declaration used to represent the control-flow. - `seq a k` executes action `a`, ignores its result, and then executes `k`. We also store the do-elements `dbgTrace!` and `assert!` as actions in a `seq`. A code block `C` is well-formed if - For every `jmp ref j as` in `C`, there is a `joinpoint j ps b k` and `jmp ref j as` is in `k`, and `ps.size == as.size` -/ inductive Code := | decl (xs : Array Name) (doElem : Syntax) (k : Code) | reassign (xs : Array Name) (doElem : Syntax) (k : Code) /- The Boolean value in `params` indicates whether we should use `(x : typeof! x)` when generating term Syntax or not -/ | joinpoint (name : Name) (params : Array (Name × Bool)) (body : Code) (k : Code) | seq (action : Syntax) (k : Code) | action (action : Syntax) | «break» (ref : Syntax) | «continue» (ref : Syntax) | «return» (ref : Syntax) (val : Syntax) /- Recall that an if-then-else may declare a variable using `optIdent` for the branches `thenBranch` and `elseBranch`. We store the variable name at `var?`. -/ | ite (ref : Syntax) (h? : Option Name) (optIdent : Syntax) (cond : Syntax) (thenBranch : Code) (elseBranch : Code) | «match» (ref : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt Code)) | jmp (ref : Syntax) (jpName : Name) (args : Array Syntax) instance : Inhabited Code := ⟨Code.«break» arbitrary⟩ instance : Inhabited (Alt Code) := ⟨{ ref := arbitrary, vars := #[], patterns := arbitrary, rhs := arbitrary }⟩ /- A code block, and the collection of variables updated by it. -/ structure CodeBlock := (code : Code) (uvars : NameSet := {}) -- set of variables updated by `code` private def nameSetToArray (s : NameSet) : Array Name := s.fold (fun (xs : Array Name) x => xs.push x) #[] private def varsToMessageData (vars : Array Name) : MessageData := MessageData.joinSep (vars.toList.map fun n => MessageData.ofName (n.simpMacroScopes)) " " partial def CodeBlocl.toMessageData (codeBlock : CodeBlock) : MessageData := let us := MessageData.ofList $ (nameSetToArray codeBlock.uvars).toList.map MessageData.ofName let rec loop : Code → MessageData | Code.decl xs _ k => m!"let {varsToMessageData xs} := ...\n{loop k}" | Code.reassign xs _ k => m!"{varsToMessageData xs} := ...\n{loop k}" | Code.joinpoint n ps body k => m!"let {n.simpMacroScopes} {varsToMessageData (ps.map Prod.fst)} := {indentD (loop body)}\n{loop k}" | Code.seq e k => m!"{e}\n{loop k}" | Code.action e => e | Code.ite _ _ _ c t e => m!"if {c} then {indentD (loop t)}\nelse{loop e}" | Code.jmp _ j xs => m!"jmp {j.simpMacroScopes} {xs.toList}" | Code.«break» _ => m!"break {us}" | Code.«continue» _ => m!"continue {us}" | Code.«return» _ v => m!"return {v} {us}" | Code.«match» _ ds t alts => m!"match {ds} with" ++ alts.foldl (init := "") fun acc alt => acc ++ m!"\n| {alt.patterns} => {loop alt.rhs}" loop codeBlock.code /- Return true if the give code contains an exit point that satisfies `p` -/ @[inline] partial def hasExitPointPred (c : Code) (p : Code → Bool) : Bool := let rec @[specialize] loop : Code → Bool | Code.decl _ _ k => loop k | Code.reassign _ _ k => loop k | Code.joinpoint _ _ b k => loop b || loop k | Code.seq _ k => loop k | Code.ite _ _ _ _ t e => loop t || loop e | Code.«match» _ _ _ alts => alts.any (loop ·.rhs) | Code.jmp _ _ _ => false | c => p c loop c def hasExitPoint (c : Code) : Bool := hasExitPointPred c fun c => true def hasReturn (c : Code) : Bool := hasExitPointPred c fun | Code.«return» _ _ => true | _ => false def hasTerminalAction (c : Code) : Bool := hasExitPointPred c fun | Code.«action» _ => true | _ => false def hasBreakContinue (c : Code) : Bool := hasExitPointPred c fun | Code.«break» _ => true | Code.«continue» _ => true | _ => false def hasBreakContinueReturn (c : Code) : Bool := hasExitPointPred c fun | Code.«break» _ => true | Code.«continue» _ => true | Code.«return» _ _ => true | _ => false def mkAuxDeclFor {m} [Monad m] [MonadQuotation m] (e : Syntax) (mkCont : Syntax → m Code) : m Code := withFreshMacroScope do let y ← `(y) let yName := y.getId let doElem ← `(doElem| let y ← $e:term) -- Add elaboration hint for producing sane error message let y ← `(ensureExpectedType! "type mismatch, result value" $y) let k ← mkCont y pure $ Code.decl #[yName] doElem k /- Convert `action _ e` instructions in `c` into `let y ← e; jmp _ jp (xs y)`. -/ partial def convertTerminalActionIntoJmp (code : Code) (jp : Name) (xs : Array Name) : MacroM Code := let rec loop : Code → MacroM Code | Code.decl xs stx k => do Code.decl xs stx (← loop k) | Code.reassign xs stx k => do Code.reassign xs stx (← loop k) | Code.joinpoint n ps b k => do Code.joinpoint n ps (← loop b) (← loop k) | Code.seq e k => do Code.seq e (← loop k) | Code.ite ref x? h c t e => do Code.ite ref x? h c (← loop t) (← loop e) | Code.«match» ref ds t alts => do Code.«match» ref ds t (← alts.mapM fun alt => do pure { alt with rhs := (← loop alt.rhs) }) | Code.action e => mkAuxDeclFor e fun y => let ref := e -- We jump to `jp` with xs **and** y let jmpArgs := xs.map $ mkIdentFrom ref let jmpArgs := jmpArgs.push y pure $ Code.jmp ref jp jmpArgs | c => pure c loop code structure JPDecl := (name : Name) (params : Array (Name × Bool)) (body : Code) def attachJP (jpDecl : JPDecl) (k : Code) : Code := Code.joinpoint jpDecl.name jpDecl.params jpDecl.body k def attachJPs (jpDecls : Array JPDecl) (k : Code) : Code := jpDecls.foldr attachJP k def mkFreshJP (ps : Array (Name × Bool)) (body : Code) : TermElabM JPDecl := do let ps ← if ps.isEmpty then let y ← mkFreshUserName `y pure #[(y, false)] else pure ps -- Remark: the compiler frontend implemented in C++ currently detects jointpoints created by -- the "do" notation by testing the name. See hack at method `visit_let` at `lcnf.cpp` -- We will remove this hack when we re-implement the compiler frontend in Lean. let name ← mkFreshUserName `_do_jp pure { name := name, params := ps, body := body } def mkFreshJP' (xs : Array Name) (body : Code) : TermElabM JPDecl := mkFreshJP (xs.map fun x => (x, true)) body def addFreshJP (ps : Array (Name × Bool)) (body : Code) : StateRefT (Array JPDecl) TermElabM Name := do let jp ← mkFreshJP ps body modify fun (jps : Array JPDecl) => jps.push jp pure jp.name def insertVars (rs : NameSet) (xs : Array Name) : NameSet := xs.foldl (·.insert ·) rs def eraseVars (rs : NameSet) (xs : Array Name) : NameSet := xs.foldl (·.erase ·) rs def eraseOptVar (rs : NameSet) (x? : Option Name) : NameSet := match x? with | none => rs | some x => rs.insert x /- Create a new jointpoint for `c`, and jump to it with the variables `rs` -/ def mkSimpleJmp (ref : Syntax) (rs : NameSet) (c : Code) : StateRefT (Array JPDecl) TermElabM Code := do let xs := nameSetToArray rs let jp ← addFreshJP (xs.map fun x => (x, true)) c if xs.isEmpty then let unit ← `(Unit.unit) pure $ Code.jmp ref jp #[unit] else pure $ Code.jmp ref jp (xs.map $ mkIdentFrom ref) /- Create a new joinpoint that takes `rs` and `val` as arguments. `val` must be syntax representing a pure value. The body of the joinpoint is created using `mkJPBody yFresh`, where `yFresh` is a fresh variable created by this method. -/ def mkJmp (ref : Syntax) (rs : NameSet) (val : Syntax) (mkJPBody : Syntax → MacroM Code) : StateRefT (Array JPDecl) TermElabM Code := do let xs := nameSetToArray rs let args := xs.map $ mkIdentFrom ref let args := args.push val let yFresh ← mkFreshUserName `y let ps := xs.map fun x => (x, true) let ps := ps.push (yFresh, false) let jpBody ← liftMacroM $ mkJPBody (mkIdentFrom ref yFresh) let jp ← addFreshJP ps jpBody pure $ Code.jmp ref jp args /- `pullExitPointsAux rs c` auxiliary method for `pullExitPoints`, `rs` is the set of update variable in the current path. -/ partial def pullExitPointsAux : NameSet → Code → StateRefT (Array JPDecl) TermElabM Code | rs, Code.decl xs stx k => do Code.decl xs stx (← pullExitPointsAux (eraseVars rs xs) k) | rs, Code.reassign xs stx k => do Code.reassign xs stx (← pullExitPointsAux (insertVars rs xs) k) | rs, Code.joinpoint j ps b k => do Code.joinpoint j ps (← pullExitPointsAux rs b) (← pullExitPointsAux rs k) | rs, Code.seq e k => do Code.seq e (← pullExitPointsAux rs k) | rs, Code.ite ref x? o c t e => do Code.ite ref x? o c (← pullExitPointsAux (eraseOptVar rs x?) t) (← pullExitPointsAux (eraseOptVar rs x?) e) | rs, Code.«match» ref ds t alts => do Code.«match» ref ds t (← alts.mapM fun alt => do pure { alt with rhs := (← pullExitPointsAux (eraseVars rs alt.vars) alt.rhs) }) | rs, c@(Code.jmp _ _ _) => pure c | rs, Code.«break» ref => mkSimpleJmp ref rs (Code.«break» ref) | rs, Code.«continue» ref => mkSimpleJmp ref rs (Code.«continue» ref) | rs, Code.«return» ref val => mkJmp ref rs val (fun y => pure $ Code.«return» ref y) | rs, Code.action e => -- We use `mkAuxDeclFor` because `e` is not pure. mkAuxDeclFor e fun y => let ref := e mkJmp ref rs y (fun yFresh => do pure $ Code.action (← `(Pure.pure $yFresh))) /- Auxiliary operation for adding new variables to the collection of updated variables in a CodeBlock. When a new variable is not already in the collection, but is shadowed by some declaration in `c`, we create auxiliary join points to make sure we preserve the semantics of the code block. Example: suppose we have the code block `print x; let x := 10; return x`. And we want to extend it with the reassignment `x := x + 1`. We first use `pullExitPoints` to create ``` let jp (x!1) := return x!1; print x; let x := 10; jmp jp x ``` and then we add the reassignment ``` x := x + 1 let jp (x!1) := return x!1; print x; let x := 10; jmp jp x ``` Note that we created a fresh variable `x!1` to avoid accidental name capture. As another example, consider ``` print x; let x := 10 y := y + 1; return x; ``` We transform it into ``` let jp (y x!1) := return x!1; print x; let x := 10 y := y + 1; jmp jp y x ``` and then we add the reassignment as in the previous example. We need to include `y` in the jump, because each exit point is implicitly returning the set of update variables. We implement the method as follows. Let `us` be `c.uvars`, then 1- for each `return _ y` in `c`, we create a join point `let j (us y!1) := return y!1` and replace the `return _ y` with `jmp us y` 2- for each `break`, we create a join point `let j (us) := break` and replace the `break` with `jmp us`. 3- Same as 2 for `continue`. -/ def pullExitPoints (c : Code) : TermElabM Code := do if hasExitPoint c then let (c, jpDecls) ← (pullExitPointsAux {} c).run #[] pure $ attachJPs jpDecls c else pure c partial def extendUpdatedVarsAux (c : Code) (ws : NameSet) : TermElabM Code := let rec update : Code → TermElabM Code | Code.joinpoint j ps b k => do Code.joinpoint j ps (← update b) (← update k) | Code.seq e k => do Code.seq e (← update k) | c@(Code.«match» ref ds t alts) => do if alts.any fun alt => alt.vars.any fun x => ws.contains x then -- If a pattern variable is shadowing a variable in ws, we `pullExitPoints` pullExitPoints c else Code.«match» ref ds t (← alts.mapM fun alt => do pure { alt with rhs := (← update alt.rhs) }) | Code.ite ref none o c t e => do Code.ite ref none o c (← update t) (← update e) | c@(Code.ite ref (some h) o cond t e) => do if ws.contains h then -- if the `h` at `if h:c then t else e` shadows a variable in `ws`, we `pullExitPoints` pullExitPoints c else Code.ite ref (some h) o cond (← update t) (← update e) | Code.reassign xs stx k => do Code.reassign xs stx (← update k) | c@(Code.decl xs stx k) => do if xs.any fun x => ws.contains x then -- One the declared variables is shadowing a variable in `ws` pullExitPoints c else Code.decl xs stx (← update k) | c => pure c update c /- Extend the set of updated variables. It assumes `ws` is a super set of `c.uvars`. We **cannot** simply update the field `c.uvars`, because `c` may have shadowed some variable in `ws`. See discussion at `pullExitPoints`. -/ partial def extendUpdatedVars (c : CodeBlock) (ws : NameSet) : TermElabM CodeBlock := do if ws.any fun x => !c.uvars.contains x then -- `ws` contains a variable that is not in `c.uvars`, but in `c.dvars` (i.e., it has been shadowed) pure { code := (← extendUpdatedVarsAux c.code ws), uvars := ws } else pure { c with uvars := ws } private def union (s₁ s₂ : NameSet) : NameSet := s₁.fold (·.insert ·) s₂ /- Given two code blocks `c₁` and `c₂`, make sure they have the same set of updated variables. Let `ws` the union of the updated variables in `c₁‵ and ‵c₂`. We use `extendUpdatedVars c₁ ws` and `extendUpdatedVars c₂ ws` -/ def homogenize (c₁ c₂ : CodeBlock) : TermElabM (CodeBlock × CodeBlock) := do let ws := union c₁.uvars c₂.uvars let c₁ ← extendUpdatedVars c₁ ws let c₂ ← extendUpdatedVars c₂ ws pure (c₁, c₂) /- Extending code blocks with variable declarations: `let x : t := v` and `let x : t ← v`. We remove `x` from the collection of updated varibles. Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables declared by it. It is an array because we have let-declarations that declare multiple variables. Example: `let (x, y) := t` -/ def mkVarDeclCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : CodeBlock := { code := Code.decl xs stx c.code, uvars := eraseVars c.uvars xs } /- Extending code blocks with reassignments: `x : t := v` and `x : t ← v`. Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables declared by it. It is an array because we have let-declarations that declare multiple variables. Example: `(x, y) ← t` -/ def mkReassignCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : TermElabM CodeBlock := do let us := c.uvars let ws := insertVars us xs -- If `xs` contains a new updated variable, then we must use `extendUpdatedVars`. -- See discussion at `pullExitPoints` let code ← if xs.any fun x => !us.contains x then extendUpdatedVarsAux c.code ws else pure c.code pure { code := Code.reassign xs stx code, uvars := ws } def mkSeq (action : Syntax) (c : CodeBlock) : CodeBlock := { c with code := Code.seq action c.code } def mkTerminalAction (action : Syntax) : CodeBlock := { code := Code.action action } def mkReturn (ref : Syntax) (val : Syntax) : CodeBlock := { code := Code.«return» ref val } def mkBreak (ref : Syntax) : CodeBlock := { code := Code.«break» ref } def mkContinue (ref : Syntax) : CodeBlock := { code := Code.«continue» ref } def mkIte (ref : Syntax) (optIdent : Syntax) (cond : Syntax) (thenBranch : CodeBlock) (elseBranch : CodeBlock) : TermElabM CodeBlock := do let x? := if optIdent.isNone then none else some optIdent[0].getId let (thenBranch, elseBranch) ← homogenize thenBranch elseBranch pure { code := Code.ite ref x? optIdent cond thenBranch.code elseBranch.code, uvars := thenBranch.uvars, } private def mkUnit (ref : Syntax) : MacroM Syntax := do let unit ← `(PUnit.unit) pure $ unit.copyInfo ref private def mkPureUnit (ref : Syntax) : MacroM Syntax := do let unit ← mkUnit ref let pureUnit ← `(Pure.pure $(unit.copyInfo ref)) pure $ pureUnit.copyInfo ref def mkPureUnitAction (ref : Syntax) : MacroM CodeBlock := do mkTerminalAction (← mkPureUnit ref) def mkUnless (ref : Syntax) (cond : Syntax) (c : CodeBlock) : MacroM CodeBlock := do let thenBranch ← mkPureUnitAction ref pure { c with code := Code.ite ref none mkNullNode cond thenBranch.code c.code } def mkMatch (ref : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt CodeBlock)) : TermElabM CodeBlock := do -- nary version of homogenize let ws := alts.foldl (union · ·.rhs.uvars) {} let alts ← alts.mapM fun alt => do let rhs ← extendUpdatedVars alt.rhs ws pure { ref := alt.ref, vars := alt.vars, patterns := alt.patterns, rhs := rhs.code : Alt Code } pure { code := Code.«match» ref discrs optType alts, uvars := ws } /- Return a code block that executes `terminal` and then `k` with the value produced by `terminal`. This method assumes `terminal` is a terminal -/ def concat (terminal : CodeBlock) (kRef : Syntax) (y? : Option Name) (k : CodeBlock) : TermElabM CodeBlock := do unless hasTerminalAction terminal.code do throwErrorAt kRef "'do' element is unreachable" let (terminal, k) ← homogenize terminal k let xs := nameSetToArray k.uvars let y ← match y? with | some y => pure y | none => mkFreshUserName `y let ps := xs.map fun x => (x, true) let ps := ps.push (y, false) let jpDecl ← mkFreshJP ps k.code let jp := jpDecl.name let terminal ← liftMacroM $ convertTerminalActionIntoJmp terminal.code jp xs pure { code := attachJP jpDecl terminal, uvars := k.uvars } def getLetIdDeclVar (letIdDecl : Syntax) : Name := letIdDecl[0].getId def getLetPatDeclVars (letPatDecl : Syntax) : TermElabM (Array Name) := do let pattern := letPatDecl[0] let patternVars ← getPatternVars pattern pure $ patternVars.filterMap fun | PatternVar.localVar x => some x | _ => none def getLetEqnsDeclVar (letEqnsDecl : Syntax) : Name := letEqnsDecl[0].getId def getLetDeclVars (letDecl : Syntax) : TermElabM (Array Name) := do let arg := letDecl[0] if arg.getKind == `Lean.Parser.Term.letIdDecl then pure #[getLetIdDeclVar arg] else if arg.getKind == `Lean.Parser.Term.letPatDecl then getLetPatDeclVars arg else if arg.getKind == `Lean.Parser.Term.letEqnsDecl then pure #[getLetEqnsDeclVar arg] else throwError "unexpected kind of let declaration" def getDoLetVars (doLet : Syntax) : TermElabM (Array Name) := -- parser! "let " >> optional "mut " >> letDecl getLetDeclVars doLet[2] def getDoHaveVar (doHave : Syntax) : Name := /- `parser! "have " >> Term.haveDecl` where ``` haveDecl := optIdent >> termParser >> (haveAssign <|> fromTerm <|> byTactic) optIdent := optional (try (ident >> " : ")) ``` -/ let optIdent := doHave[1] if optIdent.isNone then `this else optIdent[0].getId def getDoLetRecVars (doLetRec : Syntax) : TermElabM (Array Name) := do -- letRecDecls is an array of `(group (optional attributes >> letDecl))` let letRecDecls := doLetRec[1].getSepArgs let letDecls := letRecDecls.map fun p => p[1] let mut allVars := #[] for letDecl in letDecls do let vars ← getLetDeclVars letDecl allVars := allVars ++ vars pure allVars -- ident >> optType >> leftArrow >> termParser def getDoIdDeclVar (doIdDecl : Syntax) : Name := doIdDecl[0].getId def getPatternVarNames (pvars : Array PatternVar) : Array Name := pvars.filterMap fun | PatternVar.localVar x => some x | _ => none -- termParser >> leftArrow >> termParser >> optional (" | " >> termParser) def getDoPatDeclVars (doPatDecl : Syntax) : TermElabM (Array Name) := do let pattern := doPatDecl[0] let patternVars ← getPatternVars pattern pure $ getPatternVarNames patternVars -- parser! "let " >> optional "mut " >> (doIdDecl <|> doPatDecl) def getDoLetArrowVars (doLetArrow : Syntax) : TermElabM (Array Name) := do let decl := doLetArrow[2] if decl.getKind == `Lean.Parser.Term.doIdDecl then pure #[getDoIdDeclVar decl] else if decl.getKind == `Lean.Parser.Term.doPatDecl then getDoPatDeclVars decl else throwError "unexpected kind of 'do' declaration" def getDoReassignVars (doReassign : Syntax) : TermElabM (Array Name) := do let arg := doReassign[0] if arg.getKind == `Lean.Parser.Term.letIdDecl then pure #[getLetIdDeclVar arg] else if arg.getKind == `Lean.Parser.Term.letPatDecl then getLetPatDeclVars arg else throwError "unexpected kind of reassignment" def mkDoSeq (doElems : Array Syntax) : Syntax := mkNode `Lean.Parser.Term.doSeqIndent #[mkNullNode $ doElems.map fun doElem => mkNullNode #[doElem, mkNullNode]] def mkSingletonDoSeq (doElem : Syntax) : Syntax := mkDoSeq #[doElem] /- Recall that the `doIf` syntax is of the form ``` "if " >> optIdent >> termParser >> " then " >> doSeq >> many (group (" else " >> " if ") >> optIdent >> termParser >> " then " >> doSeq) >> optional (" else " >> doSeq) ``` If the given syntax is a `doIf`, return an equivalente `doIf` that has no `else if`s and the `else` is not none. -/ private def expandDoIf? (stx : Syntax) : MacroM (Option Syntax) := do if stx.getKind != `Lean.Parser.Term.doIf then pure none else let doIf := stx let ref := stx let doElseIfs := doIf[5].getArgs let doElse := doIf[6] if doElseIfs.isEmpty && !doElse.isNone then pure none else let doElse ← if doElse.isNone then let pureUnit ← mkPureUnit ref pure $ mkNullNode #[ mkAtomFrom ref "else", mkSingletonDoSeq (mkNode `Lean.Parser.Term.doExpr #[pureUnit]) ] else pure doElse let doElse := doElseIfs.foldr (fun doElseIf doElse => let ifAtom := doElseIf[0][1] let doIfArgs := (doElseIf.getArgs).set! 0 ifAtom let doIfArgs := doIfArgs.push mkNullNode let doIfArgs := doIfArgs.push doElse mkNullNode #[mkAtomFrom doElseIf "else", mkSingletonDoSeq $ mkNode `Lean.Parser.Term.doIf doIfArgs]) doElse let doIf := doIf.setArg 6 doElse pure $ some $ doIf.setArg 5 mkNullNode -- remove else-ifs structure DoIfView := (ref : Syntax) (optIdent : Syntax) (cond : Syntax) (thenBranch : Syntax) (elseBranch : Syntax) /- This method assumes `expandDoIf?` is not applicable. -/ private def mkDoIfView (doIf : Syntax) : MacroM DoIfView := do pure { ref := doIf, optIdent := doIf[1], cond := doIf[2], thenBranch := doIf[4], elseBranch := doIf[6][1] } /- We use `MProd` instead of `Prod` to group values when expanding the `do` notation. `MProd` is a universe monomorphic product. The motivation is to generate simpler universe constraints in code that was not written by the user. Note that we are not restricting the macro power since the `Bind.bind` combinator already forces values computed by monadic actions to be in the same universe. -/ private def mkTuple (ref : Syntax) (elems : Array Syntax) : MacroM Syntax := do if elems.size == 0 then mkUnit ref else if elems.size == 1 then pure elems[0] else (elems.extract 0 (elems.size - 1)).foldrM (fun elem tuple => do let tuple ← `(MProd.mk $elem $tuple) pure $ tuple.copyInfo ref) (elems.back) /- Return `some action` if `doElem` is a `doExpr <action>`-/ def isDoExpr? (doElem : Syntax) : Option Syntax := if doElem.getKind == `Lean.Parser.Term.doExpr then some doElem[0] else none /- The procedure `ToTerm.run` converts a `CodeBlock` into a `Syntax` term. We use this method to convert 1- The `CodeBlock` for a root `do ...` term into a `Syntax` term. This kind of `CodeBlock` never contains `break` nor `continue`. Moreover, the collection of updated variables is not packed into the result. Thus, we have two kinds of exit points - `Code.action e` which is converted into `e` - `Code.return _ e` which is converted into `pure e` We use `Kind.regular` for this case. 2- The `CodeBlock` for `b` at `for x in xs do b`. In this case, we need to generate a `Syntax` term representing a function for the `xs.forIn` combinator. a) If `b` contain a `Code.return _ a` exit point. The generated `Syntax` term has type `m (ForInStep (Option α × σ))`, where `a : α`, and the `σ` is the type of the tuple of variables reassigned by `b`. We use `Kind.forInWithReturn` for this case b) If `b` does not contain a `Code.return _ a` exit point. Then, the generated `Syntax` term has type `m (ForInStep σ)`. We use `Kind.forIn` for this case. 3- The `CodeBlock` `c` for a `do` sequence nested in a monadic combinator (e.g., `MonadExcept.tryCatch`). The generated `Syntax` term for `c` must inform whether `c` "exited" using `Code.action`, `Code.return`, `Code.break` or `Code.continue`. We use the auxiliary types `DoResult`s for storing this information. For example, the auxiliary type `DoResultPBC α σ` is used for a code block that exits with `Code.action`, **and** `Code.break`/`Code.continue`, `α` is the type of values produced by the exit `action`, and `σ` is the type of the tuple of reassigned variables. The type `DoResult α β σ` is usedf for code blocks that exit with `Code.action`, `Code.return`, **and** `Code.break`/`Code.continue`, `β` is the type of the returned values. We don't use `DoResult α β σ` for all cases because: a) The elaborator would not be able to infer all type parameters without extra annotations. For example, if the code block does not contain `Code.return _ _`, the elaborator will not be able to infer `β`. b) We need to pattern match on the result produced by the combinator (e.g., `MonadExcept.tryCatch`), but we don't want to consider "unreachable" cases. We do not distinguish between cases that contain `break`, but not `continue`, and vice versa. When listing all cases, we use `a` to indicate the code block contains `Code.action _`, `r` for `Code.return _ _`, and `b/c` for a code block that contains `Code.break _` or `Code.continue _`. - `a`: `Kind.regular`, type `m (α × σ)` - `r`: `Kind.regular`, type `m (α × σ)` Note that the code that pattern matches on the result will behave differently in this case. It produces `return a` for this case, and `pure a` for the previous one. - `b/c`: `Kind.nestedBC`, type `m (DoResultBC σ)` - `a` and `r`: `Kind.nestedPR`, type `m (DoResultPR α β σ)` - `a` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC α σ)` - `r` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC α σ)` Again the code that pattern matches on the result will behave differently in this case and the previous one. It produces `return a` for the constructor `DoResultSPR.pureReturn a u` for this case, and `pure a` for the previous case. - `a`, `r`, `b/c`: `Kind.nestedPRBC`, type type `m (DoResultPRBC α β σ)` Here is the recipe for adding new combinators with nested `do`s. Example: suppose we want to support `repeat doSeq`. Assuming we have `repeat : m α → m α` 1- Convert `doSeq` into `codeBlock : CodeBlock` 2- Create term `term` using `mkNestedTerm code m uvars a r bc` where `code` is `codeBlock.code`, `uvars` is an array containing `codeBlock.uvars`, `m` is a `Syntax` representing the Monad, and `a` is true if `code` contains `Code.action _`, `r` is true if `code` contains `Code.return _ _`, `bc` is true if `code` contains `Code.break _` or `Code.continue _`. Remark: for combinators such as `repeat` that take a single `doSeq`, all arguments, but `m`, are extracted from `codeBlock`. 3- Create the term `repeat $term` 4- and then, convert it into a `doSeq` using `matchNestedTermResult ref (repeat $term) uvsar a r bc` -/ namespace ToTerm inductive Kind := | regular | forIn | forInWithReturn | nestedBC | nestedPR | nestedSBC | nestedPRBC instance : Inhabited Kind := ⟨Kind.regular⟩ def Kind.isRegular : Kind → Bool | Kind.regular => true | _ => false structure Context := (m : Syntax) -- Syntax to reference the monad associated with the do notation. (uvars : Array Name) (kind : Kind) abbrev M := ReaderT Context MacroM def mkUVarTuple (ref : Syntax) : M Syntax := do let ctx ← read let uvarIdents := ctx.uvars.map fun x => mkIdentFrom ref x mkTuple ref uvarIdents def returnToTermCore (ref : Syntax) (val : Syntax) : M Syntax := do let ctx ← read let u ← mkUVarTuple ref match ctx.kind with | Kind.regular => if ctx.uvars.isEmpty then `(Pure.pure $val) else `(Pure.pure (MProd.mk $val $u)) | Kind.forIn => `(Pure.pure (ForInStep.done $u)) | Kind.forInWithReturn => `(Pure.pure (ForInStep.done (MProd.mk (some $val) $u))) | Kind.nestedBC => unreachable! | Kind.nestedPR => `(Pure.pure (DoResultPR.«return» $val $u)) | Kind.nestedSBC => `(Pure.pure (DoResultSBC.«pureReturn» $val $u)) | Kind.nestedPRBC => `(Pure.pure (DoResultPRBC.«return» $val $u)) def returnToTerm (ref : Syntax) (val : Syntax) : M Syntax := do let r ← returnToTermCore ref val pure $ r.copyInfo ref def continueToTermCore (ref : Syntax) : M Syntax := do let ctx ← read let u ← mkUVarTuple ref match ctx.kind with | Kind.regular => unreachable! | Kind.forIn => `(Pure.pure (ForInStep.yield $u)) | Kind.forInWithReturn => `(Pure.pure (ForInStep.yield (MProd.mk none $u))) | Kind.nestedBC => `(Pure.pure (DoResultBC.«continue» $u)) | Kind.nestedPR => unreachable! | Kind.nestedSBC => `(Pure.pure (DoResultSBC.«continue» $u)) | Kind.nestedPRBC => `(Pure.pure (DoResultPRBC.«continue» $u)) def continueToTerm (ref : Syntax) : M Syntax := do let r ← continueToTermCore ref pure $ r.copyInfo ref def breakToTermCore (ref : Syntax) : M Syntax := do let ctx ← read let u ← mkUVarTuple ref match ctx.kind with | Kind.regular => unreachable! | Kind.forIn => `(Pure.pure (ForInStep.done $u)) | Kind.forInWithReturn => `(Pure.pure (ForInStep.done (MProd.mk none $u))) | Kind.nestedBC => `(Pure.pure (DoResultBC.«break» $u)) | Kind.nestedPR => unreachable! | Kind.nestedSBC => `(Pure.pure (DoResultSBC.«break» $u)) | Kind.nestedPRBC => `(Pure.pure (DoResultPRBC.«break» $u)) def breakToTerm (ref : Syntax) : M Syntax := do let r ← breakToTermCore ref pure $ r.copyInfo ref def actionTerminalToTermCore (action : Syntax) : M Syntax := withFreshMacroScope do let ref := action let ctx ← read let u ← mkUVarTuple ref match ctx.kind with | Kind.regular => if ctx.uvars.isEmpty then pure action else `(Bind.bind $action fun y => Pure.pure (MProd.mk y $u)) | Kind.forIn => `(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield $u)) | Kind.forInWithReturn => `(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield (MProd.mk none $u))) | Kind.nestedBC => unreachable! | Kind.nestedPR => `(Bind.bind $action fun y => (Pure.pure (DoResultPR.«pure» y $u))) | Kind.nestedSBC => `(Bind.bind $action fun y => (Pure.pure (DoResultSBC.«pureReturn» y $u))) | Kind.nestedPRBC => `(Bind.bind $action fun y => (Pure.pure (DoResultPRBC.«pure» y $u))) def actionTerminalToTerm (action : Syntax) : M Syntax := do let ref := action let r ← actionTerminalToTermCore action pure $ r.copyInfo ref def seqToTermCore (action : Syntax) (k : Syntax) : MacroM Syntax := withFreshMacroScope do if action.getKind == `Lean.Parser.Term.doDbgTrace then let msg := action[1] `(dbgTrace! $msg; $k) else if action.getKind == `Lean.Parser.Term.doAssert then let cond := action[1] `(assert! $cond; $k) else `(Bind.bind $action (fun _ => $k)) def seqToTerm (action : Syntax) (k : Syntax) : MacroM Syntax := do let r ← seqToTermCore action k pure $ r.copyInfo action def declToTermCore (decl : Syntax) (k : Syntax) : M Syntax := withFreshMacroScope do let kind := decl.getKind if kind == `Lean.Parser.Term.doLet then let letDecl := decl[2] `(let $letDecl:letDecl; $k) else if kind == `Lean.Parser.Term.doLetRec then let letRecToken := decl[0] let letRecDecls := decl[1] pure $ mkNode `Lean.Parser.Term.letrec #[letRecToken, letRecDecls, mkNullNode, k] else if kind == `Lean.Parser.Term.doLetArrow then let arg := decl[2] let ref := arg if arg.getKind == `Lean.Parser.Term.doIdDecl then let id := arg[0] let type := expandOptType ref arg[1] let doElem := arg[3] -- `doElem` must be a `doExpr action`. See `doLetArrowToCode` match isDoExpr? doElem with | some action => `(Bind.bind $action (fun ($id:ident : $type) => $k)) | none => Macro.throwErrorAt decl "unexpected kind of 'do' declaration" else Macro.throwErrorAt decl "unexpected kind of 'do' declaration" else if kind == `Lean.Parser.Term.doHave then -- The `have` term is of the form `"have " >> haveDecl >> optSemicolon termParser` let args := decl.getArgs let args := args ++ #[mkNullNode /- optional ';' -/, k] pure $ mkNode `Lean.Parser.Term.«have» args else Macro.throwErrorAt decl "unexpected kind of 'do' declaration" def declToTerm (decl : Syntax) (k : Syntax) : M Syntax := do let r ← declToTermCore decl k pure $ r.copyInfo decl def reassignToTermCore (reassign : Syntax) (k : Syntax) : MacroM Syntax := withFreshMacroScope do let kind := reassign.getKind if kind == `Lean.Parser.Term.doReassign then -- doReassign := parser! (letIdDecl <|> letPatDecl) let arg := reassign[0] if arg.getKind == `Lean.Parser.Term.letIdDecl then -- letIdDecl := parser! ident >> many (ppSpace >> bracketedBinder) >> optType >> " := " >> termParser let x := arg[0] let val := arg[4] let newVal ← `(ensureTypeOf! $x $(quote "invalid reassignment, value") $val) let arg := arg.setArg 4 newVal let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg] `(let $letDecl:letDecl; $k) else -- TODO: ensure the types did not change let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg] `(let $letDecl:letDecl; $k) else -- Note that `doReassignArrow` is expanded by `doReassignArrowToCode Macro.throwErrorAt reassign "unexpected kind of 'do' reassignment" def reassignToTerm (reassign : Syntax) (k : Syntax) : MacroM Syntax := do let r ← reassignToTermCore reassign k pure $ r.copyInfo reassign def mkIte (ref : Syntax) (optIdent : Syntax) (cond : Syntax) (thenBranch : Syntax) (elseBranch : Syntax) : MacroM Syntax := do let r ← if optIdent.isNone then `(ite $cond $thenBranch $elseBranch) else let h := optIdent[0] `(dite $cond (fun $h => $thenBranch) (fun $h => $elseBranch)) return r.copyInfo ref def mkJoinPointCore (j : Name) (ps : Array (Name × Bool)) (body : Syntax) (k : Syntax) : M Syntax := withFreshMacroScope do let ref := body let binders ← ps.mapM fun ⟨id, useTypeOf⟩ => do let type ← if useTypeOf then `(typeOf! $(mkIdentFrom ref id)) else `(_) let binderType := mkNullNode #[mkAtomFrom ref ":", type] pure $ mkNode `Lean.Parser.Term.explicitBinder #[mkAtomFrom ref "(", mkNullNode #[mkIdentFrom ref id], binderType, mkNullNode, mkAtomFrom ref ")"] let m := (← read).m let type ← `($m _) /- We use `let*` instead of `let` for joinpoints to make sure `$k` is elaborated before `$body`. By elaborating `$k` first, we "learn" more about `$body`'s type. For example, consider the following example `do` expression ``` def f (x : Nat) : IO Unit := do if x > 0 then IO.println "x is not zero" -- Error is here IO.mkRef true ``` it is expanded into ``` def f (x : Nat) : IO Unit := do let jp (u : Unit) : IO _ := IO.mkRef true; if x > 0 then IO.println "not zero" jp () else jp () ``` If we use the regular `let` instead of `let*`, the joinpoint `jp` will be elaborated and its type will be inferred to be `Unit → IO (IO.Ref Bool)`. Then, we get a typing error at `jp ()`. By using `let*`, we first elaborate `if x > 0 ...` and learn that `jp` has type `Unit → IO Unit`. Then, we get the expected type mismatch error at `IO.mkRef true`. -/ `(let* $(mkIdentFrom ref j):ident $binders:explicitBinder* : $type := $body; $k) def mkJoinPoint (j : Name) (ps : Array (Name × Bool)) (body : Syntax) (k : Syntax) : M Syntax := do let r ← mkJoinPointCore j ps body k pure $ r.copyInfo body def mkJmp (ref : Syntax) (j : Name) (args : Array Syntax) : Syntax := Syntax.mkApp (mkIdentFrom ref j) args partial def toTerm : Code → M Syntax | Code.«return» ref val => returnToTerm ref val | Code.«continue» ref => continueToTerm ref | Code.«break» ref => breakToTerm ref | Code.action e => actionTerminalToTerm e | Code.joinpoint j ps b k => do mkJoinPoint j ps (← toTerm b) (← toTerm k) | Code.jmp ref j args => pure $ mkJmp ref j args | Code.decl _ stx k => do declToTerm stx (← toTerm k) | Code.reassign _ stx k => do reassignToTerm stx (← toTerm k) | Code.seq stx k => do seqToTerm stx (← toTerm k) | Code.ite ref _ o c t e => do mkIte ref o c (← toTerm t) (← toTerm e) | Code.«match» ref discrs optType alts => do let mut termSepAlts := #[] for alt in alts do termSepAlts := termSepAlts.push $ mkAtomFrom alt.ref "|" let rhs ← toTerm alt.rhs let termAlt := mkNode `Lean.Parser.Term.matchAlt #[alt.patterns, mkAtomFrom alt.ref "=>", rhs] termSepAlts := termSepAlts.push termAlt let firstVBar := termSepAlts[0] let termSepAlts := mkNullNode termSepAlts[1:termSepAlts.size] let termMatchAlts := mkNode `Lean.Parser.Term.matchAlts #[mkNullNode #[firstVBar], termSepAlts] pure $ mkNode `Lean.Parser.Term.«match» #[mkAtomFrom ref "match", discrs, optType, mkAtomFrom ref "with", termMatchAlts] def run (code : Code) (m : Syntax) (uvars : Array Name := #[]) (kind := Kind.regular) : MacroM Syntax := do let term ← toTerm code { m := m, kind := kind, uvars := uvars } pure term /- Given - `a` is true if the code block has a `Code.action _` exit point - `r` is true if the code block has a `Code.return _ _` exit point - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point generate Kind. See comment at the beginning of the `ToTerm` namespace. -/ def mkNestedKind (a r bc : Bool) : Kind := match a, r, bc with | true, false, false => Kind.regular | false, true, false => Kind.regular | false, false, true => Kind.nestedBC | true, true, false => Kind.nestedPR | true, false, true => Kind.nestedSBC | false, true, true => Kind.nestedSBC | true, true, true => Kind.nestedPRBC | false, false, false => unreachable! def mkNestedTerm (code : Code) (m : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM Syntax := do ToTerm.run code m uvars (mkNestedKind a r bc) /- Given a term `term` produced by `ToTerm.run`, pattern match on its result. See comment at the beginning of the `ToTerm` namespace. - `a` is true if the code block has a `Code.action _` exit point - `r` is true if the code block has a `Code.return _ _` exit point - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point The result is a sequence of `doElem` -/ def matchNestedTermResult (ref : Syntax) (term : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM (List Syntax) := do let toDoElems (auxDo : Syntax) : List Syntax := getDoSeqElems (getDoSeq auxDo) let u ← mkTuple ref (uvars.map (mkIdentFrom ref)) match a, r, bc with | true, false, false => if uvars.isEmpty then toDoElems (← `(do $term:term)) else toDoElems (← `(do let r ← $term:term; $u:term := r.2; pure r.1)) | false, true, false => if uvars.isEmpty then toDoElems (← `(do let r ← $term:term; return r)) else toDoElems (← `(do let r ← $term:term; $u:term := r.2; return r.1)) | false, false, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultBC.«break» u => $u:term := u; break | DoResultBC.«continue» u => $u:term := u; continue) | true, true, false => toDoElems <$> `(do let r ← $term:term; match r with | DoResultPR.«pure» a u => $u:term := u; pure a | DoResultPR.«return» b u => $u:term := u; return b) | true, false, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultSBC.«pureReturn» a u => $u:term := u; pure a | DoResultSBC.«break» u => $u:term := u; break | DoResultSBC.«continue» u => $u:term := u; continue) | false, true, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultSBC.«pureReturn» a u => $u:term := u; return a | DoResultSBC.«break» u => $u:term := u; break | DoResultSBC.«continue» u => $u:term := u; continue) | true, true, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultPRBC.«pure» a u => $u:term := u; pure a | DoResultPRBC.«return» a u => $u:term := u; return a | DoResultPRBC.«break» u => $u:term := u; break | DoResultPRBC.«continue» u => $u:term := u; continue) | false, false, false => unreachable! end ToTerm def isMutableLet (doElem : Syntax) : Bool := let kind := doElem.getKind (kind == `Lean.Parser.Term.doLetArrow || kind == `Lean.Parser.Term.doLet) && !doElem[1].isNone namespace ToCodeBlock structure Context := (ref : Syntax) (m : Syntax) -- Syntax representing the monad associated with the do notation. (mutableVars : NameSet := {}) (insideFor : Bool := false) abbrev M := ReaderT Context TermElabM @[inline] def withNewMutableVars {α} (newVars : Array Name) (mutable : Bool) (x : M α) : M α := withReader (fun ctx => if mutable then { ctx with mutableVars := insertVars ctx.mutableVars newVars } else ctx) x def checkReassignable (xs : Array Name) : M Unit := do let throwInvalidReassignment (x : Name) : M Unit := throwError! "'{x.simpMacroScopes}' cannot be reassigned" let ctx ← read for x in xs do unless ctx.mutableVars.contains x do throwInvalidReassignment x @[inline] def withFor {α} (x : M α) : M α := withReader (fun ctx => { ctx with insideFor := true }) x structure ToForInTermResult := (uvars : Array Name) (term : Syntax) def mkForInBody (x : Syntax) (forInBody : CodeBlock) : M ToForInTermResult := do let ctx ← read let uvars := forInBody.uvars let uvars := nameSetToArray uvars let term ← liftMacroM $ ToTerm.run forInBody.code ctx.m uvars (if hasReturn forInBody.code then ToTerm.Kind.forInWithReturn else ToTerm.Kind.forIn) pure ⟨uvars, term⟩ def ensureInsideFor : M Unit := unless (← read).insideFor do throwError "invalid 'do' element, it must be inside 'for'" def ensureEOS (doElems : List Syntax) : M Unit := unless doElems.isEmpty do throwError "must be last element in a 'do' sequence" private partial def expandLiftMethodAux : Syntax → StateT (List Syntax) MacroM Syntax | stx@(Syntax.node k args) => if liftMethodDelimiter k then pure stx else if k == `Lean.Parser.Term.liftMethod then withFreshMacroScope do let term := args[1] let term ← expandLiftMethodAux term let auxDoElem ← `(doElem| let a ← $term:term) modify fun s => s ++ [auxDoElem] `(a) else do let args ← args.mapM expandLiftMethodAux pure $ Syntax.node k args | stx => pure stx def expandLiftMethod (doElem : Syntax) : MacroM (List Syntax × Syntax) := do if !hasLiftMethod doElem then pure ([], doElem) else let (doElem, doElemsNew) ← (expandLiftMethodAux doElem).run [] pure (doElemsNew, doElem) /- "Concatenate" `c` with `doSeqToCode doElems` -/ def concatWith (doSeqToCode : List Syntax → M CodeBlock) (c : CodeBlock) (doElems : List Syntax) : M CodeBlock := match doElems with | [] => pure c | nextDoElem :: _ => do let k ← doSeqToCode doElems let ref := nextDoElem liftM $ concat c ref none k def checkLetArrowRHS (doElem : Syntax) : M Unit := do let kind := doElem.getKind if kind == `Lean.Parser.Term.doLetArrow || kind == `Lean.Parser.Term.doLet || kind == `Lean.Parser.Term.doLetRec || kind == `Lean.Parser.Term.doHave || kind == `Lean.Parser.Term.doReassign || kind == `Lean.Parser.Term.doReassignArrow then throwErrorAt! doElem "invalid kind of value '{kind}' in an assignment" /- Generate `CodeBlock` for `doLetArrow; doElems` `doLetArrow` is of the form ``` "let " >> optional "mut " >> (doIdDecl <|> doPatDecl) ``` where ``` def doIdDecl := parser! ident >> optType >> leftArrow >> doElemParser def doPatDecl := parser! termParser >> leftArrow >> doElemParser >> optional (" | " >> doElemParser) ``` -/ def doLetArrowToCode (doSeqToCode : List Syntax → M CodeBlock) (doLetArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do let ref := doLetArrow let decl := doLetArrow[2] if decl.getKind == `Lean.Parser.Term.doIdDecl then let y := decl[0].getId let doElem := decl[3] let k ← withNewMutableVars #[y] (isMutableLet doLetArrow) (doSeqToCode doElems) match isDoExpr? doElem with | some action => pure $ mkVarDeclCore #[y] doLetArrow k | none => checkLetArrowRHS doElem let c ← doSeqToCode [doElem] match doElems with | [] => pure c | kRef::_ => liftM $ concat c kRef y k else if decl.getKind == `Lean.Parser.Term.doPatDecl then let pattern := decl[0] let doElem := decl[2] let optElse := decl[3] if optElse.isNone then withFreshMacroScope do let auxDo ← if isMutableLet doLetArrow then `(do let discr ← $doElem; let mut $pattern:term := discr) else `(do let discr ← $doElem; let $pattern:term := discr) doSeqToCode $ getDoSeqElems (getDoSeq auxDo) ++ doElems else if isMutableLet doLetArrow then throwError! "'mut' is currently not supported in let-decls with 'else' case" let contSeq := mkDoSeq doElems.toArray let elseSeq := mkSingletonDoSeq optElse[1] let auxDo ← `(do let discr ← $doElem; match discr with | $pattern:term => $contSeq | _ => $elseSeq) doSeqToCode $ getDoSeqElems (getDoSeq auxDo) else throwError "unexpected kind of 'do' declaration" /- Generate `CodeBlock` for `doReassignArrow; doElems` `doReassignArrow` is of the form ``` (doIdDecl <|> doPatDecl) ``` -/ def doReassignArrowToCode (doSeqToCode : List Syntax → M CodeBlock) (doReassignArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do let ref := doReassignArrow let decl := doReassignArrow[0] if decl.getKind == `Lean.Parser.Term.doIdDecl then let doElem := decl[3] let y := decl[0] let auxDo ← `(do let r ← $doElem; $y:ident := r) doSeqToCode $ getDoSeqElems (getDoSeq auxDo) ++ doElems else if decl.getKind == `Lean.Parser.Term.doPatDecl then let pattern := decl[0] let doElem := decl[2] let optElse := decl[3] if optElse.isNone then withFreshMacroScope do let auxDo ← `(do let discr ← $doElem; $pattern:term := discr) doSeqToCode $ getDoSeqElems (getDoSeq auxDo) ++ doElems else throwError "reassignment with `|` (i.e., \"else clause\") is not currently supported" else throwError "unexpected kind of 'do' reassignment" /- Generate `CodeBlock` for `doIf; doElems` `doIf` is of the form ``` "if " >> optIdent >> termParser >> " then " >> doSeq >> many (group (try (group (" else " >> " if ")) >> optIdent >> termParser >> " then " >> doSeq)) >> optional (" else " >> doSeq) ``` -/ def doIfToCode (doSeqToCode : List Syntax → M CodeBlock) (doIf : Syntax) (doElems : List Syntax) : M CodeBlock := do let view ← liftMacroM $ mkDoIfView doIf let thenBranch ← doSeqToCode (getDoSeqElems view.thenBranch) let elseBranch ← doSeqToCode (getDoSeqElems view.elseBranch) let ite ← mkIte view.ref view.optIdent view.cond thenBranch elseBranch concatWith doSeqToCode ite doElems /- Generate `CodeBlock` for `doUnless; doElems` `doUnless` is of the form ``` "unless " >> termParser >> "do " >> doSeq ``` -/ def doUnlessToCode (doSeqToCode : List Syntax → M CodeBlock) (doUnless : Syntax) (doElems : List Syntax) : M CodeBlock := do let ref := doUnless let cond := doUnless[1] let doSeq := doUnless[3] let body ← doSeqToCode (getDoSeqElems doSeq) let unlessCode ← liftMacroM $ mkUnless ref cond body concatWith doSeqToCode unlessCode doElems /- Generate `CodeBlock` for `doFor; doElems` `doFor` is of the form ``` for " >> termParser >> " in " >> termParser >> "do " >> doSeq ``` -/ def doForToCode (doSeqToCode : List Syntax → M CodeBlock) (doFor : Syntax) (doElems : List Syntax) : M CodeBlock := do let ref := doFor let x := doFor[1] let xs := doFor[3] let forElems := getDoSeqElems doFor[5] let forInBodyCodeBlock ← withFor (doSeqToCode forElems) let ⟨uvars, forInBody⟩ ← mkForInBody x forInBodyCodeBlock let uvarsTuple ← liftMacroM $ mkTuple ref (uvars.map (mkIdentFrom ref)) if hasReturn forInBodyCodeBlock.code then let forInTerm ← `($(xs).forIn (MProd.mk none $uvarsTuple) fun $x (MProd.mk _ $uvarsTuple) => $forInBody) let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r.2; match r.1 with | none => Pure.pure (ensureExpectedType! "type mismatch, 'for'" PUnit.unit) | some a => return ensureExpectedType! "type mismatch, 'for'" a) doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems) else let forInTerm ← `($(xs).forIn $uvarsTuple fun $x $uvarsTuple => $forInBody) if doElems.isEmpty then let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r; Pure.pure (ensureExpectedType! "type mismatch, 'for'" PUnit.unit)) doSeqToCode $ getDoSeqElems (getDoSeq auxDo) else let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r) doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems) /-- Generate `CodeBlock` for `doMatch; doElems` ``` def doMatchAlt := sepBy1 termParser ", " >> darrow >> doSeq def doMatchAlts := parser! optional "| " >> sepBy1 doMatchAlt "|" def doMatch := parser! "match " >> sepBy1 matchDiscr ", " >> optType >> " with " >> doMatchAlts ``` -/ def doMatchToCode (doSeqToCode : List Syntax → M CodeBlock) (doMatch : Syntax) (doElems: List Syntax) : M CodeBlock := do let ref := doMatch let discrs := doMatch[1] let optType := doMatch[2] let matchAlts := doMatch[4][1].getSepArgs -- Array of `doMatchAlt` let alts ← matchAlts.mapM fun matchAlt => do let patterns := matchAlt[0] let pvars ← getPatternsVars patterns.getSepArgs let vars := getPatternVarNames pvars let rhs := matchAlt[2] let rhs ← doSeqToCode (getDoSeqElems rhs) pure { ref := matchAlt, vars := vars, patterns := patterns, rhs := rhs : Alt CodeBlock } let matchCode ← mkMatch ref discrs optType alts concatWith doSeqToCode matchCode doElems structure Catch := (x : Syntax) (optType : Syntax) (codeBlock : CodeBlock) def getTryCatchUpdatedVars (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) : NameSet := let ws := tryCode.uvars let ws := catches.foldl (fun ws alt => union alt.codeBlock.uvars ws) ws let ws := match finallyCode? with | none => ws | some c => union c.uvars ws ws def tryCatchPred (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) (p : Code → Bool) : Bool := p tryCode.code || catches.any (fun «catch» => p «catch».codeBlock.code) || match finallyCode? with | none => false | some finallyCode => p finallyCode.code /-- Generate `CodeBlock` for `doTry; doElems` ``` def doTry := parser! "try " >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally def doCatch := parser! "catch " >> binderIdent >> optional (":" >> termParser) >> darrow >> doSeq def doCatchMatch := parser! "catch " >> doMatchAlts def doFinally := parser! "finally " >> doSeq ``` -/ def doTryToCode (doSeqToCode : List Syntax → M CodeBlock) (doTry : Syntax) (doElems: List Syntax) : M CodeBlock := do let ref := doTry let tryCode ← doSeqToCode (getDoSeqElems doTry[1]) let optFinally := doTry[3] let catches ← doTry[2].getArgs.mapM fun catchStx => do if catchStx.getKind == `Lean.Parser.Term.doCatch then let x := catchStx[1] let optType := catchStx[2] let c ← doSeqToCode (getDoSeqElems catchStx[4]) pure { x := x, optType := optType, codeBlock := c : Catch } else if catchStx.getKind == `Lean.Parser.Term.doCatchMatch then let matchAlts := catchStx[1] let x ← `(ex) let auxDo ← `(do match ex with $matchAlts) let c ← doSeqToCode (getDoSeqElems (getDoSeq auxDo)) pure { x := x, codeBlock := c, optType := mkNullNode : Catch } else throwError "unexpected kind of 'catch'" let finallyCode? ← if optFinally.isNone then pure none else some <$> doSeqToCode (getDoSeqElems optFinally[0][1]) if catches.isEmpty && finallyCode?.isNone then throwError "invalid 'try', it must have a 'catch' or 'finally'" let ctx ← read let ws := getTryCatchUpdatedVars tryCode catches finallyCode? let uvars := nameSetToArray ws let a := tryCatchPred tryCode catches finallyCode? hasTerminalAction let r := tryCatchPred tryCode catches finallyCode? hasReturn let bc := tryCatchPred tryCode catches finallyCode? hasBreakContinue let toTerm (codeBlock : CodeBlock) : M Syntax := do let codeBlock ← liftM $ extendUpdatedVars codeBlock ws liftMacroM $ ToTerm.mkNestedTerm codeBlock.code ctx.m uvars a r bc let term ← toTerm tryCode let term ← catches.foldlM (fun term «catch» => do let catchTerm ← toTerm «catch».codeBlock if catch.optType.isNone then `(MonadExcept.tryCatch $term (fun $(«catch».x):ident => $catchTerm)) else let type := «catch».optType[1] `(tryCatchThe $type $term (fun $(«catch».x):ident => $catchTerm))) term let term ← match finallyCode? with | none => pure term | some finallyCode => withRef optFinally do unless finallyCode.uvars.isEmpty do throwError "'finally' currently does not support reassignments" if hasBreakContinueReturn finallyCode.code then throwError "'finally' currently does 'return', 'break', nor 'continue'" let finallyTerm ← liftMacroM $ ToTerm.run finallyCode.code ctx.m {} ToTerm.Kind.regular `(tryFinally $term $finallyTerm) let doElemsNew ← liftMacroM $ ToTerm.matchNestedTermResult ref term uvars a r bc doSeqToCode (doElemsNew ++ doElems) /- Generate `CodeBlock` for `doReturn` which is of the form ``` "return " >> optional termParser ``` `doElems` is only used for sanity checking. -/ def doReturnToCode (doReturn : Syntax) (doElems: List Syntax) : M CodeBlock := do let ref := doReturn ensureEOS doElems let argOpt := doReturn[1] let arg ← if argOpt.isNone then liftMacroM $ mkUnit ref else pure argOpt[0] pure $ mkReturn ref arg partial def doSeqToCode : List Syntax → M CodeBlock | [] => do let ctx ← read; liftMacroM $ mkPureUnitAction ctx.ref | doElem::doElems => withRef doElem do match (← liftMacroM $ expandMacro? doElem) with | some doElem => doSeqToCode (doElem::doElems) | none => match (← liftMacroM $ expandDoIf? doElem) with | some doElem => doSeqToCode (doElem::doElems) | none => let (liftedDoElems, doElem) ← liftM (liftMacroM $ expandLiftMethod doElem : TermElabM _) if !liftedDoElems.isEmpty then doSeqToCode (liftedDoElems ++ [doElem] ++ doElems) else let ref := doElem let concatWithRest (c : CodeBlock) : M CodeBlock := concatWith doSeqToCode c doElems let k := doElem.getKind if k == `Lean.Parser.Term.doLet then let vars ← getDoLetVars doElem mkVarDeclCore vars doElem <$> withNewMutableVars vars (isMutableLet doElem) (doSeqToCode doElems) else if k == `Lean.Parser.Term.doHave then let var := getDoHaveVar doElem mkVarDeclCore #[var] doElem <$> (doSeqToCode doElems) else if k == `Lean.Parser.Term.doLetRec then let vars ← getDoLetRecVars doElem mkVarDeclCore vars doElem <$> (doSeqToCode doElems) else if k == `Lean.Parser.Term.doReassign then let vars ← liftM $ getDoReassignVars doElem checkReassignable vars let k ← doSeqToCode doElems mkReassignCore vars doElem k else if k == `Lean.Parser.Term.doLetArrow then doLetArrowToCode doSeqToCode doElem doElems else if k == `Lean.Parser.Term.doReassignArrow then doReassignArrowToCode doSeqToCode doElem doElems else if k == `Lean.Parser.Term.doIf then doIfToCode doSeqToCode doElem doElems else if k == `Lean.Parser.Term.doUnless then doUnlessToCode doSeqToCode doElem doElems else if k == `Lean.Parser.Term.doFor then withFreshMacroScope do doForToCode doSeqToCode doElem doElems else if k == `Lean.Parser.Term.doMatch then doMatchToCode doSeqToCode doElem doElems else if k == `Lean.Parser.Term.doTry then doTryToCode doSeqToCode doElem doElems else if k == `Lean.Parser.Term.doBreak then ensureInsideFor ensureEOS doElems pure $ mkBreak ref else if k == `Lean.Parser.Term.doContinue then ensureInsideFor ensureEOS doElems pure $ mkContinue ref else if k == `Lean.Parser.Term.doReturn then doReturnToCode doElem doElems else if k == `Lean.Parser.Term.doDbgTrace then mkSeq doElem <$> doSeqToCode doElems else if k == `Lean.Parser.Term.doAssert then mkSeq doElem <$> doSeqToCode doElems else if k == `Lean.Parser.Term.doNested then let nestedDoSeq := doElem[1] doSeqToCode (getDoSeqElems nestedDoSeq ++ doElems) else if k == `Lean.Parser.Term.doExpr then let term := doElem[0] if doElems.isEmpty then pure $ mkTerminalAction term else mkSeq term <$> doSeqToCode doElems else throwError! "unexpected do-element\n{doElem}" def run (doStx : Syntax) (m : Syntax) : TermElabM CodeBlock := (doSeqToCode $ getDoSeqElems $ getDoSeq doStx).run { ref := doStx, m := m } end ToCodeBlock /- Create a synthetic metavariable `?m` and assign `m` to it. We use `?m` to refer to `m` when expanding the `do` notation. -/ private def mkMonadAlias (m : Expr) : TermElabM Syntax := do let result ← `(?m) let mType ← inferType m let mvar ← elabTerm result mType assignExprMVar mvar.mvarId! m pure result @[builtinTermElab «do»] def elabDo : TermElab := fun stx expectedType? => do tryPostponeIfNoneOrMVar expectedType? let bindInfo ← extractBind expectedType? let m ← mkMonadAlias bindInfo.m let codeBlock ← ToCodeBlock.run stx m let stxNew ← liftMacroM $ ToTerm.run codeBlock.code m trace[Elab.do]! stxNew withMacroExpansion stx stxNew $ elabTermEnsuringType stxNew bindInfo.expectedType end Do builtin_initialize registerTraceClass `Elab.do private def toDoElem (newKind : SyntaxNodeKind) : Macro := fun stx => do let stx := stx.setKind newKind let stxNew ← `(do $stx:doElem) return stxNew.copyInfo stx @[builtinMacro Lean.Parser.Term.termFor] def expandTermFor : Macro := toDoElem `Lean.Parser.Term.doFor @[builtinMacro Lean.Parser.Term.termTry] def expandTermTry : Macro := toDoElem `Lean.Parser.Term.doTry @[builtinMacro Lean.Parser.Term.termUnless] def expandTermUnless : Macro := toDoElem `Lean.Parser.Term.doUnless @[builtinMacro Lean.Parser.Term.termReturn] def expandTermReturn : Macro := toDoElem `Lean.Parser.Term.doReturn end Term end Elab end Lean
6870aef6060b24620f4f3d4b28b44718a5562c6d
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/combinatorics/simple_graph/acyclic.lean
746d6a3f2086aec5f2f7539f6904a019854b6b91
[ "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
4,742
lean
/- Copyright (c) 2022 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import combinatorics.simple_graph.connectivity /-! # Acyclic graphs and trees This module introduces *acyclic graphs* (a.k.a. *forests*) and *trees*. ## Main definitions * `simple_graph.is_acyclic` is a predicate for a graph having no cyclic walks * `simple_graph.is_tree` is a predicate for a graph being a tree (a connected acyclic graph) ## Main statements * `simple_graph.is_acyclic_iff_path_unique` characterizes acyclicity in terms of uniqueness of paths between pairs of vertices. * `simple_graph.is_acyclic_iff_forall_edge_is_bridge` characterizes acyclicity in terms of every edge being a bridge edge. * `simple_graph.is_tree_iff_exists_unique_path` characterizes trees in terms of existence and uniqueness of paths between pairs of vertices from a nonempty vertex type. ## References The structure of the proofs for `simple_graph.is_acyclic` and `simple_graph.is_tree`, including supporting lemmas about `simple_graph.is_bridge`, generally follows the high-level description for these theorems for multigraphs from [Chou1994]. ## Tags acyclic graphs, trees -/ universes u v namespace simple_graph variables {V : Type u} (G : simple_graph V) /-- A graph is *acyclic* (or a *forest*) if it has no cycles. -/ def is_acyclic : Prop := ∀ (v : V) (c : G.walk v v), ¬c.is_cycle /-- A *tree* is a connected acyclic graph. -/ @[mk_iff, protect_proj] structure is_tree : Prop := (is_connected : G.connected) (is_acyclic : G.is_acyclic) variables {G} lemma is_acyclic_iff_forall_adj_is_bridge : G.is_acyclic ↔ ∀ ⦃v w : V⦄, G.adj v w → G.is_bridge ⟦(v, w)⟧ := begin simp_rw [is_bridge_iff_adj_and_forall_cycle_not_mem], split, { intros ha v w hvw, apply and.intro hvw, intros u p hp, exact absurd hp (ha _ p), }, { rintros hb v (_ | @⟨_, _, _, ha, p⟩) hp, { exact hp.not_of_nil }, { specialize hb ha, apply hb.2 _ hp, rw [walk.edges_cons], apply list.mem_cons_self } }, end lemma is_acyclic_iff_forall_edge_is_bridge : G.is_acyclic ↔ ∀ ⦃e⦄, e ∈ G.edge_set → G.is_bridge e := by simp [is_acyclic_iff_forall_adj_is_bridge, sym2.forall] lemma is_acyclic.path_unique {G : simple_graph V} (h : G.is_acyclic) {v w : V} (p q : G.path v w) : p = q := begin obtain ⟨p, hp⟩ := p, obtain ⟨q, hq⟩ := q, simp only, induction p with u pu pv pw ph p ih generalizing q, { rw walk.is_path_iff_eq_nil at hq, exact hq.symm, }, { rw is_acyclic_iff_forall_adj_is_bridge at h, specialize h ph, rw is_bridge_iff_adj_and_forall_walk_mem_edges at h, replace h := h.2 (q.append p.reverse), simp only [walk.edges_append, walk.edges_reverse, list.mem_append, list.mem_reverse] at h, cases h, { cases q, { simpa [walk.is_path_def] using hp }, { rw walk.cons_is_path_iff at hp hq, simp only [walk.edges_cons, list.mem_cons_iff, sym2.eq_iff] at h, obtain (⟨h,rfl⟩ | ⟨rfl,rfl⟩) | h := h, { rw [ih hp.1 _ hq.1] }, { simpa using hq }, { exact absurd (walk.fst_mem_support_of_mem_edges _ h) hq.2 } } }, { rw walk.cons_is_path_iff at hp, exact absurd (walk.fst_mem_support_of_mem_edges _ h) hp.2 } } end lemma is_acyclic_of_path_unique (h : ∀ (v w : V) (p q : G.path v w), p = q) : G.is_acyclic := begin intros v c hc, simp only [walk.is_cycle_def, ne.def] at hc, cases c, { exact absurd rfl hc.2.1 }, { simp only [walk.cons_is_trail_iff, not_false_iff, walk.support_cons, list.tail_cons, true_and] at hc, specialize h _ _ ⟨c_p, by simp only [walk.is_path_def, hc.2]⟩ (path.singleton (G.symm c_h)), simp only [path.singleton] at h, simpa [-quotient.eq, sym2.eq_swap, h] using hc }, end lemma is_acyclic_iff_path_unique : G.is_acyclic ↔ ∀ ⦃v w : V⦄ (p q : G.path v w), p = q := ⟨is_acyclic.path_unique, is_acyclic_of_path_unique⟩ lemma is_tree_iff_exists_unique_path : G.is_tree ↔ nonempty V ∧ ∀ (v w : V), ∃! (p : G.walk v w), p.is_path := begin classical, rw [is_tree_iff, is_acyclic_iff_path_unique], split, { rintro ⟨hc, hu⟩, refine ⟨hc.nonempty, _⟩, intros v w, let q := (hc v w).some.to_path, use q, simp only [true_and, path.is_path], intros p hp, specialize hu ⟨p, hp⟩ q, exact subtype.ext_iff.mp hu, }, { unfreezingI { rintro ⟨hV, h⟩ }, refine ⟨connected.mk _, _⟩, { intros v w, obtain ⟨p, hp⟩ := h v w, exact p.reachable, }, { rintros v w ⟨p, hp⟩ ⟨q, hq⟩, simp only [unique_of_exists_unique (h v w) hp hq] } }, end end simple_graph
4c69bbc3e520c411713ed87bf7ddacca97558a97
8c02fed42525b65813b55c064afe2484758d6d09
/src/spec/initialstate.lean
6045322d8b4fe5ba72ca818e97a7be690eecc58a
[ "LicenseRef-scancode-generic-cla", "MIT" ]
permissive
microsoft/AliveInLean
3eac351a34154efedd3ffc4fe2fa4ec01b219e0d
4b739dd6e4266b26a045613849df221374119871
refs/heads/master
1,691,419,737,939
1,689,365,567,000
1,689,365,568,000
131,156,103
23
18
NOASSERTION
1,660,342,040,000
1,524,747,538,000
Lean
UTF-8
Lean
false
false
12,639
lean
-- Copyright (c) Microsoft Corporation. All rights reserved. -- Licensed under the MIT license. import ..smtexpr import ..smtcompile import ..bitvector import .spec import .lemmas import .lemmas_basic import .irstate import .freevar import .equiv import .closed import smt2.syntax import system.io import init.meta.tactic import init.meta.interactive namespace spec open irsem open freevar -- get_free_*_name lemma get_free_name_diff: ∀ n, get_free_sbitvec_name n ≠ get_free_sbool_name n := begin intros, intros H, unfold get_free_sbitvec_name at H, unfold get_free_sbool_name at H, rw string.eq_list at H, rw string.append_to_list at H, rw string.append_to_list at H, have H' := list.append_eq2 H, cases H' end lemma closed_regfile_apply_add_b_bv: ∀ (rf:regfile irsem_smt) (η:freevar.env) vname vz bname vb (HC:closed_regfile (rf.apply_to_values irsem_smt (env.replace_valty η))), closed_regfile (rf.apply_to_values irsem_smt (env.replace_valty ((η.add_bv vname vz).add_b bname vb))) := begin intros, revert HC, apply regfile.induction rf, { unfold closed_regfile, intros, rw regfile.empty_apply_empty, apply closed_regfile_empty }, { intros rf IH, intros, unfold closed_regfile, intros, rw regfile.apply_update_comm at HC, rw regfile.apply_update_comm, unfold closed_regfile at IH, rw closed_regfile_update_split at HC, cases HC with HC HCval, have HC := IH HC, rw closed_regfile_update_split, split, { assumption }, { cases v, unfold freevar.env.replace_valty at HCval, rw closed_ival_split at HCval, cases HCval with HCval1 HCval2, unfold freevar.env.replace_valty, rw closed_ival_split, split, { have H := closed_b_add_bv vname vz HCval1, have H := closed_b_add_b bname vb H, assumption }, { have H := closed_bv_add_bv vname vz HCval2, have H := closed_bv_add_b bname vb H, assumption } } } end lemma regfile_update_ival_closed: ∀ rf rf' (η:freevar.env) regn sz vn pn bvn p (HCRF: closed_regfile (regfile.apply_to_values irsem_smt rf (env.replace_valty η))) (HRF': rf' = regfile.update irsem_smt rf regn (valty.ival sz (sbitvec.var sz vn) (sbool.var pn))), closed_regfile (regfile.apply_to_values irsem_smt rf' (env.replace_valty (env.add_b (env.add_bv η vn bvn) pn p))) := begin intros, have H1 : closed_regfile (regfile.apply_to_values irsem_smt rf (env.replace_valty (env.add_b (env.add_bv η vn bvn) pn p))), { apply closed_regfile_apply_add_b_bv, assumption }, have H2 : closed_valty ((env.add_b (env.add_bv η vn bvn) pn p) ⟦valty.ival sz (sbitvec.var sz vn) (sbool.var pn)⟧), { apply ival_closed }, rw HRF', rw regfile.apply_update_comm, rw closed_regfile_update_split, split, assumption, assumption end lemma updatereg_closed: ∀ (ss ss':irstate_smt) (η:freevar.env) regn sz vn pn bvn p (HC:closed_irstate (η⟦ss⟧)) (HNOTIN1: vn ∉ η) (HNOTIN2: pn ∉ η) (HNOTEQ: vn ≠ pn) (HS:ss' = irstate.updatereg irsem_smt ss regn (irsem.valty.ival sz (sbitvec.var sz vn) (sbool.var pn))), closed_irstate (((η.add_bv vn bvn).add_b pn p)⟦ss'⟧) := begin intros, cases ss with sub srf, cases ss' with sub' srf', unfold freevar.env.replace at *, rw ← irstate.setub_apply_to_values at *, unfold irstate.getub at *, simp at *, unfold irstate.setub at *, unfold irstate.apply_to_values at *, rw closed_irstate_split, rw closed_irstate_split at HC, cases HC with HCUB HCRF, unfold irstate.updatereg at HS, simp at *, cases HS with h_1 h_2, subst h_1, split, { have H0: closed_b ((env.add_bv η vn bvn)⟦sub'⟧), { apply closed_b_add_bv, apply HCUB }, apply closed_b_add_b, { assumption } }, { apply regfile_update_ival_closed, assumption, assumption } end -- encode -- Note that `irstate_equiv η⟦iss⟧ ise` does not imply -- closed_irstate η⟦iss⟧. It is because, for example, -- `b_equiv (sbool.and (sbool.var _) (sbool.ff)) ff` holds. -- Then why `encode iss ise` is needed? -> encode is -- the only way to relate ise and iss. lemma init_var_encode_intty: ∀ ise iss ise' iss' (sg sg':std_gen) η n t (HENC: encode iss ise η) (HCLOSED: closed_irstate (η⟦iss⟧)) (HNOTIN1: get_free_sbitvec_name n ∉ η) (HNOTIN2: get_free_sbool_name n ∉ η) (HIE:(ise', sg') = create_init_var_exec n t (ise, sg)) (HIS:iss' = create_init_var_smt n t iss), ∃ η', (encode iss' ise' η' ∧ closed_irstate (η'⟦iss'⟧) ∧ env.added2 η (get_free_sbitvec_name n) (get_free_sbool_name n) η') := begin intros, unfold create_init_var_smt at HIS, simp at HIS, unfold create_init_var_exec at HIE, simp at HIE, generalize Hrbv':(get_rand_bv (get_sz_from_ty t) sg) = rbv', cases rbv' with rbv' sg'', rw Hrbv' at *, unfold create_init_var_exec._match_2 at HIE, generalize Hrb':(get_rand_bool sg'') = rb', cases rb' with rb' sg''', rw Hrb' at *, unfold create_init_var_exec._match_1 at HIE, injection HIE with HIE HIE_sg, simp at HIE, existsi ((η.add_b (get_free_sbool_name n) rb') .add_bv (get_free_sbitvec_name n) rbv'.to_int), split, { unfold encode, rw HIS, rw replace_updatereg, rw HIE, rw env.not_in_add_bv_irstate_comm, rw env.not_in_add_b_irstate_comm, rw HCLOSED, rw HCLOSED, rw env.not_in_add_bv_valty_comm, rw env.not_in_add_b_valty_comm, unfold freevar.env.replace_valty, -- making value.. unfold get_free_sbitvec, rw env.not_in_replace_sbv, rw env.add_b_replace_sbv, rw env.empty_replace_sbv, rw env.add_bv_replace_match, -- making poison.. unfold get_free_sbool, rw env.not_in_replace_sb, rw env.add_b_replace_match, rw env.replace_sb_of_bool, apply irstate.updatereg_equiv, { intros, cases rb', { -- poison apply val_equiv.poison_intty, { constructor, constructor }, { refl }, { refl } }, { apply val_equiv.concrete_intty, { constructor, constructor }, { cases rbv', rw sbitvec_of_int_const, constructor }, { refl } } }, { rw sbitvec_of_int_const, unfold equals_size, simp }, { apply HENC }, any_goals { assumption }, any_goals { apply env.not_in_add_b, apply get_free_name_diff, assumption }, }, split, { unfold closed_irstate, intros, rw HIS, rw replace_updatereg, rw env.not_in_add_bv_irstate_comm, rw env.not_in_add_b_irstate_comm, rw HCLOSED, rw HCLOSED, rw env.not_in_add_bv_valty_comm, rw env.not_in_add_b_valty_comm, unfold freevar.env.replace_valty, -- making value.. unfold get_free_sbitvec, rw env.not_in_replace_sbv, rw env.add_b_replace_sbv, rw env.empty_replace_sbv, rw env.add_bv_replace_match, -- making poison.. unfold get_free_sbool, rw env.not_in_replace_sb, rw env.add_b_replace_match, rw env.replace_sb_of_bool, rw replace_updatereg, unfold freevar.env.replace_valty, rw env.replace_sbv_of_int, rw env.replace_sb_of_bool, rw HCLOSED, any_goals { assumption }, apply env.not_in_add_b, apply get_free_name_diff, assumption, apply env.not_in_add_b, apply get_free_name_diff, assumption }, { unfold env.added2, split, { intros n_1 H1 H2, cases H2, apply env.not_in_add_bv, assumption, apply env.not_in_add_b, assumption, rw env.not_in_split at H1, rw env.not_in_split, assumption }, { intros n_1 H, unfold env.add_b, unfold env.add_bv, unfold has_mem.mem, simp, cases H, { rw if_neg, rw if_neg, unfold has_mem.mem at H, cases H, left, assumption, right, assumption, intros H', rw H' at H, apply HNOTIN1, assumption, intros H', rw H' at H, apply HNOTIN2, assumption, }, { cases H, { right, rw if_pos, intros H0, cases H0, assumption }, { left, rw if_pos, intros H0, cases H0, assumption } } } } end def fv_smt_names (fvnames:list string) := fvnames.map get_free_sbitvec_name ++ fvnames.map get_free_sbool_name lemma init_state_encode_strong: ∀ (freevars:list (string × ty)) (sg sg':std_gen) ise iss (HUNQ: list.unique $ freevars.map prod.fst) (HIE:(ise, sg') = create_init_state_exec freevars sg) (HIS:iss = create_init_state_smt freevars), ∃ η, (encode iss ise η ∧ closed_irstate (η⟦iss⟧) ∧ env.has_only η (fv_smt_names $ freevars.map prod.fst)) := begin intros, revert ise iss sg sg', induction freevars, { intros, unfold create_init_state_exec at HIE, unfold create_init_state_smt at HIS, simp at HIE,simp at HIS, cases HIE with HIE _, rw [HIS, HIE], existsi (freevar.env.empty), unfold encode, rw empty_replace_st, constructor, constructor, constructor, any_goals { constructor }, { apply closed_irstate_empty }, { unfold fv_smt_names, simp, unfold env.has_only, intros, split, { intros H, cases H }, { intros H, have H := (env.not_in_empty name) H, cases H } } }, { intros, rename freevars_tl tl, cases freevars_hd with vname vty, have HEtmp: ∀ h t, create_init_state_exec (h::t) sg = create_init_var_exec h.1 h.2 (create_init_state_exec t sg), { intros, refl }, rw HEtmp at HIE, clear HEtmp, have HStmp: ∀ h t, create_init_state_smt (h::t) = create_init_var_smt h.1 h.2 (create_init_state_smt t), { intros, refl }, rw HStmp at HIS, clear HStmp, generalize HE0: create_init_state_exec tl sg = ise_sg0, generalize HS0: create_init_state_smt tl = iss0, rw HE0 at *, rw HS0 at *, cases ise_sg0 with ise0 sg0, simp at HIE HIS, have HEX: (∃ (η0 : env), encode iss0 ise0 η0 ∧ closed_irstate (η0⟦iss0⟧) ∧ env.has_only η0 (fv_smt_names $ tl.map prod.fst)), { apply freevars_ih, { simp at HUNQ, cases HUNQ, assumption }, apply (eq.symm HE0), refl }, cases HEX with η0 HEX, cases HEX with HEX1 HEX2, cases HEX2 with HEX2 HEX3, -- Now add a new variable to each irstate have HUPDATED: ∃ η', (encode iss ise η' ∧ closed_irstate (η'⟦iss⟧) ∧ env.added2 η0 (get_free_sbitvec_name vname) (get_free_sbool_name vname) η'), { apply init_var_encode_intty, apply HEX1, apply HEX2, { -- get_free_sbitvec_name vname ∉ η0 simp at HUNQ, cases HUNQ, apply env.has_only_not_in, { apply HEX3 }, { unfold fv_smt_names, unfold get_free_sbitvec_name, apply list.not_mem_append, apply slist_prefix_notin, assumption, apply slist_prefix_notin2 "v_" "b_" 'v' 'b', assumption, { intros H0, cases H0 }, refl, refl } }, { -- get_free_sbool_name vname ∉ η0 simp at HUNQ, cases HUNQ, apply env.has_only_not_in, { apply HEX3 }, { unfold fv_smt_names, unfold get_free_sbool_name, apply list.not_mem_append, apply slist_prefix_notin2 "b_" "v_" 'b' 'v', assumption, { intros H0, cases H0 }, refl, refl, apply slist_prefix_notin, assumption, } }, assumption, assumption }, cases HUPDATED with η HUPDATED, cases HUPDATED with HUPDATED Htmp, -- env.has_only_added2 (Honly) (Hadd2) cases Htmp with HUPDATED2 HUPDATED3, have Hη := env.has_only_added2 HEX3 HUPDATED3, existsi η, split, assumption, split, assumption, { unfold fv_smt_names, simp, unfold fv_smt_names at Hη, simp at Hη, rw ← list.cons_append, rw ← env.has_only_shuffle (get_free_sbool_name vname), simp, rw env.has_only_shuffle2, apply Hη } } end theorem init_state_encode_prf: init_state_encode := begin unfold init_state_encode, intros, have H := init_state_encode_strong freevars sg sg' ise iss HUNQ HIE HIS, cases H with η H, cases H, existsi η, assumption end -- Future work: theorem that `freevars.get` correctly returns all -- free variables. end spec
637d75f6fb06b43428d58863f9dc0def1d2be6eb
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/qpf/multivariate/constructions/sigma.lean
08b97bc1a285a66e843219241de5a9770191bfe6
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
3,030
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import data.pfunctor.multivariate.basic import data.qpf.multivariate.basic /-! # Dependent product and sum of QPFs are QPFs -/ universes u namespace mvqpf open_locale mvfunctor variables {n : ℕ} {A : Type u} variables (F : A → typevec.{u} n → Type u) /-- Dependent sum of of an `n`-ary functor. The sum can range over data types like `ℕ` or over `Type.{u-1}` -/ def sigma (v : typevec.{u} n) : Type.{u} := Σ α : A, F α v /-- Dependent product of of an `n`-ary functor. The sum can range over data types like `ℕ` or over `Type.{u-1}` -/ def pi (v : typevec.{u} n) : Type.{u} := Π α : A, F α v instance sigma.inhabited {α} [inhabited A] [inhabited (F default α)] : inhabited (sigma F α) := ⟨⟨default, default⟩⟩ instance pi.inhabited {α} [Π a, inhabited (F a α)] : inhabited (pi F α) := ⟨λ a, default⟩ variables [Π α, mvfunctor $ F α] namespace sigma instance : mvfunctor (sigma F) := { map := λ α β f ⟨a,x⟩, ⟨a,f <$$> x⟩ } variables [Π α, mvqpf $ F α] /-- polynomial functor representation of a dependent sum -/ protected def P : mvpfunctor n := ⟨ Σ a, (P (F a)).A, λ x, (P (F x.1)).B x.2 ⟩ /-- abstraction function for dependent sums -/ protected def abs ⦃α⦄ : (sigma.P F).obj α → sigma F α | ⟨a,f⟩ := ⟨ a.1, mvqpf.abs ⟨a.2, f⟩ ⟩ /-- representation function for dependent sums -/ protected def repr ⦃α⦄ : sigma F α → (sigma.P F).obj α | ⟨a,f⟩ := let x := mvqpf.repr f in ⟨ ⟨a,x.1⟩, x.2 ⟩ instance : mvqpf (sigma F) := { P := sigma.P F, abs := sigma.abs F, repr := sigma.repr F, abs_repr := by rintros α ⟨x,f⟩; simp [sigma.repr,sigma.abs,abs_repr], abs_map := by rintros α β f ⟨x,g⟩; simp [sigma.abs,mvpfunctor.map_eq]; simp [(<$$>),mvfunctor._match_1,← abs_map,← mvpfunctor.map_eq] } end sigma namespace pi instance : mvfunctor (pi F) := { map := λ α β f x a, f <$$> x a } variables [Π α, mvqpf $ F α] /-- polynomial functor representation of a dependent product -/ protected def P : mvpfunctor n := ⟨ Π a, (P (F a)).A, λ x i, Σ a : A, (P (F a)).B (x a) i ⟩ /-- abstraction function for dependent products -/ protected def abs ⦃α⦄ : (pi.P F).obj α → pi F α | ⟨a,f⟩ := λ x, mvqpf.abs ⟨a x, λ i y, f i ⟨_,y⟩⟩ /-- representation function for dependent products -/ protected def repr ⦃α⦄ : pi F α → (pi.P F).obj α | f := ⟨ λ a, (mvqpf.repr (f a)).1, λ i a, (@mvqpf.repr _ _ _ (_inst_2 _) _ (f _)).2 _ a.2 ⟩ instance : mvqpf (pi F) := { P := pi.P F, abs := pi.abs F, repr := pi.repr F, abs_repr := by rintros α f; ext; simp [pi.repr,pi.abs,abs_repr], abs_map := by rintros α β f ⟨x,g⟩; simp only [pi.abs, mvpfunctor.map_eq]; ext; simp only [(<$$>)]; simp only [←abs_map, mvpfunctor.map_eq]; refl } end pi end mvqpf
bcfec9a52d8c10753b114335a62a8bfb40729575
66a6486e19b71391cc438afee5f081a4257564ec
/algebra/left_module.hlean
cdc293f59565614cc58f94397a085b830138460f
[ "Apache-2.0" ]
permissive
spiceghello/Spectral
c8ccd1e32d4b6a9132ccee20fcba44b477cd0331
20023aa3de27c22ab9f9b4a177f5a1efdec2b19f
refs/heads/master
1,611,263,374,078
1,523,349,717,000
1,523,349,717,000
92,312,239
0
0
null
1,495,642,470,000
1,495,642,470,000
null
UTF-8
Lean
false
false
20,316
hlean
/- Copyright (c) 2015 Nathaniel Thomas. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Floris van Doorn Modules prod vector spaces over a ring. (We use "left_module," which is more precise, because "module" is a keyword.) -/ import algebra.field ..move_to_lib .exactness algebra.group_power open is_trunc pointed function sigma eq algebra prod is_equiv equiv group structure has_scalar [class] (F V : Type) := (smul : F → V → V) infixl ` • `:73 := has_scalar.smul /- modules over a ring -/ namespace left_module structure left_module (R M : Type) [ringR : ring R] extends has_scalar R M, ab_group M renaming mul → add mul_assoc → add_assoc one → zero one_mul → zero_add mul_one → add_zero inv → neg mul_left_inv → add_left_inv mul_comm → add_comm := (smul_left_distrib : Π (r : R) (x y : M), smul r (add x y) = (add (smul r x) (smul r y))) (smul_right_distrib : Π (r s : R) (x : M), smul (ring.add _ r s) x = (add (smul r x) (smul s x))) (mul_smul : Π r s x, smul (mul r s) x = smul r (smul s x)) (one_smul : Π x, smul one x = x) /- we make it a class now (and not as part of the structure) to avoid left_module.to_ab_group to be an instance -/ attribute left_module [class] definition add_ab_group_of_left_module [reducible] [trans_instance] (R M : Type) [K : ring R] [H : left_module R M] : add_ab_group M := @left_module.to_ab_group R M K H definition has_scalar_of_left_module [reducible] [trans_instance] (R M : Type) [K : ring R] [H : left_module R M] : has_scalar R M := @left_module.to_has_scalar R M K H section left_module variables {R M : Type} variable [ringR : ring R] variable [moduleRM : left_module R M] include ringR moduleRM -- Note: the anonymous include does not work in the propositions below. proposition smul_left_distrib (a : R) (u v : M) : a • (u + v) = a • u + a • v := !left_module.smul_left_distrib proposition smul_right_distrib (a b : R) (u : M) : (a + b) • u = a • u + b • u := !left_module.smul_right_distrib proposition mul_smul (a : R) (b : R) (u : M) : (a * b) • u = a • (b • u) := !left_module.mul_smul proposition one_smul (u : M) : (1 : R) • u = u := !left_module.one_smul proposition zero_smul (u : M) : (0 : R) • u = 0 := have (0 : R) • u + 0 • u = 0 • u + 0, by rewrite [-smul_right_distrib, *add_zero], !add.left_cancel this proposition smul_zero (a : R) : a • (0 : M) = 0 := have a • (0:M) + a • 0 = a • 0 + 0, by rewrite [-smul_left_distrib, *add_zero], !add.left_cancel this proposition neg_smul (a : R) (u : M) : (-a) • u = - (a • u) := eq_neg_of_add_eq_zero (by rewrite [-smul_right_distrib, add.left_inv, zero_smul]) proposition neg_one_smul (u : M) : -(1 : R) • u = -u := by rewrite [neg_smul, one_smul] proposition smul_neg (a : R) (u : M) : a • (-u) = -(a • u) := by rewrite [-neg_one_smul, -mul_smul, mul_neg_one_eq_neg, neg_smul] proposition smul_sub_left_distrib (a : R) (u v : M) : a • (u - v) = a • u - a • v := by rewrite [sub_eq_add_neg, smul_left_distrib, smul_neg] proposition sub_smul_right_distrib (a b : R) (v : M) : (a - b) • v = a • v - b • v := by rewrite [sub_eq_add_neg, smul_right_distrib, neg_smul] end left_module /- vector spaces -/ structure vector_space [class] (F V : Type) [fieldF : field F] extends left_module F V /- homomorphisms -/ definition is_smul_hom [class] (R : Type) {M₁ M₂ : Type} [has_scalar R M₁] [has_scalar R M₂] (f : M₁ → M₂) : Type := ∀ r : R, ∀ a : M₁, f (r • a) = r • f a definition is_prop_is_smul_hom [instance] (R : Type) {M₁ M₂ : Type} [is_set M₂] [has_scalar R M₁] [has_scalar R M₂] (f : M₁ → M₂) : is_prop (is_smul_hom R f) := begin unfold is_smul_hom, apply _ end definition respect_smul (R : Type) {M₁ M₂ : Type} [has_scalar R M₁] [has_scalar R M₂] (f : M₁ → M₂) [H : is_smul_hom R f] : ∀ r : R, ∀ a : M₁, f (r • a) = r • f a := H definition is_module_hom [class] (R : Type) {M₁ M₂ : Type} [has_scalar R M₁] [has_scalar R M₂] [add_group M₁] [add_group M₂] (f : M₁ → M₂) := is_add_hom f × is_smul_hom R f definition is_add_hom_of_is_module_hom [instance] (R : Type) {M₁ M₂ : Type} [has_scalar R M₁] [has_scalar R M₂] [add_group M₁] [add_group M₂] (f : M₁ → M₂) [H : is_module_hom R f] : is_add_hom f := prod.pr1 H definition is_smul_hom_of_is_module_hom [instance] {R : Type} {M₁ M₂ : Type} [has_scalar R M₁] [has_scalar R M₂] [add_group M₁] [add_group M₂] (f : M₁ → M₂) [H : is_module_hom R f] : is_smul_hom R f := prod.pr2 H -- Why do we have to give the instance explicitly? definition is_prop_is_module_hom [instance] (R : Type) {M₁ M₂ : Type} [has_scalar R M₁] [has_scalar R M₂] [add_group M₁] [add_group M₂] (f : M₁ → M₂) : is_prop (is_module_hom R f) := have h₁ : is_prop (is_add_hom f), from is_prop_is_add_hom f, begin unfold is_module_hom, apply _ end section module_hom variables {R : Type} {M₁ M₂ M₃ : Type} variables [has_scalar R M₁] [has_scalar R M₂] [has_scalar R M₃] variables [add_group M₁] [add_group M₂] [add_group M₃] variables (g : M₂ → M₃) (f : M₁ → M₂) [is_module_hom R g] [is_module_hom R f] proposition is_module_hom_id : is_module_hom R (@id M₁) := pair (λ a₁ a₂, rfl) (λ r a, rfl) proposition is_module_hom_comp : is_module_hom R (g ∘ f) := pair (take a₁ a₂, begin esimp, rewrite [respect_add f, respect_add g] end) (take r a, by esimp; rewrite [respect_smul R f, respect_smul R g]) proposition respect_smul_add_smul (a b : R) (u v : M₁) : f (a • u + b • v) = a • f u + b • f v := by rewrite [respect_add f, +respect_smul R f] end module_hom section hom_constant variables {R : Type} {M₁ M₂ : Type} variables [ring R] [has_scalar R M₁] [add_group M₁] [left_module R M₂] proposition is_module_hom_constant : is_module_hom R (const M₁ (0 : M₂)) := (λm₁ m₂, !add_zero⁻¹, λr m, (smul_zero r)⁻¹ᵖ) end hom_constant structure LeftModule (R : Ring) := (carrier : Type) (struct : left_module R carrier) attribute LeftModule.struct [instance] section local attribute LeftModule.carrier [coercion] definition AddAbGroup_of_LeftModule [coercion] {R : Ring} (M : LeftModule R) : AddAbGroup := AddAbGroup.mk M (LeftModule.struct M) end definition LeftModule.struct2 [instance] {R : Ring} (M : LeftModule R) : left_module R M := LeftModule.struct M -- definition LeftModule.struct3 [instance] {R : Ring} (M : LeftModule R) : -- left_module R (AddAbGroup_of_LeftModule M) := -- _ definition pointed_LeftModule_carrier [instance] {R : Ring} (M : LeftModule R) : pointed (LeftModule.carrier M) := pointed.mk zero definition pSet_of_LeftModule {R : Ring} (M : LeftModule R) : Set* := pSet.mk' (LeftModule.carrier M) definition left_module_AddAbGroup_of_LeftModule [instance] {R : Ring} (M : LeftModule R) : left_module R (AddAbGroup_of_LeftModule M) := LeftModule.struct M definition left_module_of_ab_group {G : Type} [gG : add_ab_group G] {R : Type} [ring R] (smul : R → G → G) (h1 : Π (r : R) (x y : G), smul r (x + y) = (smul r x + smul r y)) (h2 : Π (r s : R) (x : G), smul (r + s) x = (smul r x + smul s x)) (h3 : Π r s x, smul (r * s) x = smul r (smul s x)) (h4 : Π x, smul 1 x = x) : left_module R G := left_module.mk smul _ add add.assoc 0 zero_add add_zero neg add.left_inv add.comm h1 h2 h3 h4 definition LeftModule_of_AddAbGroup {R : Ring} (G : AddAbGroup) (smul : R → G → G) (h1 h2 h3 h4) : LeftModule R := LeftModule.mk G (left_module_of_ab_group smul h1 h2 h3 h4) open unit definition trivial_LeftModule [constructor] (R : Ring) : LeftModule R := LeftModule_of_AddAbGroup trivial_ab_group (λr u, star) (λr u₁ u₂, idp) (λr₁ r₂ u, idp) (λr₁ r₂ u, idp) unit.eta section variables {R : Ring} {M M₁ M₂ M₃ : LeftModule R} definition smul_homomorphism [constructor] (M : LeftModule R) (r : R) : M →a M := add_homomorphism.mk (λg, r • g) (smul_left_distrib r) proposition to_smul_left_distrib (a : R) (u v : M) : a • (u + v) = a • u + a • v := !smul_left_distrib proposition to_smul_right_distrib (a b : R) (u : M) : (a + b) • u = a • u + b • u := !smul_right_distrib proposition to_mul_smul (a : R) (b : R) (u : M) : (a * b) • u = a • (b • u) := !mul_smul proposition to_one_smul (u : M) : (1 : R) • u = u := !one_smul structure homomorphism (M₁ M₂ : LeftModule R) : Type := (fn : LeftModule.carrier M₁ → LeftModule.carrier M₂) (p : is_module_hom R fn) infix ` →lm `:55 := homomorphism definition homomorphism_fn [unfold 4] [coercion] := @homomorphism.fn definition is_module_hom_of_homomorphism [unfold 4] [instance] [priority 900] {M₁ M₂ : LeftModule R} (φ : M₁ →lm M₂) : is_module_hom R φ := homomorphism.p φ section variable (φ : M₁ →lm M₂) definition to_respect_add (x y : M₁) : φ (x + y) = φ x + φ y := respect_add φ x y definition to_respect_smul (a : R) (x : M₁) : φ (a • x) = a • (φ x) := respect_smul R φ a x definition to_respect_sub (x y : M₁) : φ (x - y) = φ x - φ y := respect_sub φ x y definition is_embedding_of_homomorphism /- φ -/ (H : Π{x}, φ x = 0 → x = 0) : is_embedding φ := is_embedding_of_is_add_hom φ @H variables (M₁ M₂) definition is_set_homomorphism [instance] : is_set (M₁ →lm M₂) := begin have H : M₁ →lm M₂ ≃ Σ(f : LeftModule.carrier M₁ → LeftModule.carrier M₂), is_module_hom (Ring.carrier R) f, begin fapply equiv.MK, { intro φ, induction φ, constructor, exact p}, { intro v, induction v with f H, constructor, exact H}, { intro v, induction v, reflexivity}, { intro φ, induction φ, reflexivity} end, have ∀ f : LeftModule.carrier M₁ → LeftModule.carrier M₂, is_set (is_module_hom (Ring.carrier R) f), from _, apply is_trunc_equiv_closed_rev, exact H end variables {M₁ M₂} definition pmap_of_homomorphism [constructor] /- φ -/ : pSet_of_LeftModule M₁ →* pSet_of_LeftModule M₂ := have H : φ 0 = 0, from respect_zero φ, pmap.mk φ begin esimp, exact H end definition homomorphism_change_fun [constructor] (φ : M₁ →lm M₂) (f : M₁ → M₂) (p : φ ~ f) : M₁ →lm M₂ := homomorphism.mk f (prod.mk (λx₁ x₂, (p (x₁ + x₂))⁻¹ ⬝ to_respect_add φ x₁ x₂ ⬝ ap011 _ (p x₁) (p x₂)) (λ a x, (p (a • x))⁻¹ ⬝ to_respect_smul φ a x ⬝ ap01 _ (p x))) definition homomorphism_eq (φ₁ φ₂ : M₁ →lm M₂) (p : φ₁ ~ φ₂) : φ₁ = φ₂ := begin induction φ₁ with φ₁ q₁, induction φ₂ with φ₂ q₂, esimp at p, induction p, exact ap (homomorphism.mk φ₁) !is_prop.elim end end section definition homomorphism.mk' [constructor] (φ : M₁ → M₂) (p : Π(g₁ g₂ : M₁), φ (g₁ + g₂) = φ g₁ + φ g₂) (q : Π(r : R) x, φ (r • x) = r • φ x) : M₁ →lm M₂ := homomorphism.mk φ (p, q) definition to_respect_zero (φ : M₁ →lm M₂) : φ 0 = 0 := respect_zero φ definition homomorphism_compose [reducible] [constructor] (f' : M₂ →lm M₃) (f : M₁ →lm M₂) : M₁ →lm M₃ := homomorphism.mk (f' ∘ f) !is_module_hom_comp variable (M) definition homomorphism_id [reducible] [constructor] [refl] : M →lm M := homomorphism.mk (@id M) !is_module_hom_id variable {M} abbreviation lmid [constructor] := homomorphism_id M infixr ` ∘lm `:75 := homomorphism_compose definition lm_constant [constructor] (M₁ M₂ : LeftModule R) : M₁ →lm M₂ := homomorphism.mk (const M₁ 0) !is_module_hom_constant structure isomorphism (M₁ M₂ : LeftModule R) := (to_hom : M₁ →lm M₂) (is_equiv_to_hom : is_equiv to_hom) infix ` ≃lm `:25 := isomorphism attribute isomorphism.to_hom [coercion] attribute isomorphism.is_equiv_to_hom [instance] attribute isomorphism._trans_of_to_hom [unfold 4] definition equiv_of_isomorphism [constructor] (φ : M₁ ≃lm M₂) : M₁ ≃ M₂ := equiv.mk φ !isomorphism.is_equiv_to_hom section local attribute pSet_of_LeftModule [coercion] definition pequiv_of_isomorphism [constructor] (φ : M₁ ≃lm M₂) : M₁ ≃* M₂ := pequiv_of_equiv (equiv_of_isomorphism φ) (to_respect_zero φ) end definition isomorphism_of_equiv [constructor] (φ : M₁ ≃ M₂) (p : Π(g₁ g₂ : M₁), φ (g₁ + g₂) = φ g₁ + φ g₂) (q : Πr x, φ (r • x) = r • φ x) : M₁ ≃lm M₂ := isomorphism.mk (homomorphism.mk φ (p, q)) !to_is_equiv definition isomorphism_of_eq [constructor] {M₁ M₂ : LeftModule R} (p : M₁ = M₂ :> LeftModule R) : M₁ ≃lm M₂ := isomorphism_of_equiv (equiv_of_eq (ap LeftModule.carrier p)) begin intros, induction p, reflexivity end begin intros, induction p, reflexivity end -- definition pequiv_of_isomorphism_of_eq {M₁ M₂ : LeftModule R} (p : M₁ = M₂ :> LeftModule R) : -- pequiv_of_isomorphism (isomorphism_of_eq p) = pequiv_of_eq (ap pType_of_LeftModule p) := -- begin -- induction p, -- apply pequiv_eq, -- fapply pmap_eq, -- { intro g, reflexivity}, -- { apply is_prop.elim} -- end definition to_lminv [constructor] (φ : M₁ ≃lm M₂) : M₂ →lm M₁ := homomorphism.mk φ⁻¹ abstract begin split, intro g₁ g₂, apply eq_of_fn_eq_fn' φ, rewrite [respect_add φ, +right_inv φ], intro r x, apply eq_of_fn_eq_fn' φ, rewrite [to_respect_smul φ, +right_inv φ], end end variable (M) definition isomorphism.refl [refl] [constructor] : M ≃lm M := isomorphism.mk lmid !is_equiv_id variable {M} definition isomorphism.rfl [refl] [constructor] : M ≃lm M := isomorphism.refl M definition isomorphism.symm [symm] [constructor] (φ : M₁ ≃lm M₂) : M₂ ≃lm M₁ := isomorphism.mk (to_lminv φ) !is_equiv_inv definition isomorphism.trans [trans] [constructor] (φ : M₁ ≃lm M₂) (ψ : M₂ ≃lm M₃) : M₁ ≃lm M₃ := isomorphism.mk (ψ ∘lm φ) !is_equiv_compose definition isomorphism.eq_trans [trans] [constructor] {M₁ M₂ : LeftModule R} {M₃ : LeftModule R} (φ : M₁ = M₂) (ψ : M₂ ≃lm M₃) : M₁ ≃lm M₃ := proof isomorphism.trans (isomorphism_of_eq φ) ψ qed definition isomorphism.trans_eq [trans] [constructor] {M₁ : LeftModule R} {M₂ M₃ : LeftModule R} (φ : M₁ ≃lm M₂) (ψ : M₂ = M₃) : M₁ ≃lm M₃ := isomorphism.trans φ (isomorphism_of_eq ψ) postfix `⁻¹ˡᵐ`:(max + 1) := isomorphism.symm infixl ` ⬝lm `:75 := isomorphism.trans infixl ` ⬝lmp `:75 := isomorphism.trans_eq infixl ` ⬝plm `:75 := isomorphism.eq_trans definition homomorphism_of_eq [constructor] {M₁ M₂ : LeftModule R} (p : M₁ = M₂ :> LeftModule R) : M₁ →lm M₂ := isomorphism_of_eq p definition group_homomorphism_of_lm_homomorphism [constructor] {M₁ M₂ : LeftModule R} (φ : M₁ →lm M₂) : M₁ →a M₂ := add_homomorphism.mk φ (to_respect_add φ) definition lm_homomorphism_of_group_homomorphism [constructor] {M₁ M₂ : LeftModule R} (φ : M₁ →a M₂) (h : Π(r : R) g, φ (r • g) = r • φ g) : M₁ →lm M₂ := homomorphism.mk' φ (group.to_respect_add φ) h definition group_isomorphism_of_lm_isomorphism [constructor] {M₁ M₂ : LeftModule R} (φ : M₁ ≃lm M₂) : AddGroup_of_AddAbGroup M₁ ≃g AddGroup_of_AddAbGroup M₂ := group.isomorphism.mk (group_homomorphism_of_lm_homomorphism φ) (isomorphism.is_equiv_to_hom φ) definition lm_isomorphism_of_group_isomorphism [constructor] {M₁ M₂ : LeftModule R} (φ : AddGroup_of_AddAbGroup M₁ ≃g AddGroup_of_AddAbGroup M₂) (h : Π(r : R) g, φ (r • g) = r • φ g) : M₁ ≃lm M₂ := isomorphism.mk (lm_homomorphism_of_group_homomorphism φ h) (group.isomorphism.is_equiv_to_hom φ) section local attribute pSet_of_LeftModule [coercion] definition is_exact_mod (f : M₁ →lm M₂) (f' : M₂ →lm M₃) : Type := @is_exact M₁ M₂ M₃ (homomorphism_fn f) (homomorphism_fn f') definition is_exact_mod.mk {f : M₁ →lm M₂} {f' : M₂ →lm M₃} (h₁ : Πm, f' (f m) = 0) (h₂ : Πm, f' m = 0 → image f m) : is_exact_mod f f' := is_exact.mk h₁ h₂ structure short_exact_mod (A B C : LeftModule R) := (f : A →lm B) (g : B →lm C) (h : @is_short_exact A B C f g) local abbreviation g_of_lm := @group_homomorphism_of_lm_homomorphism definition short_exact_mod_of_is_exact {X A B C Y : LeftModule R} (k : X →lm A) (f : A →lm B) (g : B →lm C) (l : C →lm Y) (hX : is_contr X) (hY : is_contr Y) (kf : is_exact_mod k f) (fg : is_exact_mod f g) (gl : is_exact_mod g l) : short_exact_mod A B C := short_exact_mod.mk f g (is_short_exact_of_is_exact (g_of_lm k) (g_of_lm f) (g_of_lm g) (g_of_lm l) hX hY kf fg gl) definition short_exact_mod_isomorphism {A B A' B' C C' : LeftModule R} (eA : A ≃lm A') (eB : B ≃lm B') (eC : C ≃lm C') (H : short_exact_mod A' B' C') : short_exact_mod A B C := short_exact_mod.mk (eB⁻¹ˡᵐ ∘lm short_exact_mod.f H ∘lm eA) (eC⁻¹ˡᵐ ∘lm short_exact_mod.g H ∘lm eB) (is_short_exact_equiv _ _ (equiv_of_isomorphism eA) (equiv_of_isomorphism eB) (pequiv_of_isomorphism eC) (λa, to_right_inv (equiv_of_isomorphism eB) _) (λb, to_right_inv (equiv_of_isomorphism eC) _) (short_exact_mod.h H)) definition is_contr_middle_of_short_exact_mod {A B C : LeftModule R} (H : short_exact_mod A B C) (HA : is_contr A) (HC : is_contr C) : is_contr B := is_contr_middle_of_is_exact (is_exact_of_is_short_exact (short_exact_mod.h H)) definition is_contr_right_of_short_exact_mod {A B C : LeftModule R} (H : short_exact_mod A B C) (HB : is_contr B) : is_contr C := is_contr_right_of_is_short_exact (short_exact_mod.h H) _ _ definition is_contr_left_of_short_exact_mod {A B C : LeftModule R} (H : short_exact_mod A B C) (HB : is_contr B) : is_contr A := is_contr_left_of_is_short_exact (short_exact_mod.h H) _ pt definition isomorphism_of_is_contr_left {A B C : LeftModule R} (H : short_exact_mod A B C) (HA : is_contr A) : B ≃lm C := isomorphism.mk (short_exact_mod.g H) begin apply @is_equiv_right_of_is_short_exact _ _ _ (group_homomorphism_of_lm_homomorphism (short_exact_mod.f H)) (group_homomorphism_of_lm_homomorphism (short_exact_mod.g H)), rexact short_exact_mod.h H, exact HA, end definition isomorphism_of_is_contr_right {A B C : LeftModule R} (H : short_exact_mod A B C) (HC : is_contr C) : A ≃lm B := isomorphism.mk (short_exact_mod.f H) begin apply @is_equiv_left_of_is_short_exact _ _ _ (group_homomorphism_of_lm_homomorphism (short_exact_mod.f H)) (group_homomorphism_of_lm_homomorphism (short_exact_mod.g H)), rexact short_exact_mod.h H, exact HC, end end end end section int open int definition left_module_int_of_ab_group [constructor] (A : Type) [add_ab_group A] : left_module rℤ A := left_module_of_ab_group imul imul_add add_imul mul_imul one_imul definition LeftModule_int_of_AbGroup [constructor] (A : AddAbGroup) : LeftModule rℤ := LeftModule.mk A (left_module_int_of_ab_group A) definition lm_hom_int.mk [constructor] {A B : AbGroup} (φ : A →g B) : LeftModule_int_of_AbGroup A →lm LeftModule_int_of_AbGroup B := lm_homomorphism_of_group_homomorphism φ (to_respect_imul φ) definition lm_iso_int.mk [constructor] {A B : AbGroup} (φ : A ≃g B) : LeftModule_int_of_AbGroup A ≃lm LeftModule_int_of_AbGroup B := isomorphism.mk (lm_hom_int.mk φ) (group.isomorphism.is_equiv_to_hom φ) definition group_isomorphism_of_lm_isomorphism_int [constructor] {A B : AbGroup} (φ : LeftModule_int_of_AbGroup A ≃lm LeftModule_int_of_AbGroup B) : A ≃g B := group_isomorphism_of_lm_isomorphism φ end int end left_module
c20c5d3a5f2cd9f56ce0788b0b9f67c5250038e7
968e2f50b755d3048175f176376eff7139e9df70
/examples/prop_logic_theory/unnamed_949.lean
9098f1dd57ce44c9772964126b69e977f942ed33
[]
no_license
gihanmarasingha/mth1001_sphinx
190a003269ba5e54717b448302a27ca26e31d491
05126586cbf5786e521be1ea2ef5b4ba3c44e74a
refs/heads/master
1,672,913,933,677
1,604,516,583,000
1,604,516,583,000
309,245,750
1
0
null
null
null
null
UTF-8
Lean
false
false
244
lean
variables a b : Prop -- BEGIN theorem and_of_and_v2 {p q : Prop} : p ∧ q → q ∧ p := begin assume h, exact and.intro (h.right) (h.left) end example : (a → b) ∧ (b ∧ a) → (b ∧ a) ∧ (a → b) := by exact and_of_and_v2 -- END
9739ede4acd24b561571ef1ebacd4609e28420e6
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/continued_fractions/computation/approximations.lean
09633aa94d4c2857b20c930b09be84ca4c4176cb
[ "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
28,987
lean
/- Copyright (c) 2020 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import algebra.continued_fractions.computation.correctness_terminating import data.nat.fib import tactic.solve_by_elim /-! # Approximations for Continued Fraction Computations (`generalized_continued_fraction.of`) > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Summary This file contains useful approximations for the values involved in the continued fractions computation `generalized_continued_fraction.of`. In particular, we derive the so-called *determinant formula* for `generalized_continued_fraction.of`: `Aₙ * Bₙ₊₁ - Bₙ * Aₙ₊₁ = (-1)^(n + 1)`. Moreover, we derive some upper bounds for the error term when computing a continued fraction up a given position, i.e. bounds for the term `|v - (generalized_continued_fraction.of v).convergents n|`. The derived bounds will show us that the error term indeed gets smaller. As a corollary, we will be able to show that `(generalized_continued_fraction.of v).convergents` converges to `v` in `algebra.continued_fractions.computation.approximation_corollaries`. ## Main Theorems - `generalized_continued_fraction.of_part_num_eq_one`: shows that all partial numerators `aᵢ` are equal to one. - `generalized_continued_fraction.exists_int_eq_of_part_denom`: shows that all partial denominators `bᵢ` correspond to an integer. - `generalized_continued_fraction.one_le_of_nth_part_denom`: shows that `1 ≤ bᵢ`. - `generalized_continued_fraction.succ_nth_fib_le_of_nth_denom`: shows that the `n`th denominator `Bₙ` is greater than or equal to the `n + 1`th fibonacci number `nat.fib (n + 1)`. - `generalized_continued_fraction.le_of_succ_nth_denom`: shows that `bₙ * Bₙ ≤ Bₙ₊₁`, where `bₙ` is the `n`th partial denominator of the continued fraction. - `generalized_continued_fraction.abs_sub_convergents_le`: shows that `|v - Aₙ / Bₙ| ≤ 1 / (Bₙ * Bₙ₊₁)`, where `Aₙ` is the nth partial numerator. ## References - [*Hardy, GH and Wright, EM and Heath-Brown, Roger and Silverman, Joseph*][hardy2008introduction] - https://en.wikipedia.org/wiki/Generalized_continued_fraction#The_determinant_formula -/ namespace generalized_continued_fraction open generalized_continued_fraction (of) int variables {K : Type*} {v : K} {n : ℕ} [linear_ordered_field K] [floor_ring K] namespace int_fract_pair /-! We begin with some lemmas about the stream of `int_fract_pair`s, which presumably are not of great interest for the end user. -/ /-- Shows that the fractional parts of the stream are in `[0,1)`. -/ lemma nth_stream_fr_nonneg_lt_one {ifp_n : int_fract_pair K} (nth_stream_eq : int_fract_pair.stream v n = some ifp_n) : 0 ≤ ifp_n.fr ∧ ifp_n.fr < 1 := begin cases n, case nat.zero { have : int_fract_pair.of v = ifp_n, by injection nth_stream_eq, rw [←this, int_fract_pair.of], exact ⟨fract_nonneg _, fract_lt_one _⟩ }, case nat.succ { rcases (succ_nth_stream_eq_some_iff.elim_left nth_stream_eq) with ⟨_, _, _, ifp_of_eq_ifp_n⟩, rw [←ifp_of_eq_ifp_n, int_fract_pair.of], exact ⟨fract_nonneg _, fract_lt_one _⟩ } end /-- Shows that the fractional parts of the stream are nonnegative. -/ lemma nth_stream_fr_nonneg {ifp_n : int_fract_pair K} (nth_stream_eq : int_fract_pair.stream v n = some ifp_n) : 0 ≤ ifp_n.fr := (nth_stream_fr_nonneg_lt_one nth_stream_eq).left /-- Shows that the fractional parts of the stream are smaller than one. -/ lemma nth_stream_fr_lt_one {ifp_n : int_fract_pair K} (nth_stream_eq : int_fract_pair.stream v n = some ifp_n) : ifp_n.fr < 1 := (nth_stream_fr_nonneg_lt_one nth_stream_eq).right /-- Shows that the integer parts of the stream are at least one. -/ lemma one_le_succ_nth_stream_b {ifp_succ_n : int_fract_pair K} (succ_nth_stream_eq : int_fract_pair.stream v (n + 1) = some ifp_succ_n) : 1 ≤ ifp_succ_n.b := begin obtain ⟨ifp_n, nth_stream_eq, stream_nth_fr_ne_zero, ⟨-⟩⟩ : ∃ ifp_n, int_fract_pair.stream v n = some ifp_n ∧ ifp_n.fr ≠ 0 ∧ int_fract_pair.of ifp_n.fr⁻¹ = ifp_succ_n, from succ_nth_stream_eq_some_iff.elim_left succ_nth_stream_eq, suffices : 1 ≤ ifp_n.fr⁻¹, { rw_mod_cast [le_floor], assumption }, suffices : ifp_n.fr ≤ 1, { have h : 0 < ifp_n.fr, from lt_of_le_of_ne (nth_stream_fr_nonneg nth_stream_eq) stream_nth_fr_ne_zero.symm, apply one_le_inv h this }, simp only [le_of_lt (nth_stream_fr_lt_one nth_stream_eq)] end /-- Shows that the `n + 1`th integer part `bₙ₊₁` of the stream is smaller or equal than the inverse of the `n`th fractional part `frₙ` of the stream. This result is straight-forward as `bₙ₊₁` is defined as the floor of `1 / frₙ` -/ lemma succ_nth_stream_b_le_nth_stream_fr_inv {ifp_n ifp_succ_n : int_fract_pair K} (nth_stream_eq : int_fract_pair.stream v n = some ifp_n) (succ_nth_stream_eq : int_fract_pair.stream v (n + 1) = some ifp_succ_n) : (ifp_succ_n.b : K) ≤ ifp_n.fr⁻¹ := begin suffices : (⌊ifp_n.fr⁻¹⌋ : K) ≤ ifp_n.fr⁻¹, { cases ifp_n with _ ifp_n_fr, have : ifp_n_fr ≠ 0, { intro h, simpa [h, int_fract_pair.stream, nth_stream_eq] using succ_nth_stream_eq }, have : int_fract_pair.of ifp_n_fr⁻¹ = ifp_succ_n, { simpa [this, int_fract_pair.stream, nth_stream_eq, option.coe_def] using succ_nth_stream_eq }, rwa ←this }, exact (floor_le ifp_n.fr⁻¹) end end int_fract_pair /-! Next we translate above results about the stream of `int_fract_pair`s to the computed continued fraction `generalized_continued_fraction.of`. -/ /-- Shows that the integer parts of the continued fraction are at least one. -/ lemma of_one_le_nth_part_denom {b : K} (nth_part_denom_eq : (of v).partial_denominators.nth n = some b) : 1 ≤ b := begin obtain ⟨gp_n, nth_s_eq, ⟨-⟩⟩ : ∃ gp_n, (of v).s.nth n = some gp_n ∧ gp_n.b = b, from exists_s_b_of_part_denom nth_part_denom_eq, obtain ⟨ifp_n, succ_nth_stream_eq, ifp_n_b_eq_gp_n_b⟩ : ∃ ifp, int_fract_pair.stream v (n + 1) = some ifp ∧ (ifp.b : K) = gp_n.b, from int_fract_pair.exists_succ_nth_stream_of_gcf_of_nth_eq_some nth_s_eq, rw [←ifp_n_b_eq_gp_n_b], exact_mod_cast (int_fract_pair.one_le_succ_nth_stream_b succ_nth_stream_eq) end /-- Shows that the partial numerators `aᵢ` of the continued fraction are equal to one and the partial denominators `bᵢ` correspond to integers. -/ lemma of_part_num_eq_one_and_exists_int_part_denom_eq {gp : generalized_continued_fraction.pair K} (nth_s_eq : (of v).s.nth n = some gp) : gp.a = 1 ∧ ∃ (z : ℤ), gp.b = (z : K) := begin obtain ⟨ifp, stream_succ_nth_eq, -⟩ : ∃ ifp, int_fract_pair.stream v (n + 1) = some ifp ∧ _, from int_fract_pair.exists_succ_nth_stream_of_gcf_of_nth_eq_some nth_s_eq, have : gp = ⟨1, ifp.b⟩, by { have : (of v).s.nth n = some ⟨1, ifp.b⟩, from nth_of_eq_some_of_succ_nth_int_fract_pair_stream stream_succ_nth_eq, have : some gp = some ⟨1, ifp.b⟩, by rwa nth_s_eq at this, injection this }, simp [this], end /-- Shows that the partial numerators `aᵢ` are equal to one. -/ lemma of_part_num_eq_one {a : K} (nth_part_num_eq : (of v).partial_numerators.nth n = some a) : a = 1 := begin obtain ⟨gp, nth_s_eq, gp_a_eq_a_n⟩ : ∃ gp, (of v).s.nth n = some gp ∧ gp.a = a, from exists_s_a_of_part_num nth_part_num_eq, have : gp.a = 1, from (of_part_num_eq_one_and_exists_int_part_denom_eq nth_s_eq).left, rwa gp_a_eq_a_n at this end /-- Shows that the partial denominators `bᵢ` correspond to an integer. -/ lemma exists_int_eq_of_part_denom {b : K} (nth_part_denom_eq : (of v).partial_denominators.nth n = some b) : ∃ (z : ℤ), b = (z : K) := begin obtain ⟨gp, nth_s_eq, gp_b_eq_b_n⟩ : ∃ gp, (of v).s.nth n = some gp ∧ gp.b = b, from exists_s_b_of_part_denom nth_part_denom_eq, have : ∃ (z : ℤ), gp.b = (z : K), from (of_part_num_eq_one_and_exists_int_part_denom_eq nth_s_eq).right, rwa gp_b_eq_b_n at this end /-! One of our next goals is to show that `bₙ * Bₙ ≤ Bₙ₊₁`. For this, we first show that the partial denominators `Bₙ` are bounded from below by the fibonacci sequence `nat.fib`. This then implies that `0 ≤ Bₙ` and hence `Bₙ₊₂ = bₙ₊₁ * Bₙ₊₁ + Bₙ ≥ bₙ₊₁ * Bₙ₊₁ + 0 = bₙ₊₁ * Bₙ₊₁`. -/ -- open `nat` as we will make use of fibonacci numbers. open nat lemma fib_le_of_continuants_aux_b : (n ≤ 1 ∨ ¬(of v).terminated_at (n - 2)) → (fib n : K) ≤ ((of v).continuants_aux n).b := nat.strong_induction_on n begin clear n, assume n IH hyp, rcases n with _|_|n, { simp [fib_add_two, continuants_aux] }, -- case n = 0 { simp [fib_add_two, continuants_aux] }, -- case n = 1 { let g := of v, -- case 2 ≤ n have : ¬(n + 2 ≤ 1), by linarith, have not_terminated_at_n : ¬g.terminated_at n, from or.resolve_left hyp this, obtain ⟨gp, s_ppred_nth_eq⟩ : ∃ gp, g.s.nth n = some gp, from option.ne_none_iff_exists'.mp not_terminated_at_n, set pconts := g.continuants_aux (n + 1) with pconts_eq, set ppconts := g.continuants_aux n with ppconts_eq, -- use the recurrence of continuants_aux suffices : (fib n : K) + fib (n + 1) ≤ gp.a * ppconts.b + gp.b * pconts.b, by simpa [fib_add_two, add_comm, (continuants_aux_recurrence s_ppred_nth_eq ppconts_eq pconts_eq)], -- make use of the fact that gp.a = 1 suffices : (fib n : K) + fib (n + 1) ≤ ppconts.b + gp.b * pconts.b, by simpa [(of_part_num_eq_one $ part_num_eq_s_a s_ppred_nth_eq)], have not_terminated_at_pred_n : ¬g.terminated_at (n - 1), from mt (terminated_stable $ nat.sub_le n 1) not_terminated_at_n, have not_terminated_at_ppred_n : ¬terminated_at g (n - 2), from mt (terminated_stable (n - 1).pred_le) not_terminated_at_pred_n, -- use the IH to get the inequalities for `pconts` and `ppconts` have : (fib (n + 1) : K) ≤ pconts.b, from IH _ (nat.lt.base $ n + 1) (or.inr not_terminated_at_pred_n), have ppred_nth_fib_le_ppconts_B : (fib n : K) ≤ ppconts.b, from IH n (lt_trans (nat.lt.base n) $ nat.lt.base $ n + 1) (or.inr not_terminated_at_ppred_n), suffices : (fib (n + 1) : K) ≤ gp.b * pconts.b, solve_by_elim [add_le_add ppred_nth_fib_le_ppconts_B], -- finally use the fact that 1 ≤ gp.b to solve the goal suffices : 1 * (fib (n + 1) : K) ≤ gp.b * pconts.b, by rwa [one_mul] at this, have one_le_gp_b : (1 : K) ≤ gp.b, from of_one_le_nth_part_denom (part_denom_eq_s_b s_ppred_nth_eq), have : (0 : K) ≤ fib (n + 1), by exact_mod_cast (fib (n + 1)).zero_le, have : (0 : K) ≤ gp.b, from le_trans zero_le_one one_le_gp_b, mono } end /-- Shows that the `n`th denominator is greater than or equal to the `n + 1`th fibonacci number, that is `nat.fib (n + 1) ≤ Bₙ`. -/ lemma succ_nth_fib_le_of_nth_denom (hyp: n = 0 ∨ ¬(of v).terminated_at (n - 1)) : (fib (n + 1) : K) ≤ (of v).denominators n := begin rw [denom_eq_conts_b, nth_cont_eq_succ_nth_cont_aux], have : (n + 1) ≤ 1 ∨ ¬(of v).terminated_at (n - 1), by { cases n, case nat.zero : { exact (or.inl $ le_refl 1) }, case nat.succ : { exact or.inr (or.resolve_left hyp n.succ_ne_zero) } }, exact (fib_le_of_continuants_aux_b this) end /-! As a simple consequence, we can now derive that all denominators are nonnegative. -/ lemma zero_le_of_continuants_aux_b : 0 ≤ ((of v).continuants_aux n).b := begin let g := of v, induction n with n IH, case nat.zero: { refl }, case nat.succ: { cases (decidable.em $ g.terminated_at (n - 1)) with terminated not_terminated, { cases n, -- terminating case { simp [zero_le_one] }, { have : g.continuants_aux (n + 2) = g.continuants_aux (n + 1), from continuants_aux_stable_step_of_terminated terminated, simp only [this, IH] } }, { calc -- non-terminating case (0 : K) ≤ fib (n + 1) : by exact_mod_cast (n + 1).fib.zero_le ... ≤ ((of v).continuants_aux (n + 1)).b : fib_le_of_continuants_aux_b (or.inr not_terminated) } } end /-- Shows that all denominators are nonnegative. -/ lemma zero_le_of_denom : 0 ≤ (of v).denominators n := by { rw [denom_eq_conts_b, nth_cont_eq_succ_nth_cont_aux], exact zero_le_of_continuants_aux_b } lemma le_of_succ_succ_nth_continuants_aux_b {b : K} (nth_part_denom_eq : (of v).partial_denominators.nth n = some b) : b * ((of v).continuants_aux $ n + 1).b ≤ ((of v).continuants_aux $ n + 2).b := begin obtain ⟨gp_n, nth_s_eq, rfl⟩ : ∃ gp_n, (of v).s.nth n = some gp_n ∧ gp_n.b = b, from exists_s_b_of_part_denom nth_part_denom_eq, simp [of_part_num_eq_one (part_num_eq_s_a nth_s_eq), zero_le_of_continuants_aux_b, generalized_continued_fraction.continuants_aux_recurrence nth_s_eq rfl rfl] end /-- Shows that `bₙ * Bₙ ≤ Bₙ₊₁`, where `bₙ` is the `n`th partial denominator and `Bₙ₊₁` and `Bₙ` are the `n + 1`th and `n`th denominator of the continued fraction. -/ theorem le_of_succ_nth_denom {b : K} (nth_part_denom_eq : (of v).partial_denominators.nth n = some b) : b * (of v).denominators n ≤ (of v).denominators (n + 1) := begin rw [denom_eq_conts_b, nth_cont_eq_succ_nth_cont_aux], exact (le_of_succ_succ_nth_continuants_aux_b nth_part_denom_eq) end /-- Shows that the sequence of denominators is monotone, that is `Bₙ ≤ Bₙ₊₁`. -/ theorem of_denom_mono : (of v).denominators n ≤ (of v).denominators (n + 1) := begin let g := of v, cases (decidable.em $ g.partial_denominators.terminated_at n) with terminated not_terminated, { have : g.partial_denominators.nth n = none, by rwa stream.seq.terminated_at at terminated, have : g.terminated_at n, from terminated_at_iff_part_denom_none.elim_right (by rwa stream.seq.terminated_at at terminated), have : g.denominators (n + 1) = g.denominators n, from denominators_stable_of_terminated n.le_succ this, rw this }, { obtain ⟨b, nth_part_denom_eq⟩ : ∃ b, g.partial_denominators.nth n = some b, from option.ne_none_iff_exists'.mp not_terminated, have : 1 ≤ b, from of_one_le_nth_part_denom nth_part_denom_eq, calc g.denominators n ≤ b * g.denominators n : by simpa using (mul_le_mul_of_nonneg_right this zero_le_of_denom) ... ≤ g.denominators (n + 1) : le_of_succ_nth_denom nth_part_denom_eq } end section determinant /-! ### Determinant Formula Next we prove the so-called *determinant formula* for `generalized_continued_fraction.of`: `Aₙ * Bₙ₊₁ - Bₙ * Aₙ₊₁ = (-1)^(n + 1)`. -/ lemma determinant_aux (hyp: n = 0 ∨ ¬(of v).terminated_at (n - 1)) : ((of v).continuants_aux n).a * ((of v).continuants_aux (n + 1)).b - ((of v).continuants_aux n).b * ((of v).continuants_aux (n + 1)).a = (-1)^n := begin induction n with n IH, case nat.zero { simp [continuants_aux] }, case nat.succ { -- set up some shorthand notation let g := of v, let conts := continuants_aux g (n + 2), set pred_conts := continuants_aux g (n + 1) with pred_conts_eq, set ppred_conts := continuants_aux g n with ppred_conts_eq, let pA := pred_conts.a, let pB := pred_conts.b, let ppA := ppred_conts.a, let ppB := ppred_conts.b, -- let's change the goal to something more readable change pA * conts.b - pB * conts.a = (-1)^(n + 1), have not_terminated_at_n : ¬terminated_at g n, from or.resolve_left hyp n.succ_ne_zero, obtain ⟨gp, s_nth_eq⟩ : ∃ gp, g.s.nth n = some gp, from option.ne_none_iff_exists'.elim_left not_terminated_at_n, -- unfold the recurrence relation for `conts` once and simplify to derive the following suffices : pA * (ppB + gp.b * pB) - pB * (ppA + gp.b * pA) = (-1)^(n + 1), by { simp only [conts, (continuants_aux_recurrence s_nth_eq ppred_conts_eq pred_conts_eq)], have gp_a_eq_one : gp.a = 1, from of_part_num_eq_one (part_num_eq_s_a s_nth_eq), rw [gp_a_eq_one, this.symm], ring }, suffices : pA * ppB - pB * ppA = (-1)^(n + 1), calc pA * (ppB + gp.b * pB) - pB * (ppA + gp.b * pA) = pA * ppB + pA * gp.b * pB - pB * ppA - pB * gp.b * pA : by ring ... = pA * ppB - pB * ppA : by ring ... = (-1)^(n + 1) : by assumption, suffices : ppA * pB - ppB * pA = (-1)^n, by { have pow_succ_n : (-1 : K)^(n + 1) = (-1) * (-1)^n, from pow_succ (-1) n, rw [pow_succ_n, ←this], ring }, exact (IH $ or.inr $ mt (terminated_stable $ n.sub_le 1) not_terminated_at_n) } end /-- The determinant formula `Aₙ * Bₙ₊₁ - Bₙ * Aₙ₊₁ = (-1)^(n + 1)` -/ lemma determinant (not_terminated_at_n : ¬(of v).terminated_at n) : (of v).numerators n * (of v).denominators (n + 1) - (of v).denominators n * (of v).numerators (n + 1) = (-1)^(n + 1) := (determinant_aux $ or.inr $ not_terminated_at_n) end determinant section error_term /-! ### Approximation of Error Term Next we derive some approximations for the error term when computing a continued fraction up a given position, i.e. bounds for the term `|v - (generalized_continued_fraction.of v).convergents n|`. -/ /-- This lemma follows from the finite correctness proof, the determinant equality, and by simplifying the difference. -/ lemma sub_convergents_eq {ifp : int_fract_pair K} (stream_nth_eq : int_fract_pair.stream v n = some ifp) : let g := of v in let B := (g.continuants_aux (n + 1)).b in let pB := (g.continuants_aux n).b in v - g.convergents n = if ifp.fr = 0 then 0 else (-1)^n / (B * (ifp.fr⁻¹ * B + pB)) := begin -- set up some shorthand notation let g := of v, let conts := g.continuants_aux (n + 1), let pred_conts := g.continuants_aux n, have g_finite_correctness : v = generalized_continued_fraction.comp_exact_value pred_conts conts ifp.fr, from comp_exact_value_correctness_of_stream_eq_some stream_nth_eq, cases decidable.em (ifp.fr = 0) with ifp_fr_eq_zero ifp_fr_ne_zero, { suffices : v - g.convergents n = 0, by simpa [ifp_fr_eq_zero], replace g_finite_correctness : v = g.convergents n, by simpa [generalized_continued_fraction.comp_exact_value, ifp_fr_eq_zero] using g_finite_correctness, exact (sub_eq_zero.elim_right g_finite_correctness) }, { -- more shorthand notation let A := conts.a, let B := conts.b, let pA := pred_conts.a, let pB := pred_conts.b, -- first, let's simplify the goal as `ifp.fr ≠ 0` suffices : v - A / B = (-1)^n / (B * (ifp.fr⁻¹ * B + pB)), by simpa [ifp_fr_ne_zero], -- now we can unfold `g.comp_exact_value` to derive the following equality for `v` replace g_finite_correctness : v = (pA + ifp.fr⁻¹ * A) / (pB + ifp.fr⁻¹ * B), by simpa [generalized_continued_fraction.comp_exact_value, ifp_fr_ne_zero, next_continuants, next_numerator, next_denominator, add_comm] using g_finite_correctness, -- let's rewrite this equality for `v` in our goal suffices : (pA + ifp.fr⁻¹ * A) / (pB + ifp.fr⁻¹ * B) - A / B = (-1)^n / (B * (ifp.fr⁻¹ * B + pB)), by rwa g_finite_correctness, -- To continue, we need use the determinant equality. So let's derive the needed hypothesis. have n_eq_zero_or_not_terminated_at_pred_n : n = 0 ∨ ¬g.terminated_at (n - 1), by { cases n with n', { simp }, { have : int_fract_pair.stream v (n' + 1) ≠ none, by simp [stream_nth_eq], have : ¬g.terminated_at n', from (not_iff_not_of_iff of_terminated_at_n_iff_succ_nth_int_fract_pair_stream_eq_none) .elim_right this, exact (or.inr this) } }, have determinant_eq : pA * B - pB * A = (-1)^n, from determinant_aux n_eq_zero_or_not_terminated_at_pred_n, -- now all we got to do is to rewrite this equality in our goal and re-arrange terms; -- however, for this, we first have to derive quite a few tedious inequalities. have pB_ineq : (fib n : K) ≤ pB, by { have : n ≤ 1 ∨ ¬g.terminated_at (n - 2), by { cases n_eq_zero_or_not_terminated_at_pred_n with n_eq_zero not_terminated_at_pred_n, { simp [n_eq_zero] }, { exact (or.inr $ mt (terminated_stable (n - 1).pred_le) not_terminated_at_pred_n) } }, exact (fib_le_of_continuants_aux_b this) }, have B_ineq : (fib (n + 1) : K) ≤ B, by { have : n + 1 ≤ 1 ∨ ¬g.terminated_at (n + 1 - 2), by { cases n_eq_zero_or_not_terminated_at_pred_n with n_eq_zero not_terminated_at_pred_n, { simp [n_eq_zero, le_refl] }, { exact (or.inr not_terminated_at_pred_n) } }, exact (fib_le_of_continuants_aux_b this) }, have zero_lt_B : 0 < B, { have : 1 ≤ B, from le_trans (by exact_mod_cast fib_pos (lt_of_le_of_ne n.succ.zero_le n.succ_ne_zero.symm)) B_ineq, exact (lt_of_lt_of_le zero_lt_one this) }, have zero_ne_B : 0 ≠ B, from ne_of_lt zero_lt_B, have : 0 ≠ pB + ifp.fr⁻¹ * B, by { have : (0 : K) ≤ fib n, by exact_mod_cast (fib n).zero_le, -- 0 ≤ fib n ≤ pB have zero_le_pB : 0 ≤ pB, from le_trans this pB_ineq, have : 0 < ifp.fr⁻¹, by { suffices : 0 < ifp.fr, by rwa inv_pos, have : 0 ≤ ifp.fr, from int_fract_pair.nth_stream_fr_nonneg stream_nth_eq, change ifp.fr ≠ 0 at ifp_fr_ne_zero, exact lt_of_le_of_ne this ifp_fr_ne_zero.symm }, have : 0 < ifp.fr⁻¹ * B, from mul_pos this zero_lt_B, have : 0 < pB + ifp.fr⁻¹ * B, from add_pos_of_nonneg_of_pos zero_le_pB this, exact (ne_of_lt this) }, -- finally, let's do the rewriting calc (pA + ifp.fr⁻¹ * A) / (pB + ifp.fr⁻¹ * B) - A / B = ((pA + ifp.fr⁻¹ * A) * B - (pB + ifp.fr⁻¹ * B) * A) / ((pB + ifp.fr⁻¹ * B) * B) : by rw (div_sub_div _ _ this.symm zero_ne_B.symm) ... = (pA * B + ifp.fr⁻¹ * A * B - (pB * A + ifp.fr⁻¹ * B * A)) / _ : by repeat { rw [add_mul] } ... = (pA * B - pB * A) / ((pB + ifp.fr⁻¹ * B) * B) : by ring ... = (-1)^n / ((pB + ifp.fr⁻¹ * B) * B) : by rw determinant_eq ... = (-1)^n / (B * (ifp.fr⁻¹ * B + pB)) : by ac_refl } end /-- Shows that `|v - Aₙ / Bₙ| ≤ 1 / (Bₙ * Bₙ₊₁)` -/ theorem abs_sub_convergents_le (not_terminated_at_n : ¬(of v).terminated_at n) : |v - (of v).convergents n| ≤ 1 / (((of v).denominators n) * ((of v).denominators $ n + 1)) := begin -- shorthand notation let g := of v, let nextConts := g.continuants_aux (n + 2), set conts := continuants_aux g (n + 1) with conts_eq, set pred_conts := continuants_aux g n with pred_conts_eq, -- change the goal to something more readable change |v - convergents g n| ≤ 1 / (conts.b * nextConts.b), obtain ⟨gp, s_nth_eq⟩ : ∃ gp, g.s.nth n = some gp, from option.ne_none_iff_exists'.elim_left not_terminated_at_n, have gp_a_eq_one : gp.a = 1, from of_part_num_eq_one (part_num_eq_s_a s_nth_eq), -- unfold the recurrence relation for `nextConts.b` have nextConts_b_eq : nextConts.b = pred_conts.b + gp.b * conts.b, by simp [nextConts, (continuants_aux_recurrence s_nth_eq pred_conts_eq conts_eq), gp_a_eq_one, pred_conts_eq.symm, conts_eq.symm, add_comm], let denom := conts.b * (pred_conts.b + gp.b * conts.b), suffices : |v - g.convergents n| ≤ 1 / denom, by { rw [nextConts_b_eq], congr' 1 }, obtain ⟨ifp_succ_n, succ_nth_stream_eq, ifp_succ_n_b_eq_gp_b⟩ : ∃ ifp_succ_n, int_fract_pair.stream v (n + 1) = some ifp_succ_n ∧ (ifp_succ_n.b : K) = gp.b, from int_fract_pair.exists_succ_nth_stream_of_gcf_of_nth_eq_some s_nth_eq, obtain ⟨ifp_n, stream_nth_eq, stream_nth_fr_ne_zero, if_of_eq_ifp_succ_n⟩ : ∃ ifp_n, int_fract_pair.stream v n = some ifp_n ∧ ifp_n.fr ≠ 0 ∧ int_fract_pair.of ifp_n.fr⁻¹ = ifp_succ_n, from int_fract_pair.succ_nth_stream_eq_some_iff.elim_left succ_nth_stream_eq, let denom' := conts.b * (pred_conts.b + ifp_n.fr⁻¹ * conts.b), -- now we can use `sub_convergents_eq` to simplify our goal suffices : |(-1)^n / denom'| ≤ 1 / denom, by { have : v - g.convergents n = (-1)^n / denom', by { -- apply `sub_convergens_eq` and simplify the result have tmp, from sub_convergents_eq stream_nth_eq, delta at tmp, simp only [stream_nth_fr_ne_zero, conts_eq.symm, pred_conts_eq.symm] at tmp, rw tmp, simp only [denom'], ring_nf }, rwa this }, -- derive some tedious inequalities that we need to rewrite our goal have nextConts_b_ineq : (fib (n + 2) : K) ≤ (pred_conts.b + gp.b * conts.b), by { have : (fib (n + 2) : K) ≤ nextConts.b, from fib_le_of_continuants_aux_b (or.inr not_terminated_at_n), rwa [nextConts_b_eq] at this }, have conts_b_ineq : (fib (n + 1) : K) ≤ conts.b, by { have : ¬g.terminated_at (n - 1), from mt (terminated_stable n.pred_le) not_terminated_at_n, exact (fib_le_of_continuants_aux_b $ or.inr this) }, have zero_lt_conts_b : 0 < conts.b, by { have : (0 : K) < fib (n + 1), by exact_mod_cast (fib_pos (lt_of_le_of_ne n.succ.zero_le n.succ_ne_zero.symm)), exact (lt_of_lt_of_le this conts_b_ineq) }, -- `denom'` is positive, so we can remove `|⬝|` from our goal suffices : 1 / denom' ≤ 1 / denom, by { have : |(-1)^n / denom'| = 1 / denom', by { suffices : 1 / |denom'| = 1 / denom', by rwa [abs_div, (abs_neg_one_pow n)], have : 0 < denom', by { have : 0 ≤ pred_conts.b, by { have : (fib n : K) ≤ pred_conts.b, by { have : ¬g.terminated_at (n - 2), from mt (terminated_stable (n.sub_le 2)) not_terminated_at_n, exact (fib_le_of_continuants_aux_b $ or.inr this) }, exact le_trans (by exact_mod_cast (fib n).zero_le) this }, have : 0 < ifp_n.fr⁻¹, by { have zero_le_ifp_n_fract : 0 ≤ ifp_n.fr, from int_fract_pair.nth_stream_fr_nonneg stream_nth_eq, exact inv_pos.elim_right (lt_of_le_of_ne zero_le_ifp_n_fract stream_nth_fr_ne_zero.symm) }, any_goals { repeat { apply mul_pos <|> apply add_pos_of_nonneg_of_pos } }; assumption }, rwa (abs_of_pos this) }, rwa this }, suffices : 0 < denom ∧ denom ≤ denom', from div_le_div_of_le_left zero_le_one this.left this.right, split, { have : 0 < pred_conts.b + gp.b * conts.b, from lt_of_lt_of_le (by exact_mod_cast (fib_pos (lt_of_le_of_ne n.succ.succ.zero_le n.succ.succ_ne_zero.symm))) nextConts_b_ineq, solve_by_elim [mul_pos] }, { -- we can cancel multiplication by `conts.b` and addition with `pred_conts.b` suffices : gp.b * conts.b ≤ ifp_n.fr⁻¹ * conts.b, from ((mul_le_mul_left zero_lt_conts_b).elim_right $ (add_le_add_iff_left pred_conts.b).elim_right this), suffices : (ifp_succ_n.b : K) * conts.b ≤ ifp_n.fr⁻¹ * conts.b, by rwa [←ifp_succ_n_b_eq_gp_b], have : (ifp_succ_n.b : K) ≤ ifp_n.fr⁻¹, from int_fract_pair.succ_nth_stream_b_le_nth_stream_fr_inv stream_nth_eq succ_nth_stream_eq, have : 0 ≤ conts.b, from le_of_lt zero_lt_conts_b, mono } end /-- Shows that `|v - Aₙ / Bₙ| ≤ 1 / (bₙ * Bₙ * Bₙ)`. This bound is worse than the one shown in `gcf.abs_sub_convergents_le`, but sometimes it is easier to apply and sufficient for one's use case. -/ lemma abs_sub_convergents_le' {b : K} (nth_part_denom_eq : (of v).partial_denominators.nth n = some b) : |v - (of v).convergents n| ≤ 1 / (b * ((of v).denominators n) * ((of v).denominators n)) := begin have not_terminated_at_n : ¬(of v).terminated_at n, by simp [terminated_at_iff_part_denom_none, nth_part_denom_eq], refine (abs_sub_convergents_le not_terminated_at_n).trans _, -- One can show that `0 < (generalized_continued_fraction.of v).denominators n` but it's easier -- to consider the case `(generalized_continued_fraction.of v).denominators n = 0`. rcases zero_le_of_denom.eq_or_gt with (hB : (generalized_continued_fraction.of v).denominators n = 0) | hB, { simp only [hB, mul_zero, zero_mul, div_zero] }, { apply one_div_le_one_div_of_le, { have : 0 < b := zero_lt_one.trans_le (of_one_le_nth_part_denom nth_part_denom_eq), apply_rules [mul_pos] }, { conv_rhs { rw [mul_comm] }, exact mul_le_mul_of_nonneg_right (le_of_succ_nth_denom nth_part_denom_eq) hB.le } } end end error_term end generalized_continued_fraction
785254eeb9fc85a28410d60f48b4a68445cb9d0d
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/group_theory/perm/cycle/concrete.lean
beceaf7abf0ccc07a8d37be66558e8461b78d7e1
[ "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,749
lean
/- Copyright (c) 2021 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import data.list.cycle import group_theory.perm.cycle.type import group_theory.perm.list /-! # Properties of cyclic permutations constructed from lists/cycles In the following, `{α : Type*} [fintype α] [decidable_eq α]`. ## Main definitions * `cycle.form_perm`: the cyclic permutation created by looping over a `cycle α` * `equiv.perm.to_list`: the list formed by iterating application of a permutation * `equiv.perm.to_cycle`: the cycle formed by iterating application of a permutation * `equiv.perm.iso_cycle`: the equivalence between cyclic permutations `f : perm α` and the terms of `cycle α` that correspond to them * `equiv.perm.iso_cycle'`: the same equivalence as `equiv.perm.iso_cycle` but with evaluation via choosing over fintypes * The notation `c[1, 2, 3]` to emulate notation of cyclic permutations `(1 2 3)` * A `has_repr` instance for any `perm α`, by representing the `finset` of `cycle α` that correspond to the cycle factors. ## Main results * `list.is_cycle_form_perm`: a nontrivial list without duplicates, when interpreted as a permutation, is cyclic * `equiv.perm.is_cycle.exists_unique_cycle`: there is only one nontrivial `cycle α` corresponding to each cyclic `f : perm α` ## Implementation details The forward direction of `equiv.perm.iso_cycle'` uses `fintype.choose` of the uniqueness result, relying on the `fintype` instance of a `cycle.nodup` subtype. It is unclear if this works faster than the `equiv.perm.to_cycle`, which relies on recursion over `finset.univ`. Running `#eval` on even a simple noncyclic permutation `c[(1 : fin 7), 2, 3] * c[0, 5]` to show it takes a long time. TODO: is this because computing the cycle factors is slow? -/ open equiv equiv.perm list variables {α : Type*} namespace list variables [decidable_eq α] {l l' : list α} lemma form_perm_disjoint_iff (hl : nodup l) (hl' : nodup l') (hn : 2 ≤ l.length) (hn' : 2 ≤ l'.length) : perm.disjoint (form_perm l) (form_perm l') ↔ l.disjoint l' := begin rw [disjoint_iff_eq_or_eq, list.disjoint], split, { rintro h x hx hx', specialize h x, rw [form_perm_apply_mem_eq_self_iff _ hl _ hx, form_perm_apply_mem_eq_self_iff _ hl' _ hx'] at h, rcases h with hl | hl'; linarith }, { intros h x, by_cases hx : x ∈ l, by_cases hx' : x ∈ l', { exact (h hx hx').elim }, all_goals { have := form_perm_eq_self_of_not_mem _ _ ‹_›, tauto } } end lemma is_cycle_form_perm (hl : nodup l) (hn : 2 ≤ l.length) : is_cycle (form_perm l) := begin cases l with x l, { norm_num at hn }, induction l with y l IH generalizing x, { norm_num at hn }, { use x, split, { rwa form_perm_apply_mem_ne_self_iff _ hl _ (mem_cons_self _ _) }, { intros w hw, have : w ∈ (x :: y :: l) := mem_of_form_perm_ne_self _ _ hw, obtain ⟨k, hk, rfl⟩ := nth_le_of_mem this, use k, simp only [zpow_coe_nat, form_perm_pow_apply_head _ _ hl k, nat.mod_eq_of_lt hk] } } end lemma pairwise_same_cycle_form_perm (hl : nodup l) (hn : 2 ≤ l.length) : pairwise (l.form_perm.same_cycle) l := pairwise.imp_mem.mpr (pairwise_of_forall (λ x y hx hy, (is_cycle_form_perm hl hn).same_cycle ((form_perm_apply_mem_ne_self_iff _ hl _ hx).mpr hn) ((form_perm_apply_mem_ne_self_iff _ hl _ hy).mpr hn))) lemma cycle_of_form_perm (hl : nodup l) (hn : 2 ≤ l.length) (x) : cycle_of l.attach.form_perm x = l.attach.form_perm := have hn : 2 ≤ l.attach.length := by rwa ← length_attach at hn, have hl : l.attach.nodup := by rwa ← nodup_attach at hl, (is_cycle_form_perm hl hn).cycle_of_eq ((form_perm_apply_mem_ne_self_iff _ hl _ (mem_attach _ _)).mpr hn) lemma cycle_type_form_perm (hl : nodup l) (hn : 2 ≤ l.length) : cycle_type l.attach.form_perm = {l.length} := begin rw ←length_attach at hn, rw ←nodup_attach at hl, rw cycle_type_eq [l.attach.form_perm], { simp only [map, function.comp_app], rw [support_form_perm_of_nodup _ hl, card_to_finset, dedup_eq_self.mpr hl], { simp }, { intros x h, simpa [h, nat.succ_le_succ_iff] using hn } }, { simp }, { simpa using is_cycle_form_perm hl hn }, { simp } end lemma form_perm_apply_mem_eq_next (hl : nodup l) (x : α) (hx : x ∈ l) : form_perm l x = next l x hx := begin obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx, rw [next_nth_le _ hl, form_perm_apply_nth_le _ hl] end end list namespace cycle variables [decidable_eq α] (s s' : cycle α) /-- A cycle `s : cycle α` , given `nodup s` can be interpreted as a `equiv.perm α` where each element in the list is permuted to the next one, defined as `form_perm`. -/ def form_perm : Π (s : cycle α) (h : nodup s), equiv.perm α := λ s, quot.hrec_on s (λ l h, form_perm l) (λ l₁ l₂ (h : l₁ ~r l₂), begin ext, { exact h.nodup_iff }, { intros h₁ h₂ _, exact heq_of_eq (form_perm_eq_of_is_rotated h₁ h) } end) @[simp] lemma form_perm_coe (l : list α) (hl : l.nodup) : form_perm (l : cycle α) hl = l.form_perm := rfl lemma form_perm_subsingleton (s : cycle α) (h : subsingleton s) : form_perm s h.nodup = 1 := begin induction s using quot.induction_on, simp only [form_perm_coe, mk_eq_coe], simp only [length_subsingleton_iff, length_coe, mk_eq_coe] at h, cases s with hd tl, { simp }, { simp only [length_eq_zero, add_le_iff_nonpos_left, list.length, nonpos_iff_eq_zero] at h, simp [h] } end lemma is_cycle_form_perm (s : cycle α) (h : nodup s) (hn : nontrivial s) : is_cycle (form_perm s h) := begin induction s using quot.induction_on, exact list.is_cycle_form_perm h (length_nontrivial hn) end lemma support_form_perm [fintype α] (s : cycle α) (h : nodup s) (hn : nontrivial s) : support (form_perm s h) = s.to_finset := begin induction s using quot.induction_on, refine support_form_perm_of_nodup s h _, rintro _ rfl, simpa [nat.succ_le_succ_iff] using length_nontrivial hn end lemma form_perm_eq_self_of_not_mem (s : cycle α) (h : nodup s) (x : α) (hx : x ∉ s) : form_perm s h x = x := begin induction s using quot.induction_on, simpa using list.form_perm_eq_self_of_not_mem _ _ hx end lemma form_perm_apply_mem_eq_next (s : cycle α) (h : nodup s) (x : α) (hx : x ∈ s) : form_perm s h x = next s h x hx := begin induction s using quot.induction_on, simpa using list.form_perm_apply_mem_eq_next h _ _ end lemma form_perm_reverse (s : cycle α) (h : nodup s) : form_perm s.reverse (nodup_reverse_iff.mpr h) = (form_perm s h)⁻¹ := begin induction s using quot.induction_on, simpa using form_perm_reverse _ h end lemma form_perm_eq_form_perm_iff {α : Type*} [decidable_eq α] {s s' : cycle α} {hs : s.nodup} {hs' : s'.nodup} : s.form_perm hs = s'.form_perm hs' ↔ s = s' ∨ s.subsingleton ∧ s'.subsingleton := begin rw [cycle.length_subsingleton_iff, cycle.length_subsingleton_iff], revert s s', intros s s', apply quotient.induction_on₂' s s', intros l l', simpa using form_perm_eq_form_perm_iff end end cycle namespace equiv.perm section fintype variables [fintype α] [decidable_eq α] (p : equiv.perm α) (x : α) /-- `equiv.perm.to_list (f : perm α) (x : α)` generates the list `[x, f x, f (f x), ...]` until looping. That means when `f x = x`, `to_list f x = []`. -/ def to_list : list α := (list.range (cycle_of p x).support.card).map (λ k, (p ^ k) x) @[simp] lemma to_list_one : to_list (1 : perm α) x = [] := by simp [to_list, cycle_of_one] @[simp] lemma to_list_eq_nil_iff {p : perm α} {x} : to_list p x = [] ↔ x ∉ p.support := by simp [to_list] @[simp] lemma length_to_list : length (to_list p x) = (cycle_of p x).support.card := by simp [to_list] lemma to_list_ne_singleton (y : α) : to_list p x ≠ [y] := begin intro H, simpa [card_support_ne_one] using congr_arg length H end lemma two_le_length_to_list_iff_mem_support {p : perm α} {x : α} : 2 ≤ length (to_list p x) ↔ x ∈ p.support := by simp lemma length_to_list_pos_of_mem_support (h : x ∈ p.support) : 0 < length (to_list p x) := zero_lt_two.trans_le (two_le_length_to_list_iff_mem_support.mpr h) lemma nth_le_to_list (n : ℕ) (hn : n < length (to_list p x)) : nth_le (to_list p x) n hn = (p ^ n) x := by simp [to_list] lemma to_list_nth_le_zero (h : x ∈ p.support) : (to_list p x).nth_le 0 (length_to_list_pos_of_mem_support _ _ h) = x := by simp [to_list] variables {p} {x} lemma mem_to_list_iff {y : α} : y ∈ to_list p x ↔ same_cycle p x y ∧ x ∈ p.support := begin simp only [to_list, mem_range, mem_map], split, { rintro ⟨n, hx, rfl⟩, refine ⟨⟨n, rfl⟩, _⟩, contrapose! hx, rw ←support_cycle_of_eq_nil_iff at hx, simp [hx] }, { rintro ⟨h, hx⟩, simpa using same_cycle.nat_of_mem_support _ h hx } end lemma nodup_to_list (p : perm α) (x : α) : nodup (to_list p x) := begin by_cases hx : p x = x, { rw [←not_mem_support, ←to_list_eq_nil_iff] at hx, simp [hx] }, have hc : is_cycle (cycle_of p x) := is_cycle_cycle_of p hx, rw nodup_iff_nth_le_inj, rintros n m hn hm, rw [length_to_list, ←order_of_is_cycle hc] at hm hn, rw [←cycle_of_apply_self, ←ne.def, ←mem_support] at hx, rw [nth_le_to_list, nth_le_to_list, ←cycle_of_pow_apply_self p x n, ←cycle_of_pow_apply_self p x m], cases n; cases m, { simp }, { rw [←hc.mem_support_pos_pow_iff_of_lt_order_of m.zero_lt_succ hm, mem_support, cycle_of_pow_apply_self] at hx, simp [hx.symm] }, { rw [←hc.mem_support_pos_pow_iff_of_lt_order_of n.zero_lt_succ hn, mem_support, cycle_of_pow_apply_self] at hx, simp [hx] }, intro h, have hn' : ¬ order_of (p.cycle_of x) ∣ n.succ := nat.not_dvd_of_pos_of_lt n.zero_lt_succ hn, have hm' : ¬ order_of (p.cycle_of x) ∣ m.succ := nat.not_dvd_of_pos_of_lt m.zero_lt_succ hm, rw ←hc.support_pow_eq_iff at hn' hm', rw [←nat.mod_eq_of_lt hn, ←nat.mod_eq_of_lt hm, ←pow_inj_mod], refine support_congr _ _, { rw [hm', hn'], exact finset.subset.refl _ }, { rw hm', intros y hy, obtain ⟨k, rfl⟩ := hc.exists_pow_eq (mem_support.mp hx) (mem_support.mp hy), rw [←mul_apply, (commute.pow_pow_self _ _ _).eq, mul_apply, h, ←mul_apply, ←mul_apply, (commute.pow_pow_self _ _ _).eq] } end lemma next_to_list_eq_apply (p : perm α) (x y : α) (hy : y ∈ to_list p x) : next (to_list p x) y hy = p y := begin rw mem_to_list_iff at hy, obtain ⟨k, hk, hk'⟩ := hy.left.nat_of_mem_support _ hy.right, rw ←nth_le_to_list p x k (by simpa using hk) at hk', simp_rw ←hk', rw [next_nth_le _ (nodup_to_list _ _), nth_le_to_list, nth_le_to_list, ←mul_apply, ←pow_succ, length_to_list, pow_apply_eq_pow_mod_order_of_cycle_of_apply p (k + 1), order_of_is_cycle], exact is_cycle_cycle_of _ (mem_support.mp hy.right) end lemma to_list_pow_apply_eq_rotate (p : perm α) (x : α) (k : ℕ) : p.to_list ((p ^ k) x) = (p.to_list x).rotate k := begin apply ext_le, { simp }, { intros n hn hn', rw [nth_le_to_list, nth_le_rotate, nth_le_to_list, length_to_list, pow_mod_card_support_cycle_of_self_apply, pow_add, mul_apply] } end lemma same_cycle.to_list_is_rotated {f : perm α} {x y : α} (h : same_cycle f x y) : to_list f x ~r to_list f y := begin by_cases hx : x ∈ f.support, { obtain ⟨_ | k, hk, hy⟩ := h.nat_of_mem_support _ hx, { simp only [coe_one, id.def, pow_zero] at hy, simp [hy] }, use k.succ, rw [←to_list_pow_apply_eq_rotate, hy] }, { rw [to_list_eq_nil_iff.mpr hx, is_rotated_nil_iff', eq_comm, to_list_eq_nil_iff], rwa ←h.mem_support_iff } end lemma pow_apply_mem_to_list_iff_mem_support {n : ℕ} : (p ^ n) x ∈ p.to_list x ↔ x ∈ p.support := begin rw [mem_to_list_iff, and_iff_right_iff_imp], refine λ _, same_cycle.symm _, rw same_cycle_pow_left_iff end lemma to_list_form_perm_nil (x : α) : to_list (form_perm ([] : list α)) x = [] := by simp lemma to_list_form_perm_singleton (x y : α) : to_list (form_perm [x]) y = [] := by simp lemma to_list_form_perm_nontrivial (l : list α) (hl : 2 ≤ l.length) (hn : nodup l) : to_list (form_perm l) (l.nth_le 0 (zero_lt_two.trans_le hl)) = l := begin have hc : l.form_perm.is_cycle := list.is_cycle_form_perm hn hl, have hs : l.form_perm.support = l.to_finset, { refine support_form_perm_of_nodup _ hn _, rintro _ rfl, simpa [nat.succ_le_succ_iff] using hl }, rw [to_list, hc.cycle_of_eq (mem_support.mp _), hs, card_to_finset, dedup_eq_self.mpr hn], { refine list.ext_le (by simp) (λ k hk hk', _), simp [form_perm_pow_apply_nth_le _ hn, nat.mod_eq_of_lt hk'] }, { simpa [hs] using nth_le_mem _ _ _ } end lemma to_list_form_perm_is_rotated_self (l : list α) (hl : 2 ≤ l.length) (hn : nodup l) (x : α) (hx : x ∈ l): to_list (form_perm l) x ~r l := begin obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx, have hr : l ~r l.rotate k := ⟨k, rfl⟩, rw form_perm_eq_of_is_rotated hn hr, rw ←nth_le_rotate' l k k, simp only [nat.mod_eq_of_lt hk, tsub_add_cancel_of_le hk.le, nat.mod_self], rw [to_list_form_perm_nontrivial], { simp }, { simpa using hl }, { simpa using hn } end lemma form_perm_to_list (f : perm α) (x : α) : form_perm (to_list f x) = f.cycle_of x := begin by_cases hx : f x = x, { rw [(cycle_of_eq_one_iff f).mpr hx, to_list_eq_nil_iff.mpr (not_mem_support.mpr hx), form_perm_nil] }, ext y, by_cases hy : same_cycle f x y, { obtain ⟨k, hk, rfl⟩ := hy.nat_of_mem_support _ (mem_support.mpr hx), rw [cycle_of_apply_apply_pow_self, list.form_perm_apply_mem_eq_next (nodup_to_list f x), next_to_list_eq_apply, pow_succ, mul_apply], rw mem_to_list_iff, exact ⟨⟨k, rfl⟩, mem_support.mpr hx⟩ }, { rw [cycle_of_apply_of_not_same_cycle hy, form_perm_apply_of_not_mem], simp [mem_to_list_iff, hy] } end /-- Given a cyclic `f : perm α`, generate the `cycle α` in the order of application of `f`. Implemented by finding an element `x : α` in the support of `f` in `finset.univ`, and iterating on using `equiv.perm.to_list f x`. -/ def to_cycle (f : perm α) (hf : is_cycle f) : cycle α := multiset.rec_on (finset.univ : finset α).val (quot.mk _ []) (λ x s l, if f x = x then l else to_list f x) (by { intros x y m s, refine heq_of_eq _, split_ifs with hx hy hy; try { refl }, { have hc : same_cycle f x y := is_cycle.same_cycle hf hx hy, exact quotient.sound' hc.to_list_is_rotated }}) lemma to_cycle_eq_to_list (f : perm α) (hf : is_cycle f) (x : α) (hx : f x ≠ x) : to_cycle f hf = to_list f x := begin have key : (finset.univ : finset α).val = x ::ₘ finset.univ.val.erase x, { simp }, rw [to_cycle, key], simp [hx] end lemma nodup_to_cycle (f : perm α) (hf : is_cycle f) : (to_cycle f hf).nodup := begin obtain ⟨x, hx, -⟩ := id hf, simpa [to_cycle_eq_to_list f hf x hx] using nodup_to_list _ _ end lemma nontrivial_to_cycle (f : perm α) (hf : is_cycle f) : (to_cycle f hf).nontrivial := begin obtain ⟨x, hx, -⟩ := id hf, simp [to_cycle_eq_to_list f hf x hx, hx, cycle.nontrivial_coe_nodup_iff (nodup_to_list _ _)] end /-- Any cyclic `f : perm α` is isomorphic to the nontrivial `cycle α` that corresponds to repeated application of `f`. The forward direction is implemented by `equiv.perm.to_cycle`. -/ def iso_cycle : {f : perm α // is_cycle f} ≃ {s : cycle α // s.nodup ∧ s.nontrivial} := { to_fun := λ f, ⟨to_cycle (f : perm α) f.prop, nodup_to_cycle f f.prop, nontrivial_to_cycle _ f.prop⟩, inv_fun := λ s, ⟨(s : cycle α).form_perm s.prop.left, (s : cycle α).is_cycle_form_perm _ s.prop.right⟩, left_inv := λ f, by { obtain ⟨x, hx, -⟩ := id f.prop, simpa [to_cycle_eq_to_list (f : perm α) f.prop x hx, form_perm_to_list, subtype.ext_iff] using f.prop.cycle_of_eq hx }, right_inv := λ s, by { rcases s with ⟨⟨s⟩, hn, ht⟩, obtain ⟨x, -, -, hx, -⟩ := id ht, have hl : 2 ≤ s.length := by simpa using cycle.length_nontrivial ht, simp only [cycle.mk_eq_coe, cycle.nodup_coe_iff, cycle.mem_coe_iff, subtype.coe_mk, cycle.form_perm_coe] at hn hx ⊢, rw to_cycle_eq_to_list _ _ x, { refine quotient.sound' _, exact to_list_form_perm_is_rotated_self _ hl hn _ hx }, { rw [←mem_support, support_form_perm_of_nodup _ hn], { simpa using hx }, { rintro _ rfl, simpa [nat.succ_le_succ_iff] using hl } } } } end fintype section finite variables [finite α] [decidable_eq α] lemma is_cycle.exists_unique_cycle {f : perm α} (hf : is_cycle f) : ∃! (s : cycle α), ∃ (h : s.nodup), s.form_perm h = f := begin casesI nonempty_fintype α, obtain ⟨x, hx, hy⟩ := id hf, refine ⟨f.to_list x, ⟨nodup_to_list f x, _⟩, _⟩, { simp [form_perm_to_list, hf.cycle_of_eq hx] }, { rintro ⟨l⟩ ⟨hn, rfl⟩, simp only [cycle.mk_eq_coe, cycle.coe_eq_coe, subtype.coe_mk, cycle.form_perm_coe], refine (to_list_form_perm_is_rotated_self _ _ hn _ _).symm, { contrapose! hx, suffices : form_perm l = 1, { simp [this] }, rw form_perm_eq_one_iff _ hn, exact nat.le_of_lt_succ hx }, { rw ←mem_to_finset, refine support_form_perm_le l _, simpa using hx } } end lemma is_cycle.exists_unique_cycle_subtype {f : perm α} (hf : is_cycle f) : ∃! (s : {s : cycle α // s.nodup}), (s : cycle α).form_perm s.prop = f := begin obtain ⟨s, ⟨hs, rfl⟩, hs'⟩ := hf.exists_unique_cycle, refine ⟨⟨s, hs⟩, rfl, _⟩, rintro ⟨t, ht⟩ ht', simpa using hs' _ ⟨ht, ht'⟩ end lemma is_cycle.exists_unique_cycle_nontrivial_subtype {f : perm α} (hf : is_cycle f) : ∃! (s : {s : cycle α // s.nodup ∧ s.nontrivial}), (s : cycle α).form_perm s.prop.left = f := begin obtain ⟨⟨s, hn⟩, hs, hs'⟩ := hf.exists_unique_cycle_subtype, refine ⟨⟨s, hn, _⟩, _, _⟩, { rw hn.nontrivial_iff, subst f, intro H, refine hf.ne_one _, simpa using cycle.form_perm_subsingleton _ H }, { simpa using hs }, { rintro ⟨t, ht, ht'⟩ ht'', simpa using hs' ⟨t, ht⟩ ht'' } end end finite variables [fintype α] [decidable_eq α] /-- Any cyclic `f : perm α` is isomorphic to the nontrivial `cycle α` that corresponds to repeated application of `f`. The forward direction is implemented by finding this `cycle α` using `fintype.choose`. -/ def iso_cycle' : {f : perm α // is_cycle f} ≃ {s : cycle α // s.nodup ∧ s.nontrivial} := { to_fun := λ f, fintype.choose _ f.prop.exists_unique_cycle_nontrivial_subtype, inv_fun := λ s, ⟨(s : cycle α).form_perm s.prop.left, (s : cycle α).is_cycle_form_perm _ s.prop.right⟩, left_inv := λ f, by simpa [subtype.ext_iff] using fintype.choose_spec _ f.prop.exists_unique_cycle_nontrivial_subtype, right_inv := λ ⟨s, hs, ht⟩, by { simp [subtype.coe_mk], convert fintype.choose_subtype_eq (λ (s' : cycle α), s'.nodup ∧ s'.nontrivial) _, ext ⟨s', hs', ht'⟩, simp [cycle.form_perm_eq_form_perm_iff, (iff_not_comm.mp hs.nontrivial_iff), (iff_not_comm.mp hs'.nontrivial_iff), ht] } } notation `c[` l:(foldr `, ` (h t, list.cons h t) list.nil `]`) := cycle.form_perm ↑l (cycle.nodup_coe_iff.mpr dec_trivial) instance repr_perm [has_repr α] : has_repr (perm α) := ⟨λ f, repr (multiset.pmap (λ (g : perm α) (hg : g.is_cycle), iso_cycle ⟨g, hg⟩) -- to_cycle is faster? (perm.cycle_factors_finset f).val (λ g hg, (mem_cycle_factors_finset_iff.mp (finset.mem_def.mpr hg)).left))⟩ end equiv.perm
d535ae9530eb593b9ce10bc428e1e401ef9cd7f0
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/algebra/ordered_ring.lean
6333be0c6288e9eca356a4a0351f7af35f346997
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
20,384
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import tactic.split_ifs order.basic algebra.order algebra.ordered_group algebra.ring data.nat.cast universe u variable {α : Type u} -- `mul_nonneg` and `mul_pos` in core are stated in terms of `≥` and `>`, so we restate them here -- for use in syntactic tactics (e.g. `simp` and `rw`). lemma mul_nonneg' [ordered_semiring α] {a b : α} : 0 ≤ a → 0 ≤ b → 0 ≤ a * b := mul_nonneg lemma mul_pos' [ordered_semiring α] {a b : α} (ha : 0 < a) (hb : 0 < b) : 0 < a * b := mul_pos ha hb section linear_ordered_semiring variable [linear_ordered_semiring α] @[simp] lemma mul_le_mul_left {a b c : α} (h : 0 < c) : c * a ≤ c * b ↔ a ≤ b := ⟨λ h', le_of_mul_le_mul_left h' h, λ h', mul_le_mul_of_nonneg_left h' (le_of_lt h)⟩ @[simp] lemma mul_le_mul_right {a b c : α} (h : 0 < c) : a * c ≤ b * c ↔ a ≤ b := ⟨λ h', le_of_mul_le_mul_right h' h, λ h', mul_le_mul_of_nonneg_right h' (le_of_lt h)⟩ @[simp] lemma mul_lt_mul_left {a b c : α} (h : 0 < c) : c * a < c * b ↔ a < b := ⟨lt_imp_lt_of_le_imp_le $ λ h', mul_le_mul_of_nonneg_left h' (le_of_lt h), λ h', mul_lt_mul_of_pos_left h' h⟩ @[simp] lemma mul_lt_mul_right {a b c : α} (h : 0 < c) : a * c < b * c ↔ a < b := ⟨lt_imp_lt_of_le_imp_le $ λ h', mul_le_mul_of_nonneg_right h' (le_of_lt h), λ h', mul_lt_mul_of_pos_right h' h⟩ lemma mul_lt_mul'' {a b c d : α} (h1 : a < c) (h2 : b < d) (h3 : 0 ≤ a) (h4 : 0 ≤ b) : a * b < c * d := (lt_or_eq_of_le h4).elim (λ b0, mul_lt_mul h1 (le_of_lt h2) b0 (le_trans h3 (le_of_lt h1))) (λ b0, by rw [← b0, mul_zero]; exact mul_pos (lt_of_le_of_lt h3 h1) (lt_of_le_of_lt h4 h2)) lemma le_mul_iff_one_le_left {a b : α} (hb : 0 < b) : b ≤ a * b ↔ 1 ≤ a := suffices 1 * b ≤ a * b ↔ 1 ≤ a, by rwa one_mul at this, mul_le_mul_right hb lemma lt_mul_iff_one_lt_left {a b : α} (hb : 0 < b) : b < a * b ↔ 1 < a := suffices 1 * b < a * b ↔ 1 < a, by rwa one_mul at this, mul_lt_mul_right hb lemma le_mul_iff_one_le_right {a b : α} (hb : 0 < b) : b ≤ b * a ↔ 1 ≤ a := suffices b * 1 ≤ b * a ↔ 1 ≤ a, by rwa mul_one at this, mul_le_mul_left hb lemma lt_mul_iff_one_lt_right {a b : α} (hb : 0 < b) : b < b * a ↔ 1 < a := suffices b * 1 < b * a ↔ 1 < a, by rwa mul_one at this, mul_lt_mul_left hb lemma lt_mul_of_one_lt_right' {a b : α} (hb : 0 < b) : 1 < a → b < b * a := (lt_mul_iff_one_lt_right hb).2 lemma le_mul_of_one_le_right' {a b : α} (hb : 0 ≤ b) (h : 1 ≤ a) : b ≤ b * a := suffices b * 1 ≤ b * a, by rwa mul_one at this, mul_le_mul_of_nonneg_left h hb lemma le_mul_of_one_le_left' {a b : α} (hb : 0 ≤ b) (h : 1 ≤ a) : b ≤ a * b := suffices 1 * b ≤ a * b, by rwa one_mul at this, mul_le_mul_of_nonneg_right h hb theorem mul_nonneg_iff_right_nonneg_of_pos {a b : α} (h : 0 < a) : 0 ≤ b * a ↔ 0 ≤ b := ⟨assume : 0 ≤ b * a, nonneg_of_mul_nonneg_right this h, assume : 0 ≤ b, mul_nonneg this $ le_of_lt h⟩ lemma bit1_pos {a : α} (h : 0 ≤ a) : 0 < bit1 a := lt_add_of_le_of_pos (add_nonneg h h) zero_lt_one lemma bit1_pos' {a : α} (h : 0 < a) : 0 < bit1 a := bit1_pos (le_of_lt h) lemma lt_add_one (a : α) : a < a + 1 := lt_add_of_le_of_pos (le_refl _) zero_lt_one lemma lt_one_add (a : α) : a < 1 + a := by { rw [add_comm], apply lt_add_one } lemma one_lt_two : 1 < (2 : α) := lt_add_one _ lemma one_lt_mul {a b : α} (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b := (one_mul (1 : α)) ▸ mul_lt_mul' ha hb zero_le_one (lt_of_lt_of_le zero_lt_one ha) lemma mul_le_one {a b : α} (ha : a ≤ 1) (hb' : 0 ≤ b) (hb : b ≤ 1) : a * b ≤ 1 := begin rw ← one_mul (1 : α), apply mul_le_mul; {assumption <|> apply zero_le_one} end lemma one_lt_mul_of_le_of_lt {a b : α} (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b := calc 1 = 1 * 1 : by rw one_mul ... < a * b : mul_lt_mul' ha hb zero_le_one (lt_of_lt_of_le zero_lt_one ha) lemma one_lt_mul_of_lt_of_le {a b : α} (ha : 1 < a) (hb : 1 ≤ b) : 1 < a * b := calc 1 = 1 * 1 : by rw one_mul ... < a * b : mul_lt_mul ha hb zero_lt_one (le_trans zero_le_one (le_of_lt ha)) lemma mul_le_of_le_one_right {a b : α} (ha : 0 ≤ a) (hb1 : b ≤ 1) : a * b ≤ a := calc a * b ≤ a * 1 : mul_le_mul_of_nonneg_left hb1 ha ... = a : mul_one a lemma mul_le_of_le_one_left {a b : α} (hb : 0 ≤ b) (ha1 : a ≤ 1) : a * b ≤ b := calc a * b ≤ 1 * b : mul_le_mul ha1 (le_refl b) hb zero_le_one ... = b : one_mul b lemma mul_lt_one_of_nonneg_of_lt_one_left {a b : α} (ha0 : 0 ≤ a) (ha : a < 1) (hb : b ≤ 1) : a * b < 1 := calc a * b ≤ a : mul_le_of_le_one_right ha0 hb ... < 1 : ha lemma mul_lt_one_of_nonneg_of_lt_one_right {a b : α} (ha : a ≤ 1) (hb0 : 0 ≤ b) (hb : b < 1) : a * b < 1 := calc a * b ≤ b : mul_le_of_le_one_left hb0 ha ... < 1 : hb lemma mul_le_iff_le_one_left {a b : α} (hb : 0 < b) : a * b ≤ b ↔ a ≤ 1 := ⟨ λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).2 (not_lt_of_ge h)), λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).1 (not_lt_of_ge h)) ⟩ lemma mul_lt_iff_lt_one_left {a b : α} (hb : 0 < b) : a * b < b ↔ a < 1 := ⟨ λ h, lt_of_not_ge (mt (le_mul_iff_one_le_left hb).2 (not_le_of_gt h)), λ h, lt_of_not_ge (mt (le_mul_iff_one_le_left hb).1 (not_le_of_gt h)) ⟩ lemma mul_le_iff_le_one_right {a b : α} (hb : 0 < b) : b * a ≤ b ↔ a ≤ 1 := ⟨ λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).2 (not_lt_of_ge h)), λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).1 (not_lt_of_ge h)) ⟩ lemma mul_lt_iff_lt_one_right {a b : α} (hb : 0 < b) : b * a < b ↔ a < 1 := ⟨ λ h, lt_of_not_ge (mt (le_mul_iff_one_le_right hb).2 (not_le_of_gt h)), λ h, lt_of_not_ge (mt (le_mul_iff_one_le_right hb).1 (not_le_of_gt h)) ⟩ lemma nonpos_of_mul_nonneg_left {a b : α} (h : 0 ≤ a * b) (hb : b < 0) : a ≤ 0 := le_of_not_gt (λ ha, absurd h (not_le_of_gt (mul_neg_of_pos_of_neg ha hb))) lemma nonpos_of_mul_nonneg_right {a b : α} (h : 0 ≤ a * b) (ha : a < 0) : b ≤ 0 := le_of_not_gt (λ hb, absurd h (not_le_of_gt (mul_neg_of_neg_of_pos ha hb))) lemma neg_of_mul_pos_left {a b : α} (h : 0 < a * b) (hb : b ≤ 0) : a < 0 := lt_of_not_ge (λ ha, absurd h (not_lt_of_ge (mul_nonpos_of_nonneg_of_nonpos ha hb))) lemma neg_of_mul_pos_right {a b : α} (h : 0 < a * b) (ha : a ≤ 0) : b < 0 := lt_of_not_ge (λ hb, absurd h (not_lt_of_ge (mul_nonpos_of_nonpos_of_nonneg ha hb))) end linear_ordered_semiring section decidable_linear_ordered_semiring variable [decidable_linear_ordered_semiring α] @[simp] lemma decidable.mul_le_mul_left {a b c : α} (h : 0 < c) : c * a ≤ c * b ↔ a ≤ b := decidable.le_iff_le_iff_lt_iff_lt.2 $ mul_lt_mul_left h @[simp] lemma decidable.mul_le_mul_right {a b c : α} (h : 0 < c) : a * c ≤ b * c ↔ a ≤ b := decidable.le_iff_le_iff_lt_iff_lt.2 $ mul_lt_mul_right h end decidable_linear_ordered_semiring instance linear_ordered_semiring.to_no_top_order {α : Type*} [linear_ordered_semiring α] : no_top_order α := ⟨assume a, ⟨a + 1, lt_add_of_pos_right _ zero_lt_one⟩⟩ instance linear_ordered_semiring.to_no_bot_order {α : Type*} [linear_ordered_ring α] : no_bot_order α := ⟨assume a, ⟨a - 1, sub_lt_iff_lt_add.mpr $ lt_add_of_pos_right _ zero_lt_one⟩⟩ instance to_domain [s : linear_ordered_ring α] : domain α := { eq_zero_or_eq_zero_of_mul_eq_zero := @linear_ordered_ring.eq_zero_or_eq_zero_of_mul_eq_zero α s, ..s } section linear_ordered_ring variable [linear_ordered_ring α] @[simp] lemma mul_le_mul_left_of_neg {a b c : α} (h : c < 0) : c * a ≤ c * b ↔ b ≤ a := ⟨le_imp_le_of_lt_imp_lt $ λ h', mul_lt_mul_of_neg_left h' h, λ h', mul_le_mul_of_nonpos_left h' (le_of_lt h)⟩ @[simp] lemma mul_le_mul_right_of_neg {a b c : α} (h : c < 0) : a * c ≤ b * c ↔ b ≤ a := ⟨le_imp_le_of_lt_imp_lt $ λ h', mul_lt_mul_of_neg_right h' h, λ h', mul_le_mul_of_nonpos_right h' (le_of_lt h)⟩ @[simp] lemma mul_lt_mul_left_of_neg {a b c : α} (h : c < 0) : c * a < c * b ↔ b < a := lt_iff_lt_of_le_iff_le (mul_le_mul_left_of_neg h) @[simp] lemma mul_lt_mul_right_of_neg {a b c : α} (h : c < 0) : a * c < b * c ↔ b < a := lt_iff_lt_of_le_iff_le (mul_le_mul_right_of_neg h) lemma sub_one_lt (a : α) : a - 1 < a := sub_lt_iff_lt_add.2 (lt_add_one a) lemma mul_self_pos {a : α} (ha : a ≠ 0) : 0 < a * a := by rcases lt_trichotomy a 0 with h|h|h; [exact mul_pos_of_neg_of_neg h h, exact (ha h).elim, exact mul_pos h h] lemma mul_self_le_mul_self_of_le_of_neg_le {x y : α} (h₁ : x ≤ y) (h₂ : -x ≤ y) : x * x ≤ y * y := begin cases le_total 0 x, { exact mul_self_le_mul_self h h₁ }, { rw ← neg_mul_neg, exact mul_self_le_mul_self (neg_nonneg_of_nonpos h) h₂ } end lemma nonneg_of_mul_nonpos_left {a b : α} (h : a * b ≤ 0) (hb : b < 0) : 0 ≤ a := le_of_not_gt (λ ha, absurd h (not_le_of_gt (mul_pos_of_neg_of_neg ha hb))) lemma nonneg_of_mul_nonpos_right {a b : α} (h : a * b ≤ 0) (ha : a < 0) : 0 ≤ b := le_of_not_gt (λ hb, absurd h (not_le_of_gt (mul_pos_of_neg_of_neg ha hb))) lemma pos_of_mul_neg_left {a b : α} (h : a * b < 0) (hb : b ≤ 0) : 0 < a := lt_of_not_ge (λ ha, absurd h (not_lt_of_ge (mul_nonneg_of_nonpos_of_nonpos ha hb))) lemma pos_of_mul_neg_right {a b : α} (h : a * b < 0) (ha : a ≤ 0) : 0 < b := lt_of_not_ge (λ hb, absurd h (not_lt_of_ge (mul_nonneg_of_nonpos_of_nonpos ha hb))) /- The sum of two squares is zero iff both elements are zero. -/ lemma mul_self_add_mul_self_eq_zero {x y : α} : x * x + y * y = 0 ↔ x = 0 ∧ y = 0 := begin split; intro h, swap, { rcases h with ⟨rfl, rfl⟩, simp }, have : y * y ≤ 0, { rw [← h], apply le_add_of_nonneg_left (mul_self_nonneg x) }, have : y * y = 0 := le_antisymm this (mul_self_nonneg y), have hx : x = 0, { rwa [this, add_zero, mul_self_eq_zero] at h }, rw mul_self_eq_zero at this, split; assumption end end linear_ordered_ring set_option old_structure_cmd true /-- Extend `nonneg_comm_group` to support ordered rings specified by their nonnegative elements -/ class nonneg_ring (α : Type*) extends ring α, zero_ne_one_class α, nonneg_comm_group α := (mul_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a * b)) (mul_pos : ∀ {a b}, pos a → pos b → pos (a * b)) /-- Extend `nonneg_comm_group` to support linearly ordered rings specified by their nonnegative elements -/ class linear_nonneg_ring (α : Type*) extends domain α, nonneg_comm_group α := (mul_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a * b)) (nonneg_total : ∀ a, nonneg a ∨ nonneg (-a)) namespace nonneg_ring open nonneg_comm_group variable [s : nonneg_ring α] instance to_ordered_ring : ordered_ring α := { le := (≤), lt := (<), lt_iff_le_not_le := @lt_iff_le_not_le _ _, le_refl := @le_refl _ _, le_trans := @le_trans _ _, le_antisymm := @le_antisymm _ _, add_lt_add_left := @add_lt_add_left _ _, add_le_add_left := @add_le_add_left _ _, mul_nonneg := λ a b, by simp [nonneg_def.symm]; exact mul_nonneg, mul_pos := λ a b, by simp [pos_def.symm]; exact mul_pos, ..s } def to_linear_nonneg_ring (nonneg_total : ∀ a : α, nonneg a ∨ nonneg (-a)) : linear_nonneg_ring α := { nonneg_total := nonneg_total, eq_zero_or_eq_zero_of_mul_eq_zero := suffices ∀ {a} b : α, nonneg a → a * b = 0 → a = 0 ∨ b = 0, from λ a b, (nonneg_total a).elim (this b) (λ na, by simpa using this b na), suffices ∀ {a b : α}, nonneg a → nonneg b → a * b = 0 → a = 0 ∨ b = 0, from λ a b na, (nonneg_total b).elim (this na) (λ nb, by simpa using this na nb), λ a b na nb z, classical.by_cases (λ nna : nonneg (-a), or.inl (nonneg_antisymm na nna)) (λ pa, classical.by_cases (λ nnb : nonneg (-b), or.inr (nonneg_antisymm nb nnb)) (λ pb, absurd z $ ne_of_gt $ pos_def.1 $ mul_pos ((pos_iff _ _).2 ⟨na, pa⟩) ((pos_iff _ _).2 ⟨nb, pb⟩))), ..s } end nonneg_ring namespace linear_nonneg_ring open nonneg_comm_group variable [s : linear_nonneg_ring α] instance to_nonneg_ring : nonneg_ring α := { mul_pos := λ a b pa pb, let ⟨a1, a2⟩ := (pos_iff α a).1 pa, ⟨b1, b2⟩ := (pos_iff α b).1 pb in have ab : nonneg (a * b), from mul_nonneg a1 b1, (pos_iff α _).2 ⟨ab, λ hn, have a * b = 0, from nonneg_antisymm ab hn, (eq_zero_or_eq_zero_of_mul_eq_zero _ _ this).elim (ne_of_gt (pos_def.1 pa)) (ne_of_gt (pos_def.1 pb))⟩, ..s } instance to_linear_order : linear_order α := { le := (≤), lt := (<), lt_iff_le_not_le := @lt_iff_le_not_le _ _, le_refl := @le_refl _ _, le_trans := @le_trans _ _, le_antisymm := @le_antisymm _ _, le_total := nonneg_total_iff.1 nonneg_total, ..s } instance to_linear_ordered_ring : linear_ordered_ring α := { le := (≤), lt := (<), lt_iff_le_not_le := @lt_iff_le_not_le _ _, le_refl := @le_refl _ _, le_trans := @le_trans _ _, le_antisymm := @le_antisymm _ _, le_total := @le_total _ _, add_lt_add_left := @add_lt_add_left _ _, add_le_add_left := @add_le_add_left _ _, mul_nonneg := by simp [nonneg_def.symm]; exact @mul_nonneg _ _, mul_pos := by simp [pos_def.symm]; exact @nonneg_ring.mul_pos _ _, zero_lt_one := lt_of_not_ge $ λ (h : nonneg (0 - 1)), begin rw [zero_sub] at h, have := mul_nonneg h h, simp at this, exact zero_ne_one _ (nonneg_antisymm this h).symm end, ..s } instance to_decidable_linear_ordered_comm_ring [decidable_pred (@nonneg α _)] [comm : @is_commutative α (*)] : decidable_linear_ordered_comm_ring α := { decidable_le := by apply_instance, decidable_eq := by apply_instance, decidable_lt := by apply_instance, mul_comm := is_commutative.comm (*), ..@linear_nonneg_ring.to_linear_ordered_ring _ s } end linear_nonneg_ring class canonically_ordered_comm_semiring (α : Type*) extends canonically_ordered_monoid α, comm_semiring α, zero_ne_one_class α := (mul_eq_zero_iff (a b : α) : a * b = 0 ↔ a = 0 ∨ b = 0) namespace canonically_ordered_semiring open canonically_ordered_monoid lemma mul_le_mul [canonically_ordered_comm_semiring α] {a b c d : α} (hab : a ≤ b) (hcd : c ≤ d) : a * c ≤ b * d := begin rcases (le_iff_exists_add _ _).1 hab with ⟨b, rfl⟩, rcases (le_iff_exists_add _ _).1 hcd with ⟨d, rfl⟩, suffices : a * c ≤ a * c + (a * d + b * c + b * d), by simpa [mul_add, add_mul], exact (le_iff_exists_add _ _).2 ⟨_, rfl⟩ end end canonically_ordered_semiring instance : canonically_ordered_comm_semiring ℕ := { le_iff_exists_add := assume a b, ⟨assume h, let ⟨c, hc⟩ := nat.le.dest h in ⟨c, hc.symm⟩, assume ⟨c, hc⟩, hc.symm ▸ nat.le_add_right _ _⟩, zero_ne_one := ne_of_lt zero_lt_one, mul_eq_zero_iff := assume a b, iff.intro nat.eq_zero_of_mul_eq_zero (by simp [or_imp_distrib] {contextual := tt}), bot := 0, bot_le := nat.zero_le, .. (infer_instance : ordered_comm_monoid ℕ), .. (infer_instance : linear_ordered_semiring ℕ), .. (infer_instance : comm_semiring ℕ) } namespace with_top variables [canonically_ordered_comm_semiring α] [decidable_eq α] instance : mul_zero_class (with_top α) := { zero := 0, mul := λm n, if m = 0 ∨ n = 0 then 0 else m.bind (λa, n.bind $ λb, ↑(a * b)), zero_mul := assume a, if_pos $ or.inl rfl, mul_zero := assume a, if_pos $ or.inr rfl } instance : has_one (with_top α) := ⟨↑(1:α)⟩ lemma mul_def {a b : with_top α} : a * b = if a = 0 ∨ b = 0 then 0 else a.bind (λa, b.bind $ λb, ↑(a * b)) := rfl @[simp] theorem top_ne_zero [partial_order α] : ⊤ ≠ (0 : with_top α) . @[simp] theorem zero_ne_top [partial_order α] : (0 : with_top α) ≠ ⊤ . @[simp] theorem coe_eq_zero [partial_order α] {a : α} : (a : with_top α) = 0 ↔ a = 0 := iff.intro (assume h, match a, h with _, rfl := rfl end) (assume h, h.symm ▸ rfl) @[simp] theorem zero_eq_coe [partial_order α] {a : α} : 0 = (a : with_top α) ↔ a = 0 := by rw [eq_comm, coe_eq_zero] @[simp] theorem coe_zero [partial_order α] : ↑(0 : α) = (0 : with_top α) := rfl @[simp] lemma mul_top {a : with_top α} (h : a ≠ 0) : a * ⊤ = ⊤ := by cases a; simp [mul_def, h]; refl @[simp] lemma top_mul {a : with_top α} (h : a ≠ 0) : ⊤ * a = ⊤ := by cases a; simp [mul_def, h]; refl @[simp] lemma top_mul_top : (⊤ * ⊤ : with_top α) = ⊤ := top_mul top_ne_zero lemma coe_mul {a b : α} : (↑(a * b) : with_top α) = a * b := decidable.by_cases (assume : a = 0, by simp [this]) $ assume ha, decidable.by_cases (assume : b = 0, by simp [this]) $ assume hb, by simp [*, mul_def]; refl lemma mul_coe {b : α} (hb : b ≠ 0) : ∀{a : with_top α}, a * b = a.bind (λa:α, ↑(a * b)) | none := show (if (⊤:with_top α) = 0 ∨ (b:with_top α) = 0 then 0 else ⊤ : with_top α) = ⊤, by simp [hb] | (some a) := show ↑a * ↑b = ↑(a * b), from coe_mul.symm private lemma comm (a b : with_top α) : a * b = b * a := begin by_cases ha : a = 0, { simp [ha] }, by_cases hb : b = 0, { simp [hb] }, simp [ha, hb, mul_def, option.bind_comm a b, mul_comm] end @[simp] lemma mul_eq_top_iff {a b : with_top α} : a * b = ⊤ ↔ (a ≠ 0 ∧ b = ⊤) ∨ (a = ⊤ ∧ b ≠ 0) := begin have H : ∀x:α, (¬x = 0) ↔ (⊤ : with_top α) * ↑x = ⊤ := λx, ⟨λhx, by simp [top_mul, hx], λhx f, by simpa [f] using hx⟩, cases a; cases b; simp [none_eq_top, top_mul, coe_ne_top, some_eq_coe, coe_mul.symm], { rw [H b] }, { rw [H a, comm] } end private lemma distrib' (a b c : with_top α) : (a + b) * c = a * c + b * c := begin cases c, { show (a + b) * ⊤ = a * ⊤ + b * ⊤, by_cases ha : a = 0; simp [ha] }, { show (a + b) * c = a * c + b * c, by_cases hc : c = 0, { simp [hc] }, simp [mul_coe hc], cases a; cases b, repeat { refl <|> exact congr_arg some (add_mul _ _ _) } } end private lemma mul_eq_zero (a b : with_top α) : a * b = 0 ↔ a = 0 ∨ b = 0 := by cases a; cases b; dsimp [mul_def]; split_ifs; simp [*, none_eq_top, some_eq_coe, canonically_ordered_comm_semiring.mul_eq_zero_iff] at * private lemma assoc (a b c : with_top α) : (a * b) * c = a * (b * c) := begin cases a, { by_cases hb : b = 0; by_cases hc : c = 0; simp [*, none_eq_top, mul_eq_zero b c] }, cases b, { by_cases ha : a = 0; by_cases hc : c = 0; simp [*, none_eq_top, some_eq_coe, mul_eq_zero ↑a c] }, cases c, { by_cases ha : a = 0; by_cases hb : b = 0; simp [*, none_eq_top, some_eq_coe, mul_eq_zero ↑a ↑b] }, simp [some_eq_coe, coe_mul.symm, mul_assoc] end private lemma one_mul' : ∀a : with_top α, 1 * a = a | none := show ((1:α) : with_top α) * ⊤ = ⊤, by simp [-with_bot.coe_one] | (some a) := show ((1:α) : with_top α) * a = a, by simp [coe_mul.symm, -with_bot.coe_one] instance [canonically_ordered_comm_semiring α] [decidable_eq α] : canonically_ordered_comm_semiring (with_top α) := { one := (1 : α), right_distrib := distrib', left_distrib := assume a b c, by rw [comm, distrib', comm b, comm c]; refl, mul_assoc := assoc, mul_comm := comm, mul_eq_zero_iff := mul_eq_zero, one_mul := one_mul', mul_one := assume a, by rw [comm, one_mul'], zero_ne_one := assume h, @zero_ne_one α _ $ option.some.inj h, .. with_top.add_comm_monoid, .. with_top.mul_zero_class, .. with_top.canonically_ordered_monoid } @[simp] lemma coe_nat : ∀(n : nat), ((n : α) : with_top α) = n | 0 := rfl | (n+1) := have (((1 : nat) : α) : with_top α) = ((1 : nat) : with_top α) := rfl, by rw [nat.cast_add, coe_add, nat.cast_add, coe_nat n, this] @[simp] lemma nat_ne_top (n : nat) : (n : with_top α ) ≠ ⊤ := by rw [←coe_nat n]; apply coe_ne_top @[simp] lemma top_ne_nat (n : nat) : (⊤ : with_top α) ≠ n := by rw [←coe_nat n]; apply top_ne_coe @[elab_as_eliminator] lemma nat_induction {P : with_top ℕ → Prop} (a : with_top ℕ) (h0 : P 0) (hsuc : ∀n:ℕ, P n → P n.succ) (htop : (∀n : ℕ, P n) → P ⊤) : P a := begin have A : ∀n:ℕ, P n, { assume n, induction n with n IH, { exact h0 }, { exact hsuc n IH } }, cases a, { exact htop A }, { exact A a } end end with_top
2a26d256cd5aca7966037b3829803753584b256d
9338c56dfd6ceacc3e5e63e32a7918cfec5d5c69
/src/Kenny/sites/type.lean
44a0e03f6adfe2823d7538fea53b3e9ba35b2083
[]
no_license
Project-Reykjavik/lean-scheme
7322eefce504898ba33737970be89dc751108e2b
6d3ec18fecfd174b79d0ce5c85a783f326dd50f6
refs/heads/master
1,669,426,172,632
1,578,284,588,000
1,578,284,588,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
955
lean
import Kenny.sites.basic category_theory.limits.types universes u v namespace category_theory instance has_pullback_Type : has_pullback (Type u) := ⟨λ F, by apply_instance⟩ instance has_site_Type : has_site (Type u) := { cov := λ α, { S | ∀ x : α, ∃ (f : Σ β, β ⟶ α), ∃ hf : f ∈ S, x ∈ set.range f.2}, iso_mem := λ α β e x, ⟨⟨β, e.1⟩, set.mem_singleton _, e.2 x, congr_fun e.4 x⟩, comp_mem := λ α S HS F HF x, let ⟨f, hf, p, hfpx⟩ := HS x in let ⟨g, hg, q, hgqp⟩ := HF f hf p in ⟨⟨g.1, g.2 ≫ f.2⟩, ⟨f, hf, g, hg, rfl⟩, q, hfpx ▸ hgqp ▸ rfl⟩, pullback_mem := λ α S HS β f x, let ⟨g, hg, p, hgpx⟩ := HS (f x) in ⟨⟨pullback f g.2, pullback.fst f g.2⟩, ⟨g, hg, rfl⟩, ⟨λ v, pullback_diagram.rec_on v x p (f x), by intros v w h; cases h; dsimp only [pullback_diagram.to_category]; { refl <|> exact hgpx }⟩, rfl⟩ } end category_theory
253aaf84a7024a03a46c1eb10cc7295f89931957
618003631150032a5676f229d13a079ac875ff77
/src/algebra/group/with_one.lean
bafd7417b5036b5e00baf826b87aa91d78ff0bcf
[ "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
7,969
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johan Commelin -/ import algebra.group.hom import algebra.ring universes u v variable {α : Type u} @[to_additive] def with_one (α) := option α namespace with_one @[to_additive] instance : monad with_one := option.monad @[to_additive] instance : has_one (with_one α) := ⟨none⟩ @[to_additive] instance : inhabited (with_one α) := ⟨1⟩ @[to_additive] instance : has_coe_t α (with_one α) := ⟨some⟩ @[simp, to_additive] lemma one_ne_coe {a : α} : (1 : with_one α) ≠ a := λ h, option.no_confusion h @[simp, to_additive] lemma coe_ne_one {a : α} : (a : with_one α) ≠ (1 : with_one α) := λ h, option.no_confusion h @[to_additive] lemma ne_one_iff_exists : ∀ {x : with_one α}, x ≠ 1 ↔ ∃ (a : α), x = a | 1 := ⟨λ h, false.elim $ h rfl, by { rintros ⟨a,ha⟩ h, simpa using h }⟩ | (a : α) := ⟨λ h, ⟨a, rfl⟩, λ h, with_one.coe_ne_one⟩ @[to_additive] lemma coe_inj {a b : α} : (a : with_one α) = b ↔ a = b := option.some_inj @[elab_as_eliminator, to_additive] protected lemma cases_on {P : with_one α → Prop} : ∀ (x : with_one α), P 1 → (∀ a : α, P a) → P x := option.cases_on @[to_additive] instance [has_mul α] : has_mul (with_one α) := { mul := option.lift_or_get (*) } @[simp, to_additive] lemma mul_coe [has_mul α] (a b : α) : (a : with_one α) * b = (a * b : α) := rfl @[to_additive add_monoid] instance [semigroup α] : monoid (with_one α) := { mul_assoc := (option.lift_or_get_assoc _).1, one_mul := (option.lift_or_get_is_left_id _).1, mul_one := (option.lift_or_get_is_right_id _).1, ..with_one.has_one, ..with_one.has_mul } @[to_additive add_comm_monoid] instance [comm_semigroup α] : comm_monoid (with_one α) := { mul_comm := (option.lift_or_get_comm _).1, ..with_one.monoid } section lift variables [semigroup α] {β : Type v} [monoid β] /-- Lift a semigroup homomorphism `f` to a bundled monoid homorphism. We have no bundled semigroup homomorphisms, so this function takes `∀ x y, f (x * y) = f x * f y` as an explicit argument. -/ @[to_additive] def lift (f : α → β) (hf : ∀ x y, f (x * y) = f x * f y) : (with_one α) →* β := { to_fun := λ x, option.cases_on x 1 f, map_one' := rfl, map_mul' := λ x y, with_one.cases_on x (by { rw one_mul, exact (one_mul _).symm }) $ λ x, with_one.cases_on y (by { rw mul_one, exact (mul_one _).symm }) $ λ y, hf x y } variables (f : α → β) (hf : ∀ x y, f (x * y) = f x * f y) @[simp, to_additive] lemma lift_coe (x : α) : lift f hf x = f x := rfl @[simp, to_additive] lemma lift_one : lift f hf 1 = 1 := rfl @[to_additive] theorem lift_unique (f : with_one α →* β) : f = lift (f ∘ coe) (λ x y, f.map_mul x y) := monoid_hom.ext $ λ x, with_one.cases_on x f.map_one $ λ x, rfl end lift section map variables {β : Type v} [semigroup α] [semigroup β] @[to_additive] def map (f : α → β) (hf : ∀ x y, f (x * y) = f x * f y) : with_one α →* with_one β := lift (coe ∘ f) (λ x y, coe_inj.2 $ hf x y) end map end with_one namespace with_zero instance [one : has_one α] : has_one (with_zero α) := { ..one } instance [has_one α] : nonzero (with_zero α) := { zero_ne_one := λ h, option.no_confusion h } lemma coe_one [has_one α] : ((1 : α) : with_zero α) = 1 := rfl instance [has_mul α] : mul_zero_class (with_zero α) := { mul := λ o₁ o₂, o₁.bind (λ a, option.map (λ b, a * b) o₂), zero_mul := λ a, rfl, mul_zero := λ a, by cases a; refl, ..with_zero.has_zero } @[simp] lemma mul_coe [has_mul α] (a b : α) : (a : with_zero α) * b = (a * b : α) := rfl instance [semigroup α] : semigroup (with_zero α) := { mul_assoc := λ a b c, match a, b, c with | none, _, _ := rfl | some a, none, _ := rfl | some a, some b, none := rfl | some a, some b, some c := congr_arg some (mul_assoc _ _ _) end, ..with_zero.mul_zero_class } instance [comm_semigroup α] : comm_semigroup (with_zero α) := { mul_comm := λ a b, match a, b with | none, _ := (mul_zero _).symm | some a, none := rfl | some a, some b := congr_arg some (mul_comm _ _) end, ..with_zero.semigroup } instance [monoid α] : monoid (with_zero α) := { one_mul := λ a, match a with | none := rfl | some a := congr_arg some $ one_mul _ end, mul_one := λ a, match a with | none := rfl | some a := congr_arg some $ mul_one _ end, ..with_zero.has_one, ..with_zero.nonzero, ..with_zero.semigroup } instance [comm_monoid α] : comm_monoid (with_zero α) := { ..with_zero.monoid, ..with_zero.comm_semigroup } definition inv [has_inv α] (x : with_zero α) : with_zero α := do a ← x, return a⁻¹ instance [has_inv α] : has_inv (with_zero α) := ⟨with_zero.inv⟩ @[simp] lemma inv_coe [has_inv α] (a : α) : (a : with_zero α)⁻¹ = (a⁻¹ : α) := rfl @[simp] lemma inv_zero [has_inv α] : (0 : with_zero α)⁻¹ = 0 := rfl section group variables [group α] @[simp] lemma inv_one : (1 : with_zero α)⁻¹ = 1 := show ((1⁻¹ : α) : with_zero α) = 1, by simp [coe_one] definition div (x y : with_zero α) : with_zero α := x * y⁻¹ instance : has_div (with_zero α) := ⟨with_zero.div⟩ @[simp] lemma zero_div (a : with_zero α) : 0 / a = 0 := rfl @[simp] lemma div_zero (a : with_zero α) : a / 0 = 0 := by change a * _ = _; simp lemma div_coe (a b : α) : (a : with_zero α) / b = (a * b⁻¹ : α) := rfl lemma one_div (x : with_zero α) : 1 / x = x⁻¹ := one_mul _ @[simp] lemma div_one : ∀ (x : with_zero α), x / 1 = x | 0 := rfl | (a : α) := show _ * _ = _, by simp @[simp] lemma mul_right_inv : ∀ (x : with_zero α) (h : x ≠ 0), x * x⁻¹ = 1 | 0 h := false.elim $ h rfl | (a : α) h := by simp [coe_one] @[simp] lemma mul_left_inv : ∀ (x : with_zero α) (h : x ≠ 0), x⁻¹ * x = 1 | 0 h := false.elim $ h rfl | (a : α) h := by simp [coe_one] @[simp] lemma mul_inv_rev : ∀ (x y : with_zero α), (x * y)⁻¹ = y⁻¹ * x⁻¹ | 0 0 := rfl | 0 (b : α) := rfl | (a : α) 0 := rfl | (a : α) (b : α) := by simp @[simp] lemma mul_div_cancel {a b : with_zero α} (hb : b ≠ 0) : a * b / b = a := show _ * _ * _ = _, by simp [mul_assoc, hb] @[simp] lemma div_mul_cancel {a b : with_zero α} (hb : b ≠ 0) : a / b * b = a := show _ * _ * _ = _, by simp [mul_assoc, hb] lemma div_eq_iff_mul_eq {a b c : with_zero α} (hb : b ≠ 0) : a / b = c ↔ c * b = a := by split; intro h; simp [h.symm, hb] end group section comm_group variables [comm_group α] {a b c d : with_zero α} lemma div_eq_div (hb : b ≠ 0) (hd : d ≠ 0) : a / b = c / d ↔ a * d = b * c := begin rw ne_zero_iff_exists at hb hd, rcases hb with ⟨b, rfl⟩, rcases hd with ⟨d, rfl⟩, induction a using with_zero.cases_on; induction c using with_zero.cases_on, { refl }, { simp [div_coe] }, { simp [div_coe] }, erw [with_zero.coe_inj, with_zero.coe_inj], show a * b⁻¹ = c * d⁻¹ ↔ a * d = b * c, split; intro H, { rw mul_inv_eq_iff_eq_mul at H, rw [H, mul_right_comm, inv_mul_cancel_right, mul_comm] }, { rw [mul_inv_eq_iff_eq_mul, mul_right_comm, mul_comm c, ← H, mul_inv_cancel_right] } end end comm_group section semiring instance [semiring α] : semiring (with_zero α) := { left_distrib := λ a b c, begin cases a with a, {refl}, cases b with b; cases c with c; try {refl}, exact congr_arg some (left_distrib _ _ _) end, right_distrib := λ a b c, begin cases c with c, { change (a + b) * 0 = a * 0 + b * 0, simp }, cases a with a; cases b with b; try {refl}, exact congr_arg some (right_distrib _ _ _) end, ..with_zero.add_comm_monoid, ..with_zero.mul_zero_class, ..with_zero.monoid } end semiring end with_zero
9eff884ce1f9698cd70cf27965400679219f825c
37fa6e77734d3aca013fed5a19c4ee1fe1c38857
/library/init/meta/simp_tactic.lean
7b9ee1f1fec68c971880ff9eb9bc516194d71e56
[ "Apache-2.0" ]
permissive
gazimahmud/lean
8736ac0b0289850b4c7e7600604e2ce9fc8606ad
08495eef27b33f68dfc681e3bcab23b4771cbf03
refs/heads/master
1,611,158,659,846
1,498,642,351,000
1,498,671,799,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,254
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.tactic init.meta.attribute init.meta.constructor_tactic import init.meta.relation_tactics init.meta.occurrences import init.data.option.instances open tactic meta constant simp_lemmas : Type meta constant simp_lemmas.mk : simp_lemmas meta constant simp_lemmas.join : simp_lemmas → simp_lemmas → simp_lemmas meta constant simp_lemmas.erase : simp_lemmas → list name → simp_lemmas meta constant simp_lemmas.mk_default_core : transparency → tactic simp_lemmas meta constant simp_lemmas.add_core : transparency → simp_lemmas → expr → tactic simp_lemmas meta constant simp_lemmas.add_simp_core : transparency → simp_lemmas → name → tactic simp_lemmas meta constant simp_lemmas.add_congr_core : transparency → simp_lemmas → name → tactic simp_lemmas meta def simp_lemmas.mk_default : tactic simp_lemmas := simp_lemmas.mk_default_core reducible meta def simp_lemmas.add : simp_lemmas → expr → tactic simp_lemmas := simp_lemmas.add_core reducible meta def simp_lemmas.add_simp : simp_lemmas → name → tactic simp_lemmas := simp_lemmas.add_simp_core reducible meta def simp_lemmas.add_congr : simp_lemmas → name → tactic simp_lemmas := simp_lemmas.add_congr_core reducible meta def simp_lemmas.append : simp_lemmas → list expr → tactic simp_lemmas | sls [] := return sls | sls (l::ls) := do new_sls ← simp_lemmas.add sls l, simp_lemmas.append new_sls ls /-- `simp_lemmas.rewrite_core m s prove R e` apply a simplification lemma from 's' - 'prove' is used to discharge proof obligations. - 'R' is the equivalence relation being used (e.g., 'eq', 'iff') - 'e' is the expression to be "simplified" Result (new_e, pr) is the new expression 'new_e' and a proof (pr : e R new_e) -/ meta constant simp_lemmas.rewrite_core : transparency → simp_lemmas → tactic unit → name → expr → tactic (expr × expr) meta def simp_lemmas.rewrite : simp_lemmas → tactic unit → name → expr → tactic (expr × expr) := simp_lemmas.rewrite_core reducible /-- `simp_lemmas.drewrite s e` tries to rewrite 'e' using only refl lemmas in 's' -/ meta constant simp_lemmas.drewrite_core : transparency → simp_lemmas → expr → tactic expr meta def simp_lemmas.drewrite : simp_lemmas → expr → tactic expr := simp_lemmas.drewrite_core reducible /-- (Definitional) Simplify the given expression using *only* reflexivity equality lemmas from the given set of lemmas. The resulting expression is definitionally equal to the input. -/ meta constant simp_lemmas.dsimplify_core (max_steps : nat) (visit_instances : bool) : simp_lemmas → expr → tactic expr meta constant is_valid_simp_lemma_cnst : transparency → name → tactic bool meta constant is_valid_simp_lemma : transparency → expr → tactic bool def default_max_steps := 10000000 meta def simp_lemmas.dsimplify : simp_lemmas → expr → tactic expr := simp_lemmas.dsimplify_core default_max_steps ff meta constant simp_lemmas.pp : simp_lemmas → tactic format namespace tactic /-- `get_eqn_lemmas_for deps d` returns the automatically generated equational lemmas for definition d. If deps is tt, then lemmas for automatically generated auxiliary declarations used to define d are also included. -/ meta constant get_eqn_lemmas_for : bool → name → tactic (list name) meta constant dsimplify_core /- The user state type. -/ {α : Type} /- Initial user data -/ (a : α) (max_steps : nat) /- If visit_instances = ff, then instance implicit arguments are not visited, but tactic will canonize them. -/ (visit_instances : bool) /- (pre a e) is invoked before visiting the children of subterm 'e', if it succeeds the result (new_a, new_e, flag) where - 'new_a' is the new value for the user data - 'new_e' is a new expression that must be definitionally equal to 'e', - 'flag' if tt 'new_e' children should be visited, and 'post' invoked. -/ (pre : α → expr → tactic (α × expr × bool)) /- (post a e) is invoked after visiting the children of subterm 'e', The output is similar to (pre a e), but the 'flag' indicates whether the new expression should be revisited or not. -/ (post : α → expr → tactic (α × expr × bool)) : expr → tactic (α × expr) meta def dsimplify (pre : expr → tactic (expr × bool)) (post : expr → tactic (expr × bool)) : expr → tactic expr := λ e, do (a, new_e) ← dsimplify_core () default_max_steps ff (λ u e, do r ← pre e, return (u, r)) (λ u e, do r ← post e, return (u, r)) e, return new_e meta constant dunfold_expr_core : transparency → expr → tactic expr /- Remark: we use transparency.instances by default to make sure that we can unfold projections of type classes. Example: dunfold_expr (@has_add.add nat nat.has_add a b) -/ meta def dunfold_expr : expr → tactic expr := dunfold_expr_core transparency.instances meta constant unfold_projection_core : transparency → expr → tactic expr meta def unfold_projection : expr → tactic expr := unfold_projection_core transparency.instances meta constant dunfold_occs_core (m : transparency) (max_steps : nat) (occs : occurrences) (cs : list name) (e : expr) : tactic expr meta constant dunfold_core (m : transparency) (max_steps : nat) (cs : list name) (e : expr) : tactic expr meta def dunfold : list name → tactic unit := λ cs, target >>= dunfold_core transparency.instances default_max_steps cs >>= unsafe_change meta def dunfold_occs_of (occs : list nat) (c : name) : tactic unit := target >>= dunfold_occs_core transparency.instances default_max_steps (occurrences.pos occs) [c] >>= unsafe_change meta def revert_and_transform (transform : expr → tactic expr) (h : expr) : tactic unit := do num_reverted : ℕ ← revert h, t ← target, match t with | expr.pi n bi d b := do h_simp ← transform d, unsafe_change $ expr.pi n bi h_simp b | expr.elet n g e f := do h_simp ← transform g, unsafe_change $ expr.elet n h_simp e f | _ := fail "reverting hypothesis created neither a pi nor an elet expr (unreachable?)" end, intron num_reverted meta def dunfold_core_at (occs : occurrences) (cs : list name) : expr → tactic unit := revert_and_transform (dunfold_occs_core transparency.instances default_max_steps occs cs) meta def dunfold_at (cs : list name) : expr → tactic unit := revert_and_transform (dunfold_core transparency.instances default_max_steps cs) structure delta_config := (max_steps := default_max_steps) (visit_instances := tt) private meta def is_delta_target (e : expr) (cs : list name) : bool := cs.any (λ c, if e.is_app_of c then tt /- Exact match -/ else let f := e.get_app_fn in /- f is an auxiliary constant generated when compiling c -/ f.is_constant && f.const_name.is_internal && (f.const_name.get_prefix = c)) /-- Delta reduce the given constant names -/ meta def delta_core (cfg : delta_config) (cs : list name) (e : expr) : tactic expr := let unfold (u : unit) (e : expr) : tactic (unit × expr × bool) := do guard (is_delta_target e cs), (expr.const f_name f_lvls) ← return e.get_app_fn, env ← get_env, decl ← env.get f_name, new_f ← decl.instantiate_value_univ_params f_lvls, new_e ← head_beta (expr.mk_app new_f e.get_app_args), return (u, new_e, tt) in do (c, new_e) ← dsimplify_core () cfg.max_steps cfg.visit_instances (λ c e, failed) unfold e, return new_e meta def delta (cs : list name) : tactic unit := target >>= delta_core {} cs >>= unsafe_change meta def delta_at (cs : list name) : expr → tactic unit := revert_and_transform (delta_core {} cs) meta def unfold_projections_core (m : transparency) (max_steps : nat) (e : expr) : tactic expr := let unfold (changed : bool) (e : expr) : tactic (bool × expr × bool) := do new_e ← unfold_projection_core m e, return (tt, new_e, tt) in do (tt, new_e) ← dsimplify_core ff default_max_steps tt (λ c e, failed) unfold e | fail "no projections to unfold", return new_e meta def unfold_projections : tactic unit := target >>= unfold_projections_core semireducible default_max_steps >>= change meta def unfold_projections_at : expr → tactic unit := revert_and_transform (unfold_projections_core semireducible default_max_steps) structure simp_config := (max_steps : nat := default_max_steps) (contextual : bool := ff) (lift_eq : bool := tt) (canonize_instances : bool := tt) (canonize_proofs : bool := ff) (use_axioms : bool := tt) (zeta : bool := tt) (beta : bool := tt) (eta : bool := tt) (proj : bool := tt) -- reduce projections (single_pass : bool := ff) meta constant simplify_core (c : simp_config) (s : simp_lemmas) (r : name) : expr → tactic (expr × expr) meta constant ext_simplify_core /- The user state type. -/ {α : Type} /- Initial user data -/ (a : α) (c : simp_config) /- Congruence and simplification lemmas. Remark: the simplification lemmas at not applied automatically like in the simplify_core tactic. the caller must use them at pre/post. -/ (s : simp_lemmas) /- Tactic for dischaging hypothesis in conditional rewriting rules. The argument 'α' is the current user state. -/ (prove : α → tactic α) /- (pre a S r s p e) is invoked before visiting the children of subterm 'e', 'r' is the simplification relation being used, 's' is the updated set of lemmas if 'contextual' is tt, 'p' is the "parent" expression (if there is one). if it succeeds the result is (new_a, new_e, new_pr, flag) where - 'new_a' is the new value for the user data - 'new_e' is a new expression s.t. 'e r new_e' - 'new_pr' is a proof for 'e r new_e', If it is none, the proof is assumed to be by reflexivity - 'flag' if tt 'new_e' children should be visited, and 'post' invoked. -/ (pre : α → simp_lemmas → name → option expr → expr → tactic (α × expr × option expr × bool)) /- (post a r s p e) is invoked after visiting the children of subterm 'e', The output is similar to (pre a r s p e), but the 'flag' indicates whether the new expression should be revisited or not. -/ (post : α → simp_lemmas → name → option expr → expr → tactic (α × expr × option expr × bool)) /- simplification relation -/ (r : name) : expr → tactic (α × expr × expr) meta def simplify (S : simp_lemmas) (e : expr) (cfg : simp_config := {}) : tactic (expr × expr) := do e_type ← infer_type e >>= whnf, simplify_core cfg S `eq e meta def replace_target (new_target : expr) (pr : expr) : tactic unit := do t ← target, assert `htarget new_target, swap, ht ← get_local `htarget, eq_type ← mk_app `eq [t, new_target], locked_pr ← return $ expr.app (expr.app (expr.const ``id_locked [level.zero]) eq_type) pr, mk_eq_mpr locked_pr ht >>= exact meta def simplify_goal (S : simp_lemmas) (cfg : simp_config := {}) : tactic unit := do t ← target, (new_t, pr) ← simplify S t cfg, replace_target new_t pr meta def simp (cfg : simp_config := {}) : tactic unit := do S ← simp_lemmas.mk_default, simplify_goal S cfg >> try triv >> try (reflexivity reducible) meta def simp_using (hs : list expr) (cfg : simp_config := {}) : tactic unit := do S ← simp_lemmas.mk_default, S ← S.append hs, simplify_goal S cfg >> try triv meta def dsimp_core (s : simp_lemmas) : tactic unit := target >>= s.dsimplify >>= unsafe_change meta def dsimp : tactic unit := simp_lemmas.mk_default >>= dsimp_core meta def dsimp_at_core (s : simp_lemmas) : expr → tactic unit := revert_and_transform s.dsimplify meta def dsimp_at (h : expr) : tactic unit := do s ← simp_lemmas.mk_default, dsimp_at_core s h private meta def is_equation : expr → bool | (expr.pi n bi d b) := is_equation b | e := match (expr.is_eq e) with (some a) := tt | none := ff end private meta def collect_simps : list expr → tactic (list expr) | [] := return [] | (h :: hs) := do result ← collect_simps hs, htype ← infer_type h >>= whnf, if is_equation htype then return (h :: result) else do pr ← is_prop htype, return $ if pr then (h :: result) else result meta def collect_ctx_simps : tactic (list expr) := local_context >>= collect_simps /-- Simplify target using all hypotheses in the local context. -/ meta def simp_using_hs (cfg : simp_config := {}) : tactic unit := do es ← collect_ctx_simps, simp_using es cfg meta def simph (cfg : simp_config := {}) := simp_using_hs cfg meta def intro1_aux : bool → list name → tactic expr | ff _ := intro1 | tt (n::ns) := intro n | _ _ := failed meta def simp_intro_aux (cfg : simp_config) (updt : bool) : simp_lemmas → bool → list name → tactic simp_lemmas | S tt [] := try (simplify_goal S cfg) >> return S | S use_ns ns := do t ← target, if t.is_napp_of `not 1 then intro1_aux use_ns ns >> simp_intro_aux S use_ns ns.tail else if t.is_arrow then do { d ← return t.binding_domain, (new_d, h_d_eq_new_d) ← simplify S d cfg, h_d ← intro1_aux use_ns ns, h_new_d ← mk_eq_mp h_d_eq_new_d h_d, assertv_core h_d.local_pp_name new_d h_new_d, clear h_d, h_new ← intro1, new_S ← if updt then mcond (is_prop new_d) (S.add h_new) (return S) else return S, simp_intro_aux new_S use_ns ns.tail } <|> -- failed to simplify... we just introduce and continue (intro1_aux use_ns ns >> simp_intro_aux S use_ns ns.tail) else if t.is_pi || t.is_let then intro1_aux use_ns ns >> simp_intro_aux S use_ns ns.tail else do new_t ← whnf t reducible, if new_t.is_pi then unsafe_change new_t >> simp_intro_aux S use_ns ns else try (simplify_goal S cfg) >> mcond (expr.is_pi <$> target) (simp_intro_aux S use_ns ns) (if use_ns ∧ ¬ns.empty then failed else return S) meta def simp_intros_using (s : simp_lemmas) (cfg : simp_config := {}) : tactic unit := step $ simp_intro_aux cfg ff s ff [] meta def simph_intros_using (s : simp_lemmas) (cfg : simp_config := {}) : tactic unit := step $ do s ← collect_ctx_simps >>= s.append, simp_intro_aux cfg tt s ff [] meta def simp_intro_lst_using (ns : list name) (s : simp_lemmas) (cfg : simp_config := {}) : tactic unit := step $ simp_intro_aux cfg ff s tt ns meta def simph_intro_lst_using (ns : list name) (s : simp_lemmas) (cfg : simp_config := {}) : tactic unit := step $ do s ← collect_ctx_simps >>= s.append, simp_intro_aux cfg tt s tt ns meta def replace_hyp (h : expr) (h_new_type : expr) (pr : expr) : tactic expr := do h_type ← infer_type h, new_h ← assert h.local_pp_name h_new_type, mk_eq_mp pr h >>= exact, try $ clear h, return new_h meta def simp_at (h : expr) (extra_lemmas : list expr := []) (cfg : simp_config := {}) : tactic expr := do when (expr.is_local_constant h = ff) (fail "tactic simp_at failed, the given expression is not a hypothesis"), htype ← infer_type h, S ← simp_lemmas.mk_default, S ← S.append extra_lemmas, (h_new_type, pr) ← simplify S htype cfg, replace_hyp h h_new_type pr meta def simp_at_using_hs (h : expr) (extra_lemmas : list expr := []) (cfg : simp_config := {}) : tactic expr := do hs ← collect_ctx_simps, simp_at h (list.filter (≠ h) hs ++ extra_lemmas) cfg meta def simph_at (h : expr) (extra_lemmas : list expr := []) (cfg : simp_config := {}) : tactic expr := simp_at_using_hs h extra_lemmas cfg meta def mk_eq_simp_ext (simp_ext : expr → tactic (expr × expr)) : tactic unit := do (lhs, rhs) ← target >>= match_eq, (new_rhs, heq) ← simp_ext lhs, unify rhs new_rhs, exact heq /- Simp attribute support -/ meta def to_simp_lemmas : simp_lemmas → list name → tactic simp_lemmas | S [] := return S | S (n::ns) := do S' ← S.add_simp n, to_simp_lemmas S' ns meta def mk_simp_attr (attr_name : name) : command := do let t := `(caching_user_attribute simp_lemmas), let v := `({name := attr_name, descr := "simplifier attribute", mk_cache := λ ns, do {tactic.to_simp_lemmas simp_lemmas.mk ns}, dependencies := [`reducibility] } : caching_user_attribute simp_lemmas), add_decl (declaration.defn attr_name [] t v reducibility_hints.abbrev ff), attribute.register attr_name meta def get_user_simp_lemmas (attr_name : name) : tactic simp_lemmas := if attr_name = `default then simp_lemmas.mk_default else do cnst ← return (expr.const attr_name []), attr ← eval_expr (caching_user_attribute simp_lemmas) cnst, caching_user_attribute.get_cache attr meta def join_user_simp_lemmas_core : simp_lemmas → list name → tactic simp_lemmas | S [] := return S | S (attr_name::R) := do S' ← get_user_simp_lemmas attr_name, join_user_simp_lemmas_core (S.join S') R meta def join_user_simp_lemmas (no_dflt : bool) (attrs : list name) : tactic simp_lemmas := if no_dflt then join_user_simp_lemmas_core simp_lemmas.mk attrs else do s ← simp_lemmas.mk_default, join_user_simp_lemmas_core s attrs /-- Normalize numerical expression, returns a pair (n, pr) where n is the resultant numeral, and pr is a proof that the input argument is equal to n. -/ meta constant norm_num : expr → tactic (expr × expr) meta def simplify_top_down {α} (a : α) (pre : α → expr → tactic (α × expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (α × expr × expr) := ext_simplify_core a cfg simp_lemmas.mk (λ _, failed) (λ a _ _ _ e, do (new_a, new_e, pr) ← pre a e, guard (¬ new_e =ₐ e), return (new_a, new_e, some pr, tt)) (λ _ _ _ _ _, failed) `eq e meta def simp_top_down (pre : expr → tactic (expr × expr)) (cfg : simp_config := {}) : tactic unit := do t ← target, (_, new_target, pr) ← simplify_top_down () (λ _ e, do (new_e, pr) ← pre e, return ((), new_e, pr)) t cfg, replace_target new_target pr meta def simplify_bottom_up {α} (a : α) (post : α → expr → tactic (α × expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (α × expr × expr) := ext_simplify_core a cfg simp_lemmas.mk (λ _, failed) (λ _ _ _ _ _, failed) (λ a _ _ _ e, do (new_a, new_e, pr) ← post a e, guard (¬ new_e =ₐ e), return (new_a, new_e, some pr, tt)) `eq e meta def simp_bottom_up (post : expr → tactic (expr × expr)) (cfg : simp_config := {}) : tactic unit := do t ← target, (_, new_target, pr) ← simplify_bottom_up () (λ _ e, do (new_e, pr) ← post e, return ((), new_e, pr)) t cfg, replace_target new_target pr /- debugging support for algebraic normalizer -/ meta constant trace_algebra_info : expr → tactic unit end tactic export tactic (mk_simp_attr)
8e9d47eb6c55688719f1dc0d2a65554a07746987
2c41ae31b2b771ad5646ad880201393f5269a7f0
/Lean/Qualities/Available.lean
4b7c765ca3ddf20d0d9434b0f2e74ea273187481
[]
no_license
kevinsullivan/Boehm
926f25bc6f1a8b6bd47d333d936fdfc278228312
55208395bff20d48a598b7fa33a4d55a2447a9cf
refs/heads/master
1,586,127,134,302
1,488,252,326,000
1,488,252,326,000
32,836,930
0
0
null
null
null
null
UTF-8
Lean
false
false
661
lean
-- Available /- [Available] is parameterized by an instance of type [SystemType], and it's a sub-attribute to [Dependable]. An instance of type [SystemType] is deemed [Available] if and only if all the requirements are satisfied. -/ import SystemModel.System inductive Available (sys_type: SystemType): Prop | intro : (exists available: sys_type ^.Contexts -> sys_type ^.Phases -> sys_type ^.Stakeholders -> @SystemInstance sys_type -> Prop, forall c: sys_type ^.Contexts, forall p: sys_type ^.Phases, forall s: sys_type ^.Stakeholders, forall st: @SystemInstance sys_type, available c p s st) -> Available
48bb78f49a1b3203fc5fb4ba99b04c08f2509a7f
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/data/fin.lean
884b14a9cd6e0221b67f2bc77572cae6ceb8691c
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
29,889
lean
/- Copyright (c) 2017 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis, Keeley Hoek -/ import data.nat.cast /-! # The finite type with `n` elements `fin n` is the type whose elements are natural numbers smaller than `n`. This file expands on the development in the core library. ## Main definitions ### Induction principles * `fin_zero.elim` : Elimination principle for the empty set `fin 0`, generalizes `fin.elim0`. * `fin.succ_rec` : Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`. This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple. * `fin.succ_rec_on` : same as `fin.succ_rec` but `i : fin n` is the first argument; ### Casts * `cast_lt i h` : embed `i` into a `fin` where `h` proves it belongs into; * `cast_le h` : embed `fin n` into `fin m`, `h : n ≤ m`; * `cast eq` : embed `fin n` into `fin m`, `eq : n = m`; * `cast_add m` : embed `fin n` into `fin (n+m)`; * `cast_succ` : embed `fin n` into `fin (n+1)`; * `succ_above p` : embed `fin n` into `fin (n + 1)` with a hole around `p`; * `pred_above p i h` : embed `i : fin (n+1)` into `fin n` by ignoring `p`; * `sub_nat i h` : subtract `m` from `i ≥ m`, generalizes `fin.pred`; * `add_nat i h` : add `m` on `i` on the right, generalizes `fin.succ`; * `nat_add i h` adds `n` on `i` on the left; * `clamp n m` : `min n m` as an element of `fin (m + 1)`; ### Operation on tuples We interpret maps `Π i : fin n, α i` as tuples `(α 0, …, α (n-1))`. If `α i` is a constant map, then tuples are isomorphic (but not definitionally equal) to `vector`s. We define the following operations: * `tail` : the tail of an `n+1` tuple, i.e., its last `n` entries; * `cons` : adding an element at the beginning of an `n`-tuple, to get an `n+1`-tuple; * `init` : the beginning of an `n+1` tuple, i.e., its first `n` entries; * `snoc` : adding an element at the end of an `n`-tuple, to get an `n+1`-tuple. The name `snoc` comes from `cons` (i.e., adding an element to the left of a tuple) read in reverse order. * `find p` : returns the first index `n` where `p n` is satisfied, and `none` if it is never satisfied. ### Misc definitions * `fin.last n` : The greatest value of `fin (n+1)`. -/ universe u open fin nat function /-- Elimination principle for the empty set `fin 0`, dependent version. -/ def fin_zero_elim {α : fin 0 → Sort u} (x : fin 0) : α x := x.elim0 namespace fin variables {n m : ℕ} {a b : fin n} @[simp] protected lemma eta (a : fin n) (h : a.1 < n) : (⟨a.1, h⟩ : fin n) = a := by cases a; refl attribute [ext] eq_of_veq protected lemma ext_iff (a b : fin n) : a = b ↔ a.val = b.val := iff.intro (congr_arg _) fin.eq_of_veq lemma injective_val {n : ℕ} : injective (val : fin n → ℕ) := λ _ _, fin.eq_of_veq lemma eq_iff_veq (a b : fin n) : a = b ↔ a.1 = b.1 := ⟨veq_of_eq, eq_of_veq⟩ @[simp] protected lemma mk.inj_iff {n a b : ℕ} {ha : a < n} {hb : b < n} : fin.mk a ha = fin.mk b hb ↔ a = b := ⟨fin.mk.inj, λ h, by subst h⟩ instance fin_to_nat (n : ℕ) : has_coe (fin n) nat := ⟨fin.val⟩ lemma mk_val {m n : ℕ} (h : m < n) : (⟨m, h⟩ : fin n).val = m := rfl @[simp, norm_cast] lemma coe_mk {m n : ℕ} (h : m < n) : ((⟨m, h⟩ : fin n) : ℕ) = m := rfl lemma coe_eq_val (a : fin n) : (a : ℕ) = a.val := rfl attribute [simp] val_zero @[simp] lemma val_one {n : ℕ} : (1 : fin (n+2)).val = 1 := rfl @[simp] lemma val_two {n : ℕ} : (2 : fin (n+3)).val = 2 := rfl @[simp] lemma coe_zero {n : ℕ} : ((0 : fin (n+1)) : ℕ) = 0 := rfl @[simp] lemma coe_one {n : ℕ} : ((1 : fin (n+2)) : ℕ) = 1 := rfl @[simp] lemma coe_two {n : ℕ} : ((2 : fin (n+3)) : ℕ) = 2 := rfl /-- `a < b` as natural numbers if and only if `a < b` in `fin n`. -/ @[norm_cast, simp] lemma coe_fin_lt {n : ℕ} {a b : fin n} : (a : ℕ) < (b : ℕ) ↔ a < b := iff.rfl /-- `a ≤ b` as natural numbers if and only if `a ≤ b` in `fin n`. -/ @[norm_cast, simp] lemma coe_fin_le {n : ℕ} {a b : fin n} : (a : ℕ) ≤ (b : ℕ) ↔ a ≤ b := iff.rfl lemma val_add {n : ℕ} : ∀ a b : fin n, (a + b).val = (a.val + b.val) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl lemma val_mul {n : ℕ} : ∀ a b : fin n, (a * b).val = (a.val * b.val) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl lemma one_val {n : ℕ} : (1 : fin (n+1)).val = 1 % (n+1) := rfl @[simp] lemma zero_val (n : ℕ) : (0 : fin (n+1)).val = 0 := rfl @[simp] lemma of_nat_eq_coe (n : ℕ) (a : ℕ) : (of_nat a : fin (n+1)) = a := begin induction a with a ih, { refl }, ext, show (a+1) % (n+1) = fin.val (a+1 : fin (n+1)), { rw [val_add, ← ih, of_nat], exact add_mod _ _ _ } end /-- Converting an in-range number to `fin (n + 1)` produces a result whose value is the original number. -/ lemma coe_val_of_lt {n : ℕ} {a : ℕ} (h : a < n + 1) : (a : fin (n + 1)).val = a := begin rw ←of_nat_eq_coe, exact nat.mod_eq_of_lt h end /-- Converting the value of a `fin (n + 1)` to `fin (n + 1)` results in the same value. -/ @[simp] lemma coe_val_eq_self {n : ℕ} (a : fin (n + 1)) : (a.val : fin (n + 1)) = a := begin rw fin.eq_iff_veq, exact coe_val_of_lt a.is_lt end /-- Coercing an in-range number to `fin (n + 1)`, and converting back to `ℕ`, results in that number. -/ lemma coe_coe_of_lt {n : ℕ} {a : ℕ} (h : a < n + 1) : ((a : fin (n + 1)) : ℕ) = a := coe_val_of_lt h /-- Converting a `fin (n + 1)` to `ℕ` and back results in the same value. -/ @[simp] lemma coe_coe_eq_self {n : ℕ} (a : fin (n + 1)) : ((a : ℕ) : fin (n + 1)) = a := coe_val_eq_self a /-- Assume `k = l`. If two functions defined on `fin k` and `fin l` are equal on each element, then they coincide (in the heq sense). -/ protected lemma heq_fun_iff {α : Type*} {k l : ℕ} (h : k = l) {f : fin k → α} {g : fin l → α} : f == g ↔ (∀ (i : fin k), f i = g ⟨i.val, h ▸ i.2⟩) := by { induction h, simp [heq_iff_eq, function.funext_iff] } protected lemma heq_ext_iff {k l : ℕ} (h : k = l) {i : fin k} {j : fin l} : i == j ↔ i.val = j.val := by { induction h, simp [fin.ext_iff] } instance {n : ℕ} : decidable_linear_order (fin n) := decidable_linear_order.lift fin.val (@fin.eq_of_veq _) (by apply_instance) lemma exists_iff {p : fin n → Prop} : (∃ i, p i) ↔ ∃ i h, p ⟨i, h⟩ := ⟨λ h, exists.elim h (λ ⟨i, hi⟩ hpi, ⟨i, hi, hpi⟩), λ h, exists.elim h (λ i hi, ⟨⟨i, hi.fst⟩, hi.snd⟩)⟩ lemma forall_iff {p : fin n → Prop} : (∀ i, p i) ↔ ∀ i h, p ⟨i, h⟩ := ⟨λ h i hi, h ⟨i, hi⟩, λ h ⟨i, hi⟩, h i hi⟩ lemma zero_le (a : fin (n + 1)) : 0 ≤ a := zero_le a.1 lemma lt_iff_val_lt_val : a < b ↔ a.val < b.val := iff.rfl lemma le_iff_val_le_val : a ≤ b ↔ a.val ≤ b.val := iff.rfl @[simp] lemma succ_val (j : fin n) : j.succ.val = j.val.succ := by cases j; simp [fin.succ] protected theorem succ.inj (p : fin.succ a = fin.succ b) : a = b := by cases a; cases b; exact eq_of_veq (nat.succ.inj (veq_of_eq p)) @[simp] lemma succ_inj {a b : fin n} : a.succ = b.succ ↔ a = b := ⟨λh, succ.inj h, λh, by rw h⟩ lemma injective_succ (n : ℕ) : injective (@fin.succ n) := λa b, succ.inj lemma succ_ne_zero {n} : ∀ k : fin n, fin.succ k ≠ 0 | ⟨k, hk⟩ heq := nat.succ_ne_zero k $ (fin.ext_iff _ _).1 heq @[simp] lemma pred_val (j : fin (n+1)) (h : j ≠ 0) : (j.pred h).val = j.val.pred := by cases j; simp [fin.pred] @[simp] lemma succ_pred : ∀(i : fin (n+1)) (h : i ≠ 0), (i.pred h).succ = i | ⟨0, h⟩ hi := by contradiction | ⟨n + 1, h⟩ hi := rfl @[simp] lemma pred_succ (i : fin n) {h : i.succ ≠ 0} : i.succ.pred h = i := by cases i; refl @[simp] lemma pred_inj : ∀ {a b : fin (n + 1)} {ha : a ≠ 0} {hb : b ≠ 0}, a.pred ha = b.pred hb ↔ a = b | ⟨0, _⟩ b ha hb := by contradiction | ⟨i+1, _⟩ ⟨0, _⟩ ha hb := by contradiction | ⟨i+1, hi⟩ ⟨j+1, hj⟩ ha hb := by simp [fin.eq_iff_veq] /-- The greatest value of `fin (n+1)` -/ def last (n : ℕ) : fin (n+1) := ⟨_, n.lt_succ_self⟩ /-- `cast_lt i h` embeds `i` into a `fin` where `h` proves it belongs into. -/ def cast_lt (i : fin m) (h : i.1 < n) : fin n := ⟨i.1, h⟩ /-- `cast_le h i` embeds `i` into a larger `fin` type. -/ def cast_le (h : n ≤ m) (a : fin n) : fin m := cast_lt a (lt_of_lt_of_le a.2 h) /-- `cast eq i` embeds `i` into a equal `fin` type. -/ def cast (eq : n = m) : fin n → fin m := cast_le $ le_of_eq eq /-- `cast_add m i` embeds `i : fin n` in `fin (n+m)`. -/ def cast_add (m) : fin n → fin (n + m) := cast_le $ le_add_right n m /-- `cast_succ i` embeds `i : fin n` in `fin (n+1)`. -/ def cast_succ : fin n → fin (n + 1) := cast_add 1 /-- `succ_above p i` embeds `fin n` into `fin (n + 1)` with a hole around `p`. -/ def succ_above (p : fin (n+1)) (i : fin n) : fin (n+1) := if i.1 < p.1 then i.cast_succ else i.succ /-- `pred_above p i h` embeds `i : fin (n+1)` into `fin n` by ignoring `p`. -/ def pred_above (p : fin (n+1)) (i : fin (n+1)) (hi : i ≠ p) : fin n := if h : i < p then i.cast_lt (lt_of_lt_of_le h $ nat.le_of_lt_succ p.2) else i.pred $ have p < i, from lt_of_le_of_ne (le_of_not_gt h) hi.symm, ne_of_gt (lt_of_le_of_lt (zero_le p) this) /-- `sub_nat i h` subtracts `m` from `i`, generalizes `fin.pred`. -/ def sub_nat (m) (i : fin (n + m)) (h : m ≤ i.val) : fin n := ⟨i.val - m, by simp [nat.sub_lt_right_iff_lt_add h, i.is_lt]⟩ /-- `add_nat i h` adds `m` on `i`, generalizes `fin.succ`. -/ def add_nat (m) (i : fin n) : fin (n + m) := ⟨i.1 + m, add_lt_add_right i.2 _⟩ /-- `nat_add i h` adds `n` on `i` -/ def nat_add (n) {m} (i : fin m) : fin (n + m) := ⟨n + i.1, add_lt_add_left i.2 _⟩ theorem le_last (i : fin (n+1)) : i ≤ last n := le_of_lt_succ i.is_lt @[simp] lemma cast_val (k : fin n) (h : n = m) : (fin.cast h k).val = k.val := rfl @[simp] lemma cast_succ_val (k : fin n) : k.cast_succ.val = k.val := rfl @[simp] lemma cast_lt_val (k : fin m) (h : k.1 < n) : (k.cast_lt h).val = k.val := rfl @[simp] lemma cast_le_val (k : fin m) (h : m ≤ n) : (k.cast_le h).val = k.val := rfl @[simp] lemma cast_add_val (k : fin m) : (k.cast_add n).val = k.val := rfl @[simp] lemma last_val (n : ℕ) : (last n).val = n := rfl @[simp, norm_cast] lemma coe_last {n : ℕ} : (last n : ℕ) = n := rfl @[simp] lemma succ_last (n : ℕ) : (last n).succ = last (n.succ) := rfl @[simp] lemma cast_succ_cast_lt (i : fin (n + 1)) (h : i.val < n) : cast_succ (cast_lt i h) = i := fin.eq_of_veq rfl @[simp] lemma cast_lt_cast_succ {n : ℕ} (a : fin n) (h : a.1 < n) : cast_lt (cast_succ a) h = a := by cases a; refl @[simp] lemma sub_nat_val (i : fin (n + m)) (h : m ≤ i.val) : (i.sub_nat m h).val = i.val - m := rfl @[simp] lemma add_nat_val (i : fin (n + m)) (h : m ≤ i.val) : (i.add_nat m).val = i.val + m := rfl @[simp] lemma cast_succ_inj {a b : fin n} : a.cast_succ = b.cast_succ ↔ a = b := by simp [eq_iff_veq] lemma cast_succ_ne_last (a : fin n) : cast_succ a ≠ last n := by simp [eq_iff_veq, ne_of_lt a.2] lemma eq_last_of_not_lt {i : fin (n+1)} (h : ¬ i.val < n) : i = last n := le_antisymm (le_last i) (not_lt.1 h) lemma cast_succ_fin_succ (n : ℕ) (j : fin n) : cast_succ (fin.succ j) = fin.succ (cast_succ j) := by simp [fin.ext_iff] /-- `min n m` as an element of `fin (m + 1)` -/ def clamp (n m : ℕ) : fin (m + 1) := fin.of_nat $ min n m @[simp] lemma clamp_val (n m : ℕ) : (clamp n m).val = min n m := nat.mod_eq_of_lt $ nat.lt_succ_iff.mpr $ min_le_right _ _ lemma injective_cast_le {n₁ n₂ : ℕ} (h : n₁ ≤ n₂) : injective (fin.cast_le h) | ⟨i₁, h₁⟩ ⟨i₂, h₂⟩ eq := fin.eq_of_veq $ show i₁ = i₂, from fin.veq_of_eq eq lemma injective_cast_succ (n : ℕ) : injective (@fin.cast_succ n) := injective_cast_le (le_add_right n 1) theorem succ_above_ne (p : fin (n+1)) (i : fin n) : p.succ_above i ≠ p := begin assume eq, unfold fin.succ_above at eq, split_ifs at eq with h; simpa [lt_irrefl, nat.lt_succ_self, eq.symm] using h end @[simp] lemma succ_above_descend : ∀(p i : fin (n+1)) (h : i ≠ p), p.succ_above (p.pred_above i h) = i | ⟨p, hp⟩ ⟨0, hi⟩ h := fin.eq_of_veq $ by simp [succ_above, pred_above]; split_ifs; simp * at * | ⟨p, hp⟩ ⟨i+1, hi⟩ h := fin.eq_of_veq begin have : i + 1 ≠ p, by rwa [(≠), fin.ext_iff] at h, unfold succ_above pred_above, split_ifs with h1 h2; simp only [fin.cast_succ_cast_lt, add_right_inj, pred_val, ne.def, cast_succ_val, nat.pred_succ, fin.succ_pred, add_right_inj] at *, exact (this (le_antisymm h2 (le_of_not_gt h1))).elim end @[simp] lemma pred_above_succ_above (p : fin (n+1)) (i : fin n) (h : p.succ_above i ≠ p) : p.pred_above (p.succ_above i) h = i := begin unfold fin.succ_above, apply eq_of_veq, split_ifs with h₀, { simp [pred_above, h₀, lt_iff_val_lt_val], }, { unfold pred_above, split_ifs with h₁, { exfalso, rw [lt_iff_val_lt_val, succ_val] at h₁, exact h₀ (lt_trans (nat.lt_succ_self _) h₁) }, { rw [pred_succ] } } end /-- A function `f` on `fin n` is strictly monotone if and only if `f i < f (i+1)` for all `i`. -/ lemma strict_mono_iff_lt_succ {α : Type*} [preorder α] {f : fin n → α} : strict_mono f ↔ ∀ i (h : i + 1 < n), f ⟨i, lt_of_le_of_lt (nat.le_succ i) h⟩ < f ⟨i+1, h⟩ := begin split, { assume H i hi, apply H, exact nat.lt_succ_self _ }, { assume H, have A : ∀ i j (h : i < j) (h' : j < n), f ⟨i, lt_trans h h'⟩ < f ⟨j, h'⟩, { assume i j h h', induction h with k h IH, { exact H _ _ }, { exact lt_trans (IH (nat.lt_of_succ_lt h')) (H _ _) } }, assume i j hij, convert A (i : ℕ) (j : ℕ) hij j.2; simp [fin.ext_iff, fin.coe_eq_val] } end section rec /-- Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`. This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple. -/ @[elab_as_eliminator] def succ_rec {C : Π n, fin n → Sort*} (H0 : Π n, C (succ n) 0) (Hs : Π n i, C n i → C (succ n) i.succ) : Π {n : ℕ} (i : fin n), C n i | 0 i := i.elim0 | (succ n) ⟨0, _⟩ := H0 _ | (succ n) ⟨succ i, h⟩ := Hs _ _ (succ_rec ⟨i, lt_of_succ_lt_succ h⟩) /-- Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`. This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple. A version of `fin.succ_rec` taking `i : fin n` as the first argument. -/ @[elab_as_eliminator] def succ_rec_on {n : ℕ} (i : fin n) {C : Π n, fin n → Sort*} (H0 : Π n, C (succ n) 0) (Hs : Π n i, C n i → C (succ n) i.succ) : C n i := i.succ_rec H0 Hs @[simp] theorem succ_rec_on_zero {C : ∀ n, fin n → Sort*} {H0 Hs} (n) : @fin.succ_rec_on (succ n) 0 C H0 Hs = H0 n := rfl @[simp] theorem succ_rec_on_succ {C : ∀ n, fin n → Sort*} {H0 Hs} {n} (i : fin n) : @fin.succ_rec_on (succ n) i.succ C H0 Hs = Hs n i (fin.succ_rec_on i H0 Hs) := by cases i; refl /-- Define `f : Π i : fin n.succ, C i` by separately handling the cases `i = 0` and `i = j.succ`, `j : fin n`. -/ @[elab_as_eliminator] def cases {C : fin (succ n) → Sort*} (H0 : C 0) (Hs : Π i : fin n, C (i.succ)) : Π (i : fin (succ n)), C i | ⟨0, h⟩ := H0 | ⟨succ i, h⟩ := Hs ⟨i, lt_of_succ_lt_succ h⟩ @[simp] theorem cases_zero {n} {C : fin (succ n) → Sort*} {H0 Hs} : @fin.cases n C H0 Hs 0 = H0 := rfl @[simp] theorem cases_succ {n} {C : fin (succ n) → Sort*} {H0 Hs} (i : fin n) : @fin.cases n C H0 Hs i.succ = Hs i := by cases i; refl lemma forall_fin_succ {P : fin (n+1) → Prop} : (∀ i, P i) ↔ P 0 ∧ (∀ i:fin n, P i.succ) := ⟨λ H, ⟨H 0, λ i, H _⟩, λ ⟨H0, H1⟩ i, fin.cases H0 H1 i⟩ lemma exists_fin_succ {P : fin (n+1) → Prop} : (∃ i, P i) ↔ P 0 ∨ (∃i:fin n, P i.succ) := ⟨λ ⟨i, h⟩, fin.cases or.inl (λ i hi, or.inr ⟨i, hi⟩) i h, λ h, or.elim h (λ h, ⟨0, h⟩) $ λ⟨i, hi⟩, ⟨i.succ, hi⟩⟩ end rec section tuple /-! ### Tuples We can think of the type `Π(i : fin n), α i` as `n`-tuples of elements of possibly varying type `α i`. A particular case is `fin n → α` of elements with all the same type. Here are some relevant operations, first about adding or removing elements at the beginning of a tuple. -/ /-- There is exactly one tuple of size zero. -/ instance tuple0_unique (α : fin 0 → Type u) : unique (Π i : fin 0, α i) := { default := fin_zero_elim, uniq := λ x, funext fin_zero_elim } variables {α : fin (n+1) → Type u} (x : α 0) (q : Πi, α i) (p : Π(i : fin n), α (i.succ)) (i : fin n) (y : α i.succ) (z : α 0) /-- The tail of an `n+1` tuple, i.e., its last `n` entries -/ def tail (q : Πi, α i) : (Π(i : fin n), α (i.succ)) := λ i, q i.succ /-- Adding an element at the beginning of an `n`-tuple, to get an `n+1`-tuple -/ def cons (x : α 0) (p : Π(i : fin n), α (i.succ)) : Πi, α i := λ j, fin.cases x p j @[simp] lemma tail_cons : tail (cons x p) = p := by simp [tail, cons] @[simp] lemma cons_succ : cons x p i.succ = p i := by simp [cons] @[simp] lemma cons_zero : cons x p 0 = x := by simp [cons] /-- Updating a tuple and adding an element at the beginning commute. -/ @[simp] lemma cons_update : cons x (update p i y) = update (cons x p) i.succ y := begin ext j, by_cases h : j = 0, { rw h, simp [ne.symm (succ_ne_zero i)] }, { let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, cons_succ], by_cases h' : j' = i, { rw h', simp }, { have : j'.succ ≠ i.succ, by rwa [ne.def, succ_inj], rw [update_noteq h', update_noteq this, cons_succ] } } end /-- Adding an element at the beginning of a tuple and then updating it amounts to adding it directly. -/ lemma update_cons_zero : update (cons x p) 0 z = cons z p := begin ext j, by_cases h : j = 0, { rw h, simp }, { simp only [h, update_noteq, ne.def, not_false_iff], let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, cons_succ, cons_succ] } end /-- Concatenating the first element of a tuple with its tail gives back the original tuple -/ @[simp] lemma cons_self_tail : cons (q 0) (tail q) = q := begin ext j, by_cases h : j = 0, { rw h, simp }, { let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, tail, cons_succ] } end /-- Updating the first element of a tuple does not change the tail. -/ @[simp] lemma tail_update_zero : tail (update q 0 z) = tail q := by { ext j, simp [tail, fin.succ_ne_zero] } /-- Updating a nonzero element and taking the tail commute. -/ @[simp] lemma tail_update_succ : tail (update q i.succ y) = update (tail q) i y := begin ext j, by_cases h : j = i, { rw h, simp [tail] }, { simp [tail, (fin.injective_succ n).ne h, h] } end lemma comp_cons {α : Type*} {β : Type*} (g : α → β) (y : α) (q : fin n → α) : g ∘ (cons y q) = cons (g y) (g ∘ q) := begin ext j, by_cases h : j = 0, { rw h, refl }, { let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, cons_succ, comp_app, cons_succ] } end lemma comp_tail {α : Type*} {β : Type*} (g : α → β) (q : fin n.succ → α) : g ∘ (tail q) = tail (g ∘ q) := by { ext j, simp [tail] } end tuple section tuple_right /-! In the previous section, we have discussed inserting or removing elements on the left of a tuple. In this section, we do the same on the right. A difference is that `fin (n+1)` is constructed inductively from `fin n` starting from the left, not from the right. This implies that Lean needs more help to realize that elements belong to the right types, i.e., we need to insert casts at several places. -/ variables {α : fin (n+1) → Type u} (x : α (last n)) (q : Πi, α i) (p : Π(i : fin n), α i.cast_succ) (i : fin n) (y : α i.cast_succ) (z : α (last n)) /-- The beginning of an `n+1` tuple, i.e., its first `n` entries -/ def init (q : Πi, α i) (i : fin n) : α i.cast_succ := q i.cast_succ /-- Adding an element at the end of an `n`-tuple, to get an `n+1`-tuple. The name `snoc` comes from `cons` (i.e., adding an element to the left of a tuple) read in reverse order. -/ def snoc (p : Π(i : fin n), α i.cast_succ) (x : α (last n)) (i : fin (n+1)) : α i := if h : i.val < n then _root_.cast (by rw fin.cast_succ_cast_lt i h) (p (cast_lt i h)) else _root_.cast (by rw eq_last_of_not_lt h) x @[simp] lemma init_snoc : init (snoc p x) = p := begin ext i, have h' := fin.cast_lt_cast_succ i i.is_lt, simp [init, snoc, i.is_lt, h'], convert cast_eq rfl (p i) end @[simp] lemma snoc_cast_succ : snoc p x i.cast_succ = p i := begin have : i.cast_succ.val < n := i.is_lt, have h' := fin.cast_lt_cast_succ i i.is_lt, simp [snoc, this, h'], convert cast_eq rfl (p i) end @[simp] lemma snoc_last : snoc p x (last n) = x := by { simp [snoc], refl } /-- Updating a tuple and adding an element at the end commute. -/ @[simp] lemma snoc_update : snoc (update p i y) x = update (snoc p x) i.cast_succ y := begin ext j, by_cases h : j.val < n, { simp only [snoc, h, dif_pos], by_cases h' : j = cast_succ i, { have C1 : α i.cast_succ = α j, by rw h', have E1 : update (snoc p x) i.cast_succ y j = _root_.cast C1 y, { have : update (snoc p x) j (_root_.cast C1 y) j = _root_.cast C1 y, by simp, convert this, { exact h'.symm }, { exact heq_of_eq_mp (congr_arg α (eq.symm h')) rfl } }, have C2 : α i.cast_succ = α (cast_succ (cast_lt j h)), by rw [cast_succ_cast_lt, h'], have E2 : update p i y (cast_lt j h) = _root_.cast C2 y, { have : update p (cast_lt j h) (_root_.cast C2 y) (cast_lt j h) = _root_.cast C2 y, by simp, convert this, { simp [h, h'] }, { exact heq_of_eq_mp C2 rfl } }, rw [E1, E2], exact eq_rec_compose _ _ _ }, { have : ¬(cast_lt j h = i), by { assume E, apply h', rw [← E, cast_succ_cast_lt] }, simp [h', this, snoc, h] } }, { rw eq_last_of_not_lt h, simp [ne.symm (cast_succ_ne_last i)] } end /-- Adding an element at the beginning of a tuple and then updating it amounts to adding it directly. -/ lemma update_snoc_last : update (snoc p x) (last n) z = snoc p z := begin ext j, by_cases h : j.val < n, { have : j ≠ last n := ne_of_lt h, simp [h, update_noteq, this, snoc] }, { rw eq_last_of_not_lt h, simp } end /-- Concatenating the first element of a tuple with its tail gives back the original tuple -/ @[simp] lemma snoc_init_self : snoc (init q) (q (last n)) = q := begin ext j, by_cases h : j.val < n, { have : j ≠ last n := ne_of_lt h, simp [h, update_noteq, this, snoc, init, cast_succ_cast_lt], have A : cast_succ (cast_lt j h) = j := cast_succ_cast_lt _ _, rw ← cast_eq rfl (q j), congr' 1; rw A }, { rw eq_last_of_not_lt h, simp } end /-- Updating the last element of a tuple does not change the beginning. -/ @[simp] lemma init_update_last : init (update q (last n) z) = init q := by { ext j, simp [init, cast_succ_ne_last] } /-- Updating an element and taking the beginning commute. -/ @[simp] lemma init_update_cast_succ : init (update q i.cast_succ y) = update (init q) i y := begin ext j, by_cases h : j = i, { rw h, simp [init] }, { simp [init, h] } end /-- `tail` and `init` commute. We state this lemma in a non-dependent setting, as otherwise it would involve a cast to convince Lean that the two types are equal, making it harder to use. -/ lemma tail_init_eq_init_tail {β : Type*} (q : fin (n+2) → β) : tail (init q) = init (tail q) := by { ext i, simp [tail, init, cast_succ_fin_succ] } /-- `cons` and `snoc` commute. We state this lemma in a non-dependent setting, as otherwise it would involve a cast to convince Lean that the two types are equal, making it harder to use. -/ lemma cons_snoc_eq_snoc_cons {β : Type*} (a : β) (q : fin n → β) (b : β) : @cons n.succ (λ i, β) a (snoc q b) = snoc (cons a q) b := begin ext i, by_cases h : i = 0, { rw h, refl }, set j := pred i h with ji, have : i = j.succ, by rw [ji, succ_pred], rw [this, cons_succ], by_cases h' : j.val < n, { set k := cast_lt j h' with jk, have : j = k.cast_succ, by rw [jk, cast_succ_cast_lt], rw [this, ← cast_succ_fin_succ], simp }, rw [eq_last_of_not_lt h', succ_last], simp end lemma comp_snoc {α : Type*} {β : Type*} (g : α → β) (q : fin n → α) (y : α) : g ∘ (snoc q y) = snoc (g ∘ q) (g y) := begin ext j, by_cases h : j.val < n, { have : j ≠ last n := ne_of_lt h, simp [h, this, snoc, cast_succ_cast_lt], refl }, { rw eq_last_of_not_lt h, simp } end lemma comp_init {α : Type*} {β : Type*} (g : α → β) (q : fin n.succ → α) : g ∘ (init q) = init (g ∘ q) := by { ext j, simp [init] } end tuple_right section find /-- `find p` returns the first index `n` where `p n` is satisfied, and `none` if it is never satisfied. -/ def find : Π {n : ℕ} (p : fin n → Prop) [decidable_pred p], option (fin n) | 0 p _ := none | (n+1) p _ := by resetI; exact option.cases_on (@find n (λ i, p (i.cast_lt (nat.lt_succ_of_lt i.2))) _) (if h : p (fin.last n) then some (fin.last n) else none) (λ i, some (i.cast_lt (nat.lt_succ_of_lt i.2))) /-- If `find p = some i`, then `p i` holds -/ lemma find_spec : Π {n : ℕ} (p : fin n → Prop) [decidable_pred p] {i : fin n} (hi : i ∈ by exactI fin.find p), p i | 0 p I i hi := option.no_confusion hi | (n+1) p I i hi := begin dsimp [find] at hi, resetI, cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with j, { rw h at hi, dsimp at hi, split_ifs at hi with hl hl, { exact option.some_inj.1 hi ▸ hl }, { exact option.no_confusion hi } }, { rw h at hi, rw [← option.some_inj.1 hi], exact find_spec _ h } end /-- `find p` does not return `none` if and only if `p i` holds at some index `i`. -/ lemma is_some_find_iff : Π {n : ℕ} {p : fin n → Prop} [decidable_pred p], by exactI (find p).is_some ↔ ∃ i, p i | 0 p _ := iff_of_false (λ h, bool.no_confusion h) (λ ⟨i, _⟩, fin.elim0 i) | (n+1) p _ := ⟨λ h, begin resetI, rw [option.is_some_iff_exists] at h, cases h with i hi, exact ⟨i, find_spec _ hi⟩ end, λ ⟨⟨i, hin⟩, hi⟩, begin resetI, dsimp [find], cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with j, { split_ifs with hl hl, { exact option.is_some_some }, { have := (@is_some_find_iff n (λ x, p (x.cast_lt (nat.lt_succ_of_lt x.2))) _).2 ⟨⟨i, lt_of_le_of_ne (nat.le_of_lt_succ hin) (λ h, by clear_aux_decl; subst h; exact hl hi)⟩, hi⟩, rw h at this, exact this } }, { simp } end⟩ /-- `find p` returns `none` if and only if `p i` never holds. -/ lemma find_eq_none_iff {n : ℕ} {p : fin n → Prop} [decidable_pred p] : find p = none ↔ ∀ i, ¬ p i := by rw [← not_exists, ← is_some_find_iff]; cases (find p); simp /-- If `find p` returns `some i`, then `p j` does not hold for `j < i`, i.e., `i` is minimal among the indices where `p` holds. -/ lemma find_min : Π {n : ℕ} {p : fin n → Prop} [decidable_pred p] {i : fin n} (hi : i ∈ by exactI fin.find p) {j : fin n} (hj : j < i), ¬ p j | 0 p _ i hi j hj hpj := option.no_confusion hi | (n+1) p _ i hi ⟨j, hjn⟩ hj hpj := begin resetI, dsimp [find] at hi, cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with k, { rw [h] at hi, split_ifs at hi with hl hl, { have := option.some_inj.1 hi, subst this, rw [find_eq_none_iff] at h, exact h ⟨j, hj⟩ hpj }, { exact option.no_confusion hi } }, { rw h at hi, dsimp at hi, have := option.some_inj.1 hi, subst this, exact find_min h (show (⟨j, lt_trans hj k.2⟩ : fin n) < k, from hj) hpj } end lemma find_min' {p : fin n → Prop} [decidable_pred p] {i : fin n} (h : i ∈ fin.find p) {j : fin n} (hj : p j) : i ≤ j := le_of_not_gt (λ hij, find_min h hij hj) lemma nat_find_mem_find {p : fin n → Prop} [decidable_pred p] (h : ∃ i, ∃ hin : i < n, p ⟨i, hin⟩) : (⟨nat.find h, (nat.find_spec h).fst⟩ : fin n) ∈ find p := let ⟨i, hin, hi⟩ := h in begin cases hf : find p with f, { rw [find_eq_none_iff] at hf, exact (hf ⟨i, hin⟩ hi).elim }, { refine option.some_inj.2 (le_antisymm _ _), { exact find_min' hf (nat.find_spec h).snd }, { exact nat.find_min' _ ⟨f.2, by convert find_spec p hf; exact fin.eta _ _⟩ } } end lemma mem_find_iff {p : fin n → Prop} [decidable_pred p] {i : fin n} : i ∈ fin.find p ↔ p i ∧ ∀ j, p j → i ≤ j := ⟨λ hi, ⟨find_spec _ hi, λ _, find_min' hi⟩, begin rintros ⟨hpi, hj⟩, cases hfp : fin.find p, { rw [find_eq_none_iff] at hfp, exact (hfp _ hpi).elim }, { exact option.some_inj.2 (le_antisymm (find_min' hfp hpi) (hj _ (find_spec _ hfp))) } end⟩ lemma find_eq_some_iff {p : fin n → Prop} [decidable_pred p] {i : fin n} : fin.find p = some i ↔ p i ∧ ∀ j, p j → i ≤ j := mem_find_iff lemma mem_find_of_unique {p : fin n → Prop} [decidable_pred p] (h : ∀ i j, p i → p j → i = j) {i : fin n} (hi : p i) : i ∈ fin.find p := mem_find_iff.2 ⟨hi, λ j hj, le_of_eq $ h i j hi hj⟩ end find end fin
bfda189acad2f7a7eb8335f849677bf7d9f8f90e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/algebra/filter_basis.lean
5ef959246ca607cbdc9bac1bfc1088c1696928b2
[ "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
17,196
lean
/- Copyright (c) 2021 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import order.filter.bases import topology.algebra.module.basic /-! # Group and ring filter bases A `group_filter_basis` is a `filter_basis` on a group with some properties relating the basis to the group structure. The main theorem is that a `group_filter_basis` on a group gives a topology on the group which makes it into a topological group with neighborhoods of the neutral element generated by the given basis. ## Main definitions and results Given a group `G` and a ring `R`: * `group_filter_basis G`: the type of filter bases that will become neighborhood of `1` for a topology on `G` compatible with the group structure * `group_filter_basis.topology`: the associated topology * `group_filter_basis.is_topological_group`: the compatibility between the above topology and the group structure * `ring_filter_basis R`: the type of filter bases that will become neighborhood of `0` for a topology on `R` compatible with the ring structure * `ring_filter_basis.topology`: the associated topology * `ring_filter_basis.is_topological_ring`: the compatibility between the above topology and the ring structure ## References * [N. Bourbaki, *General Topology*][bourbaki1966] -/ open filter set topological_space function open_locale topological_space filter pointwise universe u /-- A `group_filter_basis` on a group is a `filter_basis` satisfying some additional axioms. Example : if `G` is a topological group then the neighbourhoods of the identity are a `group_filter_basis`. Conversely given a `group_filter_basis` one can define a topology compatible with the group structure on `G`. -/ class group_filter_basis (G : Type u) [group G] extends filter_basis G := (one' : ∀ {U}, U ∈ sets → (1 : G) ∈ U) (mul' : ∀ {U}, U ∈ sets → ∃ V ∈ sets, V * V ⊆ U) (inv' : ∀ {U}, U ∈ sets → ∃ V ∈ sets, V ⊆ (λ x, x⁻¹) ⁻¹' U) (conj' : ∀ x₀, ∀ {U}, U ∈ sets → ∃ V ∈ sets, V ⊆ (λ x, x₀*x*x₀⁻¹) ⁻¹' U) /-- A `add_group_filter_basis` on an additive group is a `filter_basis` satisfying some additional axioms. Example : if `G` is a topological group then the neighbourhoods of the identity are a `add_group_filter_basis`. Conversely given a `add_group_filter_basis` one can define a topology compatible with the group structure on `G`. -/ class add_group_filter_basis (A : Type u) [add_group A] extends filter_basis A := (zero' : ∀ {U}, U ∈ sets → (0 : A) ∈ U) (add' : ∀ {U}, U ∈ sets → ∃ V ∈ sets, V + V ⊆ U) (neg' : ∀ {U}, U ∈ sets → ∃ V ∈ sets, V ⊆ (λ x, -x) ⁻¹' U) (conj' : ∀ x₀, ∀ {U}, U ∈ sets → ∃ V ∈ sets, V ⊆ (λ x, x₀+x+-x₀) ⁻¹' U) attribute [to_additive] group_filter_basis attribute [to_additive] group_filter_basis.one' attribute [to_additive] group_filter_basis.mul' attribute [to_additive] group_filter_basis.inv' attribute [to_additive] group_filter_basis.conj' attribute [to_additive] group_filter_basis.to_filter_basis /-- `group_filter_basis` constructor in the commutative group case. -/ @[to_additive "`add_group_filter_basis` constructor in the additive commutative group case."] def group_filter_basis_of_comm {G : Type*} [comm_group G] (sets : set (set G)) (nonempty : sets.nonempty) (inter_sets : ∀ (x y), x ∈ sets → y ∈ sets → ∃ z ∈ sets, z ⊆ x ∩ y) (one : ∀ U ∈ sets, (1 : G) ∈ U) (mul : ∀ U ∈ sets, ∃ V ∈ sets, V * V ⊆ U) (inv : ∀ U ∈ sets, ∃ V ∈ sets, V ⊆ (λ x, x⁻¹) ⁻¹' U) : group_filter_basis G := { sets := sets, nonempty := nonempty, inter_sets := inter_sets, one' := one, mul' := mul, inv' := inv, conj' := λ x U U_in, ⟨U, U_in, by simp⟩ } namespace group_filter_basis variables {G : Type u} [group G] {B : group_filter_basis G} @[to_additive] instance : has_mem (set G) (group_filter_basis G) := ⟨λ s f, s ∈ f.sets⟩ @[to_additive] lemma one {U : set G} : U ∈ B → (1 : G) ∈ U := group_filter_basis.one' @[to_additive] lemma mul {U : set G} : U ∈ B → ∃ V ∈ B, V*V ⊆ U := group_filter_basis.mul' @[to_additive] lemma inv {U : set G} : U ∈ B → ∃ V ∈ B, V ⊆ (λ x, x⁻¹) ⁻¹' U := group_filter_basis.inv' @[to_additive] lemma conj : ∀ x₀, ∀ {U}, U ∈ B → ∃ V ∈ B, V ⊆ (λ x, x₀*x*x₀⁻¹) ⁻¹' U := group_filter_basis.conj' /-- The trivial group filter basis consists of `{1}` only. The associated topology is discrete. -/ @[to_additive "The trivial additive group filter basis consists of `{0}` only. The associated topology is discrete."] instance : inhabited (group_filter_basis G) := ⟨begin refine { sets := {{1}}, nonempty := singleton_nonempty _, .. }, all_goals { simp only [exists_prop, mem_singleton_iff] }, { rintros - - rfl rfl, use {1}, simp }, { simp }, { rintro - rfl, use {1}, simp }, { rintro - rfl, use {1}, simp }, { rintro x₀ - rfl, use {1}, simp } end⟩ @[to_additive] lemma prod_subset_self (B : group_filter_basis G) {U : set G} (h : U ∈ B) : U ⊆ U * U := λ x x_in, ⟨1, x, one h, x_in, one_mul x⟩ /-- The neighborhood function of a `group_filter_basis` -/ @[to_additive "The neighborhood function of a `add_group_filter_basis`"] def N (B : group_filter_basis G) : G → filter G := λ x, map (λ y, x*y) B.to_filter_basis.filter @[simp, to_additive] lemma N_one (B : group_filter_basis G) : B.N 1 = B.to_filter_basis.filter := by simp only [N, one_mul, map_id'] @[to_additive] protected lemma has_basis (B : group_filter_basis G) (x : G) : has_basis (B.N x) (λ V : set G, V ∈ B) (λ V, (λ y, x*y) '' V) := has_basis.map (λ y, x * y) to_filter_basis.has_basis /-- The topological space structure coming from a group filter basis. -/ @[to_additive "The topological space structure coming from an additive group filter basis."] def topology (B : group_filter_basis G) : topological_space G := topological_space.mk_of_nhds B.N @[to_additive] lemma nhds_eq (B : group_filter_basis G) {x₀ : G} : @nhds G (B.topology) x₀ = B.N x₀ := begin rw [topological_space.nhds_mk_of_nhds], { intros x U U_in, rw (B.has_basis x).mem_iff at U_in, rcases U_in with ⟨V, V_in, H⟩, simpa [mem_pure] using H (mem_image_of_mem _ (group_filter_basis.one V_in)), }, { intros x U U_in, rw (B.has_basis x).mem_iff at U_in, rcases U_in with ⟨V, V_in, H⟩, rcases group_filter_basis.mul V_in with ⟨W, W_in, hW⟩, use [(λ y, x*y) '' W, image_mem_map (filter_basis.mem_filter_of_mem _ W_in)], split, { rw image_subset_iff at H ⊢, exact ((B.prod_subset_self W_in).trans hW).trans H }, { rintros y ⟨t, tW, rfl⟩, rw (B.has_basis _).mem_iff, use [W, W_in], apply subset.trans _ H, clear H, rintros z ⟨w, wW, rfl⟩, exact ⟨t*w, hW (mul_mem_mul tW wW), by simp [mul_assoc]⟩ } } end @[to_additive] lemma nhds_one_eq (B : group_filter_basis G) : @nhds G (B.topology) (1 : G) = B.to_filter_basis.filter := by { rw B.nhds_eq, simp only [N, one_mul], exact map_id } @[to_additive] lemma nhds_has_basis (B : group_filter_basis G) (x₀ : G) : has_basis (@nhds G B.topology x₀) (λ V : set G, V ∈ B) (λ V, (λ y, x₀ * y) '' V) := by { rw B.nhds_eq, apply B.has_basis } @[to_additive] lemma nhds_one_has_basis (B : group_filter_basis G) : has_basis (@nhds G B.topology 1) (λ V : set G, V ∈ B) id := by { rw B.nhds_one_eq, exact B.to_filter_basis.has_basis } @[to_additive] lemma mem_nhds_one (B : group_filter_basis G) {U : set G} (hU : U ∈ B) : U ∈ @nhds G B.topology 1 := begin rw B.nhds_one_has_basis.mem_iff, exact ⟨U, hU, rfl.subset⟩ end /-- If a group is endowed with a topological structure coming from a group filter basis then it's a topological group. -/ @[to_additive "If a group is endowed with a topological structure coming from a group filter basis then it's a topological group.", priority 100] -- See note [lower instance priority] instance is_topological_group (B : group_filter_basis G) : @topological_group G B.topology _ := begin letI := B.topology, have basis := B.nhds_one_has_basis, have basis' := basis.prod basis, refine topological_group.of_nhds_one _ _ _ _, { rw basis'.tendsto_iff basis, suffices : ∀ U ∈ B, ∃ V W, (V ∈ B ∧ W ∈ B) ∧ ∀ a b, a ∈ V → b ∈ W → a * b ∈ U, by simpa, intros U U_in, rcases mul U_in with ⟨V, V_in, hV⟩, use [V, V, V_in, V_in], intros a b a_in b_in, exact hV ⟨a, b, a_in, b_in, rfl⟩ }, { rw basis.tendsto_iff basis, intros U U_in, simpa using inv U_in }, { intro x₀, rw [nhds_eq, nhds_one_eq], refl }, { intro x₀, rw basis.tendsto_iff basis, intros U U_in, exact conj x₀ U_in } end end group_filter_basis /-- A `ring_filter_basis` on a ring is a `filter_basis` satisfying some additional axioms. Example : if `R` is a topological ring then the neighbourhoods of the identity are a `ring_filter_basis`. Conversely given a `ring_filter_basis` on a ring `R`, one can define a topology on `R` which is compatible with the ring structure. -/ class ring_filter_basis (R : Type u) [ring R] extends add_group_filter_basis R := (mul' : ∀ {U}, U ∈ sets → ∃ V ∈ sets, V * V ⊆ U) (mul_left' : ∀ (x₀ : R) {U}, U ∈ sets → ∃ V ∈ sets, V ⊆ (λ x, x₀*x) ⁻¹' U) (mul_right' : ∀ (x₀ : R) {U}, U ∈ sets → ∃ V ∈ sets, V ⊆ (λ x, x*x₀) ⁻¹' U) namespace ring_filter_basis variables {R : Type u} [ring R] (B : ring_filter_basis R) instance : has_mem (set R) (ring_filter_basis R) := ⟨λ s B, s ∈ B.sets⟩ lemma mul {U : set R} (hU : U ∈ B) : ∃ V ∈ B, V * V ⊆ U := mul' hU lemma mul_left (x₀ : R) {U : set R} (hU : U ∈ B) : ∃ V ∈ B, V ⊆ (λ x, x₀*x) ⁻¹' U := mul_left' x₀ hU lemma mul_right (x₀ : R) {U : set R} (hU : U ∈ B) : ∃ V ∈ B, V ⊆ (λ x, x*x₀) ⁻¹' U := mul_right' x₀ hU /-- The topology associated to a ring filter basis. It has the given basis as a basis of neighborhoods of zero. -/ def topology : topological_space R := B.to_add_group_filter_basis.topology /-- If a ring is endowed with a topological structure coming from a ring filter basis then it's a topological ring. -/ @[priority 100] instance is_topological_ring {R : Type u} [ring R] (B : ring_filter_basis R) : @topological_ring R B.topology _ := begin let B' := B.to_add_group_filter_basis, letI := B'.topology, have basis := B'.nhds_zero_has_basis, have basis' := basis.prod basis, haveI := B'.is_topological_add_group, apply topological_ring.of_add_group_of_nhds_zero, { rw basis'.tendsto_iff basis, suffices : ∀ U ∈ B', ∃ V W, (V ∈ B' ∧ W ∈ B') ∧ ∀ a b, a ∈ V → b ∈ W → a * b ∈ U, by simpa, intros U U_in, rcases B.mul U_in with ⟨V, V_in, hV⟩, use [V, V, V_in, V_in], intros a b a_in b_in, exact hV ⟨a, b, a_in, b_in, rfl⟩ }, { intro x₀, rw basis.tendsto_iff basis, intros U, simpa using B.mul_left x₀ }, { intro x₀, rw basis.tendsto_iff basis, intros U, simpa using B.mul_right x₀ }, end end ring_filter_basis /-- A `module_filter_basis` on a module is a `filter_basis` satisfying some additional axioms. Example : if `M` is a topological module then the neighbourhoods of zero are a `module_filter_basis`. Conversely given a `module_filter_basis` one can define a topology compatible with the module structure on `M`. -/ structure module_filter_basis (R M : Type*) [comm_ring R] [topological_space R] [add_comm_group M] [module R M] extends add_group_filter_basis M := (smul' : ∀ {U}, U ∈ sets → ∃ (V ∈ 𝓝 (0 : R)) (W ∈ sets), V • W ⊆ U) (smul_left' : ∀ (x₀ : R) {U}, U ∈ sets → ∃ V ∈ sets, V ⊆ (λ x, x₀ • x) ⁻¹' U) (smul_right' : ∀ (m₀ : M) {U}, U ∈ sets → ∀ᶠ x in 𝓝 (0 : R), x • m₀ ∈ U) namespace module_filter_basis variables {R M : Type*} [comm_ring R] [topological_space R] [add_comm_group M] [module R M] (B : module_filter_basis R M) instance group_filter_basis.has_mem : has_mem (set M) (module_filter_basis R M) := ⟨λ s B, s ∈ B.sets⟩ lemma smul {U : set M} (hU : U ∈ B) : ∃ (V ∈ 𝓝 (0 : R)) (W ∈ B), V • W ⊆ U := B.smul' hU lemma smul_left (x₀ : R) {U : set M} (hU : U ∈ B) : ∃ V ∈ B, V ⊆ (λ x, x₀ • x) ⁻¹' U := B.smul_left' x₀ hU lemma smul_right (m₀ : M) {U : set M} (hU : U ∈ B) : ∀ᶠ x in 𝓝 (0 : R), x • m₀ ∈ U := B.smul_right' m₀ hU /-- If `R` is discrete then the trivial additive group filter basis on any `R`-module is a module filter basis. -/ instance [discrete_topology R] : inhabited (module_filter_basis R M) := ⟨{ smul' := begin rintro U (h : U ∈ {{(0 : M)}}), rw mem_singleton_iff at h, use [univ, univ_mem, {0}, rfl], rintros a ⟨x, m, -, hm, rfl⟩, simp [mem_singleton_iff.1 hm, h] end, smul_left' := begin rintro x₀ U (h : U ∈ {{(0 : M)}}), rw mem_singleton_iff at h, use [{0}, rfl], simp [h] end, smul_right' := begin rintro m₀ U (h : U ∈ (0 : set (set M))), rw set.mem_zero at h, simp [h, nhds_discrete] end, ..show add_group_filter_basis M, from default }⟩ /-- The topology associated to a module filter basis on a module over a topological ring. It has the given basis as a basis of neighborhoods of zero. -/ def topology : topological_space M := B.to_add_group_filter_basis.topology /-- The topology associated to a module filter basis on a module over a topological ring. It has the given basis as a basis of neighborhoods of zero. This version gets the ring topology by unification instead of type class inference. -/ def topology' {R M : Type*} [comm_ring R] {tR : topological_space R} [add_comm_group M] [module R M] (B : module_filter_basis R M) : topological_space M := B.to_add_group_filter_basis.topology /-- A topological add group whith a basis of `𝓝 0` satisfying the axioms of `module_filter_basis` is a topological module. This lemma is mathematically useless because one could obtain such a result by applying `module_filter_basis.has_continuous_smul` and use the fact that group topologies are characterized by their neighborhoods of 0 to obtain the `has_continuous_smul` on the pre-existing topology. But it turns out it's just easier to get it as a biproduct of the proof, so this is just a free quality-of-life improvement. -/ lemma _root_.has_continuous_smul.of_basis_zero {ι : Type*} [topological_ring R] [topological_space M] [topological_add_group M] {p : ι → Prop} {b : ι → set M} (h : has_basis (𝓝 0) p b) (hsmul : ∀ {i}, p i → ∃ (V ∈ 𝓝 (0 : R)) j (hj : p j), V • (b j) ⊆ b i) (hsmul_left : ∀ (x₀ : R) {i}, p i → ∃ j (hj : p j), (b j) ⊆ (λ x, x₀ • x) ⁻¹' (b i)) (hsmul_right : ∀ (m₀ : M) {i}, p i → ∀ᶠ x in 𝓝 (0 : R), x • m₀ ∈ (b i)) : has_continuous_smul R M := begin apply has_continuous_smul.of_nhds_zero, { rw h.tendsto_right_iff, intros i hi, rcases hsmul hi with ⟨V, V_in, j, hj, hVj⟩, apply mem_of_superset (prod_mem_prod V_in $ h.mem_of_mem hj), rintros ⟨v, w⟩ ⟨v_in : v ∈ V, w_in : w ∈ (b j)⟩, exact hVj (set.smul_mem_smul v_in w_in) }, { intro m₀, rw h.tendsto_right_iff, intros i hi, exact hsmul_right m₀ hi }, { intro x₀, rw h.tendsto_right_iff, intros i hi, rcases hsmul_left x₀ hi with ⟨j, hj, hji⟩, exact mem_of_superset (h.mem_of_mem hj) hji }, end /-- If a module is endowed with a topological structure coming from a module filter basis then it's a topological module. -/ @[priority 100] instance has_continuous_smul [topological_ring R] : @has_continuous_smul R M _ _ B.topology := begin let B' := B.to_add_group_filter_basis, letI := B'.topology, haveI := B'.is_topological_add_group, exact has_continuous_smul.of_basis_zero B'.nhds_zero_has_basis (λ _, B.smul) B.smul_left B.smul_right, end /-- Build a module filter basis from compatible ring and additive group filter bases. -/ def of_bases {R M : Type*} [comm_ring R] [add_comm_group M] [module R M] (BR : ring_filter_basis R) (BM : add_group_filter_basis M) (smul : ∀ {U}, U ∈ BM → ∃ (V ∈ BR) (W ∈ BM), V • W ⊆ U) (smul_left : ∀ (x₀ : R) {U}, U ∈ BM → ∃ V ∈ BM, V ⊆ (λ x, x₀ • x) ⁻¹' U) (smul_right : ∀ (m₀ : M) {U}, U ∈ BM → ∃ V ∈ BR, V ⊆ (λ x, x • m₀) ⁻¹' U) : @module_filter_basis R M _ BR.topology _ _ := { smul' := begin intros U U_in, rcases smul U_in with ⟨V, V_in, W, W_in, H⟩, exact ⟨V, BR.to_add_group_filter_basis.mem_nhds_zero V_in, W, W_in, H⟩ end, smul_left' := smul_left, smul_right' := begin intros m₀ U U_in, rcases smul_right m₀ U_in with ⟨V, V_in, H⟩, exact mem_of_superset (BR.to_add_group_filter_basis.mem_nhds_zero V_in) H end, ..BM } end module_filter_basis
e484592a502fb4f919c828d4a89c26cc6991fbaa
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/data/equiv/mul_add.lean
cdf79c7af793bf608b750268ff4e6fd01bdc3f6a
[ "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
16,276
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, Callum Sutton, Yury Kudryashov -/ import data.equiv.basic import deprecated.group /-! # Multiplicative and additive equivs In this file we define two extensions of `equiv` called `add_equiv` and `mul_equiv`, which are datatypes representing isomorphisms of `add_monoid`s/`add_group`s and `monoid`s/`group`s. We also introduce the corresponding groups of automorphisms `add_aut` and `mul_aut`. ## Notations The extended equivs all have coercions to functions, and the coercions are the canonical notation when treating the isomorphisms as maps. ## Implementation notes The fields for `mul_equiv`, `add_equiv` now avoid the unbundled `is_mul_hom` and `is_add_hom`, as these are deprecated. Definition of multiplication in the groups of automorphisms agrees with function composition, multiplication in `equiv.perm`, and multiplication in `category_theory.End`, not with `category_theory.comp`. ## Tags equiv, mul_equiv, add_equiv, mul_aut, add_aut -/ variables {A : Type*} {B : Type*} {M : Type*} {N : Type*} {P : Type*} {G : Type*} {H : Type*} set_option old_structure_cmd true /-- add_equiv α β is the type of an equiv α ≃ β which preserves addition. -/ structure add_equiv (A B : Type*) [has_add A] [has_add B] extends A ≃ B := (map_add' : ∀ x y : A, to_fun (x + y) = to_fun x + to_fun y) /-- The `equiv` underlying an `add_equiv`. -/ add_decl_doc add_equiv.to_equiv /-- `mul_equiv α β` is the type of an equiv `α ≃ β` which preserves multiplication. -/ @[to_additive] structure mul_equiv (M N : Type*) [has_mul M] [has_mul N] extends M ≃ N := (map_mul' : ∀ x y : M, to_fun (x * y) = to_fun x * to_fun y) /-- The `equiv` underlying a `mul_equiv`. -/ add_decl_doc mul_equiv.to_equiv infix ` ≃* `:25 := mul_equiv infix ` ≃+ `:25 := add_equiv namespace mul_equiv @[to_additive] instance [has_mul M] [has_mul N] : has_coe_to_fun (M ≃* N) := ⟨_, mul_equiv.to_fun⟩ variables [has_mul M] [has_mul N] [has_mul P] @[simp, to_additive] lemma to_fun_apply {f : M ≃* N} {m : M} : f.to_fun m = f m := rfl /-- A multiplicative isomorphism preserves multiplication (canonical form). -/ @[simp, to_additive] lemma map_mul (f : M ≃* N) : ∀ x y, f (x * y) = f x * f y := f.map_mul' /-- A multiplicative isomorphism preserves multiplication (deprecated). -/ @[to_additive] instance (h : M ≃* N) : is_mul_hom h := ⟨h.map_mul⟩ /-- Makes a multiplicative isomorphism from a bijection which preserves multiplication. -/ @[to_additive "Makes an additive isomorphism from a bijection which preserves addition."] def mk' (f : M ≃ N) (h : ∀ x y, f (x * y) = f x * f y) : M ≃* N := ⟨f.1, f.2, f.3, f.4, h⟩ /-- The identity map is a multiplicative isomorphism. -/ @[refl, to_additive "The identity map is an additive isomorphism."] def refl (M : Type*) [has_mul M] : M ≃* M := { map_mul' := λ _ _, rfl, ..equiv.refl _} instance : inhabited (M ≃* M) := ⟨refl M⟩ /-- The inverse of an isomorphism is an isomorphism. -/ @[symm, to_additive "The inverse of an isomorphism is an isomorphism."] def symm (h : M ≃* N) : N ≃* M := { map_mul' := λ n₁ n₂, h.left_inv.injective begin show h.to_equiv (h.to_equiv.symm (n₁ * n₂)) = h ((h.to_equiv.symm n₁) * (h.to_equiv.symm n₂)), rw h.map_mul, show _ = h.to_equiv (_) * h.to_equiv (_), rw [h.to_equiv.apply_symm_apply, h.to_equiv.apply_symm_apply, h.to_equiv.apply_symm_apply], end, ..h.to_equiv.symm} @[simp, to_additive] theorem to_equiv_symm (f : M ≃* N) : f.symm.to_equiv = f.to_equiv.symm := rfl @[simp, to_additive] theorem coe_mk (f : M → N) (g h₁ h₂ h₃) : ⇑(mul_equiv.mk f g h₁ h₂ h₃) = f := rfl @[simp, to_additive] theorem coe_symm_mk (f : M → N) (g h₁ h₂ h₃) : ⇑(mul_equiv.mk f g h₁ h₂ h₃).symm = g := rfl /-- Transitivity of multiplication-preserving isomorphisms -/ @[trans, to_additive "Transitivity of addition-preserving isomorphisms"] def trans (h1 : M ≃* N) (h2 : N ≃* P) : (M ≃* P) := { map_mul' := λ x y, show h2 (h1 (x * y)) = h2 (h1 x) * h2 (h1 y), by rw [h1.map_mul, h2.map_mul], ..h1.to_equiv.trans h2.to_equiv } /-- e.right_inv in canonical form -/ @[simp, to_additive] lemma apply_symm_apply (e : M ≃* N) : ∀ y, e (e.symm y) = y := e.to_equiv.apply_symm_apply /-- e.left_inv in canonical form -/ @[simp, to_additive] lemma symm_apply_apply (e : M ≃* N) : ∀ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply @[simp, to_additive] theorem refl_apply (m : M) : refl M m = m := rfl @[simp, to_additive] theorem trans_apply (e₁ : M ≃* N) (e₂ : N ≃* P) (m : M) : e₁.trans e₂ m = e₂ (e₁ m) := rfl /-- a multiplicative equiv of monoids sends 1 to 1 (and is hence a monoid isomorphism) -/ @[simp, to_additive] lemma map_one {M N} [monoid M] [monoid N] (h : M ≃* N) : h 1 = 1 := by rw [←mul_one (h 1), ←h.apply_symm_apply 1, ←h.map_mul, one_mul] @[simp, to_additive] lemma map_eq_one_iff {M N} [monoid M] [monoid N] (h : M ≃* N) {x : M} : h x = 1 ↔ x = 1 := h.map_one ▸ h.to_equiv.apply_eq_iff_eq x 1 @[to_additive] lemma map_ne_one_iff {M N} [monoid M] [monoid N] (h : M ≃* N) {x : M} : h x ≠ 1 ↔ x ≠ 1 := ⟨mt h.map_eq_one_iff.2, mt h.map_eq_one_iff.1⟩ /-- A bijective `monoid` homomorphism is an isomorphism -/ @[to_additive "A bijective `add_monoid` homomorphism is an isomorphism"] noncomputable def of_bijective {M N} [monoid M] [monoid N] (f : M →* N) (hf : function.bijective f) : M ≃* N := { map_mul' := f.map_mul', ..equiv.of_bijective f hf } /-- Extract the forward direction of a multiplicative equivalence as a multiplication-preserving function. -/ @[to_additive "Extract the forward direction of an additive equivalence as an addition-preserving function."] def to_monoid_hom {M N} [monoid M] [monoid N] (h : M ≃* N) : (M →* N) := { map_one' := h.map_one, .. h } @[simp, to_additive] lemma to_monoid_hom_apply {M N} [monoid M] [monoid N] (e : M ≃* N) (x : M) : e.to_monoid_hom x = e x := rfl /-- A multiplicative equivalence of groups preserves inversion. -/ @[simp, to_additive] lemma map_inv [group G] [group H] (h : G ≃* H) (x : G) : h x⁻¹ = (h x)⁻¹ := h.to_monoid_hom.map_inv x /-- A multiplicative bijection between two monoids is a monoid hom (deprecated -- use to_monoid_hom). -/ @[to_additive] instance is_monoid_hom {M N} [monoid M] [monoid N] (h : M ≃* N) : is_monoid_hom h := ⟨h.map_one⟩ /-- A multiplicative bijection between two groups is a group hom (deprecated -- use to_monoid_hom). -/ @[to_additive] instance is_group_hom {G H} [group G] [group H] (h : G ≃* H) : is_group_hom h := { map_mul := h.map_mul } /-- Two multiplicative isomorphisms agree if they are defined by the same underlying function. -/ @[ext, to_additive "Two additive isomorphisms agree if they are defined by the same underlying function."] lemma ext {f g : mul_equiv M N} (h : ∀ x, f x = g x) : f = g := begin have h₁ : f.to_equiv = g.to_equiv := equiv.ext h, cases f, cases g, congr, { exact (funext h) }, { exact congr_arg equiv.inv_fun h₁ } end attribute [ext] add_equiv.ext end mul_equiv /-- An additive equivalence of additive groups preserves subtraction. -/ lemma add_equiv.map_sub [add_group A] [add_group B] (h : A ≃+ B) (x y : A) : h (x - y) = h x - h y := h.to_add_monoid_hom.map_sub x y instance add_equiv.inhabited {M : Type*} [has_add M] : inhabited (M ≃+ M) := ⟨add_equiv.refl M⟩ /-- The group of multiplicative automorphisms. -/ @[to_additive "The group of additive automorphisms."] def mul_aut (M : Type*) [has_mul M] := M ≃* M attribute [reducible] mul_aut add_aut namespace mul_aut variables (M) [has_mul M] /-- The group operation on multiplicative automorphisms is defined by `λ g h, mul_equiv.trans h g`. This means that multiplication agrees with composition, `(g*h)(x) = g (h x)`. -/ instance : group (mul_aut M) := by refine_struct { mul := λ g h, mul_equiv.trans h g, one := mul_equiv.refl M, inv := mul_equiv.symm }; intros; ext; try { refl }; apply equiv.left_inv instance : inhabited (mul_aut M) := ⟨1⟩ @[simp] lemma coe_mul (e₁ e₂ : mul_aut M) : ⇑(e₁ * e₂) = e₁ ∘ e₂ := rfl @[simp] lemma coe_one : ⇑(1 : mul_aut M) = id := rfl lemma mul_def (e₁ e₂ : mul_aut M) : e₁ * e₂ = e₂.trans e₁ := rfl lemma one_def : (1 : mul_aut M) = mul_equiv.refl _ := rfl lemma inv_def (e₁ : mul_aut M) : e₁⁻¹ = e₁.symm := rfl @[simp] lemma mul_apply (e₁ e₂ : mul_aut M) (m : M) : (e₁ * e₂) m = e₁ (e₂ m) := rfl @[simp] lemma one_apply (m : M) : (1 : mul_aut M) m = m := rfl @[simp] lemma apply_inv_self (e : mul_aut M) (m : M) : e (e⁻¹ m) = m := mul_equiv.apply_symm_apply _ _ @[simp] lemma inv_apply_self (e : mul_aut M) (m : M) : e⁻¹ (e m) = m := mul_equiv.apply_symm_apply _ _ /-- Monoid hom from the group of multiplicative automorphisms to the group of permutations. -/ def to_perm : mul_aut M →* equiv.perm M := by refine_struct { to_fun := mul_equiv.to_equiv }; intros; refl /-- group conjugation as a group homomorphism into the automorphism group. `conj g h = g * h * g⁻¹` -/ def conj [group G] : G →* mul_aut G := { to_fun := λ g, { to_fun := λ h, g * h * g⁻¹, inv_fun := λ h, g⁻¹ * h * g, left_inv := λ _, by simp [mul_assoc], right_inv := λ _, by simp [mul_assoc], map_mul' := by simp [mul_assoc] }, map_mul' := λ _ _, by ext; simp [mul_assoc], map_one' := by ext; simp [mul_assoc] } @[simp] lemma conj_apply [group G] (g h : G) : conj g h = g * h * g⁻¹ := rfl @[simp] lemma conj_symm_apply [group G] (g h : G) : (conj g).symm h = g⁻¹ * h * g := rfl end mul_aut namespace add_aut variables (A) [has_add A] /-- The group operation on additive automorphisms is defined by `λ g h, mul_equiv.trans h g`. This means that multiplication agrees with composition, `(g*h)(x) = g (h x)`. -/ instance group : group (add_aut A) := by refine_struct { mul := λ g h, add_equiv.trans h g, one := add_equiv.refl A, inv := add_equiv.symm }; intros; ext; try { refl }; apply equiv.left_inv instance : inhabited (add_aut A) := ⟨1⟩ @[simp] lemma coe_mul (e₁ e₂ : add_aut A) : ⇑(e₁ * e₂) = e₁ ∘ e₂ := rfl @[simp] lemma coe_one : ⇑(1 : add_aut A) = id := rfl lemma mul_def (e₁ e₂ : add_aut A) : e₁ * e₂ = e₂.trans e₁ := rfl lemma one_def : (1 : add_aut A) = add_equiv.refl _ := rfl lemma inv_def (e₁ : add_aut A) : e₁⁻¹ = e₁.symm := rfl @[simp] lemma mul_apply (e₁ e₂ : add_aut A) (a : A) : (e₁ * e₂) a = e₁ (e₂ a) := rfl @[simp] lemma one_apply (a : A) : (1 : add_aut A) a = a := rfl @[simp] lemma apply_inv_self (e : add_aut A) (a : A) : e⁻¹ (e a) = a := add_equiv.apply_symm_apply _ _ @[simp] lemma inv_apply_self (e : add_aut A) (a : A) : e (e⁻¹ a) = a := add_equiv.apply_symm_apply _ _ /-- Monoid hom from the group of multiplicative automorphisms to the group of permutations. -/ def to_perm : add_aut A →* equiv.perm A := by refine_struct { to_fun := add_equiv.to_equiv }; intros; refl end add_aut /-- A group is isomorphic to its group of units. -/ @[to_additive to_add_units "An additive group is isomorphic to its group of additive units"] def to_units {G} [group G] : G ≃* units G := { to_fun := λ x, ⟨x, x⁻¹, mul_inv_self _, inv_mul_self _⟩, inv_fun := coe, left_inv := λ x, rfl, right_inv := λ u, units.ext rfl, map_mul' := λ x y, units.ext rfl } namespace units variables [monoid M] [monoid N] [monoid P] /-- A multiplicative equivalence of monoids defines a multiplicative equivalence of their groups of units. -/ def map_equiv (h : M ≃* N) : units M ≃* units N := { inv_fun := map h.symm.to_monoid_hom, left_inv := λ u, ext $ h.left_inv u, right_inv := λ u, ext $ h.right_inv u, .. map h.to_monoid_hom } /-- Left multiplication by a unit of a monoid is a permutation of the underlying type. -/ @[to_additive "Left addition of an additive unit is a permutation of the underlying type."] def mul_left (u : units M) : equiv.perm M := { to_fun := λx, u * x, inv_fun := λx, ↑u⁻¹ * x, left_inv := u.inv_mul_cancel_left, right_inv := u.mul_inv_cancel_left } @[simp, to_additive] lemma coe_mul_left (u : units M) : ⇑u.mul_left = (*) u := rfl @[simp, to_additive] lemma mul_left_symm (u : units M) : u.mul_left.symm = u⁻¹.mul_left := equiv.ext $ λ x, rfl /-- Right multiplication by a unit of a monoid is a permutation of the underlying type. -/ @[to_additive "Right addition of an additive unit is a permutation of the underlying type."] def mul_right (u : units M) : equiv.perm M := { to_fun := λx, x * u, inv_fun := λx, x * ↑u⁻¹, left_inv := λ x, mul_inv_cancel_right x u, right_inv := λ x, inv_mul_cancel_right x u } @[simp, to_additive] lemma coe_mul_right (u : units M) : ⇑u.mul_right = λ x : M, x * u := rfl @[simp, to_additive] lemma mul_right_symm (u : units M) : u.mul_right.symm = u⁻¹.mul_right := equiv.ext $ λ x, rfl end units namespace equiv section group variables [group G] /-- Left multiplication in a `group` is a permutation of the underlying type. -/ @[to_additive "Left addition in an `add_group` is a permutation of the underlying type."] protected def mul_left (a : G) : perm G := (to_units a).mul_left @[simp, to_additive] lemma coe_mul_left (a : G) : ⇑(equiv.mul_left a) = (*) a := rfl @[simp, to_additive] lemma mul_left_symm (a : G) : (equiv.mul_left a).symm = equiv.mul_left a⁻¹ := ext $ λ x, rfl /-- Right multiplication in a `group` is a permutation of the underlying type. -/ @[to_additive "Right addition in an `add_group` is a permutation of the underlying type."] protected def mul_right (a : G) : perm G := (to_units a).mul_right @[simp, to_additive] lemma coe_mul_right (a : G) : ⇑(equiv.mul_right a) = λ x, x * a := rfl @[simp, to_additive] lemma mul_right_symm (a : G) : (equiv.mul_right a).symm = equiv.mul_right a⁻¹ := ext $ λ x, rfl variable (G) /-- Inversion on a `group` is a permutation of the underlying type. -/ @[to_additive "Negation on an `add_group` is a permutation of the underlying type."] protected def inv : perm G := { to_fun := λa, a⁻¹, inv_fun := λa, a⁻¹, left_inv := assume a, inv_inv a, right_inv := assume a, inv_inv a } variable {G} @[simp, to_additive] lemma coe_inv : ⇑(equiv.inv G) = has_inv.inv := rfl @[simp, to_additive] lemma inv_symm : (equiv.inv G).symm = equiv.inv G := rfl end group section point_reflection variables [add_comm_group A] (x y : A) /-- Point reflection in `x` as a permutation. -/ def point_reflection (x : A) : perm A := (equiv.neg A).trans (equiv.add_left (x + x)) lemma point_reflection_apply : point_reflection x y = x + x - y := rfl @[simp] lemma point_reflection_self : point_reflection x x = x := add_sub_cancel _ _ lemma point_reflection_involutive : function.involutive (point_reflection x : A → A) := λ y, by simp only [point_reflection_apply, sub_sub_cancel] @[simp] lemma point_reflection_symm : (point_reflection x).symm = point_reflection x := by { ext y, rw [symm_apply_eq, point_reflection_involutive x y] } /-- `x` is the only fixed point of `point_reflection x`. This lemma requires `x + x = y + y ↔ x = y`. There is no typeclass to use here, so we add it as an explicit argument. -/ lemma point_reflection_fixed_iff_of_bit0_injective {x y : A} (h : function.injective (bit0 : A → A)) : point_reflection x y = y ↔ y = x := sub_eq_iff_eq_add.trans $ h.eq_iff.trans eq_comm end point_reflection end equiv section type_tags /-- Reinterpret `f : G ≃+ H` as `multiplicative G ≃* multiplicative H`. -/ def add_equiv.to_multiplicative [add_monoid G] [add_monoid H] (f : G ≃+ H) : multiplicative G ≃* multiplicative H := ⟨f.to_add_monoid_hom.to_multiplicative, f.symm.to_add_monoid_hom.to_multiplicative, f.3, f.4, f.5⟩ /-- Reinterpret `f : G ≃* H` as `additive G ≃+ additive H`. -/ def mul_equiv.to_additive [monoid G] [monoid H] (f : G ≃* H) : additive G ≃+ additive H := ⟨f.to_monoid_hom.to_additive, f.symm.to_monoid_hom.to_additive, f.3, f.4, f.5⟩ end type_tags
51809a8ea02089a0514b2fbaa8db97d012cfb75d
d642a6b1261b2cbe691e53561ac777b924751b63
/src/topology/list.lean
bb6e928645f5a449cec392346da7e6bd347a37cb
[ "Apache-2.0" ]
permissive
cipher1024/mathlib
fee56b9954e969721715e45fea8bcb95f9dc03fe
d077887141000fefa5a264e30fa57520e9f03522
refs/heads/master
1,651,806,490,504
1,573,508,694,000
1,573,508,694,000
107,216,176
0
0
Apache-2.0
1,647,363,136,000
1,508,213,014,000
Lean
UTF-8
Lean
false
false
8,457
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Topology on lists and vectors. -/ import topology.constructions open topological_space set filter variables {α : Type*} {β : Type*} instance [topological_space α] : topological_space (list α) := topological_space.mk_of_nhds (traverse nhds) lemma nhds_list [topological_space α] (as : list α) : nhds as = traverse nhds as := begin refine nhds_mk_of_nhds _ _ _ _, { assume l, induction l, case list.nil { exact le_refl _ }, case list.cons : a l ih { suffices : list.cons <$> pure a <*> pure l ≤ list.cons <$> nhds a <*> traverse nhds l, { simpa only [-filter.pure_def] with functor_norm using this }, exact filter.seq_mono (filter.map_mono $ pure_le_nhds a) ih } }, { assume l s hs, rcases (mem_traverse_sets_iff _ _).1 hs with ⟨u, hu, hus⟩, clear as hs, have : ∃v:list (set α), l.forall₂ (λa s, is_open s ∧ a ∈ s) v ∧ sequence v ⊆ s, { induction hu generalizing s, case list.forall₂.nil : hs this { existsi [], simpa only [list.forall₂_nil_left_iff, exists_eq_left] }, case list.forall₂.cons : a s as ss ht h ih t hts { rcases mem_nhds_sets_iff.1 ht with ⟨u, hut, hu⟩, rcases ih (subset.refl _) with ⟨v, hv, hvss⟩, exact ⟨u::v, list.forall₂.cons hu hv, subset.trans (set.seq_mono (set.image_subset _ hut) hvss) hts⟩ } }, rcases this with ⟨v, hv, hvs⟩, refine ⟨sequence v, mem_traverse_sets _ _ _, hvs, _⟩, { exact hv.imp (assume a s ⟨hs, ha⟩, mem_nhds_sets hs ha) }, { assume u hu, have hu := (list.mem_traverse _ _).1 hu, have : list.forall₂ (λa s, is_open s ∧ a ∈ s) u v, { refine list.forall₂.flip _, replace hv := hv.flip, simp only [list.forall₂_and_left, flip] at ⊢ hv, exact ⟨hv.1, hu.flip⟩ }, refine mem_sets_of_superset _ hvs, exact mem_traverse_sets _ _ (this.imp $ assume a s ⟨hs, ha⟩, mem_nhds_sets hs ha) } } end lemma nhds_nil [topological_space α] : nhds ([] : list α) = pure [] := by rw [nhds_list, list.traverse_nil _]; apply_instance lemma nhds_cons [topological_space α] (a : α) (l : list α) : nhds (a :: l) = list.cons <$> nhds a <*> nhds l := by rw [nhds_list, list.traverse_cons _, ← nhds_list]; apply_instance namespace list variables [topological_space α] [topological_space β] lemma tendsto_cons' {a : α} {l : list α} : tendsto (λp:α×list α, list.cons p.1 p.2) ((nhds a).prod (nhds l)) (nhds (a :: l)) := by rw [nhds_cons, tendsto, map_prod]; exact le_refl _ lemma tendsto_cons {α : Type*} {f : α → β} {g : α → list β} {a : _root_.filter α} {b : β} {l : list β} (hf : tendsto f a (nhds b)) (hg : tendsto g a (nhds l)) : tendsto (λa, list.cons (f a) (g a)) a (nhds (b :: l)) := tendsto_cons'.comp (tendsto.prod_mk hf hg) lemma tendsto_cons_iff {β : Type*} {f : list α → β} {b : _root_.filter β} {a : α} {l : list α} : tendsto f (nhds (a :: l)) b ↔ tendsto (λp:α×list α, f (p.1 :: p.2)) ((nhds a).prod (nhds l)) b := have nhds (a :: l) = ((nhds a).prod (nhds l)).map (λp:α×list α, (p.1 :: p.2)), begin simp only [nhds_cons, filter.prod_eq, (filter.map_def _ _).symm, (filter.seq_eq_filter_seq _ _).symm], simp [-filter.seq_eq_filter_seq, -filter.map_def, (∘)] with functor_norm, end, by rw [this, filter.tendsto_map'_iff] lemma tendsto_nhds {β : Type*} {f : list α → β} {r : list α → _root_.filter β} (h_nil : tendsto f (pure []) (r [])) (h_cons : ∀l a, tendsto f (nhds l) (r l) → tendsto (λp:α×list α, f (p.1 :: p.2)) ((nhds a).prod (nhds l)) (r (a::l))) : ∀l, tendsto f (nhds l) (r l) | [] := by rwa [nhds_nil] | (a::l) := by rw [tendsto_cons_iff]; exact h_cons l a (tendsto_nhds l) lemma continuous_at_length : ∀(l : list α), continuous_at list.length l := begin simp only [continuous_at, nhds_discrete], refine tendsto_nhds _ _, { exact tendsto_pure_pure _ _ }, { assume l a ih, dsimp only [list.length], refine tendsto.comp (tendsto_pure_pure (λx, x + 1) _) _, refine tendsto.comp ih tendsto_snd } end lemma tendsto_insert_nth' {a : α} : ∀{n : ℕ} {l : list α}, tendsto (λp:α×list α, insert_nth n p.1 p.2) ((nhds a).prod (nhds l)) (nhds (insert_nth n a l)) | 0 l := tendsto_cons' | (n+1) [] := suffices tendsto (λa, []) (nhds a) (nhds ([] : list α)), by simpa [nhds_nil, tendsto, map_prod, -filter.pure_def, (∘), insert_nth], tendsto_const_nhds | (n+1) (a'::l) := have (nhds a).prod (nhds (a' :: l)) = ((nhds a).prod ((nhds a').prod (nhds l))).map (λp:α×α×list α, (p.1, p.2.1 :: p.2.2)), begin simp only [nhds_cons, filter.prod_eq, (filter.map_def _ _).symm, (filter.seq_eq_filter_seq _ _).symm], simp [-filter.seq_eq_filter_seq, -filter.map_def, (∘)] with functor_norm end, begin rw [this, tendsto_map'_iff], exact tendsto_cons (tendsto_fst.comp tendsto_snd) ((@tendsto_insert_nth' n l).comp (tendsto.prod_mk tendsto_fst (tendsto_snd.comp tendsto_snd))) end lemma tendsto_insert_nth {β : Type*} {n : ℕ} {a : α} {l : list α} {f : β → α} {g : β → list α} {b : _root_.filter β} (hf : tendsto f b (nhds a)) (hg : tendsto g b (nhds l)) : tendsto (λb:β, insert_nth n (f b) (g b)) b (nhds (insert_nth n a l)) := tendsto_insert_nth'.comp (tendsto.prod_mk hf hg) lemma continuous_insert_nth {n : ℕ} : continuous (λp:α×list α, insert_nth n p.1 p.2) := continuous_iff_continuous_at.mpr $ assume ⟨a, l⟩, by rw [continuous_at, nhds_prod_eq]; exact tendsto_insert_nth' lemma tendsto_remove_nth : ∀{n : ℕ} {l : list α}, tendsto (λl, remove_nth l n) (nhds l) (nhds (remove_nth l n)) | _ [] := by rw [nhds_nil]; exact tendsto_pure_nhds _ _ | 0 (a::l) := by rw [tendsto_cons_iff]; exact tendsto_snd | (n+1) (a::l) := begin rw [tendsto_cons_iff], dsimp [remove_nth], exact tendsto_cons tendsto_fst ((@tendsto_remove_nth n l).comp tendsto_snd) end lemma continuous_remove_nth {n : ℕ} : continuous (λl : list α, remove_nth l n) := continuous_iff_continuous_at.mpr $ assume a, tendsto_remove_nth end list namespace vector open list instance (n : ℕ) [topological_space α] : topological_space (vector α n) := by unfold vector; apply_instance lemma cons_val {n : ℕ} {a : α} : ∀{v : vector α n}, (a :: v).val = a :: v.val | ⟨l, hl⟩ := rfl lemma tendsto_cons [topological_space α] {n : ℕ} {a : α} {l : vector α n}: tendsto (λp:α×vector α n, vector.cons p.1 p.2) ((nhds a).prod (nhds l)) (nhds (a :: l)) := by simp [tendsto_subtype_rng, cons_val]; exact tendsto_cons tendsto_fst (tendsto.comp continuous_at_subtype_val tendsto_snd) lemma tendsto_insert_nth [topological_space α] {n : ℕ} {i : fin (n+1)} {a:α} : ∀{l:vector α n}, tendsto (λp:α×vector α n, insert_nth p.1 i p.2) ((nhds a).prod (nhds l)) (nhds (insert_nth a i l)) | ⟨l, hl⟩ := begin rw [insert_nth, tendsto_subtype_rng], simp [insert_nth_val], exact list.tendsto_insert_nth tendsto_fst (tendsto.comp continuous_at_subtype_val tendsto_snd : _) end lemma continuous_insert_nth' [topological_space α] {n : ℕ} {i : fin (n+1)} : continuous (λp:α×vector α n, insert_nth p.1 i p.2) := continuous_iff_continuous_at.mpr $ assume ⟨a, l⟩, by rw [continuous_at, nhds_prod_eq]; exact tendsto_insert_nth lemma continuous_insert_nth [topological_space α] [topological_space β] {n : ℕ} {i : fin (n+1)} {f : β → α} {g : β → vector α n} (hf : continuous f) (hg : continuous g) : continuous (λb, insert_nth (f b) i (g b)) := continuous_insert_nth'.comp (continuous.prod_mk hf hg) lemma continuous_at_remove_nth [topological_space α] {n : ℕ} {i : fin (n+1)} : ∀{l:vector α (n+1)}, continuous_at (remove_nth i) l | ⟨l, hl⟩ := -- ∀{l:vector α (n+1)}, tendsto (remove_nth i) (nhds l) (nhds (remove_nth i l)) --| ⟨l, hl⟩ := begin rw [continuous_at, remove_nth, tendsto_subtype_rng], simp [remove_nth_val], exact tendsto.comp list.tendsto_remove_nth continuous_at_subtype_val end lemma continuous_remove_nth [topological_space α] {n : ℕ} {i : fin (n+1)} : continuous (remove_nth i : vector α (n+1) → vector α n) := continuous_iff_continuous_at.mpr $ assume ⟨a, l⟩, continuous_at_remove_nth end vector
e4900dc200d67fecc4def9f7eca858867b2d339b
7cef822f3b952965621309e88eadf618da0c8ae9
/src/data/fintype.lean
29e49a13b4e938d30f5780603336bb7f39599428
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
34,965
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Finite types. -/ import data.finset algebra.big_operators data.array.lemmas logic.unique import tactic.wlog universes u v variables {α : Type*} {β : Type*} {γ : Type*} /-- `fintype α` means that `α` is finite, i.e. there are only finitely many distinct elements of type `α`. The evidence of this is a finset `elems` (a list up to permutation without duplicates), together with a proof that everything of type `α` is in the list. -/ class fintype (α : Type*) := (elems : finset α) (complete : ∀ x : α, x ∈ elems) namespace finset variable [fintype α] /-- `univ` is the universal finite set of type `finset α` implied from the assumption `fintype α`. -/ def univ : finset α := fintype.elems α @[simp] theorem mem_univ (x : α) : x ∈ (univ : finset α) := fintype.complete x @[simp] theorem mem_univ_val : ∀ x, x ∈ (univ : finset α).1 := mem_univ @[simp] lemma coe_univ : ↑(univ : finset α) = (set.univ : set α) := by ext; simp theorem subset_univ (s : finset α) : s ⊆ univ := λ a _, mem_univ a theorem eq_univ_iff_forall {s : finset α} : s = univ ↔ ∀ x, x ∈ s := by simp [ext] end finset open finset function namespace fintype instance decidable_pi_fintype {α} {β : α → Type*} [fintype α] [∀a, decidable_eq (β a)] : decidable_eq (Πa, β a) := assume f g, decidable_of_iff (∀ a ∈ fintype.elems α, f a = g a) (by simp [function.funext_iff, fintype.complete]) instance decidable_forall_fintype [fintype α] {p : α → Prop} [decidable_pred p] : decidable (∀ a, p a) := decidable_of_iff (∀ a ∈ @univ α _, p a) (by simp) instance decidable_exists_fintype [fintype α] {p : α → Prop} [decidable_pred p] : decidable (∃ a, p a) := decidable_of_iff (∃ a ∈ @univ α _, p a) (by simp) instance decidable_eq_equiv_fintype [fintype α] [decidable_eq β] : decidable_eq (α ≃ β) := λ a b, decidable_of_iff (a.1 = b.1) ⟨λ h, equiv.ext _ _ (congr_fun h), congr_arg _⟩ instance decidable_injective_fintype [fintype α] [decidable_eq α] [decidable_eq β] : decidable_pred (injective : (α → β) → Prop) := λ x, by unfold injective; apply_instance instance decidable_surjective_fintype [fintype α] [fintype β] [decidable_eq β] : decidable_pred (surjective : (α → β) → Prop) := λ x, by unfold surjective; apply_instance instance decidable_bijective_fintype [fintype α] [decidable_eq α] [fintype β] [decidable_eq β] : decidable_pred (bijective : (α → β) → Prop) := λ x, by unfold bijective; apply_instance instance decidable_left_inverse_fintype [fintype α] [decidable_eq α] (f : α → β) (g : β → α) : decidable (function.right_inverse f g) := show decidable (∀ x, g (f x) = x), by apply_instance instance decidable_right_inverse_fintype [fintype β] [decidable_eq β] (f : α → β) (g : β → α) : decidable (function.left_inverse f g) := show decidable (∀ x, f (g x) = x), by apply_instance /-- Construct a proof of `fintype α` from a universal multiset -/ def of_multiset [decidable_eq α] (s : multiset α) (H : ∀ x : α, x ∈ s) : fintype α := ⟨s.to_finset, by simpa using H⟩ /-- Construct a proof of `fintype α` from a universal list -/ def of_list [decidable_eq α] (l : list α) (H : ∀ x : α, x ∈ l) : fintype α := ⟨l.to_finset, by simpa using H⟩ theorem exists_univ_list (α) [fintype α] : ∃ l : list α, l.nodup ∧ ∀ x : α, x ∈ l := let ⟨l, e⟩ := quotient.exists_rep (@univ α _).1 in by have := and.intro univ.2 mem_univ_val; exact ⟨_, by rwa ← e at this⟩ /-- `card α` is the number of elements in `α`, defined when `α` is a fintype. -/ def card (α) [fintype α] : ℕ := (@univ α _).card /-- There is (computably) a bijection between `α` and `fin n` where `n = card α`. Since it is not unique, and depends on which permutation of the universe list is used, the bijection is wrapped in `trunc` to preserve computability. -/ def equiv_fin (α) [fintype α] [decidable_eq α] : trunc (α ≃ fin (card α)) := by unfold card finset.card; exact quot.rec_on_subsingleton (@univ α _).1 (λ l (h : ∀ x:α, x ∈ l) (nd : l.nodup), trunc.mk ⟨λ a, ⟨_, list.index_of_lt_length.2 (h a)⟩, λ i, l.nth_le i.1 i.2, λ a, by simp, λ ⟨i, h⟩, fin.eq_of_veq $ list.nodup_iff_nth_le_inj.1 nd _ _ (list.index_of_lt_length.2 (list.nth_le_mem _ _ _)) h $ by simp⟩) mem_univ_val univ.2 theorem exists_equiv_fin (α) [fintype α] : ∃ n, nonempty (α ≃ fin n) := by haveI := classical.dec_eq α; exact ⟨card α, nonempty_of_trunc (equiv_fin α)⟩ instance (α : Type*) : subsingleton (fintype α) := ⟨λ ⟨s₁, h₁⟩ ⟨s₂, h₂⟩, by congr; simp [finset.ext, h₁, h₂]⟩ protected def subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : fintype {x // p x} := ⟨⟨multiset.pmap subtype.mk s.1 (λ x, (H x).1), multiset.nodup_pmap (λ a _ b _, congr_arg subtype.val) s.2⟩, λ ⟨x, px⟩, multiset.mem_pmap.2 ⟨x, (H x).2 px, rfl⟩⟩ theorem subtype_card {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : @card {x // p x} (fintype.subtype s H) = s.card := multiset.card_pmap _ _ _ theorem card_of_subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) [fintype {x // p x}] : card {x // p x} = s.card := by rw ← subtype_card s H; congr /-- Construct a fintype from a finset with the same elements. -/ def of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : fintype p := fintype.subtype s H @[simp] theorem card_of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : @fintype.card p (of_finset s H) = s.card := fintype.subtype_card s H theorem card_of_finset' {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) [fintype p] : fintype.card p = s.card := by rw ← card_of_finset s H; congr /-- If `f : α → β` is a bijection and `α` is a fintype, then `β` is also a fintype. -/ def of_bijective [fintype α] (f : α → β) (H : function.bijective f) : fintype β := ⟨univ.map ⟨f, H.1⟩, λ b, let ⟨a, e⟩ := H.2 b in e ▸ mem_map_of_mem _ (mem_univ _)⟩ /-- If `f : α → β` is a surjection and `α` is a fintype, then `β` is also a fintype. -/ def of_surjective [fintype α] [decidable_eq β] (f : α → β) (H : function.surjective f) : fintype β := ⟨univ.image f, λ b, let ⟨a, e⟩ := H b in e ▸ mem_image_of_mem _ (mem_univ _)⟩ noncomputable def of_injective [fintype β] (f : α → β) (H : function.injective f) : fintype α := by letI := classical.dec; exact if hα : nonempty α then by letI := classical.inhabited_of_nonempty hα; exact of_surjective (inv_fun f) (inv_fun_surjective H) else ⟨∅, λ x, (hα ⟨x⟩).elim⟩ /-- If `f : α ≃ β` and `α` is a fintype, then `β` is also a fintype. -/ def of_equiv (α : Type*) [fintype α] (f : α ≃ β) : fintype β := of_bijective _ f.bijective theorem of_equiv_card [fintype α] (f : α ≃ β) : @card β (of_equiv α f) = card α := multiset.card_map _ _ theorem card_congr {α β} [fintype α] [fintype β] (f : α ≃ β) : card α = card β := by rw ← of_equiv_card f; congr theorem card_eq {α β} [F : fintype α] [G : fintype β] : card α = card β ↔ nonempty (α ≃ β) := ⟨λ h, ⟨by classical; calc α ≃ fin (card α) : trunc.out (equiv_fin α) ... ≃ fin (card β) : by rw h ... ≃ β : (trunc.out (equiv_fin β)).symm⟩, λ ⟨f⟩, card_congr f⟩ def of_subsingleton (a : α) [subsingleton α] : fintype α := ⟨finset.singleton a, λ b, finset.mem_singleton.2 (subsingleton.elim _ _)⟩ @[simp] theorem univ_of_subsingleton (a : α) [subsingleton α] : @univ _ (of_subsingleton a) = finset.singleton a := rfl @[simp] theorem card_of_subsingleton (a : α) [subsingleton α] : @fintype.card _ (of_subsingleton a) = 1 := rfl lemma card_eq_sum_ones {α} [fintype α] : fintype.card α = (finset.univ : finset α).sum (λ _, 1) := finset.card_eq_sum_ones _ end fintype namespace set /-- Construct a finset enumerating a set `s`, given a `fintype` instance. -/ def to_finset (s : set α) [fintype s] : finset α := ⟨(@finset.univ s _).1.map subtype.val, multiset.nodup_map (λ a b, subtype.eq) finset.univ.2⟩ @[simp] theorem mem_to_finset {s : set α} [fintype s] {a : α} : a ∈ s.to_finset ↔ a ∈ s := by simp [to_finset] @[simp] theorem mem_to_finset_val {s : set α} [fintype s] {a : α} : a ∈ s.to_finset.1 ↔ a ∈ s := mem_to_finset end set lemma finset.card_univ [fintype α] : (finset.univ : finset α).card = fintype.card α := rfl lemma finset.card_univ_diff [fintype α] [decidable_eq α] (s : finset α) : (finset.univ \ s).card = fintype.card α - s.card := finset.card_sdiff (subset_univ s) instance (n : ℕ) : fintype (fin n) := ⟨⟨list.fin_range n, list.nodup_fin_range n⟩, list.mem_fin_range⟩ @[simp] theorem fintype.card_fin (n : ℕ) : fintype.card (fin n) = n := list.length_fin_range n @[instance, priority 10] def unique.fintype {α : Type*} [unique α] : fintype α := ⟨finset.singleton (default α), λ x, by rw [unique.eq_default x]; simp⟩ @[simp] lemma univ_unique {α : Type*} [unique α] [f : fintype α] : @finset.univ α _ = {default α} := by rw [subsingleton.elim f (@unique.fintype α _)]; refl instance : fintype empty := ⟨∅, empty.rec _⟩ @[simp] theorem fintype.univ_empty : @univ empty _ = ∅ := rfl @[simp] theorem fintype.card_empty : fintype.card empty = 0 := rfl instance : fintype pempty := ⟨∅, pempty.rec _⟩ @[simp] theorem fintype.univ_pempty : @univ pempty _ = ∅ := rfl @[simp] theorem fintype.card_pempty : fintype.card pempty = 0 := rfl instance : fintype unit := fintype.of_subsingleton () @[simp] theorem fintype.univ_unit : @univ unit _ = {()} := rfl @[simp] theorem fintype.card_unit : fintype.card unit = 1 := rfl instance : fintype punit := fintype.of_subsingleton punit.star @[simp] theorem fintype.univ_punit : @univ punit _ = {punit.star} := rfl @[simp] theorem fintype.card_punit : fintype.card punit = 1 := rfl instance : fintype bool := ⟨⟨tt::ff::0, by simp⟩, λ x, by cases x; simp⟩ @[simp] theorem fintype.univ_bool : @univ bool _ = {ff, tt} := rfl instance units_int.fintype : fintype (units ℤ) := ⟨{1, -1}, λ x, by cases int.units_eq_one_or x; simp *⟩ instance additive.fintype : Π [fintype α], fintype (additive α) := id instance multiplicative.fintype : Π [fintype α], fintype (multiplicative α) := id @[simp] theorem fintype.card_units_int : fintype.card (units ℤ) = 2 := rfl @[simp] theorem fintype.card_bool : fintype.card bool = 2 := rfl def finset.insert_none (s : finset α) : finset (option α) := ⟨none :: s.1.map some, multiset.nodup_cons.2 ⟨by simp, multiset.nodup_map (λ a b, option.some.inj) s.2⟩⟩ @[simp] theorem finset.mem_insert_none {s : finset α} : ∀ {o : option α}, o ∈ s.insert_none ↔ ∀ a ∈ o, a ∈ s | none := iff_of_true (multiset.mem_cons_self _ _) (λ a h, by cases h) | (some a) := multiset.mem_cons.trans $ by simp; refl theorem finset.some_mem_insert_none {s : finset α} {a : α} : some a ∈ s.insert_none ↔ a ∈ s := by simp instance {α : Type*} [fintype α] : fintype (option α) := ⟨univ.insert_none, λ a, by simp⟩ @[simp] theorem fintype.card_option {α : Type*} [fintype α] : fintype.card (option α) = fintype.card α + 1 := (multiset.card_cons _ _).trans (by rw multiset.card_map; refl) instance {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype (sigma β) := ⟨univ.sigma (λ _, univ), λ ⟨a, b⟩, by simp⟩ @[simp] theorem fintype.card_sigma {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype.card (sigma β) = univ.sum (λ a, fintype.card (β a)) := card_sigma _ _ instance (α β : Type*) [fintype α] [fintype β] : fintype (α × β) := ⟨univ.product univ, λ ⟨a, b⟩, by simp⟩ @[simp] theorem fintype.card_prod (α β : Type*) [fintype α] [fintype β] : fintype.card (α × β) = fintype.card α * fintype.card β := card_product _ _ def fintype.fintype_prod_left {α β} [decidable_eq α] [fintype (α × β)] [nonempty β] : fintype α := ⟨(fintype.elems (α × β)).image prod.fst, assume a, let ⟨b⟩ := ‹nonempty β› in by simp; exact ⟨b, fintype.complete _⟩⟩ def fintype.fintype_prod_right {α β} [decidable_eq β] [fintype (α × β)] [nonempty α] : fintype β := ⟨(fintype.elems (α × β)).image prod.snd, assume b, let ⟨a⟩ := ‹nonempty α› in by simp; exact ⟨a, fintype.complete _⟩⟩ instance (α : Type*) [fintype α] : fintype (ulift α) := fintype.of_equiv _ equiv.ulift.symm @[simp] theorem fintype.card_ulift (α : Type*) [fintype α] : fintype.card (ulift α) = fintype.card α := fintype.of_equiv_card _ instance (α : Type u) (β : Type v) [fintype α] [fintype β] : fintype (α ⊕ β) := @fintype.of_equiv _ _ (@sigma.fintype _ (λ b, cond b (ulift α) (ulift.{(max u v) v} β)) _ (λ b, by cases b; apply ulift.fintype)) ((equiv.sum_equiv_sigma_bool _ _).symm.trans (equiv.sum_congr equiv.ulift equiv.ulift)) @[simp] theorem fintype.card_sum (α β : Type*) [fintype α] [fintype β] : fintype.card (α ⊕ β) = fintype.card α + fintype.card β := by rw [sum.fintype, fintype.of_equiv_card]; simp lemma fintype.card_le_of_injective [fintype α] [fintype β] (f : α → β) (hf : function.injective f) : fintype.card α ≤ fintype.card β := by haveI := classical.prop_decidable; exact finset.card_le_card_of_inj_on f (λ _ _, finset.mem_univ _) (λ _ _ _ _ h, hf h) lemma fintype.card_eq_one_iff [fintype α] : fintype.card α = 1 ↔ (∃ x : α, ∀ y, y = x) := by rw [← fintype.card_unit, fintype.card_eq]; exact ⟨λ ⟨a⟩, ⟨a.symm (), λ y, a.injective (subsingleton.elim _ _)⟩, λ ⟨x, hx⟩, ⟨⟨λ _, (), λ _, x, λ _, (hx _).trans (hx _).symm, λ _, subsingleton.elim _ _⟩⟩⟩ lemma fintype.card_eq_zero_iff [fintype α] : fintype.card α = 0 ↔ (α → false) := ⟨λ h a, have e : α ≃ empty := classical.choice (fintype.card_eq.1 (by simp [h])), (e a).elim, λ h, have e : α ≃ empty := ⟨λ a, (h a).elim, λ a, a.elim, λ a, (h a).elim, λ a, a.elim⟩, by simp [fintype.card_congr e]⟩ lemma fintype.card_pos_iff [fintype α] : 0 < fintype.card α ↔ nonempty α := ⟨λ h, classical.by_contradiction (λ h₁, have fintype.card α = 0 := fintype.card_eq_zero_iff.2 (λ a, h₁ ⟨a⟩), lt_irrefl 0 $ by rwa this at h), λ ⟨a⟩, nat.pos_of_ne_zero (mt fintype.card_eq_zero_iff.1 (λ h, h a))⟩ lemma fintype.card_le_one_iff [fintype α] : fintype.card α ≤ 1 ↔ (∀ a b : α, a = b) := let n := fintype.card α in have hn : n = fintype.card α := rfl, match n, hn with | 0 := λ ha, ⟨λ h, λ a, (fintype.card_eq_zero_iff.1 ha.symm a).elim, λ _, ha ▸ nat.le_succ _⟩ | 1 := λ ha, ⟨λ h, λ a b, let ⟨x, hx⟩ := fintype.card_eq_one_iff.1 ha.symm in by rw [hx a, hx b], λ _, ha ▸ le_refl _⟩ | (n+2) := λ ha, ⟨λ h, by rw ← ha at h; exact absurd h dec_trivial, (λ h, fintype.card_unit ▸ fintype.card_le_of_injective (λ _, ()) (λ _ _ _, h _ _))⟩ end lemma fintype.exists_ne_of_one_lt_card [fintype α] (h : 1 < fintype.card α) (a : α) : ∃ b : α, b ≠ a := let ⟨b, hb⟩ := classical.not_forall.1 (mt fintype.card_le_one_iff.2 (not_le_of_gt h)) in let ⟨c, hc⟩ := classical.not_forall.1 hb in by haveI := classical.dec_eq α; exact if hba : b = a then ⟨c, by cc⟩ else ⟨b, hba⟩ lemma fintype.injective_iff_surjective [fintype α] {f : α → α} : injective f ↔ surjective f := by haveI := classical.prop_decidable; exact have ∀ {f : α → α}, injective f → surjective f, from λ f hinj x, have h₁ : image f univ = univ := eq_of_subset_of_card_le (subset_univ _) ((card_image_of_injective univ hinj).symm ▸ le_refl _), have h₂ : x ∈ image f univ := h₁.symm ▸ mem_univ _, exists_of_bex (mem_image.1 h₂), ⟨this, λ hsurj, injective_of_has_left_inverse ⟨surj_inv hsurj, left_inverse_of_surjective_of_right_inverse (this (injective_surj_inv _)) (right_inverse_surj_inv _)⟩⟩ lemma fintype.injective_iff_bijective [fintype α] {f : α → α} : injective f ↔ bijective f := by simp [bijective, fintype.injective_iff_surjective] lemma fintype.surjective_iff_bijective [fintype α] {f : α → α} : surjective f ↔ bijective f := by simp [bijective, fintype.injective_iff_surjective] lemma fintype.injective_iff_surjective_of_equiv [fintype α] {f : α → β} (e : α ≃ β) : injective f ↔ surjective f := have injective (e.symm ∘ f) ↔ surjective (e.symm ∘ f), from fintype.injective_iff_surjective, ⟨λ hinj, by simpa [function.comp] using surjective_comp e.surjective (this.1 (injective_comp e.symm.injective hinj)), λ hsurj, by simpa [function.comp] using injective_comp e.injective (this.2 (surjective_comp e.symm.surjective hsurj))⟩ instance list.subtype.fintype [decidable_eq α] (l : list α) : fintype {x // x ∈ l} := fintype.of_list l.attach l.mem_attach instance multiset.subtype.fintype [decidable_eq α] (s : multiset α) : fintype {x // x ∈ s} := fintype.of_multiset s.attach s.mem_attach instance finset.subtype.fintype (s : finset α) : fintype {x // x ∈ s} := ⟨s.attach, s.mem_attach⟩ instance finset_coe.fintype (s : finset α) : fintype (↑s : set α) := finset.subtype.fintype s @[simp] lemma fintype.card_coe (s : finset α) : fintype.card (↑s : set α) = s.card := card_attach instance plift.fintype (p : Prop) [decidable p] : fintype (plift p) := ⟨if h : p then finset.singleton ⟨h⟩ else ∅, λ ⟨h⟩, by simp [h]⟩ instance Prop.fintype : fintype Prop := ⟨⟨true::false::0, by simp [true_ne_false]⟩, classical.cases (by simp) (by simp)⟩ def set_fintype {α} [fintype α] (s : set α) [decidable_pred s] : fintype s := fintype.subtype (univ.filter (∈ s)) (by simp) instance pi.fintype {α : Type*} {β : α → Type*} [fintype α] [decidable_eq α] [∀a, fintype (β a)] : fintype (Πa, β a) := @fintype.of_equiv _ _ ⟨univ.pi $ λa:α, @univ (β a) _, λ f, finset.mem_pi.2 $ λ a ha, mem_univ _⟩ ⟨λ f a, f a (mem_univ _), λ f a _, f a, λ f, rfl, λ f, rfl⟩ @[simp] lemma fintype.card_pi {β : α → Type*} [fintype α] [decidable_eq α] [f : Π a, fintype (β a)] : fintype.card (Π a, β a) = univ.prod (λ a, fintype.card (β a)) := by letI f' : fintype (Πa∈univ, β a) := ⟨(univ.pi $ λa, univ), assume f, finset.mem_pi.2 $ assume a ha, mem_univ _⟩; exact calc fintype.card (Π a, β a) = fintype.card (Π a ∈ univ, β a) : fintype.card_congr ⟨λ f a ha, f a, λ f a, f a (mem_univ a), λ _, rfl, λ _, rfl⟩ ... = univ.prod (λ a, fintype.card (β a)) : finset.card_pi _ _ @[simp] lemma fintype.card_fun [fintype α] [decidable_eq α] [fintype β] : fintype.card (α → β) = fintype.card β ^ fintype.card α := by rw [fintype.card_pi, finset.prod_const, nat.pow_eq_pow]; refl instance d_array.fintype {n : ℕ} {α : fin n → Type*} [∀n, fintype (α n)] : fintype (d_array n α) := fintype.of_equiv _ (equiv.d_array_equiv_fin _).symm instance array.fintype {n : ℕ} {α : Type*} [fintype α] : fintype (array n α) := d_array.fintype instance vector.fintype {α : Type*} [fintype α] {n : ℕ} : fintype (vector α n) := fintype.of_equiv _ (equiv.vector_equiv_fin _ _).symm @[simp] lemma card_vector [fintype α] (n : ℕ) : fintype.card (vector α n) = fintype.card α ^ n := by rw fintype.of_equiv_card; simp instance quotient.fintype [fintype α] (s : setoid α) [decidable_rel ((≈) : α → α → Prop)] : fintype (quotient s) := fintype.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩)) instance finset.fintype [fintype α] : fintype (finset α) := ⟨univ.powerset, λ x, finset.mem_powerset.2 (finset.subset_univ _)⟩ instance subtype.fintype [fintype α] (p : α → Prop) [decidable_pred p] : fintype {x // p x} := set_fintype _ theorem fintype.card_subtype_le [fintype α] (p : α → Prop) [decidable_pred p] : fintype.card {x // p x} ≤ fintype.card α := by rw fintype.subtype_card; exact card_le_of_subset (subset_univ _) theorem fintype.card_subtype_lt [fintype α] {p : α → Prop} [decidable_pred p] {x : α} (hx : ¬ p x) : fintype.card {x // p x} < fintype.card α := by rw [fintype.subtype_card]; exact finset.card_lt_card ⟨subset_univ _, classical.not_forall.2 ⟨x, by simp [*, set.mem_def]⟩⟩ instance psigma.fintype {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] : fintype (Σ' a, β a) := fintype.of_equiv _ (equiv.psigma_equiv_sigma _).symm instance psigma.fintype_prop_left {α : Prop} {β : α → Type*} [∀ a, fintype (β a)] [decidable α] : fintype (Σ' a, β a) := if h : α then fintype.of_equiv (β h) ⟨λ x, ⟨h, x⟩, psigma.snd, λ _, rfl, λ ⟨_, _⟩, rfl⟩ else ⟨∅, λ x, h x.1⟩ instance psigma.fintype_prop_right {α : Type*} {β : α → Prop} [fintype α] [∀ a, decidable (β a)] : fintype (Σ' a, β a) := fintype.of_equiv {a // β a} ⟨λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, rfl, λ ⟨x, y⟩, rfl⟩ instance psigma.fintype_prop_prop {α : Prop} {β : α → Prop} [decidable α] [∀ a, decidable (β a)] : fintype (Σ' a, β a) := if h : ∃ a, β a then ⟨{⟨h.fst, h.snd⟩}, λ ⟨_, _⟩, by simp⟩ else ⟨∅, λ ⟨x, y⟩, h ⟨x, y⟩⟩ instance set.fintype [fintype α] [decidable_eq α] : fintype (set α) := pi.fintype instance pfun_fintype (p : Prop) [decidable p] (α : p → Type*) [Π hp, fintype (α hp)] : fintype (Π hp : p, α hp) := if hp : p then fintype.of_equiv (α hp) ⟨λ a _, a, λ f, f hp, λ _, rfl, λ _, rfl⟩ else ⟨singleton (λ h, (hp h).elim), by simp [hp, function.funext_iff]⟩ def quotient.fin_choice_aux {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι), (∀ i ∈ l, quotient (S i)) → @quotient (Π i ∈ l, α i) (by apply_instance) | [] f := ⟦λ i, false.elim⟧ | (i::l) f := begin refine quotient.lift_on₂ (f i (list.mem_cons_self _ _)) (quotient.fin_choice_aux l (λ j h, f j (list.mem_cons_of_mem _ h))) _ _, exact λ a l, ⟦λ j h, if e : j = i then by rw e; exact a else l _ (h.resolve_left e)⟧, refine λ a₁ l₁ a₂ l₂ h₁ h₂, quotient.sound (λ j h, _), by_cases e : j = i; simp [e], { subst j, exact h₁ }, { exact h₂ _ _ } end theorem quotient.fin_choice_aux_eq {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι) (f : ∀ i ∈ l, α i), quotient.fin_choice_aux l (λ i h, ⟦f i h⟧) = ⟦f⟧ | [] f := quotient.sound (λ i h, h.elim) | (i::l) f := begin simp [quotient.fin_choice_aux, quotient.fin_choice_aux_eq l], refine quotient.sound (λ j h, _), by_cases e : j = i; simp [e], subst j, refl end def quotient.fin_choice {ι : Type*} [fintype ι] [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] (f : ∀ i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) := quotient.lift_on (@quotient.rec_on _ _ (λ l : multiset ι, @quotient (Π i ∈ l, α i) (by apply_instance)) finset.univ.1 (λ l, quotient.fin_choice_aux l (λ i _, f i)) (λ a b h, begin have := λ a, quotient.fin_choice_aux_eq a (λ i h, quotient.out (f i)), simp [quotient.out_eq] at this, simp [this], let g := λ a:multiset ι, ⟦λ (i : ι) (h : i ∈ a), quotient.out (f i)⟧, refine eq_of_heq ((eq_rec_heq _ _).trans (_ : g a == g b)), congr' 1, exact quotient.sound h, end)) (λ f, ⟦λ i, f i (finset.mem_univ _)⟧) (λ a b h, quotient.sound $ λ i, h _ _) theorem quotient.fin_choice_eq {ι : Type*} [fintype ι] [decidable_eq ι] {α : ι → Type*} [∀ i, setoid (α i)] (f : ∀ i, α i) : quotient.fin_choice (λ i, ⟦f i⟧) = ⟦f⟧ := begin let q, swap, change quotient.lift_on q _ _ = _, have : q = ⟦λ i h, f i⟧, { dsimp [q], exact quotient.induction_on (@finset.univ ι _).1 (λ l, quotient.fin_choice_aux_eq _ _) }, simp [this], exact setoid.refl _ end @[simp, to_additive] lemma finset.prod_attach_univ [fintype α] [comm_monoid β] (f : {a : α // a ∈ @univ α _} → β) : univ.attach.prod (λ x, f x) = univ.prod (λ x, f ⟨x, (mem_univ _)⟩) := prod_bij (λ x _, x.1) (λ _ _, mem_univ _) (λ _ _ , by simp) (by simp) (λ b _, ⟨⟨b, mem_univ _⟩, by simp⟩) section equiv open list equiv equiv.perm variables [decidable_eq α] [decidable_eq β] def perms_of_list : list α → list (perm α) | [] := [1] | (a :: l) := perms_of_list l ++ l.bind (λ b, (perms_of_list l).map (λ f, swap a b * f)) lemma length_perms_of_list : ∀ l : list α, length (perms_of_list l) = l.length.fact | [] := rfl | (a :: l) := by rw [length_cons, nat.fact_succ]; simp [perms_of_list, length_bind, length_perms_of_list, function.comp, nat.succ_mul] lemma mem_perms_of_list_of_mem : ∀ {l : list α} {f : perm α} (h : ∀ x, f x ≠ x → x ∈ l), f ∈ perms_of_list l | [] f h := list.mem_singleton.2 $ equiv.ext _ _$ λ x, by simp [imp_false, *] at * | (a::l) f h := if hfa : f a = a then mem_append_left _ $ mem_perms_of_list_of_mem (λ x hx, mem_of_ne_of_mem (λ h, by rw h at hx; exact hx hfa) (h x hx)) else have hfa' : f (f a) ≠ f a, from mt (λ h, f.injective h) hfa, have ∀ (x : α), (swap a (f a) * f) x ≠ x → x ∈ l, from λ x hx, have hxa : x ≠ a, from λ h, by simpa [h, mul_apply] using hx, have hfxa : f x ≠ f a, from mt (λ h, f.injective h) hxa, list.mem_of_ne_of_mem hxa (h x (λ h, by simp [h, mul_apply, swap_apply_def] at hx; split_ifs at hx; cc)), suffices f ∈ perms_of_list l ∨ ∃ (b : α), b ∈ l ∧ ∃ g : perm α, g ∈ perms_of_list l ∧ swap a b * g = f, by simpa [perms_of_list], (@or_iff_not_imp_left _ _ (classical.prop_decidable _)).2 (λ hfl, ⟨f a, if hffa : f (f a) = a then mem_of_ne_of_mem hfa (h _ (mt (λ h, f.injective h) hfa)) else this _ $ by simp [mul_apply, swap_apply_def]; split_ifs; cc, ⟨swap a (f a) * f, mem_perms_of_list_of_mem this, by rw [← mul_assoc, mul_def (swap a (f a)) (swap a (f a)), swap_swap, ← equiv.perm.one_def, one_mul]⟩⟩) lemma mem_of_mem_perms_of_list : ∀ {l : list α} {f : perm α}, f ∈ perms_of_list l → ∀ {x}, f x ≠ x → x ∈ l | [] f h := have f = 1 := by simpa [perms_of_list] using h, by rw this; simp | (a::l) f h := (mem_append.1 h).elim (λ h x hx, mem_cons_of_mem _ (mem_of_mem_perms_of_list h hx)) (λ h x hx, let ⟨y, hy, hy'⟩ := list.mem_bind.1 h in let ⟨g, hg₁, hg₂⟩ := list.mem_map.1 hy' in if hxa : x = a then by simp [hxa] else if hxy : x = y then mem_cons_of_mem _ $ by rwa hxy else mem_cons_of_mem _ $ mem_of_mem_perms_of_list hg₁ $ by rw [eq_inv_mul_iff_mul_eq.2 hg₂, mul_apply, swap_inv, swap_apply_def]; split_ifs; cc) lemma mem_perms_of_list_iff {l : list α} {f : perm α} : f ∈ perms_of_list l ↔ ∀ {x}, f x ≠ x → x ∈ l := ⟨mem_of_mem_perms_of_list, mem_perms_of_list_of_mem⟩ lemma nodup_perms_of_list : ∀ {l : list α} (hl : l.nodup), (perms_of_list l).nodup | [] hl := by simp [perms_of_list] | (a::l) hl := have hl' : l.nodup, from nodup_of_nodup_cons hl, have hln' : (perms_of_list l).nodup, from nodup_perms_of_list hl', have hmeml : ∀ {f : perm α}, f ∈ perms_of_list l → f a = a, from λ f hf, not_not.1 (mt (mem_of_mem_perms_of_list hf) (nodup_cons.1 hl).1), by rw [perms_of_list, list.nodup_append, list.nodup_bind, pairwise_iff_nth_le]; exact ⟨hln', ⟨λ _ _, nodup_map (λ _ _, (mul_left_inj _).1) hln', λ i j hj hij x hx₁ hx₂, let ⟨f, hf⟩ := list.mem_map.1 hx₁ in let ⟨g, hg⟩ := list.mem_map.1 hx₂ in have hix : x a = nth_le l i (lt_trans hij hj), by rw [← hf.2, mul_apply, hmeml hf.1, swap_apply_left], have hiy : x a = nth_le l j hj, by rw [← hg.2, mul_apply, hmeml hg.1, swap_apply_left], absurd (hf.2.trans (hg.2.symm)) $ λ h, ne_of_lt hij $ nodup_iff_nth_le_inj.1 hl' i j (lt_trans hij hj) hj $ by rw [← hix, hiy]⟩, λ f hf₁ hf₂, let ⟨x, hx, hx'⟩ := list.mem_bind.1 hf₂ in let ⟨g, hg⟩ := list.mem_map.1 hx' in have hgxa : g⁻¹ x = a, from f.injective $ by rw [hmeml hf₁, ← hg.2]; simp, have hxa : x ≠ a, from λ h, (list.nodup_cons.1 hl).1 (h ▸ hx), (list.nodup_cons.1 hl).1 $ hgxa ▸ mem_of_mem_perms_of_list hg.1 (by rwa [apply_inv_self, hgxa])⟩ def perms_of_finset (s : finset α) : finset (perm α) := quotient.hrec_on s.1 (λ l hl, ⟨perms_of_list l, nodup_perms_of_list hl⟩) (λ a b hab, hfunext (congr_arg _ (quotient.sound hab)) (λ ha hb _, heq_of_eq $ finset.ext.2 $ by simp [mem_perms_of_list_iff,mem_of_perm hab])) s.2 lemma mem_perms_of_finset_iff : ∀ {s : finset α} {f : perm α}, f ∈ perms_of_finset s ↔ ∀ {x}, f x ≠ x → x ∈ s := by rintros ⟨⟨l⟩, hs⟩ f; exact mem_perms_of_list_iff lemma card_perms_of_finset : ∀ (s : finset α), (perms_of_finset s).card = s.card.fact := by rintros ⟨⟨l⟩, hs⟩; exact length_perms_of_list l def fintype_perm [fintype α] : fintype (perm α) := ⟨perms_of_finset (@finset.univ α _), by simp [mem_perms_of_finset_iff]⟩ instance [fintype α] [fintype β] : fintype (α ≃ β) := if h : fintype.card β = fintype.card α then trunc.rec_on_subsingleton (fintype.equiv_fin α) (λ eα, trunc.rec_on_subsingleton (fintype.equiv_fin β) (λ eβ, @fintype.of_equiv _ (perm α) fintype_perm (equiv_congr (equiv.refl α) (eα.trans (eq.rec_on h eβ.symm)) : (α ≃ α) ≃ (α ≃ β)))) else ⟨∅, λ x, false.elim (h (fintype.card_eq.2 ⟨x.symm⟩))⟩ lemma fintype.card_perm [fintype α] : fintype.card (perm α) = (fintype.card α).fact := subsingleton.elim (@fintype_perm α _ _) (@equiv.fintype α α _ _ _ _) ▸ card_perms_of_finset _ lemma fintype.card_equiv [fintype α] [fintype β] (e : α ≃ β) : fintype.card (α ≃ β) = (fintype.card α).fact := fintype.card_congr (equiv_congr (equiv.refl α) e) ▸ fintype.card_perm end equiv namespace fintype section choose open fintype open equiv variables [fintype α] [decidable_eq α] (p : α → Prop) [decidable_pred p] def choose_x (hp : ∃! a : α, p a) : {a // p a} := ⟨finset.choose p univ (by simp; exact hp), finset.choose_property _ _ _⟩ def choose (hp : ∃! a, p a) : α := choose_x p hp lemma choose_spec (hp : ∃! a, p a) : p (choose p hp) := (choose_x p hp).property end choose section bijection_inverse open function variables [fintype α] [decidable_eq α] variables [fintype β] [decidable_eq β] variables {f : α → β} /-- ` `bij_inv f` is the unique inverse to a bijection `f`. This acts as a computable alternative to `function.inv_fun`. -/ def bij_inv (f_bij : bijective f) (b : β) : α := fintype.choose (λ a, f a = b) begin rcases f_bij.right b with ⟨a', fa_eq_b⟩, rw ← fa_eq_b, exact ⟨a', ⟨rfl, (λ a h, f_bij.left h)⟩⟩ end lemma left_inverse_bij_inv (f_bij : bijective f) : left_inverse (bij_inv f_bij) f := λ a, f_bij.left (choose_spec (λ a', f a' = f a) _) lemma right_inverse_bij_inv (f_bij : bijective f) : right_inverse (bij_inv f_bij) f := λ b, choose_spec (λ a', f a' = b) _ lemma bijective_bij_inv (f_bij : bijective f) : bijective (bij_inv f_bij) := ⟨injective_of_left_inverse (right_inverse_bij_inv _), surjective_of_has_right_inverse ⟨f, left_inverse_bij_inv _⟩⟩ end bijection_inverse lemma well_founded_of_trans_of_irrefl [fintype α] (r : α → α → Prop) [is_trans α r] [is_irrefl α r] : well_founded r := by classical; exact have ∀ x y, r x y → (univ.filter (λ z, r z x)).card < (univ.filter (λ z, r z y)).card, from λ x y hxy, finset.card_lt_card $ by simp only [finset.lt_iff_ssubset.symm, lt_iff_le_not_le, finset.le_iff_subset, finset.subset_iff, mem_filter, true_and, mem_univ, hxy]; exact ⟨λ z hzx, trans hzx hxy, not_forall_of_exists_not ⟨x, not_imp.2 ⟨hxy, irrefl x⟩⟩⟩, subrelation.wf this (measure_wf _) lemma preorder.well_founded [fintype α] [preorder α] : well_founded ((<) : α → α → Prop) := well_founded_of_trans_of_irrefl _ @[instance, priority 10] lemma linear_order.is_well_order [fintype α] [linear_order α] : is_well_order α (<) := { wf := preorder.well_founded } end fintype class infinite (α : Type*) : Prop := (not_fintype : fintype α → false) @[simp] lemma not_nonempty_fintype {α : Type*} : ¬nonempty (fintype α) ↔ infinite α := ⟨λf, ⟨λ x, f ⟨x⟩⟩, λ⟨f⟩ ⟨x⟩, f x⟩ namespace infinite lemma exists_not_mem_finset [infinite α] (s : finset α) : ∃ x, x ∉ s := classical.not_forall.1 $ λ h, not_fintype ⟨s, h⟩ @[priority 100] -- see Note [lower instance priority] instance nonempty (α : Type*) [infinite α] : nonempty α := nonempty_of_exists (exists_not_mem_finset (∅ : finset α)) lemma of_injective [infinite β] (f : β → α) (hf : injective f) : infinite α := ⟨λ I, by exactI not_fintype (fintype.of_injective f hf)⟩ lemma of_surjective [infinite β] (f : α → β) (hf : surjective f) : infinite α := ⟨λ I, by classical; exactI not_fintype (fintype.of_surjective f hf)⟩ private noncomputable def nat_embedding_aux (α : Type*) [infinite α] : ℕ → α | n := by letI := classical.dec_eq α; exact classical.some (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux m) (λ _, multiset.mem_range.1)).to_finset) private lemma nat_embedding_aux_injective (α : Type*) [infinite α] : function.injective (nat_embedding_aux α) := begin assume m n h, letI := classical.dec_eq α, wlog hmlen : m ≤ n using m n, by_contradiction hmn, have hmn : m < n, from lt_of_le_of_ne hmlen hmn, refine (classical.some_spec (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux α m) (λ _, multiset.mem_range.1)).to_finset)) _, refine multiset.mem_to_finset.2 (multiset.mem_pmap.2 ⟨m, multiset.mem_range.2 hmn, _⟩), rw [h, nat_embedding_aux] end noncomputable def nat_embedding (α : Type*) [infinite α] : ℕ ↪ α := ⟨_, nat_embedding_aux_injective α⟩ end infinite instance nat.infinite : infinite ℕ := ⟨λ ⟨s, hs⟩, not_le_of_gt (nat.lt_succ_self (s.sum id)) $ @finset.single_le_sum _ _ _ id _ _ (λ _ _, nat.zero_le _) _ (hs _)⟩ instance int.infinite : infinite ℤ := infinite.of_injective int.of_nat (λ _ _, int.of_nat_inj)
85820fce196fe21cd824645ea7a2ba1449a5d31c
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/affine_space/finite_dimensional.lean
07ff73f8731ca53fa41014fc4f7b6802fe67596f
[ "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
33,795
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import linear_algebra.affine_space.basis import linear_algebra.finite_dimensional /-! # Finite-dimensional subspaces of affine spaces. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file provides a few results relating to finite-dimensional subspaces of affine spaces. ## Main definitions * `collinear` defines collinear sets of points as those that span a subspace of dimension at most 1. -/ noncomputable theory open_locale big_operators affine section affine_space' variables (k : Type*) {V : Type*} {P : Type*} variables {ι : Type*} include V open affine_subspace finite_dimensional module variables [division_ring k] [add_comm_group V] [module k V] [affine_space V P] /-- The `vector_span` of a finite set is finite-dimensional. -/ lemma finite_dimensional_vector_span_of_finite {s : set P} (h : set.finite s) : finite_dimensional k (vector_span k s) := span_of_finite k $ h.vsub h /-- The `vector_span` of a family indexed by a `fintype` is finite-dimensional. -/ instance finite_dimensional_vector_span_range [_root_.finite ι] (p : ι → P) : finite_dimensional k (vector_span k (set.range p)) := finite_dimensional_vector_span_of_finite k (set.finite_range _) /-- The `vector_span` of a subset of a family indexed by a `fintype` is finite-dimensional. -/ instance finite_dimensional_vector_span_image_of_finite [_root_.finite ι] (p : ι → P) (s : set ι) : finite_dimensional k (vector_span k (p '' s)) := finite_dimensional_vector_span_of_finite k (set.to_finite _) /-- The direction of the affine span of a finite set is finite-dimensional. -/ lemma finite_dimensional_direction_affine_span_of_finite {s : set P} (h : set.finite s) : finite_dimensional k (affine_span k s).direction := (direction_affine_span k s).symm ▸ finite_dimensional_vector_span_of_finite k h /-- The direction of the affine span of a family indexed by a `fintype` is finite-dimensional. -/ instance finite_dimensional_direction_affine_span_range [_root_.finite ι] (p : ι → P) : finite_dimensional k (affine_span k (set.range p)).direction := finite_dimensional_direction_affine_span_of_finite k (set.finite_range _) /-- The direction of the affine span of a subset of a family indexed by a `fintype` is finite-dimensional. -/ instance finite_dimensional_direction_affine_span_image_of_finite [_root_.finite ι] (p : ι → P) (s : set ι) : finite_dimensional k (affine_span k (p '' s)).direction := finite_dimensional_direction_affine_span_of_finite k (set.to_finite _) /-- An affine-independent family of points in a finite-dimensional affine space is finite. -/ lemma finite_of_fin_dim_affine_independent [finite_dimensional k V] {p : ι → P} (hi : affine_independent k p) : _root_.finite ι := begin nontriviality ι, inhabit ι, rw affine_independent_iff_linear_independent_vsub k p default at hi, letI : is_noetherian k V := is_noetherian.iff_fg.2 infer_instance, exact (set.finite_singleton default).finite_of_compl (set.finite_coe_iff.1 hi.finite_of_is_noetherian) end /-- An affine-independent subset of a finite-dimensional affine space is finite. -/ lemma finite_set_of_fin_dim_affine_independent [finite_dimensional k V] {s : set ι} {f : s → P} (hi : affine_independent k f) : s.finite := @set.to_finite _ s (finite_of_fin_dim_affine_independent k hi) open_locale classical variables {k} /-- The `vector_span` of a finite subset of an affinely independent family has dimension one less than its cardinality. -/ lemma affine_independent.finrank_vector_span_image_finset {p : ι → P} (hi : affine_independent k p) {s : finset ι} {n : ℕ} (hc : finset.card s = n + 1) : finrank k (vector_span k (s.image p : set P)) = n := begin have hi' := hi.range.mono (set.image_subset_range p ↑s), have hc' : (s.image p).card = n + 1, { rwa s.card_image_of_injective hi.injective }, have hn : (s.image p).nonempty, { simp [hc', ←finset.card_pos] }, rcases hn with ⟨p₁, hp₁⟩, have hp₁' : p₁ ∈ p '' s := by simpa using hp₁, rw [affine_independent_set_iff_linear_independent_vsub k hp₁', ← finset.coe_singleton, ← finset.coe_image, ← finset.coe_sdiff, finset.sdiff_singleton_eq_erase, ← finset.coe_image] at hi', have hc : (finset.image (λ (p : P), p -ᵥ p₁) ((finset.image p s).erase p₁)).card = n, { rw [finset.card_image_of_injective _ (vsub_left_injective _), finset.card_erase_of_mem hp₁], exact nat.pred_eq_of_eq_succ hc' }, rwa [vector_span_eq_span_vsub_finset_right_ne k hp₁, finrank_span_finset_eq_card, hc] end /-- The `vector_span` of a finite affinely independent family has dimension one less than its cardinality. -/ lemma affine_independent.finrank_vector_span [fintype ι] {p : ι → P} (hi : affine_independent k p) {n : ℕ} (hc : fintype.card ι = n + 1) : finrank k (vector_span k (set.range p)) = n := begin rw ← finset.card_univ at hc, rw [← set.image_univ, ← finset.coe_univ, ← finset.coe_image], exact hi.finrank_vector_span_image_finset hc end /-- The `vector_span` of a finite affinely independent family whose cardinality is one more than that of the finite-dimensional space is `⊤`. -/ lemma affine_independent.vector_span_eq_top_of_card_eq_finrank_add_one [finite_dimensional k V] [fintype ι] {p : ι → P} (hi : affine_independent k p) (hc : fintype.card ι = finrank k V + 1) : vector_span k (set.range p) = ⊤ := eq_top_of_finrank_eq $ hi.finrank_vector_span hc variables (k) /-- The `vector_span` of `n + 1` points in an indexed family has dimension at most `n`. -/ lemma finrank_vector_span_image_finset_le (p : ι → P) (s : finset ι) {n : ℕ} (hc : finset.card s = n + 1) : finrank k (vector_span k (s.image p : set P)) ≤ n := begin have hn : (s.image p).nonempty, { rw [finset.nonempty.image_iff, ← finset.card_pos, hc], apply nat.succ_pos }, rcases hn with ⟨p₁, hp₁⟩, rw [vector_span_eq_span_vsub_finset_right_ne k hp₁], refine le_trans (finrank_span_finset_le_card (((s.image p).erase p₁).image (λ p, p -ᵥ p₁))) _, rw [finset.card_image_of_injective _ (vsub_left_injective p₁), finset.card_erase_of_mem hp₁, tsub_le_iff_right, ← hc], apply finset.card_image_le end /-- The `vector_span` of an indexed family of `n + 1` points has dimension at most `n`. -/ lemma finrank_vector_span_range_le [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 1) : finrank k (vector_span k (set.range p)) ≤ n := begin rw [←set.image_univ, ←finset.coe_univ, ← finset.coe_image], rw ←finset.card_univ at hc, exact finrank_vector_span_image_finset_le _ _ _ hc end /-- `n + 1` points are affinely independent if and only if their `vector_span` has dimension `n`. -/ lemma affine_independent_iff_finrank_vector_span_eq [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 1) : affine_independent k p ↔ finrank k (vector_span k (set.range p)) = n := begin have hn : nonempty ι, by simp [←fintype.card_pos_iff, hc], cases hn with i₁, rw [affine_independent_iff_linear_independent_vsub _ _ i₁, linear_independent_iff_card_eq_finrank_span, eq_comm, vector_span_range_eq_span_range_vsub_right_ne k p i₁], congr', rw ←finset.card_univ at hc, rw fintype.subtype_card, simp [finset.filter_ne', finset.card_erase_of_mem, hc] end /-- `n + 1` points are affinely independent if and only if their `vector_span` has dimension at least `n`. -/ lemma affine_independent_iff_le_finrank_vector_span [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 1) : affine_independent k p ↔ n ≤ finrank k (vector_span k (set.range p)) := begin rw affine_independent_iff_finrank_vector_span_eq k p hc, split, { rintro rfl, refl }, { exact λ hle, le_antisymm (finrank_vector_span_range_le k p hc) hle } end /-- `n + 2` points are affinely independent if and only if their `vector_span` does not have dimension at most `n`. -/ lemma affine_independent_iff_not_finrank_vector_span_le [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 2) : affine_independent k p ↔ ¬ finrank k (vector_span k (set.range p)) ≤ n := by rw [affine_independent_iff_le_finrank_vector_span k p hc, ←nat.lt_iff_add_one_le, lt_iff_not_ge] /-- `n + 2` points have a `vector_span` with dimension at most `n` if and only if they are not affinely independent. -/ lemma finrank_vector_span_le_iff_not_affine_independent [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 2) : finrank k (vector_span k (set.range p)) ≤ n ↔ ¬ affine_independent k p := (not_iff_comm.1 (affine_independent_iff_not_finrank_vector_span_le k p hc).symm).symm variables {k} /-- If the `vector_span` of a finite subset of an affinely independent family lies in a submodule with dimension one less than its cardinality, it equals that submodule. -/ lemma affine_independent.vector_span_image_finset_eq_of_le_of_card_eq_finrank_add_one {p : ι → P} (hi : affine_independent k p) {s : finset ι} {sm : submodule k V} [finite_dimensional k sm] (hle : vector_span k (s.image p : set P) ≤ sm) (hc : finset.card s = finrank k sm + 1) : vector_span k (s.image p : set P) = sm := eq_of_le_of_finrank_eq hle $ hi.finrank_vector_span_image_finset hc /-- If the `vector_span` of a finite affinely independent family lies in a submodule with dimension one less than its cardinality, it equals that submodule. -/ lemma affine_independent.vector_span_eq_of_le_of_card_eq_finrank_add_one [fintype ι] {p : ι → P} (hi : affine_independent k p) {sm : submodule k V} [finite_dimensional k sm] (hle : vector_span k (set.range p) ≤ sm) (hc : fintype.card ι = finrank k sm + 1) : vector_span k (set.range p) = sm := eq_of_le_of_finrank_eq hle $ hi.finrank_vector_span hc /-- If the `affine_span` of a finite subset of an affinely independent family lies in an affine subspace whose direction has dimension one less than its cardinality, it equals that subspace. -/ lemma affine_independent.affine_span_image_finset_eq_of_le_of_card_eq_finrank_add_one {p : ι → P} (hi : affine_independent k p) {s : finset ι} {sp : affine_subspace k P} [finite_dimensional k sp.direction] (hle : affine_span k (s.image p : set P) ≤ sp) (hc : finset.card s = finrank k sp.direction + 1) : affine_span k (s.image p : set P) = sp := begin have hn : s.nonempty, { rw [←finset.card_pos, hc], apply nat.succ_pos }, refine eq_of_direction_eq_of_nonempty_of_le _ ((hn.image _).to_set.affine_span _)hle, have hd := direction_le hle, rw direction_affine_span at ⊢ hd, exact hi.vector_span_image_finset_eq_of_le_of_card_eq_finrank_add_one hd hc end /-- If the `affine_span` of a finite affinely independent family lies in an affine subspace whose direction has dimension one less than its cardinality, it equals that subspace. -/ lemma affine_independent.affine_span_eq_of_le_of_card_eq_finrank_add_one [fintype ι] {p : ι → P} (hi : affine_independent k p) {sp : affine_subspace k P} [finite_dimensional k sp.direction] (hle : affine_span k (set.range p) ≤ sp) (hc : fintype.card ι = finrank k sp.direction + 1) : affine_span k (set.range p) = sp := begin rw ←finset.card_univ at hc, rw [←set.image_univ, ←finset.coe_univ, ← finset.coe_image] at ⊢ hle, exact hi.affine_span_image_finset_eq_of_le_of_card_eq_finrank_add_one hle hc end /-- The `affine_span` of a finite affinely independent family is `⊤` iff the family's cardinality is one more than that of the finite-dimensional space. -/ lemma affine_independent.affine_span_eq_top_iff_card_eq_finrank_add_one [finite_dimensional k V] [fintype ι] {p : ι → P} (hi : affine_independent k p) : affine_span k (set.range p) = ⊤ ↔ fintype.card ι = finrank k V + 1 := begin split, { intros h_tot, let n := fintype.card ι - 1, have hn : fintype.card ι = n + 1, { exact (nat.succ_pred_eq_of_pos (card_pos_of_affine_span_eq_top k V P h_tot)).symm, }, rw [hn, ← finrank_top, ← (vector_span_eq_top_of_affine_span_eq_top k V P) h_tot, ← hi.finrank_vector_span hn], }, { intros hc, rw [← finrank_top, ← direction_top k V P] at hc, exact hi.affine_span_eq_of_le_of_card_eq_finrank_add_one le_top hc, }, end lemma affine.simplex.span_eq_top [finite_dimensional k V] {n : ℕ} (T : affine.simplex k V n) (hrank : finrank k V = n) : affine_span k (set.range T.points) = ⊤ := by rw [affine_independent.affine_span_eq_top_iff_card_eq_finrank_add_one T.independent, fintype.card_fin, hrank] /-- The `vector_span` of adding a point to a finite-dimensional subspace is finite-dimensional. -/ instance finite_dimensional_vector_span_insert (s : affine_subspace k P) [finite_dimensional k s.direction] (p : P) : finite_dimensional k (vector_span k (insert p (s : set P))) := begin rw [←direction_affine_span, ←affine_span_insert_affine_span], rcases (s : set P).eq_empty_or_nonempty with hs | ⟨p₀, hp₀⟩, { rw coe_eq_bot_iff at hs, rw [hs, bot_coe, span_empty, bot_coe, direction_affine_span], convert finite_dimensional_bot _ _; simp }, { rw [affine_span_coe, direction_affine_span_insert hp₀], apply_instance } end /-- The direction of the affine span of adding a point to a finite-dimensional subspace is finite-dimensional. -/ instance finite_dimensional_direction_affine_span_insert (s : affine_subspace k P) [finite_dimensional k s.direction] (p : P) : finite_dimensional k (affine_span k (insert p (s : set P))).direction := (direction_affine_span k (insert p (s : set P))).symm ▸ finite_dimensional_vector_span_insert s p variables (k) /-- The `vector_span` of adding a point to a set with a finite-dimensional `vector_span` is finite-dimensional. -/ instance finite_dimensional_vector_span_insert_set (s : set P) [finite_dimensional k (vector_span k s)] (p : P) : finite_dimensional k (vector_span k (insert p s)) := begin haveI : finite_dimensional k (affine_span k s).direction := (direction_affine_span k s).symm ▸ infer_instance, rw [←direction_affine_span, ←affine_span_insert_affine_span, direction_affine_span], exact finite_dimensional_vector_span_insert (affine_span k s) p end /-- A set of points is collinear if their `vector_span` has dimension at most `1`. -/ def collinear (s : set P) : Prop := module.rank k (vector_span k s) ≤ 1 /-- The definition of `collinear`. -/ lemma collinear_iff_rank_le_one (s : set P) : collinear k s ↔ module.rank k (vector_span k s) ≤ 1 := iff.rfl variables {k} /-- A set of points, whose `vector_span` is finite-dimensional, is collinear if and only if their `vector_span` has dimension at most `1`. -/ lemma collinear_iff_finrank_le_one {s : set P} [finite_dimensional k (vector_span k s)] : collinear k s ↔ finrank k (vector_span k s) ≤ 1 := begin have h := collinear_iff_rank_le_one k s, rw ←finrank_eq_rank at h, exact_mod_cast h end alias collinear_iff_finrank_le_one ↔ collinear.finrank_le_one _ /-- A subset of a collinear set is collinear. -/ lemma collinear.subset {s₁ s₂ : set P} (hs : s₁ ⊆ s₂) (h : collinear k s₂) : collinear k s₁ := (rank_le_of_submodule (vector_span k s₁) (vector_span k s₂) (vector_span_mono k hs)).trans h /-- The `vector_span` of collinear points is finite-dimensional. -/ lemma collinear.finite_dimensional_vector_span {s : set P} (h : collinear k s) : finite_dimensional k (vector_span k s) := is_noetherian.iff_fg.1 (is_noetherian.iff_rank_lt_aleph_0.2 (lt_of_le_of_lt h cardinal.one_lt_aleph_0)) /-- The direction of the affine span of collinear points is finite-dimensional. -/ lemma collinear.finite_dimensional_direction_affine_span {s : set P} (h : collinear k s) : finite_dimensional k (affine_span k s).direction := (direction_affine_span k s).symm ▸ h.finite_dimensional_vector_span variables (k P) /-- The empty set is collinear. -/ lemma collinear_empty : collinear k (∅ : set P) := begin rw [collinear_iff_rank_le_one, vector_span_empty], simp end variables {P} /-- A single point is collinear. -/ lemma collinear_singleton (p : P) : collinear k ({p} : set P) := begin rw [collinear_iff_rank_le_one, vector_span_singleton], simp end variables {k} /-- Given a point `p₀` in a set of points, that set is collinear if and only if the points can all be expressed as multiples of the same vector, added to `p₀`. -/ lemma collinear_iff_of_mem {s : set P} {p₀ : P} (h : p₀ ∈ s) : collinear k s ↔ ∃ v : V, ∀ p ∈ s, ∃ r : k, p = r • v +ᵥ p₀ := begin simp_rw [collinear_iff_rank_le_one, rank_submodule_le_one_iff', submodule.le_span_singleton_iff], split, { rintro ⟨v₀, hv⟩, use v₀, intros p hp, obtain ⟨r, hr⟩ := hv (p -ᵥ p₀) (vsub_mem_vector_span k hp h), use r, rw eq_vadd_iff_vsub_eq, exact hr.symm }, { rintro ⟨v, hp₀v⟩, use v, intros w hw, have hs : vector_span k s ≤ k ∙ v, { rw [vector_span_eq_span_vsub_set_right k h, submodule.span_le, set.subset_def], intros x hx, rw [set_like.mem_coe, submodule.mem_span_singleton], rw set.mem_image at hx, rcases hx with ⟨p, hp, rfl⟩, rcases hp₀v p hp with ⟨r, rfl⟩, use r, simp }, have hw' := set_like.le_def.1 hs hw, rwa submodule.mem_span_singleton at hw' } end /-- A set of points is collinear if and only if they can all be expressed as multiples of the same vector, added to the same base point. -/ lemma collinear_iff_exists_forall_eq_smul_vadd (s : set P) : collinear k s ↔ ∃ (p₀ : P) (v : V), ∀ p ∈ s, ∃ r : k, p = r • v +ᵥ p₀ := begin rcases set.eq_empty_or_nonempty s with rfl | ⟨⟨p₁, hp₁⟩⟩, { simp [collinear_empty] }, { rw collinear_iff_of_mem hp₁, split, { exact λ h, ⟨p₁, h⟩ }, { rintros ⟨p, v, hv⟩, use v, intros p₂ hp₂, rcases hv p₂ hp₂ with ⟨r, rfl⟩, rcases hv p₁ hp₁ with ⟨r₁, rfl⟩, use r - r₁, simp [vadd_vadd, ←add_smul] } } end variables (k) /-- Two points are collinear. -/ lemma collinear_pair (p₁ p₂ : P) : collinear k ({p₁, p₂} : set P) := begin rw collinear_iff_exists_forall_eq_smul_vadd, use [p₁, p₂ -ᵥ p₁], intros p hp, rw [set.mem_insert_iff, set.mem_singleton_iff] at hp, cases hp, { use 0, simp [hp] }, { use 1, simp [hp] } end variables {k} /-- Three points are affinely independent if and only if they are not collinear. -/ lemma affine_independent_iff_not_collinear {p : fin 3 → P} : affine_independent k p ↔ ¬ collinear k (set.range p) := by rw [collinear_iff_finrank_le_one, affine_independent_iff_not_finrank_vector_span_le k p (fintype.card_fin 3)] /-- Three points are collinear if and only if they are not affinely independent. -/ lemma collinear_iff_not_affine_independent {p : fin 3 → P} : collinear k (set.range p) ↔ ¬ affine_independent k p := by rw [collinear_iff_finrank_le_one, finrank_vector_span_le_iff_not_affine_independent k p (fintype.card_fin 3)] /-- Three points are affinely independent if and only if they are not collinear. -/ lemma affine_independent_iff_not_collinear_set {p₁ p₂ p₃ : P} : affine_independent k ![p₁, p₂, p₃] ↔ ¬collinear k ({p₁, p₂, p₃} : set P) := by simp [affine_independent_iff_not_collinear, -set.union_singleton] /-- Three points are collinear if and only if they are not affinely independent. -/ lemma collinear_iff_not_affine_independent_set {p₁ p₂ p₃ : P} : collinear k ({p₁, p₂, p₃} : set P) ↔ ¬affine_independent k ![p₁, p₂, p₃] := affine_independent_iff_not_collinear_set.not_left.symm /-- Three points are affinely independent if and only if they are not collinear. -/ lemma affine_independent_iff_not_collinear_of_ne {p : fin 3 → P} {i₁ i₂ i₃ : fin 3} (h₁₂ : i₁ ≠ i₂) (h₁₃ : i₁ ≠ i₃) (h₂₃ : i₂ ≠ i₃) : affine_independent k p ↔ ¬collinear k ({p i₁, p i₂, p i₃} : set P) := begin have hu : (finset.univ : finset (fin 3)) = {i₁, i₂, i₃}, by dec_trivial!, rw [affine_independent_iff_not_collinear, ←set.image_univ, ←finset.coe_univ, hu, finset.coe_insert, finset.coe_insert, finset.coe_singleton, set.image_insert_eq, set.image_pair] end /-- Three points are collinear if and only if they are not affinely independent. -/ lemma collinear_iff_not_affine_independent_of_ne {p : fin 3 → P} {i₁ i₂ i₃ : fin 3} (h₁₂ : i₁ ≠ i₂) (h₁₃ : i₁ ≠ i₃) (h₂₃ : i₂ ≠ i₃) : collinear k ({p i₁, p i₂, p i₃} : set P) ↔ ¬affine_independent k p:= (affine_independent_iff_not_collinear_of_ne h₁₂ h₁₃ h₂₃).not_left.symm /-- If three points are not collinear, the first and second are different. -/ lemma ne₁₂_of_not_collinear {p₁ p₂ p₃ : P} (h : ¬collinear k ({p₁, p₂, p₃} : set P)) : p₁ ≠ p₂ := by { rintro rfl, simpa [collinear_pair] using h } /-- If three points are not collinear, the first and third are different. -/ lemma ne₁₃_of_not_collinear {p₁ p₂ p₃ : P} (h : ¬collinear k ({p₁, p₂, p₃} : set P)) : p₁ ≠ p₃ := by { rintro rfl, simpa [collinear_pair] using h } /-- If three points are not collinear, the second and third are different. -/ lemma ne₂₃_of_not_collinear {p₁ p₂ p₃ : P} (h : ¬collinear k ({p₁, p₂, p₃} : set P)) : p₂ ≠ p₃ := by { rintro rfl, simpa [collinear_pair] using h } /-- A point in a collinear set of points lies in the affine span of any two distinct points of that set. -/ lemma collinear.mem_affine_span_of_mem_of_ne {s : set P} (h : collinear k s) {p₁ p₂ p₃ : P} (hp₁ : p₁ ∈ s) (hp₂ : p₂ ∈ s) (hp₃ : p₃ ∈ s) (hp₁p₂ : p₁ ≠ p₂) : p₃ ∈ line[k, p₁, p₂] := begin rw collinear_iff_of_mem hp₁ at h, rcases h with ⟨v, h⟩, rcases h p₂ hp₂ with ⟨r₂, rfl⟩, rcases h p₃ hp₃ with ⟨r₃, rfl⟩, rw vadd_left_mem_affine_span_pair, refine ⟨r₃ / r₂, _⟩, have h₂ : r₂ ≠ 0, { rintro rfl, simpa using hp₁p₂ }, simp [smul_smul, h₂] end /-- The affine span of any two distinct points of a collinear set of points equals the affine span of the whole set. -/ lemma collinear.affine_span_eq_of_ne {s : set P} (h : collinear k s) {p₁ p₂ : P} (hp₁ : p₁ ∈ s) (hp₂ : p₂ ∈ s) (hp₁p₂ : p₁ ≠ p₂) : line[k, p₁, p₂] = affine_span k s := le_antisymm (affine_span_mono _ (set.insert_subset.2 ⟨hp₁, set.singleton_subset_iff.2 hp₂⟩)) (affine_span_le.2 (λ p hp, h.mem_affine_span_of_mem_of_ne hp₁ hp₂ hp hp₁p₂)) /-- Given a collinear set of points, and two distinct points `p₂` and `p₃` in it, a point `p₁` is collinear with the set if and only if it is collinear with `p₂` and `p₃`. -/ lemma collinear.collinear_insert_iff_of_ne {s : set P} (h : collinear k s) {p₁ p₂ p₃ : P} (hp₂ : p₂ ∈ s) (hp₃ : p₃ ∈ s) (hp₂p₃ : p₂ ≠ p₃) : collinear k (insert p₁ s) ↔ collinear k ({p₁, p₂, p₃} : set P) := begin have hv : vector_span k (insert p₁ s) = vector_span k ({p₁, p₂, p₃} : set P), { conv_lhs { rw [←direction_affine_span, ←affine_span_insert_affine_span] }, conv_rhs { rw [←direction_affine_span, ←affine_span_insert_affine_span] }, rw h.affine_span_eq_of_ne hp₂ hp₃ hp₂p₃ }, rw [collinear, collinear, hv] end /-- Adding a point in the affine span of a set does not change whether that set is collinear. -/ lemma collinear_insert_iff_of_mem_affine_span {s : set P} {p : P} (h : p ∈ affine_span k s) : collinear k (insert p s) ↔ collinear k s := by rw [collinear, collinear, vector_span_insert_eq_vector_span h] /-- If a point lies in the affine span of two points, those three points are collinear. -/ lemma collinear_insert_of_mem_affine_span_pair {p₁ p₂ p₃ : P} (h : p₁ ∈ line[k, p₂, p₃]) : collinear k ({p₁, p₂, p₃} : set P) := begin rw collinear_insert_iff_of_mem_affine_span h, exact collinear_pair _ _ _ end /-- If two points lie in the affine span of two points, those four points are collinear. -/ lemma collinear_insert_insert_of_mem_affine_span_pair {p₁ p₂ p₃ p₄ : P} (h₁ : p₁ ∈ line[k, p₃, p₄]) (h₂ : p₂ ∈ line[k, p₃, p₄]) : collinear k ({p₁, p₂, p₃, p₄} : set P) := begin rw [collinear_insert_iff_of_mem_affine_span ((affine_subspace.le_def' _ _).1 (affine_span_mono k (set.subset_insert _ _)) _ h₁), collinear_insert_iff_of_mem_affine_span h₂], exact collinear_pair _ _ _ end /-- If three points lie in the affine span of two points, those five points are collinear. -/ lemma collinear_insert_insert_insert_of_mem_affine_span_pair {p₁ p₂ p₃ p₄ p₅ : P} (h₁ : p₁ ∈ line[k, p₄, p₅]) (h₂ : p₂ ∈ line[k, p₄, p₅]) (h₃ : p₃ ∈ line[k, p₄, p₅]) : collinear k ({p₁, p₂, p₃, p₄, p₅} : set P) := begin rw [collinear_insert_iff_of_mem_affine_span ((affine_subspace.le_def' _ _).1 (affine_span_mono k ((set.subset_insert _ _).trans (set.subset_insert _ _))) _ h₁), collinear_insert_iff_of_mem_affine_span ((affine_subspace.le_def' _ _).1 (affine_span_mono k (set.subset_insert _ _)) _ h₂), collinear_insert_iff_of_mem_affine_span h₃], exact collinear_pair _ _ _ end /-- If three points lie in the affine span of two points, the first four points are collinear. -/ lemma collinear_insert_insert_insert_left_of_mem_affine_span_pair {p₁ p₂ p₃ p₄ p₅ : P} (h₁ : p₁ ∈ line[k, p₄, p₅]) (h₂ : p₂ ∈ line[k, p₄, p₅]) (h₃ : p₃ ∈ line[k, p₄, p₅]) : collinear k ({p₁, p₂, p₃, p₄} : set P) := begin refine (collinear_insert_insert_insert_of_mem_affine_span_pair h₁ h₂ h₃).subset _, simp [set.insert_subset_insert] end /-- If three points lie in the affine span of two points, the first three points are collinear. -/ lemma collinear_triple_of_mem_affine_span_pair {p₁ p₂ p₃ p₄ p₅ : P} (h₁ : p₁ ∈ line[k, p₄, p₅]) (h₂ : p₂ ∈ line[k, p₄, p₅]) (h₃ : p₃ ∈ line[k, p₄, p₅]) : collinear k ({p₁, p₂, p₃} : set P) := begin refine (collinear_insert_insert_insert_left_of_mem_affine_span_pair h₁ h₂ h₃).subset _, simp [set.insert_subset_insert] end variables (k) /-- A set of points is coplanar if their `vector_span` has dimension at most `2`. -/ def coplanar (s : set P) : Prop := module.rank k (vector_span k s) ≤ 2 variables {k} /-- The `vector_span` of coplanar points is finite-dimensional. -/ lemma coplanar.finite_dimensional_vector_span {s : set P} (h : coplanar k s) : finite_dimensional k (vector_span k s) := begin refine is_noetherian.iff_fg.1 (is_noetherian.iff_rank_lt_aleph_0.2 (lt_of_le_of_lt h _)), simp, end /-- The direction of the affine span of coplanar points is finite-dimensional. -/ lemma coplanar.finite_dimensional_direction_affine_span {s : set P} (h : coplanar k s) : finite_dimensional k (affine_span k s).direction := (direction_affine_span k s).symm ▸ h.finite_dimensional_vector_span /-- A set of points, whose `vector_span` is finite-dimensional, is coplanar if and only if their `vector_span` has dimension at most `2`. -/ lemma coplanar_iff_finrank_le_two {s : set P} [finite_dimensional k (vector_span k s)] : coplanar k s ↔ finrank k (vector_span k s) ≤ 2 := begin have h : coplanar k s ↔ module.rank k (vector_span k s) ≤ 2 := iff.rfl, rw ←finrank_eq_rank at h, exact_mod_cast h end alias coplanar_iff_finrank_le_two ↔ coplanar.finrank_le_two _ /-- A subset of a coplanar set is coplanar. -/ lemma coplanar.subset {s₁ s₂ : set P} (hs : s₁ ⊆ s₂) (h : coplanar k s₂) : coplanar k s₁ := (rank_le_of_submodule (vector_span k s₁) (vector_span k s₂) (vector_span_mono k hs)).trans h /-- Collinear points are coplanar. -/ lemma collinear.coplanar {s : set P} (h : collinear k s) : coplanar k s := le_trans h one_le_two variables (k) (P) /-- The empty set is coplanar. -/ lemma coplanar_empty : coplanar k (∅ : set P) := (collinear_empty k P).coplanar variables {P} /-- A single point is coplanar. -/ lemma coplanar_singleton (p : P) : coplanar k ({p} : set P) := (collinear_singleton k p).coplanar /-- Two points are coplanar. -/ lemma coplanar_pair (p₁ p₂ : P) : coplanar k ({p₁, p₂} : set P) := (collinear_pair k p₁ p₂).coplanar variables {k} /-- Adding a point in the affine span of a set does not change whether that set is coplanar. -/ lemma coplanar_insert_iff_of_mem_affine_span {s : set P} {p : P} (h : p ∈ affine_span k s) : coplanar k (insert p s) ↔ coplanar k s := by rw [coplanar, coplanar, vector_span_insert_eq_vector_span h] end affine_space' section division_ring variables {k : Type*} {V : Type*} {P : Type*} include V open affine_subspace finite_dimensional module variables [division_ring k] [add_comm_group V] [module k V] [affine_space V P] /-- Adding a point to a finite-dimensional subspace increases the dimension by at most one. -/ lemma finrank_vector_span_insert_le (s : affine_subspace k P) (p : P) : finrank k (vector_span k (insert p (s : set P))) ≤ finrank k s.direction + 1 := begin by_cases hf : finite_dimensional k s.direction, swap, { have hf' : ¬finite_dimensional k (vector_span k (insert p (s : set P))), { intro h, have h' : s.direction ≤ vector_span k (insert p (s : set P)), { conv_lhs { rw [←affine_span_coe s, direction_affine_span] }, exact vector_span_mono k (set.subset_insert _ _) }, exactI hf (submodule.finite_dimensional_of_le h') }, rw [finrank_of_infinite_dimensional hf, finrank_of_infinite_dimensional hf', zero_add], exact zero_le_one }, haveI := hf, rw [←direction_affine_span, ←affine_span_insert_affine_span], rcases (s : set P).eq_empty_or_nonempty with hs | ⟨p₀, hp₀⟩, { rw coe_eq_bot_iff at hs, rw [hs, bot_coe, span_empty, bot_coe, direction_affine_span, direction_bot, finrank_bot, zero_add], convert zero_le_one' ℕ, rw ←finrank_bot k V, convert rfl; simp }, { rw [affine_span_coe, direction_affine_span_insert hp₀, add_comm], refine (submodule.finrank_add_le_finrank_add_finrank _ _).trans (add_le_add_right _ _), refine finrank_le_one ⟨p -ᵥ p₀, submodule.mem_span_singleton_self _⟩ (λ v, _), have h := v.property, rw submodule.mem_span_singleton at h, rcases h with ⟨c, hc⟩, refine ⟨c, _⟩, ext, exact hc } end variables (k) /-- Adding a point to a set with a finite-dimensional span increases the dimension by at most one. -/ lemma finrank_vector_span_insert_le_set (s : set P) (p : P) : finrank k (vector_span k (insert p s)) ≤ finrank k (vector_span k s) + 1 := begin rw [←direction_affine_span, ←affine_span_insert_affine_span, direction_affine_span], refine (finrank_vector_span_insert_le _ _).trans (add_le_add_right _ _), rw direction_affine_span end variables {k} /-- Adding a point to a collinear set produces a coplanar set. -/ lemma collinear.coplanar_insert {s : set P} (h : collinear k s) (p : P) : coplanar k (insert p s) := begin haveI := h.finite_dimensional_vector_span, rw [coplanar_iff_finrank_le_two], exact (finrank_vector_span_insert_le_set k s p).trans (add_le_add_right h.finrank_le_one _) end /-- A set of points in a two-dimensional space is coplanar. -/ lemma coplanar_of_finrank_eq_two (s : set P) (h : finrank k V = 2) : coplanar k s := begin haveI := finite_dimensional_of_finrank_eq_succ h, rw [coplanar_iff_finrank_le_two, ←h], exact submodule.finrank_le _ end /-- A set of points in a two-dimensional space is coplanar. -/ lemma coplanar_of_fact_finrank_eq_two (s : set P) [h : fact (finrank k V = 2)] : coplanar k s := coplanar_of_finrank_eq_two s h.out variables (k) /-- Three points are coplanar. -/ lemma coplanar_triple (p₁ p₂ p₃ : P) : coplanar k ({p₁, p₂, p₃} : set P) := (collinear_pair k p₂ p₃).coplanar_insert p₁ end division_ring namespace affine_basis universes u₁ u₂ u₃ u₄ variables {ι : Type u₁} {k : Type u₂} {V : Type u₃} {P : Type u₄} variables [add_comm_group V] [affine_space V P] section division_ring variables [division_ring k] [module k V] include V protected lemma finite_dimensional [finite ι] (b : affine_basis ι k P) : finite_dimensional k V := let ⟨i⟩ := b.nonempty in finite_dimensional.of_fintype_basis (b.basis_of i) protected lemma finite [finite_dimensional k V] (b : affine_basis ι k P) : finite ι := finite_of_fin_dim_affine_independent k b.ind protected lemma finite_set [finite_dimensional k V] {s : set ι} (b : affine_basis s k P) : s.finite := finite_set_of_fin_dim_affine_independent k b.ind lemma card_eq_finrank_add_one [fintype ι] (b : affine_basis ι k P) : fintype.card ι = finite_dimensional.finrank k V + 1 := begin haveI := b.finite_dimensional, exact b.ind.affine_span_eq_top_iff_card_eq_finrank_add_one.mp b.tot end variables {k V P} lemma exists_affine_basis_of_finite_dimensional [fintype ι] [finite_dimensional k V] (h : fintype.card ι = finite_dimensional.finrank k V + 1) : nonempty (affine_basis ι k P) := begin obtain ⟨s, b, hb⟩ := affine_basis.exists_affine_basis k V P, lift s to finset P using b.finite_set, refine ⟨b.reindex $ fintype.equiv_of_card_eq _⟩, rw [h, ← b.card_eq_finrank_add_one] end end division_ring end affine_basis
3de4acbe640745083b3fd41fc63495f41db9d4ac
a219dc692a6598d0a0a44aae56286b29a34ef09c
/D.lean
79f50e4bac6a76b45971ab231c36926fcbc7691c
[]
no_license
bjoernkjoshanssen/jaccard-nid
c66475f6230d062d21b0d119ce5b9da1648b042e
2a8dd9c5cc33d3cdfba94bb97ecadbfc51710fe2
refs/heads/main
1,675,404,699,874
1,608,937,501,000
1,608,937,501,000
323,006,169
0
1
null
null
null
null
UTF-8
Lean
false
false
24,543
lean
/- Copyright (c) 2020 Bjørn Kjos-Hanssen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Bjørn Kjos-Hanssen. Zulip chat help from: Alex J. Best, Johan Commelin, Kyle Miller, Pedro Minicz, Reid Barton, Scott Morrison, Heather Macbeth. Code contribution and definition of D improvement from: Jason Greuling -/ import data.finset -- finite set import data.set -- to make backslash work as set difference import data.finset.basic import topology.metric_space.basic import data.real.basic import delta import data.set.basic --set_option profiler true set_option pp.all true /-! # A theorem on metrics based on min and max In this file we give a formal proof that in terms of d(X,Y)= m min(|X\Y|, |Y\X|) + M max(|X\Y|, |Y\X|) the function D(X,Y) = d(X,Y)/(|X ∩ Y|+d(X,Y)) is a metric if and only if m ≤ M and 1 ≤ M. In particular, taking m=M=1, the Jaccard distance is a metric on finset ℕ. ## Main results - `noncomputable instance jaccard_nid.metric_space`: the proof of the main result described above. - `noncomputable instance jaccard.metric_space`: the special case of the Jaccard distance. ## Notation - `|_|` : Notation for cardinality. ## References See [KNYHLM20] for the original proof (https://math.hawaii.edu/~bjoern/nid-walcom.pdf). -/ open finset local notation |X| := X.card variables {m M : ℝ} -- in delta.lean but can't import variables section jaccard_nid variables {α : Type*} [decidable_eq α] --#check δ noncomputable def D : ℝ → ℝ → finset α → (finset α → ℝ) := λ m M x y, (δ m M x y) / (|x ∩ y| + δ m M x y) -- using Lean's "group with zero" to hand the case 0/0=0 lemma cap_sdiff (X Y Z : finset α): X ∩ Z ⊆ X ∩ Y ∪ Z \ Y := by{tidy, by_cases h: a ∈ Y, cc,cc} lemma sdiff_cap (X Y Z : finset α): X ∩ Z \ Y ⊆ Z \ Y := -- by show_term{tidy} -- by tidy? by {intros a a_1, dsimp at *, simp at *, cases a_1, cases a_1_left, fsplit, work_on_goal 0 { assumption }, assumption} --#print sdiff_cap theorem twelve_end (X Y Z : finset α) : |X ∩ Z| ≤ |X ∩ Y| + max (|Z \ Y|) (|Y \ Z|) := let z_y := |Z \ Y|, y_z := |Y \ Z|, y := |Y|, z := |Z| in (em (y ≤ z)).elim( λ h: y ≤ z, calc |X ∩ Z| ≤ |X ∩ Y ∪ Z \ Y| : card_le_of_subset (cap_sdiff X Y Z) ... ≤ |X ∩ Y| + |Z \ Y| : card_union_le (X ∩ Y) (Z \ Y) ... = |X ∩ Y| + max z_y y_z : by rw[max_eq_left (sdiff_card Z Y h)] )( λ h: ¬ y ≤ z, have h1: z ≤ y, from le_of_lt ((iff.elim_right lt_iff_not_ge') h), have h_diff: z_y ≤ y_z, from sdiff_card Y Z h1, let x110 := |X ∩ Y \ Z|, x111 := |X ∩ Y ∩ Z|, x010 := |Y \ X \ Z|, x111 := |X ∩ Y ∩ Z|, x101 := |X ∩ Z \ Y|, xz := |X ∩ Z|, xy := |X ∩ Y|, xz_y := |X ∩ Z \ Y| in have r: xz_y ≤ z_y, from card_le_of_subset (sdiff_cap X Y Z), have uni_xz: X ∩ Z = (X ∩ Z \ Y) ∪ (X ∩ Y ∩ Z), by { tidy, by_cases h: a ∈ Y, cc, cc}, have uni_xy: (X ∩ Y \ Z) ∪ (X ∩ Y ∩ Z) = X ∩ Y, by { tidy, by_cases h: a ∈ Z, cc, cc}, have uni_y_z: (X ∩ Y \ Z) ∪ (Y \ X \ Z) = Y \ Z, by { tidy, by_cases h: a ∈ X, cc, cc}, have dis_xz: disjoint (X ∩ Z \ Y) (X ∩ Y ∩ Z), by { rw disjoint_iff, tidy}, have dis_xy: disjoint (X ∩ Y \ Z) (X ∩ Y ∩ Z), by { rw disjoint_iff, tidy}, have dis_y_z: disjoint (X ∩ Y \ Z) (Y \ X \ Z), by { rw disjoint_iff, tidy}, have sum_xz: xz = x101 + x111, from calc xz = ((X ∩ Z \ Y) ∪ (X ∩ Y ∩ Z)).card : congr_arg card uni_xz ... = x101 + x111: card_disjoint_union dis_xz, have sum_xy: x110 + x111 = xy, from calc x110 + x111 = ((X ∩ Y \ Z) ∪ (X ∩ Y ∩ Z)).card: (card_disjoint_union dis_xy).symm ... = xy: (congr_arg card uni_xy), have sum_y_z: x110 + x010 = y_z, from calc x110 + x010 = ((X ∩ Y \ Z) ∪ (Y \ X \ Z)).card: (card_disjoint_union dis_y_z).symm ... = y_z: congr_arg card uni_y_z, have prelim: x101 ≤ x110 + x110 + x010, from calc x101 ≤ y_z : le_trans r h_diff ... = x110 + x010 : by rw[sum_y_z] ... = 0 + (x110 + x010) : by ring ... ≤ x110 + (x110 + x010) : add_le_add_right (nat.zero_le x110) (x110 + x010) ... = x110 + x110 + x010 : by ring, calc xz = x101 + x111 : sum_xz ... ≤ x110 + x110 + x010 + x111 : add_le_add_right prelim x111 ... = (x110 + x111) + (x110 + x010) : by ring ... = xy + max z_y y_z : by rw[sum_xy,sum_y_z,max_eq_right h_diff] ) theorem twelve_middle (hm: 0 ≤ m) (hM: 0 < M) (X Y Z : finset α) : let y_z := |Y\Z|, z_y := |Z\Y|, xy := |X ∩ Y|, xz := |X ∩ Z| in (|X ∩ Z|:ℝ) ≤ (xy:ℝ) + (max z_y y_z:ℝ) + (m/M) * (min z_y y_z:ℝ) := let y_z := |Y\Z|, z_y := |Z\Y|, xy := |X ∩ Y|, xz := |X ∩ Z| in have b: 0 ≤ m/M ↔ 0*M ≤ m, from le_div_iff hM, have a: 0*M ≤ m, from calc 0*M = 0 : by ring ... ≤ m : hm, have g:0 ≤ m/M, from (iff.elim_right b) a, have e:0 ≤ min z_y y_z, from le_min (nat.zero_le z_y) (nat.zero_le y_z), have f:0 ≤ (min z_y y_z:ℝ), begin norm_cast,exact e, end, let maxzy := (max z_y y_z:ℝ) in calc (xz:ℝ) ≤ (xy:ℝ) + (max z_y y_z:ℝ): by {norm_cast,exact (twelve_end X Y Z)} ... = (xy:ℝ) + maxzy + 0 : by ring ... ≤ (xy:ℝ) + maxzy + (m/M) * (min z_y y_z:ℝ) : add_le_add_left (mul_nonneg g f) ((xy:ℝ) + maxzy) theorem jn_self (X : finset α): D m M X X = 0 := show (δ m M X X) / (|X ∩ X| + δ m M X X) = 0, by rw[delta_self,zero_div] theorem delta_nonneg {x y : finset α} (hm: 0 ≤ m) (hM: m ≤ M): 0 ≤ δ m M x y := have alpha: δ m M x x ≤ δ m M x y + δ m M y x, from seventeen_right hm hM, have 0 ≤ 2 * δ m M x y, from calc 0 = δ m M x x: by rw[delta_self] ... ≤ δ m M x y + δ m M y x: seventeen_right hm hM ... = 2 * δ m M x y: by rw [delta_comm, two_mul], nonneg_of_mul_nonneg_left this zero_lt_two theorem jn_comm (X Y : finset α): D m M X Y = D m M Y X := show (δ m M X Y) / (|X ∩ Y| + δ m M X Y) = (δ m M Y X) / (|Y ∩ X| + δ m M Y X), from by rw[delta_comm,delta_comm,inter_comm] lemma card_inter_nonneg (X Y : finset α): 0 ≤ (|X ∩ Y|:ℝ) := by { norm_cast, exact (nat.zero_le (|X ∩ Y|))} lemma D_denom_nonneg (X Y : finset α) (hm: 0 ≤ m) (hM: m ≤ M): 0 ≤ (|X ∩ Y|:ℝ) + δ m M X Y := add_nonneg (card_inter_nonneg X Y) (delta_nonneg hm hM) theorem eq_of_jn_eq_zero (hm: 0 < m) (hM: m ≤ M) (X Y : finset α) (h: D m M X Y = 0) : X = Y := have h1: (δ m M X Y) = 0 ∨ ((|X ∩ Y|:ℝ) + δ m M X Y) = 0, from (iff.elim_left (div_eq_zero_iff)) h, h1.elim( assume g: δ m M X Y = 0, eq_of_delta_eq_zero hm hM X Y g )( assume g: (|X ∩ Y|:ℝ) + δ m M X Y = 0, have denom: 0 = δ m M X Y + |X ∩ Y| , begin rw[add_comm] at g, exact g.symm, end, have nonneg: 0 ≤ δ m M X Y, from delta_nonneg (le_of_lt hm) hM, have zero: 0 = δ m M X Y, from eq_zero_of_nonneg_of_nonneg_of_add_zero nonneg (card_inter_nonneg X Y) denom, eq_of_delta_eq_zero hm hM X Y (eq.symm zero) ) theorem D_nonneg (X Y : finset α) (hm: 0 ≤ m) (hM: m ≤ M): 0 ≤ D m M X Y := have hc: 0 ≤ δ m M X Y, from delta_nonneg hm hM, (em (0 < (|X ∩ Y|:ℝ) + δ m M X Y)).elim( λ hd: 0 < (|X ∩ Y|:ℝ) + δ m M X Y, calc 0 = 0 / ((|X ∩ Y|:ℝ) + δ m M X Y) : by rw[zero_div] ... ≤ δ m M X Y / ((|X ∩ Y|:ℝ) + δ m M X Y) : div_le_div hc hc hd (by apply_rules le_refl) )( λ hd: ¬ 0 < (|X ∩ Y|:ℝ) + δ m M X Y, -- in this case, X = Y = ∅ have hd2: 0 ≤ (|X ∩ Y|:ℝ) + δ m M X Y, from D_denom_nonneg X Y hm hM, have hdd: 0 = (|X ∩ Y|:ℝ) + δ m M X Y, from by_contra ( λ hh: ¬ 0 = (|X ∩ Y|:ℝ) + δ m M X Y, hd ((iff.elim_right lt_iff_le_and_ne) (and.intro hd2 hh)) ), calc 0 ≤ 0: le_refl 0 ... = δ m M X Y / 0: by rw[div_zero] ... = δ m M X Y / ((|X ∩ Y|:ℝ) + δ m M X Y): by rw[hdd] ) theorem D_empty_1 (m M : ℝ) {X Y : finset α} (hm: 0 < m) (hM: m ≤ M): X = ∅ → Y ≠ ∅ → D m M X Y = 1 := λ hx: X = ∅, λ hy: Y ≠ ∅, have hhh: X ∩ Y = ∅, from calc X ∩ Y = ∅ ∩ Y : by rw hx ... = ∅ :empty_inter Y, have h: |X ∩ Y| = 0, from calc |X∩ Y|=|(∅:finset α)|: by rw hhh ... = 0: card_empty, have h1: X ≠ Y, from assume h2: X = Y, have h3: Y = ∅, from eq.trans h2.symm hx, hy h3, have h0: δ m M X Y ≠ 0, from assume h2: δ m M X Y = 0, have h3: X = Y, from eq_of_delta_eq_zero (hm) hM X Y h2, h1 h3, have hh: (|X ∩ Y|:ℝ) = 0, begin norm_cast,exact h, end, calc (δ m M X Y)/(|X ∩ Y| + δ m M X Y) = (δ m M X Y)/(0 + δ m M X Y) : by rw[hh] ... = (δ m M X Y)/(δ m M X Y) : by rw[zero_add] ... = 1 : div_self h0 theorem D_empty_2 (m M : ℝ) {X Y : finset α} (hm: 0 < m) (hM: m ≤ M): X ≠ ∅ → Y = ∅ → D m M X Y = 1 := λ hx: X ≠ ∅, λ hy: Y = ∅, let dxy := δ m M X Y, dyx := δ m M Y X in calc dxy / (|X ∩ Y| + dxy) = (δ m M Y X)/(|Y ∩ X| + δ m M Y X) : by rw[delta_comm,inter_comm] ... = 1 : D_empty_1 m M hm hM hy hx lemma div_self_le_one (a:ℝ): a/a ≤ 1 := (em (a=0)).elim( λ h: a = 0, calc a/a = a/0: by rw[h] ... = 0 : div_zero a ... ≤ 1 : zero_le_one )( λ h: a ≠ 0, calc a/a = 1: div_self h ... ≤ 1: le_refl 1 ) theorem D_bounded (m M : ℝ) (X Y : finset α) (hm: 0 ≤ m) (hM: m ≤ M): D m M X Y ≤ 1 := (em (0 = (|X ∩ Y|:ℝ) + δ m M X Y)).elim( λ h0: 0 = (|X ∩ Y|:ℝ) + δ m M X Y, calc (δ m M X Y)/(|X ∩ Y| + δ m M X Y) = (δ m M X Y)/0: by rw[h0] ... = 0: div_zero (δ m M X Y) ... ≤ 1: zero_le_one )( λ h0: 0 ≠ (|X ∩ Y|:ℝ) + δ m M X Y, let dxy := δ m M X Y in have hd2: 0 ≤ (|X ∩ Y|:ℝ) + dxy, from D_denom_nonneg X Y hm hM, have pos: 0 < (|X ∩ Y|:ℝ) + dxy, from (iff.elim_right lt_iff_le_and_ne) (and.intro hd2 h0), have h: dxy ≤ |X ∩ Y| + dxy, from calc dxy = 0 + dxy: by rw[zero_add] ... ≤ |X ∩ Y| + dxy: add_le_add_right (card_inter_nonneg X Y) (dxy), calc dxy /(|X ∩ Y| + dxy) ≤ (|X ∩ Y| + dxy)/(|X ∩ Y| + dxy): div_le_div hd2 h pos (le_refl (|X ∩ Y| + dxy)) ... ≤ 1: div_self_le_one (|X ∩ Y| + dxy) ) theorem intersect_cases (m M : ℝ) (Y Z : finset α) (hm: 0<m) (hM: m≤ M) (hy: Y ≠ ∅) (hz: Z ≠ ∅): let ayz := (|Z ∩ Y|:ℝ), dyz := (δ m M Z Y) in 0 < (ayz + dyz) := let ayz := (|Z ∩ Y|:ℝ), dyz := (δ m M Z Y) in (em (Y ∩ Z = ∅)).elim( λ hxy : Y ∩ Z = ∅, have decompose: Y = Y ∩ Z ∪ Y \ Z, begin tidy,by_cases (a ∈ Z),cc,cc, end, have non_empty: ∅ ≠ Y \ Z, from assume h: ∅ = Y \ Z, have h1:Y = ∅, from calc Y = Y ∩ Z ∪ Y \ Z : decompose ... = ∅ ∪ ∅ : by rw[hxy,h] ... = ∅ : by rw union_empty, hy h1, have ne_prelim: Z ≠ Y, from assume h: Z = Y, have h0: Y \ Z = ∅, from calc Y \ Z = Z \ Z: by rw[h] ... = ∅: sdiff_self Z, have h1: ∅ = Y \ Z, from h0.symm, non_empty h1, have ne: 0 ≠ dyz, from λ zero_eq_delta: 0 = dyz, have eq: Z = Y, from eq_of_delta_eq_zero hm hM Z Y zero_eq_delta.symm, ne_prelim eq, have le: 0 ≤ dyz, from delta_nonneg (le_of_lt hm) hM, calc 0 < dyz: (iff.elim_right lt_iff_le_and_ne) (and.intro le ne) ... = 0 + dyz: by rw[zero_add] ... ≤ ayz + dyz: add_le_add_right (card_inter_nonneg Z Y) dyz )( λ hxy : Y ∩ Z ≠ ∅, have card_zero: |Y ∩ Z| = 0 ↔ Y ∩ Z = ∅, from card_eq_zero, have ne_nat: |Y ∩ Z| ≠ 0, from λ h: |Y ∩ Z| = 0, hxy ((iff.elim_left card_zero) h), have le: 0 ≤ (|Y ∩ Z|:ℝ), from card_inter_nonneg Y Z, have ne: 0 ≠ (|Y ∩ Z|:ℝ), begin norm_cast,exact ne_nat.symm, end, calc 0 < (|Y ∩ Z|:ℝ): (iff.elim_right lt_iff_le_and_ne) (and.intro le ne) ... = ayz : by rw[inter_comm] ... = ayz + 0 : by rw[add_zero] ... ≤ ayz + dyz: add_le_add_left (delta_nonneg (le_of_lt hm) hM) ayz ) lemma four_immediate_from (m M : ℝ) (X Y Z : finset α) (hm: 0 < m) (hM: m ≤ M) (h1M: 1 ≤ M) (hx: X ≠ ∅) (hy: Y ≠ ∅) (hz: Z ≠ ∅): let axy := (|X ∩ Y|:ℝ), dxz := δ m M X Z, dyz := δ m M Z Y, axz := (|X ∩ Z|:ℝ), denom := axy+dxz+dyz in dxz/denom ≤ dxz/(axz + dxz) := let dxy := (δ m M X Y), axy := (|X ∩ Y|:ℝ), dxz := δ m M X Z, dyz := (δ m M Z Y), ayz := (|Z ∩ Y|:ℝ), axz := (|X ∩ Z|:ℝ), y_z : ℕ := (Y \ Z).card, z_y : ℕ := (Z \ Y).card,x_z : ℕ := (X \ Z).card, z_x : ℕ := (Z \ X).card, xy : ℕ := (X ∩ Y).card, xz : ℕ := (X ∩ Z).card, yz : ℕ := (Y ∩ Z).card, mini := (min (|Z \ Y|) (|Y \ Z|) : ℝ), maxi := (max (|Z \ Y|) (|Y \ Z|) : ℝ), denom := (axy+dxz+dyz) in have twelve_end_real: (xz:ℝ) ≤ (xy:ℝ) + max (|Z \ Y| : ℝ) (|Y \ Z| : ℝ), from have ddd: xz ≤ xy + max ((Z \ Y).card) ((Y \ Z).card), from twelve_end X Y Z, begin norm_cast,exact ddd, end, have max_nonneg_real: 0 ≤ (max (|Z \ Y|) (|Y \ Z|) : ℝ), from have 0 ≤ max z_y y_z, from nat.zero_le (max z_y y_z), begin norm_cast, exact this,end, have min_nonneg_real: 0 ≤ (min (|Z \ Y|) (|Y \ Z|) : ℝ), from have 0 ≤ min z_y y_z, from nat.zero_le (min z_y y_z), begin norm_cast, exact this,end, have mmin_nonneg : 0 ≤ m * mini, from mul_nonneg (le_of_lt hm) min_nonneg_real, have use_h1M: 1 * maxi ≤ M * maxi, from mul_le_mul_of_nonneg_right h1M max_nonneg_real, have four_would_follow_from : axz ≤ axy + dyz, from calc axz ≤ (xy:ℝ) + maxi : twelve_end_real ... = (xy:ℝ) + 1 * maxi : by ring ... ≤ (xy:ℝ) + M * maxi : add_le_add_left use_h1M (xy:ℝ) ... = (xy:ℝ) + M * maxi + 0 : by rw[add_zero] ... ≤ (xy:ℝ) + M * maxi + m * mini : add_le_add_left mmin_nonneg ((xy:ℝ) + M * maxi) ... = (xy:ℝ) + (M * (max (|Z \ Y|) (|Y \ Z|) : ℝ) + m * (min (|Z \ Y|) (|Y \ Z|) : ℝ)): by rw[add_assoc] ... = (|X ∩ Y|:ℝ) + (δ m M Z Y): begin norm_cast, end, have le_denom:(axz + dxz) ≤ denom, from calc axz + dxz ≤ axy + dyz + dxz : add_le_add_right four_would_follow_from dxz ... = axy + dxz + dyz : by ring, have denom_pos : 0 < (axz + dxz), from intersect_cases m M Z X hm hM hz hx, have d_nonneg: 0 ≤ dxz, from delta_nonneg (le_of_lt hm) hM, div_le_div_of_le_left d_nonneg denom_pos le_denom lemma four_immediate_from_and (m M : ℝ) (X Y Z : finset α) (hm: 0 < m) (hM: m ≤ M) (h1M: 1 ≤ M) (hx: X ≠ ∅) (hy: Y ≠ ∅) (hz: Z ≠ ∅): (δ m M Z Y)/((|X ∩ Y|:ℝ) + δ m M X Z + δ m M Z Y) ≤ (δ m M Z Y)/((|Z ∩ Y|:ℝ) + δ m M Z Y) := let dzy := δ m M Z Y, dyz := δ m M Y Z, dxz := δ m M X Z, dzx := δ m M Z X in have S: (dyz) / ((|Y ∩ X|:ℝ) + (dyz) + (dzx)) ≤ (dyz) / ((|Y ∩ Z|:ℝ) + dyz), from four_immediate_from m M Y X Z hm hM h1M hy hx hz, have dzy_comm: dzy = dyz, from delta_comm, have dxz_comm: dxz = dzx, from delta_comm, have ring_in_denom: (|Y ∩ X|:ℝ) + dzx + dyz = (|Y ∩ X|:ℝ) + dyz + dzx, by ring, calc dzy / ((|X ∩ Y|:ℝ) + dxz + dzy) = dyz / ((|Y ∩ X|:ℝ) + dyz + dzx) : by rw[inter_comm,dxz_comm,dzy_comm,ring_in_denom] ... ≤ dyz / ((|Y ∩ Z|:ℝ) + dyz) : S ... = dzy / ((|Z ∩ Y|:ℝ) + dzy) : by rw[inter_comm,dzy_comm] lemma mul_le_mul_rt {a b c : ℝ} (h : 0 ≤ c) : a ≤ b → a * c ≤ b * c := (em (0 = c)).elim( λ h0: 0 = c, λ hab: a ≤ b, calc a* c = a * 0: by rw h0 ... = 0: mul_zero a ... ≤ 0: le_refl 0 ... = b * 0: by rw[mul_zero b] ... = b * c: by rw h0 )( λ h0: 0 ≠ c, λ hab: a ≤ b, have h1: 0 < c, from (iff.elim_right lt_iff_le_and_ne) (and.intro h h0), (iff.elim_right (mul_le_mul_right h1)) hab ) lemma abc_lemma {a b c : ℝ} (h : 0 ≤ a) (hb : a ≤ b) (hc : 0 ≤ c) : (a/(a+c)) ≤ (b/(b+c)) := (em (0 = a)).elim( λ ha: 0 = a, (em (0 = b)).elim( λ hhb: 0 = b, -- a=b=0 calc a/(a+c) = 0/(0+c): by rw ha ... ≤ 0/(0+c): le_refl (0/(0+c)) ... = b/(b+c): by rw hhb )( λ hhb: 0 ≠ b, -- a=0, b ≠ 0 have g0: 0 ≤ b, from (le_trans h hb), have g: 0 ≤ b + c, from add_nonneg g0 hc, calc a/(a+c) = 0/(a+c): by rw ha ... = 0: by rw zero_div ... ≤ b/(b+c): div_nonneg g0 g ) )( λ hh: 0 ≠ a, -- then, since a ≤ b, b ≠ 0 as well have ha: 0 < a, from (iff.elim_right lt_iff_le_and_ne) (and.intro h hh), have numer : a*(b+c) ≤ b*(a+c), from calc a*(b+c) = a*b + a*c : by rw left_distrib ... ≤ a*b + b*c : add_le_add_left (mul_le_mul_rt hc hb) (a*b) ... = b * (a+c) : by ring, have h6 : 0 < a+c, from lt_add_of_pos_of_le ha hc, have h7 : 0 < b+c, from lt_add_of_pos_of_le (has_lt.lt.trans_le ha hb) hc, (iff.elim_right (div_le_div_iff h6 h7)) numer ) theorem three (X Y Z : finset α) (hm: 0 < m) (hM: m ≤ M): let axy := (|X ∩ Y| : ℝ), dxy := δ m M X Y, dxz := δ m M X Z, dyz := δ m M Z Y, denom := (axy+dxz+dyz) in dxy/(axy + dxy) ≤ (dxz+dyz)/denom := let axy := (|X ∩ Y| : ℝ), dxy := δ m M X Y, dxz := δ m M X Z, dzy := δ m M Y Z, dyz := δ m M Z Y, axy := (|X ∩ Y| : ℝ), denom := (axy+dxz+dyz) in have hd : 0 ≤ δ m M X Y, from delta_nonneg (le_of_lt hm) hM, have h0 : δ m M Z Y = δ m M Y Z , by rw delta_comm, have h1 : dxy ≤ dxz + dzy, from calc dxy ≤ dxz + δ m M Z Y: delta_triangle X Z Y hm hM ... = dxz + δ m M Y Z: by rw h0, have h2: dxz + dyz + axy = axy + dxz + dyz, by ring, calc dxy / (axy + dxy) = dxy / (dxy + axy) : by rw add_comm axy dxy ... ≤ (dxz + δ m M Y Z) / (dxz + dzy + axy) : abc_lemma hd h1 (card_inter_nonneg X Y) ... = (dxz + δ m M Z Y) / (dxz + δ m M Z Y + axy) : by rw h0 ... = (dxz + δ m M Z Y) / (axy + dxz + δ m M Z Y) : by rw h2 theorem jn_triangle_nonempty (m M : ℝ) (X Y Z : finset α) (hm: 0 < m) (hM: m ≤ M) (h1M: 1 ≤ M) (hx: X ≠ ∅) (hy: Y ≠ ∅) (hz: Z ≠ ∅): D m M X Y ≤ D m M X Z + D m M Z Y := let dxy := (δ m M X Y), axy := (|X ∩ Y|:ℝ), dxz := δ m M X Z, dyz := (δ m M Z Y), ayz := (|Z ∩ Y|:ℝ), axz := (|X ∩ Z|:ℝ), denom := (axy+dxz+dyz) in have hzM: 0 < M, from calc 0 < m: hm ... ≤ M: hM, have three: dxy/(axy + dxy) ≤ (dxz+dyz)/denom, from three X Y Z hm hM, have four: (dxz+dyz)/denom ≤ dxz/(axz + dxz) + dyz/(ayz + dyz), from calc (dxz+dyz)/denom = dxz/denom + dyz/denom: add_div dxz dyz denom ... ≤ dxz/(axz + dxz) + dyz/denom: add_le_add_right (four_immediate_from m M X Y Z hm hM h1M hx hy hz) ((dyz)/denom) ... ≤ dxz/(axz + dxz) + dyz/(ayz + dyz) : add_le_add_left (four_immediate_from_and m M X Y Z hm hM h1M hx hy hz) (dxz/(axz + dxz)), le_trans three four theorem jn_triangle (m M : ℝ) (X Y Z : finset α) (hm: 0 < m) (hM: m ≤ M) (h1M: 1 ≤ M): D m M X Y ≤ D m M X Z + D m M Z Y := let dxz := D m M X Z in (em (X=∅)).elim( λ hx: X = ∅, (em (Y=∅)).elim( λ hy: Y = ∅, have h1: X = Y, from eq.trans hx hy.symm, calc D m M X Y = D m M X X : by rw[h1] ... = 0 : jn_self X ... ≤ D m M Z Y : D_nonneg Z Y (le_of_lt hm) hM ... = 0 + D m M Z Y : eq.symm (zero_add (D m M Z Y)) ... ≤ D m M X Z + D m M Z Y : add_le_add_right (D_nonneg X Z (le_of_lt hm) hM) (D m M Z Y) )( λ hy: Y ≠ ∅, (em (Z = ∅)).elim( λ hz: Z = ∅, -- 010 non Y nonempty have h3: D m M Z Y = 1, from D_empty_1 m M hm hM hz hy, calc D m M X Y = 1: D_empty_1 m M hm hM hx hy ... = 0 + 1: by rw[zero_add] ... ≤ D m M X Z + 1: add_le_add_right (D_nonneg X Z (le_of_lt hm) hM) 1 ... = D m M X Z + D m M Z Y: by rw[h3] )( λ hz: Z ≠ ∅, -- 011 only X empty have h1: D m M X Y = 1, from D_empty_1 m M hm hM hx hy, have h2: D m M X Z = 1, from D_empty_1 m M hm hM hx hz, calc D m M X Y = 1: h1 ... = 1 + 0: by rw[add_zero] ... ≤ 1 + D m M Z Y: add_le_add_left (D_nonneg Z Y (le_of_lt hm) hM) 1 ... = D m M X Z + D m M Z Y: by rw[h2] ) ) )( λ hx: X ≠ ∅, (em (Y=∅)).elim( λ hy: Y = ∅, (em (Z = ∅)).elim( λ hz: Z = ∅, -- 100 only X nonempty calc D m M X Y = 1 : D_empty_2 m M hm hM hx hy ... = 1 + 0 : by rw[add_zero] ... ≤ 1 + D m M Z Y : add_le_add_left (D_nonneg Z Y (le_of_lt hm) hM) 1 ... = D m M X Z + D m M Z Y : by rw[D_empty_2 m M hm hM hx hz] )( λ hz: Z ≠ ∅, -- 101 only Y empty calc D m M X Y = 1 : D_empty_2 m M hm hM hx hy ... = 0 + 1 : by rw[zero_add] ... ≤ D m M X Z + 1 : add_le_add_right (D_nonneg X Z (le_of_lt hm) hM) 1 ... = D m M X Z + D m M Z Y : by rw[D_empty_2 m M hm hM hz hy] ) )( λ hy: Y ≠ ∅, (em (Z = ∅)).elim( λ hz: Z = ∅, -- 110 only Z is empty have h2: D m M X Z = 1, from D_empty_2 m M hm hM hx hz, have h3: D m M Z Y = 1, from D_empty_1 m M hm hM hz hy, calc D m M X Y ≤ 1: D_bounded m M X Y (le_of_lt hm) hM ... = 0 + 1: by rw[zero_add] ... ≤ 1 + 1: add_le_add_right zero_le_one 1 ... = D m M X Z + D m M Z Y: by rw[h2,h3] )( λ hz: Z ≠ ∅, -- 111 jn_triangle_nonempty m M X Y Z hm hM h1M hx hy hz ) ) ) noncomputable instance jaccard_nid.metric_space (hm : 0 < m) (hM : m ≤ M) (h1M: 1 ≤ M): metric_space (finset α) := { dist := λx y, D m M x y, dist_self := jn_self, eq_of_dist_eq_zero := eq_of_jn_eq_zero hm hM, dist_comm := λ x y, jn_comm x y, dist_triangle := λ x z y, jn_triangle m M x y z hm hM h1M } noncomputable def J : finset α → (finset α → ℝ) := λ x y, (δ 1 1 x y) / ((|x ∩ y|:ℝ) + δ 1 1 x y) --Easy but not done yet: --theorem J_characterization (X Y : finset α): --J X Y = ((|X \ Y|) + (|Y \ X|)) / (|X ∪ Y|) := --let dxy := (1:ℝ) * (max (|X \ Y|) (|Y \ X|):ℝ) + (1:ℝ) * (min (|X \ Y|) (|Y \ X|):ℝ) in --calc dxy / ((|X ∩ Y|:ℝ) + dxy) = ((|X \ Y|) + (|Y \ X|)) / (|X ∪ Y|): sorry noncomputable instance jaccard.metric_space (hm : (0:ℝ) < (1:ℝ)) (hM : (1:ℝ) ≤ (1:ℝ)) (h1M: (1:ℝ) ≤ (1:ℝ)): metric_space (finset ℕ) := { dist := λx y, D 1 1 x y, dist_self := jn_self, eq_of_dist_eq_zero := eq_of_jn_eq_zero hm hM, dist_comm := λ x y, jn_comm x y, dist_triangle := λ x z y, jn_triangle 1 1 x y z hm hM h1M } end jaccard_nid
b0896b6acf0a15b8568fffd1992c143bb605d88e
df7bb3acd9623e489e95e85d0bc55590ab0bc393
/lean/love03_forward_proofs_exercise_solution.lean
53e73bbc5a5bcba3cb2aa76bf594f20bf635d7f1
[]
no_license
MaschavanderMarel/logical_verification_2020
a41c210b9237c56cb35f6cd399e3ac2fe42e775d
7d562ef174cc6578ca6013f74db336480470b708
refs/heads/master
1,692,144,223,196
1,634,661,675,000
1,634,661,675,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,924
lean
import .lovelib /- # LoVe Exercise 3: Forward Proofs -/ set_option pp.beta true set_option pp.generalized_field_notation false namespace LoVe /- ## Question 1: Connectives and Quantifiers 1.1. Supply structured proofs of the following lemmas. -/ lemma I (a : Prop) : a → a := assume ha : a, show a, from ha lemma K (a b : Prop) : a → b → b := assume ha : a, assume hb : b, show b, from hb lemma C (a b c : Prop) : (a → b → c) → b → a → c := assume hg : a → b → c, assume hb : b, assume ha : a, show c, from hg ha hb lemma proj_1st (a : Prop) : a → a → a := assume ha ha' : a, show a, from ha /- Please give a different answer than for `proj_1st`. -/ lemma proj_2nd (a : Prop) : a → a → a := assume ha ha' : a, show a, from ha' lemma some_nonsense (a b c : Prop) : (a → b → c) → a → (a → c) → b → c := assume hg : a → b → c, assume ha : a, assume hf : a → c, assume hb : b, have hc : c := hf ha, show c, from hc /- 1.2. Supply a structured proof of the contraposition rule. -/ lemma contrapositive (a b : Prop) : (a → b) → ¬ b → ¬ a := assume hab : a → b, assume hnb : ¬ b, assume ha : a, have hb : b := hab ha, show false, from hnb hb /- 1.3. Supply a structured proof of the distributivity of `∀` over `∧`. -/ lemma forall_and {α : Type} (p q : α → Prop) : (∀x, p x ∧ q x) ↔ (∀x, p x) ∧ (∀x, q x) := iff.intro (assume hpq : ∀x, p x ∧ q x, have hp : ∀x, p x := fix x, and.elim_left (hpq x), have hq : ∀x, q x := fix x, and.elim_right (hpq x), show (∀x, p x) ∧ (∀x, q x), from and.intro hp hq) (assume hpq : (∀x, p x) ∧ (∀x, q x), have hp : ∀x, p x := and.elim_left hpq, have hq : ∀x, q x := and.elim_right hpq, assume x : α, show p x ∧ q x, from and.intro (hp x) (hq x)) /- 1.4. Reuse, if possible, the lemma `forall_and` you proved above to prove the following instance of the lemma. -/ lemma forall_and_inst {α : Type} (r s : α → α → Prop) : (∀x, r x x ∧ s x x) ↔ (∀x, r x x) ∧ (∀x, s x x) := forall_and (λx, r x x) (λx, s x x) /- ## Question 2: Chain of Equalities 2.1. Write the following proof using `calc`. `(a + b) * (a + b)` `= a * (a + b) + b * (a + b)` `= a * a + a * b + b * a + b * b` `= a * a + a * b + a * b + b * b` `= a * a + 2 * a * b + b * b` Hint: You might need the tactics `simp` and `cc` and the lemmas `mul_add`, `add_mul`, and `two_mul`. -/ lemma binomial_square (a b : ℕ) : (a + b) * (a + b) = a * a + 2 * a * b + b * b := calc (a + b) * (a + b) = a * (a + b) + b * (a + b) : begin simp [add_mul, mul_add], cc end ... = a * a + a * b + b * a + b * b : begin simp [add_mul, mul_add], cc end ... = a * a + a * b + a * b + b * b : by cc ... = a * a + 2 * a * b + b * b : begin simp [two_mul, mul_add, add_mul], cc end /- 2.2. Prove the same argument again, this time as a structured proof. Try to reuse as much of the above proof idea as possible. -/ lemma binomial_square₂ (a b : ℕ) : (a + b) * (a + b) = a * a + 2 * a * b + b * b := have h1 : (a + b) * (a + b) = a * (a + b) + b * (a + b) := begin simp [add_mul, mul_add], cc end, have h2 : a * (a + b) + b * (a + b) = a * a + a * b + b * a + b * b := begin simp [add_mul, mul_add], cc end, have h3 : a * a + a * b + b * a + b * b = a * a + a * b + a * b + b * b := begin simp, cc end, have h4 : a * a + a * b + a * b + b * b = a * a + 2 * a * b + b * b := begin simp [two_mul, add_mul, mul_add], cc end, show _, from begin rw h1, rw h2, rw h3, rw h4 end /- 2.3. Prove the same lemma again, this time using tactics. -/ lemma binomial_square₃ (a b : ℕ) : (a + b) * (a + b) = a * a + 2 * a * b + b * b := begin simp [two_mul, add_mul, mul_add], cc end /- ## Question 3 (**optional**): One-Point Rules 3.1 (**optional**). Prove that the following wrong formulation of the one-point rule for `∀` is inconsistent, using a structured proof. -/ axiom forall.one_point_wrong {α : Type} {t : α} {p : α → Prop} : (∀x : α, x = t ∧ p x) ↔ p t lemma proof_of_false : false := begin have wrong : (∀x, x = 0 ∧ true) ↔ true := @forall.one_point_wrong ℕ 0 (λ_, true), simp at wrong, have one_eq_zero : 1 = 0 := wrong 1, cc end /- 3.2 (**optional**). Prove that the following wrong formulation of the one-point rule for `∃` is inconsistent, using a tactical or structured proof. -/ axiom exists.one_point_wrong {α : Type} {t : α} {p : α → Prop} : (∃x : α, x = t → p x) ↔ p t lemma proof_of_false₂ : false := begin have wrong : (∃x, x ≠ 0) ↔ false := @exists.one_point_wrong ℕ 0 (λ_, false), simp at wrong, have one_eq_zero : 1 = 0 := wrong 1, cc end end LoVe
f8a44992fb4cecb0b75c8b0efe4257f7a552f125
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/data/option/basic.lean
12e348c731b3bccf08b3fd4c9058ddfaf15050c1
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
6,098
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import logic.basic data.bool data.option.defs tactic.basic namespace option variables {α : Type*} {β : Type*} {γ : Type*} @[simp] theorem get_mem : ∀ {o : option α} (h : is_some o), option.get h ∈ o | (some a) _ := rfl theorem get_of_mem {a : α} : ∀ {o : option α} (h : is_some o), a ∈ o → option.get h = a | _ _ rfl := rfl @[simp] lemma not_mem_none (a : α) : a ∉ (none : option α) := λ h, option.no_confusion h @[simp] lemma some_get : ∀ {x : option α} (h : is_some x), some (option.get h) = x | (some x) hx := rfl @[simp] lemma get_some (x : α) (h : is_some (some x)) : option.get h = x := rfl theorem mem_unique {o : option α} {a b : α} (ha : a ∈ o) (hb : b ∈ o) : a = b := option.some.inj $ ha.symm.trans hb theorem injective_some (α : Type*) : function.injective (@some α) := λ _ _, some_inj.mp /-- `option.map f` is injective if `f` is injective. -/ theorem injective_map {f : α → β} (Hf : function.injective f) : function.injective (option.map f) | none none H := rfl | (some a₁) (some a₂) H := by rw Hf (option.some.inj H) @[ext] theorem ext : ∀ {o₁ o₂ : option α}, (∀ a, a ∈ o₁ ↔ a ∈ o₂) → o₁ = o₂ | none none H := rfl | (some a) o H := ((H _).1 rfl).symm | o (some b) H := (H _).2 rfl theorem eq_none_iff_forall_not_mem {o : option α} : o = none ↔ (∀ a, a ∉ o) := ⟨λ e a h, by rw e at h; cases h, λ h, ext $ by simpa⟩ @[simp] theorem none_bind {α β} (f : α → option β) : none >>= f = none := rfl @[simp] theorem some_bind {α β} (a : α) (f : α → option β) : some a >>= f = f a := rfl @[simp] theorem none_bind' (f : α → option β) : none.bind f = none := rfl @[simp] theorem some_bind' (a : α) (f : α → option β) : (some a).bind f = f a := rfl @[simp] theorem bind_some : ∀ x : option α, x >>= some = x := @bind_pure α option _ _ @[simp] theorem bind_eq_some {α β} {x : option α} {f : α → option β} {b : β} : x >>= f = some b ↔ ∃ a, x = some a ∧ f a = some b := by cases x; simp @[simp] theorem bind_eq_some' {x : option α} {f : α → option β} {b : β} : x.bind f = some b ↔ ∃ a, x = some a ∧ f a = some b := by cases x; simp @[simp] theorem bind_eq_none' {o : option α} {f : α → option β} : o.bind f = none ↔ (∀ b a, a ∈ o → b ∉ f a) := by simp only [eq_none_iff_forall_not_mem, not_exists, not_and, mem_def, bind_eq_some'] @[simp] theorem bind_eq_none {α β} {o : option α} {f : α → option β} : o >>= f = none ↔ (∀ b a, a ∈ o → b ∉ f a) := bind_eq_none' lemma bind_comm {α β γ} {f : α → β → option γ} (a : option α) (b : option β) : a.bind (λx, b.bind (f x)) = b.bind (λy, a.bind (λx, f x y)) := by cases a; cases b; refl lemma bind_assoc (x : option α) (f : α → option β) (g : β → option γ) : (x.bind f).bind g = x.bind (λ y, (f y).bind g) := by cases x; refl @[simp] theorem map_none {α β} {f : α → β} : f <$> none = none := rfl @[simp] theorem map_some {α β} {a : α} {f : α → β} : f <$> some a = some (f a) := rfl @[simp] theorem map_none' {f : α → β} : option.map f none = none := rfl @[simp] theorem map_some' {a : α} {f : α → β} : option.map f (some a) = some (f a) := rfl @[simp] theorem map_eq_some {α β} {x : option α} {f : α → β} {b : β} : f <$> x = some b ↔ ∃ a, x = some a ∧ f a = b := by cases x; simp @[simp] theorem map_eq_some' {x : option α} {f : α → β} {b : β} : x.map f = some b ↔ ∃ a, x = some a ∧ f a = b := by cases x; simp @[simp] theorem map_id' : option.map (@id α) = id := map_id @[simp] theorem seq_some {α β} {a : α} {f : α → β} : some f <*> some a = some (f a) := rfl @[simp] theorem some_orelse' (a : α) (x : option α) : (some a).orelse x = some a := rfl @[simp] theorem some_orelse (a : α) (x : option α) : (some a <|> x) = some a := rfl @[simp] theorem none_orelse' (x : option α) : none.orelse x = x := by cases x; refl @[simp] theorem none_orelse (x : option α) : (none <|> x) = x := none_orelse' x @[simp] theorem orelse_none' (x : option α) : x.orelse none = x := by cases x; refl @[simp] theorem orelse_none (x : option α) : (x <|> none) = x := orelse_none' x @[simp] theorem is_some_none : @is_some α none = ff := rfl @[simp] theorem is_some_some {a : α} : is_some (some a) = tt := rfl theorem is_some_iff_exists {x : option α} : is_some x ↔ ∃ a, x = some a := by cases x; simp [is_some]; exact ⟨_, rfl⟩ @[simp] theorem is_none_none : @is_none α none = tt := rfl @[simp] theorem is_none_some {a : α} : is_none (some a) = ff := rfl @[simp] theorem not_is_some {a : option α} : is_some a = ff ↔ a.is_none = tt := by cases a; simp lemma eq_some_iff_get_eq {o : option α} {a : α} : o = some a ↔ ∃ h : o.is_some, option.get h = a := by cases o; simp lemma not_is_some_iff_eq_none {o : option α} : ¬o.is_some ↔ o = none := by cases o; simp lemma ne_none_iff_is_some {o : option α} : o ≠ none ↔ o.is_some := by cases o; simp theorem iget_mem [inhabited α] : ∀ {o : option α}, is_some o → o.iget ∈ o | (some a) _ := rfl theorem iget_of_mem [inhabited α] {a : α} : ∀ {o : option α}, a ∈ o → o.iget = a | _ rfl := rfl @[simp] theorem guard_eq_some {p : α → Prop} [decidable_pred p] {a b : α} : guard p a = some b ↔ a = b ∧ p a := by by_cases p a; simp [option.guard, h]; intro; contradiction @[simp] theorem guard_eq_some' {p : Prop} [decidable p] : ∀ u, _root_.guard p = some u ↔ p | () := by by_cases p; simp [guard, h, pure]; intro; contradiction theorem lift_or_get_choice {f : α → α → α} (h : ∀ a b, f a b = a ∨ f a b = b) : ∀ o₁ o₂, lift_or_get f o₁ o₂ = o₁ ∨ lift_or_get f o₁ o₂ = o₂ | none none := or.inl rfl | (some a) none := or.inl rfl | none (some b) := or.inr rfl | (some a) (some b) := by simpa [lift_or_get] using h a b end option
e90f5cf6441d6459f2b13a85af048eaf31b9fe97
618003631150032a5676f229d13a079ac875ff77
/src/algebra/field.lean
7be09b4a19fd8e188be5f9473badcae3e0795510
[ "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
15,970
lean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis, Leonardo de Moura, Johannes Hölzl, Mario Carneiro -/ import algebra.ring import algebra.group_with_zero open set set_option default_priority 100 -- see Note [default priority] set_option old_structure_cmd true universe u variables {α : Type u} @[protect_proj, ancestor ring has_inv] class division_ring (α : Type u) extends ring α, has_inv α := (mul_inv_cancel : ∀ {a : α}, a ≠ 0 → a * a⁻¹ = 1) (inv_mul_cancel : ∀ {a : α}, a ≠ 0 → a⁻¹ * a = 1) (inv_zero : (0 : α)⁻¹ = 0) (zero_ne_one : (0 : α) ≠ 1) section division_ring variables [division_ring α] {a b : α} instance division_ring.to_nonzero : nonzero α := ⟨division_ring.zero_ne_one⟩ protected definition algebra.div (a b : α) : α := a * b⁻¹ instance division_ring_has_div : has_div α := ⟨algebra.div⟩ lemma division_def (a b : α) : a / b = a * b⁻¹ := rfl @[simp] lemma mul_inv_cancel (h : a ≠ 0) : a * a⁻¹ = 1 := division_ring.mul_inv_cancel h @[simp] lemma inv_mul_cancel (h : a ≠ 0) : a⁻¹ * a = 1 := division_ring.inv_mul_cancel h @[simp] lemma one_div_eq_inv (a : α) : 1 / a = a⁻¹ := one_mul a⁻¹ @[field_simps] lemma inv_eq_one_div (a : α) : a⁻¹ = 1 / a := by simp /-- Every division ring is a `group_with_zero`. -/ @[priority 10] -- see Note [lower instance priority] instance division_ring.to_group_with_zero : group_with_zero α := { mul_inv_cancel := λ _, mul_inv_cancel, .. ‹division_ring α›, .. (by apply_instance : semiring α) } local attribute [simp] division_def mul_comm mul_assoc mul_left_comm mul_inv_cancel inv_mul_cancel lemma div_eq_mul_one_div (a b : α) : a / b = a * (1 / b) := by simp lemma mul_one_div_cancel (h : a ≠ 0) : a * (1 / a) = 1 := by simp [h] lemma one_div_mul_cancel (h : a ≠ 0) : (1 / a) * a = 1 := by simp [h] @[simp] lemma div_self (h : a ≠ 0) : a / a = 1 := by simp [h] lemma one_div_one : 1 / 1 = (1:α) := div_self (ne.symm zero_ne_one) theorem inv_one : (1⁻¹ : α) = 1 := by rw [inv_eq_one_div, one_div_one] lemma mul_div_assoc (a b c : α) : (a * b) / c = a * (b / c) := by simp @[field_simps] lemma mul_div_assoc' (a b c : α) : a * (b / c) = (a * b) / c := by simp [mul_div_assoc] lemma one_div_ne_zero (h : a ≠ 0) : 1 / a ≠ 0 := assume : 1 / a = 0, have 0 = (1:α), from eq.symm (by rw [← mul_one_div_cancel h, this, mul_zero]), absurd this zero_ne_one lemma ne_zero_of_one_div_ne_zero (h : 1 / a ≠ 0) : a ≠ 0 := assume ha : a = 0, begin rw [ha, div_zero] at h, contradiction end lemma inv_ne_zero (h : a ≠ 0) : a⁻¹ ≠ 0 := by rw inv_eq_one_div; exact one_div_ne_zero h lemma eq_zero_of_one_div_eq_zero (h : 1 / a = 0) : a = 0 := classical.by_cases (assume ha, ha) (assume ha, false.elim ((one_div_ne_zero ha) h)) lemma one_inv_eq : 1⁻¹ = (1:α) := calc 1⁻¹ = 1 * 1⁻¹ : by rw [one_mul] ... = (1:α) : by simp local attribute [simp] one_inv_eq lemma div_one (a : α) : a / 1 = a := by simp lemma zero_div (a : α) : 0 / a = 0 := by simp -- note: integral domain has a "mul_ne_zero". a commutative division ring is an integral -- domain, but let's not define that class for now. lemma division_ring.mul_ne_zero (ha : a ≠ 0) (hb : b ≠ 0) : a * b ≠ 0 := assume : a * b = 0, have a * 1 = 0, by rw [← mul_one_div_cancel hb, ← mul_assoc, this, zero_mul], have a = 0, by rwa mul_one at this, absurd this ha lemma mul_ne_zero_comm (h : a * b ≠ 0) : b * a ≠ 0 := have h₁ : a ≠ 0, from ne_zero_of_mul_ne_zero_right h, have h₂ : b ≠ 0, from ne_zero_of_mul_ne_zero_left h, division_ring.mul_ne_zero h₂ h₁ lemma eq_one_div_of_mul_eq_one (h : a * b = 1) : b = 1 / a := have a ≠ 0, from assume : a = 0, have 0 = (1:α), by rwa [this, zero_mul] at h, absurd this zero_ne_one, have b = (1 / a) * a * b, by rw [one_div_mul_cancel this, one_mul], show b = 1 / a, by rwa [mul_assoc, h, mul_one] at this lemma eq_one_div_of_mul_eq_one_left (h : b * a = 1) : b = 1 / a := have a ≠ 0, from assume : a = 0, have 0 = (1:α), by rwa [this, mul_zero] at h, absurd this zero_ne_one, by rw [← h, mul_div_assoc, div_self this, mul_one] lemma division_ring.one_div_mul_one_div : (1 / a) * (1 / b) = 1 / (b * a) := match classical.em (a = 0), classical.em (b = 0) with | or.inr ha, or.inr hb := have (b * a) * ((1 / a) * (1 / b)) = 1, by rw [mul_assoc, ← mul_assoc a, mul_one_div_cancel ha, one_mul, mul_one_div_cancel hb], eq_one_div_of_mul_eq_one this | or.inl ha, _ := by simp [ha] | _ , or.inl hb := by simp [hb] end lemma one_div_neg_one_eq_neg_one : (1:α) / (-1) = -1 := have (-1) * (-1) = (1:α), by rw [neg_mul_neg, one_mul], eq.symm (eq_one_div_of_mul_eq_one this) lemma one_div_neg_eq_neg_one_div (a : α) : 1 / (- a) = - (1 / a) := calc 1 / (- a) = 1 / ((-1) * a) : by rw neg_eq_neg_one_mul ... = (1 / a) * (1 / (- 1)) : by rw division_ring.one_div_mul_one_div ... = (1 / a) * (-1) : by rw one_div_neg_one_eq_neg_one ... = - (1 / a) : by rw [mul_neg_eq_neg_mul_symm, mul_one] lemma div_neg_eq_neg_div (a b : α) : b / (- a) = - (b / a) := calc b / (- a) = b * (1 / (- a)) : by rw [← inv_eq_one_div, division_def] ... = b * -(1 / a) : by rw one_div_neg_eq_neg_one_div ... = -(b * (1 / a)) : by rw neg_mul_eq_mul_neg ... = - (b * a⁻¹) : by rw inv_eq_one_div lemma neg_div (a b : α) : (-b) / a = - (b / a) := by rw [neg_eq_neg_one_mul, mul_div_assoc, ← neg_eq_neg_one_mul] @[field_simps] lemma neg_div' {α : Type*} [division_ring α] (a b : α) : - (b / a) = (-b) / a := by simp [neg_div] lemma neg_div_neg_eq (a b : α) : (-a) / (-b) = a / b := by rw [div_neg_eq_neg_div, neg_div, neg_neg] lemma one_div_one_div (a : α) : 1 / (1 / a) = a := match classical.em (a = 0) with | or.inl h := by simp [h] | or.inr h := eq.symm (eq_one_div_of_mul_eq_one_left (mul_one_div_cancel h)) end lemma inv_inv' (a : α) : a⁻¹⁻¹ = a := by rw [inv_eq_one_div, inv_eq_one_div, one_div_one_div] lemma eq_of_one_div_eq_one_div (h : 1 / a = 1 / b) : a = b := by rw [← one_div_one_div a, h,one_div_one_div] lemma mul_inv' (a b : α) : (b * a)⁻¹ = a⁻¹ * b⁻¹ := eq.symm $ calc a⁻¹ * b⁻¹ = (1 / a) * (1 / b) : by simp ... = (1 / (b * a)) : division_ring.one_div_mul_one_div ... = (b * a)⁻¹ : by simp lemma one_div_div (a b : α) : 1 / (a / b) = b / a := by rw [one_div_eq_inv, division_def, mul_inv', inv_inv', division_def] lemma div_helper (b : α) (h : a ≠ 0) : (1 / (a * b)) * a = 1 / b := by simp only [division_def, mul_inv', one_mul, mul_assoc, inv_mul_cancel h, mul_one] lemma mul_div_cancel (a : α) {b : α} (hb : b ≠ 0) : a * b / b = a := by simp [hb] lemma div_mul_cancel (a : α) {b : α} (hb : b ≠ 0) : a / b * b = a := by simp [hb] @[field_simps] lemma div_div_eq_mul_div (a b c : α) : a / (b / c) = (a * c) / b := by rw [div_eq_mul_one_div, one_div_div, ← mul_div_assoc] lemma div_mul_left (hb : b ≠ 0) : b / (a * b) = 1 / a := by simp only [division_def, mul_inv', ← mul_assoc, mul_inv_cancel hb] lemma mul_div_mul_right (a : α) (b : α) {c : α} (hc : c ≠ 0) : (a * c) / (b * c) = a / b := by rw [mul_div_assoc, div_mul_left hc, ← mul_div_assoc, mul_one] @[field_simps] lemma div_add_div_same (a b c : α) : a / c + b / c = (a + b) / c := eq.symm $ right_distrib a b (c⁻¹) lemma div_sub_div_same (a b c : α) : (a / c) - (b / c) = (a - b) / c := by rw [sub_eq_add_neg, ← neg_div, div_add_div_same, sub_eq_add_neg] lemma neg_inv : - a⁻¹ = (- a)⁻¹ := by rw [inv_eq_one_div, inv_eq_one_div, div_neg_eq_neg_div] lemma add_div (a b c : α) : (a + b) / c = a / c + b / c := (div_add_div_same _ _ _).symm lemma sub_div (a b c : α) : (a - b) / c = a / c - b / c := (div_sub_div_same _ _ _).symm lemma division_ring.inv_inj : a⁻¹ = b⁻¹ ↔ a = b := inv_inj'' _ _ lemma division_ring.inv_eq_iff : a⁻¹ = b ↔ b⁻¹ = a := inv_eq_iff lemma div_neg (a : α) : a / -b = -(a / b) := by rw [← div_neg_eq_neg_div] lemma inv_neg : (-a)⁻¹ = -(a⁻¹) := by rw neg_inv lemma one_div_mul_add_mul_one_div_eq_one_div_add_one_div (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (a + b) * (1 / b) = 1 / a + 1 / b := by rw [(left_distrib (1 / a)), (one_div_mul_cancel ha), right_distrib, one_mul, mul_assoc, (mul_one_div_cancel hb), mul_one, add_comm] lemma one_div_mul_sub_mul_one_div_eq_one_div_add_one_div (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (b - a) * (1 / b) = 1 / a - 1 / b := by rw [(mul_sub_left_distrib (1 / a)), (one_div_mul_cancel ha), mul_sub_right_distrib, one_mul, mul_assoc, (mul_one_div_cancel hb), mul_one] lemma div_eq_one_iff_eq (a : α) {b : α} (hb : b ≠ 0) : a / b = 1 ↔ a = b := iff.intro (assume : a / b = 1, calc a = a / b * b : by simp [hb] ... = 1 * b : by rw this ... = b : by simp) (assume : a = b, by simp [this, hb]) lemma eq_of_div_eq_one (a : α) {b : α} (Hb : b ≠ 0) : a / b = 1 → a = b := iff.mp $ div_eq_one_iff_eq a Hb lemma eq_div_iff_mul_eq (a b : α) {c : α} (hc : c ≠ 0) : a = b / c ↔ a * c = b := iff.intro (assume : a = b / c, by rw [this, (div_mul_cancel _ hc)]) (assume : a * c = b, by rw [← this, mul_div_cancel _ hc]) lemma eq_div_of_mul_eq (a b : α) {c : α} (hc : c ≠ 0) : a * c = b → a = b / c := iff.mpr $ eq_div_iff_mul_eq a b hc lemma mul_eq_of_eq_div (a b: α) {c : α} (hc : c ≠ 0) : a = b / c → a * c = b := iff.mp $ eq_div_iff_mul_eq a b hc lemma add_div_eq_mul_add_div (a b : α) {c : α} (hc : c ≠ 0) : a + b / c = (a * c + b) / c := have (a + b / c) * c = a * c + b, by rw [right_distrib, (div_mul_cancel _ hc)], (iff.mpr (eq_div_iff_mul_eq _ _ hc)) this lemma mul_mul_div (a : α) {c : α} (hc : c ≠ 0) : a = a * c * (1 / c) := by simp [hc] lemma eq_of_mul_eq_mul_of_nonzero_left {a b c : α} (h : a ≠ 0) (h₂ : a * b = a * c) : b = c := by rw [← one_mul b, ← inv_mul_cancel h, mul_assoc, h₂, ← mul_assoc, inv_mul_cancel h, one_mul] lemma eq_of_mul_eq_mul_of_nonzero_right {a b c : α} (h : c ≠ 0) (h2 : a * c = b * c) : a = b := by rw [← mul_one a, ← mul_inv_cancel h, ← mul_assoc, h2, mul_assoc, mul_inv_cancel h, mul_one] instance division_ring.to_domain : domain α := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, classical.by_contradiction $ λ hn, division_ring.mul_ne_zero (mt or.inl hn) (mt or.inr hn) h ..‹division_ring α›, ..(by apply_instance : semiring α) } end division_ring @[protect_proj, ancestor division_ring comm_ring] class field (α : Type u) extends comm_ring α, has_inv α := (mul_inv_cancel : ∀ {a : α}, a ≠ 0 → a * a⁻¹ = 1) (inv_zero : (0 : α)⁻¹ = 0) (zero_ne_one : (0 : α) ≠ 1) section field variable [field α] instance field.to_division_ring : division_ring α := { inv_mul_cancel := λ _ h, by rw [mul_comm, field.mul_inv_cancel h] ..show field α, by apply_instance } lemma one_div_mul_one_div (a b : α) : (1 / a) * (1 / b) = 1 / (a * b) := by rw [division_ring.one_div_mul_one_div, mul_comm b] lemma div_mul_right {a : α} (b : α) (ha : a ≠ 0) : a / (a * b) = 1 / b := by rw [mul_comm, div_mul_left ha] lemma mul_div_cancel_left {a : α} (b : α) (ha : a ≠ 0) : a * b / a = b := by rw [mul_comm a, (mul_div_cancel _ ha)] lemma mul_div_cancel' (a : α) {b : α} (hb : b ≠ 0) : b * (a / b) = a := by rw [mul_comm, (div_mul_cancel _ hb)] lemma one_div_add_one_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : 1 / a + 1 / b = (a + b) / (a * b) := by rw [add_comm, ← div_mul_left ha, ← div_mul_right _ hb, division_def, division_def, division_def, ← right_distrib, mul_comm a] local attribute [simp] mul_assoc mul_comm mul_left_comm lemma div_mul_div (a b c d : α) : (a / b) * (c / d) = (a * c) / (b * d) := begin simp [division_def], rw [mul_inv', mul_comm d⁻¹] end lemma mul_div_mul_left (a b : α) {c : α} (hc : c ≠ 0) : (c * a) / (c * b) = a / b := by rw [← div_mul_div, div_self hc, one_mul] @[field_simps] lemma div_mul_eq_mul_div (a b c : α) : (b / c) * a = (b * a) / c := by simp [division_def] lemma div_mul_eq_mul_div_comm (a b c : α) : (b / c) * a = b * (a / c) := by rw [div_mul_eq_mul_div, ← one_mul c, ← div_mul_div, div_one, one_mul] lemma div_add_div (a : α) {b : α} (c : α) {d : α} (hb : b ≠ 0) (hd : d ≠ 0) : (a / b) + (c / d) = ((a * d) + (b * c)) / (b * d) := by rw [← mul_div_mul_right _ b hd, ← mul_div_mul_left c d hb, div_add_div_same] @[field_simps] lemma div_sub_div (a : α) {b : α} (c : α) {d : α} (hb : b ≠ 0) (hd : d ≠ 0) : (a / b) - (c / d) = ((a * d) - (b * c)) / (b * d) := begin simp [sub_eq_add_neg], rw [neg_eq_neg_one_mul, ← mul_div_assoc, div_add_div _ _ hb hd, ← mul_assoc, mul_comm b, mul_assoc, ← neg_eq_neg_one_mul] end lemma mul_eq_mul_of_div_eq_div (a : α) {b : α} (c : α) {d : α} (hb : b ≠ 0) (hd : d ≠ 0) (h : a / b = c / d) : a * d = c * b := by rw [← mul_one (a*d), mul_assoc, mul_comm d, ← mul_assoc, ← div_self hb, ← div_mul_eq_mul_div_comm, h, div_mul_eq_mul_div, div_mul_cancel _ hd] @[field_simps] lemma div_div_eq_div_mul (a b c : α) : (a / b) / c = a / (b * c) := by rw [div_eq_mul_one_div, div_mul_div, mul_one] lemma div_div_div_div_eq (a : α) {b c d : α} : (a / b) / (c / d) = (a * d) / (b * c) := by rw [div_div_eq_mul_div, div_mul_eq_mul_div, div_div_eq_div_mul] lemma div_mul_eq_div_mul_one_div (a b c : α) : a / (b * c) = (a / b) * (1 / c) := by rw [← div_div_eq_div_mul, ← div_eq_mul_one_div] lemma inv_add_inv {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ + b⁻¹ = (a + b) / (a * b) := by rw [inv_eq_one_div, inv_eq_one_div, one_div_add_one_div ha hb] lemma inv_sub_inv {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ - b⁻¹ = (b - a) / (a * b) := by rw [inv_eq_one_div, inv_eq_one_div, div_sub_div _ _ ha hb, one_mul, mul_one] @[field_simps] lemma add_div' (a b c : α) (hc : c ≠ 0) : b + a / c = (b * c + a) / c := by simpa using div_add_div b a one_ne_zero hc @[field_simps] lemma sub_div' (a b c : α) (hc : c ≠ 0) : b - a / c = (b * c - a) / c := by simpa using div_sub_div b a one_ne_zero hc @[field_simps] lemma div_add' (a b c : α) (hc : c ≠ 0) : a / c + b = (a + b * c) / c := by rwa [add_comm, add_div', add_comm] @[field_simps] lemma div_sub' (a b c : α) (hc : c ≠ 0) : a / c - b = (a - c * b) / c := by simpa using div_sub_div a b hc one_ne_zero /-- Every field is a `comm_group_with_zero`. -/ instance field.to_comm_group_with_zero : comm_group_with_zero α := { .. (_ : group_with_zero α), .. ‹field α› } @[priority 100] -- see Note [lower instance priority] instance field.to_integral_domain : integral_domain α := { ..‹field α›, ..division_ring.to_domain } end field namespace ring_hom section variables {β : Type*} [division_ring α] [division_ring β] (f : α →+* β) {x y : α} lemma map_ne_zero : f x ≠ 0 ↔ x ≠ 0 := ⟨mt $ λ h, h.symm ▸ f.map_zero, λ x0 h, one_ne_zero $ by rw [← f.map_one, ← mul_inv_cancel x0, f.map_mul, h, zero_mul]⟩ lemma map_eq_zero : f x = 0 ↔ x = 0 := by haveI := classical.dec; exact not_iff_not.1 f.map_ne_zero lemma map_inv : f x⁻¹ = (f x)⁻¹ := begin classical, by_cases h : x = 0, by simp [h], apply (domain.mul_right_inj (f.map_ne_zero.2 h)).1, rw [mul_inv_cancel (f.map_ne_zero.2 h), ← f.map_mul, mul_inv_cancel h, f.map_one] end lemma map_div : f (x / y) = f x / f y := (f.map_mul _ _).trans $ congr_arg _ $ f.map_inv lemma injective : function.injective f := f.injective_iff.2 (λ a ha, classical.by_contradiction $ λ ha0, by simpa [ha, f.map_mul, f.map_one, zero_ne_one] using congr_arg f (mul_inv_cancel ha0)) end end ring_hom
c23fd23a04076c5f55296bc6e1d2603e1bab8a5d
5749d8999a76f3a8fddceca1f6941981e33aaa96
/src/topology/metric_space/closeds.lean
61a33a326bb6355c6ca56979abb4ac32f07a6602
[ "Apache-2.0" ]
permissive
jdsalchow/mathlib
13ab43ef0d0515a17e550b16d09bd14b76125276
497e692b946d93906900bb33a51fd243e7649406
refs/heads/master
1,585,819,143,348
1,580,072,892,000
1,580,072,892,000
154,287,128
0
0
Apache-2.0
1,540,281,610,000
1,540,281,609,000
null
UTF-8
Lean
false
false
22,441
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sébastien Gouëzel -/ import topology.metric_space.hausdorff_distance topology.opens analysis.specific_limits /-! # Closed subsets This file defines the metric and emetric space structure on the types of closed subsets and nonempty compact subsets of a metric or emetric space. The Hausdorff distance induces an emetric space structure on the type of closed subsets of an emetric space, called `closeds`. Its completeness, resp. compactness, resp. second-countability, follow from the corresponding properties of the original space. In a metric space, the type of nonempty compact subsets (called `nonempty_compacts`) also inherits a metric space structure from the Hausdorff distance, as the Hausdorff edistance is always finite in this context. -/ noncomputable theory open_locale classical open_locale topological_space universe u open classical lattice set function topological_space filter namespace emetric section variables {α : Type u} [emetric_space α] {s : set α} /-- In emetric spaces, the Hausdorff edistance defines an emetric space structure on the type of closed subsets -/ instance closeds.emetric_space : emetric_space (closeds α) := { edist := λs t, Hausdorff_edist s.val t.val, edist_self := λs, Hausdorff_edist_self, edist_comm := λs t, Hausdorff_edist_comm, edist_triangle := λs t u, Hausdorff_edist_triangle, eq_of_edist_eq_zero := λs t h, subtype.eq ((Hausdorff_edist_zero_iff_eq_of_closed s.property t.property).1 h) } /-- The edistance to a closed set depends continuously on the point and the set -/ lemma continuous_inf_edist_Hausdorff_edist : continuous (λp : α × (closeds α), inf_edist p.1 (p.2).val) := begin refine continuous_of_le_add_edist 2 (by simp) _, rintros ⟨x, s⟩ ⟨y, t⟩, calc inf_edist x (s.val) ≤ inf_edist x (t.val) + Hausdorff_edist (t.val) (s.val) : inf_edist_le_inf_edist_add_Hausdorff_edist ... ≤ (inf_edist y (t.val) + edist x y) + Hausdorff_edist (t.val) (s.val) : add_le_add_right' inf_edist_le_inf_edist_add_edist ... = inf_edist y (t.val) + (edist x y + Hausdorff_edist (s.val) (t.val)) : by simp [add_comm, Hausdorff_edist_comm] ... ≤ inf_edist y (t.val) + (edist (x, s) (y, t) + edist (x, s) (y, t)) : add_le_add_left' (add_le_add' (by simp [edist, le_refl]) (by simp [edist, le_refl])) ... = inf_edist y (t.val) + 2 * edist (x, s) (y, t) : by rw [← mul_two, mul_comm] end /-- Subsets of a given closed subset form a closed set -/ lemma is_closed_subsets_of_is_closed (hs : is_closed s) : is_closed {t : closeds α | t.val ⊆ s} := begin refine is_closed_of_closure_subset (λt ht x hx, _), -- t : closeds α, ht : t ∈ closure {t : closeds α | t.val ⊆ s}, -- x : α, hx : x ∈ t.val -- goal : x ∈ s have : x ∈ closure s, { refine mem_closure_iff'.2 (λε εpos, _), rcases mem_closure_iff'.1 ht ε εpos with ⟨u, hu, Dtu⟩, -- u : closeds α, hu : u ∈ {t : closeds α | t.val ⊆ s}, hu' : edist t u < ε rcases exists_edist_lt_of_Hausdorff_edist_lt hx Dtu with ⟨y, hy, Dxy⟩, -- y : α, hy : y ∈ u.val, Dxy : edist x y < ε exact ⟨y, hu hy, Dxy⟩ }, rwa closure_eq_of_is_closed hs at this, end /-- By definition, the edistance on `closeds α` is given by the Hausdorff edistance -/ lemma closeds.edist_eq {s t : closeds α} : edist s t = Hausdorff_edist s.val t.val := rfl /-- In a complete space, the type of closed subsets is complete for the Hausdorff edistance. -/ instance closeds.complete_space [complete_space α] : complete_space (closeds α) := begin /- We will show that, if a sequence of sets `s n` satisfies `edist (s n) (s (n+1)) < 2^{-n}`, then it converges. This is enough to guarantee completeness, by a standard completeness criterion. We use the shorthand `B n = 2^{-n}` in ennreal. -/ let B : ℕ → ennreal := λ n, (2⁻¹)^n, have B_pos : ∀ n, (0:ennreal) < B n, by simp [B, ennreal.pow_pos], have B_ne_top : ∀ n, B n ≠ ⊤, by simp [B, ennreal.div_def, ennreal.pow_ne_top], /- Consider a sequence of closed sets `s n` with `edist (s n) (s (n+1)) < B n`. We will show that it converges. The limit set is t0 = ⋂n, closure (⋃m≥n, s m). We will have to show that a point in `s n` is close to a point in `t0`, and a point in `t0` is close to a point in `s n`. The completeness then follows from a standard criterion. -/ refine complete_of_convergent_controlled_sequences B B_pos (λs hs, _), let t0 := ⋂n, closure (⋃m≥n, (s m).val), let t : closeds α := ⟨t0, is_closed_Inter (λ_, is_closed_closure)⟩, use t, -- The inequality is written this way to agree with `edist_le_of_edist_le_geometric_of_tendsto₀` have I1 : ∀n:ℕ, ∀x ∈ (s n).val, ∃y ∈ t0, edist x y ≤ 2 * B n, { /- This is the main difficulty of the proof. Starting from `x ∈ s n`, we want to find a point in `t0` which is close to `x`. Define inductively a sequence of points `z m` with `z n = x` and `z m ∈ s m` and `edist (z m) (z (m+1)) ≤ B m`. This is possible since the Hausdorff distance between `s m` and `s (m+1)` is at most `B m`. This sequence is a Cauchy sequence, therefore converging as the space is complete, to a limit which satisfies the required properties. -/ assume n x hx, obtain ⟨z, hz₀, hz⟩ : ∃ z : Π l, (s (n+l)).val, (z 0:α) = x ∧ ∀ k, edist (z k:α) (z (k+1):α) ≤ B n / 2^k, { -- We prove existence of the sequence by induction. have : ∀ (l : ℕ) (z : (s (n+l)).val), ∃ z' : (s (n+l+1)).val, edist (z:α) z' ≤ B n / 2^l, { assume l z, obtain ⟨z', z'_mem, hz'⟩ : ∃ z' ∈ (s (n+l+1)).val, edist (z:α) z' < B n / 2^l, { apply exists_edist_lt_of_Hausdorff_edist_lt z.2, simp only [B, ennreal.div_def, ennreal.inv_pow'], rw [← pow_add], apply hs; simp }, exact ⟨⟨z', z'_mem⟩, le_of_lt hz'⟩ }, use [λ k, nat.rec_on k ⟨x, hx⟩ (λl z, some (this l z)), rfl], exact λ k, some_spec (this k _) }, -- it follows from the previous bound that `z` is a Cauchy sequence have : cauchy_seq (λ k, ((z k):α)), from cauchy_seq_of_edist_le_geometric_two (B n) (B_ne_top n) hz, -- therefore, it converges rcases cauchy_seq_tendsto_of_complete this with ⟨y, y_lim⟩, use y, -- the limit point `y` will be the desired point, in `t0` and close to our initial point `x`. -- First, we check it belongs to `t0`. have : y ∈ t0 := mem_Inter.2 (λk, mem_closure_of_tendsto (by simp) y_lim begin simp only [exists_prop, set.mem_Union, filter.mem_at_top_sets, set.mem_preimage, set.preimage_Union], exact ⟨k, λ m hm, ⟨n+m, zero_add k ▸ add_le_add (zero_le n) hm, (z m).2⟩⟩ end), use this, -- Then, we check that `y` is close to `x = z n`. This follows from the fact that `y` -- is the limit of `z k`, and the distance between `z n` and `z k` has already been estimated. rw [← hz₀], exact edist_le_of_edist_le_geometric_two_of_tendsto₀ (B n) hz y_lim }, have I2 : ∀n:ℕ, ∀x ∈ t0, ∃y ∈ (s n).val, edist x y ≤ 2 * B n, { /- For the (much easier) reverse inequality, we start from a point `x ∈ t0` and we want to find a point `y ∈ s n` which is close to `x`. `x` belongs to `t0`, the intersection of the closures. In particular, it is well approximated by a point `z` in `⋃m≥n, s m`, say in `s m`. Since `s m` and `s n` are close, this point is itself well approximated by a point `y` in `s n`, as required. -/ assume n x xt0, have : x ∈ closure (⋃m≥n, (s m).val), by apply mem_Inter.1 xt0 n, rcases mem_closure_iff'.1 this (B n) (B_pos n) with ⟨z, hz, Dxz⟩, -- z : α, Dxz : edist x z < B n, simp only [exists_prop, set.mem_Union] at hz, rcases hz with ⟨m, ⟨m_ge_n, hm⟩⟩, -- m : ℕ, m_ge_n : m ≥ n, hm : z ∈ (s m).val have : Hausdorff_edist (s m).val (s n).val < B n := hs n m n m_ge_n (le_refl n), rcases exists_edist_lt_of_Hausdorff_edist_lt hm this with ⟨y, hy, Dzy⟩, -- y : α, hy : y ∈ (s n).val, Dzy : edist z y < B n exact ⟨y, hy, calc edist x y ≤ edist x z + edist z y : edist_triangle _ _ _ ... ≤ B n + B n : add_le_add' (le_of_lt Dxz) (le_of_lt Dzy) ... = 2 * B n : (two_mul _).symm ⟩ }, -- Deduce from the above inequalities that the distance between `s n` and `t0` is at most `2 B n`. have main : ∀n:ℕ, edist (s n) t ≤ 2 * B n := λn, Hausdorff_edist_le_of_mem_edist (I1 n) (I2 n), -- from this, the convergence of `s n` to `t0` follows. refine (tendsto_at_top _).2 (λε εpos, _), have : tendsto (λn, 2 * B n) at_top (𝓝 (2 * 0)), from ennreal.tendsto.const_mul (ennreal.tendsto_pow_at_top_nhds_0_of_lt_1 $ by simp [ennreal.one_lt_two]) (or.inr $ by simp), rw mul_zero at this, have Z := (tendsto_order.1 this).2 ε εpos, simp only [filter.mem_at_top_sets, set.mem_set_of_eq] at Z, rcases Z with ⟨N, hN⟩, -- ∀ (b : ℕ), b ≥ N → ε > 2 * B b exact ⟨N, λn hn, lt_of_le_of_lt (main n) (hN n hn)⟩ end /-- In a compact space, the type of closed subsets is compact. -/ instance closeds.compact_space [compact_space α] : compact_space (closeds α) := ⟨begin /- by completeness, it suffices to show that it is totally bounded, i.e., for all ε>0, there is a finite set which is ε-dense. start from a set `s` which is ε-dense in α. Then the subsets of `s` are finitely many, and ε-dense for the Hausdorff distance. -/ refine compact_of_totally_bounded_is_closed (emetric.totally_bounded_iff.2 (λε εpos, _)) is_closed_univ, rcases dense εpos with ⟨δ, δpos, δlt⟩, rcases emetric.totally_bounded_iff.1 (compact_iff_totally_bounded_complete.1 (@compact_univ α _ _)).1 δ δpos with ⟨s, fs, hs⟩, -- s : set α, fs : finite s, hs : univ ⊆ ⋃ (y : α) (H : y ∈ s), eball y δ -- we first show that any set is well approximated by a subset of `s`. have main : ∀ u : set α, ∃v ⊆ s, Hausdorff_edist u v ≤ δ, { assume u, let v := {x : α | x ∈ s ∧ ∃y∈u, edist x y < δ}, existsi [v, ((λx hx, hx.1) : v ⊆ s)], refine Hausdorff_edist_le_of_mem_edist _ _, { assume x hx, have : x ∈ ⋃y ∈ s, ball y δ := hs (by simp), rcases mem_bUnion_iff.1 this with ⟨y, ys, dy⟩, have : edist y x < δ := by simp at dy; rwa [edist_comm] at dy, exact ⟨y, ⟨ys, ⟨x, hx, this⟩⟩, le_of_lt dy⟩ }, { rintros x ⟨hx1, ⟨y, yu, hy⟩⟩, exact ⟨y, yu, le_of_lt hy⟩ }}, -- introduce the set F of all subsets of `s` (seen as members of `closeds α`). let F := {f : closeds α | f.val ⊆ s}, use F, split, -- `F` is finite { apply @finite_of_finite_image _ _ F (λf, f.val), { apply set.inj_on_of_injective, simp [subtype.val_injective] }, { refine finite_subset (finite_subsets_of_finite fs) (λb, _), simp only [and_imp, set.mem_image, set.mem_set_of_eq, exists_imp_distrib], assume x hx hx', rwa hx' at hx }}, -- `F` is ε-dense { assume u _, rcases main u.val with ⟨t0, t0s, Dut0⟩, have : is_closed t0 := closed_of_compact _ (finite_subset fs t0s).compact, let t : closeds α := ⟨t0, this⟩, have : t ∈ F := t0s, have : edist u t < ε := lt_of_le_of_lt Dut0 δlt, apply mem_bUnion_iff.2, exact ⟨t, ‹t ∈ F›, this⟩ } end⟩ /-- In an emetric space, the type of non-empty compact subsets is an emetric space, where the edistance is the Hausdorff edistance -/ instance nonempty_compacts.emetric_space : emetric_space (nonempty_compacts α) := { edist := λs t, Hausdorff_edist s.val t.val, edist_self := λs, Hausdorff_edist_self, edist_comm := λs t, Hausdorff_edist_comm, edist_triangle := λs t u, Hausdorff_edist_triangle, eq_of_edist_eq_zero := λs t h, subtype.eq $ begin have : closure (s.val) = closure (t.val) := Hausdorff_edist_zero_iff_closure_eq_closure.1 h, rwa [closure_eq_iff_is_closed.2 (closed_of_compact _ s.property.2), closure_eq_iff_is_closed.2 (closed_of_compact _ t.property.2)] at this, end } /-- `nonempty_compacts.to_closeds` is a uniform embedding (as it is an isometry) -/ lemma nonempty_compacts.to_closeds.uniform_embedding : uniform_embedding (@nonempty_compacts.to_closeds α _ _) := isometry.uniform_embedding $ λx y, rfl /-- The range of `nonempty_compacts.to_closeds` is closed in a complete space -/ lemma nonempty_compacts.is_closed_in_closeds [complete_space α] : is_closed (nonempty_compacts.to_closeds '' (univ : set (nonempty_compacts α))) := begin have : nonempty_compacts.to_closeds '' univ = {s : closeds α | s.val ≠ ∅ ∧ compact s.val}, { ext, simp only [set.image_univ, set.mem_range, ne.def, set.mem_set_of_eq], split, { rintros ⟨y, hy⟩, have : x.val = y.val := by rcases hy; simp, rw this, exact y.property }, { rintros ⟨hx1, hx2⟩, existsi (⟨x.val, ⟨hx1, hx2⟩⟩ : nonempty_compacts α), apply subtype.eq, refl }}, rw this, refine is_closed_of_closure_subset (λs hs, _), split, { -- take a set set t which is nonempty and at distance at most 1 of s rcases mem_closure_iff'.1 hs 1 ennreal.zero_lt_one with ⟨t, ht, Dst⟩, rw edist_comm at Dst, -- this set t contains a point x rcases ne_empty_iff_exists_mem.1 ht.1 with ⟨x, hx⟩, -- by the Hausdorff distance control, this point x is at distance at most 1 -- of a point y in s rcases exists_edist_lt_of_Hausdorff_edist_lt hx Dst with ⟨y, hy, _⟩, -- this shows that s is not empty exact ne_empty_of_mem hy }, { refine compact_iff_totally_bounded_complete.2 ⟨_, is_complete_of_is_closed s.property⟩, refine totally_bounded_iff.2 (λε εpos, _), -- we have to show that s is covered by finitely many eballs of radius ε -- pick a nonempty compact set t at distance at most ε/2 of s rcases mem_closure_iff'.1 hs (ε/2) (ennreal.half_pos εpos) with ⟨t, ht, Dst⟩, -- cover this space with finitely many balls of radius ε/2 rcases totally_bounded_iff.1 (compact_iff_totally_bounded_complete.1 ht.2).1 (ε/2) (ennreal.half_pos εpos) with ⟨u, fu, ut⟩, refine ⟨u, ⟨fu, λx hx, _⟩⟩, -- u : set α, fu : finite u, ut : t.val ⊆ ⋃ (y : α) (H : y ∈ u), eball y (ε / 2) -- then s is covered by the union of the balls centered at u of radius ε rcases exists_edist_lt_of_Hausdorff_edist_lt hx Dst with ⟨z, hz, Dxz⟩, rcases mem_bUnion_iff.1 (ut hz) with ⟨y, hy, Dzy⟩, have : edist x y < ε := calc edist x y ≤ edist x z + edist z y : edist_triangle _ _ _ ... < ε/2 + ε/2 : ennreal.add_lt_add Dxz Dzy ... = ε : ennreal.add_halves _, exact mem_bUnion hy this }, end /-- In a complete space, the type of nonempty compact subsets is complete. This follows from the same statement for closed subsets -/ instance nonempty_compacts.complete_space [complete_space α] : complete_space (nonempty_compacts α) := begin apply complete_space_of_is_complete_univ, apply (is_complete_image_iff nonempty_compacts.to_closeds.uniform_embedding).1, apply is_complete_of_is_closed, exact nonempty_compacts.is_closed_in_closeds end /-- In a compact space, the type of nonempty compact subsets is compact. This follows from the same statement for closed subsets -/ instance nonempty_compacts.compact_space [compact_space α] : compact_space (nonempty_compacts α) := ⟨begin rw embedding.compact_iff_compact_image nonempty_compacts.to_closeds.uniform_embedding.embedding, exact nonempty_compacts.is_closed_in_closeds.compact end⟩ /-- In a second countable space, the type of nonempty compact subsets is second countable -/ instance nonempty_compacts.second_countable_topology [second_countable_topology α] : second_countable_topology (nonempty_compacts α) := begin haveI : separable_space (nonempty_compacts α) := begin /- To obtain a countable dense subset of `nonempty_compacts α`, start from a countable dense subset `s` of α, and then consider all its finite nonempty subsets. This set is countable and made of nonempty compact sets. It turns out to be dense: by total boundedness, any compact set `t` can be covered by finitely many small balls, and approximations in `s` of the centers of these balls give the required finite approximation of `t`. -/ have : separable_space α := by apply_instance, rcases this.exists_countable_closure_eq_univ with ⟨s, cs, s_dense⟩, let v0 := {t : set α | finite t ∧ t ⊆ s}, let v : set (nonempty_compacts α) := {t : nonempty_compacts α | t.val ∈ v0}, refine ⟨⟨v, ⟨_, _⟩⟩⟩, { have : countable (subtype.val '' v), { refine countable_subset (λx hx, _) (countable_set_of_finite_subset cs), rcases (mem_image _ _ _).1 hx with ⟨y, ⟨hy, yx⟩⟩, rw ← yx, exact hy }, apply countable_of_injective_of_countable_image _ this, apply inj_on_of_inj_on_of_subset (injective_iff_inj_on_univ.1 subtype.val_injective) (subset_univ _) }, { refine subset.antisymm (subset_univ _) (λt ht, mem_closure_iff'.2 (λε εpos, _)), -- t is a compact nonempty set, that we have to approximate uniformly by a a set in `v`. rcases dense εpos with ⟨δ, δpos, δlt⟩, -- construct a map F associating to a point in α an approximating point in s, up to δ/2. have Exy : ∀x, ∃y, y ∈ s ∧ edist x y < δ/2, { assume x, have : x ∈ closure s := by rw s_dense; exact mem_univ _, rcases mem_closure_iff'.1 this (δ/2) (ennreal.half_pos δpos) with ⟨y, ys, hy⟩, exact ⟨y, ⟨ys, hy⟩⟩ }, let F := λx, some (Exy x), have Fspec : ∀x, F x ∈ s ∧ edist x (F x) < δ/2 := λx, some_spec (Exy x), -- cover `t` with finitely many balls. Their centers form a set `a` have : totally_bounded t.val := (compact_iff_totally_bounded_complete.1 t.property.2).1, rcases totally_bounded_iff.1 this (δ/2) (ennreal.half_pos δpos) with ⟨a, af, ta⟩, -- a : set α, af : finite a, ta : t.val ⊆ ⋃ (y : α) (H : y ∈ a), eball y (δ / 2) -- replace each center by a nearby approximation in `s`, giving a new set `b` let b := F '' a, have : finite b := finite_image _ af, have tb : ∀x ∈ t.val, ∃y ∈ b, edist x y < δ, { assume x hx, rcases mem_bUnion_iff.1 (ta hx) with ⟨z, za, Dxz⟩, existsi [F z, mem_image_of_mem _ za], calc edist x (F z) ≤ edist x z + edist z (F z) : edist_triangle _ _ _ ... < δ/2 + δ/2 : ennreal.add_lt_add Dxz (Fspec z).2 ... = δ : ennreal.add_halves _ }, -- keep only the points in `b` that are close to point in `t`, yielding a new set `c` let c := {y ∈ b | ∃x∈t.val, edist x y < δ}, have : finite c := finite_subset ‹finite b› (λx hx, hx.1), -- points in `t` are well approximated by points in `c` have tc : ∀x ∈ t.val, ∃y ∈ c, edist x y ≤ δ, { assume x hx, rcases tb x hx with ⟨y, yv, Dxy⟩, have : y ∈ c := by simp [c, -mem_image]; exact ⟨yv, ⟨x, hx, Dxy⟩⟩, exact ⟨y, this, le_of_lt Dxy⟩ }, -- points in `c` are well approximated by points in `t` have ct : ∀y ∈ c, ∃x ∈ t.val, edist y x ≤ δ, { rintros y ⟨hy1, ⟨x, xt, Dyx⟩⟩, have : edist y x ≤ δ := calc edist y x = edist x y : edist_comm _ _ ... ≤ δ : le_of_lt Dyx, exact ⟨x, xt, this⟩ }, -- it follows that their Hausdorff distance is small have : Hausdorff_edist t.val c ≤ δ := Hausdorff_edist_le_of_mem_edist tc ct, have Dtc : Hausdorff_edist t.val c < ε := lt_of_le_of_lt this δlt, -- the set `c` is not empty, as it is well approximated by a nonempty set have : c ≠ ∅, { by_contradiction h, simp only [not_not, ne.def] at h, rw [h, Hausdorff_edist_empty t.property.1] at Dtc, exact not_top_lt Dtc }, -- let `d` be the version of `c` in the type `nonempty_compacts α` let d : nonempty_compacts α := ⟨c, ⟨‹c ≠ ∅›, ‹finite c›.compact⟩⟩, have : c ⊆ s, { assume x hx, rcases (mem_image _ _ _).1 hx.1 with ⟨y, ⟨ya, yx⟩⟩, rw ← yx, exact (Fspec y).1 }, have : d ∈ v := ⟨‹finite c›, this⟩, -- we have proved that `d` is a good approximation of `t` as requested exact ⟨d, ‹d ∈ v›, Dtc⟩ }, end, apply second_countable_of_separable, end end --section end emetric --namespace namespace metric section variables {α : Type u} [metric_space α] /-- `nonempty_compacts α` inherits a metric space structure, as the Hausdorff edistance between two such sets is finite. -/ instance nonempty_compacts.metric_space : metric_space (nonempty_compacts α) := emetric_space.to_metric_space $ λx y, Hausdorff_edist_ne_top_of_ne_empty_of_bounded x.2.1 y.2.1 (bounded_of_compact x.2.2) (bounded_of_compact y.2.2) /-- The distance on `nonempty_compacts α` is the Hausdorff distance, by construction -/ lemma nonempty_compacts.dist_eq {x y : nonempty_compacts α} : dist x y = Hausdorff_dist x.val y.val := rfl lemma lipschitz_inf_dist_set (x : α) : lipschitz_with 1 (λ s : nonempty_compacts α, inf_dist x s.val) := lipschitz_with.one_of_le_add $ assume s t, by { rw dist_comm, exact inf_dist_le_inf_dist_add_Hausdorff_dist (edist_ne_top t s) } lemma lipschitz_inf_dist : lipschitz_with 2 (λ p : α × (nonempty_compacts α), inf_dist p.1 p.2.val) := @lipschitz_with.uncurry' _ _ _ _ _ _ (λ (x : α) (s : nonempty_compacts α), inf_dist x s.val) 1 1 (λ s, lipschitz_inf_dist_pt s.val) lipschitz_inf_dist_set lemma uniform_continuous_inf_dist_Hausdorff_dist : uniform_continuous (λp : α × (nonempty_compacts α), inf_dist p.1 (p.2).val) := lipschitz_inf_dist.to_uniform_continuous end --section end metric --namespace
19244aa2366dadec868d40755a86c5b47e36db0c
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/currying.lean
37780cb02fed101c4c7b298995138d6dc2fbc6fc
[ "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,945
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.products.bifunctor /-! # Curry and uncurry, as functors. We define `curry : ((C × D) ⥤ E) ⥤ (C ⥤ (D ⥤ E))` and `uncurry : (C ⥤ (D ⥤ E)) ⥤ ((C × D) ⥤ E)`, and verify that they provide an equivalence of categories `currying : (C ⥤ (D ⥤ E)) ≌ ((C × D) ⥤ E)`. -/ namespace category_theory universes v₁ v₂ v₃ u₁ u₂ u₃ variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] {E : Type u₃} [category.{v₃} E] /-- The uncurrying functor, taking a functor `C ⥤ (D ⥤ E)` and producing a functor `(C × D) ⥤ E`. -/ def uncurry : (C ⥤ (D ⥤ E)) ⥤ ((C × D) ⥤ E) := { obj := λ F, { obj := λ X, (F.obj X.1).obj X.2, map := λ X Y f, (F.map f.1).app X.2 ≫ (F.obj Y.1).map f.2, map_comp' := λ X Y Z f g, begin simp only [prod_comp_fst, prod_comp_snd, functor.map_comp, nat_trans.comp_app, category.assoc], slice_lhs 2 3 { rw ← nat_trans.naturality }, rw category.assoc, end }, map := λ F G T, { app := λ X, (T.app X.1).app X.2, naturality' := λ X Y f, begin simp only [prod_comp_fst, prod_comp_snd, category.comp_id, category.assoc, functor.map_id, functor.map_comp, nat_trans.id_app, nat_trans.comp_app], slice_lhs 2 3 { rw nat_trans.naturality }, slice_lhs 1 2 { rw [←nat_trans.comp_app, nat_trans.naturality, nat_trans.comp_app], }, rw category.assoc, end } }. /-- The object level part of the currying functor. (See `curry` for the functorial version.) -/ def curry_obj (F : (C × D) ⥤ E) : C ⥤ (D ⥤ E) := { obj := λ X, { obj := λ Y, F.obj (X, Y), map := λ Y Y' g, F.map (𝟙 X, g) }, map := λ X X' f, { app := λ Y, F.map (f, 𝟙 Y) } } /-- The currying functor, taking a functor `(C × D) ⥤ E` and producing a functor `C ⥤ (D ⥤ E)`. -/ def curry : ((C × D) ⥤ E) ⥤ (C ⥤ (D ⥤ E)) := { obj := λ F, curry_obj F, map := λ F G T, { app := λ X, { app := λ Y, T.app (X, Y), naturality' := λ Y Y' g, begin dsimp [curry_obj], rw nat_trans.naturality, end }, naturality' := λ X X' f, begin ext, dsimp [curry_obj], rw nat_trans.naturality, end } }. @[simp] lemma uncurry.obj_obj {F : C ⥤ (D ⥤ E)} {X : C × D} : (uncurry.obj F).obj X = (F.obj X.1).obj X.2 := rfl @[simp] lemma uncurry.obj_map {F : C ⥤ (D ⥤ E)} {X Y : C × D} {f : X ⟶ Y} : (uncurry.obj F).map f = ((F.map f.1).app X.2) ≫ ((F.obj Y.1).map f.2) := rfl @[simp] lemma uncurry.map_app {F G : C ⥤ (D ⥤ E)} {α : F ⟶ G} {X : C × D} : (uncurry.map α).app X = (α.app X.1).app X.2 := rfl @[simp] lemma curry.obj_obj_obj {F : (C × D) ⥤ E} {X : C} {Y : D} : ((curry.obj F).obj X).obj Y = F.obj (X, Y) := rfl @[simp] lemma curry.obj_obj_map {F : (C × D) ⥤ E} {X : C} {Y Y' : D} {g : Y ⟶ Y'} : ((curry.obj F).obj X).map g = F.map (𝟙 X, g) := rfl @[simp] lemma curry.obj_map_app {F : (C × D) ⥤ E} {X X' : C} {f : X ⟶ X'} {Y} : ((curry.obj F).map f).app Y = F.map (f, 𝟙 Y) := rfl @[simp] lemma curry.map_app_app {F G : (C × D) ⥤ E} {α : F ⟶ G} {X} {Y} : ((curry.map α).app X).app Y = α.app (X, Y) := rfl /-- The equivalence of functor categories given by currying/uncurrying. -/ @[simps] -- create projection simp lemmas even though this isn't a `{ .. }`. def currying : (C ⥤ (D ⥤ E)) ≌ ((C × D) ⥤ E) := equivalence.mk uncurry curry (nat_iso.of_components (λ F, nat_iso.of_components (λ X, nat_iso.of_components (λ Y, iso.refl _) (by tidy)) (by tidy)) (by tidy)) (nat_iso.of_components (λ F, nat_iso.of_components (λ X, eq_to_iso (by simp)) (by tidy)) (by tidy)) end category_theory
11e9fd5340de0e201c9e4ccbdfe4a2ce04098c1f
76c77df8a58af24dbf1d75c7012076a42244d728
/tutorial_src/exercises/00_first_proofs.lean
18b25f1b8330026fd4e9b81a68add24ddcaeca84
[]
no_license
kris-brown/theorem_proving_in_lean
7a7a584ba2c657a35335dc895d49d991c997a0c9
774460c21bf857daff158210741bd88d1c8323cd
refs/heads/master
1,668,278,123,743
1,593,445,161,000
1,593,445,161,000
265,748,924
0
1
null
null
null
null
UTF-8
Lean
false
false
18,237
lean
/- This file is intended for Lean beginners. The goal is to demonstrate what it feels like to prove things using Lean and mathlib. Complicated definitions and theory building are not covered. Everything is covered again more slowly and with exercises in the next files. -/ -- We want real numbers and their basic properties import data.real.basic -- We want to be able to define functions using the law of excluded middle noncomputable theory open_locale classical /- Our first goal is to define the set of upper bounds of a set of real numbers. This is already defined in mathlib (in a more general context), but we repeat it for the sake of exposition. Right-click "upper_bounds" below to get offered to jump to mathlib's version -/ #check upper_bounds /-- The set of upper bounds of a set of real numbers ℝ -/ def up_bounds (A : set ℝ) := { x : ℝ | ∀ a ∈ A, a ≤ x} /-- Predicate `is_max a A` means `a` is a maximum of `A` -/ def is_max (a : ℝ) (A : set ℝ) := a ∈ A ∧ a ∈ up_bounds A /- In the above definition, the symbol `∧` means "and". We also see the most visible difference between set theoretic foundations and type theoretic ones (used by almost all proof assistants). In set theory, everything is a set, and the only relation you get from foundations are `=` and `∈`. In type theory, there is a meta-theoretic relation of "typing": `a : ℝ` reads "`a` is a real number" or, more precisely, "the type of `a` is `ℝ`". Here "meta-theoretic" means this is not a statement you can prove or disprove inside the theory, it's a fact that is true or not. Here we impose this fact, in other circumstances, it would be checked by the Lean kernel. By contrast, `a ∈ A` is a statement inside the theory. Here it's part of the definition, in other circumstances it could be something proven inside Lean. -/ /- For illustrative purposes, we now define an infix version of the above predicate. It will allow us to write `a is_a_max_of A`, which is closer to a sentence. -/ infix `is_a_max_of`:55 := is_max variables (x:ℝ) (A : set ℝ) (hxa : is_max x A) #reduce hxa.2 /- Let's prove something now! A set of real numbers has at most one maximum. Here everything left of the final `:` is introducing the objects and assumption. The equality `x = y` right of the colon is the conclusion. -/ lemma unique_max (A : set ℝ) (x y : ℝ) (hx : x is_a_max_of A) (hy : y is_a_max_of A) : x = y := -- We first break our assumptions in their two constituent pieces. -- We are free to choose the name following `with` match hx, hy with ⟨x_inA, x_upbound⟩, ⟨y_inA, y_upbound⟩ := begin -- Assumption `x_upbound` means x isn't less than elements of A, let's apply this to y specialize (x_upbound : x ∈ up_bounds A) (y : ℝ) , -- Assumption `x_upbound` now needs the information that `y` is indeed in `A`. specialize x_upbound y_inA, -- Let's do this quicker with roles swapped specialize y_upbound x x_inA, -- We explained to Lean the idea of this proof. -- Now we know `x ≤ y` and `y ≤ x`, and Lean shouldn't need more help. -- `linarith` proves equalities and inequalities that follow linearly from -- the assumption we have. linarith end end /- The above proof is too long, even if you remove comments. We don't really need the unpacking steps at the beginning; we can access both parts of the assumption `hx : x is_a_max_of A` using shortcuts `h.1` and `h.2`. We can also improve readability without assistance from the tactic state display, clearly announcing intermediate goals using `have`. This way we get to the following version of the same proof. -/ example (A : set ℝ) (x y : ℝ) (hx : x is_a_max_of A) (hy : y is_a_max_of A) : x = y := begin have xy : x ≤ y, from (hy.2 : ∀ a: ℝ, a ∈ A → a ≤ y) (x : ℝ) (hx.1 : x ∈ A), have yx : y ≤ x, from hx.2 y hy.1, show x=y, from le_antisymm xy yx, end /- Notice how mathematics based on type theory treats the assumption `∀ a ∈ A, a ≤ y` as a function turning an element `a` of `A` into the statement `a ≤ y`. More precisely, this assumption is the abbreviation of `∀ a : ℝ, a ∈ A → a ≤ y`. The expression `hy.2 x` appearing in the above proof is then the statement `x ∈ A → x ≤ y`, which itself is a function turning a statement `x ∈ A` into `x ≤ y` so that the full expression `hy.2 x hx.1` is indeed a proof of `x ≤ y`. One could argue a three-line-long proof of this lemma is still two lines too long. This is debatable, but mathlib's style is to write very short proofs for trivial lemmas. Those proofs are not easy to read but they are meant to indicate that the proof is probably not worth reading. In order to reach this stage, we need to know what `linarith` did for us. It invoked the lemma `le_antisymm` which says: `x ≤ y → y ≤ x → x = y`. This arrow, which is used both for function and implication, is right associative. So the statement is `x ≤ y → (y ≤ x → x = y)` which reads: I will send a proof `p` of `x ≤ y` to a function sending a proof `q'` of `y ≤ x` to a proof of `x = y`. Hence `le_antisymm p q'` is a proof of `x = y`. Using this we can get our one-line proof: -/ example (A : set ℝ) (x y : ℝ) (hx : x is_a_max_of A) (hy : y is_a_max_of A) : x = y := le_antisymm (hy.2 x hx.1) (hx.2 y hy.1) /- Such a proof is called a proof term (or a "term mode" proof). Notice it has no `begin` and `end`. It is directly the kind of low level proof that the Lean kernel is consuming. Commands like `cases`, `specialize` or `linarith` are called tactics, they help users constructing proof terms that could be very tedious to write directly. The most efficient proof style combines tactics with proof terms like our previous `have : x ≤ y, from hy.2 x hx.1` where `hy.2 x hx.1` is a proof term embeded inside a tactic mode proof. In the remaining of this file, we'll be characterizing infima of sets of real numbers in term of sequences. -/ /-- The set of lower bounds of a set of real numbers ℝ -/ def low_bounds (A : set ℝ) := { x : ℝ | ∀ a ∈ A, x ≤ a} /- We now define `a` is an infimum of `A`. Again there is already a more general version in mathlib. -/ def is_inf (x : ℝ) (A : set ℝ) := x is_a_max_of (low_bounds A) infix `is_an_inf_of`:55 := is_inf /- We need to prove that any number which is greater than the infimum of A is greater than some element of A. -/ lemma inf_lt {A : set ℝ} {x : ℝ} (hx : x is_an_inf_of A) : ∀ y, x < y → ∃ a ∈ A, a < y := begin -- Let `y` be any real number. intro y, -- Let's prove the contrapositive contrapose, -- The symbol `¬` means negation. Let's ask Lean to rewrite the goal without negation, -- pushing negation through quantifiers and inequalities push_neg, -- Let's assume the premise, calling the assumption `h` intro h, -- `h` is exactly saying `y` is a lower bound of `A` so the second part of -- the infimum assumption `hx` applied to `y` and `h` is exactly what we want. exact hx.2 y h end /- In the above proof, the sequence `contrapose, push_neg` is so common that it can be abbreviated to `contrapose!`. With these commands, we enter the gray zone between proof checking and proof finding. Practical computer proof checking crucially needs the computer to handle tedious proof steps. In the next proof, we'll start using `linarith` a bit more seriously, going one step further into automation. Our next real goal is to prove inequalities for limits of sequences. We extract the following lemma: if `y ≤ x + ε` for all positive `ε` then `y ≤ x`. -/ lemma le_of_le_add_eps {x y : ℝ} : (∀ ε > 0, y ≤ x + ε) → y ≤ x := begin -- Let's prove the contrapositive, asking Lean to push negations right away. contrapose!, -- Assume `h : x < y`. intro h, -- We need to find `ε` such that `ε` is positive and `x + ε < y`. -- Let's use `(y-x)/2` use ((y-x)/2), -- we now have two properties to prove. Let's do both in turn, using `linarith` split, linarith, linarith, end /- Note how `linarith` was used for both sub-goals at the end of the above proof. We could have shortened that using the semi-colon combinator instead of comma, writing `split ; linarith`. Next we will study a compressed version of that proof: -/ example {x y : ℝ} : (∀ ε > 0, y ≤ x + ε) → y ≤ x := begin contrapose!, exact assume h, ⟨(y-x)/2, by linarith, by linarith⟩, end /- The angle brackets `⟨` and `⟩` introduce compound data or proofs. A proof of a `∃ z, P z` statemement is composed of a witness `z₀` and a proof `h` of `P z₀`. The compound is denoted by `⟨z₀, h⟩`. In the example above, the predicate is itself compound, it is a conjunction `P z ∧ Q z`. So the proof term should read `⟨z₀, ⟨h₁, h₂⟩⟩` where `h₁` (resp. `h₂`) is a proof of `P z₀` (resp. `Q z₀`). But these so-called "anonymous constructor" brackets are right-associative, so we can get rid of the nested brackets. The keyword `by` introduces tactic mode inside term mode, it is a shorter version of the `begin`/`end` pair, which is more convenient for single tactic blocks. In this example, `begin` enters tactic mode, `exact` leaves it, `by` re-enters it. Going all the way to a proof term would make the proof much longer, because we crucially use automation with `contrapose!` and `linarith`. We can still get a one-line proof using curly braces to gather several tactic invocations, and the `by` abbreviation instead of `begin`/`end`: -/ example {x y : ℝ} : (∀ ε > 0, y ≤ x + ε) → y ≤ x := by { contrapose!, exact assume h, ⟨(y-x)/2, by linarith, by linarith⟩ } /- One could argue that the above proof is a bit too terse, and we are relying too much on linarith. Let's have more `linarith` calls for smaller steps. For the sake of (tiny) variation, we will also assume the premise and argue by contradiction instead of contraposing. -/ example {x y : ℝ} : (∀ ε > 0, y ≤ x + ε) → y ≤ x := begin intro h, -- Assume the conclusion is false, and call this assumption H. by_contradiction H, push_neg at H, -- Now let's compute. have key : y < y := calc -- Each line must end with a colon followed by a proof term -- We want to specialize our assumption `h` to `ε = (y-x)/2` but this is long to -- type, so let's put a hole `_` that Lean will fill in by comparing the -- statement we want to prove and our proof term with a hole. As usual, -- positivity of `(y-x)/2` is proved by `linarith` y ≤ x + (y-x)/2 : h _ (by linarith) ... = x/2 + y/2 : by ring ... < y : by linarith, -- our key now says `y < y` (notice how the sequence `≤`, `=`, `<` was correctly -- merged into a `<`). Let `linarith` find the desired contradiction now. linarith, -- alternatively, we could have provided the proof term -- `exact lt_irrefl y key` end /- Now we are ready for some analysis. Let's set up notation for absolute value -/ local notation `|`x`|` := abs x /- And let's define convergence of sequences of real numbers (of course there is a much more general definition in mathlib). -/ /-- The sequence `u` tends to `l` -/ def limit (u : ℕ → ℝ) (l : ℝ) := ∀ ε > 0, ∃ N, ∀ n ≥ N, |u n - l| ≤ ε /- In the above definition, `u n` denotes the n-th term of the sequence. We can add parentheses to get `u(n)` but we try to avoid parentheses because they pile up very quickly -/ -- If y ≤ u n for all n and u n goes to x then y ≤ x lemma le_lim {x y : ℝ} {u : ℕ → ℝ} (hu : limit u x) (ineq : ∀ n, y ≤ u n) : y ≤ x := begin -- Let's apply our previous lemma apply le_of_le_add_eps, -- We need to prove y ≤ x + ε for all positive ε. -- Let ε be any positive real intros ε ε_pos, -- we now specialize our limit assumption to this `ε`, and immediately -- fix a `N` as promised by the definition. cases hu ε ε_pos with N HN, -- Now we only need to compute until reaching the conclusion calc y ≤ u N : ineq N ... = x + (u N - x) : by linarith -- We'll need `add_le_add` which says `a ≤ b` and `c ≤ d` implies `a + c ≤ b + d` -- We need a lemma saying `z ≤ |z|`. Because we don't know the name of this lemma, -- let's use `library_search`. Because searching thourgh the library is slow, -- Lean will write what it found in the Lean message window when cursor is on -- that line, so that we can replace it by the lemma. We see `le_max_left` which -- says `a ≤ max a b`. Actually there is a more specific lemma `le_abs_self` ... ≤ x + |u N - x| : add_le_add (by linarith) (by library_search) ... ≤ x + ε : add_le_add (by linarith) (HN N (by linarith)), end /- The next lemma has been extracted from the main proof in order to discuss numbers. In ordinary maths, we know that ℕ is *not* contained in `ℝ`, whatever the construction of real numbers that we use. For instance a natural number is not an equivalence class of Cauchy sequences. But it's very easy to pretend otherwise. Formal maths requires slightly more care. In the statement below, the "type ascription" `(n + 1 : ℝ)` forces Lean to convert the natural number `n+1` into a real number. The "inclusion" map will be displayed in tactic state as `↑`. There are various lemmas asserting this map is compatible with addition and monotone, but we don't want to bother writing their names. The `norm_cast` tactic is designed to wisely apply those lemmas for us. -/ lemma inv_succ_pos : ∀ n : ℕ, 1/(n+1 : ℝ) > 0 := begin -- Let `n` be any integer intro n, -- Since we don't know the name of the relevant lemma, asserting that the inverse of -- a positive number is positive, let's state that is suffices -- to prove that `n+1`, seen as a real number, is positive, and ask `library_search` suffices : (n + 1 : ℝ) > 0, { library_search }, -- Now we want to reduce to a statement about natural numbers, not real numbers -- coming from natural numbers. norm_cast, -- and then get the usual help from `linarith` linarith, end /- That was a pretty long proof for an obvious fact. And stating it as a lemma feels stupid, so let's find a way to write it on one line in case we want to include it in some other proof without stating a lemma. First the `library_search` call above displays the name of the relevant lemma: `one_div_pos_of_pos`. We can also replace the `linarith` call on the last line by `library_search` to learn the name of the lemma `nat.succ_pos` asserting that the successor of a natural number is positive. There is also a variant on `norm_cast` that combines it with `exact`. The term mode analogue of `intro` is `λ`. We get down to: -/ example : ∀ n : ℕ, 1/(n+1 : ℝ) > 0 := λ n, one_div_pos_of_pos (by exact_mod_cast nat.succ_pos n) /- The next proof uses mostly known things, so we will commment only new aspects. -/ lemma limit_inv_succ : ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, 1/(n + 1 : ℝ) ≤ ε := begin intros ε ε_pos, suffices : ∃ N : ℕ, 1/ε ≤ N, { -- Because we didn't provide a name for the above statement, Lean called it `this`. -- Let's fix an `N` that works. cases this with N HN, use N, intros n Hn, -- Now we want to rewrite the goal using lemmas -- `div_le_iff' : 0 < b → (a / b ≤ c ↔ a ≤ b * c)` -- `div_le_iff : 0 < b → (a / b ≤ c ↔ a ≤ c * b)` -- the second one will be rewritten from right to left, as indicated by `←`. -- Lean will create a side goal for the required positivity assumption that -- we don't provide for `div_le_iff'`. rw [div_le_iff', ← div_le_iff ε_pos], -- We want to replace assumption `Hn` by its real counter-part so that -- linarith can find what it needs. replace Hn : (N : ℝ) ≤ n, exact_mod_cast Hn, linarith, -- we are still left with the positivity assumption, but already discussed -- how to prove it in the preceding lemma exact_mod_cast nat.succ_pos n }, -- Now we need to prove that sufficient statement. -- We want to use that `ℝ` is archimedean. So we start typing -- `exact archimedean_` and hit Ctrl-space to see what completion Lean proposes -- the lemma `archimedean_iff_nat_le` sounds promising. We select the left to -- right implication using `.1`. This a generic lemma for fields equiped with -- a linear (ie total) order. We need to provide a proof that `ℝ` is indeed -- archimedean. This is done using the `apply_instance` tactic that will be -- covered elsewhere. exact archimedean_iff_nat_le.1 (by apply_instance) (1/ε), end /- We can now put all pieces together, with almost no new things to explain. -/ lemma inf_seq (A : set ℝ) (x : ℝ) : (x is_an_inf_of A) ↔ (x ∈ low_bounds A ∧ ∃ u : ℕ → ℝ, limit u x ∧ ∀ n, u n ∈ A ) := begin split, { intro h, split, { exact h.1 }, -- On the next line, we don't need to tell Lean to treat `n+1` as a real number because -- we add `x` to it, so Lean knows there is only one way to make sense of this expression. have key : ∀ n : ℕ, ∃ a ∈ A, a < x + 1/(n+1), { intro n, -- we can use the lemma we proved above apply inf_lt h, -- and another one we proved! have : 0 < 1/(n+1 : ℝ), from inv_succ_pos n, linarith }, -- Now we need to use axiom of (countable) choice choose u hu using key, use u, split, { intros ε ε_pos, -- again we use a lemma we proved, specializing it to our fixed `ε`, and fixing a `N` cases limit_inv_succ ε ε_pos with N H, use N, intros n hn, have : x ≤ u n, from h.1 _ (hu n).1, have := calc u n < x + 1/(n + 1) : (hu n).2 ... ≤ x + ε : add_le_add (le_refl x) (H n hn), rw abs_of_nonneg ; linarith }, { intro n, exact (hu n).1 } }, { intro h, -- Assumption `h` is made of nested compound statements. We can use the -- recursive version of `cases` to unpack it in one go. rcases h with ⟨x_min, u, lim, huA⟩, split, exact x_min, intros y y_mino, apply le_lim lim, intro n, exact y_mino (u n) (huA n) }, end
003b8c76bed31c14297a1e369bd446462a741301
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/run/eq3.lean
a1e405782f49fcb3d4edff86431fe4775c42e089
[ "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
256
lean
import data.vector open nat vector definition swap {A : Type} : Π {n}, vector A (succ (succ n)) → vector A (succ (succ n)), swap (a :: b :: vs) := b :: a :: vs example (n : nat) (a b : num) (v : vector num n) : swap (a :: b :: v) = b :: a :: v := rfl
06c2a05082574598224275f425e00fb4f18618b8
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/ring_theory/ideal/local_ring.lean
1436af6d43d31387fb6a9e67d2177391eac6bf0e
[ "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
11,267
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes, Mario Carneiro -/ import algebra.algebra.basic import algebra.category.CommRing.basic import ring_theory.ideal.operations /-! # Local rings Define local rings as commutative rings having a unique maximal ideal. ## Main definitions * `local_ring`: A predicate on commutative rings, stating that every element `a` is either a unit or `1 - a` is a unit. This is shown to be equivalent to the condition that there exists a unique maximal ideal. * `local_ring.maximal_ideal`: The unique maximal ideal for a local rings. Its carrier set is the set of non units. * `is_local_ring_hom`: A predicate on semiring homomorphisms, requiring that it maps nonunits to nonunits. For local rings, this means that the image of the unique maximal ideal is again contained in the unique maximal ideal. * `local_ring.residue_field`: The quotient of a local ring by its maximal ideal. -/ universes u v w /-- A commutative ring is local if it has a unique maximal ideal. Note that `local_ring` is a predicate. -/ class local_ring (R : Type u) [comm_ring R] extends nontrivial R : Prop := (is_local : ∀ (a : R), (is_unit a) ∨ (is_unit (1 - a))) namespace local_ring variables {R : Type u} [comm_ring R] [local_ring R] lemma is_unit_or_is_unit_one_sub_self (a : R) : (is_unit a) ∨ (is_unit (1 - a)) := is_local a lemma is_unit_of_mem_nonunits_one_sub_self (a : R) (h : (1 - a) ∈ nonunits R) : is_unit a := or_iff_not_imp_right.1 (is_local a) h lemma is_unit_one_sub_self_of_mem_nonunits (a : R) (h : a ∈ nonunits R) : is_unit (1 - a) := or_iff_not_imp_left.1 (is_local a) h lemma nonunits_add {x y} (hx : x ∈ nonunits R) (hy : y ∈ nonunits R) : x + y ∈ nonunits R := begin rintros ⟨u, hu⟩, apply hy, suffices : is_unit ((↑u⁻¹ : R) * y), { rcases this with ⟨s, hs⟩, use u * s, convert congr_arg (λ z, (u : R) * z) hs, rw ← mul_assoc, simp }, rw show (↑u⁻¹ * y) = (1 - ↑u⁻¹ * x), { rw eq_sub_iff_add_eq, replace hu := congr_arg (λ z, (↑u⁻¹ : R) * z) hu.symm, simpa [mul_add, add_comm] using hu }, apply is_unit_one_sub_self_of_mem_nonunits, exact mul_mem_nonunits_right hx end variable (R) /-- The ideal of elements that are not units. -/ def maximal_ideal : ideal R := { carrier := nonunits R, zero_mem' := zero_mem_nonunits.2 $ zero_ne_one, add_mem' := λ x y hx hy, nonunits_add hx hy, smul_mem' := λ a x, mul_mem_nonunits_right } instance maximal_ideal.is_maximal : (maximal_ideal R).is_maximal := begin rw ideal.is_maximal_iff, split, { intro h, apply h, exact is_unit_one }, { intros I x hI hx H, erw not_not at hx, rcases hx with ⟨u,rfl⟩, simpa using I.mul_mem_left ↑u⁻¹ H } end lemma maximal_ideal_unique : ∃! I : ideal R, I.is_maximal := ⟨maximal_ideal R, maximal_ideal.is_maximal R, λ I hI, hI.eq_of_le (maximal_ideal.is_maximal R).1.1 $ λ x hx, hI.1.1 ∘ I.eq_top_of_is_unit_mem hx⟩ variable {R} lemma eq_maximal_ideal {I : ideal R} (hI : I.is_maximal) : I = maximal_ideal R := unique_of_exists_unique (maximal_ideal_unique R) hI $ maximal_ideal.is_maximal R lemma le_maximal_ideal {J : ideal R} (hJ : J ≠ ⊤) : J ≤ maximal_ideal R := begin rcases ideal.exists_le_maximal J hJ with ⟨M, hM1, hM2⟩, rwa ←eq_maximal_ideal hM1 end @[simp] lemma mem_maximal_ideal (x) : x ∈ maximal_ideal R ↔ x ∈ nonunits R := iff.rfl end local_ring variables {R : Type u} {S : Type v} {T : Type w} lemma local_of_nonunits_ideal [comm_ring R] (hnze : (0:R) ≠ 1) (h : ∀ x y ∈ nonunits R, x + y ∈ nonunits R) : local_ring R := { exists_pair_ne := ⟨0, 1, hnze⟩, is_local := λ x, or_iff_not_imp_left.mpr $ λ hx, begin by_contra H, apply h _ hx _ H, simp [-sub_eq_add_neg, add_sub_cancel'_right] end } lemma local_of_unique_max_ideal [comm_ring R] (h : ∃! I : ideal R, I.is_maximal) : local_ring R := local_of_nonunits_ideal (let ⟨I, Imax, _⟩ := h in (λ (H : 0 = 1), Imax.1.1 $ I.eq_top_iff_one.2 $ H ▸ I.zero_mem)) $ λ x hx y hy H, let ⟨I, Imax, Iuniq⟩ := h in let ⟨Ix, Ixmax, Hx⟩ := exists_max_ideal_of_mem_nonunits hx in let ⟨Iy, Iymax, Hy⟩ := exists_max_ideal_of_mem_nonunits hy in have xmemI : x ∈ I, from ((Iuniq Ix Ixmax) ▸ Hx), have ymemI : y ∈ I, from ((Iuniq Iy Iymax) ▸ Hy), Imax.1.1 $ I.eq_top_of_is_unit_mem (I.add_mem xmemI ymemI) H lemma local_of_unique_nonzero_prime (R : Type u) [comm_ring R] (h : ∃! P : ideal R, P ≠ ⊥ ∧ ideal.is_prime P) : local_ring R := local_of_unique_max_ideal begin rcases h with ⟨P, ⟨hPnonzero, hPnot_top, _⟩, hPunique⟩, refine ⟨P, ⟨⟨hPnot_top, _⟩⟩, λ M hM, hPunique _ ⟨_, ideal.is_maximal.is_prime hM⟩⟩, { refine ideal.maximal_of_no_maximal (λ M hPM hM, ne_of_lt hPM _), exact (hPunique _ ⟨ne_bot_of_gt hPM, ideal.is_maximal.is_prime hM⟩).symm }, { rintro rfl, exact hPnot_top (hM.1.2 P (bot_lt_iff_ne_bot.2 hPnonzero)) }, end lemma local_of_surjective [comm_ring R] [local_ring R] [comm_ring S] [nontrivial S] (f : R →+* S) (hf : function.surjective f) : local_ring S := { is_local := begin intros b, obtain ⟨a, rfl⟩ := hf b, apply (local_ring.is_unit_or_is_unit_one_sub_self a).imp f.is_unit_map _, rw [← f.map_one, ← f.map_sub], apply f.is_unit_map, end, .. ‹nontrivial S› } /-- A local ring homomorphism is a homomorphism between local rings such that the image of the maximal ideal of the source is contained within the maximal ideal of the target. -/ class is_local_ring_hom [semiring R] [semiring S] (f : R →+* S) : Prop := (map_nonunit : ∀ a, is_unit (f a) → is_unit a) instance is_local_ring_hom_id (R : Type*) [semiring R] : is_local_ring_hom (ring_hom.id R) := { map_nonunit := λ a, id } @[simp] lemma is_unit_map_iff [semiring R] [semiring S] (f : R →+* S) [is_local_ring_hom f] (a) : is_unit (f a) ↔ is_unit a := ⟨is_local_ring_hom.map_nonunit a, f.is_unit_map⟩ instance is_local_ring_hom_comp [semiring R] [semiring S] [semiring T] (g : S →+* T) (f : R →+* S) [is_local_ring_hom g] [is_local_ring_hom f] : is_local_ring_hom (g.comp f) := { map_nonunit := λ a, is_local_ring_hom.map_nonunit a ∘ is_local_ring_hom.map_nonunit (f a) } instance _root_.CommRing.is_local_ring_hom_comp {R S T : CommRing} (f : R ⟶ S) (g : S ⟶ T) [is_local_ring_hom g] [is_local_ring_hom f] : is_local_ring_hom (f ≫ g) := is_local_ring_hom_comp _ _ /-- If `f : R →+* S` is a local ring hom, then `R` is a local ring if `S` is. -/ lemma _root_.ring_hom.domain_local_ring {R S : Type*} [comm_ring R] [comm_ring S] [H : _root_.local_ring S] (f : R →+* S) [is_local_ring_hom f] : _root_.local_ring R := begin haveI : nontrivial R := pullback_nonzero f f.map_zero f.map_one, constructor, intro x, rw [← is_unit_map_iff f, ← is_unit_map_iff f, f.map_sub, f.map_one], exact _root_.local_ring.is_local (f x) end lemma is_local_ring_hom_of_comp {R S T: Type*} [comm_ring R] [comm_ring S] [comm_ring T] (f : R →+* S) (g : S →+* T) [is_local_ring_hom (g.comp f)] : is_local_ring_hom f := ⟨λ a ha, (is_unit_map_iff (g.comp f) _).mp (g.is_unit_map ha)⟩ instance is_local_ring_hom_equiv [semiring R] [semiring S] (f : R ≃+* S) : is_local_ring_hom f.to_ring_hom := { map_nonunit := λ a ha, begin convert f.symm.to_ring_hom.is_unit_map ha, rw ring_equiv.symm_to_ring_hom_apply_to_ring_hom_apply, end } @[simp] lemma is_unit_of_map_unit [semiring R] [semiring S] (f : R →+* S) [is_local_ring_hom f] (a) (h : is_unit (f a)) : is_unit a := is_local_ring_hom.map_nonunit a h theorem of_irreducible_map [semiring R] [semiring S] (f : R →+* S) [h : is_local_ring_hom f] {x : R} (hfx : irreducible (f x)) : irreducible x := ⟨λ h, hfx.not_unit $ is_unit.map f.to_monoid_hom h, λ p q hx, let ⟨H⟩ := h in or.imp (H p) (H q) $ hfx.is_unit_or_is_unit $ f.map_mul p q ▸ congr_arg f hx⟩ section open category_theory lemma is_local_ring_hom_of_iso {R S : CommRing} (f : R ≅ S) : is_local_ring_hom f.hom := { map_nonunit := λ a ha, begin convert f.inv.is_unit_map ha, rw category_theory.coe_hom_inv_id, end } @[priority 100] -- see Note [lower instance priority] instance is_local_ring_hom_of_is_iso {R S : CommRing} (f : R ⟶ S) [is_iso f] : is_local_ring_hom f := is_local_ring_hom_of_iso (as_iso f) end section open local_ring variables [comm_ring R] [local_ring R] [comm_ring S] [local_ring S] variables (f : R →+* S) [is_local_ring_hom f] lemma map_nonunit (a : R) (h : a ∈ maximal_ideal R) : f a ∈ maximal_ideal S := λ H, h $ is_unit_of_map_unit f a H end namespace local_ring variables [comm_ring R] [local_ring R] [comm_ring S] [local_ring S] /-- A ring homomorphism between local rings is a local ring hom iff it reflects units, i.e. any preimage of a unit is still a unit. https://stacks.math.columbia.edu/tag/07BJ -/ theorem local_hom_tfae (f : R →+* S) : tfae [is_local_ring_hom f, f '' (maximal_ideal R).1 ⊆ maximal_ideal S, (maximal_ideal R).map f ≤ maximal_ideal S, maximal_ideal R ≤ (maximal_ideal S).comap f, (maximal_ideal S).comap f = maximal_ideal R] := begin tfae_have : 1 → 2, rintros _ _ ⟨a,ha,rfl⟩, resetI, exact map_nonunit f a ha, tfae_have : 2 → 4, exact set.image_subset_iff.1, tfae_have : 3 ↔ 4, exact ideal.map_le_iff_le_comap, tfae_have : 4 → 1, intro h, fsplit, exact λ x, not_imp_not.1 (@h x), tfae_have : 1 → 5, intro, resetI, ext, exact not_iff_not.2 (is_unit_map_iff f x), tfae_have : 5 → 4, exact λ h, le_of_eq h.symm, tfae_finish, end variable (R) /-- The residue field of a local ring is the quotient of the ring by its maximal ideal. -/ def residue_field := R ⧸ maximal_ideal R noncomputable instance residue_field.field : field (residue_field R) := ideal.quotient.field (maximal_ideal R) noncomputable instance : inhabited (residue_field R) := ⟨37⟩ /-- The quotient map from a local ring to its residue field. -/ def residue : R →+* (residue_field R) := ideal.quotient.mk _ noncomputable instance residue_field.algebra : algebra R (residue_field R) := (residue R).to_algebra namespace residue_field variables {R S} /-- The map on residue fields induced by a local homomorphism between local rings -/ noncomputable def map (f : R →+* S) [is_local_ring_hom f] : residue_field R →+* residue_field S := ideal.quotient.lift (maximal_ideal R) ((ideal.quotient.mk _).comp f) $ λ a ha, begin erw ideal.quotient.eq_zero_iff_mem, exact map_nonunit f a ha end end residue_field variables {R} lemma ker_eq_maximal_ideal {K : Type*} [field K] (φ : R →+* K) (hφ : function.surjective φ) : φ.ker = maximal_ideal R := local_ring.eq_maximal_ideal $ φ.ker_is_maximal_of_surjective hφ end local_ring namespace field variables [field R] open_locale classical @[priority 100] -- see Note [lower instance priority] instance : local_ring R := { is_local := λ a, if h : a = 0 then or.inr (by rw [h, sub_zero]; exact is_unit_one) else or.inl $ is_unit.mk0 a h } end field
7b7ce12a1975169169aeed704d81bde7d19a8645
82e44445c70db0f03e30d7be725775f122d72f3e
/src/data/nat/basic.lean
309bcf2bf444fa247c6b1fdd63da7774d858abf0
[ "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
60,087
lean
/- Copyright (c) 2014 Floris van Doorn (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import algebra.ordered_ring /-! # Basic operations on the natural numbers This file contains: - instances on the natural numbers - some basic lemmas about natural numbers - extra recursors: * `le_rec_on`, `le_induction`: recursion and induction principles starting at non-zero numbers * `decreasing_induction`: recursion growing downwards * `strong_rec'`: recursion based on strong inequalities - decidability instances on predicates about the natural numbers -/ universes u v /-! ### instances -/ instance : nontrivial ℕ := ⟨⟨0, 1, nat.zero_ne_one⟩⟩ instance : comm_semiring nat := { add := nat.add, add_assoc := nat.add_assoc, zero := nat.zero, zero_add := nat.zero_add, add_zero := nat.add_zero, add_comm := nat.add_comm, mul := nat.mul, mul_assoc := nat.mul_assoc, one := nat.succ nat.zero, one_mul := nat.one_mul, mul_one := nat.mul_one, left_distrib := nat.left_distrib, right_distrib := nat.right_distrib, zero_mul := nat.zero_mul, mul_zero := nat.mul_zero, mul_comm := nat.mul_comm, nsmul := λ m n, m * n, nsmul_zero' := nat.zero_mul, nsmul_succ' := λ n x, by rw [nat.succ_eq_one_add, nat.right_distrib, nat.one_mul] } instance : linear_ordered_semiring nat := { add_left_cancel := @nat.add_left_cancel, lt := nat.lt, add_le_add_left := @nat.add_le_add_left, le_of_add_le_add_left := @nat.le_of_add_le_add_left, zero_le_one := nat.le_of_lt (nat.zero_lt_succ 0), mul_lt_mul_of_pos_left := @nat.mul_lt_mul_of_pos_left, mul_lt_mul_of_pos_right := @nat.mul_lt_mul_of_pos_right, decidable_eq := nat.decidable_eq, exists_pair_ne := ⟨0, 1, ne_of_lt nat.zero_lt_one⟩, ..nat.comm_semiring, ..nat.linear_order } -- all the fields are already included in the linear_ordered_semiring instance instance : linear_ordered_cancel_add_comm_monoid ℕ := { add_left_cancel := @nat.add_left_cancel, ..nat.linear_ordered_semiring } instance : linear_ordered_comm_monoid_with_zero ℕ := { mul_le_mul_left := λ a b h c, nat.mul_le_mul_left c h, ..nat.linear_ordered_semiring, ..(infer_instance : comm_monoid_with_zero ℕ)} /-! Extra instances to short-circuit type class resolution -/ instance : add_comm_monoid nat := by apply_instance instance : add_monoid nat := by apply_instance instance : monoid nat := by apply_instance instance : comm_monoid nat := by apply_instance instance : comm_semigroup nat := by apply_instance instance : semigroup nat := by apply_instance instance : add_comm_semigroup nat := by apply_instance instance : add_semigroup nat := by apply_instance instance : distrib nat := by apply_instance instance : semiring nat := by apply_instance instance : ordered_semiring nat := by apply_instance instance : canonically_ordered_comm_semiring ℕ := { le_iff_exists_add := assume a b, ⟨assume h, let ⟨c, hc⟩ := nat.le.dest h in ⟨c, hc.symm⟩, assume ⟨c, hc⟩, hc.symm ▸ nat.le_add_right _ _⟩, eq_zero_or_eq_zero_of_mul_eq_zero := assume a b, nat.eq_zero_of_mul_eq_zero, bot := 0, bot_le := nat.zero_le, .. nat.nontrivial, .. (infer_instance : ordered_add_comm_monoid ℕ), .. (infer_instance : linear_ordered_semiring ℕ), .. (infer_instance : comm_semiring ℕ) } instance : canonically_linear_ordered_add_monoid ℕ := { .. (infer_instance : canonically_ordered_add_monoid ℕ), .. nat.linear_order } instance nat.subtype.semilattice_sup_bot (s : set ℕ) [decidable_pred (∈ s)] [h : nonempty s] : semilattice_sup_bot s := { bot := ⟨nat.find (nonempty_subtype.1 h), nat.find_spec (nonempty_subtype.1 h)⟩, bot_le := λ x, nat.find_min' _ x.2, ..subtype.linear_order s, ..lattice_of_linear_order } theorem nat.nsmul_eq_mul (m n : ℕ) : m • n = m * n := rfl theorem nat.eq_of_mul_eq_mul_right {n m k : ℕ} (Hm : 0 < m) (H : n * m = k * m) : n = k := by rw [mul_comm n m, mul_comm k m] at H; exact nat.eq_of_mul_eq_mul_left Hm H instance nat.comm_cancel_monoid_with_zero : comm_cancel_monoid_with_zero ℕ := { mul_left_cancel_of_ne_zero := λ _ _ _ h1 h2, nat.eq_of_mul_eq_mul_left (nat.pos_of_ne_zero h1) h2, mul_right_cancel_of_ne_zero := λ _ _ _ h1 h2, nat.eq_of_mul_eq_mul_right (nat.pos_of_ne_zero h1) h2, .. (infer_instance : comm_monoid_with_zero ℕ) } attribute [simp] nat.not_lt_zero nat.succ_ne_zero nat.succ_ne_self nat.zero_ne_one nat.one_ne_zero nat.zero_ne_bit1 nat.bit1_ne_zero nat.bit0_ne_one nat.one_ne_bit0 nat.bit0_ne_bit1 nat.bit1_ne_bit0 /-! Inject some simple facts into the type class system. This `fact` should not be confused with the factorial function `nat.fact`! -/ section facts instance succ_pos'' (n : ℕ) : fact (0 < n.succ) := ⟨n.succ_pos⟩ instance pos_of_one_lt (n : ℕ) [h : fact (1 < n)] : fact (0 < n) := ⟨lt_trans zero_lt_one h.1⟩ end facts variables {m n k : ℕ} namespace nat /-! ### Recursion and `set.range` -/ section set open set theorem zero_union_range_succ : {0} ∪ range succ = univ := by { ext n, cases n; simp } variables {α : Type*} theorem range_of_succ (f : ℕ → α) : {f 0} ∪ range (f ∘ succ) = range f := by rw [← image_singleton, range_comp, ← image_union, zero_union_range_succ, image_univ] theorem range_rec {α : Type*} (x : α) (f : ℕ → α → α) : (set.range (λ n, nat.rec x f n) : set α) = {x} ∪ set.range (λ n, nat.rec (f 0 x) (f ∘ succ) n) := begin convert (range_of_succ _).symm, ext n, induction n with n ihn, { refl }, { dsimp at ihn ⊢, rw ihn } end theorem range_cases_on {α : Type*} (x : α) (f : ℕ → α) : (set.range (λ n, nat.cases_on n x f) : set α) = {x} ∪ set.range f := (range_of_succ _).symm end set /-! ### The units of the natural numbers as a `monoid` and `add_monoid` -/ theorem units_eq_one (u : units ℕ) : u = 1 := units.ext $ nat.eq_one_of_dvd_one ⟨u.inv, u.val_inv.symm⟩ theorem add_units_eq_zero (u : add_units ℕ) : u = 0 := add_units.ext $ (nat.eq_zero_of_add_eq_zero u.val_neg).1 @[simp] protected theorem is_unit_iff {n : ℕ} : is_unit n ↔ n = 1 := iff.intro (assume ⟨u, hu⟩, match n, u, hu, nat.units_eq_one u with _, _, rfl, rfl := rfl end) (assume h, h.symm ▸ ⟨1, rfl⟩) instance unique_units : unique (units ℕ) := { default := 1, uniq := nat.units_eq_one } instance unique_add_units : unique (add_units ℕ) := { default := 0, uniq := nat.add_units_eq_zero } /-! ### Equalities and inequalities involving zero and one -/ lemma one_lt_iff_ne_zero_and_ne_one : ∀ {n : ℕ}, 1 < n ↔ n ≠ 0 ∧ n ≠ 1 | 0 := dec_trivial | 1 := dec_trivial | (n+2) := dec_trivial protected theorem mul_ne_zero {n m : ℕ} (n0 : n ≠ 0) (m0 : m ≠ 0) : n * m ≠ 0 | nm := (eq_zero_of_mul_eq_zero nm).elim n0 m0 @[simp] protected theorem mul_eq_zero {a b : ℕ} : a * b = 0 ↔ a = 0 ∨ b = 0 := iff.intro eq_zero_of_mul_eq_zero (by simp [or_imp_distrib] {contextual := tt}) @[simp] protected theorem zero_eq_mul {a b : ℕ} : 0 = a * b ↔ a = 0 ∨ b = 0 := by rw [eq_comm, nat.mul_eq_zero] lemma eq_zero_of_double_le {a : ℕ} (h : 2 * a ≤ a) : a = 0 := nat.eq_zero_of_le_zero $ by rwa [two_mul, nat.add_le_to_le_sub, nat.sub_self] at h; refl lemma eq_zero_of_mul_le {a b : ℕ} (hb : 2 ≤ b) (h : b * a ≤ a) : a = 0 := eq_zero_of_double_le $ le_trans (nat.mul_le_mul_right _ hb) h theorem le_zero_iff {i : ℕ} : i ≤ 0 ↔ i = 0 := ⟨nat.eq_zero_of_le_zero, assume h, h ▸ le_refl i⟩ lemma zero_max {m : ℕ} : max 0 m = m := max_eq_right (zero_le _) @[simp] lemma min_eq_zero_iff {m n : ℕ} : min m n = 0 ↔ m = 0 ∨ n = 0 := begin split, { intro h, cases le_total n m with H H, { simpa [H] using or.inr h }, { simpa [H] using or.inl h } }, { rintro (rfl|rfl); simp } end @[simp] lemma max_eq_zero_iff {m n : ℕ} : max m n = 0 ↔ m = 0 ∧ n = 0 := begin split, { intro h, cases le_total n m with H H, { simp only [H, max_eq_left] at h, exact ⟨h, le_antisymm (H.trans h.le) (zero_le _)⟩ }, { simp only [H, max_eq_right] at h, exact ⟨le_antisymm (H.trans h.le) (zero_le _), h⟩ } }, { rintro ⟨rfl, rfl⟩, simp } end lemma add_eq_max_iff {n m : ℕ} : n + m = max n m ↔ n = 0 ∨ m = 0 := begin rw ←min_eq_zero_iff, cases le_total n m with H H; simp [H] end lemma add_eq_min_iff {n m : ℕ} : n + m = min n m ↔ n = 0 ∧ m = 0 := begin rw ←max_eq_zero_iff, cases le_total n m with H H; simp [H] end lemma one_le_of_lt {n m : ℕ} (h : n < m) : 1 ≤ m := lt_of_le_of_lt (nat.zero_le _) h theorem eq_one_of_mul_eq_one_right {m n : ℕ} (H : m * n = 1) : m = 1 := eq_one_of_dvd_one ⟨n, H.symm⟩ theorem eq_one_of_mul_eq_one_left {m n : ℕ} (H : m * n = 1) : n = 1 := eq_one_of_mul_eq_one_right (by rwa mul_comm) /-! ### `succ` -/ theorem eq_of_lt_succ_of_not_lt {a b : ℕ} (h1 : a < b + 1) (h2 : ¬ a < b) : a = b := have h3 : a ≤ b, from le_of_lt_succ h1, or.elim (eq_or_lt_of_not_lt h2) (λ h, h) (λ h, absurd h (not_lt_of_ge h3)) lemma eq_of_le_of_lt_succ {n m : ℕ} (h₁ : n ≤ m) (h₂ : m < n + 1) : m = n := nat.le_antisymm (le_of_succ_le_succ h₂) h₁ theorem one_add (n : ℕ) : 1 + n = succ n := by simp [add_comm] @[simp] lemma succ_pos' {n : ℕ} : 0 < succ n := succ_pos n theorem succ_inj' {n m : ℕ} : succ n = succ m ↔ n = m := ⟨succ.inj, congr_arg _⟩ theorem succ_injective : function.injective nat.succ := λ x y, succ.inj lemma succ_ne_succ {n m : ℕ} : succ n ≠ succ m ↔ n ≠ m := succ_injective.ne_iff @[simp] lemma succ_succ_ne_one (n : ℕ) : n.succ.succ ≠ 1 := succ_ne_succ.mpr n.succ_ne_zero @[simp] lemma one_lt_succ_succ (n : ℕ) : 1 < n.succ.succ := succ_lt_succ $ succ_pos n theorem succ_le_succ_iff {m n : ℕ} : succ m ≤ succ n ↔ m ≤ n := ⟨le_of_succ_le_succ, succ_le_succ⟩ theorem max_succ_succ {m n : ℕ} : max (succ m) (succ n) = succ (max m n) := begin by_cases h1 : m ≤ n, rw [max_eq_right h1, max_eq_right (succ_le_succ h1)], { rw not_le at h1, have h2 := le_of_lt h1, rw [max_eq_left h2, max_eq_left (succ_le_succ h2)] } end lemma not_succ_lt_self {n : ℕ} : ¬succ n < n := not_lt_of_ge (nat.le_succ _) theorem lt_succ_iff {m n : ℕ} : m < succ n ↔ m ≤ n := ⟨le_of_lt_succ, lt_succ_of_le⟩ lemma succ_le_iff {m n : ℕ} : succ m ≤ n ↔ m < n := ⟨lt_of_succ_le, succ_le_of_lt⟩ lemma lt_iff_add_one_le {m n : ℕ} : m < n ↔ m + 1 ≤ n := by rw succ_le_iff -- Just a restatement of `nat.lt_succ_iff` using `+1`. lemma lt_add_one_iff {a b : ℕ} : a < b + 1 ↔ a ≤ b := lt_succ_iff -- A flipped version of `lt_add_one_iff`. lemma lt_one_add_iff {a b : ℕ} : a < 1 + b ↔ a ≤ b := by simp only [add_comm, lt_succ_iff] -- This is true reflexively, by the definition of `≤` on ℕ, -- but it's still useful to have, to convince Lean to change the syntactic type. lemma add_one_le_iff {a b : ℕ} : a + 1 ≤ b ↔ a < b := iff.refl _ lemma one_add_le_iff {a b : ℕ} : 1 + a ≤ b ↔ a < b := by simp only [add_comm, add_one_le_iff] theorem of_le_succ {n m : ℕ} (H : n ≤ m.succ) : n ≤ m ∨ n = m.succ := H.lt_or_eq_dec.imp le_of_lt_succ id lemma succ_lt_succ_iff {m n : ℕ} : succ m < succ n ↔ m < n := ⟨lt_of_succ_lt_succ, succ_lt_succ⟩ @[simp] lemma lt_one_iff {n : ℕ} : n < 1 ↔ n = 0 := lt_succ_iff.trans le_zero_iff lemma div_le_iff_le_mul_add_pred {m n k : ℕ} (n0 : 0 < n) : m / n ≤ k ↔ m ≤ n * k + (n - 1) := begin rw [← lt_succ_iff, div_lt_iff_lt_mul _ _ n0, succ_mul, mul_comm], cases n, {cases n0}, exact lt_succ_iff, end /-! ### `add` -/ -- Sometimes a bare `nat.add` or similar appears as a consequence of unfolding -- during pattern matching. These lemmas package them back up as typeclass -- mediated operations. @[simp] theorem add_def {a b : ℕ} : nat.add a b = a + b := rfl @[simp] theorem mul_def {a b : ℕ} : nat.mul a b = a * b := rfl attribute [simp] nat.add_sub_cancel nat.add_sub_cancel_left attribute [simp] nat.sub_self lemma exists_eq_add_of_le : ∀ {m n : ℕ}, m ≤ n → ∃ k : ℕ, n = m + k | 0 0 h := ⟨0, by simp⟩ | 0 (n+1) h := ⟨n+1, by simp⟩ | (m+1) (n+1) h := let ⟨k, hk⟩ := exists_eq_add_of_le (nat.le_of_succ_le_succ h) in ⟨k, by simp [hk, add_comm, add_left_comm]⟩ lemma exists_eq_add_of_lt : ∀ {m n : ℕ}, m < n → ∃ k : ℕ, n = m + k + 1 | 0 0 h := false.elim $ lt_irrefl _ h | 0 (n+1) h := ⟨n, by simp⟩ | (m+1) (n+1) h := let ⟨k, hk⟩ := exists_eq_add_of_le (nat.le_of_succ_le_succ h) in ⟨k, by simp [hk]⟩ theorem add_pos_left {m : ℕ} (h : 0 < m) (n : ℕ) : 0 < m + n := calc m + n > 0 + n : nat.add_lt_add_right h n ... = n : nat.zero_add n ... ≥ 0 : zero_le n theorem add_pos_right (m : ℕ) {n : ℕ} (h : 0 < n) : 0 < m + n := begin rw add_comm, exact add_pos_left h m end theorem add_pos_iff_pos_or_pos (m n : ℕ) : 0 < m + n ↔ 0 < m ∨ 0 < n := iff.intro begin intro h, cases m with m, {simp [zero_add] at h, exact or.inr h}, exact or.inl (succ_pos _) end begin intro h, cases h with mpos npos, { apply add_pos_left mpos }, apply add_pos_right _ npos end lemma add_eq_one_iff : ∀ {a b : ℕ}, a + b = 1 ↔ (a = 0 ∧ b = 1) ∨ (a = 1 ∧ b = 0) | 0 0 := dec_trivial | 0 1 := dec_trivial | 1 0 := dec_trivial | 1 1 := dec_trivial | (a+2) _ := by rw add_right_comm; exact dec_trivial | _ (b+2) := by rw [← add_assoc]; simp only [nat.succ_inj', nat.succ_ne_zero]; simp theorem le_add_one_iff {i j : ℕ} : i ≤ j + 1 ↔ (i ≤ j ∨ i = j + 1) := ⟨assume h, match nat.eq_or_lt_of_le h with | or.inl h := or.inr h | or.inr h := or.inl $ nat.le_of_succ_le_succ h end, or.rec (assume h, le_trans h $ nat.le_add_right _ _) le_of_eq⟩ lemma add_succ_lt_add {a b c d : ℕ} (hab : a < b) (hcd : c < d) : a + c + 1 < b + d := begin rw add_assoc, exact add_lt_add_of_lt_of_le hab (nat.succ_le_iff.2 hcd) end -- TODO: generalize to some ordered add_monoids, based on #6145 lemma le_of_add_le_left {a b c : ℕ} (h : a + b ≤ c) : a ≤ c := by { refine le_trans _ h, simp } lemma le_of_add_le_right {a b c : ℕ} (h : a + b ≤ c) : b ≤ c := by { refine le_trans _ h, simp } /-! ### `pred` -/ @[simp] lemma add_succ_sub_one (n m : ℕ) : (n + succ m) - 1 = n + m := by rw [add_succ, succ_sub_one] @[simp] lemma succ_add_sub_one (n m : ℕ) : (succ n + m) - 1 = n + m := by rw [succ_add, succ_sub_one] lemma pred_eq_sub_one (n : ℕ) : pred n = n - 1 := rfl theorem pred_eq_of_eq_succ {m n : ℕ} (H : m = n.succ) : m.pred = n := by simp [H] @[simp] lemma pred_eq_succ_iff {n m : ℕ} : pred n = succ m ↔ n = m + 2 := by cases n; split; rintro ⟨⟩; refl theorem pred_sub (n m : ℕ) : pred n - m = pred (n - m) := by rw [← sub_one, nat.sub_sub, one_add]; refl lemma le_pred_of_lt {n m : ℕ} (h : m < n) : m ≤ n - 1 := nat.sub_le_sub_right h 1 lemma le_of_pred_lt {m n : ℕ} : pred m < n → m ≤ n := match m with | 0 := le_of_lt | m+1 := id end /-- This ensures that `simp` succeeds on `pred (n + 1) = n`. -/ @[simp] lemma pred_one_add (n : ℕ) : pred (1 + n) = n := by rw [add_comm, add_one, pred_succ] /-! ### `sub` -/ protected theorem le_sub_add (n m : ℕ) : n ≤ n - m + m := or.elim (le_total n m) (assume : n ≤ m, begin rw [sub_eq_zero_of_le this, zero_add], exact this end) (assume : m ≤ n, begin rw (nat.sub_add_cancel this) end) theorem sub_add_eq_max (n m : ℕ) : n - m + m = max n m := eq_max (nat.le_sub_add _ _) (le_add_left _ _) $ λ k h₁ h₂, by rw ← nat.sub_add_cancel h₂; exact add_le_add_right (nat.sub_le_sub_right h₁ _) _ theorem add_sub_eq_max (n m : ℕ) : n + (m - n) = max n m := by rw [add_comm, max_comm, sub_add_eq_max] theorem sub_add_min (n m : ℕ) : n - m + min n m = n := (le_total n m).elim (λ h, by rw [min_eq_left h, sub_eq_zero_of_le h, zero_add]) (λ h, by rw [min_eq_right h, nat.sub_add_cancel h]) protected theorem add_sub_cancel' {n m : ℕ} (h : m ≤ n) : m + (n - m) = n := by rw [add_comm, nat.sub_add_cancel h] protected theorem sub_add_sub_cancel {a b c : ℕ} (hab : b ≤ a) (hbc : c ≤ b) : (a - b) + (b - c) = a - c := by rw [←nat.add_sub_assoc hbc, ←nat.sub_add_comm hab, nat.add_sub_cancel] protected theorem sub_eq_of_eq_add (h : k = m + n) : k - m = n := begin rw [h, nat.add_sub_cancel_left] end theorem sub_cancel {a b c : ℕ} (h₁ : a ≤ b) (h₂ : a ≤ c) (w : b - a = c - a) : b = c := by rw [←nat.sub_add_cancel h₁, ←nat.sub_add_cancel h₂, w] lemma sub_sub_sub_cancel_right {a b c : ℕ} (h₂ : c ≤ b) : (a - c) - (b - c) = a - b := by rw [nat.sub_sub, ←nat.add_sub_assoc h₂, nat.add_sub_cancel_left] lemma add_sub_cancel_right (n m k : ℕ) : n + (m + k) - k = n + m := by { rw [nat.add_sub_assoc, nat.add_sub_cancel], apply k.le_add_left } protected lemma sub_add_eq_add_sub {a b c : ℕ} (h : b ≤ a) : (a - b) + c = (a + c) - b := by rw [add_comm a, nat.add_sub_assoc h, add_comm] theorem sub_min (n m : ℕ) : n - min n m = n - m := nat.sub_eq_of_eq_add $ by rw [add_comm, sub_add_min] theorem sub_sub_assoc {a b c : ℕ} (h₁ : b ≤ a) (h₂ : c ≤ b) : a - (b - c) = a - b + c := (nat.sub_eq_iff_eq_add (le_trans (nat.sub_le _ _) h₁)).2 $ by rw [add_right_comm, add_assoc, nat.sub_add_cancel h₂, nat.sub_add_cancel h₁] protected theorem lt_of_sub_pos (h : 0 < n - m) : m < n := lt_of_not_ge (assume : n ≤ m, have n - m = 0, from sub_eq_zero_of_le this, begin rw this at h, exact lt_irrefl _ h end) protected theorem lt_of_sub_lt_sub_right : m - k < n - k → m < n := lt_imp_lt_of_le_imp_le (λ h, nat.sub_le_sub_right h _) protected theorem lt_of_sub_lt_sub_left : m - n < m - k → k < n := lt_imp_lt_of_le_imp_le (nat.sub_le_sub_left _) protected theorem sub_lt_self (h₁ : 0 < m) (h₂ : 0 < n) : m - n < m := calc m - n = succ (pred m) - succ (pred n) : by rw [succ_pred_eq_of_pos h₁, succ_pred_eq_of_pos h₂] ... = pred m - pred n : by rw succ_sub_succ ... ≤ pred m : sub_le _ _ ... < succ (pred m) : lt_succ_self _ ... = m : succ_pred_eq_of_pos h₁ protected theorem le_sub_right_of_add_le (h : m + k ≤ n) : m ≤ n - k := by rw ← nat.add_sub_cancel m k; exact nat.sub_le_sub_right h k protected theorem le_sub_left_of_add_le (h : k + m ≤ n) : m ≤ n - k := nat.le_sub_right_of_add_le (by rwa add_comm at h) protected theorem lt_sub_right_of_add_lt (h : m + k < n) : m < n - k := lt_of_succ_le $ nat.le_sub_right_of_add_le $ by rw succ_add; exact succ_le_of_lt h protected theorem lt_sub_left_of_add_lt (h : k + m < n) : m < n - k := nat.lt_sub_right_of_add_lt (by rwa add_comm at h) protected theorem add_lt_of_lt_sub_right (h : m < n - k) : m + k < n := @nat.lt_of_sub_lt_sub_right _ _ k (by rwa nat.add_sub_cancel) protected theorem add_lt_of_lt_sub_left (h : m < n - k) : k + m < n := by rw add_comm; exact nat.add_lt_of_lt_sub_right h protected theorem le_add_of_sub_le_right : n - k ≤ m → n ≤ m + k := le_imp_le_of_lt_imp_lt nat.lt_sub_right_of_add_lt protected theorem le_add_of_sub_le_left : n - k ≤ m → n ≤ k + m := le_imp_le_of_lt_imp_lt nat.lt_sub_left_of_add_lt protected theorem lt_add_of_sub_lt_right : n - k < m → n < m + k := lt_imp_lt_of_le_imp_le nat.le_sub_right_of_add_le protected theorem lt_add_of_sub_lt_left : n - k < m → n < k + m := lt_imp_lt_of_le_imp_le nat.le_sub_left_of_add_le protected theorem sub_le_left_of_le_add : n ≤ k + m → n - k ≤ m := le_imp_le_of_lt_imp_lt nat.add_lt_of_lt_sub_left protected theorem sub_le_right_of_le_add : n ≤ m + k → n - k ≤ m := le_imp_le_of_lt_imp_lt nat.add_lt_of_lt_sub_right protected theorem sub_lt_left_iff_lt_add (H : n ≤ k) : k - n < m ↔ k < n + m := ⟨nat.lt_add_of_sub_lt_left, λ h₁, have succ k ≤ n + m, from succ_le_of_lt h₁, have succ (k - n) ≤ m, from calc succ (k - n) = succ k - n : by rw (succ_sub H) ... ≤ n + m - n : nat.sub_le_sub_right this n ... = m : by rw nat.add_sub_cancel_left, lt_of_succ_le this⟩ protected theorem le_sub_left_iff_add_le (H : m ≤ k) : n ≤ k - m ↔ m + n ≤ k := le_iff_le_iff_lt_iff_lt.2 (nat.sub_lt_left_iff_lt_add H) protected theorem le_sub_right_iff_add_le (H : n ≤ k) : m ≤ k - n ↔ m + n ≤ k := by rw [nat.le_sub_left_iff_add_le H, add_comm] protected theorem lt_sub_left_iff_add_lt : n < k - m ↔ m + n < k := ⟨nat.add_lt_of_lt_sub_left, nat.lt_sub_left_of_add_lt⟩ protected theorem lt_sub_right_iff_add_lt : m < k - n ↔ m + n < k := by rw [nat.lt_sub_left_iff_add_lt, add_comm] theorem sub_le_left_iff_le_add : m - n ≤ k ↔ m ≤ n + k := le_iff_le_iff_lt_iff_lt.2 nat.lt_sub_left_iff_add_lt theorem sub_le_right_iff_le_add : m - k ≤ n ↔ m ≤ n + k := by rw [nat.sub_le_left_iff_le_add, add_comm] protected theorem sub_lt_right_iff_lt_add (H : k ≤ m) : m - k < n ↔ m < n + k := by rw [nat.sub_lt_left_iff_lt_add H, add_comm] protected theorem sub_le_sub_left_iff (H : k ≤ m) : m - n ≤ m - k ↔ k ≤ n := ⟨λ h, have k + (m - k) - n ≤ m - k, by rwa nat.add_sub_cancel' H, nat.le_of_add_le_add_right (nat.le_add_of_sub_le_left this), nat.sub_le_sub_left _⟩ protected theorem sub_lt_sub_right_iff (H : k ≤ m) : m - k < n - k ↔ m < n := lt_iff_lt_of_le_iff_le (nat.sub_le_sub_right_iff _ _ _ H) protected theorem sub_lt_sub_left_iff (H : n ≤ m) : m - n < m - k ↔ k < n := lt_iff_lt_of_le_iff_le (nat.sub_le_sub_left_iff H) protected theorem sub_le_iff : m - n ≤ k ↔ m - k ≤ n := nat.sub_le_left_iff_le_add.trans nat.sub_le_right_iff_le_add.symm protected lemma sub_le_self (n m : ℕ) : n - m ≤ n := nat.sub_le_left_of_le_add (nat.le_add_left _ _) protected theorem sub_lt_iff (h₁ : n ≤ m) (h₂ : k ≤ m) : m - n < k ↔ m - k < n := (nat.sub_lt_left_iff_lt_add h₁).trans (nat.sub_lt_right_iff_lt_add h₂).symm lemma pred_le_iff {n m : ℕ} : pred n ≤ m ↔ n ≤ succ m := @nat.sub_le_right_iff_le_add n m 1 lemma lt_pred_iff {n m : ℕ} : n < pred m ↔ succ n < m := @nat.lt_sub_right_iff_add_lt n 1 m lemma lt_of_lt_pred {a b : ℕ} (h : a < b - 1) : a < b := lt_of_succ_lt (lt_pred_iff.1 h) lemma le_or_le_of_add_eq_add_pred {a b c d : ℕ} (h : c + d = a + b - 1) : a ≤ c ∨ b ≤ d := begin cases le_or_lt a c with h' h'; [left, right], { exact h', }, { replace h' := add_lt_add_right h' d, rw h at h', cases b.eq_zero_or_pos with hb hb, { rw hb, exact zero_le d, }, rw [a.add_sub_assoc hb, add_lt_add_iff_left] at h', exact nat.le_of_pred_lt h', }, end /-! ### `mul` -/ lemma succ_mul_pos (m : ℕ) (hn : 0 < n) : 0 < (succ m) * n := mul_pos (succ_pos m) hn theorem mul_self_le_mul_self {n m : ℕ} (h : n ≤ m) : n * n ≤ m * m := decidable.mul_le_mul h h (zero_le _) (zero_le _) theorem mul_self_lt_mul_self : Π {n m : ℕ}, n < m → n * n < m * m | 0 m h := mul_pos h h | (succ n) m h := decidable.mul_lt_mul h (le_of_lt h) (succ_pos _) (zero_le _) theorem mul_self_le_mul_self_iff {n m : ℕ} : n ≤ m ↔ n * n ≤ m * m := ⟨mul_self_le_mul_self, le_imp_le_of_lt_imp_lt mul_self_lt_mul_self⟩ theorem mul_self_lt_mul_self_iff {n m : ℕ} : n < m ↔ n * n < m * m := le_iff_le_iff_lt_iff_lt.1 mul_self_le_mul_self_iff theorem le_mul_self : Π (n : ℕ), n ≤ n * n | 0 := le_refl _ | (n+1) := let t := mul_le_mul_left (n+1) (succ_pos n) in by simp at t; exact t lemma le_mul_of_pos_left {m n : ℕ} (h : 0 < n) : m ≤ n * m := begin conv {to_lhs, rw [← one_mul(m)]}, exact decidable.mul_le_mul_of_nonneg_right (nat.succ_le_of_lt h) dec_trivial, end lemma le_mul_of_pos_right {m n : ℕ} (h : 0 < n) : m ≤ m * n := begin conv {to_lhs, rw [← mul_one(m)]}, exact decidable.mul_le_mul_of_nonneg_left (nat.succ_le_of_lt h) dec_trivial, end theorem two_mul_ne_two_mul_add_one {n m} : 2 * n ≠ 2 * m + 1 := mt (congr_arg (%2)) (by { rw [add_comm, add_mul_mod_self_left, mul_mod_right, mod_eq_of_lt]; simp }) lemma mul_eq_one_iff : ∀ {a b : ℕ}, a * b = 1 ↔ a = 1 ∧ b = 1 | 0 0 := dec_trivial | 0 1 := dec_trivial | 1 0 := dec_trivial | (a+2) 0 := by simp | 0 (b+2) := by simp | (a+1) (b+1) := ⟨ λ h, by simp only [add_mul, mul_add, mul_add, one_mul, mul_one, (add_assoc _ _ _).symm, nat.succ_inj', add_eq_zero_iff] at h; simp [h.1.2, h.2], λ h, by simp only [h, mul_one]⟩ protected theorem mul_left_inj {a b c : ℕ} (ha : 0 < a) : b * a = c * a ↔ b = c := ⟨nat.eq_of_mul_eq_mul_right ha, λ e, e ▸ rfl⟩ protected theorem mul_right_inj {a b c : ℕ} (ha : 0 < a) : a * b = a * c ↔ b = c := ⟨nat.eq_of_mul_eq_mul_left ha, λ e, e ▸ rfl⟩ lemma mul_left_injective {a : ℕ} (ha : 0 < a) : function.injective (λ x, x * a) := λ _ _, eq_of_mul_eq_mul_right ha lemma mul_right_injective {a : ℕ} (ha : 0 < a) : function.injective (λ x, a * x) := λ _ _, eq_of_mul_eq_mul_left ha lemma mul_ne_mul_left {a b c : ℕ} (ha : 0 < a) : b * a ≠ c * a ↔ b ≠ c := (mul_left_injective ha).ne_iff lemma mul_ne_mul_right {a b c : ℕ} (ha : 0 < a) : a * b ≠ a * c ↔ b ≠ c := (mul_right_injective ha).ne_iff lemma mul_right_eq_self_iff {a b : ℕ} (ha : 0 < a) : a * b = a ↔ b = 1 := suffices a * b = a * 1 ↔ b = 1, by rwa mul_one at this, nat.mul_right_inj ha lemma mul_left_eq_self_iff {a b : ℕ} (hb : 0 < b) : a * b = b ↔ a = 1 := by rw [mul_comm, nat.mul_right_eq_self_iff hb] lemma lt_succ_iff_lt_or_eq {n i : ℕ} : n < i.succ ↔ (n < i ∨ n = i) := lt_succ_iff.trans decidable.le_iff_lt_or_eq theorem mul_self_inj {n m : ℕ} : n * n = m * m ↔ n = m := le_antisymm_iff.trans (le_antisymm_iff.trans (and_congr mul_self_le_mul_self_iff mul_self_le_mul_self_iff)).symm /-! ### Recursion and induction principles This section is here due to dependencies -- the lemmas here require some of the lemmas proved above, and some of the results in later sections depend on the definitions in this section. -/ @[simp] lemma rec_zero {C : ℕ → Sort u} (h0 : C 0) (h : ∀ n, C n → C (n + 1)) : (nat.rec h0 h : Π n, C n) 0 = h0 := rfl @[simp] lemma rec_add_one {C : ℕ → Sort u} (h0 : C 0) (h : ∀ n, C n → C (n + 1)) (n : ℕ) : (nat.rec h0 h : Π n, C n) (n + 1) = h n ((nat.rec h0 h : Π n, C n) n) := rfl /-- Recursion starting at a non-zero number: given a map `C k → C (k+1)` for each `k`, there is a map from `C n` to each `C m`, `n ≤ m`. -/ @[elab_as_eliminator] def le_rec_on {C : ℕ → Sort u} {n : ℕ} : Π {m : ℕ}, n ≤ m → (Π {k}, C k → C (k+1)) → C n → C m | 0 H next x := eq.rec_on (eq_zero_of_le_zero H) x | (m+1) H next x := or.by_cases (of_le_succ H) (λ h : n ≤ m, next $ le_rec_on h @next x) (λ h : n = m + 1, eq.rec_on h x) theorem le_rec_on_self {C : ℕ → Sort u} {n} {h : n ≤ n} {next} (x : C n) : (le_rec_on h next x : C n) = x := by cases n; unfold le_rec_on or.by_cases; rw [dif_neg n.not_succ_le_self, dif_pos rfl] theorem le_rec_on_succ {C : ℕ → Sort u} {n m} (h1 : n ≤ m) {h2 : n ≤ m+1} {next} (x : C n) : (le_rec_on h2 @next x : C (m+1)) = next (le_rec_on h1 @next x : C m) := by conv { to_lhs, rw [le_rec_on, or.by_cases, dif_pos h1] } theorem le_rec_on_succ' {C : ℕ → Sort u} {n} {h : n ≤ n+1} {next} (x : C n) : (le_rec_on h next x : C (n+1)) = next x := by rw [le_rec_on_succ (le_refl n), le_rec_on_self] theorem le_rec_on_trans {C : ℕ → Sort u} {n m k} (hnm : n ≤ m) (hmk : m ≤ k) {next} (x : C n) : (le_rec_on (le_trans hnm hmk) @next x : C k) = le_rec_on hmk @next (le_rec_on hnm @next x) := begin induction hmk with k hmk ih, { rw le_rec_on_self }, rw [le_rec_on_succ (le_trans hnm hmk), ih, le_rec_on_succ] end theorem le_rec_on_succ_left {C : ℕ → Sort u} {n m} (h1 : n ≤ m) (h2 : n+1 ≤ m) {next : Π{{k}}, C k → C (k+1)} (x : C n) : (le_rec_on h2 next (next x) : C m) = (le_rec_on h1 next x : C m) := begin rw [subsingleton.elim h1 (le_trans (le_succ n) h2), le_rec_on_trans (le_succ n) h2, le_rec_on_succ'] end theorem le_rec_on_injective {C : ℕ → Sort u} {n m} (hnm : n ≤ m) (next : Π n, C n → C (n+1)) (Hnext : ∀ n, function.injective (next n)) : function.injective (le_rec_on hnm next) := begin induction hnm with m hnm ih, { intros x y H, rwa [le_rec_on_self, le_rec_on_self] at H }, intros x y H, rw [le_rec_on_succ hnm, le_rec_on_succ hnm] at H, exact ih (Hnext _ H) end theorem le_rec_on_surjective {C : ℕ → Sort u} {n m} (hnm : n ≤ m) (next : Π n, C n → C (n+1)) (Hnext : ∀ n, function.surjective (next n)) : function.surjective (le_rec_on hnm next) := begin induction hnm with m hnm ih, { intros x, use x, rw le_rec_on_self }, intros x, rcases Hnext _ x with ⟨w, rfl⟩, rcases ih w with ⟨x, rfl⟩, use x, rw le_rec_on_succ end /-- Recursion principle based on `<`. -/ @[elab_as_eliminator] protected def strong_rec' {p : ℕ → Sort u} (H : ∀ n, (∀ m, m < n → p m) → p n) : ∀ (n : ℕ), p n | n := H n (λ m hm, strong_rec' m) /-- Recursion principle based on `<` applied to some natural number. -/ @[elab_as_eliminator] def strong_rec_on' {P : ℕ → Sort*} (n : ℕ) (h : ∀ n, (∀ m, m < n → P m) → P n) : P n := nat.strong_rec' h n theorem strong_rec_on_beta' {P : ℕ → Sort*} {h} {n : ℕ} : (strong_rec_on' n h : P n) = h n (λ m hmn, (strong_rec_on' m h : P m)) := by { simp only [strong_rec_on'], rw nat.strong_rec' } /-- Induction principle starting at a non-zero number. For maps to a `Sort*` see `le_rec_on`. -/ @[elab_as_eliminator] lemma le_induction {P : nat → Prop} {m} (h0 : P m) (h1 : ∀ n, m ≤ n → P n → P (n + 1)) : ∀ n, m ≤ n → P n := by apply nat.less_than_or_equal.rec h0; exact h1 /-- Decreasing induction: if `P (k+1)` implies `P k`, then `P n` implies `P m` for all `m ≤ n`. Also works for functions to `Sort*`. -/ @[elab_as_eliminator] def decreasing_induction {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (mn : m ≤ n) (hP : P n) : P m := le_rec_on mn (λ k ih hsk, ih $ h k hsk) (λ h, h) hP @[simp] lemma decreasing_induction_self {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {n : ℕ} (nn : n ≤ n) (hP : P n) : (decreasing_induction h nn hP : P n) = hP := by { dunfold decreasing_induction, rw [le_rec_on_self] } lemma decreasing_induction_succ {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (mn : m ≤ n) (msn : m ≤ n + 1) (hP : P (n+1)) : (decreasing_induction h msn hP : P m) = decreasing_induction h mn (h n hP) := by { dunfold decreasing_induction, rw [le_rec_on_succ] } @[simp] lemma decreasing_induction_succ' {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m : ℕ} (msm : m ≤ m + 1) (hP : P (m+1)) : (decreasing_induction h msm hP : P m) = h m hP := by { dunfold decreasing_induction, rw [le_rec_on_succ'] } lemma decreasing_induction_trans {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n k : ℕ} (mn : m ≤ n) (nk : n ≤ k) (hP : P k) : (decreasing_induction h (le_trans mn nk) hP : P m) = decreasing_induction h mn (decreasing_induction h nk hP) := by { induction nk with k nk ih, rw [decreasing_induction_self], rw [decreasing_induction_succ h (le_trans mn nk), ih, decreasing_induction_succ] } lemma decreasing_induction_succ_left {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (smn : m + 1 ≤ n) (mn : m ≤ n) (hP : P n) : (decreasing_induction h mn hP : P m) = h m (decreasing_induction h smn hP) := by { rw [subsingleton.elim mn (le_trans (le_succ m) smn), decreasing_induction_trans, decreasing_induction_succ'] } /-! ### `div` -/ attribute [simp] nat.div_self protected lemma div_le_of_le_mul' {m n : ℕ} {k} (h : m ≤ k * n) : m / k ≤ n := (eq_zero_or_pos k).elim (λ k0, by rw [k0, nat.div_zero]; apply zero_le) (λ k0, (_root_.mul_le_mul_left k0).1 $ calc k * (m / k) ≤ m % k + k * (m / k) : le_add_left _ _ ... = m : mod_add_div _ _ ... ≤ k * n : h) protected lemma div_le_self' (m n : ℕ) : m / n ≤ m := (eq_zero_or_pos n).elim (λ n0, by rw [n0, nat.div_zero]; apply zero_le) (λ n0, nat.div_le_of_le_mul' $ calc m = 1 * m : (one_mul _).symm ... ≤ n * m : mul_le_mul_right _ n0) /-- A version of `nat.div_lt_self` using successors, rather than additional hypotheses. -/ lemma div_lt_self' (n b : ℕ) : (n+1)/(b+2) < n+1 := nat.div_lt_self (nat.succ_pos n) (nat.succ_lt_succ (nat.succ_pos _)) theorem le_div_iff_mul_le' {x y : ℕ} {k : ℕ} (k0 : 0 < k) : x ≤ y / k ↔ x * k ≤ y := le_div_iff_mul_le x y k0 theorem div_lt_iff_lt_mul' {x y : ℕ} {k : ℕ} (k0 : 0 < k) : x / k < y ↔ x < y * k := lt_iff_lt_of_le_iff_le $ le_div_iff_mul_le' k0 protected theorem div_le_div_right {n m : ℕ} (h : n ≤ m) {k : ℕ} : n / k ≤ m / k := (nat.eq_zero_or_pos k).elim (λ k0, by simp [k0]) $ λ hk, (le_div_iff_mul_le' hk).2 $ le_trans (nat.div_mul_le_self _ _) h lemma lt_of_div_lt_div {m n k : ℕ} : m / k < n / k → m < n := lt_imp_lt_of_le_imp_le $ λ h, nat.div_le_div_right h protected lemma div_pos {a b : ℕ} (hba : b ≤ a) (hb : 0 < b) : 0 < a / b := nat.pos_of_ne_zero (λ h, lt_irrefl a (calc a = a % b : by simpa [h] using (mod_add_div a b).symm ... < b : nat.mod_lt a hb ... ≤ a : hba)) protected lemma div_lt_of_lt_mul {m n k : ℕ} (h : m < n * k) : m / n < k := lt_of_mul_lt_mul_left (calc n * (m / n) ≤ m % n + n * (m / n) : nat.le_add_left _ _ ... = m : mod_add_div _ _ ... < n * k : h) (nat.zero_le n) lemma lt_mul_of_div_lt {a b c : ℕ} (h : a / c < b) (w : 0 < c) : a < b * c := lt_of_not_ge $ not_le_of_gt h ∘ (nat.le_div_iff_mul_le _ _ w).2 protected lemma div_eq_zero_iff {a b : ℕ} (hb : 0 < b) : a / b = 0 ↔ a < b := ⟨λ h, by rw [← mod_add_div a b, h, mul_zero, add_zero]; exact mod_lt _ hb, λ h, by rw [← nat.mul_right_inj hb, ← @add_left_cancel_iff _ _ (a % b), mod_add_div, mod_eq_of_lt h, mul_zero, add_zero]⟩ protected lemma div_eq_zero {a b : ℕ} (hb : a < b) : a / b = 0 := (nat.div_eq_zero_iff $ (zero_le a).trans_lt hb).mpr hb lemma eq_zero_of_le_div {a b : ℕ} (hb : 2 ≤ b) (h : a ≤ a / b) : a = 0 := eq_zero_of_mul_le hb $ by rw mul_comm; exact (nat.le_div_iff_mul_le' (lt_of_lt_of_le dec_trivial hb)).1 h lemma mul_div_le_mul_div_assoc (a b c : ℕ) : a * (b / c) ≤ (a * b) / c := if hc0 : c = 0 then by simp [hc0] else (nat.le_div_iff_mul_le _ _ (nat.pos_of_ne_zero hc0)).2 (by rw [mul_assoc]; exact mul_le_mul_left _ (nat.div_mul_le_self _ _)) lemma div_mul_div_le_div (a b c : ℕ) : ((a / c) * b) / a ≤ b / c := if ha0 : a = 0 then by simp [ha0] else calc a / c * b / a ≤ b * a / c / a : nat.div_le_div_right (by rw [mul_comm]; exact mul_div_le_mul_div_assoc _ _ _) ... = b / c : by rw [nat.div_div_eq_div_mul, mul_comm b, mul_comm c, nat.mul_div_mul _ _ (nat.pos_of_ne_zero ha0)] lemma eq_zero_of_le_half {a : ℕ} (h : a ≤ a / 2) : a = 0 := eq_zero_of_le_div (le_refl _) h protected theorem eq_mul_of_div_eq_right {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := by rw [← H2, nat.mul_div_cancel' H1] protected theorem div_eq_iff_eq_mul_right {a b c : ℕ} (H : 0 < b) (H' : b ∣ a) : a / b = c ↔ a = b * c := ⟨nat.eq_mul_of_div_eq_right H', nat.div_eq_of_eq_mul_right H⟩ protected theorem div_eq_iff_eq_mul_left {a b c : ℕ} (H : 0 < b) (H' : b ∣ a) : a / b = c ↔ a = c * b := by rw mul_comm; exact nat.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_left {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := by rw [mul_comm, nat.eq_mul_of_div_eq_right H1 H2] protected theorem mul_div_cancel_left' {a b : ℕ} (Hd : a ∣ b) : a * (b / a) = b := by rw [mul_comm,nat.div_mul_cancel Hd] /-! ### `mod`, `dvd` -/ lemma div_add_mod (m k : ℕ) : k * (m / k) + m % k = m := (nat.add_comm _ _).trans (mod_add_div _ _) lemma mod_add_div' (m k : ℕ) : m % k + (m / k) * k = m := by { rw mul_comm, exact mod_add_div _ _ } lemma div_add_mod' (m k : ℕ) : (m / k) * k + m % k = m := by { rw mul_comm, exact div_add_mod _ _ } protected theorem div_mod_unique {n k m d : ℕ} (h : 0 < k) : n / k = d ∧ n % k = m ↔ m + k * d = n ∧ m < k := ⟨λ ⟨e₁, e₂⟩, e₁ ▸ e₂ ▸ ⟨mod_add_div _ _, mod_lt _ h⟩, λ ⟨h₁, h₂⟩, h₁ ▸ by rw [add_mul_div_left _ _ h, add_mul_mod_self_left]; simp [div_eq_of_lt, mod_eq_of_lt, h₂]⟩ lemma two_mul_odd_div_two {n : ℕ} (hn : n % 2 = 1) : 2 * (n / 2) = n - 1 := by conv {to_rhs, rw [← nat.mod_add_div n 2, hn, nat.add_sub_cancel_left]} lemma div_dvd_of_dvd {a b : ℕ} (h : b ∣ a) : (a / b) ∣ a := ⟨b, (nat.div_mul_cancel h).symm⟩ protected lemma div_div_self : ∀ {a b : ℕ}, b ∣ a → 0 < a → a / (a / b) = b | a 0 h₁ h₂ := by rw [eq_zero_of_zero_dvd h₁, nat.div_zero, nat.div_zero] | 0 b h₁ h₂ := absurd h₂ dec_trivial | (a+1) (b+1) h₁ h₂ := (nat.mul_left_inj (nat.div_pos (le_of_dvd (succ_pos a) h₁) (succ_pos b))).1 $ by rw [nat.div_mul_cancel (div_dvd_of_dvd h₁), nat.mul_div_cancel' h₁] lemma mod_mul_right_div_self (a b c : ℕ) : a % (b * c) / b = (a / b) % c := begin rcases eq_zero_or_pos b with rfl|hb, { simp }, rcases eq_zero_or_pos c with rfl|hc, { simp }, conv_rhs { rw ← mod_add_div a (b * c) }, rw [mul_assoc, nat.add_mul_div_left _ _ hb, add_mul_mod_self_left, mod_eq_of_lt (nat.div_lt_of_lt_mul (mod_lt _ (mul_pos hb hc)))] end lemma mod_mul_left_div_self (a b c : ℕ) : a % (c * b) / b = (a / b) % c := by rw [mul_comm c, mod_mul_right_div_self] @[simp] protected theorem dvd_one {n : ℕ} : n ∣ 1 ↔ n = 1 := ⟨eq_one_of_dvd_one, λ e, e.symm ▸ dvd_refl _⟩ protected theorem dvd_add_left {k m n : ℕ} (h : k ∣ n) : k ∣ m + n ↔ k ∣ m := (nat.dvd_add_iff_left h).symm protected theorem dvd_add_right {k m n : ℕ} (h : k ∣ m) : k ∣ m + n ↔ k ∣ n := (nat.dvd_add_iff_right h).symm @[simp] protected theorem not_two_dvd_bit1 (n : ℕ) : ¬ 2 ∣ bit1 n := by { rw [bit1, nat.dvd_add_right two_dvd_bit0, nat.dvd_one], cc } /-- A natural number `m` divides the sum `m + n` if and only if `m` divides `n`.-/ @[simp] protected lemma dvd_add_self_left {m n : ℕ} : m ∣ m + n ↔ m ∣ n := nat.dvd_add_right (dvd_refl m) /-- A natural number `m` divides the sum `n + m` if and only if `m` divides `n`.-/ @[simp] protected lemma dvd_add_self_right {m n : ℕ} : m ∣ n + m ↔ m ∣ n := nat.dvd_add_left (dvd_refl m) -- TODO: update `nat.dvd_sub` in core lemma dvd_sub' {k m n : ℕ} (h₁ : k ∣ m) (h₂ : k ∣ n) : k ∣ m - n := begin cases le_total n m with H H, { exact dvd_sub H h₁ h₂ }, { rw nat.sub_eq_zero_of_le H, exact dvd_zero k }, end lemma not_dvd_of_pos_of_lt {a b : ℕ} (h1 : 0 < b) (h2 : b < a) : ¬ a ∣ b := begin rintros ⟨c, rfl⟩, rcases eq_zero_or_pos c with (rfl | hc), { exact lt_irrefl 0 h1 }, { exact not_lt.2 (le_mul_of_pos_right hc) h2 }, end protected theorem mul_dvd_mul_iff_left {a b c : ℕ} (ha : 0 < a) : a * b ∣ a * c ↔ b ∣ c := exists_congr $ λ d, by rw [mul_assoc, nat.mul_right_inj ha] protected theorem mul_dvd_mul_iff_right {a b c : ℕ} (hc : 0 < c) : a * c ∣ b * c ↔ a ∣ b := exists_congr $ λ d, by rw [mul_right_comm, nat.mul_left_inj hc] lemma succ_div : ∀ (a b : ℕ), (a + 1) / b = a / b + if b ∣ a + 1 then 1 else 0 | a 0 := by simp | 0 1 := by simp | 0 (b+2) := have hb2 : b + 2 > 1, from dec_trivial, by simp [ne_of_gt hb2, div_eq_of_lt hb2] | (a+1) (b+1) := begin rw [nat.div_def], conv_rhs { rw nat.div_def }, by_cases hb_eq_a : b = a + 1, { simp [hb_eq_a, le_refl] }, by_cases hb_le_a1 : b ≤ a + 1, { have hb_le_a : b ≤ a, from le_of_lt_succ (lt_of_le_of_ne hb_le_a1 hb_eq_a), have h₁ : (0 < b + 1 ∧ b + 1 ≤ a + 1 + 1), from ⟨succ_pos _, (add_le_add_iff_right _).2 hb_le_a1⟩, have h₂ : (0 < b + 1 ∧ b + 1 ≤ a + 1), from ⟨succ_pos _, (add_le_add_iff_right _).2 hb_le_a⟩, have dvd_iff : b + 1 ∣ a - b + 1 ↔ b + 1 ∣ a + 1 + 1, { rw [nat.dvd_add_iff_left (dvd_refl (b + 1)), ← nat.add_sub_add_right a 1 b, add_comm (_ - _), add_assoc, nat.sub_add_cancel (succ_le_succ hb_le_a), add_comm 1] }, have wf : a - b < a + 1, from lt_succ_of_le (nat.sub_le_self _ _), rw [if_pos h₁, if_pos h₂, nat.add_sub_add_right, nat.sub_add_comm hb_le_a, by exact have _ := wf, succ_div (a - b), nat.add_sub_add_right], simp [dvd_iff, succ_eq_add_one, add_comm 1, add_assoc] }, { have hba : ¬ b ≤ a, from not_le_of_gt (lt_trans (lt_succ_self a) (lt_of_not_ge hb_le_a1)), have hb_dvd_a : ¬ b + 1 ∣ a + 2, from λ h, hb_le_a1 (le_of_succ_le_succ (le_of_dvd (succ_pos _) h)), simp [hba, hb_le_a1, hb_dvd_a], } end lemma succ_div_of_dvd {a b : ℕ} (hba : b ∣ a + 1) : (a + 1) / b = a / b + 1 := by rw [succ_div, if_pos hba] lemma succ_div_of_not_dvd {a b : ℕ} (hba : ¬ b ∣ a + 1) : (a + 1) / b = a / b := by rw [succ_div, if_neg hba, add_zero] @[simp] theorem mod_mod_of_dvd (n : nat) {m k : nat} (h : m ∣ k) : n % k % m = n % m := begin conv { to_rhs, rw ←mod_add_div n k }, rcases h with ⟨t, rfl⟩, rw [mul_assoc, add_mul_mod_self_left] end @[simp] theorem mod_mod (a n : ℕ) : (a % n) % n = a % n := (eq_zero_or_pos n).elim (λ n0, by simp [n0]) (λ npos, mod_eq_of_lt (mod_lt _ npos)) /-- If `a` and `b` are equal mod `c`, `a - b` is zero mod `c`. -/ lemma sub_mod_eq_zero_of_mod_eq {a b c : ℕ} (h : a % c = b % c) : (a - b) % c = 0 := by rw [←nat.mod_add_div a c, ←nat.mod_add_div b c, ←h, ←nat.sub_sub, nat.add_sub_cancel_left, ←nat.mul_sub_left_distrib, nat.mul_mod_right] @[simp] lemma one_mod (n : ℕ) : 1 % (n + 2) = 1 := nat.mod_eq_of_lt (add_lt_add_right n.succ_pos 1) lemma dvd_sub_mod (k : ℕ) : n ∣ (k - (k % n)) := ⟨k / n, nat.sub_eq_of_eq_add (nat.mod_add_div k n).symm⟩ @[simp] theorem mod_add_mod (m n k : ℕ) : (m % n + k) % n = (m + k) % n := by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm; rwa [add_right_comm, mod_add_div] at this @[simp] theorem add_mod_mod (m n k : ℕ) : (m + n % k) % k = (m + n) % k := by rw [add_comm, mod_add_mod, add_comm] lemma add_mod (a b n : ℕ) : (a + b) % n = ((a % n) + (b % n)) % n := by rw [add_mod_mod, mod_add_mod] theorem add_mod_eq_add_mod_right {m n k : ℕ} (i : ℕ) (H : m % n = k % n) : (m + i) % n = (k + i) % n := by rw [← mod_add_mod, ← mod_add_mod k, H] theorem add_mod_eq_add_mod_left {m n k : ℕ} (i : ℕ) (H : m % n = k % n) : (i + m) % n = (i + k) % n := by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm] lemma add_mod_eq_ite {a b n : ℕ} : (a + b) % n = if n ≤ a % n + b % n then a % n + b % n - n else a % n + b % n := begin cases n, { simp }, rw nat.add_mod, split_ifs with h, { rw [nat.mod_eq_sub_mod h, nat.mod_eq_of_lt], exact (nat.sub_lt_right_iff_lt_add h).mpr (nat.add_lt_add (a.mod_lt n.zero_lt_succ) (b.mod_lt n.zero_lt_succ)) }, { exact nat.mod_eq_of_lt (lt_of_not_ge h) } end lemma mul_mod (a b n : ℕ) : (a * b) % n = ((a % n) * (b % n)) % n := begin conv_lhs { rw [←mod_add_div a n, ←mod_add_div' b n, right_distrib, left_distrib, left_distrib, mul_assoc, mul_assoc, ←left_distrib n _ _, add_mul_mod_self_left, ← mul_assoc, add_mul_mod_self_right] } end lemma dvd_div_of_mul_dvd {a b c : ℕ} (h : a * b ∣ c) : b ∣ c / a := if ha : a = 0 then by simp [ha] else have ha : 0 < a, from nat.pos_of_ne_zero ha, have h1 : ∃ d, c = a * b * d, from h, let ⟨d, hd⟩ := h1 in have h2 : c / a = b * d, from nat.div_eq_of_eq_mul_right ha (by simpa [mul_assoc] using hd), show ∃ d, c / a = b * d, from ⟨d, h2⟩ lemma mul_dvd_of_dvd_div {a b c : ℕ} (hab : c ∣ b) (h : a ∣ b / c) : c * a ∣ b := have h1 : ∃ d, b / c = a * d, from h, have h2 : ∃ e, b = c * e, from hab, let ⟨d, hd⟩ := h1, ⟨e, he⟩ := h2 in have h3 : b = a * d * c, from nat.eq_mul_of_div_eq_left hab hd, show ∃ d, b = c * a * d, from ⟨d, by cc⟩ lemma div_mul_div {a b c d : ℕ} (hab : b ∣ a) (hcd : d ∣ c) : (a / b) * (c / d) = (a * c) / (b * d) := have exi1 : ∃ x, a = b * x, from hab, have exi2 : ∃ y, c = d * y, from hcd, if hb : b = 0 then by simp [hb] else have 0 < b, from nat.pos_of_ne_zero hb, if hd : d = 0 then by simp [hd] else have 0 < d, from nat.pos_of_ne_zero hd, begin cases exi1 with x hx, cases exi2 with y hy, rw [hx, hy, nat.mul_div_cancel_left, nat.mul_div_cancel_left], symmetry, apply nat.div_eq_of_eq_mul_left, apply mul_pos, repeat {assumption}, cc end @[simp] lemma div_div_div_eq_div : ∀ {a b c : ℕ} (dvd : b ∣ a) (dvd2 : a ∣ c), (c / (a / b)) / b = c / a | 0 _ := by simp | (a + 1) 0 := λ _ dvd _, by simpa using dvd | (a + 1) (c + 1) := have a_split : a + 1 ≠ 0 := succ_ne_zero a, have c_split : c + 1 ≠ 0 := succ_ne_zero c, λ b dvd dvd2, begin rcases dvd2 with ⟨k, rfl⟩, rcases dvd with ⟨k2, pr⟩, have k2_nonzero : k2 ≠ 0 := λ k2_zero, by simpa [k2_zero] using pr, rw [nat.mul_div_cancel_left k (nat.pos_of_ne_zero a_split), pr, nat.mul_div_cancel_left k2 (nat.pos_of_ne_zero c_split), nat.mul_comm ((c + 1) * k2) k, ←nat.mul_assoc k (c + 1) k2, nat.mul_div_cancel _ (nat.pos_of_ne_zero k2_nonzero), nat.mul_div_cancel _ (nat.pos_of_ne_zero c_split)], end lemma eq_of_dvd_of_div_eq_one {a b : ℕ} (w : a ∣ b) (h : b / a = 1) : a = b := by rw [←nat.div_mul_cancel w, h, one_mul] lemma eq_zero_of_dvd_of_div_eq_zero {a b : ℕ} (w : a ∣ b) (h : b / a = 0) : b = 0 := by rw [←nat.div_mul_cancel w, h, zero_mul] /-- If a small natural number is divisible by a larger natural number, the small number is zero. -/ lemma eq_zero_of_dvd_of_lt {a b : ℕ} (w : a ∣ b) (h : b < a) : b = 0 := nat.eq_zero_of_dvd_of_div_eq_zero w ((nat.div_eq_zero_iff (lt_of_le_of_lt (zero_le b) h)).elim_right h) lemma div_le_div_left {a b c : ℕ} (h₁ : c ≤ b) (h₂ : 0 < c) : a / b ≤ a / c := (nat.le_div_iff_mul_le _ _ h₂).2 $ le_trans (mul_le_mul_left _ h₁) (div_mul_le_self _ _) lemma div_eq_self {a b : ℕ} : a / b = a ↔ a = 0 ∨ b = 1 := begin split, { intro, cases b, { simp * at * }, { cases b, { right, refl }, { left, have : a / (b + 2) ≤ a / 2 := div_le_div_left (by simp) dec_trivial, refine eq_zero_of_le_half _, simp * at * } } }, { rintros (rfl|rfl); simp } end lemma lt_iff_le_pred : ∀ {m n : ℕ}, 0 < n → (m < n ↔ m ≤ n - 1) | m (n+1) _ := lt_succ_iff lemma div_eq_sub_mod_div {m n : ℕ} : m / n = (m - m % n) / n := begin by_cases n0 : n = 0, { rw [n0, nat.div_zero, nat.div_zero] }, { rw [← mod_add_div m n] { occs := occurrences.pos [2] }, rw [nat.add_sub_cancel_left, mul_div_right _ (nat.pos_of_ne_zero n0)] } end lemma mul_div_le (m n : ℕ) : n * (m / n) ≤ m := begin cases nat.eq_zero_or_pos n with n0 h, { rw [n0, zero_mul], exact m.zero_le }, { rw [mul_comm, ← nat.le_div_iff_mul_le' h] }, end lemma lt_mul_div_succ (m : ℕ) {n : ℕ} (n0 : 0 < n) : m < n * ((m / n) + 1) := begin rw [mul_comm, ← nat.div_lt_iff_lt_mul' n0], exact lt_succ_self _ end @[simp] lemma mod_div_self (m n : ℕ) : m % n / n = 0 := begin cases n, { exact (m % 0).div_zero }, { exact nat.div_eq_zero (m.mod_lt n.succ_pos) } end /-- `m` is not divisible by `n` iff it is between `n * k` and `n * (k + 1)` for some `k`. -/ lemma exists_lt_and_lt_iff_not_dvd (m : ℕ) {n : ℕ} (hn : 0 < n) : (∃ k, n * k < m ∧ m < n * (k + 1)) ↔ ¬ n ∣ m := begin split, { rintro ⟨k, h1k, h2k⟩ ⟨l, rfl⟩, rw [mul_lt_mul_left hn] at h1k h2k, rw [lt_succ_iff, ← not_lt] at h2k, exact h2k h1k }, { intro h, rw [dvd_iff_mod_eq_zero, ← ne.def, ← pos_iff_ne_zero] at h, simp only [← mod_add_div m n] {single_pass := tt}, refine ⟨m / n, lt_add_of_pos_left _ h, _⟩, rw [add_comm _ 1, left_distrib, mul_one], exact add_lt_add_right (mod_lt _ hn) _ } end /-- Two natural numbers are equal if and only if the have the same multiples. -/ lemma dvd_right_iff_eq {m n : ℕ} : (∀ a : ℕ, m ∣ a ↔ n ∣ a) ↔ m = n := ⟨λ h, dvd_antisymm ((h _).mpr (dvd_refl _)) ((h _).mp (dvd_refl _)), λ h n, by rw h⟩ /-- Two natural numbers are equal if and only if the have the same divisors. -/ lemma dvd_left_iff_eq {m n : ℕ} : (∀ a : ℕ, a ∣ m ↔ a ∣ n) ↔ m = n := ⟨λ h, dvd_antisymm ((h _).mp (dvd_refl _)) ((h _).mpr (dvd_refl _)), λ h n, by rw h⟩ /-- `dvd` is injective in the left argument -/ lemma dvd_left_injective : function.injective ((∣) : ℕ → ℕ → Prop) := λ m n h, dvd_right_iff_eq.mp $ λ a, iff_of_eq (congr_fun h a) /-! ### `find` -/ section find variables {p q : ℕ → Prop} [decidable_pred p] [decidable_pred q] lemma find_eq_iff (h : ∃ n : ℕ, p n) : nat.find h = m ↔ p m ∧ ∀ n < m, ¬ p n := begin split, { rintro rfl, exact ⟨nat.find_spec h, λ _, nat.find_min h⟩ }, { rintro ⟨hm, hlt⟩, exact le_antisymm (nat.find_min' h hm) (not_lt.1 $ imp_not_comm.1 (hlt _) $ nat.find_spec h) } end @[simp] lemma find_lt_iff (h : ∃ n : ℕ, p n) (n : ℕ) : nat.find h < n ↔ ∃ m < n, p m := ⟨λ h2, ⟨nat.find h, h2, nat.find_spec h⟩, λ ⟨m, hmn, hm⟩, (nat.find_min' h hm).trans_lt hmn⟩ @[simp] lemma find_le_iff (h : ∃ n : ℕ, p n) (n : ℕ) : nat.find h ≤ n ↔ ∃ m ≤ n, p m := by simp only [exists_prop, ← lt_succ_iff, find_lt_iff] @[simp] lemma le_find_iff (h : ∃ (n : ℕ), p n) (n : ℕ) : n ≤ nat.find h ↔ ∀ m < n, ¬ p m := by simp_rw [← not_lt, find_lt_iff, not_exists] @[simp] lemma lt_find_iff (h : ∃ n : ℕ, p n) (n : ℕ) : n < nat.find h ↔ ∀ m ≤ n, ¬ p m := by simp only [← succ_le_iff, le_find_iff, succ_le_succ_iff] @[simp] lemma find_eq_zero (h : ∃ n : ℕ, p n) : nat.find h = 0 ↔ p 0 := by simp [find_eq_iff] @[simp] lemma find_pos (h : ∃ n : ℕ, p n) : 0 < nat.find h ↔ ¬ p 0 := by rw [pos_iff_ne_zero, ne, nat.find_eq_zero] theorem find_le (h : ∀ n, q n → p n) (hp : ∃ n, p n) (hq : ∃ n, q n) : nat.find hp ≤ nat.find hq := nat.find_min' _ (h _ (nat.find_spec hq)) lemma find_comp_succ (h₁ : ∃ n, p n) (h₂ : ∃ n, p (n + 1)) (h0 : ¬ p 0) : nat.find h₁ = nat.find h₂ + 1 := begin refine (find_eq_iff _).2 ⟨nat.find_spec h₂, λ n hn, _⟩, cases n with n, exacts [h0, @nat.find_min (λ n, p (n + 1)) _ h₂ _ (succ_lt_succ_iff.1 hn)] end end find /-! ### `find_greatest` -/ section find_greatest /-- `find_greatest P b` is the largest `i ≤ bound` such that `P i` holds, or `0` if no such `i` exists -/ protected def find_greatest (P : ℕ → Prop) [decidable_pred P] : ℕ → ℕ | 0 := 0 | (n + 1) := if P (n + 1) then n + 1 else find_greatest n variables {P : ℕ → Prop} [decidable_pred P] @[simp] lemma find_greatest_zero : nat.find_greatest P 0 = 0 := rfl @[simp] lemma find_greatest_eq : ∀{b}, P b → nat.find_greatest P b = b | 0 h := rfl | (n + 1) h := by simp [nat.find_greatest, h] @[simp] lemma find_greatest_of_not {b} (h : ¬ P (b + 1)) : nat.find_greatest P (b + 1) = nat.find_greatest P b := by simp [nat.find_greatest, h] lemma find_greatest_eq_iff {b m} : nat.find_greatest P b = m ↔ m ≤ b ∧ (m ≠ 0 → P m) ∧ (∀ ⦃n⦄, m < n → n ≤ b → ¬P n) := begin induction b with b ihb generalizing m, { rw [eq_comm, iff.comm], simp only [nonpos_iff_eq_zero, ne.def, and_iff_left_iff_imp, find_greatest_zero], rintro rfl, exact ⟨λ h, (h rfl).elim, λ n hlt heq, (hlt.ne heq.symm).elim⟩ }, { by_cases hb : P (b + 1), { rw [find_greatest_eq hb], split, { rintro rfl, exact ⟨le_refl _, λ _, hb, λ n hlt hle, (hlt.not_le hle).elim⟩ }, { rintros ⟨hle, h0, hm⟩, rcases decidable.eq_or_lt_of_le hle with rfl|hlt, exacts [rfl, (hm hlt (le_refl _) hb).elim] } }, { rw [find_greatest_of_not hb, ihb], split, { rintros ⟨hle, hP, hm⟩, refine ⟨hle.trans b.le_succ, hP, λ n hlt hle, _⟩, rcases decidable.eq_or_lt_of_le hle with rfl|hlt', exacts [hb, hm hlt $ lt_succ_iff.1 hlt'] }, { rintros ⟨hle, hP, hm⟩, refine ⟨lt_succ_iff.1 (hle.lt_of_ne _), hP, λ n hlt hle, hm hlt (hle.trans b.le_succ)⟩, rintro rfl, exact hb (hP b.succ_ne_zero) } } } end lemma find_greatest_eq_zero_iff {b} : nat.find_greatest P b = 0 ↔ ∀ ⦃n⦄, 0 < n → n ≤ b → ¬P n := by simp [find_greatest_eq_iff] lemma find_greatest_spec {b} (h : ∃m, m ≤ b ∧ P m) : P (nat.find_greatest P b) := begin rcases h with ⟨m, hmb, hm⟩, by_cases h : nat.find_greatest P b = 0, { cases m, { rwa h }, exact ((find_greatest_eq_zero_iff.1 h) m.zero_lt_succ hmb hm).elim }, { exact (find_greatest_eq_iff.1 rfl).2.1 h } end lemma find_greatest_le {b} : nat.find_greatest P b ≤ b := (find_greatest_eq_iff.1 rfl).1 lemma le_find_greatest {b m} (hmb : m ≤ b) (hm : P m) : m ≤ nat.find_greatest P b := le_of_not_lt $ λ hlt, (find_greatest_eq_iff.1 rfl).2.2 hlt hmb hm lemma find_greatest_is_greatest {b k} (hk : nat.find_greatest P b < k) (hkb : k ≤ b) : ¬ P k := (find_greatest_eq_iff.1 rfl).2.2 hk hkb lemma find_greatest_of_ne_zero {b m} (h : nat.find_greatest P b = m) (h0 : m ≠ 0) : P m := (find_greatest_eq_iff.1 h).2.1 h0 end find_greatest /-! ### `bodd_div2` and `bodd` -/ @[simp] theorem bodd_div2_eq (n : ℕ) : bodd_div2 n = (bodd n, div2 n) := by unfold bodd div2; cases bodd_div2 n; refl @[simp] lemma bodd_bit0 (n) : bodd (bit0 n) = ff := bodd_bit ff n @[simp] lemma bodd_bit1 (n) : bodd (bit1 n) = tt := bodd_bit tt n @[simp] lemma div2_bit0 (n) : div2 (bit0 n) = n := div2_bit ff n @[simp] lemma div2_bit1 (n) : div2 (bit1 n) = n := div2_bit tt n /-! ### `bit0` and `bit1` -/ -- There is no need to prove `bit0_eq_zero : bit0 n = 0 ↔ n = 0` -- as this is true for any `[semiring R] [no_zero_divisors R] [char_zero R]` -- However the lemmas `bit0_eq_bit0`, `bit1_eq_bit1`, `bit1_eq_one`, `one_eq_bit1` -- need `[ring R] [no_zero_divisors R] [char_zero R]` in general, -- so we prove `ℕ` specialized versions here. @[simp] lemma bit0_eq_bit0 {m n : ℕ} : bit0 m = bit0 n ↔ m = n := ⟨nat.bit0_inj, λ h, by subst h⟩ @[simp] lemma bit1_eq_bit1 {m n : ℕ} : bit1 m = bit1 n ↔ m = n := ⟨nat.bit1_inj, λ h, by subst h⟩ @[simp] lemma bit1_eq_one {n : ℕ} : bit1 n = 1 ↔ n = 0 := ⟨@nat.bit1_inj n 0, λ h, by subst h⟩ @[simp] lemma one_eq_bit1 {n : ℕ} : 1 = bit1 n ↔ n = 0 := ⟨λ h, (@nat.bit1_inj 0 n h).symm, λ h, by subst h⟩ protected theorem bit0_le {n m : ℕ} (h : n ≤ m) : bit0 n ≤ bit0 m := add_le_add h h protected theorem bit1_le {n m : ℕ} (h : n ≤ m) : bit1 n ≤ bit1 m := succ_le_succ (add_le_add h h) theorem bit_le : ∀ (b : bool) {n m : ℕ}, n ≤ m → bit b n ≤ bit b m | tt n m h := nat.bit1_le h | ff n m h := nat.bit0_le h theorem bit_ne_zero (b) {n} (h : n ≠ 0) : bit b n ≠ 0 := by cases b; [exact nat.bit0_ne_zero h, exact nat.bit1_ne_zero _] theorem bit0_le_bit : ∀ (b) {m n : ℕ}, m ≤ n → bit0 m ≤ bit b n | tt m n h := le_of_lt $ nat.bit0_lt_bit1 h | ff m n h := nat.bit0_le h theorem bit_le_bit1 : ∀ (b) {m n : ℕ}, m ≤ n → bit b m ≤ bit1 n | ff m n h := le_of_lt $ nat.bit0_lt_bit1 h | tt m n h := nat.bit1_le h theorem bit_lt_bit0 : ∀ (b) {n m : ℕ}, n < m → bit b n < bit0 m | tt n m h := nat.bit1_lt_bit0 h | ff n m h := nat.bit0_lt h theorem bit_lt_bit (a b) {n m : ℕ} (h : n < m) : bit a n < bit b m := lt_of_lt_of_le (bit_lt_bit0 _ h) (bit0_le_bit _ (le_refl _)) @[simp] lemma bit0_le_bit1_iff : bit0 k ≤ bit1 n ↔ k ≤ n := ⟨λ h, by rwa [← nat.lt_succ_iff, n.bit1_eq_succ_bit0, ← n.bit0_succ_eq, bit0_lt_bit0, nat.lt_succ_iff] at h, λ h, le_of_lt (nat.bit0_lt_bit1 h)⟩ @[simp] lemma bit0_lt_bit1_iff : bit0 k < bit1 n ↔ k ≤ n := ⟨λ h, bit0_le_bit1_iff.1 (le_of_lt h), nat.bit0_lt_bit1⟩ @[simp] lemma bit1_le_bit0_iff : bit1 k ≤ bit0 n ↔ k < n := ⟨λ h, by rwa [k.bit1_eq_succ_bit0, succ_le_iff, bit0_lt_bit0] at h, λ h, le_of_lt (nat.bit1_lt_bit0 h)⟩ @[simp] lemma bit1_lt_bit0_iff : bit1 k < bit0 n ↔ k < n := ⟨λ h, bit1_le_bit0_iff.1 (le_of_lt h), nat.bit1_lt_bit0⟩ @[simp] lemma one_le_bit0_iff : 1 ≤ bit0 n ↔ 0 < n := by { convert bit1_le_bit0_iff, refl, } @[simp] lemma one_lt_bit0_iff : 1 < bit0 n ↔ 1 ≤ n := by { convert bit1_lt_bit0_iff, refl, } @[simp] lemma bit_le_bit_iff : ∀ {b : bool}, bit b k ≤ bit b n ↔ k ≤ n | ff := bit0_le_bit0 | tt := bit1_le_bit1 @[simp] lemma bit_lt_bit_iff : ∀ {b : bool}, bit b k < bit b n ↔ k < n | ff := bit0_lt_bit0 | tt := bit1_lt_bit1 @[simp] lemma bit_le_bit1_iff : ∀ {b : bool}, bit b k ≤ bit1 n ↔ k ≤ n | ff := bit0_le_bit1_iff | tt := bit1_le_bit1 @[simp] lemma bit0_mod_two : bit0 n % 2 = 0 := by { rw nat.mod_two_of_bodd, simp } @[simp] lemma bit1_mod_two : bit1 n % 2 = 1 := by { rw nat.mod_two_of_bodd, simp } lemma pos_of_bit0_pos {n : ℕ} (h : 0 < bit0 n) : 0 < n := by { cases n, cases h, apply succ_pos, } /-- Define a function on `ℕ` depending on parity of the argument. -/ @[elab_as_eliminator] def bit_cases {C : ℕ → Sort u} (H : Π b n, C (bit b n)) (n : ℕ) : C n := eq.rec_on n.bit_decomp (H (bodd n) (div2 n)) /-! ### decidability of predicates -/ instance decidable_ball_lt (n : nat) (P : Π k < n, Prop) : ∀ [H : ∀ n h, decidable (P n h)], decidable (∀ n h, P n h) := begin induction n with n IH; intro; resetI, { exact is_true (λ n, dec_trivial) }, cases IH (λ k h, P k (lt_succ_of_lt h)) with h, { refine is_false (mt _ h), intros hn k h, apply hn }, by_cases p : P n (lt_succ_self n), { exact is_true (λ k h', (le_of_lt_succ h').lt_or_eq_dec.elim (h _) (λ e, match k, e, h' with _, rfl, h := p end)) }, { exact is_false (mt (λ hn, hn _ _) p) } end instance decidable_forall_fin {n : ℕ} (P : fin n → Prop) [H : decidable_pred P] : decidable (∀ i, P i) := decidable_of_iff (∀ k h, P ⟨k, h⟩) ⟨λ a ⟨k, h⟩, a k h, λ a k h, a ⟨k, h⟩⟩ instance decidable_ball_le (n : ℕ) (P : Π k ≤ n, Prop) [H : ∀ n h, decidable (P n h)] : decidable (∀ n h, P n h) := decidable_of_iff (∀ k (h : k < succ n), P k (le_of_lt_succ h)) ⟨λ a k h, a k (lt_succ_of_le h), λ a k h, a k _⟩ instance decidable_lo_hi (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x < hi → P x) := decidable_of_iff (∀ x < hi - lo, P (lo + x)) ⟨λal x hl hh, by have := al (x - lo) (lt_of_not_ge $ (not_congr (nat.sub_le_sub_right_iff _ _ _ hl)).2 $ not_le_of_gt hh); rwa [nat.add_sub_of_le hl] at this, λal x h, al _ (nat.le_add_right _ _) (nat.add_lt_of_lt_sub_left h)⟩ instance decidable_lo_hi_le (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x ≤ hi → P x) := decidable_of_iff (∀x, lo ≤ x → x < hi + 1 → P x) $ ball_congr $ λ x hl, imp_congr lt_succ_iff iff.rfl instance decidable_exists_lt {P : ℕ → Prop} [h : decidable_pred P] : decidable_pred (λ n, ∃ (m : ℕ), m < n ∧ P m) | 0 := is_false (by simp) | (n + 1) := decidable_of_decidable_of_iff (@or.decidable _ _ (decidable_exists_lt n) (h n)) (by simp only [lt_succ_iff_lt_or_eq, or_and_distrib_right, exists_or_distrib, exists_eq_left]) end nat
307a77f22d7fd72255acbfb8a497e8a012d5f3da
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Elab/LetRec.lean
fd621c1755239732f5226a061e099b89219b5377
[ "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,324
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Attributes import Lean.Elab.Binders import Lean.Elab.DeclModifiers import Lean.Elab.SyntheticMVars import Lean.Elab.DeclarationRange namespace Lean.Elab.Term open Meta structure LetRecDeclView where ref : Syntax attrs : Array Attribute shortDeclName : Name declName : Name binderIds : Array Syntax type : Expr mvar : Expr -- auxiliary metavariable used to lift the 'let rec' valStx : Syntax structure LetRecView where decls : Array LetRecDeclView body : Syntax /- group ("let " >> nonReservedSymbol "rec ") >> sepBy1 (group (optional «attributes» >> letDecl)) ", " >> "; " >> termParser -/ private def mkLetRecDeclView (letRec : Syntax) : TermElabM LetRecView := do let decls ← letRec[1][0].getSepArgs.mapM fun (attrDeclStx : Syntax) => do let docStr? ← expandOptDocComment? attrDeclStx[0] let attrOptStx := attrDeclStx[1] let attrs ← if attrOptStx.isNone then pure #[] else elabDeclAttrs attrOptStx[0] let decl := attrDeclStx[2][0] if decl.isOfKind `Lean.Parser.Term.letPatDecl then throwErrorAt decl "patterns are not allowed in 'let rec' expressions" else if decl.isOfKind `Lean.Parser.Term.letIdDecl || decl.isOfKind `Lean.Parser.Term.letEqnsDecl then let declId := decl[0] let shortDeclName := declId.getId let currDeclName? ← getDeclName? let declName := currDeclName?.getD Name.anonymous ++ shortDeclName checkNotAlreadyDeclared declName applyAttributesAt declName attrs AttributeApplicationTime.beforeElaboration addDocString' declName docStr? addAuxDeclarationRanges declName decl declId let binders := decl[1].getArgs let typeStx := expandOptType declId decl[2] let (type, binderIds) ← elabBindersEx binders fun xs => do let type ← elabType typeStx registerCustomErrorIfMVar type typeStx "failed to infer 'let rec' declaration type" let (binderIds, xs) := xs.unzip let type ← mkForallFVars xs type pure (type, binderIds) let mvar ← mkFreshExprMVar type MetavarKind.syntheticOpaque let valStx ← if decl.isOfKind `Lean.Parser.Term.letIdDecl then pure decl[4] else liftMacroM $ expandMatchAltsIntoMatch decl decl[3] pure { ref := decl, attrs := attrs, shortDeclName := shortDeclName, declName := declName, binderIds := binderIds, type := type, mvar := mvar, valStx := valStx : LetRecDeclView } else throwUnsupportedSyntax pure { decls := decls, body := letRec[3] } private partial def withAuxLocalDecls {α} (views : Array LetRecDeclView) (k : Array Expr → TermElabM α) : TermElabM α := let rec loop (i : Nat) (fvars : Array Expr) : TermElabM α := if h : i < views.size then let view := views.get ⟨i, h⟩ withLocalDeclD view.shortDeclName view.type fun fvar => loop (i+1) (fvars.push fvar) else k fvars loop 0 #[] private def elabLetRecDeclValues (view : LetRecView) : TermElabM (Array Expr) := view.decls.mapM fun view => do forallBoundedTelescope view.type view.binderIds.size fun xs type => do -- Add new info nodes for new fvars. The server will detect all fvars of a binder by the binder's source location. for i in [0:view.binderIds.size] do addTermInfo (isBinder := true) view.binderIds[i] xs[i] withDeclName view.declName do let value ← elabTermEnsuringType view.valStx type mkLambdaFVars xs value private def registerLetRecsToLift (views : Array LetRecDeclView) (fvars : Array Expr) (values : Array Expr) : TermElabM Unit := do let letRecsToLiftCurr := (← get).letRecsToLift for view in views do if letRecsToLiftCurr.any fun toLift => toLift.declName == view.declName then withRef view.ref do throwError "'{view.declName}' has already been declared" let lctx ← getLCtx let localInsts ← getLocalInstances let toLift := views.mapIdx fun i view => { ref := view.ref, fvarId := fvars[i].fvarId!, attrs := view.attrs, shortDeclName := view.shortDeclName, declName := view.declName, lctx := lctx, localInstances := localInsts, type := view.type, val := values[i], mvarId := view.mvar.mvarId! : LetRecToLift } modify fun s => { s with letRecsToLift := toLift.toList ++ s.letRecsToLift } @[builtinTermElab «letrec»] def elabLetRec : TermElab := fun stx expectedType? => do let view ← mkLetRecDeclView stx withAuxLocalDecls view.decls fun fvars => do for decl in view.decls, fvar in fvars do addTermInfo (isBinder := true) decl.ref[0] fvar let values ← elabLetRecDeclValues view let body ← elabTermEnsuringType view.body expectedType? registerLetRecsToLift view.decls fvars values let mvars := view.decls.map (·.mvar) pure $ mkAppN (← mkLambdaFVars fvars body) mvars end Lean.Elab.Term
7408731dbf5dfb5143d5b0b71112f807ac1e696a
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/geometry/manifold/algebra/smooth_functions.lean
2ec4afafa85631da6eb3babe04bb168fff974ae8
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,473
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri -/ import geometry.manifold.algebra.structures /-! # Algebraic structures over smooth functions In this file, we define instances of algebraic structures over smooth functions. -/ noncomputable theory open_locale manifold variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H : Type*} [topological_space H] {I : model_with_corners 𝕜 E H} {H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} {N : Type*} [topological_space N] [charted_space H N] {E'' : Type*} [normed_group E''] [normed_space 𝕜 E''] {H'' : Type*} [topological_space H''] {I'' : model_with_corners 𝕜 E'' H''} {N' : Type*} [topological_space N'] [charted_space H'' N'] namespace smooth_map @[to_additive] instance has_mul {G : Type*} [has_mul G] [topological_space G] [charted_space H' G] [has_smooth_mul I' G] : has_mul C^∞⟮I, N; I', G⟯ := ⟨λ f g, ⟨f * g, f.smooth.mul g.smooth⟩⟩ @[simp, to_additive] lemma coe_mul {G : Type*} [has_mul G] [topological_space G] [charted_space H' G] [has_smooth_mul I' G] (f g : C^∞⟮I, N; I', G⟯) : ⇑(f * g) = f * g := rfl @[simp, to_additive] lemma mul_comp {G : Type*} [has_mul G] [topological_space G] [charted_space H' G] [has_smooth_mul I' G] (f g : C^∞⟮I'', N'; I', G⟯) (h : C^∞⟮I, N; I'', N'⟯) : (f * g).comp h = (f.comp h) * (g.comp h) := by ext; simp only [times_cont_mdiff_map.comp_apply, coe_mul, pi.mul_apply] @[to_additive] instance has_one {G : Type*} [monoid G] [topological_space G] [charted_space H' G] : has_one C^∞⟮I, N; I', G⟯ := ⟨times_cont_mdiff_map.const (1 : G)⟩ @[simp, to_additive] lemma coe_one {G : Type*} [monoid G] [topological_space G] [charted_space H' G] : ⇑(1 : C^∞⟮I, N; I', G⟯) = 1 := rfl section group_structure /-! ### Group structure In this section we show that smooth functions valued in a Lie group inherit a group structure under pointwise multiplication. -/ @[to_additive] instance semigroup {G : Type*} [semigroup G] [topological_space G] [charted_space H' G] [has_smooth_mul I' G] : semigroup C^∞⟮I, N; I', G⟯ := { mul_assoc := λ a b c, by ext; exact mul_assoc _ _ _, ..smooth_map.has_mul} @[to_additive] instance monoid {G : Type*} [monoid G] [topological_space G] [charted_space H' G] [has_smooth_mul I' G] : monoid C^∞⟮I, N; I', G⟯ := { one_mul := λ a, by ext; exact one_mul _, mul_one := λ a, by ext; exact mul_one _, ..smooth_map.semigroup, ..smooth_map.has_one } /-- Coercion to a function as an `monoid_hom`. Similar to `monoid_hom.coe_fn`. -/ @[to_additive "Coercion to a function as an `add_monoid_hom`. Similar to `add_monoid_hom.coe_fn`.", simps] def coe_fn_monoid_hom {G : Type*} [monoid G] [topological_space G] [charted_space H' G] [has_smooth_mul I' G] : C^∞⟮I, N; I', G⟯ →* (N → G) := { to_fun := coe_fn, map_one' := coe_one, map_mul' := coe_mul } @[to_additive] instance comm_monoid {G : Type*} [comm_monoid G] [topological_space G] [charted_space H' G] [has_smooth_mul I' G] : comm_monoid C^∞⟮I, N; I', G⟯ := { mul_comm := λ a b, by ext; exact mul_comm _ _, ..smooth_map.monoid, ..smooth_map.has_one } @[to_additive] instance group {G : Type*} [group G] [topological_space G] [charted_space H' G] [lie_group I' G] : group C^∞⟮I, N; I', G⟯ := { inv := λ f, ⟨λ x, (f x)⁻¹, f.smooth.inv⟩, mul_left_inv := λ a, by ext; exact mul_left_inv _, div := λ f g, ⟨f / g, f.smooth.div g.smooth⟩, div_eq_mul_inv := λ f g, by ext; exact div_eq_mul_inv _ _, .. smooth_map.monoid } @[simp, to_additive] lemma coe_inv {G : Type*} [group G] [topological_space G] [charted_space H' G] [lie_group I' G] (f : C^∞⟮I, N; I', G⟯) : ⇑f⁻¹ = f⁻¹ := rfl @[simp, to_additive] lemma coe_div {G : Type*} [group G] [topological_space G] [charted_space H' G] [lie_group I' G] (f g : C^∞⟮I, N; I', G⟯) : ⇑(f / g) = f / g := rfl @[to_additive] instance comm_group {G : Type*} [comm_group G] [topological_space G] [charted_space H' G] [lie_group I' G] : comm_group C^∞⟮I, N; I', G⟯ := { ..smooth_map.group, ..smooth_map.comm_monoid } end group_structure section ring_structure /-! ### Ring stucture In this section we show that smooth functions valued in a smooth ring `R` inherit a ring structure under pointwise multiplication. -/ instance semiring {R : Type*} [semiring R] [topological_space R] [charted_space H' R] [smooth_ring I' R] : semiring C^∞⟮I, N; I', R⟯ := { left_distrib := λ a b c, by ext; exact left_distrib _ _ _, right_distrib := λ a b c, by ext; exact right_distrib _ _ _, zero_mul := λ a, by ext; exact zero_mul _, mul_zero := λ a, by ext; exact mul_zero _, ..smooth_map.add_comm_monoid, ..smooth_map.monoid } instance ring {R : Type*} [ring R] [topological_space R] [charted_space H' R] [smooth_ring I' R] : ring C^∞⟮I, N; I', R⟯ := { ..smooth_map.semiring, ..smooth_map.add_comm_group, } instance comm_ring {R : Type*} [comm_ring R] [topological_space R] [charted_space H' R] [smooth_ring I' R] : comm_ring C^∞⟮I, N; I', R⟯ := { ..smooth_map.semiring, ..smooth_map.add_comm_group, ..smooth_map.comm_monoid,} /-- Coercion to a function as a `ring_hom`. -/ @[simps] def coe_fn_ring_hom {R : Type*} [comm_ring R] [topological_space R] [charted_space H' R] [smooth_ring I' R] : C^∞⟮I, N; I', R⟯ →+* (N → R) := { to_fun := coe_fn, ..(coe_fn_monoid_hom : C^∞⟮I, N; I', R⟯ →* _), ..(coe_fn_add_monoid_hom : C^∞⟮I, N; I', R⟯ →+ _) } /-- `function.eval` as a `ring_hom` on the ring of smooth functions. -/ def eval_ring_hom {R : Type*} [comm_ring R] [topological_space R] [charted_space H' R] [smooth_ring I' R] (n : N) : C^∞⟮I, N; I', R⟯ →+* R := (pi.eval_ring_hom _ n : (N → R) →+* R).comp smooth_map.coe_fn_ring_hom end ring_structure section module_structure /-! ### Semiodule stucture In this section we show that smooth functions valued in a vector space `M` over a normed field `𝕜` inherit a vector space structure. -/ instance has_scalar {V : Type*} [normed_group V] [normed_space 𝕜 V] : has_scalar 𝕜 C^∞⟮I, N; 𝓘(𝕜, V), V⟯ := ⟨λ r f, ⟨r • f, smooth_const.smul f.smooth⟩⟩ @[simp] lemma coe_smul {V : Type*} [normed_group V] [normed_space 𝕜 V] (r : 𝕜) (f : C^∞⟮I, N; 𝓘(𝕜, V), V⟯) : ⇑(r • f) = r • f := rfl @[simp] lemma smul_comp {V : Type*} [normed_group V] [normed_space 𝕜 V] (r : 𝕜) (g : C^∞⟮I'', N'; 𝓘(𝕜, V), V⟯) (h : C^∞⟮I, N; I'', N'⟯) : (r • g).comp h = r • (g.comp h) := rfl instance module {V : Type*} [normed_group V] [normed_space 𝕜 V] : module 𝕜 C^∞⟮I, N; 𝓘(𝕜, V), V⟯ := module.of_core $ { smul := (•), smul_add := λ c f g, by ext x; exact smul_add c (f x) (g x), add_smul := λ c₁ c₂ f, by ext x; exact add_smul c₁ c₂ (f x), mul_smul := λ c₁ c₂ f, by ext x; exact mul_smul c₁ c₂ (f x), one_smul := λ f, by ext x; exact one_smul 𝕜 (f x), } /-- Coercion to a function as a `linear_map`. -/ @[simps] def coe_fn_linear_map {V : Type*} [normed_group V] [normed_space 𝕜 V] : C^∞⟮I, N; 𝓘(𝕜, V), V⟯ →ₗ[𝕜] (N → V) := { to_fun := coe_fn, map_smul' := coe_smul, ..(coe_fn_add_monoid_hom : C^∞⟮I, N; 𝓘(𝕜, V), V⟯ →+ _) } end module_structure section algebra_structure /-! ### Algebra structure In this section we show that smooth functions valued in a normed algebra `A` over a normed field `𝕜` inherit an algebra structure. -/ variables {A : Type*} [normed_ring A] [normed_algebra 𝕜 A] [smooth_ring 𝓘(𝕜, A) A] /-- Smooth constant functions as a `ring_hom`. -/ def C : 𝕜 →+* C^∞⟮I, N; 𝓘(𝕜, A), A⟯ := { to_fun := λ c : 𝕜, ⟨λ x, ((algebra_map 𝕜 A) c), smooth_const⟩, map_one' := by ext x; exact (algebra_map 𝕜 A).map_one, map_mul' := λ c₁ c₂, by ext x; exact (algebra_map 𝕜 A).map_mul _ _, map_zero' := by ext x; exact (algebra_map 𝕜 A).map_zero, map_add' := λ c₁ c₂, by ext x; exact (algebra_map 𝕜 A).map_add _ _ } instance algebra : algebra 𝕜 C^∞⟮I, N; 𝓘(𝕜, A), A⟯ := { smul := λ r f, ⟨r • f, smooth_const.smul f.smooth⟩, to_ring_hom := smooth_map.C, commutes' := λ c f, by ext x; exact algebra.commutes' _ _, smul_def' := λ c f, by ext x; exact algebra.smul_def' _ _, ..smooth_map.semiring } /-- Coercion to a function as an `alg_hom`. -/ @[simps] def coe_fn_alg_hom : C^∞⟮I, N; 𝓘(𝕜, A), A⟯ →ₐ[𝕜] (N → A) := { to_fun := coe_fn, commutes' := λ r, rfl, -- `..(smooth_map.coe_fn_ring_hom : C^∞⟮I, N; 𝓘(𝕜, A), A⟯ →+* _)` times out for some reason map_zero' := smooth_map.coe_zero, map_one' := smooth_map.coe_one, map_add' := smooth_map.coe_add, map_mul' := smooth_map.coe_mul } end algebra_structure section module_over_continuous_functions /-! ### Structure as module over scalar functions If `V` is a module over `𝕜`, then we show that the space of smooth functions from `N` to `V` is naturally a vector space over the ring of smooth functions from `N` to `𝕜`. -/ instance has_scalar' {V : Type*} [normed_group V] [normed_space 𝕜 V] : has_scalar C^∞⟮I, N; 𝕜⟯ C^∞⟮I, N; 𝓘(𝕜, V), V⟯ := ⟨λ f g, ⟨λ x, (f x) • (g x), (smooth.smul f.2 g.2)⟩⟩ @[simp] lemma smul_comp' {V : Type*} [normed_group V] [normed_space 𝕜 V] (f : C^∞⟮I'', N'; 𝕜⟯) (g : C^∞⟮I'', N'; 𝓘(𝕜, V), V⟯) (h : C^∞⟮I, N; I'', N'⟯) : (f • g).comp h = (f.comp h) • (g.comp h) := rfl instance module' {V : Type*} [normed_group V] [normed_space 𝕜 V] : module C^∞⟮I, N; 𝓘(𝕜), 𝕜⟯ C^∞⟮I, N; 𝓘(𝕜, V), V⟯ := { smul := (•), smul_add := λ c f g, by ext x; exact smul_add (c x) (f x) (g x), add_smul := λ c₁ c₂ f, by ext x; exact add_smul (c₁ x) (c₂ x) (f x), mul_smul := λ c₁ c₂ f, by ext x; exact mul_smul (c₁ x) (c₂ x) (f x), one_smul := λ f, by ext x; exact one_smul 𝕜 (f x), zero_smul := λ f, by ext x; exact zero_smul _ _, smul_zero := λ r, by ext x; exact smul_zero _, } end module_over_continuous_functions end smooth_map
a02bd02d8c6d700a43c36073f87ba03d9f4067be
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/data/padics/hensel.lean
7141f9db26e1238c5d7b5e65c629badf81c3aba4
[ "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
20,862
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis A proof of Hensel's lemma on ℤ_p, roughly following Keith Conrad's writeup: http://www.math.uconn.edu/~kconrad/blurbs/gradnumthy/hensel.pdf -/ import data.padics.padic_integers data.polynomial topology.metric_space.cau_seq_filter import analysis.specific_limits topology.instances.polynomial import tactic.simpa noncomputable theory local attribute [instance] classical.prop_decidable lemma padic_polynomial_dist {p : ℕ} [p.prime] (F : polynomial ℤ_[p]) (x y : ℤ_[p]) : ∥F.eval x - F.eval y∥ ≤ ∥x - y∥ := let ⟨z, hz⟩ := F.eval_sub_factor x y in calc ∥F.eval x - F.eval y∥ = ∥z∥ * ∥x - y∥ : by simp [hz] ... ≤ 1 * ∥x - y∥ : mul_le_mul_of_nonneg_right (padic_norm_z.le_one _) (norm_nonneg _) ... = ∥x - y∥ : by simp open filter metric private lemma comp_tendsto_lim {p : ℕ} [p.prime] {F : polynomial ℤ_[p]} (ncs : cau_seq ℤ_[p] norm) : tendsto (λ i, F.eval (ncs i)) at_top (nhds (F.eval ncs.lim)) := @tendsto.comp _ _ _ ncs (λ k, F.eval k) _ _ _ (tendsto_limit ncs) (continuous_iff_continuous_at.1 F.continuous_eval _) section parameters {p : ℕ} [nat.prime p] {ncs : cau_seq ℤ_[p] norm} {F : polynomial ℤ_[p]} {a : ℤ_[p]} (ncs_der_val : ∀ n, ∥F.derivative.eval (ncs n)∥ = ∥F.derivative.eval a∥) include ncs_der_val private lemma ncs_tendsto_const : tendsto (λ i, ∥F.derivative.eval (ncs i)∥) at_top (nhds ∥F.derivative.eval a∥) := by convert tendsto_const_nhds; ext; rw ncs_der_val private lemma ncs_tendsto_lim : tendsto (λ i, ∥F.derivative.eval (ncs i)∥) at_top (nhds (∥F.derivative.eval ncs.lim∥)) := tendsto.comp (comp_tendsto_lim _) (continuous_iff_continuous_at.1 continuous_norm _) private lemma norm_deriv_eq : ∥F.derivative.eval ncs.lim∥ = ∥F.derivative.eval a∥ := tendsto_nhds_unique at_top_ne_bot ncs_tendsto_lim ncs_tendsto_const end section parameters {p : ℕ} [nat.prime p] {ncs : cau_seq ℤ_[p] norm} {F : polynomial ℤ_[p]} (hnorm : tendsto (λ i, ∥F.eval (ncs i)∥) at_top (nhds 0)) include hnorm private lemma tendsto_zero_of_norm_tendsto_zero : tendsto (λ i, F.eval (ncs i)) at_top (nhds 0) := tendsto_iff_norm_tendsto_zero.2 (by simpa using hnorm) lemma limit_zero_of_norm_tendsto_zero : F.eval ncs.lim = 0 := tendsto_nhds_unique at_top_ne_bot (comp_tendsto_lim _) tendsto_zero_of_norm_tendsto_zero end section hensel open nat parameters {p : ℕ} [nat.prime p] {F : polynomial ℤ_[p]} {a : ℤ_[p]} (hnorm : ∥F.eval a∥ < ∥F.derivative.eval a∥^2) (hnsol : F.eval a ≠ 0) include hnorm private def T : ℝ := ∥(F.eval a).val / ((F.derivative.eval a).val)^2∥ private lemma deriv_sq_norm_pos : 0 < ∥F.derivative.eval a∥ ^ 2 := lt_of_le_of_lt (norm_nonneg _) hnorm private lemma deriv_sq_norm_ne_zero : ∥F.derivative.eval a∥^2 ≠ 0 := ne_of_gt deriv_sq_norm_pos private lemma deriv_norm_ne_zero : ∥F.derivative.eval a∥ ≠ 0 := λ h, deriv_sq_norm_ne_zero (by simp [*, _root_.pow_two]) private lemma deriv_norm_pos : 0 < ∥F.derivative.eval a∥ := lt_of_le_of_ne (norm_nonneg _) (ne.symm deriv_norm_ne_zero) private lemma deriv_ne_zero : F.derivative.eval a ≠ 0 := mt (norm_eq_zero _).2 deriv_norm_ne_zero private lemma T_def : T = ∥F.eval a∥ / ∥F.derivative.eval a∥^2 := calc T = ∥(F.eval a).val∥ / ∥((F.derivative.eval a).val)^2∥ : norm_div _ _ ... = ∥F.eval a∥ / ∥(F.derivative.eval a)^2∥ : by simp [norm, padic_norm_z] ... = ∥F.eval a∥ / ∥(F.derivative.eval a)∥^2 : by simp [pow, monoid.pow] private lemma T_lt_one : T < 1 := let h := (div_lt_one_iff_lt deriv_sq_norm_pos).2 hnorm in by rw T_def; apply h private lemma T_pow {n : ℕ} (hn : n > 0) : T ^ n < 1 := have T ^ n ≤ T ^ 1, from pow_le_pow_of_le_one (norm_nonneg _) (le_of_lt T_lt_one) (succ_le_of_lt hn), lt_of_le_of_lt (by simpa) T_lt_one private lemma T_pow' (n : ℕ) : T ^ (2 ^ n) < 1 := (T_pow (nat.pow_pos (by norm_num) _)) private lemma T_pow_nonneg (n : ℕ) : T ^ n ≥ 0 := pow_nonneg (norm_nonneg _) _ private def ih (n : ℕ) (z : ℤ_[p]) : Prop := ∥F.derivative.eval z∥ = ∥F.derivative.eval a∥ ∧ ∥F.eval z∥ ≤ ∥F.derivative.eval a∥^2 * T ^ (2^n) private lemma ih_0 : ih 0 a := ⟨ rfl, by simp [T_def, mul_div_cancel' _ (ne_of_gt (deriv_sq_norm_pos hnorm))] ⟩ private lemma calc_norm_le_one {n : ℕ} {z : ℤ_[p]} (hz : ih n z) : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1 := calc ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ = ∥(↑(F.eval z) : ℚ_[p])∥ / ∥(↑(F.derivative.eval z) : ℚ_[p])∥ : norm_div _ _ ... = ∥F.eval z∥ / ∥F.derivative.eval a∥ : by simp [hz.1] ... ≤ ∥F.derivative.eval a∥^2 * T^(2^n) / ∥F.derivative.eval a∥ : (div_le_div_right deriv_norm_pos).2 hz.2 ... = ∥F.derivative.eval a∥ * T^(2^n) : div_sq_cancel (ne_of_gt deriv_norm_pos) _ ... ≤ 1 : mul_le_one (padic_norm_z.le_one _) (T_pow_nonneg _) (le_of_lt (T_pow' _)) private lemma calc_deriv_dist {z z' z1 : ℤ_[p]} (hz' : z' = z - z1) (hz1 : ∥z1∥ = ∥F.eval z∥ / ∥F.derivative.eval a∥) {n} (hz : ih n z) : ∥F.derivative.eval z' - F.derivative.eval z∥ < ∥F.derivative.eval a∥ := calc ∥F.derivative.eval z' - F.derivative.eval z∥ ≤ ∥z' - z∥ : padic_polynomial_dist _ _ _ ... = ∥z1∥ : by simp [hz'] ... = ∥F.eval z∥ / ∥F.derivative.eval a∥ : hz1 ... ≤ ∥F.derivative.eval a∥^2 * T^(2^n) / ∥F.derivative.eval a∥ : (div_le_div_right deriv_norm_pos).2 hz.2 ... = ∥F.derivative.eval a∥ * T^(2^n) : div_sq_cancel deriv_norm_ne_zero _ ... < ∥F.derivative.eval a∥ : (mul_lt_iff_lt_one_right deriv_norm_pos).2 (T_pow (pow_pos (by norm_num) _)) private def calc_eval_z' {z z' z1 : ℤ_[p]} (hz' : z' = z - z1) {n} (hz : ih n z) (h1 : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1) (hzeq : z1 = ⟨_, h1⟩) : {q : ℤ_[p] // F.eval z' = q * z1^2} := have hdzne' : (↑(F.derivative.eval z) : ℚ_[p]) ≠ 0, from have hdzne : F.derivative.eval z ≠ 0, from mt (norm_eq_zero _).2 (by rw hz.1; apply deriv_norm_ne_zero; assumption), λ h, hdzne $ subtype.ext.2 h, let ⟨q, hq⟩ := F.binom_expansion z (-z1) in have ∥(↑(F.derivative.eval z) * (↑(F.eval z) / ↑(F.derivative.eval z)) : ℚ_[p])∥ ≤ 1, by {rw padic_norm_e.mul, apply mul_le_one, apply padic_norm_z.le_one, apply norm_nonneg, apply h1}, have F.derivative.eval z * (-z1) = -F.eval z, from calc F.derivative.eval z * (-z1) = (F.derivative.eval z) * -⟨↑(F.eval z) / ↑(F.derivative.eval z), h1⟩ : by rw [hzeq] ... = -((F.derivative.eval z) * ⟨↑(F.eval z) / ↑(F.derivative.eval z), h1⟩) : by simp ... = -(⟨↑(F.derivative.eval z) * (↑(F.eval z) / ↑(F.derivative.eval z)), this⟩) : subtype.ext.2 $ by simp ... = -(F.eval z) : by simp [mul_div_cancel' _ hdzne'], have heq : F.eval z' = q * z1^2, by simpa [this, hz'] using hq, ⟨q, heq⟩ private def calc_eval_z'_norm {z z' z1 : ℤ_[p]} {n} (hz : ih n z) {q} (heq : F.eval z' = q * z1^2) (h1 : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1) (hzeq : z1 = ⟨_, h1⟩) : ∥F.eval z'∥ ≤ ∥F.derivative.eval a∥^2 * T^(2^(n+1)) := calc ∥F.eval z'∥ = ∥q∥ * ∥z1∥^2 : by simp [heq] ... ≤ 1 * ∥z1∥^2 : mul_le_mul_of_nonneg_right (padic_norm_z.le_one _) (pow_nonneg (norm_nonneg _) _) ... = ∥F.eval z∥^2 / ∥F.derivative.eval a∥^2 : by simp [hzeq, hz.1, div_pow _ (deriv_norm_ne_zero hnorm)] ... ≤ (∥F.derivative.eval a∥^2 * T^(2^n))^2 / ∥F.derivative.eval a∥^2 : (div_le_div_right deriv_sq_norm_pos).2 (pow_le_pow_of_le_left (norm_nonneg _) hz.2 _) ... = (∥F.derivative.eval a∥^2)^2 * (T^(2^n))^2 / ∥F.derivative.eval a∥^2 : by simp only [_root_.mul_pow] ... = ∥F.derivative.eval a∥^2 * (T^(2^n))^2 : div_sq_cancel deriv_sq_norm_ne_zero _ ... = ∥F.derivative.eval a∥^2 * T^(2^(n + 1)) : by rw [←pow_mul]; refl set_option eqn_compiler.zeta true -- we need (ih k) in order to construct the value for k+1, otherwise it might not be an integer. private def ih_n {n : ℕ} {z : ℤ_[p]} (hz : ih n z) : {z' : ℤ_[p] // ih (n+1) z'} := have h1 : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1, from calc_norm_le_one hz, let z1 : ℤ_[p] := ⟨_, h1⟩, z' : ℤ_[p] := z - z1 in ⟨ z', have hdist : ∥F.derivative.eval z' - F.derivative.eval z∥ < ∥F.derivative.eval a∥, from calc_deriv_dist rfl (by simp [z1, hz.1]) hz, have hfeq : ∥F.derivative.eval z'∥ = ∥F.derivative.eval a∥, begin rw [sub_eq_add_neg, ← hz.1, ←norm_neg (F.derivative.eval z)] at hdist, have := padic_norm_z.eq_of_norm_add_lt_right hdist, rwa [norm_neg, hz.1] at this end, let ⟨q, heq⟩ := calc_eval_z' rfl hz h1 rfl in have hnle : ∥F.eval z'∥ ≤ ∥F.derivative.eval a∥^2 * T^(2^(n+1)), from calc_eval_z'_norm hz heq h1 rfl, ⟨hfeq, hnle⟩⟩ set_option eqn_compiler.zeta false -- why doesn't "noncomputable theory" stick here? private noncomputable def newton_seq_aux : Π n : ℕ, {z : ℤ_[p] // ih n z} | 0 := ⟨a, ih_0⟩ | (k+1) := ih_n (newton_seq_aux k).2 private def newton_seq (n : ℕ) : ℤ_[p] := (newton_seq_aux n).1 private lemma newton_seq_deriv_norm (n : ℕ) : ∥F.derivative.eval (newton_seq n)∥ = ∥F.derivative.eval a∥ := (newton_seq_aux n).2.1 private lemma newton_seq_norm_le (n : ℕ) : ∥F.eval (newton_seq n)∥ ≤ ∥F.derivative.eval a∥^2 * T ^ (2^n) := (newton_seq_aux n).2.2 private lemma newton_seq_norm_eq (n : ℕ) : ∥newton_seq (n+1) - newton_seq n∥ = ∥F.eval (newton_seq n)∥ / ∥F.derivative.eval (newton_seq n)∥ := by induction n; simp [newton_seq, newton_seq_aux, ih_n] private lemma newton_seq_succ_dist (n : ℕ) : ∥newton_seq (n+1) - newton_seq n∥ ≤ ∥F.derivative.eval a∥ * T^(2^n) := calc ∥newton_seq (n+1) - newton_seq n∥ = ∥F.eval (newton_seq n)∥ / ∥F.derivative.eval (newton_seq n)∥ : newton_seq_norm_eq _ ... = ∥F.eval (newton_seq n)∥ / ∥F.derivative.eval a∥ : by rw newton_seq_deriv_norm ... ≤ ∥F.derivative.eval a∥^2 * T ^ (2^n) / ∥F.derivative.eval a∥ : (div_le_div_right deriv_norm_pos).2 (newton_seq_norm_le _) ... = ∥F.derivative.eval a∥ * T^(2^n) : div_sq_cancel (ne_of_gt deriv_norm_pos) _ include hnsol private lemma T_pos : T > 0 := begin rw T_def, apply div_pos_of_pos_of_pos, { apply (norm_pos_iff _).2, apply hnsol }, { exact deriv_sq_norm_pos hnorm } end private lemma newton_seq_succ_dist_weak (n : ℕ) : ∥newton_seq (n+2) - newton_seq (n+1)∥ < ∥F.eval a∥ / ∥F.derivative.eval a∥ := have 2 ≤ 2^(n+1), from have _, from pow_le_pow (by norm_num : 1 ≤ 2) (nat.le_add_left _ _ : 1 ≤ n + 1), by simpa using this, calc ∥newton_seq (n+2) - newton_seq (n+1)∥ ≤ ∥F.derivative.eval a∥ * T^(2^(n+1)) : newton_seq_succ_dist _ ... ≤ ∥F.derivative.eval a∥ * T^2 : mul_le_mul_of_nonneg_left (pow_le_pow_of_le_one (norm_nonneg _) (le_of_lt T_lt_one) this) (norm_nonneg _) ... < ∥F.derivative.eval a∥ * T^1 : mul_lt_mul_of_pos_left (pow_lt_pow_of_lt_one T_pos T_lt_one (by norm_num)) deriv_norm_pos ... = ∥F.eval a∥ / ∥F.derivative.eval a∥ : begin rw [T, _root_.pow_two, _root_.pow_one, norm_div, ←mul_div_assoc, padic_norm_e.mul], apply mul_div_mul_left', apply deriv_norm_ne_zero; assumption end private lemma newton_seq_dist_aux (n : ℕ) : ∀ k : ℕ, ∥newton_seq (n + k) - newton_seq n∥ ≤ ∥F.derivative.eval a∥ * T^(2^n) | 0 := begin simp, apply mul_nonneg, {apply norm_nonneg}, {apply T_pow_nonneg} end | (k+1) := have 2^n ≤ 2^(n+k), by {rw [←nat.pow_eq_pow, ←nat.pow_eq_pow], apply pow_le_pow, norm_num, apply nat.le_add_right}, calc ∥newton_seq (n + (k + 1)) - newton_seq n∥ = ∥newton_seq ((n + k) + 1) - newton_seq n∥ : by simp ... = ∥(newton_seq ((n + k) + 1) - newton_seq (n+k)) + (newton_seq (n+k) - newton_seq n)∥ : by rw ←sub_add_sub_cancel ... ≤ max (∥newton_seq ((n + k) + 1) - newton_seq (n+k)∥) (∥newton_seq (n+k) - newton_seq n∥) : padic_norm_z.nonarchimedean _ _ ... ≤ max (∥F.derivative.eval a∥ * T^(2^((n + k)))) (∥F.derivative.eval a∥ * T^(2^n)) : max_le_max (newton_seq_succ_dist _) (newton_seq_dist_aux _) ... = ∥F.derivative.eval a∥ * T^(2^n) : max_eq_right $ mul_le_mul_of_nonneg_left (pow_le_pow_of_le_one (norm_nonneg _) (le_of_lt T_lt_one) this) (norm_nonneg _) private lemma newton_seq_dist {n k : ℕ} (hnk : n ≤ k) : ∥newton_seq k - newton_seq n∥ ≤ ∥F.derivative.eval a∥ * T^(2^n) := have hex : ∃ m, k = n + m, from exists_eq_add_of_le hnk, -- ⟨k - n, by rw [←nat.add_sub_assoc hnk, add_comm, nat.add_sub_assoc (le_refl n), nat.sub_self, nat.add_zero]⟩, let ⟨_, hex'⟩ := hex in by rw hex'; apply newton_seq_dist_aux; assumption private lemma newton_seq_dist_to_a : ∀ n : ℕ, 0 < n → ∥newton_seq n - a∥ = ∥F.eval a∥ / ∥F.derivative.eval a∥ | 1 h := by simp [newton_seq, newton_seq_aux, ih_n]; apply norm_div | (k+2) h := have hlt : ∥newton_seq (k+2) - newton_seq (k+1)∥ < ∥newton_seq (k+1) - a∥, by rw newton_seq_dist_to_a (k+1) (succ_pos _); apply newton_seq_succ_dist_weak; assumption, have hne' : ∥newton_seq (k + 2) - newton_seq (k+1)∥ ≠ ∥newton_seq (k+1) - a∥, from ne_of_lt hlt, calc ∥newton_seq (k + 2) - a∥ = ∥(newton_seq (k + 2) - newton_seq (k+1)) + (newton_seq (k+1) - a)∥ : by rw ←sub_add_sub_cancel ... = max (∥newton_seq (k + 2) - newton_seq (k+1)∥) (∥newton_seq (k+1) - a∥) : padic_norm_z.add_eq_max_of_ne hne' ... = ∥newton_seq (k+1) - a∥ : max_eq_right_of_lt hlt ... = ∥polynomial.eval a F∥ / ∥polynomial.eval a (polynomial.derivative F)∥ : newton_seq_dist_to_a (k+1) (succ_pos _) private lemma bound' : tendsto (λ n : ℕ, ∥F.derivative.eval a∥ * T^(2^n)) at_top (nhds 0) := begin rw ←mul_zero (∥F.derivative.eval a∥), exact tendsto_mul (tendsto_const_nhds) (tendsto.comp (tendsto_pow_at_top_at_top_of_gt_1_nat (by norm_num)) (tendsto_pow_at_top_nhds_0_of_lt_1 (norm_nonneg _) (T_lt_one hnorm))) end private lemma bound : ∀ {ε}, ε > 0 → ∃ N : ℕ, ∀ {n}, n ≥ N → ∥F.derivative.eval a∥ * T^(2^n) < ε := have mtn : ∀ n : ℕ, ∥polynomial.eval a (polynomial.derivative F)∥ * T ^ (2 ^ n) ≥ 0, from λ n, mul_nonneg (norm_nonneg _) (T_pow_nonneg _), begin have := bound' hnorm hnsol, simp [tendsto, nhds] at this, intros ε hε, cases this (ball 0 ε) (mem_ball_self hε) (is_open_ball) with N hN, existsi N, intros n hn, simpa [normed_field.norm_mul, real.norm_eq_abs, abs_of_nonneg (mtn n)] using hN _ hn end private lemma bound'_sq : tendsto (λ n : ℕ, ∥F.derivative.eval a∥^2 * T^(2^n)) at_top (nhds 0) := begin rw [←mul_zero (∥F.derivative.eval a∥), _root_.pow_two], simp only [mul_assoc], apply tendsto_mul, { apply tendsto_const_nhds }, { apply bound', assumption } end private theorem newton_seq_is_cauchy : is_cau_seq norm newton_seq := begin intros ε hε, cases bound hnorm hnsol hε with N hN, existsi N, intros j hj, apply lt_of_le_of_lt, { apply newton_seq_dist _ _ hj, assumption }, { apply hN, apply le_refl } end private def newton_cau_seq : cau_seq ℤ_[p] norm := ⟨_, newton_seq_is_cauchy⟩ private def soln : ℤ_[p] := newton_cau_seq.lim private lemma soln_spec {ε : ℝ} (hε : ε > 0) : ∃ (N : ℕ), ∀ {i : ℕ}, i ≥ N → ∥soln - newton_cau_seq i∥ < ε := setoid.symm (cau_seq.equiv_lim newton_cau_seq) _ hε private lemma soln_deriv_norm : ∥F.derivative.eval soln∥ = ∥F.derivative.eval a∥ := norm_deriv_eq newton_seq_deriv_norm private lemma newton_seq_norm_tendsto_zero : tendsto (λ i, ∥F.eval (newton_cau_seq i)∥) at_top (nhds 0) := squeeze_zero (λ _, norm_nonneg _) newton_seq_norm_le bound'_sq private lemma newton_seq_dist_tendsto : tendsto (λ n, ∥newton_cau_seq n - a∥) at_top (nhds (∥F.eval a∥ / ∥F.derivative.eval a∥)) := tendsto.congr' (suffices ∃ k, ∀ n ≥ k, ∥F.eval a∥ / ∥F.derivative.eval a∥ = ∥newton_cau_seq n - a∥, by simpa, ⟨1, λ _ hx, (newton_seq_dist_to_a _ hx).symm⟩) (tendsto_const_nhds) private lemma newton_seq_dist_tendsto' : tendsto (λ n, ∥newton_cau_seq n - a∥) at_top (nhds ∥soln - a∥) := tendsto.comp (tendsto_sub (tendsto_limit _) tendsto_const_nhds) (continuous_iff_continuous_at.1 continuous_norm _) private lemma soln_dist_to_a : ∥soln - a∥ = ∥F.eval a∥ / ∥F.derivative.eval a∥ := tendsto_nhds_unique at_top_ne_bot newton_seq_dist_tendsto' newton_seq_dist_tendsto private lemma soln_dist_to_a_lt_deriv : ∥soln - a∥ < ∥F.derivative.eval a∥ := begin rw soln_dist_to_a, apply div_lt_of_mul_lt_of_pos, { apply deriv_norm_pos; assumption }, { rwa _root_.pow_two at hnorm } end private lemma eval_soln : F.eval soln = 0 := limit_zero_of_norm_tendsto_zero newton_seq_norm_tendsto_zero private lemma soln_unique (z : ℤ_[p]) (hev : F.eval z = 0) (hnlt : ∥z - a∥ < ∥F.derivative.eval a∥) : z = soln := have soln_dist : ∥z - soln∥ < ∥F.derivative.eval a∥, from calc ∥z - soln∥ = ∥(z - a) + (a - soln)∥ : by rw sub_add_sub_cancel ... ≤ max (∥z - a∥) (∥a - soln∥) : padic_norm_z.nonarchimedean _ _ ... < ∥F.derivative.eval a∥ : max_lt hnlt (by rw norm_sub_rev; apply soln_dist_to_a_lt_deriv), let h := z - soln, ⟨q, hq⟩ := F.binom_expansion soln h in have (F.derivative.eval soln + q * h) * h = 0, from eq.symm (calc 0 = F.eval (soln + h) : by simp [hev, h] ... = F.derivative.eval soln * h + q * h^2 : by rw [hq, eval_soln, zero_add] ... = (F.derivative.eval soln + q * h) * h : by rw [_root_.pow_two, right_distrib, mul_assoc]), have h = 0, from by_contradiction $ λ hne, have F.derivative.eval soln + q * h = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right hne, have F.derivative.eval soln = (-q) * h, by simpa using eq_neg_of_add_eq_zero this, lt_irrefl ∥F.derivative.eval soln∥ (calc ∥F.derivative.eval soln∥ = ∥(-q) * h∥ : by rw this ... ≤ 1 * ∥h∥ : by rw [padic_norm_z.mul]; exact mul_le_mul_of_nonneg_right (padic_norm_z.le_one _) (norm_nonneg _) ... = ∥z - soln∥ : by simp [h] ... < ∥F.derivative.eval soln∥ : by rw soln_deriv_norm; apply soln_dist), eq_of_sub_eq_zero (by rw ←this; refl) end hensel variables {p : ℕ} [nat.prime p] {F : polynomial ℤ_[p]} {a : ℤ_[p]} private lemma a_soln_is_unique (ha : F.eval a = 0) (z' : ℤ_[p]) (hz' : F.eval z' = 0) (hnormz' : ∥z' - a∥ < ∥F.derivative.eval a∥) : z' = a := let h := z' - a, ⟨q, hq⟩ := F.binom_expansion a h in have (F.derivative.eval a + q * h) * h = 0, from eq.symm (calc 0 = F.eval (a + h) : show 0 = F.eval (a + (z' - a)), by rw add_comm; simp [hz'] ... = F.derivative.eval a * h + q * h^2 : by rw [hq, ha, zero_add] ... = (F.derivative.eval a + q * h) * h : by rw [_root_.pow_two, right_distrib, mul_assoc]), have h = 0, from by_contradiction $ λ hne, have F.derivative.eval a + q * h = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right hne, have F.derivative.eval a = (-q) * h, by simpa using eq_neg_of_add_eq_zero this, lt_irrefl ∥F.derivative.eval a∥ (calc ∥F.derivative.eval a∥ = ∥q∥*∥h∥ : by simp [this] ... ≤ 1*∥h∥ : mul_le_mul_of_nonneg_right (padic_norm_z.le_one _) (norm_nonneg _) ... < ∥F.derivative.eval a∥ : by simpa [h]), eq_of_sub_eq_zero (by rw ←this; refl) variable (hnorm : ∥F.eval a∥ < ∥F.derivative.eval a∥^2) include hnorm private lemma a_is_soln (ha : F.eval a = 0) : F.eval a = 0 ∧ ∥a - a∥ < ∥F.derivative.eval a∥ ∧ ∥F.derivative.eval a∥ = ∥F.derivative.eval a∥ ∧ ∀ z', F.eval z' = 0 → ∥z' - a∥ < ∥F.derivative.eval a∥ → z' = a := ⟨ha, by simp; apply deriv_norm_pos; apply hnorm, rfl, a_soln_is_unique ha⟩ lemma hensels_lemma : ∃ z : ℤ_[p], F.eval z = 0 ∧ ∥z - a∥ < ∥F.derivative.eval a∥ ∧ ∥F.derivative.eval z∥ = ∥F.derivative.eval a∥ ∧ ∀ z', F.eval z' = 0 → ∥z' - a∥ < ∥F.derivative.eval a∥ → z' = z := if ha : F.eval a = 0 then ⟨a, a_is_soln hnorm ha⟩ else by refine ⟨soln _ _, eval_soln _ _, soln_dist_to_a_lt_deriv _ _, soln_deriv_norm _ _, soln_unique _ _⟩; assumption
8c9eb165b945f83a1d69e7c44977f35b3a4e3f4d
94e33a31faa76775069b071adea97e86e218a8ee
/src/measure_theory/function/l1_space.lean
8b6c841d5e12ac8096757fec24d0d9599d64862e
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
51,341
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import measure_theory.function.lp_order /-! # Integrable functions and `L¹` space In the first part of this file, the predicate `integrable` is defined and basic properties of integrable functions are proved. Such a predicate is already available under the name `mem_ℒp 1`. We give a direct definition which is easier to use, and show that it is equivalent to `mem_ℒp 1` In the second part, we establish an API between `integrable` and the space `L¹` of equivalence classes of integrable functions, already defined as a special case of `L^p` spaces for `p = 1`. ## Notation * `α →₁[μ] β` is the type of `L¹` space, where `α` is a `measure_space` and `β` is a `normed_group` with a `second_countable_topology`. `f : α →ₘ β` is a "function" in `L¹`. In comments, `[f]` is also used to denote an `L¹` function. `₁` can be typed as `\1`. ## Main definitions * Let `f : α → β` be a function, where `α` is a `measure_space` and `β` a `normed_group`. Then `has_finite_integral f` means `(∫⁻ a, ∥f a∥₊) < ∞`. * If `β` is moreover a `measurable_space` then `f` is called `integrable` if `f` is `measurable` and `has_finite_integral f` holds. ## Implementation notes To prove something for an arbitrary integrable function, a useful theorem is `integrable.induction` in the file `set_integral`. ## Tags integrable, function space, l1 -/ noncomputable theory open_locale classical topological_space big_operators ennreal measure_theory nnreal open set filter topological_space ennreal emetric measure_theory variables {α β γ δ : Type*} {m : measurable_space α} {μ ν : measure α} [measurable_space δ] variables [normed_group β] variables [normed_group γ] namespace measure_theory /-! ### Some results about the Lebesgue integral involving a normed group -/ lemma lintegral_nnnorm_eq_lintegral_edist (f : α → β) : ∫⁻ a, ∥f a∥₊ ∂μ = ∫⁻ a, edist (f a) 0 ∂μ := by simp only [edist_eq_coe_nnnorm] lemma lintegral_norm_eq_lintegral_edist (f : α → β) : ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ = ∫⁻ a, edist (f a) 0 ∂μ := by simp only [of_real_norm_eq_coe_nnnorm, edist_eq_coe_nnnorm] lemma lintegral_edist_triangle {f g h : α → β} (hf : ae_strongly_measurable f μ) (hh : ae_strongly_measurable h μ) : ∫⁻ a, edist (f a) (g a) ∂μ ≤ ∫⁻ a, edist (f a) (h a) ∂μ + ∫⁻ a, edist (g a) (h a) ∂μ := begin rw ← lintegral_add_left' (hf.edist hh), refine lintegral_mono (λ a, _), apply edist_triangle_right end lemma lintegral_nnnorm_zero : ∫⁻ a : α, ∥(0 : β)∥₊ ∂μ = 0 := by simp lemma lintegral_nnnorm_add_left {f : α → β} (hf : ae_strongly_measurable f μ) (g : α → γ) : ∫⁻ a, ∥f a∥₊ + ∥g a∥₊ ∂μ = ∫⁻ a, ∥f a∥₊ ∂μ + ∫⁻ a, ∥g a∥₊ ∂μ := lintegral_add_left' hf.ennnorm _ lemma lintegral_nnnorm_add_right (f : α → β) {g : α → γ} (hg : ae_strongly_measurable g μ) : ∫⁻ a, ∥f a∥₊ + ∥g a∥₊ ∂μ = ∫⁻ a, ∥f a∥₊ ∂μ + ∫⁻ a, ∥g a∥₊ ∂μ := lintegral_add_right' _ hg.ennnorm lemma lintegral_nnnorm_neg {f : α → β} : ∫⁻ a, ∥(-f) a∥₊ ∂μ = ∫⁻ a, ∥f a∥₊ ∂μ := by simp only [pi.neg_apply, nnnorm_neg] /-! ### The predicate `has_finite_integral` -/ /-- `has_finite_integral f μ` means that the integral `∫⁻ a, ∥f a∥ ∂μ` is finite. `has_finite_integral f` means `has_finite_integral f volume`. -/ def has_finite_integral {m : measurable_space α} (f : α → β) (μ : measure α . volume_tac) : Prop := ∫⁻ a, ∥f a∥₊ ∂μ < ∞ lemma has_finite_integral_iff_norm (f : α → β) : has_finite_integral f μ ↔ ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ < ∞ := by simp only [has_finite_integral, of_real_norm_eq_coe_nnnorm] lemma has_finite_integral_iff_edist (f : α → β) : has_finite_integral f μ ↔ ∫⁻ a, edist (f a) 0 ∂μ < ∞ := by simp only [has_finite_integral_iff_norm, edist_dist, dist_zero_right] lemma has_finite_integral_iff_of_real {f : α → ℝ} (h : 0 ≤ᵐ[μ] f) : has_finite_integral f μ ↔ ∫⁻ a, ennreal.of_real (f a) ∂μ < ∞ := have lintegral_eq : ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ = ∫⁻ a, ennreal.of_real (f a) ∂μ := begin refine lintegral_congr_ae (h.mono $ λ a h, _), rwa [real.norm_eq_abs, abs_of_nonneg] end, by rw [has_finite_integral_iff_norm, lintegral_eq] lemma has_finite_integral_iff_of_nnreal {f : α → ℝ≥0} : has_finite_integral (λ x, (f x : ℝ)) μ ↔ ∫⁻ a, f a ∂μ < ∞ := by simp [has_finite_integral_iff_norm] lemma has_finite_integral.mono {f : α → β} {g : α → γ} (hg : has_finite_integral g μ) (h : ∀ᵐ a ∂μ, ∥f a∥ ≤ ∥g a∥) : has_finite_integral f μ := begin simp only [has_finite_integral_iff_norm] at *, calc ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ ≤ ∫⁻ (a : α), (ennreal.of_real ∥g a∥) ∂μ : lintegral_mono_ae (h.mono $ assume a h, of_real_le_of_real h) ... < ∞ : hg end lemma has_finite_integral.mono' {f : α → β} {g : α → ℝ} (hg : has_finite_integral g μ) (h : ∀ᵐ a ∂μ, ∥f a∥ ≤ g a) : has_finite_integral f μ := hg.mono $ h.mono $ λ x hx, le_trans hx (le_abs_self _) lemma has_finite_integral.congr' {f : α → β} {g : α → γ} (hf : has_finite_integral f μ) (h : ∀ᵐ a ∂μ, ∥f a∥ = ∥g a∥) : has_finite_integral g μ := hf.mono $ eventually_eq.le $ eventually_eq.symm h lemma has_finite_integral_congr' {f : α → β} {g : α → γ} (h : ∀ᵐ a ∂μ, ∥f a∥ = ∥g a∥) : has_finite_integral f μ ↔ has_finite_integral g μ := ⟨λ hf, hf.congr' h, λ hg, hg.congr' $ eventually_eq.symm h⟩ lemma has_finite_integral.congr {f g : α → β} (hf : has_finite_integral f μ) (h : f =ᵐ[μ] g) : has_finite_integral g μ := hf.congr' $ h.fun_comp norm lemma has_finite_integral_congr {f g : α → β} (h : f =ᵐ[μ] g) : has_finite_integral f μ ↔ has_finite_integral g μ := has_finite_integral_congr' $ h.fun_comp norm lemma has_finite_integral_const_iff {c : β} : has_finite_integral (λ x : α, c) μ ↔ c = 0 ∨ μ univ < ∞ := by simp [has_finite_integral, lintegral_const, lt_top_iff_ne_top, or_iff_not_imp_left] lemma has_finite_integral_const [is_finite_measure μ] (c : β) : has_finite_integral (λ x : α, c) μ := has_finite_integral_const_iff.2 (or.inr $ measure_lt_top _ _) lemma has_finite_integral_of_bounded [is_finite_measure μ] {f : α → β} {C : ℝ} (hC : ∀ᵐ a ∂μ, ∥f a∥ ≤ C) : has_finite_integral f μ := (has_finite_integral_const C).mono' hC lemma has_finite_integral.mono_measure {f : α → β} (h : has_finite_integral f ν) (hμ : μ ≤ ν) : has_finite_integral f μ := lt_of_le_of_lt (lintegral_mono' hμ le_rfl) h lemma has_finite_integral.add_measure {f : α → β} (hμ : has_finite_integral f μ) (hν : has_finite_integral f ν) : has_finite_integral f (μ + ν) := begin simp only [has_finite_integral, lintegral_add_measure] at *, exact add_lt_top.2 ⟨hμ, hν⟩ end lemma has_finite_integral.left_of_add_measure {f : α → β} (h : has_finite_integral f (μ + ν)) : has_finite_integral f μ := h.mono_measure $ measure.le_add_right $ le_rfl lemma has_finite_integral.right_of_add_measure {f : α → β} (h : has_finite_integral f (μ + ν)) : has_finite_integral f ν := h.mono_measure $ measure.le_add_left $ le_rfl @[simp] lemma has_finite_integral_add_measure {f : α → β} : has_finite_integral f (μ + ν) ↔ has_finite_integral f μ ∧ has_finite_integral f ν := ⟨λ h, ⟨h.left_of_add_measure, h.right_of_add_measure⟩, λ h, h.1.add_measure h.2⟩ lemma has_finite_integral.smul_measure {f : α → β} (h : has_finite_integral f μ) {c : ℝ≥0∞} (hc : c ≠ ∞) : has_finite_integral f (c • μ) := begin simp only [has_finite_integral, lintegral_smul_measure] at *, exact mul_lt_top hc h.ne end @[simp] lemma has_finite_integral_zero_measure {m : measurable_space α} (f : α → β) : has_finite_integral f (0 : measure α) := by simp only [has_finite_integral, lintegral_zero_measure, with_top.zero_lt_top] variables (α β μ) @[simp] lemma has_finite_integral_zero : has_finite_integral (λa:α, (0:β)) μ := by simp [has_finite_integral] variables {α β μ} lemma has_finite_integral.neg {f : α → β} (hfi : has_finite_integral f μ) : has_finite_integral (-f) μ := by simpa [has_finite_integral] using hfi @[simp] lemma has_finite_integral_neg_iff {f : α → β} : has_finite_integral (-f) μ ↔ has_finite_integral f μ := ⟨λ h, neg_neg f ▸ h.neg, has_finite_integral.neg⟩ lemma has_finite_integral.norm {f : α → β} (hfi : has_finite_integral f μ) : has_finite_integral (λa, ∥f a∥) μ := have eq : (λa, (nnnorm ∥f a∥ : ℝ≥0∞)) = λa, (∥f a∥₊ : ℝ≥0∞), by { funext, rw nnnorm_norm }, by { rwa [has_finite_integral, eq] } lemma has_finite_integral_norm_iff (f : α → β) : has_finite_integral (λa, ∥f a∥) μ ↔ has_finite_integral f μ := has_finite_integral_congr' $ eventually_of_forall $ λ x, norm_norm (f x) lemma has_finite_integral_to_real_of_lintegral_ne_top {f : α → ℝ≥0∞} (hf : ∫⁻ x, f x ∂μ ≠ ∞) : has_finite_integral (λ x, (f x).to_real) μ := begin have : ∀ x, (∥(f x).to_real∥₊ : ℝ≥0∞) = @coe ℝ≥0 ℝ≥0∞ _ (⟨(f x).to_real, ennreal.to_real_nonneg⟩ : ℝ≥0), { intro x, rw real.nnnorm_of_nonneg }, simp_rw [has_finite_integral, this], refine lt_of_le_of_lt (lintegral_mono (λ x, _)) (lt_top_iff_ne_top.2 hf), by_cases hfx : f x = ∞, { simp [hfx] }, { lift f x to ℝ≥0 using hfx with fx, simp [← h] } end lemma is_finite_measure_with_density_of_real {f : α → ℝ} (hfi : has_finite_integral f μ) : is_finite_measure (μ.with_density (λ x, ennreal.of_real $ f x)) := begin refine is_finite_measure_with_density ((lintegral_mono $ λ x, _).trans_lt hfi).ne, exact real.of_real_le_ennnorm (f x) end section dominated_convergence variables {F : ℕ → α → β} {f : α → β} {bound : α → ℝ} lemma all_ae_of_real_F_le_bound (h : ∀ n, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a) : ∀ n, ∀ᵐ a ∂μ, ennreal.of_real ∥F n a∥ ≤ ennreal.of_real (bound a) := λn, (h n).mono $ λ a h, ennreal.of_real_le_of_real h lemma all_ae_tendsto_of_real_norm (h : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top $ 𝓝 $ f a) : ∀ᵐ a ∂μ, tendsto (λn, ennreal.of_real ∥F n a∥) at_top $ 𝓝 $ ennreal.of_real ∥f a∥ := h.mono $ λ a h, tendsto_of_real $ tendsto.comp (continuous.tendsto continuous_norm _) h lemma all_ae_of_real_f_le_bound (h_bound : ∀ n, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) : ∀ᵐ a ∂μ, ennreal.of_real ∥f a∥ ≤ ennreal.of_real (bound a) := begin have F_le_bound := all_ae_of_real_F_le_bound h_bound, rw ← ae_all_iff at F_le_bound, apply F_le_bound.mp ((all_ae_tendsto_of_real_norm h_lim).mono _), assume a tendsto_norm F_le_bound, exact le_of_tendsto' tendsto_norm (F_le_bound) end lemma has_finite_integral_of_dominated_convergence {F : ℕ → α → β} {f : α → β} {bound : α → ℝ} (bound_has_finite_integral : has_finite_integral bound μ) (h_bound : ∀ n, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) : has_finite_integral f μ := /- `∥F n a∥ ≤ bound a` and `∥F n a∥ --> ∥f a∥` implies `∥f a∥ ≤ bound a`, and so `∫ ∥f∥ ≤ ∫ bound < ∞` since `bound` is has_finite_integral -/ begin rw has_finite_integral_iff_norm, calc ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ ≤ ∫⁻ a, ennreal.of_real (bound a) ∂μ : lintegral_mono_ae $ all_ae_of_real_f_le_bound h_bound h_lim ... < ∞ : begin rw ← has_finite_integral_iff_of_real, { exact bound_has_finite_integral }, exact (h_bound 0).mono (λ a h, le_trans (norm_nonneg _) h) end end lemma tendsto_lintegral_norm_of_dominated_convergence {F : ℕ → α → β} {f : α → β} {bound : α → ℝ} (F_measurable : ∀ n, ae_strongly_measurable (F n) μ) (bound_has_finite_integral : has_finite_integral bound μ) (h_bound : ∀ n, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) : tendsto (λn, ∫⁻ a, (ennreal.of_real ∥F n a - f a∥) ∂μ) at_top (𝓝 0) := have f_measurable : ae_strongly_measurable f μ := ae_strongly_measurable_of_tendsto_ae _ F_measurable h_lim, let b := λ a, 2 * ennreal.of_real (bound a) in /- `∥F n a∥ ≤ bound a` and `F n a --> f a` implies `∥f a∥ ≤ bound a`, and thus by the triangle inequality, have `∥F n a - f a∥ ≤ 2 * (bound a). -/ have hb : ∀ n, ∀ᵐ a ∂μ, ennreal.of_real ∥F n a - f a∥ ≤ b a, begin assume n, filter_upwards [all_ae_of_real_F_le_bound h_bound n, all_ae_of_real_f_le_bound h_bound h_lim] with a h₁ h₂, calc ennreal.of_real ∥F n a - f a∥ ≤ (ennreal.of_real ∥F n a∥) + (ennreal.of_real ∥f a∥) : begin rw [← ennreal.of_real_add], apply of_real_le_of_real, { apply norm_sub_le }, { exact norm_nonneg _ }, { exact norm_nonneg _ } end ... ≤ (ennreal.of_real (bound a)) + (ennreal.of_real (bound a)) : add_le_add h₁ h₂ ... = b a : by rw ← two_mul end, /- On the other hand, `F n a --> f a` implies that `∥F n a - f a∥ --> 0` -/ have h : ∀ᵐ a ∂μ, tendsto (λ n, ennreal.of_real ∥F n a - f a∥) at_top (𝓝 0), begin rw ← ennreal.of_real_zero, refine h_lim.mono (λ a h, (continuous_of_real.tendsto _).comp _), rwa ← tendsto_iff_norm_tendsto_zero end, /- Therefore, by the dominated convergence theorem for nonnegative integration, have ` ∫ ∥f a - F n a∥ --> 0 ` -/ begin suffices h : tendsto (λn, ∫⁻ a, (ennreal.of_real ∥F n a - f a∥) ∂μ) at_top (𝓝 (∫⁻ (a:α), 0 ∂μ)), { rwa lintegral_zero at h }, -- Using the dominated convergence theorem. refine tendsto_lintegral_of_dominated_convergence' _ _ hb _ _, -- Show `λa, ∥f a - F n a∥` is almost everywhere measurable for all `n` { exact λ n, measurable_of_real.comp_ae_measurable ((F_measurable n).sub f_measurable).norm.ae_measurable }, -- Show `2 * bound` is has_finite_integral { rw has_finite_integral_iff_of_real at bound_has_finite_integral, { calc ∫⁻ a, b a ∂μ = 2 * ∫⁻ a, ennreal.of_real (bound a) ∂μ : by { rw lintegral_const_mul', exact coe_ne_top } ... ≠ ∞ : mul_ne_top coe_ne_top bound_has_finite_integral.ne }, filter_upwards [h_bound 0] with _ h using le_trans (norm_nonneg _) h }, -- Show `∥f a - F n a∥ --> 0` { exact h } end end dominated_convergence section pos_part /-! Lemmas used for defining the positive part of a `L¹` function -/ lemma has_finite_integral.max_zero {f : α → ℝ} (hf : has_finite_integral f μ) : has_finite_integral (λa, max (f a) 0) μ := hf.mono $ eventually_of_forall $ λ x, by simp [abs_le, le_abs_self] lemma has_finite_integral.min_zero {f : α → ℝ} (hf : has_finite_integral f μ) : has_finite_integral (λa, min (f a) 0) μ := hf.mono $ eventually_of_forall $ λ x, by simp [abs_le, neg_le, neg_le_abs_self, abs_eq_max_neg, le_total] end pos_part section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma has_finite_integral.smul (c : 𝕜) {f : α → β} : has_finite_integral f μ → has_finite_integral (c • f) μ := begin simp only [has_finite_integral], assume hfi, calc ∫⁻ (a : α), ∥c • f a∥₊ ∂μ = ∫⁻ (a : α), (∥c∥₊) * ∥f a∥₊ ∂μ : by simp only [nnnorm_smul, ennreal.coe_mul] ... < ∞ : begin rw lintegral_const_mul', exacts [mul_lt_top coe_ne_top hfi.ne, coe_ne_top] end end lemma has_finite_integral_smul_iff {c : 𝕜} (hc : c ≠ 0) (f : α → β) : has_finite_integral (c • f) μ ↔ has_finite_integral f μ := begin split, { assume h, simpa only [smul_smul, inv_mul_cancel hc, one_smul] using h.smul c⁻¹ }, exact has_finite_integral.smul _ end lemma has_finite_integral.const_mul {f : α → ℝ} (h : has_finite_integral f μ) (c : ℝ) : has_finite_integral (λ x, c * f x) μ := (has_finite_integral.smul c h : _) lemma has_finite_integral.mul_const {f : α → ℝ} (h : has_finite_integral f μ) (c : ℝ) : has_finite_integral (λ x, f x * c) μ := by simp_rw [mul_comm, h.const_mul _] end normed_space /-! ### The predicate `integrable` -/ -- variables [measurable_space β] [measurable_space γ] [measurable_space δ] /-- `integrable f μ` means that `f` is measurable and that the integral `∫⁻ a, ∥f a∥ ∂μ` is finite. `integrable f` means `integrable f volume`. -/ def integrable {α} {m : measurable_space α} (f : α → β) (μ : measure α . volume_tac) : Prop := ae_strongly_measurable f μ ∧ has_finite_integral f μ lemma mem_ℒp_one_iff_integrable {f : α → β} : mem_ℒp f 1 μ ↔ integrable f μ := by simp_rw [integrable, has_finite_integral, mem_ℒp, snorm_one_eq_lintegral_nnnorm] lemma integrable.ae_strongly_measurable {f : α → β} (hf : integrable f μ) : ae_strongly_measurable f μ := hf.1 lemma integrable.ae_measurable [measurable_space β] [borel_space β] {f : α → β} (hf : integrable f μ) : ae_measurable f μ := hf.ae_strongly_measurable.ae_measurable lemma integrable.has_finite_integral {f : α → β} (hf : integrable f μ) : has_finite_integral f μ := hf.2 lemma integrable.mono {f : α → β} {g : α → γ} (hg : integrable g μ) (hf : ae_strongly_measurable f μ) (h : ∀ᵐ a ∂μ, ∥f a∥ ≤ ∥g a∥) : integrable f μ := ⟨hf, hg.has_finite_integral.mono h⟩ lemma integrable.mono' {f : α → β} {g : α → ℝ} (hg : integrable g μ) (hf : ae_strongly_measurable f μ) (h : ∀ᵐ a ∂μ, ∥f a∥ ≤ g a) : integrable f μ := ⟨hf, hg.has_finite_integral.mono' h⟩ lemma integrable.congr' {f : α → β} {g : α → γ} (hf : integrable f μ) (hg : ae_strongly_measurable g μ) (h : ∀ᵐ a ∂μ, ∥f a∥ = ∥g a∥) : integrable g μ := ⟨hg, hf.has_finite_integral.congr' h⟩ lemma integrable_congr' {f : α → β} {g : α → γ} (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) (h : ∀ᵐ a ∂μ, ∥f a∥ = ∥g a∥) : integrable f μ ↔ integrable g μ := ⟨λ h2f, h2f.congr' hg h, λ h2g, h2g.congr' hf $ eventually_eq.symm h⟩ lemma integrable.congr {f g : α → β} (hf : integrable f μ) (h : f =ᵐ[μ] g) : integrable g μ := ⟨hf.1.congr h, hf.2.congr h⟩ lemma integrable_congr {f g : α → β} (h : f =ᵐ[μ] g) : integrable f μ ↔ integrable g μ := ⟨λ hf, hf.congr h, λ hg, hg.congr h.symm⟩ lemma integrable_const_iff {c : β} : integrable (λ x : α, c) μ ↔ c = 0 ∨ μ univ < ∞ := begin have : ae_strongly_measurable (λ (x : α), c) μ := ae_strongly_measurable_const, rw [integrable, and_iff_right this, has_finite_integral_const_iff] end lemma integrable_const [is_finite_measure μ] (c : β) : integrable (λ x : α, c) μ := integrable_const_iff.2 $ or.inr $ measure_lt_top _ _ lemma mem_ℒp.integrable_norm_rpow {f : α → β} {p : ℝ≥0∞} (hf : mem_ℒp f p μ) (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) : integrable (λ (x : α), ∥f x∥ ^ p.to_real) μ := begin rw ← mem_ℒp_one_iff_integrable, exact hf.norm_rpow hp_ne_zero hp_ne_top, end lemma mem_ℒp.integrable_norm_rpow' [is_finite_measure μ] {f : α → β} {p : ℝ≥0∞} (hf : mem_ℒp f p μ) : integrable (λ (x : α), ∥f x∥ ^ p.to_real) μ := begin by_cases h_zero : p = 0, { simp [h_zero, integrable_const] }, by_cases h_top : p = ∞, { simp [h_top, integrable_const] }, exact hf.integrable_norm_rpow h_zero h_top end lemma integrable.mono_measure {f : α → β} (h : integrable f ν) (hμ : μ ≤ ν) : integrable f μ := ⟨h.ae_strongly_measurable.mono_measure hμ, h.has_finite_integral.mono_measure hμ⟩ lemma integrable.of_measure_le_smul {μ' : measure α} (c : ℝ≥0∞) (hc : c ≠ ∞) (hμ'_le : μ' ≤ c • μ) {f : α → β} (hf : integrable f μ) : integrable f μ' := by { rw ← mem_ℒp_one_iff_integrable at hf ⊢, exact hf.of_measure_le_smul c hc hμ'_le, } lemma integrable.add_measure {f : α → β} (hμ : integrable f μ) (hν : integrable f ν) : integrable f (μ + ν) := begin simp_rw ← mem_ℒp_one_iff_integrable at hμ hν ⊢, refine ⟨hμ.ae_strongly_measurable.add_measure hν.ae_strongly_measurable, _⟩, rw [snorm_one_add_measure, ennreal.add_lt_top], exact ⟨hμ.snorm_lt_top, hν.snorm_lt_top⟩, end lemma integrable.left_of_add_measure {f : α → β} (h : integrable f (μ + ν)) : integrable f μ := by { rw ← mem_ℒp_one_iff_integrable at h ⊢, exact h.left_of_add_measure, } lemma integrable.right_of_add_measure {f : α → β} (h : integrable f (μ + ν)) : integrable f ν := by { rw ← mem_ℒp_one_iff_integrable at h ⊢, exact h.right_of_add_measure, } @[simp] lemma integrable_add_measure {f : α → β} : integrable f (μ + ν) ↔ integrable f μ ∧ integrable f ν := ⟨λ h, ⟨h.left_of_add_measure, h.right_of_add_measure⟩, λ h, h.1.add_measure h.2⟩ @[simp] lemma integrable_zero_measure {m : measurable_space α} {f : α → β} : integrable f (0 : measure α) := ⟨ae_strongly_measurable_zero_measure f, has_finite_integral_zero_measure f⟩ theorem integrable_finset_sum_measure {ι} {m : measurable_space α} {f : α → β} {μ : ι → measure α} {s : finset ι} : integrable f (∑ i in s, μ i) ↔ ∀ i ∈ s, integrable f (μ i) := by induction s using finset.induction_on; simp [*] lemma integrable.smul_measure {f : α → β} (h : integrable f μ) {c : ℝ≥0∞} (hc : c ≠ ∞) : integrable f (c • μ) := by { rw ← mem_ℒp_one_iff_integrable at h ⊢, exact h.smul_measure hc, } lemma integrable_smul_measure {f : α → β} {c : ℝ≥0∞} (h₁ : c ≠ 0) (h₂ : c ≠ ∞) : integrable f (c • μ) ↔ integrable f μ := ⟨λ h, by simpa only [smul_smul, ennreal.inv_mul_cancel h₁ h₂, one_smul] using h.smul_measure (ennreal.inv_ne_top.2 h₁), λ h, h.smul_measure h₂⟩ lemma integrable.to_average {f : α → β} (h : integrable f μ) : integrable f ((μ univ)⁻¹ • μ) := begin rcases eq_or_ne μ 0 with rfl|hne, { rwa smul_zero }, { apply h.smul_measure, simpa } end lemma integrable_average [is_finite_measure μ] {f : α → β} : integrable f ((μ univ)⁻¹ • μ) ↔ integrable f μ := (eq_or_ne μ 0).by_cases (λ h, by simp [h]) $ λ h, integrable_smul_measure (ennreal.inv_ne_zero.2 $ measure_ne_top _ _) (ennreal.inv_ne_top.2 $ mt measure.measure_univ_eq_zero.1 h) lemma integrable_map_measure {f : α → δ} {g : δ → β} (hg : ae_strongly_measurable g (measure.map f μ)) (hf : ae_measurable f μ) : integrable g (measure.map f μ) ↔ integrable (g ∘ f) μ := by { simp_rw ← mem_ℒp_one_iff_integrable, exact mem_ℒp_map_measure_iff hg hf, } lemma integrable.comp_ae_measurable {f : α → δ} {g : δ → β} (hg : integrable g (measure.map f μ)) (hf : ae_measurable f μ) : integrable (g ∘ f) μ := (integrable_map_measure hg.ae_strongly_measurable hf).mp hg lemma integrable.comp_measurable {f : α → δ} {g : δ → β} (hg : integrable g (measure.map f μ)) (hf : measurable f) : integrable (g ∘ f) μ := hg.comp_ae_measurable hf.ae_measurable lemma _root_.measurable_embedding.integrable_map_iff {f : α → δ} (hf : measurable_embedding f) {g : δ → β} : integrable g (measure.map f μ) ↔ integrable (g ∘ f) μ := by { simp_rw ← mem_ℒp_one_iff_integrable, exact hf.mem_ℒp_map_measure_iff, } lemma integrable_map_equiv (f : α ≃ᵐ δ) (g : δ → β) : integrable g (measure.map f μ) ↔ integrable (g ∘ f) μ := by { simp_rw ← mem_ℒp_one_iff_integrable, exact f.mem_ℒp_map_measure_iff, } lemma measure_preserving.integrable_comp {ν : measure δ} {g : δ → β} {f : α → δ} (hf : measure_preserving f μ ν) (hg : ae_strongly_measurable g ν) : integrable (g ∘ f) μ ↔ integrable g ν := by { rw ← hf.map_eq at hg ⊢, exact (integrable_map_measure hg hf.measurable.ae_measurable).symm } lemma measure_preserving.integrable_comp_emb {f : α → δ} {ν} (h₁ : measure_preserving f μ ν) (h₂ : measurable_embedding f) {g : δ → β} : integrable (g ∘ f) μ ↔ integrable g ν := h₁.map_eq ▸ iff.symm h₂.integrable_map_iff lemma lintegral_edist_lt_top {f g : α → β} (hf : integrable f μ) (hg : integrable g μ) : ∫⁻ a, edist (f a) (g a) ∂μ < ∞ := lt_of_le_of_lt (lintegral_edist_triangle hf.ae_strongly_measurable ae_strongly_measurable_zero) (ennreal.add_lt_top.2 $ by { simp_rw [pi.zero_apply, ← has_finite_integral_iff_edist], exact ⟨hf.has_finite_integral, hg.has_finite_integral⟩ }) variables (α β μ) @[simp] lemma integrable_zero : integrable (λ _, (0 : β)) μ := by simp [integrable, ae_strongly_measurable_const] variables {α β μ} lemma integrable.add' {f g : α → β} (hf : integrable f μ) (hg : integrable g μ) : has_finite_integral (f + g) μ := calc ∫⁻ a, ∥f a + g a∥₊ ∂μ ≤ ∫⁻ a, ∥f a∥₊ + ∥g a∥₊ ∂μ : lintegral_mono (λ a, by exact_mod_cast nnnorm_add_le _ _) ... = _ : lintegral_nnnorm_add_left hf.ae_strongly_measurable _ ... < ∞ : add_lt_top.2 ⟨hf.has_finite_integral, hg.has_finite_integral⟩ lemma integrable.add {f g : α → β} (hf : integrable f μ) (hg : integrable g μ) : integrable (f + g) μ := ⟨hf.ae_strongly_measurable.add hg.ae_strongly_measurable, hf.add' hg⟩ lemma integrable_finset_sum' {ι} (s : finset ι) {f : ι → α → β} (hf : ∀ i ∈ s, integrable (f i) μ) : integrable (∑ i in s, f i) μ := finset.sum_induction f (λ g, integrable g μ) (λ _ _, integrable.add) (integrable_zero _ _ _) hf lemma integrable_finset_sum {ι} (s : finset ι) {f : ι → α → β} (hf : ∀ i ∈ s, integrable (f i) μ) : integrable (λ a, ∑ i in s, f i a) μ := by simpa only [← finset.sum_apply] using integrable_finset_sum' s hf lemma integrable.neg {f : α → β} (hf : integrable f μ) : integrable (-f) μ := ⟨hf.ae_strongly_measurable.neg, hf.has_finite_integral.neg⟩ @[simp] lemma integrable_neg_iff {f : α → β} : integrable (-f) μ ↔ integrable f μ := ⟨λ h, neg_neg f ▸ h.neg, integrable.neg⟩ lemma integrable.sub {f g : α → β} (hf : integrable f μ) (hg : integrable g μ) : integrable (f - g) μ := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma integrable.norm {f : α → β} (hf : integrable f μ) : integrable (λ a, ∥f a∥) μ := ⟨hf.ae_strongly_measurable.norm, hf.has_finite_integral.norm⟩ lemma integrable.inf {β} [normed_lattice_add_comm_group β] {f g : α → β} (hf : integrable f μ) (hg : integrable g μ) : integrable (f ⊓ g) μ := by { rw ← mem_ℒp_one_iff_integrable at hf hg ⊢, exact hf.inf hg, } lemma integrable.sup {β} [normed_lattice_add_comm_group β] {f g : α → β} (hf : integrable f μ) (hg : integrable g μ) : integrable (f ⊔ g) μ := by { rw ← mem_ℒp_one_iff_integrable at hf hg ⊢, exact hf.sup hg, } lemma integrable.abs {β} [normed_lattice_add_comm_group β] {f : α → β} (hf : integrable f μ) : integrable (λ a, |f a|) μ := by { rw ← mem_ℒp_one_iff_integrable at hf ⊢, exact hf.abs, } lemma integrable.bdd_mul {F : Type*} [normed_division_ring F] {f g : α → F} (hint : integrable g μ) (hm : ae_strongly_measurable f μ) (hfbdd : ∃ C, ∀ x, ∥f x∥ ≤ C) : integrable (λ x, f x * g x) μ := begin casesI is_empty_or_nonempty α with hα hα, { rw μ.eq_zero_of_is_empty, exact integrable_zero_measure }, { refine ⟨hm.mul hint.1, _⟩, obtain ⟨C, hC⟩ := hfbdd, have hCnonneg : 0 ≤ C := le_trans (norm_nonneg _) (hC hα.some), have : (λ x, ∥f x * g x∥₊) ≤ λ x, ⟨C, hCnonneg⟩ * ∥g x∥₊, { intro x, simp only [nnnorm_mul], exact mul_le_mul_of_nonneg_right (hC x) (zero_le _) }, refine lt_of_le_of_lt (lintegral_mono_nnreal this) _, simp only [ennreal.coe_mul], rw lintegral_const_mul' _ _ ennreal.coe_ne_top, exact ennreal.mul_lt_top ennreal.coe_ne_top (ne_of_lt hint.2) }, end lemma integrable_norm_iff {f : α → β} (hf : ae_strongly_measurable f μ) : integrable (λa, ∥f a∥) μ ↔ integrable f μ := by simp_rw [integrable, and_iff_right hf, and_iff_right hf.norm, has_finite_integral_norm_iff] lemma integrable_of_norm_sub_le {f₀ f₁ : α → β} {g : α → ℝ} (hf₁_m : ae_strongly_measurable f₁ μ) (hf₀_i : integrable f₀ μ) (hg_i : integrable g μ) (h : ∀ᵐ a ∂μ, ∥f₀ a - f₁ a∥ ≤ g a) : integrable f₁ μ := begin have : ∀ᵐ a ∂μ, ∥f₁ a∥ ≤ ∥f₀ a∥ + g a, { apply h.mono, intros a ha, calc ∥f₁ a∥ ≤ ∥f₀ a∥ + ∥f₀ a - f₁ a∥ : norm_le_insert _ _ ... ≤ ∥f₀ a∥ + g a : add_le_add_left ha _ }, exact integrable.mono' (hf₀_i.norm.add hg_i) hf₁_m this end lemma integrable.prod_mk {f : α → β} {g : α → γ} (hf : integrable f μ) (hg : integrable g μ) : integrable (λ x, (f x, g x)) μ := ⟨hf.ae_strongly_measurable.prod_mk hg.ae_strongly_measurable, (hf.norm.add' hg.norm).mono $ eventually_of_forall $ λ x, calc max ∥f x∥ ∥g x∥ ≤ ∥f x∥ + ∥g x∥ : max_le_add_of_nonneg (norm_nonneg _) (norm_nonneg _) ... ≤ ∥(∥f x∥ + ∥g x∥)∥ : le_abs_self _⟩ lemma mem_ℒp.integrable {q : ℝ≥0∞} (hq1 : 1 ≤ q) {f : α → β} [is_finite_measure μ] (hfq : mem_ℒp f q μ) : integrable f μ := mem_ℒp_one_iff_integrable.mp (hfq.mem_ℒp_of_exponent_le hq1) lemma lipschitz_with.integrable_comp_iff_of_antilipschitz {K K'} {f : α → β} {g : β → γ} (hg : lipschitz_with K g) (hg' : antilipschitz_with K' g) (g0 : g 0 = 0) : integrable (g ∘ f) μ ↔ integrable f μ := by simp [← mem_ℒp_one_iff_integrable, hg.mem_ℒp_comp_iff_of_antilipschitz hg' g0] lemma integrable.real_to_nnreal {f : α → ℝ} (hf : integrable f μ) : integrable (λ x, ((f x).to_nnreal : ℝ)) μ := begin refine ⟨hf.ae_strongly_measurable.ae_measurable .real_to_nnreal.coe_nnreal_real.ae_strongly_measurable, _⟩, rw has_finite_integral_iff_norm, refine lt_of_le_of_lt _ ((has_finite_integral_iff_norm _).1 hf.has_finite_integral), apply lintegral_mono, assume x, simp [ennreal.of_real_le_of_real, abs_le, le_abs_self], end lemma of_real_to_real_ae_eq {f : α → ℝ≥0∞} (hf : ∀ᵐ x ∂μ, f x < ∞) : (λ x, ennreal.of_real (f x).to_real) =ᵐ[μ] f := begin filter_upwards [hf], assume x hx, simp only [hx.ne, of_real_to_real, ne.def, not_false_iff], end lemma coe_to_nnreal_ae_eq {f : α → ℝ≥0∞} (hf : ∀ᵐ x ∂μ, f x < ∞) : (λ x, ((f x).to_nnreal : ℝ≥0∞)) =ᵐ[μ] f := begin filter_upwards [hf], assume x hx, simp only [hx.ne, ne.def, not_false_iff, coe_to_nnreal], end section variables {E : Type*} [normed_group E] [normed_space ℝ E] lemma integrable_with_density_iff_integrable_coe_smul {f : α → ℝ≥0} (hf : measurable f) {g : α → E} : integrable g (μ.with_density (λ x, f x)) ↔ integrable (λ x, (f x : ℝ) • g x) μ := begin by_cases H : ae_strongly_measurable (λ (x : α), (f x : ℝ) • g x) μ, { simp only [integrable, ae_strongly_measurable_with_density_iff hf, has_finite_integral, H, true_and], rw lintegral_with_density_eq_lintegral_mul₀' hf.coe_nnreal_ennreal.ae_measurable, { congr', ext1 x, simp only [nnnorm_smul, nnreal.nnnorm_eq, coe_mul, pi.mul_apply] }, { rw ae_measurable_with_density_ennreal_iff hf, convert H.ennnorm, ext1 x, simp only [nnnorm_smul, nnreal.nnnorm_eq, coe_mul] } }, { simp only [integrable, ae_strongly_measurable_with_density_iff hf, H, false_and] } end lemma integrable_with_density_iff_integrable_smul {f : α → ℝ≥0} (hf : measurable f) {g : α → E} : integrable g (μ.with_density (λ x, f x)) ↔ integrable (λ x, f x • g x) μ := integrable_with_density_iff_integrable_coe_smul hf lemma integrable_with_density_iff_integrable_smul' {f : α → ℝ≥0∞} (hf : measurable f) (hflt : ∀ᵐ x ∂μ, f x < ∞) {g : α → E} : integrable g (μ.with_density f) ↔ integrable (λ x, (f x).to_real • g x) μ := begin rw [← with_density_congr_ae (coe_to_nnreal_ae_eq hflt), integrable_with_density_iff_integrable_smul], { refl }, { exact hf.ennreal_to_nnreal }, end lemma integrable_with_density_iff_integrable_coe_smul₀ {f : α → ℝ≥0} (hf : ae_measurable f μ) {g : α → E} : integrable g (μ.with_density (λ x, f x)) ↔ integrable (λ x, (f x : ℝ) • g x) μ := calc integrable g (μ.with_density (λ x, f x)) ↔ integrable g (μ.with_density (λ x, hf.mk f x)) : begin suffices : (λ x, (f x : ℝ≥0∞)) =ᵐ[μ] (λ x, hf.mk f x), by rw with_density_congr_ae this, filter_upwards [hf.ae_eq_mk] with x hx, simp [hx], end ... ↔ integrable (λ x, (hf.mk f x : ℝ) • g x) μ : integrable_with_density_iff_integrable_coe_smul hf.measurable_mk ... ↔ integrable (λ x, (f x : ℝ) • g x) μ : begin apply integrable_congr, filter_upwards [hf.ae_eq_mk] with x hx, simp [hx], end lemma integrable_with_density_iff_integrable_smul₀ {f : α → ℝ≥0} (hf : ae_measurable f μ) {g : α → E} : integrable g (μ.with_density (λ x, f x)) ↔ integrable (λ x, f x • g x) μ := integrable_with_density_iff_integrable_coe_smul₀ hf end lemma integrable_with_density_iff {f : α → ℝ≥0∞} (hf : measurable f) (hflt : ∀ᵐ x ∂μ, f x < ∞) {g : α → ℝ} : integrable g (μ.with_density f) ↔ integrable (λ x, g x * (f x).to_real) μ := begin have : (λ x, g x * (f x).to_real) = (λ x, (f x).to_real • g x), by simp [mul_comm], rw this, exact integrable_with_density_iff_integrable_smul' hf hflt, end section variables {E : Type*} [normed_group E] [normed_space ℝ E] lemma mem_ℒ1_smul_of_L1_with_density {f : α → ℝ≥0} (f_meas : measurable f) (u : Lp E 1 (μ.with_density (λ x, f x))) : mem_ℒp (λ x, f x • u x) 1 μ := mem_ℒp_one_iff_integrable.2 $ (integrable_with_density_iff_integrable_smul f_meas).1 $ mem_ℒp_one_iff_integrable.1 (Lp.mem_ℒp u) variable (μ) /-- The map `u ↦ f • u` is an isometry between the `L^1` spaces for `μ.with_density f` and `μ`. -/ noncomputable def with_density_smul_li {f : α → ℝ≥0} (f_meas : measurable f) : Lp E 1 (μ.with_density (λ x, f x)) →ₗᵢ[ℝ] Lp E 1 μ := { to_fun := λ u, (mem_ℒ1_smul_of_L1_with_density f_meas u).to_Lp _, map_add' := begin assume u v, ext1, filter_upwards [(mem_ℒ1_smul_of_L1_with_density f_meas u).coe_fn_to_Lp, (mem_ℒ1_smul_of_L1_with_density f_meas v).coe_fn_to_Lp, (mem_ℒ1_smul_of_L1_with_density f_meas (u + v)).coe_fn_to_Lp, Lp.coe_fn_add ((mem_ℒ1_smul_of_L1_with_density f_meas u).to_Lp _) ((mem_ℒ1_smul_of_L1_with_density f_meas v).to_Lp _), (ae_with_density_iff f_meas.coe_nnreal_ennreal).1 (Lp.coe_fn_add u v)], assume x hu hv huv h' h'', rw [huv, h', pi.add_apply, hu, hv], rcases eq_or_ne (f x) 0 with hx|hx, { simp only [hx, zero_smul, add_zero] }, { rw [h'' _, pi.add_apply, smul_add], simpa only [ne.def, ennreal.coe_eq_zero] using hx } end, map_smul' := begin assume r u, ext1, filter_upwards [(ae_with_density_iff f_meas.coe_nnreal_ennreal).1 (Lp.coe_fn_smul r u), (mem_ℒ1_smul_of_L1_with_density f_meas (r • u)).coe_fn_to_Lp, Lp.coe_fn_smul r ((mem_ℒ1_smul_of_L1_with_density f_meas u).to_Lp _), (mem_ℒ1_smul_of_L1_with_density f_meas u).coe_fn_to_Lp], assume x h h' h'' h''', rw [ring_hom.id_apply, h', h'', pi.smul_apply, h'''], rcases eq_or_ne (f x) 0 with hx|hx, { simp only [hx, zero_smul, smul_zero] }, { rw [h _, smul_comm, pi.smul_apply], simpa only [ne.def, ennreal.coe_eq_zero] using hx } end, norm_map' := begin assume u, simp only [snorm, linear_map.coe_mk, Lp.norm_to_Lp, one_ne_zero, ennreal.one_ne_top, ennreal.one_to_real, if_false, snorm', ennreal.rpow_one, _root_.div_one, Lp.norm_def], rw lintegral_with_density_eq_lintegral_mul_non_measurable _ f_meas.coe_nnreal_ennreal (filter.eventually_of_forall (λ x, ennreal.coe_lt_top)), congr' 1, apply lintegral_congr_ae, filter_upwards [(mem_ℒ1_smul_of_L1_with_density f_meas u).coe_fn_to_Lp] with x hx, rw [hx, pi.mul_apply], change ↑∥(f x : ℝ) • u x∥₊ = ↑(f x) * ↑∥u x∥₊, simp only [nnnorm_smul, nnreal.nnnorm_eq, ennreal.coe_mul], end } @[simp] lemma with_density_smul_li_apply {f : α → ℝ≥0} (f_meas : measurable f) (u : Lp E 1 (μ.with_density (λ x, f x))) : with_density_smul_li μ f_meas u = (mem_ℒ1_smul_of_L1_with_density f_meas u).to_Lp (λ x, f x • u x) := rfl end lemma mem_ℒ1_to_real_of_lintegral_ne_top {f : α → ℝ≥0∞} (hfm : ae_measurable f μ) (hfi : ∫⁻ x, f x ∂μ ≠ ∞) : mem_ℒp (λ x, (f x).to_real) 1 μ := begin rw [mem_ℒp, snorm_one_eq_lintegral_nnnorm], exact ⟨(ae_measurable.ennreal_to_real hfm).ae_strongly_measurable, has_finite_integral_to_real_of_lintegral_ne_top hfi⟩ end lemma integrable_to_real_of_lintegral_ne_top {f : α → ℝ≥0∞} (hfm : ae_measurable f μ) (hfi : ∫⁻ x, f x ∂μ ≠ ∞) : integrable (λ x, (f x).to_real) μ := mem_ℒp_one_iff_integrable.1 $ mem_ℒ1_to_real_of_lintegral_ne_top hfm hfi section pos_part /-! ### Lemmas used for defining the positive part of a `L¹` function -/ lemma integrable.pos_part {f : α → ℝ} (hf : integrable f μ) : integrable (λ a, max (f a) 0) μ := ⟨(hf.ae_strongly_measurable.ae_measurable.max ae_measurable_const).ae_strongly_measurable, hf.has_finite_integral.max_zero⟩ lemma integrable.neg_part {f : α → ℝ} (hf : integrable f μ) : integrable (λ a, max (-f a) 0) μ := hf.neg.pos_part end pos_part section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma integrable.smul (c : 𝕜) {f : α → β} (hf : integrable f μ) : integrable (c • f) μ := ⟨hf.ae_strongly_measurable.const_smul c, hf.has_finite_integral.smul c⟩ lemma integrable_smul_iff {c : 𝕜} (hc : c ≠ 0) (f : α → β) : integrable (c • f) μ ↔ integrable f μ := and_congr (ae_strongly_measurable_const_smul_iff₀ hc) (has_finite_integral_smul_iff hc f) lemma integrable.const_mul {f : α → ℝ} (h : integrable f μ) (c : ℝ) : integrable (λ x, c * f x) μ := integrable.smul c h lemma integrable.const_mul' {f : α → ℝ} (h : integrable f μ) (c : ℝ) : integrable ((λ (x : α), c) * f) μ := integrable.smul c h lemma integrable.mul_const {f : α → ℝ} (h : integrable f μ) (c : ℝ) : integrable (λ x, f x * c) μ := by simp_rw [mul_comm, h.const_mul _] lemma integrable.mul_const' {f : α → ℝ} (h : integrable f μ) (c : ℝ) : integrable (f * (λ (x : α), c)) μ := integrable.mul_const h c lemma integrable.div_const {f : α → ℝ} (h : integrable f μ) (c : ℝ) : integrable (λ x, f x / c) μ := by simp_rw [div_eq_mul_inv, h.mul_const] end normed_space section normed_space_over_complete_field variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] [complete_space 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] lemma integrable_smul_const {f : α → 𝕜} {c : E} (hc : c ≠ 0) : integrable (λ x, f x • c) μ ↔ integrable f μ := begin simp_rw [integrable, ae_strongly_measurable_smul_const_iff hc, and.congr_right_iff, has_finite_integral, nnnorm_smul, ennreal.coe_mul], intro hf, rw [lintegral_mul_const' _ _ ennreal.coe_ne_top, ennreal.mul_lt_top_iff], have : ∀ x : ℝ≥0∞, x = 0 → x < ∞ := by simp, simp [hc, or_iff_left_of_imp (this _)] end end normed_space_over_complete_field section is_R_or_C variables {𝕜 : Type*} [is_R_or_C 𝕜] {f : α → 𝕜} lemma integrable.of_real {f : α → ℝ} (hf : integrable f μ) : integrable (λ x, (f x : 𝕜)) μ := by { rw ← mem_ℒp_one_iff_integrable at hf ⊢, exact hf.of_real } lemma integrable.re_im_iff : integrable (λ x, is_R_or_C.re (f x)) μ ∧ integrable (λ x, is_R_or_C.im (f x)) μ ↔ integrable f μ := by { simp_rw ← mem_ℒp_one_iff_integrable, exact mem_ℒp_re_im_iff } lemma integrable.re (hf : integrable f μ) : integrable (λ x, is_R_or_C.re (f x)) μ := by { rw ← mem_ℒp_one_iff_integrable at hf ⊢, exact hf.re, } lemma integrable.im (hf : integrable f μ) : integrable (λ x, is_R_or_C.im (f x)) μ := by { rw ← mem_ℒp_one_iff_integrable at hf ⊢, exact hf.im, } end is_R_or_C section inner_product variables {𝕜 E : Type*} [is_R_or_C 𝕜] [inner_product_space 𝕜 E] {f : α → E} local notation `⟪`x`, `y`⟫` := @inner 𝕜 E _ x y lemma integrable.const_inner (c : E) (hf : integrable f μ) : integrable (λ x, ⟪c, f x⟫) μ := by { rw ← mem_ℒp_one_iff_integrable at hf ⊢, exact hf.const_inner c, } lemma integrable.inner_const (hf : integrable f μ) (c : E) : integrable (λ x, ⟪f x, c⟫) μ := by { rw ← mem_ℒp_one_iff_integrable at hf ⊢, exact hf.inner_const c, } end inner_product section trim variables {H : Type*} [normed_group H] {m0 : measurable_space α} {μ' : measure α} {f : α → H} lemma integrable.trim (hm : m ≤ m0) (hf_int : integrable f μ') (hf : strongly_measurable[m] f) : integrable f (μ'.trim hm) := begin refine ⟨hf.ae_strongly_measurable, _⟩, rw [has_finite_integral, lintegral_trim hm _], { exact hf_int.2, }, { exact @strongly_measurable.ennnorm _ m _ _ f hf }, end lemma integrable_of_integrable_trim (hm : m ≤ m0) (hf_int : integrable f (μ'.trim hm)) : integrable f μ' := begin obtain ⟨hf_meas_ae, hf⟩ := hf_int, refine ⟨ae_strongly_measurable_of_ae_strongly_measurable_trim hm hf_meas_ae, _⟩, rw has_finite_integral at hf ⊢, rwa lintegral_trim_ae hm _ at hf, exact ae_strongly_measurable.ennnorm hf_meas_ae end end trim section sigma_finite variables {E : Type*} {m0 : measurable_space α} [normed_group E] lemma integrable_of_forall_fin_meas_le' {μ : measure α} (hm : m ≤ m0) [sigma_finite (μ.trim hm)] (C : ℝ≥0∞) (hC : C < ∞) {f : α → E} (hf_meas : ae_strongly_measurable f μ) (hf : ∀ s, measurable_set[m] s → μ s ≠ ∞ → ∫⁻ x in s, ∥f x∥₊ ∂μ ≤ C) : integrable f μ := ⟨hf_meas, (lintegral_le_of_forall_fin_meas_le' hm C hf_meas.ennnorm hf).trans_lt hC⟩ lemma integrable_of_forall_fin_meas_le [sigma_finite μ] (C : ℝ≥0∞) (hC : C < ∞) {f : α → E} (hf_meas : ae_strongly_measurable f μ) (hf : ∀ s : set α, measurable_set s → μ s ≠ ∞ → ∫⁻ x in s, ∥f x∥₊ ∂μ ≤ C) : integrable f μ := @integrable_of_forall_fin_meas_le' _ _ _ _ _ _ _ (by rwa trim_eq_self) C hC _ hf_meas hf end sigma_finite /-! ### The predicate `integrable` on measurable functions modulo a.e.-equality -/ namespace ae_eq_fun section /-- A class of almost everywhere equal functions is `integrable` if its function representative is integrable. -/ def integrable (f : α →ₘ[μ] β) : Prop := integrable f μ lemma integrable_mk {f : α → β} (hf : ae_strongly_measurable f μ ) : (integrable (mk f hf : α →ₘ[μ] β)) ↔ measure_theory.integrable f μ := begin simp [integrable], apply integrable_congr, exact coe_fn_mk f hf end lemma integrable_coe_fn {f : α →ₘ[μ] β} : (measure_theory.integrable f μ) ↔ integrable f := by rw [← integrable_mk, mk_coe_fn] lemma integrable_zero : integrable (0 : α →ₘ[μ] β) := (integrable_zero α β μ).congr (coe_fn_mk _ _).symm end section lemma integrable.neg {f : α →ₘ[μ] β} : integrable f → integrable (-f) := induction_on f $ λ f hfm hfi, (integrable_mk _).2 ((integrable_mk hfm).1 hfi).neg section lemma integrable_iff_mem_L1 {f : α →ₘ[μ] β} : integrable f ↔ f ∈ (α →₁[μ] β) := by rw [← integrable_coe_fn, ← mem_ℒp_one_iff_integrable, Lp.mem_Lp_iff_mem_ℒp] lemma integrable.add {f g : α →ₘ[μ] β} : integrable f → integrable g → integrable (f + g) := begin refine induction_on₂ f g (λ f hf g hg hfi hgi, _), simp only [integrable_mk, mk_add_mk] at hfi hgi ⊢, exact hfi.add hgi end lemma integrable.sub {f g : α →ₘ[μ] β} (hf : integrable f) (hg : integrable g) : integrable (f - g) := (sub_eq_add_neg f g).symm ▸ hf.add hg.neg end section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma integrable.smul {c : 𝕜} {f : α →ₘ[μ] β} : integrable f → integrable (c • f) := induction_on f $ λ f hfm hfi, (integrable_mk _).2 $ ((integrable_mk hfm).1 hfi).smul _ end normed_space end end ae_eq_fun namespace L1 lemma integrable_coe_fn (f : α →₁[μ] β) : integrable f μ := by { rw ← mem_ℒp_one_iff_integrable, exact Lp.mem_ℒp f } lemma has_finite_integral_coe_fn (f : α →₁[μ] β) : has_finite_integral f μ := (integrable_coe_fn f).has_finite_integral lemma strongly_measurable_coe_fn (f : α →₁[μ] β) : strongly_measurable f := Lp.strongly_measurable f lemma measurable_coe_fn [measurable_space β] [borel_space β] (f : α →₁[μ] β) : measurable f := (Lp.strongly_measurable f).measurable lemma ae_strongly_measurable_coe_fn (f : α →₁[μ] β) : ae_strongly_measurable f μ := Lp.ae_strongly_measurable f lemma ae_measurable_coe_fn [measurable_space β] [borel_space β] (f : α →₁[μ] β) : ae_measurable f μ := (Lp.strongly_measurable f).measurable.ae_measurable lemma edist_def (f g : α →₁[μ] β) : edist f g = ∫⁻ a, edist (f a) (g a) ∂μ := by { simp [Lp.edist_def, snorm, snorm'], simp [edist_eq_coe_nnnorm_sub] } lemma dist_def (f g : α →₁[μ] β) : dist f g = (∫⁻ a, edist (f a) (g a) ∂μ).to_real := by { simp [Lp.dist_def, snorm, snorm'], simp [edist_eq_coe_nnnorm_sub] } lemma norm_def (f : α →₁[μ] β) : ∥f∥ = (∫⁻ a, ∥f a∥₊ ∂μ).to_real := by { simp [Lp.norm_def, snorm, snorm'] } /-- Computing the norm of a difference between two L¹-functions. Note that this is not a special case of `norm_def` since `(f - g) x` and `f x - g x` are not equal (but only a.e.-equal). -/ lemma norm_sub_eq_lintegral (f g : α →₁[μ] β) : ∥f - g∥ = (∫⁻ x, (∥f x - g x∥₊ : ℝ≥0∞) ∂μ).to_real := begin rw [norm_def], congr' 1, rw lintegral_congr_ae, filter_upwards [Lp.coe_fn_sub f g] with _ ha, simp only [ha, pi.sub_apply], end lemma of_real_norm_eq_lintegral (f : α →₁[μ] β) : ennreal.of_real ∥f∥ = ∫⁻ x, (∥f x∥₊ : ℝ≥0∞) ∂μ := by { rw [norm_def, ennreal.of_real_to_real], exact ne_of_lt (has_finite_integral_coe_fn f) } /-- Computing the norm of a difference between two L¹-functions. Note that this is not a special case of `of_real_norm_eq_lintegral` since `(f - g) x` and `f x - g x` are not equal (but only a.e.-equal). -/ lemma of_real_norm_sub_eq_lintegral (f g : α →₁[μ] β) : ennreal.of_real ∥f - g∥ = ∫⁻ x, (∥f x - g x∥₊ : ℝ≥0∞) ∂μ := begin simp_rw [of_real_norm_eq_lintegral, ← edist_eq_coe_nnnorm], apply lintegral_congr_ae, filter_upwards [Lp.coe_fn_sub f g] with _ ha, simp only [ha, pi.sub_apply], end end L1 namespace integrable /-- Construct the equivalence class `[f]` of an integrable function `f`, as a member of the space `L1 β 1 μ`. -/ def to_L1 (f : α → β) (hf : integrable f μ) : α →₁[μ] β := (mem_ℒp_one_iff_integrable.2 hf).to_Lp f @[simp] lemma to_L1_coe_fn (f : α →₁[μ] β) (hf : integrable f μ) : hf.to_L1 f = f := by simp [integrable.to_L1] lemma coe_fn_to_L1 {f : α → β} (hf : integrable f μ) : hf.to_L1 f =ᵐ[μ] f := ae_eq_fun.coe_fn_mk _ _ @[simp] lemma to_L1_zero (h : integrable (0 : α → β) μ) : h.to_L1 0 = 0 := rfl @[simp] lemma to_L1_eq_mk (f : α → β) (hf : integrable f μ) : (hf.to_L1 f : α →ₘ[μ] β) = ae_eq_fun.mk f hf.ae_strongly_measurable := rfl @[simp] lemma to_L1_eq_to_L1_iff (f g : α → β) (hf : integrable f μ) (hg : integrable g μ) : to_L1 f hf = to_L1 g hg ↔ f =ᵐ[μ] g := mem_ℒp.to_Lp_eq_to_Lp_iff _ _ lemma to_L1_add (f g : α → β) (hf : integrable f μ) (hg : integrable g μ) : to_L1 (f + g) (hf.add hg) = to_L1 f hf + to_L1 g hg := rfl lemma to_L1_neg (f : α → β) (hf : integrable f μ) : to_L1 (- f) (integrable.neg hf) = - to_L1 f hf := rfl lemma to_L1_sub (f g : α → β) (hf : integrable f μ) (hg : integrable g μ) : to_L1 (f - g) (hf.sub hg) = to_L1 f hf - to_L1 g hg := rfl lemma norm_to_L1 (f : α → β) (hf : integrable f μ) : ∥hf.to_L1 f∥ = ennreal.to_real (∫⁻ a, edist (f a) 0 ∂μ) := by { simp [to_L1, snorm, snorm'], simp [edist_eq_coe_nnnorm] } lemma norm_to_L1_eq_lintegral_norm (f : α → β) (hf : integrable f μ) : ∥hf.to_L1 f∥ = ennreal.to_real (∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ) := by { rw [norm_to_L1, lintegral_norm_eq_lintegral_edist] } @[simp] lemma edist_to_L1_to_L1 (f g : α → β) (hf : integrable f μ) (hg : integrable g μ) : edist (hf.to_L1 f) (hg.to_L1 g) = ∫⁻ a, edist (f a) (g a) ∂μ := by { simp [integrable.to_L1, snorm, snorm'], simp [edist_eq_coe_nnnorm_sub] } @[simp] lemma edist_to_L1_zero (f : α → β) (hf : integrable f μ) : edist (hf.to_L1 f) 0 = ∫⁻ a, edist (f a) 0 ∂μ := by { simp [integrable.to_L1, snorm, snorm'], simp [edist_eq_coe_nnnorm] } variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma to_L1_smul (f : α → β) (hf : integrable f μ) (k : 𝕜) : to_L1 (λ a, k • f a) (hf.smul k) = k • to_L1 f hf := rfl lemma to_L1_smul' (f : α → β) (hf : integrable f μ) (k : 𝕜) : to_L1 (k • f) (hf.smul k) = k • to_L1 f hf := rfl end integrable end measure_theory open measure_theory variables {E : Type*} [normed_group E] {𝕜 : Type*} [nondiscrete_normed_field 𝕜] [normed_space 𝕜 E] {H : Type*} [normed_group H] [normed_space 𝕜 H] lemma measure_theory.integrable.apply_continuous_linear_map {φ : α → H →L[𝕜] E} (φ_int : integrable φ μ) (v : H) : integrable (λ a, φ a v) μ := (φ_int.norm.mul_const ∥v∥).mono' (φ_int.ae_strongly_measurable.apply_continuous_linear_map v) (eventually_of_forall $ λ a, (φ a).le_op_norm v) lemma continuous_linear_map.integrable_comp {φ : α → H} (L : H →L[𝕜] E) (φ_int : integrable φ μ) : integrable (λ (a : α), L (φ a)) μ := ((integrable.norm φ_int).const_mul ∥L∥).mono' (L.continuous.comp_ae_strongly_measurable φ_int.ae_strongly_measurable) (eventually_of_forall $ λ a, L.le_op_norm (φ a))
f1e15ae2536f1e732a31ad9d86f757fe874994c5
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/doc/demo/kernel.lean
35111d0b1dfbc5e2541fcf1da980ade41476447d
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
26,058
lean
import macros universe U ≥ 1 definition TypeU := (Type U) variable Bool : Type -- The following builtin declarations can be removed as soon as Lean supports inductive datatypes and match expressions builtin true : Bool builtin false : Bool definition not (a : Bool) := a → false notation 40 ¬ _ : not definition or (a b : Bool) := ¬ a → b infixr 30 || : or infixr 30 \/ : or infixr 30 ∨ : or definition and (a b : Bool) := ¬ (a → ¬ b) infixr 35 && : and infixr 35 /\ : and infixr 35 ∧ : and definition implies (a b : Bool) := a → b builtin eq {A : (Type U)} (a b : A) : Bool infix 50 = : eq definition neq {A : TypeU} (a b : A) := ¬ (a = b) infix 50 ≠ : neq definition iff (a b : Bool) := a = b infixr 25 <-> : iff infixr 25 ↔ : iff -- The Lean parser has special treatment for the constant exists. -- It allows us to write -- exists x y : A, P x y and ∃ x y : A, P x y -- as syntax sugar for -- exists A (fun x : A, exists A (fun y : A, P x y)) -- That is, it treats the exists as an extra binder such as fun and forall. -- It also provides an alias (Exists) that should be used when we -- want to treat exists as a constant. definition Exists (A : TypeU) (P : A → Bool) := ¬ (∀ x, ¬ (P x)) definition nonempty (A : TypeU) := ∃ x : A, true -- If we have an element of type A, then A is nonempty theorem nonempty_intro {A : TypeU} (a : A) : nonempty A := assume H : (∀ x, ¬ true), (H a) theorem em (a : Bool) : a ∨ ¬ a := assume Hna : ¬ a, Hna axiom case (P : Bool → Bool) (H1 : P true) (H2 : P false) (a : Bool) : P a axiom refl {A : TypeU} (a : A) : a = a axiom subst {A : TypeU} {a b : A} {P : A → Bool} (H1 : P a) (H2 : a = b) : P b -- Function extensionality axiom funext {A : TypeU} {B : A → TypeU} {f g : ∀ x : A, B x} (H : ∀ x : A, f x = g x) : f = g -- Forall extensionality axiom allext {A : TypeU} {B C : A → Bool} (H : ∀ x : A, B x = C x) : (∀ x : A, B x) = (∀ x : A, C x) -- Epsilon (Hilbert's operator) variable eps {A : TypeU} (H : nonempty A) (P : A → Bool) : A alias ε : eps axiom eps_ax {A : TypeU} (H : nonempty A) {P : A → Bool} (a : A) : P a → P (ε H P) -- Proof irrelevance axiom proof_irrel {a : Bool} (H1 H2 : a) : H1 = H2 theorem eps_th {A : TypeU} {P : A → Bool} (a : A) : P a → P (ε (nonempty_intro a) P) := assume H : P a, @eps_ax A (nonempty_intro a) P a H -- Alias for subst where we can provide P explicitly, but keep A,a,b implicit theorem substp {A : TypeU} {a b : A} (P : A → Bool) (H1 : P a) (H2 : a = b) : P b := subst H1 H2 -- We will mark not as opaque later theorem not_intro {a : Bool} (H : a → false) : ¬ a := H theorem eta {A : TypeU} {B : A → TypeU} (f : ∀ x : A, B x) : (λ x : A, f x) = f := funext (λ x : A, refl (f x)) -- create default rewrite rule set (* mk_rewrite_rule_set() *) theorem trivial : true := refl true theorem absurd {a : Bool} (H1 : a) (H2 : ¬ a) : false := H2 H1 theorem eqmp {a b : Bool} (H1 : a = b) (H2 : a) : b := subst H2 H1 infixl 100 <| : eqmp infixl 100 ◂ : eqmp theorem boolcomplete (a : Bool) : a = true ∨ a = false := case (λ x, x = true ∨ x = false) trivial trivial a theorem false_elim (a : Bool) (H : false) : a := case (λ x, x) trivial H a theorem imp_trans {a b c : Bool} (H1 : a → b) (H2 : b → c) : a → c := assume Ha, H2 (H1 Ha) theorem imp_eq_trans {a b c : Bool} (H1 : a → b) (H2 : b = c) : a → c := assume Ha, H2 ◂ (H1 Ha) theorem eq_imp_trans {a b c : Bool} (H1 : a = b) (H2 : b → c) : a → c := assume Ha, H2 (H1 ◂ Ha) theorem not_not_eq (a : Bool) : ¬ ¬ a ↔ a := case (λ x, ¬ ¬ x ↔ x) trivial trivial a theorem not_not_elim {a : Bool} (H : ¬ ¬ a) : a := (not_not_eq a) ◂ H theorem mt {a b : Bool} (H1 : a → b) (H2 : ¬ b) : ¬ a := assume Ha : a, absurd (H1 Ha) H2 theorem contrapos {a b : Bool} (H : a → b) : ¬ b → ¬ a := assume Hnb : ¬ b, mt H Hnb theorem absurd_elim {a : Bool} (b : Bool) (H1 : a) (H2 : ¬ a) : b := false_elim b (absurd H1 H2) theorem not_imp_eliml {a b : Bool} (Hnab : ¬ (a → b)) : a := not_not_elim (have ¬ ¬ a : assume Hna : ¬ a, absurd (assume Ha : a, absurd_elim b Ha Hna) Hnab) theorem not_imp_elimr {a b : Bool} (H : ¬ (a → b)) : ¬ b := assume Hb : b, absurd (assume Ha : a, Hb) H theorem resolve1 {a b : Bool} (H1 : a ∨ b) (H2 : ¬ a) : b := H1 H2 -- Recall that and is defined as ¬ (a → ¬ b) theorem and_intro {a b : Bool} (H1 : a) (H2 : b) : a ∧ b := assume H : a → ¬ b, absurd H2 (H H1) theorem and_eliml {a b : Bool} (H : a ∧ b) : a := not_imp_eliml H theorem and_elimr {a b : Bool} (H : a ∧ b) : b := not_not_elim (not_imp_elimr H) -- Recall that or is defined as ¬ a → b theorem or_introl {a : Bool} (H : a) (b : Bool) : a ∨ b := assume H1 : ¬ a, absurd_elim b H H1 theorem or_intror {b : Bool} (a : Bool) (H : b) : a ∨ b := assume H1 : ¬ a, H theorem or_elim {a b c : Bool} (H1 : a ∨ b) (H2 : a → c) (H3 : b → c) : c := not_not_elim (assume H : ¬ c, absurd (have c : H3 (have b : resolve1 H1 (have ¬ a : (mt (assume Ha : a, H2 Ha) H)))) H) theorem refute {a : Bool} (H : ¬ a → false) : a := or_elim (em a) (λ H1 : a, H1) (λ H1 : ¬ a, false_elim a (H H1)) theorem symm {A : TypeU} {a b : A} (H : a = b) : b = a := subst (refl a) H theorem eqmpr {a b : Bool} (H1 : a = b) (H2 : b) : a := (symm H1) ◂ H2 theorem trans {A : TypeU} {a b c : A} (H1 : a = b) (H2 : b = c) : a = c := subst H1 H2 theorem ne_symm {A : TypeU} {a b : A} (H : a ≠ b) : b ≠ a := assume H1 : b = a, H (symm H1) theorem eq_ne_trans {A : TypeU} {a b c : A} (H1 : a = b) (H2 : b ≠ c) : a ≠ c := subst H2 (symm H1) theorem ne_eq_trans {A : TypeU} {a b c : A} (H1 : a ≠ b) (H2 : b = c) : a ≠ c := subst H1 H2 theorem eqt_elim {a : Bool} (H : a = true) : a := (symm H) ◂ trivial theorem eqf_elim {a : Bool} (H : a = false) : ¬ a := not_intro (λ Ha : a, H ◂ Ha) theorem congr1 {A B : TypeU} {f g : A → B} (a : A) (H : f = g) : f a = g a := substp (fun h : A → B, f a = h a) (refl (f a)) H theorem congr2 {A B : TypeU} {a b : A} (f : A → B) (H : a = b) : f a = f b := substp (fun x : A, f a = f x) (refl (f a)) H theorem congr {A B : TypeU} {f g : A → B} {a b : A} (H1 : f = g) (H2 : a = b) : f a = g b := subst (congr2 f H2) (congr1 b H1) -- Recall that exists is defined as ¬ ∀ x : A, ¬ P x theorem exists_elim {A : TypeU} {P : A → Bool} {B : Bool} (H1 : Exists A P) (H2 : ∀ (a : A) (H : P a), B) : B := refute (λ R : ¬ B, absurd (take a : A, mt (assume H : P a, H2 a H) R) H1) theorem exists_intro {A : TypeU} {P : A → Bool} (a : A) (H : P a) : Exists A P := assume H1 : (∀ x : A, ¬ P x), absurd H (H1 a) theorem nonempty_elim {A : TypeU} (H1 : nonempty A) {B : Bool} (H2 : A → B) : B := obtain (w : A) (Hw : true), from H1, H2 w theorem nonempty_ex_intro {A : TypeU} {P : A → Bool} (H : ∃ x, P x) : nonempty A := obtain (w : A) (Hw : P w), from H, exists_intro w trivial theorem exists_to_eps {A : TypeU} {P : A → Bool} (H : ∃ x, P x) : P (ε (nonempty_ex_intro H) P) := obtain (w : A) (Hw : P w), from H, eps_ax (nonempty_ex_intro H) w Hw theorem axiom_of_choice {A : TypeU} {B : A → TypeU} {R : ∀ x : A, B x → Bool} (H : ∀ x, ∃ y, R x y) : ∃ f, ∀ x, R x (f x) := exists_intro (λ x, ε (nonempty_ex_intro (H x)) (λ y, R x y)) -- witness for f (λ x, exists_to_eps (H x)) -- proof that witness satisfies ∀ x, R x (f x) theorem boolext {a b : Bool} (Hab : a → b) (Hba : b → a) : a = b := or_elim (boolcomplete a) (λ Hat : a = true, or_elim (boolcomplete b) (λ Hbt : b = true, trans Hat (symm Hbt)) (λ Hbf : b = false, false_elim (a = b) (subst (Hab (eqt_elim Hat)) Hbf))) (λ Haf : a = false, or_elim (boolcomplete b) (λ Hbt : b = true, false_elim (a = b) (subst (Hba (eqt_elim Hbt)) Haf)) (λ Hbf : b = false, trans Haf (symm Hbf))) theorem iff_intro {a b : Bool} (Hab : a → b) (Hba : b → a) : a ↔ b := boolext Hab Hba theorem iff_eliml {a b : Bool} (H : a ↔ b) : a → b := (λ Ha : a, eqmp H Ha) theorem iff_elimr {a b : Bool} (H : a ↔ b) : b → a := (λ Hb : b, eqmpr H Hb) theorem skolem_th {A : TypeU} {B : A → TypeU} {P : ∀ x : A, B x → Bool} : (∀ x, ∃ y, P x y) ↔ ∃ f, (∀ x, P x (f x)) := iff_intro (λ H : (∀ x, ∃ y, P x y), axiom_of_choice H) (λ H : (∃ f, (∀ x, P x (f x))), take x, obtain (fw : ∀ x, B x) (Hw : ∀ x, P x (fw x)), from H, exists_intro (fw x) (Hw x)) theorem eqt_intro {a : Bool} (H : a) : a = true := boolext (assume H1 : a, trivial) (assume H2 : true, H) theorem eqf_intro {a : Bool} (H : ¬ a) : a = false := boolext (assume H1 : a, absurd H1 H) (assume H2 : false, false_elim a H2) theorem neq_elim {A : TypeU} {a b : A} (H : a ≠ b) : a = b ↔ false := eqf_intro H theorem eq_id {A : TypeU} (a : A) : (a = a) ↔ true := eqt_intro (refl a) theorem iff_id (a : Bool) : (a ↔ a) ↔ true := eqt_intro (refl a) theorem or_comm (a b : Bool) : (a ∨ b) = (b ∨ a) := boolext (assume H, or_elim H (λ H1, or_intror b H1) (λ H2, or_introl H2 a)) (assume H, or_elim H (λ H1, or_intror a H1) (λ H2, or_introl H2 b)) theorem or_assoc (a b c : Bool) : (a ∨ b) ∨ c ↔ a ∨ (b ∨ c) := boolext (assume H : (a ∨ b) ∨ c, or_elim H (λ H1 : a ∨ b, or_elim H1 (λ Ha : a, or_introl Ha (b ∨ c)) (λ Hb : b, or_intror a (or_introl Hb c))) (λ Hc : c, or_intror a (or_intror b Hc))) (assume H : a ∨ (b ∨ c), or_elim H (λ Ha : a, (or_introl (or_introl Ha b) c)) (λ H1 : b ∨ c, or_elim H1 (λ Hb : b, or_introl (or_intror a Hb) c) (λ Hc : c, or_intror (a ∨ b) Hc))) theorem or_id (a : Bool) : a ∨ a ↔ a := boolext (assume H, or_elim H (λ H1, H1) (λ H2, H2)) (assume H, or_introl H a) theorem or_falsel (a : Bool) : a ∨ false ↔ a := boolext (assume H, or_elim H (λ H1, H1) (λ H2, false_elim a H2)) (assume H, or_introl H false) theorem or_falser (a : Bool) : false ∨ a ↔ a := trans (or_comm false a) (or_falsel a) theorem or_truel (a : Bool) : true ∨ a ↔ true := eqt_intro (case (λ x : Bool, true ∨ x) trivial trivial a) theorem or_truer (a : Bool) : a ∨ true ↔ true := trans (or_comm a true) (or_truel a) theorem or_tauto (a : Bool) : a ∨ ¬ a ↔ true := eqt_intro (em a) theorem and_comm (a b : Bool) : a ∧ b ↔ b ∧ a := boolext (assume H, and_intro (and_elimr H) (and_eliml H)) (assume H, and_intro (and_elimr H) (and_eliml H)) theorem and_id (a : Bool) : a ∧ a ↔ a := boolext (assume H, and_eliml H) (assume H, and_intro H H) theorem and_assoc (a b c : Bool) : (a ∧ b) ∧ c ↔ a ∧ (b ∧ c) := boolext (assume H, and_intro (and_eliml (and_eliml H)) (and_intro (and_elimr (and_eliml H)) (and_elimr H))) (assume H, and_intro (and_intro (and_eliml H) (and_eliml (and_elimr H))) (and_elimr (and_elimr H))) theorem and_truer (a : Bool) : a ∧ true ↔ a := boolext (assume H : a ∧ true, and_eliml H) (assume H : a, and_intro H trivial) theorem and_truel (a : Bool) : true ∧ a ↔ a := trans (and_comm true a) (and_truer a) theorem and_falsel (a : Bool) : a ∧ false ↔ false := boolext (assume H, and_elimr H) (assume H, false_elim (a ∧ false) H) theorem and_falser (a : Bool) : false ∧ a ↔ false := trans (and_comm false a) (and_falsel a) theorem and_absurd (a : Bool) : a ∧ ¬ a ↔ false := boolext (assume H, absurd (and_eliml H) (and_elimr H)) (assume H, false_elim (a ∧ ¬ a) H) theorem imp_truer (a : Bool) : (a → true) ↔ true := case (λ x, (x → true) ↔ true) trivial trivial a theorem imp_truel (a : Bool) : (true → a) ↔ a := case (λ x, (true → x) ↔ x) trivial trivial a theorem imp_falser (a : Bool) : (a → false) ↔ ¬ a := refl _ theorem imp_falsel (a : Bool) : (false → a) ↔ true := case (λ x, (false → x) ↔ true) trivial trivial a theorem imp_or (a b : Bool) : (a → b) ↔ ¬ a ∨ b := iff_intro (assume H : a → b, (or_elim (em a) (λ Ha : a, or_intror (¬ a) (H Ha)) (λ Hna : ¬ a, or_introl Hna b))) (assume H : ¬ a ∨ b, assume Ha : a, resolve1 H ((symm (not_not_eq a)) ◂ Ha)) theorem not_true : ¬ true ↔ false := trivial theorem not_false : ¬ false ↔ true := trivial theorem not_neq {A : TypeU} (a b : A) : ¬ (a ≠ b) ↔ a = b := not_not_eq (a = b) theorem not_neq_elim {A : TypeU} {a b : A} (H : ¬ (a ≠ b)) : a = b := (not_neq a b) ◂ H theorem not_and (a b : Bool) : ¬ (a ∧ b) ↔ ¬ a ∨ ¬ b := case (λ x, ¬ (x ∧ b) ↔ ¬ x ∨ ¬ b) (case (λ y, ¬ (true ∧ y) ↔ ¬ true ∨ ¬ y) trivial trivial b) (case (λ y, ¬ (false ∧ y) ↔ ¬ false ∨ ¬ y) trivial trivial b) a theorem not_and_elim {a b : Bool} (H : ¬ (a ∧ b)) : ¬ a ∨ ¬ b := (not_and a b) ◂ H theorem not_or (a b : Bool) : ¬ (a ∨ b) ↔ ¬ a ∧ ¬ b := case (λ x, ¬ (x ∨ b) ↔ ¬ x ∧ ¬ b) (case (λ y, ¬ (true ∨ y) ↔ ¬ true ∧ ¬ y) trivial trivial b) (case (λ y, ¬ (false ∨ y) ↔ ¬ false ∧ ¬ y) trivial trivial b) a theorem not_or_elim {a b : Bool} (H : ¬ (a ∨ b)) : ¬ a ∧ ¬ b := (not_or a b) ◂ H theorem not_iff (a b : Bool) : ¬ (a ↔ b) ↔ (¬ a ↔ b) := case (λ x, ¬ (x ↔ b) ↔ ((¬ x) ↔ b)) (case (λ y, ¬ (true ↔ y) ↔ ((¬ true) ↔ y)) trivial trivial b) (case (λ y, ¬ (false ↔ y) ↔ ((¬ false) ↔ y)) trivial trivial b) a theorem not_iff_elim {a b : Bool} (H : ¬ (a ↔ b)) : (¬ a) ↔ b := (not_iff a b) ◂ H theorem not_implies (a b : Bool) : ¬ (a → b) ↔ a ∧ ¬ b := case (λ x, ¬ (x → b) ↔ x ∧ ¬ b) (case (λ y, ¬ (true → y) ↔ true ∧ ¬ y) trivial trivial b) (case (λ y, ¬ (false → y) ↔ false ∧ ¬ y) trivial trivial b) a theorem not_implies_elim {a b : Bool} (H : ¬ (a → b)) : a ∧ ¬ b := (not_implies a b) ◂ H theorem not_congr {a b : Bool} (H : a ↔ b) : ¬ a ↔ ¬ b := congr2 not H theorem exists_rem {A : TypeU} (H : nonempty A) (p : Bool) : (∃ x : A, p) ↔ p := iff_intro (assume Hl : (∃ x : A, p), obtain (w : A) (Hw : p), from Hl, Hw) (assume Hr : p, nonempty_elim H (λ w, exists_intro w Hr)) theorem forall_rem {A : TypeU} (H : nonempty A) (p : Bool) : (∀ x : A, p) ↔ p := iff_intro (assume Hl : (∀ x : A, p), nonempty_elim H (λ w, Hl w)) (assume Hr : p, take x, Hr) theorem eq_exists_intro {A : (Type U)} {P Q : A → Bool} (H : ∀ x : A, P x ↔ Q x) : (∃ x : A, P x) ↔ (∃ x : A, Q x) := congr2 (Exists A) (funext H) theorem not_forall (A : (Type U)) (P : A → Bool) : ¬ (∀ x : A, P x) ↔ (∃ x : A, ¬ P x) := calc (¬ ∀ x : A, P x) = ¬ ∀ x : A, ¬ ¬ P x : not_congr (allext (λ x : A, symm (not_not_eq (P x)))) ... = ∃ x : A, ¬ P x : refl (∃ x : A, ¬ P x) theorem not_forall_elim {A : (Type U)} {P : A → Bool} (H : ¬ (∀ x : A, P x)) : ∃ x : A, ¬ P x := (not_forall A P) ◂ H theorem not_exists (A : (Type U)) (P : A → Bool) : ¬ (∃ x : A, P x) ↔ (∀ x : A, ¬ P x) := calc (¬ ∃ x : A, P x) = ¬ ¬ ∀ x : A, ¬ P x : refl (¬ ∃ x : A, P x) ... = ∀ x : A, ¬ P x : not_not_eq (∀ x : A, ¬ P x) theorem not_exists_elim {A : (Type U)} {P : A → Bool} (H : ¬ ∃ x : A, P x) : ∀ x : A, ¬ P x := (not_exists A P) ◂ H theorem exists_unfold1 {A : TypeU} {P : A → Bool} (a : A) (H : ∃ x : A, P x) : P a ∨ (∃ x : A, x ≠ a ∧ P x) := exists_elim H (λ (w : A) (H1 : P w), or_elim (em (w = a)) (λ Heq : w = a, or_introl (subst H1 Heq) (∃ x : A, x ≠ a ∧ P x)) (λ Hne : w ≠ a, or_intror (P a) (exists_intro w (and_intro Hne H1)))) theorem exists_unfold2 {A : TypeU} {P : A → Bool} (a : A) (H : P a ∨ (∃ x : A, x ≠ a ∧ P x)) : ∃ x : A, P x := or_elim H (λ H1 : P a, exists_intro a H1) (λ H2 : (∃ x : A, x ≠ a ∧ P x), exists_elim H2 (λ (w : A) (Hw : w ≠ a ∧ P w), exists_intro w (and_elimr Hw))) theorem exists_unfold {A : TypeU} (P : A → Bool) (a : A) : (∃ x : A, P x) ↔ (P a ∨ (∃ x : A, x ≠ a ∧ P x)) := boolext (assume H : (∃ x : A, P x), exists_unfold1 a H) (assume H : (P a ∨ (∃ x : A, x ≠ a ∧ P x)), exists_unfold2 a H) -- Remark: ordered rewriting + assoc + comm + left_comm sorts a term lexicographically theorem left_comm {A : TypeU} {R : A -> A -> A} (comm : ∀ x y, R x y = R y x) (assoc : ∀ x y z, R (R x y) z = R x (R y z)) : ∀ x y z, R x (R y z) = R y (R x z) := take x y z, calc R x (R y z) = R (R x y) z : symm (assoc x y z) ... = R (R y x) z : { comm x y } ... = R y (R x z) : assoc y x z theorem and_left_comm (a b c : Bool) : a ∧ (b ∧ c) ↔ b ∧ (a ∧ c) := left_comm and_comm and_assoc a b c theorem or_left_comm (a b c : Bool) : a ∨ (b ∨ c) ↔ b ∨ (a ∨ c) := left_comm or_comm or_assoc a b c -- Congruence theorems for contextual simplification -- Simplify a → b, by first simplifying a to c using the fact that ¬ b is true, and then -- b to d using the fact that c is true theorem imp_congrr {a b c d : Bool} (H_ac : ∀ (H_nb : ¬ b), a = c) (H_bd : ∀ (H_c : c), b = d) : (a → b) = (c → d) := or_elim (em b) (λ H_b : b, or_elim (em c) (λ H_c : c, calc (a → b) = (a → true) : { eqt_intro H_b } ... = true : imp_truer a ... = (c → true) : symm (imp_truer c) ... = (c → b) : { symm (eqt_intro H_b) } ... = (c → d) : { H_bd H_c }) (λ H_nc : ¬ c, calc (a → b) = (a → true) : { eqt_intro H_b } ... = true : imp_truer a ... = (false → d) : symm (imp_falsel d) ... = (c → d) : { symm (eqf_intro H_nc) })) (λ H_nb : ¬ b, or_elim (em c) (λ H_c : c, calc (a → b) = (c → b) : { H_ac H_nb } ... = (c → d) : { H_bd H_c }) (λ H_nc : ¬ c, calc (a → b) = (c → b) : { H_ac H_nb } ... = (false → b) : { eqf_intro H_nc } ... = true : imp_falsel b ... = (false → d) : symm (imp_falsel d) ... = (c → d) : { symm (eqf_intro H_nc) })) -- Simplify a → b, by first simplifying b to d using the fact that a is true, and then -- b to d using the fact that ¬ d is true. -- This kind of congruence seems to be useful in very rare cases. theorem imp_congrl {a b c d : Bool} (H_bd : ∀ (H_a : a), b = d) (H_ac : ∀ (H_nd : ¬ d), a = c) : (a → b) = (c → d) := or_elim (em a) (λ H_a : a, or_elim (em d) (λ H_d : d, calc (a → b) = (a → d) : { H_bd H_a } ... = (a → true) : { eqt_intro H_d } ... = true : imp_truer a ... = (c → true) : symm (imp_truer c) ... = (c → d) : { symm (eqt_intro H_d) }) (λ H_nd : ¬ d, calc (a → b) = (c → b) : { H_ac H_nd } ... = (c → d) : { H_bd H_a })) (λ H_na : ¬ a, or_elim (em d) (λ H_d : d, calc (a → b) = (false → b) : { eqf_intro H_na } ... = true : imp_falsel b ... = (c → true) : symm (imp_truer c) ... = (c → d) : { symm (eqt_intro H_d) }) (λ H_nd : ¬ d, calc (a → b) = (false → b) : { eqf_intro H_na } ... = true : imp_falsel b ... = (false → d) : symm (imp_falsel d) ... = (a → d) : { symm (eqf_intro H_na) } ... = (c → d) : { H_ac H_nd })) -- (Common case) simplify a to c, and then b to d using the fact that c is true theorem imp_congr {a b c d : Bool} (H_ac : a = c) (H_bd : ∀ (H_c : c), b = d) : (a → b) = (c → d) := imp_congrr (λ H, H_ac) H_bd -- In the following theorems we are using the fact that a ∨ b is defined as ¬ a → b theorem or_congrr {a b c d : Bool} (H_ac : ∀ (H_nb : ¬ b), a = c) (H_bd : ∀ (H_nc : ¬ c), b = d) : a ∨ b ↔ c ∨ d := imp_congrr (λ H_nb : ¬ b, congr2 not (H_ac H_nb)) H_bd theorem or_congrl {a b c d : Bool} (H_bd : ∀ (H_na : ¬ a), b = d) (H_ac : ∀ (H_nd : ¬ d), a = c) : a ∨ b ↔ c ∨ d := imp_congrl H_bd (λ H_nd : ¬ d, congr2 not (H_ac H_nd)) -- (Common case) simplify a to c, and then b to d using the fact that ¬ c is true theorem or_congr {a b c d : Bool} (H_ac : a = c) (H_bd : ∀ (H_nc : ¬ c), b = d) : a ∨ b ↔ c ∨ d := or_congrr (λ H, H_ac) H_bd -- In the following theorems we are using the fact hat a ∧ b is defined as ¬ (a → ¬ b) theorem and_congrr {a b c d : Bool} (H_ac : ∀ (H_b : b), a = c) (H_bd : ∀ (H_c : c), b = d) : a ∧ b ↔ c ∧ d := congr2 not (imp_congrr (λ (H_nnb : ¬ ¬ b), H_ac (not_not_elim H_nnb)) (λ H_c : c, congr2 not (H_bd H_c))) theorem and_congrl {a b c d : Bool} (H_bd : ∀ (H_a : a), b = d) (H_ac : ∀ (H_d : d), a = c) : a ∧ b ↔ c ∧ d := congr2 not (imp_congrl (λ H_a : a, congr2 not (H_bd H_a)) (λ (H_nnd : ¬ ¬ d), H_ac (not_not_elim H_nnd))) -- (Common case) simplify a to c, and then b to d using the fact that c is true theorem and_congr {a b c d : Bool} (H_ac : a = c) (H_bd : ∀ (H_c : c), b = d) : a ∧ b ↔ c ∧ d := and_congrr (λ H, H_ac) H_bd theorem forall_or_distributer {A : TypeU} (p : Bool) (φ : A → Bool) : (∀ x, p ∨ φ x) = (p ∨ ∀ x, φ x) := boolext (assume H : (∀ x, p ∨ φ x), or_elim (em p) (λ Hp : p, or_introl Hp (∀ x, φ x)) (λ Hnp : ¬ p, or_intror p (take x, resolve1 (H x) Hnp))) (assume H : (p ∨ ∀ x, φ x), take x, or_elim H (λ H1 : p, or_introl H1 (φ x)) (λ H2 : (∀ x, φ x), or_intror p (H2 x))) theorem forall_or_distributel {A : Type} (p : Bool) (φ : A → Bool) : (∀ x, φ x ∨ p) = ((∀ x, φ x) ∨ p) := calc (∀ x, φ x ∨ p) = (∀ x, p ∨ φ x) : allext (λ x, or_comm (φ x) p) ... = (p ∨ ∀ x, φ x) : forall_or_distributer p φ ... = ((∀ x, φ x) ∨ p) : or_comm p (∀ x, φ x) theorem forall_and_distribute {A : TypeU} (φ ψ : A → Bool) : (∀ x, φ x ∧ ψ x) ↔ (∀ x, φ x) ∧ (∀ x, ψ x) := boolext (assume H : (∀ x, φ x ∧ ψ x), and_intro (take x, and_eliml (H x)) (take x, and_elimr (H x))) (assume H : (∀ x, φ x) ∧ (∀ x, ψ x), take x, and_intro (and_eliml H x) (and_elimr H x)) theorem exists_and_distributer {A : TypeU} (p : Bool) (φ : A → Bool) : (∃ x, p ∧ φ x) ↔ p ∧ ∃ x, φ x := boolext (assume H : (∃ x, p ∧ φ x), obtain (w : A) (Hw : p ∧ φ w), from H, and_intro (and_eliml Hw) (exists_intro w (and_elimr Hw))) (assume H : (p ∧ ∃ x, φ x), obtain (w : A) (Hw : φ w), from (and_elimr H), exists_intro w (and_intro (and_eliml H) Hw)) theorem exists_and_distributel {A : TypeU} (p : Bool) (φ : A → Bool) : (∃ x, φ x ∧ p) ↔ (∃ x, φ x) ∧ p := calc (∃ x, φ x ∧ p) = (∃ x, p ∧ φ x) : eq_exists_intro (λ x, and_comm (φ x) p) ... = (p ∧ (∃ x, φ x)) : exists_and_distributer p φ ... = ((∃ x, φ x) ∧ p) : and_comm p (∃ x, φ x) theorem exists_or_distribute {A : TypeU} (φ ψ : A → Bool) : (∃ x, φ x ∨ ψ x) ↔ (∃ x, φ x) ∨ (∃ x, ψ x) := boolext (assume H : (∃ x, φ x ∨ ψ x), obtain (w : A) (Hw : φ w ∨ ψ w), from H, or_elim Hw (λ Hw1 : φ w, or_introl (exists_intro w Hw1) (∃ x, ψ x)) (λ Hw2 : ψ w, or_intror (∃ x, φ x) (exists_intro w Hw2))) (assume H : (∃ x, φ x) ∨ (∃ x, ψ x), or_elim H (λ H1 : (∃ x, φ x), obtain (w : A) (Hw : φ w), from H1, exists_intro w (or_introl Hw (ψ w))) (λ H2 : (∃ x, ψ x), obtain (w : A) (Hw : ψ w), from H2, exists_intro w (or_intror (φ w) Hw))) theorem exists_imp_distribute {A : TypeU} (φ ψ : A → Bool) : (∃ x, φ x → ψ x) ↔ ((∀ x, φ x) → (∃ x, ψ x)) := calc (∃ x, φ x → ψ x) = (∃ x, ¬ φ x ∨ ψ x) : eq_exists_intro (λ x, imp_or (φ x) (ψ x)) ... = (∃ x, ¬ φ x) ∨ (∃ x, ψ x) : exists_or_distribute _ _ ... = ¬ (∀ x, φ x) ∨ (∃ x, ψ x) : { symm (not_forall A φ) } ... = (∀ x, φ x) → (∃ x, ψ x) : symm (imp_or _ _) set_opaque exists true set_opaque not true set_opaque or true set_opaque and true set_opaque implies true
9421e97e6dcfaf3b5a028c8af11eac28330a3bb7
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/hom/centroid.lean
42578ad72ff4a38a6ac09730a26a4894081fe609
[ "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,855
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Christopher Hoskin -/ import algebra.group_power.lemmas import algebra.hom.group_instances /-! # Centroid homomorphisms > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Let `A` be a (non unital, non associative) algebra. The centroid of `A` is the set of linear maps `T` on `A` such that `T` commutes with left and right multiplication, that is to say, for all `a` and `b` in `A`, $$ T(ab) = (Ta)b, T(ab) = a(Tb). $$ In mathlib we call elements of the centroid "centroid homomorphisms" (`centroid_hom`) in keeping with `add_monoid_hom` etc. We use the `fun_like` design, so each type of morphisms has a companion typeclass which is meant to be satisfied by itself and all stricter types. ## Types of morphisms * `centroid_hom`: Maps which preserve left and right multiplication. ## Typeclasses * `centroid_hom_class` ## References * [Jacobson, Structure of Rings][Jacobson1956] * [McCrimmon, A taste of Jordan algebras][mccrimmon2004] ## Tags centroid -/ open function variables {F α : Type*} -- Making `centroid_hom` an old structure will allow the lemma `to_add_monoid_hom_eq_coe` -- to be true by `rfl`. After upgrading to Lean 4, this should no longer be needed -- because eta for structures should provide the same result. set_option old_structure_cmd true /-- The type of centroid homomorphisms from `α` to `α`. -/ structure centroid_hom (α : Type*) [non_unital_non_assoc_semiring α] extends α →+ α := (map_mul_left' (a b : α) : to_fun (a * b) = a * to_fun b) (map_mul_right' (a b : α) : to_fun (a * b) = to_fun a * b) attribute [nolint doc_blame] centroid_hom.to_add_monoid_hom /-- `centroid_hom_class F α` states that `F` is a type of centroid homomorphisms. You should extend this class when you extend `centroid_hom`. -/ class centroid_hom_class (F : Type*) (α : out_param $ Type*) [non_unital_non_assoc_semiring α] extends add_monoid_hom_class F α α := (map_mul_left (f : F) (a b : α) : f (a * b) = a * f b) (map_mul_right (f : F) (a b : α) : f (a * b) = f a * b) export centroid_hom_class (map_mul_left map_mul_right) instance [non_unital_non_assoc_semiring α] [centroid_hom_class F α] : has_coe_t F (centroid_hom α) := ⟨λ f, { to_fun := f, map_mul_left' := map_mul_left f, map_mul_right' := map_mul_right f, ..(f : α →+ α) }⟩ /-! ### Centroid homomorphisms -/ namespace centroid_hom section non_unital_non_assoc_semiring variables [non_unital_non_assoc_semiring α] instance : centroid_hom_class (centroid_hom α) α := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by { cases f, cases g, congr' }, map_zero := λ f, f.map_zero', map_add := λ f, f.map_add', map_mul_left := λ f, f.map_mul_left', map_mul_right := λ f, f.map_mul_right' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (centroid_hom α) (λ _, α → α) := fun_like.has_coe_to_fun @[simp] lemma to_fun_eq_coe {f : centroid_hom α} : f.to_fun = (f : α → α) := rfl @[ext] lemma ext {f g : centroid_hom α} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h @[simp, norm_cast] lemma coe_to_add_monoid_hom (f : centroid_hom α) : ⇑(f : α →+ α) = f := rfl @[simp] lemma to_add_monoid_hom_eq_coe (f : centroid_hom α) : f.to_add_monoid_hom = f := rfl lemma coe_to_add_monoid_hom_injective : injective (coe : centroid_hom α → α →+ α) := λ f g h, ext $ λ a, by { have := fun_like.congr_fun h a, exact this } /-- Turn a centroid homomorphism into an additive monoid endomorphism. -/ def to_End (f : centroid_hom α) : add_monoid.End α := (f : α →+ α) lemma to_End_injective : injective (centroid_hom.to_End : centroid_hom α → add_monoid.End α) := coe_to_add_monoid_hom_injective /-- Copy of a `centroid_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : centroid_hom α) (f' : α → α) (h : f' = f) : centroid_hom α := { to_fun := f', map_mul_left' := λ a b, by simp_rw [h, map_mul_left], map_mul_right' := λ a b, by simp_rw [h, map_mul_right], ..f.to_add_monoid_hom.copy f' $ by exact h } @[simp] lemma coe_copy (f : centroid_hom α) (f' : α → α) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl lemma copy_eq (f : centroid_hom α) (f' : α → α) (h : f' = f) : f.copy f' h = f := fun_like.ext' h variables (α) /-- `id` as a `centroid_hom`. -/ protected def id : centroid_hom α := { map_mul_left' := λ _ _, rfl, map_mul_right' := λ _ _, rfl, .. add_monoid_hom.id α } instance : inhabited (centroid_hom α) := ⟨centroid_hom.id α⟩ @[simp, norm_cast] lemma coe_id : ⇑(centroid_hom.id α) = id := rfl @[simp, norm_cast] lemma coe_to_add_monoid_hom_id : (centroid_hom.id α : α →+ α) = add_monoid_hom.id α := rfl variables {α} @[simp] lemma id_apply (a : α) : centroid_hom.id α a = a := rfl /-- Composition of `centroid_hom`s as a `centroid_hom`. -/ def comp (g f : centroid_hom α) : centroid_hom α := { map_mul_left' := λ a b, (congr_arg g $ f.map_mul_left' _ _).trans $ g.map_mul_left' _ _, map_mul_right' := λ a b, (congr_arg g $ f.map_mul_right' _ _).trans $ g.map_mul_right' _ _, .. g.to_add_monoid_hom.comp f.to_add_monoid_hom } @[simp, norm_cast] lemma coe_comp (g f : centroid_hom α) : ⇑(g.comp f) = g ∘ f := rfl @[simp] lemma comp_apply (g f : centroid_hom α) (a : α) : g.comp f a = g (f a) := rfl @[simp, norm_cast] lemma coe_comp_add_monoid_hom (g f : centroid_hom α) : (g.comp f : α →+ α) = (g : α →+ α).comp f := rfl @[simp] lemma comp_assoc (h g f : centroid_hom α) : (h.comp g).comp f = h.comp (g.comp f) := rfl @[simp] lemma comp_id (f : centroid_hom α) : f.comp (centroid_hom.id α) = f := ext $ λ a, rfl @[simp] lemma id_comp (f : centroid_hom α) : (centroid_hom.id α).comp f = f := ext $ λ a, rfl lemma cancel_right {g₁ g₂ f : centroid_hom α} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g f₁ f₂ : centroid_hom α} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ext $ λ a, hg $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩ instance : has_zero (centroid_hom α) := ⟨{ map_mul_left' := λ a b, (mul_zero _).symm, map_mul_right' := λ a b, (zero_mul _).symm, ..(0 : α →+ α) }⟩ instance : has_one (centroid_hom α) := ⟨centroid_hom.id α⟩ instance : has_add (centroid_hom α) := ⟨λ f g, { map_mul_left' := λ a b, by simp [map_mul_left, mul_add], map_mul_right' := λ a b, by simp [map_mul_right, add_mul], ..(f + g : α →+ α) } ⟩ instance : has_mul (centroid_hom α) := ⟨comp⟩ instance has_nsmul : has_smul ℕ (centroid_hom α) := ⟨λ n f, { map_mul_left' := λ a b, by { change n • f (a * b) = a * n • f b, rw [map_mul_left f, ←mul_smul_comm] }, map_mul_right' := λ a b, by { change n • f (a * b) = n • f a * b, rw [map_mul_right f, ←smul_mul_assoc] }, .. (n • f : α →+ α) }⟩ instance has_npow_nat : has_pow (centroid_hom α) ℕ := ⟨λ f n, { map_mul_left' := λ a b, begin induction n with n ih, { simp }, { rw pow_succ, exact (congr_arg f.to_End ih).trans (f.map_mul_left' _ _) } end, map_mul_right' := λ a b, begin induction n with n ih, { simp }, { rw pow_succ, exact (congr_arg f.to_End ih).trans (f.map_mul_right' _ _) } end, ..(f.to_End ^ n : add_monoid.End α) }⟩ @[simp, norm_cast] lemma coe_zero : ⇑(0 : centroid_hom α) = 0 := rfl @[simp, norm_cast] lemma coe_one : ⇑(1 : centroid_hom α) = id := rfl @[simp, norm_cast] lemma coe_add (f g : centroid_hom α) : ⇑(f + g) = f + g := rfl @[simp, norm_cast] lemma coe_mul (f g : centroid_hom α) : ⇑(f * g) = f ∘ g := rfl -- Eligible for `dsimp` @[simp, norm_cast, nolint simp_nf] lemma coe_nsmul (f : centroid_hom α) (n : ℕ) : ⇑(n • f) = n • f := rfl @[simp] lemma zero_apply (a : α) : (0 : centroid_hom α) a = 0 := rfl @[simp] lemma one_apply (a : α) : (1 : centroid_hom α) a = a := rfl @[simp] lemma add_apply (f g : centroid_hom α) (a : α) : (f + g) a = f a + g a := rfl @[simp] lemma mul_apply (f g : centroid_hom α) (a : α) : (f * g) a = f (g a) := rfl -- Eligible for `dsimp` @[simp, nolint simp_nf] lemma nsmul_apply (f : centroid_hom α) (n : ℕ) (a : α) : (n • f) a = n • f a := rfl @[simp] lemma to_End_zero : (0 : centroid_hom α).to_End = 0 := rfl @[simp] lemma to_End_add (x y : centroid_hom α) : (x + y).to_End = x.to_End + y.to_End := rfl lemma to_End_nsmul (x : centroid_hom α) (n : ℕ) : (n • x).to_End = n • x.to_End := rfl -- cf.`add_monoid_hom.add_comm_monoid` instance : add_comm_monoid (centroid_hom α) := coe_to_add_monoid_hom_injective.add_comm_monoid _ to_End_zero to_End_add to_End_nsmul instance : has_nat_cast (centroid_hom α) := { nat_cast := λ n, n • 1 } @[simp, norm_cast] lemma coe_nat_cast (n : ℕ) : ⇑(n : centroid_hom α) = n • id := rfl lemma nat_cast_apply (n : ℕ) (m : α): (n : centroid_hom α) m = n • m := rfl @[simp] lemma to_End_one : (1 : centroid_hom α).to_End = 1 := rfl @[simp] lemma to_End_mul (x y : centroid_hom α) : (x * y).to_End = x.to_End * y.to_End := rfl @[simp] lemma to_End_pow (x : centroid_hom α) (n : ℕ) : (x ^ n).to_End = x.to_End ^ n := by { ext, refl } @[simp, norm_cast] lemma to_End_nat_cast (n : ℕ) : (n : centroid_hom α).to_End = ↑n := rfl -- cf `add_monoid.End.semiring` instance : semiring (centroid_hom α) := to_End_injective.semiring _ to_End_zero to_End_one to_End_add to_End_mul to_End_nsmul to_End_pow to_End_nat_cast lemma comp_mul_comm (T S : centroid_hom α) (a b : α) : (T ∘ S) (a * b) = (S ∘ T) (a * b) := by rw [comp_app, map_mul_right, map_mul_left, ←map_mul_right, ←map_mul_left] end non_unital_non_assoc_semiring section non_unital_non_assoc_ring variables [non_unital_non_assoc_ring α] /-- Negation of `centroid_hom`s as a `centroid_hom`. -/ instance : has_neg (centroid_hom α) := ⟨λ f, { map_mul_left' := by simp [map_mul_left], map_mul_right' := by simp [map_mul_right], .. (-f : α →+ α) }⟩ instance : has_sub (centroid_hom α) := ⟨λ f g, { map_mul_left' := λ a b, by simp [map_mul_left, mul_sub], map_mul_right' := λ a b, by simp [map_mul_right, sub_mul], .. (f - g : α →+ α) }⟩ instance has_zsmul : has_smul ℤ (centroid_hom α) := ⟨λ n f, { map_mul_left' := λ a b, by { change n • f (a * b) = a * n • f b, rw [map_mul_left f, ←mul_smul_comm] }, map_mul_right' := λ a b, by { change n • f (a * b) = n • f a * b, rw [map_mul_right f, ←smul_mul_assoc] }, .. (n • f : α →+ α) }⟩ instance : has_int_cast (centroid_hom α) := { int_cast := λ z, z • 1 } @[simp, norm_cast] lemma coe_int_cast (z : ℤ) : ⇑(z : centroid_hom α) = z • id := rfl lemma int_cast_apply (z : ℤ) (m : α) : (z : centroid_hom α) m = z • m := rfl @[simp] lemma to_End_neg (x : centroid_hom α) : (-x).to_End = -x.to_End := rfl @[simp] lemma to_End_sub (x y : centroid_hom α) : (x - y).to_End = x.to_End - y.to_End := rfl lemma to_End_zsmul (x : centroid_hom α) (n : ℤ) : (n • x).to_End = n • x.to_End := rfl instance : add_comm_group (centroid_hom α) := to_End_injective.add_comm_group _ to_End_zero to_End_add to_End_neg to_End_sub to_End_nsmul to_End_zsmul @[simp, norm_cast] lemma coe_neg (f : centroid_hom α) : ⇑(-f) = -f := rfl @[simp, norm_cast] lemma coe_sub (f g : centroid_hom α) : ⇑(f - g) = f - g := rfl @[simp] lemma neg_apply (f : centroid_hom α) (a : α) : (-f) a = - f a := rfl @[simp] lemma sub_apply (f g : centroid_hom α) (a : α) : (f - g) a = f a - g a := rfl @[simp, norm_cast] lemma to_End_int_cast (z : ℤ) : (z : centroid_hom α).to_End = ↑z := rfl instance : ring (centroid_hom α) := to_End_injective.ring _ to_End_zero to_End_one to_End_add to_End_mul to_End_neg to_End_sub to_End_nsmul to_End_zsmul to_End_pow to_End_nat_cast to_End_int_cast end non_unital_non_assoc_ring section non_unital_ring variables [non_unital_ring α] /-- A prime associative ring has commutative centroid. -/ @[reducible] -- See note [reducible non instances] def comm_ring (h : ∀ a b : α, (∀ r : α, a * r * b = 0) → a = 0 ∨ b = 0) : comm_ring (centroid_hom α) := { mul_comm := λ f g, begin ext, refine sub_eq_zero.1 ((or_self _).1 $ h _ _ $ λ r, _), rw [mul_assoc, sub_mul, sub_eq_zero, ← map_mul_right, ← map_mul_right, coe_mul, coe_mul, comp_mul_comm], end, ..centroid_hom.ring } end non_unital_ring end centroid_hom
a97aa497e9251efaedbd86d5452d676c1a98411a
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/measure_theory/category/Meas_auto.lean
bfdccca5b122c912f2a32d639d929f20c778346a
[]
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
3,926
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 -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.category.Top.basic import Mathlib.measure_theory.giry_monad import Mathlib.category_theory.monad.algebra import Mathlib.PostPort universes u u_1 namespace Mathlib /- * Meas, the category of measurable spaces Measurable spaces and measurable functions form a (concrete) category Meas. Measure : Meas ⥤ Meas is the functor which sends a measurable space X to the space of measures on X; it is a monad (the "Giry monad"). Borel : Top ⥤ Meas sends a topological space X to X equipped with the σ-algebra of Borel sets (the σ-algebra generated by the open subsets of X). ## Tags measurable space, giry monad, borel -/ /-- The category of measurable spaces and measurable functions. -/ def Meas := category_theory.bundled measurable_space namespace Meas protected instance measurable_space (X : Meas) : measurable_space ↥X := category_theory.bundled.str X /-- Construct a bundled `Meas` from the underlying type and the typeclass. -/ def of (α : Type u) [measurable_space α] : Meas := category_theory.bundled.mk α @[simp] theorem coe_of (X : Type u) [measurable_space X] : ↥(of X) = X := rfl protected instance unbundled_hom : category_theory.unbundled_hom measurable := category_theory.unbundled_hom.mk measurable_id measurable.comp protected instance large_category : category_theory.large_category Meas := category_theory.bundled_hom.category fun (α β : Type u_1) (Iα : measurable_space α) (Iβ : measurable_space β) => Subtype measurable protected instance inhabited : Inhabited Meas := { default := of empty } /-- `Measure X` is the measurable space of measures over the measurable space `X`. It is the weakest measurable space, s.t. λμ, μ s is measurable for all measurable sets `s` in `X`. An important purpose is to assign a monadic structure on it, the Giry monad. In the Giry monad, the pure values are the Dirac measure, and the bind operation maps to the integral: `(μ >>= ν) s = ∫ x. (ν x) s dμ`. In probability theory, the `Meas`-morphisms `X → Prob X` are (sub-)Markov kernels (here `Prob` is the restriction of `Measure` to (sub-)probability space.) -/ def Measure : Meas ⥤ Meas := category_theory.functor.mk (fun (X : Meas) => category_theory.bundled.mk (measure_theory.measure (category_theory.bundled.α X))) fun (X Y : Meas) (f : X ⟶ Y) => { val := ⇑(measure_theory.measure.map ↑f), property := sorry } /-- The Giry monad, i.e. the monadic structure associated with `Measure`. -/ protected instance Measure.category_theory.monad : category_theory.monad Measure := category_theory.monad.mk (category_theory.nat_trans.mk fun (X : Meas) => { val := measure_theory.measure.dirac, property := sorry }) (category_theory.nat_trans.mk fun (X : Meas) => { val := measure_theory.measure.join, property := sorry }) /-- An example for an algebra on `Measure`: the nonnegative Lebesgue integral is a hom, behaving nicely under the monad operations. -/ def Integral : category_theory.monad.algebra Measure := category_theory.monad.algebra.mk (of ennreal) { val := fun (m : measure_theory.measure ennreal) => measure_theory.lintegral m fun (x : ennreal) => x, property := sorry } end Meas protected instance Top.has_forget_to_Meas : category_theory.has_forget₂ Top Meas := category_theory.bundled_hom.mk_has_forget₂ borel (fun (X Y : category_theory.bundled topological_space) (f : X ⟶ Y) => { val := continuous_map.to_fun f, property := sorry }) sorry /-- The Borel functor, the canonical embedding of topological spaces into measurable spaces. -/ def Borel : Top ⥤ Meas := category_theory.forget₂ Top Meas end Mathlib
59bedaaad45b32db1c3bf24daf57dae46d6aeadb
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/ring_theory/adjoin_root.lean
0b3a2f9ac9e8735e37eb31b20b31faf4bcc40da7
[ "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
9,919
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Chris Hughes Adjoining roots of polynomials -/ import data.polynomial.field_division import linear_algebra.finite_dimensional import ring_theory.adjoin.basic import ring_theory.power_basis import ring_theory.principal_ideal_domain /-! # Adjoining roots of polynomials This file defines the commutative ring `adjoin_root f`, the ring R[X]/(f) obtained from a commutative ring `R` and a polynomial `f : R[X]`. If furthermore `R` is a field and `f` is irreducible, the field structure on `adjoin_root f` is constructed. ## Main definitions and results The main definitions are in the `adjoin_root` namespace. * `mk f : polynomial R →+* adjoin_root f`, the natural ring homomorphism. * `of f : R →+* adjoin_root f`, the natural ring homomorphism. * `root f : adjoin_root f`, the image of X in R[X]/(f). * `lift (i : R →+* S) (x : S) (h : f.eval₂ i x = 0) : (adjoin_root f) →+* S`, the ring homomorphism from R[X]/(f) to S extending `i : R →+* S` and sending `X` to `x`. * `lift_hom (x : S) (hfx : aeval x f = 0) : adjoin_root f →ₐ[R] S`, the algebra homomorphism from R[X]/(f) to S extending `algebra_map R S` and sending `X` to `x` * `equiv : (adjoin_root f →ₐ[F] E) ≃ {x // x ∈ (f.map (algebra_map F E)).roots}` a bijection between algebra homomorphisms from `adjoin_root` and roots of `f` in `S` -/ noncomputable theory open_locale classical open_locale big_operators universes u v w variables {R : Type u} {S : Type v} {K : Type w} open polynomial ideal /-- Adjoin a root of a polynomial `f` to a commutative ring `R`. We define the new ring as the quotient of `R` by the principal ideal of `f`. -/ def adjoin_root [comm_ring R] (f : polynomial R) : Type u := ideal.quotient (span {f} : ideal (polynomial R)) namespace adjoin_root section comm_ring variables [comm_ring R] (f : polynomial R) instance : comm_ring (adjoin_root f) := ideal.quotient.comm_ring _ instance : inhabited (adjoin_root f) := ⟨0⟩ instance : decidable_eq (adjoin_root f) := classical.dec_eq _ /-- Ring homomorphism from `R[x]` to `adjoin_root f` sending `X` to the `root`. -/ def mk : polynomial R →+* adjoin_root f := ideal.quotient.mk _ @[elab_as_eliminator] theorem induction_on {C : adjoin_root f → Prop} (x : adjoin_root f) (ih : ∀ p : polynomial R, C (mk f p)) : C x := quotient.induction_on' x ih /-- Embedding of the original ring `R` into `adjoin_root f`. -/ def of : R →+* adjoin_root f := (mk f).comp (ring_hom.of C) instance : algebra R (adjoin_root f) := (of f).to_algebra @[simp] lemma algebra_map_eq : algebra_map R (adjoin_root f) = of f := rfl /-- The adjoined root. -/ def root : adjoin_root f := mk f X variables {f} instance adjoin_root.has_coe_t : has_coe_t R (adjoin_root f) := ⟨of f⟩ @[simp] lemma mk_self : mk f f = 0 := quotient.sound' (mem_span_singleton.2 $ by simp) @[simp] lemma mk_C (x : R) : mk f (C x) = x := rfl @[simp] lemma mk_X : mk f X = root f := rfl @[simp] lemma aeval_eq (p : polynomial R) : aeval (root f) p = mk f p := polynomial.induction_on p (λ x, by { rw aeval_C, refl }) (λ p q ihp ihq, by rw [alg_hom.map_add, ring_hom.map_add, ihp, ihq]) (λ n x ih, by { rw [alg_hom.map_mul, aeval_C, alg_hom.map_pow, aeval_X, ring_hom.map_mul, mk_C, ring_hom.map_pow, mk_X], refl }) theorem adjoin_root_eq_top : algebra.adjoin R ({root f} : set (adjoin_root f)) = ⊤ := algebra.eq_top_iff.2 $ λ x, induction_on f x $ λ p, (algebra.adjoin_singleton_eq_range R (root f)).symm ▸ ⟨p, aeval_eq p⟩ @[simp] lemma eval₂_root (f : polynomial R) : f.eval₂ (of f) (root f) = 0 := by rw [← algebra_map_eq, ← aeval_def, aeval_eq, mk_self] lemma is_root_root (f : polynomial R) : is_root (f.map (of f)) (root f) := by rw [is_root, eval_map, eval₂_root] variables [comm_ring S] /-- Lift a ring homomorphism `i : R →+* S` to `adjoin_root f →+* S`. -/ def lift (i : R →+* S) (x : S) (h : f.eval₂ i x = 0) : (adjoin_root f) →+* S := begin apply ideal.quotient.lift _ (eval₂_ring_hom i x), intros g H, rcases mem_span_singleton.1 H with ⟨y, hy⟩, rw [hy, ring_hom.map_mul, coe_eval₂_ring_hom, h, zero_mul] end variables {i : R →+* S} {a : S} {h : f.eval₂ i a = 0} @[simp] lemma lift_mk {g : polynomial R} : lift i a h (mk f g) = g.eval₂ i a := ideal.quotient.lift_mk _ _ _ @[simp] lemma lift_root : lift i a h (root f) = a := by rw [root, lift_mk, eval₂_X] @[simp] lemma lift_of {x : R} : lift i a h x = i x := by rw [← mk_C x, lift_mk, eval₂_C] @[simp] lemma lift_comp_of : (lift i a h).comp (of f) = i := ring_hom.ext $ λ _, @lift_of _ _ _ _ _ _ _ h _ variables (f) [algebra R S] /-- Produce an algebra homomorphism `adjoin_root f →ₐ[R] S` sending `root f` to a root of `f` in `S`. -/ def lift_hom (x : S) (hfx : aeval x f = 0) : adjoin_root f →ₐ[R] S := { commutes' := λ r, show lift _ _ hfx r = _, from lift_of, .. lift (algebra_map R S) x hfx } @[simp] lemma coe_lift_hom (x : S) (hfx : aeval x f = 0) : (lift_hom f x hfx : adjoin_root f →+* S) = lift (algebra_map R S) x hfx := rfl @[simp] lemma aeval_alg_hom_eq_zero (ϕ : adjoin_root f →ₐ[R] S) : aeval (ϕ (root f)) f = 0 := begin have h : ϕ.to_ring_hom.comp (of f) = algebra_map R S := ring_hom.ext_iff.mpr (ϕ.commutes), rw [aeval_def, ←h, ←ring_hom.map_zero ϕ.to_ring_hom, ←eval₂_root f, hom_eval₂], refl, end @[simp] lemma lift_hom_eq_alg_hom (f : polynomial R) (ϕ : adjoin_root f →ₐ[R] S) : lift_hom f (ϕ (root f)) (aeval_alg_hom_eq_zero f ϕ) = ϕ := begin suffices : ϕ.equalizer (lift_hom f (ϕ (root f)) (aeval_alg_hom_eq_zero f ϕ)) = ⊤, { exact (alg_hom.ext (λ x, (set_like.ext_iff.mp (this) x).mpr algebra.mem_top)).symm }, rw [eq_top_iff, ←adjoin_root_eq_top, algebra.adjoin_le_iff, set.singleton_subset_iff], exact (@lift_root _ _ _ _ _ _ _ (aeval_alg_hom_eq_zero f ϕ)).symm, end /-- If `E` is a field extension of `F` and `f` is a polynomial over `F` then the set of maps from `F[x]/(f)` into `E` is in bijection with the set of roots of `f` in `E`. -/ def equiv (F E : Type*) [field F] [field E] [algebra F E] (f : polynomial F) (hf : f ≠ 0) : (adjoin_root f →ₐ[F] E) ≃ {x // x ∈ (f.map (algebra_map F E)).roots} := { to_fun := λ ϕ, ⟨ϕ (root f), begin rw [mem_roots (map_ne_zero hf), is_root.def, ←eval₂_eq_eval_map], exact aeval_alg_hom_eq_zero f ϕ, exact field.to_nontrivial E, end⟩, inv_fun := λ x, lift_hom f ↑x (begin rw [aeval_def, eval₂_eq_eval_map, ←is_root.def, ←mem_roots (map_ne_zero hf)], exact subtype.mem x, exact field.to_nontrivial E end), left_inv := λ ϕ, lift_hom_eq_alg_hom f ϕ, right_inv := λ x, begin ext, refine @lift_root F E _ f _ _ ↑x _, rw [eval₂_eq_eval_map, ←is_root.def, ←mem_roots (map_ne_zero hf), ←multiset.mem_to_finset], exact multiset.mem_to_finset.mpr (subtype.mem x), exact field.to_nontrivial E end } end comm_ring section irreducible variables [field K] {f : polynomial K} [irreducible f] instance is_maximal_span : is_maximal (span {f} : ideal (polynomial K)) := principal_ideal_ring.is_maximal_of_irreducible ‹irreducible f› noncomputable instance field : field (adjoin_root f) := { ..adjoin_root.comm_ring f, ..ideal.quotient.field (span {f} : ideal (polynomial K)) } lemma coe_injective : function.injective (coe : K → adjoin_root f) := (of f).injective variable (f) lemma mul_div_root_cancel : ((X - C (root f)) * (f.map (of f) / (X - C (root f))) : polynomial (adjoin_root f)) = f.map (of f) := mul_div_eq_iff_is_root.2 $ is_root_root _ end irreducible section power_basis variables [field K] {f : polynomial K} /-- The elements `1, root f, ..., root f ^ (d - 1)` form a basis for `adjoin_root f`, where `f` is an irreducible polynomial over a field of degree `d`. -/ def power_basis_aux (hf : f ≠ 0) : basis (fin f.nat_degree) K (adjoin_root f) := begin set f' := f * C (f.leading_coeff⁻¹) with f'_def, have deg_f' : f'.nat_degree = f.nat_degree, { rw [nat_degree_mul hf, nat_degree_C, add_zero], { rwa [ne.def, C_eq_zero, inv_eq_zero, leading_coeff_eq_zero] } }, have f'_monic : monic f' := monic_mul_leading_coeff_inv hf, have aeval_f' : aeval (root f) f' = 0, { rw [f'_def, alg_hom.map_mul, aeval_eq, mk_self, zero_mul] }, have hx : is_integral K (root f) := ⟨f', f'_monic, aeval_f'⟩, have minpoly_eq : f' = minpoly K (root f), { apply minpoly.unique K _ f'_monic aeval_f', intros q q_monic q_aeval, have commutes : (lift (algebra_map K (adjoin_root f)) (root f) q_aeval).comp (mk q) = mk f, { ext, { simp only [ring_hom.comp_apply, mk_C, lift_of], refl }, { simp only [ring_hom.comp_apply, mk_X, lift_root] } }, rw [degree_eq_nat_degree f'_monic.ne_zero, degree_eq_nat_degree q_monic.ne_zero, with_bot.coe_le_coe, deg_f'], apply nat_degree_le_of_dvd, { have : mk f q = 0, by rw [←commutes, ring_hom.comp_apply, mk_self, ring_hom.map_zero], rwa [←ideal.mem_span_singleton, ←ideal.quotient.eq_zero_iff_mem] }, { exact q_monic.ne_zero } }, apply @basis.mk _ _ _ (λ (i : fin f.nat_degree), (root f ^ i.val)), { rw [←deg_f', minpoly_eq], exact hx.linear_independent_pow }, { rw _root_.eq_top_iff, rintros y -, rw [←deg_f', minpoly_eq], apply hx.mem_span_pow, obtain ⟨g⟩ := y, use g, rw aeval_eq, refl } end /-- The power basis `1, root f, ..., root f ^ (d - 1)` for `adjoin_root f`, where `f` is an irreducible polynomial over a field of degree `d`. -/ @[simps] def power_basis (hf : f ≠ 0) : power_basis K (adjoin_root f) := { gen := root f, dim := f.nat_degree, basis := power_basis_aux hf, basis_eq_pow := basis.mk_apply _ _ } end power_basis end adjoin_root
29d53b9042e86663c18195242c48634249e97756
74924b1fe80b8f61262cefcfc0cd4d96135c8731
/src/analysis/specific_limits.lean
a087f576f066d2038bd0b6a94bfa59d77db3e766
[ "Apache-2.0" ]
permissive
101damnations/mathlib
0938b3806a09032d8716d3642cbab65db7688c23
900c53ae6d5e3f8cc47953363479593e8debc4d8
refs/heads/master
1,593,832,305,164
1,565,631,735,000
1,565,631,735,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,778
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 A collection of specific limit computations. -/ import analysis.normed_space.basic import topology.instances.ennreal noncomputable theory local attribute [instance] classical.prop_decidable open classical function lattice filter finset metric variables {α : Type*} {β : Type*} {ι : Type*} lemma summable_of_absolute_convergence_real {f : ℕ → ℝ} : (∃r, tendsto (λn, (range n).sum (λi, abs (f i))) at_top (nhds r)) → summable f | ⟨r, hr⟩ := begin refine summable_of_summable_norm ⟨r, (has_sum_iff_tendsto_nat_of_nonneg _ _).2 _⟩, exact assume i, norm_nonneg _, simpa only using hr end lemma tendsto_pow_at_top_at_top_of_gt_1 {r : ℝ} (h : r > 1) : tendsto (λn:ℕ, r ^ n) at_top at_top := tendsto_infi.2 $ assume p, tendsto_principal.2 $ let ⟨n, hn⟩ := exists_nat_gt (p / (r - 1)) in have hn_nn : (0:ℝ) ≤ n, from nat.cast_nonneg n, have r - 1 > 0, from sub_lt_iff_lt_add.mp $ by simp; assumption, have p ≤ r ^ n, from calc p = (p / (r - 1)) * (r - 1) : (div_mul_cancel _ $ ne_of_gt this).symm ... ≤ n * (r - 1) : mul_le_mul (le_of_lt hn) (le_refl _) (le_of_lt this) hn_nn ... ≤ 1 + n * (r - 1) : le_add_of_nonneg_of_le zero_le_one (le_refl _) ... = 1 + add_monoid.smul n (r - 1) : by rw [add_monoid.smul_eq_mul] ... ≤ (1 + (r - 1)) ^ n : pow_ge_one_add_mul (le_of_lt this) _ ... ≤ r ^ n : by simp; exact le_refl _, show {n | p ≤ r ^ n} ∈ at_top, from mem_at_top_sets.mpr ⟨n, assume m hnm, le_trans this (pow_le_pow (le_of_lt h) hnm)⟩ lemma tendsto_inverse_at_top_nhds_0 : tendsto (λr:ℝ, r⁻¹) at_top (nhds 0) := tendsto_orderable_unbounded (no_top 0) (no_bot 0) $ assume l u hl hu, mem_at_top_sets.mpr ⟨u⁻¹ + 1, assume b hb, have u⁻¹ < b, from lt_of_lt_of_le (lt_add_of_pos_right _ zero_lt_one) hb, ⟨lt_trans hl $ inv_pos $ lt_trans (inv_pos hu) this, lt_of_one_div_lt_one_div hu $ begin rw [inv_eq_one_div], simp [-one_div_eq_inv, div_div_eq_mul_div, div_one], simp [this] end⟩⟩ lemma tendsto_pow_at_top_nhds_0_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : tendsto (λn:ℕ, r^n) at_top (nhds 0) := by_cases (assume : r = 0, (tendsto_add_at_top_iff_nat 1).mp $ by simp [pow_succ, this, tendsto_const_nhds]) (assume : r ≠ 0, have tendsto (λn, (r⁻¹ ^ n)⁻¹) at_top (nhds 0), from tendsto.comp tendsto_inverse_at_top_nhds_0 (tendsto_pow_at_top_at_top_of_gt_1 $ one_lt_inv (lt_of_le_of_ne h₁ this.symm) h₂), tendsto.congr' (univ_mem_sets' $ by simp *) this) lemma tendsto_pow_at_top_nhds_0_of_lt_1_normed_field {K : Type*} [normed_field K] {ξ : K} (_ : ∥ξ∥ < 1) : tendsto (λ n : ℕ, ξ^n) at_top (nhds 0) := begin rw[tendsto_iff_norm_tendsto_zero], convert tendsto_pow_at_top_nhds_0_of_lt_1 (norm_nonneg ξ) ‹∥ξ∥ < 1›, ext n, simp end lemma tendsto_pow_at_top_at_top_of_gt_1_nat {k : ℕ} (h : 1 < k) : tendsto (λn:ℕ, k ^ n) at_top at_top := tendsto_coe_nat_real_at_top_iff.1 $ have hr : 1 < (k : ℝ), by rw [← nat.cast_one, nat.cast_lt]; exact h, by simpa using tendsto_pow_at_top_at_top_of_gt_1 hr lemma tendsto_inverse_at_top_nhds_0_nat : tendsto (λ n : ℕ, (n : ℝ)⁻¹) at_top (nhds 0) := tendsto.comp tendsto_inverse_at_top_nhds_0 (tendsto_coe_nat_real_at_top_iff.2 tendsto_id) lemma tendsto_one_div_at_top_nhds_0_nat : tendsto (λ n : ℕ, 1/(n : ℝ)) at_top (nhds 0) := by simpa only [inv_eq_one_div] using tendsto_inverse_at_top_nhds_0_nat lemma tendsto_one_div_add_at_top_nhds_0_nat : tendsto (λ n : ℕ, 1 / ((n : ℝ) + 1)) at_top (nhds 0) := suffices tendsto (λ n : ℕ, 1 / (↑(n + 1) : ℝ)) at_top (nhds 0), by simpa, (tendsto_add_at_top_iff_nat 1).2 tendsto_one_div_at_top_nhds_0_nat lemma has_sum_geometric {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : has_sum (λn:ℕ, r ^ n) (1 / (1 - r)) := have r ≠ 1, from ne_of_lt h₂, have r + -1 ≠ 0, by rw [←sub_eq_add_neg, ne, sub_eq_iff_eq_add]; simp; assumption, have tendsto (λn, (r ^ n - 1) * (r - 1)⁻¹) at_top (nhds ((0 - 1) * (r - 1)⁻¹)), from tendsto_mul (tendsto_sub (tendsto_pow_at_top_nhds_0_of_lt_1 h₁ h₂) tendsto_const_nhds) tendsto_const_nhds, (has_sum_iff_tendsto_nat_of_nonneg (pow_nonneg h₁) _).mpr $ by simp [neg_inv, geom_sum, div_eq_mul_inv, *] at * lemma summable_geometric {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : summable (λn:ℕ, r ^ n) := ⟨_, has_sum_geometric h₁ h₂⟩ lemma tsum_geometric {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : (∑n:ℕ, r ^ n) = 1 / (1 - r) := tsum_eq_has_sum (has_sum_geometric h₁ h₂) lemma has_sum_geometric_two : has_sum (λn:ℕ, ((1:ℝ)/2) ^ n) 2 := by convert has_sum_geometric _ _; norm_num lemma summable_geometric_two : summable (λn:ℕ, ((1:ℝ)/2) ^ n) := ⟨_, has_sum_geometric_two⟩ lemma tsum_geometric_two : (∑n:ℕ, ((1:ℝ)/2) ^ n) = 2 := tsum_eq_has_sum has_sum_geometric_two lemma has_sum_geometric_two' (a : ℝ) : has_sum (λn:ℕ, (a / 2) / 2 ^ n) a := begin convert has_sum_mul_left (a / 2) (has_sum_geometric (le_of_lt one_half_pos) one_half_lt_one), { funext n, simp, rw ← pow_inv; [refl, exact two_ne_zero] }, { norm_num, rw div_mul_cancel _ two_ne_zero } end def pos_sum_of_encodable {ε : ℝ} (hε : 0 < ε) (ι) [encodable ι] : {ε' : ι → ℝ // (∀ i, 0 < ε' i) ∧ ∃ c, has_sum ε' c ∧ c ≤ ε} := begin let f := λ n, (ε / 2) / 2 ^ n, have hf : has_sum f ε := has_sum_geometric_two' _, have f0 : ∀ n, 0 < f n := λ n, div_pos (half_pos hε) (pow_pos two_pos _), refine ⟨f ∘ encodable.encode, λ i, f0 _, _⟩, rcases summable_comp_of_summable_of_injective f (summable_spec hf) (@encodable.encode_injective ι _) with ⟨c, hg⟩, refine ⟨c, hg, has_sum_le_inj _ (@encodable.encode_injective ι _) _ _ hg hf⟩, { assume i _, exact le_of_lt (f0 _) }, { assume n, exact le_refl _ } end lemma cauchy_seq_of_le_geometric [metric_space α] (r C : ℝ) (hr : r < 1) {f : ℕ → α} (hu : ∀n, dist (f n) (f (n+1)) ≤ C * r^n) : cauchy_seq f := begin refine cauchy_seq_of_summable_dist (summable_of_norm_bounded (λn, C * r^n) _ _), { by_cases h : C = 0, { simp [h, summable_zero] }, { have Cpos : C > 0, { have := le_trans dist_nonneg (hu 0), simp only [mul_one, pow_zero] at this, exact lt_of_le_of_ne this (ne.symm h) }, have rnonneg: r ≥ 0, { have := le_trans dist_nonneg (hu 1), simp only [pow_one] at this, exact nonneg_of_mul_nonneg_left this Cpos }, refine summable_mul_left C _, exact summable_spec (@has_sum_geometric r rnonneg hr) }}, show ∀n, abs (dist (f n) (f (n+1))) ≤ C * r^n, { assume n, rw abs_of_nonneg (dist_nonneg), exact hu n } end namespace real lemma continuous_sqrt : continuous sqrt := begin rw continuous_iff_continuous_at, assume x, rw [continuous_at, metric.tendsto_nhds], assume ε hε, refine ⟨set.Ioo (x - ε * ε) (x + ε * ε), _, _⟩, { rw Ioo_eq_ball, convert ball_mem_nhds _ _, { finish }, { have : (x + ε * ε - (x - ε * ε)) / 2 = ε * ε, ring, rw this, exact mul_self_pos (ne_of_gt hε) } }, { assume y hy, have : abs (x - y) < ε * ε, rw abs_lt, rw set.mem_Ioo at hy, split, linarith [hy.2], linarith [hy.1], show abs (sqrt y - sqrt x) < ε, refine lt_of_le_of_lt (abs_sqrt_sub_sqrt_le_sqrt_abs _ _) _, rw mul_self_lt_mul_self_iff, rw mul_self_sqrt (abs_nonneg _), rwa abs_sub, exact sqrt_nonneg _, exact le_of_lt hε } end end real namespace nnreal theorem exists_pos_sum_of_encodable {ε : nnreal} (hε : 0 < ε) (ι) [encodable ι] : ∃ ε' : ι → nnreal, (∀ i, 0 < ε' i) ∧ ∃c, has_sum ε' c ∧ c < ε := let ⟨a, a0, aε⟩ := dense hε in let ⟨ε', hε', c, hc, hcε⟩ := pos_sum_of_encodable a0 ι in ⟨ λi, ⟨ε' i, le_of_lt $ hε' i⟩, assume i, nnreal.coe_lt.2 $ hε' i, ⟨c, has_sum_le (assume i, le_of_lt $ hε' i) has_sum_zero hc ⟩, nnreal.has_sum_coe.1 hc, lt_of_le_of_lt (nnreal.coe_le.1 hcε) aε ⟩ end nnreal namespace ennreal theorem exists_pos_sum_of_encodable {ε : ennreal} (hε : 0 < ε) (ι) [encodable ι] : ∃ ε' : ι → nnreal, (∀ i, 0 < ε' i) ∧ (∑ i, (ε' i : ennreal)) < ε := begin rcases dense hε with ⟨r, h0r, hrε⟩, rcases lt_iff_exists_coe.1 hrε with ⟨x, rfl, hx⟩, rcases nnreal.exists_pos_sum_of_encodable (coe_lt_coe.1 h0r) ι with ⟨ε', hp, c, hc, hcr⟩, exact ⟨ε', hp, (ennreal.tsum_coe_eq hc).symm ▸ lt_trans (coe_lt_coe.2 hcr) hrε⟩ end end ennreal
75ee31c58b8c0865bd10aa2d197e1c717c2bfd96
b7f22e51856f4989b970961f794f1c435f9b8f78
/hott/homotopy/circle.hlean
e1f3d37b1e08b3b2f2bbb56bbe20bac5bcca5bec
[ "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
12,894
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Declaration of the circle -/ import .sphere import types.int.hott import algebra.homotopy_group .connectedness open eq susp bool sphere_index is_equiv equiv is_trunc is_conn pi algebra pointed definition circle : Type₀ := sphere 1 namespace circle notation `S¹` := circle definition base1 : S¹ := !north definition base2 : S¹ := !south definition seg1 : base1 = base2 := merid !north definition seg2 : base1 = base2 := merid !south definition base : S¹ := base1 definition loop : base = base := seg2 ⬝ seg1⁻¹ definition rec2 {P : S¹ → Type} (Pb1 : P base1) (Pb2 : P base2) (Ps1 : Pb1 =[seg1] Pb2) (Ps2 : Pb1 =[seg2] Pb2) (x : S¹) : P x := begin induction x with b, { exact Pb1}, { exact Pb2}, { esimp at *, induction b with y, { exact Ps1}, { exact Ps2}, { cases y}}, end definition rec2_on [reducible] {P : S¹ → Type} (x : S¹) (Pb1 : P base1) (Pb2 : P base2) (Ps1 : Pb1 =[seg1] Pb2) (Ps2 : Pb1 =[seg2] Pb2) : P x := circle.rec2 Pb1 Pb2 Ps1 Ps2 x theorem rec2_seg1 {P : S¹ → Type} (Pb1 : P base1) (Pb2 : P base2) (Ps1 : Pb1 =[seg1] Pb2) (Ps2 : Pb1 =[seg2] Pb2) : apd (rec2 Pb1 Pb2 Ps1 Ps2) seg1 = Ps1 := !rec_merid theorem rec2_seg2 {P : S¹ → Type} (Pb1 : P base1) (Pb2 : P base2) (Ps1 : Pb1 =[seg1] Pb2) (Ps2 : Pb1 =[seg2] Pb2) : apd (rec2 Pb1 Pb2 Ps1 Ps2) seg2 = Ps2 := !rec_merid definition elim2 {P : Type} (Pb1 Pb2 : P) (Ps1 Ps2 : Pb1 = Pb2) (x : S¹) : P := rec2 Pb1 Pb2 (pathover_of_eq _ Ps1) (pathover_of_eq _ Ps2) x definition elim2_on [reducible] {P : Type} (x : S¹) (Pb1 Pb2 : P) (Ps1 : Pb1 = Pb2) (Ps2 : Pb1 = Pb2) : P := elim2 Pb1 Pb2 Ps1 Ps2 x theorem elim2_seg1 {P : Type} (Pb1 Pb2 : P) (Ps1 : Pb1 = Pb2) (Ps2 : Pb1 = Pb2) : ap (elim2 Pb1 Pb2 Ps1 Ps2) seg1 = Ps1 := begin apply eq_of_fn_eq_fn_inv !(pathover_constant seg1), rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑elim2,rec2_seg1], end theorem elim2_seg2 {P : Type} (Pb1 Pb2 : P) (Ps1 : Pb1 = Pb2) (Ps2 : Pb1 = Pb2) : ap (elim2 Pb1 Pb2 Ps1 Ps2) seg2 = Ps2 := begin apply eq_of_fn_eq_fn_inv !(pathover_constant seg2), rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑elim2,rec2_seg2], end definition elim2_type (Pb1 Pb2 : Type) (Ps1 Ps2 : Pb1 ≃ Pb2) (x : S¹) : Type := elim2 Pb1 Pb2 (ua Ps1) (ua Ps2) x definition elim2_type_on [reducible] (x : S¹) (Pb1 Pb2 : Type) (Ps1 Ps2 : Pb1 ≃ Pb2) : Type := elim2_type Pb1 Pb2 Ps1 Ps2 x theorem elim2_type_seg1 (Pb1 Pb2 : Type) (Ps1 Ps2 : Pb1 ≃ Pb2) : transport (elim2_type Pb1 Pb2 Ps1 Ps2) seg1 = Ps1 := by rewrite [tr_eq_cast_ap_fn,↑elim2_type,elim2_seg1];apply cast_ua_fn theorem elim2_type_seg2 (Pb1 Pb2 : Type) (Ps1 Ps2 : Pb1 ≃ Pb2) : transport (elim2_type Pb1 Pb2 Ps1 Ps2) seg2 = Ps2 := by rewrite [tr_eq_cast_ap_fn,↑elim2_type,elim2_seg2];apply cast_ua_fn protected definition rec {P : S¹ → Type} (Pbase : P base) (Ploop : Pbase =[loop] Pbase) (x : S¹) : P x := begin fapply (rec2_on x), { exact Pbase}, { exact (transport P seg1 Pbase)}, { apply pathover_tr}, { apply pathover_tr_of_pathover, exact Ploop} end protected definition rec_on [reducible] {P : S¹ → Type} (x : S¹) (Pbase : P base) (Ploop : Pbase =[loop] Pbase) : P x := circle.rec Pbase Ploop x theorem rec_loop_helper {A : Type} (P : A → Type) {x y z : A} {p : x = y} {p' : z = y} {u : P x} {v : P z} (q : u =[p ⬝ p'⁻¹] v) : pathover_tr_of_pathover q ⬝o !pathover_tr⁻¹ᵒ = q := by cases p'; cases q; exact idp definition con_refl {A : Type} {x y : A} (p : x = y) : p ⬝ refl _ = p := eq.rec_on p idp theorem rec_loop {P : S¹ → Type} (Pbase : P base) (Ploop : Pbase =[loop] Pbase) : apd (circle.rec Pbase Ploop) loop = Ploop := begin rewrite [↑loop,apd_con,↑circle.rec,↑circle.rec2_on,↑base,rec2_seg2,apd_inv,rec2_seg1], apply rec_loop_helper end protected definition elim {P : Type} (Pbase : P) (Ploop : Pbase = Pbase) (x : S¹) : P := circle.rec Pbase (pathover_of_eq _ Ploop) x protected definition elim_on [reducible] {P : Type} (x : S¹) (Pbase : P) (Ploop : Pbase = Pbase) : P := circle.elim Pbase Ploop x theorem elim_loop {P : Type} (Pbase : P) (Ploop : Pbase = Pbase) : ap (circle.elim Pbase Ploop) loop = Ploop := begin apply eq_of_fn_eq_fn_inv !(pathover_constant loop), rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑circle.elim,rec_loop], end theorem elim_seg1 {P : Type} (Pbase : P) (Ploop : Pbase = Pbase) : ap (circle.elim Pbase Ploop) seg1 = (tr_constant seg1 Pbase)⁻¹ := begin apply eq_of_fn_eq_fn_inv !(pathover_constant seg1), rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑circle.elim,↑circle.rec], rewrite [↑circle.rec2_on,rec2_seg1], apply inverse, apply pathover_of_eq_tr_constant_inv end theorem elim_seg2 {P : Type} (Pbase : P) (Ploop : Pbase = Pbase) : ap (circle.elim Pbase Ploop) seg2 = Ploop ⬝ (tr_constant seg1 Pbase)⁻¹ := begin apply eq_of_fn_eq_fn_inv !(pathover_constant seg2), rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑circle.elim,↑circle.rec], rewrite [↑circle.rec2_on,rec2_seg2], assert l : Π(A B : Type)(a a₂ a₂' : A)(b b' : B)(p : a = a₂)(p' : a₂' = a₂) (q : b = b'), pathover_tr_of_pathover (pathover_of_eq _ q) = pathover_of_eq _ (q ⬝ (tr_constant p' b')⁻¹) :> b =[p] p' ▸ b', { intros, cases q, cases p', cases p, reflexivity }, apply l end protected definition elim_type (Pbase : Type) (Ploop : Pbase ≃ Pbase) (x : S¹) : Type := circle.elim Pbase (ua Ploop) x protected definition elim_type_on [reducible] (x : S¹) (Pbase : Type) (Ploop : Pbase ≃ Pbase) : Type := circle.elim_type Pbase Ploop x theorem elim_type_loop (Pbase : Type) (Ploop : Pbase ≃ Pbase) : transport (circle.elim_type Pbase Ploop) loop = Ploop := by rewrite [tr_eq_cast_ap_fn,↑circle.elim_type,elim_loop];apply cast_ua_fn theorem elim_type_loop_inv (Pbase : Type) (Ploop : Pbase ≃ Pbase) : transport (circle.elim_type Pbase Ploop) loop⁻¹ = to_inv Ploop := by rewrite [tr_inv_fn]; apply inv_eq_inv; apply elim_type_loop end circle attribute circle.base1 circle.base2 circle.base [constructor] attribute circle.rec2 circle.elim2 [unfold 6] [recursor 6] attribute circle.elim2_type [unfold 5] attribute circle.rec2_on circle.elim2_on [unfold 2] attribute circle.elim2_type [unfold 1] attribute circle.rec circle.elim [unfold 4] [recursor 4] attribute circle.elim_type [unfold 3] attribute circle.rec_on circle.elim_on [unfold 2] attribute circle.elim_type_on [unfold 1] namespace circle open sigma /- universal property of the circle -/ definition circle_pi_equiv [constructor] (P : S¹ → Type) : (Π(x : S¹), P x) ≃ Σ(p : P base), p =[loop] p := begin fapply equiv.MK, { intro f, exact ⟨f base, apd f loop⟩}, { intro v x, induction v with p q, induction x, { exact p}, { exact q}}, { intro v, induction v with p q, fapply sigma_eq, { reflexivity}, { esimp, apply pathover_idp_of_eq, apply rec_loop}}, { intro f, apply eq_of_homotopy, intro x, induction x, { reflexivity}, { apply eq_pathover_dep, apply hdeg_squareover, esimp, apply rec_loop}} end definition circle_arrow_equiv [constructor] (P : Type) : (S¹ → P) ≃ Σ(p : P), p = p := begin fapply equiv.MK, { intro f, exact ⟨f base, ap f loop⟩}, { intro v x, induction v with p q, induction x, { exact p}, { exact q}}, { intro v, induction v with p q, fapply sigma_eq, { reflexivity}, { esimp, apply pathover_idp_of_eq, apply elim_loop}}, { intro f, apply eq_of_homotopy, intro x, induction x, { reflexivity}, { apply eq_pathover, apply hdeg_square, esimp, apply elim_loop}} end definition pointed_circle [instance] [constructor] : pointed S¹ := pointed.mk base definition pcircle [constructor] : Type* := pointed.mk' S¹ notation `S¹*` := pcircle definition loop_neq_idp : loop ≠ idp := assume H : loop = idp, have H2 : Π{A : Type₁} {a : A} {p : a = a}, p = idp, from λA a p, calc p = ap (circle.elim a p) loop : elim_loop ... = ap (circle.elim a p) (refl base) : by rewrite H, eq_bnot_ne_idp H2 definition circle_turn [reducible] (x : S¹) : x = x := begin induction x, { exact loop }, { apply eq_pathover, apply square_of_eq, rewrite ap_id } end definition turn_neq_idp : circle_turn ≠ (λx, idp) := assume H : circle_turn = λx, idp, have H2 : loop = idp, from apd10 H base, absurd H2 loop_neq_idp open int protected definition code [unfold 1] (x : S¹) : Type₀ := circle.elim_type_on x ℤ equiv_succ definition transport_code_loop (a : ℤ) : transport circle.code loop a = succ a := ap10 !elim_type_loop a definition transport_code_loop_inv (a : ℤ) : transport circle.code loop⁻¹ a = pred a := ap10 !elim_type_loop_inv a protected definition encode [unfold 2] {x : S¹} (p : base = x) : circle.code x := transport circle.code p (0 : ℤ) protected definition decode [unfold 1] {x : S¹} : circle.code x → base = x := begin induction x, { exact power loop}, { apply arrow_pathover_left, intro b, apply eq_pathover_constant_left_id_right, apply square_of_eq, rewrite [idp_con, power_con,transport_code_loop]} end definition circle_eq_equiv [constructor] (x : S¹) : (base = x) ≃ circle.code x := begin fapply equiv.MK, { exact circle.encode}, { exact circle.decode}, { exact abstract [irreducible] begin induction x, { intro a, esimp, apply rec_nat_on a, { exact idp}, { intros n p, rewrite [↑circle.encode, -power_con, con_tr, transport_code_loop], exact ap succ p}, { intros n p, rewrite [↑circle.encode, nat_succ_eq_int_succ, neg_succ, -power_con_inv, @con_tr _ circle.code, transport_code_loop_inv, ↑[circle.encode] at p, p, -neg_succ] }}, { apply pathover_of_tr_eq, apply eq_of_homotopy, intro a, apply @is_set.elim, esimp, exact _} end end}, { intro p, cases p, exact idp}, end definition base_eq_base_equiv [constructor] : base = base ≃ ℤ := circle_eq_equiv base definition decode_add (a b : ℤ) : circle.decode (a +[ℤ] b) = circle.decode a ⬝ circle.decode b := !power_con_power⁻¹ definition encode_con (p q : base = base) : circle.encode (p ⬝ q) = circle.encode p +[ℤ] circle.encode q := preserve_binary_of_inv_preserve base_eq_base_equiv concat (@add ℤ _) decode_add p q --the carrier of π₁(S¹) is the set-truncation of base = base. open algebra trunc group definition fg_carrier_equiv_int : π[1](S¹*) ≃ ℤ := trunc_equiv_trunc 0 base_eq_base_equiv ⬝e @(trunc_equiv 0 ℤ) proof _ qed definition con_comm_base (p q : base = base) : p ⬝ q = q ⬝ p := eq_of_fn_eq_fn base_eq_base_equiv (by esimp;rewrite [+encode_con,add.comm]) definition fundamental_group_of_circle : π₁(S¹*) ≃g gℤ := begin apply (isomorphism_of_equiv fg_carrier_equiv_int), intros g h, induction g with g', induction h with h', apply encode_con, end open nat definition homotopy_group_of_circle (n : ℕ) : πg[n+2] S¹* ≃g G0 := begin refine @trivial_homotopy_add_of_is_set_loopn S¹* 1 n _, apply is_trunc_equiv_closed_rev, apply base_eq_base_equiv end definition eq_equiv_Z (x : S¹) : x = x ≃ ℤ := begin induction x, { apply base_eq_base_equiv}, { apply equiv_pathover, intro p p' q, apply pathover_of_eq, note H := eq_of_square (square_of_pathover q), rewrite con_comm_base at H, note H' := cancel_left _ H, induction H', reflexivity} end proposition is_trunc_circle [instance] : is_trunc 1 S¹ := begin apply is_trunc_succ_of_is_trunc_loop, { apply trunc_index.minus_one_le_succ}, { intro x, apply is_trunc_equiv_closed_rev, apply eq_equiv_Z} end proposition is_conn_circle [instance] : is_conn 0 S¹ := sphere.is_conn_sphere -1.+2 definition is_conn_pcircle [instance] : is_conn 0 S¹* := !is_conn_circle definition is_trunc_pcircle [instance] : is_trunc 1 S¹* := !is_trunc_circle definition circle_mul [reducible] (x y : S¹) : S¹ := circle.elim y (circle_turn y) x definition circle_mul_base (x : S¹) : circle_mul x base = x := begin induction x, { reflexivity }, { apply eq_pathover_id_right, apply hdeg_square, apply elim_loop } end definition circle_base_mul [reducible] (x : S¹) : circle_mul base x = x := idp end circle
59279e246d8b8a93c41711709abce038fc470ddd
618003631150032a5676f229d13a079ac875ff77
/src/data/fintype/intervals.lean
7ff3f5428f02553b15b88511290de65a9c725c84
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
1,597
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.set.intervals import data.set.finite import data.pnat.intervals /-! # fintype instances for intervals We provide `fintype` instances for `Ico l u`, for `l u : ℕ`, and for `l u : ℤ`. -/ namespace set instance Ico_ℕ_fintype (l u : ℕ) : fintype (Ico l u) := fintype.of_finset (finset.Ico l u) $ (λ n, by { simp only [mem_Ico, finset.Ico.mem], }) @[simp] lemma Ico_ℕ_card (l u : ℕ) : fintype.card (Ico l u) = u - l := calc fintype.card (Ico l u) = (finset.Ico l u).card : fintype.card_of_finset _ _ ... = u - l : finset.Ico.card l u instance Ico_pnat_fintype (l u : ℕ+) : fintype (Ico l u) := fintype.of_finset (pnat.Ico l u) $ (λ n, by { simp only [mem_Ico, pnat.Ico.mem], }) @[simp] lemma Ico_pnat_card (l u : ℕ+) : fintype.card (Ico l u) = u - l := calc fintype.card (Ico l u) = (pnat.Ico l u).card : fintype.card_of_finset _ _ ... = u - l : pnat.Ico.card l u instance Ico_ℤ_fintype (l u : ℤ) : fintype (Ico l u) := fintype.of_finset (finset.Ico_ℤ l u) $ (λ n, by { simp only [mem_Ico, finset.Ico_ℤ.mem], }) @[simp] lemma Ico_ℤ_card (l u : ℤ) : fintype.card (Ico l u) = (u - l).to_nat := calc fintype.card (Ico l u) = (finset.Ico_ℤ l u).card : fintype.card_of_finset _ _ ... = (u - l).to_nat : finset.Ico_ℤ.card l u -- TODO other useful instances: fin n, zmod? end set
245d17a827bed0b506ed50a5449cba88036df9da
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/topology/local_homeomorph.lean
8e4f4210a1467855bf7b91ae98dc1257a53704a1
[ "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
47,409
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import data.equiv.local_equiv import topology.opens /-! # Local homeomorphisms This file defines homeomorphisms between open subsets of topological spaces. An element `e` of `local_homeomorph α β` is an extension of `local_equiv α β`, i.e., it is a pair of functions `e.to_fun` and `e.inv_fun`, inverse of each other on the sets `e.source` and `e.target`. Additionally, we require that these sets are open, and that the functions are continuous on them. Equivalently, they are homeomorphisms there. As in equivs, we register a coercion to functions, and we use `e x` and `e.symm x` throughout instead of `e.to_fun x` and `e.inv_fun x`. ## Main definitions `homeomorph.to_local_homeomorph`: associating a local homeomorphism to a homeomorphism, with source = target = univ `local_homeomorph.symm` : the inverse of a local homeomorphism `local_homeomorph.trans` : the composition of two local homeomorphisms `local_homeomorph.refl` : the identity local homeomorphism `local_homeomorph.of_set`: the identity on a set `s` `eq_on_source` : equivalence relation describing the "right" notion of equality for local homeomorphisms ## Implementation notes Most statements are copied from their local_equiv versions, although some care is required especially when restricting to subsets, as these should be open subsets. For design notes, see `local_equiv.lean`. ### Local coding conventions If a lemma deals with the intersection of a set with either source or target of a `local_equiv`, then it should use `e.source ∩ s` or `e.target ∩ t`, not `s ∩ e.source` or `t ∩ e.target`. -/ open function set filter topological_space (second_countable_topology) open_locale topological_space variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] /-- local homeomorphisms, defined on open subsets of the space -/ @[nolint has_inhabited_instance] structure local_homeomorph (α : Type*) (β : Type*) [topological_space α] [topological_space β] extends local_equiv α β := (open_source : is_open source) (open_target : is_open target) (continuous_to_fun : continuous_on to_fun source) (continuous_inv_fun : continuous_on inv_fun target) /-- A homeomorphism induces a local homeomorphism on the whole space -/ def homeomorph.to_local_homeomorph (e : α ≃ₜ β) : local_homeomorph α β := { open_source := is_open_univ, open_target := is_open_univ, continuous_to_fun := by { erw ← continuous_iff_continuous_on_univ, exact e.continuous_to_fun }, continuous_inv_fun := by { erw ← continuous_iff_continuous_on_univ, exact e.continuous_inv_fun }, ..e.to_equiv.to_local_equiv } namespace local_homeomorph variables (e : local_homeomorph α β) (e' : local_homeomorph β γ) instance : has_coe_to_fun (local_homeomorph α β) (λ _, α → β) := ⟨λ e, e.to_fun⟩ /-- The inverse of a local homeomorphism -/ protected def symm : local_homeomorph β α := { open_source := e.open_target, open_target := e.open_source, continuous_to_fun := e.continuous_inv_fun, continuous_inv_fun := e.continuous_to_fun, ..e.to_local_equiv.symm } /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def simps.apply (e : local_homeomorph α β) : α → β := e /-- See Note [custom simps projection] -/ def simps.symm_apply (e : local_homeomorph α β) : β → α := e.symm initialize_simps_projections local_homeomorph (to_local_equiv_to_fun → apply, to_local_equiv_inv_fun → symm_apply, to_local_equiv_source → source, to_local_equiv_target → target, -to_local_equiv) protected lemma continuous_on : continuous_on e e.source := e.continuous_to_fun lemma continuous_on_symm : continuous_on e.symm e.target := e.continuous_inv_fun @[simp, mfld_simps] lemma mk_coe (e : local_equiv α β) (a b c d) : (local_homeomorph.mk e a b c d : α → β) = e := rfl @[simp, mfld_simps] lemma mk_coe_symm (e : local_equiv α β) (a b c d) : ((local_homeomorph.mk e a b c d).symm : β → α) = e.symm := rfl /- Register a few simp lemmas to make sure that `simp` puts the application of a local homeomorphism in its normal form, i.e., in terms of its coercion to a function. -/ @[simp, mfld_simps] lemma to_fun_eq_coe (e : local_homeomorph α β) : e.to_fun = e := rfl @[simp, mfld_simps] lemma inv_fun_eq_coe (e : local_homeomorph α β) : e.inv_fun = e.symm := rfl @[simp, mfld_simps] lemma coe_coe : (e.to_local_equiv : α → β) = e := rfl @[simp, mfld_simps] lemma coe_coe_symm : (e.to_local_equiv.symm : β → α) = e.symm := rfl @[simp, mfld_simps] lemma map_source {x : α} (h : x ∈ e.source) : e x ∈ e.target := e.map_source' h @[simp, mfld_simps] lemma map_target {x : β} (h : x ∈ e.target) : e.symm x ∈ e.source := e.map_target' h @[simp, mfld_simps] lemma left_inv {x : α} (h : x ∈ e.source) : e.symm (e x) = x := e.left_inv' h @[simp, mfld_simps] lemma right_inv {x : β} (h : x ∈ e.target) : e (e.symm x) = x := e.right_inv' h protected lemma maps_to : maps_to e e.source e.target := λ x, e.map_source protected lemma symm_maps_to : maps_to e.symm e.target e.source := e.symm.maps_to protected lemma left_inv_on : left_inv_on e.symm e e.source := λ x, e.left_inv protected lemma right_inv_on : right_inv_on e.symm e e.target := λ x, e.right_inv protected lemma inv_on : inv_on e.symm e e.source e.target := ⟨e.left_inv_on, e.right_inv_on⟩ protected lemma inj_on : inj_on e e.source := e.left_inv_on.inj_on protected lemma bij_on : bij_on e e.source e.target := e.inv_on.bij_on e.maps_to e.symm_maps_to protected lemma surj_on : surj_on e e.source e.target := e.bij_on.surj_on /-- Replace `to_local_equiv` field to provide better definitional equalities. -/ def replace_equiv (e : local_homeomorph α β) (e' : local_equiv α β) (h : e.to_local_equiv = e') : local_homeomorph α β := { to_local_equiv := e', open_source := h ▸ e.open_source, open_target := h ▸ e.open_target, continuous_to_fun := h ▸ e.continuous_to_fun, continuous_inv_fun := h ▸ e.continuous_inv_fun } lemma replace_equiv_eq_self (e : local_homeomorph α β) (e' : local_equiv α β) (h : e.to_local_equiv = e') : e.replace_equiv e' h = e := by { cases e, subst e', refl } lemma source_preimage_target : e.source ⊆ e ⁻¹' e.target := e.maps_to lemma eq_of_local_equiv_eq {e e' : local_homeomorph α β} (h : e.to_local_equiv = e'.to_local_equiv) : e = e' := by { cases e, cases e', cases h, refl } lemma eventually_left_inverse (e : local_homeomorph α β) {x} (hx : x ∈ e.source) : ∀ᶠ y in 𝓝 x, e.symm (e y) = y := (e.open_source.eventually_mem hx).mono e.left_inv' lemma eventually_left_inverse' (e : local_homeomorph α β) {x} (hx : x ∈ e.target) : ∀ᶠ y in 𝓝 (e.symm x), e.symm (e y) = y := e.eventually_left_inverse (e.map_target hx) lemma eventually_right_inverse (e : local_homeomorph α β) {x} (hx : x ∈ e.target) : ∀ᶠ y in 𝓝 x, e (e.symm y) = y := (e.open_target.eventually_mem hx).mono e.right_inv' lemma eventually_right_inverse' (e : local_homeomorph α β) {x} (hx : x ∈ e.source) : ∀ᶠ y in 𝓝 (e x), e (e.symm y) = y := e.eventually_right_inverse (e.map_source hx) lemma eventually_ne_nhds_within (e : local_homeomorph α β) {x} (hx : x ∈ e.source) : ∀ᶠ x' in 𝓝[≠] x, e x' ≠ e x := eventually_nhds_within_iff.2 $ (e.eventually_left_inverse hx).mono $ λ x' hx', mt $ λ h, by rw [mem_singleton_iff, ← e.left_inv hx, ← h, hx'] lemma nhds_within_source_inter {x} (hx : x ∈ e.source) (s : set α) : 𝓝[e.source ∩ s] x = 𝓝[s] x := nhds_within_inter_of_mem (mem_nhds_within_of_mem_nhds $ is_open.mem_nhds e.open_source hx) lemma nhds_within_target_inter {x} (hx : x ∈ e.target) (s : set β) : 𝓝[e.target ∩ s] x = 𝓝[s] x := e.symm.nhds_within_source_inter hx s lemma image_eq_target_inter_inv_preimage {s : set α} (h : s ⊆ e.source) : e '' s = e.target ∩ e.symm ⁻¹' s := e.to_local_equiv.image_eq_target_inter_inv_preimage h lemma image_source_inter_eq' (s : set α) : e '' (e.source ∩ s) = e.target ∩ e.symm ⁻¹' s := e.to_local_equiv.image_source_inter_eq' s lemma image_source_inter_eq (s : set α) : e '' (e.source ∩ s) = e.target ∩ e.symm ⁻¹' (e.source ∩ s) := e.to_local_equiv.image_source_inter_eq s lemma symm_image_eq_source_inter_preimage {s : set β} (h : s ⊆ e.target) : e.symm '' s = e.source ∩ e ⁻¹' s := e.symm.image_eq_target_inter_inv_preimage h lemma symm_image_target_inter_eq (s : set β) : e.symm '' (e.target ∩ s) = e.source ∩ e ⁻¹' (e.target ∩ s) := e.symm.image_source_inter_eq _ lemma source_inter_preimage_inv_preimage (s : set α) : e.source ∩ e ⁻¹' (e.symm ⁻¹' s) = e.source ∩ s := e.to_local_equiv.source_inter_preimage_inv_preimage s lemma target_inter_inv_preimage_preimage (s : set β) : e.target ∩ e.symm ⁻¹' (e ⁻¹' s) = e.target ∩ s := e.symm.source_inter_preimage_inv_preimage _ lemma source_inter_preimage_target_inter (s : set β) : e.source ∩ (e ⁻¹' (e.target ∩ s)) = e.source ∩ (e ⁻¹' s) := e.to_local_equiv.source_inter_preimage_target_inter s /-- Two local homeomorphisms are equal when they have equal `to_fun`, `inv_fun` and `source`. It is not sufficient to have equal `to_fun` and `source`, as this only determines `inv_fun` on the target. This would only be true for a weaker notion of equality, arguably the right one, called `eq_on_source`. -/ @[ext] protected lemma ext (e' : local_homeomorph α β) (h : ∀x, e x = e' x) (hinv : ∀x, e.symm x = e'.symm x) (hs : e.source = e'.source) : e = e' := eq_of_local_equiv_eq (local_equiv.ext h hinv hs) @[simp, mfld_simps] lemma symm_to_local_equiv : e.symm.to_local_equiv = e.to_local_equiv.symm := rfl -- The following lemmas are already simp via local_equiv lemma symm_source : e.symm.source = e.target := rfl lemma symm_target : e.symm.target = e.source := rfl @[simp, mfld_simps] lemma symm_symm : e.symm.symm = e := eq_of_local_equiv_eq $ by simp /-- A local homeomorphism is continuous at any point of its source -/ protected lemma continuous_at {x : α} (h : x ∈ e.source) : continuous_at e x := (e.continuous_on x h).continuous_at (is_open.mem_nhds e.open_source h) /-- A local homeomorphism inverse is continuous at any point of its target -/ lemma continuous_at_symm {x : β} (h : x ∈ e.target) : continuous_at e.symm x := e.symm.continuous_at h lemma tendsto_symm {x} (hx : x ∈ e.source) : tendsto e.symm (𝓝 (e x)) (𝓝 x) := by simpa only [continuous_at, e.left_inv hx] using e.continuous_at_symm (e.map_source hx) lemma map_nhds_eq {x} (hx : x ∈ e.source) : map e (𝓝 x) = 𝓝 (e x) := le_antisymm (e.continuous_at hx) $ le_map_of_right_inverse (e.eventually_right_inverse' hx) (e.tendsto_symm hx) lemma symm_map_nhds_eq {x} (hx : x ∈ e.source) : map e.symm (𝓝 (e x)) = 𝓝 x := (e.symm.map_nhds_eq $ e.map_source hx).trans $ by rw e.left_inv hx lemma image_mem_nhds {x} (hx : x ∈ e.source) {s : set α} (hs : s ∈ 𝓝 x) : e '' s ∈ 𝓝 (e x) := e.map_nhds_eq hx ▸ filter.image_mem_map hs lemma map_nhds_within_eq (e : local_homeomorph α β) {x} (hx : x ∈ e.source) (s : set α) : map e (𝓝[s] x) = 𝓝[e '' (e.source ∩ s)] (e x) := calc map e (𝓝[s] x) = map e (𝓝[e.source ∩ s] x) : congr_arg (map e) (e.nhds_within_source_inter hx _).symm ... = 𝓝[e '' (e.source ∩ s)] (e x) : (e.left_inv_on.mono $ inter_subset_left _ _).map_nhds_within_eq (e.left_inv hx) (e.continuous_at_symm (e.map_source hx)).continuous_within_at (e.continuous_at hx).continuous_within_at lemma map_nhds_within_preimage_eq (e : local_homeomorph α β) {x} (hx : x ∈ e.source) (s : set β) : map e (𝓝[e ⁻¹' s] x) = 𝓝[s] (e x) := by rw [e.map_nhds_within_eq hx, e.image_source_inter_eq', e.target_inter_inv_preimage_preimage, e.nhds_within_target_inter (e.map_source hx)] lemma preimage_open_of_open {s : set β} (hs : is_open s) : is_open (e.source ∩ e ⁻¹' s) := e.continuous_on.preimage_open_of_open e.open_source hs /-! ### `local_homeomorph.is_image` relation We say that `t : set β` is an image of `s : set α` under a local homeomorphism `e` if any of the following equivalent conditions hold: * `e '' (e.source ∩ s) = e.target ∩ t`; * `e.source ∩ e ⁻¹ t = e.source ∩ s`; * `∀ x ∈ e.source, e x ∈ t ↔ x ∈ s` (this one is used in the definition). This definition is a restatement of `local_equiv.is_image` for local homeomorphisms. In this section we transfer API about `local_equiv.is_image` to local homeomorphisms and add a few `local_homeomorph`-specific lemmas like `local_homeomorph.is_image.closure`. -/ /-- We say that `t : set β` is an image of `s : set α` under a local homeomorphism `e` if any of the following equivalent conditions hold: * `e '' (e.source ∩ s) = e.target ∩ t`; * `e.source ∩ e ⁻¹ t = e.source ∩ s`; * `∀ x ∈ e.source, e x ∈ t ↔ x ∈ s` (this one is used in the definition). -/ def is_image (s : set α) (t : set β) : Prop := ∀ ⦃x⦄, x ∈ e.source → (e x ∈ t ↔ x ∈ s) namespace is_image variables {e} {s : set α} {t : set β} {x : α} {y : β} lemma to_local_equiv (h : e.is_image s t) : e.to_local_equiv.is_image s t := h lemma apply_mem_iff (h : e.is_image s t) (hx : x ∈ e.source) : e x ∈ t ↔ x ∈ s := h hx protected lemma symm (h : e.is_image s t) : e.symm.is_image t s := h.to_local_equiv.symm lemma symm_apply_mem_iff (h : e.is_image s t) (hy : y ∈ e.target) : (e.symm y ∈ s ↔ y ∈ t) := h.symm hy @[simp] lemma symm_iff : e.symm.is_image t s ↔ e.is_image s t := ⟨λ h, h.symm, λ h, h.symm⟩ protected lemma maps_to (h : e.is_image s t) : maps_to e (e.source ∩ s) (e.target ∩ t) := h.to_local_equiv.maps_to lemma symm_maps_to (h : e.is_image s t) : maps_to e.symm (e.target ∩ t) (e.source ∩ s) := h.symm.maps_to lemma image_eq (h : e.is_image s t) : e '' (e.source ∩ s) = e.target ∩ t := h.to_local_equiv.image_eq lemma symm_image_eq (h : e.is_image s t) : e.symm '' (e.target ∩ t) = e.source ∩ s := h.symm.image_eq lemma iff_preimage_eq : e.is_image s t ↔ e.source ∩ e ⁻¹' t = e.source ∩ s := local_equiv.is_image.iff_preimage_eq alias iff_preimage_eq ↔ local_homeomorph.is_image.preimage_eq local_homeomorph.is_image.of_preimage_eq lemma iff_symm_preimage_eq : e.is_image s t ↔ e.target ∩ e.symm ⁻¹' s = e.target ∩ t := symm_iff.symm.trans iff_preimage_eq alias iff_symm_preimage_eq ↔ local_homeomorph.is_image.symm_preimage_eq local_homeomorph.is_image.of_symm_preimage_eq lemma iff_symm_preimage_eq' : e.is_image s t ↔ e.target ∩ e.symm ⁻¹' (e.source ∩ s) = e.target ∩ t := by rw [iff_symm_preimage_eq, ← image_source_inter_eq, ← image_source_inter_eq'] alias iff_symm_preimage_eq' ↔ local_homeomorph.is_image.symm_preimage_eq' local_homeomorph.is_image.of_symm_preimage_eq' lemma iff_preimage_eq' : e.is_image s t ↔ e.source ∩ e ⁻¹' (e.target ∩ t) = e.source ∩ s := symm_iff.symm.trans iff_symm_preimage_eq' alias iff_preimage_eq' ↔ local_homeomorph.is_image.preimage_eq' local_homeomorph.is_image.of_preimage_eq' lemma of_image_eq (h : e '' (e.source ∩ s) = e.target ∩ t) : e.is_image s t := local_equiv.is_image.of_image_eq h lemma of_symm_image_eq (h : e.symm '' (e.target ∩ t) = e.source ∩ s) : e.is_image s t := local_equiv.is_image.of_symm_image_eq h protected lemma compl (h : e.is_image s t) : e.is_image sᶜ tᶜ := λ x hx, not_congr (h hx) protected lemma inter {s' t'} (h : e.is_image s t) (h' : e.is_image s' t') : e.is_image (s ∩ s') (t ∩ t') := λ x hx, and_congr (h hx) (h' hx) protected lemma union {s' t'} (h : e.is_image s t) (h' : e.is_image s' t') : e.is_image (s ∪ s') (t ∪ t') := λ x hx, or_congr (h hx) (h' hx) protected lemma diff {s' t'} (h : e.is_image s t) (h' : e.is_image s' t') : e.is_image (s \ s') (t \ t') := h.inter h'.compl lemma left_inv_on_piecewise {e' : local_homeomorph α β} [∀ i, decidable (i ∈ s)] [∀ i, decidable (i ∈ t)] (h : e.is_image s t) (h' : e'.is_image s t) : left_inv_on (t.piecewise e.symm e'.symm) (s.piecewise e e') (s.ite e.source e'.source) := h.to_local_equiv.left_inv_on_piecewise h' lemma inter_eq_of_inter_eq_of_eq_on {e' : local_homeomorph α β} (h : e.is_image s t) (h' : e'.is_image s t) (hs : e.source ∩ s = e'.source ∩ s) (Heq : eq_on e e' (e.source ∩ s)) : e.target ∩ t = e'.target ∩ t := h.to_local_equiv.inter_eq_of_inter_eq_of_eq_on h' hs Heq lemma symm_eq_on_of_inter_eq_of_eq_on {e' : local_homeomorph α β} (h : e.is_image s t) (hs : e.source ∩ s = e'.source ∩ s) (Heq : eq_on e e' (e.source ∩ s)) : eq_on e.symm e'.symm (e.target ∩ t) := h.to_local_equiv.symm_eq_on_of_inter_eq_of_eq_on hs Heq lemma map_nhds_within_eq (h : e.is_image s t) (hx : x ∈ e.source) : map e (𝓝[s] x) = 𝓝[t] (e x) := by rw [e.map_nhds_within_eq hx, h.image_eq, e.nhds_within_target_inter (e.map_source hx)] protected lemma closure (h : e.is_image s t) : e.is_image (closure s) (closure t) := λ x hx, by simp only [mem_closure_iff_nhds_within_ne_bot, ← h.map_nhds_within_eq hx, map_ne_bot_iff] protected lemma interior (h : e.is_image s t) : e.is_image (interior s) (interior t) := by simpa only [closure_compl, compl_compl] using h.compl.closure.compl protected lemma frontier (h : e.is_image s t) : e.is_image (frontier s) (frontier t) := h.closure.diff h.interior lemma is_open_iff (h : e.is_image s t) : is_open (e.source ∩ s) ↔ is_open (e.target ∩ t) := ⟨λ hs, h.symm_preimage_eq' ▸ e.symm.preimage_open_of_open hs, λ hs, h.preimage_eq' ▸ e.preimage_open_of_open hs⟩ /-- Restrict a `local_homeomorph` to a pair of corresponding open sets. -/ @[simps to_local_equiv] def restr (h : e.is_image s t) (hs : is_open (e.source ∩ s)) : local_homeomorph α β := { to_local_equiv := h.to_local_equiv.restr, open_source := hs, open_target := h.is_open_iff.1 hs, continuous_to_fun := e.continuous_on.mono (inter_subset_left _ _), continuous_inv_fun := e.symm.continuous_on.mono (inter_subset_left _ _) } end is_image lemma is_image_source_target : e.is_image e.source e.target := e.to_local_equiv.is_image_source_target lemma is_image_source_target_of_disjoint (e' : local_homeomorph α β) (hs : disjoint e.source e'.source) (ht : disjoint e.target e'.target) : e.is_image e'.source e'.target := e.to_local_equiv.is_image_source_target_of_disjoint e'.to_local_equiv hs ht /-- Preimage of interior or interior of preimage coincide for local homeomorphisms, when restricted to the source. -/ lemma preimage_interior (s : set β) : e.source ∩ e ⁻¹' (interior s) = e.source ∩ interior (e ⁻¹' s) := (is_image.of_preimage_eq rfl).interior.preimage_eq lemma preimage_closure (s : set β) : e.source ∩ e ⁻¹' (closure s) = e.source ∩ closure (e ⁻¹' s) := (is_image.of_preimage_eq rfl).closure.preimage_eq lemma preimage_frontier (s : set β) : e.source ∩ e ⁻¹' (frontier s) = e.source ∩ frontier (e ⁻¹' s) := (is_image.of_preimage_eq rfl).frontier.preimage_eq lemma preimage_open_of_open_symm {s : set α} (hs : is_open s) : is_open (e.target ∩ e.symm ⁻¹' s) := e.symm.continuous_on.preimage_open_of_open e.open_target hs /-- The image of an open set in the source is open. -/ lemma image_open_of_open {s : set α} (hs : is_open s) (h : s ⊆ e.source) : is_open (e '' s) := begin have : e '' s = e.target ∩ e.symm ⁻¹' s := e.to_local_equiv.image_eq_target_inter_inv_preimage h, rw this, exact e.continuous_on_symm.preimage_open_of_open e.open_target hs end /-- The image of the restriction of an open set to the source is open. -/ lemma image_open_of_open' {s : set α} (hs : is_open s) : is_open (e '' (e.source ∩ s)) := image_open_of_open _ (is_open.inter e.open_source hs) (inter_subset_left _ _) /-- A `local_equiv` with continuous open forward map and an open source is a `local_homeomorph`. -/ def of_continuous_open_restrict (e : local_equiv α β) (hc : continuous_on e e.source) (ho : is_open_map (e.source.restrict e)) (hs : is_open e.source) : local_homeomorph α β := { to_local_equiv := e, open_source := hs, open_target := by simpa only [range_restrict, e.image_source_eq_target] using ho.is_open_range, continuous_to_fun := hc, continuous_inv_fun := e.image_source_eq_target ▸ ho.continuous_on_image_of_left_inv_on e.left_inv_on } /-- A `local_equiv` with continuous open forward map and an open source is a `local_homeomorph`. -/ def of_continuous_open (e : local_equiv α β) (hc : continuous_on e e.source) (ho : is_open_map e) (hs : is_open e.source) : local_homeomorph α β := of_continuous_open_restrict e hc (ho.restrict hs) hs /-- Restricting a local homeomorphism `e` to `e.source ∩ s` when `s` is open. This is sometimes hard to use because of the openness assumption, but it has the advantage that when it can be used then its local_equiv is defeq to local_equiv.restr -/ protected def restr_open (s : set α) (hs : is_open s) : local_homeomorph α β := (@is_image.of_symm_preimage_eq α β _ _ e s (e.symm ⁻¹' s) rfl).restr (is_open.inter e.open_source hs) @[simp, mfld_simps] lemma restr_open_to_local_equiv (s : set α) (hs : is_open s) : (e.restr_open s hs).to_local_equiv = e.to_local_equiv.restr s := rfl -- Already simp via local_equiv lemma restr_open_source (s : set α) (hs : is_open s) : (e.restr_open s hs).source = e.source ∩ s := rfl /-- Restricting a local homeomorphism `e` to `e.source ∩ interior s`. We use the interior to make sure that the restriction is well defined whatever the set s, since local homeomorphisms are by definition defined on open sets. In applications where `s` is open, this coincides with the restriction of local equivalences -/ @[simps apply symm_apply (mfld_cfg), simps source target {attrs := []}] protected def restr (s : set α) : local_homeomorph α β := e.restr_open (interior s) is_open_interior @[simp, mfld_simps] lemma restr_to_local_equiv (s : set α) : (e.restr s).to_local_equiv = (e.to_local_equiv).restr (interior s) := rfl lemma restr_source' (s : set α) (hs : is_open s) : (e.restr s).source = e.source ∩ s := by rw [e.restr_source, hs.interior_eq] lemma restr_to_local_equiv' (s : set α) (hs : is_open s): (e.restr s).to_local_equiv = e.to_local_equiv.restr s := by rw [e.restr_to_local_equiv, hs.interior_eq] lemma restr_eq_of_source_subset {e : local_homeomorph α β} {s : set α} (h : e.source ⊆ s) : e.restr s = e := begin apply eq_of_local_equiv_eq, rw restr_to_local_equiv, apply local_equiv.restr_eq_of_source_subset, exact interior_maximal h e.open_source end @[simp, mfld_simps] lemma restr_univ {e : local_homeomorph α β} : e.restr univ = e := restr_eq_of_source_subset (subset_univ _) lemma restr_source_inter (s : set α) : e.restr (e.source ∩ s) = e.restr s := begin refine local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) _, simp [e.open_source.interior_eq, ← inter_assoc] end /-- The identity on the whole space as a local homeomorphism. -/ @[simps apply (mfld_cfg), simps source target {attrs := []}] protected def refl (α : Type*) [topological_space α] : local_homeomorph α α := (homeomorph.refl α).to_local_homeomorph @[simp, mfld_simps] lemma refl_local_equiv : (local_homeomorph.refl α).to_local_equiv = local_equiv.refl α := rfl @[simp, mfld_simps] lemma refl_symm : (local_homeomorph.refl α).symm = local_homeomorph.refl α := rfl section variables {s : set α} (hs : is_open s) /-- The identity local equiv on a set `s` -/ @[simps apply (mfld_cfg), simps source target {attrs := []}] def of_set (s : set α) (hs : is_open s) : local_homeomorph α α := { open_source := hs, open_target := hs, continuous_to_fun := continuous_id.continuous_on, continuous_inv_fun := continuous_id.continuous_on, ..local_equiv.of_set s } @[simp, mfld_simps] lemma of_set_to_local_equiv : (of_set s hs).to_local_equiv = local_equiv.of_set s := rfl @[simp, mfld_simps] lemma of_set_symm : (of_set s hs).symm = of_set s hs := rfl @[simp, mfld_simps] lemma of_set_univ_eq_refl : of_set univ is_open_univ = local_homeomorph.refl α := by ext; simp end /-- Composition of two local homeomorphisms when the target of the first and the source of the second coincide. -/ protected def trans' (h : e.target = e'.source) : local_homeomorph α γ := { open_source := e.open_source, open_target := e'.open_target, continuous_to_fun := begin apply continuous_on.comp e'.continuous_to_fun e.continuous_to_fun, rw ← h, exact e.to_local_equiv.source_subset_preimage_target end, continuous_inv_fun := begin apply continuous_on.comp e.continuous_inv_fun e'.continuous_inv_fun, rw h, exact e'.to_local_equiv.target_subset_preimage_source end, ..local_equiv.trans' e.to_local_equiv e'.to_local_equiv h } /-- Composing two local homeomorphisms, by restricting to the maximal domain where their composition is well defined. -/ protected def trans : local_homeomorph α γ := local_homeomorph.trans' (e.symm.restr_open e'.source e'.open_source).symm (e'.restr_open e.target e.open_target) (by simp [inter_comm]) @[simp, mfld_simps] lemma trans_to_local_equiv : (e.trans e').to_local_equiv = e.to_local_equiv.trans e'.to_local_equiv := rfl @[simp, mfld_simps] lemma coe_trans : (e.trans e' : α → γ) = e' ∘ e := rfl @[simp, mfld_simps] lemma coe_trans_symm : ((e.trans e').symm : γ → α) = e.symm ∘ e'.symm := rfl lemma trans_symm_eq_symm_trans_symm : (e.trans e').symm = e'.symm.trans e.symm := by cases e; cases e'; refl /- This could be considered as a simp lemma, but there are many situations where it makes something simple into something more complicated. -/ lemma trans_source : (e.trans e').source = e.source ∩ e ⁻¹' e'.source := local_equiv.trans_source e.to_local_equiv e'.to_local_equiv lemma trans_source' : (e.trans e').source = e.source ∩ e ⁻¹' (e.target ∩ e'.source) := local_equiv.trans_source' e.to_local_equiv e'.to_local_equiv lemma trans_source'' : (e.trans e').source = e.symm '' (e.target ∩ e'.source) := local_equiv.trans_source'' e.to_local_equiv e'.to_local_equiv lemma image_trans_source : e '' (e.trans e').source = e.target ∩ e'.source := local_equiv.image_trans_source e.to_local_equiv e'.to_local_equiv lemma trans_target : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' e.target := rfl lemma trans_target' : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' (e'.source ∩ e.target) := trans_source' e'.symm e.symm lemma trans_target'' : (e.trans e').target = e' '' (e'.source ∩ e.target) := trans_source'' e'.symm e.symm lemma inv_image_trans_target : e'.symm '' (e.trans e').target = e'.source ∩ e.target := image_trans_source e'.symm e.symm lemma trans_assoc (e'' : local_homeomorph γ δ) : (e.trans e').trans e'' = e.trans (e'.trans e'') := eq_of_local_equiv_eq $ local_equiv.trans_assoc e.to_local_equiv e'.to_local_equiv e''.to_local_equiv @[simp, mfld_simps] lemma trans_refl : e.trans (local_homeomorph.refl β) = e := eq_of_local_equiv_eq $ local_equiv.trans_refl e.to_local_equiv @[simp, mfld_simps] lemma refl_trans : (local_homeomorph.refl α).trans e = e := eq_of_local_equiv_eq $ local_equiv.refl_trans e.to_local_equiv lemma trans_of_set {s : set β} (hs : is_open s) : e.trans (of_set s hs) = e.restr (e ⁻¹' s) := local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) $ by simp [local_equiv.trans_source, (e.preimage_interior _).symm, hs.interior_eq] lemma trans_of_set' {s : set β} (hs : is_open s) : e.trans (of_set s hs) = e.restr (e.source ∩ e ⁻¹' s) := by rw [trans_of_set, restr_source_inter] lemma of_set_trans {s : set α} (hs : is_open s) : (of_set s hs).trans e = e.restr s := local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) $ by simp [local_equiv.trans_source, hs.interior_eq, inter_comm] lemma of_set_trans' {s : set α} (hs : is_open s) : (of_set s hs).trans e = e.restr (e.source ∩ s) := by rw [of_set_trans, restr_source_inter] @[simp, mfld_simps] lemma of_set_trans_of_set {s : set α} (hs : is_open s) {s' : set α} (hs' : is_open s') : (of_set s hs).trans (of_set s' hs') = of_set (s ∩ s') (is_open.inter hs hs') := begin rw (of_set s hs).trans_of_set hs', ext; simp [hs'.interior_eq] end lemma restr_trans (s : set α) : (e.restr s).trans e' = (e.trans e').restr s := eq_of_local_equiv_eq $ local_equiv.restr_trans e.to_local_equiv e'.to_local_equiv (interior s) /-- `eq_on_source e e'` means that `e` and `e'` have the same source, and coincide there. They should really be considered the same local equiv. -/ def eq_on_source (e e' : local_homeomorph α β) : Prop := e.source = e'.source ∧ (eq_on e e' e.source) lemma eq_on_source_iff (e e' : local_homeomorph α β) : eq_on_source e e' ↔ local_equiv.eq_on_source e.to_local_equiv e'.to_local_equiv := iff.rfl /-- `eq_on_source` is an equivalence relation -/ instance : setoid (local_homeomorph α β) := { r := eq_on_source, iseqv := ⟨ λe, (@local_equiv.eq_on_source_setoid α β).iseqv.1 e.to_local_equiv, λe e' h, (@local_equiv.eq_on_source_setoid α β).iseqv.2.1 ((eq_on_source_iff e e').1 h), λe e' e'' h h', (@local_equiv.eq_on_source_setoid α β).iseqv.2.2 ((eq_on_source_iff e e').1 h) ((eq_on_source_iff e' e'').1 h')⟩ } lemma eq_on_source_refl : e ≈ e := setoid.refl _ /-- If two local homeomorphisms are equivalent, so are their inverses -/ lemma eq_on_source.symm' {e e' : local_homeomorph α β} (h : e ≈ e') : e.symm ≈ e'.symm := local_equiv.eq_on_source.symm' h /-- Two equivalent local homeomorphisms have the same source -/ lemma eq_on_source.source_eq {e e' : local_homeomorph α β} (h : e ≈ e') : e.source = e'.source := h.1 /-- Two equivalent local homeomorphisms have the same target -/ lemma eq_on_source.target_eq {e e' : local_homeomorph α β} (h : e ≈ e') : e.target = e'.target := h.symm'.1 /-- Two equivalent local homeomorphisms have coinciding `to_fun` on the source -/ lemma eq_on_source.eq_on {e e' : local_homeomorph α β} (h : e ≈ e') : eq_on e e' e.source := h.2 /-- Two equivalent local homeomorphisms have coinciding `inv_fun` on the target -/ lemma eq_on_source.symm_eq_on_target {e e' : local_homeomorph α β} (h : e ≈ e') : eq_on e.symm e'.symm e.target := h.symm'.2 /-- Composition of local homeomorphisms respects equivalence -/ lemma eq_on_source.trans' {e e' : local_homeomorph α β} {f f' : local_homeomorph β γ} (he : e ≈ e') (hf : f ≈ f') : e.trans f ≈ e'.trans f' := local_equiv.eq_on_source.trans' he hf /-- Restriction of local homeomorphisms respects equivalence -/ lemma eq_on_source.restr {e e' : local_homeomorph α β} (he : e ≈ e') (s : set α) : e.restr s ≈ e'.restr s := local_equiv.eq_on_source.restr he _ /-- Composition of a local homeomorphism and its inverse is equivalent to the restriction of the identity to the source -/ lemma trans_self_symm : e.trans e.symm ≈ local_homeomorph.of_set e.source e.open_source := local_equiv.trans_self_symm _ lemma trans_symm_self : e.symm.trans e ≈ local_homeomorph.of_set e.target e.open_target := e.symm.trans_self_symm lemma eq_of_eq_on_source_univ {e e' : local_homeomorph α β} (h : e ≈ e') (s : e.source = univ) (t : e.target = univ) : e = e' := eq_of_local_equiv_eq $ local_equiv.eq_of_eq_on_source_univ _ _ h s t section prod /-- The product of two local homeomorphisms, as a local homeomorphism on the product space. -/ @[simps to_local_equiv apply (mfld_cfg), simps source target symm_apply {attrs := []}] def prod (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : local_homeomorph (α × γ) (β × δ) := { open_source := e.open_source.prod e'.open_source, open_target := e.open_target.prod e'.open_target, continuous_to_fun := e.continuous_on.prod_map e'.continuous_on, continuous_inv_fun := e.continuous_on_symm.prod_map e'.continuous_on_symm, to_local_equiv := e.to_local_equiv.prod e'.to_local_equiv } @[simp, mfld_simps] lemma prod_symm (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : (e.prod e').symm = (e.symm.prod e'.symm) := rfl @[simp, mfld_simps] lemma prod_trans {η : Type*} {ε : Type*} [topological_space η] [topological_space ε] (e : local_homeomorph α β) (f : local_homeomorph β γ) (e' : local_homeomorph δ η) (f' : local_homeomorph η ε) : (e.prod e').trans (f.prod f') = (e.trans f).prod (e'.trans f') := local_homeomorph.eq_of_local_equiv_eq $ by dsimp only [trans_to_local_equiv, prod_to_local_equiv]; apply local_equiv.prod_trans end prod section piecewise /-- Combine two `local_homeomorph`s using `set.piecewise`. The source of the new `local_homeomorph` is `s.ite e.source e'.source = e.source ∩ s ∪ e'.source \ s`, and similarly for target. The function sends `e.source ∩ s` to `e.target ∩ t` using `e` and `e'.source \ s` to `e'.target \ t` using `e'`, and similarly for the inverse function. To ensure that the maps `to_fun` and `inv_fun` are inverse of each other on the new `source` and `target`, the definition assumes that the sets `s` and `t` are related both by `e.is_image` and `e'.is_image`. To ensure that the new maps are continuous on `source`/`target`, it also assumes that `e.source` and `e'.source` meet `frontier s` on the same set and `e x = e' x` on this intersection. -/ @[simps to_local_equiv apply {fully_applied := ff}] def piecewise (e e' : local_homeomorph α β) (s : set α) (t : set β) [∀ x, decidable (x ∈ s)] [∀ y, decidable (y ∈ t)] (H : e.is_image s t) (H' : e'.is_image s t) (Hs : e.source ∩ frontier s = e'.source ∩ frontier s) (Heq : eq_on e e' (e.source ∩ frontier s)) : local_homeomorph α β := { to_local_equiv := e.to_local_equiv.piecewise e'.to_local_equiv s t H H', open_source := e.open_source.ite e'.open_source Hs, open_target := e.open_target.ite e'.open_target $ H.frontier.inter_eq_of_inter_eq_of_eq_on H'.frontier Hs Heq, continuous_to_fun := continuous_on_piecewise_ite e.continuous_on e'.continuous_on Hs Heq, continuous_inv_fun := continuous_on_piecewise_ite e.continuous_on_symm e'.continuous_on_symm (H.frontier.inter_eq_of_inter_eq_of_eq_on H'.frontier Hs Heq) (H.frontier.symm_eq_on_of_inter_eq_of_eq_on Hs Heq) } @[simp] lemma symm_piecewise (e e' : local_homeomorph α β) {s : set α} {t : set β} [∀ x, decidable (x ∈ s)] [∀ y, decidable (y ∈ t)] (H : e.is_image s t) (H' : e'.is_image s t) (Hs : e.source ∩ frontier s = e'.source ∩ frontier s) (Heq : eq_on e e' (e.source ∩ frontier s)) : (e.piecewise e' s t H H' Hs Heq).symm = e.symm.piecewise e'.symm t s H.symm H'.symm (H.frontier.inter_eq_of_inter_eq_of_eq_on H'.frontier Hs Heq) (H.frontier.symm_eq_on_of_inter_eq_of_eq_on Hs Heq) := rfl /-- Combine two `local_homeomorph`s with disjoint sources and disjoint targets. We reuse `local_homeomorph.piecewise` then override `to_local_equiv` to `local_equiv.disjoint_union`. This way we have better definitional equalities for `source` and `target`. -/ def disjoint_union (e e' : local_homeomorph α β) [∀ x, decidable (x ∈ e.source)] [∀ y, decidable (y ∈ e.target)] (Hs : disjoint e.source e'.source) (Ht : disjoint e.target e'.target) : local_homeomorph α β := (e.piecewise e' e.source e.target e.is_image_source_target (e'.is_image_source_target_of_disjoint e Hs.symm Ht.symm) (by rw [e.open_source.inter_frontier_eq, e'.open_source.inter_frontier_eq_empty_of_disjoint Hs]) (by { rw e.open_source.inter_frontier_eq, exact eq_on_empty _ _ })).replace_equiv (e.to_local_equiv.disjoint_union e'.to_local_equiv Hs Ht) (local_equiv.disjoint_union_eq_piecewise _ _ _ _).symm end piecewise section pi variables {ι : Type*} [fintype ι] {Xi Yi : ι → Type*} [Π i, topological_space (Xi i)] [Π i, topological_space (Yi i)] (ei : Π i, local_homeomorph (Xi i) (Yi i)) /-- The product of a finite family of `local_homeomorph`s. -/ @[simps to_local_equiv] def pi : local_homeomorph (Π i, Xi i) (Π i, Yi i) := { to_local_equiv := local_equiv.pi (λ i, (ei i).to_local_equiv), open_source := is_open_set_pi finite_univ $ λ i hi, (ei i).open_source, open_target := is_open_set_pi finite_univ $ λ i hi, (ei i).open_target, continuous_to_fun := continuous_on_pi.2 $ λ i, (ei i).continuous_on.comp (continuous_apply _).continuous_on (λ f hf, hf i trivial), continuous_inv_fun := continuous_on_pi.2 $ λ i, (ei i).continuous_on_symm.comp (continuous_apply _).continuous_on (λ f hf, hf i trivial) } end pi section continuity /-- Continuity within a set at a point can be read under right composition with a local homeomorphism, if the point is in its target -/ lemma continuous_within_at_iff_continuous_within_at_comp_right {f : β → γ} {s : set β} {x : β} (h : x ∈ e.target) : continuous_within_at f s x ↔ continuous_within_at (f ∘ e) (e ⁻¹' s) (e.symm x) := by simp_rw [continuous_within_at, ← @tendsto_map'_iff _ _ _ _ e, e.map_nhds_within_preimage_eq (e.map_target h), (∘), e.right_inv h] /-- Continuity at a point can be read under right composition with a local homeomorphism, if the point is in its target -/ lemma continuous_at_iff_continuous_at_comp_right {f : β → γ} {x : β} (h : x ∈ e.target) : continuous_at f x ↔ continuous_at (f ∘ e) (e.symm x) := by rw [← continuous_within_at_univ, e.continuous_within_at_iff_continuous_within_at_comp_right h, preimage_univ, continuous_within_at_univ] /-- A function is continuous on a set if and only if its composition with a local homeomorphism on the right is continuous on the corresponding set. -/ lemma continuous_on_iff_continuous_on_comp_right {f : β → γ} {s : set β} (h : s ⊆ e.target) : continuous_on f s ↔ continuous_on (f ∘ e) (e.source ∩ e ⁻¹' s) := begin simp only [← e.symm_image_eq_source_inter_preimage h, continuous_on, ball_image_iff], refine forall₂_congr (λ x hx, _), rw [e.continuous_within_at_iff_continuous_within_at_comp_right (h hx), e.symm_image_eq_source_inter_preimage h, inter_comm, continuous_within_at_inter], exact is_open.mem_nhds e.open_source (e.map_target (h hx)) end /-- Continuity within a set at a point can be read under left composition with a local homeomorphism if a neighborhood of the initial point is sent to the source of the local homeomorphism-/ lemma continuous_within_at_iff_continuous_within_at_comp_left {f : γ → α} {s : set γ} {x : γ} (hx : f x ∈ e.source) (h : f ⁻¹' e.source ∈ 𝓝[s] x) : continuous_within_at f s x ↔ continuous_within_at (e ∘ f) s x := begin refine ⟨(e.continuous_at hx).tendsto.comp, λ fe_cont, _⟩, rw [← continuous_within_at_inter' h] at fe_cont ⊢, have : continuous_within_at (e.symm ∘ (e ∘ f)) (s ∩ f ⁻¹' e.source) x, { have : continuous_within_at e.symm univ (e (f x)) := (e.continuous_at_symm (e.map_source hx)).continuous_within_at, exact continuous_within_at.comp this fe_cont (subset_univ _) }, exact this.congr (λy hy, by simp [e.left_inv hy.2]) (by simp [e.left_inv hx]) end /-- Continuity at a point can be read under left composition with a local homeomorphism if a neighborhood of the initial point is sent to the source of the local homeomorphism-/ lemma continuous_at_iff_continuous_at_comp_left {f : γ → α} {x : γ} (h : f ⁻¹' e.source ∈ 𝓝 x) : continuous_at f x ↔ continuous_at (e ∘ f) x := begin have hx : f x ∈ e.source := (mem_of_mem_nhds h : _), have h' : f ⁻¹' e.source ∈ 𝓝[univ] x, by rwa nhds_within_univ, rw [← continuous_within_at_univ, ← continuous_within_at_univ, e.continuous_within_at_iff_continuous_within_at_comp_left hx h'] end /-- A function is continuous on a set if and only if its composition with a local homeomorphism on the left is continuous on the corresponding set. -/ lemma continuous_on_iff_continuous_on_comp_left {f : γ → α} {s : set γ} (h : s ⊆ f ⁻¹' e.source) : continuous_on f s ↔ continuous_on (e ∘ f) s := forall₂_congr $ λ x hx, e.continuous_within_at_iff_continuous_within_at_comp_left (h hx) (mem_of_superset self_mem_nhds_within h) end continuity /-- A local homeomrphism defines a homeomorphism between its source and target. -/ def to_homeomorph_source_target : e.source ≃ₜ e.target := { to_fun := e.maps_to.restrict _ _ _, inv_fun := e.symm_maps_to.restrict _ _ _, left_inv := λ x, subtype.eq $ e.left_inv x.2, right_inv := λ x, subtype.eq $ e.right_inv x.2, continuous_to_fun := continuous_subtype_mk _ $ continuous_on_iff_continuous_restrict.1 e.continuous_on, continuous_inv_fun := continuous_subtype_mk _ $ continuous_on_iff_continuous_restrict.1 e.symm.continuous_on } lemma second_countable_topology_source [second_countable_topology β] (e : local_homeomorph α β) : second_countable_topology e.source := e.to_homeomorph_source_target.second_countable_topology /-- If a local homeomorphism has source and target equal to univ, then it induces a homeomorphism between the whole spaces, expressed in this definition. -/ @[simps apply symm_apply (mfld_cfg)] def to_homeomorph_of_source_eq_univ_target_eq_univ (h : e.source = (univ : set α)) (h' : e.target = univ) : α ≃ₜ β := { to_fun := e, inv_fun := e.symm, left_inv := λx, e.left_inv $ by { rw h, exact mem_univ _ }, right_inv := λx, e.right_inv $ by { rw h', exact mem_univ _ }, continuous_to_fun := begin rw [continuous_iff_continuous_on_univ], convert e.continuous_to_fun, rw h end, continuous_inv_fun := begin rw [continuous_iff_continuous_on_univ], convert e.continuous_inv_fun, rw h' end } /-- A local homeomorphism whose source is all of `α` defines an open embedding of `α` into `β`. The converse is also true; see `open_embedding.to_local_homeomorph`. -/ lemma to_open_embedding (h : e.source = set.univ) : open_embedding e := begin apply open_embedding_of_continuous_injective_open, { apply continuous_iff_continuous_on_univ.mpr, rw ← h, exact e.continuous_to_fun }, { apply set.injective_iff_inj_on_univ.mpr, rw ← h, exact e.inj_on }, { intros U hU, simpa only [h, subset_univ] with mfld_simps using e.image_open_of_open hU} end end local_homeomorph namespace homeomorph variables (e : α ≃ₜ β) (e' : β ≃ₜ γ) /- Register as simp lemmas that the fields of a local homeomorphism built from a homeomorphism correspond to the fields of the original homeomorphism. -/ attribute [simps apply source target {simp_rhs := tt, .. mfld_cfg}] to_local_homeomorph @[simp, mfld_simps] lemma to_local_homeomorph_coe_symm : (e.to_local_homeomorph.symm : β → α) = e.symm := rfl @[simp, mfld_simps] lemma refl_to_local_homeomorph : (homeomorph.refl α).to_local_homeomorph = local_homeomorph.refl α := rfl @[simp, mfld_simps] lemma symm_to_local_homeomorph : e.symm.to_local_homeomorph = e.to_local_homeomorph.symm := rfl @[simp, mfld_simps] lemma trans_to_local_homeomorph : (e.trans e').to_local_homeomorph = e.to_local_homeomorph.trans e'.to_local_homeomorph := local_homeomorph.eq_of_local_equiv_eq $ equiv.trans_to_local_equiv _ _ end homeomorph namespace open_embedding variables (f : α → β) (h : open_embedding f) /-- An open embedding of `α` into `β`, with `α` nonempty, defines a local homeomorphism whose source is all of `α`. The converse is also true; see `local_homeomorph.to_open_embedding`. -/ @[simps apply source target (mfld_cfg)] noncomputable def to_local_homeomorph [nonempty α] : local_homeomorph α β := local_homeomorph.of_continuous_open ((h.to_embedding.inj.inj_on univ).to_local_equiv _ _) h.continuous.continuous_on h.is_open_map is_open_univ lemma continuous_at_iff {f : α → β} {g : β → γ} (hf : open_embedding f) {x : α} : continuous_at (g ∘ f) x ↔ continuous_at g (f x) := begin haveI : nonempty α := ⟨x⟩, convert (((hf.to_local_homeomorph f).continuous_at_iff_continuous_at_comp_right) _).symm, { apply (local_homeomorph.left_inv _ _).symm, simp, }, { simp, }, end end open_embedding namespace topological_space.opens open topological_space variables (s : opens α) [nonempty s] /-- The inclusion of an open subset `s` of a space `α` into `α` is a local homeomorphism from the subtype `s` to `α`. -/ noncomputable def local_homeomorph_subtype_coe : local_homeomorph s α := open_embedding.to_local_homeomorph _ s.2.open_embedding_subtype_coe @[simp, mfld_simps] lemma local_homeomorph_subtype_coe_coe : (s.local_homeomorph_subtype_coe : s → α) = coe := rfl @[simp, mfld_simps] lemma local_homeomorph_subtype_coe_source : s.local_homeomorph_subtype_coe.source = set.univ := rfl @[simp, mfld_simps] lemma local_homeomorph_subtype_coe_target : s.local_homeomorph_subtype_coe.target = s := by { simp only [local_homeomorph_subtype_coe, subtype.range_coe_subtype] with mfld_simps, refl } end topological_space.opens namespace local_homeomorph open topological_space variables (e : local_homeomorph α β) variables (s : opens α) [nonempty s] /-- The restriction of a local homeomorphism `e` to an open subset `s` of the domain type produces a local homeomorphism whose domain is the subtype `s`.-/ noncomputable def subtype_restr : local_homeomorph s β := s.local_homeomorph_subtype_coe.trans e lemma subtype_restr_def : e.subtype_restr s = s.local_homeomorph_subtype_coe.trans e := rfl @[simp, mfld_simps] lemma subtype_restr_coe : ((e.subtype_restr s : local_homeomorph s β) : s → β) = set.restrict (e : α → β) s := rfl @[simp, mfld_simps] lemma subtype_restr_source : (e.subtype_restr s).source = coe ⁻¹' e.source := by simp only [subtype_restr_def] with mfld_simps /- This lemma characterizes the transition functions of an open subset in terms of the transition functions of the original space. -/ lemma subtype_restr_symm_trans_subtype_restr (f f' : local_homeomorph α β) : (f.subtype_restr s).symm.trans (f'.subtype_restr s) ≈ (f.symm.trans f').restr (f.target ∩ (f.symm) ⁻¹' s) := begin simp only [subtype_restr_def, trans_symm_eq_symm_trans_symm], have openness₁ : is_open (f.target ∩ f.symm ⁻¹' s) := f.preimage_open_of_open_symm s.2, rw [← of_set_trans _ openness₁, ← trans_assoc, ← trans_assoc], refine eq_on_source.trans' _ (eq_on_source_refl _), -- f' has been eliminated !!! have sets_identity : f.symm.source ∩ (f.target ∩ (f.symm) ⁻¹' s) = f.symm.source ∩ f.symm ⁻¹' s, { mfld_set_tac }, have openness₂ : is_open (s : set α) := s.2, rw [of_set_trans', sets_identity, ← trans_of_set' _ openness₂, trans_assoc], refine eq_on_source.trans' (eq_on_source_refl _) _, -- f has been eliminated !!! refine setoid.trans (trans_symm_self s.local_homeomorph_subtype_coe) _, simp only with mfld_simps, end end local_homeomorph
3663cef8e6ec2920de767837839d5110fe29f18f
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/asymptotics/superpolynomial_decay.lean
4a9f43f38c4e6dc61155a0fbd4f1875748fa3926
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
15,021
lean
/- Copyright (c) 2021 Devon Tuma. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Devon Tuma -/ import analysis.asymptotics.asymptotics import analysis.normed.order.basic import data.polynomial.eval import topology.algebra.order.liminf_limsup /-! # Super-Polynomial Function Decay This file defines a predicate `asymptotics.superpolynomial_decay f` for a function satisfying one of following equivalent definitions (The definition is in terms of the first condition): * `x ^ n * f` tends to `𝓝 0` for all (or sufficiently large) naturals `n` * `|x ^ n * f|` tends to `𝓝 0` for all naturals `n` (`superpolynomial_decay_iff_abs_tendsto_zero`) * `|x ^ n * f|` is bounded for all naturals `n` (`superpolynomial_decay_iff_abs_is_bounded_under`) * `f` is `o(x ^ c)` for all integers `c` (`superpolynomial_decay_iff_is_o`) * `f` is `O(x ^ c)` for all integers `c` (`superpolynomial_decay_iff_is_O`) These conditions are all equivalent to conditions in terms of polynomials, replacing `x ^ c` with `p(x)` or `p(x)⁻¹` as appropriate, since asymptotically `p(x)` behaves like `X ^ p.nat_degree`. These further equivalences are not proven in mathlib but would be good future projects. The definition of superpolynomial decay for `f : α → β` is relative to a parameter `k : α → β`. Super-polynomial decay then means `f x` decays faster than `(k x) ^ c` for all integers `c`. Equivalently `f x` decays faster than `p.eval (k x)` for all polynomials `p : β[X]`. The definition is also relative to a filter `l : filter α` where the decay rate is compared. When the map `k` is given by `n ↦ ↑n : ℕ → ℝ` this defines negligible functions: https://en.wikipedia.org/wiki/Negligible_function When the map `k` is given by `(r₁,...,rₙ) ↦ r₁*...*rₙ : ℝⁿ → ℝ` this is equivalent to the definition of rapidly decreasing functions given here: https://ncatlab.org/nlab/show/rapidly+decreasing+function # Main Theorems * `superpolynomial_decay.polynomial_mul` says that if `f(x)` is negligible, then so is `p(x) * f(x)` for any polynomial `p`. * `superpolynomial_decay_iff_zpow_tendsto_zero` gives an equivalence between definitions in terms of decaying faster than `k(x) ^ n` for all naturals `n` or `k(x) ^ c` for all integer `c`. -/ namespace asymptotics open_locale topological_space polynomial open filter /-- `f` has superpolynomial decay in parameter `k` along filter `l` if `k ^ n * f` tends to zero at `l` for all naturals `n` -/ def superpolynomial_decay {α β : Type*} [topological_space β] [comm_semiring β] (l : filter α) (k : α → β) (f : α → β) := ∀ (n : ℕ), tendsto (λ (a : α), (k a) ^ n * f a) l (𝓝 0) variables {α β : Type*} {l : filter α} {k : α → β} {f g g' : α → β} section comm_semiring variables [topological_space β] [comm_semiring β] lemma superpolynomial_decay.congr' (hf : superpolynomial_decay l k f) (hfg : f =ᶠ[l] g) : superpolynomial_decay l k g := λ z, (hf z).congr' (eventually_eq.mul (eventually_eq.refl l _) hfg) lemma superpolynomial_decay.congr (hf : superpolynomial_decay l k f) (hfg : ∀ x, f x = g x) : superpolynomial_decay l k g := λ z, (hf z).congr (λ x, congr_arg (λ a, k x ^ z * a) $ hfg x) @[simp] lemma superpolynomial_decay_zero (l : filter α) (k : α → β) : superpolynomial_decay l k 0 := λ z, by simpa only [pi.zero_apply, mul_zero] using tendsto_const_nhds lemma superpolynomial_decay.add [has_continuous_add β] (hf : superpolynomial_decay l k f) (hg : superpolynomial_decay l k g) : superpolynomial_decay l k (f + g) := λ z, by simpa only [mul_add, add_zero, pi.add_apply] using (hf z).add (hg z) lemma superpolynomial_decay.mul [has_continuous_mul β] (hf : superpolynomial_decay l k f) (hg : superpolynomial_decay l k g) : superpolynomial_decay l k (f * g) := λ z, by simpa only [mul_assoc, one_mul, mul_zero, pow_zero] using (hf z).mul (hg 0) lemma superpolynomial_decay.mul_const [has_continuous_mul β] (hf : superpolynomial_decay l k f) (c : β) : superpolynomial_decay l k (λ n, f n * c) := λ z, by simpa only [←mul_assoc, zero_mul] using tendsto.mul_const c (hf z) lemma superpolynomial_decay.const_mul [has_continuous_mul β] (hf : superpolynomial_decay l k f) (c : β) : superpolynomial_decay l k (λ n, c * f n) := (hf.mul_const c).congr (λ _, mul_comm _ _) lemma superpolynomial_decay.param_mul (hf : superpolynomial_decay l k f) : superpolynomial_decay l k (k * f) := λ z, tendsto_nhds.2 (λ s hs hs0, l.sets_of_superset ((tendsto_nhds.1 (hf $ z + 1)) s hs hs0) (λ x hx, by simpa only [set.mem_preimage, pi.mul_apply, ← mul_assoc, ← pow_succ'] using hx)) lemma superpolynomial_decay.mul_param (hf : superpolynomial_decay l k f) : superpolynomial_decay l k (f * k) := (hf.param_mul).congr (λ _, mul_comm _ _) lemma superpolynomial_decay.param_pow_mul (hf : superpolynomial_decay l k f) (n : ℕ) : superpolynomial_decay l k (k ^ n * f) := begin induction n with n hn, { simpa only [one_mul, pow_zero] using hf }, { simpa only [pow_succ, mul_assoc] using hn.param_mul } end lemma superpolynomial_decay.mul_param_pow (hf : superpolynomial_decay l k f) (n : ℕ) : superpolynomial_decay l k (f * k ^ n) := (hf.param_pow_mul n).congr (λ _, mul_comm _ _) lemma superpolynomial_decay.polynomial_mul [has_continuous_add β] [has_continuous_mul β] (hf : superpolynomial_decay l k f) (p : β[X]) : superpolynomial_decay l k (λ x, (p.eval $ k x) * f x) := polynomial.induction_on' p (λ p q hp hq, by simpa [add_mul] using hp.add hq) (λ n c, by simpa [mul_assoc] using (hf.param_pow_mul n).const_mul c) lemma superpolynomial_decay.mul_polynomial [has_continuous_add β] [has_continuous_mul β] (hf : superpolynomial_decay l k f) (p : β[X]) : superpolynomial_decay l k (λ x, f x * (p.eval $ k x)) := (hf.polynomial_mul p).congr (λ _, mul_comm _ _) end comm_semiring section ordered_comm_semiring variables [topological_space β] [ordered_comm_semiring β] [order_topology β] lemma superpolynomial_decay.trans_eventually_le (hk : 0 ≤ᶠ[l] k) (hg : superpolynomial_decay l k g) (hg' : superpolynomial_decay l k g') (hfg : g ≤ᶠ[l] f) (hfg' : f ≤ᶠ[l] g') : superpolynomial_decay l k f := λ z, tendsto_of_tendsto_of_tendsto_of_le_of_le' (hg z) (hg' z) (hfg.mp (hk.mono $ λ x hx hx', mul_le_mul_of_nonneg_left hx' (pow_nonneg hx z))) (hfg'.mp (hk.mono $ λ x hx hx', mul_le_mul_of_nonneg_left hx' (pow_nonneg hx z))) end ordered_comm_semiring section linear_ordered_comm_ring variables [topological_space β] [linear_ordered_comm_ring β] [order_topology β] variables (l k f) lemma superpolynomial_decay_iff_abs_tendsto_zero : superpolynomial_decay l k f ↔ ∀ (n : ℕ), tendsto (λ (a : α), |(k a) ^ n * f a|) l (𝓝 0) := ⟨λ h z, (tendsto_zero_iff_abs_tendsto_zero _).1 (h z), λ h z, (tendsto_zero_iff_abs_tendsto_zero _).2 (h z)⟩ lemma superpolynomial_decay_iff_superpolynomial_decay_abs : superpolynomial_decay l k f ↔ superpolynomial_decay l (λ a, |k a|) (λ a, |f a|) := (superpolynomial_decay_iff_abs_tendsto_zero l k f).trans (by simp_rw [superpolynomial_decay, abs_mul, abs_pow]) variables {l k f} lemma superpolynomial_decay.trans_eventually_abs_le (hf : superpolynomial_decay l k f) (hfg : abs ∘ g ≤ᶠ[l] abs ∘ f) : superpolynomial_decay l k g := begin rw superpolynomial_decay_iff_abs_tendsto_zero at hf ⊢, refine λ z, tendsto_of_tendsto_of_tendsto_of_le_of_le' (tendsto_const_nhds) (hf z) (eventually_of_forall $ λ x, abs_nonneg _) (hfg.mono $ λ x hx, _), calc |k x ^ z * g x| = |k x ^ z| * |g x| : abs_mul (k x ^ z) (g x) ... ≤ |k x ^ z| * |f x| : mul_le_mul le_rfl hx (abs_nonneg _) (abs_nonneg _) ... = |k x ^ z * f x| : (abs_mul (k x ^ z) (f x)).symm, end lemma superpolynomial_decay.trans_abs_le (hf : superpolynomial_decay l k f) (hfg : ∀ x, |g x| ≤ |f x|) : superpolynomial_decay l k g := hf.trans_eventually_abs_le (eventually_of_forall hfg) end linear_ordered_comm_ring section field variables [topological_space β] [field β] (l k f) lemma superpolynomial_decay_mul_const_iff [has_continuous_mul β] {c : β} (hc0 : c ≠ 0) : superpolynomial_decay l k (λ n, f n * c) ↔ superpolynomial_decay l k f := ⟨λ h, (h.mul_const c⁻¹).congr (λ x, by simp [mul_assoc, mul_inv_cancel hc0]), λ h, h.mul_const c⟩ lemma superpolynomial_decay_const_mul_iff [has_continuous_mul β] {c : β} (hc0 : c ≠ 0) : superpolynomial_decay l k (λ n, c * f n) ↔ superpolynomial_decay l k f := ⟨λ h, (h.const_mul c⁻¹).congr (λ x, by simp [← mul_assoc, inv_mul_cancel hc0]), λ h, h.const_mul c⟩ variables {l k f} end field section linear_ordered_field variables [topological_space β] [linear_ordered_field β] [order_topology β] variable (f) lemma superpolynomial_decay_iff_abs_is_bounded_under (hk : tendsto k l at_top) : superpolynomial_decay l k f ↔ ∀ (z : ℕ), is_bounded_under (≤) l (λ (a : α), |(k a) ^ z * f a|) := begin refine ⟨λ h z, tendsto.is_bounded_under_le (tendsto.abs (h z)), λ h, (superpolynomial_decay_iff_abs_tendsto_zero l k f).2 (λ z, _)⟩, obtain ⟨m, hm⟩ := h (z + 1), have h1 : tendsto (λ (a : α), (0 : β)) l (𝓝 0) := tendsto_const_nhds, have h2 : tendsto (λ (a : α), |(k a)⁻¹| * m) l (𝓝 0) := (zero_mul m) ▸ tendsto.mul_const m ((tendsto_zero_iff_abs_tendsto_zero _).1 hk.inv_tendsto_at_top), refine tendsto_of_tendsto_of_tendsto_of_le_of_le' h1 h2 (eventually_of_forall (λ x, abs_nonneg _)) ((eventually_map.1 hm).mp _), refine ((hk.eventually_ne_at_top 0).mono $ λ x hk0 hx, _), refine eq.trans_le _ (mul_le_mul_of_nonneg_left hx $ abs_nonneg (k x)⁻¹), rw [← abs_mul, ← mul_assoc, pow_succ, ← mul_assoc, inv_mul_cancel hk0, one_mul], end lemma superpolynomial_decay_iff_zpow_tendsto_zero (hk : tendsto k l at_top) : superpolynomial_decay l k f ↔ ∀ (z : ℤ), tendsto (λ (a : α), (k a) ^ z * f a) l (𝓝 0) := begin refine ⟨λ h z, _, λ h n, by simpa only [zpow_coe_nat] using h (n : ℤ)⟩, by_cases hz : 0 ≤ z, { lift z to ℕ using hz, simpa using h z }, { have : tendsto (λ a, (k a) ^ z) l (𝓝 0) := tendsto.comp (tendsto_zpow_at_top_zero (not_le.1 hz)) hk, have h : tendsto f l (𝓝 0) := by simpa using h 0, exact (zero_mul (0 : β)) ▸ this.mul h }, end variable {f} lemma superpolynomial_decay.param_zpow_mul (hk : tendsto k l at_top) (hf : superpolynomial_decay l k f) (z : ℤ) : superpolynomial_decay l k (λ a, k a ^ z * f a) := begin rw superpolynomial_decay_iff_zpow_tendsto_zero _ hk at hf ⊢, refine λ z', (hf $ z' + z).congr' ((hk.eventually_ne_at_top 0).mono (λ x hx, _)), simp [zpow_add₀ hx, mul_assoc, pi.mul_apply], end lemma superpolynomial_decay.mul_param_zpow (hk : tendsto k l at_top) (hf : superpolynomial_decay l k f) (z : ℤ) : superpolynomial_decay l k (λ a, f a * k a ^ z) := (hf.param_zpow_mul hk z).congr (λ _, mul_comm _ _) lemma superpolynomial_decay.inv_param_mul (hk : tendsto k l at_top) (hf : superpolynomial_decay l k f) : superpolynomial_decay l k (k⁻¹ * f) := by simpa using (hf.param_zpow_mul hk (-1)) lemma superpolynomial_decay.param_inv_mul (hk : tendsto k l at_top) (hf : superpolynomial_decay l k f) : superpolynomial_decay l k (f * k⁻¹) := (hf.inv_param_mul hk).congr (λ _, mul_comm _ _) variable (f) lemma superpolynomial_decay_param_mul_iff (hk : tendsto k l at_top) : superpolynomial_decay l k (k * f) ↔ superpolynomial_decay l k f := ⟨λ h, (h.inv_param_mul hk).congr' ((hk.eventually_ne_at_top 0).mono (λ x hx, by simp [← mul_assoc, inv_mul_cancel hx])), λ h, h.param_mul⟩ lemma superpolynomial_decay_mul_param_iff (hk : tendsto k l at_top) : superpolynomial_decay l k (f * k) ↔ superpolynomial_decay l k f := by simpa [mul_comm k] using superpolynomial_decay_param_mul_iff f hk lemma superpolynomial_decay_param_pow_mul_iff (hk : tendsto k l at_top) (n : ℕ) : superpolynomial_decay l k (k ^ n * f) ↔ superpolynomial_decay l k f := begin induction n with n hn, { simp }, { simpa [pow_succ, ← mul_comm k, mul_assoc, superpolynomial_decay_param_mul_iff (k ^ n * f) hk] using hn } end lemma superpolynomial_decay_mul_param_pow_iff (hk : tendsto k l at_top) (n : ℕ) : superpolynomial_decay l k (f * k ^ n) ↔ superpolynomial_decay l k f := by simpa [mul_comm f] using superpolynomial_decay_param_pow_mul_iff f hk n variable {f} end linear_ordered_field section normed_linear_ordered_field variable [normed_linear_ordered_field β] variables (l k f) lemma superpolynomial_decay_iff_norm_tendsto_zero : superpolynomial_decay l k f ↔ ∀ (n : ℕ), tendsto (λ (a : α), ‖(k a) ^ n * f a‖) l (𝓝 0) := ⟨λ h z, tendsto_zero_iff_norm_tendsto_zero.1 (h z), λ h z, tendsto_zero_iff_norm_tendsto_zero.2 (h z)⟩ lemma superpolynomial_decay_iff_superpolynomial_decay_norm : superpolynomial_decay l k f ↔ superpolynomial_decay l (λ a, ‖k a‖) (λ a, ‖f a‖) := (superpolynomial_decay_iff_norm_tendsto_zero l k f).trans (by simp [superpolynomial_decay]) variables {l k} variable [order_topology β] lemma superpolynomial_decay_iff_is_O (hk : tendsto k l at_top) : superpolynomial_decay l k f ↔ ∀ (z : ℤ), f =O[l] (λ (a : α), (k a) ^ z) := begin refine (superpolynomial_decay_iff_zpow_tendsto_zero f hk).trans _, have hk0 : ∀ᶠ x in l, k x ≠ 0 := hk.eventually_ne_at_top 0, refine ⟨λ h z, _, λ h z, _⟩, { refine is_O_of_div_tendsto_nhds (hk0.mono (λ x hx hxz, absurd (zpow_eq_zero hxz) hx)) 0 _, have : (λ (a : α), k a ^ z)⁻¹ = (λ (a : α), k a ^ (- z)) := funext (λ x, by simp), rw [div_eq_mul_inv, mul_comm f, this], exact h (-z) }, { suffices : (λ (a : α), k a ^ z * f a) =O[l] (λ (a : α), (k a)⁻¹), from is_O.trans_tendsto this hk.inv_tendsto_at_top, refine ((is_O_refl (λ a, (k a) ^ z) l).mul (h (- (z + 1)))).trans (is_O.of_bound 1 $ hk0.mono (λ a ha0, _)), simp only [one_mul, neg_add z 1, zpow_add₀ ha0, ← mul_assoc, zpow_neg, mul_inv_cancel (zpow_ne_zero z ha0), zpow_one] } end lemma superpolynomial_decay_iff_is_o (hk : tendsto k l at_top) : superpolynomial_decay l k f ↔ ∀ (z : ℤ), f =o[l] (λ (a : α), (k a) ^ z) := begin refine ⟨λ h z, _, λ h, (superpolynomial_decay_iff_is_O f hk).2 (λ z, (h z).is_O)⟩, have hk0 : ∀ᶠ x in l, k x ≠ 0 := hk.eventually_ne_at_top 0, have : (λ (x : α), (1 : β)) =o[l] k := is_o_of_tendsto' (hk0.mono (λ x hkx hkx', absurd hkx' hkx)) (by simpa using hk.inv_tendsto_at_top), have : f =o[l] (λ (x : α), k x * k x ^ (z - 1)), by simpa using this.mul_is_O (((superpolynomial_decay_iff_is_O f hk).1 h) $ z - 1), refine this.trans_is_O (is_O.of_bound 1 (hk0.mono $ λ x hkx, le_of_eq _)), rw [one_mul, zpow_sub_one₀ hkx, mul_comm (k x), mul_assoc, inv_mul_cancel hkx, mul_one], end end normed_linear_ordered_field end asymptotics
4611fcf578c8356c8493e327c3dfd924af926ec6
4727251e0cd73359b15b664c3170e5d754078599
/src/group_theory/semidirect_product.lean
3b42805cfb8986f9f574314e498efe0336340bbf
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
9,057
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 algebra.hom.aut import logic.function.basic import group_theory.subgroup.basic /-! # Semidirect product This file defines semidirect products of groups, and the canonical maps in and out of the semidirect product. The semidirect product of `N` and `G` given a hom `φ` from `G` to the automorphism group of `N` is the product of sets with the group `⟨n₁, g₁⟩ * ⟨n₂, g₂⟩ = ⟨n₁ * φ g₁ n₂, g₁ * g₂⟩` ## Key definitions There are two homs into the semidirect product `inl : N →* N ⋊[φ] G` and `inr : G →* N ⋊[φ] G`, and `lift` can be used to define maps `N ⋊[φ] G →* H` out of the semidirect product given maps `f₁ : N →* H` and `f₂ : G →* H` that satisfy the condition `∀ n g, f₁ (φ g n) = f₂ g * f₁ n * f₂ g⁻¹` ## Notation This file introduces the global notation `N ⋊[φ] G` for `semidirect_product N G φ` ## Tags group, semidirect product -/ variables (N : Type*) (G : Type*) {H : Type*} [group N] [group G] [group H] /-- The semidirect product of groups `N` and `G`, given a map `φ` from `G` to the automorphism group of `N`. It the product of sets with the group operation `⟨n₁, g₁⟩ * ⟨n₂, g₂⟩ = ⟨n₁ * φ g₁ n₂, g₁ * g₂⟩` -/ @[ext, derive decidable_eq] structure semidirect_product (φ : G →* mul_aut N) := (left : N) (right : G) attribute [pp_using_anonymous_constructor] semidirect_product notation N` ⋊[`:35 φ:35`] `:0 G :35 := semidirect_product N G φ namespace semidirect_product variables {N G} {φ : G →* mul_aut N} private def one_aux : N ⋊[φ] G := ⟨1, 1⟩ private def mul_aux (a b : N ⋊[φ] G) : N ⋊[φ] G := ⟨a.1 * φ a.2 b.1, a.right * b.right⟩ private def inv_aux (a : N ⋊[φ] G) : N ⋊[φ] G := let i := a.2⁻¹ in ⟨φ i a.1⁻¹, i⟩ private lemma mul_assoc_aux (a b c : N ⋊[φ] G) : mul_aux (mul_aux a b) c = mul_aux a (mul_aux b c) := by simp [mul_aux, mul_assoc, mul_equiv.map_mul] private lemma mul_one_aux (a : N ⋊[φ] G) : mul_aux a one_aux = a := by cases a; simp [mul_aux, one_aux] private lemma one_mul_aux (a : N ⋊[φ] G) : mul_aux one_aux a = a := by cases a; simp [mul_aux, one_aux] private lemma mul_left_inv_aux (a : N ⋊[φ] G) : mul_aux (inv_aux a) a = one_aux := by simp only [mul_aux, inv_aux, one_aux, ← mul_equiv.map_mul, mul_left_inv]; simp instance : group (N ⋊[φ] G) := { one := one_aux, inv := inv_aux, mul := mul_aux, mul_assoc := mul_assoc_aux, one_mul := one_mul_aux, mul_one := mul_one_aux, mul_left_inv := mul_left_inv_aux } instance : inhabited (N ⋊[φ] G) := ⟨1⟩ @[simp] lemma one_left : (1 : N ⋊[φ] G).left = 1 := rfl @[simp] lemma one_right : (1 : N ⋊[φ] G).right = 1 := rfl @[simp] lemma inv_left (a : N ⋊[φ] G) : (a⁻¹).left = φ a.right⁻¹ a.left⁻¹ := rfl @[simp] lemma inv_right (a : N ⋊[φ] G) : (a⁻¹).right = a.right⁻¹ := rfl @[simp] lemma mul_left (a b : N ⋊[φ] G) : (a * b).left = a.left * φ a.right b.left := rfl @[simp] lemma mul_right (a b : N ⋊[φ] G) : (a * b).right = a.right * b.right := rfl /-- The canonical map `N →* N ⋊[φ] G` sending `n` to `⟨n, 1⟩` -/ def inl : N →* N ⋊[φ] G := { to_fun := λ n, ⟨n, 1⟩, map_one' := rfl, map_mul' := by intros; ext; simp } @[simp] lemma left_inl (n : N) : (inl n : N ⋊[φ] G).left = n := rfl @[simp] lemma right_inl (n : N) : (inl n : N ⋊[φ] G).right = 1 := rfl lemma inl_injective : function.injective (inl : N → N ⋊[φ] G) := function.injective_iff_has_left_inverse.2 ⟨left, left_inl⟩ @[simp] lemma inl_inj {n₁ n₂ : N} : (inl n₁ : N ⋊[φ] G) = inl n₂ ↔ n₁ = n₂ := inl_injective.eq_iff /-- The canonical map `G →* N ⋊[φ] G` sending `g` to `⟨1, g⟩` -/ def inr : G →* N ⋊[φ] G := { to_fun := λ g, ⟨1, g⟩, map_one' := rfl, map_mul' := by intros; ext; simp } @[simp] lemma left_inr (g : G) : (inr g : N ⋊[φ] G).left = 1 := rfl @[simp] lemma right_inr (g : G) : (inr g : N ⋊[φ] G).right = g := rfl lemma inr_injective : function.injective (inr : G → N ⋊[φ] G) := function.injective_iff_has_left_inverse.2 ⟨right, right_inr⟩ @[simp] lemma inr_inj {g₁ g₂ : G} : (inr g₁ : N ⋊[φ] G) = inr g₂ ↔ g₁ = g₂ := inr_injective.eq_iff lemma inl_aut (g : G) (n : N) : (inl (φ g n) : N ⋊[φ] G) = inr g * inl n * inr g⁻¹ := by ext; simp lemma inl_aut_inv (g : G) (n : N) : (inl ((φ g)⁻¹ n) : N ⋊[φ] G) = inr g⁻¹ * inl n * inr g := by rw [← monoid_hom.map_inv, inl_aut, inv_inv] @[simp] lemma mk_eq_inl_mul_inr (g : G) (n : N) : (⟨n, g⟩ : N ⋊[φ] G) = inl n * inr g := by ext; simp @[simp] lemma inl_left_mul_inr_right (x : N ⋊[φ] G) : inl x.left * inr x.right = x := by ext; simp /-- The canonical projection map `N ⋊[φ] G →* G`, as a group hom. -/ def right_hom : N ⋊[φ] G →* G := { to_fun := semidirect_product.right, map_one' := rfl, map_mul' := λ _ _, rfl } @[simp] lemma right_hom_eq_right : (right_hom : N ⋊[φ] G → G) = right := rfl @[simp] lemma right_hom_comp_inl : (right_hom : N ⋊[φ] G →* G).comp inl = 1 := by ext; simp [right_hom] @[simp] lemma right_hom_comp_inr : (right_hom : N ⋊[φ] G →* G).comp inr = monoid_hom.id _ := by ext; simp [right_hom] @[simp] lemma right_hom_inl (n : N) : right_hom (inl n : N ⋊[φ] G) = 1 := by simp [right_hom] @[simp] lemma right_hom_inr (g : G) : right_hom (inr g : N ⋊[φ] G) = g := by simp [right_hom] lemma right_hom_surjective : function.surjective (right_hom : N ⋊[φ] G → G) := function.surjective_iff_has_right_inverse.2 ⟨inr, right_hom_inr⟩ lemma range_inl_eq_ker_right_hom : (inl : N →* N ⋊[φ] G).range = right_hom.ker := le_antisymm (λ _, by simp [monoid_hom.mem_ker, eq_comm] {contextual := tt}) (λ x hx, ⟨x.left, by ext; simp [*, monoid_hom.mem_ker] at *⟩) section lift variables (f₁ : N →* H) (f₂ : G →* H) (h : ∀ g, f₁.comp (φ g).to_monoid_hom = (mul_aut.conj (f₂ g)).to_monoid_hom.comp f₁) /-- Define a group hom `N ⋊[φ] G →* H`, by defining maps `N →* H` and `G →* H` -/ def lift (f₁ : N →* H) (f₂ : G →* H) (h : ∀ g, f₁.comp (φ g).to_monoid_hom = (mul_aut.conj (f₂ g)).to_monoid_hom.comp f₁) : N ⋊[φ] G →* H := { to_fun := λ a, f₁ a.1 * f₂ a.2, map_one' := by simp, map_mul' := λ a b, begin have := λ n g, monoid_hom.ext_iff.1 (h n) g, simp only [mul_aut.conj_apply, monoid_hom.comp_apply, mul_equiv.coe_to_monoid_hom] at this, simp [this, mul_assoc] end } @[simp] lemma lift_inl (n : N) : lift f₁ f₂ h (inl n) = f₁ n := by simp [lift] @[simp] lemma lift_comp_inl : (lift f₁ f₂ h).comp inl = f₁ := by ext; simp @[simp] lemma lift_inr (g : G) : lift f₁ f₂ h (inr g) = f₂ g := by simp [lift] @[simp] lemma lift_comp_inr : (lift f₁ f₂ h).comp inr = f₂ := by ext; simp lemma lift_unique (F : N ⋊[φ] G →* H) : F = lift (F.comp inl) (F.comp inr) (λ _, by ext; simp [inl_aut]) := begin ext, simp only [lift, monoid_hom.comp_apply, monoid_hom.coe_mk], rw [← F.map_mul, inl_left_mul_inr_right], end /-- Two maps out of the semidirect product are equal if they're equal after composition with both `inl` and `inr` -/ lemma hom_ext {f g : (N ⋊[φ] G) →* H} (hl : f.comp inl = g.comp inl) (hr : f.comp inr = g.comp inr) : f = g := by { rw [lift_unique f, lift_unique g], simp only * } end lift section map variables {N₁ : Type*} {G₁ : Type*} [group N₁] [group G₁] {φ₁ : G₁ →* mul_aut N₁} /-- Define a map from `N ⋊[φ] G` to `N₁ ⋊[φ₁] G₁` given maps `N →* N₁` and `G →* G₁` that satisfy a commutativity condition `∀ n g, f₁ (φ g n) = φ₁ (f₂ g) (f₁ n)`. -/ def map (f₁ : N →* N₁) (f₂ : G →* G₁) (h : ∀ g : G, f₁.comp (φ g).to_monoid_hom = (φ₁ (f₂ g)).to_monoid_hom.comp f₁) : N ⋊[φ] G →* N₁ ⋊[φ₁] G₁ := { to_fun := λ x, ⟨f₁ x.1, f₂ x.2⟩, map_one' := by simp, map_mul' := λ x y, begin replace h := monoid_hom.ext_iff.1 (h x.right) y.left, ext; simp * at *, end } variables (f₁ : N →* N₁) (f₂ : G →* G₁) (h : ∀ g : G, f₁.comp (φ g).to_monoid_hom = (φ₁ (f₂ g)).to_monoid_hom.comp f₁) @[simp] lemma map_left (g : N ⋊[φ] G) : (map f₁ f₂ h g).left = f₁ g.left := rfl @[simp] lemma map_right (g : N ⋊[φ] G) : (map f₁ f₂ h g).right = f₂ g.right := rfl @[simp] lemma right_hom_comp_map : right_hom.comp (map f₁ f₂ h) = f₂.comp right_hom := rfl @[simp] lemma map_inl (n : N) : map f₁ f₂ h (inl n) = inl (f₁ n) := by simp [map] @[simp] lemma map_comp_inl : (map f₁ f₂ h).comp inl = inl.comp f₁ := by ext; simp @[simp] lemma map_inr (g : G) : map f₁ f₂ h (inr g) = inr (f₂ g) := by simp [map] @[simp] lemma map_comp_inr : (map f₁ f₂ h).comp inr = inr.comp f₂ := by ext; simp [map] end map end semidirect_product
a9f012ef5f0d1f8959b55503e7fee1fa92c2471a
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebraic_topology/alternating_face_map_complex.lean
2a571c2195c973923bbc930b3ee33beab1422364
[ "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
11,440
lean
/- Copyright (c) 2021 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou, Adam Topaz, Johan Commelin -/ import algebra.homology.additive import algebraic_topology.Moore_complex import algebra.big_operators.fin import category_theory.preadditive.opposite /-! # The alternating face map complex of a simplicial object in a preadditive category We construct the alternating face map complex, as a functor `alternating_face_map_complex : simplicial_object C ⥤ chain_complex C ℕ` for any preadditive category `C`. For any simplicial object `X` in `C`, this is the homological complex `... → X_2 → X_1 → X_0` where the differentials are alternating sums of faces. The dual version `alternating_coface_map_complex : cosimplicial_object C ⥤ cochain_complex C ℕ` is also constructed. We also construct the natural transformation `inclusion_of_Moore_complex : normalized_Moore_complex A ⟶ alternating_face_map_complex A` when `A` is an abelian category. ## References * https://stacks.math.columbia.edu/tag/0194 * https://ncatlab.org/nlab/show/Moore+complex -/ open category_theory category_theory.limits category_theory.subobject open category_theory.preadditive category_theory.category open opposite open_locale big_operators open_locale simplicial noncomputable theory namespace algebraic_topology namespace alternating_face_map_complex /-! ## Construction of the alternating face map complex -/ variables {C : Type*} [category C] [preadditive C] variables (X : simplicial_object C) variables (Y : simplicial_object C) /-- The differential on the alternating face map complex is the alternate sum of the face maps -/ @[simp] def obj_d (n : ℕ) : X _[n+1] ⟶ X _[n] := ∑ (i : fin (n+2)), (-1 : ℤ)^(i : ℕ) • X.δ i /-- ## The chain complex relation `d ≫ d` -/ lemma d_squared (n : ℕ) : obj_d X (n+1) ≫ obj_d X n = 0 := begin /- we start by expanding d ≫ d as a double sum -/ dsimp, rw comp_sum, let d_l := λ (j : fin (n+3)), (-1 : ℤ)^(j : ℕ) • X.δ j, let d_r := λ (i : fin (n+2)), (-1 : ℤ)^(i : ℕ) • X.δ i, rw [show (λ i , (∑ j : fin (n+3), d_l j) ≫ d_r i) = (λ i, ∑ j : fin (n+3), (d_l j ≫ d_r i)), by { ext i, rw sum_comp, }], rw ← finset.sum_product', /- then, we decompose the index set P into a subet S and its complement Sᶜ -/ let P := fin (n+2) × fin (n+3), let S := finset.univ.filter (λ (ij : P), (ij.2 : ℕ) ≤ (ij.1 : ℕ)), let term := λ (ij : P), d_l ij.2 ≫ d_r ij.1, erw [show ∑ (ij : P), term ij = (∑ ij in S, term ij) + (∑ ij in Sᶜ, term ij), by rw finset.sum_add_sum_compl], rw [← eq_neg_iff_add_eq_zero, ← finset.sum_neg_distrib], /- we are reduced to showing that two sums are equal, and this is obtained by constructing a bijection φ : S -> Sᶜ, which maps (i,j) to (j,i+1), and by comparing the terms -/ let φ : Π (ij : P), ij ∈ S → P := λ ij hij, (fin.cast_lt ij.2 (lt_of_le_of_lt (finset.mem_filter.mp hij).right (fin.is_lt ij.1)), ij.1.succ), apply finset.sum_bij φ, { -- φ(S) is contained in Sᶜ intros ij hij, simp only [finset.mem_univ, finset.compl_filter, finset.mem_filter, true_and, fin.coe_succ, fin.coe_cast_lt] at hij ⊢, linarith, }, { /- identification of corresponding terms in both sums -/ rintro ⟨i, j⟩ hij, simp only [term, d_l, d_r, φ, comp_zsmul, zsmul_comp, ← neg_smul, ← mul_smul, pow_add, neg_mul, mul_one, fin.coe_cast_lt, fin.coe_succ, pow_one, mul_neg, neg_neg], let jj : fin (n+2) := (φ (i,j) hij).1, have ineq : jj ≤ i, { rw ← fin.coe_fin_le, simpa using hij, }, rw [category_theory.simplicial_object.δ_comp_δ X ineq, fin.cast_succ_cast_lt, mul_comm] }, { -- φ : S → Sᶜ is injective rintro ⟨i, j⟩ ⟨i', j'⟩ hij hij' h, rw [prod.mk.inj_iff], refine ⟨by simpa using congr_arg prod.snd h, _⟩, have h1 := congr_arg fin.cast_succ (congr_arg prod.fst h), simpa [fin.cast_succ_cast_lt] using h1 }, { -- φ : S → Sᶜ is surjective rintro ⟨i', j'⟩ hij', simp only [true_and, finset.mem_univ, finset.compl_filter, not_le, finset.mem_filter] at hij', refine ⟨(j'.pred _, fin.cast_succ i'), _, _⟩, { intro H, simpa only [H, nat.not_lt_zero, fin.coe_zero] using hij' }, { simpa only [true_and, finset.mem_univ, fin.coe_cast_succ, fin.coe_pred, finset.mem_filter] using nat.le_pred_of_lt hij', }, { simp only [prod.mk.inj_iff, fin.succ_pred, fin.cast_lt_cast_succ], split; refl }, }, end /-! ## Construction of the alternating face map complex functor -/ /-- The alternating face map complex, on objects -/ def obj : chain_complex C ℕ := chain_complex.of (λ n, X _[n]) (obj_d X) (d_squared X) @[simp] lemma obj_X (X : simplicial_object C) (n : ℕ) : (alternating_face_map_complex.obj X).X n = X _[n] := rfl @[simp] lemma obj_d_eq (X : simplicial_object C) (n : ℕ) : (alternating_face_map_complex.obj X).d (n+1) n = ∑ (i : fin (n+2)), (-1 : ℤ)^(i : ℕ) • X.δ i := by apply chain_complex.of_d variables {X} {Y} /-- The alternating face map complex, on morphisms -/ def map (f : X ⟶ Y) : obj X ⟶ obj Y := chain_complex.of_hom _ _ _ _ _ _ (λ n, f.app (op [n])) (λ n, begin dsimp, rw [comp_sum, sum_comp], apply finset.sum_congr rfl (λ x h, _), rw [comp_zsmul, zsmul_comp], congr' 1, symmetry, apply f.naturality, end) @[simp] lemma map_f (f : X ⟶ Y) (n : ℕ) : (map f).f n = f.app (op [n]) := rfl end alternating_face_map_complex variables (C : Type*) [category C] [preadditive C] /-- The alternating face map complex, as a functor -/ def alternating_face_map_complex : simplicial_object C ⥤ chain_complex C ℕ := { obj := alternating_face_map_complex.obj, map := λ X Y f, alternating_face_map_complex.map f } variable {C} @[simp] lemma alternating_face_map_complex_obj_X (X : simplicial_object C) (n : ℕ) : ((alternating_face_map_complex C).obj X).X n = X _[n] := rfl @[simp] lemma alternating_face_map_complex_obj_d (X : simplicial_object C) (n : ℕ) : ((alternating_face_map_complex C).obj X).d (n+1) n = alternating_face_map_complex.obj_d X n := by apply chain_complex.of_d @[simp] lemma alternating_face_map_complex_map_f {X Y : simplicial_object C} (f : X ⟶ Y) (n : ℕ) : ((alternating_face_map_complex C).map f).f n = f.app (op [n]) := rfl lemma map_alternating_face_map_complex {D : Type*} [category D] [preadditive D] (F : C ⥤ D) [F.additive] : alternating_face_map_complex C ⋙ F.map_homological_complex _ = (simplicial_object.whiskering C D).obj F ⋙ alternating_face_map_complex D := begin apply category_theory.functor.ext, { intros X Y f, ext n, simp only [functor.comp_map, homological_complex.comp_f, alternating_face_map_complex_map_f, functor.map_homological_complex_map_f, homological_complex.eq_to_hom_f, eq_to_hom_refl, comp_id, id_comp, simplicial_object.whiskering_obj_map_app], }, { intro X, apply homological_complex.ext, { rintros i j (rfl : j + 1 = i), dsimp only [functor.comp_obj], simpa only [functor.map_homological_complex_obj_d, alternating_face_map_complex_obj_d, eq_to_hom_refl, id_comp, comp_id, alternating_face_map_complex.obj_d, functor.map_sum, functor.map_zsmul], }, { ext n, refl, }, }, end /-! ## Construction of the natural inclusion of the normalized Moore complex -/ variables {A : Type*} [category A] [abelian A] /-- The inclusion map of the Moore complex in the alternating face map complex -/ def inclusion_of_Moore_complex_map (X : simplicial_object A) : (normalized_Moore_complex A).obj X ⟶ (alternating_face_map_complex A).obj X := chain_complex.of_hom _ _ _ _ _ _ (λ n, (normalized_Moore_complex.obj_X X n).arrow) (λ n, begin /- we have to show the compatibility of the differentials on the alternating face map complex with those defined on the normalized Moore complex: we first get rid of the terms of the alternating sum that are obviously zero on the normalized_Moore_complex -/ simp only [alternating_face_map_complex.obj_d], rw comp_sum, let t := λ (j : fin (n+2)), (normalized_Moore_complex.obj_X X (n+1)).arrow ≫ ((-1 : ℤ)^(j : ℕ) • X.δ j), have def_t : (∀ j : fin (n+2), t j = (normalized_Moore_complex.obj_X X (n+1)).arrow ≫ ((-1 : ℤ)^(j : ℕ) • X.δ j)) := by { intro j, refl, }, rw [fin.sum_univ_succ t], have null : ∀ j : fin (n+1), t j.succ = 0, { intro j, rw [def_t, comp_zsmul, ← zsmul_zero ((-1 : ℤ)^(j.succ : ℕ))], apply congr_arg, rw normalized_Moore_complex.obj_X, rw ← factor_thru_arrow _ _ (finset_inf_arrow_factors finset.univ _ j (by simp only [finset.mem_univ])), slice_lhs 2 3 { rw kernel_subobject_arrow_comp (X.δ j.succ), }, simp only [comp_zero], }, rw [fintype.sum_eq_zero _ null], simp only [add_zero], /- finally, we study the remaining term which is induced by X.δ 0 -/ let eq := def_t 0, rw [show (-1 : ℤ)^((0 : fin (n+2)) : ℕ) = 1, by ring] at eq, rw one_smul at eq, rw eq, cases n; dsimp; simp, end) @[simp] lemma inclusion_of_Moore_complex_map_f (X : simplicial_object A) (n : ℕ) : (inclusion_of_Moore_complex_map X).f n = (normalized_Moore_complex.obj_X X n).arrow := chain_complex.of_hom_f _ _ _ _ _ _ _ _ n variables (A) /-- The inclusion map of the Moore complex in the alternating face map complex, as a natural transformation -/ @[simps] def inclusion_of_Moore_complex : (normalized_Moore_complex A) ⟶ (alternating_face_map_complex A) := { app := inclusion_of_Moore_complex_map, } namespace alternating_coface_map_complex variables (X Y : cosimplicial_object C) /-- The differential on the alternating coface map complex is the alternate sum of the coface maps -/ @[simp] def obj_d (n : ℕ) : X.obj [n] ⟶ X.obj [n+1] := ∑ (i : fin (n+2)), (-1 : ℤ)^(i : ℕ) • X.δ i lemma d_eq_unop_d (n : ℕ) : obj_d X n = (alternating_face_map_complex.obj_d ((cosimplicial_simplicial_equiv C).functor.obj (op X)) n).unop := by simpa only [obj_d, alternating_face_map_complex.obj_d, unop_sum, unop_zsmul] lemma d_squared (n : ℕ) : obj_d X n ≫ obj_d X (n+1) = 0 := by simp only [d_eq_unop_d, ← unop_comp, alternating_face_map_complex.d_squared, unop_zero] /-- The alternating coface map complex, on objects -/ def obj : cochain_complex C ℕ := cochain_complex.of (λ n, X.obj [n]) (obj_d X) (d_squared X) variables {X} {Y} /-- The alternating face map complex, on morphisms -/ @[simp] def map (f : X ⟶ Y) : obj X ⟶ obj Y := cochain_complex.of_hom _ _ _ _ _ _ (λ n, f.app [n]) (λ n, begin dsimp, rw [comp_sum, sum_comp], apply finset.sum_congr rfl (λ x h, _), rw [comp_zsmul, zsmul_comp], congr' 1, symmetry, apply f.naturality, end) end alternating_coface_map_complex variable (C) /-- The alternating coface map complex, as a functor -/ @[simps] def alternating_coface_map_complex : cosimplicial_object C ⥤ cochain_complex C ℕ := { obj := alternating_coface_map_complex.obj, map := λ X Y f, alternating_coface_map_complex.map f } end algebraic_topology
1b46f7673d9c5b7a3d408d24a553c8c5272472c2
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/calculus/conformal/normed_space.lean
3806e1b13728239ad707ee5cd9de2b15e4c1141e
[ "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
4,967
lean
/- Copyright (c) 2021 Yourong Zang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yourong Zang -/ import analysis.normed_space.conformal_linear_map import analysis.calculus.fderiv.add import analysis.calculus.fderiv.mul import analysis.calculus.fderiv.equiv import analysis.calculus.fderiv.restrict_scalars /-! # Conformal Maps > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A continuous linear map between real normed spaces `X` and `Y` is `conformal_at` some point `x` if it is real differentiable at that point and its differential `is_conformal_linear_map`. ## Main definitions * `conformal_at`: the main definition of conformal maps * `conformal`: maps that are conformal at every point * `conformal_factor_at`: the conformal factor of a conformal map at some point ## Main results * The conformality of the composition of two conformal maps, the identity map and multiplications by nonzero constants * `conformal_at_iff_is_conformal_map_fderiv`: an equivalent definition of the conformality of a map In `analysis.calculus.conformal.inner_product`: * `conformal_at_iff`: an equivalent definition of the conformality of a map In `geometry.euclidean.angle.unoriented.conformal`: * `conformal_at.preserves_angle`: if a map is conformal at `x`, then its differential preserves all angles at `x` ## Tags conformal ## Warning The definition of conformality in this file does NOT require the maps to be orientation-preserving. Maps such as the complex conjugate are considered to be conformal. -/ noncomputable theory variables {X Y Z : Type*} [normed_add_comm_group X] [normed_add_comm_group Y] [normed_add_comm_group Z] [normed_space ℝ X] [normed_space ℝ Y] [normed_space ℝ Z] section loc_conformality open linear_isometry continuous_linear_map /-- A map `f` is said to be conformal if it has a conformal differential `f'`. -/ def conformal_at (f : X → Y) (x : X) := ∃ (f' : X →L[ℝ] Y), has_fderiv_at f f' x ∧ is_conformal_map f' lemma conformal_at_id (x : X) : conformal_at id x := ⟨id ℝ X, has_fderiv_at_id _, is_conformal_map_id⟩ lemma conformal_at_const_smul {c : ℝ} (h : c ≠ 0) (x : X) : conformal_at (λ (x': X), c • x') x := ⟨c • continuous_linear_map.id ℝ X, (has_fderiv_at_id x).const_smul c, is_conformal_map_const_smul h⟩ @[nontriviality] lemma subsingleton.conformal_at [subsingleton X] (f : X → Y) (x : X) : conformal_at f x := ⟨0, has_fderiv_at_of_subsingleton _ _, is_conformal_map_of_subsingleton _⟩ /-- A function is a conformal map if and only if its differential is a conformal linear map-/ lemma conformal_at_iff_is_conformal_map_fderiv {f : X → Y} {x : X} : conformal_at f x ↔ is_conformal_map (fderiv ℝ f x) := begin split, { rintros ⟨f', hf, hf'⟩, rwa hf.fderiv }, { intros H, by_cases h : differentiable_at ℝ f x, { exact ⟨fderiv ℝ f x, h.has_fderiv_at, H⟩, }, { nontriviality X, exact absurd (fderiv_zero_of_not_differentiable_at h) H.ne_zero } }, end namespace conformal_at lemma differentiable_at {f : X → Y} {x : X} (h : conformal_at f x) : differentiable_at ℝ f x := let ⟨_, h₁, _⟩ := h in h₁.differentiable_at lemma congr {f g : X → Y} {x : X} {u : set X} (hx : x ∈ u) (hu : is_open u) (hf : conformal_at f x) (h : ∀ (x : X), x ∈ u → g x = f x) : conformal_at g x := let ⟨f', hfderiv, hf'⟩ := hf in ⟨f', hfderiv.congr_of_eventually_eq ((hu.eventually_mem hx).mono h), hf'⟩ lemma comp {f : X → Y} {g : Y → Z} (x : X) (hg : conformal_at g (f x)) (hf : conformal_at f x) : conformal_at (g ∘ f) x := begin rcases hf with ⟨f', hf₁, cf⟩, rcases hg with ⟨g', hg₁, cg⟩, exact ⟨g'.comp f', hg₁.comp x hf₁, cg.comp cf⟩, end lemma const_smul {f : X → Y} {x : X} {c : ℝ} (hc : c ≠ 0) (hf : conformal_at f x) : conformal_at (c • f) x := (conformal_at_const_smul hc $ f x).comp x hf end conformal_at end loc_conformality section global_conformality /-- A map `f` is conformal if it's conformal at every point. -/ def conformal (f : X → Y) := ∀ (x : X), conformal_at f x lemma conformal_id : conformal (id : X → X) := λ x, conformal_at_id x lemma conformal_const_smul {c : ℝ} (h : c ≠ 0) : conformal (λ (x : X), c • x) := λ x, conformal_at_const_smul h x namespace conformal lemma conformal_at {f : X → Y} (h : conformal f) (x : X) : conformal_at f x := h x lemma differentiable {f : X → Y} (h : conformal f) : differentiable ℝ f := λ x, (h x).differentiable_at lemma comp {f : X → Y} {g : Y → Z} (hf : conformal f) (hg : conformal g) : conformal (g ∘ f) := λ x, (hg $ f x).comp x (hf x) lemma const_smul {f : X → Y} (hf : conformal f) {c : ℝ} (hc : c ≠ 0) : conformal (c • f) := λ x, (hf x).const_smul hc end conformal end global_conformality