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
d2f335ed0ef49e8ea27714bd1e64f601285916e0
b328e8ebb2ba923140e5137c83f09fa59516b793
/stage0/src/Lean/Util/Trace.lean
c1e5a416e3e9a90ae27998f7ac0e50a81bfabb7b
[ "Apache-2.0" ]
permissive
DrMaxis/lean4
a781bcc095511687c56ab060e816fd948553e162
5a02c4facc0658aad627cfdcc3db203eac0cb544
refs/heads/master
1,677,051,517,055
1,611,876,226,000
1,611,876,226,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,519
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich, Leonardo de Moura -/ import Lean.Message import Lean.MonadEnv universe u namespace Lean open Std (PersistentArray) structure TraceElem where ref : Syntax msg : MessageData deriving Inhabited structure TraceState where enabled : Bool := true traces : PersistentArray TraceElem := {} deriving Inhabited namespace TraceState private def toFormat (traces : PersistentArray TraceElem) (sep : Format) : IO Format := traces.size.foldM (fun i r => do let curr ← (traces.get! i).msg.format pure $ if i > 0 then r ++ sep ++ curr else r ++ curr) Format.nil end TraceState class MonadTrace (m : Type → Type) where modifyTraceState : (TraceState → TraceState) → m Unit getTraceState : m TraceState export MonadTrace (getTraceState modifyTraceState) instance (m n) [MonadLift m n] [MonadTrace m] : MonadTrace n where modifyTraceState := fun f => liftM (modifyTraceState f : m _) getTraceState := liftM (getTraceState : m _) variable {α : Type} {m : Type → Type} [Monad m] [MonadTrace m] def printTraces {m} [Monad m] [MonadTrace m] [MonadLiftT IO m] : m Unit := do let traceState ← getTraceState traceState.traces.forM fun m => do let d ← m.msg.format IO.println d def resetTraceState {m} [MonadTrace m] : m Unit := modifyTraceState (fun _ => {}) private def checkTraceOptionAux (opts : Options) : Name → Bool | n@(Name.str p _ _) => opts.getBool n || (!opts.contains n && checkTraceOptionAux opts p) | _ => false def checkTraceOption (opts : Options) (cls : Name) : Bool := if opts.isEmpty then false else checkTraceOptionAux opts (`trace ++ cls) private def checkTraceOptionM [MonadOptions m] (cls : Name) : m Bool := do let opts ← getOptions pure $ checkTraceOption opts cls @[inline] def isTracingEnabledFor [MonadOptions m] (cls : Name) : m Bool := do let s ← getTraceState if !s.enabled then pure false else checkTraceOptionM cls @[inline] def enableTracing (b : Bool) : m Bool := do let s ← getTraceState let oldEnabled := s.enabled modifyTraceState fun s => { s with enabled := b } pure oldEnabled @[inline] def getTraces : m (PersistentArray TraceElem) := do let s ← getTraceState pure s.traces @[inline] def modifyTraces (f : PersistentArray TraceElem → PersistentArray TraceElem) : m Unit := modifyTraceState fun s => { s with traces := f s.traces } @[inline] def setTraceState (s : TraceState) : m Unit := modifyTraceState fun _ => s private def addNode (oldTraces : PersistentArray TraceElem) (cls : Name) (ref : Syntax) : m Unit := modifyTraces fun traces => if traces.isEmpty then oldTraces else let d := MessageData.tagged cls (MessageData.node (traces.toArray.map fun elem => elem.msg)) oldTraces.push { ref := ref, msg := d } private def getResetTraces : m (PersistentArray TraceElem) := do let oldTraces ← getTraces modifyTraces fun _ => {} pure oldTraces section variable [MonadRef m] [AddMessageContext m] [MonadOptions m] def addTrace (cls : Name) (msg : MessageData) : m Unit := do let ref ← getRef let msg ← addMessageContext msg modifyTraces fun traces => traces.push { ref := ref, msg := MessageData.tagged cls msg } @[inline] def trace (cls : Name) (msg : Unit → MessageData) : m Unit := do if (← isTracingEnabledFor cls) then addTrace cls (msg ()) @[inline] def traceM (cls : Name) (mkMsg : m MessageData) : m Unit := do if (← isTracingEnabledFor cls) then let msg ← mkMsg addTrace cls msg @[inline] def traceCtx [MonadFinally m] (cls : Name) (ctx : m α) : m α := do let b ← isTracingEnabledFor cls if !b then let old ← enableTracing false try ctx finally enableTracing old else let ref ← getRef let oldCurrTraces ← getResetTraces try ctx finally addNode oldCurrTraces cls ref -- TODO: delete after fix old frontend def MonadTracer.trace (cls : Name) (msg : Unit → MessageData) : m Unit := Lean.trace cls msg end def registerTraceClass (traceClassName : Name) : IO Unit := registerOption (`trace ++ traceClassName) { group := "trace", defValue := false, descr := "enable/disable tracing for the given module and submodules" } macro:max "trace!" id:term:max msg:term : term => `(trace $id fun _ => ($msg : MessageData)) syntax "trace[" ident "]!" (interpolatedStr(term) <|> term) : term macro_rules | `(trace[$id]! $s) => if s.getKind == interpolatedStrKind then `(Lean.trace $(quote id.getId) fun _ => m! $s) else `(Lean.trace $(quote id.getId) fun _ => ($s : MessageData)) variable {α : Type} {m : Type → Type} [Monad m] [MonadTrace m] [MonadOptions m] [MonadRef m] def withNestedTraces [MonadFinally m] (x : m α) : m α := do let s ← getTraceState if !s.enabled then x else let currTraces ← getTraces modifyTraces fun _ => {} let ref ← getRef try x finally modifyTraces fun traces => if traces.size == 0 then currTraces else if traces.size == 1 && traces[0].msg.isNest then currTraces ++ traces -- No nest of nest else let d := traces.foldl (init := MessageData.nil) fun d elem => if d.isNil then elem.msg else m!"{d}\n{elem.msg}" currTraces.push { ref := ref, msg := MessageData.nestD d } end Lean
6acfe671989f8e112687f8c7bdf5acc495162d2a
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/set_theory/game/state.lean
784d1ee2cc473c2a89382a0c5717aeaea34117e7
[ "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
8,424
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 set_theory.game.short /-! # Games described via "the state of the board". We provide a simple mechanism for constructing combinatorial (pre-)games, by describing "the state of the board", and providing an upper bound on the number of turns remaining. ## Implementation notes We're very careful to produce a computable definition, so small games can be evaluated using `dec_trivial`. To achieve this, I've had to rely solely on induction on natural numbers: relying on general well-foundedness seems to be poisonous to computation? See `set_theory/game/domineering` for an example using this construction. -/ universe u namespace pgame /-- `pgame_state S` describes how to interpret `s : S` as a state of a combinatorial game. Use `pgame.of s` or `game.of s` to construct the game. `pgame_state.L : S → finset S` and `pgame_state.R : S → finset S` describe the states reachable by a move by Left or Right. `pgame_state.turn_bound : S → ℕ` gives an upper bound on the number of possible turns remaining from this state. -/ class state (S : Type u) := (turn_bound : S → ℕ) (L : S → finset S) (R : S → finset S) (left_bound : ∀ {s t : S} (m : t ∈ L s), turn_bound t < turn_bound s) (right_bound : ∀ {s t : S} (m : t ∈ R s), turn_bound t < turn_bound s) open state variables {S : Type u} [state S] lemma turn_bound_ne_zero_of_left_move {s t : S} (m : t ∈ L s) : turn_bound s ≠ 0 := begin intro h, have t := state.left_bound m, rw h at t, exact nat.not_succ_le_zero _ t, end lemma turn_bound_ne_zero_of_right_move {s t : S} (m : t ∈ R s) : turn_bound s ≠ 0 := begin intro h, have t := state.right_bound m, rw h at t, exact nat.not_succ_le_zero _ t, end lemma turn_bound_of_left {s t : S} (m : t ∈ L s) (n : ℕ) (h : turn_bound s ≤ n + 1) : turn_bound t ≤ n := nat.le_of_lt_succ (nat.lt_of_lt_of_le (left_bound m) h) lemma turn_bound_of_right {s t : S} (m : t ∈ R s) (n : ℕ) (h : turn_bound s ≤ n + 1) : turn_bound t ≤ n := nat.le_of_lt_succ (nat.lt_of_lt_of_le (right_bound m) h) /-- Construct a `pgame` from a state and a (not necessarily optimal) bound on the number of turns remaining. -/ def of_aux : Π (n : ℕ) (s : S) (h : turn_bound s ≤ n), pgame | 0 s h := pgame.mk {t // t ∈ L s} {t // t ∈ R s} (λ t, begin exfalso, exact turn_bound_ne_zero_of_left_move t.2 (nonpos_iff_eq_zero.mp h) end) (λ t, begin exfalso, exact turn_bound_ne_zero_of_right_move t.2 (nonpos_iff_eq_zero.mp h) end) | (n+1) s h := pgame.mk {t // t ∈ L s} {t // t ∈ R s} (λ t, of_aux n t (turn_bound_of_left t.2 n h)) (λ t, of_aux n t (turn_bound_of_right t.2 n h)) /-- Two different (valid) turn bounds give equivalent games. -/ def of_aux_relabelling : Π (s : S) (n m : ℕ) (hn : turn_bound s ≤ n) (hm : turn_bound s ≤ m), relabelling (of_aux n s hn) (of_aux m s hm) | s 0 0 hn hm := begin dsimp [pgame.of_aux], fsplit, refl, refl, { intro i, dsimp at i, exfalso, exact turn_bound_ne_zero_of_left_move i.2 (nonpos_iff_eq_zero.mp hn) }, { intro j, dsimp at j, exfalso, exact turn_bound_ne_zero_of_right_move j.2 (nonpos_iff_eq_zero.mp hm) } end | s 0 (m+1) hn hm := begin dsimp [pgame.of_aux], fsplit, refl, refl, { intro i, dsimp at i, exfalso, exact turn_bound_ne_zero_of_left_move i.2 (nonpos_iff_eq_zero.mp hn) }, { intro j, dsimp at j, exfalso, exact turn_bound_ne_zero_of_right_move j.2 (nonpos_iff_eq_zero.mp hn) } end | s (n+1) 0 hn hm := begin dsimp [pgame.of_aux], fsplit, refl, refl, { intro i, dsimp at i, exfalso, exact turn_bound_ne_zero_of_left_move i.2 (nonpos_iff_eq_zero.mp hm) }, { intro j, dsimp at j, exfalso, exact turn_bound_ne_zero_of_right_move j.2 (nonpos_iff_eq_zero.mp hm) } end | s (n+1) (m+1) hn hm := begin dsimp [pgame.of_aux], fsplit, refl, refl, { intro i, apply of_aux_relabelling, }, { intro j, apply of_aux_relabelling, } end /-- Construct a combinatorial `pgame` from a state. -/ def of (s : S) : pgame := of_aux (turn_bound s) s (refl _) /-- The equivalence between `left_moves` for a `pgame` constructed using `of_aux _ s _`, and `L s`. -/ def left_moves_of_aux (n : ℕ) {s : S} (h : turn_bound s ≤ n) : left_moves (of_aux n s h) ≃ {t // t ∈ L s} := by induction n; refl /-- The equivalence between `left_moves` for a `pgame` constructed using `of s`, and `L s`. -/ def left_moves_of (s : S) : left_moves (of s) ≃ {t // t ∈ L s} := left_moves_of_aux _ _ /-- The equivalence between `right_moves` for a `pgame` constructed using `of_aux _ s _`, and `R s`. -/ def right_moves_of_aux (n : ℕ) {s : S} (h : turn_bound s ≤ n) : right_moves (of_aux n s h) ≃ {t // t ∈ R s} := by induction n; refl /-- The equivalence between `right_moves` for a `pgame` constructed using `of s`, and `R s`. -/ def right_moves_of (s : S) : right_moves (of s) ≃ {t // t ∈ R s} := right_moves_of_aux _ _ /-- The relabelling showing `move_left` applied to a game constructed using `of_aux` has itself been constructed using `of_aux`. -/ def relabelling_move_left_aux (n : ℕ) {s : S} (h : turn_bound s ≤ n) (t : left_moves (of_aux n s h)) : relabelling (move_left (of_aux n s h) t) (of_aux (n-1) (((left_moves_of_aux n h) t) : S) ((turn_bound_of_left ((left_moves_of_aux n h) t).2 (n-1) (nat.le_trans h (nat.le_sub_add n 1))))) := begin induction n, { have t' := (left_moves_of_aux 0 h) t, exfalso, exact turn_bound_ne_zero_of_left_move t'.2 (nonpos_iff_eq_zero.mp h), }, { refl }, end /-- The relabelling showing `move_left` applied to a game constructed using `of` has itself been constructed using `of`. -/ def relabelling_move_left (s : S) (t : left_moves (of s)) : relabelling (move_left (of s) t) (of (((left_moves_of s).to_fun t) : S)) := begin transitivity, apply relabelling_move_left_aux, apply of_aux_relabelling, end /-- The relabelling showing `move_right` applied to a game constructed using `of_aux` has itself been constructed using `of_aux`. -/ def relabelling_move_right_aux (n : ℕ) {s : S} (h : turn_bound s ≤ n) (t : right_moves (of_aux n s h)) : relabelling (move_right (of_aux n s h) t) (of_aux (n-1) (((right_moves_of_aux n h) t) : S) ((turn_bound_of_right ((right_moves_of_aux n h) t).2 (n-1) (nat.le_trans h (nat.le_sub_add n 1))))) := begin induction n, { have t' := (right_moves_of_aux 0 h) t, exfalso, exact turn_bound_ne_zero_of_right_move t'.2 (nonpos_iff_eq_zero.mp h), }, { refl }, end /-- The relabelling showing `move_right` applied to a game constructed using `of` has itself been constructed using `of`. -/ def relabelling_move_right (s : S) (t : right_moves (of s)) : relabelling (move_right (of s) t) (of (((right_moves_of s).to_fun t) : S)) := begin transitivity, apply relabelling_move_right_aux, apply of_aux_relabelling, end instance fintype_left_moves_of_aux (n : ℕ) (s : S) (h : turn_bound s ≤ n) : fintype (left_moves (of_aux n s h)) := begin apply fintype.of_equiv _ (left_moves_of_aux _ _).symm, apply_instance, end instance fintype_right_moves_of_aux (n : ℕ) (s : S) (h : turn_bound s ≤ n) : fintype (right_moves (of_aux n s h)) := begin apply fintype.of_equiv _ (right_moves_of_aux _ _).symm, apply_instance, end instance short_of_aux : Π (n : ℕ) {s : S} (h : turn_bound s ≤ n), short (of_aux n s h) | 0 s h := short.mk' (λ i, begin have i := (left_moves_of_aux _ _).to_fun i, exfalso, exact turn_bound_ne_zero_of_left_move i.2 (nonpos_iff_eq_zero.mp h), end) (λ j, begin have j := (right_moves_of_aux _ _).to_fun j, exfalso, exact turn_bound_ne_zero_of_right_move j.2 (nonpos_iff_eq_zero.mp h), end) | (n+1) s h := short.mk' (λ i, short_of_relabelling (relabelling_move_left_aux (n+1) h i).symm (short_of_aux n _)) (λ j, short_of_relabelling (relabelling_move_right_aux (n+1) h j).symm (short_of_aux n _)) instance short_of (s : S) : short (of s) := begin dsimp [pgame.of], apply_instance end end pgame namespace game /-- Construct a combinatorial `game` from a state. -/ def of {S : Type u} [pgame.state S] (s : S) : game := ⟦pgame.of s⟧ end game
160d55916b783806eb60a6847b952e1582f3d076
c09f5945267fd905e23a77be83d9a78580e04a4a
/src/topology/stone_cech.lean
075e80aed0e02f4fadf01dc35ecfe9ccdcc2510d
[ "Apache-2.0" ]
permissive
OHIHIYA20/mathlib
023a6df35355b5b6eb931c404f7dd7535dccfa89
1ec0a1f49db97d45e8666a3bf33217ff79ca1d87
refs/heads/master
1,587,964,529,965
1,551,819,319,000
1,551,819,319,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,706
lean
/- Copyright (c) 2018 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton Construction of the Stone-Čech compactification using ultrafilters. Parts of the formalization are based on "Ultrafilters and Topology" by Marius Stekelenburg, particularly section 5. -/ import topology.constructions noncomputable theory open filter lattice set universes u v section ultrafilter /- The set of ultrafilters on α carries a natural topology which makes it the Stone-Čech compactification of α (viewed as a discrete space). -/ /-- Basis for the topology on `ultrafilter α`. -/ def ultrafilter_basis (α : Type u) : set (set (ultrafilter α)) := {t | ∃ (s : set α), t = {u | s ∈ u.val.sets}} variables {α : Type u} instance : topological_space (ultrafilter α) := topological_space.generate_from (ultrafilter_basis α) lemma ultrafilter_basis_is_basis : topological_space.is_topological_basis (ultrafilter_basis α) := ⟨begin rintros _ ⟨a, rfl⟩ _ ⟨b, rfl⟩ u ⟨ua, ub⟩, refine ⟨_, ⟨a ∩ b, rfl⟩, u.val.inter_sets ua ub, assume v hv, ⟨_, _⟩⟩; apply v.val.sets_of_superset hv; simp end, eq_univ_of_univ_subset $ subset_sUnion_of_mem $ ⟨univ, eq.symm (eq_univ_of_forall (λ u, u.val.univ_sets))⟩, rfl⟩ /-- The basic open sets for the topology on ultrafilters are open. -/ lemma ultrafilter_is_open_basic (s : set α) : is_open {u : ultrafilter α | s ∈ u.val.sets} := topological_space.is_open_of_is_topological_basis ultrafilter_basis_is_basis ⟨s, rfl⟩ /-- The basic open sets for the topology on ultrafilters are also closed. -/ lemma ultrafilter_is_closed_basic (s : set α) : is_closed {u : ultrafilter α | s ∈ u.val.sets} := begin change is_open (- _), convert ultrafilter_is_open_basic (-s), ext u, exact (ultrafilter_iff_compl_mem_iff_not_mem.mp u.property s).symm end /-- Every ultrafilter `u` on `ultrafilter α` converges to a unique point of `ultrafilter α`, namely `mjoin u`. -/ lemma ultrafilter_converges_iff {u : ultrafilter (ultrafilter α)} {x : ultrafilter α} : u.val ≤ nhds x ↔ x = mjoin u := begin rw [eq_comm, ultrafilter.eq_iff_val_le_val], change u.val ≤ nhds x ↔ x.val.sets ⊆ {a | {v : ultrafilter α | a ∈ v.val.sets} ∈ u.val.sets}, simp only [topological_space.nhds_generate_from, lattice.le_infi_iff, ultrafilter_basis, le_principal_iff], split; intro h, { intros a ha, exact h _ ⟨ha, a, rfl⟩ }, { rintros _ ⟨xi, a, rfl⟩, exact h xi } end instance ultrafilter_compact : compact_space (ultrafilter α) := ⟨compact_iff_ultrafilter_le_nhds.mpr $ assume f uf _, ⟨mjoin ⟨f, uf⟩, trivial, ultrafilter_converges_iff.mpr rfl⟩⟩ instance ultrafilter.t2_space : t2_space (ultrafilter α) := t2_iff_ultrafilter.mpr $ assume f x y u fx fy, have hx : x = mjoin ⟨f, u⟩, from ultrafilter_converges_iff.mp fx, have hy : y = mjoin ⟨f, u⟩, from ultrafilter_converges_iff.mp fy, hx.trans hy.symm lemma ultrafilter_comap_pure_nhds (b : ultrafilter α) : comap pure (nhds b) ≤ b.val := begin rw topological_space.nhds_generate_from, simp only [comap_infi, comap_principal], intros s hs, rw ←le_principal_iff, refine lattice.infi_le_of_le {u | s ∈ u.val.sets} _, refine lattice.infi_le_of_le ⟨hs, ⟨s, rfl⟩⟩ _, rw principal_mono, intros a ha, exact mem_pure_iff.mp ha end section embedding lemma ultrafilter_pure_injective : function.injective (pure : α → ultrafilter α) := begin intros x y h, have : {x} ∈ (pure x : ultrafilter α).val.sets := singleton_mem_pure_sets, rw h at this, exact (mem_singleton_iff.mp (mem_pure_sets.mp this)).symm end open topological_space /-- `pure : α → ultrafilter α` defines a dense embedding of `α` in `ultrafilter α`. -/ lemma dense_embedding_pure : @dense_embedding _ _ ⊤ _ (pure : α → ultrafilter α) := by letI : topological_space α := ⊤; exact dense_embedding.mk' pure continuous_top (assume x, mem_closure_iff_ultrafilter.mpr ⟨x.map ultrafilter.pure, range_mem_map, ultrafilter_converges_iff.mpr (bind_pure x).symm⟩) ultrafilter_pure_injective (assume a s as, ⟨{u | s ∈ u.val.sets}, mem_nhds_sets (ultrafilter_is_open_basic s) (mem_pure_sets.mpr (mem_of_nhds as)), assume b hb, mem_pure_sets.mp hb⟩) end embedding section extension /- Goal: Any function `α → γ` to a compact Hausdorff space `γ` has a unique extension to a continuous function `ultrafilter α → γ`. We already know it must be unique because `α → ultrafilter α` is a dense embedding and `γ` is Hausdorff. For existence, we will invoke `dense_embedding.continuous_extend`. -/ variables {γ : Type*} [topological_space γ] /-- The extension of a function `α → γ` to a function `ultrafilter α → γ`. When `γ` is a compact Hausdorff space it will be continuous. -/ def ultrafilter.extend (f : α → γ) : ultrafilter α → γ := by letI : topological_space α := ⊤; exact dense_embedding_pure.extend f lemma ultrafilter_extend_extends (f : α → γ) : ultrafilter.extend f ∘ pure = f := by letI : topological_space α := ⊤; exact funext dense_embedding_pure.extend_e_eq variables [t2_space γ] [compact_space γ] lemma continuous_ultrafilter_extend (f : α → γ) : continuous (ultrafilter.extend f) := have ∀ (b : ultrafilter α), ∃ c, tendsto f (comap ultrafilter.pure (nhds b)) (nhds c) := assume b, -- b.map f is an ultrafilter on γ, which is compact, so it converges to some c in γ. let ⟨c, _, h⟩ := compact_iff_ultrafilter_le_nhds.mp compact_univ (b.map f).val (b.map f).property (by rw [le_principal_iff]; exact univ_mem_sets) in ⟨c, le_trans (map_mono (ultrafilter_comap_pure_nhds _)) h⟩, begin letI : topological_space α := ⊤, letI : normal_space γ := normal_of_compact_t2, exact dense_embedding_pure.continuous_extend this end /-- The value of `ultrafilter.extend f` on an ultrafilter `b` is the unique limit of the ultrafilter `b.map f` in `γ`. -/ lemma ultrafilter_extend_eq_iff {f : α → γ} {b : ultrafilter α} {c : γ} : ultrafilter.extend f b = c ↔ b.val.map f ≤ nhds c := ⟨assume h, begin -- Write b as an ultrafilter limit of pure ultrafilters, and use -- the facts that ultrafilter.extend is a continuous extension of f. let b' : ultrafilter (ultrafilter α) := b.map pure, have t : b'.val ≤ nhds b, from ultrafilter_converges_iff.mpr (by exact (bind_pure _).symm), rw ←h, have := (continuous_ultrafilter_extend f).tendsto b, refine le_trans _ (le_trans (map_mono t) this), change _ ≤ map (ultrafilter.extend f ∘ pure) b.val, rw ultrafilter_extend_extends, exact le_refl _ end, assume h, by letI : topological_space α := ⊤; exact dense_embedding_pure.extend_eq (le_trans (map_mono (ultrafilter_comap_pure_nhds _)) h)⟩ end extension end ultrafilter section stone_cech /- Now, we start with a (not necessarily discrete) topological space α and we want to construct its Stone-Čech compactification. We can build it as a quotient of `ultrafilter α` by the relation which identifies two points if the extension of every continuous function α → γ to a compact Hausdorff space sends the two points to the same point of γ. -/ variables (α : Type u) [topological_space α] instance stone_cech_setoid : setoid (ultrafilter α) := { r := λ x y, ∀ (γ : Type u) [topological_space γ], by exactI ∀ [t2_space γ] [compact_space γ] (f : α → γ) (hf : continuous f), ultrafilter.extend f x = ultrafilter.extend f y, iseqv := ⟨assume x γ tγ h₁ h₂ f hf, rfl, assume x y xy γ tγ h₁ h₂ f hf, by exactI (xy γ f hf).symm, assume x y z xy yz γ tγ h₁ h₂ f hf, by exactI (xy γ f hf).trans (yz γ f hf)⟩ } /-- The Stone-Čech compactification of a topological space. -/ def stone_cech : Type u := quotient (stone_cech_setoid α) variables {α} instance : topological_space (stone_cech α) := by unfold stone_cech; apply_instance /-- The natural map from α to its Stone-Čech compactification. -/ def stone_cech_unit (x : α) : stone_cech α := ⟦pure x⟧ /-- The image of stone_cech_unit is dense. (But stone_cech_unit need not be an embedding, for example if α is not Hausdorff.) -/ lemma stone_cech_unit_dense : closure (range (@stone_cech_unit α _)) = univ := begin convert quotient_dense_of_dense (eq_univ_iff_forall.mp dense_embedding_pure.closure_range), rw [←range_comp], refl end section extension variables {γ : Type u} [topological_space γ] [t2_space γ] [compact_space γ] variables {f : α → γ} (hf : continuous f) local attribute [elab_with_expected_type] quotient.lift /-- The extension of a continuous function from α to a compact Hausdorff space γ to the Stone-Čech compactification of α. -/ def stone_cech_extend : stone_cech α → γ := quotient.lift (ultrafilter.extend f) (λ x y xy, xy γ f hf) lemma stone_cech_extend_extends : stone_cech_extend hf ∘ stone_cech_unit = f := ultrafilter_extend_extends f lemma continuous_stone_cech_extend : continuous (stone_cech_extend hf) := continuous_quot_lift _ (continuous_ultrafilter_extend f) end extension lemma convergent_eqv_pure {u : ultrafilter α} {x : α} (ux : u.val ≤ nhds x) : u ≈ pure x := assume γ tγ h₁ h₂ f hf, begin resetI, transitivity f x, swap, symmetry, all_goals { refine ultrafilter_extend_eq_iff.mpr (le_trans (map_mono _) (hf.tendsto _)) }, { apply pure_le_nhds }, { exact ux } end lemma continuous_stone_cech_unit : continuous (stone_cech_unit : α → stone_cech α) := continuous_iff_ultrafilter.mpr $ λ x g u gx, let g' : ultrafilter α := ⟨g, u⟩ in have (g'.map ultrafilter.pure).val ≤ nhds g', by rw ultrafilter_converges_iff; exact (bind_pure _).symm, have (g'.map stone_cech_unit).val ≤ nhds ⟦g'⟧, from (continuous_at_iff_ultrafilter g').mp (continuous_quotient_mk.tendsto g') _ (ultrafilter_map u) this, by rwa (show ⟦g'⟧ = ⟦pure x⟧, from quotient.sound $ convergent_eqv_pure gx) at this instance stone_cech.t2_space : t2_space (stone_cech α) := begin rw t2_iff_ultrafilter, rintros g ⟨x⟩ ⟨y⟩ u gx gy, apply quotient.sound, intros γ tγ h₁ h₂ f hf, resetI, change stone_cech_extend hf ⟦x⟧ = stone_cech_extend hf ⟦y⟧, refine tendsto_nhds_unique u.1 _ _, { exact stone_cech_extend hf }, all_goals { refine le_trans (map_mono _) ((continuous_stone_cech_extend hf).tendsto _), assumption } end instance stone_cech.compact_space : compact_space (stone_cech α) := quotient.compact_space end stone_cech
062d60dc87700c9a699e9f2132326e9abff21e23
8cb37a089cdb4af3af9d8bf1002b417e407a8e9e
/tests/lean/run/sebastien_coe_simp.lean
ff8c24ad43b65c672abc9a6eab4fd59a9ce6b2c8
[ "Apache-2.0" ]
permissive
kbuzzard/lean
ae3c3db4bb462d750dbf7419b28bafb3ec983ef7
ed1788fd674bb8991acffc8fca585ec746711928
refs/heads/master
1,620,983,366,617
1,618,937,600,000
1,618,937,600,000
359,886,396
1
0
Apache-2.0
1,618,936,987,000
1,618,936,987,000
null
UTF-8
Lean
false
false
541
lean
variable (α : Type*) structure my_equiv := (to_fun : α → α) instance : has_coe_to_fun (my_equiv α) := ⟨_, my_equiv.to_fun⟩ def my_equiv1 : my_equiv α := { to_fun := id } def my_equiv2 : my_equiv α := { to_fun := id } @[simp] lemma one_eq_two : my_equiv1 α = my_equiv2 α := rfl lemma other (x : ℕ) : my_equiv1 ℕ (x + 0) = my_equiv2 ℕ x := by simp [nat.add_zero] -- does not fail @[simp] lemma two_apply (x : α) : my_equiv2 α x = x := rfl lemma one_apply (x : α) : my_equiv1 α x = x := by simp -- does not fail
97f8a1090988f619a4389b5885165c43191622c5
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/elabissues/leaky_tmp_metavars2.lean
519f5beace7d5937645e41818974d330dddd8998
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
2,036
lean
/- Here is an example where temporary metavariables from typeclass resolution could spill into nested typeclass resolution, for which the outer TC succeeds iff: 1. the inner TC is still called, even with the leaked tmp mvars 2. the inner TC is allowed to assign the leaked tmp mvars This example will *NOT* work in Lean4. Although it would be easy to allow inner TC to set the outer TC tmp mvars, the issue is that the solution to the inner TC problem may not be unique, and it would be extremely difficult to allow backtracking from the outer TC through to the inner TC. In Lean4, inner TC can be called with leaked temporary mvars from the outer TC, but they are treated as opaque, just as regular mvars are treated in the outer TC. So, this example will fail. -/ class Foo (α : Type) : Type := (x : Unit) class Zoo (α : Type) : Type := (x : Unit) class Bar (α : Type) : Type := (x : Unit) class HasParam (α : Type) [Bar α] : Type := (x : Unit) instance FooToBar (α : Type) [f : Foo α] : Bar α := match f.x with | () => {x:=()} instance ZooToBar (α : Type) [z : Zoo α] : Bar α := match z.x with | () => {x:=()} instance HasParamInst (α : Type) [h : Foo α] : HasParam α := {x:=()} class Top : Type := (x : Unit) instance FooInt : Foo Int := {x:=()} instance AllZoo (α : Type) : Zoo α := {x:=()} instance Bad (α : Type) [HasParam α] : Top := Top.mk () set_option pp.all true set_option trace.class_instances true set_option trace.type_context.complete_instance true def foo [Top] : Unit := () #check @foo _ /- [class_instances] class-instance resolution trace [class_instances] (0) ?x_0 : Top := @Bad ?x_1 ?x_2 [class_instances] (1) ?x_2 : @HasParam ?x_1 (@ZooToBar ?x_1 (AllZoo ?x_1)) := @HasParamInst ?x_3 ?x_4 [type_context.complete_instance] would have synthed: Foo ?x_3 [type_context.complete_instance] would have synthed: Foo ?x_3 failed is_def_eq -/ def couldWork : Top := @Bad Int (@HasParamInst Int FooInt) #print couldWork /- def couldWork : Top := @Bad Int (@HasParamInst Int FooInt) -/
ee59055fcfe124cea5002bacc7991547a9aa3f90
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/rat/big_operators.lean
faa9503277d6dbd77b1d918e566f92e7435fbef4
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
1,491
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, Mario Carneiro -/ import data.rat.cast import algebra.big_operators.basic /-! # Casting lemmas for rational numbers involving sums and products > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ open_locale big_operators variables {ι α : Type*} namespace rat section with_div_ring variables [division_ring α] [char_zero α] @[simp, norm_cast] lemma cast_list_sum (s : list ℚ) : (↑(s.sum) : α) = (s.map coe).sum := map_list_sum (rat.cast_hom α) _ @[simp, norm_cast] lemma cast_multiset_sum (s : multiset ℚ) : (↑(s.sum) : α) = (s.map coe).sum := map_multiset_sum (rat.cast_hom α) _ @[simp, norm_cast] lemma cast_sum (s : finset ι) (f : ι → ℚ) : (↑(∑ i in s, f i) : α) = ∑ i in s, f i := map_sum (rat.cast_hom α) _ _ @[simp, norm_cast] lemma cast_list_prod (s : list ℚ) : (↑(s.prod) : α) = (s.map coe).prod := map_list_prod (rat.cast_hom α) _ end with_div_ring section field variables [field α] [char_zero α] @[simp, norm_cast] lemma cast_multiset_prod (s : multiset ℚ) : (↑(s.prod) : α) = (s.map coe).prod := map_multiset_prod (rat.cast_hom α) _ @[simp, norm_cast] lemma cast_prod (s : finset ι) (f : ι → ℚ) : (↑(∏ i in s, f i) : α) = ∏ i in s, f i := map_prod (rat.cast_hom α) _ _ end field end rat
35847c116141725fd6bc46e1dcd35342437bfb59
94e33a31faa76775069b071adea97e86e218a8ee
/src/category_theory/subobject/limits.lean
e880716772f180326c74f6a1cbc231617a2ee561
[ "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
14,205
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Scott Morrison -/ import category_theory.subobject.lattice /-! # Specific subobjects We define `equalizer_subobject`, `kernel_subobject` and `image_subobject`, which are the subobjects represented by the equalizer, kernel and image of (a pair of) morphism(s) and provide conditions for `P.factors f`, where `P` is one of these special subobjects. TODO: Add conditions for when `P` is a pullback subobject. TODO: an iff characterisation of `(image_subobject f).factors h` -/ universes v u noncomputable theory open category_theory category_theory.category category_theory.limits category_theory.subobject variables {C : Type u} [category.{v} C] {X Y Z : C} namespace category_theory namespace limits section equalizer variables (f g : X ⟶ Y) [has_equalizer f g] /-- The equalizer of morphisms `f g : X ⟶ Y` as a `subobject X`. -/ abbreviation equalizer_subobject : subobject X := subobject.mk (equalizer.ι f g) /-- The underlying object of `equalizer_subobject f g` is (up to isomorphism!) the same as the chosen object `equalizer f g`. -/ def equalizer_subobject_iso : (equalizer_subobject f g : C) ≅ equalizer f g := subobject.underlying_iso (equalizer.ι f g) @[simp, reassoc] lemma equalizer_subobject_arrow : (equalizer_subobject_iso f g).hom ≫ equalizer.ι f g = (equalizer_subobject f g).arrow := by simp [equalizer_subobject_iso] @[simp, reassoc] lemma equalizer_subobject_arrow' : (equalizer_subobject_iso f g).inv ≫ (equalizer_subobject f g).arrow = equalizer.ι f g := by simp [equalizer_subobject_iso] @[reassoc] lemma equalizer_subobject_arrow_comp : (equalizer_subobject f g).arrow ≫ f = (equalizer_subobject f g).arrow ≫ g := by rw [←equalizer_subobject_arrow, category.assoc, category.assoc, equalizer.condition] lemma equalizer_subobject_factors {W : C} (h : W ⟶ X) (w : h ≫ f = h ≫ g) : (equalizer_subobject f g).factors h := ⟨equalizer.lift h w, by simp⟩ lemma equalizer_subobject_factors_iff {W : C} (h : W ⟶ X) : (equalizer_subobject f g).factors h ↔ h ≫ f = h ≫ g := ⟨λ w, by rw [←subobject.factor_thru_arrow _ _ w, category.assoc, equalizer_subobject_arrow_comp, category.assoc], equalizer_subobject_factors f g h⟩ end equalizer section kernel variables [has_zero_morphisms C] (f : X ⟶ Y) [has_kernel f] /-- The kernel of a morphism `f : X ⟶ Y` as a `subobject X`. -/ abbreviation kernel_subobject : subobject X := subobject.mk (kernel.ι f) /-- The underlying object of `kernel_subobject f` is (up to isomorphism!) the same as the chosen object `kernel f`. -/ def kernel_subobject_iso : (kernel_subobject f : C) ≅ kernel f := subobject.underlying_iso (kernel.ι f) @[simp, reassoc, elementwise] lemma kernel_subobject_arrow : (kernel_subobject_iso f).hom ≫ kernel.ι f = (kernel_subobject f).arrow := by simp [kernel_subobject_iso] @[simp, reassoc, elementwise] lemma kernel_subobject_arrow' : (kernel_subobject_iso f).inv ≫ (kernel_subobject f).arrow = kernel.ι f := by simp [kernel_subobject_iso] @[simp, reassoc, elementwise] lemma kernel_subobject_arrow_comp : (kernel_subobject f).arrow ≫ f = 0 := by { rw [←kernel_subobject_arrow], simp only [category.assoc, kernel.condition, comp_zero], } lemma kernel_subobject_factors {W : C} (h : W ⟶ X) (w : h ≫ f = 0) : (kernel_subobject f).factors h := ⟨kernel.lift _ h w, by simp⟩ lemma kernel_subobject_factors_iff {W : C} (h : W ⟶ X) : (kernel_subobject f).factors h ↔ h ≫ f = 0 := ⟨λ w, by rw [←subobject.factor_thru_arrow _ _ w, category.assoc, kernel_subobject_arrow_comp, comp_zero], kernel_subobject_factors f h⟩ /-- A factorisation of `h : W ⟶ X` through `kernel_subobject f`, assuming `h ≫ f = 0`. -/ def factor_thru_kernel_subobject {W : C} (h : W ⟶ X) (w : h ≫ f = 0) : W ⟶ kernel_subobject f := (kernel_subobject f).factor_thru h (kernel_subobject_factors f h w) @[simp] lemma factor_thru_kernel_subobject_comp_arrow {W : C} (h : W ⟶ X) (w : h ≫ f = 0) : factor_thru_kernel_subobject f h w ≫ (kernel_subobject f).arrow = h := by { dsimp [factor_thru_kernel_subobject], simp, } @[simp] lemma factor_thru_kernel_subobject_comp_kernel_subobject_iso {W : C} (h : W ⟶ X) (w : h ≫ f = 0) : factor_thru_kernel_subobject f h w ≫ (kernel_subobject_iso f).hom = kernel.lift f h w := (cancel_mono (kernel.ι f)).1 $ by simp section variables {f} {X' Y' : C} {f' : X' ⟶ Y'} [has_kernel f'] /-- A commuting square induces a morphism between the kernel subobjects. -/ def kernel_subobject_map (sq : arrow.mk f ⟶ arrow.mk f') : (kernel_subobject f : C) ⟶ (kernel_subobject f' : C) := subobject.factor_thru _ ((kernel_subobject f).arrow ≫ sq.left) (kernel_subobject_factors _ _ (by simp [sq.w])) @[simp, reassoc, elementwise] lemma kernel_subobject_map_arrow (sq : arrow.mk f ⟶ arrow.mk f') : kernel_subobject_map sq ≫ (kernel_subobject f').arrow = (kernel_subobject f).arrow ≫ sq.left := by simp [kernel_subobject_map] @[simp] lemma kernel_subobject_map_id : kernel_subobject_map (𝟙 (arrow.mk f)) = 𝟙 _ := by { ext, simp, dsimp, simp, } -- See library note [dsimp, simp]. @[simp] lemma kernel_subobject_map_comp {X'' Y'' : C} {f'' : X'' ⟶ Y''} [has_kernel f''] (sq : arrow.mk f ⟶ arrow.mk f') (sq' : arrow.mk f' ⟶ arrow.mk f'') : kernel_subobject_map (sq ≫ sq') = kernel_subobject_map sq ≫ kernel_subobject_map sq' := by { ext, simp, } end @[simp] lemma kernel_subobject_zero {A B : C} : kernel_subobject (0 : A ⟶ B) = ⊤ := (is_iso_iff_mk_eq_top _).mp (by apply_instance) instance is_iso_kernel_subobject_zero_arrow : is_iso (kernel_subobject (0 : X ⟶ Y)).arrow := (is_iso_arrow_iff_eq_top _).mpr kernel_subobject_zero lemma le_kernel_subobject (A : subobject X) (h : A.arrow ≫ f = 0) : A ≤ kernel_subobject f := subobject.le_mk_of_comm (kernel.lift f A.arrow h) (by simp) /-- The isomorphism between the kernel of `f ≫ g` and the kernel of `g`, when `f` is an isomorphism. -/ def kernel_subobject_iso_comp {X' : C} (f : X' ⟶ X) [is_iso f] (g : X ⟶ Y) [has_kernel g] : (kernel_subobject (f ≫ g) : C) ≅ (kernel_subobject g : C) := (kernel_subobject_iso _) ≪≫ (kernel_is_iso_comp f g) ≪≫ (kernel_subobject_iso _).symm @[simp] lemma kernel_subobject_iso_comp_hom_arrow {X' : C} (f : X' ⟶ X) [is_iso f] (g : X ⟶ Y) [has_kernel g] : (kernel_subobject_iso_comp f g).hom ≫ (kernel_subobject g).arrow = (kernel_subobject (f ≫ g)).arrow ≫ f := by { simp [kernel_subobject_iso_comp], } @[simp] lemma kernel_subobject_iso_comp_inv_arrow {X' : C} (f : X' ⟶ X) [is_iso f] (g : X ⟶ Y) [has_kernel g] : (kernel_subobject_iso_comp f g).inv ≫ (kernel_subobject (f ≫ g)).arrow = (kernel_subobject g).arrow ≫ inv f := by { simp [kernel_subobject_iso_comp], } /-- The kernel of `f` is always a smaller subobject than the kernel of `f ≫ h`. -/ lemma kernel_subobject_comp_le (f : X ⟶ Y) [has_kernel f] {Z : C} (h : Y ⟶ Z) [has_kernel (f ≫ h)]: kernel_subobject f ≤ kernel_subobject (f ≫ h) := le_kernel_subobject _ _ (by simp) /-- Postcomposing by an monomorphism does not change the kernel subobject. -/ @[simp] lemma kernel_subobject_comp_mono (f : X ⟶ Y) [has_kernel f] {Z : C} (h : Y ⟶ Z) [mono h] : kernel_subobject (f ≫ h) = kernel_subobject f := le_antisymm (le_kernel_subobject _ _ ((cancel_mono h).mp (by simp))) (kernel_subobject_comp_le f h) instance kernel_subobject_comp_mono_is_iso (f : X ⟶ Y) [has_kernel f] {Z : C} (h : Y ⟶ Z) [mono h] : is_iso (subobject.of_le _ _ (kernel_subobject_comp_le f h)) := begin rw of_le_mk_le_mk_of_comm (kernel_comp_mono f h).inv, { apply_instance, }, { simp, }, end end kernel section image variables (f : X ⟶ Y) [has_image f] /-- The image of a morphism `f g : X ⟶ Y` as a `subobject Y`. -/ abbreviation image_subobject : subobject Y := subobject.mk (image.ι f) /-- The underlying object of `image_subobject f` is (up to isomorphism!) the same as the chosen object `image f`. -/ def image_subobject_iso : (image_subobject f : C) ≅ image f := subobject.underlying_iso (image.ι f) @[simp, reassoc] lemma image_subobject_arrow : (image_subobject_iso f).hom ≫ image.ι f = (image_subobject f).arrow := by simp [image_subobject_iso] @[simp, reassoc] lemma image_subobject_arrow' : (image_subobject_iso f).inv ≫ (image_subobject f).arrow = image.ι f := by simp [image_subobject_iso] /-- A factorisation of `f : X ⟶ Y` through `image_subobject f`. -/ def factor_thru_image_subobject : X ⟶ image_subobject f := factor_thru_image f ≫ (image_subobject_iso f).inv instance [has_equalizers C] : epi (factor_thru_image_subobject f) := by { dsimp [factor_thru_image_subobject], apply epi_comp, } @[simp, reassoc, elementwise] lemma image_subobject_arrow_comp : factor_thru_image_subobject f ≫ (image_subobject f).arrow = f := by simp [factor_thru_image_subobject, image_subobject_arrow] lemma image_subobject_arrow_comp_eq_zero [has_zero_morphisms C] {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} [has_image f] [epi (factor_thru_image_subobject f)] (h : f ≫ g = 0) : (image_subobject f).arrow ≫ g = 0 := zero_of_epi_comp (factor_thru_image_subobject f) $ by simp [h] lemma image_subobject_factors_comp_self {W : C} (k : W ⟶ X) : (image_subobject f).factors (k ≫ f) := ⟨k ≫ factor_thru_image f, by simp⟩ @[simp] lemma factor_thru_image_subobject_comp_self {W : C} (k : W ⟶ X) (h) : (image_subobject f).factor_thru (k ≫ f) h = k ≫ factor_thru_image_subobject f := by { ext, simp, } @[simp] lemma factor_thru_image_subobject_comp_self_assoc {W W' : C} (k : W ⟶ W') (k' : W' ⟶ X) (h) : (image_subobject f).factor_thru (k ≫ k' ≫ f) h = k ≫ k' ≫ factor_thru_image_subobject f := by { ext, simp, } /-- The image of `h ≫ f` is always a smaller subobject than the image of `f`. -/ lemma image_subobject_comp_le {X' : C} (h : X' ⟶ X) (f : X ⟶ Y) [has_image f] [has_image (h ≫ f)] : image_subobject (h ≫ f) ≤ image_subobject f := subobject.mk_le_mk_of_comm (image.pre_comp h f) (by simp) section open_locale zero_object variables [has_zero_morphisms C] [has_zero_object C] @[simp] lemma image_subobject_zero_arrow : (image_subobject (0 : X ⟶ Y)).arrow = 0 := by { rw ←image_subobject_arrow, simp, } @[simp] lemma image_subobject_zero {A B : C} : image_subobject (0 : A ⟶ B) = ⊥ := subobject.eq_of_comm (image_subobject_iso _ ≪≫ image_zero ≪≫ subobject.bot_coe_iso_zero.symm) (by simp) end section variables [has_equalizers C] local attribute [instance] epi_comp /-- The morphism `image_subobject (h ≫ f) ⟶ image_subobject f` is an epimorphism when `h` is an epimorphism. In general this does not imply that `image_subobject (h ≫ f) = image_subobject f`, although it will when the ambient category is abelian. -/ instance image_subobject_comp_le_epi_of_epi {X' : C} (h : X' ⟶ X) [epi h] (f : X ⟶ Y) [has_image f] [has_image (h ≫ f)] : epi (subobject.of_le _ _ (image_subobject_comp_le h f)) := begin rw of_le_mk_le_mk_of_comm (image.pre_comp h f), { apply_instance, }, { simp, }, end end section variables [has_equalizers C] /-- Postcomposing by an isomorphism gives an isomorphism between image subobjects. -/ def image_subobject_comp_iso (f : X ⟶ Y) [has_image f] {Y' : C} (h : Y ⟶ Y') [is_iso h] : (image_subobject (f ≫ h) : C) ≅ (image_subobject f : C) := (image_subobject_iso _) ≪≫ (image.comp_iso _ _).symm ≪≫ (image_subobject_iso _).symm @[simp, reassoc] lemma image_subobject_comp_iso_hom_arrow (f : X ⟶ Y) [has_image f] {Y' : C} (h : Y ⟶ Y') [is_iso h] : (image_subobject_comp_iso f h).hom ≫ (image_subobject f).arrow = (image_subobject (f ≫ h)).arrow ≫ inv h := by simp [image_subobject_comp_iso] @[simp, reassoc] lemma image_subobject_comp_iso_inv_arrow (f : X ⟶ Y) [has_image f] {Y' : C} (h : Y ⟶ Y') [is_iso h] : (image_subobject_comp_iso f h).inv ≫ (image_subobject (f ≫ h)).arrow = (image_subobject f).arrow ≫ h := by simp [image_subobject_comp_iso] end lemma image_subobject_mono (f : X ⟶ Y) [mono f] : image_subobject f = mk f := eq_of_comm (image_subobject_iso f ≪≫ image_mono_iso_source f ≪≫ (underlying_iso f).symm) (by simp) /-- Precomposing by an isomorphism does not change the image subobject. -/ lemma image_subobject_iso_comp [has_equalizers C] {X' : C} (h : X' ⟶ X) [is_iso h] (f : X ⟶ Y) [has_image f] : image_subobject (h ≫ f) = image_subobject f := le_antisymm (image_subobject_comp_le h f) (subobject.mk_le_mk_of_comm (inv (image.pre_comp h f)) (by simp)) lemma image_subobject_le {A B : C} {X : subobject B} (f : A ⟶ B) [has_image f] (h : A ⟶ X) (w : h ≫ X.arrow = f) : image_subobject f ≤ X := subobject.le_of_comm ((image_subobject_iso f).hom ≫ image.lift { I := (X : C), e := h, m := X.arrow, }) (by simp) lemma image_subobject_le_mk {A B : C} {X : C} (g : X ⟶ B) [mono g] (f : A ⟶ B) [has_image f] (h : A ⟶ X) (w : h ≫ g = f) : image_subobject f ≤ subobject.mk g := image_subobject_le f (h ≫ (subobject.underlying_iso g).inv) (by simp [w]) /-- Given a commutative square between morphisms `f` and `g`, we have a morphism in the category from `image_subobject f` to `image_subobject g`. -/ def image_subobject_map {W X Y Z : C} {f : W ⟶ X} [has_image f] {g : Y ⟶ Z} [has_image g] (sq : arrow.mk f ⟶ arrow.mk g) [has_image_map sq] : (image_subobject f : C) ⟶ (image_subobject g : C) := (image_subobject_iso f).hom ≫ image.map sq ≫ (image_subobject_iso g).inv @[simp, reassoc] lemma image_subobject_map_arrow {W X Y Z : C} {f : W ⟶ X} [has_image f] {g : Y ⟶ Z} [has_image g] (sq : arrow.mk f ⟶ arrow.mk g) [has_image_map sq] : image_subobject_map sq ≫ (image_subobject g).arrow = (image_subobject f).arrow ≫ sq.right := begin simp only [image_subobject_map, category.assoc, image_subobject_arrow'], erw [image.map_ι, ←category.assoc, image_subobject_arrow], end end image end limits end category_theory
242b386d03bd3afab071a3f7d3e7ffeb77603894
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/sheaves/sheaf_of_functions.lean
898392538653793b789b33c68a32051747258463
[ "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
3,985
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Scott Morrison -/ import category_theory.limits.shapes.types import topology.sheaves.presheaf_of_functions import topology.sheaves.sheaf_condition.unique_gluing /-! # Sheaf conditions for presheaves of (continuous) functions. We show that * `Top.presheaf.to_Type_is_sheaf`: not-necessarily-continuous functions into a type form a sheaf * `Top.presheaf.to_Types_is_sheaf`: in fact, these may be dependent functions into a type family For * `Top.sheaf_to_Top`: continuous functions into a topological space form a sheaf please see `topology/sheaves/local_predicate.lean`, where we set up a general framework for constructing sub(pre)sheaves of the sheaf of dependent functions. ## Future work Obviously there's more to do: * sections of a fiber bundle * various classes of smooth and structure preserving functions * functions into spaces with algebraic structure, which the sections inherit -/ open category_theory open category_theory.limits open topological_space open topological_space.opens universe u noncomputable theory variables (X : Top.{u}) open Top namespace Top.presheaf /-- We show that the presheaf of functions to a type `T` (no continuity assumptions, just plain functions) form a sheaf. In fact, the proof is identical when we do this for dependent functions to a type family `T`, so we do the more general case. -/ lemma to_Types_is_sheaf (T : X → Type u) : (presheaf_to_Types X T).is_sheaf := is_sheaf_of_is_sheaf_unique_gluing_types _ $ λ ι U sf hsf, -- We use the sheaf condition in terms of unique gluing -- U is a family of open sets, indexed by `ι` and `sf` is a compatible family of sections. -- In the informal comments below, I'll just write `U` to represent the union. begin -- Our first goal is to define a function "lifted" to all of `U`. -- We do this one point at a time. Using the axiom of choice, we can pick for each -- `x : supr U` an index `i : ι` such that `x` lies in `U i` choose index index_spec using λ x : supr U, opens.mem_supr.mp x.2, -- Using this data, we can glue our functions together to a single section let s : Π x : supr U, T x := λ x, sf (index x) ⟨x.1, index_spec x⟩, refine ⟨s,_,_⟩, { intro i, ext x, -- Now we need to verify that this lifted function restricts correctly to each set `U i`. -- Of course, the difficulty is that at any given point `x ∈ U i`, -- we may have used the axiom of choice to pick a different `j` with `x ∈ U j` -- when defining the function. -- Thus we'll need to use the fact that the restrictions are compatible. convert congr_fun (hsf (index ⟨x,_⟩) i) ⟨x,⟨index_spec ⟨x.1,_⟩,x.2⟩⟩, ext, refl }, { -- Now we just need to check that the lift we picked was the only possible one. -- So we suppose we had some other gluing `t` of our sections intros t ht, -- and observe that we need to check that it agrees with our choice -- for each `f : s .X` and each `x ∈ supr U`. ext x, convert congr_fun (ht (index x)) ⟨x.1,index_spec x⟩, ext, refl } end -- We verify that the non-dependent version is an immediate consequence: /-- The presheaf of not-necessarily-continuous functions to a target type `T` satsifies the sheaf condition. -/ lemma to_Type_is_sheaf (T : Type u) : (presheaf_to_Type X T).is_sheaf := to_Types_is_sheaf X (λ _, T) end Top.presheaf namespace Top /-- The sheaf of not-necessarily-continuous functions on `X` with values in type family `T : X → Type u`. -/ def sheaf_to_Types (T : X → Type u) : sheaf (Type u) X := ⟨presheaf_to_Types X T, presheaf.to_Types_is_sheaf _ _⟩ /-- The sheaf of not-necessarily-continuous functions on `X` with values in a type `T`. -/ def sheaf_to_Type (T : Type u) : sheaf (Type u) X := ⟨presheaf_to_Type X T, presheaf.to_Type_is_sheaf _ _⟩ end Top
6f77e54fb4f0cc2f992c065baf487a9718568e17
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/number_theory/pell.lean
1fee2ef79f7f99fb1e698f57492a3b534e569839
[ "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
37,677
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.nat.modeq import number_theory.zsqrtd.basic /-! # Pell's equation and Matiyasevic's theorem This file solves Pell's equation, i.e. integer solutions to `x ^ 2 - d * y ^ 2 = 1` in the special case that `d = a ^ 2 - 1`. This is then applied to prove Matiyasevic's theorem that the power function is Diophantine, which is the last key ingredient in the solution to Hilbert's tenth problem. For the definition of Diophantine function, see `dioph.lean`. ## Main definition * `pell` is a function assigning to a natural number `n` the `n`-th solution to Pell's equation constructed recursively from the initial solution `(0, 1)`. ## Main statements * `eq_pell` shows that every solution to Pell's equation is recursively obtained using `pell` * `matiyasevic` shows that a certain system of Diophantine equations has a solution if and only if the first variable is the `x`-component in a solution to Pell's equation - the key step towards Hilbert's tenth problem in Davis' version of Matiyasevic's theorem. * `eq_pow_of_pell` shows that the power function is Diophantine. ## Implementation notes The proof of Matiyasevic's theorem doesn't follow Matiyasevic's original account of using Fibonacci numbers but instead Davis' variant of using solutions to Pell's equation. ## References * [M. Carneiro, _A Lean formalization of Matiyasevič's theorem_][carneiro2018matiyasevic] * [M. Davis, _Hilbert's tenth problem is unsolvable_][MR317916] ## Tags Pell's equation, Matiyasevic's theorem, Hilbert's tenth problem ## TODO * Provide solutions to Pell's equation for the case of arbitrary `d` (not just `d = a ^ 2 - 1` like in the current version) and furthermore also for `x ^ 2 - d * y ^ 2 = -1`. * Connect solutions to the continued fraction expansion of `√d`. -/ namespace pell open nat section parameters {a : ℕ} (a1 : 1 < a) include a1 private def d := a*a - 1 @[simp] theorem d_pos : 0 < d := nat.sub_pos_of_lt (mul_lt_mul a1 (le_of_lt a1) dec_trivial dec_trivial : 1*1<a*a) /-- The Pell sequences, i.e. the sequence of integer solutions to `x ^ 2 - d * y ^ 2 = 1`, where `d = a ^ 2 - 1`, defined together in mutual recursion. -/ -- TODO(lint): Fix double namespace issue @[nolint dup_namespace] def pell : ℕ → ℕ × ℕ := λn, nat.rec_on n (1, 0) (λn xy, (xy.1*a + d*xy.2, xy.1 + xy.2*a)) /-- The Pell `x` sequence. -/ def xn (n : ℕ) : ℕ := (pell n).1 /-- The Pell `y` sequence. -/ def yn (n : ℕ) : ℕ := (pell n).2 @[simp] theorem pell_val (n : ℕ) : pell n = (xn n, yn n) := show pell n = ((pell n).1, (pell n).2), from match pell n with (a, b) := rfl end @[simp] theorem xn_zero : xn 0 = 1 := rfl @[simp] theorem yn_zero : yn 0 = 0 := rfl @[simp] theorem xn_succ (n : ℕ) : xn (n+1) = xn n * a + d * yn n := rfl @[simp] theorem yn_succ (n : ℕ) : yn (n+1) = xn n + yn n * a := rfl @[simp] theorem xn_one : xn 1 = a := by simp @[simp] theorem yn_one : yn 1 = 1 := by simp /-- The Pell `x` sequence, considered as an integer sequence.-/ def xz (n : ℕ) : ℤ := xn n /-- The Pell `y` sequence, considered as an integer sequence.-/ def yz (n : ℕ) : ℤ := yn n section omit a1 /-- The element `a` such that `d = a ^ 2 - 1`, considered as an integer.-/ def az : ℤ := a end theorem asq_pos : 0 < a*a := le_trans (le_of_lt a1) (by have := @nat.mul_le_mul_left 1 a a (le_of_lt a1); rwa mul_one at this) theorem dz_val : ↑d = az*az - 1 := have 1 ≤ a*a, from asq_pos, show ↑(a*a - 1) = _, by rw int.coe_nat_sub this; refl @[simp] theorem xz_succ (n : ℕ) : xz (n+1) = xz n * az + ↑d * yz n := rfl @[simp] theorem yz_succ (n : ℕ) : yz (n+1) = xz n + yz n * az := rfl /-- The Pell sequence can also be viewed as an element of `ℤ√d` -/ def pell_zd (n : ℕ) : ℤ√d := ⟨xn n, yn n⟩ @[simp] theorem pell_zd_re (n : ℕ) : (pell_zd n).re = xn n := rfl @[simp] theorem pell_zd_im (n : ℕ) : (pell_zd n).im = yn n := rfl /-- The property of being a solution to the Pell equation, expressed as a property of elements of `ℤ√d`. -/ def is_pell : ℤ√d → Prop | ⟨x, y⟩ := x*x - d*y*y = 1 theorem is_pell_nat {x y : ℕ} : is_pell ⟨x, y⟩ ↔ x*x - d*y*y = 1 := ⟨λh, int.coe_nat_inj (by rw int.coe_nat_sub (int.le_of_coe_nat_le_coe_nat $ int.le.intro_sub h); exact h), λh, show ((x*x : ℕ) - (d*y*y:ℕ) : ℤ) = 1, by rw [← int.coe_nat_sub $ le_of_lt $ nat.lt_of_sub_eq_succ h, h]; refl⟩ theorem is_pell_norm : Π {b : ℤ√d}, is_pell b ↔ b * b.conj = 1 | ⟨x, y⟩ := by simp [zsqrtd.ext, is_pell, mul_comm]; ring_nf theorem is_pell_mul {b c : ℤ√d} (hb : is_pell b) (hc : is_pell c) : is_pell (b * c) := is_pell_norm.2 (by simp [mul_comm, mul_left_comm, zsqrtd.conj_mul, pell.is_pell_norm.1 hb, pell.is_pell_norm.1 hc]) theorem is_pell_conj : ∀ {b : ℤ√d}, is_pell b ↔ is_pell b.conj | ⟨x, y⟩ := by simp [is_pell, zsqrtd.conj] @[simp] theorem pell_zd_succ (n : ℕ) : pell_zd (n+1) = pell_zd n * ⟨a, 1⟩ := by simp [zsqrtd.ext] theorem is_pell_one : is_pell ⟨a, 1⟩ := show az*az-d*1*1=1, by simp [dz_val]; ring theorem is_pell_pell_zd : ∀ (n : ℕ), is_pell (pell_zd n) | 0 := rfl | (n+1) := let o := is_pell_one in by simp; exact pell.is_pell_mul (is_pell_pell_zd n) o @[simp] theorem pell_eqz (n : ℕ) : xz n * xz n - d * yz n * yz n = 1 := is_pell_pell_zd n @[simp] theorem pell_eq (n : ℕ) : xn n * xn n - d * yn n * yn n = 1 := let pn := pell_eqz n in have h : (↑(xn n * xn n) : ℤ) - ↑(d * yn n * yn n) = 1, by repeat {rw int.coe_nat_mul}; exact pn, have hl : d * yn n * yn n ≤ xn n * xn n, from int.le_of_coe_nat_le_coe_nat $ int.le.intro $ add_eq_of_eq_sub' $ eq.symm h, int.coe_nat_inj (by rw int.coe_nat_sub hl; exact h) instance dnsq : zsqrtd.nonsquare d := ⟨λn h, have n*n + 1 = a*a, by rw ← h; exact nat.succ_pred_eq_of_pos (asq_pos a1), have na : n < a, from nat.mul_self_lt_mul_self_iff.2 (by rw ← this; exact nat.lt_succ_self _), have (n+1)*(n+1) ≤ n*n + 1, by rw this; exact nat.mul_self_le_mul_self na, have n+n ≤ 0, from @nat.le_of_add_le_add_right (n*n + 1) _ _ (by ring_nf at this ⊢; assumption), ne_of_gt d_pos $ by rwa nat.eq_zero_of_le_zero ((nat.le_add_left _ _).trans this) at h⟩ theorem xn_ge_a_pow : ∀ (n : ℕ), a^n ≤ xn n | 0 := le_refl 1 | (n+1) := by simp [pow_succ']; exact le_trans (nat.mul_le_mul_right _ (xn_ge_a_pow n)) (nat.le_add_right _ _) theorem n_lt_a_pow : ∀ (n : ℕ), n < a^n | 0 := nat.le_refl 1 | (n+1) := begin have IH := n_lt_a_pow n, have : a^n + a^n ≤ a^n * a, { rw ← mul_two, exact nat.mul_le_mul_left _ a1 }, simp [pow_succ'], refine lt_of_lt_of_le _ this, exact add_lt_add_of_lt_of_le IH (lt_of_le_of_lt (nat.zero_le _) IH) end theorem n_lt_xn (n) : n < xn n := lt_of_lt_of_le (n_lt_a_pow n) (xn_ge_a_pow n) theorem x_pos (n) : 0 < xn n := lt_of_le_of_lt (nat.zero_le n) (n_lt_xn n) lemma eq_pell_lem : ∀n (b:ℤ√d), 1 ≤ b → is_pell b → b ≤ pell_zd n → ∃n, b = pell_zd n | 0 b := λh1 hp hl, ⟨0, @zsqrtd.le_antisymm _ dnsq _ _ hl h1⟩ | (n+1) b := λh1 hp h, have a1p : (0:ℤ√d) ≤ ⟨a, 1⟩, from trivial, have am1p : (0:ℤ√d) ≤ ⟨a, -1⟩, from show (_:nat) ≤ _, by simp; exact nat.pred_le _, have a1m : (⟨a, 1⟩ * ⟨a, -1⟩ : ℤ√d) = 1, from is_pell_norm.1 is_pell_one, if ha : (⟨↑a, 1⟩ : ℤ√d) ≤ b then let ⟨m, e⟩ := eq_pell_lem n (b * ⟨a, -1⟩) (by rw ← a1m; exact mul_le_mul_of_nonneg_right ha am1p) (is_pell_mul hp (is_pell_conj.1 is_pell_one)) (by have t := mul_le_mul_of_nonneg_right h am1p; rwa [pell_zd_succ, mul_assoc, a1m, mul_one] at t) in ⟨m+1, by rw [show b = b * ⟨a, -1⟩ * ⟨a, 1⟩, by rw [mul_assoc, eq.trans (mul_comm _ _) a1m]; simp, pell_zd_succ, e]⟩ else suffices ¬1 < b, from ⟨0, show b = 1, from (or.resolve_left (lt_or_eq_of_le h1) this).symm⟩, λ h1l, by cases b with x y; exact have bm : (_*⟨_,_⟩ :ℤ√(d a1)) = 1, from pell.is_pell_norm.1 hp, have y0l : (0:ℤ√(d a1)) < ⟨x - x, y - -y⟩, from sub_lt_sub h1l $ λ(hn : (1:ℤ√(d a1)) ≤ ⟨x, -y⟩), by have t := mul_le_mul_of_nonneg_left hn (le_trans zero_le_one h1); rw [bm, mul_one] at t; exact h1l t, have yl2 : (⟨_, _⟩ : ℤ√_) < ⟨_, _⟩, from show (⟨x, y⟩ - ⟨x, -y⟩ : ℤ√(d a1)) < ⟨a, 1⟩ - ⟨a, -1⟩, from sub_lt_sub (by exact ha) $ λ(hn : (⟨x, -y⟩ : ℤ√(d a1)) ≤ ⟨a, -1⟩), by have t := mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left hn (le_trans zero_le_one h1)) a1p; rw [bm, one_mul, mul_assoc, eq.trans (mul_comm _ _) a1m, mul_one] at t; exact ha t, by simp at y0l; simp at yl2; exact match y, y0l, (yl2 : (⟨_, _⟩ : ℤ√_) < ⟨_, _⟩) with | 0, y0l, yl2 := y0l (le_refl 0) | (y+1 : ℕ), y0l, yl2 := yl2 (zsqrtd.le_of_le_le (le_refl 0) (let t := int.coe_nat_le_coe_nat_of_le (nat.succ_pos y) in add_le_add t t)) | -[1+y], y0l, yl2 := y0l trivial end theorem eq_pell_zd (b : ℤ√d) (b1 : 1 ≤ b) (hp : is_pell b) : ∃n, b = pell_zd n := let ⟨n, h⟩ := @zsqrtd.le_arch d b in eq_pell_lem n b b1 hp $ zsqrtd.le_trans h $ by rw zsqrtd.coe_nat_val; exact zsqrtd.le_of_le_le (int.coe_nat_le_coe_nat_of_le $ le_of_lt $ n_lt_xn _ _) (int.coe_zero_le _) /-- Every solution to **Pell's equation** is recursively obtained from the initial solution `(1,0)` using the recursion `pell`. -/ theorem eq_pell {x y : ℕ} (hp : x*x - d*y*y = 1) : ∃n, x = xn n ∧ y = yn n := have (1:ℤ√d) ≤ ⟨x, y⟩, from match x, hp with | 0, (hp : 0 - _ = 1) := by rw nat.zero_sub at hp; contradiction | (x+1), hp := zsqrtd.le_of_le_le (int.coe_nat_le_coe_nat_of_le $ nat.succ_pos x) (int.coe_zero_le _) end, let ⟨m, e⟩ := eq_pell_zd ⟨x, y⟩ this (is_pell_nat.2 hp) in ⟨m, match x, y, e with ._, ._, rfl := ⟨rfl, rfl⟩ end⟩ theorem pell_zd_add (m) : ∀ n, pell_zd (m + n) = pell_zd m * pell_zd n | 0 := (mul_one _).symm | (n+1) := by rw[← add_assoc, pell_zd_succ, pell_zd_succ, pell_zd_add n, ← mul_assoc] theorem xn_add (m n) : xn (m + n) = xn m * xn n + d * yn m * yn n := by injection (pell_zd_add _ m n) with h _; repeat {rw ← int.coe_nat_add at h <|> rw ← int.coe_nat_mul at h}; exact int.coe_nat_inj h theorem yn_add (m n) : yn (m + n) = xn m * yn n + yn m * xn n := by injection (pell_zd_add _ m n) with _ h; repeat {rw ← int.coe_nat_add at h <|> rw ← int.coe_nat_mul at h}; exact int.coe_nat_inj h theorem pell_zd_sub {m n} (h : n ≤ m) : pell_zd (m - n) = pell_zd m * (pell_zd n).conj := let t := pell_zd_add n (m - n) in by rw [nat.add_sub_of_le h] at t; rw [t, mul_comm (pell_zd _ n) _, mul_assoc, (is_pell_norm _).1 (is_pell_pell_zd _ _), mul_one] theorem xz_sub {m n} (h : n ≤ m) : xz (m - n) = xz m * xz n - d * yz m * yz n := by injection (pell_zd_sub _ h) with h _; repeat {rw ← neg_mul_eq_mul_neg at h}; exact h theorem yz_sub {m n} (h : n ≤ m) : yz (m - n) = xz n * yz m - xz m * yz n := by injection (pell_zd_sub a1 h) with _ h; repeat {rw ← neg_mul_eq_mul_neg at h}; rw [add_comm, mul_comm] at h; exact h theorem xy_coprime (n) : (xn n).coprime (yn n) := nat.coprime_of_dvd' $ λk kp kx ky, let p := pell_eq n in by rw ← p; exact nat.dvd_sub (le_of_lt $ nat.lt_of_sub_eq_succ p) (kx.mul_left _) (ky.mul_left _) theorem strict_mono_y : strict_mono yn | m 0 h := absurd h $ nat.not_lt_zero _ | m (n+1) h := have yn m ≤ yn n, from or.elim (lt_or_eq_of_le $ nat.le_of_succ_le_succ h) (λhl, le_of_lt $ strict_mono_y hl) (λe, by rw e), by simp; refine lt_of_le_of_lt _ (nat.lt_add_of_pos_left $ x_pos a1 n); rw ← mul_one (yn a1 m); exact mul_le_mul this (le_of_lt a1) (nat.zero_le _) (nat.zero_le _) theorem strict_mono_x : strict_mono xn | m 0 h := absurd h $ nat.not_lt_zero _ | m (n+1) h := have xn m ≤ xn n, from or.elim (lt_or_eq_of_le $ nat.le_of_succ_le_succ h) (λhl, le_of_lt $ strict_mono_x hl) (λe, by rw e), by simp; refine lt_of_lt_of_le (lt_of_le_of_lt this _) (nat.le_add_right _ _); have t := nat.mul_lt_mul_of_pos_left a1 (x_pos a1 n); rwa mul_one at t theorem yn_ge_n : Π n, n ≤ yn n | 0 := nat.zero_le _ | (n+1) := show n < yn (n+1), from lt_of_le_of_lt (yn_ge_n n) (strict_mono_y $ nat.lt_succ_self n) theorem y_mul_dvd (n) : ∀k, yn n ∣ yn (n * k) | 0 := dvd_zero _ | (k+1) := by rw [nat.mul_succ, yn_add]; exact dvd_add (dvd_mul_left _ _) ((y_mul_dvd k).mul_right _) theorem y_dvd_iff (m n) : yn m ∣ yn n ↔ m ∣ n := ⟨λh, nat.dvd_of_mod_eq_zero $ (nat.eq_zero_or_pos _).resolve_right $ λhp, have co : nat.coprime (yn m) (xn (m * (n / m))), from nat.coprime.symm $ (xy_coprime _).coprime_dvd_right (y_mul_dvd m (n / m)), have m0 : 0 < m, from m.eq_zero_or_pos.resolve_left $ λe, by rw [e, nat.mod_zero] at hp; rw [e] at h; exact ne_of_lt (strict_mono_y a1 hp) (eq_zero_of_zero_dvd h).symm, by rw [← nat.mod_add_div n m, yn_add] at h; exact not_le_of_gt (strict_mono_y _ $ nat.mod_lt n m0) (nat.le_of_dvd (strict_mono_y _ hp) $ co.dvd_of_dvd_mul_right $ (nat.dvd_add_iff_right $ (y_mul_dvd _ _ _).mul_left _).2 h), λ⟨k, e⟩, by rw e; apply y_mul_dvd⟩ theorem xy_modeq_yn (n) : ∀ k, xn (n * k) ≡ (xn n)^k [MOD (yn n)^2] ∧ yn (n * k) ≡ k * (xn n)^(k-1) * yn n [MOD (yn n)^3] | 0 := by constructor; simp | (k+1) := let ⟨hx, hy⟩ := xy_modeq_yn k in have L : xn (n * k) * xn n + d * yn (n * k) * yn n ≡ xn n^k * xn n + 0 [MOD yn n^2], from (hx.mul_right _ ).add $ modeq_zero_iff_dvd.2 $ by rw pow_succ'; exact mul_dvd_mul_right (dvd_mul_of_dvd_right (modeq_zero_iff_dvd.1 $ (hy.modeq_of_dvd $ by simp [pow_succ']).trans $ modeq_zero_iff_dvd.2 $ by simp [-mul_comm, -mul_assoc]) _) _, have R : xn (n * k) * yn n + yn (n * k) * xn n ≡ xn n^k * yn n + k * xn n^k * yn n [MOD yn n^3], from modeq.add (by { rw pow_succ', exact hx.mul_right' _ }) $ have k * xn n^(k - 1) * yn n * xn n = k * xn n^k * yn n, by clear _let_match; cases k with k; simp [pow_succ', mul_comm, mul_left_comm], by { rw ← this, exact hy.mul_right _ }, by { rw [nat.add_sub_cancel, nat.mul_succ, xn_add, yn_add, pow_succ' (xn _ n), nat.succ_mul, add_comm (k * xn _ n^k) (xn _ n^k), right_distrib], exact ⟨L, R⟩ } theorem ysq_dvd_yy (n) : yn n * yn n ∣ yn (n * yn n) := modeq_zero_iff_dvd.1 $ ((xy_modeq_yn n (yn n)).right.modeq_of_dvd $ by simp [pow_succ]).trans (modeq_zero_iff_dvd.2 $ by simp [mul_dvd_mul_left, mul_assoc]) theorem dvd_of_ysq_dvd {n t} (h : yn n * yn n ∣ yn t) : yn n ∣ t := have nt : n ∣ t, from (y_dvd_iff n t).1 $ dvd_of_mul_left_dvd h, n.eq_zero_or_pos.elim (λ n0, by rwa n0 at ⊢ nt) $ λ (n0l : 0 < n), let ⟨k, ke⟩ := nt in have yn n ∣ k * (xn n)^(k-1), from nat.dvd_of_mul_dvd_mul_right (strict_mono_y n0l) $ modeq_zero_iff_dvd.1 $ by have xm := (xy_modeq_yn a1 n k).right; rw ← ke at xm; exact (xm.modeq_of_dvd $ by simp [pow_succ]).symm.trans h.modeq_zero_nat, by rw ke; exact dvd_mul_of_dvd_right (((xy_coprime _ _).pow_left _).symm.dvd_of_dvd_mul_right this) _ theorem pell_zd_succ_succ (n) : pell_zd (n + 2) + pell_zd n = (2 * a : ℕ) * pell_zd (n + 1) := have (1:ℤ√d) + ⟨a, 1⟩ * ⟨a, 1⟩ = ⟨a, 1⟩ * (2 * a), by { rw zsqrtd.coe_nat_val, change (⟨_,_⟩:ℤ√(d a1))=⟨_,_⟩, rw dz_val, dsimp [az], rw zsqrtd.ext, dsimp, split; ring }, by simpa [mul_add, mul_comm, mul_left_comm, add_comm] using congr_arg (* pell_zd a1 n) this theorem xy_succ_succ (n) : xn (n + 2) + xn n = (2 * a) * xn (n + 1) ∧ yn (n + 2) + yn n = (2 * a) * yn (n + 1) := begin have := pell_zd_succ_succ a1 n, unfold pell_zd at this, rw [← int.cast_coe_nat, zsqrtd.smul_val] at this, injection this with h₁ h₂, split; apply int.coe_nat_inj; [simpa using h₁, simpa using h₂] end theorem xn_succ_succ (n) : xn (n + 2) + xn n = (2 * a) * xn (n + 1) := (xy_succ_succ n).1 theorem yn_succ_succ (n) : yn (n + 2) + yn n = (2 * a) * yn (n + 1) := (xy_succ_succ n).2 theorem xz_succ_succ (n) : xz (n + 2) = (2 * a : ℕ) * xz (n + 1) - xz n := eq_sub_of_add_eq $ by delta xz; rw [← int.coe_nat_add, ← int.coe_nat_mul, xn_succ_succ] theorem yz_succ_succ (n) : yz (n + 2) = (2 * a : ℕ) * yz (n + 1) - yz n := eq_sub_of_add_eq $ by delta yz; rw [← int.coe_nat_add, ← int.coe_nat_mul, yn_succ_succ] theorem yn_modeq_a_sub_one : ∀ n, yn n ≡ n [MOD a-1] | 0 := by simp | 1 := by simp | (n+2) := (yn_modeq_a_sub_one n).add_right_cancel $ begin rw [yn_succ_succ, (by ring : n + 2 + n = 2 * (n + 1))], exact ((modeq_sub a1.le).mul_left 2).mul (yn_modeq_a_sub_one (n+1)), end theorem yn_modeq_two : ∀ n, yn n ≡ n [MOD 2] | 0 := by simp | 1 := by simp | (n+2) := (yn_modeq_two n).add_right_cancel $ begin rw [yn_succ_succ, mul_assoc, (by ring : n + 2 + n = 2 * (n + 1))], exact (dvd_mul_right 2 _).modeq_zero_nat.trans (dvd_mul_right 2 _).zero_modeq_nat, end section omit a1 lemma x_sub_y_dvd_pow_lem (y2 y1 y0 yn1 yn0 xn1 xn0 ay a2 : ℤ) : (a2 * yn1 - yn0) * ay + y2 - (a2 * xn1 - xn0) = y2 - a2 * y1 + y0 + a2 * (yn1 * ay + y1 - xn1) - (yn0 * ay + y0 - xn0) := by ring end theorem x_sub_y_dvd_pow (y : ℕ) : ∀ n, (2*a*y - y*y - 1 : ℤ) ∣ yz n * (a - y) + ↑(y^n) - xz n | 0 := by simp [xz, yz, int.coe_nat_zero, int.coe_nat_one] | 1 := by simp [xz, yz, int.coe_nat_zero, int.coe_nat_one] | (n+2) := have (2*a*y - y*y - 1 : ℤ) ∣ ↑(y^(n + 2)) - ↑(2 * a) * ↑(y^(n + 1)) + ↑(y^n), from ⟨-↑(y^n), by { simp [pow_succ, mul_add, int.coe_nat_mul, show ((2:ℕ):ℤ) = 2, from rfl, mul_comm, mul_left_comm], ring }⟩, by { rw [xz_succ_succ, yz_succ_succ, x_sub_y_dvd_pow_lem ↑(y^(n+2)) ↑(y^(n+1)) ↑(y^n)], exact dvd_sub (dvd_add this $ (x_sub_y_dvd_pow (n+1)).mul_left _) (x_sub_y_dvd_pow n) } theorem xn_modeq_x2n_add_lem (n j) : xn n ∣ d * yn n * (yn n * xn j) + xn j := have h1 : d * yn n * (yn n * xn j) + xn j = (d * yn n * yn n + 1) * xn j, by simp [add_mul, mul_assoc], have h2 : d * yn n * yn n + 1 = xn n * xn n, by apply int.coe_nat_inj; repeat {rw int.coe_nat_add <|> rw int.coe_nat_mul}; exact add_eq_of_eq_sub' (eq.symm $ pell_eqz _ _), by rw h2 at h1; rw [h1, mul_assoc]; exact dvd_mul_right _ _ theorem xn_modeq_x2n_add (n j) : xn (2 * n + j) + xn j ≡ 0 [MOD xn n] := begin rw [two_mul, add_assoc, xn_add, add_assoc, ←zero_add 0], refine (dvd_mul_right (xn a1 n) (xn a1 (n + j))).modeq_zero_nat.add _, rw [yn_add, left_distrib, add_assoc, ←zero_add 0], exact ((dvd_mul_right _ _).mul_left _).modeq_zero_nat.add (xn_modeq_x2n_add_lem _ _ _).modeq_zero_nat, end lemma xn_modeq_x2n_sub_lem {n j} (h : j ≤ n) : xn (2 * n - j) + xn j ≡ 0 [MOD xn n] := have h1 : xz n ∣ ↑d * yz n * yz (n - j) + xz j, by rw [yz_sub _ h, mul_sub_left_distrib, sub_add_eq_add_sub]; exact dvd_sub (by delta xz; delta yz; repeat {rw ← int.coe_nat_add <|> rw ← int.coe_nat_mul}; rw mul_comm (xn a1 j) (yn a1 n); exact int.coe_nat_dvd.2 (xn_modeq_x2n_add_lem _ _ _)) ((dvd_mul_right _ _).mul_left _), begin rw [two_mul, nat.add_sub_assoc h, xn_add, add_assoc, ←zero_add 0], exact (dvd_mul_right _ _).modeq_zero_nat.add (int.coe_nat_dvd.1 $ by simpa [xz, yz] using h1).modeq_zero_nat, end theorem xn_modeq_x2n_sub {n j} (h : j ≤ 2 * n) : xn (2 * n - j) + xn j ≡ 0 [MOD xn n] := (le_total j n).elim xn_modeq_x2n_sub_lem (λjn, have 2 * n - j + j ≤ n + j, by rw [nat.sub_add_cancel h, two_mul]; exact nat.add_le_add_left jn _, let t := xn_modeq_x2n_sub_lem (nat.le_of_add_le_add_right this) in by rwa [nat.sub_sub_self h, add_comm] at t) theorem xn_modeq_x4n_add (n j) : xn (4 * n + j) ≡ xn j [MOD xn n] := modeq.add_right_cancel' (xn (2 * n + j)) $ by refine @modeq.trans _ _ 0 _ _ (by rw add_comm; exact (xn_modeq_x2n_add _ _ _).symm); rw [show 4*n = 2*n + 2*n, from right_distrib 2 2 n, add_assoc]; apply xn_modeq_x2n_add theorem xn_modeq_x4n_sub {n j} (h : j ≤ 2 * n) : xn (4 * n - j) ≡ xn j [MOD xn n] := have h' : j ≤ 2*n, from le_trans h (by rw nat.succ_mul; apply nat.le_add_left), modeq.add_right_cancel' (xn (2 * n - j)) $ by refine @modeq.trans _ _ 0 _ _ (by rw add_comm; exact (xn_modeq_x2n_sub _ h).symm); rw [show 4*n = 2*n + 2*n, from right_distrib 2 2 n, nat.add_sub_assoc h']; apply xn_modeq_x2n_add theorem eq_of_xn_modeq_lem1 {i n} : Π {j}, i < j → j < n → xn i % xn n < xn j % xn n | 0 ij _ := absurd ij (nat.not_lt_zero _) | (j+1) ij jn := suffices xn j % xn n < xn (j + 1) % xn n, from (lt_or_eq_of_le (nat.le_of_succ_le_succ ij)).elim (λh, lt_trans (eq_of_xn_modeq_lem1 h (le_of_lt jn)) this) (λh, by rw h; exact this), by rw [nat.mod_eq_of_lt (strict_mono_x _ (nat.lt_of_succ_lt jn)), nat.mod_eq_of_lt (strict_mono_x _ jn)]; exact strict_mono_x _ (nat.lt_succ_self _) theorem eq_of_xn_modeq_lem2 {n} (h : 2 * xn n = xn (n + 1)) : a = 2 ∧ n = 0 := by rw [xn_succ, mul_comm] at h; exact have n = 0, from n.eq_zero_or_pos.resolve_right $ λnp, ne_of_lt (lt_of_le_of_lt (nat.mul_le_mul_left _ a1) (nat.lt_add_of_pos_right $ mul_pos (d_pos a1) (strict_mono_y a1 np))) h, by cases this; simp at h; exact ⟨h.symm, rfl⟩ theorem eq_of_xn_modeq_lem3 {i n} (npos : 0 < n) : Π {j}, i < j → j ≤ 2 * n → j ≠ n → ¬(a = 2 ∧ n = 1 ∧ i = 0 ∧ j = 2) → xn i % xn n < xn j % xn n | 0 ij _ _ _ := absurd ij (nat.not_lt_zero _) | (j+1) ij j2n jnn ntriv := have lem2 : ∀k > n, k ≤ 2*n → (↑(xn k % xn n) : ℤ) = xn n - xn (2 * n - k), from λk kn k2n, let k2nl := lt_of_add_lt_add_right $ show 2*n-k+k < n+k, by {rw nat.sub_add_cancel, rw two_mul; exact (add_lt_add_left kn n), exact k2n } in have xle : xn (2 * n - k) ≤ xn n, from le_of_lt $ strict_mono_x k2nl, suffices xn k % xn n = xn n - xn (2 * n - k), by rw [this, int.coe_nat_sub xle], by { rw ← nat.mod_eq_of_lt (nat.sub_lt (x_pos a1 n) (x_pos a1 (2 * n - k))), apply modeq.add_right_cancel' (xn a1 (2 * n - k)), rw [nat.sub_add_cancel xle], have t := xn_modeq_x2n_sub_lem a1 k2nl.le, rw nat.sub_sub_self k2n at t, exact t.trans dvd_rfl.zero_modeq_nat }, (lt_trichotomy j n).elim (λ (jn : j < n), eq_of_xn_modeq_lem1 ij (lt_of_le_of_ne jn jnn)) $ λ o, o.elim (λ (jn : j = n), by { cases jn, apply int.lt_of_coe_nat_lt_coe_nat, rw [lem2 (n+1) (nat.lt_succ_self _) j2n, show 2 * n - (n + 1) = n - 1, by rw[two_mul, ← nat.sub_sub, nat.add_sub_cancel]], refine lt_sub_left_of_add_lt (int.coe_nat_lt_coe_nat_of_lt _), cases (lt_or_eq_of_le $ nat.le_of_succ_le_succ ij) with lin ein, { rw nat.mod_eq_of_lt (strict_mono_x _ lin), have ll : xn a1 (n-1) + xn a1 (n-1) ≤ xn a1 n, { rw [← two_mul, mul_comm, show xn a1 n = xn a1 (n-1+1), by rw [nat.sub_add_cancel npos], xn_succ], exact le_trans (nat.mul_le_mul_left _ a1) (nat.le_add_right _ _) }, have npm : (n-1).succ = n := nat.succ_pred_eq_of_pos npos, have il : i ≤ n - 1, { apply nat.le_of_succ_le_succ, rw npm, exact lin }, cases lt_or_eq_of_le il with ill ile, { exact lt_of_lt_of_le (nat.add_lt_add_left (strict_mono_x a1 ill) _) ll }, { rw ile, apply lt_of_le_of_ne ll, rw ← two_mul, exact λe, ntriv $ let ⟨a2, s1⟩ := @eq_of_xn_modeq_lem2 _ a1 (n-1) (by rwa [nat.sub_add_cancel npos]) in have n1 : n = 1, from le_antisymm (nat.le_of_sub_eq_zero s1) npos, by rw [ile, a2, n1]; exact ⟨rfl, rfl, rfl, rfl⟩ } }, { rw [ein, nat.mod_self, add_zero], exact strict_mono_x _ (nat.pred_lt $ ne_of_gt npos) } }) (λ (jn : j > n), have lem1 : j ≠ n → xn j % xn n < xn (j + 1) % xn n → xn i % xn n < xn (j + 1) % xn n, from λjn s, (lt_or_eq_of_le (nat.le_of_succ_le_succ ij)).elim (λh, lt_trans (eq_of_xn_modeq_lem3 h (le_of_lt j2n) jn $ λ⟨a1, n1, i0, j2⟩, by rw [n1, j2] at j2n; exact absurd j2n dec_trivial) s) (λh, by rw h; exact s), lem1 (ne_of_gt jn) $ int.lt_of_coe_nat_lt_coe_nat $ by { rw [lem2 j jn (le_of_lt j2n), lem2 (j+1) (nat.le_succ_of_le jn) j2n], refine sub_lt_sub_left (int.coe_nat_lt_coe_nat_of_lt $ strict_mono_x _ _) _, rw [nat.sub_succ], exact nat.pred_lt (ne_of_gt $ nat.sub_pos_of_lt j2n) }) theorem eq_of_xn_modeq_le {i j n} (npos : 0 < n) (ij : i ≤ j) (j2n : j ≤ 2 * n) (h : xn i ≡ xn j [MOD xn n]) (ntriv : ¬(a = 2 ∧ n = 1 ∧ i = 0 ∧ j = 2)) : i = j := (lt_or_eq_of_le ij).resolve_left $ λij', if jn : j = n then by { refine ne_of_gt _ h, rw [jn, nat.mod_self], have x0 : 0 < xn a1 0 % xn a1 n := by rw [nat.mod_eq_of_lt (strict_mono_x a1 npos)]; exact dec_trivial, cases i with i, exact x0, rw jn at ij', exact x0.trans (eq_of_xn_modeq_lem3 _ npos (nat.succ_pos _) (le_trans ij j2n) (ne_of_lt ij') $ λ⟨a1, n1, _, i2⟩, by rw [n1, i2] at ij'; exact absurd ij' dec_trivial) } else ne_of_lt (eq_of_xn_modeq_lem3 npos ij' j2n jn ntriv) h theorem eq_of_xn_modeq {i j n} (npos : 0 < n) (i2n : i ≤ 2 * n) (j2n : j ≤ 2 * n) (h : xn i ≡ xn j [MOD xn n]) (ntriv : a = 2 → n = 1 → (i = 0 → j ≠ 2) ∧ (i = 2 → j ≠ 0)) : i = j := (le_total i j).elim (λij, eq_of_xn_modeq_le npos ij j2n h $ λ⟨a2, n1, i0, j2⟩, (ntriv a2 n1).left i0 j2) (λij, (eq_of_xn_modeq_le npos ij i2n h.symm $ λ⟨a2, n1, j0, i2⟩, (ntriv a2 n1).right i2 j0).symm) theorem eq_of_xn_modeq' {i j n} (ipos : 0 < i) (hin : i ≤ n) (j4n : j ≤ 4 * n) (h : xn j ≡ xn i [MOD xn n]) : j = i ∨ j + i = 4 * n := have i2n : i ≤ 2*n, by apply le_trans hin; rw two_mul; apply nat.le_add_left, have npos : 0 < n, from lt_of_lt_of_le ipos hin, (le_or_gt j (2 * n)).imp (λj2n : j ≤ 2 * n, eq_of_xn_modeq npos j2n i2n h $ λa2 n1, ⟨λj0 i2, by rw [n1, i2] at hin; exact absurd hin dec_trivial, λj2 i0, ne_of_gt ipos i0⟩) (λj2n : 2 * n < j, suffices i = 4*n - j, by rw [this, nat.add_sub_of_le j4n], have j42n : 4*n - j ≤ 2*n, from @nat.le_of_add_le_add_right j _ _ $ by rw [nat.sub_add_cancel j4n, show 4*n = 2*n + 2*n, from right_distrib 2 2 n]; exact nat.add_le_add_left (le_of_lt j2n) _, eq_of_xn_modeq npos i2n j42n (h.symm.trans $ let t := xn_modeq_x4n_sub j42n in by rwa [nat.sub_sub_self j4n] at t) (λa2 n1, ⟨λi0, absurd i0 (ne_of_gt ipos), λi2, by { rw [n1, i2] at hin, exact absurd hin dec_trivial }⟩)) theorem modeq_of_xn_modeq {i j n} (ipos : 0 < i) (hin : i ≤ n) (h : xn j ≡ xn i [MOD xn n]) : j ≡ i [MOD 4 * n] ∨ j + i ≡ 0 [MOD 4 * n] := let j' := j % (4 * n) in have n4 : 0 < 4 * n, from mul_pos dec_trivial (ipos.trans_le hin), have jl : j' < 4 * n, from nat.mod_lt _ n4, have jj : j ≡ j' [MOD 4 * n], by delta modeq; rw nat.mod_eq_of_lt jl, have ∀j q, xn (j + 4 * n * q) ≡ xn j [MOD xn n], begin intros j q, induction q with q IH, { simp }, rw [nat.mul_succ, ← add_assoc, add_comm], exact (xn_modeq_x4n_add _ _ _).trans IH end, or.imp (λ(ji : j' = i), by rwa ← ji) (λ(ji : j' + i = 4 * n), (jj.add_right _).trans $ by { rw ji, exact dvd_rfl.modeq_zero_nat }) (eq_of_xn_modeq' ipos hin jl.le $ (h.symm.trans $ by { rw ← nat.mod_add_div j (4*n), exact this j' _ }).symm) end theorem xy_modeq_of_modeq {a b c} (a1 : 1 < a) (b1 : 1 < b) (h : a ≡ b [MOD c]) : ∀ n, xn a1 n ≡ xn b1 n [MOD c] ∧ yn a1 n ≡ yn b1 n [MOD c] | 0 := by constructor; refl | 1 := by simp; exact ⟨h, modeq.refl 1⟩ | (n+2) := ⟨ (xy_modeq_of_modeq n).left.add_right_cancel $ by { rw [xn_succ_succ a1, xn_succ_succ b1], exact (h.mul_left _ ).mul (xy_modeq_of_modeq (n+1)).left }, (xy_modeq_of_modeq n).right.add_right_cancel $ by { rw [yn_succ_succ a1, yn_succ_succ b1], exact (h.mul_left _ ).mul (xy_modeq_of_modeq (n+1)).right }⟩ theorem matiyasevic {a k x y} : (∃ a1 : 1 < a, xn a1 k = x ∧ yn a1 k = y) ↔ 1 < a ∧ k ≤ y ∧ (x = 1 ∧ y = 0 ∨ ∃ (u v s t b : ℕ), x * x - (a * a - 1) * y * y = 1 ∧ u * u - (a * a - 1) * v * v = 1 ∧ s * s - (b * b - 1) * t * t = 1 ∧ 1 < b ∧ b ≡ 1 [MOD 4 * y] ∧ b ≡ a [MOD u] ∧ 0 < v ∧ y * y ∣ v ∧ s ≡ x [MOD u] ∧ t ≡ k [MOD 4 * y]) := ⟨λ⟨a1, hx, hy⟩, by rw [← hx, ← hy]; refine ⟨a1, (nat.eq_zero_or_pos k).elim (λk0, by rw k0; exact ⟨le_rfl, or.inl ⟨rfl, rfl⟩⟩) (λkpos, _)⟩; exact let x := xn a1 k, y := yn a1 k, m := 2 * (k * y), u := xn a1 m, v := yn a1 m in have ky : k ≤ y, from yn_ge_n a1 k, have yv : y * y ∣ v, from (ysq_dvd_yy a1 k).trans $ (y_dvd_iff _ _ _).2 $ dvd_mul_left _ _, have uco : nat.coprime u (4 * y), from have 2 ∣ v, from modeq_zero_iff_dvd.1 $ (yn_modeq_two _ _).trans (dvd_mul_right _ _).modeq_zero_nat, have nat.coprime u 2, from (xy_coprime a1 m).coprime_dvd_right this, (this.mul_right this).mul_right $ (xy_coprime _ _).coprime_dvd_right (dvd_of_mul_left_dvd yv), let ⟨b, ba, bm1⟩ := chinese_remainder uco a 1 in have m1 : 1 < m, from have 0 < k * y, from mul_pos kpos (strict_mono_y a1 kpos), nat.mul_le_mul_left 2 this, have vp : 0 < v, from strict_mono_y a1 (lt_trans zero_lt_one m1), have b1 : 1 < b, from have xn a1 1 < u, from strict_mono_x a1 m1, have a < u, by simp at this; exact this, lt_of_lt_of_le a1 $ by delta modeq at ba; rw nat.mod_eq_of_lt this at ba; rw ← ba; apply nat.mod_le, let s := xn b1 k, t := yn b1 k in have sx : s ≡ x [MOD u], from (xy_modeq_of_modeq b1 a1 ba k).left, have tk : t ≡ k [MOD 4 * y], from have 4 * y ∣ b - 1, from int.coe_nat_dvd.1 $ by rw int.coe_nat_sub (le_of_lt b1); exact bm1.symm.dvd, (yn_modeq_a_sub_one _ _).modeq_of_dvd this, ⟨ky, or.inr ⟨u, v, s, t, b, pell_eq _ _, pell_eq _ _, pell_eq _ _, b1, bm1, ba, vp, yv, sx, tk⟩⟩, λ⟨a1, ky, o⟩, ⟨a1, match o with | or.inl ⟨x1, y0⟩ := by rw y0 at ky; rw [nat.eq_zero_of_le_zero ky, x1, y0]; exact ⟨rfl, rfl⟩ | or.inr ⟨u, v, s, t, b, xy, uv, st, b1, rem⟩ := match x, y, eq_pell a1 xy, u, v, eq_pell a1 uv, s, t, eq_pell b1 st, rem, ky with | ._, ._, ⟨i, rfl, rfl⟩, ._, ._, ⟨n, rfl, rfl⟩, ._, ._, ⟨j, rfl, rfl⟩, ⟨(bm1 : b ≡ 1 [MOD 4 * yn a1 i]), (ba : b ≡ a [MOD xn a1 n]), (vp : 0 < yn a1 n), (yv : yn a1 i * yn a1 i ∣ yn a1 n), (sx : xn b1 j ≡ xn a1 i [MOD xn a1 n]), (tk : yn b1 j ≡ k [MOD 4 * yn a1 i])⟩, (ky : k ≤ yn a1 i) := (nat.eq_zero_or_pos i).elim (λi0, by simp [i0] at ky; rw [i0, ky]; exact ⟨rfl, rfl⟩) $ λipos, suffices i = k, by rw this; exact ⟨rfl, rfl⟩, by clear _x o rem xy uv st _match _match _fun_match; exact have iln : i ≤ n, from le_of_not_gt $ λhin, not_lt_of_ge (nat.le_of_dvd vp (dvd_of_mul_left_dvd yv)) (strict_mono_y a1 hin), have yd : 4 * yn a1 i ∣ 4 * n, from mul_dvd_mul_left _ $ dvd_of_ysq_dvd a1 yv, have jk : j ≡ k [MOD 4 * yn a1 i], from have 4 * yn a1 i ∣ b - 1, from int.coe_nat_dvd.1 $ by rw int.coe_nat_sub (le_of_lt b1); exact bm1.symm.dvd, ((yn_modeq_a_sub_one b1 _).modeq_of_dvd this).symm.trans tk, have ki : k + i < 4 * yn a1 i, from lt_of_le_of_lt (add_le_add ky (yn_ge_n a1 i)) $ by rw ← two_mul; exact nat.mul_lt_mul_of_pos_right dec_trivial (strict_mono_y a1 ipos), have ji : j ≡ i [MOD 4 * n], from have xn a1 j ≡ xn a1 i [MOD xn a1 n], from (xy_modeq_of_modeq b1 a1 ba j).left.symm.trans sx, (modeq_of_xn_modeq a1 ipos iln this).resolve_right $ λ (ji : j + i ≡ 0 [MOD 4 * n]), not_le_of_gt ki $ nat.le_of_dvd (lt_of_lt_of_le ipos $ nat.le_add_left _ _) $ modeq_zero_iff_dvd.1 $ (jk.symm.add_right i).trans $ ji.modeq_of_dvd yd, by have : i % (4 * yn a1 i) = k % (4 * yn a1 i) := (ji.modeq_of_dvd yd).symm.trans jk; rwa [nat.mod_eq_of_lt (lt_of_le_of_lt (nat.le_add_left _ _) ki), nat.mod_eq_of_lt (lt_of_le_of_lt (nat.le_add_right _ _) ki)] at this end end⟩⟩ lemma eq_pow_of_pell_lem {a y k} (a1 : 1 < a) (ypos : 0 < y) : 0 < k → y^k < a → (↑(y^k) : ℤ) < 2*a*y - y*y - 1 := have y < a → a + (y*y + 1) ≤ 2*a*y, begin intro ya, induction y with y IH, exact absurd ypos (lt_irrefl _), cases nat.eq_zero_or_pos y with y0 ypos, { rw y0, simpa [two_mul], }, { rw [nat.mul_succ, nat.mul_succ, nat.succ_mul y], have : y + nat.succ y ≤ 2 * a, { change y + y < 2 * a, rw ← two_mul, exact mul_lt_mul_of_pos_left (nat.lt_of_succ_lt ya) dec_trivial }, have := add_le_add (IH ypos (nat.lt_of_succ_lt ya)) this, convert this using 1, ring } end, λk0 yak, lt_of_lt_of_le (int.coe_nat_lt_coe_nat_of_lt yak) $ by rw sub_sub; apply le_sub_right_of_add_le; apply int.coe_nat_le_coe_nat_of_le; have y1 := nat.pow_le_pow_of_le_right ypos k0; simp at y1; exact this (lt_of_le_of_lt y1 yak) theorem eq_pow_of_pell {m n k} : (n^k = m ↔ k = 0 ∧ m = 1 ∨ 0 < k ∧ (n = 0 ∧ m = 0 ∨ 0 < n ∧ ∃ (w a t z : ℕ) (a1 : 1 < a), xn a1 k ≡ yn a1 k * (a - n) + m [MOD t] ∧ 2 * a * n = t + (n * n + 1) ∧ m < t ∧ n ≤ w ∧ k ≤ w ∧ a * a - ((w + 1) * (w + 1) - 1) * (w * z) * (w * z) = 1)) := ⟨λe, by rw ← e; refine (nat.eq_zero_or_pos k).elim (λk0, by rw k0; exact or.inl ⟨rfl, rfl⟩) (λkpos, or.inr ⟨kpos, _⟩); refine (nat.eq_zero_or_pos n).elim (λn0, by rw [n0, zero_pow kpos]; exact or.inl ⟨rfl, rfl⟩) (λnpos, or.inr ⟨npos, _⟩); exact let w := max n k in have nw : n ≤ w, from le_max_left _ _, have kw : k ≤ w, from le_max_right _ _, have wpos : 0 < w, from lt_of_lt_of_le npos nw, have w1 : 1 < w + 1, from nat.succ_lt_succ wpos, let a := xn w1 w in have a1 : 1 < a, from strict_mono_x w1 wpos, let x := xn a1 k, y := yn a1 k in let ⟨z, ze⟩ := show w ∣ yn w1 w, from modeq_zero_iff_dvd.1 $ (yn_modeq_a_sub_one w1 w).trans dvd_rfl.modeq_zero_nat in have nt : (↑(n^k) : ℤ) < 2 * a * n - n * n - 1, from eq_pow_of_pell_lem a1 npos kpos $ calc n^k ≤ n^w : nat.pow_le_pow_of_le_right npos kw ... < (w + 1)^w : nat.pow_lt_pow_of_lt_left (nat.lt_succ_of_le nw) wpos ... ≤ a : xn_ge_a_pow w1 w, let ⟨t, te⟩ := int.eq_coe_of_zero_le $ le_trans (int.coe_zero_le _) nt.le in have na : n ≤ a, from nw.trans $ le_of_lt $ n_lt_xn w1 w, have tm : x ≡ y * (a - n) + n^k [MOD t], begin apply modeq_of_dvd, rw [int.coe_nat_add, int.coe_nat_mul, int.coe_nat_sub na, ← te], exact x_sub_y_dvd_pow a1 n k end, have ta : 2 * a * n = t + (n * n + 1), from int.coe_nat_inj $ by rw [int.coe_nat_add, ← te, sub_sub]; repeat {rw int.coe_nat_add <|> rw int.coe_nat_mul}; rw [int.coe_nat_one, sub_add_cancel]; refl, have mt : n^k < t, from int.lt_of_coe_nat_lt_coe_nat $ by rw ← te; exact nt, have zp : a * a - ((w + 1) * (w + 1) - 1) * (w * z) * (w * z) = 1, by rw ← ze; exact pell_eq w1 w, ⟨w, a, t, z, a1, tm, ta, mt, nw, kw, zp⟩, λo, match o with | or.inl ⟨k0, m1⟩ := by rw [k0, m1]; refl | or.inr ⟨kpos, or.inl ⟨n0, m0⟩⟩ := by rw [n0, m0, zero_pow kpos] | or.inr ⟨kpos, or.inr ⟨npos, w, a, t, z, (a1 : 1 < a), (tm : xn a1 k ≡ yn a1 k * (a - n) + m [MOD t]), (ta : 2 * a * n = t + (n * n + 1)), (mt : m < t), (nw : n ≤ w), (kw : k ≤ w), (zp : a * a - ((w + 1) * (w + 1) - 1) * (w * z) * (w * z) = 1)⟩⟩ := have wpos : 0 < w, from lt_of_lt_of_le npos nw, have w1 : 1 < w + 1, from nat.succ_lt_succ wpos, let ⟨j, xj, yj⟩ := eq_pell w1 zp in by clear _match o _let_match; exact have jpos : 0 < j, from (nat.eq_zero_or_pos j).resolve_left $ λj0, have a1 : a = 1, by rw j0 at xj; exact xj, have 2 * n = t + (n * n + 1), by rw a1 at ta; exact ta, have n1 : n = 1, from have n * n < n * 2, by rw [mul_comm n 2, this]; apply nat.le_add_left, have n ≤ 1, from nat.le_of_lt_succ $ lt_of_mul_lt_mul_left this (nat.zero_le _), le_antisymm this npos, by rw n1 at this; rw ← @nat.add_right_cancel 0 2 t this at mt; exact nat.not_lt_zero _ mt, have wj : w ≤ j, from nat.le_of_dvd jpos $ modeq_zero_iff_dvd.1 $ (yn_modeq_a_sub_one w1 j).symm.trans $ modeq_zero_iff_dvd.2 ⟨z, yj.symm⟩, have nt : (↑(n^k) : ℤ) < 2 * a * n - n * n - 1, from eq_pow_of_pell_lem a1 npos kpos $ calc n^k ≤ n^j : nat.pow_le_pow_of_le_right npos (le_trans kw wj) ... < (w + 1)^j : nat.pow_lt_pow_of_lt_left (nat.lt_succ_of_le nw) jpos ... ≤ xn w1 j : xn_ge_a_pow w1 j ... = a : xj.symm, have na : n ≤ a, by rw xj; exact le_trans (le_trans nw wj) (le_of_lt $ n_lt_xn _ _), have te : (t : ℤ) = 2 * ↑a * ↑n - ↑n * ↑n - 1, by rw sub_sub; apply eq_sub_of_add_eq; apply (int.coe_nat_eq_coe_nat_iff _ _).2; exact ta.symm, have xn a1 k ≡ yn a1 k * (a - n) + n^k [MOD t], by have := x_sub_y_dvd_pow a1 n k; rw [← te, ← int.coe_nat_sub na] at this; exact modeq_of_dvd this, have n^k % t = m % t, from (this.symm.trans tm).add_left_cancel' _, by rw ← te at nt; rwa [nat.mod_eq_of_lt (int.lt_of_coe_nat_lt_coe_nat nt), nat.mod_eq_of_lt mt] at this end⟩ end pell
a169c9497bb3e888517556010594ef0aec7e733f
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/abelian/images.lean
84368319191fcfc4dea6acad2528ad218a0f6239
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
3,999
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel, Scott Morrison -/ import category_theory.limits.shapes.kernels /-! # The abelian image and coimage. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In an abelian category we usually want the image of a morphism `f` to be defined as `kernel (cokernel.π f)`, and the coimage to be defined as `cokernel (kernel.ι f)`. We make these definitions here, as `abelian.image f` and `abelian.coimage f` (without assuming the category is actually abelian), and later relate these to the usual categorical notions when in an abelian category. There is a canonical morphism `coimage_image_comparison : abelian.coimage f ⟶ abelian.image f`. Later we show that this is always an isomorphism in an abelian category, and conversely a category with (co)kernels and finite products in which this morphism is always an isomorphism is an abelian category. -/ noncomputable theory universes v u open category_theory open category_theory.limits namespace category_theory.abelian variables {C : Type u} [category.{v} C] [has_zero_morphisms C] [has_kernels C] [has_cokernels C] variables {P Q : C} (f : P ⟶ Q) section image /-- The kernel of the cokernel of `f` is called the (abelian) image of `f`. -/ protected abbreviation image : C := kernel (cokernel.π f) /-- The inclusion of the image into the codomain. -/ protected abbreviation image.ι : abelian.image f ⟶ Q := kernel.ι (cokernel.π f) /-- There is a canonical epimorphism `p : P ⟶ image f` for every `f`. -/ protected abbreviation factor_thru_image : P ⟶ abelian.image f := kernel.lift (cokernel.π f) f $ cokernel.condition f /-- `f` factors through its image via the canonical morphism `p`. -/ @[simp, reassoc] protected lemma image.fac : abelian.factor_thru_image f ≫ image.ι f = f := kernel.lift_ι _ _ _ instance mono_factor_thru_image [mono f] : mono (abelian.factor_thru_image f) := mono_of_mono_fac $ image.fac f end image section coimage /-- The cokernel of the kernel of `f` is called the (abelian) coimage of `f`. -/ protected abbreviation coimage : C := cokernel (kernel.ι f) /-- The projection onto the coimage. -/ protected abbreviation coimage.π : P ⟶ abelian.coimage f := cokernel.π (kernel.ι f) /-- There is a canonical monomorphism `i : coimage f ⟶ Q`. -/ protected abbreviation factor_thru_coimage : abelian.coimage f ⟶ Q := cokernel.desc (kernel.ι f) f $ kernel.condition f /-- `f` factors through its coimage via the canonical morphism `p`. -/ protected lemma coimage.fac : coimage.π f ≫ abelian.factor_thru_coimage f = f := cokernel.π_desc _ _ _ instance epi_factor_thru_coimage [epi f] : epi (abelian.factor_thru_coimage f) := epi_of_epi_fac $ coimage.fac f end coimage /-- The canonical map from the abelian coimage to the abelian image. In any abelian category this is an isomorphism. Conversely, any additive category with kernels and cokernels and in which this is always an isomorphism, is abelian. See <https://stacks.math.columbia.edu/tag/0107> -/ def coimage_image_comparison : abelian.coimage f ⟶ abelian.image f := cokernel.desc (kernel.ι f) (kernel.lift (cokernel.π f) f (by simp)) $ (by { ext, simp, }) /-- An alternative formulation of the canonical map from the abelian coimage to the abelian image. -/ def coimage_image_comparison' : abelian.coimage f ⟶ abelian.image f := kernel.lift (cokernel.π f) (cokernel.desc (kernel.ι f) f (by simp)) (by { ext, simp, }) lemma coimage_image_comparison_eq_coimage_image_comparison' : coimage_image_comparison f = coimage_image_comparison' f := by { ext, simp [coimage_image_comparison, coimage_image_comparison'], } @[simp, reassoc] lemma coimage_image_factorisation : coimage.π f ≫ coimage_image_comparison f ≫ image.ι f = f := by simp [coimage_image_comparison] end category_theory.abelian
de8d8eff95e7c970e64585203a3d643cd6f0c642
4727251e0cd73359b15b664c3170e5d754078599
/src/data/zmod/quotient.lean
da2352fce381c41f29ff8f01c94e60c4772f7743
[ "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
3,670
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import data.zmod.basic import group_theory.quotient_group import ring_theory.int.basic /-! # `zmod n` and quotient groups / rings This file relates `zmod n` to the quotient group `quotient_add_group.quotient (add_subgroup.zmultiples n)` and to the quotient ring `(ideal.span {n}).quotient`. ## Main definitions - `zmod.quotient_zmultiples_nat_equiv_zmod` and `zmod.quotient_zmultiples_equiv_zmod`: `zmod n` is the group quotient of `ℤ` by `n ℤ := add_subgroup.zmultiples (n)`, (where `n : ℕ` and `n : ℤ` respectively) - `zmod.quotient_span_nat_equiv_zmod` and `zmod.quotient_span_equiv_zmod`: `zmod n` is the ring quotient of `ℤ` by `n ℤ : ideal.span {n}` (where `n : ℕ` and `n : ℤ` respectively) - `zmod.lift n f` is the map from `zmod n` induced by `f : ℤ →+ A` that maps `n` to `0`. ## Tags zmod, quotient group, quotient ring, ideal quotient -/ open quotient_add_group open zmod variables (n : ℕ) {A R : Type*} [add_group A] [ring R] namespace int /-- `ℤ` modulo multiples of `n : ℕ` is `zmod n`. -/ def quotient_zmultiples_nat_equiv_zmod : ℤ ⧸ add_subgroup.zmultiples (n : ℤ) ≃+ zmod n := (equiv_quotient_of_eq (zmod.ker_int_cast_add_hom _)).symm.trans $ quotient_ker_equiv_of_right_inverse (int.cast_add_hom (zmod n)) coe int_cast_zmod_cast /-- `ℤ` modulo multiples of `a : ℤ` is `zmod a.nat_abs`. -/ def quotient_zmultiples_equiv_zmod (a : ℤ) : ℤ ⧸ add_subgroup.zmultiples a ≃+ zmod a.nat_abs := (equiv_quotient_of_eq (zmultiples_nat_abs a)).symm.trans (quotient_zmultiples_nat_equiv_zmod a.nat_abs) /-- `ℤ` modulo the ideal generated by `n : ℕ` is `zmod n`. -/ def quotient_span_nat_equiv_zmod : ℤ ⧸ ideal.span {↑n} ≃+* zmod n := (ideal.quot_equiv_of_eq (zmod.ker_int_cast_ring_hom _)).symm.trans $ ring_hom.quotient_ker_equiv_of_right_inverse $ show function.right_inverse coe (int.cast_ring_hom (zmod n)), from int_cast_zmod_cast /-- `ℤ` modulo the ideal generated by `a : ℤ` is `zmod a.nat_abs`. -/ def quotient_span_equiv_zmod (a : ℤ) : ℤ ⧸ ideal.span ({a} : set ℤ) ≃+* zmod a.nat_abs := (ideal.quot_equiv_of_eq (span_nat_abs a)).symm.trans (quotient_span_nat_equiv_zmod a.nat_abs) end int namespace add_action open add_subgroup add_monoid_hom add_equiv function variables {α β : Type*} [add_group α] (a : α) [add_action α β] (b : β) /-- The quotient `(ℤ ∙ a) ⧸ (stabilizer b)` is cyclic of order `minimal_period ((+ᵥ) a) b`. -/ noncomputable def zmultiples_quotient_stabilizer_equiv : zmultiples a ⧸ stabilizer (zmultiples a) b ≃+ zmod (minimal_period ((+ᵥ) a) b) := (of_bijective (map _ (stabilizer (zmultiples a) b) (zmultiples_hom (zmultiples a) ⟨a, mem_zmultiples a⟩) (by { rw [zmultiples_le, mem_comap, mem_stabilizer_iff, zmultiples_hom_apply, coe_nat_zsmul, ←vadd_iterate], exact is_periodic_pt_minimal_period ((+ᵥ) a) b })) ⟨by { rw [←ker_eq_bot_iff, eq_bot_iff], refine λ q, induction_on' q (λ n hn, _), rw [mem_bot, eq_zero_iff, int.mem_zmultiples_iff, ←zsmul_vadd_eq_iff_minimal_period_dvd], exact (eq_zero_iff _).mp hn }, λ q, induction_on' q (λ ⟨_, n, rfl⟩, ⟨n, rfl⟩)⟩).symm.trans (int.quotient_zmultiples_nat_equiv_zmod (minimal_period ((+ᵥ) a) b)) lemma zmultiples_quotient_stabilizer_equiv_symm_apply (n : zmod (minimal_period ((+ᵥ) a) b)) : (zmultiples_quotient_stabilizer_equiv a b).symm n = (n : ℤ) • (⟨a, mem_zmultiples a⟩ : zmultiples a) := rfl end add_action
6f7dce90d6c159165a63ec981a57c68e7ce413b2
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/rb_map1.lean
a95d2109a503e77cd2617ffb7bdd1e1e748424c2
[ "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
693
lean
import system.IO section open nat_map vm_eval size (insert (insert (mk nat) 10 20) 10 21) meta_definition m := (insert (insert (insert (mk nat) 10 20) 5 50) 10 21) vm_eval find m 10 vm_eval find m 5 vm_eval find m 8 vm_eval contains m 5 vm_eval contains m 8 open list meta_definition m2 := of_list [((1:nat), "one"), (2, "two"), (3, "three")] vm_eval size m2 vm_eval find m2 1 vm_eval find m2 4 vm_eval find m2 3 vm_eval do pp m2, put_str "\n" vm_eval m2 end section open rb_map -- Mapping from (nat × nat) → nat meta_definition m3 := insert (insert (mk (nat × nat) nat) (1, 2) 3) (2, 2) 4 vm_eval find m3 (1, 2) vm_eval find m3 (2, 1) vm_eval find m3 (2, 2) vm_eval pp m3 end
fa5d2a17bbd3e1dc06184b2b8120bc678871b0a4
0845ae2ca02071debcfd4ac24be871236c01784f
/library/init/lean/projfns.lean
9df48487ff3abd00056a17b235b60a2e64bb1a9c
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
2,525
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.lean.environment namespace Lean /- Given a structure `S`, Lean automatically creates an auxiliary definition (projection function) for each field. This structure caches information about these auxiliary definitions. -/ structure ProjectionFunctionInfo := (ctorName : Name) -- Constructor associated with the auxiliary projection function. (nparams : Nat) -- Number of parameters in the structure (i : Nat) -- The field index associated with the auxiliary projection function. (fromClass : Bool) -- `true` if the structure is a class instance ProjectionFunctionInfo.inhabited : Inhabited ProjectionFunctionInfo := ⟨{ ctorName := default _, nparams := default _, i := 0, fromClass := false }⟩ def mkProjectionFnInfoExtension : IO (SimplePersistentEnvExtension (Name × ProjectionFunctionInfo) (NameMap ProjectionFunctionInfo)) := registerSimplePersistentEnvExtension { name := `projinfo, addImportedFn := fun as => {}, addEntryFn := fun s p => s.insert p.1 p.2, toArrayFn := fun es => es.toArray.qsort (fun a b => Name.quickLt a.1 b.1) } @[init mkProjectionFnInfoExtension] constant projectionFnInfoExt : SimplePersistentEnvExtension (Name × ProjectionFunctionInfo) (NameMap ProjectionFunctionInfo) := default _ @[export lean.add_projection_info_core] def addProjectionFnInfo (env : Environment) (projName : Name) (ctorName : Name) (nparams : Nat) (i : Nat) (fromClass : Bool) : Environment := projectionFnInfoExt.addEntry env (projName, { ctorName := ctorName, nparams := nparams, i := i, fromClass := fromClass }) namespace Environment @[export lean.get_projection_info_core] def getProjectionFnInfo (env : Environment) (projName : Name) : Option ProjectionFunctionInfo := match env.getModuleIdxFor projName with | some modIdx => match (projectionFnInfoExt.getModuleEntries env modIdx).binSearch (projName, default _) (fun a b => Name.quickLt a.1 b.1) with | some e => some e.2 | none => none | none => (projectionFnInfoExt.getState env).find projName def isProjectionFn (env : Environment) (n : Name) : Bool := match env.getModuleIdxFor n with | some modIdx => (projectionFnInfoExt.getModuleEntries env modIdx).binSearchContains (n, default _) (fun a b => Name.quickLt a.1 b.1) | none => (projectionFnInfoExt.getState env).contains n end Environment end Lean
82f296977b792c13f21ca558e393d955ae3b61bc
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/int/char_zero.lean
3ce54c05a6f57de6016654cf51683b3b8c1dc5d2
[ "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
1,544
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.int.cast.field /-! # Injectivity of `int.cast` into characteristic zero rings and fields. -/ variables {α : Type*} open nat namespace int @[simp] theorem cast_eq_zero [add_group_with_one α] [char_zero α] {n : ℤ} : (n : α) = 0 ↔ n = 0 := ⟨λ h, begin cases n, { rw [int.cast_of_nat] at h, exact congr_arg coe (nat.cast_eq_zero.1 h) }, { rw [cast_neg_succ_of_nat, neg_eq_zero, nat.cast_eq_zero] at h, contradiction } end, λ h, by rw [h, cast_zero]⟩ @[simp, norm_cast] theorem cast_inj [add_group_with_one α] [char_zero α] {m n : ℤ} : (m : α) = n ↔ m = n := by rw [← sub_eq_zero, ← cast_sub, cast_eq_zero, sub_eq_zero] theorem cast_injective [add_group_with_one α] [char_zero α] : function.injective (coe : ℤ → α) | m n := cast_inj.1 theorem cast_ne_zero [add_group_with_one α] [char_zero α] {n : ℤ} : (n : α) ≠ 0 ↔ n ≠ 0 := not_congr cast_eq_zero @[simp, norm_cast] theorem cast_div_char_zero {k : Type*} [field k] [char_zero k] {m n : ℤ} (n_dvd : n ∣ m) : ((m / n : ℤ) : k) = m / n := begin rcases eq_or_ne n 0 with rfl | hn, { simp [int.div_zero] }, { exact cast_div n_dvd (cast_ne_zero.mpr hn), }, end end int lemma ring_hom.injective_int {α : Type*} [non_assoc_ring α] (f : ℤ →+* α) [char_zero α] : function.injective f := subsingleton.elim (int.cast_ring_hom _) f ▸ int.cast_injective
f5526bfeb2427d7a9e049fe0a20c3bfc6e8926da
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Util/Trace.lean
0830bdf510c68d595257f2178fa1fe6b99b090c1
[ "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
7,327
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich, Leonardo de Moura -/ import Lean.Message import Lean.MonadEnv /-! # Trace messages Trace messages explain to the user what problem Lean solved and what steps it took. Think of trace messages like a figure in a paper. They are shown in the editor as a collapsible tree, usually as `[class.name] message ▸`. Every trace node has a class name, a message, and an array of children. This module provides the API to produce trace messages, the key entry points are: - ``registerTraceMessage `class.name`` registers a trace class - ``withTraceNode `class.name (fun result => return msg) do body` produces a trace message containing the trace messages in `body` as children - `trace[class.name] msg` produces a trace message without children Users can enable trace options for a class using `set_option trace.class.name true`. This only enables trace messages for the `class.name` trace class as well as child classes that are explicitly marked as inherited (see `registerTraceClass`). Internally, trace messages are stored as `MessageData`: `.trace cls msg #[.trace .., .trace ..]` When writing trace messages, try to follow these guidelines: 1. **Expansion progressively increases detail.** Each level of expansion (of the trace node in the editor) should reveal more details. For example, the unexpanded node should show the top-level goal. Expanding it should show a list of steps. Expanding one of the steps then shows what happens during that step. 2. **One trace message per step.** The `[trace.class]` marker functions as a visual bullet point, making it easy to identify the different steps at a glance. 3. **Outcome first.** The top-level trace message should already show whether the action failed or succeeded, as opposed to a "success" trace message that comes pages later. 4. **Be concise.** Keep messages short. Avoid repetitive text. (This is also why the editor plugins abbreviate the common prefixes.) 5. **Emoji are concisest.** Several helper functions in this module help with a consistent emoji language. 6. **Good defaults.** Setting `set_option trace.Meta.synthInstance true` (etc.) should produce great trace messages out-of-the-box, without needing extra options to tweak it. -/ namespace Lean open Std (PersistentArray) structure TraceElem where ref : Syntax msg : MessageData deriving Inhabited structure TraceState where traces : PersistentArray TraceElem := {} deriving Inhabited builtin_initialize inheritedTraceOptions : IO.Ref (Std.HashSet Name) ← IO.mkRef ∅ class MonadTrace (m : Type → Type) where modifyTraceState : (TraceState → TraceState) → m Unit getTraceState : m TraceState export MonadTrace (getTraceState modifyTraceState) instance (m n) [MonadLift m n] [MonadTrace m] : MonadTrace n where modifyTraceState := fun f => liftM (modifyTraceState f : m _) getTraceState := liftM (getTraceState : m _) variable {α : Type} {m : Type → Type} [Monad m] [MonadTrace m] [MonadOptions m] [MonadLiftT IO m] def printTraces : m Unit := do for {msg, ..} in (← getTraceState).traces do IO.println (← msg.format) def resetTraceState : m Unit := modifyTraceState (fun _ => {}) private def checkTraceOption (inherited : Std.HashSet Name) (opts : Options) (cls : Name) : Bool := !opts.isEmpty && go (`trace ++ cls) where go (opt : Name) : Bool := if let some enabled := opts.get? opt then enabled else if let .str parent _ := opt then inherited.contains opt && go parent else false def isTracingEnabledFor (cls : Name) : m Bool := do let inherited ← (inheritedTraceOptions.get : IO _) pure (checkTraceOption inherited (← getOptions) cls) @[inline] def getTraces : m (PersistentArray TraceElem) := do let s ← getTraceState pure s.traces @[inline] def modifyTraces (f : PersistentArray TraceElem → PersistentArray TraceElem) : m Unit := modifyTraceState fun s => { s with traces := f s.traces } @[inline] def setTraceState (s : TraceState) : m Unit := modifyTraceState fun _ => s private def getResetTraces : m (PersistentArray TraceElem) := do let oldTraces ← getTraces modifyTraces fun _ => {} pure oldTraces section variable [MonadRef m] [AddMessageContext m] [MonadOptions m] def addRawTrace (msg : MessageData) : m Unit := do let ref ← getRef let msg ← addMessageContext msg modifyTraces (·.push { ref, msg }) def addTrace (cls : Name) (msg : MessageData) : m Unit := do let ref ← getRef let msg ← addMessageContext msg modifyTraces (·.push { ref, msg := .trace cls msg #[] }) @[inline] def trace (cls : Name) (msg : Unit → MessageData) : m Unit := do if (← isTracingEnabledFor cls) then addTrace cls (msg ()) @[inline] def traceM (cls : Name) (mkMsg : m MessageData) : m Unit := do if (← isTracingEnabledFor cls) then let msg ← mkMsg addTrace cls msg private def addTraceNode (oldTraces : PersistentArray TraceElem) (cls : Name) (ref : Syntax) (msg : MessageData) (collapsed : Bool) : m Unit := withRef ref do let msg ← addMessageContext msg modifyTraces fun newTraces => oldTraces.push { ref, msg := .trace cls msg (newTraces.toArray.map (·.msg)) collapsed } def withTraceNode [MonadExcept ε m] (cls : Name) (msg : Except ε α → m MessageData) (k : m α) (collapsed := true) : m α := do if !(← isTracingEnabledFor cls) then k else let ref ← getRef let oldTraces ← getResetTraces let res ← observing k addTraceNode oldTraces cls ref (← msg res) collapsed MonadExcept.ofExcept res def withTraceNode' [MonadExcept Exception m] (cls : Name) (k : m (α × MessageData)) (collapsed := true) : m α := let msg := fun | .ok (_, msg) => return msg | .error err => return err.toMessageData Prod.fst <$> withTraceNode cls msg k collapsed end /-- Registers a trace class. By default, trace classes are not inherited; that is, `set_option trace.foo true` does not imply `set_option trace.foo.bar true`. Calling ``registerTraceClass `foo.bar (inherited := true)`` enables this inheritance on an opt-in basis. -/ def registerTraceClass (traceClassName : Name) (inherited := false) : IO Unit := do let optionName := `trace ++ traceClassName registerOption optionName { group := "trace" defValue := false descr := "enable/disable tracing for the given module and submodules" } if inherited then inheritedTraceOptions.modify (·.insert optionName) macro "trace[" id:ident "]" s:(interpolatedStr(term) <|> term) : doElem => do let msg ← if s.raw.getKind == interpolatedStrKind then `(m! $(⟨s⟩)) else `(($(⟨s⟩) : MessageData)) `(doElem| do let cls := $(quote id.getId.eraseMacroScopes) if (← Lean.isTracingEnabledFor cls) then Lean.addTrace cls $msg) def bombEmoji := "💥" def checkEmoji := "✅" def crossEmoji := "❌" def exceptBoolEmoji : Except ε Bool → String | .error _ => bombEmoji | .ok true => checkEmoji | .ok false => crossEmoji def exceptOptionEmoji : Except ε (Option α) → String | .error _ => bombEmoji | .ok (some _) => checkEmoji | .ok none => crossEmoji end Lean
edc9b661b3e0ce70bcf359a3952f8d42883789e8
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/src/Std/Data/PersistentArray.lean
5ff7051e23ef84b956f4a0fa094410245ef9af8f
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
13,821
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ universe u v w namespace Std inductive PersistentArrayNode (α : Type u) where | node (cs : Array (PersistentArrayNode α)) : PersistentArrayNode α | leaf (vs : Array α) : PersistentArrayNode α deriving Inhabited namespace PersistentArrayNode def isNode {α} : PersistentArrayNode α → Bool | node _ => true | leaf _ => false end PersistentArrayNode abbrev PersistentArray.initShift : USize := 5 abbrev PersistentArray.branching : USize := USize.ofNat (2 ^ PersistentArray.initShift.toNat) structure PersistentArray (α : Type u) where /- Recall that we run out of memory if we have more than `usizeSz/8` elements. So, we can stop adding elements at `root` after `size > usizeSz`, and keep growing the `tail`. This modification allow us to use `USize` instead of `Nat` when traversing `root`. -/ root : PersistentArrayNode α := PersistentArrayNode.node (Array.mkEmpty PersistentArray.branching.toNat) tail : Array α := Array.mkEmpty PersistentArray.branching.toNat size : Nat := 0 shift : USize := PersistentArray.initShift tailOff : Nat := 0 deriving Inhabited abbrev PArray (α : Type u) := PersistentArray α namespace PersistentArray /- TODO: use proofs for showing that array accesses are not out of bounds. We can do it after we reimplement the tactic framework. -/ variable {α : Type u} open Std.PersistentArrayNode def empty : PersistentArray α := {} def isEmpty (a : PersistentArray α) : Bool := a.size == 0 def mkEmptyArray : Array α := Array.mkEmpty branching.toNat abbrev mul2Shift (i : USize) (shift : USize) : USize := i.shiftLeft shift abbrev div2Shift (i : USize) (shift : USize) : USize := i.shiftRight shift abbrev mod2Shift (i : USize) (shift : USize) : USize := USize.land i ((USize.shiftLeft 1 shift) - 1) partial def getAux [Inhabited α] : PersistentArrayNode α → USize → USize → α | node cs, i, shift => getAux (cs.get! (div2Shift i shift).toNat) (mod2Shift i shift) (shift - initShift) | leaf cs, i, _ => cs.get! i.toNat def get! [Inhabited α] (t : PersistentArray α) (i : Nat) : α := if i >= t.tailOff then t.tail.get! (i - t.tailOff) else getAux t.root (USize.ofNat i) t.shift def getOp [Inhabited α] (self : PersistentArray α) (idx : Nat) : α := self.get! idx partial def setAux : PersistentArrayNode α → USize → USize → α → PersistentArrayNode α | node cs, i, shift, a => let j := div2Shift i shift let i := mod2Shift i shift let shift := shift - initShift node $ cs.modify j.toNat $ fun c => setAux c i shift a | leaf cs, i, _, a => leaf (cs.set! i.toNat a) def set (t : PersistentArray α) (i : Nat) (a : α) : PersistentArray α := if i >= t.tailOff then { t with tail := t.tail.set! (i - t.tailOff) a } else { t with root := setAux t.root (USize.ofNat i) t.shift a } @[specialize] partial def modifyAux [Inhabited α] (f : α → α) : PersistentArrayNode α → USize → USize → PersistentArrayNode α | node cs, i, shift => let j := div2Shift i shift let i := mod2Shift i shift let shift := shift - initShift node $ cs.modify j.toNat $ fun c => modifyAux f c i shift | leaf cs, i, _ => leaf (cs.modify i.toNat f) @[specialize] def modify [Inhabited α] (t : PersistentArray α) (i : Nat) (f : α → α) : PersistentArray α := if i >= t.tailOff then { t with tail := t.tail.modify (i - t.tailOff) f } else { t with root := modifyAux f t.root (USize.ofNat i) t.shift } partial def mkNewPath (shift : USize) (a : Array α) : PersistentArrayNode α := if shift == 0 then leaf a else node (mkEmptyArray.push (mkNewPath (shift - initShift) a)) partial def insertNewLeaf : PersistentArrayNode α → USize → USize → Array α → PersistentArrayNode α | node cs, i, shift, a => if i < branching then node (cs.push (leaf a)) else let j := div2Shift i shift let i := mod2Shift i shift let shift := shift - initShift if j.toNat < cs.size then node $ cs.modify j.toNat fun c => insertNewLeaf c i shift a else node $ cs.push $ mkNewPath shift a | n, _, _, _ => n -- unreachable def mkNewTail (t : PersistentArray α) : PersistentArray α := if t.size <= (mul2Shift 1 (t.shift + initShift)).toNat then { t with tail := mkEmptyArray, root := insertNewLeaf t.root (USize.ofNat (t.size - 1)) t.shift t.tail, tailOff := t.size } else { t with tail := #[], root := let n := mkEmptyArray.push t.root; node (n.push (mkNewPath t.shift t.tail)), shift := t.shift + initShift, tailOff := t.size } def tooBig : Nat := USize.size / 8 def push (t : PersistentArray α) (a : α) : PersistentArray α := let r := { t with tail := t.tail.push a, size := t.size + 1 } if r.tail.size < branching.toNat || t.size >= tooBig then r else mkNewTail r private def emptyArray {α : Type u} : Array (PersistentArrayNode α) := Array.mkEmpty PersistentArray.branching.toNat partial def popLeaf : PersistentArrayNode α → Option (Array α) × Array (PersistentArrayNode α) | n@(node cs) => if h : cs.size ≠ 0 then let idx : Fin cs.size := ⟨cs.size - 1, by exact Nat.predLt h⟩ let last := cs.get idx let cs' := cs.set idx arbitrary match popLeaf last with | (none, _) => (none, emptyArray) | (some l, newLast) => if newLast.size == 0 then let cs' := cs'.pop if cs'.isEmpty then (some l, emptyArray) else (some l, cs') else (some l, cs'.set (Array.size_set cs idx _ ▸ idx) (node newLast)) else (none, emptyArray) | leaf vs => (some vs, emptyArray) def pop (t : PersistentArray α) : PersistentArray α := if t.tail.size > 0 then { t with tail := t.tail.pop, size := t.size - 1 } else match popLeaf t.root with | (none, _) => t | (some last, newRoots) => let last := last.pop let newSize := t.size - 1 let newTailOff := newSize - last.size if newRoots.size == 1 && (newRoots.get! 0).isNode then { root := newRoots.get! 0, shift := t.shift - initShift, size := newSize, tail := last, tailOff := newTailOff } else { t with root := node newRoots, size := newSize, tail := last, tailOff := newTailOff } section variable {m : Type v → Type w} [Monad m] variable {β : Type v} @[specialize] private partial def foldlMAux (f : β → α → m β) : PersistentArrayNode α → β → m β | node cs, b => cs.foldlM (fun b c => foldlMAux f c b) b | leaf vs, b => vs.foldlM f b @[specialize] private partial def foldlFromMAux (f : β → α → m β) : PersistentArrayNode α → USize → USize → β → m β | node cs, i, shift, b => do let j := (div2Shift i shift).toNat let b ← foldlFromMAux f (cs.get! j) (mod2Shift i shift) (shift - initShift) b cs.foldlM (init := b) (start := j+1) fun b c => foldlMAux f c b | leaf vs, i, _, b => vs.foldlM (init := b) (start := i.toNat) f @[specialize] def foldlM (t : PersistentArray α) (f : β → α → m β) (init : β) (start : Nat := 0) : m β := do if start == 0 then let b ← foldlMAux f t.root init t.tail.foldlM f b else if start >= t.tailOff then t.tail.foldlM (init := init) (start := start - t.tailOff) f else do let b ← foldlFromMAux f t.root (USize.ofNat start) t.shift init; t.tail.foldlM f b @[specialize] partial def forInAux {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] [inh : Inhabited β] (f : α → β → m (ForInStep β)) (n : PersistentArrayNode α) (b : β) : m (ForInStep β) := do let mut b := b match n with | leaf vs => for v in vs do match (← f v b) with | r@(ForInStep.done _) => return r | ForInStep.yield bNew => b := bNew return ForInStep.yield b | node cs => for c in cs do match (← forInAux f c b) with | r@(ForInStep.done _) => return r | ForInStep.yield bNew => b := bNew return ForInStep.yield b @[specialize] protected def forIn (t : PersistentArray α) (init : β) (f : α → β → m (ForInStep β)) : m β := do match (← forInAux (inh := ⟨init⟩) f t.root init) with | ForInStep.done b => pure b | ForInStep.yield b => let mut b := b for v in t.tail do match (← f v b) with | ForInStep.done r => return r | ForInStep.yield bNew => b := bNew return b instance : ForIn m (PersistentArray α) α where forIn := PersistentArray.forIn @[specialize] partial def findSomeMAux (f : α → m (Option β)) : PersistentArrayNode α → m (Option β) | node cs => cs.findSomeM? (fun c => findSomeMAux f c) | leaf vs => vs.findSomeM? f @[specialize] def findSomeM? (t : PersistentArray α) (f : α → m (Option β)) : m (Option β) := do match (← findSomeMAux f t.root) with | none => t.tail.findSomeM? f | some b => pure (some b) @[specialize] partial def findSomeRevMAux (f : α → m (Option β)) : PersistentArrayNode α → m (Option β) | node cs => cs.findSomeRevM? (fun c => findSomeRevMAux f c) | leaf vs => vs.findSomeRevM? f @[specialize] def findSomeRevM? (t : PersistentArray α) (f : α → m (Option β)) : m (Option β) := do match (← t.tail.findSomeRevM? f) with | none => findSomeRevMAux f t.root | some b => pure (some b) @[specialize] partial def forMAux (f : α → m PUnit) : PersistentArrayNode α → m PUnit | node cs => cs.forM (fun c => forMAux f c) | leaf vs => vs.forM f @[specialize] def forM (t : PersistentArray α) (f : α → m PUnit) : m PUnit := forMAux f t.root *> t.tail.forM f end @[inline] def foldl {β} (t : PersistentArray α) (f : β → α → β) (init : β) (start : Nat := 0) : β := Id.run $ t.foldlM f init start @[inline] def filter (as : PersistentArray α) (p : α → Bool) : PersistentArray α := as.foldl (init := {}) fun asNew a => if p a then asNew.push a else asNew def toArray (t : PersistentArray α) : Array α := t.foldl Array.push #[] def append (t₁ t₂ : PersistentArray α) : PersistentArray α := if t₁.isEmpty then t₂ else t₂.foldl PersistentArray.push t₁ instance : Append (PersistentArray α) := ⟨append⟩ @[inline] def findSome? {β} (t : PersistentArray α) (f : α → (Option β)) : Option β := Id.run $ t.findSomeM? f @[inline] def findSomeRev? {β} (t : PersistentArray α) (f : α → (Option β)) : Option β := Id.run $ t.findSomeRevM? f def toList (t : PersistentArray α) : List α := (t.foldl (init := []) fun xs x => x :: xs).reverse section variable {m : Type → Type w} [Monad m] @[specialize] partial def anyMAux (p : α → m Bool) : PersistentArrayNode α → m Bool | node cs => cs.anyM fun c => anyMAux p c | leaf vs => vs.anyM p @[specialize] def anyM (t : PersistentArray α) (p : α → m Bool) : m Bool := anyMAux p t.root <||> t.tail.anyM p @[inline] def allM (a : PersistentArray α) (p : α → m Bool) : m Bool := do let b ← anyM a (fun v => do let b ← p v; pure (not b)) pure (not b) end @[inline] def any (a : PersistentArray α) (p : α → Bool) : Bool := Id.run $ anyM a p @[inline] def all (a : PersistentArray α) (p : α → Bool) : Bool := !any a fun v => !p v section variable {m : Type u → Type v} [Monad m] variable {β : Type u} @[specialize] partial def mapMAux (f : α → m β) : PersistentArrayNode α → m (PersistentArrayNode β) | node cs => node <$> cs.mapM (fun c => mapMAux f c) | leaf vs => leaf <$> vs.mapM f @[specialize] def mapM (f : α → m β) (t : PersistentArray α) : m (PersistentArray β) := do let root ← mapMAux f t.root let tail ← t.tail.mapM f pure { t with tail := tail, root := root } end @[inline] def map {β} (f : α → β) (t : PersistentArray α) : PersistentArray β := Id.run $ t.mapM f structure Stats where numNodes : Nat depth : Nat tailSize : Nat partial def collectStats : PersistentArrayNode α → Stats → Nat → Stats | node cs, s, d => cs.foldl (fun s c => collectStats c s (d+1)) { s with numNodes := s.numNodes + 1, depth := Nat.max d s.depth } | leaf vs, s, d => { s with numNodes := s.numNodes + 1, depth := Nat.max d s.depth } def stats (r : PersistentArray α) : Stats := collectStats r.root { numNodes := 0, depth := 0, tailSize := r.tail.size } 0 def Stats.toString (s : Stats) : String := s!"\{nodes := {s.numNodes}, depth := {s.depth}, tail size := {s.tailSize}}" instance : ToString Stats := ⟨Stats.toString⟩ end PersistentArray def mkPersistentArray {α : Type u} (n : Nat) (v : α) : PArray α := n.fold (init := PersistentArray.empty) fun i p => p.push v @[inline] def mkPArray {α : Type u} (n : Nat) (v : α) : PArray α := mkPersistentArray n v end Std open Std (PersistentArray PersistentArray.empty) def List.toPersistentArrayAux {α : Type u} : List α → PersistentArray α → PersistentArray α | [], t => t | x::xs, t => toPersistentArrayAux xs (t.push x) def List.toPersistentArray {α : Type u} (xs : List α) : PersistentArray α := xs.toPersistentArrayAux {} def Array.toPersistentArray {α : Type u} (xs : Array α) : PersistentArray α := xs.foldl (init := PersistentArray.empty) fun p x => p.push x @[inline] def Array.toPArray {α : Type u} (xs : Array α) : PersistentArray α := xs.toPersistentArray
247fd1a543da345cde855be2dafd5ca04d4ba857
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/typeAscImp.lean
4322b0e9359ea19e4955886291c0341c425257b3
[ "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
215
lean
def Ctx := String → Type abbrev State (Γ : Ctx) := {x : String} → Γ x opaque p {Γ : Ctx} (s : State Γ) : Prop theorem ex {Γ : Ctx} (s : State Γ) (h : (a : State Γ) → @p Γ a) : @p Γ s := h ‹_›
80b38a26e7d01044bb566d31c9f6d31c55bce6e9
ddf69e0b8ad10bfd251aa1fb492bd92f064768ec
/src/category_theory/limits/cones.lean
c49953c3d640e0b6b698bd7045c23bd13c4122d7
[ "Apache-2.0" ]
permissive
MaboroshiChan/mathlib
db1c1982df384a2604b19a5e1f5c6464c7c76de1
7f74e6b35f6bac86b9218250e83441ac3e17264c
refs/heads/master
1,671,993,587,476
1,601,911,102,000
1,601,911,102,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
26,384
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, Floris van Doorn -/ import category_theory.const import category_theory.yoneda import category_theory.reflects_isomorphisms universes v u u' -- declare the `v`'s first; see `category_theory.category` for an explanation open category_theory variables {J : Type v} [small_category J] variables {C : Type u} [category.{v} C] open category_theory open category_theory.category open category_theory.functor open opposite namespace category_theory namespace functor variables {J C} (F : J ⥤ C) /-- `F.cones` is the functor assigning to an object `X` the type of natural transformations from the constant functor with value `X` to `F`. An object representing this functor is a limit of `F`. -/ def cones : Cᵒᵖ ⥤ Type v := (const J).op ⋙ (yoneda.obj F) lemma cones_obj (X : Cᵒᵖ) : F.cones.obj X = ((const J).obj (unop X) ⟶ F) := rfl @[simp] lemma cones_map_app {X₁ X₂ : Cᵒᵖ} (f : X₁ ⟶ X₂) (t : F.cones.obj X₁) (j : J) : (F.cones.map f t).app j = f.unop ≫ t.app j := rfl /-- `F.cocones` is the functor assigning to an object `X` the type of natural transformations from `F` to the constant functor with value `X`. An object corepresenting this functor is a colimit of `F`. -/ def cocones : C ⥤ Type v := const J ⋙ coyoneda.obj (op F) lemma cocones_obj (X : C) : F.cocones.obj X = (F ⟶ (const J).obj X) := rfl @[simp] lemma cocones_map_app {X₁ X₂ : C} (f : X₁ ⟶ X₂) (t : F.cocones.obj X₁) (j : J) : (F.cocones.map f t).app j = t.app j ≫ f := rfl end functor section variables (J C) /-- Functorially associated to each functor `J ⥤ C`, we have the `C`-presheaf consisting of cones with a given cone point. -/ @[simps] def cones : (J ⥤ C) ⥤ (Cᵒᵖ ⥤ Type v) := { obj := functor.cones, map := λ F G f, whisker_left (const J).op (yoneda.map f) } /-- Contravariantly associated to each functor `J ⥤ C`, we have the `C`-copresheaf consisting of cocones with a given cocone point. -/ @[simps] def cocones : (J ⥤ C)ᵒᵖ ⥤ (C ⥤ Type v) := { obj := λ F, functor.cocones (unop F), map := λ F G f, whisker_left (const J) (coyoneda.map f) } end namespace limits /-- A `c : cone F` is: * an object `c.X` and * a natural transformation `c.π : c.X ⟶ F` from the constant `c.X` functor to `F`. `cone F` is equivalent, via `cone.equiv` below, to `Σ X, F.cones.obj X`. -/ structure cone (F : J ⥤ C) := (X : C) (π : (const J).obj X ⟶ F) @[simp, reassoc] lemma cone.w {F : J ⥤ C} (c : cone F) {j j' : J} (f : j ⟶ j') : c.π.app j ≫ F.map f = c.π.app j' := by { rw ← (c.π.naturality f), apply id_comp } /-- A `c : cocone F` is * an object `c.X` and * a natural transformation `c.ι : F ⟶ c.X` from `F` to the constant `c.X` functor. `cocone F` is equivalent, via `cone.equiv` below, to `Σ X, F.cocones.obj X`. -/ structure cocone (F : J ⥤ C) := (X : C) (ι : F ⟶ (const J).obj X) @[simp, reassoc] lemma cocone.w {F : J ⥤ C} (c : cocone F) {j j' : J} (f : j ⟶ j') : F.map f ≫ c.ι.app j' = c.ι.app j := by { rw (c.ι.naturality f), apply comp_id } variables {F : J ⥤ C} namespace cone /-- The isomorphism between a cone on `F` and an element of the functor `F.cones`. -/ def equiv (F : J ⥤ C) : cone F ≅ Σ X, F.cones.obj X := { hom := λ c, ⟨op c.X, c.π⟩, inv := λ c, { X := unop c.1, π := c.2 }, hom_inv_id' := begin ext, cases x, refl, end, inv_hom_id' := begin ext, cases x, refl, end } @[simp] def extensions (c : cone F) : yoneda.obj c.X ⟶ F.cones := { app := λ X f, (const J).map f ≫ c.π } /-- A map to the vertex of a cone induces a cone by composition. -/ @[simp] def extend (c : cone F) {X : C} (f : X ⟶ c.X) : cone F := { X := X, π := c.extensions.app (op X) f } @[simp] lemma extend_π (c : cone F) {X : Cᵒᵖ} (f : unop X ⟶ c.X) : (extend c f).π = c.extensions.app X f := rfl /-- Whisker a cone by precomposition of a functor. -/ @[simps] def whisker {K : Type v} [small_category K] (E : K ⥤ J) (c : cone F) : cone (E ⋙ F) := { X := c.X, π := whisker_left E c.π } end cone namespace cocone /-- The isomorphism between a cocone on `F` and an element of the functor `F.cocones`. -/ def equiv (F : J ⥤ C) : cocone F ≅ Σ X, F.cocones.obj X := { hom := λ c, ⟨c.X, c.ι⟩, inv := λ c, { X := c.1, ι := c.2 }, hom_inv_id' := begin ext, cases x, refl, end, inv_hom_id' := begin ext, cases x, refl, end } @[simp] def extensions (c : cocone F) : coyoneda.obj (op c.X) ⟶ F.cocones := { app := λ X f, c.ι ≫ (const J).map f } /-- A map from the vertex of a cocone induces a cocone by composition. -/ @[simp] def extend (c : cocone F) {X : C} (f : c.X ⟶ X) : cocone F := { X := X, ι := c.extensions.app X f } @[simp] lemma extend_ι (c : cocone F) {X : C} (f : c.X ⟶ X) : (extend c f).ι = c.extensions.app X f := rfl /-- Whisker a cocone by precomposition of a functor. See `whiskering` for a functorial version. -/ @[simps] def whisker {K : Type v} [small_category K] (E : K ⥤ J) (c : cocone F) : cocone (E ⋙ F) := { X := c.X, ι := whisker_left E c.ι } end cocone /-- A cone morphism between two cones for the same diagram is a morphism of the cone points which commutes with the cone legs. -/ @[ext] structure cone_morphism (A B : cone F) := (hom : A.X ⟶ B.X) (w' : ∀ j : J, hom ≫ B.π.app j = A.π.app j . obviously) restate_axiom cone_morphism.w' attribute [simp, reassoc] cone_morphism.w /-- The category of cones on a given diagram. -/ @[simps] instance cone.category : category.{v} (cone F) := { hom := λ A B, cone_morphism A B, comp := λ X Y Z f g, { hom := f.hom ≫ g.hom }, id := λ B, { hom := 𝟙 B.X } } namespace cones /-- To give an isomorphism between cones, it suffices to give an isomorphism between their vertices which commutes with the cone maps. -/ @[ext, simps] def ext {c c' : cone F} (φ : c.X ≅ c'.X) (w : ∀ j, c.π.app j = φ.hom ≫ c'.π.app j) : c ≅ c' := { hom := { hom := φ.hom }, inv := { hom := φ.inv, w' := λ j, φ.inv_comp_eq.mpr (w j) } } /-- Given a cone morphism whose object part is an isomorphism, produce an isomorphism of cones. -/ def cone_iso_of_hom_iso {K : J ⥤ C} {c d : cone K} (f : c ⟶ d) [i : is_iso f.hom] : is_iso f := { inv := { hom := i.inv, w' := λ j, (as_iso f.hom).inv_comp_eq.2 (f.w j).symm } } /-- Functorially postcompose a cone for `F` by a natural transformation `F ⟶ G` to give a cone for `G`. -/ @[simps] def postcompose {G : J ⥤ C} (α : F ⟶ G) : cone F ⥤ cone G := { obj := λ c, { X := c.X, π := c.π ≫ α }, map := λ c₁ c₂ f, { hom := f.hom, w' := by intro; erw ← category.assoc; simp [-category.assoc] } } /-- Postcomposing a cone by the composite natural transformation `α ≫ β` is the same as postcomposing by `α` and then by `β`. -/ def postcompose_comp {G H : J ⥤ C} (α : F ⟶ G) (β : G ⟶ H) : postcompose (α ≫ β) ≅ postcompose α ⋙ postcompose β := nat_iso.of_components (λ s, cones.ext (iso.refl _) (by tidy)) (by tidy) /-- Postcomposing by the identity does not change the cone up to isomorphism. -/ def postcompose_id : postcompose (𝟙 F) ≅ 𝟭 (cone F) := nat_iso.of_components (λ s, cones.ext (iso.refl _) (by tidy)) (by tidy) /-- If `F` and `G` are naturally isomorphic functors, then they have equivalent categories of cones. -/ @[simps] def postcompose_equivalence {G : J ⥤ C} (α : F ≅ G) : cone F ≌ cone G := { functor := postcompose α.hom, inverse := postcompose α.inv, unit_iso := nat_iso.of_components (λ s, cones.ext (iso.refl _) (by tidy)) (by tidy), counit_iso := nat_iso.of_components (λ s, cones.ext (iso.refl _) (by tidy)) (by tidy) } /-- Whiskering on the left by `E : K ⥤ J` gives a functor from `cone F` to `cone (E ⋙ F)`. -/ @[simps] def whiskering {K : Type v} [small_category K] (E : K ⥤ J) : cone F ⥤ cone (E ⋙ F) := { obj := λ c, c.whisker E, map := λ c c' f, { hom := f.hom, } } /-- Whiskering by an equivalence gives an equivalence between categories of cones. -/ @[simps] def whiskering_equivalence {K : Type v} [small_category K] (e : K ≌ J) : cone F ≌ cone (e.functor ⋙ F) := { functor := whiskering e.functor, inverse := whiskering e.inverse ⋙ postcompose ((functor.associator _ _ _).inv ≫ (whisker_right (e.counit_iso).hom F) ≫ (functor.left_unitor F).hom), unit_iso := nat_iso.of_components (λ s, cones.ext (iso.refl _) (by tidy)) (by tidy), counit_iso := nat_iso.of_components (λ s, cones.ext (iso.refl _) (begin intro k, have t := s.π.naturality (e.unit_inv.app k), dsimp at t, simp only [←e.counit_app_functor k, id_comp] at t, dsimp, simp [t], end)) (by tidy), } /-- The categories of cones over `F` and `G` are equivalent if `F` and `G` are naturally isomorphic (possibly after changing the indexing category by an equivalence). -/ def equivalence_of_reindexing {K : Type v} [small_category K] {G : K ⥤ C} (e : K ≌ J) (α : e.functor ⋙ F ≅ G) : cone F ≌ cone G := (whiskering_equivalence e).trans (postcompose_equivalence α) @[simp] lemma equivalence_of_reindexing_functor_obj {K : Type v} [small_category K] {G : K ⥤ C} (e : K ≌ J) (α : e.functor ⋙ F ≅ G) (c : cone F) : (equivalence_of_reindexing e α).functor.obj c = (postcompose α.hom).obj (cone.whisker e.functor c) := rfl section variable (F) /-- Forget the cone structure and obtain just the cone point. -/ @[simps] def forget : cone F ⥤ C := { obj := λ t, t.X, map := λ s t f, f.hom } variables {D : Type u'} [category.{v} D] (G : C ⥤ D) /-- A functor `G : C ⥤ D` sends cones over `F` to cones over `F ⋙ G` functorially. -/ @[simps] def functoriality : cone F ⥤ cone (F ⋙ G) := { obj := λ A, { X := G.obj A.X, π := { app := λ j, G.map (A.π.app j), naturality' := by intros; erw ←G.map_comp; tidy } }, map := λ X Y f, { hom := G.map f.hom, w' := by intros; rw [←functor.map_comp, f.w] } } instance functoriality_full [full G] [faithful G] : full (functoriality F G) := { preimage := λ X Y t, { hom := G.preimage t.hom, w' := λ j, G.map_injective (by simpa using t.w j) } } instance functoriality_faithful [faithful G] : faithful (cones.functoriality F G) := { map_injective' := λ X Y f g e, by { ext1, injection e, apply G.map_injective h_1 } } /-- If `e : C ≌ D` is an equivalence of categories, then `functoriality F e.functor` induces an equivalence between cones over `F` and cones over `F ⋙ e.functor`. -/ @[simps] def functoriality_equivalence (e : C ≌ D) : cone F ≌ cone (F ⋙ e.functor) := let f : (F ⋙ e.functor) ⋙ e.inverse ≅ F := functor.associator _ _ _ ≪≫ iso_whisker_left _ (e.unit_iso).symm ≪≫ functor.right_unitor _ in { functor := functoriality F e.functor, inverse := (functoriality (F ⋙ e.functor) e.inverse) ⋙ (postcompose_equivalence f).functor, unit_iso := nat_iso.of_components (λ c, cones.ext (e.unit_iso.app _) (by tidy)) (by tidy), counit_iso := nat_iso.of_components (λ c, cones.ext (e.counit_iso.app _) (by tidy)) (by tidy), } /-- If `F` reflects isomorphisms, then `cones.functoriality F` reflects isomorphisms as well. -/ instance reflects_cone_isomorphism (F : C ⥤ D) [reflects_isomorphisms F] (K : J ⥤ C) : reflects_isomorphisms (cones.functoriality K F) := begin constructor, introsI, haveI : is_iso (F.map f.hom) := (cones.forget (K ⋙ F)).map_is_iso ((cones.functoriality K F).map f), haveI := reflects_isomorphisms.reflects F f.hom, apply cone_iso_of_hom_iso end end end cones /-- A cocone morphism between two cocones for the same diagram is a morphism of the cocone points which commutes with the cocone legs. -/ @[ext] structure cocone_morphism (A B : cocone F) := (hom : A.X ⟶ B.X) (w' : ∀ j : J, A.ι.app j ≫ hom = B.ι.app j . obviously) restate_axiom cocone_morphism.w' attribute [simp, reassoc] cocone_morphism.w @[simps] instance cocone.category : category.{v} (cocone F) := { hom := λ A B, cocone_morphism A B, comp := λ _ _ _ f g, { hom := f.hom ≫ g.hom }, id := λ B, { hom := 𝟙 B.X } } namespace cocones /-- To give an isomorphism between cocones, it suffices to give an isomorphism between their vertices which commutes with the cocone maps. -/ @[ext, simps] def ext {c c' : cocone F} (φ : c.X ≅ c'.X) (w : ∀ j, c.ι.app j ≫ φ.hom = c'.ι.app j) : c ≅ c' := { hom := { hom := φ.hom }, inv := { hom := φ.inv, w' := λ j, φ.comp_inv_eq.mpr (w j).symm } } /-- Given a cocone morphism whose object part is an isomorphism, produce an isomorphism of cocones. -/ def cocone_iso_of_hom_iso {K : J ⥤ C} {c d : cocone K} (f : c ⟶ d) [i : is_iso f.hom] : is_iso f := { inv := { hom := i.inv, w' := λ j, (as_iso f.hom).comp_inv_eq.2 (f.w j).symm } } /-- Functorially precompose a cocone for `F` by a natural transformation `G ⟶ F` to give a cocone for `G`. -/ @[simps] def precompose {G : J ⥤ C} (α : G ⟶ F) : cocone F ⥤ cocone G := { obj := λ c, { X := c.X, ι := α ≫ c.ι }, map := λ c₁ c₂ f, { hom := f.hom } } /-- Precomposing a cocone by the composite natural transformation `α ≫ β` is the same as precomposing by `β` and then by `α`. -/ def precompose_comp {G H : J ⥤ C} (α : F ⟶ G) (β : G ⟶ H) : precompose (α ≫ β) ≅ precompose β ⋙ precompose α := nat_iso.of_components (λ s, cocones.ext (iso.refl _) (by tidy)) (by tidy) /-- Precomposing by the identity does not change the cocone up to isomorphism. -/ def precompose_id : precompose (𝟙 F) ≅ 𝟭 (cocone F) := nat_iso.of_components (λ s, cocones.ext (iso.refl _) (by tidy)) (by tidy) /-- If `F` and `G` are naturally isomorphic functors, then they have equivalent categories of cocones. -/ @[simps] def precompose_equivalence {G : J ⥤ C} (α : G ≅ F) : cocone F ≌ cocone G := { functor := precompose α.hom, inverse := precompose α.inv, unit_iso := nat_iso.of_components (λ s, cocones.ext (iso.refl _) (by tidy)) (by tidy), counit_iso := nat_iso.of_components (λ s, cocones.ext (iso.refl _) (by tidy)) (by tidy) } /-- Whiskering on the left by `E : K ⥤ J` gives a functor from `cocone F` to `cocone (E ⋙ F)`. -/ @[simps] def whiskering {K : Type v} [small_category K] (E : K ⥤ J) : cocone F ⥤ cocone (E ⋙ F) := { obj := λ c, c.whisker E, map := λ c c' f, { hom := f.hom, } } /-- Whiskering by an equivalence gives an equivalence between categories of cones. -/ @[simps] def whiskering_equivalence {K : Type v} [small_category K] (e : K ≌ J) : cocone F ≌ cocone (e.functor ⋙ F) := { functor := whiskering e.functor, inverse := whiskering e.inverse ⋙ precompose ((functor.left_unitor F).inv ≫ (whisker_right (e.counit_iso).inv F) ≫ (functor.associator _ _ _).inv), unit_iso := nat_iso.of_components (λ s, cocones.ext (iso.refl _) (by tidy)) (by tidy), counit_iso := nat_iso.of_components (λ s, cocones.ext (iso.refl _) (begin intro k, have t := s.ι.naturality (e.unit.app k), dsimp at t, simp only [←e.counit_inv_app_functor k, comp_id] at t, dsimp, simp [t], end)) (by tidy), } /-- The categories of cocones over `F` and `G` are equivalent if `F` and `G` are naturally isomorphic (possibly after changing the indexing category by an equivalence). -/ def equivalence_of_reindexing {K : Type v} [small_category K] {G : K ⥤ C} (e : K ≌ J) (α : e.functor ⋙ F ≅ G) : cocone F ≌ cocone G := (whiskering_equivalence e).trans (precompose_equivalence α.symm) @[simp] lemma equivalence_of_reindexing_functor_obj {K : Type v} [small_category K] {G : K ⥤ C} (e : K ≌ J) (α : e.functor ⋙ F ≅ G) (c : cocone F) : (equivalence_of_reindexing e α).functor.obj c = (precompose α.inv).obj (cocone.whisker e.functor c) := rfl section variable (F) /-- Forget the cocone structure and obtain just the cocone point. -/ @[simps] def forget : cocone F ⥤ C := { obj := λ t, t.X, map := λ s t f, f.hom } variables {D : Type u'} [category.{v} D] (G : C ⥤ D) /-- A functor `G : C ⥤ D` sends cocones over `F` to cocones over `F ⋙ G` functorially. -/ @[simps] def functoriality : cocone F ⥤ cocone (F ⋙ G) := { obj := λ A, { X := G.obj A.X, ι := { app := λ j, G.map (A.ι.app j), naturality' := by intros; erw ←G.map_comp; tidy } }, map := λ _ _ f, { hom := G.map f.hom, w' := by intros; rw [←functor.map_comp, cocone_morphism.w] } } instance functoriality_full [full G] [faithful G] : full (functoriality F G) := { preimage := λ X Y t, { hom := G.preimage t.hom, w' := λ j, G.map_injective (by simpa using t.w j) } } instance functoriality_faithful [faithful G] : faithful (functoriality F G) := { map_injective' := λ X Y f g e, by { ext1, injection e, apply G.map_injective h_1 } } /-- If `e : C ≌ D` is an equivalence of categories, then `functoriality F e.functor` induces an equivalence between cocones over `F` and cocones over `F ⋙ e.functor`. -/ @[simps] def functoriality_equivalence (e : C ≌ D) : cocone F ≌ cocone (F ⋙ e.functor) := let f : (F ⋙ e.functor) ⋙ e.inverse ≅ F := functor.associator _ _ _ ≪≫ iso_whisker_left _ (e.unit_iso).symm ≪≫ functor.right_unitor _ in { functor := functoriality F e.functor, inverse := (functoriality (F ⋙ e.functor) e.inverse) ⋙ (precompose_equivalence f.symm).functor, unit_iso := nat_iso.of_components (λ c, cocones.ext (e.unit_iso.app _) (by tidy)) (by tidy), counit_iso := nat_iso.of_components (λ c, cocones.ext (e.counit_iso.app _) begin -- Unfortunately this doesn't work by `tidy`. -- In this configuration `simp` reaches a dead-end and needs help. intros j, dsimp, simp only [←equivalence.counit_inv_app_functor, iso.inv_hom_id_app, map_comp, equivalence.fun_inv_map, assoc, id_comp, iso.inv_hom_id_app_assoc], dsimp, simp, -- See note [dsimp, simp]. end) (by tidy), } /-- If `F` reflects isomorphisms, then `cocones.functoriality F` reflects isomorphisms as well. -/ instance reflects_cocone_isomorphism (F : C ⥤ D) [reflects_isomorphisms F] (K : J ⥤ C) : reflects_isomorphisms (cocones.functoriality K F) := begin constructor, introsI, haveI : is_iso (F.map f.hom) := (cocones.forget (K ⋙ F)).map_is_iso ((cocones.functoriality K F).map f), haveI := reflects_isomorphisms.reflects F f.hom, apply cocone_iso_of_hom_iso end end end cocones end limits namespace functor variables {D : Type u'} [category.{v} D] variables {F : J ⥤ C} {G : J ⥤ C} (H : C ⥤ D) open category_theory.limits /-- The image of a cone in C under a functor G : C ⥤ D is a cone in D. -/ def map_cone (c : cone F) : cone (F ⋙ H) := (cones.functoriality F H).obj c /-- The image of a cocone in C under a functor G : C ⥤ D is a cocone in D. -/ def map_cocone (c : cocone F) : cocone (F ⋙ H) := (cocones.functoriality F H).obj c @[simp] lemma map_cone_X (c : cone F) : (H.map_cone c).X = H.obj c.X := rfl @[simp] lemma map_cocone_X (c : cocone F) : (H.map_cocone c).X = H.obj c.X := rfl /-- Given a cone morphism `c ⟶ c'`, construct a cone morphism on the mapped cones functorially. -/ def map_cone_morphism {c c' : cone F} (f : c ⟶ c') : H.map_cone c ⟶ H.map_cone c' := (cones.functoriality F H).map f /-- Given a cocone morphism `c ⟶ c'`, construct a cocone morphism on the mapped cocones functorially. -/ def map_cocone_morphism {c c' : cocone F} (f : c ⟶ c') : H.map_cocone c ⟶ H.map_cocone c' := (cocones.functoriality F H).map f @[simp] lemma map_cone_π (c : cone F) (j : J) : (map_cone H c).π.app j = H.map (c.π.app j) := rfl @[simp] lemma map_cocone_ι (c : cocone F) (j : J) : (map_cocone H c).ι.app j = H.map (c.ι.app j) := rfl /-- If `H` is an equivalence, we invert `H.map_cone` and get a cone for `F` from a cone for `F ⋙ H`.-/ def map_cone_inv [is_equivalence H] (c : cone (F ⋙ H)) : cone F := (limits.cones.functoriality_equivalence F (as_equivalence H)).inverse.obj c /-- `map_cone` is the left inverse to `map_cone_inv`. -/ def map_cone_map_cone_inv {F : J ⥤ D} (H : D ⥤ C) [is_equivalence H] (c : cone (F ⋙ H)) : map_cone H (map_cone_inv H c) ≅ c := (limits.cones.functoriality_equivalence F (as_equivalence H)).counit_iso.app c /-- `map_cone` is the right inverse to `map_cone_inv`. -/ def map_cone_inv_map_cone {F : J ⥤ D} (H : D ⥤ C) [is_equivalence H] (c : cone F) : map_cone_inv H (map_cone H c) ≅ c := (limits.cones.functoriality_equivalence F (as_equivalence H)).unit_iso.symm.app c /-- If `H` is an equivalence, we invert `H.map_cone` and get a cone for `F` from a cone for `F ⋙ H`.-/ def map_cocone_inv [is_equivalence H] (c : cocone (F ⋙ H)) : cocone F := (limits.cocones.functoriality_equivalence F (as_equivalence H)).inverse.obj c /-- `map_cocone` is the left inverse to `map_cocone_inv`. -/ def map_cocone_map_cocone_inv {F : J ⥤ D} (H : D ⥤ C) [is_equivalence H] (c : cocone (F ⋙ H)) : map_cocone H (map_cocone_inv H c) ≅ c := (limits.cocones.functoriality_equivalence F (as_equivalence H)).counit_iso.app c /-- `map_cocone` is the right inverse to `map_cocone_inv`. -/ def map_cocone_inv_map_cocone {F : J ⥤ D} (H : D ⥤ C) [is_equivalence H] (c : cocone F) : map_cocone_inv H (map_cocone H c) ≅ c := (limits.cocones.functoriality_equivalence F (as_equivalence H)).unit_iso.symm.app c end functor end category_theory namespace category_theory.limits section variables {F : J ⥤ C} /-- Change a `cocone F` into a `cone F.op`. -/ @[simps] def cocone.op (c : cocone F) : cone F.op := { X := op c.X, π := { app := λ j, (c.ι.app (unop j)).op, naturality' := λ j j' f, has_hom.hom.unop_inj (by tidy) } } /-- Change a `cone F` into a `cocone F.op`. -/ @[simps] def cone.op (c : cone F) : cocone F.op := { X := op c.X, ι := { app := λ j, (c.π.app (unop j)).op, naturality' := λ j j' f, has_hom.hom.unop_inj (by tidy) } } /-- Change a `cocone F.op` into a `cone F`. -/ @[simps] def cocone.unop (c : cocone F.op) : cone F := { X := unop c.X, π := { app := λ j, (c.ι.app (op j)).unop, naturality' := λ j j' f, has_hom.hom.op_inj begin dsimp, simp only [comp_id], exact (c.w f.op).symm, end } } /-- Change a `cone F.op` into a `cocone F`. -/ @[simps] def cone.unop (c : cone F.op) : cocone F := { X := unop c.X, ι := { app := λ j, (c.π.app (op j)).unop, naturality' := λ j j' f, has_hom.hom.op_inj begin dsimp, simp only [id_comp], exact (c.w f.op), end } } variables (F) /-- The category of cocones on `F` is equivalent to the opposite category of the category of cones on the opposite of `F`. -/ @[simps] def cocone_equivalence_op_cone_op : cocone F ≌ (cone F.op)ᵒᵖ := { functor := { obj := λ c, op (cocone.op c), map := λ X Y f, has_hom.hom.op { hom := f.hom.op, w' := λ j, by { apply has_hom.hom.unop_inj, dsimp, simp, }, } }, inverse := { obj := λ c, cone.unop (unop c), map := λ X Y f, { hom := f.unop.hom.unop, w' := λ j, by { apply has_hom.hom.op_inj, dsimp, simp, }, } }, unit_iso := nat_iso.of_components (λ c, cocones.ext (iso.refl _) (by tidy)) (by tidy), counit_iso := nat_iso.of_components (λ c, by { op_induction c, dsimp, apply iso.op, exact cones.ext (iso.refl _) (by tidy), }) begin intros, have hX : X = op (unop X) := rfl, revert hX, generalize : unop X = X', rintro rfl, have hY : Y = op (unop Y) := rfl, revert hY, generalize : unop Y = Y', rintro rfl, apply has_hom.hom.unop_inj, apply cone_morphism.ext, dsimp, simp, end, functor_unit_iso_comp' := λ c, begin apply has_hom.hom.unop_inj, ext, dsimp, simp, end } end section variables {F : J ⥤ Cᵒᵖ} /-- Change a cocone on `F.left_op : Jᵒᵖ ⥤ C` to a cocone on `F : J ⥤ Cᵒᵖ`. -/ -- Here and below we only automatically generate the `@[simp]` lemma for the `X` field, -- as we can write a simpler `rfl` lemma for the components of the natural transformation by hand. @[simps X] def cone_of_cocone_left_op (c : cocone F.left_op) : cone F := { X := op c.X, π := nat_trans.remove_left_op (c.ι ≫ (const.op_obj_unop (op c.X)).hom) } @[simp] lemma cone_of_cocone_left_op_π_app (c : cocone F.left_op) (j) : (cone_of_cocone_left_op c).π.app j = (c.ι.app (op j)).op := by { dsimp [cone_of_cocone_left_op], simp } /-- Change a cone on `F : J ⥤ Cᵒᵖ` to a cocone on `F.left_op : Jᵒᵖ ⥤ C`. -/ @[simps X] def cocone_left_op_of_cone (c : cone F) : cocone (F.left_op) := { X := unop c.X, ι := nat_trans.left_op c.π } @[simp] lemma cocone_left_op_of_cone_ι_app (c : cone F) (j) : (cocone_left_op_of_cone c).ι.app j = (c.π.app (unop j)).unop := by { dsimp [cocone_left_op_of_cone], simp } /-- Change a cone on `F.left_op : Jᵒᵖ ⥤ C` to a cocone on `F : J ⥤ Cᵒᵖ`. -/ @[simps X] def cocone_of_cone_left_op (c : cone F.left_op) : cocone F := { X := op c.X, ι := nat_trans.remove_left_op ((const.op_obj_unop (op c.X)).hom ≫ c.π) } @[simp] lemma cocone_of_cone_left_op_ι_app (c : cone F.left_op) (j) : (cocone_of_cone_left_op c).ι.app j = (c.π.app (op j)).op := by { dsimp [cocone_of_cone_left_op], simp } /-- Change a cocone on `F : J ⥤ Cᵒᵖ` to a cone on `F.left_op : Jᵒᵖ ⥤ C`. -/ @[simps X] def cone_left_op_of_cocone (c : cocone F) : cone (F.left_op) := { X := unop c.X, π := nat_trans.left_op c.ι } @[simp] lemma cone_left_op_of_cocone_π_app (c : cocone F) (j) : (cone_left_op_of_cocone c).π.app j = (c.ι.app (unop j)).unop := by { dsimp [cone_left_op_of_cocone], simp } end end category_theory.limits namespace category_theory.functor open category_theory.limits variables {F : J ⥤ C} variables {D : Type u'} [category.{v} D] section variables (G : C ⥤ D) /-- The opposite cocone of the image of a cone is the image of the opposite cocone. -/ def map_cone_op (t : cone F) : (G.map_cone t).op ≅ (G.op.map_cocone t.op) := cocones.ext (iso.refl _) (by tidy) /-- The opposite cone of the image of a cocone is the image of the opposite cone. -/ def map_cocone_op {t : cocone F} : (G.map_cocone t).op ≅ (G.op.map_cone t.op) := cones.ext (iso.refl _) (by tidy) end end category_theory.functor
2af3ae807c5dda7cb0b5f7078081088c0eba5db1
e61a235b8468b03aee0120bf26ec615c045005d2
/tests/lean/ctor_layout.lean
ae61cf7f62f680ee107f3d9f309495da176a37d3
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
632
lean
import Init.Lean.Compiler.IR open Lean open Lean.IR def tst : IO Unit := do env ← importModules [{module := `Init.Lean.Compiler.IR.Basic}]; ctorLayout ← IO.ofExcept $ getCtorLayout env `Lean.IR.Expr.reuse; ctorLayout.fieldInfo.forM $ fun finfo => IO.println (format finfo); IO.println "---"; ctorLayout ← IO.ofExcept $ getCtorLayout env `Lean.EnvironmentHeader.mk; ctorLayout.fieldInfo.forM $ fun finfo => IO.println (format finfo); IO.println "---"; ctorLayout ← IO.ofExcept $ getCtorLayout env `Subtype.mk; ctorLayout.fieldInfo.forM $ fun finfo => IO.println (format finfo); pure () #eval tst
6762755edbaa2f43dc410c2113b0865dd8f70e7e
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/data/bool.lean
43d60f361abdde899ceb00942e816ca83db8d194
[ "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
4,294
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, Jeremy Avigad -/ namespace bool @[simp] theorem coe_sort_tt : coe_sort.{1 1} tt = true := eq_true_intro rfl @[simp] theorem coe_sort_ff : coe_sort.{1 1} ff = false := eq_false_intro ff_ne_tt @[simp] theorem to_bool_true {h} : @to_bool true h = tt := show _ = to_bool true, by congr @[simp] theorem to_bool_false {h} : @to_bool false h = ff := show _ = to_bool false, by congr @[simp] theorem to_bool_coe (b:bool) {h} : @to_bool b h = b := (show _ = to_bool b, by congr).trans (by cases b; refl) @[simp] theorem coe_to_bool (p : Prop) [decidable p] : to_bool p ↔ p := to_bool_iff _ @[simp] lemma of_to_bool_iff {p : Prop} [decidable p] : to_bool p ↔ p := ⟨of_to_bool_true, _root_.to_bool_true⟩ @[simp] lemma tt_eq_to_bool_iff {p : Prop} [decidable p] : tt = to_bool p ↔ p := eq_comm.trans of_to_bool_iff @[simp] lemma ff_eq_to_bool_iff {p : Prop} [decidable p] : ff = to_bool p ↔ ¬ p := eq_comm.trans (to_bool_ff_iff _) @[simp] theorem to_bool_not (p : Prop) [decidable p] : to_bool (¬ p) = bnot (to_bool p) := by by_cases p; simp * @[simp] theorem to_bool_and (p q : Prop) [decidable p] [decidable q] : to_bool (p ∧ q) = p && q := by by_cases p; by_cases q; simp * @[simp] theorem to_bool_or (p q : Prop) [decidable p] [decidable q] : to_bool (p ∨ q) = p || q := by by_cases p; by_cases q; simp * @[simp] theorem to_bool_eq {p q : Prop} [decidable p] [decidable q] : to_bool p = to_bool q ↔ (p ↔ q) := ⟨λ h, (coe_to_bool p).symm.trans $ by simp [h], to_bool_congr⟩ lemma not_ff : ¬ ff := by simp @[simp] theorem default_bool : default bool = ff := rfl theorem dichotomy (b : bool) : b = ff ∨ b = tt := by cases b; simp theorem forall_bool {p : bool → Prop} : (∀ b, p b) ↔ p ff ∧ p tt := ⟨λ h, by simp [h], λ ⟨h₁, h₂⟩ b, by cases b; assumption⟩ theorem exists_bool {p : bool → Prop} : (∃ b, p b) ↔ p ff ∨ p tt := ⟨λ ⟨b, h⟩, by cases b; [exact or.inl h, exact or.inr h], λ h, by cases h; exact ⟨_, h⟩⟩ instance decidable_forall_bool {p : bool → Prop} [∀ b, decidable (p b)] : decidable (∀ b, p b) := decidable_of_decidable_of_iff and.decidable forall_bool.symm instance decidable_exists_bool {p : bool → Prop} [∀ b, decidable (p b)] : decidable (∃ b, p b) := decidable_of_decidable_of_iff or.decidable exists_bool.symm @[simp] theorem cond_ff {α} (t e : α) : cond ff t e = e := rfl @[simp] theorem cond_tt {α} (t e : α) : cond tt t e = t := rfl @[simp] theorem cond_to_bool {α} (p : Prop) [decidable p] (t e : α) : cond (to_bool p) t e = if p then t else e := by by_cases p; simp * theorem eq_tt_of_ne_ff : ∀ {a : bool}, a ≠ ff → a = tt := dec_trivial theorem eq_ff_of_ne_tt : ∀ {a : bool}, a ≠ tt → a = ff := dec_trivial @[simp] theorem bor_comm : ∀ a b, a || b = b || a := dec_trivial @[simp] theorem bor_assoc : ∀ a b c, (a || b) || c = a || (b || c) := dec_trivial @[simp] theorem bor_left_comm : ∀ a b c, a || (b || c) = b || (a || c) := dec_trivial theorem bor_inl {a b : bool} (H : a) : a || b := by simp [H] theorem bor_inr {a b : bool} (H : b) : a || b := by simp [H] @[simp] theorem band_comm : ∀ a b, a && b = b && a := dec_trivial @[simp] theorem band_assoc : ∀ a b c, (a && b) && c = a && (b && c) := dec_trivial @[simp] theorem band_left_comm : ∀ a b c, a && (b && c) = b && (a && c) := dec_trivial theorem band_elim_left : ∀ {a b : bool}, a && b → a := dec_trivial theorem band_intro : ∀ {a b : bool}, a → b → a && b := dec_trivial theorem band_elim_right : ∀ {a b : bool}, a && b → b := dec_trivial @[simp] theorem bnot_false : bnot ff = tt := rfl @[simp] theorem bnot_true : bnot tt = ff := rfl theorem eq_tt_of_bnot_eq_ff : ∀ {a : bool}, bnot a = ff → a = tt := dec_trivial theorem eq_ff_of_bnot_eq_tt : ∀ {a : bool}, bnot a = tt → a = ff := dec_trivial @[simp] theorem bxor_comm : ∀ a b, bxor a b = bxor b a := dec_trivial @[simp] theorem bxor_assoc : ∀ a b c, bxor (bxor a b) c = bxor a (bxor b c) := dec_trivial @[simp] theorem bxor_left_comm : ∀ a b c, bxor a (bxor b c) = bxor b (bxor a c) := dec_trivial end bool
3fdaf181d7c44e4d085aee6975e663bf57e12fa5
5c5878e769950eabe897ad08485b3ba1a619cea9
/src/categories/universal/kernels.lean
b20086d2d2e033ca9a16b400c176518d6fde888d
[ "Apache-2.0" ]
permissive
semorrison/lean-category-theory-pr
39dc2077fcb41b438e61be1685e4cbca298767ed
7adc8d91835e883db0fe75aa33661bc1480dbe55
refs/heads/master
1,583,748,682,010
1,535,111,040,000
1,535,111,040,000
128,731,071
1
2
Apache-2.0
1,528,069,880,000
1,523,258,452,000
Lean
UTF-8
Lean
false
false
3,025
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 categories.universal.instances open category_theory open category_theory.initial namespace category_theory.universal universes u v w section variables {C : Type u} [𝒞 : category.{u v} C] [has_ZeroObject.{u v} C] include 𝒞 variables {X Y : C} structure Kernel (f : X ⟶ Y) := (kernel : C) (inclusion : kernel ⟶ X) (map : ∀ {Z : C} (k : Z ⟶ X) (w : k ≫ f = zero_morphism Z Y), Z ⟶ kernel) (witness : inclusion ≫ f = zero_morphism kernel Y . obviously) (factorisation : ∀ {Z : C} (k : Z ⟶ X) (w : k ≫ f = zero_morphism Z Y), (map k w) ≫ inclusion = k . obviously) (uniqueness : ∀ {Z : C} (a b : Z ⟶ kernel) (witness : a ≫ inclusion = b ≫ inclusion), a = b . obviously) def Kernel_to_Equalizer (f : X ⟶ Y) (kernel : Kernel f) : Equalizer f (zero_morphism X Y) := { equalizer := kernel.kernel, inclusion := kernel.inclusion, map := λ Z k w, kernel.map k begin simp [zero_morphism_left] at w, exact w, end, -- TODO why do we need to specify zero_morphism_left explicitly here? Isn't it a simp lemma? witness := sorry, -- FIXME factorisation := sorry, uniqueness := sorry } structure Cokernel (f : X ⟶ Y) := (cokernel : C) (projection : Y ⟶ cokernel) (map : ∀ {Z : C} (k : Y ⟶ Z) (w : f ≫ k = zero_morphism X Z), cokernel ⟶ Z) (witness : f ≫ projection = zero_morphism X cokernel . obviously) (factorisation : ∀ {Z : C} (k : Y ⟶ Z) (w : f ≫ k = zero_morphism X Z), projection ≫ (map k w) = k . obviously) (uniqueness : ∀ {Z : C} (a b : cokernel ⟶ Z) (witness : projection ≫ a = projection ≫ b), a = b . obviously) def Cokernel_to_Coequalizer (f : X ⟶ Y) (cokernel : Cokernel f) : Coequalizer f (zero_morphism X Y) := { coequalizer := cokernel.cokernel, projection := cokernel.projection, map := λ Z k w, cokernel.map k begin simp at w, exact w, end, witness := sorry, -- FIXME factorisation := sorry, uniqueness := sorry } -- TODO Kernels_are_unique, from Equalizers_are_unique def Kernels_are_Equalizers (f : X ⟶ Y) (equalizer : Equalizer f (zero_morphism X Y)) (kernel : Kernel f) : equalizer.equalizer ≅ kernel.kernel := sorry -- prove this by uniqueness of equalizers and the above variables (C) class has_Kernels := (kernel : Π {X Y : C} (f : X ⟶ Y), Kernel f) class has_Cokernels := (cokernel : Π {X Y : C} (f : X ⟶ Y), Cokernel f) variables {C} def kernel [has_Kernels.{u v} C] {X Y : C} (f : X ⟶ Y) := has_Kernels.kernel f def kernel_object [has_Kernels.{u v} C] {X Y : C} (f : X ⟶ Y) : C := (kernel f).kernel def cokernel [has_Cokernels.{u v} C] {X Y : C} (f : X ⟶ Y) := has_Cokernels.cokernel f def cokernel_object [has_Cokernels.{u v} C] {X Y : C} (f : X ⟶ Y) : C := (cokernel f).cokernel end end category_theory.universal
8e74d2450837c211de676f99c3a882d810525728
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/src/category_theory/comma.lean
58a4e37219426a727dc70c69b5c12d814194d344
[ "Apache-2.0" ]
permissive
johoelzl/mathlib
253f46daa30b644d011e8e119025b01ad69735c4
592e3c7a2dfbd5826919b4605559d35d4d75938f
refs/heads/master
1,625,657,216,488
1,551,374,946,000
1,551,374,946,000
98,915,829
0
0
Apache-2.0
1,522,917,267,000
1,501,524,499,000
Lean
UTF-8
Lean
false
false
11,561
lean
-- Copyright (c) 2018 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison, Johan Commelin import category_theory.types import category_theory.isomorphism import category_theory.whiskering import category_theory.opposites import category_theory.punit import category_theory.equivalence namespace category_theory universes v₁ v₂ v₃ u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {A : Type u₁} [𝒜 : category.{v₁} A] variables {B : Type u₂} [ℬ : category.{v₂} B] variables {T : Type u₃} [𝒯 : category.{v₃} T] include 𝒜 ℬ 𝒯 structure comma (L : A ⥤ T) (R : B ⥤ T) := (left : A . obviously) (right : B . obviously) (hom : L.obj left ⟶ R.obj right) variables {L : A ⥤ T} {R : B ⥤ T} structure comma_morphism (X Y : comma L R) := (left : X.left ⟶ Y.left . obviously) (right : X.right ⟶ Y.right . obviously) (w' : L.map left ≫ Y.hom = X.hom ≫ R.map right . obviously) restate_axiom comma_morphism.w' attribute [simp] comma_morphism.w namespace comma_morphism @[extensionality] lemma ext {X Y : comma L R} {f g : comma_morphism X Y} (l : f.left = g.left) (r : f.right = g.right) : f = g := begin cases f, cases g, congr; assumption end end comma_morphism instance comma_category : category (comma L R) := { hom := comma_morphism, id := λ X, { left := 𝟙 X.left, right := 𝟙 X.right }, comp := λ X Y Z f g, { left := f.left ≫ g.left, right := f.right ≫ g.right, w' := begin rw [functor.map_comp, category.assoc, g.w, ←category.assoc, f.w, functor.map_comp, category.assoc], end }} namespace comma section variables {X Y Z : comma L R} {f : X ⟶ Y} {g : Y ⟶ Z} @[simp] lemma comp_left : (f ≫ g).left = f.left ≫ g.left := rfl @[simp] lemma comp_right : (f ≫ g).right = f.right ≫ g.right := rfl end variables (L) (R) def fst : comma L R ⥤ A := { obj := λ X, X.left, map := λ _ _ f, f.left } def snd : comma L R ⥤ B := { obj := λ X, X.right, map := λ _ _ f, f.right } @[simp] lemma fst_obj {X : comma L R} : (fst L R).obj X = X.left := rfl @[simp] lemma snd_obj {X : comma L R} : (snd L R).obj X = X.right := rfl @[simp] lemma fst_map {X Y : comma L R} {f : X ⟶ Y} : (fst L R).map f = f.left := rfl @[simp] lemma snd_map {X Y : comma L R} {f : X ⟶ Y} : (snd L R).map f = f.right := rfl def nat_trans : fst L R ⋙ L ⟹ snd L R ⋙ R := { app := λ X, X.hom } section variables {L₁ L₂ L₃ : A ⥤ T} {R₁ R₂ R₃ : B ⥤ T} def map_left (l : L₁ ⟹ L₂) : comma L₂ R ⥤ comma L₁ R := { obj := λ X, { left := X.left, right := X.right, hom := l.app X.left ≫ X.hom }, map := λ X Y f, { left := f.left, right := f.right, w' := by tidy; rw [←category.assoc, l.naturality f.left, category.assoc]; tidy } } section variables {X Y : comma L₂ R} {f : X ⟶ Y} {l : L₁ ⟹ L₂} @[simp] lemma map_left_obj_left : ((map_left R l).obj X).left = X.left := rfl @[simp] lemma map_left_obj_right : ((map_left R l).obj X).right = X.right := rfl @[simp] lemma map_left_obj_hom : ((map_left R l).obj X).hom = l.app X.left ≫ X.hom := rfl @[simp] lemma map_left_map_left : ((map_left R l).map f).left = f.left := rfl @[simp] lemma map_left_map_right : ((map_left R l).map f).right = f.right := rfl end def map_left_id : map_left R (𝟙 L) ≅ functor.id _ := { hom := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } }, inv := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } } } section variables {X : comma L R} @[simp] lemma map_left_id_hom_app_left : (((map_left_id L R).hom).app X).left = 𝟙 (X.left) := rfl @[simp] lemma map_left_id_hom_app_right : (((map_left_id L R).hom).app X).right = 𝟙 (X.right) := rfl @[simp] lemma map_left_id_inv_app_left : (((map_left_id L R).inv).app X).left = 𝟙 (X.left) := rfl @[simp] lemma map_left_id_inv_app_right : (((map_left_id L R).inv).app X).right = 𝟙 (X.right) := rfl end def map_left_comp (l : L₁ ⟹ L₂) (l' : L₂ ⟹ L₃) : (map_left R (l ⊟ l')) ≅ (map_left R l') ⋙ (map_left R l) := { hom := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } }, inv := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } } } section variables {X : comma L₃ R} {l : L₁ ⟹ L₂} {l' : L₂ ⟹ L₃} @[simp] lemma map_left_comp_hom_app_left : (((map_left_comp R l l').hom).app X).left = 𝟙 (X.left) := rfl @[simp] lemma map_left_comp_hom_app_right : (((map_left_comp R l l').hom).app X).right = 𝟙 (X.right) := rfl @[simp] lemma map_left_comp_inv_app_left : (((map_left_comp R l l').inv).app X).left = 𝟙 (X.left) := rfl @[simp] lemma map_left_comp_inv_app_right : (((map_left_comp R l l').inv).app X).right = 𝟙 (X.right) := rfl end def map_right (r : R₁ ⟹ R₂) : comma L R₁ ⥤ comma L R₂ := { obj := λ X, { left := X.left, right := X.right, hom := X.hom ≫ r.app X.right }, map := λ X Y f, { left := f.left, right := f.right, w' := by tidy; rw [←r.naturality f.right, ←category.assoc]; tidy } } section variables {X Y : comma L R₁} {f : X ⟶ Y} {r : R₁ ⟹ R₂} @[simp] lemma map_right_obj_left : ((map_right L r).obj X).left = X.left := rfl @[simp] lemma map_right_obj_right : ((map_right L r).obj X).right = X.right := rfl @[simp] lemma map_right_obj_hom : ((map_right L r).obj X).hom = X.hom ≫ r.app X.right := rfl @[simp] lemma map_right_map_left : ((map_right L r).map f).left = f.left := rfl @[simp] lemma map_right_map_right : ((map_right L r).map f).right = f.right := rfl end def map_right_id : map_right L (𝟙 R) ≅ functor.id _ := { hom := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } }, inv := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } } } section variables {X : comma L R} @[simp] lemma map_right_id_hom_app_left : (((map_right_id L R).hom).app X).left = 𝟙 (X.left) := rfl @[simp] lemma map_right_id_hom_app_right : (((map_right_id L R).hom).app X).right = 𝟙 (X.right) := rfl @[simp] lemma map_right_id_inv_app_left : (((map_right_id L R).inv).app X).left = 𝟙 (X.left) := rfl @[simp] lemma map_right_id_inv_app_right : (((map_right_id L R).inv).app X).right = 𝟙 (X.right) := rfl end def map_right_comp (r : R₁ ⟹ R₂) (r' : R₂ ⟹ R₃) : (map_right L (r ⊟ r')) ≅ (map_right L r) ⋙ (map_right L r') := { hom := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } }, inv := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } } } section variables {X : comma L R₁} {r : R₁ ⟹ R₂} {r' : R₂ ⟹ R₃} @[simp] lemma map_right_comp_hom_app_left : (((map_right_comp L r r').hom).app X).left = 𝟙 (X.left) := rfl @[simp] lemma map_right_comp_hom_app_right : (((map_right_comp L r r').hom).app X).right = 𝟙 (X.right) := rfl @[simp] lemma map_right_comp_inv_app_left : (((map_right_comp L r r').inv).app X).left = 𝟙 (X.left) := rfl @[simp] lemma map_right_comp_inv_app_right : (((map_right_comp L r r').inv).app X).right = 𝟙 (X.right) := rfl end end end comma omit 𝒜 ℬ def over (X : T) := comma.{v₃ 0 v₃} (functor.id T) (functor.of.obj X) namespace over variables {X : T} instance category : category (over X) := by delta over; apply_instance @[extensionality] lemma over_morphism.ext {X : T} {U V : over X} {f g : U ⟶ V} (h : f.left = g.left) : f = g := by tidy @[simp] lemma over_right (U : over X) : U.right = punit.star := by tidy @[simp] lemma over_morphism_right {U V : over X} (f : U ⟶ V) : f.right = 𝟙 punit.star := by tidy @[simp] lemma id_left (U : over X) : comma_morphism.left (𝟙 U) = 𝟙 U.left := rfl @[simp] lemma comp_left (a b c : over X) (f : a ⟶ b) (g : b ⟶ c) : (f ≫ g).left = f.left ≫ g.left := rfl @[simp] lemma w {A B : over X} (f : A ⟶ B) : f.left ≫ B.hom = A.hom := by have := f.w; tidy def mk {X Y : T} (f : Y ⟶ X) : over X := { left := Y, hom := f } @[simp] lemma mk_left {X Y : T} (f : Y ⟶ X) : (mk f).left = Y := rfl @[simp] lemma mk_hom {X Y : T} (f : Y ⟶ X) : (mk f).hom = f := rfl def hom_mk {U V : over X} (f : U.left ⟶ V.left) (w : f ≫ V.hom = U.hom . obviously) : U ⟶ V := { left := f } @[simp] lemma hom_mk_left {U V : over X} (f : U.left ⟶ V.left) (w : f ≫ V.hom = U.hom) : (hom_mk f).left = f := rfl def forget : (over X) ⥤ T := comma.fst _ _ @[simp] lemma forget_obj {U : over X} : forget.obj U = U.left := rfl @[simp] lemma forget_map {U V : over X} {f : U ⟶ V} : forget.map f = f.left := rfl def map {Y : T} (f : X ⟶ Y) : over X ⥤ over Y := comma.map_right _ $ functor.of.map f section variables {Y : T} {f : X ⟶ Y} {U V : over X} {g : U ⟶ V} @[simp] lemma map_obj_left : ((map f).obj U).left = U.left := rfl @[simp] lemma map_obj_hom : ((map f).obj U).hom = U.hom ≫ f := rfl @[simp] lemma map_map_left : ((map f).map g).left = g.left := rfl end section variables {D : Type u₃} [Dcat : category.{v₃} D] include Dcat def post (F : T ⥤ D) : over X ⥤ over (F.obj X) := { obj := λ Y, mk $ F.map Y.hom, map := λ Y₁ Y₂ f, { left := F.map f.left, w' := by tidy; erw [← F.map_comp, w] } } end end over def under (X : T) := comma.{0 v₃ v₃} (functor.of.obj X) (functor.id T) namespace under variables {X : T} instance : category (under X) := by delta under; apply_instance @[extensionality] lemma under_morphism.ext {X : T} {U V : under X} {f g : U ⟶ V} (h : f.right = g.right) : f = g := by tidy @[simp] lemma under_left (U : under X) : U.left = punit.star := by tidy @[simp] lemma under_morphism_left {U V : under X} (f : U ⟶ V) : f.left = 𝟙 punit.star := by tidy @[simp] lemma id_right (U : under X) : comma_morphism.right (𝟙 U) = 𝟙 U.right := rfl @[simp] lemma comp_right (a b c : under X) (f : a ⟶ b) (g : b ⟶ c) : (f ≫ g).right = f.right ≫ g.right := rfl @[simp] lemma w {A B : under X} (f : A ⟶ B) : A.hom ≫ f.right = B.hom := by have := f.w; tidy def mk {X Y : T} (f : X ⟶ Y) : under X := { right := Y, hom := f } @[simp] lemma mk_right {X Y : T} (f : X ⟶ Y) : (mk f).right = Y := rfl @[simp] lemma mk_hom {X Y : T} (f : X ⟶ Y) : (mk f).hom = f := rfl def hom_mk {U V : under X} (f : U.right ⟶ V.right) (w : U.hom ≫ f = V.hom . obviously) : U ⟶ V := { right := f } @[simp] lemma hom_mk_right {U V : under X} (f : U.right ⟶ V.right) (w : U.hom ≫ f = V.hom) : (hom_mk f).right = f := rfl def forget : (under X) ⥤ T := comma.snd _ _ @[simp] lemma forget_obj {U : under X} : forget.obj U = U.right := rfl @[simp] lemma forget_map {U V : under X} {f : U ⟶ V} : forget.map f = f.right := rfl def map {Y : T} (f : X ⟶ Y) : under Y ⥤ under X := comma.map_left _ $ functor.of.map f section variables {Y : T} {f : X ⟶ Y} {U V : under Y} {g : U ⟶ V} @[simp] lemma map_obj_right : ((map f).obj U).right = U.right := rfl @[simp] lemma map_obj_hom : ((map f).obj U).hom = f ≫ U.hom := rfl @[simp] lemma map_map_right : ((map f).map g).right = g.right := rfl end section variables {D : Type u₃} [Dcat : category.{v₃} D] include Dcat def post {X : T} (F : T ⥤ D) : under X ⥤ under (F.obj X) := { obj := λ Y, mk $ F.map Y.hom, map := λ Y₁ Y₂ f, { right := F.map f.right, w' := by tidy; erw [← F.map_comp, w] } } end end under end category_theory
2c041ddab68d88553004d02d07ccfd4849f8fd2b
c777c32c8e484e195053731103c5e52af26a25d1
/src/geometry/euclidean/angle/oriented/rotation.lean
890777df7fb5ffe37abc172ad19e918bd9487613
[ "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
20,736
lean
/- Copyright (c) 2022 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers, Heather Macbeth -/ import analysis.special_functions.complex.circle import geometry.euclidean.angle.oriented.basic /-! # Rotations by oriented angles. This file defines rotations by oriented angles in real inner product spaces. ## Main definitions * `orientation.rotation` is the rotation by an oriented angle with respect to an orientation. -/ noncomputable theory open finite_dimensional complex open_locale real real_inner_product_space complex_conjugate namespace orientation local attribute [instance] fact_finite_dimensional_of_finrank_eq_succ local attribute [instance] complex.finrank_real_complex_fact variables {V V' : Type*} variables [normed_add_comm_group V] [normed_add_comm_group V'] variables [inner_product_space ℝ V] [inner_product_space ℝ V'] variables [fact (finrank ℝ V = 2)] [fact (finrank ℝ V' = 2)] (o : orientation ℝ V (fin 2)) local notation `J` := o.right_angle_rotation /-- Auxiliary construction to build a rotation by the oriented angle `θ`. -/ def rotation_aux (θ : real.angle) : V →ₗᵢ[ℝ] V := linear_map.isometry_of_inner (real.angle.cos θ • linear_map.id + real.angle.sin θ • ↑(linear_isometry_equiv.to_linear_equiv J)) begin intros x y, simp only [is_R_or_C.conj_to_real, id.def, linear_map.smul_apply, linear_map.add_apply, linear_map.id_coe, linear_equiv.coe_coe, linear_isometry_equiv.coe_to_linear_equiv, orientation.area_form_right_angle_rotation_left, orientation.inner_right_angle_rotation_left, orientation.inner_right_angle_rotation_right, inner_add_left, inner_smul_left, inner_add_right, inner_smul_right], linear_combination inner x y * θ.cos_sq_add_sin_sq, end @[simp] lemma rotation_aux_apply (θ : real.angle) (x : V) : o.rotation_aux θ x = real.angle.cos θ • x + real.angle.sin θ • J x := rfl /-- A rotation by the oriented angle `θ`. -/ def rotation (θ : real.angle) : V ≃ₗᵢ[ℝ] V := linear_isometry_equiv.of_linear_isometry (o.rotation_aux θ) (real.angle.cos θ • linear_map.id - real.angle.sin θ • ↑(linear_isometry_equiv.to_linear_equiv J)) begin ext x, convert congr_arg (λ t : ℝ, t • x) θ.cos_sq_add_sin_sq using 1, { simp only [o.right_angle_rotation_right_angle_rotation, o.rotation_aux_apply, function.comp_app, id.def, linear_equiv.coe_coe, linear_isometry.coe_to_linear_map, linear_isometry_equiv.coe_to_linear_equiv, map_smul, map_sub, linear_map.coe_comp, linear_map.id_coe, linear_map.smul_apply, linear_map.sub_apply, ← mul_smul, add_smul, smul_add, smul_neg, smul_sub, mul_comm, sq], abel }, { simp }, end begin ext x, convert congr_arg (λ t : ℝ, t • x) θ.cos_sq_add_sin_sq using 1, { simp only [o.right_angle_rotation_right_angle_rotation, o.rotation_aux_apply, function.comp_app, id.def, linear_equiv.coe_coe, linear_isometry.coe_to_linear_map, linear_isometry_equiv.coe_to_linear_equiv, map_add, map_smul, linear_map.coe_comp, linear_map.id_coe, linear_map.smul_apply, linear_map.sub_apply, add_smul, ← mul_smul, mul_comm, smul_add, smul_neg, sq], abel }, { simp }, end lemma rotation_apply (θ : real.angle) (x : V) : o.rotation θ x = real.angle.cos θ • x + real.angle.sin θ • J x := rfl lemma rotation_symm_apply (θ : real.angle) (x : V) : (o.rotation θ).symm x = real.angle.cos θ • x - real.angle.sin θ • J x := rfl attribute [irreducible] rotation lemma rotation_eq_matrix_to_lin (θ : real.angle) {x : V} (hx : x ≠ 0) : (o.rotation θ).to_linear_map = matrix.to_lin (o.basis_right_angle_rotation x hx) (o.basis_right_angle_rotation x hx) !![θ.cos, -θ.sin; θ.sin, θ.cos] := begin apply (o.basis_right_angle_rotation x hx).ext, intros i, fin_cases i, { rw matrix.to_lin_self, simp [rotation_apply, fin.sum_univ_succ] }, { rw matrix.to_lin_self, simp [rotation_apply, fin.sum_univ_succ, add_comm] }, end /-- The determinant of `rotation` (as a linear map) is equal to `1`. -/ @[simp] lemma det_rotation (θ : real.angle) : (o.rotation θ).to_linear_map.det = 1 := begin haveI : nontrivial V := finite_dimensional.nontrivial_of_finrank_eq_succ (fact.out (finrank ℝ V = 2)), obtain ⟨x, hx⟩ : ∃ x, x ≠ (0:V) := exists_ne (0:V), rw o.rotation_eq_matrix_to_lin θ hx, simpa [sq] using θ.cos_sq_add_sin_sq, end /-- The determinant of `rotation` (as a linear equiv) is equal to `1`. -/ @[simp] lemma linear_equiv_det_rotation (θ : real.angle) : (o.rotation θ).to_linear_equiv.det = 1 := units.ext $ o.det_rotation θ /-- The inverse of `rotation` is rotation by the negation of the angle. -/ @[simp] lemma rotation_symm (θ : real.angle) : (o.rotation θ).symm = o.rotation (-θ) := by ext; simp [o.rotation_apply, o.rotation_symm_apply, sub_eq_add_neg] /-- Rotation by 0 is the identity. -/ @[simp] lemma rotation_zero : o.rotation 0 = linear_isometry_equiv.refl ℝ V := by ext; simp [rotation] /-- Rotation by π is negation. -/ @[simp] lemma rotation_pi : o.rotation π = linear_isometry_equiv.neg ℝ := begin ext x, simp [rotation] end /-- Rotation by π is negation. -/ lemma rotation_pi_apply (x : V) : o.rotation π x = -x := by simp /-- Rotation by π / 2 is the "right-angle-rotation" map `J`. -/ lemma rotation_pi_div_two : o.rotation (π / 2 : ℝ) = J := begin ext x, simp [rotation], end /-- Rotating twice is equivalent to rotating by the sum of the angles. -/ @[simp] lemma rotation_rotation (θ₁ θ₂ : real.angle) (x : V) : o.rotation θ₁ (o.rotation θ₂ x) = o.rotation (θ₁ + θ₂) x := begin simp only [o.rotation_apply, ←mul_smul, real.angle.cos_add, real.angle.sin_add, add_smul, sub_smul, linear_isometry_equiv.trans_apply, smul_add, linear_isometry_equiv.map_add, linear_isometry_equiv.map_smul, right_angle_rotation_right_angle_rotation, smul_neg], ring_nf, abel, end /-- Rotating twice is equivalent to rotating by the sum of the angles. -/ @[simp] lemma rotation_trans (θ₁ θ₂ : real.angle) : (o.rotation θ₁).trans (o.rotation θ₂) = o.rotation (θ₂ + θ₁) := linear_isometry_equiv.ext $ λ _, by rw [←rotation_rotation, linear_isometry_equiv.trans_apply] /-- Rotating the first of two vectors by `θ` scales their Kahler form by `cos θ - sin θ * I`. -/ @[simp] lemma kahler_rotation_left (x y : V) (θ : real.angle) : o.kahler (o.rotation θ x) y = conj (θ.exp_map_circle : ℂ) * o.kahler x y := begin simp only [o.rotation_apply, map_add, map_mul, linear_map.map_smulₛₗ, ring_hom.id_apply, linear_map.add_apply, linear_map.smul_apply, real_smul, kahler_right_angle_rotation_left, real.angle.coe_exp_map_circle, is_R_or_C.conj_of_real, conj_I], ring, end /-- Negating a rotation is equivalent to rotation by π plus the angle. -/ lemma neg_rotation (θ : real.angle) (x : V) : -o.rotation θ x = o.rotation (π + θ) x := by rw [←o.rotation_pi_apply, rotation_rotation] /-- Negating a rotation by -π / 2 is equivalent to rotation by π / 2. -/ @[simp] lemma neg_rotation_neg_pi_div_two (x : V) : -o.rotation (-π / 2 : ℝ) x = o.rotation (π / 2 : ℝ) x := by rw [neg_rotation, ←real.angle.coe_add, neg_div, ←sub_eq_add_neg, sub_half] /-- Negating a rotation by π / 2 is equivalent to rotation by -π / 2. -/ lemma neg_rotation_pi_div_two (x : V) : -o.rotation (π / 2 : ℝ) x = o.rotation (-π / 2 : ℝ) x := (neg_eq_iff_eq_neg.mp $ o.neg_rotation_neg_pi_div_two _).symm /-- Rotating the first of two vectors by `θ` scales their Kahler form by `cos (-θ) + sin (-θ) * I`. -/ lemma kahler_rotation_left' (x y : V) (θ : real.angle) : o.kahler (o.rotation θ x) y = (-θ).exp_map_circle * o.kahler x y := by simpa [coe_inv_circle_eq_conj, -kahler_rotation_left] using o.kahler_rotation_left x y θ /-- Rotating the second of two vectors by `θ` scales their Kahler form by `cos θ + sin θ * I`. -/ @[simp] lemma kahler_rotation_right (x y : V) (θ : real.angle) : o.kahler x (o.rotation θ y) = θ.exp_map_circle * o.kahler x y := begin simp only [o.rotation_apply, map_add, linear_map.map_smulₛₗ, ring_hom.id_apply, real_smul, kahler_right_angle_rotation_right, real.angle.coe_exp_map_circle], ring, end /-- Rotating the first vector by `θ` subtracts `θ` from the angle between two vectors. -/ @[simp] lemma oangle_rotation_left {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) (θ : real.angle) : o.oangle (o.rotation θ x) y = o.oangle x y - θ := begin simp only [oangle, o.kahler_rotation_left'], rw [complex.arg_mul_coe_angle, real.angle.arg_exp_map_circle], { abel }, { exact ne_zero_of_mem_circle _ }, { exact o.kahler_ne_zero hx hy }, end /-- Rotating the second vector by `θ` adds `θ` to the angle between two vectors. -/ @[simp] lemma oangle_rotation_right {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) (θ : real.angle) : o.oangle x (o.rotation θ y) = o.oangle x y + θ := begin simp only [oangle, o.kahler_rotation_right], rw [complex.arg_mul_coe_angle, real.angle.arg_exp_map_circle], { abel }, { exact ne_zero_of_mem_circle _ }, { exact o.kahler_ne_zero hx hy }, end /-- The rotation of a vector by `θ` has an angle of `-θ` from that vector. -/ @[simp] lemma oangle_rotation_self_left {x : V} (hx : x ≠ 0) (θ : real.angle) : o.oangle (o.rotation θ x) x = -θ := by simp [hx] /-- A vector has an angle of `θ` from the rotation of that vector by `θ`. -/ @[simp] lemma oangle_rotation_self_right {x : V} (hx : x ≠ 0) (θ : real.angle) : o.oangle x (o.rotation θ x) = θ := by simp [hx] /-- Rotating the first vector by the angle between the two vectors results an an angle of 0. -/ @[simp] lemma oangle_rotation_oangle_left (x y : V) : o.oangle (o.rotation (o.oangle x y) x) y = 0 := begin by_cases hx : x = 0, { simp [hx] }, { by_cases hy : y = 0, { simp [hy] }, { simp [hx, hy] } } end /-- Rotating the first vector by the angle between the two vectors and swapping the vectors results an an angle of 0. -/ @[simp] lemma oangle_rotation_oangle_right (x y : V) : o.oangle y (o.rotation (o.oangle x y) x) = 0 := begin rw [oangle_rev], simp end /-- Rotating both vectors by the same angle does not change the angle between those vectors. -/ @[simp] lemma oangle_rotation (x y : V) (θ : real.angle) : o.oangle (o.rotation θ x) (o.rotation θ y) = o.oangle x y := begin by_cases hx : x = 0; by_cases hy : y = 0; simp [hx, hy] end /-- A rotation of a nonzero vector equals that vector if and only if the angle is zero. -/ @[simp] lemma rotation_eq_self_iff_angle_eq_zero {x : V} (hx : x ≠ 0) (θ : real.angle) : o.rotation θ x = x ↔ θ = 0 := begin split, { intro h, rw eq_comm, simpa [hx, h] using o.oangle_rotation_right hx hx θ }, { intro h, simp [h] } end /-- A nonzero vector equals a rotation of that vector if and only if the angle is zero. -/ @[simp] lemma eq_rotation_self_iff_angle_eq_zero {x : V} (hx : x ≠ 0) (θ : real.angle) : x = o.rotation θ x ↔ θ = 0 := by rw [←o.rotation_eq_self_iff_angle_eq_zero hx, eq_comm] /-- A rotation of a vector equals that vector if and only if the vector or the angle is zero. -/ lemma rotation_eq_self_iff (x : V) (θ : real.angle) : o.rotation θ x = x ↔ x = 0 ∨ θ = 0 := begin by_cases h : x = 0; simp [h] end /-- A vector equals a rotation of that vector if and only if the vector or the angle is zero. -/ lemma eq_rotation_self_iff (x : V) (θ : real.angle) : x = o.rotation θ x ↔ x = 0 ∨ θ = 0 := by rw [←rotation_eq_self_iff, eq_comm] /-- Rotating a vector by the angle to another vector gives the second vector if and only if the norms are equal. -/ @[simp] lemma rotation_oangle_eq_iff_norm_eq (x y : V) : o.rotation (o.oangle x y) x = y ↔ ‖x‖ = ‖y‖ := begin split, { intro h, rw [←h, linear_isometry_equiv.norm_map] }, { intro h, rw o.eq_iff_oangle_eq_zero_of_norm_eq; simp [h] } end /-- The angle between two nonzero vectors is `θ` if and only if the second vector is the first rotated by `θ` and scaled by the ratio of the norms. -/ lemma oangle_eq_iff_eq_norm_div_norm_smul_rotation_of_ne_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) (θ : real.angle) : o.oangle x y = θ ↔ y = (‖y‖ / ‖x‖) • o.rotation θ x := begin have hp := div_pos (norm_pos_iff.2 hy) (norm_pos_iff.2 hx), split, { rintro rfl, rw [←linear_isometry_equiv.map_smul, ←o.oangle_smul_left_of_pos x y hp, eq_comm, rotation_oangle_eq_iff_norm_eq, norm_smul, real.norm_of_nonneg hp.le, div_mul_cancel _ (norm_ne_zero_iff.2 hx)] }, { intro hye, rw [hye, o.oangle_smul_right_of_pos _ _ hp, o.oangle_rotation_self_right hx] } end /-- The angle between two nonzero vectors is `θ` if and only if the second vector is the first rotated by `θ` and scaled by a positive real. -/ lemma oangle_eq_iff_eq_pos_smul_rotation_of_ne_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) (θ : real.angle) : o.oangle x y = θ ↔ ∃ r : ℝ, 0 < r ∧ y = r • o.rotation θ x := begin split, { intro h, rw o.oangle_eq_iff_eq_norm_div_norm_smul_rotation_of_ne_zero hx hy at h, exact ⟨‖y‖ / ‖x‖, div_pos (norm_pos_iff.2 hy) (norm_pos_iff.2 hx), h⟩ }, { rintro ⟨r, hr, rfl⟩, rw [o.oangle_smul_right_of_pos _ _ hr, o.oangle_rotation_self_right hx] } end /-- The angle between two vectors is `θ` if and only if they are nonzero and the second vector is the first rotated by `θ` and scaled by the ratio of the norms, or `θ` and at least one of the vectors are zero. -/ lemma oangle_eq_iff_eq_norm_div_norm_smul_rotation_or_eq_zero {x y : V} (θ : real.angle) : o.oangle x y = θ ↔ (x ≠ 0 ∧ y ≠ 0 ∧ y = (‖y‖ / ‖x‖) • o.rotation θ x) ∨ (θ = 0 ∧ (x = 0 ∨ y = 0)) := begin by_cases hx : x = 0, { simp [hx, eq_comm] }, { by_cases hy : y = 0, { simp [hy, eq_comm] }, { rw o.oangle_eq_iff_eq_norm_div_norm_smul_rotation_of_ne_zero hx hy, simp [hx, hy] } } end /-- The angle between two vectors is `θ` if and only if they are nonzero and the second vector is the first rotated by `θ` and scaled by a positive real, or `θ` and at least one of the vectors are zero. -/ lemma oangle_eq_iff_eq_pos_smul_rotation_or_eq_zero {x y : V} (θ : real.angle) : o.oangle x y = θ ↔ (x ≠ 0 ∧ y ≠ 0 ∧ ∃ r : ℝ, 0 < r ∧ y = r • o.rotation θ x) ∨ (θ = 0 ∧ (x = 0 ∨ y = 0)) := begin by_cases hx : x = 0, { simp [hx, eq_comm] }, { by_cases hy : y = 0, { simp [hy, eq_comm] }, { rw o.oangle_eq_iff_eq_pos_smul_rotation_of_ne_zero hx hy, simp [hx, hy] } } end /-- Any linear isometric equivalence in `V` with positive determinant is `rotation`. -/ lemma exists_linear_isometry_equiv_eq_of_det_pos {f : V ≃ₗᵢ[ℝ] V} (hd : 0 < (f.to_linear_equiv : V →ₗ[ℝ] V).det) : ∃ θ : real.angle, f = o.rotation θ := begin haveI : nontrivial V := finite_dimensional.nontrivial_of_finrank_eq_succ (fact.out (finrank ℝ V = 2)), obtain ⟨x, hx⟩ : ∃ x, x ≠ (0:V) := exists_ne (0:V), use o.oangle x (f x), apply linear_isometry_equiv.to_linear_equiv_injective, apply linear_equiv.to_linear_map_injective, apply (o.basis_right_angle_rotation x hx).ext, intros i, symmetry, fin_cases i, { simp }, have : o.oangle (J x) (f (J x)) = o.oangle x (f x), { simp only [oangle, o.linear_isometry_equiv_comp_right_angle_rotation f hd, o.kahler_comp_right_angle_rotation] }, simp [← this], end lemma rotation_map (θ : real.angle) (f : V ≃ₗᵢ[ℝ] V') (x : V') : (orientation.map (fin 2) f.to_linear_equiv o).rotation θ x = f (o.rotation θ (f.symm x)) := by simp [rotation_apply, o.right_angle_rotation_map] @[simp] protected lemma _root_.complex.rotation (θ : real.angle) (z : ℂ) : complex.orientation.rotation θ z = θ.exp_map_circle * z := begin simp only [rotation_apply, complex.right_angle_rotation, real.angle.coe_exp_map_circle, real_smul], ring end /-- Rotation in an oriented real inner product space of dimension 2 can be evaluated in terms of a complex-number representation of the space. -/ lemma rotation_map_complex (θ : real.angle) (f : V ≃ₗᵢ[ℝ] ℂ) (hf : (orientation.map (fin 2) f.to_linear_equiv o) = complex.orientation) (x : V) : f (o.rotation θ x) = θ.exp_map_circle * f x := begin rw [← complex.rotation, ← hf, o.rotation_map], simp, end /-- Negating the orientation negates the angle in `rotation`. -/ lemma rotation_neg_orientation_eq_neg (θ : real.angle) : (-o).rotation θ = o.rotation (-θ) := linear_isometry_equiv.ext $ by simp [rotation_apply] /-- The inner product between a `π / 2` rotation of a vector and that vector is zero. -/ @[simp] lemma inner_rotation_pi_div_two_left (x : V) : ⟪o.rotation (π / 2 : ℝ) x, x⟫ = 0 := by rw [rotation_pi_div_two, inner_right_angle_rotation_self] /-- The inner product between a vector and a `π / 2` rotation of that vector is zero. -/ @[simp] lemma inner_rotation_pi_div_two_right (x : V) : ⟪x, o.rotation (π / 2 : ℝ) x⟫ = 0 := by rw [real_inner_comm, inner_rotation_pi_div_two_left] /-- The inner product between a multiple of a `π / 2` rotation of a vector and that vector is zero. -/ @[simp] lemma inner_smul_rotation_pi_div_two_left (x : V) (r : ℝ) : ⟪r • o.rotation (π / 2 : ℝ) x, x⟫ = 0 := by rw [inner_smul_left, inner_rotation_pi_div_two_left, mul_zero] /-- The inner product between a vector and a multiple of a `π / 2` rotation of that vector is zero. -/ @[simp] lemma inner_smul_rotation_pi_div_two_right (x : V) (r : ℝ) : ⟪x, r • o.rotation (π / 2 : ℝ) x⟫ = 0 := by rw [real_inner_comm, inner_smul_rotation_pi_div_two_left] /-- The inner product between a `π / 2` rotation of a vector and a multiple of that vector is zero. -/ @[simp] lemma inner_rotation_pi_div_two_left_smul (x : V) (r : ℝ) : ⟪o.rotation (π / 2 : ℝ) x, r • x⟫ = 0 := by rw [inner_smul_right, inner_rotation_pi_div_two_left, mul_zero] /-- The inner product between a multiple of a vector and a `π / 2` rotation of that vector is zero. -/ @[simp] lemma inner_rotation_pi_div_two_right_smul (x : V) (r : ℝ) : ⟪r • x, o.rotation (π / 2 : ℝ) x⟫ = 0 := by rw [real_inner_comm, inner_rotation_pi_div_two_left_smul] /-- The inner product between a multiple of a `π / 2` rotation of a vector and a multiple of that vector is zero. -/ @[simp] lemma inner_smul_rotation_pi_div_two_smul_left (x : V) (r₁ r₂ : ℝ) : ⟪r₁ • o.rotation (π / 2 : ℝ) x, r₂ • x⟫ = 0 := by rw [inner_smul_right, inner_smul_rotation_pi_div_two_left, mul_zero] /-- The inner product between a multiple of a vector and a multiple of a `π / 2` rotation of that vector is zero. -/ @[simp] lemma inner_smul_rotation_pi_div_two_smul_right (x : V) (r₁ r₂ : ℝ) : ⟪r₂ • x, r₁ • o.rotation (π / 2 : ℝ) x⟫ = 0 := by rw [real_inner_comm, inner_smul_rotation_pi_div_two_smul_left] /-- The inner product between two vectors is zero if and only if the first vector is zero or the second is a multiple of a `π / 2` rotation of that vector. -/ lemma inner_eq_zero_iff_eq_zero_or_eq_smul_rotation_pi_div_two {x y : V} : ⟪x, y⟫ = 0 ↔ (x = 0 ∨ ∃ r : ℝ, r • o.rotation (π / 2 : ℝ) x = y) := begin rw ←o.eq_zero_or_oangle_eq_iff_inner_eq_zero, refine ⟨λ h, _, λ h, _⟩, { rcases h with rfl | rfl | h | h, { exact or.inl rfl }, { exact or.inr ⟨0, zero_smul _ _⟩ }, { obtain ⟨r, hr, rfl⟩ := (o.oangle_eq_iff_eq_pos_smul_rotation_of_ne_zero (o.left_ne_zero_of_oangle_eq_pi_div_two h) (o.right_ne_zero_of_oangle_eq_pi_div_two h) _).1 h, exact or.inr ⟨r, rfl⟩ }, { obtain ⟨r, hr, rfl⟩ := (o.oangle_eq_iff_eq_pos_smul_rotation_of_ne_zero (o.left_ne_zero_of_oangle_eq_neg_pi_div_two h) (o.right_ne_zero_of_oangle_eq_neg_pi_div_two h) _).1 h, refine or.inr ⟨-r, _⟩, rw [neg_smul, ←smul_neg, o.neg_rotation_pi_div_two] } }, { rcases h with rfl | ⟨r, rfl⟩, { exact or.inl rfl }, { by_cases hx : x = 0, { exact or.inl hx }, rcases lt_trichotomy r 0 with hr | rfl | hr, { refine or.inr (or.inr (or.inr _)), rw [o.oangle_smul_right_of_neg _ _ hr, o.neg_rotation_pi_div_two, o.oangle_rotation_self_right hx] }, { exact or.inr (or.inl (zero_smul _ _)) }, { refine or.inr (or.inr (or.inl _)), rw [o.oangle_smul_right_of_pos _ _ hr, o.oangle_rotation_self_right hx] } } } end end orientation
000cf08d89e66dd317aa3f71cc3377ca8d9c3fd1
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/topology/sheaves/presheaf_of_functions.lean
55dfb85181dadaabca68c8dae2a83df23f0378d7
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
3,000
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 topology.sheaves.presheaf import topology.category.TopCommRing import topology.algebra.continuous_functions universes v u open category_theory open topological_space open opposite namespace Top variables (X Y : Top.{v}) /-- The presheaf of continuous functions on `X` with values in fixed target topological space `T`. -/ def presheaf_to_Top (T : Top.{v}) : X.presheaf (Type v) := (opens.to_Top X).op ⋙ (yoneda.obj T) /-- The (bundled) commutative ring of continuous functions from a topological space to a topological commutative ring, with pointwise multiplication. -/ -- TODO upgrade the result to TopCommRing? def continuous_functions (X : Top.{v}ᵒᵖ) (R : TopCommRing.{v}) : CommRing.{v} := CommRing.of (unop X ⟶ (forget₂ TopCommRing Top).obj R) namespace continuous_functions /-- Pulling back functions into a topological ring along a continuous map is a ring homomorphism. -/ def pullback {X Y : Topᵒᵖ} (f : X ⟶ Y) (R : TopCommRing) : continuous_functions X R ⟶ continuous_functions Y R := { to_fun := λ g, f.unop ≫ g, map_one' := rfl, map_zero' := rfl, map_add' := by tidy, map_mul' := by tidy } /-- A homomorphism of topological rings can be postcomposed with functions from a source space `X`; this is a ring homomorphism (with respect to the pointwise ring operations on functions). -/ def map (X : Top.{u}ᵒᵖ) {R S : TopCommRing.{u}} (φ : R ⟶ S) : continuous_functions X R ⟶ continuous_functions X S := { to_fun := λ g, g ≫ ((forget₂ TopCommRing Top).map φ), map_one' := by ext; exact φ.1.map_one, map_zero' := by ext; exact φ.1.map_zero, map_add' := by intros; ext; apply φ.1.map_add, map_mul' := by intros; ext; apply φ.1.map_mul } end continuous_functions /-- An upgraded version of the Yoneda embedding, observing that the continuous maps from `X : Top` to `R : TopCommRing` form a commutative ring, functorial in both `X` and `R`. -/ def CommRing_yoneda : TopCommRing.{u} ⥤ (Top.{u}ᵒᵖ ⥤ CommRing.{u}) := { obj := λ R, { obj := λ X, continuous_functions X R, map := λ X Y f, continuous_functions.pullback f R }, map := λ R S φ, { app := λ X, continuous_functions.map X φ } } /-- The presheaf (of commutative rings), consisting of functions on an open set `U ⊆ X` with values in some topological commutative ring `T`. -/ def presheaf_to_TopCommRing (T : TopCommRing.{v}) : X.presheaf CommRing.{v} := (opens.to_Top X).op ⋙ (CommRing_yoneda.obj T) /-- The presheaf (of commutative rings) of real valued functions. -/ noncomputable def presheaf_ℝ (Y : Top) : Y.presheaf CommRing := presheaf_to_TopCommRing Y (TopCommRing.of ℝ) /-- The presheaf (of commutative rings) of complex valued functions. -/ noncomputable def presheaf_ℂ (Y : Top) : Y.presheaf CommRing := presheaf_to_TopCommRing Y (TopCommRing.of ℂ) end Top
5f2346317bd4b3f81578e564a5f8175ec0d5163f
f083c4ed5d443659f3ed9b43b1ca5bb037ddeb58
/category/traversable/instances.lean
690dde012d0362518bba9f8043924a516f5af8db
[ "Apache-2.0" ]
permissive
semorrison/mathlib
1be6f11086e0d24180fec4b9696d3ec58b439d10
20b4143976dad48e664c4847b75a85237dca0a89
refs/heads/master
1,583,799,212,170
1,535,634,130,000
1,535,730,505,000
129,076,205
0
0
Apache-2.0
1,551,697,998,000
1,523,442,265,000
Lean
UTF-8
Lean
false
false
5,263
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon Instances of `traversable` for types from the core library -/ import category.traversable.basic category.basic category.functor category.applicative universes u v open function instance : traversable id := ⟨λ _ _ _ _, id⟩ instance : is_lawful_traversable id := by refine {..}; intros; refl section option open function functor section inst variables {F : Type u → Type v} [applicative F] instance : traversable option := ⟨@option.traverse⟩ end inst variables {F G : Type u → Type u} variables [applicative F] [applicative G] variables [is_lawful_applicative F] [is_lawful_applicative G] lemma option.id_traverse {α} (x : option α) : option.traverse id.mk x = x := by cases x; refl lemma option.comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : option α) : option.traverse (comp.mk ∘ (<$>) f ∘ g) x = comp.mk (option.traverse f <$> option.traverse g x) := by cases x; simp! with functor_norm; refl lemma option.traverse_eq_map_id {α β} (f : α → β) (x : option α) : traverse (id.mk ∘ f) x = id.mk (f <$> x) := by cases x; refl variable (η : applicative_transformation F G) lemma option.naturality {α β} (f : α → F β) (x : option α) : η (option.traverse f x) = option.traverse (@η _ ∘ f) x := by cases x with x; simp! [*] with functor_norm end option instance : is_lawful_traversable option := { id_traverse := @option.id_traverse, comp_traverse := @option.comp_traverse, traverse_eq_map_id := @option.traverse_eq_map_id, naturality := @option.naturality } section list variables {F G : Type u → Type u} variables [applicative F] [applicative G] variables [is_lawful_applicative F] [is_lawful_applicative G] open applicative functor open list (cons) protected lemma list.id_traverse {α} (xs : list α) : list.traverse id.mk xs = xs := by induction xs; simp! * with functor_norm; refl protected lemma list.comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : list α) : list.traverse (comp.mk ∘ (<$>) f ∘ g) x = comp.mk (list.traverse f <$> list.traverse g x) := by induction x; simp! * with functor_norm; refl protected lemma list.traverse_eq_map_id {α β} (f : α → β) (x : list α) : list.traverse (id.mk ∘ f) x = id.mk (f <$> x) := by induction x; simp! * with functor_norm; refl variable (η : applicative_transformation F G) protected lemma list.naturality {α β} (f : α → F β) (x : list α) : η (list.traverse f x) = list.traverse (@η _ ∘ f) x := by induction x; simp! * with functor_norm open nat instance : traversable list := ⟨@list.traverse⟩ instance : is_lawful_traversable list := { id_traverse := @list.id_traverse, comp_traverse := @list.comp_traverse, traverse_eq_map_id := @list.traverse_eq_map_id, naturality := @list.naturality } lemma traverse_append {α β : Type*} (g : α → F β) (xs ys : list α) : traverse g (xs ++ ys) = (++) <$> traverse g xs <*> traverse g ys := begin simp! [traverse], induction xs, { have : append (@list.nil β) = id, { funext, simp }, simp! [this] }, { simp! [traverse,xs_ih] with functor_norm, refl } end end list namespace sum section traverse variables {σ : Type u} variables {F G : Type u → Type u} variables [applicative F] [applicative G] open applicative functor open list (cons) protected def traverse {α β} (f : α → F β) : σ ⊕ α → F (σ ⊕ β) | (sum.inl x) := pure (sum.inl x) | (sum.inr x) := sum.inr <$> f x variables [is_lawful_applicative F] [is_lawful_applicative G] protected lemma id_traverse {σ α} (x : σ ⊕ α) : sum.traverse id.mk x = x := by cases x; refl protected lemma comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : σ ⊕ α) : sum.traverse (comp.mk ∘ (<$>) f ∘ g) x = comp.mk (sum.traverse f <$> sum.traverse g x) := by cases x; simp! [sum.traverse,map_id] with functor_norm; refl protected lemma traverse_eq_map_id {α β} (f : α → β) (x : σ ⊕ α) : sum.traverse (id.mk ∘ f) x = id.mk (f <$> x) := by induction x; simp! * with functor_norm; refl protected lemma map_traverse {α β γ} (g : α → G β) (f : β → γ) (x : σ ⊕ α) : (<$>) f <$> sum.traverse g x = sum.traverse ((<$>) f ∘ g) x := by cases x; simp [(<$>), sum.mapr, sum.traverse, id_map] with functor_norm; congr protected lemma traverse_map {α β γ : Type u} (g : α → β) (f : β → G γ) (x : σ ⊕ α) : sum.traverse f (g <$> x) = sum.traverse (f ∘ g) x := by cases x; simp [(<$>), sum.mapr, sum.traverse, id_map] with functor_norm variable (η : applicative_transformation F G) protected lemma naturality {α β} (f : α → F β) (x : σ ⊕ α) : η (sum.traverse f x) = sum.traverse (@η _ ∘ f) x := by cases x; simp! [sum.traverse] with functor_norm end traverse instance {σ : Type u} : traversable.{u} (sum σ) := ⟨@sum.traverse _⟩ instance {σ : Type u} : is_lawful_traversable.{u} (sum σ) := { id_traverse := @sum.id_traverse σ, comp_traverse := @sum.comp_traverse σ, traverse_eq_map_id := @sum.traverse_eq_map_id σ, naturality := @sum.naturality σ } end sum
ce7bb82d58d35bb258109e6a97bf0a200bf8cf05
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/measure_theory/constructions/borel_space.lean
781446f33ff8a810f97ba4868abf3bdbd480dcba
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
68,529
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Yury Kudryashov -/ import measure_theory.function.ae_measurable_sequence import analysis.complex.basic import analysis.normed_space.finite_dimension import topology.G_delta import measure_theory.group.arithmetic import topology.semicontinuous import topology.instances.ereal /-! # Borel (measurable) space ## Main definitions * `borel α` : the least `σ`-algebra that contains all open sets; * `class borel_space` : a space with `topological_space` and `measurable_space` structures such that `‹measurable_space α› = borel α`; * `class opens_measurable_space` : a space with `topological_space` and `measurable_space` structures such that all open sets are measurable; equivalently, `borel α ≤ ‹measurable_space α›`. * `borel_space` instances on `empty`, `unit`, `bool`, `nat`, `int`, `rat`; * `measurable` and `borel_space` instances on `ℝ`, `ℝ≥0`, `ℝ≥0∞`. ## Main statements * `is_open.measurable_set`, `is_closed.measurable_set`: open and closed sets are measurable; * `continuous.measurable` : a continuous function is measurable; * `continuous.measurable2` : if `f : α → β` and `g : α → γ` are measurable and `op : β × γ → δ` is continuous, then `λ x, op (f x, g y)` is measurable; * `measurable.add` etc : dot notation for arithmetic operations on `measurable` predicates, and similarly for `dist` and `edist`; * `ae_measurable.add` : similar dot notation for almost everywhere measurable functions; * `measurable.ennreal*` : special cases for arithmetic operations on `ℝ≥0∞`. -/ noncomputable theory open classical set filter measure_theory open_locale classical big_operators topological_space nnreal ennreal interval universes u v w x y variables {α β γ γ₂ δ : Type*} {ι : Sort y} {s t u : set α} open measurable_space topological_space /-- `measurable_space` structure generated by `topological_space`. -/ def borel (α : Type u) [topological_space α] : measurable_space α := generate_from {s : set α | is_open s} lemma borel_eq_top_of_discrete [topological_space α] [discrete_topology α] : borel α = ⊤ := top_le_iff.1 $ λ s hs, generate_measurable.basic s (is_open_discrete s) lemma borel_eq_top_of_encodable [topological_space α] [t1_space α] [encodable α] : borel α = ⊤ := begin refine (top_le_iff.1 $ λ s hs, bUnion_of_singleton s ▸ _), apply measurable_set.bUnion s.countable_encodable, intros x hx, apply measurable_set.of_compl, apply generate_measurable.basic, exact is_closed_singleton.is_open_compl end lemma borel_eq_generate_from_of_subbasis {s : set (set α)} [t : topological_space α] [second_countable_topology α] (hs : t = generate_from s) : borel α = generate_from s := le_antisymm (generate_from_le $ assume u (hu : t.is_open u), begin rw [hs] at hu, induction hu, case generate_open.basic : u hu { exact generate_measurable.basic u hu }, case generate_open.univ { exact @measurable_set.univ α (generate_from s) }, case generate_open.inter : s₁ s₂ _ _ hs₁ hs₂ { exact @measurable_set.inter α (generate_from s) _ _ hs₁ hs₂ }, case generate_open.sUnion : f hf ih { rcases is_open_sUnion_countable f (by rwa hs) with ⟨v, hv, vf, vu⟩, rw ← vu, exact @measurable_set.sUnion α (generate_from s) _ hv (λ x xv, ih _ (vf xv)) } end) (generate_from_le $ assume u hu, generate_measurable.basic _ $ show t.is_open u, by rw [hs]; exact generate_open.basic _ hu) lemma topological_space.is_topological_basis.borel_eq_generate_from [topological_space α] [second_countable_topology α] {s : set (set α)} (hs : is_topological_basis s) : borel α = generate_from s := borel_eq_generate_from_of_subbasis hs.eq_generate_from lemma is_pi_system_is_open [topological_space α] : is_pi_system (is_open : set α → Prop) := λ s t hs ht hst, is_open.inter hs ht lemma borel_eq_generate_from_is_closed [topological_space α] : borel α = generate_from {s | is_closed s} := le_antisymm (generate_from_le $ λ t ht, @measurable_set.of_compl α _ (generate_from {s | is_closed s}) (generate_measurable.basic _ $ is_closed_compl_iff.2 ht)) (generate_from_le $ λ t ht, @measurable_set.of_compl α _ (borel α) (generate_measurable.basic _ $ is_open_compl_iff.2 ht)) section order_topology variable (α) variables [topological_space α] [second_countable_topology α] [linear_order α] [order_topology α] lemma is_pi_system_Ioo_mem {α : Type*} [linear_order α] (s t : set α) : is_pi_system {S | ∃ (l ∈ s) (u ∈ t), l < u ∧ Ioo l u = S} := begin rintro _ _ ⟨l₁, hls₁, u₁, hut₁, hlu₁, rfl⟩ ⟨l₂, hls₂, u₂, hut₂, hlu₂, rfl⟩ ⟨x, ⟨hlx₁ : l₁ < x, hxu₁ : x < u₁⟩, ⟨hlx₂ : l₂ < x, hxu₂ : x < u₂⟩⟩, refine ⟨l₁ ⊔ l₂, sup_ind l₁ l₂ hls₁ hls₂, u₁ ⊓ u₂, inf_ind u₁ u₂ hut₁ hut₂, _, Ioo_inter_Ioo.symm⟩, simp [hlx₂.trans hxu₁, hlx₁.trans hxu₂, *] end lemma is_pi_system_Ioo {α β : Type*} [linear_order β] (f : α → β) : @is_pi_system β (⋃ l u (h : f l < f u), {Ioo (f l) (f u)}) := begin convert is_pi_system_Ioo_mem (range f) (range f), ext s, simp [@eq_comm _ _ s] end lemma borel_eq_generate_Iio : borel α = generate_from (range Iio) := begin refine le_antisymm _ (generate_from_le _), { rw borel_eq_generate_from_of_subbasis (@order_topology.topology_eq_generate_intervals α _ _ _), letI : measurable_space α := measurable_space.generate_from (range Iio), have H : ∀ a : α, measurable_set (Iio a) := λ a, generate_measurable.basic _ ⟨_, rfl⟩, refine generate_from_le _, rintro _ ⟨a, rfl | rfl⟩; [skip, apply H], by_cases h : ∃ a', ∀ b, a < b ↔ a' ≤ b, { rcases h with ⟨a', ha'⟩, rw (_ : Ioi a = (Iio a')ᶜ), { exact (H _).compl }, simp [set.ext_iff, ha'] }, { rcases is_open_Union_countable (λ a' : {a' : α // a < a'}, {b | a'.1 < b}) (λ a', is_open_lt' _) with ⟨v, ⟨hv⟩, vu⟩, simp [set.ext_iff] at vu, have : Ioi a = ⋃ x : v, (Iio x.1.1)ᶜ, { simp [set.ext_iff], refine λ x, ⟨λ ax, _, λ ⟨a', ⟨h, av⟩, ax⟩, lt_of_lt_of_le h ax⟩, rcases (vu x).2 _ with ⟨a', h₁, h₂⟩, { exact ⟨a', h₁, le_of_lt h₂⟩ }, refine not_imp_comm.1 (λ h, _) h, exact ⟨x, λ b, ⟨λ ab, le_of_not_lt (λ h', h ⟨b, ab, h'⟩), lt_of_lt_of_le ax⟩⟩ }, rw this, resetI, apply measurable_set.Union, exact λ _, (H _).compl } }, { rw forall_range_iff, intro a, exact generate_measurable.basic _ is_open_Iio } end lemma borel_eq_generate_Ioi : borel α = generate_from (range Ioi) := @borel_eq_generate_Iio (order_dual α) _ (by apply_instance : second_countable_topology α) _ _ end order_topology lemma borel_comap {f : α → β} {t : topological_space β} : @borel α (t.induced f) = (@borel β t).comap f := comap_generate_from.symm lemma continuous.borel_measurable [topological_space α] [topological_space β] {f : α → β} (hf : continuous f) : @measurable α β (borel α) (borel β) f := measurable.of_le_map $ generate_from_le $ λ s hs, generate_measurable.basic (f ⁻¹' s) (hs.preimage hf) /-- A space with `measurable_space` and `topological_space` structures such that all open sets are measurable. -/ class opens_measurable_space (α : Type*) [topological_space α] [h : measurable_space α] : Prop := (borel_le : borel α ≤ h) /-- A space with `measurable_space` and `topological_space` structures such that the `σ`-algebra of measurable sets is exactly the `σ`-algebra generated by open sets. -/ class borel_space (α : Type*) [topological_space α] [measurable_space α] : Prop := (measurable_eq : ‹measurable_space α› = borel α) /-- In a `borel_space` all open sets are measurable. -/ @[priority 100] instance borel_space.opens_measurable {α : Type*} [topological_space α] [measurable_space α] [borel_space α] : opens_measurable_space α := ⟨ge_of_eq $ borel_space.measurable_eq⟩ instance subtype.borel_space {α : Type*} [topological_space α] [measurable_space α] [hα : borel_space α] (s : set α) : borel_space s := ⟨by { rw [hα.1, subtype.measurable_space, ← borel_comap], refl }⟩ instance subtype.opens_measurable_space {α : Type*} [topological_space α] [measurable_space α] [h : opens_measurable_space α] (s : set α) : opens_measurable_space s := ⟨by { rw [borel_comap], exact comap_mono h.1 }⟩ theorem _root_.measurable_set.induction_on_open [topological_space α] [measurable_space α] [borel_space α] {C : set α → Prop} (h_open : ∀ U, is_open U → C U) (h_compl : ∀ t, measurable_set t → C t → C tᶜ) (h_union : ∀ f : ℕ → set α, pairwise (disjoint on f) → (∀ i, measurable_set (f i)) → (∀ i, C (f i)) → C (⋃ i, f i)) : ∀ ⦃t⦄, measurable_set t → C t := measurable_space.induction_on_inter borel_space.measurable_eq is_pi_system_is_open (h_open _ is_open_empty) h_open h_compl h_union section variables [topological_space α] [measurable_space α] [opens_measurable_space α] [topological_space β] [measurable_space β] [opens_measurable_space β] [topological_space γ] [measurable_space γ] [borel_space γ] [topological_space γ₂] [measurable_space γ₂] [borel_space γ₂] [measurable_space δ] lemma is_open.measurable_set (h : is_open s) : measurable_set s := opens_measurable_space.borel_le _ $ generate_measurable.basic _ h @[measurability] lemma measurable_set_interior : measurable_set (interior s) := is_open_interior.measurable_set lemma is_Gδ.measurable_set (h : is_Gδ s) : measurable_set s := begin rcases h with ⟨S, hSo, hSc, rfl⟩, exact measurable_set.sInter hSc (λ t ht, (hSo t ht).measurable_set) end lemma measurable_set_of_continuous_at {β} [emetric_space β] (f : α → β) : measurable_set {x | continuous_at f x} := (is_Gδ_set_of_continuous_at f).measurable_set lemma is_closed.measurable_set (h : is_closed s) : measurable_set s := h.is_open_compl.measurable_set.of_compl lemma is_compact.measurable_set [t2_space α] (h : is_compact s) : measurable_set s := h.is_closed.measurable_set @[measurability] lemma measurable_set_closure : measurable_set (closure s) := is_closed_closure.measurable_set lemma measurable_of_is_open {f : δ → γ} (hf : ∀ s, is_open s → measurable_set (f ⁻¹' s)) : measurable f := by { rw [‹borel_space γ›.measurable_eq], exact measurable_generate_from hf } lemma measurable_of_is_closed {f : δ → γ} (hf : ∀ s, is_closed s → measurable_set (f ⁻¹' s)) : measurable f := begin apply measurable_of_is_open, intros s hs, rw [← measurable_set.compl_iff, ← preimage_compl], apply hf, rw [is_closed_compl_iff], exact hs end lemma measurable_of_is_closed' {f : δ → γ} (hf : ∀ s, is_closed s → s.nonempty → s ≠ univ → measurable_set (f ⁻¹' s)) : measurable f := begin apply measurable_of_is_closed, intros s hs, cases eq_empty_or_nonempty s with h1 h1, { simp [h1] }, by_cases h2 : s = univ, { simp [h2] }, exact hf s hs h1 h2 end instance nhds_is_measurably_generated (a : α) : (𝓝 a).is_measurably_generated := begin rw [nhds, infi_subtype'], refine @filter.infi_is_measurably_generated _ _ _ _ (λ i, _), exact i.2.2.measurable_set.principal_is_measurably_generated end /-- If `s` is a measurable set, then `𝓝[s] a` is a measurably generated filter for each `a`. This cannot be an `instance` because it depends on a non-instance `hs : measurable_set s`. -/ lemma measurable_set.nhds_within_is_measurably_generated {s : set α} (hs : measurable_set s) (a : α) : (𝓝[s] a).is_measurably_generated := by haveI := hs.principal_is_measurably_generated; exact filter.inf_is_measurably_generated _ _ @[priority 100] -- see Note [lower instance priority] instance opens_measurable_space.to_measurable_singleton_class [t1_space α] : measurable_singleton_class α := ⟨λ x, is_closed_singleton.measurable_set⟩ instance pi.opens_measurable_space {ι : Type*} {π : ι → Type*} [fintype ι] [t' : Π i, topological_space (π i)] [Π i, measurable_space (π i)] [∀ i, second_countable_topology (π i)] [∀ i, opens_measurable_space (π i)] : opens_measurable_space (Π i, π i) := begin constructor, have : Pi.topological_space = generate_from {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ countable_basis (π a)) ∧ t = pi ↑i s}, { rw [funext (λ a, @eq_generate_from_countable_basis (π a) _ _), pi_generate_from_eq] }, rw [borel_eq_generate_from_of_subbasis this], apply generate_from_le, rintros _ ⟨s, i, hi, rfl⟩, refine measurable_set.pi i.countable_to_set (λ a ha, is_open.measurable_set _), rw [eq_generate_from_countable_basis (π a)], exact generate_open.basic _ (hi a ha) end instance prod.opens_measurable_space [second_countable_topology α] [second_countable_topology β] : opens_measurable_space (α × β) := begin constructor, rw [((is_basis_countable_basis α).prod (is_basis_countable_basis β)).borel_eq_generate_from], apply generate_from_le, rintros _ ⟨u, v, hu, hv, rfl⟩, exact (is_open_of_mem_countable_basis hu).measurable_set.prod (is_open_of_mem_countable_basis hv).measurable_set end variables {α' : Type*} [topological_space α'] [measurable_space α'] lemma measure_interior_of_null_bdry {μ : measure α'} {s : set α'} (h_nullbdry : μ (frontier s) = 0) : μ (interior s) = μ s := measure_eq_measure_smaller_of_between_null_diff interior_subset subset_closure h_nullbdry lemma measure_closure_of_null_bdry {μ : measure α'} {s : set α'} (h_nullbdry : μ (frontier s) = 0) : μ (closure s) = μ s := (measure_eq_measure_larger_of_between_null_diff interior_subset subset_closure h_nullbdry).symm section preorder variables [preorder α] [order_closed_topology α] {a b x : α} @[simp, measurability] lemma measurable_set_Ici : measurable_set (Ici a) := is_closed_Ici.measurable_set @[simp, measurability] lemma measurable_set_Iic : measurable_set (Iic a) := is_closed_Iic.measurable_set @[simp, measurability] lemma measurable_set_Icc : measurable_set (Icc a b) := is_closed_Icc.measurable_set instance nhds_within_Ici_is_measurably_generated : (𝓝[Ici b] a).is_measurably_generated := measurable_set_Ici.nhds_within_is_measurably_generated _ instance nhds_within_Iic_is_measurably_generated : (𝓝[Iic b] a).is_measurably_generated := measurable_set_Iic.nhds_within_is_measurably_generated _ instance nhds_within_Icc_is_measurably_generated : is_measurably_generated (𝓝[Icc a b] x) := by { rw [← Ici_inter_Iic, nhds_within_inter], apply_instance } instance at_top_is_measurably_generated : (filter.at_top : filter α).is_measurably_generated := @filter.infi_is_measurably_generated _ _ _ _ $ λ a, (measurable_set_Ici : measurable_set (Ici a)).principal_is_measurably_generated instance at_bot_is_measurably_generated : (filter.at_bot : filter α).is_measurably_generated := @filter.infi_is_measurably_generated _ _ _ _ $ λ a, (measurable_set_Iic : measurable_set (Iic a)).principal_is_measurably_generated end preorder section partial_order variables [partial_order α] [order_closed_topology α] [second_countable_topology α] {a b : α} @[measurability] lemma measurable_set_le' : measurable_set {p : α × α | p.1 ≤ p.2} := order_closed_topology.is_closed_le'.measurable_set @[measurability] lemma measurable_set_le {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable_set {a | f a ≤ g a} := hf.prod_mk hg measurable_set_le' end partial_order section linear_order variables [linear_order α] [order_closed_topology α] {a b x : α} @[simp, measurability] lemma measurable_set_Iio : measurable_set (Iio a) := is_open_Iio.measurable_set @[simp, measurability] lemma measurable_set_Ioi : measurable_set (Ioi a) := is_open_Ioi.measurable_set @[simp, measurability] lemma measurable_set_Ioo : measurable_set (Ioo a b) := is_open_Ioo.measurable_set @[simp, measurability] lemma measurable_set_Ioc : measurable_set (Ioc a b) := measurable_set_Ioi.inter measurable_set_Iic @[simp, measurability] lemma measurable_set_Ico : measurable_set (Ico a b) := measurable_set_Ici.inter measurable_set_Iio instance nhds_within_Ioi_is_measurably_generated : (𝓝[Ioi b] a).is_measurably_generated := measurable_set_Ioi.nhds_within_is_measurably_generated _ instance nhds_within_Iio_is_measurably_generated : (𝓝[Iio b] a).is_measurably_generated := measurable_set_Iio.nhds_within_is_measurably_generated _ instance nhds_within_interval_is_measurably_generated : is_measurably_generated (𝓝[[a, b]] x) := nhds_within_Icc_is_measurably_generated @[measurability] lemma measurable_set_lt' [second_countable_topology α] : measurable_set {p : α × α | p.1 < p.2} := (is_open_lt continuous_fst continuous_snd).measurable_set @[measurability] lemma measurable_set_lt [second_countable_topology α] {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable_set {a | f a < g a} := hf.prod_mk hg measurable_set_lt' lemma set.ord_connected.measurable_set (h : ord_connected s) : measurable_set s := begin let u := ⋃ (x ∈ s) (y ∈ s), Ioo x y, have huopen : is_open u := is_open_bUnion (λ x hx, is_open_bUnion (λ y hy, is_open_Ioo)), have humeas : measurable_set u := huopen.measurable_set, have hfinite : (s \ u).finite, { refine set.finite_of_forall_between_eq_endpoints (s \ u) (λ x hx y hy z hz hxy hyz, _), by_contra h, push_neg at h, exact hy.2 (mem_bUnion_iff.mpr ⟨x, hx.1, mem_bUnion_iff.mpr ⟨z, hz.1, lt_of_le_of_ne hxy h.1, lt_of_le_of_ne hyz h.2⟩⟩) }, have : u ⊆ s := bUnion_subset (λ x hx, bUnion_subset (λ y hy, Ioo_subset_Icc_self.trans (h.out hx hy))), rw ← union_diff_cancel this, exact humeas.union hfinite.measurable_set end lemma is_preconnected.measurable_set (h : is_preconnected s) : measurable_set s := h.ord_connected.measurable_set end linear_order section linear_order variables [linear_order α] [order_closed_topology α] @[measurability] lemma measurable_set_interval {a b : α} : measurable_set (interval a b) := measurable_set_Icc variables [second_countable_topology α] @[measurability] lemma measurable.max {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable (λ a, max (f a) (g a)) := by simpa only [max_def] using hf.piecewise (measurable_set_le hg hf) hg @[measurability] lemma ae_measurable.max {f g : δ → α} {μ : measure δ} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, max (f a) (g a)) μ := ⟨λ a, max (hf.mk f a) (hg.mk g a), hf.measurable_mk.max hg.measurable_mk, eventually_eq.comp₂ hf.ae_eq_mk _ hg.ae_eq_mk⟩ @[measurability] lemma measurable.min {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable (λ a, min (f a) (g a)) := by simpa only [min_def] using hf.piecewise (measurable_set_le hf hg) hg @[measurability] lemma ae_measurable.min {f g : δ → α} {μ : measure δ} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, min (f a) (g a)) μ := ⟨λ a, min (hf.mk f a) (hg.mk g a), hf.measurable_mk.min hg.measurable_mk, eventually_eq.comp₂ hf.ae_eq_mk _ hg.ae_eq_mk⟩ end linear_order /-- A continuous function from an `opens_measurable_space` to a `borel_space` is measurable. -/ lemma continuous.measurable {f : α → γ} (hf : continuous f) : measurable f := hf.borel_measurable.mono opens_measurable_space.borel_le (le_of_eq $ borel_space.measurable_eq) /-- A continuous function from an `opens_measurable_space` to a `borel_space` is ae-measurable. -/ lemma continuous.ae_measurable {f : α → γ} (h : continuous f) (μ : measure α) : ae_measurable f μ := h.measurable.ae_measurable lemma closed_embedding.measurable {f : α → γ} (hf : closed_embedding f) : measurable f := hf.continuous.measurable @[priority 100, to_additive] instance has_continuous_mul.has_measurable_mul [has_mul γ] [has_continuous_mul γ] : has_measurable_mul γ := { measurable_const_mul := λ c, (continuous_const.mul continuous_id).measurable, measurable_mul_const := λ c, (continuous_id.mul continuous_const).measurable } @[priority 100] instance has_continuous_sub.has_measurable_sub [has_sub γ] [has_continuous_sub γ] : has_measurable_sub γ := { measurable_const_sub := λ c, (continuous_const.sub continuous_id).measurable, measurable_sub_const := λ c, (continuous_id.sub continuous_const).measurable } @[priority 100, to_additive] instance topological_group.has_measurable_inv [group γ] [topological_group γ] : has_measurable_inv γ := ⟨continuous_inv.measurable⟩ @[priority 100] instance has_continuous_smul.has_measurable_smul {M α} [topological_space M] [topological_space α] [measurable_space M] [measurable_space α] [opens_measurable_space M] [borel_space α] [has_scalar M α] [has_continuous_smul M α] : has_measurable_smul M α := ⟨λ c, (continuous_const.smul continuous_id).measurable, λ y, (continuous_id.smul continuous_const).measurable⟩ section homeomorph /-- A homeomorphism between two Borel spaces is a measurable equivalence.-/ def homeomorph.to_measurable_equiv (h : γ ≃ₜ γ₂) : γ ≃ᵐ γ₂ := { measurable_to_fun := h.continuous_to_fun.measurable, measurable_inv_fun := h.continuous_inv_fun.measurable, .. h } @[simp] lemma homeomorph.to_measurable_equiv_coe (h : γ ≃ₜ γ₂) : (h.to_measurable_equiv : γ → γ₂) = h := rfl @[simp] lemma homeomorph.to_measurable_equiv_symm_coe (h : γ ≃ₜ γ₂) : (h.to_measurable_equiv.symm : γ₂ → γ) = h.symm := rfl @[measurability] lemma homeomorph.measurable (h : α ≃ₜ γ) : measurable h := h.continuous.measurable end homeomorph lemma measurable_of_continuous_on_compl_singleton [t1_space α] {f : α → γ} (a : α) (hf : continuous_on f {a}ᶜ) : measurable f := measurable_of_measurable_on_compl_singleton a (continuous_on_iff_continuous_restrict.1 hf).measurable lemma continuous.measurable2 [second_countable_topology α] [second_countable_topology β] {f : δ → α} {g : δ → β} {c : α → β → γ} (h : continuous (λ p : α × β, c p.1 p.2)) (hf : measurable f) (hg : measurable g) : measurable (λ a, c (f a) (g a)) := h.measurable.comp (hf.prod_mk hg) lemma continuous.ae_measurable2 [second_countable_topology α] [second_countable_topology β] {f : δ → α} {g : δ → β} {c : α → β → γ} {μ : measure δ} (h : continuous (λ p : α × β, c p.1 p.2)) (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, c (f a) (g a)) μ := h.measurable.comp_ae_measurable (hf.prod_mk hg) @[priority 100] instance has_continuous_inv₀.has_measurable_inv [group_with_zero γ] [t1_space γ] [has_continuous_inv₀ γ] : has_measurable_inv γ := ⟨measurable_of_continuous_on_compl_singleton 0 continuous_on_inv₀⟩ @[priority 100, to_additive] instance has_continuous_mul.has_measurable_mul₂ [second_countable_topology γ] [has_mul γ] [has_continuous_mul γ] : has_measurable_mul₂ γ := ⟨continuous_mul.measurable⟩ @[priority 100] instance has_continuous_sub.has_measurable_sub₂ [second_countable_topology γ] [has_sub γ] [has_continuous_sub γ] : has_measurable_sub₂ γ := ⟨continuous_sub.measurable⟩ @[priority 100] instance has_continuous_smul.has_measurable_smul₂ {M α} [topological_space M] [second_countable_topology M] [measurable_space M] [opens_measurable_space M] [topological_space α] [second_countable_topology α] [measurable_space α] [borel_space α] [has_scalar M α] [has_continuous_smul M α] : has_measurable_smul₂ M α := ⟨continuous_smul.measurable⟩ end section borel_space variables [topological_space α] [measurable_space α] [borel_space α] [topological_space β] [measurable_space β] [borel_space β] [topological_space γ] [measurable_space γ] [borel_space γ] [measurable_space δ] lemma pi_le_borel_pi {ι : Type*} {π : ι → Type*} [Π i, topological_space (π i)] [Π i, measurable_space (π i)] [∀ i, borel_space (π i)] : measurable_space.pi ≤ borel (Π i, π i) := begin have : ‹Π i, measurable_space (π i)› = λ i, borel (π i) := funext (λ i, borel_space.measurable_eq), rw [this], exact supr_le (λ i, comap_le_iff_le_map.2 $ (continuous_apply i).borel_measurable) end lemma prod_le_borel_prod : prod.measurable_space ≤ borel (α × β) := begin rw [‹borel_space α›.measurable_eq, ‹borel_space β›.measurable_eq], refine sup_le _ _, { exact comap_le_iff_le_map.mpr continuous_fst.borel_measurable }, { exact comap_le_iff_le_map.mpr continuous_snd.borel_measurable } end instance pi.borel_space {ι : Type*} {π : ι → Type*} [fintype ι] [t' : Π i, topological_space (π i)] [Π i, measurable_space (π i)] [∀ i, second_countable_topology (π i)] [∀ i, borel_space (π i)] : borel_space (Π i, π i) := ⟨le_antisymm pi_le_borel_pi opens_measurable_space.borel_le⟩ instance prod.borel_space [second_countable_topology α] [second_countable_topology β] : borel_space (α × β) := ⟨le_antisymm prod_le_borel_prod opens_measurable_space.borel_le⟩ lemma closed_embedding.measurable_inv_fun [n : nonempty β] {g : β → γ} (hg : closed_embedding g) : measurable (function.inv_fun g) := begin refine measurable_of_is_closed (λ s hs, _), by_cases h : classical.choice n ∈ s, { rw preimage_inv_fun_of_mem hg.to_embedding.inj h, exact (hg.closed_iff_image_closed.mp hs).measurable_set.union hg.closed_range.measurable_set.compl }, { rw preimage_inv_fun_of_not_mem hg.to_embedding.inj h, exact (hg.closed_iff_image_closed.mp hs).measurable_set } end lemma measurable_comp_iff_of_closed_embedding {f : δ → β} (g : β → γ) (hg : closed_embedding g) : measurable (g ∘ f) ↔ measurable f := begin refine ⟨λ hf, _, λ hf, hg.measurable.comp hf⟩, apply measurable_of_is_closed, intros s hs, convert hf (hg.is_closed_map s hs).measurable_set, rw [@preimage_comp _ _ _ f g, preimage_image_eq _ hg.to_embedding.inj] end lemma ae_measurable_comp_iff_of_closed_embedding {f : δ → β} {μ : measure δ} (g : β → γ) (hg : closed_embedding g) : ae_measurable (g ∘ f) μ ↔ ae_measurable f μ := begin casesI is_empty_or_nonempty β, { haveI := function.is_empty f, simp only [(measurable_of_empty (g ∘ f)).ae_measurable, (measurable_of_empty f).ae_measurable] }, { refine ⟨λ hf, _, λ hf, hg.measurable.comp_ae_measurable hf⟩, convert hg.measurable_inv_fun.comp_ae_measurable hf, ext x, exact (function.left_inverse_inv_fun hg.to_embedding.inj (f x)).symm }, end lemma ae_measurable_comp_right_iff_of_closed_embedding {g : α → β} {μ : measure α} {f : β → δ} (hg : closed_embedding g) : ae_measurable (f ∘ g) μ ↔ ae_measurable f (measure.map g μ) := begin refine ⟨λ h, _, λ h, h.comp_measurable hg.measurable⟩, casesI is_empty_or_nonempty α, { simp [μ.eq_zero_of_is_empty] }, refine ⟨(h.mk _) ∘ (function.inv_fun g), h.measurable_mk.comp hg.measurable_inv_fun, _⟩, have : μ = measure.map (function.inv_fun g) (measure.map g μ), by rw [measure.map_map hg.measurable_inv_fun hg.measurable, (function.left_inverse_inv_fun hg.to_embedding.inj).comp_eq_id, measure.map_id], rw this at h, filter_upwards [ae_of_ae_map hg.measurable_inv_fun h.ae_eq_mk, ae_map_mem_range g hg.closed_range.measurable_set μ], assume x hx₁ hx₂, convert hx₁, exact ((function.left_inverse_inv_fun hg.to_embedding.inj).right_inv_on_range hx₂).symm, end section linear_order variables [linear_order α] [order_topology α] [second_countable_topology α] lemma measurable_of_Iio {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Iio x)) : measurable f := begin convert measurable_generate_from _, exact borel_space.measurable_eq.trans (borel_eq_generate_Iio _), rintro _ ⟨x, rfl⟩, exact hf x end lemma upper_semicontinuous.measurable [topological_space δ] [opens_measurable_space δ] {f : δ → α} (hf : upper_semicontinuous f) : measurable f := measurable_of_Iio (λ y, (hf.is_open_preimage y).measurable_set) lemma measurable_of_Ioi {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Ioi x)) : measurable f := begin convert measurable_generate_from _, exact borel_space.measurable_eq.trans (borel_eq_generate_Ioi _), rintro _ ⟨x, rfl⟩, exact hf x end lemma lower_semicontinuous.measurable [topological_space δ] [opens_measurable_space δ] {f : δ → α} (hf : lower_semicontinuous f) : measurable f := measurable_of_Ioi (λ y, (hf.is_open_preimage y).measurable_set) lemma measurable_of_Iic {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Iic x)) : measurable f := begin apply measurable_of_Ioi, simp_rw [← compl_Iic, preimage_compl, measurable_set.compl_iff], assumption end lemma measurable_of_Ici {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Ici x)) : measurable f := begin apply measurable_of_Iio, simp_rw [← compl_Ici, preimage_compl, measurable_set.compl_iff], assumption end lemma measurable.is_lub {ι} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, measurable (f i)) (hg : ∀ b, is_lub {a | ∃ i, f i b = a} (g b)) : measurable g := begin change ∀ b, is_lub (range $ λ i, f i b) (g b) at hg, rw [‹borel_space α›.measurable_eq, borel_eq_generate_Ioi α], apply measurable_generate_from, rintro _ ⟨a, rfl⟩, simp_rw [set.preimage, mem_Ioi, lt_is_lub_iff (hg _), exists_range_iff, set_of_exists], exact measurable_set.Union (λ i, hf i (is_open_lt' _).measurable_set) end private lemma ae_measurable.is_lub_of_nonempty {ι} (hι : nonempty ι) {μ : measure δ} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_lub {a | ∃ i, f i b = a} (g b)) : ae_measurable g μ := begin let p : δ → (ι → α) → Prop := λ x f', is_lub {a | ∃ i, f' i = a} (g x), let g_seq := λ x, ite (x ∈ ae_seq_set hf p) (g x) (⟨g x⟩ : nonempty α).some, have hg_seq : ∀ b, is_lub {a | ∃ i, ae_seq hf p i b = a} (g_seq b), { intro b, haveI hα : nonempty α := nonempty.map g ⟨b⟩, simp only [ae_seq, g_seq], split_ifs, { have h_set_eq : {a : α | ∃ (i : ι), (hf i).mk (f i) b = a} = {a : α | ∃ (i : ι), f i b = a}, { ext x, simp_rw [set.mem_set_of_eq, ae_seq.mk_eq_fun_of_mem_ae_seq_set hf h], }, rw h_set_eq, exact ae_seq.fun_prop_of_mem_ae_seq_set hf h, }, { have h_singleton : {a : α | ∃ (i : ι), hα.some = a} = {hα.some}, { ext1 x, exact ⟨λ hx, hx.some_spec.symm, λ hx, ⟨hι.some, hx.symm⟩⟩, }, rw h_singleton, exact is_lub_singleton, }, }, refine ⟨g_seq, measurable.is_lub (ae_seq.measurable hf p) hg_seq, _⟩, exact (ite_ae_eq_of_measure_compl_zero g (λ x, (⟨g x⟩ : nonempty α).some) (ae_seq_set hf p) (ae_seq.measure_compl_ae_seq_set_eq_zero hf hg)).symm, end lemma ae_measurable.is_lub {ι} {μ : measure δ} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_lub {a | ∃ i, f i b = a} (g b)) : ae_measurable g μ := begin by_cases hμ : μ = 0, { rw hμ, exact ae_measurable_zero_measure }, haveI : μ.ae.ne_bot, { simpa [ne_bot_iff] }, by_cases hι : nonempty ι, { exact ae_measurable.is_lub_of_nonempty hι hf hg, }, suffices : ∃ x, g =ᵐ[μ] λ y, g x, by { exact ⟨(λ y, g this.some), measurable_const, this.some_spec⟩, }, have h_empty : ∀ x, {a : α | ∃ (i : ι), f i x = a} = ∅, { intro x, ext1 y, rw [set.mem_set_of_eq, set.mem_empty_eq, iff_false], exact λ hi, hι (nonempty_of_exists hi), }, simp_rw h_empty at hg, exact ⟨hg.exists.some, hg.mono (λ y hy, is_lub.unique hy hg.exists.some_spec)⟩, end lemma measurable.is_glb {ι} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, measurable (f i)) (hg : ∀ b, is_glb {a | ∃ i, f i b = a} (g b)) : measurable g := begin change ∀ b, is_glb (range $ λ i, f i b) (g b) at hg, rw [‹borel_space α›.measurable_eq, borel_eq_generate_Iio α], apply measurable_generate_from, rintro _ ⟨a, rfl⟩, simp_rw [set.preimage, mem_Iio, is_glb_lt_iff (hg _), exists_range_iff, set_of_exists], exact measurable_set.Union (λ i, hf i (is_open_gt' _).measurable_set) end private lemma ae_measurable.is_glb_of_nonempty {ι} (hι : nonempty ι) {μ : measure δ} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_glb {a | ∃ i, f i b = a} (g b)) : ae_measurable g μ := begin let p : δ → (ι → α) → Prop := λ x f', is_glb {a | ∃ i, f' i = a} (g x), let g_seq := λ x, ite (x ∈ ae_seq_set hf p) (g x) (⟨g x⟩ : nonempty α).some, have hg_seq : ∀ b, is_glb {a | ∃ i, ae_seq hf p i b = a} (g_seq b), { intro b, haveI hα : nonempty α := nonempty.map g ⟨b⟩, simp only [ae_seq, g_seq], split_ifs, { have h_set_eq : {a : α | ∃ (i : ι), (hf i).mk (f i) b = a} = {a : α | ∃ (i : ι), f i b = a}, { ext x, simp_rw [set.mem_set_of_eq, ae_seq.mk_eq_fun_of_mem_ae_seq_set hf h], }, rw h_set_eq, exact ae_seq.fun_prop_of_mem_ae_seq_set hf h, }, { have h_singleton : {a : α | ∃ (i : ι), hα.some = a} = {hα.some}, { ext1 x, exact ⟨λ hx, hx.some_spec.symm, λ hx, ⟨hι.some, hx.symm⟩⟩, }, rw h_singleton, exact is_glb_singleton, }, }, refine ⟨g_seq, measurable.is_glb (ae_seq.measurable hf p) hg_seq, _⟩, exact (ite_ae_eq_of_measure_compl_zero g (λ x, (⟨g x⟩ : nonempty α).some) (ae_seq_set hf p) (ae_seq.measure_compl_ae_seq_set_eq_zero hf hg)).symm, end lemma ae_measurable.is_glb {ι} {μ : measure δ} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_glb {a | ∃ i, f i b = a} (g b)) : ae_measurable g μ := begin by_cases hμ : μ = 0, { rw hμ, exact ae_measurable_zero_measure }, haveI : μ.ae.ne_bot, { simpa [ne_bot_iff] }, by_cases hι : nonempty ι, { exact ae_measurable.is_glb_of_nonempty hι hf hg, }, suffices : ∃ x, g =ᵐ[μ] λ y, g x, by { exact ⟨(λ y, g this.some), measurable_const, this.some_spec⟩, }, have h_empty : ∀ x, {a : α | ∃ (i : ι), f i x = a} = ∅, { intro x, ext1 y, rw [set.mem_set_of_eq, set.mem_empty_eq, iff_false], exact λ hi, hι (nonempty_of_exists hi), }, simp_rw h_empty at hg, exact ⟨hg.exists.some, hg.mono (λ y hy, is_glb.unique hy hg.exists.some_spec)⟩, end protected lemma monotone.measurable [linear_order β] [order_closed_topology β] {f : β → α} (hf : monotone f) : measurable f := suffices h : ∀ x, ord_connected (f ⁻¹' Ioi x), from measurable_of_Ioi (λ x, (h x).measurable_set), λ x, ord_connected_def.mpr (λ a ha b hb c hc, lt_of_lt_of_le ha (hf hc.1)) lemma ae_measurable_restrict_of_monotone_on [linear_order β] [order_closed_topology β] {μ : measure β} {s : set β} (hs : measurable_set s) {f : β → α} (hf : monotone_on f s) : ae_measurable f (μ.restrict s) := have this : monotone (f ∘ coe : s → α), from λ ⟨x, hx⟩ ⟨y, hy⟩ (hxy : x ≤ y), hf hx hy hxy, ae_measurable_restrict_of_measurable_subtype hs this.measurable protected lemma antitone.measurable [linear_order β] [order_closed_topology β] {f : β → α} (hf : antitone f) : measurable f := @monotone.measurable (order_dual α) β _ _ ‹_› _ _ _ _ _ ‹_› _ _ _ hf lemma ae_measurable_restrict_of_antitone_on [linear_order β] [order_closed_topology β] {μ : measure β} {s : set β} (hs : measurable_set s) {f : β → α} (hf : antitone_on f s) : ae_measurable f (μ.restrict s) := @ae_measurable_restrict_of_monotone_on (order_dual α) β _ _ ‹_› _ _ _ _ _ ‹_› _ _ _ _ hs _ hf end linear_order @[measurability] lemma measurable.supr_Prop {α} [measurable_space α] [complete_lattice α] (p : Prop) {f : δ → α} (hf : measurable f) : measurable (λ b, ⨆ h : p, f b) := classical.by_cases (assume h : p, begin convert hf, funext, exact supr_pos h end) (assume h : ¬p, begin convert measurable_const, funext, exact supr_neg h end) @[measurability] lemma measurable.infi_Prop {α} [measurable_space α] [complete_lattice α] (p : Prop) {f : δ → α} (hf : measurable f) : measurable (λ b, ⨅ h : p, f b) := classical.by_cases (assume h : p, begin convert hf, funext, exact infi_pos h end ) (assume h : ¬p, begin convert measurable_const, funext, exact infi_neg h end) section complete_linear_order variables [complete_linear_order α] [order_topology α] [second_countable_topology α] @[measurability] lemma measurable_supr {ι} [encodable ι] {f : ι → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨆ i, f i b) := measurable.is_lub hf $ λ b, is_lub_supr @[measurability] lemma ae_measurable_supr {ι} {μ : measure δ} [encodable ι] {f : ι → δ → α} (hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨆ i, f i b) μ := ae_measurable.is_lub hf $ (ae_of_all μ (λ b, is_lub_supr)) @[measurability] lemma measurable_infi {ι} [encodable ι] {f : ι → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨅ i, f i b) := measurable.is_glb hf $ λ b, is_glb_infi @[measurability] lemma ae_measurable_infi {ι} {μ : measure δ} [encodable ι] {f : ι → δ → α} (hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨅ i, f i b) μ := ae_measurable.is_glb hf $ (ae_of_all μ (λ b, is_glb_infi)) lemma measurable_bsupr {ι} (s : set ι) {f : ι → δ → α} (hs : countable s) (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨆ i ∈ s, f i b) := by { haveI : encodable s := hs.to_encodable, simp only [supr_subtype'], exact measurable_supr (λ i, hf i) } lemma ae_measurable_bsupr {ι} {μ : measure δ} (s : set ι) {f : ι → δ → α} (hs : countable s) (hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨆ i ∈ s, f i b) μ := begin haveI : encodable s := hs.to_encodable, simp only [supr_subtype'], exact ae_measurable_supr (λ i, hf i), end lemma measurable_binfi {ι} (s : set ι) {f : ι → δ → α} (hs : countable s) (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨅ i ∈ s, f i b) := by { haveI : encodable s := hs.to_encodable, simp only [infi_subtype'], exact measurable_infi (λ i, hf i) } lemma ae_measurable_binfi {ι} {μ : measure δ} (s : set ι) {f : ι → δ → α} (hs : countable s) (hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨅ i ∈ s, f i b) μ := begin haveI : encodable s := hs.to_encodable, simp only [infi_subtype'], exact ae_measurable_infi (λ i, hf i), end /-- `liminf` over a general filter is measurable. See `measurable_liminf` for the version over `ℕ`. -/ lemma measurable_liminf' {ι ι'} {f : ι → δ → α} {u : filter ι} (hf : ∀ i, measurable (f i)) {p : ι' → Prop} {s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) : measurable (λ x, liminf u (λ i, f i x)) := begin simp_rw [hu.to_has_basis.liminf_eq_supr_infi], refine measurable_bsupr _ hu.countable _, exact λ i, measurable_binfi _ (hs i) hf end /-- `limsup` over a general filter is measurable. See `measurable_limsup` for the version over `ℕ`. -/ lemma measurable_limsup' {ι ι'} {f : ι → δ → α} {u : filter ι} (hf : ∀ i, measurable (f i)) {p : ι' → Prop} {s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) : measurable (λ x, limsup u (λ i, f i x)) := begin simp_rw [hu.to_has_basis.limsup_eq_infi_supr], refine measurable_binfi _ hu.countable _, exact λ i, measurable_bsupr _ (hs i) hf end /-- `liminf` over `ℕ` is measurable. See `measurable_liminf'` for a version with a general filter. -/ @[measurability] lemma measurable_liminf {f : ℕ → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ x, liminf at_top (λ i, f i x)) := measurable_liminf' hf at_top_countable_basis (λ i, countable_encodable _) /-- `limsup` over `ℕ` is measurable. See `measurable_limsup'` for a version with a general filter. -/ @[measurability] lemma measurable_limsup {f : ℕ → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ x, limsup at_top (λ i, f i x)) := measurable_limsup' hf at_top_countable_basis (λ i, countable_encodable _) end complete_linear_order section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] [order_topology α] [second_countable_topology α] lemma measurable_cSup {ι} {f : ι → δ → α} {s : set ι} (hs : s.countable) (hf : ∀ i, measurable (f i)) (bdd : ∀ x, bdd_above ((λ i, f i x) '' s)) : measurable (λ x, Sup ((λ i, f i x) '' s)) := begin cases eq_empty_or_nonempty s with h2s h2s, { simp [h2s, measurable_const] }, { apply measurable_of_Iic, intro y, simp_rw [preimage, mem_Iic, cSup_le_iff (bdd _) (h2s.image _), ball_image_iff, set_of_forall], exact measurable_set.bInter hs (λ i hi, measurable_set_le (hf i) measurable_const) } end end conditionally_complete_linear_order /-- Convert a `homeomorph` to a `measurable_equiv`. -/ def homemorph.to_measurable_equiv (h : α ≃ₜ β) : α ≃ᵐ β := { to_equiv := h.to_equiv, measurable_to_fun := h.continuous_to_fun.measurable, measurable_inv_fun := h.continuous_inv_fun.measurable } end borel_space instance empty.borel_space : borel_space empty := ⟨borel_eq_top_of_discrete.symm⟩ instance unit.borel_space : borel_space unit := ⟨borel_eq_top_of_discrete.symm⟩ instance bool.borel_space : borel_space bool := ⟨borel_eq_top_of_discrete.symm⟩ instance nat.borel_space : borel_space ℕ := ⟨borel_eq_top_of_discrete.symm⟩ instance int.borel_space : borel_space ℤ := ⟨borel_eq_top_of_discrete.symm⟩ instance rat.borel_space : borel_space ℚ := ⟨borel_eq_top_of_encodable.symm⟩ instance real.measurable_space : measurable_space ℝ := borel ℝ instance real.borel_space : borel_space ℝ := ⟨rfl⟩ instance nnreal.measurable_space : measurable_space ℝ≥0 := subtype.measurable_space instance nnreal.borel_space : borel_space ℝ≥0 := subtype.borel_space _ instance ennreal.measurable_space : measurable_space ℝ≥0∞ := borel ℝ≥0∞ instance ennreal.borel_space : borel_space ℝ≥0∞ := ⟨rfl⟩ instance ereal.measurable_space : measurable_space ereal := borel ereal instance ereal.borel_space : borel_space ereal := ⟨rfl⟩ instance complex.measurable_space : measurable_space ℂ := borel ℂ instance complex.borel_space : borel_space ℂ := ⟨rfl⟩ section metric_space variables [metric_space α] [measurable_space α] [opens_measurable_space α] variables [measurable_space β] {x : α} {ε : ℝ} open metric @[measurability] lemma measurable_set_ball : measurable_set (metric.ball x ε) := metric.is_open_ball.measurable_set @[measurability] lemma measurable_set_closed_ball : measurable_set (metric.closed_ball x ε) := metric.is_closed_ball.measurable_set @[measurability] lemma measurable_inf_dist {s : set α} : measurable (λ x, inf_dist x s) := (continuous_inf_dist_pt s).measurable @[measurability] lemma measurable.inf_dist {f : β → α} (hf : measurable f) {s : set α} : measurable (λ x, inf_dist (f x) s) := measurable_inf_dist.comp hf @[measurability] lemma measurable_inf_nndist {s : set α} : measurable (λ x, inf_nndist x s) := (continuous_inf_nndist_pt s).measurable @[measurability] lemma measurable.inf_nndist {f : β → α} (hf : measurable f) {s : set α} : measurable (λ x, inf_nndist (f x) s) := measurable_inf_nndist.comp hf variables [second_countable_topology α] @[measurability] lemma measurable_dist : measurable (λ p : α × α, dist p.1 p.2) := continuous_dist.measurable @[measurability] lemma measurable.dist {f g : β → α} (hf : measurable f) (hg : measurable g) : measurable (λ b, dist (f b) (g b)) := (@continuous_dist α _).measurable2 hf hg @[measurability] lemma measurable_nndist : measurable (λ p : α × α, nndist p.1 p.2) := continuous_nndist.measurable @[measurability] lemma measurable.nndist {f g : β → α} (hf : measurable f) (hg : measurable g) : measurable (λ b, nndist (f b) (g b)) := (@continuous_nndist α _).measurable2 hf hg end metric_space section emetric_space variables [emetric_space α] [measurable_space α] [opens_measurable_space α] variables [measurable_space β] {x : α} {ε : ℝ≥0∞} open emetric @[measurability] lemma measurable_set_eball : measurable_set (emetric.ball x ε) := emetric.is_open_ball.measurable_set @[measurability] lemma measurable_edist_right : measurable (edist x) := (continuous_const.edist continuous_id).measurable @[measurability] lemma measurable_edist_left : measurable (λ y, edist y x) := (continuous_id.edist continuous_const).measurable @[measurability] lemma measurable_inf_edist {s : set α} : measurable (λ x, inf_edist x s) := continuous_inf_edist.measurable @[measurability] lemma measurable.inf_edist {f : β → α} (hf : measurable f) {s : set α} : measurable (λ x, inf_edist (f x) s) := measurable_inf_edist.comp hf variables [second_countable_topology α] @[measurability] lemma measurable_edist : measurable (λ p : α × α, edist p.1 p.2) := continuous_edist.measurable @[measurability] lemma measurable.edist {f g : β → α} (hf : measurable f) (hg : measurable g) : measurable (λ b, edist (f b) (g b)) := (@continuous_edist α _).measurable2 hf hg @[measurability] lemma ae_measurable.edist {f g : β → α} {μ : measure β} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, edist (f a) (g a)) μ := (@continuous_edist α _).ae_measurable2 hf hg end emetric_space namespace real open measurable_space measure_theory lemma borel_eq_generate_from_Ioo_rat : borel ℝ = generate_from (⋃(a b : ℚ) (h : a < b), {Ioo a b}) := is_topological_basis_Ioo_rat.borel_eq_generate_from lemma is_pi_system_Ioo_rat : @is_pi_system ℝ (⋃ (a b : ℚ) (h : a < b), {Ioo a b}) := by simpa using is_pi_system_Ioo (coe : ℚ → ℝ) /-- The intervals `(-(n + 1), (n + 1))` form a finite spanning sets in the set of open intervals with rational endpoints for a locally finite measure `μ` on `ℝ`. -/ def finite_spanning_sets_in_Ioo_rat (μ : measure ℝ) [is_locally_finite_measure μ] : μ.finite_spanning_sets_in (⋃ (a b : ℚ) (h : a < b), {Ioo a b}) := { set := λ n, Ioo (-(n + 1)) (n + 1), set_mem := λ n, begin simp only [mem_Union, mem_singleton_iff], refine ⟨-(n + 1), n + 1, _, by norm_cast⟩, exact (neg_nonpos.2 (@nat.cast_nonneg ℚ _ (n + 1))).trans_lt n.cast_add_one_pos end, finite := λ n, measure_Ioo_lt_top, spanning := Union_eq_univ_iff.2 $ λ x, ⟨⌊|x|⌋₊, neg_lt.1 ((neg_le_abs_self x).trans_lt (nat.lt_floor_add_one _)), (le_abs_self x).trans_lt (nat.lt_floor_add_one _)⟩ } lemma measure_ext_Ioo_rat {μ ν : measure ℝ} [is_locally_finite_measure μ] (h : ∀ a b : ℚ, μ (Ioo a b) = ν (Ioo a b)) : μ = ν := (finite_spanning_sets_in_Ioo_rat μ).ext borel_eq_generate_from_Ioo_rat is_pi_system_Ioo_rat $ by { simp only [mem_Union, mem_singleton_iff], rintro _ ⟨a, b, -, rfl⟩, apply h } lemma borel_eq_generate_from_Iio_rat : borel ℝ = generate_from (⋃ a : ℚ, {Iio a}) := begin let g : measurable_space ℝ := generate_from (⋃ a : ℚ, {Iio a}), apply le_antisymm _ (measurable_space.generate_from_le (λ t, _)), { rw borel_eq_generate_from_Ioo_rat, refine generate_from_le (λ t, _), simp only [mem_Union, mem_singleton_iff], rintro ⟨a, b, h, rfl⟩, rw (set.ext (λ x, _) : Ioo (a : ℝ) b = (⋃c>a, (Iio c)ᶜ) ∩ Iio b), { have hg : ∀ q : ℚ, g.measurable_set' (Iio q) := λ q, generate_measurable.basic (Iio q) (by { simp, exact ⟨_, rfl⟩ }), refine @measurable_set.inter _ g _ _ _ (hg _), refine @measurable_set.bUnion _ _ g _ _ (countable_encodable _) (λ c h, _), exact @measurable_set.compl _ _ g (hg _) }, { suffices : x < ↑b → (↑a < x ↔ ∃ (i : ℚ), a < i ∧ ↑i ≤ x), by simpa, refine λ _, ⟨λ h, _, λ ⟨i, hai, hix⟩, (rat.cast_lt.2 hai).trans_le hix⟩, rcases exists_rat_btwn h with ⟨c, ac, cx⟩, exact ⟨c, rat.cast_lt.1 ac, cx.le⟩ } }, { simp only [mem_Union, mem_singleton_iff], rintro ⟨r, rfl⟩, exact measurable_set_Iio } end end real variable [measurable_space α] @[measurability] lemma measurable_real_to_nnreal : measurable (real.to_nnreal) := nnreal.continuous_of_real.measurable @[measurability] lemma measurable.real_to_nnreal {f : α → ℝ} (hf : measurable f) : measurable (λ x, real.to_nnreal (f x)) := measurable_real_to_nnreal.comp hf @[measurability] lemma ae_measurable.real_to_nnreal {f : α → ℝ} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, real.to_nnreal (f x)) μ := measurable_real_to_nnreal.comp_ae_measurable hf @[measurability] lemma measurable_coe_nnreal_real : measurable (coe : ℝ≥0 → ℝ) := nnreal.continuous_coe.measurable @[measurability] lemma measurable.coe_nnreal_real {f : α → ℝ≥0} (hf : measurable f) : measurable (λ x, (f x : ℝ)) := measurable_coe_nnreal_real.comp hf @[measurability] lemma ae_measurable.coe_nnreal_real {f : α → ℝ≥0} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x : ℝ)) μ := measurable_coe_nnreal_real.comp_ae_measurable hf @[measurability] lemma measurable_coe_nnreal_ennreal : measurable (coe : ℝ≥0 → ℝ≥0∞) := ennreal.continuous_coe.measurable @[measurability] lemma measurable.coe_nnreal_ennreal {f : α → ℝ≥0} (hf : measurable f) : measurable (λ x, (f x : ℝ≥0∞)) := ennreal.continuous_coe.measurable.comp hf @[measurability] lemma ae_measurable.coe_nnreal_ennreal {f : α → ℝ≥0} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x : ℝ≥0∞)) μ := ennreal.continuous_coe.measurable.comp_ae_measurable hf @[measurability] lemma measurable.ennreal_of_real {f : α → ℝ} (hf : measurable f) : measurable (λ x, ennreal.of_real (f x)) := ennreal.continuous_of_real.measurable.comp hf /-- The set of finite `ℝ≥0∞` numbers is `measurable_equiv` to `ℝ≥0`. -/ def measurable_equiv.ennreal_equiv_nnreal : {r : ℝ≥0∞ | r ≠ ∞} ≃ᵐ ℝ≥0 := ennreal.ne_top_homeomorph_nnreal.to_measurable_equiv namespace ennreal lemma measurable_of_measurable_nnreal {f : ℝ≥0∞ → α} (h : measurable (λ p : ℝ≥0, f p)) : measurable f := measurable_of_measurable_on_compl_singleton ∞ (measurable_equiv.ennreal_equiv_nnreal.symm.measurable_coe_iff.1 h) /-- `ℝ≥0∞` is `measurable_equiv` to `ℝ≥0 ⊕ unit`. -/ def ennreal_equiv_sum : ℝ≥0∞ ≃ᵐ ℝ≥0 ⊕ unit := { measurable_to_fun := measurable_of_measurable_nnreal measurable_inl, measurable_inv_fun := measurable_sum measurable_coe_nnreal_ennreal (@measurable_const ℝ≥0∞ unit _ _ ∞), .. equiv.option_equiv_sum_punit ℝ≥0 } open function (uncurry) lemma measurable_of_measurable_nnreal_prod [measurable_space β] [measurable_space γ] {f : ℝ≥0∞ × β → γ} (H₁ : measurable (λ p : ℝ≥0 × β, f (p.1, p.2))) (H₂ : measurable (λ x, f (∞, x))) : measurable f := let e : ℝ≥0∞ × β ≃ᵐ ℝ≥0 × β ⊕ unit × β := (ennreal_equiv_sum.prod_congr (measurable_equiv.refl β)).trans (measurable_equiv.sum_prod_distrib _ _ _) in e.symm.measurable_coe_iff.1 $ measurable_sum H₁ (H₂.comp measurable_id.snd) lemma measurable_of_measurable_nnreal_nnreal [measurable_space β] {f : ℝ≥0∞ × ℝ≥0∞ → β} (h₁ : measurable (λ p : ℝ≥0 × ℝ≥0, f (p.1, p.2))) (h₂ : measurable (λ r : ℝ≥0, f (∞, r))) (h₃ : measurable (λ r : ℝ≥0, f (r, ∞))) : measurable f := measurable_of_measurable_nnreal_prod (measurable_swap_iff.1 $ measurable_of_measurable_nnreal_prod (h₁.comp measurable_swap) h₃) (measurable_of_measurable_nnreal h₂) @[measurability] lemma measurable_of_real : measurable ennreal.of_real := ennreal.continuous_of_real.measurable @[measurability] lemma measurable_to_real : measurable ennreal.to_real := ennreal.measurable_of_measurable_nnreal measurable_coe_nnreal_real @[measurability] lemma measurable_to_nnreal : measurable ennreal.to_nnreal := ennreal.measurable_of_measurable_nnreal measurable_id instance : has_measurable_mul₂ ℝ≥0∞ := begin refine ⟨measurable_of_measurable_nnreal_nnreal _ _ _⟩, { simp only [← ennreal.coe_mul, measurable_mul.coe_nnreal_ennreal] }, { simp only [ennreal.top_mul, ennreal.coe_eq_zero], exact measurable_const.piecewise (measurable_set_singleton _) measurable_const }, { simp only [ennreal.mul_top, ennreal.coe_eq_zero], exact measurable_const.piecewise (measurable_set_singleton _) measurable_const } end instance : has_measurable_sub₂ ℝ≥0∞ := ⟨by apply measurable_of_measurable_nnreal_nnreal; simp [← with_top.coe_sub, continuous_sub.measurable.coe_nnreal_ennreal]⟩ instance : has_measurable_inv ℝ≥0∞ := ⟨ennreal.continuous_inv.measurable⟩ end ennreal @[measurability] lemma measurable.ennreal_to_nnreal {f : α → ℝ≥0∞} (hf : measurable f) : measurable (λ x, (f x).to_nnreal) := ennreal.measurable_to_nnreal.comp hf @[measurability] lemma ae_measurable.ennreal_to_nnreal {f : α → ℝ≥0∞} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x).to_nnreal) μ := ennreal.measurable_to_nnreal.comp_ae_measurable hf lemma measurable_coe_nnreal_ennreal_iff {f : α → ℝ≥0} : measurable (λ x, (f x : ℝ≥0∞)) ↔ measurable f := ⟨λ h, h.ennreal_to_nnreal, λ h, h.coe_nnreal_ennreal⟩ @[measurability] lemma measurable.ennreal_to_real {f : α → ℝ≥0∞} (hf : measurable f) : measurable (λ x, ennreal.to_real (f x)) := ennreal.measurable_to_real.comp hf @[measurability] lemma ae_measurable.ennreal_to_real {f : α → ℝ≥0∞} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, ennreal.to_real (f x)) μ := ennreal.measurable_to_real.comp_ae_measurable hf /-- note: `ℝ≥0∞` can probably be generalized in a future version of this lemma. -/ @[measurability] lemma measurable.ennreal_tsum {ι} [encodable ι] {f : ι → α → ℝ≥0∞} (h : ∀ i, measurable (f i)) : measurable (λ x, ∑' i, f i x) := by { simp_rw [ennreal.tsum_eq_supr_sum], apply measurable_supr, exact λ s, s.measurable_sum (λ i _, h i) } @[measurability] lemma measurable.ennreal_tsum' {ι} [encodable ι] {f : ι → α → ℝ≥0∞} (h : ∀ i, measurable (f i)) : measurable (∑' i, f i) := begin convert measurable.ennreal_tsum h, ext1 x, exact tsum_apply (pi.summable.2 (λ _, ennreal.summable)), end @[measurability] lemma measurable.nnreal_tsum {ι} [encodable ι] {f : ι → α → ℝ≥0} (h : ∀ i, measurable (f i)) : measurable (λ x, ∑' i, f i x) := begin simp_rw [nnreal.tsum_eq_to_nnreal_tsum], exact (measurable.ennreal_tsum (λ i, (h i).coe_nnreal_ennreal)).ennreal_to_nnreal, end @[measurability] lemma ae_measurable.ennreal_tsum {ι} [encodable ι] {f : ι → α → ℝ≥0∞} {μ : measure α} (h : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ x, ∑' i, f i x) μ := by { simp_rw [ennreal.tsum_eq_supr_sum], apply ae_measurable_supr, exact λ s, finset.ae_measurable_sum s (λ i _, h i) } @[measurability] lemma measurable_coe_real_ereal : measurable (coe : ℝ → ereal) := continuous_coe_real_ereal.measurable @[measurability] lemma measurable.coe_real_ereal {f : α → ℝ} (hf : measurable f) : measurable (λ x, (f x : ereal)) := measurable_coe_real_ereal.comp hf @[measurability] lemma ae_measurable.coe_real_ereal {f : α → ℝ} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x : ereal)) μ := measurable_coe_real_ereal.comp_ae_measurable hf /-- The set of finite `ereal` numbers is `measurable_equiv` to `ℝ`. -/ def measurable_equiv.ereal_equiv_real : ({⊥, ⊤} : set ereal).compl ≃ᵐ ℝ := ereal.ne_bot_top_homeomorph_real.to_measurable_equiv lemma ereal.measurable_of_measurable_real {f : ereal → α} (h : measurable (λ p : ℝ, f p)) : measurable f := measurable_of_measurable_on_compl_finite {⊥, ⊤} (by simp) (measurable_equiv.ereal_equiv_real.symm.measurable_coe_iff.1 h) @[measurability] lemma measurable_ereal_to_real : measurable ereal.to_real := ereal.measurable_of_measurable_real (by simpa using measurable_id) @[measurability] lemma measurable.ereal_to_real {f : α → ereal} (hf : measurable f) : measurable (λ x, (f x).to_real) := measurable_ereal_to_real.comp hf @[measurability] lemma ae_measurable.ereal_to_real {f : α → ereal} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x).to_real) μ := measurable_ereal_to_real.comp_ae_measurable hf @[measurability] lemma measurable_coe_ennreal_ereal : measurable (coe : ℝ≥0∞ → ereal) := continuous_coe_ennreal_ereal.measurable @[measurability] lemma measurable.coe_ereal_ennreal {f : α → ℝ≥0∞} (hf : measurable f) : measurable (λ x, (f x : ereal)) := measurable_coe_ennreal_ereal.comp hf @[measurability] lemma ae_measurable.coe_ereal_ennreal {f : α → ℝ≥0∞} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x : ereal)) μ := measurable_coe_ennreal_ereal.comp_ae_measurable hf section normed_group variables [normed_group α] [opens_measurable_space α] [measurable_space β] @[measurability] lemma measurable_norm : measurable (norm : α → ℝ) := continuous_norm.measurable @[measurability] lemma measurable.norm {f : β → α} (hf : measurable f) : measurable (λ a, norm (f a)) := measurable_norm.comp hf @[measurability] lemma ae_measurable.norm {f : β → α} {μ : measure β} (hf : ae_measurable f μ) : ae_measurable (λ a, norm (f a)) μ := measurable_norm.comp_ae_measurable hf @[measurability] lemma measurable_nnnorm : measurable (nnnorm : α → ℝ≥0) := continuous_nnnorm.measurable @[measurability] lemma measurable.nnnorm {f : β → α} (hf : measurable f) : measurable (λ a, nnnorm (f a)) := measurable_nnnorm.comp hf @[measurability] lemma ae_measurable.nnnorm {f : β → α} {μ : measure β} (hf : ae_measurable f μ) : ae_measurable (λ a, nnnorm (f a)) μ := measurable_nnnorm.comp_ae_measurable hf @[measurability] lemma measurable_ennnorm : measurable (λ x : α, (nnnorm x : ℝ≥0∞)) := measurable_nnnorm.coe_nnreal_ennreal @[measurability] lemma measurable.ennnorm {f : β → α} (hf : measurable f) : measurable (λ a, (nnnorm (f a) : ℝ≥0∞)) := hf.nnnorm.coe_nnreal_ennreal @[measurability] lemma ae_measurable.ennnorm {f : β → α} {μ : measure β} (hf : ae_measurable f μ) : ae_measurable (λ a, (nnnorm (f a) : ℝ≥0∞)) μ := measurable_ennnorm.comp_ae_measurable hf end normed_group section limits variables [measurable_space β] [metric_space β] [borel_space β] open metric /-- A limit (over a general filter) of measurable `ℝ≥0` valued functions is measurable. The assumption `hs` can be dropped using `filter.is_countably_generated.has_antitone_basis`, but we don't need that case yet. -/ lemma measurable_of_tendsto_nnreal' {ι ι'} {f : ι → α → ℝ≥0} {g : α → ℝ≥0} (u : filter ι) [ne_bot u] (hf : ∀ i, measurable (f i)) (lim : tendsto f u (𝓝 g)) {p : ι' → Prop} {s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) : measurable g := begin rw [tendsto_pi] at lim, rw [← measurable_coe_nnreal_ennreal_iff], have : ∀ x, liminf u (λ n, (f n x : ℝ≥0∞)) = (g x : ℝ≥0∞) := λ x, ((ennreal.continuous_coe.tendsto (g x)).comp (lim x)).liminf_eq, simp_rw [← this], show measurable (λ x, liminf u (λ n, (f n x : ℝ≥0∞))), exact measurable_liminf' (λ i, (hf i).coe_nnreal_ennreal) hu hs, end /-- A sequential limit of measurable `ℝ≥0` valued functions is measurable. -/ lemma measurable_of_tendsto_nnreal {f : ℕ → α → ℝ≥0} {g : α → ℝ≥0} (hf : ∀ i, measurable (f i)) (lim : tendsto f at_top (𝓝 g)) : measurable g := measurable_of_tendsto_nnreal' at_top hf lim at_top_countable_basis (λ i, countable_encodable _) /-- A limit (over a general filter) of measurable functions valued in a metric space is measurable. The assumption `hs` can be dropped using `filter.is_countably_generated.has_antitone_basis`, but we don't need that case yet. -/ lemma measurable_of_tendsto_metric' {ι ι'} {f : ι → α → β} {g : α → β} (u : filter ι) [ne_bot u] (hf : ∀ i, measurable (f i)) (lim : tendsto f u (𝓝 g)) {p : ι' → Prop} {s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) : measurable g := begin apply measurable_of_is_closed', intros s h1s h2s h3s, have : measurable (λ x, inf_nndist (g x) s), { refine measurable_of_tendsto_nnreal' u (λ i, (hf i).inf_nndist) _ hu hs, swap, rw [tendsto_pi], rw [tendsto_pi] at lim, intro x, exact ((continuous_inf_nndist_pt s).tendsto (g x)).comp (lim x) }, have h4s : g ⁻¹' s = (λ x, inf_nndist (g x) s) ⁻¹' {0}, { ext x, simp [h1s, ← h1s.mem_iff_inf_dist_zero h2s, ← nnreal.coe_eq_zero] }, rw [h4s], exact this (measurable_set_singleton 0), end /-- A sequential limit of measurable functions valued in a metric space is measurable. -/ lemma measurable_of_tendsto_metric {f : ℕ → α → β} {g : α → β} (hf : ∀ i, measurable (f i)) (lim : tendsto f at_top (𝓝 g)) : measurable g := measurable_of_tendsto_metric' at_top hf lim at_top_countable_basis (λ i, countable_encodable _) lemma ae_measurable_of_tendsto_metric_ae {μ : measure α} {f : ℕ → α → β} {g : α → β} (hf : ∀ n, ae_measurable (f n) μ) (h_ae_tendsto : ∀ᵐ x ∂μ, filter.at_top.tendsto (λ n, f n x) (𝓝 (g x))) : ae_measurable g μ := begin let p : α → (ℕ → β) → Prop := λ x f', filter.at_top.tendsto (λ n, f' n) (𝓝 (g x)), let hp : ∀ᵐ x ∂μ, p x (λ n, f n x), from h_ae_tendsto, let ae_seq_lim := λ x, ite (x ∈ ae_seq_set hf p) (g x) (⟨f 0 x⟩ : nonempty β).some, refine ⟨ae_seq_lim, _, (ite_ae_eq_of_measure_compl_zero g (λ x, (⟨f 0 x⟩ : nonempty β).some) (ae_seq_set hf p) (ae_seq.measure_compl_ae_seq_set_eq_zero hf hp)).symm⟩, refine measurable_of_tendsto_metric (@ae_seq.measurable α β _ _ _ f μ hf p) _, refine tendsto_pi.mpr (λ x, _), simp_rw [ae_seq, ae_seq_lim], split_ifs with hx, { simp_rw ae_seq.mk_eq_fun_of_mem_ae_seq_set hf hx, exact @ae_seq.fun_prop_of_mem_ae_seq_set α β _ _ _ _ _ _ hf x hx, }, { exact tendsto_const_nhds, }, end lemma measurable_of_tendsto_metric_ae {μ : measure α} [μ.is_complete] {f : ℕ → α → β} {g : α → β} (hf : ∀ n, measurable (f n)) (h_ae_tendsto : ∀ᵐ x ∂μ, filter.at_top.tendsto (λ n, f n x) (𝓝 (g x))) : measurable g := ae_measurable_iff_measurable.mp (ae_measurable_of_tendsto_metric_ae (λ i, (hf i).ae_measurable) h_ae_tendsto) lemma measurable_limit_of_tendsto_metric_ae {μ : measure α} {f : ℕ → α → β} (hf : ∀ n, ae_measurable (f n) μ) (h_ae_tendsto : ∀ᵐ x ∂μ, ∃ l : β, filter.at_top.tendsto (λ n, f n x) (𝓝 l)) : ∃ (f_lim : α → β) (hf_lim_meas : measurable f_lim), ∀ᵐ x ∂μ, filter.at_top.tendsto (λ n, f n x) (𝓝 (f_lim x)) := begin let p : α → (ℕ → β) → Prop := λ x f', ∃ l : β, filter.at_top.tendsto (λ n, f' n) (𝓝 l), have hp_mem : ∀ x, x ∈ ae_seq_set hf p → p x (λ n, f n x), from λ x hx, ae_seq.fun_prop_of_mem_ae_seq_set hf hx, have hμ_compl : μ (ae_seq_set hf p)ᶜ = 0, from ae_seq.measure_compl_ae_seq_set_eq_zero hf h_ae_tendsto, let f_lim : α → β := λ x, dite (x ∈ ae_seq_set hf p) (λ h, (hp_mem x h).some) (λ h, (⟨f 0 x⟩ : nonempty β).some), have hf_lim_conv : ∀ x, x ∈ ae_seq_set hf p → filter.at_top.tendsto (λ n, f n x) (𝓝 (f_lim x)), { intros x hx_conv, simp only [f_lim, hx_conv, dif_pos], exact (hp_mem x hx_conv).some_spec, }, have hf_lim : ∀ x, filter.at_top.tendsto (λ n, ae_seq hf p n x) (𝓝 (f_lim x)), { intros x, simp only [f_lim, ae_seq], split_ifs, { rw funext (λ n, ae_seq.mk_eq_fun_of_mem_ae_seq_set hf h n), exact (hp_mem x h).some_spec, }, { exact tendsto_const_nhds, }, }, have h_ae_tendsto_f_lim : ∀ᵐ x ∂μ, filter.at_top.tendsto (λ n, f n x) (𝓝 (f_lim x)), { refine le_antisymm (le_of_eq (measure_mono_null _ hμ_compl)) (zero_le _), exact set.compl_subset_compl.mpr (λ x hx, hf_lim_conv x hx), }, have h_f_lim_meas : measurable f_lim, from measurable_of_tendsto_metric (ae_seq.measurable hf p) (tendsto_pi.mpr (λ x, hf_lim x)), exact ⟨f_lim, h_f_lim_meas, h_ae_tendsto_f_lim⟩, end end limits namespace continuous_linear_map variables {𝕜 : Type*} [normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [measurable_space E] variables [opens_measurable_space E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] [measurable_space F] [borel_space F] @[measurability] protected lemma measurable (L : E →L[𝕜] F) : measurable L := L.continuous.measurable lemma measurable_comp (L : E →L[𝕜] F) {φ : α → E} (φ_meas : measurable φ) : measurable (λ (a : α), L (φ a)) := L.measurable.comp φ_meas end continuous_linear_map namespace continuous_linear_map variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] instance : measurable_space (E →L[𝕜] F) := borel _ instance : borel_space (E →L[𝕜] F) := ⟨rfl⟩ @[measurability] lemma measurable_apply [measurable_space F] [borel_space F] (x : E) : measurable (λ f : E →L[𝕜] F, f x) := (apply 𝕜 F x).continuous.measurable @[measurability] lemma measurable_apply' [measurable_space E] [opens_measurable_space E] [measurable_space F] [borel_space F] : measurable (λ (x : E) (f : E →L[𝕜] F), f x) := measurable_pi_lambda _ $ λ f, f.measurable @[measurability] lemma measurable_coe [measurable_space F] [borel_space F] : measurable (λ (f : E →L[𝕜] F) (x : E), f x) := measurable_pi_lambda _ measurable_apply end continuous_linear_map section continuous_linear_map_nondiscrete_normed_field variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [measurable_space E] [borel_space E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] @[measurability] lemma measurable.apply_continuous_linear_map {φ : α → F →L[𝕜] E} (hφ : measurable φ) (v : F) : measurable (λ a, φ a v) := (continuous_linear_map.apply 𝕜 E v).measurable.comp hφ @[measurability] lemma ae_measurable.apply_continuous_linear_map {φ : α → F →L[𝕜] E} {μ : measure α} (hφ : ae_measurable φ μ) (v : F) : ae_measurable (λ a, φ a v) μ := (continuous_linear_map.apply 𝕜 E v).measurable.comp_ae_measurable hφ end continuous_linear_map_nondiscrete_normed_field section normed_space variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] [complete_space 𝕜] [measurable_space 𝕜] variables [borel_space 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [measurable_space E] [borel_space E] lemma measurable_smul_const {f : α → 𝕜} {c : E} (hc : c ≠ 0) : measurable (λ x, f x • c) ↔ measurable f := measurable_comp_iff_of_closed_embedding (λ y : 𝕜, y • c) (closed_embedding_smul_left hc) lemma ae_measurable_smul_const {f : α → 𝕜} {μ : measure α} {c : E} (hc : c ≠ 0) : ae_measurable (λ x, f x • c) μ ↔ ae_measurable f μ := ae_measurable_comp_iff_of_closed_embedding (λ y : 𝕜, y • c) (closed_embedding_smul_left hc) end normed_space
3f675aa0dabd8871a5388fc0d32e92d6dd8bf1e2
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/format_macro.lean
f4906428642764d1cc8c89e3257186f6eab773ab
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
404
lean
#eval to_string $ format!"hi" #eval to_string $ format! "hi" #eval to_string $ format!"hi\nhi" #eval to_string $ format!"{1}+{1}" #eval to_string $ format!"{1+1}" #eval to_string $ format!"{{{1+1}}}" #eval to_string $ format!"a{1}" #eval to_string $ format!"{1}a" #eval to_string $ format!"}}" #check λ α, format!"{α}" #eval format!"{" #eval format!"{}" #eval format!"{1+}" #eval sformat!"a{'b'}c"
25953cf91654c7f8f0a5ad6755345571756d002f
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/analysis/analytic/basic.lean
6d1b4182d33215e5e679c3b0a159be4d9c0136dd
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
38,036
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.calculus.times_cont_diff import tactic.omega import analysis.special_functions.pow /-! # Analytic functions A function is analytic in one dimension around `0` if it can be written as a converging power series `Σ pₙ zⁿ`. This definition can be extended to any dimension (even in infinite dimension) by requiring that `pₙ` is a continuous `n`-multilinear map. In general, `pₙ` is not unique (in two dimensions, taking `p₂ (x, y) (x', y') = x y'` or `y x'` gives the same map when applied to a vector `(x, y) (x, y)`). A way to guarantee uniqueness is to take a symmetric `pₙ`, but this is not always possible in nonzero characteristic (in characteristic 2, the previous example has no symmetric representative). Therefore, we do not insist on symmetry or uniqueness in the definition, and we only require the existence of a converging series. The general framework is important to say that the exponential map on bounded operators on a Banach space is analytic, as well as the inverse on invertible operators. ## Main definitions Let `p` be a formal multilinear series from `E` to `F`, i.e., `p n` is a multilinear map on `E^n` for `n : ℕ`. * `p.radius`: the largest `r : ennreal` such that `∥p n∥ * r^n` grows subexponentially, defined as a liminf. * `p.le_radius_of_bound`, `p.bound_of_lt_radius`, `p.geometric_bound_of_lt_radius`: relating the value of the radius with the growth of `∥p n∥ * r^n`. * `p.partial_sum n x`: the sum `∑_{i = 0}^{n-1} pᵢ xⁱ`. * `p.sum x`: the sum `∑'_{i = 0}^{∞} pᵢ xⁱ`. Additionally, let `f` be a function from `E` to `F`. * `has_fpower_series_on_ball f p x r`: on the ball of center `x` with radius `r`, `f (x + y) = ∑'_n pₙ yⁿ`. * `has_fpower_series_at f p x`: on some ball of center `x` with positive radius, holds `has_fpower_series_on_ball f p x r`. * `analytic_at 𝕜 f x`: there exists a power series `p` such that holds `has_fpower_series_at f p x`. We develop the basic properties of these notions, notably: * If a function admits a power series, it is continuous (see `has_fpower_series_on_ball.continuous_on` and `has_fpower_series_at.continuous_at` and `analytic_at.continuous_at`). * In a complete space, the sum of a formal power series with positive radius is well defined on the disk of convergence, see `formal_multilinear_series.has_fpower_series_on_ball`. * If a function admits a power series in a ball, then it is analytic at any point `y` of this ball, and the power series there can be expressed in terms of the initial power series `p` as `p.change_origin y`. See `has_fpower_series_on_ball.change_origin`. It follows in particular that the set of points at which a given function is analytic is open, see `is_open_analytic_at`. ## Implementation details We only introduce the radius of convergence of a power series, as `p.radius`. For a power series in finitely many dimensions, there is a finer (directional, coordinate-dependent) notion, describing the polydisk of convergence. This notion is more specific, and not necessary to build the general theory. We do not define it here. -/ noncomputable theory variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {G : Type*} [normed_group G] [normed_space 𝕜 G] open_locale topological_space classical open filter /-! ### The radius of a formal multilinear series -/ namespace formal_multilinear_series /-- The radius of a formal multilinear series is the largest `r` such that the sum `Σ pₙ yⁿ` converges for all `∥y∥ < r`. -/ def radius (p : formal_multilinear_series 𝕜 E F) : ennreal := liminf at_top (λ n, 1/((nnnorm (p n)) ^ (1 / (n : ℝ)) : nnreal)) /--If `∥pₙ∥ rⁿ` is bounded in `n`, then the radius of `p` is at least `r`. -/ lemma le_radius_of_bound (p : formal_multilinear_series 𝕜 E F) (C : nnreal) {r : nnreal} (h : ∀ (n : ℕ), nnnorm (p n) * r^n ≤ C) : (r : ennreal) ≤ p.radius := begin have L : tendsto (λ n : ℕ, (r : ennreal) / ((C + 1)^(1/(n : ℝ)) : nnreal)) at_top (𝓝 ((r : ennreal) / ((C + 1)^(0 : ℝ) : nnreal))), { apply ennreal.tendsto.div tendsto_const_nhds, { simp }, { rw ennreal.tendsto_coe, apply tendsto_const_nhds.nnrpow (tendsto_const_div_at_top_nhds_0_nat 1), simp }, { simp } }, have A : ∀ n : ℕ , 0 < n → (r : ennreal) ≤ ((C + 1)^(1/(n : ℝ)) : nnreal) * (1 / (nnnorm (p n) ^ (1/(n:ℝ)) : nnreal)), { assume n npos, simp only [one_div_eq_inv, mul_assoc, mul_one, eq.symm ennreal.mul_div_assoc], rw [ennreal.le_div_iff_mul_le _ _, ← nnreal.pow_nat_rpow_nat_inv r npos, ← ennreal.coe_mul, ennreal.coe_le_coe, ← nnreal.mul_rpow, mul_comm], { exact nnreal.rpow_le_rpow (le_trans (h n) (le_add_right (le_refl _))) (by simp) }, { simp }, { simp } }, have B : ∀ᶠ (n : ℕ) in at_top, (r : ennreal) / ((C + 1)^(1/(n : ℝ)) : nnreal) ≤ 1 / (nnnorm (p n) ^ (1/(n:ℝ)) : nnreal), { apply eventually_at_top.2 ⟨1, λ n hn, _⟩, rw [ennreal.div_le_iff_le_mul, mul_comm], { apply A n hn }, { simp }, { simp } }, have D : liminf at_top (λ n : ℕ, (r : ennreal) / ((C + 1)^(1/(n : ℝ)) : nnreal)) ≤ p.radius := liminf_le_liminf B, rw liminf_eq_of_tendsto filter.at_top_ne_bot L at D, simpa using D end /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` is bounded. -/ lemma bound_of_lt_radius (p : formal_multilinear_series 𝕜 E F) {r : nnreal} (h : (r : ennreal) < p.radius) : ∃ (C : nnreal), ∀ n, nnnorm (p n) * r^n ≤ C := begin obtain ⟨N, hN⟩ : ∃ (N : ℕ), ∀ n, n ≥ N → (r : ennreal) < 1 / ↑(nnnorm (p n) ^ (1 / (n : ℝ))) := eventually.exists_forall_of_at_top (eventually_lt_of_lt_liminf h), obtain ⟨D, hD⟩ : ∃D, ∀ x ∈ (↑((finset.range N.succ).image (λ i, nnnorm (p i) * r^i))), x ≤ D := finset.bdd_above _, refine ⟨max D 1, λ n, _⟩, cases le_or_lt n N with hn hn, { refine le_trans _ (le_max_left D 1), apply hD, have : n ∈ finset.range N.succ := list.mem_range.mpr (nat.lt_succ_iff.mpr hn), exact finset.mem_image_of_mem _ this }, { by_cases hpn : nnnorm (p n) = 0, { simp [hpn] }, have A : nnnorm (p n) ^ (1 / (n : ℝ)) ≠ 0, by simp [nnreal.rpow_eq_zero_iff, hpn], have B : r < (nnnorm (p n) ^ (1 / (n : ℝ)))⁻¹, { have := hN n (le_of_lt hn), rwa [ennreal.div_def, ← ennreal.coe_inv A, one_mul, ennreal.coe_lt_coe] at this }, rw [nnreal.lt_inv_iff_mul_lt A, mul_comm] at B, have : (nnnorm (p n) ^ (1 / (n : ℝ)) * r) ^ n ≤ 1 := pow_le_one n (zero_le (nnnorm (p n) ^ (1 / ↑n) * r)) (le_of_lt B), rw [mul_pow, one_div_eq_inv, nnreal.rpow_nat_inv_pow_nat _ (lt_of_le_of_lt (zero_le _) hn)] at this, exact le_trans this (le_max_right _ _) }, end /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` tends to zero exponentially. -/ lemma geometric_bound_of_lt_radius (p : formal_multilinear_series 𝕜 E F) {r : nnreal} (h : (r : ennreal) < p.radius) : ∃ a C, a < 1 ∧ ∀ n, nnnorm (p n) * r^n ≤ C * a^n := begin obtain ⟨t, rt, tp⟩ : ∃ (t : nnreal), (r : ennreal) < t ∧ (t : ennreal) < p.radius := ennreal.lt_iff_exists_nnreal_btwn.1 h, rw ennreal.coe_lt_coe at rt, have tpos : t ≠ 0 := ne_of_gt (lt_of_le_of_lt (zero_le _) rt), obtain ⟨C, hC⟩ : ∃ (C : nnreal), ∀ n, nnnorm (p n) * t^n ≤ C := p.bound_of_lt_radius tp, refine ⟨r / t, C, nnreal.div_lt_one_of_lt rt, λ n, _⟩, calc nnnorm (p n) * r ^ n = (nnnorm (p n) * t ^ n) * (r / t) ^ n : by { field_simp [tpos], ac_refl } ... ≤ C * (r / t) ^ n : mul_le_mul_of_nonneg_right (hC n) (zero_le _) end /-- The radius of the sum of two formal series is at least the minimum of their two radii. -/ lemma min_radius_le_radius_add (p q : formal_multilinear_series 𝕜 E F) : min p.radius q.radius ≤ (p + q).radius := begin refine le_of_forall_ge_of_dense (λ r hr, _), cases r, { simpa using hr }, obtain ⟨Cp, hCp⟩ : ∃ (C : nnreal), ∀ n, nnnorm (p n) * r^n ≤ C := p.bound_of_lt_radius (lt_of_lt_of_le hr (min_le_left _ _)), obtain ⟨Cq, hCq⟩ : ∃ (C : nnreal), ∀ n, nnnorm (q n) * r^n ≤ C := q.bound_of_lt_radius (lt_of_lt_of_le hr (min_le_right _ _)), have : ∀ n, nnnorm ((p + q) n) * r^n ≤ Cp + Cq, { assume n, calc nnnorm (p n + q n) * r ^ n ≤ (nnnorm (p n) + nnnorm (q n)) * r ^ n : mul_le_mul_of_nonneg_right (norm_add_le (p n) (q n)) (zero_le (r ^ n)) ... ≤ Cp + Cq : by { rw add_mul, exact add_le_add (hCp n) (hCq n) } }, exact (p + q).le_radius_of_bound _ this end lemma radius_neg (p : formal_multilinear_series 𝕜 E F) : (-p).radius = p.radius := by simp [formal_multilinear_series.radius, nnnorm_neg] /-- Given a formal multilinear series `p` and a vector `x`, then `p.sum x` is the sum `Σ pₙ xⁿ`. A priori, it only behaves well when `∥x∥ < p.radius`. -/ protected def sum (p : formal_multilinear_series 𝕜 E F) (x : E) : F := tsum (λn:ℕ, p n (λ(i : fin n), x)) /-- Given a formal multilinear series `p` and a vector `x`, then `p.partial_sum n x` is the sum `Σ pₖ xᵏ` for `k ∈ {0,..., n-1}`. -/ def partial_sum (p : formal_multilinear_series 𝕜 E F) (n : ℕ) (x : E) : F := (finset.range n).sum (λ k, p k (λ(i : fin k), x)) /-- The partial sums of a formal multilinear series are continuous. -/ lemma partial_sum_continuous (p : formal_multilinear_series 𝕜 E F) (n : ℕ) : continuous (p.partial_sum n) := continuous_finset_sum (finset.range n) $ λ k hk, (p k).cont.comp (continuous_pi (λ i, continuous_id)) end formal_multilinear_series /-! ### Expanding a function as a power series -/ section variables {f g : E → F} {p pf pg : formal_multilinear_series 𝕜 E F} {x : E} {r r' : ennreal} /-- Given a function `f : E → F` and a formal multilinear series `p`, we say that `f` has `p` as a power series on the ball of radius `r > 0` around `x` if `f (x + y) = ∑' pₙ yⁿ` for all `∥y∥ < r`. -/ structure has_fpower_series_on_ball (f : E → F) (p : formal_multilinear_series 𝕜 E F) (x : E) (r : ennreal) : Prop := (r_le : r ≤ p.radius) (r_pos : 0 < r) (has_sum : ∀ {y}, y ∈ emetric.ball (0 : E) r → has_sum (λn:ℕ, p n (λ(i : fin n), y)) (f (x + y))) /-- Given a function `f : E → F` and a formal multilinear series `p`, we say that `f` has `p` as a power series around `x` if `f (x + y) = ∑' pₙ yⁿ` for all `y` in a neighborhood of `0`. -/ def has_fpower_series_at (f : E → F) (p : formal_multilinear_series 𝕜 E F) (x : E) := ∃ r, has_fpower_series_on_ball f p x r variable (𝕜) /-- Given a function `f : E → F`, we say that `f` is analytic at `x` if it admits a convergent power series expansion around `x`. -/ def analytic_at (f : E → F) (x : E) := ∃ (p : formal_multilinear_series 𝕜 E F), has_fpower_series_at f p x variable {𝕜} lemma has_fpower_series_on_ball.has_fpower_series_at (hf : has_fpower_series_on_ball f p x r) : has_fpower_series_at f p x := ⟨r, hf⟩ lemma has_fpower_series_at.analytic_at (hf : has_fpower_series_at f p x) : analytic_at 𝕜 f x := ⟨p, hf⟩ lemma has_fpower_series_on_ball.analytic_at (hf : has_fpower_series_on_ball f p x r) : analytic_at 𝕜 f x := hf.has_fpower_series_at.analytic_at lemma has_fpower_series_on_ball.radius_pos (hf : has_fpower_series_on_ball f p x r) : 0 < p.radius := lt_of_lt_of_le hf.r_pos hf.r_le lemma has_fpower_series_at.radius_pos (hf : has_fpower_series_at f p x) : 0 < p.radius := let ⟨r, hr⟩ := hf in hr.radius_pos lemma has_fpower_series_on_ball.mono (hf : has_fpower_series_on_ball f p x r) (r'_pos : 0 < r') (hr : r' ≤ r) : has_fpower_series_on_ball f p x r' := ⟨le_trans hr hf.1, r'_pos, λ y hy, hf.has_sum (emetric.ball_subset_ball hr hy)⟩ lemma has_fpower_series_on_ball.add (hf : has_fpower_series_on_ball f pf x r) (hg : has_fpower_series_on_ball g pg x r) : has_fpower_series_on_ball (f + g) (pf + pg) x r := { r_le := le_trans (le_min_iff.2 ⟨hf.r_le, hg.r_le⟩) (pf.min_radius_le_radius_add pg), r_pos := hf.r_pos, has_sum := λ y hy, (hf.has_sum hy).add (hg.has_sum hy) } lemma has_fpower_series_at.add (hf : has_fpower_series_at f pf x) (hg : has_fpower_series_at g pg x) : has_fpower_series_at (f + g) (pf + pg) x := begin rcases hf with ⟨rf, hrf⟩, rcases hg with ⟨rg, hrg⟩, have P : 0 < min rf rg, by simp [hrf.r_pos, hrg.r_pos], exact ⟨min rf rg, (hrf.mono P (min_le_left _ _)).add (hrg.mono P (min_le_right _ _))⟩ end lemma analytic_at.add (hf : analytic_at 𝕜 f x) (hg : analytic_at 𝕜 g x) : analytic_at 𝕜 (f + g) x := let ⟨pf, hpf⟩ := hf, ⟨qf, hqf⟩ := hg in (hpf.add hqf).analytic_at lemma has_fpower_series_on_ball.neg (hf : has_fpower_series_on_ball f pf x r) : has_fpower_series_on_ball (-f) (-pf) x r := { r_le := by { rw pf.radius_neg, exact hf.r_le }, r_pos := hf.r_pos, has_sum := λ y hy, (hf.has_sum hy).neg } lemma has_fpower_series_at.neg (hf : has_fpower_series_at f pf x) : has_fpower_series_at (-f) (-pf) x := let ⟨rf, hrf⟩ := hf in hrf.neg.has_fpower_series_at lemma analytic_at.neg (hf : analytic_at 𝕜 f x) : analytic_at 𝕜 (-f) x := let ⟨pf, hpf⟩ := hf in hpf.neg.analytic_at lemma has_fpower_series_on_ball.sub (hf : has_fpower_series_on_ball f pf x r) (hg : has_fpower_series_on_ball g pg x r) : has_fpower_series_on_ball (f - g) (pf - pg) x r := hf.add hg.neg lemma has_fpower_series_at.sub (hf : has_fpower_series_at f pf x) (hg : has_fpower_series_at g pg x) : has_fpower_series_at (f - g) (pf - pg) x := hf.add hg.neg lemma analytic_at.sub (hf : analytic_at 𝕜 f x) (hg : analytic_at 𝕜 g x) : analytic_at 𝕜 (f - g) x := hf.add hg.neg lemma has_fpower_series_on_ball.coeff_zero (hf : has_fpower_series_on_ball f pf x r) (v : fin 0 → E) : pf 0 v = f x := begin have v_eq : v = (λ i, 0), by { ext i, apply fin_zero_elim i }, have zero_mem : (0 : E) ∈ emetric.ball (0 : E) r, by simp [hf.r_pos], have : ∀ i ≠ 0, pf i (λ j, 0) = 0, { assume i hi, have : 0 < i := bot_lt_iff_ne_bot.mpr hi, apply continuous_multilinear_map.map_coord_zero _ (⟨0, this⟩ : fin i), refl }, have A := has_sum_unique (hf.has_sum zero_mem) (has_sum_single _ this), simpa [v_eq] using A.symm, end lemma has_fpower_series_at.coeff_zero (hf : has_fpower_series_at f pf x) (v : fin 0 → E) : pf 0 v = f x := let ⟨rf, hrf⟩ := hf in hrf.coeff_zero v /-- If a function admits a power series expansion, then it is exponentially close to the partial sums of this power series on strict subdisks of the disk of convergence. -/ lemma has_fpower_series_on_ball.uniform_geometric_approx {r' : nnreal} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ennreal) < r) : ∃ (a C : nnreal), a < 1 ∧ (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * a ^ n) := begin obtain ⟨a, C, ha, hC⟩ : ∃ a C, a < 1 ∧ ∀ n, nnnorm (p n) * r' ^n ≤ C * a^n := p.geometric_bound_of_lt_radius (lt_of_lt_of_le h hf.r_le), refine ⟨a, C / (1 - a), ha, λ y hy n, _⟩, have yr' : ∥y∥ < r', by { rw ball_0_eq at hy, exact hy }, have : y ∈ emetric.ball (0 : E) r, { rw [emetric.mem_ball, edist_eq_coe_nnnorm], apply lt_trans _ h, rw [ennreal.coe_lt_coe, ← nnreal.coe_lt_coe], exact yr' }, simp only [nnreal.coe_sub (le_of_lt ha), nnreal.coe_sub, nnreal.coe_div, nnreal.coe_one], rw [← dist_eq_norm, dist_comm, dist_eq_norm, ← mul_div_right_comm], apply norm_sub_le_of_geometric_bound_of_has_sum ha _ (hf.has_sum this), assume n, calc ∥(p n) (λ (i : fin n), y)∥ ≤ ∥p n∥ * (finset.univ.prod (λ i : fin n, ∥y∥)) : continuous_multilinear_map.le_op_norm _ _ ... = nnnorm (p n) * (nnnorm y)^n : by simp ... ≤ nnnorm (p n) * r' ^ n : mul_le_mul_of_nonneg_left (pow_le_pow_of_le_left (nnreal.coe_nonneg _) (le_of_lt yr') _) (nnreal.coe_nonneg _) ... ≤ C * a ^ n : by exact_mod_cast hC n, end /-- If a function admits a power series expansion at `x`, then it is the uniform limit of the partial sums of this power series on strict subdisks of the disk of convergence, i.e., `f (x + y)` is the uniform limit of `p.partial_sum n y` there. -/ lemma has_fpower_series_on_ball.tendsto_uniformly_on {r' : nnreal} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ennreal) < r) : tendsto_uniformly_on (λ n y, p.partial_sum n y) (λ y, f (x + y)) at_top (metric.ball (0 : E) r') := begin rcases hf.uniform_geometric_approx h with ⟨a, C, ha, hC⟩, refine metric.tendsto_uniformly_on_iff.2 (λ ε εpos, _), have L : tendsto (λ n, (C : ℝ) * a^n) at_top (𝓝 ((C : ℝ) * 0)) := tendsto_const_nhds.mul (tendsto_pow_at_top_nhds_0_of_lt_1 (a.2) ha), rw mul_zero at L, apply ((tendsto_order.1 L).2 ε εpos).mono (λ n hn, _), assume y hy, rw dist_eq_norm, exact lt_of_le_of_lt (hC y hy n) hn end /-- If a function admits a power series expansion at `x`, then it is the locally uniform limit of the partial sums of this power series on the disk of convergence, i.e., `f (x + y)` is the locally uniform limit of `p.partial_sum n y` there. -/ lemma has_fpower_series_on_ball.tendsto_locally_uniformly_on (hf : has_fpower_series_on_ball f p x r) : tendsto_locally_uniformly_on (λ n y, p.partial_sum n y) (λ y, f (x + y)) at_top (emetric.ball (0 : E) r) := begin assume u hu x hx, rcases ennreal.lt_iff_exists_nnreal_btwn.1 hx with ⟨r', xr', hr'⟩, have : emetric.ball (0 : E) r' ∈ 𝓝 x := mem_nhds_sets emetric.is_open_ball xr', refine ⟨emetric.ball (0 : E) r', mem_nhds_within_of_mem_nhds this, _⟩, simpa [metric.emetric_ball_nnreal] using hf.tendsto_uniformly_on hr' u hu end /-- If a function admits a power series expansion at `x`, then it is the uniform limit of the partial sums of this power series on strict subdisks of the disk of convergence, i.e., `f y` is the uniform limit of `p.partial_sum n (y - x)` there. -/ lemma has_fpower_series_on_ball.tendsto_uniformly_on' {r' : nnreal} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ennreal) < r) : tendsto_uniformly_on (λ n y, p.partial_sum n (y - x)) f at_top (metric.ball (x : E) r') := begin convert (hf.tendsto_uniformly_on h).comp (λ y, y - x), { ext z, simp }, { ext z, simp [dist_eq_norm] } end /-- If a function admits a power series expansion at `x`, then it is the locally uniform limit of the partial sums of this power series on the disk of convergence, i.e., `f y` is the locally uniform limit of `p.partial_sum n (y - x)` there. -/ lemma has_fpower_series_on_ball.tendsto_locally_uniformly_on' (hf : has_fpower_series_on_ball f p x r) : tendsto_locally_uniformly_on (λ n y, p.partial_sum n (y - x)) f at_top (emetric.ball (x : E) r) := begin have A : continuous_on (λ (y : E), y - x) (emetric.ball (x : E) r) := (continuous_id.sub continuous_const).continuous_on, convert (hf.tendsto_locally_uniformly_on).comp (λ (y : E), y - x) _ A, { ext z, simp }, { assume z, simp [edist_eq_coe_nnnorm, edist_eq_coe_nnnorm_sub] } end /-- If a function admits a power series expansion on a disk, then it is continuous there. -/ lemma has_fpower_series_on_ball.continuous_on (hf : has_fpower_series_on_ball f p x r) : continuous_on f (emetric.ball x r) := begin apply hf.tendsto_locally_uniformly_on'.continuous_on _ at_top_ne_bot, exact λ n, ((p.partial_sum_continuous n).comp (continuous_id.sub continuous_const)).continuous_on end lemma has_fpower_series_at.continuous_at (hf : has_fpower_series_at f p x) : continuous_at f x := let ⟨r, hr⟩ := hf in hr.continuous_on.continuous_at (emetric.ball_mem_nhds x (hr.r_pos)) lemma analytic_at.continuous_at (hf : analytic_at 𝕜 f x) : continuous_at f x := let ⟨p, hp⟩ := hf in hp.continuous_at /-- In a complete space, the sum of a converging power series `p` admits `p` as a power series. This is not totally obvious as we need to check the convergence of the series. -/ lemma formal_multilinear_series.has_fpower_series_on_ball [complete_space F] (p : formal_multilinear_series 𝕜 E F) (h : 0 < p.radius) : has_fpower_series_on_ball p.sum p 0 p.radius := { r_le := le_refl _, r_pos := h, has_sum := λ y hy, begin rw zero_add, replace hy : (nnnorm y : ennreal) < p.radius, by { convert hy, exact (edist_eq_coe_nnnorm _).symm }, obtain ⟨a, C, ha, hC⟩ : ∃ a C, a < 1 ∧ ∀ n, nnnorm (p n) * (nnnorm y)^n ≤ C * a^n := p.geometric_bound_of_lt_radius hy, refine (summable_of_norm_bounded (λ n, (C : ℝ) * a ^ n) ((summable_geometric_of_lt_1 a.2 ha).mul_left _) (λ n, _)).has_sum, calc ∥(p n) (λ (i : fin n), y)∥ ≤ ∥p n∥ * (finset.univ.prod (λ i : fin n, ∥y∥)) : continuous_multilinear_map.le_op_norm _ _ ... = nnnorm (p n) * (nnnorm y)^n : by simp ... ≤ C * a ^ n : by exact_mod_cast hC n end } lemma has_fpower_series_on_ball.sum [complete_space F] (h : has_fpower_series_on_ball f p x r) {y : E} (hy : y ∈ emetric.ball (0 : E) r) : f (x + y) = p.sum y := begin have A := h.has_sum hy, have B := (p.has_fpower_series_on_ball h.radius_pos).has_sum (lt_of_lt_of_le hy h.r_le), simpa using has_sum_unique A B end /-- The sum of a converging power series is continuous in its disk of convergence. -/ lemma formal_multilinear_series.continuous_on [complete_space F] : continuous_on p.sum (emetric.ball 0 p.radius) := begin by_cases h : 0 < p.radius, { exact (p.has_fpower_series_on_ball h).continuous_on }, { simp at h, simp [h, continuous_on_empty] } end end /-! ### Changing origin in a power series If a function is analytic in a disk `D(x, R)`, then it is analytic in any disk contained in that one. Indeed, one can write $$ f (x + y + z) = \sum_{n} p_n (y + z)^n = \sum_{n, k} \choose n k p_n y^{n-k} z^k = \sum_{k} (\sum_{n} \choose n k p_n y^{n-k}) z^k. $$ The corresponding power series has thus a `k`-th coefficient equal to `\sum_{n} \choose n k p_n y^{n-k}`. In the general case where `pₙ` is a multilinear map, this has to be interpreted suitably: instead of having a binomial coefficient, one should sum over all possible subsets `s` of `fin n` of cardinal `k`, and attribute `z` to the indices in `s` and `y` to the indices outside of `s`. In this paragraph, we implement this. The new power series is called `p.change_origin y`. Then, we check its convergence and the fact that its sum coincides with the original sum. The outcome of this discussion is that the set of points where a function is analytic is open. -/ namespace formal_multilinear_series variables (p : formal_multilinear_series 𝕜 E F) {x y : E} {r : nnreal} /-- Changing the origin of a formal multilinear series `p`, so that `p.sum (x+y) = (p.change_origin x).sum y` when this makes sense. Here, we don't use the bracket notation `⟨n, s, hs⟩` in place of the argument `i` in the lambda, as this leads to a bad definition with auxiliary `_match` statements, but we will try to use pattern matching in lambdas as much as possible in the proofs below to increase readability. -/ def change_origin (x : E) : formal_multilinear_series 𝕜 E F := λ k, tsum (λi, (p i.1).restr i.2.1 i.2.2 x : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → (E [×k]→L[𝕜] F)) /-- Auxiliary lemma controlling the summability of the sequence appearing in the definition of `p.change_origin`, first version. -/ -- Note here and below it is necessary to use `@` and provide implicit arguments using `_`, -- so that it is possible to use pattern matching in the lambda. -- Overall this seems a good trade-off in readability. lemma change_origin_summable_aux1 (h : (nnnorm x + r : ennreal) < p.radius) : @summable ℝ _ _ _ ((λ ⟨n, s⟩, ∥p n∥ * ∥x∥ ^ (n - s.card) * r ^ s.card) : (Σ (n : ℕ), finset (fin n)) → ℝ) := begin obtain ⟨a, C, ha, hC⟩ : ∃ a C, a < 1 ∧ ∀ n, nnnorm (p n) * (nnnorm x + r) ^ n ≤ C * a^n := p.geometric_bound_of_lt_radius h, let Bnnnorm : (Σ (n : ℕ), finset (fin n)) → nnreal := λ ⟨n, s⟩, nnnorm (p n) * (nnnorm x) ^ (n - s.card) * r ^ s.card, have : ((λ ⟨n, s⟩, ∥p n∥ * ∥x∥ ^ (n - s.card) * r ^ s.card) : (Σ (n : ℕ), finset (fin n)) → ℝ) = (λ b, (Bnnnorm b : ℝ)), by { ext b, rcases b with ⟨n, s⟩, simp [Bnnnorm, nnreal.coe_pow, coe_nnnorm] }, rw [this, nnreal.summable_coe, ← ennreal.tsum_coe_ne_top_iff_summable], apply ne_of_lt, calc (∑' b, ↑(Bnnnorm b)) = (∑' n, (∑' s, ↑(Bnnnorm ⟨n, s⟩))) : by exact ennreal.tsum_sigma' _ ... ≤ (∑' n, (((nnnorm (p n) * (nnnorm x + r)^n) : nnreal) : ennreal)) : begin refine ennreal.tsum_le_tsum (λ n, _), rw [tsum_fintype, ← ennreal.coe_finset_sum, ennreal.coe_le_coe], apply le_of_eq, calc finset.univ.sum (λ (s : finset (fin n)), Bnnnorm ⟨n, s⟩) = finset.univ.sum (λ (s : finset (fin n)), nnnorm (p n) * ((nnnorm x) ^ (n - s.card) * r ^ s.card)) : by simp [← mul_assoc] ... = nnnorm (p n) * (nnnorm x + r) ^ n : by { rw [add_comm, ← finset.mul_sum, ← fin.sum_pow_mul_eq_add_pow], congr, ext s, ring } end ... ≤ (∑' (n : ℕ), (C * a ^ n : ennreal)) : tsum_le_tsum (λ n, by exact_mod_cast hC n) ennreal.summable ennreal.summable ... < ⊤ : by simp [ennreal.mul_eq_top, ha, ennreal.tsum_mul_left, ennreal.tsum_geometric, ennreal.lt_top_iff_ne_top] end /-- Auxiliary lemma controlling the summability of the sequence appearing in the definition of `p.change_origin`, second version. -/ lemma change_origin_summable_aux2 (h : (nnnorm x + r : ennreal) < p.radius) : @summable ℝ _ _ _ ((λ ⟨k, n, s, hs⟩, ∥(p n).restr s hs x∥ * ↑r ^ k) : (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ) := begin let γ : ℕ → Type* := λ k, (Σ (n : ℕ), {s : finset (fin n) // s.card = k}), let Bnorm : (Σ (n : ℕ), finset (fin n)) → ℝ := λ ⟨n, s⟩, ∥p n∥ * ∥x∥ ^ (n - s.card) * r ^ s.card, have SBnorm : summable Bnorm := p.change_origin_summable_aux1 h, let Anorm : (Σ (n : ℕ), finset (fin n)) → ℝ := λ ⟨n, s⟩, ∥(p n).restr s rfl x∥ * r ^ s.card, have SAnorm : summable Anorm, { refine summable_of_norm_bounded _ SBnorm (λ i, _), rcases i with ⟨n, s⟩, suffices H : ∥(p n).restr s rfl x∥ * (r : ℝ) ^ s.card ≤ (∥p n∥ * ∥x∥ ^ (n - finset.card s) * r ^ s.card), { have : ∥(r: ℝ)∥ = r, by rw [real.norm_eq_abs, abs_of_nonneg (nnreal.coe_nonneg _)], simpa [Anorm, Bnorm, this] using H }, exact mul_le_mul_of_nonneg_right ((p n).norm_restr s rfl x) (pow_nonneg (nnreal.coe_nonneg _) _) }, let e : (Σ (n : ℕ), finset (fin n)) ≃ (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // finset.card s = k}) := { to_fun := λ ⟨n, s⟩, ⟨s.card, n, s, rfl⟩, inv_fun := λ ⟨k, n, s, hs⟩, ⟨n, s⟩, left_inv := λ ⟨n, s⟩, rfl, right_inv := λ ⟨k, n, s, hs⟩, by { induction hs, refl } }, rw ← e.summable_iff, convert SAnorm, ext i, rcases i with ⟨n, s⟩, refl end /-- An auxiliary definition for `change_origin_radius`. -/ def change_origin_summable_aux_j (k : ℕ) : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // finset.card s = k}) := λ ⟨n, s, hs⟩, ⟨k, n, s, hs⟩ lemma change_origin_summable_aux_j_inj (k : ℕ) : function.injective (change_origin_summable_aux_j k) := begin rintros ⟨_, ⟨_, _⟩⟩ ⟨_, ⟨_, _⟩⟩ a, simp only [change_origin_summable_aux_j, true_and, eq_self_iff_true, heq_iff_eq, sigma.mk.inj_iff] at a, rcases a with ⟨rfl, a⟩, simpa using a, end /-- Auxiliary lemma controlling the summability of the sequence appearing in the definition of `p.change_origin`, third version. -/ lemma change_origin_summable_aux3 (k : ℕ) (h : (nnnorm x : ennreal) < p.radius) : @summable ℝ _ _ _ (λ ⟨n, s, hs⟩, ∥(p n).restr s hs x∥ : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ) := begin obtain ⟨r, rpos, hr⟩ : ∃ (r : nnreal), 0 < r ∧ ((nnnorm x + r) : ennreal) < p.radius := ennreal.lt_iff_exists_add_pos_lt.mp h, have S : @summable ℝ _ _ _ ((λ ⟨n, s, hs⟩, ∥(p n).restr s hs x∥ * (r : ℝ) ^ k) : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ), { convert summable.summable_comp_of_injective (p.change_origin_summable_aux2 hr) (change_origin_summable_aux_j_inj k), -- again, cleanup that could be done by `tidy`: ext p, rcases p with ⟨_, ⟨_, _⟩⟩, refl }, have : (r : ℝ)^k ≠ 0, by simp [pow_ne_zero, nnreal.coe_eq_zero, ne_of_gt rpos], apply (summable_mul_right_iff this).2, convert S, -- again, cleanup that could be done by `tidy`: ext p, rcases p with ⟨_, ⟨_, _⟩⟩, refl, end /-- The radius of convergence of `p.change_origin x` is at least `p.radius - ∥x∥`. In other words, `p.change_origin x` is well defined on the largest ball contained in the original ball of convergence.-/ lemma change_origin_radius : p.radius - nnnorm x ≤ (p.change_origin x).radius := begin by_cases h : p.radius ≤ nnnorm x, { have : radius p - ↑(nnnorm x) = 0 := ennreal.sub_eq_zero_of_le h, rw this, exact zero_le _ }, replace h : (nnnorm x : ennreal) < p.radius, by simpa using h, refine le_of_forall_ge_of_dense (λ r hr, _), cases r, { simpa using hr }, rw [ennreal.lt_sub_iff_add_lt, add_comm] at hr, let A : (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ := λ ⟨k, n, s, hs⟩, ∥(p n).restr s hs x∥ * (r : ℝ) ^ k, have SA : summable A := p.change_origin_summable_aux2 hr, have A_nonneg : ∀ i, 0 ≤ A i, { rintros ⟨k, n, s, hs⟩, change 0 ≤ ∥(p n).restr s hs x∥ * (r : ℝ) ^ k, refine mul_nonneg' (norm_nonneg _) (pow_nonneg (nnreal.coe_nonneg _) _) }, have tsum_nonneg : 0 ≤ tsum A := tsum_nonneg A_nonneg, apply le_radius_of_bound _ (nnreal.of_real (tsum A)) (λ k, _), rw [← nnreal.coe_le_coe, nnreal.coe_mul, nnreal.coe_pow, coe_nnnorm, nnreal.coe_of_real _ tsum_nonneg], calc ∥change_origin p x k∥ * ↑r ^ k = ∥@tsum (E [×k]→L[𝕜] F) _ _ _ (λ i, (p i.1).restr i.2.1 i.2.2 x : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → (E [×k]→L[𝕜] F))∥ * ↑r ^ k : rfl ... ≤ tsum (λ i, ∥(p i.1).restr i.2.1 i.2.2 x∥ : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ) * ↑r ^ k : begin apply mul_le_mul_of_nonneg_right _ (pow_nonneg (nnreal.coe_nonneg _) _), apply norm_tsum_le_tsum_norm, convert p.change_origin_summable_aux3 k h, ext a, tidy end ... = tsum (λ i, ∥(p i.1).restr i.2.1 i.2.2 x∥ * ↑r ^ k : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ) : by { rw tsum_mul_right, convert p.change_origin_summable_aux3 k h, tidy } ... = tsum (A ∘ change_origin_summable_aux_j k) : by { congr, tidy } ... ≤ tsum A : tsum_comp_le_tsum_of_inj SA A_nonneg (change_origin_summable_aux_j_inj k) end -- From this point on, assume that the space is complete, to make sure that series that converge -- in norm also converge in `F`. variable [complete_space F] /-- The `k`-th coefficient of `p.change_origin` is the sum of a summable series. -/ lemma change_origin_has_sum (k : ℕ) (h : (nnnorm x : ennreal) < p.radius) : @has_sum (E [×k]→L[𝕜] F) _ _ _ ((λ i, (p i.1).restr i.2.1 i.2.2 x) : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → (E [×k]→L[𝕜] F)) (p.change_origin x k) := begin apply summable.has_sum, apply summable_of_summable_norm, convert p.change_origin_summable_aux3 k h, tidy end /-- Summing the series `p.change_origin x` at a point `y` gives back `p (x + y)`-/ theorem change_origin_eval (h : (nnnorm x + nnnorm y : ennreal) < p.radius) : has_sum ((λk:ℕ, p.change_origin x k (λ (i : fin k), y))) (p.sum (x + y)) := begin /- The series on the left is a series of series. If we order the terms differently, we get back to `p.sum (x + y)`, in which the `n`-th term is expanded by multilinearity. In the proof below, the term on the left is the sum of a series of terms `A`, the sum on the right is the sum of a series of terms `B`, and we show that they correspond to each other by reordering to conclude the proof. -/ have radius_pos : 0 < p.radius := lt_of_le_of_lt (zero_le _) h, -- `A` is the terms of the series whose sum gives the series for `p.change_origin` let A : (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // s.card = k}) → F := λ ⟨k, n, s, hs⟩, (p n).restr s hs x (λ(i : fin k), y), -- `B` is the terms of the series whose sum gives `p (x + y)`, after expansion by multilinearity. let B : (Σ (n : ℕ), finset (fin n)) → F := λ ⟨n, s⟩, (p n).restr s rfl x (λ (i : fin s.card), y), let Bnorm : (Σ (n : ℕ), finset (fin n)) → ℝ := λ ⟨n, s⟩, ∥p n∥ * ∥x∥ ^ (n - s.card) * ∥y∥ ^ s.card, have SBnorm : summable Bnorm, by convert p.change_origin_summable_aux1 h, have SB : summable B, { refine summable_of_norm_bounded _ SBnorm _, rintros ⟨n, s⟩, calc ∥(p n).restr s rfl x (λ (i : fin s.card), y)∥ ≤ ∥(p n).restr s rfl x∥ * ∥y∥ ^ s.card : begin convert ((p n).restr s rfl x).le_op_norm (λ (i : fin s.card), y), simp [(finset.prod_const (∥y∥))], end ... ≤ (∥p n∥ * ∥x∥ ^ (n - s.card)) * ∥y∥ ^ s.card : mul_le_mul_of_nonneg_right ((p n).norm_restr _ _ _) (pow_nonneg (norm_nonneg _) _) }, -- Check that indeed the sum of `B` is `p (x + y)`. have has_sum_B : has_sum B (p.sum (x + y)), { have K1 : ∀ n, has_sum (λ (s : finset (fin n)), B ⟨n, s⟩) (p n (λ (i : fin n), x + y)), { assume n, have : (p n) (λ (i : fin n), y + x) = finset.univ.sum (λ (s : finset (fin n)), p n (finset.piecewise s (λ (i : fin n), y) (λ (i : fin n), x))) := (p n).map_add_univ (λ i, y) (λ i, x), simp [add_comm y x] at this, rw this, exact has_sum_fintype _ }, have K2 : has_sum (λ (n : ℕ), (p n) (λ (i : fin n), x + y)) (p.sum (x + y)), { have : x + y ∈ emetric.ball (0 : E) p.radius, { apply lt_of_le_of_lt _ h, rw [edist_eq_coe_nnnorm, ← ennreal.coe_add, ennreal.coe_le_coe], exact norm_add_le x y }, simpa using (p.has_fpower_series_on_ball radius_pos).has_sum this }, exact has_sum.sigma_of_has_sum K2 K1 SB }, -- Deduce that the sum of `A` is also `p (x + y)`, as the terms `A` and `B` are the same up to -- reordering have has_sum_A : has_sum A (p.sum (x + y)), { let e : (Σ (n : ℕ), finset (fin n)) ≃ (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // finset.card s = k}) := { to_fun := λ ⟨n, s⟩, ⟨s.card, n, s, rfl⟩, inv_fun := λ ⟨k, n, s, hs⟩, ⟨n, s⟩, left_inv := λ ⟨n, s⟩, rfl, right_inv := λ ⟨k, n, s, hs⟩, by { induction hs, refl } }, have : A ∘ e = B, by { ext x, cases x, refl }, rw ← e.has_sum_iff, convert has_sum_B }, -- Summing `A ⟨k, c⟩` with fixed `k` and varying `c` is exactly the `k`-th term in the series -- defining `p.change_origin`, by definition have J : ∀k, has_sum (λ c, A ⟨k, c⟩) (p.change_origin x k (λ(i : fin k), y)), { assume k, have : (nnnorm x : ennreal) < radius p := lt_of_le_of_lt (le_add_right (le_refl _)) h, convert continuous_multilinear_map.has_sum_eval (p.change_origin_has_sum k this) (λ(i : fin k), y), ext i, tidy }, exact has_sum_A.sigma J end end formal_multilinear_series section variables [complete_space F] {f : E → F} {p : formal_multilinear_series 𝕜 E F} {x y : E} {r : ennreal} /-- If a function admits a power series expansion `p` on a ball `B (x, r)`, then it also admits a power series on any subball of this ball (even with a different center), given by `p.change_origin`. -/ theorem has_fpower_series_on_ball.change_origin (hf : has_fpower_series_on_ball f p x r) (h : (nnnorm y : ennreal) < r) : has_fpower_series_on_ball f (p.change_origin y) (x + y) (r - nnnorm y) := { r_le := begin apply le_trans _ p.change_origin_radius, exact ennreal.sub_le_sub hf.r_le (le_refl _) end, r_pos := by simp [h], has_sum := begin assume z hz, have A : (nnnorm y : ennreal) + nnnorm z < r, { have : edist z 0 < r - ↑(nnnorm y) := hz, rwa [edist_eq_coe_nnnorm, ennreal.lt_sub_iff_add_lt, add_comm] at this }, convert p.change_origin_eval (lt_of_lt_of_le A hf.r_le), have : y + z ∈ emetric.ball (0 : E) r := calc edist (y + z) 0 ≤ ↑(nnnorm y) + ↑(nnnorm z) : by { rw [edist_eq_coe_nnnorm, ← ennreal.coe_add, ennreal.coe_le_coe], exact norm_add_le y z } ... < r : A, simpa using hf.sum this end } lemma has_fpower_series_on_ball.analytic_at_of_mem (hf : has_fpower_series_on_ball f p x r) (h : y ∈ emetric.ball x r) : analytic_at 𝕜 f y := begin have : (nnnorm (y - x) : ennreal) < r, by simpa [edist_eq_coe_nnnorm_sub] using h, have := hf.change_origin this, rw [add_sub_cancel'_right] at this, exact this.analytic_at end variables (𝕜 f) lemma is_open_analytic_at : is_open {x | analytic_at 𝕜 f x} := begin rw is_open_iff_forall_mem_open, assume x hx, rcases hx with ⟨p, r, hr⟩, refine ⟨emetric.ball x r, λ y hy, hr.analytic_at_of_mem hy, emetric.is_open_ball, _⟩, simp only [edist_self, emetric.mem_ball, hr.r_pos] end variables {𝕜 f} end
b4ed311ff878858bd4a01a6f50710fe854d1c18e
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/data/finset/basic.lean
1b2f6a2d4409c9ebd74477aa32497b4c5866d1ca
[ "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
28,582
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura, Jeremy Avigad Finite sets. -/ import data.fintype.basic data.nat data.list.perm algebra.binary open nat quot list subtype binary function eq.ops open [decl] perm definition nodup_list (A : Type) := {l : list A | nodup l} variable {A : Type} definition to_nodup_list_of_nodup {l : list A} (n : nodup l) : nodup_list A := tag l n definition to_nodup_list [decidable_eq A] (l : list A) : nodup_list A := @to_nodup_list_of_nodup A (erase_dup l) (nodup_erase_dup l) private definition eqv (l₁ l₂ : nodup_list A) := perm (elt_of l₁) (elt_of l₂) local infix ~ := eqv private definition eqv.refl (l : nodup_list A) : l ~ l := !perm.refl private definition eqv.symm {l₁ l₂ : nodup_list A} : l₁ ~ l₂ → l₂ ~ l₁ := perm.symm private definition eqv.trans {l₁ l₂ l₃ : nodup_list A} : l₁ ~ l₂ → l₂ ~ l₃ → l₁ ~ l₃ := perm.trans definition finset.nodup_list_setoid [instance] (A : Type) : setoid (nodup_list A) := setoid.mk (@eqv A) (mk_equivalence (@eqv A) (@eqv.refl A) (@eqv.symm A) (@eqv.trans A)) definition finset (A : Type) : Type := quot (finset.nodup_list_setoid A) namespace finset -- give finset notation higher priority than set notation, so that it is tried first protected definition prio : num := num.succ std.priority.default definition to_finset_of_nodup (l : list A) (n : nodup l) : finset A := ⟦to_nodup_list_of_nodup n⟧ definition to_finset [decidable_eq A] (l : list A) : finset A := ⟦to_nodup_list l⟧ lemma to_finset_eq_of_nodup [decidable_eq A] {l : list A} (n : nodup l) : to_finset_of_nodup l n = to_finset l := have P : to_nodup_list_of_nodup n = to_nodup_list l, from begin rewrite [↑to_nodup_list, ↑to_nodup_list_of_nodup], congruence, rewrite [erase_dup_eq_of_nodup n] end, quot.sound (eq.subst P !setoid.refl) definition has_decidable_eq [instance] [decidable_eq A] : decidable_eq (finset A) := λ s₁ s₂, quot.rec_on_subsingleton₂ s₁ s₂ (λ l₁ l₂, match decidable_perm (elt_of l₁) (elt_of l₂) with | decidable.inl e := decidable.inl (quot.sound e) | decidable.inr n := decidable.inr (λ e : ⟦l₁⟧ = ⟦l₂⟧, absurd (quot.exact e) n) end) definition mem (a : A) (s : finset A) : Prop := quot.lift_on s (λ l, a ∈ elt_of l) (λ l₁ l₂ (e : l₁ ~ l₂), propext (iff.intro (λ ainl₁, mem_perm e ainl₁) (λ ainl₂, mem_perm (perm.symm e) ainl₂))) infix [priority finset.prio] ∈ := mem notation [priority finset.prio] a ∉ b := ¬ mem a b theorem mem_of_mem_list {a : A} {l : nodup_list A} : a ∈ elt_of l → a ∈ ⟦l⟧ := λ ainl, ainl theorem mem_list_of_mem {a : A} {l : nodup_list A} : a ∈ ⟦l⟧ → a ∈ elt_of l := λ ainl, ainl definition decidable_mem [instance] [h : decidable_eq A] : ∀ (a : A) (s : finset A), decidable (a ∈ s) := λ a s, quot.rec_on_subsingleton s (λ l, match list.decidable_mem a (elt_of l) with | decidable.inl p := decidable.inl (mem_of_mem_list p) | decidable.inr n := decidable.inr (λ p, absurd (mem_list_of_mem p) n) end) theorem mem_to_finset [decidable_eq A] {a : A} {l : list A} : a ∈ l → a ∈ to_finset l := λ ainl, mem_erase_dup ainl theorem mem_to_finset_of_nodup {a : A} {l : list A} (n : nodup l) : a ∈ l → a ∈ to_finset_of_nodup l n := λ ainl, ainl /- extensionality -/ theorem ext {s₁ s₂ : finset A} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ e, quot.sound (perm_ext (has_property l₁) (has_property l₂) e)) /- empty -/ definition empty : finset A := to_finset_of_nodup [] nodup_nil notation [priority finset.prio] `∅` := !empty theorem not_mem_empty [simp] (a : A) : a ∉ ∅ := λ aine : a ∈ ∅, aine theorem mem_empty_iff [simp] (x : A) : x ∈ ∅ ↔ false := iff_false_intro !not_mem_empty theorem mem_empty_eq (x : A) : x ∈ ∅ = false := propext !mem_empty_iff theorem eq_empty_of_forall_not_mem {s : finset A} (H : ∀x, ¬ x ∈ s) : s = ∅ := ext (take x, iff_false_intro (H x)) /- universe -/ definition univ [h : fintype A] : finset A := to_finset_of_nodup (@fintype.elems A h) (@fintype.unique A h) theorem mem_univ [fintype A] (x : A) : x ∈ univ := fintype.complete x theorem mem_univ_eq [fintype A] (x : A) : x ∈ univ = true := propext (iff_true_intro !mem_univ) /- card -/ definition card (s : finset A) : nat := quot.lift_on s (λ l, length (elt_of l)) (λ l₁ l₂ p, length_eq_length_of_perm p) theorem card_empty : card (@empty A) = 0 := rfl lemma ne_empty_of_card_eq_succ {s : finset A} {n : nat} : card s = succ n → s ≠ ∅ := by intros; substvars; contradiction /- insert -/ section insert variable [h : decidable_eq A] include h definition insert (a : A) (s : finset A) : finset A := quot.lift_on s (λ l, to_finset_of_nodup (insert a (elt_of l)) (nodup_insert a (has_property l))) (λ (l₁ l₂ : nodup_list A) (p : l₁ ~ l₂), quot.sound (perm_insert a p)) -- set builder notation notation [priority finset.prio] `'{`:max a:(foldr `, ` (x b, insert x b) ∅) `}`:0 := a theorem mem_insert (a : A) (s : finset A) : a ∈ insert a s := quot.induction_on s (λ l : nodup_list A, mem_to_finset_of_nodup _ !list.mem_insert) theorem mem_insert_of_mem {a : A} {s : finset A} (b : A) : a ∈ s → a ∈ insert b s := quot.induction_on s (λ (l : nodup_list A) (ainl : a ∈ ⟦l⟧), mem_to_finset_of_nodup _ (list.mem_insert_of_mem _ ainl)) theorem eq_or_mem_of_mem_insert {x a : A} {s : finset A} : x ∈ insert a s → x = a ∨ x ∈ s := quot.induction_on s (λ l : nodup_list A, λ H, list.eq_or_mem_of_mem_insert H) theorem mem_of_mem_insert_of_ne {x a : A} {s : finset A} (xin : x ∈ insert a s) : x ≠ a → x ∈ s := or_resolve_right (eq_or_mem_of_mem_insert xin) theorem mem_insert_iff (x a : A) (s : finset A) : x ∈ insert a s ↔ (x = a ∨ x ∈ s) := iff.intro !eq_or_mem_of_mem_insert (or.rec (λH', (eq.substr H' !mem_insert)) !mem_insert_of_mem) theorem mem_insert_eq (x a : A) (s : finset A) : x ∈ insert a s = (x = a ∨ x ∈ s) := propext !mem_insert_iff theorem mem_singleton_iff (x a : A) : x ∈ '{a} ↔ (x = a) := by rewrite [mem_insert_eq, mem_empty_eq, or_false] theorem mem_singleton (a : A) : a ∈ '{a} := mem_insert a ∅ theorem mem_singleton_of_eq {x a : A} (H : x = a) : x ∈ '{a} := by rewrite H; apply mem_insert theorem eq_of_mem_singleton {x a : A} (H : x ∈ '{a}) : x = a := iff.mp !mem_singleton_iff H theorem eq_of_singleton_eq {a b : A} (H : '{a} = '{b}) : a = b := have a ∈ '{b}, by rewrite -H; apply mem_singleton, eq_of_mem_singleton this theorem insert_eq_of_mem {a : A} {s : finset A} (H : a ∈ s) : insert a s = s := ext (λ x, eq.substr (mem_insert_eq x a s) (or_iff_right_of_imp (λH1, eq.substr H1 H))) theorem singleton_ne_empty (a : A) : '{a} ≠ ∅ := begin intro H, apply not_mem_empty a, rewrite -H, apply mem_insert end theorem pair_eq_singleton (a : A) : '{a, a} = '{a} := by rewrite [insert_eq_of_mem !mem_singleton] -- useful in proofs by induction theorem forall_of_forall_insert {P : A → Prop} {a : A} {s : finset A} (H : ∀ x, x ∈ insert a s → P x) : ∀ x, x ∈ s → P x := λ x xs, H x (!mem_insert_of_mem xs) theorem insert.comm (x y : A) (s : finset A) : insert x (insert y s) = insert y (insert x s) := ext (take a, by rewrite [*mem_insert_eq, propext !or.left_comm]) theorem card_insert_of_mem {a : A} {s : finset A} : a ∈ s → card (insert a s) = card s := quot.induction_on s (λ (l : nodup_list A) (ainl : a ∈ ⟦l⟧), list.length_insert_of_mem ainl) theorem card_insert_of_not_mem {a : A} {s : finset A} : a ∉ s → card (insert a s) = card s + 1 := quot.induction_on s (λ (l : nodup_list A) (nainl : a ∉ ⟦l⟧), list.length_insert_of_not_mem nainl) theorem card_insert_le (a : A) (s : finset A) : card (insert a s) ≤ card s + 1 := if H : a ∈ s then by rewrite [card_insert_of_mem H]; apply le_succ else by rewrite [card_insert_of_not_mem H] protected theorem induction [recursor 6] {P : finset A → Prop} (H1 : P empty) (H2 : ∀ ⦃a : A⦄, ∀{s : finset A}, a ∉ s → P s → P (insert a s)) : ∀s, P s := take s, quot.induction_on s (take u, subtype.destruct u (take l, list.induction_on l (assume nodup_l, H1) (take a l', assume IH nodup_al', have aux₁: a ∉ l', from not_mem_of_nodup_cons nodup_al', have e : list.insert a l' = a :: l', from insert_eq_of_not_mem aux₁, have nodup l', from nodup_of_nodup_cons nodup_al', have P (quot.mk (subtype.tag l' this)), from IH this, have P (insert a (quot.mk (subtype.tag l' _))), from H2 aux₁ this, begin revert nodup_al', rewrite [-e], intros, apply this end))) protected theorem induction_on {P : finset A → Prop} (s : finset A) (H1 : P empty) (H2 : ∀ ⦃a : A⦄, ∀ {s : finset A}, a ∉ s → P s → P (insert a s)) : P s := finset.induction H1 H2 s theorem exists_mem_of_ne_empty {s : finset A} : s ≠ ∅ → ∃ a : A, a ∈ s := begin induction s with a s nin ih, {intro h, exact absurd rfl h}, {intro h, existsi a, apply mem_insert} end theorem eq_empty_of_card_eq_zero {s : finset A} (H : card s = 0) : s = ∅ := begin induction s with a s' H1 IH, { reflexivity }, { rewrite (card_insert_of_not_mem H1) at H, apply nat.no_confusion H} end end insert /- erase -/ section erase variable [h : decidable_eq A] include h definition erase (a : A) (s : finset A) : finset A := quot.lift_on s (λ l, to_finset_of_nodup (erase a (elt_of l)) (nodup_erase_of_nodup a (has_property l))) (λ (l₁ l₂ : nodup_list A) (p : l₁ ~ l₂), quot.sound (erase_perm_erase_of_perm a p)) theorem not_mem_erase (a : A) (s : finset A) : a ∉ erase a s := quot.induction_on s (λ l, list.mem_erase_of_nodup _ (has_property l)) theorem card_erase_of_mem {a : A} {s : finset A} : a ∈ s → card (erase a s) = pred (card s) := quot.induction_on s (λ l ainl, list.length_erase_of_mem ainl) theorem card_erase_of_not_mem {a : A} {s : finset A} : a ∉ s → card (erase a s) = card s := quot.induction_on s (λ l nainl, list.length_erase_of_not_mem nainl) theorem erase_empty (a : A) : erase a ∅ = ∅ := rfl theorem ne_of_mem_erase {a b : A} {s : finset A} : b ∈ erase a s → b ≠ a := by intro h beqa; subst b; exact absurd h !not_mem_erase theorem mem_of_mem_erase {a b : A} {s : finset A} : b ∈ erase a s → b ∈ s := quot.induction_on s (λ l bin, mem_of_mem_erase bin) theorem mem_erase_of_ne_of_mem {a b : A} {s : finset A} : a ≠ b → a ∈ s → a ∈ erase b s := quot.induction_on s (λ l n ain, list.mem_erase_of_ne_of_mem n ain) theorem mem_erase_iff (a b : A) (s : finset A) : a ∈ erase b s ↔ a ∈ s ∧ a ≠ b := iff.intro (assume H, and.intro (mem_of_mem_erase H) (ne_of_mem_erase H)) (assume H, mem_erase_of_ne_of_mem (and.right H) (and.left H)) theorem mem_erase_eq (a b : A) (s : finset A) : a ∈ erase b s = (a ∈ s ∧ a ≠ b) := propext !mem_erase_iff open decidable theorem erase_insert {a : A} {s : finset A} : a ∉ s → erase a (insert a s) = s := λ anins, finset.ext (λ b, by_cases (λ beqa : b = a, iff.intro (λ bin, by subst b; exact absurd bin !not_mem_erase) (λ bin, by subst b; contradiction)) (λ bnea : b ≠ a, iff.intro (λ bin, have b ∈ insert a s, from mem_of_mem_erase bin, mem_of_mem_insert_of_ne this bnea) (λ bin, have b ∈ insert a s, from mem_insert_of_mem _ bin, mem_erase_of_ne_of_mem bnea this))) theorem insert_erase {a : A} {s : finset A} : a ∈ s → insert a (erase a s) = s := λ ains, finset.ext (λ b, by_cases (suppose b = a, iff.intro (λ bin, by subst b; assumption) (λ bin, by subst b; apply mem_insert)) (suppose b ≠ a, iff.intro (λ bin, mem_of_mem_erase (mem_of_mem_insert_of_ne bin `b ≠ a`)) (λ bin, mem_insert_of_mem _ (mem_erase_of_ne_of_mem `b ≠ a` bin)))) end erase /- union -/ section union variable [h : decidable_eq A] include h definition union (s₁ s₂ : finset A) : finset A := quot.lift_on₂ s₁ s₂ (λ l₁ l₂, to_finset_of_nodup (list.union (elt_of l₁) (elt_of l₂)) (nodup_union_of_nodup_of_nodup (has_property l₁) (has_property l₂))) (λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound (perm_union p₁ p₂)) infix [priority finset.prio] ∪ := union theorem mem_union_left {a : A} {s₁ : finset A} (s₂ : finset A) : a ∈ s₁ → a ∈ s₁ ∪ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₁, list.mem_union_left _ ainl₁) theorem mem_union_l {a : A} {s₁ : finset A} {s₂ : finset A} : a ∈ s₁ → a ∈ s₁ ∪ s₂ := mem_union_left s₂ theorem mem_union_right {a : A} {s₂ : finset A} (s₁ : finset A) : a ∈ s₂ → a ∈ s₁ ∪ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₂, list.mem_union_right _ ainl₂) theorem mem_union_r {a : A} {s₂ : finset A} {s₁ : finset A} : a ∈ s₂ → a ∈ s₁ ∪ s₂ := mem_union_right s₁ theorem mem_or_mem_of_mem_union {a : A} {s₁ s₂ : finset A} : a ∈ s₁ ∪ s₂ → a ∈ s₁ ∨ a ∈ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₁l₂, list.mem_or_mem_of_mem_union ainl₁l₂) theorem mem_union_iff (a : A) (s₁ s₂ : finset A) : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := iff.intro (λ h, mem_or_mem_of_mem_union h) (λ d, or.elim d (λ i, mem_union_left _ i) (λ i, mem_union_right _ i)) theorem mem_union_eq (a : A) (s₁ s₂ : finset A) : (a ∈ s₁ ∪ s₂) = (a ∈ s₁ ∨ a ∈ s₂) := propext !mem_union_iff theorem union_comm (s₁ s₂ : finset A) : s₁ ∪ s₂ = s₂ ∪ s₁ := ext (λ a, by rewrite [*mem_union_eq]; exact or.comm) theorem union_assoc (s₁ s₂ s₃ : finset A) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := ext (λ a, by rewrite [*mem_union_eq]; exact or.assoc) theorem union_left_comm (s₁ s₂ s₃ : finset A) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := !left_comm union_comm union_assoc s₁ s₂ s₃ theorem union_right_comm (s₁ s₂ s₃ : finset A) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := !right_comm union_comm union_assoc s₁ s₂ s₃ theorem union_self (s : finset A) : s ∪ s = s := ext (λ a, iff.intro (λ ain, or.elim (mem_or_mem_of_mem_union ain) (λ i, i) (λ i, i)) (λ i, mem_union_left _ i)) theorem union_empty (s : finset A) : s ∪ ∅ = s := ext (λ a, iff.intro (suppose a ∈ s ∪ ∅, or.elim (mem_or_mem_of_mem_union this) (λ i, i) (λ i, absurd i !not_mem_empty)) (suppose a ∈ s, mem_union_left _ this)) theorem empty_union (s : finset A) : ∅ ∪ s = s := calc ∅ ∪ s = s ∪ ∅ : union_comm ... = s : union_empty theorem insert_eq (a : A) (s : finset A) : insert a s = '{a} ∪ s := ext (take x, by rewrite [mem_insert_iff, mem_union_iff, mem_singleton_iff]) theorem insert_union (a : A) (s t : finset A) : insert a (s ∪ t) = insert a s ∪ t := by rewrite [insert_eq, insert_eq a s, union_assoc] end union /- inter -/ section inter variable [h : decidable_eq A] include h definition inter (s₁ s₂ : finset A) : finset A := quot.lift_on₂ s₁ s₂ (λ l₁ l₂, to_finset_of_nodup (list.inter (elt_of l₁) (elt_of l₂)) (nodup_inter_of_nodup _ (has_property l₁))) (λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound (perm_inter p₁ p₂)) infix [priority finset.prio] ∩ := inter theorem mem_of_mem_inter_left {a : A} {s₁ s₂ : finset A} : a ∈ s₁ ∩ s₂ → a ∈ s₁ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₁l₂, list.mem_of_mem_inter_left ainl₁l₂) theorem mem_of_mem_inter_right {a : A} {s₁ s₂ : finset A} : a ∈ s₁ ∩ s₂ → a ∈ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₁l₂, list.mem_of_mem_inter_right ainl₁l₂) theorem mem_inter {a : A} {s₁ s₂ : finset A} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₁ ainl₂, list.mem_inter_of_mem_of_mem ainl₁ ainl₂) theorem mem_inter_iff (a : A) (s₁ s₂ : finset A) : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := iff.intro (λ h, and.intro (mem_of_mem_inter_left h) (mem_of_mem_inter_right h)) (λ h, mem_inter (and.elim_left h) (and.elim_right h)) theorem mem_inter_eq (a : A) (s₁ s₂ : finset A) : (a ∈ s₁ ∩ s₂) = (a ∈ s₁ ∧ a ∈ s₂) := propext !mem_inter_iff theorem inter_comm (s₁ s₂ : finset A) : s₁ ∩ s₂ = s₂ ∩ s₁ := ext (λ a, by rewrite [*mem_inter_eq]; exact and.comm) theorem inter_assoc (s₁ s₂ s₃ : finset A) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) := ext (λ a, by rewrite [*mem_inter_eq]; exact and.assoc) theorem inter_left_comm (s₁ s₂ s₃ : finset A) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := !left_comm inter_comm inter_assoc s₁ s₂ s₃ theorem inter_right_comm (s₁ s₂ s₃ : finset A) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := !right_comm inter_comm inter_assoc s₁ s₂ s₃ theorem inter_self (s : finset A) : s ∩ s = s := ext (λ a, iff.intro (λ h, mem_of_mem_inter_right h) (λ h, mem_inter h h)) theorem inter_empty (s : finset A) : s ∩ ∅ = ∅ := ext (λ a, iff.intro (suppose a ∈ s ∩ ∅, absurd (mem_of_mem_inter_right this) !not_mem_empty) (suppose a ∈ ∅, absurd this !not_mem_empty)) theorem empty_inter (s : finset A) : ∅ ∩ s = ∅ := calc ∅ ∩ s = s ∩ ∅ : inter_comm ... = ∅ : inter_empty theorem singleton_inter_of_mem {a : A} {s : finset A} (H : a ∈ s) : '{a} ∩ s = '{a} := ext (take x, begin rewrite [mem_inter_eq, !mem_singleton_iff], exact iff.intro (suppose x = a ∧ x ∈ s, and.left this) (suppose x = a, and.intro this (eq.subst (eq.symm this) H)) end) theorem singleton_inter_of_not_mem {a : A} {s : finset A} (H : a ∉ s) : '{a} ∩ s = ∅ := ext (take x, begin rewrite [mem_inter_eq, !mem_singleton_iff, mem_empty_eq], exact iff.intro (suppose x = a ∧ x ∈ s, H (eq.subst (and.left this) (and.right this))) (false.elim) end) end inter /- distributivity laws -/ section inter variable [h : decidable_eq A] include h theorem inter_distrib_left (s t u : finset A) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := ext (take x, by rewrite [mem_inter_eq, *mem_union_eq, *mem_inter_eq]; apply and.left_distrib) theorem inter_distrib_right (s t u : finset A) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := ext (take x, by rewrite [mem_inter_eq, *mem_union_eq, *mem_inter_eq]; apply and.right_distrib) theorem union_distrib_left (s t u : finset A) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := ext (take x, by rewrite [mem_union_eq, *mem_inter_eq, *mem_union_eq]; apply or.left_distrib) theorem union_distrib_right (s t u : finset A) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := ext (take x, by rewrite [mem_union_eq, *mem_inter_eq, *mem_union_eq]; apply or.right_distrib) end inter /- disjoint -/ -- Mainly for internal use; library will use s₁ ∩ s₂ = ∅. Note that it does not require decidable equality. definition disjoint (s₁ s₂ : finset A) : Prop := quot.lift_on₂ s₁ s₂ (λ l₁ l₂, disjoint (elt_of l₁) (elt_of l₂)) (λ v₁ v₂ w₁ w₂ p₁ p₂, propext (iff.intro (λ d₁ a (ainw₁ : a ∈ elt_of w₁), have a ∈ elt_of v₁, from mem_perm (perm.symm p₁) ainw₁, have a ∉ elt_of v₂, from disjoint_left d₁ this, not_mem_perm p₂ this) (λ d₂ a (ainv₁ : a ∈ elt_of v₁), have a ∈ elt_of w₁, from mem_perm p₁ ainv₁, have a ∉ elt_of w₂, from disjoint_left d₂ this, not_mem_perm (perm.symm p₂) this))) theorem disjoint.elim {s₁ s₂ : finset A} {x : A} : disjoint s₁ s₂ → x ∈ s₁ → x ∈ s₂ → false := quot.induction_on₂ s₁ s₂ (take u₁ u₂, assume H H1 H2, H x H1 H2) theorem disjoint.intro {s₁ s₂ : finset A} : (∀{x : A}, x ∈ s₁ → x ∈ s₂ → false) → disjoint s₁ s₂ := quot.induction_on₂ s₁ s₂ (take u₁ u₂, assume H, H) theorem inter_eq_empty_of_disjoint [h : decidable_eq A] {s₁ s₂ : finset A} (H : disjoint s₁ s₂) : s₁ ∩ s₂ = ∅ := ext (take x, iff_false_intro (assume H1, disjoint.elim H (mem_of_mem_inter_left H1) (mem_of_mem_inter_right H1))) theorem disjoint_of_inter_eq_empty [h : decidable_eq A] {s₁ s₂ : finset A} (H : s₁ ∩ s₂ = ∅) : disjoint s₁ s₂ := disjoint.intro (take x H1 H2, have x ∈ s₁ ∩ s₂, from mem_inter H1 H2, !not_mem_empty (eq.subst H this)) theorem disjoint.comm {s₁ s₂ : finset A} : disjoint s₁ s₂ → disjoint s₂ s₁ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ d, list.disjoint.comm d) theorem inter_eq_empty [h : decidable_eq A] {s₁ s₂ : finset A} (H : ∀x : A, x ∈ s₁ → x ∈ s₂ → false) : s₁ ∩ s₂ = ∅ := inter_eq_empty_of_disjoint (disjoint.intro H) /- subset -/ definition subset (s₁ s₂ : finset A) : Prop := quot.lift_on₂ s₁ s₂ (λ l₁ l₂, sublist (elt_of l₁) (elt_of l₂)) (λ v₁ v₂ w₁ w₂ p₁ p₂, propext (iff.intro (λ s₁ a i, mem_perm p₂ (s₁ a (mem_perm (perm.symm p₁) i))) (λ s₂ a i, mem_perm (perm.symm p₂) (s₂ a (mem_perm p₁ i))))) infix [priority finset.prio] ⊆ := subset theorem empty_subset (s : finset A) : ∅ ⊆ s := quot.induction_on s (λ l, list.nil_sub (elt_of l)) theorem subset_univ [h : fintype A] (s : finset A) : s ⊆ univ := quot.induction_on s (λ l a i, fintype.complete a) theorem subset.refl (s : finset A) : s ⊆ s := quot.induction_on s (λ l, list.sub.refl (elt_of l)) theorem subset.trans {s₁ s₂ s₃ : finset A} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := quot.induction_on₃ s₁ s₂ s₃ (λ l₁ l₂ l₃ h₁ h₂, list.sub.trans h₁ h₂) theorem mem_of_subset_of_mem {s₁ s₂ : finset A} {a : A} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ h₁ h₂, h₁ a h₂) theorem subset.antisymm {s₁ s₂ : finset A} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := ext (take x, iff.intro (assume H, mem_of_subset_of_mem H₁ H) (assume H, mem_of_subset_of_mem H₂ H)) -- alternative name theorem eq_of_subset_of_subset {s₁ s₂ : finset A} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := subset.antisymm H₁ H₂ theorem subset_of_forall {s₁ s₂ : finset A} : (∀x, x ∈ s₁ → x ∈ s₂) → s₁ ⊆ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ H, H) theorem subset_insert [h : decidable_eq A] (s : finset A) (a : A) : s ⊆ insert a s := subset_of_forall (take x, suppose x ∈ s, mem_insert_of_mem _ this) theorem eq_empty_of_subset_empty {x : finset A} (H : x ⊆ ∅) : x = ∅ := subset.antisymm H (empty_subset x) theorem subset_empty_iff (x : finset A) : x ⊆ ∅ ↔ x = ∅ := iff.intro eq_empty_of_subset_empty (take xeq, by rewrite xeq; apply subset.refl ∅) section variable [decA : decidable_eq A] include decA theorem erase_subset_erase (a : A) {s t : finset A} (H : s ⊆ t) : erase a s ⊆ erase a t := begin apply subset_of_forall, intro x, rewrite *mem_erase_eq, intro H', show x ∈ t ∧ x ≠ a, from and.intro (mem_of_subset_of_mem H (and.left H')) (and.right H') end theorem erase_subset (a : A) (s : finset A) : erase a s ⊆ s := begin apply subset_of_forall, intro x, rewrite mem_erase_eq, intro H, apply and.left H end theorem erase_eq_of_not_mem {a : A} {s : finset A} (anins : a ∉ s) : erase a s = s := eq_of_subset_of_subset !erase_subset (subset_of_forall (take x, assume xs : x ∈ s, have x ≠ a, from assume H', anins (eq.subst H' xs), mem_erase_of_ne_of_mem this xs)) theorem erase_insert_subset (a : A) (s : finset A) : erase a (insert a s) ⊆ s := decidable.by_cases (assume ains : a ∈ s, by rewrite [insert_eq_of_mem ains]; apply erase_subset) (assume nains : a ∉ s, by rewrite [!erase_insert nains]; apply subset.refl) theorem erase_subset_of_subset_insert {a : A} {s t : finset A} (H : s ⊆ insert a t) : erase a s ⊆ t := subset.trans (!erase_subset_erase H) !erase_insert_subset theorem insert_erase_subset (a : A) (s : finset A) : s ⊆ insert a (erase a s) := decidable.by_cases (assume ains : a ∈ s, by rewrite [!insert_erase ains]; apply subset.refl) (assume nains : a ∉ s, by rewrite[erase_eq_of_not_mem nains]; apply subset_insert) theorem insert_subset_insert (a : A) {s t : finset A} (H : s ⊆ t) : insert a s ⊆ insert a t := begin apply subset_of_forall, intro x, rewrite *mem_insert_eq, intro H', cases H' with [xeqa, xins], exact (or.inl xeqa), exact (or.inr (mem_of_subset_of_mem H xins)) end theorem subset_insert_of_erase_subset {s t : finset A} {a : A} (H : erase a s ⊆ t) : s ⊆ insert a t := subset.trans (insert_erase_subset a s) (!insert_subset_insert H) theorem subset_insert_iff (s t : finset A) (a : A) : s ⊆ insert a t ↔ erase a s ⊆ t := iff.intro !erase_subset_of_subset_insert !subset_insert_of_erase_subset end /- upto -/ section upto definition upto (n : nat) : finset nat := to_finset_of_nodup (list.upto n) (nodup_upto n) theorem card_upto : ∀ n, card (upto n) = n := list.length_upto theorem lt_of_mem_upto {n a : nat} : a ∈ upto n → a < n := list.lt_of_mem_upto theorem mem_upto_succ_of_mem_upto {n a : nat} : a ∈ upto n → a ∈ upto (succ n) := list.mem_upto_succ_of_mem_upto theorem mem_upto_of_lt {n a : nat} : a < n → a ∈ upto n := list.mem_upto_of_lt theorem mem_upto_iff (a n : nat) : a ∈ upto n ↔ a < n := iff.intro lt_of_mem_upto mem_upto_of_lt theorem mem_upto_eq (a n : nat) : a ∈ upto n = (a < n) := propext !mem_upto_iff end upto theorem upto_zero : upto 0 = ∅ := rfl theorem upto_succ (n : ℕ) : upto (succ n) = upto n ∪ '{n} := begin apply ext, intro x, rewrite [mem_union_iff, *mem_upto_iff, mem_singleton_iff, lt_succ_iff_le, nat.le_iff_lt_or_eq], end /- useful rules for calculations with quantifiers -/ theorem exists_mem_empty_iff {A : Type} (P : A → Prop) : (∃ x, x ∈ ∅ ∧ P x) ↔ false := iff.intro (assume H, obtain x (H1 : x ∈ ∅ ∧ P x), from H, !not_mem_empty (and.left H1)) (assume H, false.elim H) theorem exists_mem_empty_eq {A : Type} (P : A → Prop) : (∃ x, x ∈ ∅ ∧ P x) = false := propext !exists_mem_empty_iff theorem exists_mem_insert_iff {A : Type} [d : decidable_eq A] (a : A) (s : finset A) (P : A → Prop) : (∃ x, x ∈ insert a s ∧ P x) ↔ P a ∨ (∃ x, x ∈ s ∧ P x) := iff.intro (assume H, obtain x [H1 H2], from H, or.elim (eq_or_mem_of_mem_insert H1) (suppose x = a, or.inl (eq.subst this H2)) (suppose x ∈ s, or.inr (exists.intro x (and.intro this H2)))) (assume H, or.elim H (suppose P a, exists.intro a (and.intro !mem_insert this)) (suppose ∃ x, x ∈ s ∧ P x, obtain x [H2 H3], from this, exists.intro x (and.intro (!mem_insert_of_mem H2) H3))) theorem exists_mem_insert_eq {A : Type} [d : decidable_eq A] (a : A) (s : finset A) (P : A → Prop) : (∃ x, x ∈ insert a s ∧ P x) = (P a ∨ (∃ x, x ∈ s ∧ P x)) := propext !exists_mem_insert_iff theorem forall_mem_empty_iff {A : Type} (P : A → Prop) : (∀ x, x ∈ ∅ → P x) ↔ true := iff.intro (assume H, trivial) (assume H, take x, assume H', absurd H' !not_mem_empty) theorem forall_mem_empty_eq {A : Type} (P : A → Prop) : (∀ x, x ∈ ∅ → P x) = true := propext !forall_mem_empty_iff theorem forall_mem_insert_iff {A : Type} [d : decidable_eq A] (a : A) (s : finset A) (P : A → Prop) : (∀ x, x ∈ insert a s → P x) ↔ P a ∧ (∀ x, x ∈ s → P x) := iff.intro (assume H, and.intro (H _ !mem_insert) (take x, assume H', H _ (!mem_insert_of_mem H'))) (assume H, take x, assume H' : x ∈ insert a s, or.elim (eq_or_mem_of_mem_insert H') (suppose x = a, eq.subst (eq.symm this) (and.left H)) (suppose x ∈ s, and.right H _ this)) theorem forall_mem_insert_eq {A : Type} [d : decidable_eq A] (a : A) (s : finset A) (P : A → Prop) : (∀ x, x ∈ insert a s → P x) = (P a ∧ (∀ x, x ∈ s → P x)) := propext !forall_mem_insert_iff end finset
10212cfc5a32b218fa03f168d238d500d7a7c788
54d7e71c3616d331b2ec3845d31deb08f3ff1dea
/tests/lean/structure_instance_bug2.lean
58510fb2f36053cc0f681763ce048cef809ebda9
[ "Apache-2.0" ]
permissive
pachugupta/lean
6f3305c4292288311cc4ab4550060b17d49ffb1d
0d02136a09ac4cf27b5c88361750e38e1f485a1a
refs/heads/master
1,611,110,653,606
1,493,130,117,000
1,493,167,649,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
213
lean
def default_smt_pre_config : smt_pre_config := {} def my_pre_config1 : smt_pre_config := { default_smt_pre_config . zeta := tt } def my_pre_config2 : smt_pre_config := { default_smt_pre_config with zeta := tt }
74860a9af9c86f791144c90a18f3e96ede96f72f
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/fintype/powerset.lean
00d0d0f68ac524a20b47436ab313b2af559b0866
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
2,179
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.fintype.card import data.finset.powerset /-! # fintype instance for `set α`, when `α` is a fintype > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ variables {α : Type*} open finset instance finset.fintype [fintype α] : fintype (finset α) := ⟨univ.powerset, λ x, finset.mem_powerset.2 (finset.subset_univ _)⟩ @[simp] lemma fintype.card_finset [fintype α] : fintype.card (finset α) = 2 ^ (fintype.card α) := finset.card_powerset finset.univ @[simp] lemma finset.powerset_univ [fintype α] : (univ : finset α).powerset = univ := coe_injective $ by simp [-coe_eq_univ] @[simp] lemma finset.powerset_eq_univ [fintype α] {s : finset α} : s.powerset = univ ↔ s = univ := by rw [←finset.powerset_univ, powerset_inj] lemma finset.mem_powerset_len_univ_iff [fintype α] {s : finset α} {k : ℕ} : s ∈ powerset_len k (univ : finset α) ↔ card s = k := mem_powerset_len.trans $ and_iff_right $ subset_univ _ @[simp] lemma finset.univ_filter_card_eq (α : Type*) [fintype α] (k : ℕ) : (finset.univ : finset (finset α)).filter (λ s, s.card = k) = finset.univ.powerset_len k := by { ext, simp [finset.mem_powerset_len] } @[simp] lemma fintype.card_finset_len [fintype α] (k : ℕ) : fintype.card {s : finset α // s.card = k} = nat.choose (fintype.card α) k := by simp [fintype.subtype_card, finset.card_univ] instance set.fintype [fintype α] : fintype (set α) := ⟨(@finset.univ α _).powerset.map ⟨coe, coe_injective⟩, λ s, begin classical, refine mem_map.2 ⟨finset.univ.filter s, mem_powerset.2 (subset_univ _), _⟩, apply (coe_filter _ _).trans, rw [coe_univ, set.sep_univ], refl end⟩ -- Not to be confused with `set.finite`, the predicate instance set.finite' [finite α] : finite (set α) := by { casesI nonempty_fintype α, apply_instance } @[simp] lemma fintype.card_set [fintype α] : fintype.card (set α) = 2 ^ fintype.card α := (finset.card_map _).trans (finset.card_powerset _)
9cbedc33ecf22bb46d06dcc539140638931e5cdc
f98c49f30cbc7120b78f92246f22dedad3f11f62
/lean/book/Logic_and_Proof/LP_04_Propositional_Logic_in_Lean.lean
e7e0d6d3cd703c2e0c730deef738b7c5069a85b3
[ "Unlicense" ]
permissive
haroldcarr/learn-haskell-coq-ml-etc
5a88bbbb0e0f435798ee9cab29d9e9da854174e2
a7247caa22097573cbfa1e95fa81debeb146c12a
refs/heads/master
1,683,755,751,897
1,682,914,556,000
1,682,914,556,000
12,350,346
36
9
null
null
null
null
UTF-8
Lean
false
false
18,894
lean
------------------------------------------------------------------------------ -- 4.1 Expressions for Propositions and Proofs -- Declare variables. variables A B C D : Prop -- Check the type of an expression. #check A ∧ ¬ B → C -- Declare that a hypothesis is true (in this case A ∨ ¬ B). -- Any proposition can be viewed as a type, the type of proof of that proposition. -- A hypothesis, or premise, is just a variable of tyhat type. -- Build proofs by creating expressions of the correct type. variable h₀ : A ∧ ¬ B #check h₀ -- left elimination says A is true #check and.left h₀ -- right elimination says ¬ B is true #check and.right h₀ -- construct ¬ B ∧ A #check and.intro (and.right h₀) (and.left h₀) -- implication-elimination (modus ponens) is application (associates to left) /- A → B A ------------ →E B -/ section example : A ∧ (A → B) → B := λ (h₁ : A ∧ (A → B)) , have h₂ : A , from and.left h₁ , have h₃ : A → B, from and.right h₁ , show B , from h₃ h₂ -- APPLICATION end variable h₁' : A → (B → C) variable h₂' : D → A variable h₃' : D variable h₄' : B #check h₂' h₃' #check h₁' (h₂' h₃') #check (h₁' (h₂' h₃')) h₄' -- Implication-introduction via assume (note: can cancel a hypothesis). /- ----- 1 A . . B ----- 1 →I A → B -/ -- A and B have type Prop -- h is premise that A holds -- P is proof of B, possibly involving h. -- expression 'assume h : A, P' -- proof of A → B -- e.g., proof of A → A ∧ A #check (assume h : A, and.intro h h) -- Above, do no need declare A as a premise. -- 'assume" makes premise local to expression in parens (parens not always needed): #check assume h : A, and.intro h h -- proof of A ∧ ¬ B → ¬ B ∧ A #check (assume h : A ∧ ¬ B, and.intro (and.right h) (and.left h)) -- 'assume' is alternative to lambda #check (λ h : A ∧ ¬ B, and.intro (and.right h) (and.left h)) ------------------------------------------------------------------------------ -- 4.2 More commands -- 'example' says you are proving a theorem of a given type, followed by a proof (an expression) -- Lean type checks the expression. example : A ∧ ¬ B → ¬ B ∧ A := assume h : A ∧ ¬ B, and.intro (and.right h) (and.left h) -- 'example' provides type info, so can omit info, e.g., type of assumption: example : A ∧ ¬ B → ¬ B ∧ A := assume h, and.intro (and.right h) (and.left h) -- Lean knows proving implication with premise A ∧ ¬ B. -- Infers h labels assumption A ∧ ¬ B. -- Can also give more info via 'show'. -- If A is proposition and P is proof, then 'show A, from P' means same thing as P alone, -- but signals intention that P is a proof of A. -- Lean confirms P is a proof of A, before parsing surrounding expression). example : A ∧ ¬ B → ¬ B ∧ A := assume h : A ∧ ¬ B , show ¬ B ∧ A , from and.intro (and.right h) (and.left h) example : A ∧ ¬ B → ¬ B ∧ A := assume h : A ∧ ¬ B , show ¬ B ∧ A , from and.intro (show ¬ B, from and.right h) (show A , from and.left h) -- rather than declare variables and premises, present them as "arguments" example (A B : Prop) : A ∧ ¬ B → ¬ B ∧ A := assume h : A ∧ ¬ B , show ¬ B ∧ A , from and.intro (and.right h) (and.left h) -- SORRY (e.g., like Haskell's 'undefined') -- Provides proof of anything. -- Helps to construct proofs incrementally. example : A ∧ ¬ B → ¬ B ∧ A := assume h, sorry example : A ∧ ¬ B → ¬ B ∧ A := assume h, and.intro sorry sorry example : A ∧ ¬ B → ¬ B ∧ A := assume h, and.intro (and.right h) sorry example : A ∧ ¬ B → ¬ B ∧ A := assume h, and.intro (and.right h) (and.left h) -- PLACEHOLDERS (i.e., "holes") -- UNDERSCORE -- ask Lean to fill in value from the context. -- _ for proof : error msg saying what is missing. -- Helps write proof terms in a backward-driven fashion. -- Above, try replacing 'sorry' by _. -- Delimit scope of variables or premises introduced via 'variables', put them in a block that begins 'section' and ends 'end'. ------------------------------------------------------------------------------ -- 4.3 Building Natural Deduction Proofs -- IMPLICATION -- implication introduction : 'assume' (or lambda) -- implication elimination : application example : A → B := assume h : A, show B, from sorry section variable h₁ : A → B variable h₂ : A example : B := h₁ h₂ end -- CONJUNCTION -- and-introduction : and.intro /- A B ------- ∧I A ∧ B -/ section variables (h₁ : A) (h₂ : B) example : A ∧ B := and.intro h₁ h₂ end -- and-elimination : and.left and.right /- A ∧ B A ∧ B ------- ∧E left ------- ∧E right A B -/ section variable h : A ∧ B example : A := and.left h example : B := and.right h end -- DISJUNCTION -- or-introduction : or.inl or.inr /- A B ----- ∨I left ----- ∨I right A ∨ B A ∨ B -/ section variable h : A example : A ∨ B := or.inl h end section variable h : B example : A ∨ B := or.inr h end -- or-elimination /- --- 1 --- 1 A B . . . . A ∨ B C C ------------------- 1 ∨E C -/ -- prove C from A ∨ B -- need three arguments -- proof h' of A ∨ B -- proof of C from A -- proof of C from B -- Note : can reuse local label h₁ in each branch section variable h' : A ∨ B variables (ha : A → C) (hb : B → C) example : C := or.elim h' (assume h1 : A, show C, from ha h1) (assume h1 : B, show C, from hb h1) end example (A B C : Prop) : C := have h : A ∨ B, from sorry , show C , from or.elim h (assume h₁ : A, show C, from sorry) (assume h₂ : B, show C, from sorry) -- NEGATION -- negation ¬ A is defined by A → false, says A implies something impossible. -- So rules for negation similar to implication. -- To prove ¬ A, assume A and derive a contradiction. -- There is no introduction rule. -- "false" is false. -- There is no way to prove it, other than extract it from contradictory hypotheses. /- A . . ⊥ --- 1 ¬I -- does not exist ¬A -/ section example : ¬ A := assume h : A, show false, from sorry end -- After proving ¬ A, get a contradiction by applying it to a proof of A. -- not-elimination /- ¬A A ------- ¬E ⊥ -/ section variable h₁ : ¬ A variable h₂ : A example : false := h₁ h₂ end -- Can conclude anything from a contradiction. -- "ex falso sequitur quodlibet" : anything you want follows from falsity" /- ⊥ --- ⊥E A -/ -- TRUTH and FALSITY -- false-elimination : ex falso rule : false.elim /- ⊥ --- ⊥E A -/ section variable h' : false example : A := false.elim h' end -- true is true -- true-introduction /- --- ⊤I ⊤ -/ example : true := trivial -- BI-IMPLICATION -- bi-implication-introduction : "if and only if" : iff.intro /- --- 1 --- 1 A B . . . . B A ------------ 1 ↔I A ↔ B -/ example : A ↔ B := iff.intro (assume h : A, show B, from sorry) (assume h : B, show A, from sorry) -- Note h used in scoped branches -- bi-implication elimination iff.elim_left iff.elim_right /- A ↔ B A A ↔ B B ----------- ↔El ----------- ↔Er B A -/ section variable h₁ : A ↔ B variable h₂ : A example : B := iff.elim_left h₁ h₂ end section variable h₁ : A ↔ B variable h₂ : B example : A := iff.elim_right h₁ h₂ end -- abbreviations -- iff.mp for iff.elim_left ("mp" : "modus ponens) -- iff.mpr for iff.elim_right ("modus ponens reverse) -- Reductio ad absurdum (PROOF BY CONTRADICTION) /- ----- 1 ¬A . . ⊥ ----- 1 RAA A -/ -- see Ch 5 for more detail -- by_contradiction -- one arg : proof of false from ¬ A -- enable classical reasoning : open classical section open classical example : A := by_contradiction (assume h : ¬ A, show false, from sorry) end -- EXAMPLES -- TRANSITIVITY /- --- 1 A A → B ------------- B B → C ------------------ C ----- 1 A → C -/ section variable h₁ : A → B variable h₂ : B → C example : A → C := assume h : A , show C , from h₂ (h₁ h) end section variable h₁ : A → B variable h₂ : B → C example : A → C := assume h : A , have h₃ : B, from h₁ h , show C , from h₂ h₃ end /- ------ 1 A ∧ B ------------- 2 ----- ----- A → (B → C) A A ∧ B -------------------- ----- B → C B ---------------------- C ---------- 1 A ∧ B → C ---------------------------- 2 (A → (B → C)) → (A ∧ B → C) -/ example (A B C : Prop) : (A → (B → C)) → (A ∧ B → C) := assume h₁ : A → (B → C) , assume h₂ : A ∧ B , show C , from h₁ (and.left h₂) -- proof of A (and.right h₂) -- proof of B example (A B C : Prop) : (A → (B → C)) → (A ∧ B → C) := assume h₁ : A → (B → C) , assume h₂ : A ∧ B , have h₃ : A, from and.left h₂ , have h₄ : B, from and.right h₂ , show C , from h₁ h₃ h₄ example (A B C : Prop) : (A → (B → C)) → (A ∧ B → C) := assume h₁ : A → (B → C) , assume h₂ : A ∧ B , have h₃ : A , from and.left h₂ , have h₄ : B , from and.right h₂ , have h₅ : B → C, from h₁ h₃ , show C , from h₅ h₄ -- DISTRIBUTION /- ----------- 2 ----------- 2 A ∧ (B ∨ C) A ∧ (B ∨ C) ----------- -- 1 ----------- -- 1 A B A C ----------- 2 -------------- ------------- A ∧ (B ∨ C) A ∧ B A ∧ C ----------- ----------------- ----------------- B ∨ C (A ∧ B) ∨ (A ∧ C) (A ∧ B) ∨ (A ∧ C) -------------------------------------------------- 1 (A ∧ B) ∨ (A ∧ C) ---------------------------------- 2 (A ∧ (B ∨ C) → ((A ∧ B) ∨ (A ∧ C)) -/ -- see or-elimination description to understand example (A B C : Prop) : A ∧ (B ∨ C) → (A ∧ B) ∨ (A ∧ C) := assume h₁ : A ∧ (B ∨ C) , or.elim -- proof of (B ∨ C) (and.right h₁) -- proof of (A ∧ B) ∨ (A ∧ C) ( assume h₂ : B , show (A ∧ B) ∨ (A ∧ C) , from or.inl (and.intro -- A ∧ B (and.left h₁) -- A h₂) ) -- B -- proof of (A ∧ B) ∨ (A ∧ C) ( assume h₂ : C , show (A ∧ B) ∨ (A ∧ C) , from or.inr (and.intro -- A ∧ C (and.left h₁) -- A h₂) ) -- C -- assume is λ -- Lean can infer type of assumption -- so same thing as above example (A B C : Prop) : A ∧ (B ∨ C) → (A ∧ B) ∨ (A ∧ C) := λ h₁, or.elim (and.right h₁) (λ h₂, or.inl (and.intro (and.left h₁) h₂)) (λ h₂, or.inr (and.intro (and.left h₁) h₂)) example (A B C : Prop) : A ∧ (B ∨ C) → (A ∧ B) ∨ (A ∧ C) := assume h₁ : A ∧ (B ∨ C) , have h₂ : A , from and.left h₁ , have h₃ : B ∨ C, from and.right h₁ , show (A ∧ B) ∨ (A ∧ C) , from or.elim h₃ ( assume h₄ : B , have h₅ : A ∧ B, from and.intro h₂ h₄ , show (A ∧ B) ∨ (A ∧ C), from or.inl h₅ ) ( assume h₄ : C , have h₅ : A ∧ C, from and.intro h₂ h₄ , show (A ∧ B) ∨ (A ∧ C), from or.inr h₅ ) ------------------------------------------------------------------------------ -- 4.4 Forward Reasoning via 'have' -- (hc: mixed in with proofs above) -- AND COMMUTES (with 'have') example (A B : Prop) : A ∧ B → B ∧ A := assume h₁ : A ∧ B , have h₂ : A, from and.left h₁ , have h₃ : B, from and.right h₁ , show B ∧ A , from and.intro h₃ h₂ -- AND COMMUTES (better without 'have') example (A B : Prop) : A ∧ B → B ∧ A := assume h₁ : A ∧ B , show B ∧ A , from and.intro (show B, from and.right h₁) (show A, from and.left h₁) -- AMD COMMUTES (better, in this case) example (A B : Prop) : A ∧ B → B ∧ A := λ h, and.intro (and.right h) (and.left h) ------------------------------------------------------------------------------ -- 4.5 Definitions and Theorems -- name DEFINITIONS def triple_and (A B C : Prop) : Prop := A ∧ (B ∧ C) -- for later use, e.g., variables E F G : Prop #check triple_and (D ∨ E) (¬ F → G) (¬ D) def double (n : ℕ) : ℕ := n + n -- name THEOREMS theorem and_commute0 (A B : Prop) : A ∧ B → B ∧ A := assume h, and.intro (and.right h) (and.left h) section variable h₁ : C ∧ ¬ D variable h₂ : ¬ D ∧ C → E example : E := h₂ (and_commute0 C (¬ D) h₁) end -- to obviate giving args C and ¬ D explicitly (because implicit in h₁), use 'implicits' theorem and_commute1 {A B : Prop} : A ∧ B → B ∧ A := assume h, and.intro (and.right h) (and.left h) -- squiggly : args A and B are implicit (Lean infers them) section variable h₁ : C ∧ ¬ D variable h₂ : ¬ D ∧ C → E example : E := h₂ (and_commute1 h₁) end -- avoid 'assume' by making hypothesis into an arg theorem and_commute2 {A B : Prop} (h : A ∧ B) : B ∧ A := and.intro (and.right h) (and.left h) -- NAMESPACE -- Lean’s defines or.resolve_left, or.resolve_right, and absurd. -- Define again without clashing: namespace hidden -- variables {A B : Prop} theorem or_resolve_left (h₁ : A ∨ B) (h₂ : ¬ A) : B := or.elim h₁ (assume h₃ : A, show B, from false.elim (h₂ h₃)) (assume h₃ : B, show B, from h₃) theorem or_resolve_right (h₁ : A ∨ B) (h₂ : ¬ B) : A := or.elim h₁ (assume h₃ : A, show A, from h₃) (assume h₃ : B, show A, from false.elim (h₂ h₃)) theorem absurd (h₁ : ¬ A) (h₂ : A) : B := false.elim (h₁ h₂) end hidden ------------------------------------------------------------------------------ -- 4.6 Additional Syntax (for power users) -- SUBSCRIPTS : h5 : h backslash 5 : h₅ -- OMIT ASSUME LABEL (i.e., "anonymous” hypothesis") -- refer to last anonymous via THIS example : A → A ∨ B := assume : A , show A ∨ B, from or.inl this -- or via French quotes: example : A → B → A ∧ B := assume : A, assume : B, show A ∧ B, from and.intro ‹A› ‹B› -- 'have' without label via THIS and French quotes theorem my_theorem {A B C : Prop} : A ∧ (B ∨ C) → (A ∧ B) ∨ (A ∧ C) := assume h : A ∧ (B ∨ C) , have A , from and.left h , have B ∨ C, from and.right h , show (A ∧ B) ∨ (A ∧ C) , from or.elim ‹B ∨ C› ( assume : B , have A ∧ B, from and.intro ‹A› ‹B› , show (A ∧ B) ∨ (A ∧ C), from or.inl this ) ( assume : C , have A ∧ C, from and.intro ‹A› ‹C› , show (A ∧ B) ∨ (A ∧ C), from or.inr this ) -- AND/OR shorthand -- AND -- h.left h.right instead of and.left h and.right h -- ⟨h1, h2⟩ (using \< and \>) instead of and.intro h1 h2 example (A B : Prop) : A ∧ B → B ∧ A := assume h : A ∧ B, show B ∧ A, from and.intro (and.right h) (and.left h) example (A B : Prop) : A ∧ B → B ∧ A := assume h : A ∧ B, show B ∧ A, from ⟨h.right, h.left⟩ example (A B : Prop) : A ∧ B → B ∧ A := assume h, ⟨h.right, h.left⟩ -- take apart a conjunction with ASSUME example (A B : Prop) : A ∧ B → B ∧ A := assume ⟨h₁, h₂⟩, ⟨h₂, h₁⟩ -- if h is BICONDITIONAL -- h.mp and h.mpr instead of iff.mp h and iff.mpr h -- ⟨h1, h2⟩ instead of iff.intro h1 h2 example (A B : Prop) : B ∧ (A ↔ B) → A := assume ⟨hB, hAB⟩, hAB.mpr hB example (A B : Prop) : A ∧ B ↔ B ∧ A := ⟨ assume ⟨h₁, h₂⟩, ⟨h₂, h₁⟩ , assume ⟨h₁, h₂⟩, ⟨h₂, h₁⟩ ⟩ ------------------------------------------------------------------------------ -- 4.7 Exercises -- variables A B C D : Prop example : A ∧ (A → B) → B := λ (h : A ∧ (A → B)) , have a : A , from and.left h , have fab : A → B, from and.right h , fab a -- show B, from fab a example : A → ¬ (¬ A ∧ B) := sorry example : ¬ (A ∧ B) → (A → ¬ B) := sorry -- HC : warmup for two following this one example (h₁ : A) (h₂ : A → C) (h₃ : A → D) : C ∨ D := have hc : C, from h₂ h₁ , or.inl hc example (h₁ : A) (h₂ : A → C) (h₃ : A → D) : C ∨ D := have hd : D, from h₃ h₁ , or.inr hd -- from 3.4 /- 𝐴∨𝐵, 𝐴→𝐶, and 𝐵→𝐷, conclude 𝐶∨𝐷. --- 1 --- 1 A → C A B → D B ----------- ----------- A ∨ B C ∨ D C ∨ D --------------------------------- 1 C ∨ D -/ -- left version section variables (hbc : B → C) example (h₁ : A ∨ B) (h₂ : A → C) (h₃ : B → D) : C ∨ D := have hc : C, from or.elim h₁ (λ (a : A), show C, from h₂ a) (λ (b : B), show C, from hbc b) , or.inl hc end -- right version section variables (had : A -> D) example (h₁ : A ∨ B) (h₂ : A → C) (h₃ : B → D) : C ∨ D := have hc : D, from or.elim h₁ (λ (a : A), show D, from had a) (λ (b : B), show D, from h₃ b) , or.inr hc end -- HC : from 3 - the reverse of the example after this /- --- 1 --- 2 A B --------- 3 ------- -------- 3 ------- ¬(A ∨ B) A ∨ B ¬(A ∨ B) A ∨ B ----------------------- --------------------- ⊥ ⊥ --- 1 --- 2 ¬A ¬B ------------------------------ ¬A ∧ ¬B ------------------ ¬(A ∨ B) → ¬A ∧ ¬B -/ /- example (h : ¬ (A ∨ B)) : ¬ A ∧ ¬ B := λ (a : A) (b : B), show ¬ A ∧ ¬ B, from false.elim (h (or.inl a)) example (h : ¬ (A ∨ B)) : ¬ A ∧ ¬ B := λ (a : A) , have aOrB₁ : A ∨ B, from or.inl a , have x : false, from h aOrB₁ , have notA : ¬ A , from false.elim x , have notB : ¬ B , from false.elim x , show ¬ A ∧ ¬ B , from and.intro notA notB -/ example (h : ¬ A ∧ ¬ B) : ¬ (A ∨ B) := sorry example : ¬ (A ↔ ¬ A) := sorry
f4a591437436e478366bce5ba51c41c97eb8088d
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/ordered_group.lean
5268818f5ea8c3c6447f3e82edb32c46b490e9d8
[ "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
36,485
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl -/ import algebra.ordered_monoid /-! # Ordered groups This file develops the basics of ordered groups. ## Implementation details Unfortunately, the number of `'` appended to lemmas in this file may differ between the multiplicative and the additive version of a lemma. The reason is that we did not want to change existing names in the library. -/ set_option old_structure_cmd true universe u variable {α : Type u} @[to_additive] instance group.covariant_class_le.to_contravariant_class_le [group α] [has_le α] [covariant_class α α (*) (≤)] : contravariant_class α α (*) (≤) := { elim := λ a b c bc, calc b = a⁻¹ * (a * b) : eq_inv_mul_of_mul_eq rfl ... ≤ a⁻¹ * (a * c) : mul_le_mul_left' bc a⁻¹ ... = c : inv_mul_cancel_left a c } @[to_additive] instance group.swap.covariant_class_le.to_contravariant_class_le [group α] [has_le α] [covariant_class α α (function.swap (*)) (≤)] : contravariant_class α α (function.swap (*)) (≤) := { elim := λ a b c bc, calc b = b * a * a⁻¹ : eq_mul_inv_of_mul_eq rfl ... ≤ c * a * a⁻¹ : mul_le_mul_right' bc a⁻¹ ... = c : mul_inv_eq_of_eq_mul rfl } @[to_additive] instance group.covariant_class_lt.to_contravariant_class_lt [group α] [has_lt α] [covariant_class α α (*) (<)] : contravariant_class α α (*) (<) := { elim := λ a b c bc, calc b = a⁻¹ * (a * b) : eq_inv_mul_of_mul_eq rfl ... < a⁻¹ * (a * c) : mul_lt_mul_left' bc a⁻¹ ... = c : inv_mul_cancel_left a c } @[to_additive] instance group.swap.covariant_class_lt.to_contravariant_class_lt [group α] [has_lt α] [covariant_class α α (function.swap (*)) (<)] : contravariant_class α α (function.swap (*)) (<) := { elim := λ a b c bc, calc b = b * a * a⁻¹ : eq_mul_inv_of_mul_eq rfl ... < c * a * a⁻¹ : mul_lt_mul_right' bc a⁻¹ ... = c : mul_inv_eq_of_eq_mul rfl } /-- An ordered additive commutative group is an additive commutative group with a partial order in which addition is strictly monotone. -/ @[protect_proj, ancestor add_comm_group partial_order] class ordered_add_comm_group (α : Type u) extends add_comm_group α, partial_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) /-- An ordered commutative group is an commutative group with a partial order in which multiplication is strictly monotone. -/ @[protect_proj, ancestor comm_group partial_order] class ordered_comm_group (α : Type u) extends comm_group α, partial_order α := (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) attribute [to_additive] ordered_comm_group @[to_additive] instance units.covariant_class [ordered_comm_monoid α] : covariant_class (units α) (units α) (*) (≤) := { elim := λ a b c bc, show (a : α) * b ≤ a * c, from mul_le_mul_left' bc _ } @[to_additive] instance ordered_comm_group.to_covariant_class_left_le (α : Type u) [ordered_comm_group α] : covariant_class α α (*) (≤) := { elim := λ a b c bc, ordered_comm_group.mul_le_mul_left b c bc a } /--The units of an ordered commutative monoid form an ordered commutative group. -/ @[to_additive] instance units.ordered_comm_group [ordered_comm_monoid α] : ordered_comm_group (units α) := { mul_le_mul_left := λ a b h c, (mul_le_mul_left' (h : (a : α) ≤ b) _ : (c : α) * a ≤ c * b), .. units.partial_order, .. (infer_instance : comm_group (units α)) } section ordered_comm_group variables [ordered_comm_group α] {a b c d : α} @[priority 100, to_additive] -- see Note [lower instance priority] instance ordered_comm_group.to_ordered_cancel_comm_monoid (α : Type u) [s : ordered_comm_group α] : ordered_cancel_comm_monoid α := { mul_left_cancel := λ a b c, (mul_right_inj a).mp, le_of_mul_le_mul_left := λ a b c, (mul_le_mul_iff_left a).mp, ..s } @[priority 100, to_additive] instance ordered_comm_group.has_exists_mul_of_le (α : Type u) [ordered_comm_group α] : has_exists_mul_of_le α := ⟨λ a b hab, ⟨b * a⁻¹, (mul_inv_cancel_comm_assoc a b).symm⟩⟩ @[to_additive neg_le_neg] lemma inv_le_inv' (h : a ≤ b) : b⁻¹ ≤ a⁻¹ := have 1 ≤ a⁻¹ * b, from mul_left_inv a ▸ mul_le_mul_left' h _, have 1 * b⁻¹ ≤ a⁻¹ * b * b⁻¹, from mul_le_mul_right' this _, by rwa [mul_inv_cancel_right, one_mul] at this @[to_additive] lemma le_of_inv_le_inv (h : b⁻¹ ≤ a⁻¹) : a ≤ b := suffices (a⁻¹)⁻¹ ≤ (b⁻¹)⁻¹, from begin simp [inv_inv] at this, assumption end, inv_le_inv' h @[to_additive] lemma one_le_of_inv_le_one (h : a⁻¹ ≤ 1) : 1 ≤ a := have a⁻¹ ≤ 1⁻¹, by rwa one_inv, le_of_inv_le_inv this @[to_additive] lemma inv_le_one_of_one_le (h : 1 ≤ a) : a⁻¹ ≤ 1 := have a⁻¹ ≤ 1⁻¹, from inv_le_inv' h, by rwa one_inv at this @[to_additive nonpos_of_neg_nonneg] lemma le_one_of_one_le_inv (h : 1 ≤ a⁻¹) : a ≤ 1 := have 1⁻¹ ≤ a⁻¹, by rwa one_inv, le_of_inv_le_inv this @[to_additive neg_nonneg_of_nonpos] lemma one_le_inv_of_le_one (h : a ≤ 1) : 1 ≤ a⁻¹ := have 1⁻¹ ≤ a⁻¹, from inv_le_inv' h, by rwa one_inv at this @[to_additive neg_lt_neg] lemma inv_lt_inv' (h : a < b) : b⁻¹ < a⁻¹ := have 1 < a⁻¹ * b, from mul_left_inv a ▸ mul_lt_mul_left' h (a⁻¹), have 1 * b⁻¹ < a⁻¹ * b * b⁻¹, from mul_lt_mul_right' this (b⁻¹), by rwa [mul_inv_cancel_right, one_mul] at this @[to_additive] lemma lt_of_inv_lt_inv (h : b⁻¹ < a⁻¹) : a < b := inv_inv a ▸ inv_inv b ▸ inv_lt_inv' h @[to_additive] lemma one_lt_of_inv_inv (h : a⁻¹ < 1) : 1 < a := have a⁻¹ < 1⁻¹, by rwa one_inv, lt_of_inv_lt_inv this @[to_additive] lemma inv_inv_of_one_lt (h : 1 < a) : a⁻¹ < 1 := have a⁻¹ < 1⁻¹, from inv_lt_inv' h, by rwa one_inv at this @[to_additive neg_of_neg_pos] lemma inv_of_one_lt_inv (h : 1 < a⁻¹) : a < 1 := have 1⁻¹ < a⁻¹, by rwa one_inv, lt_of_inv_lt_inv this @[to_additive neg_pos_of_neg] lemma one_lt_inv_of_inv (h : a < 1) : 1 < a⁻¹ := have 1⁻¹ < a⁻¹, from inv_lt_inv' h, by rwa one_inv at this @[to_additive] lemma le_inv_of_le_inv (h : a ≤ b⁻¹) : b ≤ a⁻¹ := begin have h := inv_le_inv' h, rwa inv_inv at h end @[to_additive] lemma inv_le_of_inv_le (h : a⁻¹ ≤ b) : b⁻¹ ≤ a := begin have h := inv_le_inv' h, rwa inv_inv at h end @[to_additive] lemma lt_inv_of_lt_inv (h : a < b⁻¹) : b < a⁻¹ := begin have h := inv_lt_inv' h, rwa inv_inv at h end @[to_additive] lemma inv_lt_of_inv_lt (h : a⁻¹ < b) : b⁻¹ < a := begin have h := inv_lt_inv' h, rwa inv_inv at h end @[to_additive] lemma mul_le_of_le_inv_mul (h : b ≤ a⁻¹ * c) : a * b ≤ c := begin have h := mul_le_mul_left' h a, rwa mul_inv_cancel_left at h end @[to_additive] lemma le_inv_mul_of_mul_le (h : a * b ≤ c) : b ≤ a⁻¹ * c := begin have h := mul_le_mul_left' h a⁻¹, rwa inv_mul_cancel_left at h end @[to_additive] lemma le_mul_of_inv_mul_le (h : b⁻¹ * a ≤ c) : a ≤ b * c := begin have h := mul_le_mul_left' h b, rwa mul_inv_cancel_left at h end @[to_additive] lemma inv_mul_le_of_le_mul (h : a ≤ b * c) : b⁻¹ * a ≤ c := begin have h := mul_le_mul_left' h b⁻¹, rwa inv_mul_cancel_left at h end @[to_additive] lemma le_mul_of_inv_mul_le_left (h : b⁻¹ * a ≤ c) : a ≤ b * c := le_mul_of_inv_mul_le h @[to_additive] lemma inv_mul_le_left_of_le_mul (h : a ≤ b * c) : b⁻¹ * a ≤ c := inv_mul_le_of_le_mul h @[to_additive] lemma le_mul_of_inv_mul_le_right (h : c⁻¹ * a ≤ b) : a ≤ b * c := by { rw mul_comm, exact le_mul_of_inv_mul_le h } @[to_additive] lemma inv_mul_le_right_of_le_mul (h : a ≤ b * c) : c⁻¹ * a ≤ b := by { rw mul_comm at h, apply inv_mul_le_left_of_le_mul h } @[to_additive] lemma mul_lt_of_lt_inv_mul (h : b < a⁻¹ * c) : a * b < c := begin have h := mul_lt_mul_left' h a, rwa mul_inv_cancel_left at h end @[to_additive] lemma lt_inv_mul_of_mul_lt (h : a * b < c) : b < a⁻¹ * c := begin have h := mul_lt_mul_left' h (a⁻¹), rwa inv_mul_cancel_left at h end @[to_additive] lemma lt_mul_of_inv_mul_lt (h : b⁻¹ * a < c) : a < b * c := begin have h := mul_lt_mul_left' h b, rwa mul_inv_cancel_left at h end @[to_additive] lemma inv_mul_lt_of_lt_mul (h : a < b * c) : b⁻¹ * a < c := begin have h := mul_lt_mul_left' h (b⁻¹), rwa inv_mul_cancel_left at h end @[to_additive] lemma lt_mul_of_inv_mul_lt_left (h : b⁻¹ * a < c) : a < b * c := lt_mul_of_inv_mul_lt h @[to_additive] lemma inv_mul_lt_left_of_lt_mul (h : a < b * c) : b⁻¹ * a < c := inv_mul_lt_of_lt_mul h @[to_additive] lemma lt_mul_of_inv_mul_lt_right (h : c⁻¹ * a < b) : a < b * c := by { rw mul_comm, exact lt_mul_of_inv_mul_lt h } @[to_additive] lemma inv_mul_lt_right_of_lt_mul (h : a < b * c) : c⁻¹ * a < b := by { rw mul_comm at h, exact inv_mul_lt_of_lt_mul h } @[simp, to_additive] lemma inv_lt_one_iff_one_lt : a⁻¹ < 1 ↔ 1 < a := ⟨ one_lt_of_inv_inv, inv_inv_of_one_lt ⟩ @[simp, to_additive] lemma inv_le_inv_iff : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := have a * b * a⁻¹ ≤ a * b * b⁻¹ ↔ a⁻¹ ≤ b⁻¹, from mul_le_mul_iff_left _, by { rw [mul_inv_cancel_right, mul_comm a, mul_inv_cancel_right] at this, rw [this] } @[to_additive neg_le] lemma inv_le' : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := have a⁻¹ ≤ (b⁻¹)⁻¹ ↔ b⁻¹ ≤ a, from inv_le_inv_iff, by rwa inv_inv at this @[to_additive le_neg] lemma le_inv' : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := have (a⁻¹)⁻¹ ≤ b⁻¹ ↔ b ≤ a⁻¹, from inv_le_inv_iff, by rwa inv_inv at this @[to_additive neg_le_iff_add_nonneg] lemma inv_le_iff_one_le_mul : a⁻¹ ≤ b ↔ 1 ≤ b * a := (mul_le_mul_iff_right a).symm.trans $ by rw inv_mul_self @[to_additive neg_le_iff_add_nonneg'] lemma inv_le_iff_one_le_mul' : a⁻¹ ≤ b ↔ 1 ≤ a * b := (mul_le_mul_iff_left a).symm.trans $ by rw mul_inv_self @[to_additive] lemma inv_lt_iff_one_lt_mul : a⁻¹ < b ↔ 1 < b * a := (mul_lt_mul_iff_right a).symm.trans $ by rw inv_mul_self @[to_additive] lemma inv_lt_iff_one_lt_mul' : a⁻¹ < b ↔ 1 < a * b := (mul_lt_mul_iff_left a).symm.trans $ by rw mul_inv_self @[to_additive] lemma le_inv_iff_mul_le_one : a ≤ b⁻¹ ↔ a * b ≤ 1 := (mul_le_mul_iff_right b).symm.trans $ by rw inv_mul_self @[to_additive] lemma le_inv_iff_mul_le_one' : a ≤ b⁻¹ ↔ b * a ≤ 1 := (mul_le_mul_iff_left b).symm.trans $ by rw mul_inv_self @[to_additive] lemma lt_inv_iff_mul_lt_one : a < b⁻¹ ↔ a * b < 1 := (mul_lt_mul_iff_right b).symm.trans $ by rw inv_mul_self @[to_additive] lemma lt_inv_iff_mul_lt_one' : a < b⁻¹ ↔ b * a < 1 := (mul_lt_mul_iff_left b).symm.trans $ by rw mul_inv_self @[simp, to_additive neg_nonpos] lemma inv_le_one' : a⁻¹ ≤ 1 ↔ 1 ≤ a := have a⁻¹ ≤ 1⁻¹ ↔ 1 ≤ a, from inv_le_inv_iff, by rwa one_inv at this @[simp, to_additive neg_nonneg] lemma one_le_inv' : 1 ≤ a⁻¹ ↔ a ≤ 1 := have 1⁻¹ ≤ a⁻¹ ↔ a ≤ 1, from inv_le_inv_iff, by rwa one_inv at this @[to_additive] lemma inv_le_self (h : 1 ≤ a) : a⁻¹ ≤ a := le_trans (inv_le_one'.2 h) h @[to_additive] lemma self_le_inv (h : a ≤ 1) : a ≤ a⁻¹ := le_trans h (one_le_inv'.2 h) @[simp, to_additive] lemma inv_lt_inv_iff : a⁻¹ < b⁻¹ ↔ b < a := have a * b * a⁻¹ < a * b * b⁻¹ ↔ a⁻¹ < b⁻¹, from mul_lt_mul_iff_left _, by { rw [mul_inv_cancel_right, mul_comm a, mul_inv_cancel_right] at this, rw [this] } @[to_additive neg_lt_zero] lemma inv_lt_one' : a⁻¹ < 1 ↔ 1 < a := have a⁻¹ < 1⁻¹ ↔ 1 < a, from inv_lt_inv_iff, by rwa one_inv at this @[to_additive neg_pos] lemma one_lt_inv' : 1 < a⁻¹ ↔ a < 1 := have 1⁻¹ < a⁻¹ ↔ a < 1, from inv_lt_inv_iff, by rwa one_inv at this @[to_additive neg_lt] lemma inv_lt' : a⁻¹ < b ↔ b⁻¹ < a := have a⁻¹ < (b⁻¹)⁻¹ ↔ b⁻¹ < a, from inv_lt_inv_iff, by rwa inv_inv at this @[to_additive lt_neg] lemma lt_inv' : a < b⁻¹ ↔ b < a⁻¹ := have (a⁻¹)⁻¹ < b⁻¹ ↔ b < a⁻¹, from inv_lt_inv_iff, by rwa inv_inv at this @[to_additive] lemma inv_lt_self (h : 1 < a) : a⁻¹ < a := (inv_lt_one'.2 h).trans h @[to_additive] lemma le_inv_mul_iff_mul_le : b ≤ a⁻¹ * c ↔ a * b ≤ c := have a⁻¹ * (a * b) ≤ a⁻¹ * c ↔ a * b ≤ c, from mul_le_mul_iff_left _, by rwa inv_mul_cancel_left at this @[simp, to_additive] lemma inv_mul_le_iff_le_mul : b⁻¹ * a ≤ c ↔ a ≤ b * c := have b⁻¹ * a ≤ b⁻¹ * (b * c) ↔ a ≤ b * c, from mul_le_mul_iff_left _, by rwa inv_mul_cancel_left at this @[to_additive] lemma mul_inv_le_iff_le_mul : a * c⁻¹ ≤ b ↔ a ≤ b * c := by rw [mul_comm a, mul_comm b, inv_mul_le_iff_le_mul] @[simp, to_additive] lemma mul_inv_le_iff_le_mul' : a * b⁻¹ ≤ c ↔ a ≤ b * c := by rw [← inv_mul_le_iff_le_mul, mul_comm] @[to_additive] lemma inv_mul_le_iff_le_mul' : c⁻¹ * a ≤ b ↔ a ≤ b * c := by rw [inv_mul_le_iff_le_mul, mul_comm] @[simp, to_additive] lemma lt_inv_mul_iff_mul_lt : b < a⁻¹ * c ↔ a * b < c := have a⁻¹ * (a * b) < a⁻¹ * c ↔ a * b < c, from mul_lt_mul_iff_left _, by rwa inv_mul_cancel_left at this @[simp, to_additive] lemma inv_mul_lt_iff_lt_mul : b⁻¹ * a < c ↔ a < b * c := have b⁻¹ * a < b⁻¹ * (b * c) ↔ a < b * c, from mul_lt_mul_iff_left _, by rwa inv_mul_cancel_left at this @[to_additive] lemma inv_mul_lt_iff_lt_mul_right : c⁻¹ * a < b ↔ a < b * c := by rw [inv_mul_lt_iff_lt_mul, mul_comm] @[to_additive add_neg_le_add_neg_iff] lemma mul_inv_le_mul_inv_iff' : a * b⁻¹ ≤ c * d⁻¹ ↔ a * d ≤ c * b := begin split ; intro h, have := mul_le_mul_right' (mul_le_mul_right' h b) d, rwa [inv_mul_cancel_right, mul_assoc _ _ b, mul_comm _ b, ← mul_assoc, inv_mul_cancel_right] at this, have := mul_le_mul_right' (mul_le_mul_right' h d⁻¹) b⁻¹, rwa [mul_inv_cancel_right, _root_.mul_assoc, _root_.mul_comm d⁻¹ b⁻¹, ← mul_assoc, mul_inv_cancel_right] at this, end @[simp, to_additive] lemma div_le_self_iff (a : α) {b : α} : a / b ≤ a ↔ 1 ≤ b := by simp [div_eq_mul_inv] @[simp, to_additive] lemma div_lt_self_iff (a : α) {b : α} : a / b < a ↔ 1 < b := by simp [div_eq_mul_inv] /-- Pullback an `ordered_comm_group` under an injective map. See note [reducible non-instances]. -/ @[reducible, to_additive function.injective.ordered_add_comm_group "Pullback an `ordered_add_comm_group` under an injective map."] def function.injective.ordered_comm_group {β : Type*} [has_one β] [has_mul β] [has_inv β] [has_div β] (f : β → α) (hf : function.injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) : ordered_comm_group β := { ..partial_order.lift f hf, ..hf.ordered_comm_monoid f one mul, ..hf.comm_group f one mul inv div } end ordered_comm_group section ordered_add_comm_group variables [ordered_add_comm_group α] {a b c d : α} lemma sub_le_sub (hab : a ≤ b) (hcd : c ≤ d) : a - d ≤ b - c := by simpa only [sub_eq_add_neg] using add_le_add hab (neg_le_neg hcd) lemma sub_lt_sub (hab : a < b) (hcd : c < d) : a - d < b - c := by simpa only [sub_eq_add_neg] using add_lt_add hab (neg_lt_neg hcd) alias sub_le_self_iff ↔ _ sub_le_self alias sub_lt_self_iff ↔ _ sub_lt_self lemma sub_le_sub_iff : a - b ≤ c - d ↔ a + d ≤ c + b := by simpa only [sub_eq_add_neg] using add_neg_le_add_neg_iff @[simp] lemma sub_le_sub_iff_left (a : α) {b c : α} : a - b ≤ a - c ↔ c ≤ b := by rw [sub_eq_add_neg, sub_eq_add_neg, add_le_add_iff_left, neg_le_neg_iff] lemma sub_le_sub_left (h : a ≤ b) (c : α) : c - b ≤ c - a := (sub_le_sub_iff_left c).2 h @[simp] lemma sub_le_sub_iff_right (c : α) : a - c ≤ b - c ↔ a ≤ b := by simpa only [sub_eq_add_neg] using add_le_add_iff_right _ lemma sub_le_sub_right (h : a ≤ b) (c : α) : a - c ≤ b - c := (sub_le_sub_iff_right c).2 h @[simp] lemma sub_lt_sub_iff_left (a : α) {b c : α} : a - b < a - c ↔ c < b := by rw [sub_eq_add_neg, sub_eq_add_neg, add_lt_add_iff_left, neg_lt_neg_iff] lemma sub_lt_sub_left (h : a < b) (c : α) : c - b < c - a := (sub_lt_sub_iff_left c).2 h @[simp] lemma sub_lt_sub_iff_right (c : α) : a - c < b - c ↔ a < b := by simpa only [sub_eq_add_neg] using add_lt_add_iff_right _ lemma sub_lt_sub_right (h : a < b) (c : α) : a - c < b - c := (sub_lt_sub_iff_right c).2 h @[simp] lemma sub_nonneg : 0 ≤ a - b ↔ b ≤ a := by rw [← sub_self a, sub_le_sub_iff_left] alias sub_nonneg ↔ le_of_sub_nonneg sub_nonneg_of_le @[simp] lemma sub_nonpos : a - b ≤ 0 ↔ a ≤ b := by rw [← sub_self b, sub_le_sub_iff_right] alias sub_nonpos ↔ le_of_sub_nonpos sub_nonpos_of_le @[simp] lemma sub_pos : 0 < a - b ↔ b < a := by rw [← sub_self a, sub_lt_sub_iff_left] alias sub_pos ↔ lt_of_sub_pos sub_pos_of_lt @[simp] lemma sub_lt_zero : a - b < 0 ↔ a < b := by rw [← sub_self b, sub_lt_sub_iff_right] alias sub_lt_zero ↔ lt_of_sub_neg sub_neg_of_lt lemma le_sub_iff_add_le' : b ≤ c - a ↔ a + b ≤ c := by rw [sub_eq_add_neg, add_comm, le_neg_add_iff_add_le] lemma le_sub_iff_add_le : a ≤ c - b ↔ a + b ≤ c := by rw [le_sub_iff_add_le', add_comm] alias le_sub_iff_add_le ↔ add_le_of_le_sub_right le_sub_right_of_add_le lemma sub_le_iff_le_add' : a - b ≤ c ↔ a ≤ b + c := by rw [sub_eq_add_neg, add_comm, neg_add_le_iff_le_add] alias le_sub_iff_add_le' ↔ add_le_of_le_sub_left le_sub_left_of_add_le lemma sub_le_iff_le_add : a - c ≤ b ↔ a ≤ b + c := by rw [sub_le_iff_le_add', add_comm] @[simp] lemma neg_le_sub_iff_le_add : -b ≤ a - c ↔ c ≤ a + b := le_sub_iff_add_le.trans neg_add_le_iff_le_add' lemma neg_le_sub_iff_le_add' : -a ≤ b - c ↔ c ≤ a + b := by rw [neg_le_sub_iff_le_add, add_comm] lemma sub_le : a - b ≤ c ↔ a - c ≤ b := sub_le_iff_le_add'.trans sub_le_iff_le_add.symm theorem le_sub : a ≤ b - c ↔ c ≤ b - a := le_sub_iff_add_le'.trans le_sub_iff_add_le.symm lemma lt_sub_iff_add_lt' : b < c - a ↔ a + b < c := by rw [sub_eq_add_neg, add_comm, lt_neg_add_iff_add_lt] alias lt_sub_iff_add_lt' ↔ add_lt_of_lt_sub_left lt_sub_left_of_add_lt lemma lt_sub_iff_add_lt : a < c - b ↔ a + b < c := by rw [lt_sub_iff_add_lt', add_comm] alias lt_sub_iff_add_lt ↔ add_lt_of_lt_sub_right lt_sub_right_of_add_lt lemma sub_lt_iff_lt_add' : a - b < c ↔ a < b + c := by rw [sub_eq_add_neg, add_comm, neg_add_lt_iff_lt_add] alias sub_lt_iff_lt_add' ↔ lt_add_of_sub_left_lt sub_left_lt_of_lt_add lemma sub_lt_iff_lt_add : a - c < b ↔ a < b + c := by rw [sub_lt_iff_lt_add', add_comm] alias sub_lt_iff_lt_add ↔ lt_add_of_sub_right_lt sub_right_lt_of_lt_add @[simp] lemma neg_lt_sub_iff_lt_add : -b < a - c ↔ c < a + b := lt_sub_iff_add_lt.trans neg_add_lt_iff_lt_add_right lemma neg_lt_sub_iff_lt_add' : -a < b - c ↔ c < a + b := by rw [neg_lt_sub_iff_lt_add, add_comm] lemma sub_lt : a - b < c ↔ a - c < b := sub_lt_iff_lt_add'.trans sub_lt_iff_lt_add.symm theorem lt_sub : a < b - c ↔ c < b - a := lt_sub_iff_add_lt'.trans lt_sub_iff_add_lt.symm end ordered_add_comm_group /-! ### Linearly ordered commutative groups -/ /-- A linearly ordered additive commutative group is an additive commutative group with a linear order in which addition is monotone. -/ @[protect_proj, ancestor ordered_add_comm_group linear_order] class linear_ordered_add_comm_group (α : Type u) extends ordered_add_comm_group α, linear_order α /-- A linearly ordered commutative monoid with an additively absorbing `⊤` element. Instances should include number systems with an infinite element adjoined.` -/ @[protect_proj, ancestor linear_ordered_add_comm_monoid_with_top sub_neg_monoid nontrivial] class linear_ordered_add_comm_group_with_top (α : Type*) extends linear_ordered_add_comm_monoid_with_top α, sub_neg_monoid α, nontrivial α := (neg_top : - (⊤ : α) = ⊤) (add_neg_cancel : ∀ a:α, a ≠ ⊤ → a + (- a) = 0) /-- A linearly ordered commutative group is a commutative group with a linear order in which multiplication is monotone. -/ @[protect_proj, ancestor ordered_comm_group linear_order, to_additive] class linear_ordered_comm_group (α : Type u) extends ordered_comm_group α, linear_order α section linear_ordered_comm_group variables [linear_ordered_comm_group α] {a b c : α} @[priority 100, to_additive] -- see Note [lower instance priority] instance linear_ordered_comm_group.to_linear_ordered_cancel_comm_monoid : linear_ordered_cancel_comm_monoid α := { le_of_mul_le_mul_left := λ x y z, le_of_mul_le_mul_left', mul_left_cancel := λ x y z, mul_left_cancel, ..‹linear_ordered_comm_group α› } /-- Pullback a `linear_ordered_comm_group` under an injective map. See note [reducible non-instances]. -/ @[reducible, to_additive function.injective.linear_ordered_add_comm_group "Pullback a `linear_ordered_add_comm_group` under an injective map."] def function.injective.linear_ordered_comm_group {β : Type*} [has_one β] [has_mul β] [has_inv β] [has_div β] (f : β → α) (hf : function.injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) : linear_ordered_comm_group β := { ..linear_order.lift f hf, ..hf.ordered_comm_group f one mul inv div } @[to_additive linear_ordered_add_comm_group.add_lt_add_left] lemma linear_ordered_comm_group.mul_lt_mul_left' (a b : α) (h : a < b) (c : α) : c * a < c * b := mul_lt_mul_left' h c @[to_additive min_neg_neg] lemma min_inv_inv' (a b : α) : min (a⁻¹) (b⁻¹) = (max a b)⁻¹ := eq.symm $ @monotone.map_max α (order_dual α) _ _ has_inv.inv a b $ λ a b, inv_le_inv' @[to_additive max_neg_neg] lemma max_inv_inv' (a b : α) : max (a⁻¹) (b⁻¹) = (min a b)⁻¹ := eq.symm $ @monotone.map_min α (order_dual α) _ _ has_inv.inv a b $ λ a b, inv_le_inv' @[to_additive min_sub_sub_right] lemma min_div_div_right' (a b c : α) : min (a / c) (b / c) = min a b / c := by simpa only [div_eq_mul_inv] using min_mul_mul_right a b (c⁻¹) @[to_additive max_sub_sub_right] lemma max_div_div_right' (a b c : α) : max (a / c) (b / c) = max a b / c := by simpa only [div_eq_mul_inv] using max_mul_mul_right a b (c⁻¹) @[to_additive min_sub_sub_left] lemma min_div_div_left' (a b c : α) : min (a / b) (a / c) = a / max b c := by simp only [div_eq_mul_inv, min_mul_mul_left, min_inv_inv'] @[to_additive max_sub_sub_left] lemma max_div_div_left' (a b c : α) : max (a / b) (a / c) = a / min b c := by simp only [div_eq_mul_inv, max_mul_mul_left, max_inv_inv'] @[to_additive max_zero_sub_eq_self] lemma max_one_div_eq_self' (a : α) : max a 1 / max (a⁻¹) 1 = a := begin rcases le_total a 1, { rw [max_eq_right h, max_eq_left, one_div, inv_inv], { rwa [le_inv', one_inv] } }, { rw [max_eq_left, max_eq_right, div_eq_mul_inv, one_inv, mul_one], { rwa [inv_le', one_inv] }, exact h } end @[to_additive eq_zero_of_neg_eq] lemma eq_one_of_inv_eq' (h : a⁻¹ = a) : a = 1 := match lt_trichotomy a 1 with | or.inl h₁ := have 1 < a, from h ▸ one_lt_inv_of_inv h₁, absurd h₁ this.asymm | or.inr (or.inl h₁) := h₁ | or.inr (or.inr h₁) := have a < 1, from h ▸ inv_inv_of_one_lt h₁, absurd h₁ this.asymm end @[to_additive exists_zero_lt] lemma exists_one_lt' [nontrivial α] : ∃ (a:α), 1 < a := begin obtain ⟨y, hy⟩ := decidable.exists_ne (1 : α), cases hy.lt_or_lt, { exact ⟨y⁻¹, one_lt_inv'.mpr h⟩ }, { exact ⟨y, h⟩ } end @[priority 100, to_additive] -- see Note [lower instance priority] instance linear_ordered_comm_group.to_no_top_order [nontrivial α] : no_top_order α := ⟨ begin obtain ⟨y, hy⟩ : ∃ (a:α), 1 < a := exists_one_lt', exact λ a, ⟨a * y, lt_mul_of_one_lt_right' a hy⟩ end ⟩ @[priority 100, to_additive] -- see Note [lower instance priority] instance linear_ordered_comm_group.to_no_bot_order [nontrivial α] : no_bot_order α := ⟨ begin obtain ⟨y, hy⟩ : ∃ (a:α), 1 < a := exists_one_lt', exact λ a, ⟨a / y, (div_lt_self_iff a).mpr hy⟩ end ⟩ end linear_ordered_comm_group section linear_ordered_add_comm_group variables [linear_ordered_add_comm_group α] {a b c : α} @[simp] lemma sub_le_sub_flip : a - b ≤ b - a ↔ a ≤ b := begin rw [sub_le_iff_le_add, sub_add_eq_add_sub, le_sub_iff_add_le], split, { intro h, by_contra H, rw not_le at H, apply not_lt.2 h, exact add_lt_add H H, }, { intro h, exact add_le_add h h, } end @[simp] lemma max_zero_sub_max_neg_zero_eq_self (a : α) : max a 0 - max (-a) 0 = a := by { rcases le_total a 0 with h|h; simp [h] } lemma le_of_forall_pos_le_add [densely_ordered α] (h : ∀ ε : α, 0 < ε → a ≤ b + ε) : a ≤ b := le_of_forall_le_of_dense $ λ c hc, calc a ≤ b + (c - b) : h _ (sub_pos_of_lt hc) ... = c : add_sub_cancel'_right _ _ lemma le_iff_forall_pos_le_add [densely_ordered α] : a ≤ b ↔ ∀ ε, 0 < ε → a ≤ b + ε := ⟨λ h ε ε_pos, le_add_of_le_of_nonneg h ε_pos.le, le_of_forall_pos_le_add⟩ lemma le_of_forall_pos_lt_add (h : ∀ ε : α, 0 < ε → a < b + ε) : a ≤ b := le_of_not_lt $ λ h₁, by simpa using h _ (sub_pos_of_lt h₁) lemma le_iff_forall_pos_lt_add : a ≤ b ↔ ∀ ε, 0 < ε → a < b + ε := ⟨λ h ε, lt_add_of_le_of_pos h, le_of_forall_pos_lt_add⟩ /-- `abs a` is the absolute value of `a`. -/ def abs (a : α) : α := max a (-a) lemma abs_choice (x : α) : abs x = x ∨ abs x = -x := max_choice _ _ lemma abs_of_nonneg (h : 0 ≤ a) : abs a = a := max_eq_left $ (neg_nonpos.2 h).trans h lemma abs_of_pos (h : 0 < a) : abs a = a := abs_of_nonneg h.le lemma abs_of_nonpos (h : a ≤ 0) : abs a = -a := max_eq_right $ h.trans (neg_nonneg.2 h) lemma abs_of_neg (h : a < 0) : abs a = -a := abs_of_nonpos h.le @[simp] lemma abs_zero : abs 0 = (0:α) := abs_of_nonneg le_rfl @[simp] lemma abs_neg (a : α) : abs (-a) = abs a := begin unfold abs, rw [max_comm, neg_neg] end @[simp] lemma abs_pos : 0 < abs a ↔ a ≠ 0 := begin rcases lt_trichotomy a 0 with (ha|rfl|ha), { simp [abs_of_neg ha, neg_pos, ha.ne, ha] }, { simp }, { simp [abs_of_pos ha, ha, ha.ne.symm] } end lemma abs_pos_of_pos (h : 0 < a) : 0 < abs a := abs_pos.2 h.ne.symm lemma abs_pos_of_neg (h : a < 0) : 0 < abs a := abs_pos.2 h.ne lemma abs_sub_comm (a b : α) : abs (a - b) = abs (b - a) := by rw [← neg_sub, abs_neg] lemma abs_le' : abs a ≤ b ↔ a ≤ b ∧ -a ≤ b := max_le_iff lemma abs_le : abs a ≤ b ↔ - b ≤ a ∧ a ≤ b := by rw [abs_le', and.comm, neg_le] lemma neg_le_of_abs_le (h : abs a ≤ b) : -b ≤ a := (abs_le.mp h).1 lemma le_of_abs_le (h : abs a ≤ b) : a ≤ b := (abs_le.mp h).2 lemma le_abs : a ≤ abs b ↔ a ≤ b ∨ a ≤ -b := le_max_iff lemma le_abs_self (a : α) : a ≤ abs a := le_max_left _ _ lemma neg_le_abs_self (a : α) : -a ≤ abs a := le_max_right _ _ lemma neg_abs_le_self (a : α) : -abs a ≤ a := neg_le.mpr $ neg_le_abs_self a lemma abs_nonneg (a : α) : 0 ≤ abs a := (le_total 0 a).elim (λ h, h.trans (le_abs_self a)) (λ h, (neg_nonneg.2 h).trans $ neg_le_abs_self a) @[simp] lemma abs_abs (a : α) : abs (abs a) = abs a := abs_of_nonneg $ abs_nonneg a @[simp] lemma abs_eq_zero : abs a = 0 ↔ a = 0 := decidable.not_iff_not.1 $ ne_comm.trans $ (abs_nonneg a).lt_iff_ne.symm.trans abs_pos @[simp] lemma abs_nonpos_iff {a : α} : abs a ≤ 0 ↔ a = 0 := (abs_nonneg a).le_iff_eq.trans abs_eq_zero lemma abs_lt : abs a < b ↔ - b < a ∧ a < b := max_lt_iff.trans $ and.comm.trans $ by rw [neg_lt] lemma neg_lt_of_abs_lt (h : abs a < b) : -b < a := (abs_lt.mp h).1 lemma lt_of_abs_lt (h : abs a < b) : a < b := (abs_lt.mp h).2 lemma lt_abs : a < abs b ↔ a < b ∨ a < -b := lt_max_iff lemma max_sub_min_eq_abs' (a b : α) : max a b - min a b = abs (a - b) := begin cases le_total a b with ab ba, { rw [max_eq_right ab, min_eq_left ab, abs_of_nonpos, neg_sub], rwa sub_nonpos }, { rw [max_eq_left ba, min_eq_right ba, abs_of_nonneg], rwa sub_nonneg } end lemma max_sub_min_eq_abs (a b : α) : max a b - min a b = abs (b - a) := by { rw abs_sub_comm, exact max_sub_min_eq_abs' _ _ } lemma abs_add (a b : α) : abs (a + b) ≤ abs a + abs b := abs_le.2 ⟨(neg_add (abs a) (abs b)).symm ▸ add_le_add (neg_le.2 $ neg_le_abs_self _) (neg_le.2 $ neg_le_abs_self _), add_le_add (le_abs_self _) (le_abs_self _)⟩ theorem abs_sub (a b : α) : abs (a - b) ≤ abs a + abs b := by { rw [sub_eq_add_neg, ←abs_neg b], exact abs_add a _ } lemma abs_sub_le_iff : abs (a - b) ≤ c ↔ a - b ≤ c ∧ b - a ≤ c := by rw [abs_le, neg_le_sub_iff_le_add, @sub_le_iff_le_add' _ _ b, and_comm] lemma abs_sub_lt_iff : abs (a - b) < c ↔ a - b < c ∧ b - a < c := by rw [abs_lt, neg_lt_sub_iff_lt_add, @sub_lt_iff_lt_add' _ _ b, and_comm] lemma sub_le_of_abs_sub_le_left (h : abs (a - b) ≤ c) : b - c ≤ a := sub_le.1 $ (abs_sub_le_iff.1 h).2 lemma sub_le_of_abs_sub_le_right (h : abs (a - b) ≤ c) : a - c ≤ b := sub_le_of_abs_sub_le_left (abs_sub_comm a b ▸ h) lemma sub_lt_of_abs_sub_lt_left (h : abs (a - b) < c) : b - c < a := sub_lt.1 $ (abs_sub_lt_iff.1 h).2 lemma sub_lt_of_abs_sub_lt_right (h : abs (a - b) < c) : a - c < b := sub_lt_of_abs_sub_lt_left (abs_sub_comm a b ▸ h) lemma abs_sub_abs_le_abs_sub (a b : α) : abs a - abs b ≤ abs (a - b) := sub_le_iff_le_add.2 $ calc abs a = abs (a - b + b) : by rw [sub_add_cancel] ... ≤ abs (a - b) + abs b : abs_add _ _ lemma abs_abs_sub_abs_le_abs_sub (a b : α) : abs (abs a - abs b) ≤ abs (a - b) := abs_sub_le_iff.2 ⟨abs_sub_abs_le_abs_sub _ _, by rw abs_sub_comm; apply abs_sub_abs_le_abs_sub⟩ lemma eq_or_eq_neg_of_abs_eq (h : abs a = b) : a = b ∨ a = -b := by simpa only [← h, eq_comm, eq_neg_iff_eq_neg] using abs_choice a lemma abs_eq (hb : 0 ≤ b) : abs a = b ↔ a = b ∨ a = -b := begin refine ⟨eq_or_eq_neg_of_abs_eq, _⟩, rintro (rfl|rfl); simp only [abs_neg, abs_of_nonneg hb] end lemma abs_eq_abs : abs a = abs b ↔ a = b ∨ a = -b := begin refine ⟨λ h, _, λ h, _⟩, { obtain rfl | rfl := eq_or_eq_neg_of_abs_eq h; simpa only [neg_eq_iff_neg_eq, neg_inj, or.comm, @eq_comm _ (-b)] using abs_choice b }, { cases h; simp only [h, abs_neg] }, end lemma abs_le_max_abs_abs (hab : a ≤ b) (hbc : b ≤ c) : abs b ≤ max (abs a) (abs c) := abs_le'.2 ⟨by simp [hbc.trans (le_abs_self c)], by simp [(neg_le_neg hab).trans (neg_le_abs_self a)]⟩ theorem abs_le_abs (h₀ : a ≤ b) (h₁ : -a ≤ b) : abs a ≤ abs b := (abs_le'.2 ⟨h₀, h₁⟩).trans (le_abs_self b) lemma abs_max_sub_max_le_abs (a b c : α) : abs (max a c - max b c) ≤ abs (a - b) := begin simp_rw [abs_le, le_sub_iff_add_le, sub_le_iff_le_add, ← max_add_add_left], split; apply max_le_max; simp only [← le_sub_iff_add_le, ← sub_le_iff_le_add, sub_self, neg_le, neg_le_abs_self, neg_zero, abs_nonneg, le_abs_self] end lemma eq_of_abs_sub_eq_zero {a b : α} (h : abs (a - b) = 0) : a = b := sub_eq_zero.1 $ abs_eq_zero.1 h lemma abs_by_cases (P : α → Prop) {a : α} (h1 : P a) (h2 : P (-a)) : P (abs a) := sup_ind _ _ h1 h2 lemma abs_sub_le (a b c : α) : abs (a - c) ≤ abs (a - b) + abs (b - c) := calc abs (a - c) = abs (a - b + (b - c)) : by rw [sub_add_sub_cancel] ... ≤ abs (a - b) + abs (b - c) : abs_add _ _ lemma abs_add_three (a b c : α) : abs (a + b + c) ≤ abs a + abs b + abs c := (abs_add _ _).trans (add_le_add_right (abs_add _ _) _) lemma dist_bdd_within_interval {a b lb ub : α} (hal : lb ≤ a) (hau : a ≤ ub) (hbl : lb ≤ b) (hbu : b ≤ ub) : abs (a - b) ≤ ub - lb := abs_sub_le_iff.2 ⟨sub_le_sub hau hbl, sub_le_sub hbu hal⟩ lemma eq_of_abs_sub_nonpos (h : abs (a - b) ≤ 0) : a = b := eq_of_abs_sub_eq_zero (le_antisymm h (abs_nonneg (a - b))) instance with_top.linear_ordered_add_comm_group_with_top : linear_ordered_add_comm_group_with_top (with_top α) := { neg := option.map (λ a : α, -a), neg_top := @option.map_none _ _ (λ a : α, -a), add_neg_cancel := begin rintro (a | a) ha, { exact (ha rfl).elim }, exact with_top.coe_add.symm.trans (with_top.coe_eq_coe.2 (add_neg_self a)), end, .. with_top.linear_ordered_add_comm_monoid_with_top, .. option.nontrivial } end linear_ordered_add_comm_group /-- This is not so much a new structure as a construction mechanism for ordered groups, by specifying only the "positive cone" of the group. -/ class nonneg_add_comm_group (α : Type*) extends add_comm_group α := (nonneg : α → Prop) (pos : α → Prop := λ a, nonneg a ∧ ¬ nonneg (neg a)) (pos_iff : ∀ a, pos a ↔ nonneg a ∧ ¬ nonneg (-a) . order_laws_tac) (zero_nonneg : nonneg 0) (add_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a + b)) (nonneg_antisymm : ∀ {a}, nonneg a → nonneg (-a) → a = 0) namespace nonneg_add_comm_group variable [s : nonneg_add_comm_group α] include s @[reducible, priority 100] -- see Note [lower instance priority] instance to_ordered_add_comm_group : ordered_add_comm_group α := { le := λ a b, nonneg (b - a), lt := λ a b, pos (b - a), lt_iff_le_not_le := λ a b, by simp; rw [pos_iff]; simp, le_refl := λ a, by simp [zero_nonneg], le_trans := λ a b c nab nbc, by simp [-sub_eq_add_neg]; rw ← sub_add_sub_cancel; exact add_nonneg nbc nab, le_antisymm := λ a b nab nba, eq_of_sub_eq_zero $ nonneg_antisymm nba (by rw neg_sub; exact nab), add_le_add_left := λ a b nab c, by simpa [(≤), preorder.le] using nab, ..s } theorem nonneg_def {a : α} : nonneg a ↔ 0 ≤ a := show _ ↔ nonneg _, by simp theorem pos_def {a : α} : pos a ↔ 0 < a := show _ ↔ pos _, by simp theorem not_zero_pos : ¬ pos (0 : α) := mt pos_def.1 (lt_irrefl _) theorem zero_lt_iff_nonneg_nonneg {a : α} : 0 < a ↔ nonneg a ∧ ¬ nonneg (-a) := pos_def.symm.trans (pos_iff _) theorem nonneg_total_iff : (∀ a : α, nonneg a ∨ nonneg (-a)) ↔ (∀ a b : α, a ≤ b ∨ b ≤ a) := ⟨λ h a b, by have := h (b - a); rwa [neg_sub] at this, λ h a, by rw [nonneg_def, nonneg_def, neg_nonneg]; apply h⟩ /-- A `nonneg_add_comm_group` is a `linear_ordered_add_comm_group` if `nonneg` is total and decidable. -/ def to_linear_ordered_add_comm_group [decidable_pred (@nonneg α _)] (nonneg_total : ∀ a : α, nonneg a ∨ nonneg (-a)) : linear_ordered_add_comm_group α := { le := (≤), lt := (<), le_total := nonneg_total_iff.1 nonneg_total, decidable_le := by apply_instance, decidable_lt := by apply_instance, ..@nonneg_add_comm_group.to_ordered_add_comm_group _ s } end nonneg_add_comm_group namespace order_dual instance [ordered_add_comm_group α] : ordered_add_comm_group (order_dual α) := { add_left_neg := λ a : α, add_left_neg a, sub := λ a b, (a - b : α), ..order_dual.ordered_add_comm_monoid, ..show add_comm_group α, by apply_instance } instance [linear_ordered_add_comm_group α] : linear_ordered_add_comm_group (order_dual α) := { add_le_add_left := λ a b h c, by exact add_le_add_left h _, ..order_dual.linear_order α, ..show add_comm_group α, by apply_instance } end order_dual namespace prod variables {G H : Type*} @[to_additive] instance [ordered_comm_group G] [ordered_comm_group H] : ordered_comm_group (G × H) := { .. prod.comm_group, .. prod.partial_order G H, .. prod.ordered_cancel_comm_monoid } end prod section type_tags instance [ordered_add_comm_group α] : ordered_comm_group (multiplicative α) := { ..multiplicative.comm_group, ..multiplicative.ordered_comm_monoid } instance [ordered_comm_group α] : ordered_add_comm_group (additive α) := { ..additive.add_comm_group, ..additive.ordered_add_comm_monoid } instance [linear_ordered_add_comm_group α] : linear_ordered_comm_group (multiplicative α) := { ..multiplicative.linear_order, ..multiplicative.ordered_comm_group } instance [linear_ordered_comm_group α] : linear_ordered_add_comm_group (additive α) := { ..additive.linear_order, ..additive.ordered_add_comm_group } end type_tags
2eae61d86f4c6216a47ca4d2e02b27eccca99bb4
130c49f47783503e462c16b2eff31933442be6ff
/src/Lean/MetavarContext.lean
b39a987a567408a4fb20f10ec2fdcabacea1dd79
[ "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
54,588
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.MonadCache import Lean.LocalContext namespace Lean /- The metavariable context stores metavariable declarations and their assignments. It is used in the elaborator, tactic framework, unifier (aka `isDefEq`), and type class resolution (TC). First, we list all the requirements imposed by these modules. - We may invoke TC while executing `isDefEq`. We need this feature to be able to solve unification problems such as: ``` f ?a (ringAdd ?s) ?x ?y =?= f Int intAdd n m ``` where `(?a : Type) (?s : Ring ?a) (?x ?y : ?a)` During `isDefEq` (i.e., unification), it will need to solve the constrain ``` ringAdd ?s =?= intAdd ``` We say `ringAdd ?s` is stuck because it cannot be reduced until we synthesize the term `?s : Ring ?a` using TC. This can be done since we have assigned `?a := Int` when solving `?a =?= Int`. - TC uses `isDefEq`, and `isDefEq` may create TC problems as shown above. Thus, we may have nested TC problems. - `isDefEq` extends the local context when going inside binders. Thus, the local context for nested TC may be an extension of the local context for outer TC. - TC should not assign metavariables created by the elaborator, simp, tactic framework, and outer TC problems. Reason: TC commits to the first solution it finds. Consider the TC problem `Coe Nat ?x`, where `?x` is a metavariable created by the caller. There are many solutions to this problem (e.g., `?x := Int`, `?x := Real`, ...), and it doesn’t make sense to commit to the first one since TC does not know the constraints the caller may impose on `?x` after the TC problem is solved. Remark: we claim it is not feasible to make the whole system backtrackable, and allow the caller to backtrack back to TC and ask it for another solution if the first one found did not work. We claim it would be too inefficient. - TC metavariables should not leak outside of TC. Reason: we want to get rid of them after we synthesize the instance. - `simp` invokes `isDefEq` for matching the left-hand-side of equations to terms in our goal. Thus, it may invoke TC indirectly. - In Lean3, we didn’t have to create a fresh pattern for trying to match the left-hand-side of equations when executing `simp`. We had a mechanism called "tmp" metavariables. It avoided this overhead, but it created many problems since `simp` may indirectly call TC which may recursively call TC. Moreover, we may want to allow TC to invoke tactics in the future. Thus, when `simp` invokes `isDefEq`, it may indirectly invoke a tactic and `simp` itself. The Lean3 approach assumed that metavariables were short-lived, this is not true in Lean4, and to some extent was also not true in Lean3 since `simp`, in principle, could trigger an arbitrary number of nested TC problems. - Here are some possible call stack traces we could have in Lean3 (and Lean4). ``` Elaborator (-> TC -> isDefEq)+ Elaborator -> isDefEq (-> TC -> isDefEq)* Elaborator -> simp -> isDefEq (-> TC -> isDefEq)* ``` In Lean4, TC may also invoke tactics in the future. - In Lean3 and Lean4, TC metavariables are not really short-lived. We solve an arbitrary number of unification problems, and we may have nested TC invocations. - TC metavariables do not share the same local context even in the same invocation. In the C++ and Lean implementations we use a trick to ensure they do: https://github.com/leanprover/lean/blob/92826917a252a6092cffaf5fc5f1acb1f8cef379/src/library/type_context.cpp#L3583-L3594 - Metavariables may be natural, synthetic or syntheticOpaque. a) Natural metavariables may be assigned by unification (i.e., `isDefEq`). b) Synthetic metavariables may still be assigned by unification, but whenever possible `isDefEq` will avoid the assignment. For example, if we have the unification constaint `?m =?= ?n`, where `?m` is synthetic, but `?n` is not, `isDefEq` solves it by using the assignment `?n := ?m`. We use synthetic metavariables for type class resolution. Any module that creates synthetic metavariables, must also check whether they have been assigned by `isDefEq`, and then still synthesize them, and check whether the sythesized result is compatible with the one assigned by `isDefEq`. c) SyntheticOpaque metavariables are never assigned by `isDefEq`. That is, the constraint `?n =?= Nat.succ Nat.zero` always fail if `?n` is a syntheticOpaque metavariable. This kind of metavariable is created by tactics such as `intro`. Reason: in the tactic framework, subgoals as represented as metavariables, and a subgoal `?n` is considered as solved whenever the metavariable is assigned. This distinction was not precise in Lean3 and produced counterintuitive behavior. For example, the following hack was added in Lean3 to work around one of these issues: https://github.com/leanprover/lean/blob/92826917a252a6092cffaf5fc5f1acb1f8cef379/src/library/type_context.cpp#L2751 - When creating lambda/forall expressions, we need to convert/abstract free variables and convert them to bound variables. Now, suppose we a trying to create a lambda/forall expression by abstracting free variable `xs` and a term `t[?m]` which contains a metavariable `?m`, and the local context of `?m` contains `xs`. The term ``` fun xs => t[?m] ``` will be ill-formed if we later assign a term `s` to `?m`, and `s` contains free variables in `xs`. We address this issue by changing the free variable abstraction procedure. We consider two cases: `?m` is natural, `?m` is synthetic. Assume the type of `?m` is `A[xs]`. Then, in both cases we create an auxiliary metavariable `?n` with type `forall xs => A[xs]`, and local context := local context of `?m` - `xs`. In both cases, we produce the term `fun xs => t[?n xs]` 1- If `?m` is natural or synthetic, then we assign `?m := ?n xs`, and we produce the term `fun xs => t[?n xs]` 2- If `?m` is syntheticOpaque, then we mark `?n` as a syntheticOpaque variable. However, `?n` is managed by the metavariable context itself. We say we have a "delayed assignment" `?n xs := ?m`. That is, after a term `s` is assigned to `?m`, and `s` does not contain metavariables, we replace any occurrence `?n ts` with `s[xs := ts]`. Gruesome details: - When we create the type `forall xs => A` for `?n`, we may encounter the same issue if `A` contains metavariables. So, the process above is recursive. We claim it terminates because we keep creating new metavariables with smaller local contexts. - Suppose, we have `t[?m]` and we want to create a let-expression by abstracting a let-decl free variable `x`, and the local context of `?m` contatins `x`. Similarly to the previous case ``` let x : T := v; t[?m] ``` will be ill-formed if we later assign a term `s` to `?m`, and `s` contains free variable `x`. Again, assume the type of `?m` is `A[x]`. 1- If `?m` is natural or synthetic, then we create `?n : (let x : T := v; A[x])` with and local context := local context of `?m` - `x`, we assign `?m := ?n`, and produce the term `let x : T := v; t[?n]`. That is, we are just making sure `?n` must never be assigned to a term containing `x`. 2- If `?m` is syntheticOpaque, we create a fresh syntheticOpaque `?n` with type `?n : T -> (let x : T := v; A[x])` and local context := local context of `?m` - `x`, create the delayed assignment `?n #[x] := ?m`, and produce the term `let x : T := v; t[?n x]`. Now suppose we assign `s` to `?m`. We do not assign the term `fun (x : T) => s` to `?n`, since `fun (x : T) => s` may not even be type correct. Instead, we just replace applications `?n r` with `s[x/r]`. The term `r` may not necessarily be a bound variable. For example, a tactic may have reduced `let x : T := v; t[?n x]` into `t[?n v]`. We are essentially using the pair "delayed assignment + application" to implement a delayed substitution. - We use TC for implementing coercions. Both Joe Hendrix and Reid Barton reported a nasty limitation. In Lean3, TC will not be used if there are metavariables in the TC problem. For example, the elaborator will not try to synthesize `Coe Nat ?x`. This is good, but this constraint is too strict for problems such as `Coe (Vector Bool ?n) (BV ?n)`. The coercion exists independently of `?n`. Thus, during TC, we want `isDefEq` to throw an exception instead of return `false` whenever it tries to assign a metavariable owned by its caller. The idea is to sign to the caller that it cannot solve the TC problem at this point, and more information is needed. That is, the caller must make progress an assign its metavariables before trying to invoke TC again. In Lean4, we are using a simpler design for the `MetavarContext`. - No distinction betwen temporary and regular metavariables. - Metavariables have a `depth` Nat field. - MetavarContext also has a `depth` field. - We bump the `MetavarContext` depth when we create a nested problem. Example: Elaborator (depth = 0) -> Simplifier matcher (depth = 1) -> TC (level = 2) -> TC (level = 3) -> ... - When `MetavarContext` is at depth N, `isDefEq` does not assign variables from `depth < N`. - Metavariables from depth N+1 must be fully assigned before we return to level N. - New design even allows us to invoke tactics from TC. * Main concern We don't have tmp metavariables anymore in Lean4. Thus, before trying to match the left-hand-side of an equation in `simp`. We first must bump the level of the `MetavarContext`, create fresh metavariables, then create a new pattern by replacing the free variable on the left-hand-side with these metavariables. We are hoping to minimize this overhead by - Using better indexing data structures in `simp`. They should reduce the number of time `simp` must invoke `isDefEq`. - Implementing `isDefEqApprox` which ignores metavariables and returns only `false` or `undef`. It is a quick filter that allows us to fail quickly and avoid the creation of new fresh metavariables, and a new pattern. - Adding built-in support for arithmetic, Logical connectives, etc. Thus, we avoid a bunch of lemmas in the simp set. - Adding support for AC-rewriting. In Lean3, users use AC lemmas as rewriting rules for "sorting" terms. This is inefficient, requires a quadratic number of rewrite steps, and does not preserve the structure of the goal. The temporary metavariables were also used in the "app builder" module used in Lean3. The app builder uses `isDefEq`. So, it could, in principle, invoke an arbitrary number of nested TC problems. However, in Lean3, all app builder uses are controlled. That is, it is mainly used to synthesize implicit arguments using very simple unification and/or non-nested TC. So, if the "app builder" becomes a bottleneck without tmp metavars, we may solve the issue by implementing `isDefEqCheap` that never invokes TC and uses tmp metavars. -/ structure LocalInstance where className : Name fvar : Expr deriving Inhabited abbrev LocalInstances := Array LocalInstance instance : BEq LocalInstance where beq i₁ i₂ := i₁.fvar == i₂.fvar /-- Remove local instance with the given `fvarId`. Do nothing if `localInsts` does not contain any free variable with id `fvarId`. -/ def LocalInstances.erase (localInsts : LocalInstances) (fvarId : FVarId) : LocalInstances := match localInsts.findIdx? (fun inst => inst.fvar.fvarId! == fvarId) with | some idx => localInsts.eraseIdx idx | _ => localInsts inductive MetavarKind where | natural | synthetic | syntheticOpaque deriving Inhabited def MetavarKind.isSyntheticOpaque : MetavarKind → Bool | MetavarKind.syntheticOpaque => true | _ => false def MetavarKind.isNatural : MetavarKind → Bool | MetavarKind.natural => true | _ => false structure MetavarDecl where userName : Name := Name.anonymous lctx : LocalContext type : Expr depth : Nat localInstances : LocalInstances kind : MetavarKind numScopeArgs : Nat := 0 -- See comment at `CheckAssignment` `Meta/ExprDefEq.lean` index : Nat -- We use this field to track how old a metavariable is. It is set using a counter at `MetavarContext` deriving Inhabited /-- A delayed assignment for a metavariable `?m`. It represents an assignment of the form `?m := (fun fvars => val)`. The local context `lctx` provides the declarations for `fvars`. Note that `fvars` may not be defined in the local context for `?m`. - TODO: after we delete the old frontend, we can remove the field `lctx`. This field is only used in old C++ implementation. -/ structure DelayedMetavarAssignment where lctx : LocalContext fvars : Array Expr val : Expr open Std (HashMap PersistentHashMap) structure MetavarContext where depth : Nat := 0 mvarCounter : Nat := 0 -- Counter for setting the field `index` at `MetavarDecl` lDepth : PersistentHashMap MVarId Nat := {} decls : PersistentHashMap MVarId MetavarDecl := {} lAssignment : PersistentHashMap MVarId Level := {} eAssignment : PersistentHashMap MVarId Expr := {} dAssignment : PersistentHashMap MVarId DelayedMetavarAssignment := {} class MonadMCtx (m : Type → Type) where getMCtx : m MetavarContext modifyMCtx : (MetavarContext → MetavarContext) → m Unit export MonadMCtx (getMCtx modifyMCtx) instance (m n) [MonadLift m n] [MonadMCtx m] : MonadMCtx n where getMCtx := liftM (getMCtx : m _) modifyMCtx := fun f => liftM (modifyMCtx f : m _) namespace MetavarContext instance : Inhabited MetavarContext := ⟨{}⟩ @[export lean_mk_metavar_ctx] def mkMetavarContext : Unit → MetavarContext := fun _ => {} /- Low level API for adding/declaring metavariable declarations. It is used to implement actions in the monads `MetaM`, `ElabM` and `TacticM`. It should not be used directly since the argument `(mvarId : MVarId)` is assumed to be "unique". -/ def addExprMVarDecl (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) (lctx : LocalContext) (localInstances : LocalInstances) (type : Expr) (kind : MetavarKind := MetavarKind.natural) (numScopeArgs : Nat := 0) : MetavarContext := { mctx with mvarCounter := mctx.mvarCounter + 1 decls := mctx.decls.insert mvarId { depth := mctx.depth index := mctx.mvarCounter userName lctx localInstances type kind numScopeArgs } } def addExprMVarDeclExp (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) (lctx : LocalContext) (localInstances : LocalInstances) (type : Expr) (kind : MetavarKind) : MetavarContext := addExprMVarDecl mctx mvarId userName lctx localInstances type kind /- Low level API for adding/declaring universe level metavariable declarations. It is used to implement actions in the monads `MetaM`, `ElabM` and `TacticM`. It should not be used directly since the argument `(mvarId : MVarId)` is assumed to be "unique". -/ def addLevelMVarDecl (mctx : MetavarContext) (mvarId : MVarId) : MetavarContext := { mctx with lDepth := mctx.lDepth.insert mvarId mctx.depth } def findDecl? (mctx : MetavarContext) (mvarId : MVarId) : Option MetavarDecl := mctx.decls.find? mvarId def getDecl (mctx : MetavarContext) (mvarId : MVarId) : MetavarDecl := match mctx.decls.find? mvarId with | some decl => decl | none => panic! "unknown metavariable" def findUserName? (mctx : MetavarContext) (userName : Name) : Option MVarId := let search : Except MVarId Unit := mctx.decls.forM fun mvarId decl => if decl.userName == userName then throw mvarId else pure () match search with | Except.ok _ => none | Except.error mvarId => some mvarId def setMVarKind (mctx : MetavarContext) (mvarId : MVarId) (kind : MetavarKind) : MetavarContext := let decl := mctx.getDecl mvarId { mctx with decls := mctx.decls.insert mvarId { decl with kind := kind } } def setMVarUserName (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) : MetavarContext := let decl := mctx.getDecl mvarId { mctx with decls := mctx.decls.insert mvarId { decl with userName := userName } } /- Update the type of the given metavariable. This function assumes the new type is definitionally equal to the current one -/ def setMVarType (mctx : MetavarContext) (mvarId : MVarId) (type : Expr) : MetavarContext := let decl := mctx.getDecl mvarId { mctx with decls := mctx.decls.insert mvarId { decl with type := type } } def findLevelDepth? (mctx : MetavarContext) (mvarId : MVarId) : Option Nat := mctx.lDepth.find? mvarId def getLevelDepth (mctx : MetavarContext) (mvarId : MVarId) : Nat := match mctx.findLevelDepth? mvarId with | some d => d | none => panic! "unknown metavariable" def isAnonymousMVar (mctx : MetavarContext) (mvarId : MVarId) : Bool := match mctx.findDecl? mvarId with | none => false | some mvarDecl => mvarDecl.userName.isAnonymous def renameMVar (mctx : MetavarContext) (mvarId : MVarId) (newUserName : Name) : MetavarContext := match mctx.findDecl? mvarId with | none => panic! "unknown metavariable" | some mvarDecl => { mctx with decls := mctx.decls.insert mvarId { mvarDecl with userName := newUserName } } def assignLevel (m : MetavarContext) (mvarId : MVarId) (val : Level) : MetavarContext := { m with lAssignment := m.lAssignment.insert mvarId val } def assignExpr (m : MetavarContext) (mvarId : MVarId) (val : Expr) : MetavarContext := { m with eAssignment := m.eAssignment.insert mvarId val } def assignDelayed (m : MetavarContext) (mvarId : MVarId) (lctx : LocalContext) (fvars : Array Expr) (val : Expr) : MetavarContext := { m with dAssignment := m.dAssignment.insert mvarId { lctx := lctx, fvars := fvars, val := val } } def getLevelAssignment? (m : MetavarContext) (mvarId : MVarId) : Option Level := m.lAssignment.find? mvarId def getExprAssignment? (m : MetavarContext) (mvarId : MVarId) : Option Expr := m.eAssignment.find? mvarId def getDelayedAssignment? (m : MetavarContext) (mvarId : MVarId) : Option DelayedMetavarAssignment := m.dAssignment.find? mvarId def isLevelAssigned (m : MetavarContext) (mvarId : MVarId) : Bool := m.lAssignment.contains mvarId def isExprAssigned (m : MetavarContext) (mvarId : MVarId) : Bool := m.eAssignment.contains mvarId def isDelayedAssigned (m : MetavarContext) (mvarId : MVarId) : Bool := m.dAssignment.contains mvarId def eraseDelayed (m : MetavarContext) (mvarId : MVarId) : MetavarContext := { m with dAssignment := m.dAssignment.erase mvarId } /- Given a sequence of delayed assignments ``` mvarId₁ := mvarId₂ ...; ... mvarIdₙ := mvarId_root ... -- where `mvarId_root` is not delayed assigned ``` in `mctx`, `getDelayedRoot mctx mvarId₁` return `mvarId_root`. If `mvarId₁` is not delayed assigned then return `mvarId₁` -/ partial def getDelayedRoot (m : MetavarContext) : MVarId → MVarId | mvarId => match getDelayedAssignment? m mvarId with | some d => match d.val.getAppFn with | Expr.mvar mvarId _ => getDelayedRoot m mvarId | _ => mvarId | none => mvarId def isLevelAssignable (mctx : MetavarContext) (mvarId : MVarId) : Bool := match mctx.lDepth.find? mvarId with | some d => d == mctx.depth | _ => panic! "unknown universe metavariable" def isExprAssignable (mctx : MetavarContext) (mvarId : MVarId) : Bool := let decl := mctx.getDecl mvarId decl.depth == mctx.depth def incDepth (mctx : MetavarContext) : MetavarContext := { mctx with depth := mctx.depth + 1 } /-- Return true iff the given level contains an assigned metavariable. -/ def hasAssignedLevelMVar (mctx : MetavarContext) : Level → Bool | Level.succ lvl _ => lvl.hasMVar && hasAssignedLevelMVar mctx lvl | Level.max lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignedLevelMVar mctx lvl₁) || (lvl₂.hasMVar && hasAssignedLevelMVar mctx lvl₂) | Level.imax lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignedLevelMVar mctx lvl₁) || (lvl₂.hasMVar && hasAssignedLevelMVar mctx lvl₂) | Level.mvar mvarId _ => mctx.isLevelAssigned mvarId | Level.zero _ => false | Level.param _ _ => false /-- Return `true` iff expression contains assigned (level/expr) metavariables or delayed assigned mvars -/ def hasAssignedMVar (mctx : MetavarContext) : Expr → Bool | Expr.const _ lvls _ => lvls.any (hasAssignedLevelMVar mctx) | Expr.sort lvl _ => hasAssignedLevelMVar mctx lvl | Expr.app f a _ => (f.hasMVar && hasAssignedMVar mctx f) || (a.hasMVar && hasAssignedMVar mctx a) | Expr.letE _ t v b _ => (t.hasMVar && hasAssignedMVar mctx t) || (v.hasMVar && hasAssignedMVar mctx v) || (b.hasMVar && hasAssignedMVar mctx b) | Expr.forallE _ d b _ => (d.hasMVar && hasAssignedMVar mctx d) || (b.hasMVar && hasAssignedMVar mctx b) | Expr.lam _ d b _ => (d.hasMVar && hasAssignedMVar mctx d) || (b.hasMVar && hasAssignedMVar mctx b) | Expr.fvar _ _ => false | Expr.bvar _ _ => false | Expr.lit _ _ => false | Expr.mdata _ e _ => e.hasMVar && hasAssignedMVar mctx e | Expr.proj _ _ e _ => e.hasMVar && hasAssignedMVar mctx e | Expr.mvar mvarId _ => mctx.isExprAssigned mvarId || mctx.isDelayedAssigned mvarId /-- Return true iff the given level contains a metavariable that can be assigned. -/ def hasAssignableLevelMVar (mctx : MetavarContext) : Level → Bool | Level.succ lvl _ => lvl.hasMVar && hasAssignableLevelMVar mctx lvl | Level.max lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignableLevelMVar mctx lvl₁) || (lvl₂.hasMVar && hasAssignableLevelMVar mctx lvl₂) | Level.imax lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignableLevelMVar mctx lvl₁) || (lvl₂.hasMVar && hasAssignableLevelMVar mctx lvl₂) | Level.mvar mvarId _ => mctx.isLevelAssignable mvarId | Level.zero _ => false | Level.param _ _ => false /-- Return `true` iff expression contains a metavariable that can be assigned. -/ def hasAssignableMVar (mctx : MetavarContext) : Expr → Bool | Expr.const _ lvls _ => lvls.any (hasAssignableLevelMVar mctx) | Expr.sort lvl _ => hasAssignableLevelMVar mctx lvl | Expr.app f a _ => (f.hasMVar && hasAssignableMVar mctx f) || (a.hasMVar && hasAssignableMVar mctx a) | Expr.letE _ t v b _ => (t.hasMVar && hasAssignableMVar mctx t) || (v.hasMVar && hasAssignableMVar mctx v) || (b.hasMVar && hasAssignableMVar mctx b) | Expr.forallE _ d b _ => (d.hasMVar && hasAssignableMVar mctx d) || (b.hasMVar && hasAssignableMVar mctx b) | Expr.lam _ d b _ => (d.hasMVar && hasAssignableMVar mctx d) || (b.hasMVar && hasAssignableMVar mctx b) | Expr.fvar _ _ => false | Expr.bvar _ _ => false | Expr.lit _ _ => false | Expr.mdata _ e _ => e.hasMVar && hasAssignableMVar mctx e | Expr.proj _ _ e _ => e.hasMVar && hasAssignableMVar mctx e | Expr.mvar mvarId _ => mctx.isExprAssignable mvarId /- Notes on artificial eta-expanded terms due to metavariables. We try avoid synthetic terms such as `((fun x y => t) a b)` in the output produced by the elaborator. This kind of term may be generated when instantiating metavariable assignments. This module tries to avoid their generation because they often introduce unnecessary dependencies and may affect automation. When elaborating terms, we use metavariables to represent "holes". Each hole has a context which includes all free variables that may be used to "fill" the hole. Suppose, we create a metavariable (hole) `?m : Nat` in a context containing `(x : Nat) (y : Nat) (b : Bool)`, then we can assign terms such as `x + y` to `?m` since `x` and `y` are in the context used to create `?m`. Now, suppose we have the term `?m + 1` and we want to create the lambda expression `fun x => ?m + 1`. This term is not correct since we may assign to `?m` a term containing `x`. We address this issue by create a synthetic metavariable `?n : Nat → Nat` and adding the delayed assignment `?n #[x] := ?m`, and the term `fun x => ?n x + 1`. When we later assign a term `t[x]` to `?m`, `fun x => t[x]` is assigned to `?n`, and if we substitute it at `fun x => ?n x + 1`, we produce `fun x => ((fun x => t[x]) x) + 1`. To avoid this term eta-expanded term, we apply beta-reduction when instantiating metavariable assignments in this module. This operation is performed at `instantiateExprMVars`, `elimMVarDeps`, and `levelMVarToParam`. -/ partial def instantiateLevelMVars [Monad m] [MonadMCtx m] : Level → m Level | lvl@(Level.succ lvl₁ _) => return Level.updateSucc! lvl (← instantiateLevelMVars lvl₁) | lvl@(Level.max lvl₁ lvl₂ _) => return Level.updateMax! lvl (← instantiateLevelMVars lvl₁) (← instantiateLevelMVars lvl₂) | lvl@(Level.imax lvl₁ lvl₂ _) => return Level.updateIMax! lvl (← instantiateLevelMVars lvl₁) (← instantiateLevelMVars lvl₂) | lvl@(Level.mvar mvarId _) => do match getLevelAssignment? (← getMCtx) mvarId with | some newLvl => if !newLvl.hasMVar then pure newLvl else do let newLvl' ← instantiateLevelMVars newLvl modifyMCtx fun mctx => mctx.assignLevel mvarId newLvl' pure newLvl' | none => pure lvl | lvl => pure lvl /-- instantiateExprMVars main function -/ partial def instantiateExprMVars [Monad m] [MonadMCtx m] [STWorld ω m] [MonadLiftT (ST ω) m] (e : Expr) : MonadCacheT ExprStructEq Expr m Expr := if !e.hasMVar then pure e else checkCache { val := e : ExprStructEq } fun _ => do match e with | Expr.proj _ _ s _ => return e.updateProj! (← instantiateExprMVars s) | Expr.forallE _ d b _ => return e.updateForallE! (← instantiateExprMVars d) (← instantiateExprMVars b) | Expr.lam _ d b _ => return e.updateLambdaE! (← instantiateExprMVars d) (← instantiateExprMVars b) | Expr.letE _ t v b _ => return e.updateLet! (← instantiateExprMVars t) (← instantiateExprMVars v) (← instantiateExprMVars b) | Expr.const _ lvls _ => return e.updateConst! (← lvls.mapM instantiateLevelMVars) | Expr.sort lvl _ => return e.updateSort! (← instantiateLevelMVars lvl) | Expr.mdata _ b _ => return e.updateMData! (← instantiateExprMVars b) | Expr.app .. => e.withApp fun f args => do let instArgs (f : Expr) : MonadCacheT ExprStructEq Expr m Expr := do let args ← args.mapM instantiateExprMVars pure (mkAppN f args) let instApp : MonadCacheT ExprStructEq Expr m Expr := do let wasMVar := f.isMVar let f ← instantiateExprMVars f if wasMVar && f.isLambda then /- Some of the arguments in args are irrelevant after we beta reduce. -/ instantiateExprMVars (f.betaRev args.reverse) else instArgs f match f with | Expr.mvar mvarId _ => let mctx ← getMCtx match mctx.getDelayedAssignment? mvarId with | none => instApp | some { fvars := fvars, val := val, .. } => /- Apply "delayed substitution" (i.e., delayed assignment + application). That is, `f` is some metavariable `?m`, that is delayed assigned to `val`. If after instantiating `val`, we obtain `newVal`, and `newVal` does not contain metavariables, we replace the free variables `fvars` in `newVal` with the first `fvars.size` elements of `args`. -/ if fvars.size > args.size then /- We don't have sufficient arguments for instantiating the free variables `fvars`. This can only happy if a tactic or elaboration function is not implemented correctly. We decided to not use `panic!` here and report it as an error in the frontend when we are checking for unassigned metavariables in an elaborated term. -/ instArgs f else let newVal ← instantiateExprMVars val if newVal.hasExprMVar then instArgs f else do let args ← args.mapM instantiateExprMVars /- Example: suppose we have `?m t1 t2 t3` That is, `f := ?m` and `args := #[t1, t2, t3]` Morever, `?m` is delayed assigned `?m #[x, y] := f x y` where, `fvars := #[x, y]` and `newVal := f x y`. After abstracting `newVal`, we have `f (Expr.bvar 0) (Expr.bvar 1)`. After `instantiaterRevRange 0 2 args`, we have `f t1 t2`. After `mkAppRange 2 3`, we have `f t1 t2 t3` -/ let newVal := newVal.abstract fvars let result := newVal.instantiateRevRange 0 fvars.size args let result := mkAppRange result fvars.size args.size args pure result | _ => instApp | e@(Expr.mvar mvarId _) => checkCache { val := e : ExprStructEq } fun _ => do let mctx ← getMCtx match mctx.getExprAssignment? mvarId with | some newE => do let newE' ← instantiateExprMVars newE modifyMCtx fun mctx => mctx.assignExpr mvarId newE' pure newE' | none => pure e | e => pure e instance : MonadMCtx (StateRefT MetavarContext (ST ω)) where getMCtx := get modifyMCtx := modify def instantiateMVars (mctx : MetavarContext) (e : Expr) : Expr × MetavarContext := if !e.hasMVar then (e, mctx) else let instantiate {ω} (e : Expr) : (MonadCacheT ExprStructEq Expr $ StateRefT MetavarContext $ ST ω) Expr := instantiateExprMVars e runST fun _ => instantiate e |>.run |>.run mctx def instantiateLCtxMVars (mctx : MetavarContext) (lctx : LocalContext) : LocalContext × MetavarContext := lctx.foldl (init := ({}, mctx)) fun (lctx, mctx) ldecl => match ldecl with | LocalDecl.cdecl _ fvarId userName type bi => let (type, mctx) := mctx.instantiateMVars type (lctx.mkLocalDecl fvarId userName type bi, mctx) | LocalDecl.ldecl _ fvarId userName type value nonDep => let (type, mctx) := mctx.instantiateMVars type let (value, mctx) := mctx.instantiateMVars value (lctx.mkLetDecl fvarId userName type value nonDep, mctx) def instantiateMVarDeclMVars (mctx : MetavarContext) (mvarId : MVarId) : MetavarContext := let mvarDecl := mctx.getDecl mvarId let (lctx, mctx) := mctx.instantiateLCtxMVars mvarDecl.lctx let (type, mctx) := mctx.instantiateMVars mvarDecl.type { mctx with decls := mctx.decls.insert mvarId { mvarDecl with lctx := lctx, type := type } } namespace DependsOn private abbrev M := StateM ExprSet private def shouldVisit (e : Expr) : M Bool := do if !e.hasMVar && !e.hasFVar then return false else if (← get).contains e then return false else modify fun s => s.insert e return true @[specialize] private partial def dep (mctx : MetavarContext) (p : FVarId → Bool) (e : Expr) : M Bool := let rec visit (e : Expr) : M Bool := do if !(← shouldVisit e) then pure false else visitMain e, visitMain : Expr → M Bool | Expr.proj _ _ s _ => visit s | Expr.forallE _ d b _ => visit d <||> visit b | Expr.lam _ d b _ => visit d <||> visit b | Expr.letE _ t v b _ => visit t <||> visit v <||> visit b | Expr.mdata _ b _ => visit b | Expr.app f a _ => visit a <||> if f.isApp then visitMain f else visit f | Expr.mvar mvarId _ => match mctx.getExprAssignment? mvarId with | some a => visit a | none => let lctx := (mctx.getDecl mvarId).lctx return lctx.any fun decl => p decl.fvarId | Expr.fvar fvarId _ => return p fvarId | e => pure false visit e @[inline] partial def main (mctx : MetavarContext) (p : FVarId → Bool) (e : Expr) : M Bool := if !e.hasFVar && !e.hasMVar then pure false else dep mctx p e end DependsOn /-- Return `true` iff `e` depends on a free variable `x` s.t. `p x` is `true`. For each metavariable `?m` occurring in `x` 1- If `?m := t`, then we visit `t` looking for `x` 2- If `?m` is unassigned, then we consider the worst case and check whether `x` is in the local context of `?m`. This case is a "may dependency". That is, we may assign a term `t` to `?m` s.t. `t` contains `x`. -/ @[inline] def findExprDependsOn (mctx : MetavarContext) (e : Expr) (p : FVarId → Bool) : Bool := DependsOn.main mctx p e |>.run' {} /-- Similar to `findExprDependsOn`, but checks the expressions in the given local declaration depends on a free variable `x` s.t. `p x` is `true`. -/ @[inline] def findLocalDeclDependsOn (mctx : MetavarContext) (localDecl : LocalDecl) (p : FVarId → Bool) : Bool := match localDecl with | LocalDecl.cdecl (type := t) .. => findExprDependsOn mctx t p | LocalDecl.ldecl (type := t) (value := v) .. => (DependsOn.main mctx p t <||> DependsOn.main mctx p v).run' {} def exprDependsOn (mctx : MetavarContext) (e : Expr) (fvarId : FVarId) : Bool := findExprDependsOn mctx e fun fvarId' => fvarId == fvarId' def localDeclDependsOn (mctx : MetavarContext) (localDecl : LocalDecl) (fvarId : FVarId) : Bool := findLocalDeclDependsOn mctx localDecl fun fvarId' => fvarId == fvarId' namespace MkBinding inductive Exception where | revertFailure (mctx : MetavarContext) (lctx : LocalContext) (toRevert : Array Expr) (decl : LocalDecl) instance : ToString Exception where toString | Exception.revertFailure _ lctx toRevert decl => "failed to revert " ++ toString (toRevert.map (fun x => "'" ++ toString (lctx.getFVar! x).userName ++ "'")) ++ ", '" ++ toString decl.userName ++ "' depends on them, and it is an auxiliary declaration created by the elaborator" ++ " (possible solution: use tactic 'clear' to remove '" ++ toString decl.userName ++ "' from local context)" /-- `MkBinding` and `elimMVarDepsAux` are mutually recursive, but `cache` is only used at `elimMVarDepsAux`. We use a single state object for convenience. We have a `NameGenerator` because we need to generate fresh auxiliary metavariables. -/ structure State where mctx : MetavarContext ngen : NameGenerator cache : HashMap ExprStructEq Expr := {} abbrev MCore := EStateM Exception State abbrev M := ReaderT Bool MCore def preserveOrder : M Bool := read instance : MonadHashMapCacheAdapter ExprStructEq Expr M where getCache := do let s ← get; pure s.cache modifyCache := fun f => modify fun s => { s with cache := f s.cache } /-- Return the local declaration of the free variable `x` in `xs` with the smallest index -/ private def getLocalDeclWithSmallestIdx (lctx : LocalContext) (xs : Array Expr) : LocalDecl := do let mut d : LocalDecl := lctx.getFVar! xs[0] for i in [1:xs.size] do let curr := lctx.getFVar! xs[i] if curr.index < d.index then d := curr return d /-- Given `toRevert` an array of free variables s.t. `lctx` contains their declarations, return a new array of free variables that contains `toRevert` and all free variables in `lctx` that may depend on `toRevert`. Remark: the result is sorted by `LocalDecl` indices. Remark: We used to throw an `Exception.revertFailure` exception when an auxiliary declaration had to be reversed. Recall that auxiliary declarations are created when compiling (mutually) recursive definitions. The `revertFailure` due to auxiliary declaration dependency was originally introduced in Lean3 to address issue https://github.com/leanprover/lean/issues/1258. In Lean4, this solution is not satisfactory because all definitions/theorems are potentially recursive. So, even an simple (incomplete) definition such as ``` variables {α : Type} in def f (a : α) : List α := _ ``` would trigger the `Exception.revertFailure` exception. In the definition above, the elaborator creates the auxiliary definition `f : {α : Type} → List α`. The `_` is elaborated as a new fresh variable `?m` that contains `α : Type`, `a : α`, and `f : α → List α` in its context, When we try to create the lambda `fun {α : Type} (a : α) => ?m`, we first need to create an auxiliary `?n` which do not contain `α` and `a` in its context. That is, we create the metavariable `?n : {α : Type} → (a : α) → (f : α → List α) → List α`, add the delayed assignment `?n #[α, a, f] := ?m α a f`, and create the lambda `fun {α : Type} (a : α) => ?n α a f`. See `elimMVarDeps` for more information. If we kept using the Lean3 approach, we would get the `Exception.revertFailure` exception because we are reverting the auxiliary definition `f`. Note that https://github.com/leanprover/lean/issues/1258 is not an issue in Lean4 because we have changed how we compile recursive definitions. -/ def collectDeps (mctx : MetavarContext) (lctx : LocalContext) (toRevert : Array Expr) (preserveOrder : Bool) : Except Exception (Array Expr) := do if toRevert.size == 0 then pure toRevert else if preserveOrder then -- Make sure none of `toRevert` is an AuxDecl -- Make sure toRevert[j] does not depend on toRevert[i] for j > i toRevert.size.forM fun i => do let fvar := toRevert[i] let decl := lctx.getFVar! fvar i.forM fun j => do let prevFVar := toRevert[j] let prevDecl := lctx.getFVar! prevFVar if localDeclDependsOn mctx prevDecl fvar.fvarId! then throw (Exception.revertFailure mctx lctx toRevert prevDecl) let newToRevert := if preserveOrder then toRevert else Array.mkEmpty toRevert.size let firstDeclToVisit := getLocalDeclWithSmallestIdx lctx toRevert let initSize := newToRevert.size lctx.foldlM (init := newToRevert) (start := firstDeclToVisit.index) fun (newToRevert : Array Expr) decl => if initSize.any fun i => decl.fvarId == (newToRevert.get! i).fvarId! then pure newToRevert else if toRevert.any fun x => decl.fvarId == x.fvarId! then pure (newToRevert.push decl.toExpr) else if findLocalDeclDependsOn mctx decl (fun fvarId => newToRevert.any fun x => x.fvarId! == fvarId) then pure (newToRevert.push decl.toExpr) else pure newToRevert /-- Create a new `LocalContext` by removing the free variables in `toRevert` from `lctx`. We use this function when we create auxiliary metavariables at `elimMVarDepsAux`. -/ def reduceLocalContext (lctx : LocalContext) (toRevert : Array Expr) : LocalContext := toRevert.foldr (init := lctx) fun x lctx => lctx.erase x.fvarId! @[inline] private def getMCtx : M MetavarContext := return (← get).mctx /-- Return free variables in `xs` that are in the local context `lctx` -/ private def getInScope (lctx : LocalContext) (xs : Array Expr) : Array Expr := xs.foldl (init := #[]) fun scope x => if lctx.contains x.fvarId! then scope.push x else scope /-- Execute `x` with an empty cache, and then restore the original cache. -/ @[inline] private def withFreshCache (x : M α) : M α := do let cache ← modifyGet fun s => (s.cache, { s with cache := {} }) let a ← x modify fun s => { s with cache := cache } pure a /-- Create an application `mvar ys` where `ys` are the free variables. See "Gruesome details" in the beginning of the file for understanding how let-decl free variables are handled. -/ private def mkMVarApp (lctx : LocalContext) (mvar : Expr) (xs : Array Expr) (kind : MetavarKind) : Expr := xs.foldl (init := mvar) fun e x => match kind with | MetavarKind.syntheticOpaque => mkApp e x | _ => if (lctx.getFVar! x).isLet then e else mkApp e x /-- Return true iff some `e` in `es` depends on `fvarId` -/ private def anyDependsOn (mctx : MetavarContext) (es : Array Expr) (fvarId : FVarId) : Bool := es.any fun e => exprDependsOn mctx e fvarId mutual private partial def visit (xs : Array Expr) (e : Expr) : M Expr := if !e.hasMVar then pure e else checkCache { val := e : ExprStructEq } fun _ => elim xs e private partial def elim (xs : Array Expr) (e : Expr) : M Expr := match e with | Expr.proj _ _ s _ => return e.updateProj! (← visit xs s) | Expr.forallE _ d b _ => return e.updateForallE! (← visit xs d) (← visit xs b) | Expr.lam _ d b _ => return e.updateLambdaE! (← visit xs d) (← visit xs b) | Expr.letE _ t v b _ => return e.updateLet! (← visit xs t) (← visit xs v) (← visit xs b) | Expr.mdata _ b _ => return e.updateMData! (← visit xs b) | Expr.app _ _ _ => e.withApp fun f args => elimApp xs f args | Expr.mvar mvarId _ => elimApp xs e #[] | e => return e private partial def mkAuxMVarType (lctx : LocalContext) (xs : Array Expr) (kind : MetavarKind) (e : Expr) : M Expr := do let e ← abstractRangeAux xs xs.size e xs.size.foldRevM (init := e) fun i e => let x := xs[i] match lctx.getFVar! x with | LocalDecl.cdecl _ _ n type bi => do let type := type.headBeta let type ← abstractRangeAux xs i type pure <| Lean.mkForall n bi type e | LocalDecl.ldecl _ _ n type value nonDep => do let type := type.headBeta let type ← abstractRangeAux xs i type let value ← abstractRangeAux xs i value let e := mkLet n type value e nonDep match kind with | MetavarKind.syntheticOpaque => -- See "Gruesome details" section in the beginning of the file let e := e.liftLooseBVars 0 1 pure <| mkForall n BinderInfo.default type e | _ => pure e where abstractRangeAux (xs : Array Expr) (i : Nat) (e : Expr) : M Expr := do let e ← elim xs e pure (e.abstractRange i xs) private partial def elimMVar (xs : Array Expr) (mvarId : MVarId) (args : Array Expr) : M (Expr × Array Expr) := do let mctx ← getMCtx let mvarDecl := mctx.getDecl mvarId let mvarLCtx := mvarDecl.lctx let toRevert := getInScope mvarLCtx xs if toRevert.size == 0 then let args ← args.mapM (visit xs) return (mkAppN (mkMVar mvarId) args, #[]) else /- `newMVarKind` is the kind for the new auxiliary metavariable. There is an alternative approach where we use ``` let newMVarKind := if !mctx.isExprAssignable mvarId || mvarDecl.isSyntheticOpaque then MetavarKind.syntheticOpaque else MetavarKind.natural ``` In this approach, we use the natural kind for the new auxiliary metavariable if the original metavariable is synthetic and assignable. Since we mainly use synthetic metavariables for pending type class (TC) resolution problems, this approach may minimize the number of TC resolution problems that may need to be resolved. A potential disadvantage is that `isDefEq` will not eagerly use `synthPending` for natural metavariables. That being said, we should try this approach as soon as we have an extensive test suite. -/ let newMVarKind := if !mctx.isExprAssignable mvarId then MetavarKind.syntheticOpaque else mvarDecl.kind /- If `mvarId` is the lhs of a delayed assignment `?m #[x_1, ... x_n] := val`, then `nestedFVars` is `#[x_1, ..., x_n]`. In this case, we produce a new `syntheticOpaque` metavariable `?n` and a delayed assignment ``` ?n #[y_1, ..., y_m, x_1, ... x_n] := ?m x_1 ... x_n ``` where `#[y_1, ..., y_m]` is `toRevert` after `collectDeps`. Remark: `newMVarKind != MetavarKind.syntheticOpaque ==> nestedFVars == #[]` -/ let rec cont (nestedFVars : Array Expr) (nestedLCtx : LocalContext) : M (Expr × Array Expr) := do let args ← args.mapM (visit xs) let preserve ← preserveOrder match collectDeps mctx mvarLCtx toRevert preserve with | Except.error ex => throw ex | Except.ok toRevert => let newMVarLCtx := reduceLocalContext mvarLCtx toRevert let newLocalInsts := mvarDecl.localInstances.filter fun inst => toRevert.all fun x => inst.fvar != x -- Remark: we must reset the before processing `mkAuxMVarType` because `toRevert` may not be equal to `xs` let newMVarType ← withFreshCache do mkAuxMVarType mvarLCtx toRevert newMVarKind mvarDecl.type let newMVarId := (← get).ngen.curr let newMVar := mkMVar newMVarId let result := mkMVarApp mvarLCtx newMVar toRevert newMVarKind let numScopeArgs := mvarDecl.numScopeArgs + result.getAppNumArgs modify fun s => { s with mctx := s.mctx.addExprMVarDecl newMVarId Name.anonymous newMVarLCtx newLocalInsts newMVarType newMVarKind numScopeArgs, ngen := s.ngen.next } match newMVarKind with | MetavarKind.syntheticOpaque => modify fun s => { s with mctx := assignDelayed s.mctx newMVarId nestedLCtx (toRevert ++ nestedFVars) (mkAppN (mkMVar mvarId) nestedFVars) } | _ => modify fun s => { s with mctx := assignExpr s.mctx mvarId result } return (mkAppN result args, toRevert) if !mvarDecl.kind.isSyntheticOpaque then cont #[] mvarLCtx else match mctx.getDelayedAssignment? mvarId with | none => cont #[] mvarLCtx | some { fvars := fvars, lctx := nestedLCtx, .. } => cont fvars nestedLCtx -- Remark: nestedLCtx is bigger than mvarLCtx private partial def elimApp (xs : Array Expr) (f : Expr) (args : Array Expr) : M Expr := do match f with | Expr.mvar mvarId _ => match (← getMCtx).getExprAssignment? mvarId with | some newF => if newF.isLambda then let args ← args.mapM (visit xs) elim xs <| newF.betaRev args.reverse else elimApp xs newF args | none => return (← elimMVar xs mvarId args).1 | _ => return mkAppN (← visit xs f) (← args.mapM (visit xs)) end partial def elimMVarDeps (xs : Array Expr) (e : Expr) : M Expr := if !e.hasMVar then pure e else withFreshCache do elim xs e partial def revert (xs : Array Expr) (mvarId : MVarId) : M (Expr × Array Expr) := withFreshCache do elimMVar xs mvarId #[] /-- Similar to `Expr.abstractRange`, but handles metavariables correctly. It uses `elimMVarDeps` to ensure `e` and the type of the free variables `xs` do not contain a metavariable `?m` s.t. local context of `?m` contains a free variable in `xs`. `elimMVarDeps` is defined later in this file. -/ @[inline] def abstractRange (xs : Array Expr) (i : Nat) (e : Expr) : M Expr := do let e ← elimMVarDeps xs e pure (e.abstractRange i xs) /-- Similar to `LocalContext.mkBinding`, but handles metavariables correctly. If `usedOnly == false` then `forall` and `lambda` expressions are created only for used variables. If `usedLetOnly == false` then `let` expressions are created only for used (let-) variables. -/ @[specialize] def mkBinding (isLambda : Bool) (lctx : LocalContext) (xs : Array Expr) (e : Expr) (usedOnly : Bool) (usedLetOnly : Bool) : M (Expr × Nat) := do let e ← abstractRange xs xs.size e xs.size.foldRevM (fun i (p : Expr × Nat) => do let (e, num) := p; let x := xs[i] match lctx.getFVar! x with | LocalDecl.cdecl _ _ n type bi => if !usedOnly || e.hasLooseBVar 0 then let type := type.headBeta; let type ← abstractRange xs i type if isLambda then pure (Lean.mkLambda n bi type e, num + 1) else pure (Lean.mkForall n bi type e, num + 1) else pure (e.lowerLooseBVars 1 1, num) | LocalDecl.ldecl _ _ n type value nonDep => if !usedLetOnly || e.hasLooseBVar 0 then let type ← abstractRange xs i type let value ← abstractRange xs i value pure (mkLet n type value e nonDep, num + 1) else pure (e.lowerLooseBVars 1 1, num)) (e, 0) end MkBinding abbrev MkBindingM := ReaderT LocalContext MkBinding.MCore def elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool) : MkBindingM Expr := fun _ => MkBinding.elimMVarDeps xs e preserveOrder def revert (xs : Array Expr) (mvarId : MVarId) (preserveOrder : Bool) : MkBindingM (Expr × Array Expr) := fun _ => MkBinding.revert xs mvarId preserveOrder def mkBinding (isLambda : Bool) (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MkBindingM (Expr × Nat) := fun lctx => MkBinding.mkBinding isLambda lctx xs e usedOnly usedLetOnly false @[inline] def mkLambda (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MkBindingM Expr := do let (e, _) ← mkBinding (isLambda := true) xs e usedOnly usedLetOnly pure e @[inline] def mkForall (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MkBindingM Expr := do let (e, _) ← mkBinding (isLambda := false) xs e usedOnly usedLetOnly pure e @[inline] def abstractRange (e : Expr) (n : Nat) (xs : Array Expr) : MkBindingM Expr := fun _ => MkBinding.abstractRange xs n e false /-- `isWellFormed mctx lctx e` return true if - All locals in `e` are declared in `lctx` - All metavariables `?m` in `e` have a local context which is a subprefix of `lctx` or are assigned, and the assignment is well-formed. -/ partial def isWellFormed (mctx : MetavarContext) (lctx : LocalContext) : Expr → Bool | Expr.mdata _ e _ => isWellFormed mctx lctx e | Expr.proj _ _ e _ => isWellFormed mctx lctx e | e@(Expr.app f a _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed mctx lctx f && isWellFormed mctx lctx a) | e@(Expr.lam _ d b _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed mctx lctx d && isWellFormed mctx lctx b) | e@(Expr.forallE _ d b _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed mctx lctx d && isWellFormed mctx lctx b) | e@(Expr.letE _ t v b _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed mctx lctx t && isWellFormed mctx lctx v && isWellFormed mctx lctx b) | Expr.const .. => true | Expr.bvar .. => true | Expr.sort .. => true | Expr.lit .. => true | Expr.mvar mvarId _ => let mvarDecl := mctx.getDecl mvarId; if mvarDecl.lctx.isSubPrefixOf lctx then true else match mctx.getExprAssignment? mvarId with | none => false | some v => isWellFormed mctx lctx v | Expr.fvar fvarId _ => lctx.contains fvarId namespace LevelMVarToParam structure Context where paramNamePrefix : Name alreadyUsedPred : Name → Bool structure State where mctx : MetavarContext paramNames : Array Name := #[] nextParamIdx : Nat cache : HashMap ExprStructEq Expr := {} abbrev M := ReaderT Context $ StateM State instance : MonadCache ExprStructEq Expr M where findCached? e := return (← get).cache.find? e cache e v := modify fun s => { s with cache := s.cache.insert e v } partial def mkParamName : M Name := do let ctx ← read let s ← get let newParamName := ctx.paramNamePrefix.appendIndexAfter s.nextParamIdx if ctx.alreadyUsedPred newParamName then modify fun s => { s with nextParamIdx := s.nextParamIdx + 1 } mkParamName else do modify fun s => { s with nextParamIdx := s.nextParamIdx + 1, paramNames := s.paramNames.push newParamName } pure newParamName partial def visitLevel (u : Level) : M Level := do match u with | Level.succ v _ => return u.updateSucc! (← visitLevel v) | Level.max v₁ v₂ _ => return u.updateMax! (← visitLevel v₁) (← visitLevel v₂) | Level.imax v₁ v₂ _ => return u.updateIMax! (← visitLevel v₁) (← visitLevel v₂) | Level.zero _ => pure u | Level.param .. => pure u | Level.mvar mvarId _ => let s ← get match s.mctx.getLevelAssignment? mvarId with | some v => visitLevel v | none => let p ← mkParamName let p := mkLevelParam p modify fun s => { s with mctx := s.mctx.assignLevel mvarId p } pure p partial def main (e : Expr) : M Expr := if !e.hasMVar then return e else checkCache { val := e : ExprStructEq } fun _ => do match e with | Expr.proj _ _ s _ => return e.updateProj! (← main s) | Expr.forallE _ d b _ => return e.updateForallE! (← main d) (← main b) | Expr.lam _ d b _ => return e.updateLambdaE! (← main d) (← main b) | Expr.letE _ t v b _ => return e.updateLet! (← main t) (← main v) (← main b) | Expr.app .. => e.withApp fun f args => visitApp f args | Expr.mdata _ b _ => return e.updateMData! (← main b) | Expr.const _ us _ => return e.updateConst! (← us.mapM visitLevel) | Expr.sort u _ => return e.updateSort! (← visitLevel u) | Expr.mvar .. => visitApp e #[] | e => return e where visitApp (f : Expr) (args : Array Expr) : M Expr := do match f with | Expr.mvar mvarId .. => match (← get).mctx.getExprAssignment? mvarId with | some v => return (← visitApp v args).headBeta | none => return mkAppN f (← args.mapM main) | _ => return mkAppN (← main f) (← args.mapM main) end LevelMVarToParam structure UnivMVarParamResult where mctx : MetavarContext newParamNames : Array Name nextParamIdx : Nat expr : Expr def levelMVarToParam (mctx : MetavarContext) (alreadyUsedPred : Name → Bool) (e : Expr) (paramNamePrefix : Name := `u) (nextParamIdx : Nat := 1) : UnivMVarParamResult := let (e, s) := LevelMVarToParam.main e { paramNamePrefix := paramNamePrefix, alreadyUsedPred := alreadyUsedPred } { mctx := mctx, nextParamIdx := nextParamIdx } { mctx := s.mctx, newParamNames := s.paramNames, nextParamIdx := s.nextParamIdx, expr := e } def getExprAssignmentDomain (mctx : MetavarContext) : Array MVarId := mctx.eAssignment.foldl (init := #[]) fun a mvarId _ => Array.push a mvarId end MetavarContext end Lean
8d6324c9d299723397d1e9d76218f7c64a096d00
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/analysis/complex/polynomial.lean
f386d4c8bee15b43573ee3a5b1c65ae2d3cc2489
[]
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
848
lean
/- Copyright (c) 2019 Chris Hughes All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.algebra.polynomial import Mathlib.analysis.special_functions.pow import Mathlib.PostPort namespace Mathlib /-! # The fundamental theorem of algebra This file proves that every nonconstant complex polynomial has a root. -/ namespace complex /- The following proof uses the method given at <https://ncatlab.org/nlab/show/fundamental+theorem+of+algebra#classical_fta_via_advanced_calculus> -/ /-- The fundamental theorem of algebra. Every non constant complex polynomial has a root -/ theorem exists_root {f : polynomial ℂ} (hf : 0 < polynomial.degree f) : ∃ (z : ℂ), polynomial.is_root f z := sorry
9a356e5bd4b8e7b9517c0b42b7a7cfeff0031041
0845ae2ca02071debcfd4ac24be871236c01784f
/library/init/lean/compiler/ir/expandresetreuse.lean
5d3ee581ae7c4c623ea935cd5ab41d4e13ac8c70
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
9,569
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.control.state import init.control.reader import init.lean.compiler.ir.compilerm import init.lean.compiler.ir.normids import init.lean.compiler.ir.freevars namespace Lean namespace IR namespace ExpandResetReuse /- Mapping from variable to projections -/ abbrev ProjMap := HashMap VarId Expr namespace CollectProjMap abbrev Collector := ProjMap → ProjMap @[inline] def collectVDecl (x : VarId) (v : Expr) : Collector := fun m => match v with | Expr.proj _ _ => m.insert x v | Expr.sproj _ _ _ => m.insert x v | Expr.uproj _ _ => m.insert x v | _ => m partial def collectFnBody : FnBody → Collector | (FnBody.vdecl x _ v b) := collectVDecl x v ∘ collectFnBody b | (FnBody.jdecl _ _ v b) := collectFnBody v ∘ collectFnBody b | (FnBody.case _ _ alts) := fun s => alts.foldl (fun s alt => collectFnBody alt.body s) s | e := if e.isTerminal then id else collectFnBody e.body end CollectProjMap /- Create a mapping from variables to projections. This function assumes variable ids have been normalized -/ def mkProjMap (d : Decl) : ProjMap := match d with | Decl.fdecl _ _ _ b => CollectProjMap.collectFnBody b {} | _ => {} structure Context := (projMap : ProjMap) /- Return true iff `x` is consumed in all branches of the current block. Here consumption means the block contains a `dec x` or `reuse x ...`. -/ partial def consumed (x : VarId) : FnBody → Bool | (FnBody.vdecl _ _ v b) := match v with | Expr.reuse y _ _ _ => x == y || consumed b | _ => consumed b | (FnBody.dec y _ _ b) := x == y || consumed b | (FnBody.case _ _ alts) := alts.all $ fun alt => consumed alt.body | e := !e.isTerminal && consumed e.body abbrev Mask := Array (Option VarId) /- Auxiliary function for eraseProjIncFor -/ partial def eraseProjIncForAux (y : VarId) : Array FnBody → Mask → Array FnBody → Array FnBody × Mask | bs mask keep := let done (_ : Unit) := (bs ++ keep.reverse, mask); let keepInstr (b : FnBody) := eraseProjIncForAux bs.pop mask (keep.push b); if bs.size < 2 then done () else let b := bs.back; match b with | (FnBody.vdecl _ _ (Expr.sproj _ _ _) _) => keepInstr b | (FnBody.vdecl _ _ (Expr.uproj _ _) _) => keepInstr b | (FnBody.inc z n c _) => if n == 0 then done () else let b' := bs.get (bs.size - 2); match b' with | (FnBody.vdecl w _ (Expr.proj i x) _) => if w == z && y == x then /- Found ``` let z := proj[i] y; inc z n c ``` We keep `proj`, and `inc` when `n > 1` -/ let bs := bs.pop.pop; let mask := mask.set i (some z); let keep := keep.push b'; let keep := if n == 1 then keep else keep.push (FnBody.inc z (n-1) c FnBody.nil); eraseProjIncForAux bs mask keep else done () | other => done () | other => done () /- Try to erase `inc` instructions on projections of `y` occurring in the tail of `bs`. Return the updated `bs` and a bit mask specifying which `inc`s have been removed. -/ def eraseProjIncFor (n : Nat) (y : VarId) (bs : Array FnBody) : Array FnBody × Mask := eraseProjIncForAux y bs (mkArray n none) Array.empty /- Replace `reuse x ctor ...` with `ctor ...`, and remoce `dec x` -/ partial def reuseToCtor (x : VarId) : FnBody → FnBody | (FnBody.dec y n c b) := if x == y then b -- n must be 1 since `x := reset ...` else FnBody.dec y n c (reuseToCtor b) | (FnBody.vdecl z t v b) := match v with | Expr.reuse y c u xs => if x == y then FnBody.vdecl z t (Expr.ctor c xs) b else FnBody.vdecl z t v (reuseToCtor b) | _ => FnBody.vdecl z t v (reuseToCtor b) | (FnBody.case tid y alts) := let alts := alts.map $ fun alt => alt.modifyBody reuseToCtor; FnBody.case tid y alts | e := if e.isTerminal then e else let (instr, b) := e.split; let b := reuseToCtor b; instr.setBody b /- replace ``` x := reset y; b ``` with ``` inc z_1; ...; inc z_i; dec y; b' ``` where `z_i`'s are the variables in `mask`, and `b'` is `b` where we removed `dec x` and replaced `reuse x ctor_i ...` with `ctor_i ...`. -/ def mkSlowPath (x y : VarId) (mask : Mask) (b : FnBody) : FnBody := let b := reuseToCtor x b; let b := FnBody.dec y 1 true b; mask.foldl (fun b m => match m with | some z => FnBody.inc z 1 true b | none => b) b abbrev M := ReaderT Context (State Nat) def mkFresh : M VarId := do idx ← get; modify (fun n => n + 1); pure { idx := idx } def releaseUnreadFields (y : VarId) (mask : Mask) (b : FnBody) : M FnBody := mask.size.mfold (fun i b => match mask.get i with | some _ => pure b -- code took ownership of this field | none => do fld ← mkFresh; pure (FnBody.vdecl fld IRType.object (Expr.proj i y) (FnBody.dec fld 1 true b))) b def setFields (y : VarId) (zs : Array Arg) (b : FnBody) : FnBody := zs.size.fold (fun i b => FnBody.set y i (zs.get i) b) b /- Given `set x[i] := y`, return true iff `y := proj[i] x` -/ def isSelfSet (ctx : Context) (x : VarId) (i : Nat) (y : Arg) : Bool := match y with | Arg.var y => match ctx.projMap.find y with | some (Expr.proj j w) => j == i && w == x | _ => false | _ => false /- Given `uset x[i] := y`, return true iff `y := uproj[i] x` -/ def isSelfUSet (ctx : Context) (x : VarId) (i : Nat) (y : VarId) : Bool := match ctx.projMap.find y with | some (Expr.uproj j w) => j == i && w == x | _ => false /- Given `sset x[n, i] := y`, return true iff `y := sproj[n, i] x` -/ def isSelfSSet (ctx : Context) (x : VarId) (n : Nat) (i : Nat) (y : VarId) : Bool := match ctx.projMap.find y with | some (Expr.sproj m j w) => n == m && j == i && w == x | _ => false /- Remove unnecessary `set/uset/sset` operations -/ partial def removeSelfSet (ctx : Context) : FnBody → FnBody | (FnBody.set x i y b) := if isSelfSet ctx x i y then removeSelfSet b else FnBody.set x i y (removeSelfSet b) | (FnBody.uset x i y b) := if isSelfUSet ctx x i y then removeSelfSet b else FnBody.uset x i y (removeSelfSet b) | (FnBody.sset x n i y t b) := if isSelfSSet ctx x n i y then removeSelfSet b else FnBody.sset x n i y t (removeSelfSet b) | (FnBody.case tid y alts) := let alts := alts.map $ fun alt => alt.modifyBody removeSelfSet; FnBody.case tid y alts | e := if e.isTerminal then e else let (instr, b) := e.split; let b := removeSelfSet b; instr.setBody b partial def reuseToSet (ctx : Context) (x y : VarId) : FnBody → FnBody | (FnBody.dec z n c b) := if x == z then FnBody.del y b else FnBody.dec z n c (reuseToSet b) | (FnBody.vdecl z t v b) := match v with | Expr.reuse w c u zs => if x == w then let b := setFields y zs (b.replaceVar z y); let b := if u then FnBody.setTag y c.cidx b else b; removeSelfSet ctx b else FnBody.vdecl z t v (reuseToSet b) | _ => FnBody.vdecl z t v (reuseToSet b) | (FnBody.case tid y alts) := let alts := alts.map $ fun alt => alt.modifyBody reuseToSet; FnBody.case tid y alts | e := if e.isTerminal then e else let (instr, b) := e.split; let b := reuseToSet b; instr.setBody b /- replace ``` x := reset y; b ``` with ``` let f_i_1 := proj[i_1] y; ... let f_i_k := proj[i_k] y; b' ``` where `i_j`s are the field indexes that the code did not touch immediately before the reset. That is `mask[j] == none`. `b'` is `b` where `y` `dec x` is replaced with `del y`, and `z := reuse x ctor_i ws; F` is replaced with `set x i ws[i]` operations, and we replace `z` with `x` in `F` -/ def mkFastPath (x y : VarId) (mask : Mask) (b : FnBody) : M FnBody := do ctx ← read; let b := reuseToSet ctx x y b; releaseUnreadFields y mask b -- Expand `bs; x := reset[n] y; b` partial def expand (mainFn : FnBody → Array FnBody → M FnBody) (bs : Array FnBody) (x : VarId) (n : Nat) (y : VarId) (b : FnBody) : M FnBody := do let bOld := FnBody.vdecl x IRType.object (Expr.reset n y) b; let (bs, mask) := eraseProjIncFor n y bs; let bSlow := mkSlowPath x y mask b; bFast ← mkFastPath x y mask b; /- We only optimize recursively the fast. -/ bFast ← mainFn bFast Array.empty; c ← mkFresh; let b := FnBody.vdecl c IRType.uint8 (Expr.isShared y) (mkIf c bSlow bFast); pure $ reshape bs b partial def searchAndExpand : FnBody → Array FnBody → M FnBody | d@(FnBody.vdecl x t (Expr.reset n y) b) bs := if consumed x b then do expand searchAndExpand bs x n y b else searchAndExpand b (push bs d) | (FnBody.jdecl j xs v b) bs := do v ← searchAndExpand v Array.empty; searchAndExpand b (push bs (FnBody.jdecl j xs v FnBody.nil)) | (FnBody.case tid x alts) bs := do alts ← alts.mmap $ fun alt => alt.mmodifyBody $ fun b => searchAndExpand b Array.empty; pure $ reshape bs (FnBody.case tid x alts) | b bs := if b.isTerminal then pure $ reshape bs b else searchAndExpand b.body (push bs b) def main (d : Decl) : Decl := let d := d.normalizeIds; match d with | (Decl.fdecl f xs t b) => let m := mkProjMap d; let nextIdx := d.maxIndex + 1; let b := (searchAndExpand b Array.empty { projMap := m }).run' nextIdx; Decl.fdecl f xs t b | d => d end ExpandResetReuse /-- (Try to) expand `reset` and `reuse` instructions. -/ def Decl.expandResetReuse (d : Decl) : Decl := ExpandResetReuse.main d end IR end Lean
adab3a71cdabc7ea0caf0c450700929e87f07b73
12dabd587ce2621d9a4eff9f16e354d02e206c8e
/world10/level09.lean
5620950a844723fadebea2d16ba2eeabd6fa811e
[]
no_license
abdelq/natural-number-game
a1b5b8f1d52625a7addcefc97c966d3f06a48263
bbddadc6d2e78ece2e9acd40fa7702ecc2db75c2
refs/heads/master
1,668,606,478,691
1,594,175,058,000
1,594,175,058,000
278,673,209
0
1
null
null
null
null
UTF-8
Lean
false
false
250
lean
theorem le_total (a b : mynat) : a ≤ b ∨ b ≤ a := begin revert a, induction b with d hd, intro a, right, exact zero_le _, intro a, cases a, left, exact zero_le _, cases hd a, left, exact succ_le_succ _ _ h, right, exact succ_le_succ _ _ h, end
2cacae85f93c08a6a662966f34d0872fb81d6976
0c1546a496eccfb56620165cad015f88d56190c5
/library/init/meta/mk_dec_eq_instance.lean
6d2daf019b772e0edec6324aa285e335c40bf81a
[ "Apache-2.0" ]
permissive
Solertis/lean
491e0939957486f664498fbfb02546e042699958
84188c5aa1673fdf37a082b2de8562dddf53df3f
refs/heads/master
1,610,174,257,606
1,486,263,620,000
1,486,263,620,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,281
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 Helper tactic for showing that a type has decidable equality. -/ prelude import init.meta.contradiction_tactic init.meta.constructor_tactic import init.meta.injection_tactic init.meta.relation_tactics import init.meta.rec_util init.meta.interactive namespace tactic open expr environment list /- Retrieve the name of the type we are building a decidable equality proof for. -/ private meta def get_dec_eq_type_name : tactic name := do { (pi x1 i1 d1 (pi x2 i2 d2 b)) ← target >>= whnf | failed, (const n ls) ← return (get_app_fn b) | failed, when (n ≠ `decidable) failed, (const I ls) ← return (get_app_fn d1) | failed, return I } <|> fail "mk_dec_eq_instance tactic failed, target type is expected to be of the form (decidable_eq ...)" /- Extract (lhs, rhs) from a goal (decidable (lhs = rhs)) -/ private meta def get_lhs_rhs : tactic (expr × expr) := do (app dec lhs_eq_rhs) ← target | fail "mk_dec_eq_instance failed, unexpected case", match_eq lhs_eq_rhs private meta def find_next_target : list expr → list expr → tactic (expr × expr) | (t::ts) (r::rs) := if t = r then find_next_target ts rs else return (t, r) | l1 l2 := failed /- Create an inhabitant of (decidable (lhs = rhs)) -/ private meta def mk_dec_eq_for (lhs : expr) (rhs : expr) : tactic expr := do lhs_type ← infer_type lhs, dec_type ← mk_app `decidable_eq [lhs_type] >>= whnf, do { inst ← mk_instance dec_type, return $ inst lhs rhs } <|> do { f ← pp dec_type, fail $ to_fmt "mk_dec_eq_instance failed, failed to generate instance for" ++ format.nest 2 (format.line ++ f) } /- Target is of the form (decidable (C ... = C ...)) where C is a constructor -/ private meta def dec_eq_same_constructor : name → name → nat → tactic unit | I_name F_name num_rec := do (lhs, rhs) ← get_lhs_rhs, -- Try easy case first, where the proof is just reflexivity (unify lhs rhs >> right >> reflexivity) <|> do { lhs_list : list expr ← return $ get_app_args lhs, rhs_list : list expr ← return $ get_app_args rhs, when (length lhs_list ≠ length rhs_list) (fail "mk_dec_eq_instance failed, constructor applications have different number of arguments"), (lhs_arg, rhs_arg) ← find_next_target lhs_list rhs_list, rec ← is_type_app_of lhs_arg I_name, inst ← if rec then do { inst_fn : expr ← mk_brec_on_rec_value F_name num_rec, return $ app inst_fn rhs_arg } else do { mk_dec_eq_for lhs_arg rhs_arg }, `[apply @decidable.by_cases _ _ %%inst], -- discharge first (positive) case by recursion intro1 >>= subst >> dec_eq_same_constructor I_name F_name (if rec then num_rec + 1 else num_rec), -- discharge second (negative) case by contradiction intro1, left, -- decidable.is_false intro1 >>= injection, intros, contradiction, return () } /- Easy case: target is of the form (decidable (C_1 ... = C_2 ...)) where C_1 and C_2 are distinct constructors -/ private meta def dec_eq_diff_constructor : tactic unit := left >> intron 1 >> contradiction /- This tactic is invoked for each case of decidable_eq. There n^2 cases, where n is the number of constructors. -/ private meta def dec_eq_case_2 (I_name : name) (F_name : name) : tactic unit := do (lhs, rhs) ← get_lhs_rhs, lhs_fn : expr ← return $ get_app_fn lhs, rhs_fn : expr ← return $ get_app_fn rhs, if lhs_fn = rhs_fn then dec_eq_same_constructor I_name F_name 0 else dec_eq_diff_constructor private meta def dec_eq_case_1 (I_name : name) (F_name : name) : tactic unit := intro `w >>= cases >> all_goals (dec_eq_case_2 I_name F_name) meta def mk_dec_eq_instance_core : tactic unit := do I_name ← get_dec_eq_type_name, env ← get_env, v_name ← return `_v, F_name ← return `_F, num_indices ← return $ inductive_num_indices env I_name, idx_names ← return $ list.map (λ (p : name × nat), mk_num_name p~>fst p~>snd) (list.zip (list.repeat `idx num_indices) (list.iota num_indices)), -- Use brec_on if type is recursive. -- We store the functional in the variable F. if is_recursive env I_name then intro1 >>= (λ x, induction_core semireducible x (I_name <.> "brec_on") (idx_names ++ [v_name, F_name])) else intro v_name >> return (), -- Apply cases to first element of type (I ...) get_local v_name >>= cases, all_goals (dec_eq_case_1 I_name F_name) meta def mk_dec_eq_instance : tactic unit := do env ← get_env, (pi x1 i1 d1 (pi x2 i2 d2 b)) ← target >>= whnf | failed, (const I_name ls) ← return (get_app_fn d1) | failed, when (is_ginductive env I_name ∧ ¬ is_inductive env I_name) $ do { d1' ← whnf d1, (app I_basic_const I_idx) ← return d1' | failed, I_idx_type ← infer_type I_idx, new_goal ← to_expr `(∀ (_idx : %%I_idx_type), decidable_eq (%%I_basic_const _idx)), assert `_basic_dec_eq new_goal, swap, to_expr `(_basic_dec_eq %%I_idx) >>= exact, intro1, return () }, mk_dec_eq_instance_core end tactic
3ac0e93ec2b730c18560dfc4c7d2c8b01c51bb54
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/simp19.lean
16b4b83482313f858afa868d12c53048dede2fd6
[ "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
984
lean
variable vec : Nat → Type variable concat {n m : Nat} (v : vec n) (w : vec m) : vec (n + m) infixl 65 ; : concat axiom concat_assoc {n1 n2 n3 : Nat} (v1 : vec n1) (v2 : vec n2) (v3 : vec n3) : (v1 ; v2) ; v3 = cast (to_heq (congr2 vec (symm (Nat::add_assoc n1 n2 n3)))) (v1 ; (v2 ; v3)) variable empty : vec 0 axiom concat_empty {n : Nat} (v : vec n) : v ; empty = cast (to_heq (congr2 vec (symm (Nat::add_zeror n)))) v rewrite_set simple add_rewrite concat_assoc concat_empty Nat::add_assoc Nat::add_zeror : simple universe M >= 1 definition TypeM := (Type M) variable n : Nat variable v : vec n variable w : vec n variable f {A : TypeM} : A → A (* local opts = options({"simplifier", "heq"}, true) local t = parse_lean([[ f ((v ; w) ; empty ; (v ; empty)) ]]) print(t) print("===>") local t2, pr = simplify(t, "simple", opts) print(t2) print(pr) get_environment():type_check(pr) *)
c3c3ac15e61cde53748225781b238ae2acad22b4
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/private_names.lean
708623a43c326f0e8862381c4440e48a8e3027aa
[ "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
186
lean
namespace bla section private definition foo : inhabited Prop := inhabited.mk false attribute foo [instance, priority 1000] example : default Prop = false := rfl end end bla
cc05683047e5deaee199024b184e439c30de3e34
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/712.lean
8b899e5661c0397fa09876aec0b28e92cd4b8628
[ "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
455
lean
reserve infix `~~~`:50 reserve notation `[` a `][` b:10 `]` section local infix `~~~` := eq print notation ~~~ local infix `~~~`:50 := eq print notation ~~~ local infix `~~~`:100 := eq infix `~~~`:100 := eq -- FAIL print notation ~~~ local notation `[` a `][`:10 b:20 `]` := a = b print notation ][ end notation `[` a `][`:10 b:20 `]` := a = b -- FAIL notation `[` a `][` b `]` := a = b infix `~~~` := eq print notation ~~~ print notation ][
d108e23f7dda70376fc28beafeee56bfb32868d8
737dc4b96c97368cb66b925eeea3ab633ec3d702
/src/Init/Notation.lean
7226f97094a01654884b15c83391ce1690bb30a1
[ "Apache-2.0" ]
permissive
Bioye97/lean4
1ace34638efd9913dc5991443777b01a08983289
bc3900cbb9adda83eed7e6affeaade7cfd07716d
refs/heads/master
1,690,589,820,211
1,631,051,000,000
1,631,067,598,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,707
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura Notation for operators defined at Prelude.lean -/ prelude import Init.Prelude -- DSL for specifying parser precedences and priorities namespace Lean.Parser.Syntax syntax:65 (name := addPrec) prec " + " prec:66 : prec syntax:65 (name := subPrec) prec " - " prec:66 : prec syntax:65 (name := addPrio) prio " + " prio:66 : prio syntax:65 (name := subPrio) prio " - " prio:66 : prio end Lean.Parser.Syntax macro "max" : prec => `(1024) -- maximum precedence used in term parsers, in particular for terms in function position (`ident`, `paren`, ...) macro "arg" : prec => `(1023) -- precedence used for application arguments (`do`, `by`, ...) macro "lead" : prec => `(1022) -- precedence used for terms not supposed to be used as arguments (`let`, `have`, ...) macro "(" p:prec ")" : prec => p macro "min" : prec => `(10) -- minimum precedence used in term parsers macro "min1" : prec => `(11) -- `(min+1) we can only `min+1` after `Meta.lean` /- `max:prec` as a term. It is equivalent to `eval_prec max` for `eval_prec` defined at `Meta.lean`. We use `max_prec` to workaround bootstrapping issues. -/ macro "max_prec" : term => `(1024) macro "default" : prio => `(1000) macro "low" : prio => `(100) macro "mid" : prio => `(1000) macro "high" : prio => `(10000) macro "(" p:prio ")" : prio => p -- Basic notation for defining parsers -- NOTE: precedence must be at least `arg` to be used in `macro` without parentheses syntax:arg stx:max "+" : stx syntax:arg stx:max "*" : stx syntax:arg stx:max "?" : stx syntax:2 stx:2 " <|> " stx:1 : stx macro_rules | `(stx| $p +) => `(stx| many1($p)) | `(stx| $p *) => `(stx| many($p)) | `(stx| $p ?) => `(stx| optional($p)) | `(stx| $p₁ <|> $p₂) => `(stx| orelse($p₁, $p₂)) /- Comma-separated sequence. -/ macro:arg x:stx:max ",*" : stx => `(stx| sepBy($x, ",", ", ")) macro:arg x:stx:max ",+" : stx => `(stx| sepBy1($x, ",", ", ")) /- Comma-separated sequence with optional trailing comma. -/ macro:arg x:stx:max ",*,?" : stx => `(stx| sepBy($x, ",", ", ", allowTrailingSep)) macro:arg x:stx:max ",+,?" : stx => `(stx| sepBy1($x, ",", ", ", allowTrailingSep)) macro:arg "!" x:stx:max : stx => `(stx| notFollowedBy($x)) syntax (name := rawNatLit) "nat_lit " num : term infixr:90 " ∘ " => Function.comp infixr:35 " × " => Prod infixl:55 " ||| " => HOr.hOr infixl:58 " ^^^ " => HXor.hXor infixl:60 " &&& " => HAnd.hAnd infixl:65 " + " => HAdd.hAdd infixl:65 " - " => HSub.hSub infixl:70 " * " => HMul.hMul infixl:70 " / " => HDiv.hDiv infixl:70 " % " => HMod.hMod infixl:75 " <<< " => HShiftLeft.hShiftLeft infixl:75 " >>> " => HShiftRight.hShiftRight infixr:80 " ^ " => HPow.hPow infixl:65 " ++ " => HAppend.hAppend prefix:100 "-" => Neg.neg prefix:100 "~~~" => Complement.complement /- Remark: the infix commands above ensure a delaborator is generated for each relations. We redefine the macros below to be able to use the auxiliary `binop%` elaboration helper for binary operators. It addresses issue #382. -/ macro_rules | `($x ||| $y) => `(binop% HOr.hOr $x $y) macro_rules | `($x ^^^ $y) => `(binop% HXor.hXor $x $y) macro_rules | `($x &&& $y) => `(binop% HAnd.hAnd $x $y) macro_rules | `($x + $y) => `(binop% HAdd.hAdd $x $y) macro_rules | `($x - $y) => `(binop% HSub.hSub $x $y) macro_rules | `($x * $y) => `(binop% HMul.hMul $x $y) macro_rules | `($x / $y) => `(binop% HDiv.hDiv $x $y) macro_rules | `($x ++ $y) => `(binop% HAppend.hAppend $x $y) -- declare ASCII alternatives first so that the latter Unicode unexpander wins infix:50 " <= " => LE.le infix:50 " ≤ " => LE.le infix:50 " < " => LT.lt infix:50 " >= " => GE.ge infix:50 " ≥ " => GE.ge infix:50 " > " => GT.gt infix:50 " = " => Eq infix:50 " == " => BEq.beq infix:50 " ~= " => HEq infix:50 " ≅ " => HEq /- Remark: the infix commands above ensure a delaborator is generated for each relations. We redefine the macros below to be able to use the auxiliary `binrel%` elaboration helper for binary relations. It has better support for applying coercions. For example, suppose we have `binrel% Eq n i` where `n : Nat` and `i : Int`. The default elaborator fails because we don't have a coercion from `Int` to `Nat`, but `binrel%` succeeds because it also tries a coercion from `Nat` to `Int` even when the nat occurs before the int. -/ macro_rules | `($x <= $y) => `(binrel% LE.le $x $y) macro_rules | `($x ≤ $y) => `(binrel% LE.le $x $y) macro_rules | `($x < $y) => `(binrel% LT.lt $x $y) macro_rules | `($x > $y) => `(binrel% GT.gt $x $y) macro_rules | `($x >= $y) => `(binrel% GE.ge $x $y) macro_rules | `($x ≥ $y) => `(binrel% GE.ge $x $y) macro_rules | `($x = $y) => `(binrel% Eq $x $y) macro_rules | `($x == $y) => `(binrel% BEq.beq $x $y) infixr:35 " /\\ " => And infixr:35 " ∧ " => And infixr:30 " \\/ " => Or infixr:30 " ∨ " => Or notation:max "¬" p:40 => Not p infixl:35 " && " => and infixl:30 " || " => or notation:max "!" b:40 => not b infixr:67 " :: " => List.cons syntax:20 term:21 " <|> " term:20 : term syntax:60 term:61 " >> " term:60 : term infixl:55 " >>= " => Bind.bind notation:60 a:60 " <*> " b:61 => Seq.seq a fun _ : Unit => b notation:60 a:60 " <* " b:61 => SeqLeft.seqLeft a fun _ : Unit => b notation:60 a:60 " *> " b:61 => SeqRight.seqRight a fun _ : Unit => b infixr:100 " <$> " => Functor.map macro_rules | `($x <|> $y) => `(binop_lazy% HOrElse.hOrElse $x $y) macro_rules | `($x >> $y) => `(binop_lazy% HAndThen.hAndThen $x $y) syntax (name := termDepIfThenElse) ppGroup(ppDedent("if " ident " : " term " then" ppSpace term ppDedent(ppSpace "else") ppSpace term)) : term macro_rules | `(if $h:ident : $c then $t:term else $e:term) => ``(dite $c (fun $h:ident => $t) (fun $h:ident => $e)) syntax (name := termIfThenElse) ppGroup(ppDedent("if " term " then" ppSpace term ppDedent(ppSpace "else") ppSpace term)) : term macro_rules | `(if $c then $t:term else $e:term) => ``(ite $c $t $e) macro "if " "let " pat:term " := " d:term " then " t:term " else " e:term : term => `(match $d:term with | $pat:term => $t | _ => $e) syntax:min term "<|" term:min : term macro_rules | `($f $args* <| $a) => let args := args.push a; `($f $args*) | `($f <| $a) => `($f $a) syntax:min term "|>" term:min1 : term macro_rules | `($a |> $f $args*) => let args := args.push a; `($f $args*) | `($a |> $f) => `($f $a) -- Haskell-like pipe <| -- Note that we have a whitespace after `$` to avoid an ambiguity with the antiquotations. syntax:min term atomic("$" ws) term:min : term macro_rules | `($f $args* $ $a) => let args := args.push a; `($f $args*) | `($f $ $a) => `($f $a) syntax "{ " ident (" : " term)? " // " term " }" : term macro_rules | `({ $x : $type // $p }) => ``(Subtype (fun ($x:ident : $type) => $p)) | `({ $x // $p }) => ``(Subtype (fun ($x:ident : _) => $p)) /- `without_expected_type t` instructs Lean to elaborate `t` without an expected type. Recall that terms such as `match ... with ...` and `⟨...⟩` will postpone elaboration until expected type is known. So, `without_expected_type` is not effective in this case. -/ macro "without_expected_type " x:term : term => `(let aux := $x; aux) syntax "[" term,* "]" : term syntax "%[" term,* "|" term "]" : term -- auxiliary notation for creating big list literals namespace Lean macro_rules | `([ $elems,* ]) => do let rec expandListLit (i : Nat) (skip : Bool) (result : Syntax) : MacroM Syntax := do match i, skip with | 0, _ => pure result | i+1, true => expandListLit i false result | i+1, false => expandListLit i true (← ``(List.cons $(elems.elemsAndSeps[i]) $result)) if elems.elemsAndSeps.size < 64 then expandListLit elems.elemsAndSeps.size false (← ``(List.nil)) else `(%[ $elems,* | List.nil ]) notation:50 e:51 " matches " p:51 => match e with | p => true | _ => false namespace Parser.Tactic /-- Introduce one or more hypotheses, optionally naming and/or pattern-matching them. For each hypothesis to be introduced, the remaining main goal's target type must be a `let` or function type. * `intro` by itself introduces one anonymous hypothesis, which can be accessed by e.g. `assumption`. * `intro x y` introduces two hypotheses and names them. Individual hypotheses can be anonymized via `_`, or matched against a pattern: ```lean -- ... ⊢ α × β → ... intro (a, b) -- ..., a : α, b : β ⊢ ... ``` * Alternatively, `intro` can be combined with pattern matching much like `fun`: ```lean intro | n + 1, 0 => tac | ... ``` -/ syntax (name := intro) "intro " notFollowedBy("|") (colGt term:max)* : tactic /-- `intros x...` behaves like `intro x...`, but then keeps introducing (anonymous) hypotheses until goal is not of a function type. -/ syntax (name := intros) "intros " (colGt (ident <|> "_"))* : tactic /-- `rename t => x` renames the most recent hypothesis whose type matches `t` (which may contain placeholders) to `x`, or fails if no such hypothesis could be found. -/ syntax (name := rename) "rename " term " => " ident : tactic /-- `revert x...` is the inverse of `intro x...`: it moves the given hypotheses into the main goal's target type. -/ syntax (name := revert) "revert " (colGt ident)+ : tactic /-- `clear x...` removes the given hypotheses, or fails if there are remaining references to a hypothesis. -/ syntax (name := clear) "clear " (colGt ident)+ : tactic /-- `subst x...` substitutes each `x` with `e` in the goal if there is a hypothesis of type `x = e` or `e = x`. If `x` is itself a hypothesis of type `y = e` or `e = y`, `y` is substituted instead. -/ syntax (name := subst) "subst " (colGt ident)+ : tactic /-- `assumption` tries to solve the main goal using a hypothesis of compatible type, or else fails. Note also the `‹t›` term notation, which is a shorthand for `show t by assumption`. -/ syntax (name := assumption) "assumption" : tactic /-- `contradiction` closes the main goal if its hypotheses are "trivially contradictory". ```lean example (h : False) : p := by contradiction -- inductive type/family with no applicable constructors example (h : none = some true) : p := by contradiction -- injectivity of constructors example (h : 2 + 2 = 3) : p := by contradiction -- decidable false proposition example (h : p) (h' : ¬ p) : q := by contradiction example (x : Nat) (h : x ≠ x) : p := by contradiction ``` -/ syntax (name := contradiction) "contradiction" : tactic /-- `apply e` tries to match the current goal against the conclusion of `e`'s type. If it succeeds, then the tactic returns as many subgoals as the number of premises that have not been fixed by type inference or type class resolution. Non-dependent premises are added before dependent ones. The `apply` tactic uses higher-order pattern matching, type class resolution, and first-order unification with dependent types. -/ syntax (name := apply) "apply " term : tactic /-- `exact e` closes the main goal if its target type matches that of `e`. -/ syntax (name := exact) "exact " term : tactic /-- `refine e` behaves like `exact e`, except that named (`?x`) or unnamed (`?_`) holes in `e` that are not solved by unification with the main goal's target type are converted into new goals, using the hole's name, if any, as the goal case name. -/ syntax (name := refine) "refine " term : tactic /-- `refine' e` behaves like `refine e`, except that unsolved placeholders (`_`) and implicit parameters are also converted into new goals. -/ syntax (name := refine') "refine' " term : tactic /-- If the main goal's target type is an inductive type, `constructor` solves it with the first matching constructor, or else fails. -/ syntax (name := constructor) "constructor" : tactic /-- `case tag => tac` focuses on the goal with case name `tag` and solves it using `tac`, or else fails. `case tag x₁ ... xₙ => tac` additionally renames the `n` most recent hypotheses with inaccessible names to the given names. -/ syntax (name := case) "case " (ident <|> "_") (ident <|> "_")* " => " tacticSeq : tactic /-- `next => tac` focuses on the next goal solves it using `tac`, or else fails. `next x₁ ... xₙ => tac` additionally renames the `n` most recent hypotheses with inaccessible names to the given names. -/ macro "next " args:(ident <|> "_")* " => " tac:tacticSeq : tactic => `(tactic| case _ $(args.getArgs)* => $tac) /-- `allGoals tac` runs `tac` on each goal, concatenating the resulting goals, if any. -/ syntax (name := allGoals) "allGoals " tacticSeq : tactic /-- `anyGoals tac` applies the tactic `tac` to every goal, and succeeds if at least one application succeeds. -/ syntax (name := anyGoals) "anyGoals " tacticSeq : tactic /-- `focus tac` focuses on the main goal, suppressing all other goals, and runs `tac` on it. Usually `· tac`, which enforces that the goal is closed by `tac`, should be preferred. -/ syntax (name := focus) "focus " tacticSeq : tactic /-- `skip` does nothing. -/ syntax (name := skip) "skip" : tactic /-- `done` succeeds iff there are no remaining goals. -/ syntax (name := done) "done" : tactic syntax (name := traceState) "traceState" : tactic syntax (name := failIfSuccess) "failIfSuccess " tacticSeq : tactic syntax (name := paren) "(" tacticSeq ")" : tactic syntax (name := withReducible) "withReducible " tacticSeq : tactic syntax (name := withReducibleAndInstances) "withReducibleAndInstances " tacticSeq : tactic /-- `first | tac | ...` runs each `tac` until one succeeds, or else fails. -/ syntax (name := first) "first " withPosition((group(colGe "|" tacticSeq))+) : tactic syntax (name := rotateLeft) "rotateLeft" (num)? : tactic syntax (name := rotateRight) "rotateRight" (num)? : tactic /-- `try tac` runs `tac` and succeeds even if `tac` failed. -/ macro "try " t:tacticSeq : tactic => `(first | $t | skip) /-- `tac <;> tac'` runs `tac` on the main goal and `tac'` on each produced goal, concatenating all goals produced by `tac'`. -/ macro:1 x:tactic " <;> " y:tactic:0 : tactic => `(tactic| focus ($x:tactic; allGoals $y:tactic)) /-- `· tac` focuses on the main goal and tries to solve it using `tac`, or else fails. -/ macro dot:("·" <|> ".") ts:tacticSeq : tactic => `(tactic| {%$dot ($ts:tacticSeq) }) /-- `rfl` is a shorthand for `exact rfl`. -/ macro "rfl" : tactic => `(exact rfl) /-- `admit` is a shorthand for `exact sorry`. -/ macro "admit" : tactic => `(exact sorry) macro "inferInstance" : tactic => `(exact inferInstance) syntax locationWildcard := "*" syntax locationHyp := (colGt ident)+ ("⊢" <|> "|-")? -- TODO: delete syntax locationTargets := (colGt ident)+ ("⊢" <|> "|-")? syntax location := withPosition("at " locationWildcard <|> locationHyp) syntax (name := change) "change " term (location)? : tactic syntax (name := changeWith) "change " term " with " term (location)? : tactic syntax rwRule := ("←" <|> "<-")? term syntax rwRuleSeq := "[" rwRule,+,? "]" syntax (name := rewriteSeq) "rewrite " rwRuleSeq (location)? : tactic syntax (name := erewriteSeq) "erewrite " rwRuleSeq (location)? : tactic syntax (name := rwSeq) "rw " rwRuleSeq (location)? : tactic syntax (name := erwSeq) "erw " rwRuleSeq (location)? : tactic def rwWithRfl (kind : SyntaxNodeKind) (atom : String) (stx : Syntax) : MacroM Syntax := do -- We show the `rfl` state on `]` let seq := stx[1] let rbrak := seq[2] -- Replace `]` token with one without position information in the expanded tactic let seq := seq.setArg 2 (mkAtom "]") let tac := stx.setKind kind |>.setArg 0 (mkAtomFrom stx atom) |>.setArg 1 seq `(tactic| $tac; try (withReducible rfl%$rbrak)) @[macro rwSeq] def expandRwSeq : Macro := rwWithRfl ``Lean.Parser.Tactic.rewriteSeq "rewrite" @[macro erwSeq] def expandERwSeq : Macro := rwWithRfl ``Lean.Parser.Tactic.erewriteSeq "erewrite" syntax (name := injection) "injection " term (" with " (colGt (ident <|> "_"))+)? : tactic syntax (name := injections) "injections" : tactic syntax simpPre := "↓" syntax simpPost := "↑" syntax simpLemma := (simpPre <|> simpPost)? ("←" <|> "<-")? term syntax simpErase := "-" ident syntax simpStar := "*" syntax (name := simp) "simp " ("(" &"config" " := " term ")")? (&"only ")? ("[" (simpStar <|> simpErase <|> simpLemma),* "]")? (location)? : tactic syntax (name := simpAll) "simp_all " ("(" &"config" " := " term ")")? (&"only ")? ("[" (simpErase <|> simpLemma),* "]")? : tactic -- Auxiliary macro for lifting have/suffices/let/... -- It makes sure the "continuation" `?_` is the main goal after refining macro "refineLift " e:term : tactic => `(focus (refine noImplicitLambda% $e; rotateRight)) macro "have " d:haveDecl : tactic => `(refineLift have $d:haveDecl; ?_) /- We use a priority > default, to avoid ambiguity with previous `have` notation -/ macro (priority := high) "have" x:ident " := " p:term : tactic => `(have $x:ident : _ := $p) macro "suffices " d:sufficesDecl : tactic => `(refineLift suffices $d:sufficesDecl; ?_) macro "let " d:letDecl : tactic => `(refineLift let $d:letDecl; ?_) macro "show " e:term : tactic => `(refineLift show $e:term from ?_) syntax (name := letrec) withPosition(atomic(group("let " &"rec ")) letRecDecls) : tactic macro_rules | `(tactic| let rec $d:letRecDecls) => `(tactic| refineLift let rec $d:letRecDecls; ?_) -- Similar to `refineLift`, but using `refine'` macro "refineLift' " e:term : tactic => `(focus (refine' noImplicitLambda% $e; rotateRight)) macro "have' " d:haveDecl : tactic => `(refineLift' have $d:haveDecl; ?_) macro (priority := high) "have'" x:ident " := " p:term : tactic => `(have' $x:ident : _ := $p) macro "let' " d:letDecl : tactic => `(refineLift' let $d:letDecl; ?_) syntax inductionAlt := "| " (group("@"? ident) <|> "_") (ident <|> "_")* " => " (hole <|> syntheticHole <|> tacticSeq) syntax inductionAlts := "with " (tactic)? withPosition( (colGe inductionAlt)+) syntax (name := induction) "induction " term,+ (" using " ident)? ("generalizing " ident+)? (inductionAlts)? : tactic syntax generalizeArg := atomic(ident " : ")? term:51 " = " ident /-- `generalize ([h :] e = x),+` replaces all occurrences `e`s in the main goal with a fresh hypothesis `x`s. If `h` is given, `h : e = x` is introduced as well. -/ syntax (name := generalize) "generalize " generalizeArg,+ : tactic syntax casesTarget := atomic(ident " : ")? term syntax (name := cases) "cases " casesTarget,+ (" using " ident)? (inductionAlts)? : tactic syntax (name := existsIntro) "exists " term : tactic /-- `renameI x_1 ... x_n` renames the last `n` inaccessible names using the given names. -/ syntax (name := renameI) "renameI " (colGt (ident <|> "_"))+ : tactic syntax "repeat " tacticSeq : tactic macro_rules | `(tactic| repeat $seq) => `(tactic| first | ($seq); repeat $seq | skip) syntax "trivial" : tactic syntax (name := split) "split " (colGt term)? (location)? : tactic macro_rules | `(tactic| trivial) => `(tactic| assumption) macro_rules | `(tactic| trivial) => `(tactic| rfl) macro_rules | `(tactic| trivial) => `(tactic| contradiction) macro_rules | `(tactic| trivial) => `(tactic| apply True.intro) macro_rules | `(tactic| trivial) => `(tactic| apply And.intro <;> trivial) macro "unhygienic " t:tacticSeq : tactic => `(set_option tactic.hygienic false in $t:tacticSeq) end Tactic namespace Attr -- simp attribute syntax syntax (name := simp) "simp" (Tactic.simpPre <|> Tactic.simpPost)? (prio)? : attr end Attr end Parser end Lean macro "‹" type:term "›" : term => `((by assumption : $type))
c1052143d2d3df2117b127319e64d8d58331dd16
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/category/Groupoid.lean
5c4794374cef99c204d694086573bbea9c67bdb3
[ "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
3,998
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import category_theory.single_obj import category_theory.limits.shapes.products import category_theory.pi.basic import category_theory.limits.is_limit /-! # Category of groupoids This file contains the definition of the category `Groupoid` of all groupoids. In this category objects are groupoids and morphisms are functors between these groupoids. We also provide two “forgetting” functors: `objects : Groupoid ⥤ Type` and `forget_to_Cat : Groupoid ⥤ Cat`. ## Implementation notes Though `Groupoid` is not a concrete category, we use `bundled` to define its carrier type. -/ universes v u namespace category_theory /-- Category of groupoids -/ @[nolint check_univs] -- intended to be used with explicit universe parameters def Groupoid := bundled groupoid.{v u} namespace Groupoid instance : inhabited Groupoid := ⟨bundled.of (single_obj punit)⟩ instance str (C : Groupoid.{v u}) : groupoid.{v u} C.α := C.str instance : has_coe_to_sort Groupoid Type* := bundled.has_coe_to_sort /-- Construct a bundled `Groupoid` from the underlying type and the typeclass. -/ def of (C : Type u) [groupoid.{v} C] : Groupoid.{v u} := bundled.of C @[simp] lemma coe_of (C : Type u) [groupoid C] : (of C : Type u) = C := rfl /-- Category structure on `Groupoid` -/ instance category : large_category.{max v u} Groupoid.{v u} := { hom := λ C D, C ⥤ D, id := λ C, 𝟭 C, comp := λ C D E F G, F ⋙ G, id_comp' := λ C D F, by cases F; refl, comp_id' := λ C D F, by cases F; refl, assoc' := by intros; refl } /-- Functor that gets the set of objects of a groupoid. It is not called `forget`, because it is not a faithful functor. -/ def objects : Groupoid.{v u} ⥤ Type u := { obj := bundled.α, map := λ C D F, F.obj } /-- Forgetting functor to `Cat` -/ def forget_to_Cat : Groupoid.{v u} ⥤ Cat.{v u} := { obj := λ C, Cat.of C, map := λ C D, id } instance forget_to_Cat_full : full forget_to_Cat := { preimage := λ C D, id } instance forget_to_Cat_faithful : faithful forget_to_Cat := { } /-- Convert arrows in the category of groupoids to functors, which sometimes helps in applying simp lemmas -/ lemma hom_to_functor {C D E : Groupoid.{v u}} (f : C ⟶ D) (g : D ⟶ E) : f ≫ g = f ⋙ g := rfl /-- Converts identity in the category of groupoids to the functor identity -/ lemma id_to_functor {C : Groupoid.{v u}} : 𝟭 C = 𝟙 C := rfl section products /-- The cone for the product of a family of groupoids indexed by J is a limit cone -/ @[simps] def pi_limit_cone {J : Type u} (F : discrete J ⥤ Groupoid.{u u}) : limits.limit_cone F := { cone := { X := @of (Π j : J, F.obj j) _, π := { app := λ j : J, category_theory.pi.eval _ j, } }, is_limit := { lift := λ s, functor.pi' s.π.app, fac' := by { intros, simp [hom_to_functor], }, uniq' := begin intros s m w, apply functor.pi_ext, intro j, specialize w j, simpa, end } } /-- `pi_limit_cone` reinterpreted as a fan -/ abbreviation pi_limit_fan {J : Type u} (F : J → Groupoid.{u u}) : limits.fan F := (pi_limit_cone (discrete.functor F)).cone instance has_pi : limits.has_products Groupoid.{u u} := λ J, { has_limit := λ F, { exists_limit := nonempty.intro (pi_limit_cone F) } } /-- The product of a family of groupoids is isomorphic to the product object in the category of Groupoids -/ noncomputable def pi_iso_pi (J : Type u) (f : J → Groupoid.{u u}) : @of (Π j, f j) _ ≅ ∏ f := limits.is_limit.cone_point_unique_up_to_iso (pi_limit_cone (discrete.functor f)).is_limit (limits.limit.is_limit (discrete.functor f)) @[simp] lemma pi_iso_pi_hom_π (J : Type u) (f : J → Groupoid.{u u}) (j : J) : (pi_iso_pi J f).hom ≫ (limits.pi.π f j) = category_theory.pi.eval _ j := by { simp [pi_iso_pi], refl, } end products end Groupoid end category_theory
2999bb4a1c7a0c966e37fa1b7c1f09ac54908e90
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/category_theory/is_connected.lean
651c26884b19f311946ee33961e24717c593526c
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
14,284
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import data.list.chain import category_theory.punit import category_theory.groupoid /-! # Connected category Define a connected category as a _nonempty_ category for which every functor to a discrete category is isomorphic to the constant functor. NB. Some authors include the empty category as connected, we do not. We instead are interested in categories with exactly one 'connected component'. We give some equivalent definitions: - A nonempty category for which every functor to a discrete category is constant on objects. See `any_functor_const_on_obj` and `connected.of_any_functor_const_on_obj`. - A nonempty category for which every function `F` for which the presence of a morphism `f : j₁ ⟶ j₂` implies `F j₁ = F j₂` must be constant everywhere. See `constant_of_preserves_morphisms` and `connected.of_constant_of_preserves_morphisms`. - A nonempty category for which any subset of its elements containing the default and closed under morphisms is everything. See `induct_on_objects` and `connected.of_induct`. - A nonempty category for which every object is related under the reflexive transitive closure of the relation "there is a morphism in some direction from `j₁` to `j₂`". See `connected_zigzag` and `zigzag_connected`. - A nonempty category for which for any two objects there is a sequence of morphisms (some reversed) from one to the other. See `exists_zigzag'` and `connected_of_zigzag`. We also prove the result that the functor given by `(X × -)` preserves any connected limit. That is, any limit of shape `J` where `J` is a connected category is preserved by the functor `(X × -)`. This appears in `category_theory.limits.connected`. -/ universes v₁ v₂ u₁ u₂ noncomputable theory open category_theory.category open opposite namespace category_theory /-- A possibly empty category for which every functor to a discrete category is constant. -/ class is_preconnected (J : Type u₁) [category.{v₁} J] : Prop := (iso_constant : Π {α : Type u₁} (F : J ⥤ discrete α) (j : J), nonempty (F ≅ (functor.const J).obj (F.obj j))) /-- We define a connected category as a _nonempty_ category for which every functor to a discrete category is constant. NB. Some authors include the empty category as connected, we do not. We instead are interested in categories with exactly one 'connected component'. This allows us to show that the functor X ⨯ - preserves connected limits. See https://stacks.math.columbia.edu/tag/002S -/ class is_connected (J : Type u₁) [category.{v₁} J] extends is_preconnected J : Prop := [is_nonempty : nonempty J] attribute [instance, priority 100] is_connected.is_nonempty variables {J : Type u₁} [category.{v₁} J] variables {K : Type u₂} [category.{v₂} K] /-- If `J` is connected, any functor `F : J ⥤ discrete α` is isomorphic to the constant functor with value `F.obj j` (for any choice of `j`). -/ def iso_constant [is_preconnected J] {α : Type u₁} (F : J ⥤ discrete α) (j : J) : F ≅ (functor.const J).obj (F.obj j) := (is_preconnected.iso_constant F j).some /-- If J is connected, any functor to a discrete category is constant on objects. The converse is given in `is_connected.of_any_functor_const_on_obj`. -/ lemma any_functor_const_on_obj [is_preconnected J] {α : Type u₁} (F : J ⥤ discrete α) (j j' : J) : F.obj j = F.obj j' := ((iso_constant F j').hom.app j).down.1 /-- If any functor to a discrete category is constant on objects, J is connected. The converse of `any_functor_const_on_obj`. -/ lemma is_connected.of_any_functor_const_on_obj [nonempty J] (h : ∀ {α : Type u₁} (F : J ⥤ discrete α), ∀ (j j' : J), F.obj j = F.obj j') : is_connected J := { iso_constant := λ α F j', ⟨nat_iso.of_components (λ j, eq_to_iso (h F j j')) (λ _ _ _, subsingleton.elim _ _)⟩ } /-- If `J` is connected, then given any function `F` such that the presence of a morphism `j₁ ⟶ j₂` implies `F j₁ = F j₂`, we have that `F` is constant. This can be thought of as a local-to-global property. The converse is shown in `is_connected.of_constant_of_preserves_morphisms` -/ lemma constant_of_preserves_morphisms [is_preconnected J] {α : Type u₁} (F : J → α) (h : ∀ (j₁ j₂ : J) (f : j₁ ⟶ j₂), F j₁ = F j₂) (j j' : J) : F j = F j' := any_functor_const_on_obj { obj := F, map := λ _ _ f, eq_to_hom (h _ _ f) } j j' /-- `J` is connected if: given any function `F : J → α` which is constant for any `j₁, j₂` for which there is a morphism `j₁ ⟶ j₂`, then `F` is constant. This can be thought of as a local-to-global property. The converse of `constant_of_preserves_morphisms`. -/ lemma is_connected.of_constant_of_preserves_morphisms [nonempty J] (h : ∀ {α : Type u₁} (F : J → α), (∀ {j₁ j₂ : J} (f : j₁ ⟶ j₂), F j₁ = F j₂) → (∀ j j' : J, F j = F j')) : is_connected J := is_connected.of_any_functor_const_on_obj (λ _ F, h F.obj (λ _ _ f, (F.map f).down.1)) /-- An inductive-like property for the objects of a connected category. If the set `p` is nonempty, and `p` is closed under morphisms of `J`, then `p` contains all of `J`. The converse is given in `is_connected.of_induct`. -/ lemma induct_on_objects [is_preconnected J] (p : set J) {j₀ : J} (h0 : j₀ ∈ p) (h1 : ∀ {j₁ j₂ : J} (f : j₁ ⟶ j₂), j₁ ∈ p ↔ j₂ ∈ p) (j : J) : j ∈ p := begin injection (constant_of_preserves_morphisms (λ k, ulift.up (k ∈ p)) (λ j₁ j₂ f, _) j j₀) with i, rwa i, dsimp, exact congr_arg ulift.up (propext (h1 f)), end /-- If any maximal connected component containing some element j₀ of J is all of J, then J is connected. The converse of `induct_on_objects`. -/ lemma is_connected.of_induct [nonempty J] {j₀ : J} (h : ∀ (p : set J), j₀ ∈ p → (∀ {j₁ j₂ : J} (f : j₁ ⟶ j₂), j₁ ∈ p ↔ j₂ ∈ p) → ∀ (j : J), j ∈ p) : is_connected J := is_connected.of_constant_of_preserves_morphisms (λ α F a, begin have w := h {j | F j = F j₀} rfl (λ _ _ f, by simp [a f]), dsimp at w, intros j j', rw [w j, w j'], end) /-- Another induction principle for `is_preconnected J`: given a type family `Z : J → Sort*` and a rule for transporting in *both* directions along a morphism in `J`, we can transport an `x : Z j₀` to a point in `Z j` for any `j`. -/ lemma is_preconnected_induction [is_preconnected J] (Z : J → Sort*) (h₁ : Π {j₁ j₂ : J} (f : j₁ ⟶ j₂), Z j₁ → Z j₂) (h₂ : Π {j₁ j₂ : J} (f : j₁ ⟶ j₂), Z j₂ → Z j₁) {j₀ : J} (x : Z j₀) (j : J) : nonempty (Z j) := (induct_on_objects {j | nonempty (Z j)} ⟨x⟩ (λ j₁ j₂ f, ⟨by { rintro ⟨y⟩, exact ⟨h₁ f y⟩, }, by { rintro ⟨y⟩, exact ⟨h₂ f y⟩, }⟩) j : _) /-- If `J` and `K` are equivalent, then if `J` is preconnected then `K` is as well. -/ lemma is_preconnected_of_equivalent {K : Type u₁} [category.{v₂} K] [is_preconnected J] (e : J ≌ K) : is_preconnected K := { iso_constant := λ α F k, ⟨ calc F ≅ e.inverse ⋙ e.functor ⋙ F : (e.inv_fun_id_assoc F).symm ... ≅ e.inverse ⋙ (functor.const J).obj ((e.functor ⋙ F).obj (e.inverse.obj k)) : iso_whisker_left e.inverse (iso_constant (e.functor ⋙ F) (e.inverse.obj k)) ... ≅ e.inverse ⋙ (functor.const J).obj (F.obj k) : iso_whisker_left _ ((F ⋙ functor.const J).map_iso (e.counit_iso.app k)) ... ≅ (functor.const K).obj (F.obj k) : nat_iso.of_components (λ X, iso.refl _) (by simp), ⟩ } /-- If `J` and `K` are equivalent, then if `J` is connected then `K` is as well. -/ lemma is_connected_of_equivalent {K : Type u₁} [category.{v₂} K] (e : J ≌ K) [is_connected J] : is_connected K := { is_nonempty := nonempty.map e.functor.obj (by apply_instance), to_is_preconnected := is_preconnected_of_equivalent e } /-- If `J` is preconnected, then `Jᵒᵖ` is preconnected as well. -/ instance is_preconnected_op [is_preconnected J] : is_preconnected Jᵒᵖ := { iso_constant := λ α F X, ⟨ nat_iso.of_components (λ Y, (nonempty.some $ is_preconnected.iso_constant (F.right_op ⋙ (discrete.opposite α).functor) (unop X)).app (unop Y)) (λ Y Z f, subsingleton.elim _ _) ⟩ } /-- If `J` is connected, then `Jᵒᵖ` is connected as well. -/ instance is_connected_op [is_connected J] : is_connected Jᵒᵖ := { is_nonempty := nonempty.intro (op (classical.arbitrary J)) } lemma is_preconnected_of_is_preconnected_op [is_preconnected Jᵒᵖ] : is_preconnected J := is_preconnected_of_equivalent (op_op_equivalence J) lemma is_connected_of_is_connected_op [is_connected Jᵒᵖ] : is_connected J := is_connected_of_equivalent (op_op_equivalence J) /-- j₁ and j₂ are related by `zag` if there is a morphism between them. -/ @[reducible] def zag (j₁ j₂ : J) : Prop := nonempty (j₁ ⟶ j₂) ∨ nonempty (j₂ ⟶ j₁) lemma zag_symmetric : symmetric (@zag J _) := λ j₂ j₁ h, h.swap /-- `j₁` and `j₂` are related by `zigzag` if there is a chain of morphisms from `j₁` to `j₂`, with backward morphisms allowed. -/ @[reducible] def zigzag : J → J → Prop := relation.refl_trans_gen zag lemma zigzag_symmetric : symmetric (@zigzag J _) := relation.refl_trans_gen.symmetric zag_symmetric lemma zigzag_equivalence : _root_.equivalence (@zigzag J _) := mk_equivalence _ relation.reflexive_refl_trans_gen zigzag_symmetric relation.transitive_refl_trans_gen /-- The setoid given by the equivalence relation `zigzag`. A quotient for this setoid is a connected component of the category. -/ def zigzag.setoid (J : Type u₂) [category.{v₁} J] : setoid J := { r := zigzag, iseqv := zigzag_equivalence } /-- If there is a zigzag from `j₁` to `j₂`, then there is a zigzag from `F j₁` to `F j₂` as long as `F` is a functor. -/ lemma zigzag_obj_of_zigzag (F : J ⥤ K) {j₁ j₂ : J} (h : zigzag j₁ j₂) : zigzag (F.obj j₁) (F.obj j₂) := h.lift _ $ λ j k, or.imp (nonempty.map (λ f, F.map f)) (nonempty.map (λ f, F.map f)) -- TODO: figure out the right way to generalise this to `zigzag`. lemma zag_of_zag_obj (F : J ⥤ K) [full F] {j₁ j₂ : J} (h : zag (F.obj j₁) (F.obj j₂)) : zag j₁ j₂ := or.imp (nonempty.map F.preimage) (nonempty.map F.preimage) h /-- Any equivalence relation containing (⟶) holds for all pairs of a connected category. -/ lemma equiv_relation [is_connected J] (r : J → J → Prop) (hr : _root_.equivalence r) (h : ∀ {j₁ j₂ : J} (f : j₁ ⟶ j₂), r j₁ j₂) : ∀ (j₁ j₂ : J), r j₁ j₂ := begin have z : ∀ (j : J), r (classical.arbitrary J) j := induct_on_objects (λ k, r (classical.arbitrary J) k) (hr.1 (classical.arbitrary J)) (λ _ _ f, ⟨λ t, hr.2.2 t (h f), λ t, hr.2.2 t (hr.2.1 (h f))⟩), intros, apply hr.2.2 (hr.2.1 (z _)) (z _) end /-- In a connected category, any two objects are related by `zigzag`. -/ lemma is_connected_zigzag [is_connected J] (j₁ j₂ : J) : zigzag j₁ j₂ := equiv_relation _ zigzag_equivalence (λ _ _ f, relation.refl_trans_gen.single (or.inl (nonempty.intro f))) _ _ /-- If any two objects in an nonempty category are related by `zigzag`, the category is connected. -/ lemma zigzag_is_connected [nonempty J] (h : ∀ (j₁ j₂ : J), zigzag j₁ j₂) : is_connected J := begin apply is_connected.of_induct, intros p hp hjp j, have: ∀ (j₁ j₂ : J), zigzag j₁ j₂ → (j₁ ∈ p ↔ j₂ ∈ p), { introv k, induction k with _ _ rt_zag zag, { refl }, { rw k_ih, rcases zag with ⟨⟨_⟩⟩ | ⟨⟨_⟩⟩, apply hjp zag, apply (hjp zag).symm } }, rwa this j (classical.arbitrary J) (h _ _) end lemma exists_zigzag' [is_connected J] (j₁ j₂ : J) : ∃ l, list.chain zag j₁ l ∧ list.last (j₁ :: l) (list.cons_ne_nil _ _) = j₂ := list.exists_chain_of_relation_refl_trans_gen (is_connected_zigzag _ _) /-- If any two objects in an nonempty category are linked by a sequence of (potentially reversed) morphisms, then J is connected. The converse of `exists_zigzag'`. -/ lemma is_connected_of_zigzag [nonempty J] (h : ∀ (j₁ j₂ : J), ∃ l, list.chain zag j₁ l ∧ list.last (j₁ :: l) (list.cons_ne_nil _ _) = j₂) : is_connected J := begin apply zigzag_is_connected, intros j₁ j₂, rcases h j₁ j₂ with ⟨l, hl₁, hl₂⟩, apply list.relation_refl_trans_gen_of_exists_chain l hl₁ hl₂, end /-- If `discrete α` is connected, then `α` is (type-)equivalent to `punit`. -/ def discrete_is_connected_equiv_punit {α : Type u₁} [is_connected (discrete α)] : α ≃ punit := discrete.equiv_of_equivalence.{u₁ u₁} { functor := functor.star α, inverse := discrete.functor (λ _, classical.arbitrary _), unit_iso := by { exact (iso_constant _ (classical.arbitrary _)), }, counit_iso := functor.punit_ext _ _ } variables {C : Type u₂} [category.{u₁} C] /-- For objects `X Y : C`, any natural transformation `α : const X ⟶ const Y` from a connected category must be constant. This is the key property of connected categories which we use to establish properties about limits. -/ lemma nat_trans_from_is_connected [is_preconnected J] {X Y : C} (α : (functor.const J).obj X ⟶ (functor.const J).obj Y) : ∀ (j j' : J), α.app j = (α.app j' : X ⟶ Y) := @constant_of_preserves_morphisms _ _ _ (X ⟶ Y) (λ j, α.app j) (λ _ _ f, (by { have := α.naturality f, erw [id_comp, comp_id] at this, exact this.symm })) instance [is_connected J] : full (functor.const J : C ⥤ J ⥤ C) := { preimage := λ X Y f, f.app (classical.arbitrary J), witness' := λ X Y f, begin ext j, apply nat_trans_from_is_connected f (classical.arbitrary J) j, end } instance nonempty_hom_of_connected_groupoid {G} [groupoid G] [is_connected G] : ∀ (x y : G), nonempty (x ⟶ y) := begin refine equiv_relation _ _ (λ j₁ j₂, nonempty.intro), exact ⟨λ j, ⟨𝟙 _⟩, λ j₁ j₂, nonempty.map (λ f, inv f), λ _ _ _, nonempty.map2 (≫)⟩, end end category_theory
ff5f8fd0637690da6a3abc864d27d6362ebf7e97
037dba89703a79cd4a4aec5e959818147f97635d
/src/2020/relations/equality_nonsense.lean
68e220ba719a53010b68b8fc2c86b9130cd33eed
[]
no_license
ImperialCollegeLondon/M40001_lean
3a6a09298da395ab51bc220a535035d45bbe919b
62a76fa92654c855af2b2fc2bef8e60acd16ccec
refs/heads/master
1,666,750,403,259
1,665,771,117,000
1,665,771,117,000
209,141,835
115
12
null
1,640,270,596,000
1,568,749,174,000
Lean
UTF-8
Lean
false
false
304
lean
import tactic variables (α : Type) (x y z : α) --set_option pp.notation false example : x = x := begin refl, end example : x = y → y = x := begin intro h, induction h, refl, end example : x = y → y = z → x = z := begin intro hxy, intro hyz, induction hxy, assumption, end
c43922452890c52d6e5214d52142a1828ffd6c86
6329dd15b8fd567a4737f2dacd02bd0e8c4b3ae4
/src/game/world1/level15.lean
6321dd034967ac66be4b7a89201f1eb5a4095d47
[ "Apache-2.0" ]
permissive
agusakov/mathematics_in_lean_game
76e455a688a8826b05160c16c0490b9e3d39f071
ad45fd42148f2203b973537adec7e8a48677ba2a
refs/heads/master
1,666,147,402,274
1,592,119,137,000
1,592,119,137,000
272,111,226
0
0
null
null
null
null
UTF-8
Lean
false
false
565
lean
import data.real.basic --imports the real numbers import tactic.maths_in_lean_game -- hide namespace calculating -- hide /- #Calculating ## Level 15: `calc` keyword Now try proving the same theorem you proved in Level 14, only this time using a more structured `calc` proof: -/ variables a b c d : ℝ /- Lemma : no-side-bar For all natural numbers $a$, we have $$a + \operatorname{succ}(0) = \operatorname{succ}(a).$$ -/ lemma example15 : (a + b) * (c + d) = a * c + a * d + b * c + b * d := begin [maths_in_lean_game] sorry end end calculating -- hide
067c33af6ab4049623de1332dbb4b4b5e09fa02f
271e26e338b0c14544a889c31c30b39c989f2e0f
/tests/lean/run/coroutine.lean
3f4963860e0405b493a8747b8b45541e1ca339f8
[ "Apache-2.0" ]
permissive
dgorokho/lean4
805f99b0b60c545b64ac34ab8237a8504f89d7d4
e949a052bad59b1c7b54a82d24d516a656487d8a
refs/heads/master
1,607,061,363,851
1,578,006,086,000
1,578,006,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,514
lean
universes u v w r s inductive coroutineResultCore (coroutine : Type (max u v w)) (α : Type u) (δ : Type v) (β : Type w) : Type (max u v w) | done {} : β → coroutineResultCore | yielded {} : δ → coroutine → coroutineResultCore /-- Asymmetric coroutines `coroutine α δ β` takes inputs of Type `α`, yields elements of Type `δ`, and produces an element of Type `β`. Asymmetric coroutines are so called because they involve two types of control transfer operations: one for resuming/invoking a coroutine and one for suspending it, the latter returning control to the coroutine invoker. An asymmetric coroutine can be regarded as subordinate to its caller, the relationship between them being similar to that between a called and a calling routine. -/ inductive coroutine (α : Type u) (δ : Type v) (β : Type w) : Type (max u v w) | mk {} : (α → coroutineResultCore coroutine α δ β) → coroutine abbrev coroutineResult (α : Type u) (δ : Type v) (β : Type w) : Type (max u v w) := coroutineResultCore (coroutine α δ β) α δ β namespace coroutine variables {α : Type u} {δ : Type v} {β γ : Type w} export coroutineResultCore (done yielded) /-- `resume c a` resumes/invokes the coroutine `c` with input `a`. -/ @[inline] def resume : coroutine α δ β → α → coroutineResult α δ β | mk k, a => k a @[inline] protected def pure (b : β) : coroutine α δ β := mk $ fun _ => done b /-- Read the input argument passed to the coroutine. Remark: should we use a different Name? I added an instance [MonadReader] later. -/ @[inline] protected def read : coroutine α δ α := mk $ fun a => done a /-- Run nested coroutine with transformed input argument. Like `ReaderT.adapt`, but cannot change the input Type. -/ @[inline] protected def adapt (f : α → α) (c : coroutine α δ β) : coroutine α δ β := mk $ fun a => c.resume (f a) /-- Return the control to the invoker with Result `d` -/ @[inline] protected def yield (d : δ) : coroutine α δ PUnit := mk $ fun a => yielded d (coroutine.pure ⟨⟩) /- TODO(Leo): following relations have been commented because Lean4 is currently accepting non-terminating programs. /-- Auxiliary relation for showing that bind/pipe terminate -/ inductive directSubcoroutine : coroutine α δ β → coroutine α δ β → Prop | mk : ∀ (k : α → coroutineResult α δ β) (a : α) (d : δ) (c : coroutine α δ β), k a = yielded d c → directSubcoroutine c (mk k) theorem directSubcoroutineWf : WellFounded (@directSubcoroutine α δ β) := begin Constructor, intro c, apply @coroutine.ind _ _ _ (fun c => Acc directSubcoroutine c) (fun r => ∀ (d : δ) (c : coroutine α δ β), r = yielded d c → Acc directSubcoroutine c), { intros k ih, dsimp at ih, Constructor, intros c' h, cases h, apply ih hA hD, assumption }, { intros, contradiction }, { intros d c ih d₁ c₁ Heq, injection Heq, subst c, assumption } end /-- Transitive closure of directSubcoroutine. It is not used here, but may be useful when defining more complex procedures. -/ def subcoroutine : coroutine α δ β → coroutine α δ β → Prop := Tc directSubcoroutine theorem subcoroutineWf : WellFounded (@subcoroutine α δ β) := Tc.wf directSubcoroutineWf -- Local instances for proving termination by well founded relation def bindWfInst : HasWellFounded (Σ' a : coroutine α δ β, (β → coroutine α δ γ)) := { r := Psigma.Lex directSubcoroutine (fun _ => emptyRelation), wf := Psigma.lexWf directSubcoroutineWf (fun _ => emptyWf) } def pipeWfInst : HasWellFounded (Σ' a : coroutine α δ β, coroutine δ γ β) := { r := Psigma.Lex directSubcoroutine (fun _ => emptyRelation), wf := Psigma.lexWf directSubcoroutineWf (fun _ => emptyWf) } local attribute [instance] wfInst₁ wfInst₂ open wellFoundedTactics -/ /- TODO: remove `unsafe` keyword after we restore well-founded recursion -/ @[inlineIfReduce] protected unsafe def bind : coroutine α δ β → (β → coroutine α δ γ) → coroutine α δ γ | mk k, f => mk $ fun a => match k a, rfl : ∀ (n : _), n = k a → _ with | done b, _ => coroutine.resume (f b) a | yielded d c, h => -- have directSubcoroutine c (mk k), { apply directSubcoroutine.mk k a d, rw h }, yielded d (bind c f) -- usingWellFounded { decTac := unfoldWfRel >> processLex (tactic.assumption) } unsafe def pipe : coroutine α δ β → coroutine δ γ β → coroutine α γ β | mk k₁, mk k₂ => mk $ fun a => match k₁ a, rfl : ∀ (n : _), n = k₁ a → _ with | done b, h => done b | yielded d k₁', h => match k₂ d with | done b => done b | yielded r k₂' => -- have directSubcoroutine k₁' (mk k₁), { apply directSubcoroutine.mk k₁ a d, rw h }, yielded r (pipe k₁' k₂') -- usingWellFounded { decTac := unfoldWfRel >> processLex (tactic.assumption) } private unsafe def finishAux (f : δ → α) : coroutine α δ β → α → List δ → List δ × β | mk k, a, ds => match k a with | done b => (ds.reverse, b) | yielded d k' => finishAux k' (f d) (d::ds) /-- Run a coroutine to completion, feeding back yielded items after transforming them with `f`. -/ unsafe def finish (f : δ → α) : coroutine α δ β → α → List δ × β := fun k a => finishAux f k a [] unsafe instance : Monad (coroutine α δ) := { pure := @coroutine.pure _ _, bind := @coroutine.bind _ _ } unsafe instance : MonadReader α (coroutine α δ) := { read := @coroutine.read _ _ } end coroutine /-- Auxiliary class for lifiting `yield` -/ class monadCoroutine (α : outParam (Type u)) (δ : outParam (Type v)) (m : Type w → Type r) := (yield {} : δ → m PUnit) instance (α : Type u) (δ : Type v) : monadCoroutine α δ (coroutine α δ) := { yield := coroutine.yield } instance monadCoroutineTrans (α : Type u) (δ : Type v) (m : Type w → Type r) (n : Type w → Type s) [monadCoroutine α δ m] [HasMonadLift m n] : monadCoroutine α δ n := { yield := fun d => monadLift (monadCoroutine.yield d : m _) } export monadCoroutine (yield) open coroutine namespace ex1 inductive tree (α : Type u) | leaf {} : tree | Node : tree → α → tree → tree /-- Coroutine as generators/iterators -/ unsafe def visit {α : Type v} : tree α → coroutine Unit α Unit | tree.leaf => pure () | tree.Node l a r => do visit l; yield a; visit r unsafe def tst {α : Type} [HasToString α] (t : tree α) : ExceptT String IO Unit := do c ← pure $ visit t; (yielded v₁ c) ← pure $ resume c (); (yielded v₂ c) ← pure $ resume c (); IO.println $ toString v₁; IO.println $ toString v₂; pure () -- #eval tst (tree.Node (tree.Node (tree.Node tree.leaf 5 tree.leaf) 10 (tree.Node tree.leaf 20 tree.leaf)) 30 tree.leaf) end ex1 namespace ex2 unsafe def ex : StateT Nat (coroutine Nat String) Unit := do x ← read; y ← get; set (y+5); yield ("1) val: " ++ toString (x+y)); x ← read; y ← get; yield ("2) val: " ++ toString (x+y)); pure () unsafe def tst2 : ExceptT String IO Unit := do let c := StateT.run ex 5; (yielded r c₁) ← pure $ resume c 10; IO.println r; (yielded r c₂) ← pure $ resume c₁ 20; IO.println r; (done _) ← pure $ resume c₂ 30; (yielded r c₃) ← pure $ resume c₁ 100; IO.println r; IO.println "done"; pure () -- #eval tst2 end ex2
131c3f8c3b4214bcf4d6a64db43d5fade699ed4a
9dc8cecdf3c4634764a18254e94d43da07142918
/src/linear_algebra/dual.lean
48f3ddbfe73423c63c58d14707deb47a979315d8
[ "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
30,597
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Fabian Glöckle -/ import linear_algebra.finite_dimensional import linear_algebra.projection import linear_algebra.sesquilinear_form import ring_theory.finiteness import linear_algebra.free_module.finite.rank /-! # Dual vector spaces The dual space of an R-module M is the R-module of linear maps `M → R`. ## Main definitions * `dual R M` defines the dual space of M over R. * Given a basis for an `R`-module `M`, `basis.to_dual` produces a map from `M` to `dual R M`. * Given families of vectors `e` and `ε`, `module.dual_bases e ε` states that these families have the characteristic properties of a basis and a dual. * `dual_annihilator W` is the submodule of `dual R M` where every element annihilates `W`. ## Main results * `to_dual_equiv` : the linear equivalence between the dual module and primal module, given a finite basis. * `module.dual_bases.basis` and `module.dual_bases.eq_dual`: if `e` and `ε` form a dual pair, `e` is a basis and `ε` is its dual basis. * `quot_equiv_annihilator`: the quotient by a subspace is isomorphic to its dual annihilator. ## Notation We sometimes use `V'` as local notation for `dual K V`. ## TODO Erdös-Kaplansky theorem about the dimension of a dual vector space in case of infinite dimension. -/ noncomputable theory namespace module variables (R : Type*) (M : Type*) variables [comm_semiring R] [add_comm_monoid M] [module R M] /-- The dual space of an R-module M is the R-module of linear maps `M → R`. -/ @[derive [add_comm_monoid, module R]] def dual := M →ₗ[R] R instance {S : Type*} [comm_ring S] {N : Type*} [add_comm_group N] [module S N] : add_comm_group (dual S N) := linear_map.add_comm_group instance : linear_map_class (dual R M) R M R := linear_map.semilinear_map_class /-- The canonical pairing of a vector space and its algebraic dual. -/ def dual_pairing (R M) [comm_semiring R] [add_comm_monoid M] [module R M] : module.dual R M →ₗ[R] M →ₗ[R] R := linear_map.id @[simp] lemma dual_pairing_apply (v x) : dual_pairing R M v x = v x := rfl namespace dual instance : inhabited (dual R M) := linear_map.inhabited instance : has_coe_to_fun (dual R M) (λ _, M → R) := ⟨linear_map.to_fun⟩ /-- Maps a module M to the dual of the dual of M. See `module.erange_coe` and `module.eval_equiv`. -/ def eval : M →ₗ[R] (dual R (dual R M)) := linear_map.flip linear_map.id @[simp] lemma eval_apply (v : M) (a : dual R M) : eval R M v a = a v := begin dunfold eval, rw [linear_map.flip_apply, linear_map.id_apply] end variables {R M} {M' : Type*} [add_comm_monoid M'] [module R M'] /-- The transposition of linear maps, as a linear map from `M →ₗ[R] M'` to `dual R M' →ₗ[R] dual R M`. -/ def transpose : (M →ₗ[R] M') →ₗ[R] (dual R M' →ₗ[R] dual R M) := (linear_map.llcomp R M M' R).flip lemma transpose_apply (u : M →ₗ[R] M') (l : dual R M') : transpose u l = l.comp u := rfl variables {M'' : Type*} [add_comm_monoid M''] [module R M''] lemma transpose_comp (u : M' →ₗ[R] M'') (v : M →ₗ[R] M') : transpose (u.comp v) = (transpose v).comp (transpose u) := rfl end dual end module namespace basis universes u v w open module module.dual submodule linear_map cardinal function open_locale big_operators variables {R M K V ι : Type*} section comm_semiring variables [comm_semiring R] [add_comm_monoid M] [module R M] [decidable_eq ι] variables (b : basis ι R M) /-- The linear map from a vector space equipped with basis to its dual vector space, taking basis elements to corresponding dual basis elements. -/ def to_dual : M →ₗ[R] module.dual R M := b.constr ℕ $ λ v, b.constr ℕ $ λ w, if w = v then (1 : R) else 0 lemma to_dual_apply (i j : ι) : b.to_dual (b i) (b j) = if i = j then 1 else 0 := by { erw [constr_basis b, constr_basis b], ac_refl } @[simp] lemma to_dual_total_left (f : ι →₀ R) (i : ι) : b.to_dual (finsupp.total ι M R b f) (b i) = f i := begin rw [finsupp.total_apply, finsupp.sum, linear_map.map_sum, linear_map.sum_apply], simp_rw [linear_map.map_smul, linear_map.smul_apply, to_dual_apply, smul_eq_mul, mul_boole, finset.sum_ite_eq'], split_ifs with h, { refl }, { rw finsupp.not_mem_support_iff.mp h } end @[simp] lemma to_dual_total_right (f : ι →₀ R) (i : ι) : b.to_dual (b i) (finsupp.total ι M R b f) = f i := begin rw [finsupp.total_apply, finsupp.sum, linear_map.map_sum], simp_rw [linear_map.map_smul, to_dual_apply, smul_eq_mul, mul_boole, finset.sum_ite_eq], split_ifs with h, { refl }, { rw finsupp.not_mem_support_iff.mp h } end lemma to_dual_apply_left (m : M) (i : ι) : b.to_dual m (b i) = b.repr m i := by rw [← b.to_dual_total_left, b.total_repr] lemma to_dual_apply_right (i : ι) (m : M) : b.to_dual (b i) m = b.repr m i := by rw [← b.to_dual_total_right, b.total_repr] lemma coe_to_dual_self (i : ι) : b.to_dual (b i) = b.coord i := by { ext, apply to_dual_apply_right } /-- `h.to_dual_flip v` is the linear map sending `w` to `h.to_dual w v`. -/ def to_dual_flip (m : M) : (M →ₗ[R] R) := b.to_dual.flip m lemma to_dual_flip_apply (m₁ m₂ : M) : b.to_dual_flip m₁ m₂ = b.to_dual m₂ m₁ := rfl lemma to_dual_eq_repr (m : M) (i : ι) : b.to_dual m (b i) = b.repr m i := b.to_dual_apply_left m i lemma to_dual_eq_equiv_fun [fintype ι] (m : M) (i : ι) : b.to_dual m (b i) = b.equiv_fun m i := by rw [b.equiv_fun_apply, to_dual_eq_repr] lemma to_dual_inj (m : M) (a : b.to_dual m = 0) : m = 0 := begin rw [← mem_bot R, ← b.repr.ker, mem_ker, linear_equiv.coe_coe], apply finsupp.ext, intro b, rw [← to_dual_eq_repr, a], refl end theorem to_dual_ker : b.to_dual.ker = ⊥ := ker_eq_bot'.mpr b.to_dual_inj theorem to_dual_range [_root_.finite ι] : b.to_dual.range = ⊤ := begin casesI nonempty_fintype ι, refine eq_top_iff'.2 (λ f, _), rw linear_map.mem_range, let lin_comb : ι →₀ R := finsupp.equiv_fun_on_fintype.2 (λ i, f.to_fun (b i)), refine ⟨finsupp.total ι M R b lin_comb, b.ext $ λ i, _⟩, rw [b.to_dual_eq_repr _ i, repr_total b], refl, end end comm_semiring section variables [comm_semiring R] [add_comm_monoid M] [module R M] [fintype ι] variables (b : basis ι R M) @[simp] lemma sum_dual_apply_smul_coord (f : module.dual R M) : ∑ x, f (b x) • b.coord x = f := begin ext m, simp_rw [linear_map.sum_apply, linear_map.smul_apply, smul_eq_mul, mul_comm (f _), ←smul_eq_mul, ←f.map_smul, ←f.map_sum, basis.coord_apply, basis.sum_repr], end end section comm_ring variables [comm_ring R] [add_comm_group M] [module R M] [decidable_eq ι] variables (b : basis ι R M) section finite variables [_root_.finite ι] /-- A vector space is linearly equivalent to its dual space. -/ @[simps] def to_dual_equiv : M ≃ₗ[R] dual R M := linear_equiv.of_bijective b.to_dual (ker_eq_bot.mp b.to_dual_ker) (range_eq_top.mp b.to_dual_range) /-- Maps a basis for `V` to a basis for the dual space. -/ def dual_basis : basis ι R (dual R M) := b.map b.to_dual_equiv -- We use `j = i` to match `basis.repr_self` lemma dual_basis_apply_self (i j : ι) : b.dual_basis i (b j) = if j = i then 1 else 0 := by { convert b.to_dual_apply i j using 2, rw @eq_comm _ j i } lemma total_dual_basis (f : ι →₀ R) (i : ι) : finsupp.total ι (dual R M) R b.dual_basis f (b i) = f i := begin casesI nonempty_fintype ι, rw [finsupp.total_apply, finsupp.sum_fintype, linear_map.sum_apply], { simp_rw [linear_map.smul_apply, smul_eq_mul, dual_basis_apply_self, mul_boole, finset.sum_ite_eq, if_pos (finset.mem_univ i)] }, { intro, rw zero_smul }, end lemma dual_basis_repr (l : dual R M) (i : ι) : b.dual_basis.repr l i = l (b i) := by rw [← total_dual_basis b, basis.total_repr b.dual_basis l] lemma dual_basis_apply (i : ι) (m : M) : b.dual_basis i m = b.repr m i := b.to_dual_apply_right i m @[simp] lemma coe_dual_basis : ⇑b.dual_basis = b.coord := by { ext i x, apply dual_basis_apply } @[simp] lemma to_dual_to_dual : b.dual_basis.to_dual.comp b.to_dual = dual.eval R M := begin refine b.ext (λ i, b.dual_basis.ext (λ j, _)), rw [linear_map.comp_apply, to_dual_apply_left, coe_to_dual_self, ← coe_dual_basis, dual.eval_apply, basis.repr_self, finsupp.single_apply, dual_basis_apply_self] end end finite lemma dual_basis_equiv_fun [fintype ι] (l : dual R M) (i : ι) : b.dual_basis.equiv_fun l i = l (b i) := by rw [basis.equiv_fun_apply, dual_basis_repr] theorem eval_ker {ι : Type*} (b : basis ι R M) : (dual.eval R M).ker = ⊥ := begin rw ker_eq_bot', intros m hm, simp_rw [linear_map.ext_iff, dual.eval_apply, zero_apply] at hm, exact (basis.forall_coord_eq_zero_iff _).mp (λ i, hm (b.coord i)) end lemma eval_range {ι : Type*} [_root_.finite ι] (b : basis ι R M) : (eval R M).range = ⊤ := begin classical, casesI nonempty_fintype ι, rw [← b.to_dual_to_dual, range_comp, b.to_dual_range, map_top, to_dual_range _], apply_instance end /-- A module with a basis is linearly equivalent to the dual of its dual space. -/ def eval_equiv {ι : Type*} [_root_.finite ι] (b : basis ι R M) : M ≃ₗ[R] dual R (dual R M) := linear_equiv.of_bijective (eval R M) (ker_eq_bot.mp b.eval_ker) (range_eq_top.mp b.eval_range) @[simp] lemma eval_equiv_to_linear_map {ι : Type*} [_root_.finite ι] (b : basis ι R M) : (b.eval_equiv).to_linear_map = dual.eval R M := rfl section open_locale classical variables [finite R M] [free R M] [nontrivial R] instance dual_free : free R (dual R M) := free.of_basis (free.choose_basis R M).dual_basis instance dual_finite : finite R (dual R M) := finite.of_basis (free.choose_basis R M).dual_basis end end comm_ring /-- `simp` normal form version of `total_dual_basis` -/ @[simp] lemma total_coord [comm_ring R] [add_comm_group M] [module R M] [_root_.finite ι] (b : basis ι R M) (f : ι →₀ R) (i : ι) : finsupp.total ι (dual R M) R b.coord f (b i) = f i := by { haveI := classical.dec_eq ι, rw [← coe_dual_basis, total_dual_basis] } lemma dual_dim_eq [comm_ring K] [add_comm_group V] [module K V] [_root_.finite ι] (b : basis ι K V) : cardinal.lift (module.rank K V) = module.rank K (dual K V) := begin classical, casesI nonempty_fintype ι, have := linear_equiv.lift_dim_eq b.to_dual_equiv, simp only [cardinal.lift_umax] at this, rw [this, ← cardinal.lift_umax], apply cardinal.lift_id, end end basis namespace module variables {K V : Type*} variables [field K] [add_comm_group V] [module K V] open module module.dual submodule linear_map cardinal basis finite_dimensional theorem eval_ker : (eval K V).ker = ⊥ := by { classical, exact (basis.of_vector_space K V).eval_ker } -- TODO(jmc): generalize to rings, once `module.rank` is generalized theorem dual_dim_eq [finite_dimensional K V] : cardinal.lift (module.rank K V) = module.rank K (dual K V) := (basis.of_vector_space K V).dual_dim_eq lemma erange_coe [finite_dimensional K V] : (eval K V).range = ⊤ := begin letI : is_noetherian K V := is_noetherian.iff_fg.2 infer_instance, exact (basis.of_vector_space K V).eval_range end variables (K V) /-- A vector space is linearly equivalent to the dual of its dual space. -/ def eval_equiv [finite_dimensional K V] : V ≃ₗ[K] dual K (dual K V) := linear_equiv.of_bijective (eval K V) (ker_eq_bot.mp eval_ker) (range_eq_top.mp erange_coe) variables {K V} @[simp] lemma eval_equiv_to_linear_map [finite_dimensional K V] : (eval_equiv K V).to_linear_map = dual.eval K V := rfl end module section dual_bases open module variables {R M ι : Type*} variables [comm_semiring R] [add_comm_monoid M] [module R M] [decidable_eq ι] /-- `e` and `ε` have characteristic properties of a basis and its dual -/ @[nolint has_nonempty_instance] structure module.dual_bases (e : ι → M) (ε : ι → (dual R M)) := (eval : ∀ i j : ι, ε i (e j) = if i = j then 1 else 0) (total : ∀ {m : M}, (∀ i, ε i m = 0) → m = 0) [finite : ∀ m : M, fintype {i | ε i m ≠ 0}] end dual_bases namespace module.dual_bases open module module.dual linear_map function variables {R M ι : Type*} variables [comm_ring R] [add_comm_group M] [module R M] variables {e : ι → M} {ε : ι → dual R M} /-- The coefficients of `v` on the basis `e` -/ def coeffs [decidable_eq ι] (h : dual_bases e ε) (m : M) : ι →₀ R := { to_fun := λ i, ε i m, support := by { haveI := h.finite m, exact {i : ι | ε i m ≠ 0}.to_finset }, mem_support_to_fun := by {intro i, rw set.mem_to_finset, exact iff.rfl } } @[simp] lemma coeffs_apply [decidable_eq ι] (h : dual_bases e ε) (m : M) (i : ι) : h.coeffs m i = ε i m := rfl /-- linear combinations of elements of `e`. This is a convenient abbreviation for `finsupp.total _ M R e l` -/ def lc {ι} (e : ι → M) (l : ι →₀ R) : M := l.sum (λ (i : ι) (a : R), a • (e i)) lemma lc_def (e : ι → M) (l : ι →₀ R) : lc e l = finsupp.total _ _ _ e l := rfl open module variables [decidable_eq ι] (h : dual_bases e ε) include h lemma dual_lc (l : ι →₀ R) (i : ι) : ε i (dual_bases.lc e l) = l i := begin erw linear_map.map_sum, simp only [h.eval, map_smul, smul_eq_mul], rw finset.sum_eq_single i, { simp }, { intros q q_in q_ne, simp [q_ne.symm] }, { intro p_not_in, simp [finsupp.not_mem_support_iff.1 p_not_in] }, end @[simp] lemma coeffs_lc (l : ι →₀ R) : h.coeffs (dual_bases.lc e l) = l := by { ext i, rw [h.coeffs_apply, h.dual_lc] } /-- For any m : M n, \sum_{p ∈ Q n} (ε p m) • e p = m -/ @[simp] lemma lc_coeffs (m : M) : dual_bases.lc e (h.coeffs m) = m := begin refine eq_of_sub_eq_zero (h.total _), intros i, simp [-sub_eq_add_neg, linear_map.map_sub, h.dual_lc, sub_eq_zero] end /-- `(h : dual_bases e ε).basis` shows the family of vectors `e` forms a basis. -/ @[simps] def basis : basis ι R M := basis.of_repr { to_fun := coeffs h, inv_fun := lc e, left_inv := lc_coeffs h, right_inv := coeffs_lc h, map_add' := λ v w, by { ext i, exact (ε i).map_add v w }, map_smul' := λ c v, by { ext i, exact (ε i).map_smul c v } } @[simp] lemma coe_basis : ⇑h.basis = e := by { ext i, rw basis.apply_eq_iff, ext j, rw [h.basis_repr_apply, coeffs_apply, h.eval, finsupp.single_apply], convert if_congr eq_comm rfl rfl } -- `convert` to get rid of a `decidable_eq` mismatch lemma mem_of_mem_span {H : set ι} {x : M} (hmem : x ∈ submodule.span R (e '' H)) : ∀ i : ι, ε i x ≠ 0 → i ∈ H := begin intros i hi, rcases (finsupp.mem_span_image_iff_total _).mp hmem with ⟨l, supp_l, rfl⟩, apply not_imp_comm.mp ((finsupp.mem_supported' _ _).mp supp_l i), rwa [← lc_def, h.dual_lc] at hi end lemma coe_dual_basis [fintype ι] : ⇑h.basis.dual_basis = ε := funext (λ i, h.basis.ext (λ j, by rw [h.basis.dual_basis_apply_self, h.coe_basis, h.eval, if_congr eq_comm rfl rfl])) end module.dual_bases namespace submodule universes u v w variables {R : Type u} {M : Type v} [comm_semiring R] [add_comm_monoid M] [module R M] variable {W : submodule R M} /-- The `dual_restrict` of a submodule `W` of `M` is the linear map from the dual of `M` to the dual of `W` such that the domain of each linear map is restricted to `W`. -/ def dual_restrict (W : submodule R M) : module.dual R M →ₗ[R] module.dual R W := linear_map.dom_restrict' W @[simp] lemma dual_restrict_apply (W : submodule R M) (φ : module.dual R M) (x : W) : W.dual_restrict φ x = φ (x : M) := rfl /-- The `dual_annihilator` of a submodule `W` is the set of linear maps `φ` such that `φ w = 0` for all `w ∈ W`. -/ def dual_annihilator {R : Type u} {M : Type v} [comm_semiring R] [add_comm_monoid M] [module R M] (W : submodule R M) : submodule R $ module.dual R M := W.dual_restrict.ker @[simp] lemma mem_dual_annihilator (φ : module.dual R M) : φ ∈ W.dual_annihilator ↔ ∀ w ∈ W, φ w = 0 := begin refine linear_map.mem_ker.trans _, simp_rw [linear_map.ext_iff, dual_restrict_apply], exact ⟨λ h w hw, h ⟨w, hw⟩, λ h w, h w.1 w.2⟩ end lemma dual_restrict_ker_eq_dual_annihilator (W : submodule R M) : W.dual_restrict.ker = W.dual_annihilator := rfl lemma dual_annihilator_sup_eq_inf_dual_annihilator (U V : submodule R M) : (U ⊔ V).dual_annihilator = U.dual_annihilator ⊓ V.dual_annihilator := begin ext φ, rw [mem_inf, mem_dual_annihilator, mem_dual_annihilator, mem_dual_annihilator], split; intro h, { refine ⟨_, _⟩; intros x hx, exact h x (mem_sup.2 ⟨x, hx, 0, zero_mem _, add_zero _⟩), exact h x (mem_sup.2 ⟨0, zero_mem _, x, hx, zero_add _⟩) }, { simp_rw mem_sup, rintro _ ⟨x, hx, y, hy, rfl⟩, rw [linear_map.map_add, h.1 _ hx, h.2 _ hy, add_zero] } end /-- The pullback of a submodule in the dual space along the evaluation map. -/ def dual_annihilator_comap (Φ : submodule R (module.dual R M)) : submodule R M := Φ.dual_annihilator.comap (module.dual.eval R M) lemma mem_dual_annihilator_comap_iff {Φ : submodule R (module.dual R M)} (x : M) : x ∈ Φ.dual_annihilator_comap ↔ ∀ φ ∈ Φ, (φ x : R) = 0 := by simp_rw [dual_annihilator_comap, mem_comap, mem_dual_annihilator, module.dual.eval_apply] end submodule namespace subspace open submodule linear_map universes u v w -- We work in vector spaces because `exists_is_compl` only hold for vector spaces variables {K : Type u} {V : Type v} [field K] [add_comm_group V] [module K V] /-- Given a subspace `W` of `V` and an element of its dual `φ`, `dual_lift W φ` is the natural extension of `φ` to an element of the dual of `V`. That is, `dual_lift W φ` sends `w ∈ W` to `φ x` and `x` in the complement of `W` to `0`. -/ noncomputable def dual_lift (W : subspace K V) : module.dual K W →ₗ[K] module.dual K V := let h := classical.indefinite_description _ W.exists_is_compl in (linear_map.of_is_compl_prod h.2).comp (linear_map.inl _ _ _) variable {W : subspace K V} @[simp] lemma dual_lift_of_subtype {φ : module.dual K W} (w : W) : W.dual_lift φ (w : V) = φ w := by { erw of_is_compl_left_apply _ w, refl } lemma dual_lift_of_mem {φ : module.dual K W} {w : V} (hw : w ∈ W) : W.dual_lift φ w = φ ⟨w, hw⟩ := by convert dual_lift_of_subtype ⟨w, hw⟩ @[simp] lemma dual_restrict_comp_dual_lift (W : subspace K V) : W.dual_restrict.comp W.dual_lift = 1 := by { ext φ x, simp } lemma dual_restrict_left_inverse (W : subspace K V) : function.left_inverse W.dual_restrict W.dual_lift := λ x, show W.dual_restrict.comp W.dual_lift x = x, by { rw [dual_restrict_comp_dual_lift], refl } lemma dual_lift_right_inverse (W : subspace K V) : function.right_inverse W.dual_lift W.dual_restrict := W.dual_restrict_left_inverse lemma dual_restrict_surjective : function.surjective W.dual_restrict := W.dual_lift_right_inverse.surjective lemma dual_lift_injective : function.injective W.dual_lift := W.dual_restrict_left_inverse.injective /-- The quotient by the `dual_annihilator` of a subspace is isomorphic to the dual of that subspace. -/ noncomputable def quot_annihilator_equiv (W : subspace K V) : (module.dual K V ⧸ W.dual_annihilator) ≃ₗ[K] module.dual K W := (quot_equiv_of_eq _ _ W.dual_restrict_ker_eq_dual_annihilator).symm.trans $ W.dual_restrict.quot_ker_equiv_of_surjective dual_restrict_surjective /-- The natural isomorphism forom the dual of a subspace `W` to `W.dual_lift.range`. -/ noncomputable def dual_equiv_dual (W : subspace K V) : module.dual K W ≃ₗ[K] W.dual_lift.range := linear_equiv.of_injective _ dual_lift_injective lemma dual_equiv_dual_def (W : subspace K V) : W.dual_equiv_dual.to_linear_map = W.dual_lift.range_restrict := rfl @[simp] lemma dual_equiv_dual_apply (φ : module.dual K W) : W.dual_equiv_dual φ = ⟨W.dual_lift φ, mem_range.2 ⟨φ, rfl⟩⟩ := rfl section open_locale classical open finite_dimensional variables {V₁ : Type*} [add_comm_group V₁] [module K V₁] instance [H : finite_dimensional K V] : finite_dimensional K (module.dual K V) := by apply_instance variables [finite_dimensional K V] [finite_dimensional K V₁] @[simp] lemma dual_finrank_eq : finrank K (module.dual K V) = finrank K V := linear_equiv.finrank_eq (basis.of_vector_space K V).to_dual_equiv.symm /-- The quotient by the dual is isomorphic to its dual annihilator. -/ noncomputable def quot_dual_equiv_annihilator (W : subspace K V) : (module.dual K V ⧸ W.dual_lift.range) ≃ₗ[K] W.dual_annihilator := linear_equiv.quot_equiv_of_quot_equiv $ linear_equiv.trans W.quot_annihilator_equiv W.dual_equiv_dual /-- The quotient by a subspace is isomorphic to its dual annihilator. -/ noncomputable def quot_equiv_annihilator (W : subspace K V) : (V ⧸ W) ≃ₗ[K] W.dual_annihilator := begin refine _ ≪≫ₗ W.quot_dual_equiv_annihilator, refine linear_equiv.quot_equiv_of_equiv _ (basis.of_vector_space K V).to_dual_equiv, exact (basis.of_vector_space K W).to_dual_equiv.trans W.dual_equiv_dual end open finite_dimensional @[simp] lemma finrank_dual_annihilator_comap_eq {Φ : subspace K (module.dual K V)} : finrank K Φ.dual_annihilator_comap = finrank K Φ.dual_annihilator := begin rw [submodule.dual_annihilator_comap, ← module.eval_equiv_to_linear_map], exact linear_equiv.finrank_eq (linear_equiv.of_submodule' _ _), end lemma finrank_add_finrank_dual_annihilator_comap_eq (W : subspace K (module.dual K V)) : finrank K W + finrank K W.dual_annihilator_comap = finrank K V := begin rw [finrank_dual_annihilator_comap_eq, W.quot_equiv_annihilator.finrank_eq.symm, add_comm, submodule.finrank_quotient_add_finrank, subspace.dual_finrank_eq], end end end subspace open module section dual_map variables {R : Type*} [comm_semiring R] {M₁ : Type*} {M₂ : Type*} variables [add_comm_monoid M₁] [module R M₁] [add_comm_monoid M₂] [module R M₂] /-- Given a linear map `f : M₁ →ₗ[R] M₂`, `f.dual_map` is the linear map between the dual of `M₂` and `M₁` such that it maps the functional `φ` to `φ ∘ f`. -/ def linear_map.dual_map (f : M₁ →ₗ[R] M₂) : dual R M₂ →ₗ[R] dual R M₁ := linear_map.lcomp R R f @[simp] lemma linear_map.dual_map_apply (f : M₁ →ₗ[R] M₂) (g : dual R M₂) (x : M₁) : f.dual_map g x = g (f x) := linear_map.lcomp_apply f g x @[simp] lemma linear_map.dual_map_id : (linear_map.id : M₁ →ₗ[R] M₁).dual_map = linear_map.id := by { ext, refl } lemma linear_map.dual_map_comp_dual_map {M₃ : Type*} [add_comm_group M₃] [module R M₃] (f : M₁ →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : f.dual_map.comp g.dual_map = (g.comp f).dual_map := rfl /-- The `linear_equiv` version of `linear_map.dual_map`. -/ def linear_equiv.dual_map (f : M₁ ≃ₗ[R] M₂) : dual R M₂ ≃ₗ[R] dual R M₁ := { inv_fun := f.symm.to_linear_map.dual_map, left_inv := begin intro φ, ext x, simp only [linear_map.dual_map_apply, linear_equiv.coe_to_linear_map, linear_map.to_fun_eq_coe, linear_equiv.apply_symm_apply] end, right_inv := begin intro φ, ext x, simp only [linear_map.dual_map_apply, linear_equiv.coe_to_linear_map, linear_map.to_fun_eq_coe, linear_equiv.symm_apply_apply] end, .. f.to_linear_map.dual_map } @[simp] lemma linear_equiv.dual_map_apply (f : M₁ ≃ₗ[R] M₂) (g : dual R M₂) (x : M₁) : f.dual_map g x = g (f x) := linear_map.lcomp_apply f g x @[simp] lemma linear_equiv.dual_map_refl : (linear_equiv.refl R M₁).dual_map = linear_equiv.refl R (dual R M₁) := by { ext, refl } @[simp] lemma linear_equiv.dual_map_symm {f : M₁ ≃ₗ[R] M₂} : (linear_equiv.dual_map f).symm = linear_equiv.dual_map f.symm := rfl lemma linear_equiv.dual_map_trans {M₃ : Type*} [add_comm_group M₃] [module R M₃] (f : M₁ ≃ₗ[R] M₂) (g : M₂ ≃ₗ[R] M₃) : g.dual_map.trans f.dual_map = (f.trans g).dual_map := rfl end dual_map namespace linear_map variables {R : Type*} [comm_semiring R] {M₁ : Type*} {M₂ : Type*} variables [add_comm_monoid M₁] [module R M₁] [add_comm_monoid M₂] [module R M₂] variable (f : M₁ →ₗ[R] M₂) lemma ker_dual_map_eq_dual_annihilator_range : f.dual_map.ker = f.range.dual_annihilator := begin ext φ, split; intro hφ, { rw mem_ker at hφ, rw submodule.mem_dual_annihilator, rintro y ⟨x, rfl⟩, rw [← dual_map_apply, hφ, zero_apply] }, { ext x, rw dual_map_apply, rw submodule.mem_dual_annihilator at hφ, exact hφ (f x) ⟨x, rfl⟩ } end lemma range_dual_map_le_dual_annihilator_ker : f.dual_map.range ≤ f.ker.dual_annihilator := begin rintro _ ⟨ψ, rfl⟩, simp_rw [submodule.mem_dual_annihilator, mem_ker], rintro x hx, rw [dual_map_apply, hx, map_zero] end section finite_dimensional variables {K : Type*} [field K] {V₁ : Type*} {V₂ : Type*} variables [add_comm_group V₁] [module K V₁] [add_comm_group V₂] [module K V₂] open finite_dimensional variable [finite_dimensional K V₂] @[simp] lemma finrank_range_dual_map_eq_finrank_range (f : V₁ →ₗ[K] V₂) : finrank K f.dual_map.range = finrank K f.range := begin have := submodule.finrank_quotient_add_finrank f.range, rw [(subspace.quot_equiv_annihilator f.range).finrank_eq, ← ker_dual_map_eq_dual_annihilator_range] at this, conv_rhs at this { rw ← subspace.dual_finrank_eq }, refine add_left_injective (finrank K f.dual_map.ker) _, change _ + _ = _ + _, rw [finrank_range_add_finrank_ker f.dual_map, add_comm, this], end lemma range_dual_map_eq_dual_annihilator_ker [finite_dimensional K V₁] (f : V₁ →ₗ[K] V₂) : f.dual_map.range = f.ker.dual_annihilator := begin refine eq_of_le_of_finrank_eq f.range_dual_map_le_dual_annihilator_ker _, have := submodule.finrank_quotient_add_finrank f.ker, rw (subspace.quot_equiv_annihilator f.ker).finrank_eq at this, refine add_left_injective (finrank K f.ker) _, simp_rw [this, finrank_range_dual_map_eq_finrank_range], exact finrank_range_add_finrank_ker f, end end finite_dimensional section field variables {K V : Type*} variables [field K] [add_comm_group V] [module K V] lemma dual_pairing_nondegenerate : (dual_pairing K V).nondegenerate := begin refine ⟨separating_left_iff_ker_eq_bot.mpr ker_id, _⟩, intros x, contrapose, rintros hx : x ≠ 0, rw [not_forall], let f : V →ₗ[K] K := classical.some (linear_pmap.mk_span_singleton x 1 hx).to_fun.exists_extend, use [f], refine ne_zero_of_eq_one _, have h : f.comp (K ∙ x).subtype = (linear_pmap.mk_span_singleton x 1 hx).to_fun := classical.some_spec (linear_pmap.mk_span_singleton x (1 : K) hx).to_fun.exists_extend, exact (fun_like.congr_fun h _).trans (linear_pmap.mk_span_singleton_apply _ hx _), end end field end linear_map namespace tensor_product variables (R : Type*) (M : Type*) (N : Type*) variables {ι κ : Type*} variables [decidable_eq ι] [decidable_eq κ] variables [fintype ι] [fintype κ] open_locale big_operators open_locale tensor_product local attribute [ext] tensor_product.ext open tensor_product open linear_map section variables [comm_semiring R] [add_comm_monoid M] [add_comm_monoid N] variables [module R M] [module R N] /-- The canonical linear map from `dual M ⊗ dual N` to `dual (M ⊗ N)`, sending `f ⊗ g` to the composition of `tensor_product.map f g` with the natural isomorphism `R ⊗ R ≃ R`. -/ def dual_distrib : (dual R M) ⊗[R] (dual R N) →ₗ[R] dual R (M ⊗[R] N) := (comp_right ↑(tensor_product.lid R R)) ∘ₗ hom_tensor_hom_map R M N R R variables {R M N} @[simp] lemma dual_distrib_apply (f : dual R M) (g : dual R N) (m : M) (n : N) : dual_distrib R M N (f ⊗ₜ g) (m ⊗ₜ n) = f m * g n := by simp only [dual_distrib, coe_comp, function.comp_app, hom_tensor_hom_map_apply, comp_right_apply, linear_equiv.coe_coe, map_tmul, lid_tmul, algebra.id.smul_eq_mul] end variables {R M N} variables [comm_ring R] [add_comm_group M] [add_comm_group N] variables [module R M] [module R N] /-- An inverse to `dual_tensor_dual_map` given bases. -/ noncomputable def dual_distrib_inv_of_basis (b : basis ι R M) (c : basis κ R N) : dual R (M ⊗[R] N) →ₗ[R] (dual R M) ⊗[R] (dual R N) := ∑ i j, (ring_lmap_equiv_self R ℕ _).symm (b.dual_basis i ⊗ₜ c.dual_basis j) ∘ₗ applyₗ (c j) ∘ₗ applyₗ (b i) ∘ₗ (lcurry R M N R) @[simp] lemma dual_distrib_inv_of_basis_apply (b : basis ι R M) (c : basis κ R N) (f : dual R (M ⊗[R] N)) : dual_distrib_inv_of_basis b c f = ∑ i j, (f (b i ⊗ₜ c j)) • (b.dual_basis i ⊗ₜ c.dual_basis j) := by simp [dual_distrib_inv_of_basis] /-- A linear equivalence between `dual M ⊗ dual N` and `dual (M ⊗ N)` given bases for `M` and `N`. It sends `f ⊗ g` to the composition of `tensor_product.map f g` with the natural isomorphism `R ⊗ R ≃ R`. -/ @[simps] noncomputable def dual_distrib_equiv_of_basis (b : basis ι R M) (c : basis κ R N) : (dual R M) ⊗[R] (dual R N) ≃ₗ[R] dual R (M ⊗[R] N) := begin refine linear_equiv.of_linear (dual_distrib R M N) (dual_distrib_inv_of_basis b c) _ _, { ext f m n, have h : ∀ (r s : R), r • s = s • r := is_commutative.comm, simp only [compr₂_apply, mk_apply, comp_apply, id_apply, dual_distrib_inv_of_basis_apply, linear_map.map_sum, map_smul, sum_apply, smul_apply, dual_distrib_apply, h (f _) _, ← f.map_smul, ←f.map_sum, ←smul_tmul_smul, ←tmul_sum, ←sum_tmul, basis.coe_dual_basis, basis.coord_apply, basis.sum_repr] }, { ext f g, simp only [compr₂_apply, mk_apply, comp_apply, id_apply, dual_distrib_inv_of_basis_apply, dual_distrib_apply, ←smul_tmul_smul, ←tmul_sum, ←sum_tmul, basis.coe_dual_basis, basis.sum_dual_apply_smul_coord] } end variables (R M N) variables [module.finite R M] [module.finite R N] [module.free R M] [module.free R N] variables [nontrivial R] open_locale classical /-- A linear equivalence between `dual M ⊗ dual N` and `dual (M ⊗ N)` when `M` and `N` are finite free modules. It sends `f ⊗ g` to the composition of `tensor_product.map f g` with the natural isomorphism `R ⊗ R ≃ R`. -/ @[simp] noncomputable def dual_distrib_equiv : (dual R M) ⊗[R] (dual R N) ≃ₗ[R] dual R (M ⊗[R] N) := dual_distrib_equiv_of_basis (module.free.choose_basis R M) (module.free.choose_basis R N) end tensor_product
5ac14a46515227c58e5d4a493ace43db0aa79c76
618003631150032a5676f229d13a079ac875ff77
/src/data/array/lemmas.lean
94662d68cde66a8c138e1a4aa440e0f0c66fe6d3
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
8,896
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro -/ import control.traversable.equiv import data.vector2 universes u v w namespace d_array variables {n : ℕ} {α : fin n → Type u} instance [∀ i, inhabited (α i)] : inhabited (d_array n α) := ⟨⟨λ _, default _⟩⟩ end d_array namespace array instance {n α} [inhabited α] : inhabited (array n α) := d_array.inhabited theorem to_list_of_heq {n₁ n₂ α} {a₁ : array n₁ α} {a₂ : array n₂ α} (hn : n₁ = n₂) (ha : a₁ == a₂) : a₁.to_list = a₂.to_list := by congr; assumption /- rev_list -/ section rev_list variables {n : ℕ} {α : Type u} {a : array n α} theorem rev_list_reverse_aux : ∀ i (h : i ≤ n) (t : list α), (a.iterate_aux (λ _, (::)) i h []).reverse_core t = a.rev_iterate_aux (λ _, (::)) i h t | 0 h t := rfl | (i+1) h t := rev_list_reverse_aux i _ _ @[simp] theorem rev_list_reverse : a.rev_list.reverse = a.to_list := rev_list_reverse_aux _ _ _ @[simp] theorem to_list_reverse : a.to_list.reverse = a.rev_list := by rw [←rev_list_reverse, list.reverse_reverse] end rev_list /- mem -/ section mem variables {n : ℕ} {α : Type u} {v : α} {a : array n α} theorem mem.def : v ∈ a ↔ ∃ i, a.read i = v := iff.rfl theorem mem_rev_list_aux : ∀ {i} (h : i ≤ n), (∃ (j : fin n), j.1 < i ∧ read a j = v) ↔ v ∈ a.iterate_aux (λ _, (::)) i h [] | 0 _ := ⟨λ ⟨i, n, _⟩, absurd n i.val.not_lt_zero, false.elim⟩ | (i+1) h := let IH := mem_rev_list_aux (le_of_lt h) in ⟨λ ⟨j, ji1, e⟩, or.elim (lt_or_eq_of_le $ nat.le_of_succ_le_succ ji1) (λ ji, list.mem_cons_of_mem _ $ IH.1 ⟨j, ji, e⟩) (λ je, by simp [d_array.iterate_aux]; apply or.inl; unfold read at e; have H : j = ⟨i, h⟩ := fin.eq_of_veq je; rwa [←H, e]), λ m, begin simp [d_array.iterate_aux, list.mem] at m, cases m with e m', exact ⟨⟨i, h⟩, nat.lt_succ_self _, eq.symm e⟩, exact let ⟨j, ji, e⟩ := IH.2 m' in ⟨j, nat.le_succ_of_le ji, e⟩ end⟩ @[simp] theorem mem_rev_list : v ∈ a.rev_list ↔ v ∈ a := iff.symm $ iff.trans (exists_congr $ λ j, iff.symm $ show j.1 < n ∧ read a j = v ↔ read a j = v, from and_iff_right j.2) (mem_rev_list_aux _) @[simp] theorem mem_to_list : v ∈ a.to_list ↔ v ∈ a := by rw ←rev_list_reverse; exact list.mem_reverse.trans mem_rev_list end mem /- foldr -/ section foldr variables {n : ℕ} {α : Type u} {β : Type w} {b : β} {f : α → β → β} {a : array n α} theorem rev_list_foldr_aux : ∀ {i} (h : i ≤ n), (d_array.iterate_aux a (λ _, (::)) i h []).foldr f b = d_array.iterate_aux a (λ _, f) i h b | 0 h := rfl | (j+1) h := congr_arg (f (read a ⟨j, h⟩)) (rev_list_foldr_aux _) theorem rev_list_foldr : a.rev_list.foldr f b = a.foldl b f := rev_list_foldr_aux _ end foldr /- foldl -/ section foldl variables {n : ℕ} {α : Type u} {β : Type w} {b : β} {f : β → α → β} {a : array n α} theorem to_list_foldl : a.to_list.foldl f b = a.foldl b (function.swap f) := by rw [←rev_list_reverse, list.foldl_reverse, rev_list_foldr] end foldl /- length -/ section length variables {n : ℕ} {α : Type u} theorem rev_list_length_aux (a : array n α) (i h) : (a.iterate_aux (λ _, (::)) i h []).length = i := by induction i; simp [*, d_array.iterate_aux] @[simp] theorem rev_list_length (a : array n α) : a.rev_list.length = n := rev_list_length_aux a _ _ @[simp] theorem to_list_length (a : array n α) : a.to_list.length = n := by rw[←rev_list_reverse, list.length_reverse, rev_list_length] end length /- nth -/ section nth variables {n : ℕ} {α : Type u} {a : array n α} theorem to_list_nth_le_aux (i : ℕ) (ih : i < n) : ∀ j {jh t h'}, (∀ k tl, j + k = i → list.nth_le t k tl = a.read ⟨i, ih⟩) → (a.rev_iterate_aux (λ _, (::)) j jh t).nth_le i h' = a.read ⟨i, ih⟩ | 0 _ _ _ al := al i _ $ zero_add _ | (j+1) jh t h' al := to_list_nth_le_aux j $ λ k tl hjk, show list.nth_le (a.read ⟨j, jh⟩ :: t) k tl = a.read ⟨i, ih⟩, from match k, hjk, tl with | 0, e, tl := match i, e, ih with ._, rfl, _ := rfl end | k'+1, _, tl := by simp[list.nth_le]; exact al _ _ (by simp [add_comm, add_assoc, *]; cc) end theorem to_list_nth_le (i : ℕ) (h h') : list.nth_le a.to_list i h' = a.read ⟨i, h⟩ := to_list_nth_le_aux _ _ _ (λ k tl, absurd tl k.not_lt_zero) @[simp] theorem to_list_nth_le' (a : array n α) (i : fin n) (h') : list.nth_le a.to_list i.1 h' = a.read i := by cases i; apply to_list_nth_le theorem to_list_nth {i v} : list.nth a.to_list i = some v ↔ ∃ h, a.read ⟨i, h⟩ = v := begin rw list.nth_eq_some, have ll := to_list_length a, split; intro h; cases h with h e; subst v, { exact ⟨ll ▸ h, (to_list_nth_le _ _ _).symm⟩ }, { exact ⟨ll.symm ▸ h, to_list_nth_le _ _ _⟩ } end theorem write_to_list {i v} : (a.write i v).to_list = a.to_list.update_nth i.1 v := list.ext_le (by simp) $ λ j h₁ h₂, begin have h₃ : j < n, {simpa using h₁}, rw [to_list_nth_le _ h₃], refine let ⟨_, e⟩ := list.nth_eq_some.1 _ in e.symm, by_cases ij : i.1 = j, { subst j, rw [show fin.mk i.val h₃ = i, from fin.eq_of_veq rfl, array.read_write, list.nth_update_nth_of_lt], simp [h₃] }, { rw [list.nth_update_nth_ne _ _ ij, a.read_write_of_ne, to_list_nth.2 ⟨h₃, rfl⟩], exact fin.ne_of_vne ij } end end nth /- enum -/ section enum variables {n : ℕ} {α : Type u} {a : array n α} theorem mem_to_list_enum {i v} : (i, v) ∈ a.to_list.enum ↔ ∃ h, a.read ⟨i, h⟩ = v := by simp [list.mem_iff_nth, to_list_nth, and.comm, and.assoc, and.left_comm] end enum /- to_array -/ section to_array variables {n : ℕ} {α : Type u} @[simp] theorem to_list_to_array (a : array n α) : a.to_list.to_array == a := heq_of_heq_of_eq (@@eq.drec_on (λ m (e : a.to_list.length = m), (d_array.mk (λ v, a.to_list.nth_le v.1 v.2)) == (@d_array.mk m (λ _, α) $ λ v, a.to_list.nth_le v.1 $ e.symm ▸ v.2)) a.to_list_length heq.rfl) $ d_array.ext $ λ ⟨i, h⟩, to_list_nth_le i h _ @[simp] theorem to_array_to_list (l : list α) : l.to_array.to_list = l := list.ext_le (to_list_length _) $ λ n h1 h2, to_list_nth_le _ h2 _ end to_array /- push_back -/ section push_back variables {n : ℕ} {α : Type u} {v : α} {a : array n α} lemma push_back_rev_list_aux : ∀ i h h', d_array.iterate_aux (a.push_back v) (λ _, (::)) i h [] = d_array.iterate_aux a (λ _, (::)) i h' [] | 0 h h' := rfl | (i+1) h h' := begin simp [d_array.iterate_aux], refine ⟨_, push_back_rev_list_aux _ _ _⟩, dsimp [read, d_array.read, push_back], rw [dif_neg], refl, exact ne_of_lt h', end @[simp] theorem push_back_rev_list : (a.push_back v).rev_list = v :: a.rev_list := begin unfold push_back rev_list foldl iterate d_array.iterate, dsimp [d_array.iterate_aux, read, d_array.read, push_back], rw [dif_pos (eq.refl n)], apply congr_arg, apply push_back_rev_list_aux end @[simp] theorem push_back_to_list : (a.push_back v).to_list = a.to_list ++ [v] := by rw [←rev_list_reverse, ←rev_list_reverse, push_back_rev_list, list.reverse_cons] end push_back /- foreach -/ section foreach variables {n : ℕ} {α : Type u} {β : Type v} {i : fin n} {f : fin n → α → β} {a : array n α} @[simp] theorem read_foreach : (foreach a f).read i = f i (a.read i) := rfl end foreach /- map -/ section map variables {n : ℕ} {α : Type u} {β : Type v} {i : fin n} {f : α → β} {a : array n α} theorem read_map : (a.map f).read i = f (a.read i) := read_foreach end map /- map₂ -/ section map₂ variables {n : ℕ} {α : Type u} {i : fin n} {f : α → α → α} {a₁ a₂ : array n α} @[simp] theorem read_map₂ : (map₂ f a₁ a₂).read i = f (a₁.read i) (a₂.read i) := read_foreach end map₂ end array namespace equiv def d_array_equiv_fin {n : ℕ} (α : fin n → Type*) : d_array n α ≃ (∀ i, α i) := ⟨d_array.read, d_array.mk, λ ⟨f⟩, rfl, λ f, rfl⟩ def array_equiv_fin (n : ℕ) (α : Type*) : array n α ≃ (fin n → α) := d_array_equiv_fin _ def vector_equiv_fin (α : Type*) (n : ℕ) : vector α n ≃ (fin n → α) := ⟨vector.nth, vector.of_fn, vector.of_fn_nth, λ f, funext $ vector.nth_of_fn f⟩ def vector_equiv_array (α : Type*) (n : ℕ) : vector α n ≃ array n α := (vector_equiv_fin _ _).trans (array_equiv_fin _ _).symm end equiv namespace array open function variable {n : ℕ} instance : traversable (array n) := @equiv.traversable (flip vector n) _ (λ α, equiv.vector_equiv_array α n) _ instance : is_lawful_traversable (array n) := @equiv.is_lawful_traversable (flip vector n) _ (λ α, equiv.vector_equiv_array α n) _ _ end array
86c01e555d8c5f11cc7505ba5e2ac2d15eb9dfa9
b3fced0f3ff82d577384fe81653e47df68bb2fa1
/src/data/dfinsupp.lean
771cc4f59b1914ca5875f1570c2d0e52bf848cf6
[ "Apache-2.0" ]
permissive
ratmice/mathlib
93b251ef5df08b6fd55074650ff47fdcc41a4c75
3a948a6a4cd5968d60e15ed914b1ad2f4423af8d
refs/heads/master
1,599,240,104,318
1,572,981,183,000
1,572,981,183,000
219,830,178
0
0
Apache-2.0
1,572,980,897,000
1,572,980,896,000
null
UTF-8
Lean
false
false
32,085
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Kenny Lau Dependent functions with finite support (see `data/finsupp.lean`). -/ import data.finset data.set.finite algebra.big_operators algebra.module algebra.pi_instances universes u u₁ u₂ v v₁ v₂ v₃ w x y l variables (ι : Type u) (β : ι → Type v) def decidable_zero_symm {γ : Type w} [has_zero γ] [decidable_pred (eq (0 : γ))] : decidable_pred (λ x, x = (0:γ)) := λ x, decidable_of_iff (0 = x) eq_comm local attribute [instance] decidable_zero_symm namespace dfinsupp variable [Π i, has_zero (β i)] structure pre : Type (max u v) := (to_fun : Π i, β i) (pre_support : multiset ι) (zero : ∀ i, i ∈ pre_support ∨ to_fun i = 0) instance : setoid (pre ι β) := { r := λ x y, ∀ i, x.to_fun i = y.to_fun i, iseqv := ⟨λ f i, rfl, λ f g H i, (H i).symm, λ f g h H1 H2 i, (H1 i).trans (H2 i)⟩ } end dfinsupp variable {ι} @[reducible] def dfinsupp [Π i, has_zero (β i)] : Type* := quotient (dfinsupp.setoid ι β) variable {β} notation `Π₀` binders `, ` r:(scoped f, dfinsupp f) := r infix ` →ₚ `:25 := dfinsupp namespace dfinsupp section basic variables [Π i, has_zero (β i)] variables {β₁ : ι → Type v₁} {β₂ : ι → Type v₂} variables [Π i, has_zero (β₁ i)] [Π i, has_zero (β₂ i)] instance : has_coe_to_fun (Π₀ i, β i) := ⟨λ _, Π i, β i, λ f, quotient.lift_on f pre.to_fun $ λ _ _, funext⟩ instance : has_zero (Π₀ i, β i) := ⟨⟦⟨λ i, 0, ∅, λ i, or.inr rfl⟩⟧⟩ instance : inhabited (Π₀ i, β i) := ⟨0⟩ @[simp] lemma zero_apply {i : ι} : (0 : Π₀ i, β i) i = 0 := rfl @[extensionality] lemma ext {f g : Π₀ i, β i} (H : ∀ i, f i = g i) : f = g := quotient.induction_on₂ f g (λ _ _ H, quotient.sound H) H /-- The composition of `f : β₁ → β₂` and `g : Π₀ i, β₁ i` is `map_range f hf g : Π₀ i, β₂ i`, well defined when `f 0 = 0`. -/ def map_range (f : Π i, β₁ i → β₂ i) (hf : ∀ i, f i 0 = 0) (g : Π₀ i, β₁ i) : Π₀ i, β₂ i := quotient.lift_on g (λ x, ⟦(⟨λ i, f i (x.1 i), x.2, λ i, or.cases_on (x.3 i) or.inl $ λ H, or.inr $ by rw [H, hf]⟩ : pre ι β₂)⟧) $ λ x y H, quotient.sound $ λ i, by simp only [H i] @[simp] lemma map_range_apply {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} {i : ι} : map_range f hf g i = f i (g i) := quotient.induction_on g $ λ x, rfl def zip_with (f : Π i, β₁ i → β₂ i → β i) (hf : ∀ i, f i 0 0 = 0) (g₁ : Π₀ i, β₁ i) (g₂ : Π₀ i, β₂ i) : (Π₀ i, β i) := begin refine quotient.lift_on₂ g₁ g₂ (λ x y, ⟦(⟨λ i, f i (x.1 i) (y.1 i), x.2 + y.2, λ i, _⟩ : pre ι β)⟧) _, { cases x.3 i with h1 h1, { left, rw multiset.mem_add, left, exact h1 }, cases y.3 i with h2 h2, { left, rw multiset.mem_add, right, exact h2 }, right, rw [h1, h2, hf] }, exact λ x₁ x₂ y₁ y₂ H1 H2, quotient.sound $ λ i, by simp only [H1 i, H2 i] end @[simp] lemma zip_with_apply {f : Π i, β₁ i → β₂ i → β i} {hf : ∀ i, f i 0 0 = 0} {g₁ : Π₀ i, β₁ i} {g₂ : Π₀ i, β₂ i} {i : ι} : zip_with f hf g₁ g₂ i = f i (g₁ i) (g₂ i) := quotient.induction_on₂ g₁ g₂ $ λ _ _, rfl end basic section algebra instance [Π i, add_monoid (β i)] : has_add (Π₀ i, β i) := ⟨zip_with (λ _, (+)) (λ _, add_zero 0)⟩ @[simp] lemma add_apply [Π i, add_monoid (β i)] {g₁ g₂ : Π₀ i, β i} {i : ι} : (g₁ + g₂) i = g₁ i + g₂ i := zip_with_apply instance [Π i, add_monoid (β i)] : add_monoid (Π₀ i, β i) := { add_monoid . zero := 0, add := (+), add_assoc := λ f g h, ext $ λ i, by simp only [add_apply, add_assoc], zero_add := λ f, ext $ λ i, by simp only [add_apply, zero_apply, zero_add], add_zero := λ f, ext $ λ i, by simp only [add_apply, zero_apply, add_zero] } instance [Π i, add_monoid (β i)] {i : ι} : is_add_monoid_hom (λ g : Π₀ i : ι, β i, g i) := { map_add := λ _ _, add_apply, map_zero := zero_apply } instance [Π i, add_group (β i)] : has_neg (Π₀ i, β i) := ⟨λ f, f.map_range (λ _, has_neg.neg) (λ _, neg_zero)⟩ instance [Π i, add_comm_monoid (β i)] : add_comm_monoid (Π₀ i, β i) := { add_comm := λ f g, ext $ λ i, by simp only [add_apply, add_comm], .. dfinsupp.add_monoid } @[simp] lemma neg_apply [Π i, add_group (β i)] {g : Π₀ i, β i} {i : ι} : (- g) i = - g i := map_range_apply instance [Π i, add_group (β i)] : add_group (Π₀ i, β i) := { add_left_neg := λ f, ext $ λ i, by simp only [add_apply, neg_apply, zero_apply, add_left_neg], .. dfinsupp.add_monoid, .. (infer_instance : has_neg (Π₀ i, β i)) } @[simp] lemma sub_apply [Π i, add_group (β i)] {g₁ g₂ : Π₀ i, β i} {i : ι} : (g₁ - g₂) i = g₁ i - g₂ i := by rw [sub_eq_add_neg]; simp instance [Π i, add_comm_group (β i)] : add_comm_group (Π₀ i, β i) := { add_comm := λ f g, ext $ λ i, by simp only [add_apply, add_comm], ..dfinsupp.add_group } def to_has_scalar {γ : Type w} [ring γ] [Π i, add_comm_group (β i)] [Π i, module γ (β i)] : has_scalar γ (Π₀ i, β i) := ⟨λc v, v.map_range (λ _, (•) c) (λ _, smul_zero _)⟩ local attribute [instance] to_has_scalar @[simp] lemma smul_apply {γ : Type w} [ring γ] [Π i, add_comm_group (β i)] [Π i, module γ (β i)] {i : ι} {b : γ} {v : Π₀ i, β i} : (b • v) i = b • (v i) := map_range_apply def to_module {γ : Type w} [ring γ] [Π i, add_comm_group (β i)] [Π i, module γ (β i)] : module γ (Π₀ i, β i) := module.of_core { smul_add := λ c x y, ext $ λ i, by simp only [add_apply, smul_apply, smul_add], add_smul := λ c x y, ext $ λ i, by simp only [add_apply, smul_apply, add_smul], one_smul := λ x, ext $ λ i, by simp only [smul_apply, one_smul], mul_smul := λ r s x, ext $ λ i, by simp only [smul_apply, smul_smul], .. (infer_instance : has_scalar γ (Π₀ i, β i)) } end algebra section filter_and_subtype_domain /-- `filter p f` is the function which is `f i` if `p i` is true and 0 otherwise. -/ def filter [Π i, has_zero (β i)] (p : ι → Prop) [decidable_pred p] (f : Π₀ i, β i) : Π₀ i, β i := quotient.lift_on f (λ x, ⟦(⟨λ i, if p i then x.1 i else 0, x.2, λ i, or.cases_on (x.3 i) or.inl $ λ H, or.inr $ by rw [H, if_t_t]⟩ : pre ι β)⟧) $ λ x y H, quotient.sound $ λ i, by simp only [H i] @[simp] lemma filter_apply [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] {i : ι} {f : Π₀ i, β i} : f.filter p i = if p i then f i else 0 := quotient.induction_on f $ λ x, rfl @[simp] lemma filter_apply_pos [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] {f : Π₀ i, β i} {i : ι} (h : p i) : f.filter p i = f i := by simp only [filter_apply, if_pos h] @[simp] lemma filter_apply_neg [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] {f : Π₀ i, β i} {i : ι} (h : ¬ p i) : f.filter p i = 0 := by simp only [filter_apply, if_neg h] lemma filter_pos_add_filter_neg [Π i, add_monoid (β i)] {f : Π₀ i, β i} {p : ι → Prop} [decidable_pred p] : f.filter p + f.filter (λi, ¬ p i) = f := ext $ λ i, by simp only [add_apply, filter_apply]; split_ifs; simp only [add_zero, zero_add] /-- `subtype_domain p f` is the restriction of the finitely supported function `f` to the subtype `p`. -/ def subtype_domain [Π i, has_zero (β i)] (p : ι → Prop) [decidable_pred p] (f : Π₀ i, β i) : Π₀ i : subtype p, β i.1 := begin fapply quotient.lift_on f, { intro x, refine ⟦⟨λ i, x.1 i.1, (x.2.filter p).attach.map $ λ j, ⟨j.1, (multiset.mem_filter.1 j.2).2⟩, _⟩⟧, refine λ i, or.cases_on (x.3 i.1) (λ H, _) or.inr, left, rw multiset.mem_map, refine ⟨⟨i.1, multiset.mem_filter.2 ⟨H, i.2⟩⟩, _, subtype.eta _ _⟩, apply multiset.mem_attach }, intros x y H, exact quotient.sound (λ i, H i.1) end @[simp] lemma subtype_domain_zero [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] : subtype_domain p (0 : Π₀ i, β i) = 0 := rfl @[simp] lemma subtype_domain_apply [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] {i : subtype p} {v : Π₀ i, β i} : (subtype_domain p v) i = v (i.val) := quotient.induction_on v $ λ x, rfl @[simp] lemma subtype_domain_add [Π i, add_monoid (β i)] {p : ι → Prop} [decidable_pred p] {v v' : Π₀ i, β i} : (v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p := ext $ λ i, by simp only [add_apply, subtype_domain_apply] instance subtype_domain.is_add_monoid_hom [Π i, add_monoid (β i)] {p : ι → Prop} [decidable_pred p] : is_add_monoid_hom (subtype_domain p : (Π₀ i : ι, β i) → Π₀ i : subtype p, β i) := { map_add := λ _ _, subtype_domain_add, map_zero := subtype_domain_zero } @[simp] lemma subtype_domain_neg [Π i, add_group (β i)] {p : ι → Prop} [decidable_pred p] {v : Π₀ i, β i} : (- v).subtype_domain p = - v.subtype_domain p := ext $ λ i, by simp only [neg_apply, subtype_domain_apply] @[simp] lemma subtype_domain_sub [Π i, add_group (β i)] {p : ι → Prop} [decidable_pred p] {v v' : Π₀ i, β i} : (v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p := ext $ λ i, by simp only [sub_apply, subtype_domain_apply] end filter_and_subtype_domain variable [decidable_eq ι] section basic variable [Π i, has_zero (β i)] lemma finite_supp (f : Π₀ i, β i) : set.finite {i | f i ≠ 0} := quotient.induction_on f $ λ x, set.finite_subset (finset.finite_to_set x.2.to_finset) $ λ i H, multiset.mem_to_finset.2 $ (x.3 i).resolve_right H def mk (s : finset ι) (x : Π i : (↑s : set ι), β i.1) : Π₀ i, β i := ⟦⟨λ i, if H : i ∈ s then x ⟨i, H⟩ else 0, s.1, λ i, if H : i ∈ s then or.inl H else or.inr $ dif_neg H⟩⟧ @[simp] lemma mk_apply {s : finset ι} {x : Π i : (↑s : set ι), β i.1} {i : ι} : (mk s x : Π i, β i) i = if H : i ∈ s then x ⟨i, H⟩ else 0 := rfl theorem mk_inj (s : finset ι) : function.injective (@mk ι β _ _ s) := begin intros x y H, ext i, have h1 : (mk s x : Π i, β i) i = (mk s y : Π i, β i) i, {rw H}, cases i with i hi, change i ∈ s at hi, dsimp only [mk_apply, subtype.coe_mk] at h1, simpa only [dif_pos hi] using h1 end def single (i : ι) (b : β i) : Π₀ i, β i := mk (finset.singleton i) $ λ j, eq.rec_on (finset.mem_singleton.1 j.2).symm b @[simp] lemma single_apply {i i' b} : (single i b : Π₀ i, β i) i' = (if h : i = i' then eq.rec_on h b else 0) := begin dsimp only [single], by_cases h : i = i', { have h1 : i' ∈ finset.singleton i, { simp only [h, finset.mem_singleton] }, simp only [mk_apply, dif_pos h, dif_pos h1] }, { have h1 : i' ∉ finset.singleton i, { simp only [ne.symm h, finset.mem_singleton, not_false_iff] }, simp only [mk_apply, dif_neg h, dif_neg h1] } end @[simp] lemma single_zero {i} : (single i 0 : Π₀ i, β i) = 0 := quotient.sound $ λ j, if H : j ∈ finset.singleton i then by dsimp only; rw [dif_pos H]; cases finset.mem_singleton.1 H; refl else dif_neg H @[simp] lemma single_eq_same {i b} : (single i b : Π₀ i, β i) i = b := by simp only [single_apply, dif_pos rfl] @[simp] lemma single_eq_of_ne {i i' b} (h : i ≠ i') : (single i b : Π₀ i, β i) i' = 0 := by simp only [single_apply, dif_neg h] def erase (i : ι) (f : Π₀ i, β i) : Π₀ i, β i := quotient.lift_on f (λ x, ⟦(⟨λ j, if j = i then 0 else x.1 j, x.2, λ j, or.cases_on (x.3 j) or.inl $ λ H, or.inr $ by simp only [H, if_t_t]⟩ : pre ι β)⟧) $ λ x y H, quotient.sound $ λ j, if h : j = i then by simp only [if_pos h] else by simp only [if_neg h, H j] @[simp] lemma erase_apply {i j : ι} {f : Π₀ i, β i} : (f.erase i) j = if j = i then 0 else f j := quotient.induction_on f $ λ x, rfl @[simp] lemma erase_same {i : ι} {f : Π₀ i, β i} : (f.erase i) i = 0 := by simp @[simp] lemma erase_ne {i i' : ι} {f : Π₀ i, β i} (h : i' ≠ i) : (f.erase i) i' = f i' := by simp [h] end basic section add_monoid variable [Π i, add_monoid (β i)] @[simp] lemma single_add {i : ι} {b₁ b₂ : β i} : single i (b₁ + b₂) = single i b₁ + single i b₂ := ext $ assume i', begin by_cases h : i = i', { subst h, simp only [add_apply, single_eq_same] }, { simp only [add_apply, single_eq_of_ne h, zero_add] } end lemma single_add_erase {i : ι} {f : Π₀ i, β i} : single i (f i) + f.erase i = f := ext $ λ i', if h : i = i' then by subst h; simp only [add_apply, single_apply, erase_apply, dif_pos rfl, if_pos, add_zero] else by simp only [add_apply, single_apply, erase_apply, dif_neg h, if_neg (ne.symm h), zero_add] lemma erase_add_single {i : ι} {f : Π₀ i, β i} : f.erase i + single i (f i) = f := ext $ λ i', if h : i = i' then by subst h; simp only [add_apply, single_apply, erase_apply, dif_pos rfl, if_pos, zero_add] else by simp only [add_apply, single_apply, erase_apply, dif_neg h, if_neg (ne.symm h), add_zero] protected theorem induction {p : (Π₀ i, β i) → Prop} (f : Π₀ i, β i) (h0 : p 0) (ha : ∀i b (f : Π₀ i, β i), f i = 0 → b ≠ 0 → p f → p (single i b + f)) : p f := begin refine quotient.induction_on f (λ x, _), cases x with f s H, revert f H, apply multiset.induction_on s, { intros f H, convert h0, ext i, exact (H i).resolve_left id }, intros i s ih f H, by_cases H1 : i ∈ s, { have H2 : ∀ j, j ∈ s ∨ f j = 0, { intro j, cases H j with H2 H2, { cases multiset.mem_cons.1 H2 with H3 H3, { left, rw H3, exact H1 }, { left, exact H3 } }, right, exact H2 }, have H3 : (⟦{to_fun := f, pre_support := i :: s, zero := H}⟧ : Π₀ i, β i) = ⟦{to_fun := f, pre_support := s, zero := H2}⟧, { exact quotient.sound (λ i, rfl) }, rw H3, apply ih }, have H2 : p (erase i ⟦{to_fun := f, pre_support := i :: s, zero := H}⟧), { dsimp only [erase, quotient.lift_on_beta], have H2 : ∀ j, j ∈ s ∨ ite (j = i) 0 (f j) = 0, { intro j, cases H j with H2 H2, { cases multiset.mem_cons.1 H2 with H3 H3, { right, exact if_pos H3 }, { left, exact H3 } }, right, split_ifs; [refl, exact H2] }, have H3 : (⟦{to_fun := λ (j : ι), ite (j = i) 0 (f j), pre_support := i :: s, zero := _}⟧ : Π₀ i, β i) = ⟦{to_fun := λ (j : ι), ite (j = i) 0 (f j), pre_support := s, zero := H2}⟧ := quotient.sound (λ i, rfl), rw H3, apply ih }, have H3 : single i _ + _ = (⟦{to_fun := f, pre_support := i :: s, zero := H}⟧ : Π₀ i, β i) := single_add_erase, rw ← H3, change p (single i (f i) + _), cases classical.em (f i = 0) with h h, { rw [h, single_zero, zero_add], exact H2 }, refine ha _ _ _ _ h H2, rw erase_same end lemma induction₂ {p : (Π₀ i, β i) → Prop} (f : Π₀ i, β i) (h0 : p 0) (ha : ∀i b (f : Π₀ i, β i), f i = 0 → b ≠ 0 → p f → p (f + single i b)) : p f := dfinsupp.induction f h0 $ λ i b f h1 h2 h3, have h4 : f + single i b = single i b + f, { ext j, by_cases H : i = j, { subst H, simp [h1] }, { simp [H] } }, eq.rec_on h4 $ ha i b f h1 h2 h3 end add_monoid @[simp] lemma mk_add [Π i, add_monoid (β i)] {s : finset ι} {x y : Π i : (↑s : set ι), β i.1} : mk s (x + y) = mk s x + mk s y := ext $ λ i, by simp only [add_apply, mk_apply]; split_ifs; [refl, rw zero_add] @[simp] lemma mk_zero [Π i, has_zero (β i)] {s : finset ι} : mk s (0 : Π i : (↑s : set ι), β i.1) = 0 := ext $ λ i, by simp only [mk_apply]; split_ifs; refl @[simp] lemma mk_neg [Π i, add_group (β i)] {s : finset ι} {x : Π i : (↑s : set ι), β i.1} : mk s (-x) = -mk s x := ext $ λ i, by simp only [neg_apply, mk_apply]; split_ifs; [refl, rw neg_zero] @[simp] lemma mk_sub [Π i, add_group (β i)] {s : finset ι} {x y : Π i : (↑s : set ι), β i.1} : mk s (x - y) = mk s x - mk s y := ext $ λ i, by simp only [sub_apply, mk_apply]; split_ifs; [refl, rw sub_zero] instance [Π i, add_group (β i)] {s : finset ι} : is_add_group_hom (@mk ι β _ _ s) := { map_add := λ _ _, mk_add } section local attribute [instance] to_module variables (γ : Type w) [ring γ] [Π i, add_comm_group (β i)] [Π i, module γ (β i)] include γ @[simp] lemma mk_smul {s : finset ι} {c : γ} (x : Π i : (↑s : set ι), β i.1) : mk s (c • x) = c • mk s x := ext $ λ i, by simp only [smul_apply, mk_apply]; split_ifs; [refl, rw smul_zero] @[simp] lemma single_smul {i : ι} {c : γ} {x : β i} : single i (c • x) = c • single i x := ext $ λ i, by simp only [smul_apply, single_apply]; split_ifs; [cases h, rw smul_zero]; refl variable β def lmk (s : finset ι) : (Π i : (↑s : set ι), β i.1) →ₗ[γ] Π₀ i, β i := ⟨mk s, λ _ _, mk_add, λ c x, by rw [mk_smul γ x]⟩ def lsingle (i) : β i →ₗ[γ] Π₀ i, β i := ⟨single i, λ _ _, single_add, λ _ _, single_smul _⟩ variable {β} @[simp] lemma lmk_apply {s : finset ι} {x} : lmk β γ s x = mk s x := rfl @[simp] lemma lsingle_apply {i : ι} {x : β i} : lsingle β γ i x = single i x := rfl end section support_basic variables [Π i, has_zero (β i)] [Π i, decidable_pred (eq (0 : β i))] def support (f : Π₀ i, β i) : finset ι := quotient.lift_on f (λ x, x.2.to_finset.filter $ λ i, x.1 i ≠ 0) $ begin intros x y Hxy, ext i, split, { intro H, rcases finset.mem_filter.1 H with ⟨h1, h2⟩, rw Hxy i at h2, exact finset.mem_filter.2 ⟨multiset.mem_to_finset.2 $ (y.3 i).resolve_right h2, h2⟩ }, { intro H, rcases finset.mem_filter.1 H with ⟨h1, h2⟩, rw ← Hxy i at h2, exact finset.mem_filter.2 ⟨multiset.mem_to_finset.2 $ (x.3 i).resolve_right h2, h2⟩ }, end @[simp] theorem support_mk_subset {s : finset ι} {x : Π i : (↑s : set ι), β i.1} : (mk s x).support ⊆ s := λ i H, multiset.mem_to_finset.1 (finset.mem_filter.1 H).1 @[simp] theorem mem_support_to_fun (f : Π₀ i, β i) (i) : i ∈ f.support ↔ f i ≠ 0 := begin refine quotient.induction_on f (λ x, _), dsimp only [support, quotient.lift_on_beta], rw [finset.mem_filter, multiset.mem_to_finset], exact and_iff_right_of_imp (x.3 i).resolve_right end theorem eq_mk_support (f : Π₀ i, β i) : f = mk f.support (λ i, f i.1) := by ext i; by_cases h : f i = 0; try {simp at h}; simp [h] @[simp] lemma support_zero : (0 : Π₀ i, β i).support = ∅ := rfl @[simp] lemma mem_support_iff (f : Π₀ i, β i) : ∀i:ι, i ∈ f.support ↔ f i ≠ 0 := f.mem_support_to_fun @[simp] lemma support_eq_empty {f : Π₀ i, β i} : f.support = ∅ ↔ f = 0 := ⟨λ H, ext $ by simpa [finset.ext] using H, by simp {contextual:=tt}⟩ instance decidable_zero : decidable_pred (eq (0 : Π₀ i, β i)) := λ f, decidable_of_iff _ $ support_eq_empty.trans eq_comm lemma support_subset_iff {s : set ι} {f : Π₀ i, β i} : ↑f.support ⊆ s ↔ (∀i∉s, f i = 0) := by simp [set.subset_def]; exact forall_congr (assume i, @not_imp_comm _ _ (classical.dec _) (classical.dec _)) lemma support_single_ne_zero {i : ι} {b : β i} (hb : b ≠ 0) : (single i b).support = {i} := begin ext j, by_cases h : i = j, { subst h, simp [hb] }, simp [ne.symm h, h] end lemma support_single_subset {i : ι} {b : β i} : (single i b).support ⊆ {i} := support_mk_subset section map_range_and_zip_with variables {β₁ : ι → Type v₁} {β₂ : ι → Type v₂} variables [Π i, has_zero (β₁ i)] [Π i, has_zero (β₂ i)] variables [Π i, decidable_pred (eq (0 : β₁ i))] [Π i, decidable_pred (eq (0 : β₂ i))] lemma map_range_def {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} : map_range f hf g = mk g.support (λ i, f i.1 (g i.1)) := begin ext i, by_cases h : g i = 0, { simp [h, hf] }, { simp at h, simp [h, hf] } end lemma support_map_range {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} : (map_range f hf g).support ⊆ g.support := by simp [map_range_def] @[simp] lemma map_range_single {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {i : ι} {b : β₁ i} : map_range f hf (single i b) = single i (f i b) := dfinsupp.ext $ λ i', by by_cases i = i'; [{subst i', simp}, simp [h, hf]] lemma zip_with_def {f : Π i, β₁ i → β₂ i → β i} {hf : ∀ i, f i 0 0 = 0} {g₁ : Π₀ i, β₁ i} {g₂ : Π₀ i, β₂ i} : zip_with f hf g₁ g₂ = mk (g₁.support ∪ g₂.support) (λ i, f i.1 (g₁ i.1) (g₂ i.1)) := begin ext i, by_cases h1 : g₁ i = 0; by_cases h2 : g₂ i = 0; try {simp at h1 h2}; simp [h1, h2, hf] end lemma support_zip_with {f : Π i, β₁ i → β₂ i → β i} {hf : ∀ i, f i 0 0 = 0} {g₁ : Π₀ i, β₁ i} {g₂ : Π₀ i, β₂ i} : (zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support := by simp [zip_with_def] end map_range_and_zip_with lemma erase_def (i : ι) (f : Π₀ i, β i) : f.erase i = mk (f.support.erase i) (λ j, f j.1) := begin ext j, by_cases h1 : j = i; by_cases h2 : f j = 0; try {simp at h2}; simp [h1, h2] end @[simp] lemma support_erase (i : ι) (f : Π₀ i, β i) : (f.erase i).support = f.support.erase i := begin ext j, by_cases h1 : j = i; by_cases h2 : f j = 0; try {simp at h2}; simp [h1, h2] end section filter_and_subtype_domain variables {p : ι → Prop} [decidable_pred p] lemma filter_def (f : Π₀ i, β i) : f.filter p = mk (f.support.filter p) (λ i, f i.1) := by ext i; by_cases h1 : p i; by_cases h2 : f i = 0; try {simp at h2}; simp [h1, h2] @[simp] lemma support_filter (f : Π₀ i, β i) : (f.filter p).support = f.support.filter p := by ext i; by_cases h : p i; simp [h] lemma subtype_domain_def (f : Π₀ i, β i) : f.subtype_domain p = mk (f.support.subtype p) (λ i, f i.1) := by ext i; cases i with i hi; by_cases h1 : p i; by_cases h2 : f i = 0; try {simp at h2}; dsimp; simp [h1, h2] @[simp] lemma support_subtype_domain {f : Π₀ i, β i} : (subtype_domain p f).support = f.support.subtype p := by ext i; cases i with i hi; by_cases h1 : p i; by_cases h2 : f i = 0; try {simp at h2}; dsimp; simp [h1, h2] end filter_and_subtype_domain end support_basic lemma support_add [Π i, add_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] {g₁ g₂ : Π₀ i, β i} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support := support_zip_with @[simp] lemma support_neg [Π i, add_group (β i)] [Π i, decidable_pred (eq (0 : β i))] {f : Π₀ i, β i} : support (-f) = support f := by ext i; simp local attribute [instance] dfinsupp.to_module lemma support_smul {γ : Type w} [ring γ] [Π i, add_comm_group (β i)] [Π i, module γ (β i)] [Π (i : ι), decidable_pred (eq (0 : β i))] {b : γ} {v : Π₀ i, β i} : (b • v).support ⊆ v.support := λ x, by simp [dfinsupp.mem_support_iff, not_imp_not] {contextual := tt} instance [decidable_eq ι] [Π i, has_zero (β i)] [Π i, decidable_eq (β i)] : decidable_eq (Π₀ i, β i) := assume f g, decidable_of_iff (f.support = g.support ∧ (∀i∈f.support, f i = g i)) ⟨assume ⟨h₁, h₂⟩, ext $ assume i, if h : i ∈ f.support then h₂ i h else have hf : f i = 0, by rwa [f.mem_support_iff, not_not] at h, have hg : g i = 0, by rwa [h₁, g.mem_support_iff, not_not] at h, by rw [hf, hg], by intro h; subst h; simp⟩ section prod_and_sum variables {γ : Type w} -- [to_additive sum] for dfinsupp.prod doesn't work, the equation lemmas are not generated /-- `sum f g` is the sum of `g i (f i)` over the support of `f`. -/ def sum [Π i, has_zero (β i)] [Π i, decidable_pred (eq (0 : β i))] [add_comm_monoid γ] (f : Π₀ i, β i) (g : Π i, β i → γ) : γ := f.support.sum (λi, g i (f i)) /-- `prod f g` is the product of `g i (f i)` over the support of `f`. -/ @[to_additive] def prod [Π i, has_zero (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] (f : Π₀ i, β i) (g : Π i, β i → γ) : γ := f.support.prod (λi, g i (f i)) @[to_additive] lemma prod_map_range_index {β₁ : ι → Type v₁} {β₂ : ι → Type v₂} [Π i, has_zero (β₁ i)] [Π i, has_zero (β₂ i)] [Π i, decidable_pred (eq (0 : β₁ i))] [Π i, decidable_pred (eq (0 : β₂ i))] [comm_monoid γ] {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} {h : Π i, β₂ i → γ} (h0 : ∀i, h i 0 = 1) : (map_range f hf g).prod h = g.prod (λi b, h i (f i b)) := begin rw [map_range_def], refine (finset.prod_subset support_mk_subset _).trans _, { intros i h1 h2, dsimp, simp [h1] at h2, dsimp at h2, simp [h1, h2, h0] }, { refine finset.prod_congr rfl _, intros i h1, simp [h1] } end @[to_additive] lemma prod_zero_index [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] {h : Π i, β i → γ} : (0 : Π₀ i, β i).prod h = 1 := rfl @[to_additive] lemma prod_single_index [Π i, has_zero (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] {i : ι} {b : β i} {h : Π i, β i → γ} (h_zero : h i 0 = 1) : (single i b).prod h = h i b := begin by_cases h : b = 0, { simp [h, prod_zero_index, h_zero], refl }, { simp [dfinsupp.prod, support_single_ne_zero h] } end @[to_additive] lemma prod_neg_index [Π i, add_group (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] {g : Π₀ i, β i} {h : Π i, β i → γ} (h0 : ∀i, h i 0 = 1) : (-g).prod h = g.prod (λi b, h i (- b)) := prod_map_range_index h0 @[simp] lemma sum_apply {ι₁ : Type u₁} [decidable_eq ι₁] {β₁ : ι₁ → Type v₁} [Π i₁, has_zero (β₁ i₁)] [Π i, decidable_pred (eq (0 : β₁ i))] [Π i, add_comm_monoid (β i)] {f : Π₀ i₁, β₁ i₁} {g : Π i₁, β₁ i₁ → Π₀ i, β i} {i₂ : ι} : (f.sum g) i₂ = f.sum (λi₁ b, g i₁ b i₂) := (finset.sum_hom (λf : Π₀ i, β i, f i₂)).symm lemma support_sum {ι₁ : Type u₁} [decidable_eq ι₁] {β₁ : ι₁ → Type v₁} [Π i₁, has_zero (β₁ i₁)] [Π i, decidable_pred (eq (0 : β₁ i))] [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] {f : Π₀ i₁, β₁ i₁} {g : Π i₁, β₁ i₁ → Π₀ i, β i} : (f.sum g).support ⊆ f.support.bind (λi, (g i (f i)).support) := have ∀i₁ : ι, f.sum (λ (i : ι₁) (b : β₁ i), (g i b) i₁) ≠ 0 → (∃ (i : ι₁), f i ≠ 0 ∧ ¬ (g i (f i)) i₁ = 0), from assume i₁ h, let ⟨i, hi, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in ⟨i, (f.mem_support_iff i).mp hi, ne⟩, by simpa [finset.subset_iff, mem_support_iff, finset.mem_bind, sum_apply] using this @[simp] lemma sum_zero [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] [add_comm_monoid γ] {f : Π₀ i, β i} : f.sum (λi b, (0 : γ)) = 0 := finset.sum_const_zero @[simp] lemma sum_add [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] [add_comm_monoid γ] {f : Π₀ i, β i} {h₁ h₂ : Π i, β i → γ} : f.sum (λi b, h₁ i b + h₂ i b) = f.sum h₁ + f.sum h₂ := finset.sum_add_distrib @[simp] lemma sum_neg [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] [add_comm_group γ] {f : Π₀ i, β i} {h : Π i, β i → γ} : f.sum (λi b, - h i b) = - f.sum h := finset.sum_hom (@has_neg.neg γ _) @[to_additive] lemma prod_add_index [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] {f g : Π₀ i, β i} {h : Π i, β i → γ} (h_zero : ∀i, h i 0 = 1) (h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂) : (f + g).prod h = f.prod h * g.prod h := have f_eq : (f.support ∪ g.support).prod (λi, h i (f i)) = f.prod h, from (finset.prod_subset (finset.subset_union_left _ _) $ by simp [mem_support_iff, h_zero] {contextual := tt}).symm, have g_eq : (f.support ∪ g.support).prod (λi, h i (g i)) = g.prod h, from (finset.prod_subset (finset.subset_union_right _ _) $ by simp [mem_support_iff, h_zero] {contextual := tt}).symm, calc (f + g).support.prod (λi, h i ((f + g) i)) = (f.support ∪ g.support).prod (λi, h i ((f + g) i)) : finset.prod_subset support_add $ by simp [mem_support_iff, h_zero] {contextual := tt} ... = (f.support ∪ g.support).prod (λi, h i (f i)) * (f.support ∪ g.support).prod (λi, h i (g i)) : by simp [h_add, finset.prod_mul_distrib] ... = _ : by rw [f_eq, g_eq] lemma sum_sub_index [Π i, add_comm_group (β i)] [Π i, decidable_pred (eq (0 : β i))] [add_comm_group γ] {f g : Π₀ i, β i} {h : Π i, β i → γ} (h_sub : ∀i b₁ b₂, h i (b₁ - b₂) = h i b₁ - h i b₂) : (f - g).sum h = f.sum h - g.sum h := have h_zero : ∀i, h i 0 = 0, from assume i, have h i (0 - 0) = h i 0 - h i 0, from h_sub i 0 0, by simpa using this, have h_neg : ∀i b, h i (- b) = - h i b, from assume i b, have h i (0 - b) = h i 0 - h i b, from h_sub i 0 b, by simpa [h_zero] using this, have h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ + h i b₂, from assume i b₁ b₂, have h i (b₁ - (- b₂)) = h i b₁ - h i (- b₂), from h_sub i b₁ (-b₂), by simpa [h_neg] using this, by simp [@sum_add_index ι β _ γ _ _ _ f (-g) h h_zero h_add]; simp [@sum_neg_index ι β _ γ _ _ _ g h h_zero, h_neg]; simp [@sum_neg ι β _ γ _ _ _ g h] @[to_additive] lemma prod_finset_sum_index {γ : Type w} {α : Type x} [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] [decidable_eq α] {s : finset α} {g : α → Π₀ i, β i} {h : Π i, β i → γ} (h_zero : ∀i, h i 0 = 1) (h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂) : s.prod (λi, (g i).prod h) = (s.sum g).prod h := finset.induction_on s (by simp [prod_zero_index]) (by simp [prod_add_index, h_zero, h_add] {contextual := tt}) @[to_additive] lemma prod_sum_index {ι₁ : Type u₁} [decidable_eq ι₁] {β₁ : ι₁ → Type v₁} [Π i₁, has_zero (β₁ i₁)] [Π i, decidable_pred (eq (0 : β₁ i))] [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] {f : Π₀ i₁, β₁ i₁} {g : Π i₁, β₁ i₁ → Π₀ i, β i} {h : Π i, β i → γ} (h_zero : ∀i, h i 0 = 1) (h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂) : (f.sum g).prod h = f.prod (λi b, (g i b).prod h) := (prod_finset_sum_index h_zero h_add).symm @[simp] lemma sum_single [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] {f : Π₀ i, β i} : f.sum single = f := begin apply dfinsupp.induction f, {rw [sum_zero_index]}, intros i b f H hb ih, rw [sum_add_index, ih, sum_single_index], all_goals { intros, simp } end @[to_additive] lemma prod_subtype_domain_index [Π i, has_zero (β i)] [Π i, decidable_pred (eq (0 : β i))] [comm_monoid γ] {v : Π₀ i, β i} {p : ι → Prop} [decidable_pred p] {h : Π i, β i → γ} (hp : ∀x∈v.support, p x) : (v.subtype_domain p).prod (λi b, h i.1 b) = v.prod h := finset.prod_bij (λp _, p.val) (by simp) (by simp) (assume ⟨a₀, ha₀⟩ ⟨a₁, ha₁⟩, by simp) (λ i hi, ⟨⟨i, hp i hi⟩, by simpa using hi, rfl⟩) lemma subtype_domain_sum [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] {s : finset γ} {h : γ → Π₀ i, β i} {p : ι → Prop} [decidable_pred p] : (s.sum h).subtype_domain p = s.sum (λc, (h c).subtype_domain p) := eq.symm (finset.sum_hom _) lemma subtype_domain_finsupp_sum {δ : γ → Type x} [decidable_eq γ] [Π c, has_zero (δ c)] [Π c, decidable_pred (eq (0 : δ c))] [Π i, add_comm_monoid (β i)] [Π i, decidable_pred (eq (0 : β i))] {p : ι → Prop} [decidable_pred p] {s : Π₀ c, δ c} {h : Π c, δ c → Π₀ i, β i} : (s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) := subtype_domain_sum end prod_and_sum end dfinsupp
ae46d21f29a8129b8128ccc01d2247cc43a3924d
aac33c518959cd0633fdc254edbbf27b2f581c31
/src/category_theory/adjunction.lean
742a0e2a8a030a97f0bcc4f78ba47c5d09218bbe
[ "Apache-2.0" ]
permissive
digama0/mathlib-ITP2019
992c4f9ac02260fca4a14860813c3ecbd5ca1ae6
5cbd0362e04e671ef5db1284870592af6950197c
refs/heads/master
1,588,517,123,478
1,554,081,078,000
1,554,081,078,000
178,686,466
2
1
null
null
null
null
UTF-8
Lean
false
false
14,339
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Johan Commelin -/ import category_theory.limits.preserves import category_theory.whiskering import category_theory.equivalence namespace category_theory open category open category_theory.limits universes v₁ v₂ v₃ u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation local attribute [elab_simple] whisker_left whisker_right variables {C : Type u₁} [𝒞 : category.{v₁} C] {D : Type u₂} [𝒟 : category.{v₂} D] include 𝒞 𝒟 /-- `adjunction F G` represents the data of an adjunction between two functors `F : C ⥤ D` and `G : D ⥤ C`. `F` is the left adjoint and `G` is the right adjoint. -/ structure adjunction (F : C ⥤ D) (G : D ⥤ C) := (hom_equiv : Π (X Y), (F.obj X ⟶ Y) ≃ (X ⟶ G.obj Y)) (unit : functor.id C ⟶ F.comp G) (counit : G.comp F ⟶ functor.id D) (hom_equiv_unit' : Π {X Y f}, (hom_equiv X Y) f = (unit : _ ⟹ _).app X ≫ G.map f . obviously) (hom_equiv_counit' : Π {X Y g}, (hom_equiv X Y).symm g = F.map g ≫ counit.app Y . obviously) namespace adjunction restate_axiom hom_equiv_unit' restate_axiom hom_equiv_counit' attribute [simp, priority 1] hom_equiv_unit hom_equiv_counit section variables {F : C ⥤ D} {G : D ⥤ C} (adj : adjunction F G) {X' X : C} {Y Y' : D} @[simp, priority 1] lemma hom_equiv_naturality_left_symm (f : X' ⟶ X) (g : X ⟶ G.obj Y) : (adj.hom_equiv X' Y).symm (f ≫ g) = F.map f ≫ (adj.hom_equiv X Y).symm g := by rw [hom_equiv_counit, F.map_comp, assoc, adj.hom_equiv_counit.symm] @[simp] lemma hom_equiv_naturality_left (f : X' ⟶ X) (g : F.obj X ⟶ Y) : (adj.hom_equiv X' Y) (F.map f ≫ g) = f ≫ (adj.hom_equiv X Y) g := by rw [← equiv.eq_symm_apply]; simp [-hom_equiv_unit] @[simp, priority 1] lemma hom_equiv_naturality_right (f : F.obj X ⟶ Y) (g : Y ⟶ Y') : (adj.hom_equiv X Y') (f ≫ g) = (adj.hom_equiv X Y) f ≫ G.map g := by rw [hom_equiv_unit, G.map_comp, ← assoc, ←hom_equiv_unit] @[simp] lemma hom_equiv_naturality_right_symm (f : X ⟶ G.obj Y) (g : Y ⟶ Y') : (adj.hom_equiv X Y').symm (f ≫ G.map g) = (adj.hom_equiv X Y).symm f ≫ g := by rw [equiv.symm_apply_eq]; simp [-hom_equiv_counit] @[simp] lemma left_triangle : (whisker_right adj.unit F).vcomp (whisker_left F adj.counit) = nat_trans.id _ := begin ext1 X, dsimp, erw [← adj.hom_equiv_counit, equiv.symm_apply_eq, adj.hom_equiv_unit], simp end @[simp] lemma right_triangle : (whisker_left G adj.unit).vcomp (whisker_right adj.counit G) = nat_trans.id _ := begin ext1 Y, dsimp, erw [← adj.hom_equiv_unit, ← equiv.eq_symm_apply, adj.hom_equiv_counit], simp end @[simp] lemma left_triangle_components : F.map (adj.unit.app X) ≫ adj.counit.app (F.obj X) = 𝟙 _ := congr_arg (λ (t : _ ⟹ functor.id C ⋙ F), t.app X) adj.left_triangle @[simp] lemma right_triangle_components {Y : D} : adj.unit.app (G.obj Y) ≫ G.map (adj.counit.app Y) = 𝟙 _ := congr_arg (λ (t : _ ⟹ G ⋙ functor.id C), t.app Y) adj.right_triangle end structure core_hom_equiv (F : C ⥤ D) (G : D ⥤ C) := (hom_equiv : Π (X Y), (F.obj X ⟶ Y) ≃ (X ⟶ G.obj Y)) (hom_equiv_naturality_left_symm' : Π {X' X Y} (f : X' ⟶ X) (g : X ⟶ G.obj Y), (hom_equiv X' Y).symm (f ≫ g) = F.map f ≫ (hom_equiv X Y).symm g . obviously) (hom_equiv_naturality_right' : Π {X Y Y'} (f : F.obj X ⟶ Y) (g : Y ⟶ Y'), (hom_equiv X Y') (f ≫ g) = (hom_equiv X Y) f ≫ G.map g . obviously) namespace core_hom_equiv restate_axiom hom_equiv_naturality_left_symm' restate_axiom hom_equiv_naturality_right' attribute [simp, priority 1] hom_equiv_naturality_left_symm hom_equiv_naturality_right variables {F : C ⥤ D} {G : D ⥤ C} (adj : core_hom_equiv F G) {X' X : C} {Y Y' : D} @[simp] lemma hom_equiv_naturality_left (f : X' ⟶ X) (g : F.obj X ⟶ Y) : (adj.hom_equiv X' Y) (F.map f ≫ g) = f ≫ (adj.hom_equiv X Y) g := by rw [← equiv.eq_symm_apply]; simp @[simp] lemma hom_equiv_naturality_right_symm (f : X ⟶ G.obj Y) (g : Y ⟶ Y') : (adj.hom_equiv X Y').symm (f ≫ G.map g) = (adj.hom_equiv X Y).symm f ≫ g := by rw [equiv.symm_apply_eq]; simp end core_hom_equiv structure core_unit_counit (F : C ⥤ D) (G : D ⥤ C) := (unit : functor.id C ⟶ F.comp G) (counit : G.comp F ⟶ functor.id D) (left_triangle' : (whisker_right unit F).vcomp (whisker_left F counit) = nat_trans.id _ . obviously) (right_triangle' : (whisker_left G unit).vcomp (whisker_right counit G) = nat_trans.id _ . obviously) namespace core_unit_counit restate_axiom left_triangle' restate_axiom right_triangle' attribute [simp] left_triangle right_triangle end core_unit_counit variables (F : C ⥤ D) (G : D ⥤ C) def mk_of_hom_equiv (adj : core_hom_equiv F G) : adjunction F G := { unit := { app := λ X, (adj.hom_equiv X (F.obj X)) (𝟙 (F.obj X)), naturality' := begin intros, erw [← adj.hom_equiv_naturality_left, ← adj.hom_equiv_naturality_right], dsimp, simp end }, counit := { app := λ Y, (adj.hom_equiv _ _).inv_fun (𝟙 (G.obj Y)), naturality' := begin intros, erw [← adj.hom_equiv_naturality_left_symm, ← adj.hom_equiv_naturality_right_symm], dsimp, simp end }, hom_equiv_unit' := λ X Y f, by erw [← adj.hom_equiv_naturality_right]; simp, hom_equiv_counit' := λ X Y f, by erw [← adj.hom_equiv_naturality_left_symm]; simp, .. adj } def mk_of_unit_counit (adj : core_unit_counit F G) : adjunction F G := { hom_equiv := λ X Y, { to_fun := λ f, adj.unit.app X ≫ G.map f, inv_fun := λ g, F.map g ≫ adj.counit.app Y, left_inv := λ f, begin change F.map (_ ≫ _) ≫ _ = _, rw [F.map_comp, assoc, ←functor.comp_map, adj.counit.naturality, ←assoc], convert id_comp _ f, exact congr_arg (λ t : _ ⟹ _, t.app _) adj.left_triangle end, right_inv := λ g, begin change _ ≫ G.map (_ ≫ _) = _, rw [G.map_comp, ←assoc, ←functor.comp_map, ←adj.unit.naturality, assoc], convert comp_id _ g, exact congr_arg (λ t : _ ⟹ _, t.app _) adj.right_triangle end }, .. adj } section omit 𝒟 def id : adjunction (functor.id C) (functor.id C) := { hom_equiv := λ X Y, equiv.refl _, unit := 𝟙 _, counit := 𝟙 _ } end /- TODO * define adjoint equivalences * show that every equivalence can be improved into an adjoint equivalence -/ section variables {E : Type u₃} [ℰ : category.{v₃} E] (H : D ⥤ E) (I : E ⥤ D) def comp (adj₁ : adjunction F G) (adj₂ : adjunction H I) : adjunction (F ⋙ H) (I ⋙ G) := { hom_equiv := λ X Z, equiv.trans (adj₂.hom_equiv _ _) (adj₁.hom_equiv _ _), unit := adj₁.unit ≫ (whisker_left F $ whisker_right adj₂.unit G) ≫ (functor.associator _ _ _).inv, counit := (functor.associator _ _ _).hom ≫ (whisker_left I $ whisker_right adj₁.counit H) ≫ adj₂.counit } end structure is_left_adjoint (left : C ⥤ D) := (right : D ⥤ C) (adj : adjunction left right) structure is_right_adjoint (right : D ⥤ C) := (left : C ⥤ D) (adj : adjunction left right) section construct_left -- Construction of a left adjoint. In order to construct a left -- adjoint to a functor G : D → C, it suffices to give the object part -- of a functor F : C → D together with isomorphisms Hom(FX, Y) ≃ -- Hom(X, GY) natural in Y. The action of F on morphisms can be -- constructed from this data. variables {F_obj : C → D} {G} variables (e : Π X Y, (F_obj X ⟶ Y) ≃ (X ⟶ G.obj Y)) variables (he : Π X Y Y' g h, e X Y' (h ≫ g) = e X Y h ≫ G.map g) include he private lemma he' {X Y Y'} (f g) : (e X Y').symm (f ≫ G.map g) = (e X Y).symm f ≫ g := by intros; rw [equiv.symm_apply_eq, he]; simp def left_adjoint_of_equiv : C ⥤ D := { obj := F_obj, map := λ X X' f, (e X (F_obj X')).symm (f ≫ e X' (F_obj X') (𝟙 _)), map_comp' := λ X X' X'' f f', begin rw [equiv.symm_apply_eq, he, equiv.apply_symm_apply], conv { to_rhs, rw [assoc, ←he, id_comp, equiv.apply_symm_apply] }, simp end } def adjunction_of_equiv_left : adjunction (left_adjoint_of_equiv e he) G := mk_of_hom_equiv (left_adjoint_of_equiv e he) G { hom_equiv := e, hom_equiv_naturality_left_symm' := begin intros, erw [← he' e he, ← equiv.apply_eq_iff_eq], simp [(he _ _ _ _ _).symm] end } end construct_left section construct_right -- Construction of a right adjoint, analogous to the above. variables {F} {G_obj : D → C} variables (e : Π X Y, (F.obj X ⟶ Y) ≃ (X ⟶ G_obj Y)) variables (he : Π X' X Y f g, e X' Y (F.map f ≫ g) = f ≫ e X Y g) include he private lemma he' {X' X Y} (f g) : F.map f ≫ (e X Y).symm g = (e X' Y).symm (f ≫ g) := by intros; rw [equiv.eq_symm_apply, he]; simp def right_adjoint_of_equiv : D ⥤ C := { obj := G_obj, map := λ Y Y' g, (e (G_obj Y) Y') ((e (G_obj Y) Y).symm (𝟙 _) ≫ g), map_comp' := λ Y Y' Y'' g g', begin rw [← equiv.eq_symm_apply, ← he' e he, equiv.symm_apply_apply], conv { to_rhs, rw [← assoc, he' e he, comp_id, equiv.symm_apply_apply] }, simp end } def adjunction_of_equiv_right : adjunction F (right_adjoint_of_equiv e he) := mk_of_hom_equiv F (right_adjoint_of_equiv e he) { hom_equiv := e, hom_equiv_naturality_left_symm' := by intros; rw [equiv.symm_apply_eq, he]; simp, hom_equiv_naturality_right' := begin intros X Y Y' g h, erw [←he, equiv.apply_eq_iff_eq, ←assoc, he' e he, comp_id, equiv.symm_apply_apply] end } end construct_right end adjunction end category_theory namespace category_theory.adjunction open category_theory open category_theory.functor open category_theory.limits universes u₁ u₂ v variables {C : Type u₁} [𝒞 : category.{v} C] {D : Type u₂} [𝒟 : category.{v} D] include 𝒞 𝒟 variables {F : C ⥤ D} {G : D ⥤ C} (adj : adjunction F G) include adj section preservation_colimits variables {J : Type v} [small_category J] (K : J ⥤ C) def functoriality_is_left_adjoint : is_left_adjoint (@cocones.functoriality _ _ _ _ K _ _ F) := { right := (cocones.functoriality G) ⋙ (cocones.precompose (K.right_unitor.inv ≫ (whisker_left K adj.unit) ≫ (associator _ _ _).inv)), adj := mk_of_unit_counit _ _ { unit := { app := λ c, { hom := adj.unit.app c.X, w' := λ j, by have := adj.unit.naturality (c.ι.app j); tidy }, naturality' := λ _ _ f, by have := adj.unit.naturality (f.hom); tidy }, counit := { app := λ c, { hom := adj.counit.app c.X, w' := begin intro j, dsimp, erw [category.comp_id, category.id_comp, F.map_comp, category.assoc, adj.counit.naturality (c.ι.app j), ← category.assoc, adj.left_triangle_components, category.id_comp], refl, end }, naturality' := λ _ _ f, by have := adj.counit.naturality (f.hom); tidy } } } /-- A left adjoint preserves colimits. -/ def left_adjoint_preserves_colimits : preserves_colimits F := λ J 𝒥 K, by resetI; exact { preserves := λ c hc, is_colimit_iso_unique_cocone_morphism.inv (λ s, (((adj.functoriality_is_left_adjoint _).adj).hom_equiv _ _).unique_of_equiv $ is_colimit_iso_unique_cocone_morphism.hom hc _ ) } end preservation_colimits section preservation_limits variables {J : Type v} [small_category J] (K : J ⥤ D) def functoriality_is_right_adjoint : is_right_adjoint (@cones.functoriality _ _ _ _ K _ _ G) := { left := (cones.functoriality F) ⋙ (cones.postcompose ((associator _ _ _).hom ≫ (whisker_left K adj.counit) ≫ K.right_unitor.hom)), adj := mk_of_unit_counit _ _ { unit := { app := λ c, { hom := adj.unit.app c.X, w' := begin intro j, dsimp, erw [category.comp_id, category.id_comp, G.map_comp, ← category.assoc, ← adj.unit.naturality (c.π.app j), category.assoc, adj.right_triangle_components, category.comp_id], refl, end }, naturality' := λ _ _ f, by have := adj.unit.naturality (f.hom); tidy }, counit := { app := λ c, { hom := adj.counit.app c.X, w' := λ j, by have := adj.counit.naturality (c.π.app j); tidy }, naturality' := λ _ _ f, by have := adj.counit.naturality (f.hom); tidy } } } /-- A right adjoint preserves limits. -/ def right_adjoint_preserves_limits : preserves_limits G := λ J 𝒥 K, by resetI; exact { preserves := λ c hc, is_limit_iso_unique_cone_morphism.inv (λ s, (((adj.functoriality_is_right_adjoint _).adj).hom_equiv _ _).symm.unique_of_equiv $ is_limit_iso_unique_cone_morphism.hom hc _) } end preservation_limits -- Note: this is natural in K, but we do not yet have the tools to formulate that. def cocones_iso {J : Type v} [small_category J] {K : J ⥤ C} : (cocones J D).obj (op (K ⋙ F)) ≅ G ⋙ ((cocones J C).obj (op K)) := nat_iso.of_components (λ Y, { hom := λ t, { app := λ j, (adj.hom_equiv (K.obj j) Y) (t.app j), naturality' := λ j j' f, by erw [← adj.hom_equiv_naturality_left, t.naturality]; dsimp; simp }, inv := λ t, { app := λ j, (adj.hom_equiv (K.obj j) Y).symm (t.app j), naturality' := λ j j' f, begin erw [← adj.hom_equiv_naturality_left_symm, ← adj.hom_equiv_naturality_right_symm, t.naturality], dsimp, simp end } } ) begin intros Y₁ Y₂ f, ext1 t, ext1 j, apply adj.hom_equiv_naturality_right end -- Note: this is natural in K, but we do not yet have the tools to formulate that. def cones_iso {J : Type v} [small_category J] {K : J ⥤ D} : F.op ⋙ ((cones J D).obj K) ≅ (cones J C).obj (K ⋙ G) := nat_iso.of_components (λ X, { hom := λ t, { app := λ j, (adj.hom_equiv (unop X) (K.obj j)) (t.app j), naturality' := λ j j' f, begin erw [← adj.hom_equiv_naturality_right, ← t.naturality, category.id_comp, category.id_comp], refl end }, inv := λ t, { app := λ j, (adj.hom_equiv (unop X) (K.obj j)).symm (t.app j), naturality' := λ j j' f, begin erw [← adj.hom_equiv_naturality_right_symm, ← t.naturality, category.id_comp, category.id_comp] end } } ) (by tidy) end category_theory.adjunction
70329e0243bd58fdf96c8c1b109584d93de0ab1f
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/data/nat/sqrt.lean
f18b94c7054c6eaf25cca559e1b3bb649fb1981f
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
6,995
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Johannes Hölzl, Mario Carneiro An efficient binary implementation of a (sqrt n) function that returns s s.t. s*s ≤ n ≤ s*s + s + s -/ import data.int.basic namespace nat theorem sqrt_aux_dec {b} (h : b ≠ 0) : shiftr b 2 < b := begin simp [shiftr_eq_div_pow], apply (nat.div_lt_iff_lt_mul' (dec_trivial : 0 < 4)).2, have := nat.mul_lt_mul_of_pos_left (dec_trivial : 1 < 4) (nat.pos_of_ne_zero h), rwa mul_one at this end def sqrt_aux : ℕ → ℕ → ℕ → ℕ | b r n := if b0 : b = 0 then r else let b' := shiftr b 2 in have b' < b, from sqrt_aux_dec b0, match (n - (r + b : ℕ) : ℤ) with | (n' : ℕ) := sqrt_aux b' (div2 r + b) n' | _ := sqrt_aux b' (div2 r) n end /-- `sqrt n` is the square root of a natural number `n`. If `n` is not a perfect square, it returns the largest `k:ℕ` such that `k*k ≤ n`. -/ @[pp_nodot] def sqrt (n : ℕ) : ℕ := match size n with | 0 := 0 | succ s := sqrt_aux (shiftl 1 (bit0 (div2 s))) 0 n end theorem sqrt_aux_0 (r n) : sqrt_aux 0 r n = r := by rw sqrt_aux; simp local attribute [simp] sqrt_aux_0 theorem sqrt_aux_1 {r n b} (h : b ≠ 0) {n'} (h₂ : r + b + n' = n) : sqrt_aux b r n = sqrt_aux (shiftr b 2) (div2 r + b) n' := by rw sqrt_aux; simp only [h, h₂.symm, int.coe_nat_add, if_false]; rw [add_comm _ (n':ℤ), add_sub_cancel, sqrt_aux._match_1] theorem sqrt_aux_2 {r n b} (h : b ≠ 0) (h₂ : n < r + b) : sqrt_aux b r n = sqrt_aux (shiftr b 2) (div2 r) n := begin rw sqrt_aux; simp only [h, h₂, if_false], cases int.eq_neg_succ_of_lt_zero (sub_lt_zero.2 (int.coe_nat_lt_coe_nat_of_lt h₂)) with k e, rw [e, sqrt_aux._match_1] end private def is_sqrt (n q : ℕ) : Prop := q*q ≤ n ∧ n < (q+1)*(q+1) private lemma sqrt_aux_is_sqrt_lemma (m r n : ℕ) (h₁ : r*r ≤ n) (m') (hm : shiftr (2^m * 2^m) 2 = m') (H1 : n < (r + 2^m) * (r + 2^m) → is_sqrt n (sqrt_aux m' (r * 2^m) (n - r * r))) (H2 : (r + 2^m) * (r + 2^m) ≤ n → is_sqrt n (sqrt_aux m' ((r + 2^m) * 2^m) (n - (r + 2^m) * (r + 2^m)))) : is_sqrt n (sqrt_aux (2^m * 2^m) ((2*r)*2^m) (n - r*r)) := begin have b0 := have b0:_, from ne_of_gt (@pos_pow_of_pos 2 m dec_trivial), nat.mul_ne_zero b0 b0, have lb : n - r * r < 2 * r * 2^m + 2^m * 2^m ↔ n < (r+2^m)*(r+2^m), { rw [nat.sub_lt_right_iff_lt_add h₁], simp [left_distrib, right_distrib, two_mul, mul_comm, mul_assoc, add_comm, add_assoc, add_left_comm] }, have re : div2 (2 * r * 2^m) = r * 2^m, { rw [div2_val, mul_assoc, nat.mul_div_cancel_left _ (dec_trivial:2>0)] }, cases lt_or_ge n ((r+2^m)*(r+2^m)) with hl hl, { rw [sqrt_aux_2 b0 (lb.2 hl), hm, re], apply H1 hl }, { cases le.dest hl with n' e, rw [@sqrt_aux_1 (2 * r * 2^m) (n-r*r) (2^m * 2^m) b0 (n - (r + 2^m) * (r + 2^m)), hm, re, ← right_distrib], { apply H2 hl }, apply eq.symm, apply nat.sub_eq_of_eq_add, rw [← add_assoc, (_ : r*r + _ = _)], exact (nat.add_sub_cancel' hl).symm, simp [left_distrib, right_distrib, two_mul, mul_comm, mul_assoc, add_assoc] }, end private lemma sqrt_aux_is_sqrt (n) : ∀ m r, r*r ≤ n → n < (r + 2^(m+1)) * (r + 2^(m+1)) → is_sqrt n (sqrt_aux (2^m * 2^m) (2*r*2^m) (n - r*r)) | 0 r h₁ h₂ := by apply sqrt_aux_is_sqrt_lemma 0 r n h₁ 0 rfl; intros; simp; [exact ⟨h₁, a⟩, exact ⟨a, h₂⟩] | (m+1) r h₁ h₂ := begin apply sqrt_aux_is_sqrt_lemma (m+1) r n h₁ (2^m * 2^m) (by simp [shiftr, nat.pow_succ, div2_val, mul_comm, mul_left_comm]; repeat {rw @nat.mul_div_cancel_left _ 2 dec_trivial}); intros, { have := sqrt_aux_is_sqrt m r h₁ a, simpa [nat.pow_succ, mul_comm, mul_assoc] }, { rw [nat.pow_succ, mul_two, ← add_assoc] at h₂, have := sqrt_aux_is_sqrt m (r + 2^(m+1)) a h₂, rwa show (r + 2^(m + 1)) * 2^(m+1) = 2 * (r + 2^(m + 1)) * 2^m, by simp [nat.pow_succ, mul_comm, mul_left_comm] } end private lemma sqrt_is_sqrt (n : ℕ) : is_sqrt n (sqrt n) := begin generalize e : size n = s, cases s with s; simp [e, sqrt], { rw [size_eq_zero.1 e, is_sqrt], exact dec_trivial }, { have := sqrt_aux_is_sqrt n (div2 s) 0 (zero_le _), simp [show 2^div2 s * 2^div2 s = shiftl 1 (bit0 (div2 s)), by { generalize: div2 s = x, change bit0 x with x+x, rw [one_shiftl, pow_add] }] at this, apply this, rw [← pow_add, ← mul_two], apply size_le.1, rw e, apply (@div_lt_iff_lt_mul _ _ 2 dec_trivial).1, rw [div2_val], apply lt_succ_self } end theorem sqrt_le (n : ℕ) : sqrt n * sqrt n ≤ n := (sqrt_is_sqrt n).left theorem lt_succ_sqrt (n : ℕ) : n < succ (sqrt n) * succ (sqrt n) := (sqrt_is_sqrt n).right theorem sqrt_le_add (n : ℕ) : n ≤ sqrt n * sqrt n + sqrt n + sqrt n := by rw ← succ_mul; exact le_of_lt_succ (lt_succ_sqrt n) theorem le_sqrt {m n : ℕ} : m ≤ sqrt n ↔ m*m ≤ n := ⟨λ h, le_trans (mul_self_le_mul_self h) (sqrt_le n), λ h, le_of_lt_succ $ mul_self_lt_mul_self_iff.2 $ lt_of_le_of_lt h (lt_succ_sqrt n)⟩ theorem sqrt_lt {m n : ℕ} : sqrt m < n ↔ m < n*n := lt_iff_lt_of_le_iff_le le_sqrt theorem sqrt_le_self (n : ℕ) : sqrt n ≤ n := le_trans (le_mul_self _) (sqrt_le n) theorem sqrt_le_sqrt {m n : ℕ} (h : m ≤ n) : sqrt m ≤ sqrt n := le_sqrt.2 (le_trans (sqrt_le _) h) theorem sqrt_eq_zero {n : ℕ} : sqrt n = 0 ↔ n = 0 := ⟨λ h, eq_zero_of_le_zero $ le_of_lt_succ $ (@sqrt_lt n 1).1 $ by rw [h]; exact dec_trivial, λ e, e.symm ▸ rfl⟩ theorem eq_sqrt {n q} : q = sqrt n ↔ q*q ≤ n ∧ n < (q+1)*(q+1) := ⟨λ e, e.symm ▸ sqrt_is_sqrt n, λ ⟨h₁, h₂⟩, le_antisymm (le_sqrt.2 h₁) (le_of_lt_succ $ sqrt_lt.2 h₂)⟩ theorem le_three_of_sqrt_eq_one {n : ℕ} (h : sqrt n = 1) : n ≤ 3 := le_of_lt_succ $ (@sqrt_lt n 2).1 $ by rw [h]; exact dec_trivial theorem sqrt_lt_self {n : ℕ} (h : 1 < n) : sqrt n < n := sqrt_lt.2 $ by have := nat.mul_lt_mul_of_pos_left h (lt_of_succ_lt h); rwa [mul_one] at this theorem sqrt_pos {n : ℕ} : 0 < sqrt n ↔ 0 < n := le_sqrt theorem sqrt_add_eq (n : ℕ) {a : ℕ} (h : a ≤ n + n) : sqrt (n*n + a) = n := le_antisymm (le_of_lt_succ $ sqrt_lt.2 $ by rw [succ_mul, mul_succ, add_succ, add_assoc]; exact lt_succ_of_le (nat.add_le_add_left h _)) (le_sqrt.2 $ nat.le_add_right _ _) theorem sqrt_eq (n : ℕ) : sqrt (n*n) = n := sqrt_add_eq n (zero_le _) theorem sqrt_succ_le_succ_sqrt (n : ℕ) : sqrt n.succ ≤ n.sqrt.succ := le_of_lt_succ $ sqrt_lt.2 $ lt_succ_of_le $ succ_le_succ $ le_trans (sqrt_le_add n) $ add_le_add_right (by refine add_le_add (mul_le_mul_right _ _) _; exact le_add_right _ 2) _ theorem exists_mul_self (x : ℕ) : (∃ n, n * n = x) ↔ sqrt x * sqrt x = x := ⟨λ ⟨n, hn⟩, by rw [← hn, sqrt_eq], λ h, ⟨sqrt x, h⟩⟩ end nat
be99939b3c33341cd870151441cdfc5ab7305b04
ea4aee6b11f86433e69bb5e50d0259e056d0ae61
/src/tidy/tidy.lean
f70512db2e17ad9ad46b07f9068293930ec4195b
[]
no_license
timjb/lean-tidy
e18feff0b7f0aad08c614fb4d34aaf527bf21e20
e767e259bf76c69edfd4ab8af1b76e6f1ed67f48
refs/heads/master
1,624,861,693,182
1,504,411,006,000
1,504,411,006,000
103,740,824
0
0
null
1,505,553,968,000
1,505,553,968,000
null
UTF-8
Lean
false
false
6,042
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 .force .applicable .congr_assumptions .fsplit .automatic_induction .tidy_attributes .intro_at_least_one import .monadic_chain import .smt import data.list open tactic universe variable u attribute [reducible] cast attribute [reducible] lift_t coe_t coe_b has_coe_to_fun.coe attribute [ematch] subtype.property private meta def dsimp_eq_mpr : tactic unit := `[dsimp [eq.mpr] {unfold_reducible := tt}] meta def dsimp' := `[dsimp {unfold_reducible := tt, md := semireducible}] meta def dsimp_all' := `[dsimp at * {unfold_reducible := tt, md := semireducible}] meta def if_exactly_one_goal { α : Type } ( t : tactic α ) : tactic α := do ng ← num_goals, if ng = 1 then t else fail "there is not exactly one goal" meta def build_focus_string ( s : list ( option string ) ) : tactic string := pure ("focus " ++ (s.map(λ x, option.get_or_else x "skip")).to_string) meta def if_first_goal_safe { α : Type } ( t : tactic α ) : tactic α := do ng ← num_goals, if ng = 1 then t else do { p ← target >>= is_prop, if p then t else fail "there are multiple goals, and the first goal is not a mere proposition" } -- TODO I'd love to do some profiling here, and find how much time is spent inside each tactic, -- also divided up between successful and unsuccessful calls. -- TODO also find tactics which are never used! -- TODO does cc help? meta def unsafe_tidy_tactics : list (tactic string) := [ assumption >> pure "assumption", congr_assumptions, `[simp only [id_locked_eq]] >> pure "simp only [id_locked_eq]" ] meta def safe_tidy_tactics : list (tactic string) := [ force (reflexivity) >> pure "refl", `[exact dec_trivial] >> pure "exact dec_trivial", applicable >>= λ n, pure ("fapply " ++ n.to_string), intro_at_least_one >> pure "intros", force (fsplit) >> pure "fsplit", dsimp' >> pure "dsimp'", `[simp] >> pure "simp", automatic_induction >> pure "automatic_induction", dsimp_all' >> pure "dsimp_all'", `[simp at *] >> pure "simp at *" ] private meta def any_later_goals_core { α : Type } (tac : tactic α) : list expr → list expr → list (option α) → bool → tactic (list (option α)) | [] ac results progress := guard progress >> set_goals ac >> pure results | (g :: gs) ac results progress := do set_goals [g], succeeded ← try_core tac, new_gs ← get_goals, any_later_goals_core gs (ac ++ new_gs) (succeeded :: results) (succeeded.is_some || progress) /-- Apply the given tactic to any goal besides the first where it succeeds. The tactic succeeds only if tac succeeds for at least one goal. -/ meta def any_later_goals { α : Type } (tac : tactic α ) : tactic (list (option α)) := do gs ← get_goals, any_later_goals_core tac gs [] [] ff meta def global_tidy_tactics := unsafe_tidy_tactics.map(if_first_goal_safe) ++ safe_tidy_tactics meta def safe_tactics_on_later_goals := safe_tidy_tactics.map(λ t, any_later_goals t >>= λ s, pure ("tactic.focus [ " ++ ((((none :: s).map(λ o, option.get_or_else o "skip")).intersperse ", ").foldl append "") ++ "]")) meta structure tidy_cfg extends chain_cfg := ( trace_result : bool := ff ) ( run_annotated_tactics : bool := tt ) ( extra_tactics : list (tactic string) := [] ) ( show_hints : bool := ff ) ( hints : list ℕ := [] ) ( later_goals : bool := tt ) private meta def number_tactics { α : Type } ( tactics : list (tactic α) ) : list ( tactic (α × ℕ) ) := tactics.map₂ ( λ t, λ n, (do r ← t, pure (r, n))) (list.range tactics.length) private meta def apply_hints { α : Type } ( tactics : list (tactic α) ) : list ℕ → tactic bool | list.nil := pure tt | (n :: ns) := match tactics.nth n with | none := pure ff | some t := if_then_else t (apply_hints ns) (pure ff) end meta def tidy ( cfg : tidy_cfg := {} ) : tactic unit := let tidy_tactics := global_tidy_tactics ++ (if cfg.later_goals then safe_tactics_on_later_goals else []) ++ (if cfg.run_annotated_tactics then [ run_tidy_tactics ] else []) ++ cfg.extra_tactics in let numbered_tactics := number_tactics tidy_tactics in do /- first apply hints -/ if ¬ cfg.hints.empty then do r ← apply_hints numbered_tactics cfg.hints, if ¬ r then /- hints were broken ... -/ trace "hints for 'tidy' tactic were invalid!" else skip else do original_goals ← get_goals, results ← chain numbered_tactics cfg.to_chain_cfg, if cfg.show_hints then let hints := results.map (λ p, p.2) in trace ("tidy {hints:=" ++ hints.to_string ++ "}") else skip, if cfg.trace_result then let result_strings := results.map (λ p, p.1) in trace ("chain tactic used: " ++ result_strings.to_string) else skip meta def blast ( cfg : tidy_cfg := {} ) : tactic unit := tidy { cfg with extra_tactics := cfg.extra_tactics ++ [ focus1 ( smt_eblast >> tactic.done ) >> pure "smt_eblast" ] } notation `♮` := by abstract { smt_eblast } notation `♯` := by abstract { blast } -- meta def interactive_simp := `[simp] def tidy_test_0 : ∀ x : unit, x = unit.star := begin success_if_fail { chain [ interactive_simp ] }, intro1, induction x, refl end def tidy_test (a : string): ∀ x : unit, x = unit.star := begin tidy {show_hints := tt} end
4c93674001bf9a0a5059a7074f348a4c2f6480ef
bf532e3e865883a676110e756f800e0ddeb465be
/analysis/measure_theory/outer_measure.lean
bf8b8e3989a9f42329d385b734f93e797c80d822
[ "Apache-2.0" ]
permissive
aqjune/mathlib
da42a97d9e6670d2efaa7d2aa53ed3585dafc289
f7977ff5a6bcf7e5c54eec908364ceb40dafc795
refs/heads/master
1,631,213,225,595
1,521,089,840,000
1,521,089,840,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,027
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 Outer measures -- overapproximations of measures -/ import data.set order.galois_connection algebra.big_operators analysis.ennreal analysis.limits analysis.measure_theory.measurable_space noncomputable theory open set lattice finset function filter open ennreal (of_real) local attribute [instance] classical.prop_decidable local infix ` ^ ` := monoid.pow namespace measure_theory structure outer_measure (α : Type*) := (measure_of : set α → ennreal) (empty : measure_of ∅ = 0) (mono : ∀{s₁ s₂}, s₁ ⊆ s₂ → measure_of s₁ ≤ measure_of s₂) (Union_nat : ∀(s:ℕ → set α), measure_of (⋃i, s i) ≤ (∑i, measure_of (s i))) namespace outer_measure section basic variables {α : Type*} {ms : set (outer_measure α)} {m : outer_measure α} lemma subadditive (m : outer_measure α) {s₁ s₂ : set α} : m.measure_of (s₁ ∪ s₂) ≤ m.measure_of s₁ + m.measure_of s₂ := let s := λi, ([s₁, s₂].nth i).get_or_else ∅ in calc m.measure_of (s₁ ∪ s₂) ≤ m.measure_of (⋃i, s i) : m.mono $ union_subset (subset_Union s 0) (subset_Union s 1) ... ≤ (∑i, m.measure_of (s i)) : m.Union_nat s ... = (insert 0 {1} : finset ℕ).sum (m.measure_of ∘ s) : tsum_eq_sum $ assume n h, match n, h with | 0, h := by simp at h; contradiction | 1, h := by simp at h; contradiction | nat.succ (nat.succ n), h := m.empty end ... = m.measure_of s₁ + m.measure_of s₂ : by simp [-add_comm]; refl lemma outer_measure_eq : ∀{μ₁ μ₂ : outer_measure α}, (∀s, μ₁.measure_of s = μ₂.measure_of s) → μ₁ = μ₂ | ⟨m₁, e₁, _, u₁⟩ ⟨m₂, e₂, _, u₂⟩ h := have m₁ = m₂, from funext $ assume s, h s, by simp [this] instance : has_zero (outer_measure α) := ⟨{ measure_of := λ_, 0, empty := rfl, mono := assume _ _ _, le_refl 0, Union_nat := assume s, ennreal.zero_le }⟩ instance : inhabited (outer_measure α) := ⟨0⟩ instance : has_add (outer_measure α) := ⟨λm₁ m₂, { measure_of := λs, m₁.measure_of s + m₂.measure_of s, empty := show m₁.measure_of ∅ + m₂.measure_of ∅ = 0, by simp [outer_measure.empty], mono := assume s₁ s₂ h, add_le_add' (m₁.mono h) (m₂.mono h), Union_nat := assume s, calc m₁.measure_of (⋃i, s i) + m₂.measure_of (⋃i, s i) ≤ (∑i, m₁.measure_of (s i)) + (∑i, m₂.measure_of (s i)) : add_le_add' (m₁.Union_nat s) (m₂.Union_nat s) ... = _ : (tsum_add ennreal.has_sum ennreal.has_sum).symm}⟩ instance : add_comm_monoid (outer_measure α) := { zero := 0, add := (+), add_comm := assume a b, outer_measure_eq $ assume s, add_comm _ _, add_assoc := assume a b c, outer_measure_eq $ assume s, add_assoc _ _ _, add_zero := assume a, outer_measure_eq $ assume s, add_zero _, zero_add := assume a, outer_measure_eq $ assume s, zero_add _ } instance : has_bot (outer_measure α) := ⟨0⟩ instance outer_measure.order_bot : order_bot (outer_measure α) := { le := λm₁ m₂, ∀s, m₁.measure_of s ≤ m₂.measure_of s, bot := 0, le_refl := assume a s, le_refl _, le_trans := assume a b c hab hbc s, le_trans (hab s) (hbc s), le_antisymm := assume a b hab hba, outer_measure_eq $ assume s, le_antisymm (hab s) (hba s), bot_le := assume a s, ennreal.zero_le } section supremum private def sup (ms : set (outer_measure α)) (h : ms ≠ ∅) := { outer_measure . measure_of := λs, ⨆m:ms, m.val.measure_of s, empty := let ⟨m, hm⟩ := set.exists_mem_of_ne_empty h in have ms := ⟨m, hm⟩, by simp [outer_measure.empty]; exact @supr_const _ _ _ _ ⟨this⟩, mono := assume s₁ s₂ hs, supr_le_supr $ assume ⟨m, hm⟩, m.mono hs, Union_nat := assume f, supr_le $ assume m, calc m.val.measure_of (⋃i, f i) ≤ (∑ (i : ℕ), m.val.measure_of (f i)) : m.val.Union_nat _ ... ≤ (∑i, ⨆m:ms, m.val.measure_of (f i)) : ennreal.tsum_le_tsum $ assume i, le_supr (λm:ms, m.val.measure_of (f i)) m } instance : has_Sup (outer_measure α) := ⟨λs, if h : s = ∅ then ⊥ else sup s h⟩ private lemma le_Sup (hm : m ∈ ms) : m ≤ Sup ms := show m ≤ (if h : ms = ∅ then ⊥ else sup ms h), by rw [dif_neg (set.ne_empty_of_mem hm)]; exact assume s, le_supr (λm:ms, m.val.measure_of s) ⟨m, hm⟩ private lemma Sup_le (hm : ∀m' ∈ ms, m' ≤ m) : Sup ms ≤ m := show (if h : ms = ∅ then ⊥ else sup ms h) ≤ m, begin by_cases ms = ∅, { rw [dif_pos h], exact bot_le }, { rw [dif_neg h], exact assume s, (supr_le $ assume ⟨m', h'⟩, (hm m' h') s) } end instance : has_Inf (outer_measure α) := ⟨λs, Sup {m | ∀m'∈s, m ≤ m'}⟩ private lemma Inf_le (hm : m ∈ ms) : Inf ms ≤ m := Sup_le $ assume m' h', h' _ hm private lemma le_Inf (hm : ∀m' ∈ ms, m ≤ m') : m ≤ Inf ms := le_Sup hm instance : complete_lattice (outer_measure α) := { top := Sup univ, le_top := assume a, le_Sup (mem_univ a), Sup := Sup, Sup_le := assume s m, Sup_le, le_Sup := assume s m, le_Sup, Inf := Inf, Inf_le := assume s m, Inf_le, le_Inf := assume s m, le_Inf, sup := λa b, Sup {a, b}, le_sup_left := assume a b, le_Sup $ by simp, le_sup_right := assume a b, le_Sup $ by simp, sup_le := assume a b c ha hb, Sup_le $ by simp [or_imp_distrib, ha, hb] {contextual:=tt}, inf := λa b, Inf {a, b}, inf_le_left := assume a b, Inf_le $ by simp, inf_le_right := assume a b, Inf_le $ by simp, le_inf := assume a b c ha hb, le_Inf $ by simp [or_imp_distrib, ha, hb] {contextual:=tt}, .. outer_measure.order_bot } end supremum end basic section of_function set_option eqn_compiler.zeta true -- TODO: if we move this proof into the definition of inf it does not terminate anymore private lemma aux {ε : ℝ} (hε : 0 < ε) : (∑i, of_real ((ε / 2) * 2⁻¹ ^ i)) = of_real ε := let ε' := λi, (ε / 2) * 2⁻¹ ^ i in have hε' : ∀i, 0 < ε' i, from assume i, mul_pos (div_pos_of_pos_of_pos hε two_pos) $ pow_pos (inv_pos two_pos) _, have is_sum (λi, 2⁻¹ ^ i : ℕ → ℝ) (1 / (1 - 2⁻¹)), from is_sum_geometric (le_of_lt $ inv_pos two_pos) $ inv_lt_one one_lt_two, have is_sum (λi, ε' i) ((ε / 2) * (1 / (1 - 2⁻¹))), from is_sum_mul_left this, have eq : ((ε / 2) * (1 / (1 - 2⁻¹))) = ε, begin have ne_two : (2:ℝ) ≠ 0, from (ne_of_lt two_pos).symm, rw [inv_eq_one_div, sub_eq_add_neg, ←neg_div, add_div_eq_mul_add_div _ _ ne_two], simp [bit0, bit1] at ne_two, simp [bit0, bit1, mul_div_cancel' _ ne_two, mul_comm] end, have is_sum (λi, ε' i) ε, begin rw [eq] at this, exact this end, ennreal.tsum_of_real this (assume i, le_of_lt $ hε' i) /-- Given any function `m` assigning measures to sets satisying `m ∅ = 0`, there is a unique minimal outer measure `μ` satisfying `μ s ≥ m s` for all `s : set α`. -/ protected def of_function {α : Type*} (m : set α → ennreal) (m_empty : m ∅ = 0) : outer_measure α := let μ := λs, ⨅{f : ℕ → set α} (h : s ⊆ ⋃i, f i), ∑i, m (f i) in { measure_of := μ, empty := le_antisymm (infi_le_of_le (λ_, ∅) $ infi_le_of_le (empty_subset _) $ by simp [m_empty]) (zero_le _), mono := assume s₁ s₂ hs, infi_le_infi $ assume f, infi_le_infi2 $ assume hb, ⟨subset.trans hs hb, le_refl _⟩, Union_nat := assume s, ennreal.le_of_forall_epsilon_le $ assume ε hε (hb : (∑i, μ (s i)) < ⊤), let ε' := λi, (ε / 2) * 2⁻¹ ^ i in have hε' : ∀i, 0 < ε' i, from assume i, mul_pos (div_pos_of_pos_of_pos hε two_pos) $ pow_pos (inv_pos two_pos) _, have ∀i, ∃f:ℕ → set α, s i ⊆ (⋃i, f i) ∧ (∑i, m (f i)) < μ (s i) + of_real (ε' i), from assume i, have μ (s i) < μ (s i) + of_real (ε' i), from ennreal.lt_add_right (calc μ (s i) ≤ (∑i, μ (s i)) : ennreal.le_tsum ... < ⊤ : hb) (by simp; exact hε' _), by simpa [μ, infi_lt_iff] using this, let ⟨f, hf⟩ := classical.axiom_of_choice this in let f' := λi, f (nat.unpair i).1 (nat.unpair i).2 in have hf' : (⋃ (i : ℕ), s i) ⊆ (⋃i, f' i), from Union_subset $ assume i, subset.trans (hf i).left $ Union_subset_Union2 $ assume j, ⟨nat.mkpair i j, begin simp [f'], simp [nat.unpair_mkpair], exact subset.refl _ end⟩, have (∑i, of_real (ε' i)) = of_real ε, from aux hε, have (∑i, m (f' i)) ≤ (∑i, μ (s i)) + of_real ε, from calc (∑i, m (f' i)) = (∑p:ℕ×ℕ, m (f' (nat.mkpair p.1 p.2))) : (tsum_eq_tsum_of_iso (λp:ℕ×ℕ, nat.mkpair p.1 p.2) nat.unpair (assume ⟨a, b⟩, nat.unpair_mkpair a b) nat.mkpair_unpair).symm ... = (∑i, ∑j, m (f i j)) : by dsimp [f']; rw [←ennreal.tsum_prod]; simp [nat.unpair_mkpair] ... ≤ (∑i, μ (s i) + of_real (ε' i)) : ennreal.tsum_le_tsum $ assume i, le_of_lt $ (hf i).right ... ≤ (∑i, μ (s i)) + (∑i, of_real (ε' i)) : by rw [tsum_add]; exact ennreal.has_sum ... = (∑i, μ (s i)) + of_real ε : by rw [this], show μ (⋃ (i : ℕ), s i) ≤ (∑ (i : ℕ), μ (s i)) + of_real ε, from infi_le_of_le f' $ infi_le_of_le hf' $ this } end of_function section caratheodory_measurable universe u parameters {α : Type u} (m : outer_measure α) include m local notation `μ` := m.measure_of local attribute [simp] set.inter_comm set.inter_left_comm set.inter_assoc variables {s s₁ s₂ : set α} private def C (s : set α) := ∀t, μ t = μ (t ∩ s) + μ (t \ s) @[simp] private lemma C_empty : C ∅ := by simp [C, m.empty, sdiff_empty] private lemma C_compl : C s₁ → C (- s₁) := by simp [C, sdiff_eq] @[simp] private lemma C_compl_iff : C (- s) ↔ C s := ⟨assume h, let h' := C_compl h in by simp at h'; assumption, C_compl⟩ private lemma C_union (h₁ : C s₁) (h₂ : C s₂) : C (s₁ ∪ s₂) := assume t, have e₁ : (s₁ ∪ s₂) ∩ s₁ ∩ s₂ = s₁ ∩ s₂, from set.ext $ assume x, by simp [iff_def] {contextual := tt}, have e₂ : (s₁ ∪ s₂) ∩ s₁ ∩ -s₂ = s₁ ∩ -s₂, from set.ext $ assume x, by simp [iff_def] {contextual := tt}, calc μ t = μ (t ∩ s₁ ∩ s₂) + μ (t ∩ s₁ ∩ -s₂) + μ (t ∩ -s₁ ∩ s₂) + μ (t ∩ -s₁ ∩ -s₂) : by rw [h₁ t, h₂ (t ∩ s₁), h₂ (t \ s₁)]; simp [sdiff_eq] ... = μ (t ∩ ((s₁ ∪ s₂) ∩ s₁ ∩ s₂)) + μ (t ∩ ((s₁ ∪ s₂) ∩ s₁ ∩ -s₂)) + μ (t ∩ s₂ ∩ -s₁) + μ (t ∩ -s₁ ∩ -s₂) : by rw [e₁, e₂]; simp ... = ((μ (t ∩ (s₁ ∪ s₂) ∩ s₁ ∩ s₂) + μ ((t ∩ (s₁ ∪ s₂) ∩ s₁) \ s₂)) + μ (t ∩ ((s₁ ∪ s₂) \ s₁))) + μ (t \ (s₁ ∪ s₂)) : by rw [union_sdiff_right]; simp [sdiff_eq] ... = μ (t ∩ (s₁ ∪ s₂)) + μ (t \ (s₁ ∪ s₂)) : by rw [h₁ (t ∩ (s₁ ∪ s₂)), h₂ ((t ∩ (s₁ ∪ s₂)) ∩ s₁)]; simp [sdiff_eq] private lemma C_Union_lt {s : ℕ → set α} : ∀{n:ℕ}, (∀i<n, C (s i)) → C (⋃i<n, s i) | 0 h := by simp [nat.not_lt_zero] | (n + 1) h := show C (⨆i < nat.succ n, s i), begin simp [nat.lt_succ_iff_lt_or_eq, supr_or, supr_sup_eq, sup_comm], exact C_union m (h n (le_refl (n + 1))) (C_Union_lt $ assume i hi, h i $ lt_of_lt_of_le hi $ nat.le_succ _) end private lemma C_inter (h₁ : C s₁) (h₂ : C s₂) : C (s₁ ∩ s₂) := by rw [←C_compl_iff, compl_inter]; from C_union _ (C_compl _ h₁) (C_compl _ h₂) private lemma C_sum {s : ℕ → set α} (h : ∀i, C (s i)) (hd : pairwise (disjoint on s)) {n} {t : set α} : (finset.range n).sum (λi, μ (t ∩ s i)) = μ (t ∩ ⋃i<n, s i) := begin induction n, case nat.zero { simp [nat.not_lt_zero, m.empty] }, case nat.succ : n ih { have disj : ∀x i, x ∈ s n → i < n → x ∉ s i, from assume x i hn h hi, have hx : x ∈ s i ∩ s n, from ⟨hi, hn⟩, have s i ∩ s n = ∅, from hd _ _ (ne_of_lt h), by rwa [this] at hx, have : (⋃i<n+1, s i) \ (⋃i<n, s i) = s n, { apply set.ext, intro x, simp, constructor, from assume ⟨⟨i, hin, hi⟩, hx⟩, (nat.lt_succ_iff_lt_or_eq.mp hin).elim (assume h, (hx i h hi).elim) (assume h, h ▸ hi), from assume hx, ⟨⟨n, nat.lt_succ_self _, hx⟩, assume i, disj x i hx⟩ }, have e₁ : t ∩ s n = (t ∩ ⋃i<n+1, s i) \ ⋃i<n, s i, from calc t ∩ s n = t ∩ ((⋃i<n+1, s i) \ (⋃i<n, s i)) : by rw [this] ... = (t ∩ ⋃i<n+1, s i) \ ⋃i<n, s i : by simp [sdiff_eq], have : (⋃i<n+1, s i) ∩ (⋃i<n, s i) = (⋃i<n, s i), from (inf_of_le_right $ supr_le_supr $ assume i, supr_le_supr_const $ assume hin, lt_trans hin (nat.lt_succ_self n)), have e₂ : t ∩ (⋃i<n, s i) = (t ∩ ⋃i<n+1, s i) ∩ ⋃i<n, s i, from calc t ∩ (⋃i<n, s i) = t ∩ ((⋃i<n+1, s i) ∩ (⋃i<n, s i)) : by rw [this] ... = _ : by simp, have : C _ (⋃i<n, s i), from C_Union_lt m (assume i _, h i), from calc (range (nat.succ n)).sum (λi, μ (t ∩ s i)) = μ (t ∩ s n) + μ (t ∩ ⋃i < n, s i) : by simp [range_succ, sum_insert, lt_irrefl, ih] ... = μ ((t ∩ ⋃i<n+1, s i) ∩ ⋃i<n, s i) + μ ((t ∩ ⋃i<n+1, s i) \ ⋃i<n, s i) : by rw [e₁, e₂]; simp ... = μ (t ∩ ⋃i<n+1, s i) : (this $ t ∩ ⋃i<n+1, s i).symm } end private lemma C_Union_nat {s : ℕ → set α} (h : ∀i, C (s i)) (hd : pairwise (disjoint on s)) : C (⋃i, s i) := assume t, suffices μ t ≥ μ (t ∩ (⋃i, s i)) + μ (t \ (⋃i, s i)), from le_antisymm (calc μ t ≤ μ (t ∩ (⋃i, s i) ∪ t \ (⋃i, s i)) : m.mono $ assume x ht, by by_cases x ∈ (⋃i, s i); simp [*] at * ... ≤ μ (t ∩ (⋃i, s i)) + μ (t \ (⋃i, s i)) : m.subadditive) this, have hp : μ (t ∩ ⋃i, s i) ≤ (⨆n, μ (t ∩ ⋃i<n, s i)), from calc μ (t ∩ ⋃i, s i) = μ (⋃i, t ∩ s i) : by rw [inter_distrib_Union_left] ... ≤ ∑i, μ (t ∩ s i) : m.Union_nat _ ... = ⨆n, (finset.range n).sum (λi, μ (t ∩ s i)) : ennreal.tsum_eq_supr_nat ... = ⨆n, μ (t ∩ ⋃i<n, s i) : congr_arg _ $ funext $ assume n, C_sum h hd, have hn : ∀n, μ (t \ (⋃i<n, s i)) ≥ μ (t \ (⋃i, s i)), from assume n, m.mono $ sdiff_subset_sdiff (subset.refl t) $ bUnion_subset $ assume i _, le_supr s i, calc μ (t ∩ (⋃i, s i)) + μ (t \ (⋃i, s i)) ≤ (⨆n, μ (t ∩ ⋃i<n, s i)) + μ (t \ (⋃i, s i)) : add_le_add' hp (le_refl _) ... = (⨆n, μ (t ∩ ⋃i<n, s i) + μ (t \ (⋃i, s i))) : ennreal.supr_add ... ≤ (⨆n, μ (t ∩ ⋃i<n, s i) + μ (t \ (⋃i<n, s i))) : supr_le_supr $ assume i, add_le_add' (le_refl _) (hn _) ... ≤ μ t : supr_le $ assume n, le_of_eq (C_Union_lt (assume i _, h i) t).symm private lemma f_Union {s : ℕ → set α} (h : ∀i, C (s i)) (hd : pairwise (disjoint on s)) : μ (⋃i, s i) = ∑i, μ (s i) := have ∀n, (finset.range n).sum (λ (i : ℕ), μ (s i)) ≤ μ (⋃ (i : ℕ), s i), from assume n, calc (finset.range n).sum (λi, μ (s i)) = (finset.range n).sum (λi, μ (univ ∩ s i)) : by simp [univ_inter] ... = μ (⋃i<n, s i) : by rw [C_sum _ h hd, univ_inter] ... ≤ μ (⋃ (i : ℕ), s i) : m.mono $ bUnion_subset $ assume i _, le_supr s i, suffices μ (⋃i, s i) ≥ ∑i, μ (s i), from le_antisymm (m.Union_nat s) this, calc (∑i, μ (s i)) = (⨆n, (finset.range n).sum (λi, μ (s i))) : ennreal.tsum_eq_supr_nat ... ≤ _ : supr_le this private def caratheodory_dynkin : measurable_space.dynkin_system α := { has := C, has_empty := C_empty, has_compl := assume s, C_compl, has_Union := assume f hf hn, C_Union_nat hn hf } /-- Given an outer measure `μ`, the Caratheodory measurable space is defined such that `s` is measurable if `∀t, μ t = μ (t ∩ s) + μ (t \ s)`. -/ protected def caratheodory : measurable_space α := caratheodory_dynkin.to_measurable_space $ assume s₁ s₂, C_inter lemma caratheodory_is_measurable_eq {s : set α} : caratheodory.is_measurable s = ∀t, μ t = μ (t ∩ s) + μ (t \ s) := rfl protected lemma Union_eq_of_caratheodory {s : ℕ → set α} (h : ∀i, caratheodory.is_measurable (s i)) (hd : pairwise (disjoint on s)) : μ (⋃i, s i) = ∑i, μ (s i) := f_Union h hd lemma caratheodory_is_measurable {m : set α → ennreal} {s : set α} {h₀ : m ∅ = 0} (hs : ∀t, m (t ∩ s) + m (t \ s) ≤ m t) : (outer_measure.of_function m h₀).caratheodory.is_measurable s := let o := (outer_measure.of_function m h₀), om := o.measure_of in assume t, le_antisymm (calc om t = om ((t ∩ s) ∪ (t \ s)) : congr_arg om (set.ext $ assume x, by by_cases x ∈ s; simp [iff_def, *]) ... ≤ om (t ∩ s) + om (t \ s) : o.subadditive) (le_infi $ assume f, le_infi $ assume hf, have h₁ : t ∩ s ⊆ ⋃i, f i ∩ s, by rw [←inter_distrib_Union_right]; from inter_subset_inter hf (subset.refl s), have h₂ : t \ s ⊆ ⋃i, f i \ s, from subset.trans (sdiff_subset_sdiff hf (subset.refl s)) $ by simp [set.subset_def] {contextual := tt}, calc om (t ∩ s) + om (t \ s) ≤ (∑i, m (f i ∩ s)) + (∑i, m (f i \ s)) : add_le_add' (infi_le_of_le (λi, f i ∩ s) $ infi_le_of_le h₁ $ le_refl _) (infi_le_of_le (λi, f i \ s) $ infi_le_of_le h₂ $ le_refl _) ... = (∑i, m (f i ∩ s) + m (f i \ s)) : by rw [tsum_add]; exact ennreal.has_sum ... ≤ (∑i, m (f i)) : ennreal.tsum_le_tsum $ assume i, hs _) end caratheodory_measurable end outer_measure end measure_theory
d29a8962e07af37e8fcc570fdfe3e0f4597a4923
26ac254ecb57ffcb886ff709cf018390161a9225
/src/group_theory/perm/sign.lean
d8171d8c1451253c35535c20576f26f5b3b86d0f
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
32,264
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.fintype.basic import data.finset.sort import algebra.group.conj import algebra.big_operators universes u v open equiv function fintype finset open_locale big_operators variables {α : Type u} {β : Type v} namespace equiv.perm def subtype_perm (f : perm α) {p : α → Prop} (h : ∀ x, p x ↔ p (f x)) : perm {x // p x} := ⟨λ x, ⟨f x, (h _).1 x.2⟩, λ x, ⟨f⁻¹ x, (h (f⁻¹ x)).2 $ by simpa using x.2⟩, λ _, by simp, λ _, by simp⟩ @[simp] lemma subtype_perm_one (p : α → Prop) (h : ∀ x, p x ↔ p ((1 : perm α) x)) : @subtype_perm α 1 p h = 1 := equiv.ext $ λ ⟨_, _⟩, rfl def of_subtype {p : α → Prop} [decidable_pred p] : perm (subtype p) →* perm α := { to_fun := λ f, ⟨λ x, if h : p x then f ⟨x, h⟩ else x, λ x, if h : p x then f⁻¹ ⟨x, h⟩ else x, λ x, have h : ∀ h : p x, p (f ⟨x, h⟩), from λ h, (f ⟨x, h⟩).2, by simp; split_ifs at *; simp * at *, λ x, have h : ∀ h : p x, p (f⁻¹ ⟨x, h⟩), from λ h, (f⁻¹ ⟨x, h⟩).2, by simp; split_ifs at *; simp * at *⟩, map_one' := begin ext, dsimp, split_ifs; refl, end, map_mul' := λ f g, equiv.ext $ λ x, begin by_cases h : p x, { have h₁ : p (f (g ⟨x, h⟩)), from (f (g ⟨x, h⟩)).2, have h₂ : p (g ⟨x, h⟩), from (g ⟨x, h⟩).2, simp [h, h₁, h₂] }, { simp [h] } end } lemma eq_inv_iff_eq {f : perm α} {x y : α} : x = f⁻¹ y ↔ f x = y := by conv {to_lhs, rw [← injective.eq_iff f.injective, apply_inv_self]} lemma inv_eq_iff_eq {f : perm α} {x y : α} : f⁻¹ x = y ↔ x = f y := by rw [eq_comm, eq_inv_iff_eq, eq_comm] /-- Two permutations `f` and `g` are `disjoint` if their supports are disjoint, i.e., every element is fixed either by `f`, or by `g`. -/ def disjoint (f g : perm α) := ∀ x, f x = x ∨ g x = x @[symm] lemma disjoint.symm {f g : perm α} : disjoint f g → disjoint g f := by simp [disjoint, or.comm] lemma disjoint_comm {f g : perm α} : disjoint f g ↔ disjoint g f := ⟨disjoint.symm, disjoint.symm⟩ lemma disjoint_mul_comm {f g : perm α} (h : disjoint f g) : f * g = g * f := equiv.ext $ λ x, (h x).elim (λ hf, (h (g x)).elim (λ hg, by simp [mul_apply, hf, hg]) (λ hg, by simp [mul_apply, hf, g.injective hg])) (λ hg, (h (f x)).elim (λ hf, by simp [mul_apply, f.injective hf, hg]) (λ hf, by simp [mul_apply, hf, hg])) @[simp] lemma disjoint_one_left (f : perm α) : disjoint 1 f := λ _, or.inl rfl @[simp] lemma disjoint_one_right (f : perm α) : disjoint f 1 := λ _, or.inr rfl lemma disjoint_mul_left {f g h : perm α} (H1 : disjoint f h) (H2 : disjoint g h) : disjoint (f * g) h := λ x, by cases H1 x; cases H2 x; simp * lemma disjoint_mul_right {f g h : perm α} (H1 : disjoint f g) (H2 : disjoint f h) : disjoint f (g * h) := by rw disjoint_comm; exact disjoint_mul_left H1.symm H2.symm lemma disjoint_prod_right {f : perm α} (l : list (perm α)) (h : ∀ g ∈ l, disjoint f g) : disjoint f l.prod := begin induction l with g l ih, { exact disjoint_one_right _ }, { rw list.prod_cons; exact disjoint_mul_right (h _ (list.mem_cons_self _ _)) (ih (λ g hg, h g (list.mem_cons_of_mem _ hg))) } end lemma disjoint_prod_perm {l₁ l₂ : list (perm α)} (hl : l₁.pairwise disjoint) (hp : l₁ ~ l₂) : l₁.prod = l₂.prod := hp.prod_eq' $ hl.imp $ λ f g, disjoint_mul_comm lemma of_subtype_subtype_perm {f : perm α} {p : α → Prop} [decidable_pred p] (h₁ : ∀ x, p x ↔ p (f x)) (h₂ : ∀ x, f x ≠ x → p x) : of_subtype (subtype_perm f h₁) = f := equiv.ext $ λ x, begin rw [of_subtype, subtype_perm], by_cases hx : p x, { simp [hx] }, { haveI := classical.prop_decidable, simp [hx, not_not.1 (mt (h₂ x) hx)] } end lemma of_subtype_apply_of_not_mem {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) {x : α} (hx : ¬ p x) : of_subtype f x = x := dif_neg hx lemma mem_iff_of_subtype_apply_mem {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) (x : α) : p x ↔ p ((of_subtype f : α → α) x) := if h : p x then by dsimp [of_subtype]; simpa [h] using (f ⟨x, h⟩).2 else by simp [h, of_subtype_apply_of_not_mem f h] @[simp] lemma subtype_perm_of_subtype {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) : subtype_perm (of_subtype f) (mem_iff_of_subtype_apply_mem f) = f := equiv.ext $ λ ⟨x, hx⟩, by dsimp [subtype_perm, of_subtype]; simp [show p x, from hx] lemma pow_apply_eq_self_of_apply_eq_self {f : perm α} {x : α} (hfx : f x = x) : ∀ n : ℕ, (f ^ n) x = x | 0 := rfl | (n+1) := by rw [pow_succ', mul_apply, hfx, pow_apply_eq_self_of_apply_eq_self] lemma gpow_apply_eq_self_of_apply_eq_self {f : perm α} {x : α} (hfx : f x = x) : ∀ n : ℤ, (f ^ n) x = x | (n : ℕ) := pow_apply_eq_self_of_apply_eq_self hfx n | -[1+ n] := by rw [gpow_neg_succ_of_nat, inv_eq_iff_eq, pow_apply_eq_self_of_apply_eq_self hfx] lemma pow_apply_eq_of_apply_apply_eq_self {f : perm α} {x : α} (hffx : f (f x) = x) : ∀ n : ℕ, (f ^ n) x = x ∨ (f ^ n) x = f x | 0 := or.inl rfl | (n+1) := (pow_apply_eq_of_apply_apply_eq_self n).elim (λ h, or.inr (by rw [pow_succ, mul_apply, h])) (λ h, or.inl (by rw [pow_succ, mul_apply, h, hffx])) lemma gpow_apply_eq_of_apply_apply_eq_self {f : perm α} {x : α} (hffx : f (f x) = x) : ∀ i : ℤ, (f ^ i) x = x ∨ (f ^ i) x = f x | (n : ℕ) := pow_apply_eq_of_apply_apply_eq_self hffx n | -[1+ n] := by rw [gpow_neg_succ_of_nat, inv_eq_iff_eq, ← injective.eq_iff f.injective, ← mul_apply, ← pow_succ, eq_comm, inv_eq_iff_eq, ← mul_apply, ← pow_succ', @eq_comm _ x, or.comm]; exact pow_apply_eq_of_apply_apply_eq_self hffx _ variable [decidable_eq α] def support [fintype α] (f : perm α) := univ.filter (λ x, f x ≠ x) @[simp] lemma mem_support [fintype α] {f : perm α} {x : α} : x ∈ f.support ↔ f x ≠ x := by simp [support] def is_swap (f : perm α) := ∃ x y, x ≠ y ∧ f = swap x y lemma swap_mul_eq_mul_swap (f : perm α) (x y : α) : swap x y * f = f * swap (f⁻¹ x) (f⁻¹ y) := equiv.ext $ λ z, begin simp [mul_apply, swap_apply_def], split_ifs; simp [*, eq_inv_iff_eq] at * <|> cc end lemma mul_swap_eq_swap_mul (f : perm α) (x y : α) : f * swap x y = swap (f x) (f y) * f := by rw [swap_mul_eq_mul_swap, inv_apply_self, inv_apply_self] /-- Multiplying a permutation with `swap i j` twice gives the original permutation. This specialization of `swap_mul_self` is useful when using cosets of permutations. -/ @[simp] lemma swap_mul_self_mul (i j : α) (σ : perm α) : equiv.swap i j * (equiv.swap i j * σ) = σ := by rw [←mul_assoc (swap i j) (swap i j) σ, equiv.swap_mul_self, one_mul] lemma swap_mul_eq_iff {i j : α} {σ : perm α} : swap i j * σ = σ ↔ i = j := ⟨(assume h, have swap_id : swap i j = 1 := mul_right_cancel (trans h (one_mul σ).symm), by {rw [←swap_apply_right i j, swap_id], refl}), (assume h, by erw [h, swap_self, one_mul])⟩ lemma is_swap_of_subtype {p : α → Prop} [decidable_pred p] {f : perm (subtype p)} (h : is_swap f) : is_swap (of_subtype f) := let ⟨⟨x, hx⟩, ⟨y, hy⟩, hxy⟩ := h in ⟨x, y, by simp at hxy; tauto, equiv.ext $ λ z, begin rw [hxy.2, of_subtype], simp [swap_apply_def], split_ifs; cc <|> simp * at * end⟩ lemma ne_and_ne_of_swap_mul_apply_ne_self {f : perm α} {x y : α} (hy : (swap x (f x) * f) y ≠ y) : f y ≠ y ∧ y ≠ x := begin simp only [swap_apply_def, mul_apply, injective.eq_iff f.injective] at *, by_cases h : f y = x, { split; intro; simp * at * }, { split_ifs at hy; cc } end lemma support_swap_mul_eq [fintype α] {f : perm α} {x : α} (hffx : f (f x) ≠ x) : (swap x (f x) * f).support = f.support.erase x := have hfx : f x ≠ x, from λ hfx, by simpa [hfx] using hffx, finset.ext $ λ y, ⟨λ hy, have hy' : (swap x (f x) * f) y ≠ y, from mem_support.1 hy, mem_erase.2 ⟨λ hyx, by simp [hyx, mul_apply, *] at *, mem_support.2 $ λ hfy, by simp only [mul_apply, swap_apply_def, hfy] at hy'; split_ifs at hy'; simp * at *⟩, λ hy, by simp only [mem_erase, mem_support, swap_apply_def, mul_apply] at *; intro; split_ifs at *; simp * at *⟩ lemma card_support_swap_mul [fintype α] {f : perm α} {x : α} (hx : f x ≠ x) : (swap x (f x) * f).support.card < f.support.card := finset.card_lt_card ⟨λ z hz, mem_support.2 (ne_and_ne_of_swap_mul_apply_ne_self (mem_support.1 hz)).1, λ h, absurd (h (mem_support.2 hx)) (mt mem_support.1 (by simp))⟩ def swap_factors_aux : Π (l : list α) (f : perm α), (∀ {x}, f x ≠ x → x ∈ l) → {l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} | [] := λ f h, ⟨[], equiv.ext $ λ x, by rw [list.prod_nil]; exact eq.symm (not_not.1 (mt h (list.not_mem_nil _))), by simp⟩ | (x :: l) := λ f h, if hfx : x = f x then swap_factors_aux l f (λ y hy, list.mem_of_ne_of_mem (λ h : y = x, by simpa [h, hfx.symm] using hy) (h hy)) else let m := swap_factors_aux l (swap x (f x) * f) (λ y hy, have f y ≠ y ∧ y ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hy, list.mem_of_ne_of_mem this.2 (h this.1)) in ⟨swap x (f x) :: m.1, by rw [list.prod_cons, m.2.1, ← mul_assoc, mul_def (swap x (f x)), swap_swap, ← one_def, one_mul], λ g hg, ((list.mem_cons_iff _ _ _).1 hg).elim (λ h, ⟨x, f x, hfx, h⟩) (m.2.2 _)⟩ /-- `swap_factors` represents a permutation as a product of a list of transpositions. The representation is non unique and depends on the linear order structure. For types without linear order `trunc_swap_factors` can be used -/ def swap_factors [fintype α] [decidable_linear_order α] (f : perm α) : {l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} := swap_factors_aux ((@univ α _).sort (≤)) f (λ _ _, (mem_sort _).2 (mem_univ _)) def trunc_swap_factors [fintype α] (f : perm α) : trunc {l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} := quotient.rec_on_subsingleton (@univ α _).1 (λ l h, trunc.mk (swap_factors_aux l f h)) (show ∀ x, f x ≠ x → x ∈ (@univ α _).1, from λ _ _, mem_univ _) @[elab_as_eliminator] lemma swap_induction_on [fintype α] {P : perm α → Prop} (f : perm α) : P 1 → (∀ f x y, x ≠ y → P f → P (swap x y * f)) → P f := begin cases trunc.out (trunc_swap_factors f) with l hl, induction l with g l ih generalizing f, { simp [hl.1.symm] {contextual := tt} }, { assume h1 hmul_swap, rcases hl.2 g (by simp) with ⟨x, y, hxy⟩, rw [← hl.1, list.prod_cons, hxy.2], exact hmul_swap _ _ _ hxy.1 (ih _ ⟨rfl, λ v hv, hl.2 _ (list.mem_cons_of_mem _ hv)⟩ h1 hmul_swap) } end lemma swap_mul_swap_mul_swap {x y z : α} (hwz: x ≠ y) (hxz : x ≠ z) : swap y z * swap x y * swap y z = swap z x := equiv.ext $ λ n, by simp only [swap_apply_def, mul_apply]; split_ifs; cc lemma is_conj_swap {w x y z : α} (hwx : w ≠ x) (hyz : y ≠ z) : is_conj (swap w x) (swap y z) := have h : ∀ {y z : α}, y ≠ z → w ≠ z → (swap w y * swap x z) * swap w x * (swap w y * swap x z)⁻¹ = swap y z := λ y z hyz hwz, by rw [mul_inv_rev, swap_inv, swap_inv, mul_assoc (swap w y), mul_assoc (swap w y), ← mul_assoc _ (swap x z), swap_mul_swap_mul_swap hwx hwz, ← mul_assoc, swap_mul_swap_mul_swap hwz.symm hyz.symm], if hwz : w = z then have hwy : w ≠ y, by cc, ⟨swap w z * swap x y, by rw [swap_comm y z, h hyz.symm hwy]⟩ else ⟨swap w y * swap x z, h hyz hwz⟩ /-- set of all pairs (⟨a, b⟩ : Σ a : fin n, fin n) such that b < a -/ def fin_pairs_lt (n : ℕ) : finset (Σ a : fin n, fin n) := (univ : finset (fin n)).sigma (λ a, (range a.1).attach_fin (λ m hm, lt_trans (mem_range.1 hm) a.2)) lemma mem_fin_pairs_lt {n : ℕ} {a : Σ a : fin n, fin n} : a ∈ fin_pairs_lt n ↔ a.2 < a.1 := by simp [fin_pairs_lt, fin.lt_def] def sign_aux {n : ℕ} (a : perm (fin n)) : units ℤ := ∏ x in fin_pairs_lt n, if a x.1 ≤ a x.2 then -1 else 1 @[simp] lemma sign_aux_one (n : ℕ) : sign_aux (1 : perm (fin n)) = 1 := begin unfold sign_aux, conv { to_rhs, rw ← @finset.prod_const_one _ (units ℤ) (fin_pairs_lt n) }, exact finset.prod_congr rfl (λ a ha, if_neg (not_le_of_gt (mem_fin_pairs_lt.1 ha))) end def sign_bij_aux {n : ℕ} (f : perm (fin n)) (a : Σ a : fin n, fin n) : Σ a : fin n, fin n := if hxa : f a.2 < f a.1 then ⟨f a.1, f a.2⟩ else ⟨f a.2, f a.1⟩ lemma sign_bij_aux_inj {n : ℕ} {f : perm (fin n)} : ∀ a b : Σ a : fin n, fin n, a ∈ fin_pairs_lt n → b ∈ fin_pairs_lt n → sign_bij_aux f a = sign_bij_aux f b → a = b := λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h, begin unfold sign_bij_aux at h, rw mem_fin_pairs_lt at *, have : ¬b₁ < b₂ := not_lt_of_ge (le_of_lt hb), split_ifs at h; simp [*, injective.eq_iff f.injective, sigma.mk.inj_eq] at * end lemma sign_bij_aux_surj {n : ℕ} {f : perm (fin n)} : ∀ a ∈ fin_pairs_lt n, ∃ b ∈ fin_pairs_lt n, a = sign_bij_aux f b := λ ⟨a₁, a₂⟩ ha, if hxa : f⁻¹ a₂ < f⁻¹ a₁ then ⟨⟨f⁻¹ a₁, f⁻¹ a₂⟩, mem_fin_pairs_lt.2 hxa, by dsimp [sign_bij_aux]; rw [apply_inv_self, apply_inv_self, dif_pos (mem_fin_pairs_lt.1 ha)]⟩ else ⟨⟨f⁻¹ a₂, f⁻¹ a₁⟩, mem_fin_pairs_lt.2 $ lt_of_le_of_ne (le_of_not_gt hxa) $ λ h, by simpa [mem_fin_pairs_lt, (f⁻¹).injective h, lt_irrefl] using ha, by dsimp [sign_bij_aux]; rw [apply_inv_self, apply_inv_self, dif_neg (not_lt_of_ge (le_of_lt (mem_fin_pairs_lt.1 ha)))]⟩ lemma sign_bij_aux_mem {n : ℕ} {f : perm (fin n)}: ∀ a : Σ a : fin n, fin n, a ∈ fin_pairs_lt n → sign_bij_aux f a ∈ fin_pairs_lt n := λ ⟨a₁, a₂⟩ ha, begin unfold sign_bij_aux, split_ifs with h, { exact mem_fin_pairs_lt.2 h }, { exact mem_fin_pairs_lt.2 (lt_of_le_of_ne (le_of_not_gt h) (λ h, ne_of_lt (mem_fin_pairs_lt.1 ha) (f.injective h.symm))) } end @[simp] lemma sign_aux_inv {n : ℕ} (f : perm (fin n)) : sign_aux f⁻¹ = sign_aux f := prod_bij (λ a ha, sign_bij_aux f⁻¹ a) sign_bij_aux_mem (λ ⟨a, b⟩ hab, if h : f⁻¹ b < f⁻¹ a then by rw [sign_bij_aux, dif_pos h, if_neg (not_le_of_gt h), apply_inv_self, apply_inv_self, if_neg (not_le_of_gt $ mem_fin_pairs_lt.1 hab)] else by rw [sign_bij_aux, if_pos (le_of_not_gt h), dif_neg h, apply_inv_self, apply_inv_self, if_pos (le_of_lt $ mem_fin_pairs_lt.1 hab)]) sign_bij_aux_inj sign_bij_aux_surj lemma sign_aux_mul {n : ℕ} (f g : perm (fin n)) : sign_aux (f * g) = sign_aux f * sign_aux g := begin rw ← sign_aux_inv g, unfold sign_aux, rw ← prod_mul_distrib, refine prod_bij (λ a ha, sign_bij_aux g a) sign_bij_aux_mem _ sign_bij_aux_inj sign_bij_aux_surj, rintros ⟨a, b⟩ hab, rw [sign_bij_aux, mul_apply, mul_apply], rw mem_fin_pairs_lt at hab, by_cases h : g b < g a, { rw dif_pos h, simp [not_le_of_gt hab]; congr }, { rw [dif_neg h, inv_apply_self, inv_apply_self, if_pos (le_of_lt hab)], by_cases h₁ : f (g b) ≤ f (g a), { have : f (g b) ≠ f (g a), { rw [ne.def, injective.eq_iff f.injective, injective.eq_iff g.injective]; exact ne_of_lt hab }, rw [if_pos h₁, if_neg (not_le_of_gt (lt_of_le_of_ne h₁ this))], refl }, { rw [if_neg h₁, if_pos (le_of_lt (lt_of_not_ge h₁))], refl } } end private lemma sign_aux_swap_zero_one {n : ℕ} (hn : 2 ≤ n) : sign_aux (swap (⟨0, lt_of_lt_of_le dec_trivial hn⟩ : fin n) ⟨1, lt_of_lt_of_le dec_trivial hn⟩) = -1 := let zero : fin n := ⟨0, lt_of_lt_of_le dec_trivial hn⟩ in let one : fin n := ⟨1, lt_of_lt_of_le dec_trivial hn⟩ in have hzo : zero < one := dec_trivial, show _ = ∏ x : Σ a : fin n, fin n in {(⟨one, zero⟩ : Σ a : fin n, fin n)}, if (equiv.swap zero one) x.1 ≤ swap zero one x.2 then (-1 : units ℤ) else 1, begin refine eq.symm (prod_subset (λ ⟨x₁, x₂⟩, by simp [mem_fin_pairs_lt, hzo] {contextual := tt}) (λ a ha₁ ha₂, _)), rcases a with ⟨⟨a₁, ha₁⟩, ⟨a₂, ha₂⟩⟩, replace ha₁ : a₂ < a₁ := mem_fin_pairs_lt.1 ha₁, simp only [swap_apply_def], have : ¬ 1 ≤ a₂ → a₂ = 0, from λ h, nat.le_zero_iff.1 (nat.le_of_lt_succ (lt_of_not_ge h)), have : a₁ ≤ 1 → a₁ = 0 ∨ a₁ = 1, from nat.cases_on a₁ (λ _, or.inl rfl) (λ a₁, nat.cases_on a₁ (λ _, or.inr rfl) (λ _ h, absurd h dec_trivial)), split_ifs; simp [*, lt_irrefl, -not_lt, not_le.symm, -not_le, le_refl, fin.lt_def, fin.le_def, nat.zero_le, zero, one, iff.intro fin.veq_of_eq fin.eq_of_veq, nat.le_zero_iff] at *, end lemma sign_aux_swap : ∀ {n : ℕ} {x y : fin n} (hxy : x ≠ y), sign_aux (swap x y) = -1 | 0 := dec_trivial | 1 := dec_trivial | (n+2) := λ x y hxy, have h2n : 2 ≤ n + 2 := dec_trivial, by rw [← is_conj_iff_eq, ← sign_aux_swap_zero_one h2n]; exact (monoid_hom.mk' sign_aux sign_aux_mul).map_is_conj (is_conj_swap hxy dec_trivial) def sign_aux2 : list α → perm α → units ℤ | [] f := 1 | (x::l) f := if x = f x then sign_aux2 l f else -sign_aux2 l (swap x (f x) * f) lemma sign_aux_eq_sign_aux2 {n : ℕ} : ∀ (l : list α) (f : perm α) (e : α ≃ fin n) (h : ∀ x, f x ≠ x → x ∈ l), sign_aux ((e.symm.trans f).trans e) = sign_aux2 l f | [] f e h := have f = 1, from equiv.ext $ λ y, not_not.1 (mt (h y) (list.not_mem_nil _)), by rw [this, one_def, equiv.trans_refl, equiv.symm_trans, ← one_def, sign_aux_one, sign_aux2] | (x::l) f e h := begin rw sign_aux2, by_cases hfx : x = f x, { rw if_pos hfx, exact sign_aux_eq_sign_aux2 l f _ (λ y (hy : f y ≠ y), list.mem_of_ne_of_mem (λ h : y = x, by simpa [h, hfx.symm] using hy) (h y hy) ) }, { have hy : ∀ y : α, (swap x (f x) * f) y ≠ y → y ∈ l, from λ y hy, have f y ≠ y ∧ y ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hy, list.mem_of_ne_of_mem this.2 (h _ this.1), have : (e.symm.trans (swap x (f x) * f)).trans e = (swap (e x) (e (f x))) * (e.symm.trans f).trans e, by ext; simp [← equiv.symm_trans_swap_trans, mul_def], have hefx : e x ≠ e (f x), from mt (injective.eq_iff e.injective).1 hfx, rw [if_neg hfx, ← sign_aux_eq_sign_aux2 _ _ e hy, this, sign_aux_mul, sign_aux_swap hefx], simp } end def sign_aux3 [fintype α] (f : perm α) {s : multiset α} : (∀ x, x ∈ s) → units ℤ := quotient.hrec_on s (λ l h, sign_aux2 l f) (trunc.induction_on (equiv_fin α) (λ e l₁ l₂ h, function.hfunext (show (∀ x, x ∈ l₁) = ∀ x, x ∈ l₂, by simp only [h.mem_iff]) (λ h₁ h₂ _, by rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, h₁ _), ← sign_aux_eq_sign_aux2 _ _ e (λ _ _, h₂ _)]))) lemma sign_aux3_mul_and_swap [fintype α] (f g : perm α) (s : multiset α) (hs : ∀ x, x ∈ s) : sign_aux3 (f * g) hs = sign_aux3 f hs * sign_aux3 g hs ∧ ∀ x y, x ≠ y → sign_aux3 (swap x y) hs = -1 := let ⟨l, hl⟩ := quotient.exists_rep s in let ⟨e, _⟩ := trunc.exists_rep (equiv_fin α) in begin clear _let_match _let_match, subst hl, show sign_aux2 l (f * g) = sign_aux2 l f * sign_aux2 l g ∧ ∀ x y, x ≠ y → sign_aux2 l (swap x y) = -1, have hfg : (e.symm.trans (f * g)).trans e = (e.symm.trans f).trans e * (e.symm.trans g).trans e, from equiv.ext (λ h, by simp [mul_apply]), split, { rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), ← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), ← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), hfg, sign_aux_mul] }, { assume x y hxy, have hexy : e x ≠ e y, from mt (injective.eq_iff e.injective).1 hxy, rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), equiv.symm_trans_swap_trans, sign_aux_swap hexy] } end /-- `sign` of a permutation returns the signature or parity of a permutation, `1` for even permutations, `-1` for odd permutations. It is the unique surjective group homomorphism from `perm α` to the group with two elements.-/ def sign [fintype α] : perm α →* units ℤ := monoid_hom.mk' (λ f, sign_aux3 f mem_univ) (λ f g, (sign_aux3_mul_and_swap f g _ mem_univ).1) section sign variable [fintype α] @[simp] lemma sign_mul (f g : perm α) : sign (f * g) = sign f * sign g := monoid_hom.map_mul sign f g @[simp] lemma sign_one : (sign (1 : perm α)) = 1 := monoid_hom.map_one sign @[simp] lemma sign_refl : sign (equiv.refl α) = 1 := monoid_hom.map_one sign @[simp] lemma sign_inv (f : perm α) : sign f⁻¹ = sign f := by rw [monoid_hom.map_inv sign f, int.units_inv_eq_self] lemma sign_swap {x y : α} (h : x ≠ y) : sign (swap x y) = -1 := (sign_aux3_mul_and_swap 1 1 _ mem_univ).2 x y h @[simp] lemma sign_swap' {x y : α} : (swap x y).sign = if x = y then 1 else -1 := if H : x = y then by simp [H, swap_self] else by simp [sign_swap H, H] lemma sign_eq_of_is_swap {f : perm α} (h : is_swap f) : sign f = -1 := let ⟨x, y, hxy⟩ := h in hxy.2.symm ▸ sign_swap hxy.1 lemma sign_aux3_symm_trans_trans [decidable_eq β] [fintype β] (f : perm α) (e : α ≃ β) {s : multiset α} {t : multiset β} (hs : ∀ x, x ∈ s) (ht : ∀ x, x ∈ t) : sign_aux3 ((e.symm.trans f).trans e) ht = sign_aux3 f hs := quotient.induction_on₂ t s (λ l₁ l₂ h₁ h₂, show sign_aux2 _ _ = sign_aux2 _ _, from let n := trunc.out (equiv_fin β) in by rw [← sign_aux_eq_sign_aux2 _ _ n (λ _ _, h₁ _), ← sign_aux_eq_sign_aux2 _ _ (e.trans n) (λ _ _, h₂ _)]; exact congr_arg sign_aux (equiv.ext (λ x, by simp))) ht hs lemma sign_symm_trans_trans [decidable_eq β] [fintype β] (f : perm α) (e : α ≃ β) : sign ((e.symm.trans f).trans e) = sign f := sign_aux3_symm_trans_trans f e mem_univ mem_univ lemma sign_prod_list_swap {l : list (perm α)} (hl : ∀ g ∈ l, is_swap g) : sign l.prod = (-1) ^ l.length := have h₁ : l.map sign = list.repeat (-1) l.length := list.eq_repeat.2 ⟨by simp, λ u hu, let ⟨g, hg⟩ := list.mem_map.1 hu in hg.2 ▸ sign_eq_of_is_swap (hl _ hg.1)⟩, by rw [← list.prod_repeat, ← h₁, list.prod_hom _ (@sign α _ _)] lemma sign_surjective (hα : 1 < fintype.card α) : function.surjective (sign : perm α → units ℤ) := λ a, (int.units_eq_one_or a).elim (λ h, ⟨1, by simp [h]⟩) (λ h, let ⟨x⟩ := fintype.card_pos_iff.1 (lt_trans zero_lt_one hα) in let ⟨y, hxy⟩ := fintype.exists_ne_of_one_lt_card hα x in ⟨swap y x, by rw [sign_swap hxy, h]⟩ ) lemma eq_sign_of_surjective_hom {s : perm α →* units ℤ} (hs : surjective s) : s = sign := have ∀ {f}, is_swap f → s f = -1 := λ f ⟨x, y, hxy, hxy'⟩, hxy'.symm ▸ by_contradiction (λ h, have ∀ f, is_swap f → s f = 1 := λ f ⟨a, b, hab, hab'⟩, by rw [← is_conj_iff_eq, ← or.resolve_right (int.units_eq_one_or _) h, hab']; exact (monoid_hom.of s).map_is_conj (is_conj_swap hab hxy), let ⟨g, hg⟩ := hs (-1) in let ⟨l, hl⟩ := trunc.out (trunc_swap_factors g) in have ∀ a ∈ l.map s, a = (1 : units ℤ) := λ a ha, let ⟨g, hg⟩ := list.mem_map.1 ha in hg.2 ▸ this _ (hl.2 _ hg.1), have s l.prod = 1, by rw [← l.prod_hom s, list.eq_repeat'.2 this, list.prod_repeat, one_pow], by rw [hl.1, hg] at this; exact absurd this dec_trivial), monoid_hom.ext $ λ f, let ⟨l, hl₁, hl₂⟩ := trunc.out (trunc_swap_factors f) in have hsl : ∀ a ∈ l.map s, a = (-1 : units ℤ) := λ a ha, let ⟨g, hg⟩ := list.mem_map.1 ha in hg.2 ▸ this (hl₂ _ hg.1), by rw [← hl₁, ← l.prod_hom s, list.eq_repeat'.2 hsl, list.length_map, list.prod_repeat, sign_prod_list_swap hl₂] lemma sign_subtype_perm (f : perm α) {p : α → Prop} [decidable_pred p] (h₁ : ∀ x, p x ↔ p (f x)) (h₂ : ∀ x, f x ≠ x → p x) : sign (subtype_perm f h₁) = sign f := let l := trunc.out (trunc_swap_factors (subtype_perm f h₁)) in have hl' : ∀ g' ∈ l.1.map of_subtype, is_swap g' := λ g' hg', let ⟨g, hg⟩ := list.mem_map.1 hg' in hg.2 ▸ is_swap_of_subtype (l.2.2 _ hg.1), have hl'₂ : (l.1.map of_subtype).prod = f, by rw [l.1.prod_hom of_subtype, l.2.1, of_subtype_subtype_perm _ h₂], by conv {congr, rw ← l.2.1, skip, rw ← hl'₂}; rw [sign_prod_list_swap l.2.2, sign_prod_list_swap hl', list.length_map] @[simp] lemma sign_of_subtype {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) : sign (of_subtype f) = sign f := have ∀ x, of_subtype f x ≠ x → p x, from λ x, not_imp_comm.1 (of_subtype_apply_of_not_mem f), by conv {to_rhs, rw [← subtype_perm_of_subtype f, sign_subtype_perm _ _ this]} lemma sign_eq_sign_of_equiv [decidable_eq β] [fintype β] (f : perm α) (g : perm β) (e : α ≃ β) (h : ∀ x, e (f x) = g (e x)) : sign f = sign g := have hg : g = (e.symm.trans f).trans e, from equiv.ext $ by simp [h], by rw [hg, sign_symm_trans_trans] lemma sign_bij [decidable_eq β] [fintype β] {f : perm α} {g : perm β} (i : Π x : α, f x ≠ x → β) (h : ∀ x hx hx', i (f x) hx' = g (i x hx)) (hi : ∀ x₁ x₂ hx₁ hx₂, i x₁ hx₁ = i x₂ hx₂ → x₁ = x₂) (hg : ∀ y, g y ≠ y → ∃ x hx, i x hx = y) : sign f = sign g := calc sign f = sign (@subtype_perm _ f (λ x, f x ≠ x) (by simp)) : eq.symm (sign_subtype_perm _ _ (λ _, id)) ... = sign (@subtype_perm _ g (λ x, g x ≠ x) (by simp)) : sign_eq_sign_of_equiv _ _ (equiv.of_bijective (λ x : {x // f x ≠ x}, (⟨i x.1 x.2, have f (f x) ≠ f x, from mt (λ h, f.injective h) x.2, by rw [← h _ x.2 this]; exact mt (hi _ _ this x.2) x.2⟩ : {y // g y ≠ y})) ⟨λ ⟨x, hx⟩ ⟨y, hy⟩ h, subtype.eq (hi _ _ _ _ (subtype.mk.inj h)), λ ⟨y, hy⟩, let ⟨x, hfx, hx⟩ := hg y hy in ⟨⟨x, hfx⟩, subtype.eq hx⟩⟩) (λ ⟨x, _⟩, subtype.eq (h x _ _)) ... = sign g : sign_subtype_perm _ _ (λ _, id) def is_cycle (f : perm β) := ∃ x, f x ≠ x ∧ ∀ y, f y ≠ y → ∃ i : ℤ, (f ^ i) x = y lemma is_cycle_swap {x y : α} (hxy : x ≠ y) : is_cycle (swap x y) := ⟨y, by rwa swap_apply_right, λ a (ha : ite (a = x) y (ite (a = y) x a) ≠ a), if hya : y = a then ⟨0, hya⟩ else ⟨1, by rw [gpow_one, swap_apply_def]; split_ifs at *; cc⟩⟩ lemma is_cycle_inv {f : perm β} (hf : is_cycle f) : is_cycle (f⁻¹) := let ⟨x, hx⟩ := hf in ⟨x, by simp [eq_inv_iff_eq, inv_eq_iff_eq, *] at *; cc, λ y hy, let ⟨i, hi⟩ := hx.2 y (by simp [eq_inv_iff_eq, inv_eq_iff_eq, *] at *; cc) in ⟨-i, by rwa [gpow_neg, inv_gpow, inv_inv]⟩⟩ lemma exists_gpow_eq_of_is_cycle {f : perm β} (hf : is_cycle f) {x y : β} (hx : f x ≠ x) (hy : f y ≠ y) : ∃ i : ℤ, (f ^ i) x = y := let ⟨g, hg⟩ := hf in let ⟨a, ha⟩ := hg.2 x hx in let ⟨b, hb⟩ := hg.2 y hy in ⟨b - a, by rw [← ha, ← mul_apply, ← gpow_add, sub_add_cancel, hb]⟩ lemma is_cycle_swap_mul_aux₁ : ∀ (n : ℕ) {b x : α} {f : perm α} (hb : (swap x (f x) * f) b ≠ b) (h : (f ^ n) (f x) = b), ∃ i : ℤ, ((swap x (f x) * f) ^ i) (f x) = b | 0 := λ b x f hb h, ⟨0, h⟩ | (n+1 : ℕ) := λ b x f hb h, if hfbx : f x = b then ⟨0, hfbx⟩ else have f b ≠ b ∧ b ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hb, have hb' : (swap x (f x) * f) (f⁻¹ b) ≠ f⁻¹ b, by rw [mul_apply, apply_inv_self, swap_apply_of_ne_of_ne this.2 (ne.symm hfbx), ne.def, ← injective.eq_iff f.injective, apply_inv_self]; exact this.1, let ⟨i, hi⟩ := is_cycle_swap_mul_aux₁ n hb' (f.injective $ by rw [apply_inv_self]; rwa [pow_succ, mul_apply] at h) in ⟨i + 1, by rw [add_comm, gpow_add, mul_apply, hi, gpow_one, mul_apply, apply_inv_self, swap_apply_of_ne_of_ne (ne_and_ne_of_swap_mul_apply_ne_self hb).2 (ne.symm hfbx)]⟩ lemma is_cycle_swap_mul_aux₂ : ∀ (n : ℤ) {b x : α} {f : perm α} (hb : (swap x (f x) * f) b ≠ b) (h : (f ^ n) (f x) = b), ∃ i : ℤ, ((swap x (f x) * f) ^ i) (f x) = b | (n : ℕ) := λ b x f, is_cycle_swap_mul_aux₁ n | -[1+ n] := λ b x f hb h, if hfbx : f⁻¹ x = b then ⟨-1, by rwa [gpow_neg, gpow_one, mul_inv_rev, mul_apply, swap_inv, swap_apply_right]⟩ else if hfbx' : f x = b then ⟨0, hfbx'⟩ else have f b ≠ b ∧ b ≠ x := ne_and_ne_of_swap_mul_apply_ne_self hb, have hb : (swap x (f⁻¹ x) * f⁻¹) (f⁻¹ b) ≠ f⁻¹ b, by rw [mul_apply, swap_apply_def]; split_ifs; simp [inv_eq_iff_eq, eq_inv_iff_eq] at *; cc, let ⟨i, hi⟩ := is_cycle_swap_mul_aux₁ n hb (show (f⁻¹ ^ n) (f⁻¹ x) = f⁻¹ b, by rw [← gpow_coe_nat, ← h, ← mul_apply, ← mul_apply, ← mul_apply, gpow_neg_succ_of_nat, ← inv_pow, pow_succ', mul_assoc, mul_assoc, inv_mul_self, mul_one, gpow_coe_nat, ← pow_succ', ← pow_succ]) in have h : (swap x (f⁻¹ x) * f⁻¹) (f x) = f⁻¹ x, by rw [mul_apply, inv_apply_self, swap_apply_left], ⟨-i, by rw [← add_sub_cancel i 1, neg_sub, sub_eq_add_neg, gpow_add, gpow_one, gpow_neg, ← inv_gpow, mul_inv_rev, swap_inv, mul_swap_eq_swap_mul, inv_apply_self, swap_comm _ x, gpow_add, gpow_one, mul_apply, mul_apply (_ ^ i), h, hi, mul_apply, apply_inv_self, swap_apply_of_ne_of_ne this.2 (ne.symm hfbx')]⟩ lemma eq_swap_of_is_cycle_of_apply_apply_eq_self {f : perm α} (hf : is_cycle f) {x : α} (hfx : f x ≠ x) (hffx : f (f x) = x) : f = swap x (f x) := equiv.ext $ λ y, let ⟨z, hz⟩ := hf in let ⟨i, hi⟩ := hz.2 x hfx in if hyx : y = x then by simp [hyx] else if hfyx : y = f x then by simp [hfyx, hffx] else begin rw [swap_apply_of_ne_of_ne hyx hfyx], refine by_contradiction (λ hy, _), cases hz.2 y hy with j hj, rw [← sub_add_cancel j i, gpow_add, mul_apply, hi] at hj, cases gpow_apply_eq_of_apply_apply_eq_self hffx (j - i) with hji hji, { rw [← hj, hji] at hyx, cc }, { rw [← hj, hji] at hfyx, cc } end lemma is_cycle_swap_mul {f : perm α} (hf : is_cycle f) {x : α} (hx : f x ≠ x) (hffx : f (f x) ≠ x) : is_cycle (swap x (f x) * f) := ⟨f x, by simp only [swap_apply_def, mul_apply]; split_ifs; simp [injective.eq_iff f.injective] at *; cc, λ y hy, let ⟨i, hi⟩ := exists_gpow_eq_of_is_cycle hf hx (ne_and_ne_of_swap_mul_apply_ne_self hy).1 in have hi : (f ^ (i - 1)) (f x) = y, from calc (f ^ (i - 1)) (f x) = (f ^ (i - 1) * f ^ (1 : ℤ)) x : by rw [gpow_one, mul_apply] ... = y : by rwa [← gpow_add, sub_add_cancel], is_cycle_swap_mul_aux₂ (i - 1) hy hi⟩ @[simp] lemma support_swap [fintype α] {x y : α} (hxy : x ≠ y) : (swap x y).support = {x, y} := finset.ext $ λ a, by simp [swap_apply_def]; split_ifs; cc lemma card_support_swap [fintype α] {x y : α} (hxy : x ≠ y) : (swap x y).support.card = 2 := show (swap x y).support.card = finset.card ⟨x::y::0, by simp [hxy]⟩, from congr_arg card $ by rw [support_swap hxy]; simp [*, finset.ext_iff]; cc lemma sign_cycle [fintype α] : ∀ {f : perm α} (hf : is_cycle f), sign f = -(-1) ^ f.support.card | f := λ hf, let ⟨x, hx⟩ := hf in calc sign f = sign (swap x (f x) * (swap x (f x) * f)) : by rw [← mul_assoc, mul_def, mul_def, swap_swap, trans_refl] ... = -(-1) ^ f.support.card : if h1 : f (f x) = x then have h : swap x (f x) * f = 1, begin rw eq_swap_of_is_cycle_of_apply_apply_eq_self hf hx.1 h1, simp [mul_def, one_def] end, by rw [sign_mul, sign_swap hx.1.symm, h, sign_one, eq_swap_of_is_cycle_of_apply_apply_eq_self hf hx.1 h1, card_support_swap hx.1.symm]; refl else have h : card (support (swap x (f x) * f)) + 1 = card (support f), by rw [← insert_erase (mem_support.2 hx.1), support_swap_mul_eq h1, card_insert_of_not_mem (not_mem_erase _ _)], have wf : card (support (swap x (f x) * f)) < card (support f), from card_support_swap_mul hx.1, by rw [sign_mul, sign_swap hx.1.symm, sign_cycle (is_cycle_swap_mul hf hx.1 h1), ← h]; simp [pow_add] using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ f, f.support.card)⟩]} end sign end equiv.perm
1bcf9cccce1157cafa3ffaa97000d20610f7439e
618003631150032a5676f229d13a079ac875ff77
/src/algebra/continued_fractions/basic.lean
8d592235e0f05a3c1391eb985bf9f3072d232612
[ "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
13,322
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.seq.seq import algebra.field /-! # Basic Definitions/Theorems for Continued Fractions ## Summary We define generalised, simple, and regular continued fractions and functions to evaluate their convergents. We follow the naming conventions from Wikipedia and [wall2018analytic], Chapter 1. ## Main definitions 1. Generalised continued fractions (gcfs) 2. Simple continued fractions (scfs) 3. (Regular) continued fractions ((r)cfs) 4. Computation of convergents using the recurrence relation in `convergents`. 5. Computation of convergents by directly evaluating the fraction described by the gcf in `convergents'`. ## Implementation notes 1. The most commonly used kind of continued fractions in the literature are regular continued fractions. We hence just call them `continued_fractions` in the library. 2. We use sequences from `data.seq` to encode potentially infinite sequences. ## References - <https://en.wikipedia.org/wiki/Generalized_continued_fraction> - [Wall, H.S., *Analytic Theory of Continued Fractions*][wall2018analytic] ## Tags numerics, number theory, approximations, fractions -/ -- Fix a carrier `α`. variable (α : Type*) /-- We collect a partial numerator `aᵢ` and partial denominator `bᵢ` in a pair `⟨aᵢ,bᵢ⟩`. -/ @[derive inhabited] protected structure generalized_continued_fraction.pair := (a : α) (b : α) /- Interlude: define some expected coercions and instances. -/ namespace generalized_continued_fraction.pair open generalized_continued_fraction as gcf /-- Make a gcf.pair printable. -/ instance [has_repr α] : has_repr (gcf.pair α) := ⟨λ p, "(a : " ++ (repr p.a) ++ ", b : " ++ (repr p.b) ++ ")"⟩ section coe /-! Interlude: define some expected coercions. -/ /- Fix another type `β` and assume `α` can be converted to `β`. -/ variables {α} {β : Type*} [has_coe α β] /-- Coerce a pair by elementwise coercion. -/ instance has_coe_to_generalized_continued_fraction_pair : has_coe (gcf.pair α) (gcf.pair β) := ⟨λ ⟨a, b⟩, ⟨(a : β), (b : β)⟩⟩ @[simp, norm_cast] lemma coe_to_generalized_continued_fraction_pair {a b : α} : (↑(gcf.pair.mk a b) : gcf.pair β) = gcf.pair.mk (a : β) (b : β) := rfl end coe end generalized_continued_fraction.pair /-- A *generalised continued fraction* (gcf) is a potentially infinite expression of the form a₀ h + --------------------------- a₁ b₀ + -------------------- a₂ b₁ + -------------- a₃ b₂ + -------- b₃ + ... where `h` is called the *head term* or *integer part*, the `aᵢ` are called the *partial numerators* and the `bᵢ` the *partial denominators* of the gcf. We store the sequence of partial numerators and denominators in a sequence of generalized_continued_fraction.pairs `s`. For convenience, one often writes `[h; (a₀, b₀), (a₁, b₁), (a₂, b₂),...]`. -/ structure generalized_continued_fraction := (h : α) (s : seq $ generalized_continued_fraction.pair α) variable {α} namespace generalized_continued_fraction open generalized_continued_fraction as gcf /-- Constructs a generalized continued fraction without fractional part. -/ def of_integer (a : α) : gcf α := ⟨a, seq.nil⟩ instance [inhabited α] : inhabited (gcf α) := ⟨of_integer (default _)⟩ /-- Returns the sequence of partial numerators `aᵢ` of `g`. -/ def partial_numerators (g : gcf α) : seq α := g.s.map gcf.pair.a /-- Returns the sequence of partial denominators `bᵢ` of `g`. -/ def partial_denominators (g : gcf α) : seq α := g.s.map gcf.pair.b /-- A gcf terminated at position `n` if its sequence terminates at position `n`. -/ def terminated_at (g : gcf α) (n : ℕ) : Prop := g.s.terminated_at n /-- It is decidable whether a gcf terminated at a given position. -/ instance terminated_at_decidable (g : gcf α) (n : ℕ) : decidable (g.terminated_at n) := by { unfold terminated_at, apply_instance } /-- A gcf terminates if its sequence terminates. -/ def terminates (g : gcf α) : Prop := g.s.terminates section coe /-! Interlude: define some expected coercions. -/ -- Fix another type `β` and assume `α` can be converted to `β`. variables {β : Type*} [has_coe α β] /-- Coerce a sequence by elementwise coercion. -/ def seq.coe_to_seq : has_coe (seq α) (seq β) := ⟨seq.map (λ a, (a : β))⟩ local attribute [instance] seq.coe_to_seq /-- Coerce a gcf by elementwise coercion. -/ instance has_coe_to_generalized_continued_fraction : has_coe (gcf α) (gcf β) := ⟨λ ⟨h, s⟩, ⟨(h : β), (s : seq $ gcf.pair β)⟩⟩ @[simp, norm_cast] lemma coe_to_generalized_continued_fraction {g : gcf α} : (↑(g : gcf α) : gcf β) = ⟨(g.h : β), (g.s : seq $ gcf.pair β)⟩ := by { cases g, refl } end coe end generalized_continued_fraction /-- A generalized continued fraction is a *simple continued fraction* if all partial numerators are equal to one. 1 h + --------------------------- 1 b₀ + -------------------- 1 b₁ + -------------- 1 b₂ + -------- b₃ + ... -/ def generalized_continued_fraction.is_simple_continued_fraction (g : generalized_continued_fraction α) [has_one α] : Prop := ∀ (n : ℕ) (aₙ : α), g.partial_numerators.nth n = some aₙ → aₙ = 1 variable (α) /-- A *simple continued fraction* (scf) is a generalized continued fraction (gcf) whose partial numerators are equal to one. 1 h + --------------------------- 1 b₀ + -------------------- 1 b₁ + -------------- 1 b₂ + -------- b₃ + ... For convenience, one often writes `[h; b₀, b₁, b₂,...]`. It is encoded as the subtype of gcfs that satisfy `generalized_continued_fraction.is_simple_continued_fraction`. -/ def simple_continued_fraction [has_one α] := {g : generalized_continued_fraction α // g.is_simple_continued_fraction} variable {α} /- Interlude: define some expected coercions. -/ namespace simple_continued_fraction open generalized_continued_fraction as gcf open simple_continued_fraction as scf variable [has_one α] /-- Constructs a simple continued fraction without fractional part. -/ def of_integer (a : α) : scf α := ⟨gcf.of_integer a, λ n aₙ h, by cases h⟩ instance : inhabited (scf α) := ⟨of_integer 1⟩ /-- Lift a scf to a gcf using the inclusion map. -/ instance has_coe_to_generalized_continued_fraction : has_coe (scf α) (gcf α) := by {unfold scf, apply_instance} @[simp, norm_cast] lemma coe_to_generalized_continued_fraction {s : scf α} : (↑s : gcf α) = s.val := rfl end simple_continued_fraction /-- A simple continued fraction is a *(regular) continued fraction* ((r)cf) if all partial denominators `bᵢ` are positive, i.e. `0 < bᵢ`. -/ def simple_continued_fraction.is_regular_continued_fraction [has_one α] [has_zero α] [has_lt α] (s : simple_continued_fraction α) : Prop := ∀ (n : ℕ) (bₙ : α), (↑s : generalized_continued_fraction α).partial_denominators.nth n = some bₙ → 0 < bₙ variable (α) /-- A *(regular) continued fraction* ((r)cf) is a simple continued fraction (scf) whose partial denominators are all positive. It is the subtype of scfs that satisfy `simple_continued_fraction.is_regular_continued_fraction`. -/ def continued_fraction [has_one α] [has_zero α] [has_lt α] := {s : simple_continued_fraction α // s.is_regular_continued_fraction} variable {α} /- Interlude: define some expected coercions. -/ namespace continued_fraction open generalized_continued_fraction as gcf open simple_continued_fraction as scf open continued_fraction as cf variables [has_one α] [has_zero α] [has_lt α] /-- Constructs a continued fraction without fractional part. -/ def of_integer (a : α) : cf α := ⟨scf.of_integer a, λ n bₙ h, by cases h⟩ instance : inhabited (cf α) := ⟨of_integer 0⟩ /-- Lift a cf to a scf using the inclusion map. -/ instance has_coe_to_simple_continued_fraction : has_coe (cf α) (scf α) := by {unfold cf, apply_instance} @[simp, norm_cast] lemma coe_to_simple_continued_fraction {c : cf α} : (↑c : scf α) = c.val := rfl /-- Lift a cf to a scf using the inclusion map. -/ instance has_coe_to_generalized_continued_fraction : has_coe (cf α) (gcf α) := ⟨λ c, ↑(↑c : scf α)⟩ @[simp, norm_cast squash] lemma coe_to_generalized_continued_fraction {c : cf α} : (↑c : gcf α) = c.val := rfl end continued_fraction /- We now define how to compute the convergents of a gcf. There are two standard ways to do this: directly evaluating the (infinite) fraction described by the gcf or using a recurrence relation. For (r)cfs, these computations are equivalent as shown in `algebra.continued_fractions.convergents_equiv`. -/ namespace generalized_continued_fraction open generalized_continued_fraction as gcf -- Fix a division ring for the computations. variables {K : Type*} [division_ring K] /- We start with the definition of the recurrence relation. Given a gcf `g`, for all `n ≥ 1`, we define `A₋₁ = 1, A₀ = h, Aₙ = bₙ-₁ * Aₙ₋₁ + aₙ-₁ * Aₙ₋₂`, and `B₋₁ = 0, B₀ = 1, Bₙ = bₙ-₁ * Bₙ₋₁ + aₙ-₁ * Bₙ₋₂`. `Aₙ, `Bₙ` are called the *nth continuants*, Aₙ the *nth numerator*, and `Bₙ` the *nth denominator* of `g`. The *nth convergent* of `g` is given by `Aₙ / Bₙ`. -/ /-- Returns the next numerator `Aₙ = bₙ-₁ * Aₙ₋₁ + aₙ-₁ * Aₙ₋₂`, where `predA` is `Aₙ₋₁`, `ppredA` is `Aₙ₋₂`, `a` is `aₙ₋₁`, and `b` is `bₙ₋₁`. -/ def next_numerator (a b ppredA predA : K) : K := b * predA + a * ppredA /-- Returns the next denominator `Bₙ = bₙ-₁ * Bₙ₋₁ + aₙ-₁ * Bₙ₋₂``, where `predB` is `Bₙ₋₁` and `ppredB` is `Bₙ₋₂`, `a` is `aₙ₋₁`, and `b` is `bₙ₋₁`. -/ def next_denominator (aₙ bₙ ppredB predB : K) : K := bₙ * predB + aₙ * ppredB /-- Returns the next continuants `⟨Aₙ, Bₙ⟩` using `next_numerator` and `next_denominator`, where `pred` is `⟨Aₙ₋₁, Bₙ₋₁⟩`, `ppred` is `⟨Aₙ₋₂, Bₙ₋₂⟩`, `a` is `aₙ₋₁`, and `b` is `bₙ₋₁`. -/ def next_continuants (a b : K) (ppred pred : gcf.pair K) : gcf.pair K := ⟨next_numerator a b ppred.a pred.a, next_denominator a b ppred.b pred.b⟩ /-- Returns the continuants `⟨Aₙ₋₁, Bₙ₋₁⟩` of `g`. -/ def continuants_aux (g : gcf K) : stream (gcf.pair K) | 0 := ⟨1, 0⟩ | 1 := ⟨g.h, 1⟩ | (n + 2) := match g.s.nth n with | none := continuants_aux (n + 1) | some gp := next_continuants gp.a gp.b (continuants_aux n) (continuants_aux $ n + 1) end /-- Returns the continuants `⟨Aₙ, Bₙ⟩` of `g`. -/ def continuants (g : gcf K) : stream (gcf.pair K) := g.continuants_aux.tail /-- Returns the numerators `Aₙ` of `g`. -/ def numerators (g : gcf K) : stream K := g.continuants.map gcf.pair.a /-- Returns the denominators `Bₙ` of `g`. -/ def denominators (g : gcf K) : stream K := g.continuants.map gcf.pair.b /-- Returns the convergents `Aₙ / Bₙ` of `g`, where `Aₙ, Bₙ` are the nth continuants of `g`. -/ def convergents (g : gcf K) : stream K := λ (n : ℕ), (g.numerators n) / (g.denominators n) /-- Returns the approximation of the fraction described by the given sequence up to a given position n. For example, `convergents'_aux [(1, 2), (3, 4), (5, 6)] 2 = 1 / (2 + 3 / 4)` and `convergents'_aux [(1, 2), (3, 4), (5, 6)] 0 = 0`. -/ def convergents'_aux : seq (gcf.pair K) → ℕ → K | s 0 := 0 | s (n + 1) := match s.head with | none := 0 | some gp := gp.a / (gp.b + convergents'_aux s.tail n) end /-- Returns the convergents of `g` by evaluating the fraction described by `g` up to a given position `n`. For example, `convergents' [9; (1, 2), (3, 4), (5, 6)] 2 = 9 + 1 / (2 + 3 / 4)` and `convergents' [9; (1, 2), (3, 4), (5, 6)] 0 = 9` -/ def convergents' (g : gcf K) (n : ℕ) : K := g.h + convergents'_aux g.s n end generalized_continued_fraction -- Now, some basic, general theorems namespace generalized_continued_fraction open generalized_continued_fraction as gcf /-- Two gcfs `g` and `g'` are equal if and only if their components are equal. -/ protected lemma ext_iff {g g' : gcf α} : g = g' ↔ g.h = g'.h ∧ g.s = g'.s := by { cases g, cases g', simp } @[ext] protected lemma ext {g g' : gcf α} (hyp : g.h = g'.h ∧ g.s = g'.s) : g = g' := generalized_continued_fraction.ext_iff.elim_right hyp end generalized_continued_fraction
cf611d7afffc2f8d424721dc1b7a83ba625e17f4
5e3548e65f2c037cb94cd5524c90c623fbd6d46a
/src_icannos_totilas/applications_lineaires/cpge_applin_1_a.lean
e870fbec88e219c44f8e71bb67e3574eb54255db
[]
no_license
ahayat16/lean_exos
d4f08c30adb601a06511a71b5ffb4d22d12ef77f
682f2552d5b04a8c8eb9e4ab15f875a91b03845c
refs/heads/main
1,693,101,073,585
1,636,479,336,000
1,636,479,336,000
415,000,441
0
0
null
null
null
null
UTF-8
Lean
false
false
296
lean
import algebra.module.linear_map import data.real.basic def f (x y z : ℝ) : ℝ := x+y+2*z theorem cpge_applin_1_a [module ℝ (prod ℝ (prod ℝ ℝ))] [E : set (prod ℝ ℝ)]: ∃ g : (linear_map ℝ (prod ℝ (prod ℝ ℝ)) ℝ), ∀ x y z : ℝ , (f x y z) = (g (x, y, z)) := sorry
9d0349bdde791bd453ecde0f057dbdcce9267b67
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Elab/Structure.lean
e60d2f575cd95e66d78e41bf9d9de404ba9eac61
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
45,472
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.Parser.Command import Lean.Meta.Closure import Lean.Meta.SizeOf import Lean.Meta.Injective import Lean.Meta.Structure import Lean.Meta.AppBuilder import Lean.Elab.Command import Lean.Elab.DeclModifiers import Lean.Elab.DeclUtil import Lean.Elab.Inductive import Lean.Elab.DeclarationRange import Lean.Elab.Binders namespace Lean.Elab.Command open Meta open TSyntax.Compat /-! Recall that the `structure command syntax is ``` leading_parser (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional «extends» >> Term.optType >> optional (" := " >> optional structCtor >> structFields) ``` -/ structure StructCtorView where ref : Syntax modifiers : Modifiers name : Name declName : Name structure StructFieldView where ref : Syntax modifiers : Modifiers binderInfo : BinderInfo declName : Name name : Name -- The field name as it is going to be registered in the kernel. It does not include macroscopes. rawName : Name -- Same as `name` but including macroscopes. binders : Syntax type? : Option Syntax value? : Option Syntax structure StructView where ref : Syntax modifiers : Modifiers scopeLevelNames : List Name -- All `universe` declarations in the current scope allUserLevelNames : List Name -- `scopeLevelNames` ++ explicit universe parameters provided in the `structure` command isClass : Bool declName : Name scopeVars : Array Expr -- All `variable` declaration in the current scope params : Array Expr -- Explicit parameters provided in the `structure` command parents : Array Syntax type : Syntax ctor : StructCtorView fields : Array StructFieldView inductive StructFieldKind where | newField | copiedField | fromParent | subobject deriving Inhabited, DecidableEq, Repr structure StructFieldInfo where name : Name declName : Name -- Remark: for `fromParent` fields, `declName` is only relevant in the generation of auxiliary "default value" functions. fvar : Expr kind : StructFieldKind value? : Option Expr := none deriving Inhabited, Repr def StructFieldInfo.isFromParent (info : StructFieldInfo) : Bool := match info.kind with | StructFieldKind.fromParent => true | _ => false def StructFieldInfo.isSubobject (info : StructFieldInfo) : Bool := match info.kind with | StructFieldKind.subobject => true | _ => false structure ElabStructResult where decl : Declaration projInfos : List ProjectionInfo projInstances : List Name -- projections (to parent classes) that must be marked as instances. mctx : MetavarContext lctx : LocalContext localInsts : LocalInstances defaultAuxDecls : Array (Name × Expr × Expr) private def defaultCtorName := `mk /- The structure constructor syntax is ``` leading_parser try (declModifiers >> ident >> " :: ") ``` -/ private def expandCtor (structStx : Syntax) (structModifiers : Modifiers) (structDeclName : Name) : TermElabM StructCtorView := do let useDefault := do let declName := structDeclName ++ defaultCtorName addAuxDeclarationRanges declName structStx[2] structStx[2] pure { ref := structStx, modifiers := {}, name := defaultCtorName, declName } if structStx[5].isNone then useDefault else let optCtor := structStx[5][1] if optCtor.isNone then useDefault else let ctor := optCtor[0] withRef ctor do let ctorModifiers ← elabModifiers ctor[0] checkValidCtorModifier ctorModifiers if ctorModifiers.isPrivate && structModifiers.isPrivate then throwError "invalid 'private' constructor in a 'private' structure" if ctorModifiers.isProtected && structModifiers.isPrivate then throwError "invalid 'protected' constructor in a 'private' structure" let name := ctor[1].getId let declName := structDeclName ++ name let declName ← applyVisibility ctorModifiers.visibility declName addDocString' declName ctorModifiers.docString? addAuxDeclarationRanges declName ctor[1] ctor[1] pure { ref := ctor, name, modifiers := ctorModifiers, declName } def checkValidFieldModifier (modifiers : Modifiers) : TermElabM Unit := do if modifiers.isNoncomputable then throwError "invalid use of 'noncomputable' in field declaration" if modifiers.isPartial then throwError "invalid use of 'partial' in field declaration" if modifiers.isUnsafe then throwError "invalid use of 'unsafe' in field declaration" if modifiers.attrs.size != 0 then throwError "invalid use of attributes in field declaration" /- ``` def structExplicitBinder := leading_parser atomic (declModifiers true >> "(") >> many1 ident >> optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault) >> ")" def structImplicitBinder := leading_parser atomic (declModifiers true >> "{") >> many1 ident >> declSig >> "}" def structInstBinder := leading_parser atomic (declModifiers true >> "[") >> many1 ident >> declSig >> "]" def structSimpleBinder := leading_parser atomic (declModifiers true >> ident) >> optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault) def structFields := leading_parser many (structExplicitBinder <|> structImplicitBinder <|> structInstBinder) ``` -/ private def expandFields (structStx : Syntax) (structModifiers : Modifiers) (structDeclName : Name) : TermElabM (Array StructFieldView) := let fieldBinders := if structStx[5].isNone then #[] else structStx[5][2][0].getArgs fieldBinders.foldlM (init := #[]) fun (views : Array StructFieldView) fieldBinder => withRef fieldBinder do let mut fieldBinder := fieldBinder if fieldBinder.getKind == ``Parser.Command.structSimpleBinder then fieldBinder := mkNode ``Parser.Command.structExplicitBinder #[ fieldBinder[0], mkAtomFrom fieldBinder "(", mkNullNode #[ fieldBinder[1] ], fieldBinder[2], fieldBinder[3], fieldBinder[4], mkAtomFrom fieldBinder ")" ] let k := fieldBinder.getKind let binfo ← if k == ``Parser.Command.structExplicitBinder then pure BinderInfo.default else if k == ``Parser.Command.structImplicitBinder then pure BinderInfo.implicit else if k == ``Parser.Command.structInstBinder then pure BinderInfo.instImplicit else throwError "unexpected kind of structure field" let fieldModifiers ← elabModifiers fieldBinder[0] checkValidFieldModifier fieldModifiers if fieldModifiers.isPrivate && structModifiers.isPrivate then throwError "invalid 'private' field in a 'private' structure" if fieldModifiers.isProtected && structModifiers.isPrivate then throwError "invalid 'protected' field in a 'private' structure" let (binders, type?) ← if binfo == BinderInfo.default then let (binders, type?) := expandOptDeclSig fieldBinder[3] let optBinderTacticDefault := fieldBinder[4] if optBinderTacticDefault.isNone then pure (binders, type?) else if optBinderTacticDefault[0].getKind != ``Parser.Term.binderTactic then pure (binders, type?) else let binderTactic := optBinderTacticDefault[0] match type? with | none => throwErrorAt binderTactic "invalid field declaration, type must be provided when auto-param (tactic) is used" | some type => let tac := binderTactic[2] let name ← Term.declareTacticSyntax tac -- The tactic should be for binders+type. -- It is safe to reset the binders to a "null" node since there is no value to be elaborated let type ← `(forall $(binders.getArgs):bracketedBinder*, $type) let type ← `(autoParam $type $(mkIdentFrom tac name)) pure (mkNullNode, some type.raw) else let (binders, type) := expandDeclSig fieldBinder[3] pure (binders, some type) let value? ← if binfo != BinderInfo.default then pure none else let optBinderTacticDefault := fieldBinder[4] -- trace[Elab.struct] ">>> {optBinderTacticDefault}" if optBinderTacticDefault.isNone then pure none else if optBinderTacticDefault[0].getKind == ``Parser.Term.binderTactic then pure none else -- binderDefault := leading_parser " := " >> termParser pure (some optBinderTacticDefault[0][1]) let idents := fieldBinder[2].getArgs idents.foldlM (init := views) fun (views : Array StructFieldView) ident => withRef ident do let rawName := ident.getId let name := rawName.eraseMacroScopes unless name.isAtomic do throwErrorAt ident "invalid field name '{name.eraseMacroScopes}', field names must be atomic" let declName := structDeclName ++ name let declName ← applyVisibility fieldModifiers.visibility declName addDocString' declName fieldModifiers.docString? return views.push { ref := ident modifiers := fieldModifiers binderInfo := binfo declName name rawName binders type? value? } private def validStructType (type : Expr) : Bool := match type with | Expr.sort .. => true | _ => false private def findFieldInfo? (infos : Array StructFieldInfo) (fieldName : Name) : Option StructFieldInfo := infos.find? fun info => info.name == fieldName private def containsFieldName (infos : Array StructFieldInfo) (fieldName : Name) : Bool := (findFieldInfo? infos fieldName).isSome private def updateFieldInfoVal (infos : Array StructFieldInfo) (fieldName : Name) (value : Expr) : Array StructFieldInfo := infos.map fun info => if info.name == fieldName then { info with value? := value } else info register_builtin_option structureDiamondWarning : Bool := { defValue := false descr := "enable/disable warning messages for structure diamonds" } /-- Return `some fieldName` if field `fieldName` of the parent structure `parentStructName` is already in `infos` -/ private def findExistingField? (infos : Array StructFieldInfo) (parentStructName : Name) : CoreM (Option Name) := do let fieldNames := getStructureFieldsFlattened (← getEnv) parentStructName for fieldName in fieldNames do if containsFieldName infos fieldName then return some fieldName return none private partial def processSubfields (structDeclName : Name) (parentFVar : Expr) (parentStructName : Name) (subfieldNames : Array Name) (infos : Array StructFieldInfo) (k : Array StructFieldInfo → TermElabM α) : TermElabM α := go 0 infos where go (i : Nat) (infos : Array StructFieldInfo) := do if h : i < subfieldNames.size then let subfieldName := subfieldNames.get ⟨i, h⟩ if containsFieldName infos subfieldName then throwError "field '{subfieldName}' from '{parentStructName}' has already been declared" let val ← mkProjection parentFVar subfieldName let type ← inferType val withLetDecl subfieldName type val fun subfieldFVar => /- The following `declName` is only used for creating the `_default` auxiliary declaration name when its default value is overwritten in the structure. If the default value is not overwritten, then its value is irrelevant. -/ let declName := structDeclName ++ subfieldName let infos := infos.push { name := subfieldName, declName, fvar := subfieldFVar, kind := StructFieldKind.fromParent } go (i+1) infos else k infos /-- Given `obj.foo.bar.baz`, return `obj`. -/ private partial def getNestedProjectionArg (e : Expr) : MetaM Expr := do if let Expr.const subProjName .. := e.getAppFn then if let some { numParams, .. } ← getProjectionFnInfo? subProjName then if e.getAppNumArgs == numParams + 1 then return ← getNestedProjectionArg e.appArg! return e /-- Get field type of `fieldName` in `parentType`, but replace references to other fields of that structure by existing field fvars. Auxiliary method for `copyNewFieldsFrom`. -/ private def getFieldType (infos : Array StructFieldInfo) (parentType : Expr) (fieldName : Name) : MetaM Expr := do withLocalDeclD (← mkFreshId) parentType fun parent => do let proj ← mkProjection parent fieldName let projType ← inferType proj /- Eliminate occurrences of `parent.field`. This happens when the structure contains dependent fields. If the copied parent extended another structure via a subobject, then the occurrence can also look like `parent.toGrandparent.field` (where `toGrandparent` is not a field of the current structure). -/ let visit (e : Expr) : MetaM TransformStep := do if let Expr.const subProjName .. := e.getAppFn then if let some { numParams, .. } ← getProjectionFnInfo? subProjName then let Name.str _ subFieldName .. := subProjName | throwError "invalid projection name {subProjName}" let args := e.getAppArgs if let some major := args.get? numParams then if (← getNestedProjectionArg major) == parent then if let some existingFieldInfo := findFieldInfo? infos subFieldName then return TransformStep.done <| mkAppN existingFieldInfo.fvar args[numParams+1:args.size] return TransformStep.done e let projType ← Meta.transform projType (post := visit) if projType.containsFVar parent.fvarId! then throwError "unsupported dependent field in {fieldName} : {projType}" if let some info := getFieldInfo? (← getEnv) (← getStructureName parentType) fieldName then if let some autoParamExpr := info.autoParam? then return (← mkAppM ``autoParam #[projType, autoParamExpr]) return projType private def toVisibility (fieldInfo : StructureFieldInfo) : CoreM Visibility := do if isProtected (← getEnv) fieldInfo.projFn then return Visibility.protected else if isPrivateName fieldInfo.projFn then return Visibility.private else return Visibility.regular abbrev FieldMap := NameMap Expr -- Map from field name to expression representing the field /-- Reduce projetions of the structures in `structNames` -/ private def reduceProjs (e : Expr) (structNames : NameSet) : MetaM Expr := let reduce (e : Expr) : MetaM TransformStep := do match (← reduceProjOf? e structNames.contains) with | some v => return TransformStep.done v | _ => return TransformStep.done e transform e (post := reduce) /-- Copy the default value for field `fieldName` set at structure `structName`. The arguments for the `_default` auxiliary function are provided by `fieldMap`. Recall some of the entries in `fieldMap` are constructor applications, and they needed to be reduced using `reduceProjs`. Otherwise, the produced default value may be "cyclic". That is, we reduce projections of the structures in `expandedStructNames`. Here is an example that shows why the reduction is needed. ``` structure A where a : Nat structure B where a : Nat b : Nat c : Nat structure C extends B where d : Nat c := b + d structure D extends A, C #print D.c._default ``` Without the reduction, it produces ``` def D.c._default : A → Nat → Nat → Nat → Nat := fun toA b c d => id ({ a := toA.a, b := b, c := c : B }.b + d) ``` -/ private partial def copyDefaultValue? (fieldMap : FieldMap) (expandedStructNames : NameSet) (structName : Name) (fieldName : Name) : TermElabM (Option Expr) := do match getDefaultFnForField? (← getEnv) structName fieldName with | none => return none | some defaultFn => let cinfo ← getConstInfo defaultFn let us ← mkFreshLevelMVarsFor cinfo go? (← instantiateValueLevelParams cinfo us) where failed : TermElabM (Option Expr) := do logWarning s!"ignoring default value for field '{fieldName}' defined at '{structName}'" return none go? (e : Expr) : TermElabM (Option Expr) := do match e with | Expr.lam n d b c => if c.isExplicit then match fieldMap.find? n with | none => failed | some val => let valType ← inferType val if (← isDefEq valType d) then go? (b.instantiate1 val) else failed else let arg ← mkFreshExprMVar d go? (b.instantiate1 arg) | e => let r := if e.isAppOfArity ``id 2 then e.appArg! else e return some (← reduceProjs (← instantiateMVars r) expandedStructNames) private partial def copyNewFieldsFrom (structDeclName : Name) (infos : Array StructFieldInfo) (parentType : Expr) (k : Array StructFieldInfo → TermElabM α) : TermElabM α := do copyFields infos {} parentType fun infos _ _ => k infos where copyFields (infos : Array StructFieldInfo) (expandedStructNames : NameSet) (parentType : Expr) (k : Array StructFieldInfo → FieldMap → NameSet → TermElabM α) : TermElabM α := do let parentStructName ← getStructureName parentType let fieldNames := getStructureFields (← getEnv) parentStructName let rec copy (i : Nat) (infos : Array StructFieldInfo) (fieldMap : FieldMap) (expandedStructNames : NameSet) : TermElabM α := do if h : i < fieldNames.size then let fieldName := fieldNames.get ⟨i, h⟩ let fieldType ← getFieldType infos parentType fieldName match findFieldInfo? infos fieldName with | some existingFieldInfo => let existingFieldType ← inferType existingFieldInfo.fvar unless (← isDefEq fieldType existingFieldType) do throwError "parent field type mismatch, field '{fieldName}' from parent '{parentStructName}' {← mkHasTypeButIsExpectedMsg fieldType existingFieldType}" /- Remark: if structure has a default value for this field, it will be set at the `processOveriddenDefaultValues` below. -/ copy (i+1) infos (fieldMap.insert fieldName existingFieldInfo.fvar) expandedStructNames | none => let some fieldInfo := getFieldInfo? (← getEnv) parentStructName fieldName | unreachable! let addNewField : TermElabM α := do let value? ← copyDefaultValue? fieldMap expandedStructNames parentStructName fieldName withLocalDecl fieldName fieldInfo.binderInfo fieldType fun fieldFVar => do let fieldDeclName := structDeclName ++ fieldName let fieldDeclName ← applyVisibility (← toVisibility fieldInfo) fieldDeclName let infos := infos.push { name := fieldName, declName := fieldDeclName, fvar := fieldFVar, value?, kind := StructFieldKind.copiedField } copy (i+1) infos (fieldMap.insert fieldName fieldFVar) expandedStructNames if fieldInfo.subobject?.isSome then let fieldParentStructName ← getStructureName fieldType if (← findExistingField? infos fieldParentStructName).isSome then -- See comment at `copyDefaultValue?` let expandedStructNames := expandedStructNames.insert fieldParentStructName copyFields infos expandedStructNames fieldType fun infos nestedFieldMap expandedStructNames => do let fieldVal ← mkCompositeField fieldType nestedFieldMap copy (i+1) infos (fieldMap.insert fieldName fieldVal) expandedStructNames else let subfieldNames := getStructureFieldsFlattened (← getEnv) fieldParentStructName let fieldName := fieldInfo.fieldName withLocalDecl fieldName fieldInfo.binderInfo fieldType fun parentFVar => let infos := infos.push { name := fieldName, declName := structDeclName ++ fieldName, fvar := parentFVar, kind := StructFieldKind.subobject } processSubfields structDeclName parentFVar fieldParentStructName subfieldNames infos fun infos => copy (i+1) infos (fieldMap.insert fieldName parentFVar) expandedStructNames else addNewField else let infos ← processOveriddenDefaultValues infos fieldMap expandedStructNames parentStructName k infos fieldMap expandedStructNames copy 0 infos {} expandedStructNames processOveriddenDefaultValues (infos : Array StructFieldInfo) (fieldMap : FieldMap) (expandedStructNames : NameSet) (parentStructName : Name) : TermElabM (Array StructFieldInfo) := infos.mapM fun info => do match (← copyDefaultValue? fieldMap expandedStructNames parentStructName info.name) with | some value => return { info with value? := value } | none => return info mkCompositeField (parentType : Expr) (fieldMap : FieldMap) : TermElabM Expr := do let env ← getEnv let Expr.const parentStructName us ← pure parentType.getAppFn | unreachable! let parentCtor := getStructureCtor env parentStructName let mut result := mkAppN (mkConst parentCtor.name us) parentType.getAppArgs for fieldName in getStructureFields env parentStructName do match fieldMap.find? fieldName with | some val => result := mkApp result val | none => throwError "failed to copy fields from parent structure{indentExpr parentType}" -- TODO improve error message return result private partial def mkToParentName (parentStructName : Name) (p : Name → Bool) : Name := Id.run do let base := Name.mkSimple $ "to" ++ parentStructName.eraseMacroScopes.getString! if p base then base else let rec go (i : Nat) : Name := let curr := base.appendIndexAfter i if p curr then curr else go (i+1) go 1 private partial def withParents (view : StructView) (k : Array StructFieldInfo → Array Expr → TermElabM α) : TermElabM α := do go 0 #[] #[] where go (i : Nat) (infos : Array StructFieldInfo) (copiedParents : Array Expr) : TermElabM α := do if h : i < view.parents.size then let parentStx := view.parents.get ⟨i, h⟩ withRef parentStx do let parentType ← Term.elabType parentStx let parentStructName ← getStructureName parentType if let some existingFieldName ← findExistingField? infos parentStructName then if structureDiamondWarning.get (← getOptions) then logWarning s!"field '{existingFieldName}' from '{parentStructName}' has already been declared" copyNewFieldsFrom view.declName infos parentType fun infos => go (i+1) infos (copiedParents.push parentType) -- TODO: if `class`, then we need to create a let-decl that stores the local instance for the `parentStructure` else let env ← getEnv let subfieldNames := getStructureFieldsFlattened env parentStructName let toParentName := mkToParentName parentStructName fun n => !containsFieldName infos n && !subfieldNames.contains n let binfo := if view.isClass && isClass env parentStructName then BinderInfo.instImplicit else BinderInfo.default withLocalDecl toParentName binfo parentType fun parentFVar => let infos := infos.push { name := toParentName, declName := view.declName ++ toParentName, fvar := parentFVar, kind := StructFieldKind.subobject } processSubfields view.declName parentFVar parentStructName subfieldNames infos fun infos => go (i+1) infos copiedParents else k infos copiedParents private def elabFieldTypeValue (view : StructFieldView) : TermElabM (Option Expr × Option Expr) := Term.withAutoBoundImplicit <| Term.withAutoBoundImplicitForbiddenPred (fun n => view.name == n) <| Term.elabBinders view.binders.getArgs fun params => do match view.type? with | none => match view.value? with | none => return (none, none) | some valStx => Term.synthesizeSyntheticMVarsNoPostponing -- TODO: add forbidden predicate using `shortDeclName` from `view` let params ← Term.addAutoBoundImplicits params let value ← Term.withoutAutoBoundImplicit <| Term.elabTerm valStx none let value ← mkLambdaFVars params value return (none, value) | some typeStx => let type ← Term.elabType typeStx Term.synthesizeSyntheticMVarsNoPostponing let params ← Term.addAutoBoundImplicits params match view.value? with | none => let type ← mkForallFVars params type return (type, none) | some valStx => let value ← Term.withoutAutoBoundImplicit <| Term.elabTermEnsuringType valStx type Term.synthesizeSyntheticMVarsNoPostponing let type ← mkForallFVars params type let value ← mkLambdaFVars params value return (type, value) private partial def withFields (views : Array StructFieldView) (infos : Array StructFieldInfo) (k : Array StructFieldInfo → TermElabM α) : TermElabM α := do go 0 {} infos where go (i : Nat) (defaultValsOverridden : NameSet) (infos : Array StructFieldInfo) : TermElabM α := do if h : i < views.size then let view := views.get ⟨i, h⟩ withRef view.ref do match findFieldInfo? infos view.name with | none => let (type?, value?) ← elabFieldTypeValue view match type?, value? with | none, none => throwError "invalid field, type expected" | some type, _ => withLocalDecl view.rawName view.binderInfo type fun fieldFVar => let infos := infos.push { name := view.name, declName := view.declName, fvar := fieldFVar, value? := value?, kind := StructFieldKind.newField } go (i+1) defaultValsOverridden infos | none, some value => let type ← inferType value withLocalDecl view.rawName view.binderInfo type fun fieldFVar => let infos := infos.push { name := view.name, declName := view.declName, fvar := fieldFVar, value? := value, kind := StructFieldKind.newField } go (i+1) defaultValsOverridden infos | some info => let updateDefaultValue : TermElabM α := do match view.value? with | none => throwError "field '{view.name}' has been declared in parent structure" | some valStx => if let some type := view.type? then throwErrorAt type "omit field '{view.name}' type to set default value" else if defaultValsOverridden.contains info.name then throwError "field '{view.name}' new default value has already been set" let defaultValsOverridden := defaultValsOverridden.insert info.name let mut valStx := valStx if view.binders.getArgs.size > 0 then valStx ← `(fun $(view.binders.getArgs)* => $valStx:term) let fvarType ← inferType info.fvar let value ← Term.elabTermEnsuringType valStx fvarType pushInfoLeaf <| .ofFieldRedeclInfo { stx := view.ref } let infos := updateFieldInfoVal infos info.name value go (i+1) defaultValsOverridden infos match info.kind with | StructFieldKind.newField => throwError "field '{view.name}' has already been declared" | StructFieldKind.subobject => throwError "unexpected subobject field reference" -- improve error message | StructFieldKind.copiedField => updateDefaultValue | StructFieldKind.fromParent => updateDefaultValue else k infos private def getResultUniverse (type : Expr) : TermElabM Level := do let type ← whnf type match type with | Expr.sort u => pure u | _ => throwError "unexpected structure resulting type" private def collectUsed (params : Array Expr) (fieldInfos : Array StructFieldInfo) : StateRefT CollectFVars.State MetaM Unit := do params.forM fun p => do let type ← inferType p type.collectFVars fieldInfos.forM fun info => do let fvarType ← inferType info.fvar fvarType.collectFVars match info.value? with | none => pure () | some value => value.collectFVars private def removeUnused (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM (LocalContext × LocalInstances × Array Expr) := do let (_, used) ← (collectUsed params fieldInfos).run {} Meta.removeUnused scopeVars used private def withUsed {α} (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) (k : Array Expr → TermElabM α) : TermElabM α := do let (lctx, localInsts, vars) ← removeUnused scopeVars params fieldInfos withLCtx lctx localInsts <| k vars private def levelMVarToParam (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) (univToInfer? : Option LMVarId) : TermElabM (Array StructFieldInfo) := do levelMVarToParamFVars scopeVars levelMVarToParamFVars params fieldInfos.mapM fun info => do levelMVarToParamFVar info.fvar match info.value? with | none => pure info | some value => let value ← levelMVarToParam' value pure { info with value? := value } where levelMVarToParam' (type : Expr) : TermElabM Expr := do Term.levelMVarToParam type (except := fun mvarId => univToInfer? == some mvarId) levelMVarToParamFVars (fvars : Array Expr) : TermElabM Unit := fvars.forM levelMVarToParamFVar levelMVarToParamFVar (fvar : Expr) : TermElabM Unit := do let type ← inferType fvar discard <| levelMVarToParam' type private partial def collectUniversesFromFields (r : Level) (rOffset : Nat) (fieldInfos : Array StructFieldInfo) : TermElabM (Array Level) := do let (_, us) ← go |>.run #[] return us where go : StateRefT (Array Level) TermElabM Unit := for info in fieldInfos do let type ← inferType info.fvar let u ← getLevel type let u ← instantiateLevelMVars u match (← modifyGet fun s => accLevel u r rOffset |>.run |>.run s) with | some _ => pure () | none => let typeType ← inferType type let mut msg := m!"failed to compute resulting universe level of structure, field '{info.declName}' has type{indentD m!"{type} : {typeType}"}\nstructure resulting type{indentExpr (mkSort (r.addOffset rOffset))}" if r.isMVar then msg := msg ++ "\nrecall that Lean only infers the resulting universe level automatically when there is a unique solution for the universe level constraints, consider explicitly providing the structure resulting universe level" throwError msg private def updateResultingUniverse (fieldInfos : Array StructFieldInfo) (type : Expr) : TermElabM Expr := do let r ← getResultUniverse type let rOffset : Nat := r.getOffset let r : Level := r.getLevelOffset match r with | Level.mvar mvarId => let us ← collectUniversesFromFields r rOffset fieldInfos let rNew := mkResultUniverse us rOffset assignLevelMVar mvarId rNew instantiateMVars type | _ => throwError "failed to compute resulting universe level of structure, provide universe explicitly" private def collectLevelParamsInFVar (s : CollectLevelParams.State) (fvar : Expr) : TermElabM CollectLevelParams.State := do let type ← inferType fvar let type ← instantiateMVars type return collectLevelParams s type private def collectLevelParamsInFVars (fvars : Array Expr) (s : CollectLevelParams.State) : TermElabM CollectLevelParams.State := fvars.foldlM collectLevelParamsInFVar s private def collectLevelParamsInStructure (structType : Expr) (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM (Array Name) := do let s := collectLevelParams {} structType let s ← collectLevelParamsInFVars scopeVars s let s ← collectLevelParamsInFVars params s let s ← fieldInfos.foldlM (init := s) fun s info => collectLevelParamsInFVar s info.fvar return s.params private def addCtorFields (fieldInfos : Array StructFieldInfo) : Nat → Expr → TermElabM Expr | 0, type => pure type | i+1, type => do let info := fieldInfos[i]! let decl ← Term.getFVarLocalDecl! info.fvar let type ← instantiateMVars type let type := type.abstract #[info.fvar] match info.kind with | StructFieldKind.fromParent => let val := decl.value addCtorFields fieldInfos i (type.instantiate1 val) | _ => addCtorFields fieldInfos i (mkForall decl.userName decl.binderInfo decl.type type) private def mkCtor (view : StructView) (levelParams : List Name) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM Constructor := withRef view.ref do let type := mkAppN (mkConst view.declName (levelParams.map mkLevelParam)) params let type ← addCtorFields fieldInfos fieldInfos.size type let type ← mkForallFVars params type let type ← instantiateMVars type let type := type.inferImplicit params.size true pure { name := view.ctor.declName, type } @[extern "lean_mk_projections"] private opaque mkProjections (env : Environment) (structName : Name) (projs : List Name) (isClass : Bool) : Except KernelException Environment private def addProjections (structName : Name) (projs : List Name) (isClass : Bool) : TermElabM Unit := do let env ← getEnv match mkProjections env structName projs isClass with | Except.ok env => setEnv env | Except.error ex => throwKernelException ex private def registerStructure (structName : Name) (infos : Array StructFieldInfo) : TermElabM Unit := do let fields ← infos.filterMapM fun info => do if info.kind == StructFieldKind.fromParent then return none else return some { fieldName := info.name projFn := info.declName binderInfo := (← getFVarLocalDecl info.fvar).binderInfo autoParam? := (← inferType info.fvar).getAutoParamTactic? subobject? := if info.kind == StructFieldKind.subobject then match (← getEnv).find? info.declName with | some (ConstantInfo.defnInfo val) => match val.type.getForallBody.getAppFn with | Expr.const parentName .. => some parentName | _ => panic! "ill-formed structure" | _ => panic! "ill-formed environment" else none } modifyEnv fun env => Lean.registerStructure env { structName, fields } private def mkAuxConstructions (declName : Name) : TermElabM Unit := do let env ← getEnv let hasUnit := env.contains `PUnit let hasEq := env.contains `Eq let hasHEq := env.contains `HEq mkRecOn declName if hasUnit then mkCasesOn declName if hasUnit && hasEq && hasHEq then mkNoConfusion declName private def addDefaults (lctx : LocalContext) (defaultAuxDecls : Array (Name × Expr × Expr)) : TermElabM Unit := do let localInsts ← getLocalInstances withLCtx lctx localInsts do defaultAuxDecls.forM fun (declName, type, value) => do let value ← instantiateMVars value if value.hasExprMVar then throwError "invalid default value for field, it contains metavariables{indentExpr value}" /- The identity function is used as "marker". -/ let value ← mkId value discard <| mkAuxDefinition declName type value (zeta := true) setReducibleAttribute declName private partial def mkCoercionToCopiedParent (levelParams : List Name) (params : Array Expr) (view : StructView) (parentType : Expr) : MetaM Unit := do let env ← getEnv let structName := view.declName let sourceFieldNames := getStructureFieldsFlattened env structName let structType := mkAppN (Lean.mkConst structName (levelParams.map mkLevelParam)) params let Expr.const parentStructName _ ← pure parentType.getAppFn | unreachable! let binfo := if view.isClass && isClass env parentStructName then BinderInfo.instImplicit else BinderInfo.default withLocalDecl `self binfo structType fun source => do let declType ← instantiateMVars (← mkForallFVars params (← mkForallFVars #[source] parentType)) let declType := declType.inferImplicit params.size true let rec copyFields (parentType : Expr) : MetaM Expr := do let Expr.const parentStructName us ← pure parentType.getAppFn | unreachable! let parentCtor := getStructureCtor env parentStructName let mut result := mkAppN (mkConst parentCtor.name us) parentType.getAppArgs for fieldName in getStructureFields env parentStructName do if sourceFieldNames.contains fieldName then let fieldVal ← mkProjection source fieldName result := mkApp result fieldVal else -- fieldInfo must be a field of `parentStructName` let some fieldInfo := getFieldInfo? env parentStructName fieldName | unreachable! if fieldInfo.subobject?.isNone then throwError "failed to build coercion to parent structure" let resultType ← whnfD (← inferType result) unless resultType.isForall do throwError "failed to build coercion to parent structure, unexpect type{indentExpr resultType}" let fieldVal ← copyFields resultType.bindingDomain! result := mkApp result fieldVal return result let declVal ← instantiateMVars (← mkLambdaFVars params (← mkLambdaFVars #[source] (← copyFields parentType))) let declName := structName ++ mkToParentName (← getStructureName parentType) fun n => !env.contains (structName ++ n) addAndCompile <| Declaration.defnDecl { name := declName levelParams := levelParams type := declType value := declVal hints := ReducibilityHints.abbrev safety := if view.modifiers.isUnsafe then DefinitionSafety.unsafe else DefinitionSafety.safe } if binfo.isInstImplicit then addInstance declName AttributeKind.global (eval_prio default) else setReducibleAttribute declName private def elabStructureView (view : StructView) : TermElabM Unit := do view.fields.forM fun field => do if field.declName == view.ctor.declName then throwErrorAt field.ref "invalid field name '{field.name}', it is equal to structure constructor name" addAuxDeclarationRanges field.declName field.ref field.ref let type ← Term.elabType view.type unless validStructType type do throwErrorAt view.type "expected Type" withRef view.ref do withParents view fun fieldInfos copiedParents => do withFields view.fields fieldInfos fun fieldInfos => do Term.synthesizeSyntheticMVarsNoPostponing let u ← getResultUniverse type let univToInfer? ← shouldInferResultUniverse u withUsed view.scopeVars view.params fieldInfos fun scopeVars => do let fieldInfos ← levelMVarToParam scopeVars view.params fieldInfos univToInfer? let type ← withRef view.ref do if univToInfer?.isSome then updateResultingUniverse fieldInfos type else checkResultingUniverse (← getResultUniverse type) pure type trace[Elab.structure] "type: {type}" let usedLevelNames ← collectLevelParamsInStructure type scopeVars view.params fieldInfos match sortDeclLevelParams view.scopeLevelNames view.allUserLevelNames usedLevelNames with | Except.error msg => withRef view.ref <| throwError msg | Except.ok levelParams => let params := scopeVars ++ view.params let ctor ← mkCtor view levelParams params fieldInfos let type ← mkForallFVars params type let type ← instantiateMVars type let indType := { name := view.declName, type := type, ctors := [ctor] : InductiveType } let decl := Declaration.inductDecl levelParams params.size [indType] view.modifiers.isUnsafe Term.ensureNoUnassignedMVars decl addDecl decl let projNames := (fieldInfos.filter fun (info : StructFieldInfo) => !info.isFromParent).toList.map fun (info : StructFieldInfo) => info.declName addProjections view.declName projNames view.isClass registerStructure view.declName fieldInfos mkAuxConstructions view.declName let instParents ← fieldInfos.filterM fun info => do let decl ← Term.getFVarLocalDecl! info.fvar pure (info.isSubobject && decl.binderInfo.isInstImplicit) withSaveInfoContext do -- save new env Term.addLocalVarInfo view.ref[1] (← mkConstWithLevelParams view.declName) if let some _ := view.ctor.ref[1].getPos? (canonicalOnly := true) then Term.addTermInfo' view.ctor.ref[1] (← mkConstWithLevelParams view.ctor.declName) (isBinder := true) for field in view.fields do -- may not exist if overriding inherited field if (← getEnv).contains field.declName then Term.addTermInfo' field.ref (← mkConstWithLevelParams field.declName) (isBinder := true) Term.applyAttributesAt view.declName view.modifiers.attrs AttributeApplicationTime.afterTypeChecking let projInstances := instParents.toList.map fun info => info.declName projInstances.forM fun declName => addInstance declName AttributeKind.global (eval_prio default) copiedParents.forM fun parent => mkCoercionToCopiedParent levelParams params view parent let lctx ← getLCtx let fieldsWithDefault := fieldInfos.filter fun info => info.value?.isSome let defaultAuxDecls ← fieldsWithDefault.mapM fun info => do let type ← inferType info.fvar pure (mkDefaultFnOfProjFn info.declName, type, info.value?.get!) /- The `lctx` and `defaultAuxDecls` are used to create the auxiliary "default value" declarations The parameters `params` for these definitions must be marked as implicit, and all others as explicit. -/ let lctx := params.foldl (init := lctx) fun (lctx : LocalContext) (p : Expr) => lctx.setBinderInfo p.fvarId! BinderInfo.implicit let lctx := fieldInfos.foldl (init := lctx) fun (lctx : LocalContext) (info : StructFieldInfo) => if info.isFromParent then lctx -- `fromParent` fields are elaborated as let-decls, and are zeta-expanded when creating "default value" auxiliary functions else lctx.setBinderInfo info.fvar.fvarId! BinderInfo.default addDefaults lctx defaultAuxDecls /- leading_parser (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional «extends» >> Term.optType >> " := " >> optional structCtor >> structFields >> optDeriving where def «extends» := leading_parser " extends " >> sepBy1 termParser ", " def typeSpec := leading_parser " : " >> termParser def optType : Parser := optional typeSpec def structFields := leading_parser many (structExplicitBinder <|> structImplicitBinder <|> structInstBinder) def structCtor := leading_parser try (declModifiers >> ident >> " :: ") -/ def elabStructure (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do checkValidInductiveModifier modifiers let isClass := stx[0].getKind == ``Parser.Command.classTk let modifiers := if isClass then modifiers.addAttribute { name := `class } else modifiers let declId := stx[1] let params := stx[2].getArgs let exts := stx[3] let parents := if exts.isNone then #[] else exts[0][1].getSepArgs let optType := stx[4] let derivingClassViews ← getOptDerivingClasses stx[6] let type ← if optType.isNone then `(Sort _) else pure optType[0][1] let declName ← runTermElabM fun scopeVars => do let scopeLevelNames ← Term.getLevelNames let ⟨name, declName, allUserLevelNames⟩ ← Elab.expandDeclId (← getCurrNamespace) scopeLevelNames declId modifiers Term.withAutoBoundImplicitForbiddenPred (fun n => name == n) do addDeclarationRanges declName stx Term.withDeclName declName do let ctor ← expandCtor stx modifiers declName let fields ← expandFields stx modifiers declName Term.withLevelNames allUserLevelNames <| Term.withAutoBoundImplicit <| Term.elabBinders params fun params => do Term.synthesizeSyntheticMVarsNoPostponing let params ← Term.addAutoBoundImplicits params let allUserLevelNames ← Term.getLevelNames elabStructureView { ref := stx modifiers scopeLevelNames allUserLevelNames declName isClass scopeVars params parents type ctor fields } unless isClass do mkSizeOfInstances declName mkInjectiveTheorems declName return declName derivingClassViews.forM fun view => view.applyHandlers #[declName] runTermElabM fun _ => Term.withDeclName declName do Term.applyAttributesAt declName modifiers.attrs .afterCompilation builtin_initialize registerTraceClass `Elab.structure end Lean.Elab.Command
cd38c7656d3a6d7ee3f2850155f312662402bd68
5749d8999a76f3a8fddceca1f6941981e33aaa96
/src/analysis/asymptotics.lean
12e588d54d825e8a3186fece089f128b20576ef5
[ "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
40,116
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Yury Kudryashov -/ import analysis.normed_space.basic tactic.alias /-! # Asymptotics We introduce these relations: * `is_O_with c f g l` : "f is big O of g along l with constant c"; * `is_O f g l` : "f is big O of g along l"; * `is_o f g l` : "f is little o of g along l". Here `l` is any filter on the domain of `f` and `g`, which are assumed to be the same. The codomains of `f` and `g` do not need to be the same; all that is needed that there is a norm associated with these types, and it is the norm that is compared asymptotically. The relation `is_O_with c` is introduced to factor out common algebraic arguments in the proofs of similar properties of `is_O` and `is_o`. Usually proofs outside of this file should use `is_O` instead. Often the ranges of `f` and `g` will be the real numbers, in which case the norm is the absolute value. In general, we have `is_O f g l ↔ is_O (λ x, ∥f x∥) (λ x, ∥g x∥) l`, and similarly for `is_o`. But our setup allows us to use the notions e.g. with functions to the integers, rationals, complex numbers, or any normed vector space without mentioning the norm explicitly. If `f` and `g` are functions to a normed field like the reals or complex numbers and `g` is always nonzero, we have `is_o f g l ↔ tendsto (λ x, f x / (g x)) l (𝓝 0)`. In fact, the right-to-left direction holds without the hypothesis on `g`, and in the other direction it suffices to assume that `f` is zero wherever `g` is. (This generalization is useful in defining the Fréchet derivative.) -/ open filter set open_locale topological_space namespace asymptotics variables {α : Type*} {β : Type*} {E : Type*} {F : Type*} {G : Type*} {E' : Type*} {F' : Type*} {G' : Type*} {R : Type*} {R' : Type*} {𝕜 : Type*} {𝕜' : Type*} variables [has_norm E] [has_norm F] [has_norm G] [normed_group E'] [normed_group F'] [normed_group G'] [normed_ring R] [normed_ring R'] [normed_field 𝕜] [normed_field 𝕜'] {c c' : ℝ} {f : α → E} {g : α → F} {k : α → G} {f' : α → E'} {g' : α → F'} {k' : α → G'} {l l' : filter α} section defs /-! ### Definitions -/ /-- This version of the Landau notation `is_O_with C f g l` where `f` and `g` are two functions on a type `α` and `l` is a filter on `α`, means that eventually for `l`, `∥f∥` is bounded by `C * ∥g∥`. In other words, `∥f∥ / ∥g∥` is eventually bounded by `C`, modulo division by zero issues that are avoided by this definition. Probably you want to use `is_O` instead of this relation. -/ def is_O_with (c : ℝ) (f : α → E) (g : α → F) (l : filter α) : Prop := { x | ∥ f x ∥ ≤ c * ∥ g x ∥ } ∈ l /-- The Landau notation `is_O f g l` where `f` and `g` are two functions on a type `α` and `l` is a filter on `α`, means that eventually for `l`, `∥f∥` is bounded by a constant multiple of `∥g∥`. In other words, `∥f∥ / ∥g∥` is eventually bounded, modulo division by zero issues that are avoided by this definition. -/ def is_O (f : α → E) (g : α → F) (l : filter α) : Prop := ∃ c : ℝ, is_O_with c f g l /-- The Landau notation `is_o f g l` where `f` and `g` are two functions on a type `α` and `l` is a filter on `α`, means that eventually for `l`, `∥f∥` is bounded by an arbitrarily small constant multiple of `∥g∥`. In other words, `∥f∥ / ∥g∥` tends to `0` along `l`, modulo division by zero issues that are avoided by this definition. -/ def is_o (f : α → E) (g : α → F) (l : filter α) : Prop := ∀ ⦃c : ℝ⦄, 0 < c → is_O_with c f g l end defs /-! ### Conversions -/ theorem is_O_with.is_O (h : is_O_with c f g l) : is_O f g l := ⟨c, h⟩ theorem is_o.is_O_with (hgf : is_o f g l) : is_O_with 1 f g l := hgf zero_lt_one theorem is_o.is_O (hgf : is_o f g l) : is_O f g l := hgf.is_O_with.is_O theorem is_O_with.weaken (h : is_O_with c f g' l) (hc : c ≤ c') : is_O_with c' f g' l := mem_sets_of_superset h $ λ x hx, calc ∥f x∥ ≤ c * ∥g' x∥ : hx ... ≤ _ : mul_le_mul_of_nonneg_right hc (norm_nonneg _) theorem is_O_with.exists_pos (h : is_O_with c f g' l) : ∃ c' (H : 0 < c'), is_O_with c' f g' l := ⟨max c 1, lt_of_lt_of_le zero_lt_one (le_max_right c 1), h.weaken $ le_max_left c 1⟩ theorem is_O.exists_pos (h : is_O f g' l) : ∃ c (H : 0 < c), is_O_with c f g' l := let ⟨c, hc⟩ := h in hc.exists_pos theorem is_O_with.exists_nonneg (h : is_O_with c f g' l) : ∃ c' (H : 0 ≤ c'), is_O_with c' f g' l := let ⟨c, cpos, hc⟩ := h.exists_pos in ⟨c, le_of_lt cpos, hc⟩ theorem is_O.exists_nonneg (h : is_O f g' l) : ∃ c (H : 0 ≤ c), is_O_with c f g' l := let ⟨c, hc⟩ := h in hc.exists_nonneg /-! ### Congruence -/ theorem is_O_with_congr {c₁ c₂} {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hc : c₁ = c₂) (hf : {x | f₁ x = f₂ x} ∈ l) (hg : {x | g₁ x = g₂ x} ∈ l) : is_O_with c₁ f₁ g₁ l ↔ is_O_with c₂ f₂ g₂ l := begin subst c₂, apply filter.congr_sets, filter_upwards [hf, hg], assume x e₁ e₂, dsimp at e₁ e₂ ⊢, rw [e₁, e₂] end theorem is_O_with.congr' {c₁ c₂} {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hc : c₁ = c₂) (hf : {x | f₁ x = f₂ x} ∈ l) (hg : {x | g₁ x = g₂ x} ∈ l) : is_O_with c₁ f₁ g₁ l → is_O_with c₂ f₂ g₂ l := (is_O_with_congr hc hf hg).mp theorem is_O_with.congr {c₁ c₂} {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hc : c₁ = c₂) (hf : ∀ x, f₁ x = f₂ x) (hg : ∀ x, g₁ x = g₂ x) : is_O_with c₁ f₁ g₁ l → is_O_with c₂ f₂ g₂ l := λ h, h.congr' hc (univ_mem_sets' hf) (univ_mem_sets' hg) theorem is_O_with.congr_left {f₁ f₂ : α → E} {l : filter α} (hf : ∀ x, f₁ x = f₂ x) : is_O_with c f₁ g l → is_O_with c f₂ g l := is_O_with.congr rfl hf (λ _, rfl) theorem is_O_with.congr_right {g₁ g₂ : α → F} {l : filter α} (hg : ∀ x, g₁ x = g₂ x) : is_O_with c f g₁ l → is_O_with c f g₂ l := is_O_with.congr rfl (λ _, rfl) hg theorem is_O_with.congr_const {c₁ c₂} {l : filter α} (hc : c₁ = c₂) : is_O_with c₁ f g l → is_O_with c₂ f g l := is_O_with.congr hc (λ _, rfl) (λ _, rfl) theorem is_O_congr {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hf : {x | f₁ x = f₂ x} ∈ l) (hg : {x | g₁ x = g₂ x} ∈ l) : is_O f₁ g₁ l ↔ is_O f₂ g₂ l := exists_congr $ λ c, is_O_with_congr rfl hf hg theorem is_O.congr' {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hf : {x | f₁ x = f₂ x} ∈ l) (hg : {x | g₁ x = g₂ x} ∈ l) : is_O f₁ g₁ l → is_O f₂ g₂ l := (is_O_congr hf hg).mp theorem is_O.congr {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hf : ∀ x, f₁ x = f₂ x) (hg : ∀ x, g₁ x = g₂ x) : is_O f₁ g₁ l → is_O f₂ g₂ l := λ h, h.congr' (univ_mem_sets' hf) (univ_mem_sets' hg) theorem is_O.congr_left {f₁ f₂ : α → E} {l : filter α} (hf : ∀ x, f₁ x = f₂ x) : is_O f₁ g l → is_O f₂ g l := is_O.congr hf (λ _, rfl) theorem is_O.congr_right {g₁ g₂ : α → E} {l : filter α} (hg : ∀ x, g₁ x = g₂ x) : is_O f g₁ l → is_O f g₂ l := is_O.congr (λ _, rfl) hg theorem is_o_congr {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hf : {x | f₁ x = f₂ x} ∈ l) (hg : {x | g₁ x = g₂ x} ∈ l) : is_o f₁ g₁ l ↔ is_o f₂ g₂ l := ball_congr (λ c hc, is_O_with_congr (eq.refl c) hf hg) theorem is_o.congr' {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hf : {x | f₁ x = f₂ x} ∈ l) (hg : {x | g₁ x = g₂ x} ∈ l) : is_o f₁ g₁ l → is_o f₂ g₂ l := (is_o_congr hf hg).mp theorem is_o.congr {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hf : ∀ x, f₁ x = f₂ x) (hg : ∀ x, g₁ x = g₂ x) : is_o f₁ g₁ l → is_o f₂ g₂ l := λ h, h.congr' (univ_mem_sets' hf) (univ_mem_sets' hg) theorem is_o.congr_left {f₁ f₂ : α → E} {l : filter α} (hf : ∀ x, f₁ x = f₂ x) : is_o f₁ g l → is_o f₂ g l := is_o.congr hf (λ _, rfl) theorem is_o.congr_right {g₁ g₂ : α → E} {l : filter α} (hg : ∀ x, g₁ x = g₂ x) : is_o f g₁ l → is_o f g₂ l := is_o.congr (λ _, rfl) hg /-! ### Filter operations and transitivity -/ theorem is_O_with.comp_tendsto (hcfg : is_O_with c f g l) {k : β → α} {l' : filter β} (hk : tendsto k l' l): is_O_with c (f ∘ k) (g ∘ k) l' := hk hcfg theorem is_O.comp_tendsto (hfg : is_O f g l) {k : β → α} {l' : filter β} (hk : tendsto k l' l) : is_O (f ∘ k) (g ∘ k) l' := hfg.imp (λ c h, h.comp_tendsto hk) theorem is_o.comp_tendsto (hfg : is_o f g l) {k : β → α} {l' : filter β} (hk : tendsto k l' l) : is_o (f ∘ k) (g ∘ k) l' := λ c cpos, (hfg cpos).comp_tendsto hk theorem is_O_with.mono (h : is_O_with c f g l') (hl : l ≤ l') : is_O_with c f g l := hl h theorem is_O.mono (h : is_O f g l') (hl : l ≤ l') : is_O f g l := h.imp (λ c h, h.mono hl) theorem is_o.mono (h : is_o f g l') (hl : l ≤ l') : is_o f g l := λ c cpos, (h cpos).mono hl theorem is_O_with.trans (hfg : is_O_with c f g l) (hgk : is_O_with c' g k l) (hc : 0 ≤ c) : is_O_with (c * c') f k l := begin filter_upwards [hfg, hgk], assume x hx hx', calc ∥f x∥ ≤ c * ∥g x∥ : hx ... ≤ c * (c' * ∥k x∥) : mul_le_mul_of_nonneg_left hx' hc ... = c * c' * ∥k x∥ : (mul_assoc _ _ _).symm end theorem is_O.trans (hfg : is_O f g' l) (hgk : is_O g' k l) : is_O f k l := let ⟨c, cnonneg, hc⟩ := hfg.exists_nonneg, ⟨c', hc'⟩ := hgk in (hc.trans hc' cnonneg).is_O theorem is_o.trans_is_O_with (hfg : is_o f g l) (hgk : is_O_with c g k l) (hc : 0 < c) : is_o f k l := begin intros c' c'pos, have : 0 < c' / c, from div_pos c'pos hc, exact ((hfg this).trans hgk (le_of_lt this)).congr_const (div_mul_cancel _ (ne_of_gt hc)) end theorem is_o.trans_is_O (hfg : is_o f g l) (hgk : is_O g k' l) : is_o f k' l := let ⟨c, cpos, hc⟩ := hgk.exists_pos in hfg.trans_is_O_with hc cpos theorem is_O_with.trans_is_o (hfg : is_O_with c f g l) (hgk : is_o g k l) (hc : 0 < c) : is_o f k l := begin intros c' c'pos, have : 0 < c' / c, from div_pos c'pos hc, exact (hfg.trans (hgk this) (le_of_lt hc)).congr_const (mul_div_cancel' _ (ne_of_gt hc)) end theorem is_O.trans_is_o (hfg : is_O f g' l) (hgk : is_o g' k l) : is_o f k l := let ⟨c, cpos, hc⟩ := hfg.exists_pos in hc.trans_is_o hgk cpos theorem is_o.trans (hfg : is_o f g l) (hgk : is_o g k' l) : is_o f k' l := hfg.trans_is_O hgk.is_O theorem is_o.trans' (hfg : is_o f g' l) (hgk : is_o g' k l) : is_o f k l := hfg.is_O.trans_is_o hgk section variable (l) theorem is_O_with_of_le' (hfg : ∀ x, ∥f x∥ ≤ c * ∥g x∥) : is_O_with c f g l := univ_mem_sets' hfg theorem is_O_with_of_le (hfg : ∀ x, ∥f x∥ ≤ ∥g x∥) : is_O_with 1 f g l := is_O_with_of_le' l $ λ x, by { rw one_mul, exact hfg x } theorem is_O_of_le' (hfg : ∀ x, ∥f x∥ ≤ c * ∥g x∥) : is_O f g l := (is_O_with_of_le' l hfg).is_O theorem is_O_of_le (hfg : ∀ x, ∥f x∥ ≤ ∥g x∥) : is_O f g l := (is_O_with_of_le l hfg).is_O end theorem is_O_with_refl (f : α → E) (l : filter α) : is_O_with 1 f f l := is_O_with_of_le l $ λ _, le_refl _ theorem is_O_refl (f : α → E) (l : filter α) : is_O f f l := (is_O_with_refl f l).is_O theorem is_O_with.trans_le (hfg : is_O_with c f g l) (hgk : ∀ x, ∥g x∥ ≤ ∥k x∥) (hc : 0 ≤ c) : is_O_with c f k l := (hfg.trans (is_O_with_of_le l hgk) hc).congr_const $ mul_one c theorem is_O.trans_le (hfg : is_O f g' l) (hgk : ∀ x, ∥g' x∥ ≤ ∥k x∥) : is_O f k l := hfg.trans (is_O_of_le l hgk) section bot variables (c f g) theorem is_O_with_bot : is_O_with c f g ⊥ := trivial theorem is_O_bot : is_O f g ⊥ := (is_O_with_bot c f g).is_O theorem is_o_bot : is_o f g ⊥ := λ c _, is_O_with_bot c f g end bot theorem is_O_with.join (h : is_O_with c f g l) (h' : is_O_with c f g l') : is_O_with c f g (l ⊔ l') := mem_sup_sets.2 ⟨h, h'⟩ theorem is_O_with.join' (h : is_O_with c f g' l) (h' : is_O_with c' f g' l') : is_O_with (max c c') f g' (l ⊔ l') := mem_sup_sets.2 ⟨(h.weaken $ le_max_left c c'), (h'.weaken $ le_max_right c c')⟩ theorem is_O.join (h : is_O f g' l) (h' : is_O f g' l') : is_O f g' (l ⊔ l') := let ⟨c, hc⟩ := h, ⟨c', hc'⟩ := h' in (hc.join' hc').is_O theorem is_o.join (h : is_o f g l) (h' : is_o f g l') : is_o f g (l ⊔ l') := λ c cpos, (h cpos).join (h' cpos) /-! ### Simplification : norm -/ @[simp] theorem is_O_with_norm_right : is_O_with c f (λ x, ∥g' x∥) l ↔ is_O_with c f g' l := by simp only [is_O_with, norm_norm] alias is_O_with_norm_right ↔ asymptotics.is_O_with.of_norm_right asymptotics.is_O_with.norm_right @[simp] theorem is_O_norm_right : is_O f (λ x, ∥g' x∥) l ↔ is_O f g' l := exists_congr $ λ _, is_O_with_norm_right alias is_O_norm_right ↔ asymptotics.is_O.of_norm_right asymptotics.is_O.norm_right @[simp] theorem is_o_norm_right : is_o f (λ x, ∥g' x∥) l ↔ is_o f g' l := forall_congr $ λ _, forall_congr $ λ _, is_O_with_norm_right alias is_o_norm_right ↔ asymptotics.is_o.of_norm_right asymptotics.is_o.norm_right @[simp] theorem is_O_with_norm_left : is_O_with c (λ x, ∥f' x∥) g l ↔ is_O_with c f' g l := by simp only [is_O_with, norm_norm] alias is_O_with_norm_left ↔ asymptotics.is_O_with.of_norm_left asymptotics.is_O_with.norm_left @[simp] theorem is_O_norm_left : is_O (λ x, ∥f' x∥) g l ↔ is_O f' g l := exists_congr $ λ _, is_O_with_norm_left alias is_O_norm_left ↔ asymptotics.is_O.of_norm_left asymptotics.is_O.norm_left @[simp] theorem is_o_norm_left : is_o (λ x, ∥f' x∥) g l ↔ is_o f' g l := forall_congr $ λ _, forall_congr $ λ _, is_O_with_norm_left alias is_o_norm_left ↔ asymptotics.is_o.of_norm_left asymptotics.is_o.norm_left theorem is_O_with_norm_norm : is_O_with c (λ x, ∥f' x∥) (λ x, ∥g' x∥) l ↔ is_O_with c f' g' l := is_O_with_norm_left.trans is_O_with_norm_right alias is_O_with_norm_norm ↔ asymptotics.is_O_with.of_norm_norm asymptotics.is_O_with.norm_norm theorem is_O_norm_norm : is_O (λ x, ∥f' x∥) (λ x, ∥g' x∥) l ↔ is_O f' g' l := is_O_norm_left.trans is_O_norm_right alias is_O_norm_norm ↔ asymptotics.is_O.of_norm_norm asymptotics.is_O.norm_norm theorem is_o_norm_norm : is_o (λ x, ∥f' x∥) (λ x, ∥g' x∥) l ↔ is_o f' g' l := is_o_norm_left.trans is_o_norm_right alias is_o_norm_norm ↔ asymptotics.is_o.of_norm_norm asymptotics.is_o.norm_norm /-! ### Simplification: negate -/ @[simp] theorem is_O_with_neg_right : is_O_with c f (λ x, -(g' x)) l ↔ is_O_with c f g' l := by simp only [is_O_with, norm_neg] alias is_O_with_neg_right ↔ asymptotics.is_O_with.of_neg_right asymptotics.is_O_with.neg_right @[simp] theorem is_O_neg_right : is_O f (λ x, -(g' x)) l ↔ is_O f g' l := exists_congr $ λ _, is_O_with_neg_right alias is_O_neg_right ↔ asymptotics.is_O.of_neg_right asymptotics.is_O.neg_right @[simp] theorem is_o_neg_right : is_o f (λ x, -(g' x)) l ↔ is_o f g' l := forall_congr $ λ _, forall_congr $ λ _, is_O_with_neg_right alias is_o_neg_right ↔ asymptotics.is_o.of_neg_right asymptotics.is_o.neg_right @[simp] theorem is_O_with_neg_left : is_O_with c (λ x, -(f' x)) g l ↔ is_O_with c f' g l := by simp only [is_O_with, norm_neg] alias is_O_with_neg_left ↔ asymptotics.is_O_with.of_neg_left asymptotics.is_O_with.neg_left @[simp] theorem is_O_neg_left : is_O (λ x, -(f' x)) g l ↔ is_O f' g l := exists_congr $ λ _, is_O_with_neg_left alias is_O_neg_left ↔ asymptotics.is_O.of_neg_left asymptotics.is_O.neg_left @[simp] theorem is_o_neg_left : is_o (λ x, -(f' x)) g l ↔ is_o f' g l := forall_congr $ λ _, forall_congr $ λ _, is_O_with_neg_left alias is_o_neg_left ↔ asymptotics.is_o.of_neg_right asymptotics.is_o.neg_left /-! ### Product of functions (right) -/ lemma is_O_with_fst_prod : is_O_with 1 f' (λ x, (f' x, g' x)) l := is_O_with_of_le l $ λ x, le_max_left _ _ lemma is_O_with_snd_prod : is_O_with 1 g' (λ x, (f' x, g' x)) l := is_O_with_of_le l $ λ x, le_max_right _ _ lemma is_O_fst_prod : is_O f' (λ x, (f' x, g' x)) l := is_O_with_fst_prod.is_O lemma is_O_snd_prod : is_O g' (λ x, (f' x, g' x)) l := is_O_with_snd_prod.is_O section variables (f' k') lemma is_O_with.prod_rightl (h : is_O_with c f g' l) (hc : 0 ≤ c) : is_O_with c f (λ x, (g' x, k' x)) l := (h.trans is_O_with_fst_prod hc).congr_const (mul_one c) lemma is_O.prod_rightl (h : is_O f g' l) : is_O f (λx, (g' x, k' x)) l := let ⟨c, cnonneg, hc⟩ := h.exists_nonneg in (hc.prod_rightl k' cnonneg).is_O lemma is_o.prod_rightl (h : is_o f g' l) : is_o f (λ x, (g' x, k' x)) l := λ c cpos, (h cpos).prod_rightl k' (le_of_lt cpos) lemma is_O_with.prod_rightr (h : is_O_with c f g' l) (hc : 0 ≤ c) : is_O_with c f (λ x, (f' x, g' x)) l := (h.trans is_O_with_snd_prod hc).congr_const (mul_one c) lemma is_O.prod_rightr (h : is_O f g' l) : is_O f (λx, (f' x, g' x)) l := let ⟨c, cnonneg, hc⟩ := h.exists_nonneg in (hc.prod_rightr f' cnonneg).is_O lemma is_o.prod_rightr (h : is_o f g' l) : is_o f (λx, (f' x, g' x)) l := λ c cpos, (h cpos).prod_rightr f' (le_of_lt cpos) end lemma is_O_with.prod_left_same (hf : is_O_with c f' k' l) (hg : is_O_with c g' k' l) : is_O_with c (λ x, (f' x, g' x)) k' l := begin filter_upwards [hf, hg], simp only [mem_set_of_eq], exact λ x, max_le end lemma is_O_with.prod_left (hf : is_O_with c f' k' l) (hg : is_O_with c' g' k' l) : is_O_with (max c c') (λ x, (f' x, g' x)) k' l := (hf.weaken $ le_max_left c c').prod_left_same (hg.weaken $ le_max_right c c') lemma is_O_with.prod_left_fst (h : is_O_with c (λ x, (f' x, g' x)) k' l) : is_O_with c f' k' l := (is_O_with_fst_prod.trans h zero_le_one).congr_const $ one_mul c lemma is_O_with.prod_left_snd (h : is_O_with c (λ x, (f' x, g' x)) k' l) : is_O_with c g' k' l := (is_O_with_snd_prod.trans h zero_le_one).congr_const $ one_mul c lemma is_O_with_prod_left : is_O_with c (λ x, (f' x, g' x)) k' l ↔ is_O_with c f' k' l ∧ is_O_with c g' k' l := ⟨λ h, ⟨h.prod_left_fst, h.prod_left_snd⟩, λ h, h.1.prod_left_same h.2⟩ lemma is_O.prod_left (hf : is_O f' k' l) (hg : is_O g' k' l) : is_O (λ x, (f' x, g' x)) k' l := let ⟨c, hf⟩ := hf, ⟨c', hg⟩ := hg in (hf.prod_left hg).is_O lemma is_O.prod_left_fst (h : is_O (λ x, (f' x, g' x)) k' l) : is_O f' k' l := is_O_fst_prod.trans h lemma is_O.prod_left_snd (h : is_O (λ x, (f' x, g' x)) k' l) : is_O g' k' l := is_O_snd_prod.trans h @[simp] lemma is_O_prod_left : is_O (λ x, (f' x, g' x)) k' l ↔ is_O f' k' l ∧ is_O g' k' l := ⟨λ h, ⟨h.prod_left_fst, h.prod_left_snd⟩, λ h, h.1.prod_left h.2⟩ lemma is_o.prod_left (hf : is_o f' k' l) (hg : is_o g' k' l) : is_o (λ x, (f' x, g' x)) k' l := λ c hc, (hf hc).prod_left_same (hg hc) lemma is_o.prod_left_fst (h : is_o (λ x, (f' x, g' x)) k' l) : is_o f' k' l := is_O_fst_prod.trans_is_o h lemma is_o.prod_left_snd (h : is_o (λ x, (f' x, g' x)) k' l) : is_o g' k' l := is_O_snd_prod.trans_is_o h @[simp] lemma is_o_prod_left : is_o (λ x, (f' x, g' x)) k' l ↔ is_o f' k' l ∧ is_o g' k' l := ⟨λ h, ⟨h.prod_left_fst, h.prod_left_snd⟩, λ h, h.1.prod_left h.2⟩ /-! ### Addition and subtraction -/ section add_sub variables {c₁ c₂ : ℝ} {f₁ f₂ : α → E'} theorem is_O_with.add (h₁ : is_O_with c₁ f₁ g l) (h₂ : is_O_with c₂ f₂ g l) : is_O_with (c₁ + c₂) (λ x, f₁ x + f₂ x) g l := by filter_upwards [h₁, h₂] λ x hx₁ hx₂, calc ∥f₁ x + f₂ x∥ ≤ c₁ * ∥g x∥ + c₂ * ∥g x∥ : norm_add_le_of_le hx₁ hx₂ ... = (c₁ + c₂) * ∥g x∥ : (add_mul _ _ _).symm theorem is_O.add : is_O f₁ g l → is_O f₂ g l → is_O (λ x, f₁ x + f₂ x) g l | ⟨c₁, hc₁⟩ ⟨c₂, hc₂⟩ := (hc₁.add hc₂).is_O theorem is_o.add (h₁ : is_o f₁ g l) (h₂ : is_o f₂ g l) : is_o (λ x, f₁ x + f₂ x) g l := λ c cpos, ((h₁ $ half_pos cpos).add (h₂ $ half_pos cpos)).congr_const (add_halves c) theorem is_O.add_is_o (h₁ : is_O f₁ g l) (h₂ : is_o f₂ g l) : is_O (λ x, f₁ x + f₂ x) g l := h₁.add h₂.is_O theorem is_o.add_is_O (h₁ : is_o f₁ g l) (h₂ : is_O f₂ g l) : is_O (λ x, f₁ x + f₂ x) g l := h₁.is_O.add h₂ theorem is_O_with.add_is_o (h₁ : is_O_with c₁ f₁ g l) (h₂ : is_o f₂ g l) (hc : c₁ < c₂) : is_O_with c₂ (λx, f₁ x + f₂ x) g l := (h₁.add (h₂ (sub_pos.2 hc))).congr_const (add_sub_cancel'_right _ _) theorem is_o.add_is_O_with (h₁ : is_o f₁ g l) (h₂ : is_O_with c₁ f₂ g l) (hc : c₁ < c₂) : is_O_with c₂ (λx, f₁ x + f₂ x) g l := (h₂.add_is_o h₁ hc).congr_left $ λ _, add_comm _ _ theorem is_O_with.sub (h₁ : is_O_with c₁ f₁ g l) (h₂ : is_O_with c₂ f₂ g l) : is_O_with (c₁ + c₂) (λ x, f₁ x - f₂ x) g l := h₁.add h₂.neg_left theorem is_O_with.sub_is_o (h₁ : is_O_with c₁ f₁ g l) (h₂ : is_o f₂ g l) (hc : c₁ < c₂) : is_O_with c₂ (λ x, f₁ x - f₂ x) g l := h₁.add_is_o h₂.neg_left hc theorem is_O.sub (h₁ : is_O f₁ g l) (h₂ : is_O f₂ g l) : is_O (λ x, f₁ x - f₂ x) g l := h₁.add h₂.neg_left theorem is_o.sub (h₁ : is_o f₁ g l) (h₂ : is_o f₂ g l) : is_o (λ x, f₁ x - f₂ x) g l := h₁.add h₂.neg_left end add_sub /-! ### Lemmas about `is_O (f₁ - f₂) g l` / `is_o (f₁ - f₂) g l` treated as a binary relation -/ section is_oO_as_rel variables {f₁ f₂ f₃ : α → E'} theorem is_O_with.symm (h : is_O_with c (λ x, f₁ x - f₂ x) g l) : is_O_with c (λ x, f₂ x - f₁ x) g l := h.neg_left.congr_left $ λ x, neg_sub _ _ theorem is_O_with_comm : is_O_with c (λ x, f₁ x - f₂ x) g l ↔ is_O_with c (λ x, f₂ x - f₁ x) g l := ⟨is_O_with.symm, is_O_with.symm⟩ theorem is_O.symm (h : is_O (λ x, f₁ x - f₂ x) g l) : is_O (λ x, f₂ x - f₁ x) g l := h.neg_left.congr_left $ λ x, neg_sub _ _ theorem is_O_comm : is_O (λ x, f₁ x - f₂ x) g l ↔ is_O (λ x, f₂ x - f₁ x) g l := ⟨is_O.symm, is_O.symm⟩ theorem is_o.symm (h : is_o (λ x, f₁ x - f₂ x) g l) : is_o (λ x, f₂ x - f₁ x) g l := by simpa only [neg_sub] using h.neg_left theorem is_o_comm : is_o (λ x, f₁ x - f₂ x) g l ↔ is_o (λ x, f₂ x - f₁ x) g l := ⟨is_o.symm, is_o.symm⟩ theorem is_O_with.triangle (h₁ : is_O_with c (λ x, f₁ x - f₂ x) g l) (h₂ : is_O_with c' (λ x, f₂ x - f₃ x) g l) : is_O_with (c + c') (λ x, f₁ x - f₃ x) g l := (h₁.add h₂).congr_left $ λ x, sub_add_sub_cancel _ _ _ theorem is_O.triangle (h₁ : is_O (λ x, f₁ x - f₂ x) g l) (h₂ : is_O (λ x, f₂ x - f₃ x) g l) : is_O (λ x, f₁ x - f₃ x) g l := (h₁.add h₂).congr_left $ λ x, sub_add_sub_cancel _ _ _ theorem is_o.triangle (h₁ : is_o (λ x, f₁ x - f₂ x) g l) (h₂ : is_o (λ x, f₂ x - f₃ x) g l) : is_o (λ x, f₁ x - f₃ x) g l := (h₁.add h₂).congr_left $ λ x, sub_add_sub_cancel _ _ _ theorem is_O.congr_of_sub (h : is_O (λ x, f₁ x - f₂ x) g l) : is_O f₁ g l ↔ is_O f₂ g l := ⟨λ h', (h'.sub h).congr_left (λ x, sub_sub_cancel _ _), λ h', (h.add h').congr_left (λ x, sub_add_cancel _ _)⟩ theorem is_o.congr_of_sub (h : is_o (λ x, f₁ x - f₂ x) g l) : is_o f₁ g l ↔ is_o f₂ g l := ⟨λ h', (h'.sub h).congr_left (λ x, sub_sub_cancel _ _), λ h', (h.add h').congr_left (λ x, sub_add_cancel _ _)⟩ end is_oO_as_rel /-! ### Zero, one, and other constants -/ section zero_const variables (g' l) theorem is_o_zero : is_o (λ x, (0 : E')) g' l := λ c hc, univ_mem_sets' $ λ x, by simpa using mul_nonneg (le_of_lt hc) (norm_nonneg $ g' x) theorem is_O_with_zero (hc : 0 < c) : is_O_with c (λ x, (0 : E')) g' l := (is_o_zero g' l) hc theorem is_O_zero : is_O (λ x, (0 : E')) g' l := (is_o_zero g' l).is_O theorem is_O_refl_left : is_O (λ x, f' x - f' x) g' l := (is_O_zero g' l).congr_left $ λ x, (sub_self _).symm theorem is_o_refl_left : is_o (λ x, f' x - f' x) g' l := (is_o_zero g' l).congr_left $ λ x, (sub_self _).symm variables {g' l} theorem is_O_with_zero_right_iff : is_O_with c f' (λ x, (0 : F')) l ↔ {x | f' x = 0} ∈ l := by simp only [is_O_with, exists_prop, true_and, norm_zero, mul_zero, norm_le_zero_iff] theorem is_O_zero_right_iff : is_O f' (λ x, (0 : F')) l ↔ {x | f' x = 0} ∈ l := ⟨λ h, let ⟨c, hc⟩ := h in (is_O_with_zero_right_iff).1 hc, λ h, (is_O_with_zero_right_iff.2 h : is_O_with 1 _ _ _).is_O⟩ theorem is_o_zero_right_iff : is_o f' (λ x, (0 : F')) l ↔ {x | f' x = 0} ∈ l := ⟨λ h, is_O_zero_right_iff.1 h.is_O, λ h c hc, is_O_with_zero_right_iff.2 h⟩ theorem is_O_with_const_const (c : E) {c' : F'} (hc' : c' ≠ 0) (l : filter α) : is_O_with (∥c∥ / ∥c'∥) (λ x : α, c) (λ x, c') l := begin apply univ_mem_sets', intro x, rw [mem_set_of_eq, div_mul_cancel], rwa [ne.def, norm_eq_zero] end theorem is_O_const_const (c : E) {c' : F'} (hc' : c' ≠ 0) (l : filter α) : is_O (λ x : α, c) (λ x, c') l := (is_O_with_const_const c hc' l).is_O end zero_const theorem is_O_with_const_one (c : E) (l : filter α) : is_O_with ∥c∥ (λ x : α, c) (λ x, (1 : 𝕜)) l := begin refine (is_O_with_const_const c _ l).congr_const _, { rw [normed_field.norm_one, div_one] }, { exact one_ne_zero } end theorem is_O_const_one (c : E) (l : filter α) : is_O (λ x : α, c) (λ x, (1 : 𝕜)) l := (is_O_with_const_one c l).is_O section variable (𝕜) theorem is_o_const_iff_is_o_one {c : F'} (hc : c ≠ 0) : is_o f (λ x, c) l ↔ is_o f (λ x, (1:𝕜)) l := ⟨λ h, h.trans_is_O $ is_O_const_one c l, λ h, h.trans_is_O $ is_O_const_const _ hc _⟩ end theorem is_o_const_iff {c : F'} (hc : c ≠ 0) : is_o f' (λ x, c) l ↔ tendsto f' l (𝓝 0) := (is_o_const_iff_is_o_one ℝ hc).trans begin clear hc c, simp only [is_o, is_O_with, normed_field.norm_one, mul_one, normed_group.tendsto_nhds_zero], -- Now the only difference is `≤` vs `<` split, { intros h ε hε0, apply mem_sets_of_superset (h (half_pos hε0)), intros x hx, simp only [mem_set_of_eq] at hx ⊢, exact lt_of_le_of_lt hx (half_lt_self hε0) }, { intros h ε hε0, apply mem_sets_of_superset (h ε hε0), intros x hx, simp only [mem_set_of_eq] at hx ⊢, exact le_of_lt hx } end theorem is_O_const_of_tendsto {y : E'} (h : tendsto f' l (𝓝 y)) {c : F'} (hc : c ≠ 0) : is_O f' (λ x, c) l := begin refine is_O.trans _ (is_O_const_const (∥y∥ + 1) hc l), use 1, simp only [is_O_with, one_mul], have : tendsto (λx, ∥f' x∥) l (𝓝 ∥y∥), from (continuous_norm.tendsto _).comp h, have Iy : ∥y∥ < ∥∥y∥ + 1∥, from lt_of_lt_of_le (lt_add_one _) (le_abs_self _), exact this (ge_mem_nhds Iy) end section variable (𝕜) theorem is_o_one_iff : is_o f' (λ x, (1 : 𝕜)) l ↔ tendsto f' l (𝓝 0) := is_o_const_iff one_ne_zero theorem is_O_one_of_tendsto {y : E'} (h : tendsto f' l (𝓝 y)) : is_O f' (λ x, (1:𝕜)) l := is_O_const_of_tendsto h one_ne_zero theorem is_O.trans_tendsto_nhds (hfg : is_O f g' l) {y : F'} (hg : tendsto g' l (𝓝 y)) : is_O f (λ x, (1:𝕜)) l := hfg.trans $ is_O_one_of_tendsto 𝕜 hg end theorem is_O.trans_tendsto (hfg : is_O f' g' l) (hg : tendsto g' l (𝓝 0)) : tendsto f' l (𝓝 0) := (is_o_one_iff ℝ).1 $ hfg.trans_is_o $ (is_o_one_iff ℝ).2 hg theorem is_o.trans_tendsto (hfg : is_o f' g' l) (hg : tendsto g' l (𝓝 0)) : tendsto f' l (𝓝 0) := hfg.is_O.trans_tendsto hg /-! ### Multiplication by a constant -/ theorem is_O_with_const_mul_self (c : R) (f : α → R) (l : filter α) : is_O_with ∥c∥ (λ x, c * f x) f l := is_O_with_of_le' _ $ λ x, norm_mul_le _ _ theorem is_O_const_mul_self (c : R) (f : α → R) (l : filter α) : is_O (λ x, c * f x) f l := (is_O_with_const_mul_self c f l).is_O theorem is_O_with.const_mul_left {f : α → R} (h : is_O_with c f g l) (c' : R) : is_O_with (∥c'∥ * c) (λ x, c' * f x) g l := (is_O_with_const_mul_self c' f l).trans h (norm_nonneg c') theorem is_O.const_mul_left {f : α → R} (h : is_O f g l) (c' : R) : is_O (λ x, c' * f x) g l := let ⟨c, hc⟩ := h in (hc.const_mul_left c').is_O theorem is_O_with_self_const_mul' (u : units R) (f : α → R) (l : filter α) : is_O_with ∥(↑u⁻¹:R)∥ f (λ x, ↑u * f x) l := (is_O_with_const_mul_self ↑u⁻¹ _ l).congr_left $ λ x, u.inv_mul_cancel_left (f x) theorem is_O_with_self_const_mul (c : 𝕜) (hc : c ≠ 0) (f : α → 𝕜) (l : filter α) : is_O_with ∥c∥⁻¹ f (λ x, c * f x) l := (is_O_with_self_const_mul' (units.mk0 c hc) f l).congr_const $ normed_field.norm_inv c theorem is_O_self_const_mul' {c : R} (hc : is_unit c) (f : α → R) (l : filter α) : is_O f (λ x, c * f x) l := let ⟨u, hu⟩ := hc in hu.symm ▸ (is_O_with_self_const_mul' u f l).is_O theorem is_O_self_const_mul (c : 𝕜) (hc : c ≠ 0) (f : α → 𝕜) (l : filter α) : is_O f (λ x, c * f x) l := is_O_self_const_mul' (is_unit.mk0 c hc) f l theorem is_O_const_mul_left_iff' {f : α → R} {c : R} (hc : is_unit c) : is_O (λ x, c * f x) g l ↔ is_O f g l := ⟨(is_O_self_const_mul' hc f l).trans, λ h, h.const_mul_left c⟩ theorem is_O_const_mul_left_iff {f : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) : is_O (λ x, c * f x) g l ↔ is_O f g l := is_O_const_mul_left_iff' $ is_unit.mk0 c hc theorem is_o.const_mul_left {f : α → R} (h : is_o f g l) (c : R) : is_o (λ x, c * f x) g l := (is_O_const_mul_self c f l).trans_is_o h theorem is_o_const_mul_left_iff' {f : α → R} {c : R} (hc : is_unit c) : is_o (λ x, c * f x) g l ↔ is_o f g l := ⟨(is_O_self_const_mul' hc f l).trans_is_o, λ h, h.const_mul_left c⟩ theorem is_o_const_mul_left_iff {f : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) : is_o (λ x, c * f x) g l ↔ is_o f g l := is_o_const_mul_left_iff' $ is_unit.mk0 c hc theorem is_O_with.of_const_mul_right {g : α → R} {c : R} (hc' : 0 ≤ c') (h : is_O_with c' f (λ x, c * g x) l) : is_O_with (c' * ∥c∥) f g l := h.trans (is_O_with_const_mul_self c g l) hc' theorem is_O.of_const_mul_right {g : α → R} {c : R} (h : is_O f (λ x, c * g x) l) : is_O f g l := let ⟨c, cnonneg, hc⟩ := h.exists_nonneg in (hc.of_const_mul_right cnonneg).is_O theorem is_O_with.const_mul_right' {g : α → R} {u : units R} {c' : ℝ} (hc' : 0 ≤ c') (h : is_O_with c' f g l) : is_O_with (c' * ∥(↑u⁻¹:R)∥) f (λ x, ↑u * g x) l := h.trans (is_O_with_self_const_mul' _ _ _) hc' theorem is_O_with.const_mul_right {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) {c' : ℝ} (hc' : 0 ≤ c') (h : is_O_with c' f g l) : is_O_with (c' * ∥c∥⁻¹) f (λ x, c * g x) l := h.trans (is_O_with_self_const_mul c hc g l) hc' theorem is_O.const_mul_right' {g : α → R} {c : R} (hc : is_unit c) (h : is_O f g l) : is_O f (λ x, c * g x) l := h.trans (is_O_self_const_mul' hc g l) theorem is_O.const_mul_right {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) (h : is_O f g l) : is_O f (λ x, c * g x) l := h.const_mul_right' $ is_unit.mk0 c hc theorem is_O_const_mul_right_iff' {g : α → R} {c : R} (hc : is_unit c) : is_O f (λ x, c * g x) l ↔ is_O f g l := ⟨λ h, h.of_const_mul_right, λ h, h.const_mul_right' hc⟩ theorem is_O_const_mul_right_iff {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) : is_O f (λ x, c * g x) l ↔ is_O f g l := is_O_const_mul_right_iff' $ is_unit.mk0 c hc theorem is_o.of_const_mul_right {g : α → R} {c : R} (h : is_o f (λ x, c * g x) l) : is_o f g l := h.trans_is_O (is_O_const_mul_self c g l) theorem is_o.const_mul_right' {g : α → R} {c : R} (hc : is_unit c) (h : is_o f g l) : is_o f (λ x, c * g x) l := h.trans_is_O (is_O_self_const_mul' hc g l) theorem is_o.const_mul_right {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) (h : is_o f g l) : is_o f (λ x, c * g x) l := h.const_mul_right' $ is_unit.mk0 c hc theorem is_o_const_mul_right_iff' {g : α → R} {c : R} (hc : is_unit c) : is_o f (λ x, c * g x) l ↔ is_o f g l := ⟨λ h, h.of_const_mul_right, λ h, h.const_mul_right' hc⟩ theorem is_o_const_mul_right_iff {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) : is_o f (λ x, c * g x) l ↔ is_o f g l := is_o_const_mul_right_iff' $ is_unit.mk0 c hc /-! ### Multiplication -/ theorem is_O_with.mul {f₁ f₂ : α → R} {g₁ g₂ : α → 𝕜} {c₁ c₂ : ℝ} (h₁ : is_O_with c₁ f₁ g₁ l) (h₂ : is_O_with c₂ f₂ g₂ l) : is_O_with (c₁ * c₂) (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l := begin filter_upwards [h₁, h₂], simp only [mem_set_of_eq], intros x hx₁ hx₂, apply le_trans (norm_mul_le _ _), convert mul_le_mul hx₁ hx₂ (norm_nonneg _) (le_trans (norm_nonneg _) hx₁) using 1, rw normed_field.norm_mul, ac_refl end theorem is_O.mul {f₁ f₂ : α → R} {g₁ g₂ : α → 𝕜} (h₁ : is_O f₁ g₁ l) (h₂ : is_O f₂ g₂ l) : is_O (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l := let ⟨c, hc⟩ := h₁, ⟨c', hc'⟩ := h₂ in (hc.mul hc').is_O theorem is_O.mul_is_o {f₁ f₂ : α → R} {g₁ g₂ : α → 𝕜} (h₁ : is_O f₁ g₁ l) (h₂ : is_o f₂ g₂ l) : is_o (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l := begin intros c cpos, rcases h₁.exists_pos with ⟨c', c'pos, hc'⟩, exact (hc'.mul (h₂ (div_pos cpos c'pos))).congr_const (mul_div_cancel' _ (ne_of_gt c'pos)) end theorem is_o.mul_is_O {f₁ f₂ : α → R} {g₁ g₂ : α → 𝕜} (h₁ : is_o f₁ g₁ l) (h₂ : is_O f₂ g₂ l) : is_o (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l := begin intros c cpos, rcases h₂.exists_pos with ⟨c', c'pos, hc'⟩, exact ((h₁ (div_pos cpos c'pos)).mul hc').congr_const (div_mul_cancel _ (ne_of_gt c'pos)) end theorem is_o.mul {f₁ f₂ : α → R} {g₁ g₂ : α → 𝕜} (h₁ : is_o f₁ g₁ l) (h₂ : is_o f₂ g₂ l) : is_o (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l := h₁.mul_is_O h₂.is_O /-! ### Scalar multiplication -/ section smul_const variables [normed_space 𝕜 E'] theorem is_O_with.const_smul_left (h : is_O_with c f' g l) (c' : 𝕜) : is_O_with (∥c'∥ * c) (λ x, c' • f' x) g l := by refine ((h.norm_left.const_mul_left (∥c'∥)).congr _ _ (λ _, rfl)).of_norm_left; intros; simp only [norm_norm, norm_smul] theorem is_O_const_smul_left_iff {c : 𝕜} (hc : c ≠ 0) : is_O (λ x, c • f' x) g l ↔ is_O f' g l := begin have cne0 : ∥c∥ ≠ 0, from mt (norm_eq_zero _).mp hc, rw [←is_O_norm_left], simp only [norm_smul], rw [is_O_const_mul_left_iff cne0, is_O_norm_left], end theorem is_o_const_smul_left (h : is_o f' g l) (c : 𝕜) : is_o (λ x, c • f' x) g l := begin refine ((h.norm_left.const_mul_left (∥c∥)).congr_left _).of_norm_left, exact λ x, (norm_smul _ _).symm end theorem is_o_const_smul_left_iff {c : 𝕜} (hc : c ≠ 0) : is_o (λ x, c • f' x) g l ↔ is_o f' g l := begin have cne0 : ∥c∥ ≠ 0, from mt (norm_eq_zero _).mp hc, rw [←is_o_norm_left], simp only [norm_smul], rw [is_o_const_mul_left_iff cne0, is_o_norm_left] end theorem is_O_const_smul_right {c : 𝕜} (hc : c ≠ 0) : is_O f (λ x, c • f' x) l ↔ is_O f f' l := begin have cne0 : ∥c∥ ≠ 0, from mt (norm_eq_zero _).mp hc, rw [←is_O_norm_right], simp only [norm_smul], rw [is_O_const_mul_right_iff cne0, is_O_norm_right] end theorem is_o_const_smul_right {c : 𝕜} (hc : c ≠ 0) : is_o f (λ x, c • f' x) l ↔ is_o f f' l := begin have cne0 : ∥c∥ ≠ 0, from mt (norm_eq_zero _).mp hc, rw [←is_o_norm_right], simp only [norm_smul], rw [is_o_const_mul_right_iff cne0, is_o_norm_right] end end smul_const section smul variables [normed_space 𝕜 E'] [normed_space 𝕜 F'] theorem is_O_with.smul {k₁ k₂ : α → 𝕜} (h₁ : is_O_with c k₁ k₂ l) (h₂ : is_O_with c' f' g' l) : is_O_with (c * c') (λ x, k₁ x • f' x) (λ x, k₂ x • g' x) l := by refine ((h₁.norm_norm.mul h₂.norm_norm).congr rfl _ _).of_norm_norm; by intros; simp only [norm_smul] theorem is_O.smul {k₁ k₂ : α → 𝕜} (h₁ : is_O k₁ k₂ l) (h₂ : is_O f' g' l) : is_O (λ x, k₁ x • f' x) (λ x, k₂ x • g' x) l := by refine ((h₁.norm_norm.mul h₂.norm_norm).congr _ _).of_norm_norm; by intros; simp only [norm_smul] theorem is_O.smul_is_o {k₁ k₂ : α → 𝕜} (h₁ : is_O k₁ k₂ l) (h₂ : is_o f' g' l) : is_o (λ x, k₁ x • f' x) (λ x, k₂ x • g' x) l := by refine ((h₁.norm_norm.mul_is_o h₂.norm_norm).congr _ _).of_norm_norm; by intros; simp only [norm_smul] theorem is_o.smul_is_O {k₁ k₂ : α → 𝕜} (h₁ : is_o k₁ k₂ l) (h₂ : is_O f' g' l) : is_o (λ x, k₁ x • f' x) (λ x, k₂ x • g' x) l := by refine ((h₁.norm_norm.mul_is_O h₂.norm_norm).congr _ _).of_norm_norm; by intros; simp only [norm_smul] theorem is_o.smul {k₁ k₂ : α → 𝕜} (h₁ : is_o k₁ k₂ l) (h₂ : is_o f' g' l) : is_o (λ x, k₁ x • f' x) (λ x, k₂ x • g' x) l := by refine ((h₁.norm_norm.mul h₂.norm_norm).congr _ _).of_norm_norm; by intros; simp only [norm_smul] end smul /-! ### Relation between `f = o(g)` and `f / g → 0` -/ theorem is_o.tendsto_0 {f g : α → 𝕜} {l : filter α} (h : is_o f g l) : tendsto (λ x, f x / (g x)) l (𝓝 0) := have eq₁ : is_o (λ x, f x / g x) (λ x, g x / g x) l, from h.mul_is_O (is_O_refl _ _), have eq₂ : is_O (λ x, g x / g x) (λ x, (1 : 𝕜)) l, from is_O_of_le _ (λ x, by by_cases h : ∥g x∥ = 0; simp [h, zero_le_one]), (is_o_one_iff 𝕜).mp (eq₁.trans_is_O eq₂) private theorem is_o_of_tendsto {f g : α → 𝕜} {l : filter α} (hgf : ∀ x, g x = 0 → f x = 0) (h : tendsto (λ x, f x / (g x)) l (𝓝 0)) : is_o f g l := have eq₁ : is_o (λ x, f x / (g x)) (λ x, (1 : 𝕜)) l, from (is_o_one_iff _).mpr h, have eq₂ : is_o (λ x, f x / g x * g x) g l, by convert eq₁.mul_is_O (is_O_refl _ _); simp, have eq₃ : is_O f (λ x, f x / g x * g x) l, begin refine is_O_of_le _ (λ x, _), by_cases H : g x = 0, { simp only [H, hgf _ H, mul_zero] }, { simp only [div_mul_cancel _ H] } end, eq₃.trans_is_o eq₂ theorem is_o_iff_tendsto {f g : α → 𝕜} {l : filter α} (hgf : ∀ x, g x = 0 → f x = 0) : is_o f g l ↔ tendsto (λ x, f x / (g x)) l (𝓝 0) := iff.intro is_o.tendsto_0 (is_o_of_tendsto hgf) /-! ### Miscellanous lemmas -/ theorem is_o_pow_pow {m n : ℕ} (h : m < n) : is_o (λ(x : 𝕜), x^n) (λx, x^m) (𝓝 0) := begin let p := n - m, have nmp : n = m + p := (nat.add_sub_cancel' (le_of_lt h)).symm, have : (λ(x : 𝕜), x^m) = (λx, x^m * 1), by simp only [mul_one], simp only [this, pow_add, nmp], refine is_O.mul_is_o (is_O_refl _ _) ((is_o_one_iff _).2 _), convert (continuous_pow p).tendsto (0 : 𝕜), exact (zero_pow (nat.sub_pos_of_lt h)).symm end theorem is_o_pow_id {n : ℕ} (h : 1 < n) : is_o (λ(x : 𝕜), x^n) (λx, x) (𝓝 0) := by { convert is_o_pow_pow h, simp only [pow_one] } theorem is_O_with.right_le_sub_of_lt_1 {f₁ f₂ : α → E'} (h : is_O_with c f₁ f₂ l) (hc : c < 1) : is_O_with (1 / (1 - c)) f₂ (λx, f₂ x - f₁ x) l := mem_sets_of_superset h $ λ x hx, begin simp only [mem_set_of_eq] at hx ⊢, rw [mul_comm, one_div_eq_inv, ← div_eq_mul_inv, le_div_iff, mul_sub, mul_one, mul_comm], { exact le_trans (sub_le_sub_left hx _) (norm_sub_norm_le _ _) }, { exact sub_pos.2 hc } end theorem is_O_with.right_le_add_of_lt_1 {f₁ f₂ : α → E'} (h : is_O_with c f₁ f₂ l) (hc : c < 1) : is_O_with (1 / (1 - c)) f₂ (λx, f₁ x + f₂ x) l := (h.neg_right.right_le_sub_of_lt_1 hc).neg_right.neg_left.congr rfl (λ x, neg_neg _) (λ x, by rw [neg_sub, sub_neg_eq_add]) end asymptotics
d2db54dd6742bdf2022deaf7226445fa8c667b1a
d1bbf1801b3dcb214451d48214589f511061da63
/src/combinatorics/simple_graph/basic.lean
7a264a9dc80e4fd0d6a01abb199e537cd35b9419
[ "Apache-2.0" ]
permissive
cheraghchi/mathlib
5c366f8c4f8e66973b60c37881889da8390cab86
f29d1c3038422168fbbdb2526abf7c0ff13e86db
refs/heads/master
1,676,577,831,283
1,610,894,638,000
1,610,894,638,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,196
lean
/- Copyright (c) 2020 Aaron Anderson, Jalex Stark, Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Aaron Anderson, Jalex Stark, Kyle Miller, Alena Gusakov -/ import data.fintype.basic import data.sym2 /-! # Simple graphs This module defines simple graphs on a vertex type `V` as an irreflexive symmetric relation. There is a basic API for locally finite graphs and for graphs with finitely many vertices. ## Main definitions * `simple_graph` is a structure for symmetric, irreflexive relations * `neighbor_set` is the `set` of vertices adjacent to a given vertex * `neighbor_finset` is the `finset` of vertices adjacent to a given vertex, if `neighbor_set` is finite * `incidence_set` is the `set` of edges containing a given vertex * `incidence_finset` is the `finset` of edges containing a given vertex, if `incidence_set` is finite ## Implementation notes * A locally finite graph is one with instances `∀ v, fintype (G.neighbor_set v)`. * Given instances `decidable_rel G.adj` and `fintype V`, then the graph is locally finite, too. TODO: This is the simplest notion of an unoriented graph. This should eventually fit into a more complete combinatorics hierarchy which includes multigraphs and directed graphs. We begin with simple graphs in order to start learning what the combinatorics hierarchy should look like. TODO: Part of this would include defining, for example, subgraphs of a simple graph. -/ open finset universe u /-- A simple graph is an irreflexive symmetric relation `adj` on a vertex type `V`. The relation describes which pairs of vertices are adjacent. There is exactly one edge for every pair of adjacent edges; see `simple_graph.edge_set` for the corresponding edge set. -/ @[ext] structure simple_graph (V : Type u) := (adj : V → V → Prop) (sym : symmetric adj . obviously) (loopless : irreflexive adj . obviously) /-- Construct the simple graph induced by the given relation. It symmetrizes the relation and makes it irreflexive. -/ def simple_graph.from_rel {V : Type u} (r : V → V → Prop) : simple_graph V := { adj := λ a b, (a ≠ b) ∧ (r a b ∨ r b a), sym := λ a b ⟨hn, hr⟩, ⟨hn.symm, hr.symm⟩, loopless := λ a ⟨hn, _⟩, hn rfl } noncomputable instance {V : Type u} [fintype V] : fintype (simple_graph V) := by { classical, exact fintype.of_injective simple_graph.adj simple_graph.ext } @[simp] lemma simple_graph.from_rel_adj {V : Type u} (r : V → V → Prop) (v w : V) : (simple_graph.from_rel r).adj v w ↔ v ≠ w ∧ (r v w ∨ r w v) := by refl /-- The complete graph on a type `V` is the simple graph with all pairs of distinct vertices adjacent. -/ def complete_graph (V : Type u) : simple_graph V := { adj := ne } instance (V : Type u) : inhabited (simple_graph V) := ⟨complete_graph V⟩ instance complete_graph_adj_decidable (V : Type u) [decidable_eq V] : decidable_rel (complete_graph V).adj := by { dsimp [complete_graph], apply_instance } namespace simple_graph variables {V : Type u} (G : simple_graph V) /-- `G.neighbor_set v` is the set of vertices adjacent to `v` in `G`. -/ def neighbor_set (v : V) : set V := set_of (G.adj v) lemma ne_of_adj {a b : V} (hab : G.adj a b) : a ≠ b := by { rintro rfl, exact G.loopless a hab } /-- The edges of G consist of the unordered pairs of vertices related by `G.adj`. -/ def edge_set : set (sym2 V) := sym2.from_rel G.sym /-- The `incidence_set` is the set of edges incident to a given vertex. -/ def incidence_set (v : V) : set (sym2 V) := {e ∈ G.edge_set | v ∈ e} lemma incidence_set_subset (v : V) : G.incidence_set v ⊆ G.edge_set := λ _ h, h.1 @[simp] lemma mem_edge_set {v w : V} : ⟦(v, w)⟧ ∈ G.edge_set ↔ G.adj v w := by refl /-- Two vertices are adjacent iff there is an edge between them. The condition `v ≠ w` ensures they are different endpoints of the edge, which is necessary since when `v = w` the existential `∃ (e ∈ G.edge_set), v ∈ e ∧ w ∈ e` is satisfied by every edge incident to `v`. -/ lemma adj_iff_exists_edge {v w : V} : G.adj v w ↔ v ≠ w ∧ ∃ (e ∈ G.edge_set), v ∈ e ∧ w ∈ e := begin refine ⟨λ _, ⟨G.ne_of_adj ‹_›, ⟦(v,w)⟧, _⟩, _⟩, { simpa }, { rintro ⟨hne, e, he, hv⟩, rw sym2.elems_iff_eq hne at hv, subst e, rwa mem_edge_set at he } end lemma edge_other_ne {e : sym2 V} (he : e ∈ G.edge_set) {v : V} (h : v ∈ e) : h.other ≠ v := begin erw [← sym2.mem_other_spec h, sym2.eq_swap] at he, exact G.ne_of_adj he, end instance edges_fintype [decidable_eq V] [fintype V] [decidable_rel G.adj] : fintype G.edge_set := by { dunfold edge_set, exact subtype.fintype _ } instance mem_edge_set_decidable [decidable_rel G.adj] (e : sym2 V) : decidable (e ∈ G.edge_set) := by { dunfold edge_set, apply_instance } instance mem_incidence_set_decidable [decidable_eq V] [decidable_rel G.adj] (v : V) (e : sym2 V) : decidable (e ∈ G.incidence_set v) := by { dsimp [incidence_set], apply_instance } /-- The `edge_set` of the graph as a `finset`. -/ def edge_finset [decidable_eq V] [fintype V] [decidable_rel G.adj] : finset (sym2 V) := set.to_finset G.edge_set @[simp] lemma mem_edge_finset [decidable_eq V] [fintype V] [decidable_rel G.adj] (e : sym2 V) : e ∈ G.edge_finset ↔ e ∈ G.edge_set := by { dunfold edge_finset, simp } @[simp] lemma edge_set_univ_card [decidable_eq V] [fintype V] [decidable_rel G.adj] : (univ : finset G.edge_set).card = G.edge_finset.card := fintype.card_of_subtype G.edge_finset (mem_edge_finset _) @[simp] lemma irrefl {v : V} : ¬G.adj v v := G.loopless v @[symm] lemma edge_symm (u v : V) : G.adj u v ↔ G.adj v u := ⟨λ x, G.sym x, λ x, G.sym x⟩ @[simp] lemma mem_neighbor_set (v w : V) : w ∈ G.neighbor_set v ↔ G.adj v w := by tauto @[simp] lemma mem_incidence_set (v w : V) : ⟦(v, w)⟧ ∈ G.incidence_set v ↔ G.adj v w := by simp [incidence_set] lemma mem_incidence_iff_neighbor {v w : V} : ⟦(v, w)⟧ ∈ G.incidence_set v ↔ w ∈ G.neighbor_set v := by simp only [mem_incidence_set, mem_neighbor_set] lemma adj_incidence_set_inter {v : V} {e : sym2 V} (he : e ∈ G.edge_set) (h : v ∈ e) : G.incidence_set v ∩ G.incidence_set h.other = {e} := begin ext e', simp only [incidence_set, set.mem_sep_eq, set.mem_inter_eq, set.mem_singleton_iff], split, { intro h', rw ←sym2.mem_other_spec h, exact (sym2.elems_iff_eq (edge_other_ne G he h).symm).mp ⟨h'.1.2, h'.2.2⟩, }, { rintro rfl, use [he, h, he], apply sym2.mem_other_mem, }, end /-- The set of common neighbors between two vertices `v` and `w` in a graph `G` is the intersection of the neighbor sets of `v` and `w`. -/ def common_neighbors (v w : V) : set V := G.neighbor_set v ∩ G.neighbor_set w lemma common_neighbors_eq (v w : V) : G.common_neighbors v w = G.neighbor_set v ∩ G.neighbor_set w := rfl lemma mem_common_neighbors {u v w : V} : u ∈ G.common_neighbors v w ↔ G.adj v u ∧ G.adj w u := by simp [common_neighbors] lemma common_neighbors_symm (v w : V) : G.common_neighbors v w = G.common_neighbors w v := by { rw [common_neighbors, set.inter_comm], refl } lemma not_mem_common_neighbors_left (v w : V) : v ∉ G.common_neighbors v w := by simp [common_neighbors] lemma not_mem_common_neighbors_right (v w : V) : w ∉ G.common_neighbors v w := by simp [common_neighbors] lemma common_neighbors_subset_neighbor_set (v w : V) : G.common_neighbors v w ⊆ G.neighbor_set v := by simp [common_neighbors] section incidence variable [decidable_eq V] /-- Given an edge incident to a particular vertex, get the other vertex on the edge. -/ def other_vertex_of_incident {v : V} {e : sym2 V} (h : e ∈ G.incidence_set v) : V := h.2.other' lemma edge_mem_other_incident_set {v : V} {e : sym2 V} (h : e ∈ G.incidence_set v) : e ∈ G.incidence_set (G.other_vertex_of_incident h) := by { use h.1, simp [other_vertex_of_incident, sym2.mem_other_mem'] } lemma incidence_other_prop {v : V} {e : sym2 V} (h : e ∈ G.incidence_set v) : G.other_vertex_of_incident h ∈ G.neighbor_set v := by { cases h with he hv, rwa [←sym2.mem_other_spec' hv, mem_edge_set] at he } @[simp] lemma incidence_other_neighbor_edge {v w : V} (h : w ∈ G.neighbor_set v) : G.other_vertex_of_incident (G.mem_incidence_iff_neighbor.mpr h) = w := sym2.congr_right.mp (sym2.mem_other_spec' (G.mem_incidence_iff_neighbor.mpr h).right) /-- There is an equivalence between the set of edges incident to a given vertex and the set of vertices adjacent to the vertex. -/ @[simps] def incidence_set_equiv_neighbor_set (v : V) : G.incidence_set v ≃ G.neighbor_set v := { to_fun := λ e, ⟨G.other_vertex_of_incident e.2, G.incidence_other_prop e.2⟩, inv_fun := λ w, ⟨⟦(v, w.1)⟧, G.mem_incidence_iff_neighbor.mpr w.2⟩, left_inv := λ x, by simp [other_vertex_of_incident], right_inv := λ ⟨w, hw⟩, by simp } end incidence section finite_at /-! ## Finiteness at a vertex This section contains definitions and lemmas concerning vertices that have finitely many adjacent vertices. We denote this condition by `fintype (G.neighbor_set v)`. We define `G.neighbor_finset v` to be the `finset` version of `G.neighbor_set v`. Use `neighbor_finset_eq_filter` to rewrite this definition as a `filter`. -/ variables (v : V) [fintype (G.neighbor_set v)] /-- `G.neighbors v` is the `finset` version of `G.adj v` in case `G` is locally finite at `v`. -/ def neighbor_finset : finset V := (G.neighbor_set v).to_finset @[simp] lemma mem_neighbor_finset (w : V) : w ∈ G.neighbor_finset v ↔ G.adj v w := by simp [neighbor_finset] /-- `G.degree v` is the number of vertices adjacent to `v`. -/ def degree : ℕ := (G.neighbor_finset v).card @[simp] lemma card_neighbor_set_eq_degree : fintype.card (G.neighbor_set v) = G.degree v := by simp [degree, neighbor_finset] lemma degree_pos_iff_exists_adj : 0 < G.degree v ↔ ∃ w, G.adj v w := by simp only [degree, card_pos, finset.nonempty, mem_neighbor_finset] instance incidence_set_fintype [decidable_eq V] : fintype (G.incidence_set v) := fintype.of_equiv (G.neighbor_set v) (G.incidence_set_equiv_neighbor_set v).symm /-- This is the `finset` version of `incidence_set`. -/ def incidence_finset [decidable_eq V] : finset (sym2 V) := (G.incidence_set v).to_finset @[simp] lemma card_incidence_set_eq_degree [decidable_eq V] : fintype.card (G.incidence_set v) = G.degree v := by { rw fintype.card_congr (G.incidence_set_equiv_neighbor_set v), simp } @[simp] lemma mem_incidence_finset [decidable_eq V] (e : sym2 V) : e ∈ G.incidence_finset v ↔ e ∈ G.incidence_set v := set.mem_to_finset end finite_at section locally_finite /-- A graph is locally finite if every vertex has a finite neighbor set. -/ @[reducible] def locally_finite := Π (v : V), fintype (G.neighbor_set v) variable [locally_finite G] /-- A locally finite simple graph is regular of degree `d` if every vertex has degree `d`. -/ def is_regular_of_degree (d : ℕ) : Prop := ∀ (v : V), G.degree v = d lemma is_regular_of_degree_eq {d : ℕ} (h : G.is_regular_of_degree d) (v : V) : G.degree v = d := h v end locally_finite section finite variables [fintype V] instance neighbor_set_fintype [decidable_rel G.adj] (v : V) : fintype (G.neighbor_set v) := @subtype.fintype _ _ (by { simp_rw mem_neighbor_set, apply_instance }) _ lemma neighbor_finset_eq_filter {v : V} [decidable_rel G.adj] : G.neighbor_finset v = finset.univ.filter (G.adj v) := by { ext, simp } @[simp] lemma complete_graph_degree [decidable_eq V] (v : V) : (complete_graph V).degree v = fintype.card V - 1 := begin convert univ.card.pred_eq_sub_one, erw [degree, neighbor_finset_eq_filter, filter_ne, card_erase_of_mem (mem_univ v)], end lemma complete_graph_is_regular [decidable_eq V] : (complete_graph V).is_regular_of_degree (fintype.card V - 1) := by { intro v, simp } /-- The minimum degree of all vertices -/ def min_degree (G : simple_graph V) [nonempty V] [decidable_rel G.adj] : ℕ := finset.min' (univ.image (λ (v : V), G.degree v)) (nonempty.image univ_nonempty _) /-- The maximum degree of all vertices -/ def max_degree (G : simple_graph V) [nonempty V] [decidable_rel G.adj] : ℕ := finset.max' (univ.image (λ (v : V), G.degree v)) (nonempty.image univ_nonempty _) lemma degree_lt_card_verts (G : simple_graph V) (v : V) : G.degree v < fintype.card V := begin classical, apply finset.card_lt_card, rw finset.ssubset_iff, exact ⟨v, by simp, finset.subset_univ _⟩, end end finite section complement /-! ## Complement of a simple graph This section contains definitions and lemmas concerning the complement of a simple graph. -/ /-- We define `compl G` to be the `simple_graph V` such that no two adjacent vertices in `G` are adjacent in the complement, and every nonadjacent pair of vertices is adjacent (still ensuring that vertices are not adjacent to themselves.) -/ def compl (G : simple_graph V) : simple_graph V := { adj := λ v w, v ≠ w ∧ ¬G.adj v w, sym := λ v w ⟨hne, _⟩, ⟨hne.symm, by rwa edge_symm⟩, loopless := λ v ⟨hne, _⟩, false.elim (hne rfl) } instance has_compl : has_compl (simple_graph V) := { compl := compl } @[simp] lemma compl_adj (G : simple_graph V) (v w : V) : Gᶜ.adj v w ↔ v ≠ w ∧ ¬G.adj v w := iff.rfl @[simp] lemma compl_compl (G : simple_graph V) : Gᶜᶜ = G := begin ext v w, split; simp only [compl_adj, not_and, not_not], { exact λ ⟨hne, h⟩, h hne }, { intro h, simpa [G.ne_of_adj h], }, end @[simp] lemma compl_involutive : function.involutive (@compl V) := compl_compl lemma compl_neighbor_set_disjoint (G : simple_graph V) (v : V) : disjoint (G.neighbor_set v) (Gᶜ.neighbor_set v) := begin rw set.disjoint_iff, rintro w ⟨h, h'⟩, rw [mem_neighbor_set, compl_adj] at h', exact h'.2 h, end lemma neighbor_set_union_compl_neighbor_set_eq (G : simple_graph V) (v : V) : G.neighbor_set v ∪ Gᶜ.neighbor_set v = {v}ᶜ := begin ext w, have h := @ne_of_adj _ G, simp_rw [set.mem_union, mem_neighbor_set, compl_adj, set.mem_compl_eq, set.mem_singleton_iff], tauto, end end complement end simple_graph
d1467a548939bd0ddcf0a10c0b19f182badd6693
94637389e03c919023691dcd05bd4411b1034aa5
/src/zzz_junk/lang/assertion.lean
898db95aebb05df6e8f1752e7dec730e239f3950
[]
no_license
kevinsullivan/complogic-s21
7c4eef2105abad899e46502270d9829d913e8afc
99039501b770248c8ceb39890be5dfe129dc1082
refs/heads/master
1,682,985,669,944
1,621,126,241,000
1,621,126,241,000
335,706,272
0
38
null
1,618,325,669,000
1,612,374,118,000
Lean
UTF-8
Lean
false
false
354
lean
import .imp -- An assertion is a predicate on system state def Assertion := env → Prop -- What it means for program c to satisfy pre/post spec def satisfies (c : cmd) (pre post : Assertion) := ∀ (st st' : env), pre st → c_sem c st st' → post st' -- Hoare triple notation notation pre {c} post := satisfies c pre post -- Hoare triple
a3a0b95a348bef447a9599d68163a7ff6b54b7f5
63abd62053d479eae5abf4951554e1064a4c45b4
/test/squeeze.lean
097f39c666ebc65b22299ed1d1084bbed5627120
[ "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
1,351
lean
import data.nat.basic import tactic.squeeze import data.list.perm namespace tactic namespace interactive setup_tactic_parser /-- version of squeeze_simp that tests whether the output matches the expected output -/ meta def squeeze_simp_test (key : parse cur_pos) (slow_and_accurate : parse (tk "?")?) (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 struct_inst?) (_ : parse (tk "=")) (l : parse simp_arg_list) : tactic unit := do (cfg',c) ← parse_config cfg, squeeze_simp_core slow_and_accurate.is_some no_dflt hs (λ l_no_dft l_args, simp use_iota_eqn l_no_dft l_args attr_names locat cfg') (λ args, guard ((args.map to_string).perm (l.map to_string)) <|> fail!"{args} expected.") end interactive end tactic -- Test that squeeze_simp succeeds when it closes the goal. example : 1 = 1 := by { squeeze_simp_test = [eq_self_iff_true] } -- Test that `squeeze_simp` succeeds when given arguments. example {a b : ℕ} (h : a + a = b) : b + 0 = 2 * a := by { squeeze_simp_test [←h, two_mul] = [←h, two_mul, add_zero] } -- Test that the order of the given hypotheses do not matter. example {a b : ℕ} (h : a + a = b) : b + 0 = 2 * a := by { squeeze_simp_test [←h, two_mul] = [←h, add_zero, two_mul] }
636df6a09f2c4b2a16ae1f1a8e14ae8a628a7060
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/src/Lean/Meta/LevelDefEq.lean
d6968678a515f13a86def09ed763c9dcd80c72d1
[ "Apache-2.0" ]
permissive
gebner/lean4-old
a4129a041af2d4d12afb3a8d4deedabde727719b
ee51cdfaf63ee313c914d83264f91f414a0e3b6e
refs/heads/master
1,683,628,606,745
1,622,651,300,000
1,622,654,405,000
142,608,821
1
0
null
null
null
null
UTF-8
Lean
false
false
11,174
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.CollectMVars import Lean.Util.ReplaceExpr import Lean.Meta.Basic import Lean.Meta.InferType namespace Lean.Meta private partial def decAux? : Level → MetaM (Option Level) | Level.zero _ => return none | Level.param _ _ => return none | Level.mvar mvarId _ => do let mctx ← getMCtx match mctx.getLevelAssignment? mvarId with | some u => decAux? u | none => if (← isReadOnlyLevelMVar mvarId) then return none else let u ← mkFreshLevelMVar assignLevelMVar mvarId (mkLevelSucc u) return u | Level.succ u _ => return u | u => let process (u v : Level) : MetaM (Option Level) := do match (← decAux? u) with | none => return none | some u => do match (← decAux? v) with | none => return none | some v => return mkLevelMax' u v match u with | Level.max u v _ => process u v /- Remark: If `decAux? v` returns `some ...`, then `imax u v` is equivalent to `max u v`. -/ | Level.imax u v _ => process u v | _ => unreachable! def decLevel? (u : Level) : MetaM (Option Level) := do let mctx ← getMCtx match (← decAux? u) with | some v => return some v | none => do modify fun s => { s with mctx := mctx } return none def decLevel (u : Level) : MetaM Level := do match (← decLevel? u) with | some u => return u | none => throwError "invalid universe level, {u} is not greater than 0" /- This method is useful for inferring universe level parameters for function that take arguments such as `{α : Type u}`. Recall that `Type u` is `Sort (u+1)` in Lean. Thus, given `α`, we must infer its universe level, and then decrement 1 to obtain `u`. -/ def getDecLevel (type : Expr) : MetaM Level := do decLevel (← getLevel type) /-- Return true iff `lvl` occurs in `max u_1 ... u_n` and `lvl != u_i` for all `i in [1, n]`. That is, `lvl` is a proper level subterm of some `u_i`. -/ private def strictOccursMax (lvl : Level) : Level → Bool | Level.max u v _ => visit u || visit v | _ => false where visit : Level → Bool | Level.max u v _ => visit u || visit v | u => u != lvl && lvl.occurs u /-- `mkMaxArgsDiff mvarId (max u_1 ... (mvar mvarId) ... u_n) v` => `max v u_1 ... u_n` -/ private def mkMaxArgsDiff (mvarId : MVarId) : Level → Level → Level | Level.max u v _, acc => mkMaxArgsDiff mvarId v <| mkMaxArgsDiff mvarId u acc | l@(Level.mvar id _), acc => if id != mvarId then mkLevelMax' acc l else acc | l, acc => mkLevelMax' acc l /-- Solve `?m =?= max ?m v` by creating a fresh metavariable `?n` and assigning `?m := max ?n v` -/ private def solveSelfMax (mvarId : MVarId) (v : Level) : MetaM Unit := do assert! v.isMax let n ← mkFreshLevelMVar assignLevelMVar mvarId <| mkMaxArgsDiff mvarId v n private def postponeIsLevelDefEq (lhs : Level) (rhs : Level) : MetaM Unit := do let ref ← getRef let ctx ← read trace[Meta.isLevelDefEq.stuck] "{lhs} =?= {rhs}" modifyPostponed fun postponed => postponed.push { lhs := lhs, rhs := rhs, ref := ref, ctx? := ctx.defEqCtx? } mutual private partial def solve (u v : Level) : MetaM LBool := do match u, v with | Level.mvar mvarId _, _ => if (← isReadOnlyLevelMVar mvarId) then return LBool.undef else if !u.occurs v then assignLevelMVar u.mvarId! v return LBool.true else if v.isMax && !strictOccursMax u v then solveSelfMax u.mvarId! v return LBool.true else return LBool.undef | Level.zero _, Level.max v₁ v₂ _ => Bool.toLBool <$> (isLevelDefEqAux levelZero v₁ <&&> isLevelDefEqAux levelZero v₂) | Level.zero _, Level.imax _ v₂ _ => Bool.toLBool <$> isLevelDefEqAux levelZero v₂ | Level.zero _, Level.succ .. => return LBool.false | Level.succ u _, v => if v.isParam then return LBool.false else if u.isMVar && u.occurs v then return LBool.undef else match (← Meta.decLevel? v) with | some v => Bool.toLBool <$> isLevelDefEqAux u v | none => return LBool.undef | _, _ => return LBool.undef partial def isLevelDefEqAux : Level → Level → MetaM Bool | Level.succ lhs _, Level.succ rhs _ => isLevelDefEqAux lhs rhs | lhs, rhs => do if lhs.getLevelOffset == rhs.getLevelOffset then return lhs.getOffset == rhs.getOffset else trace[Meta.isLevelDefEq.step] "{lhs} =?= {rhs}" let lhs' ← instantiateLevelMVars lhs let lhs' := lhs'.normalize let rhs' ← instantiateLevelMVars rhs let rhs' := rhs'.normalize if lhs != lhs' || rhs != rhs' then isLevelDefEqAux lhs' rhs' else let r ← solve lhs rhs; if r != LBool.undef then return r == LBool.true else let r ← solve rhs lhs; if r != LBool.undef then return r == LBool.true else do let mctx ← getMCtx if !mctx.hasAssignableLevelMVar lhs && !mctx.hasAssignableLevelMVar rhs then let ctx ← read if ctx.config.isDefEqStuckEx && (lhs.isMVar || rhs.isMVar) then do trace[Meta.isLevelDefEq.stuck] "{lhs} =?= {rhs}" Meta.throwIsDefEqStuck else return false else postponeIsLevelDefEq lhs rhs return true end def isListLevelDefEqAux : List Level → List Level → MetaM Bool | [], [] => return true | u::us, v::vs => isLevelDefEqAux u v <&&> isListLevelDefEqAux us vs | _, _ => return false private def getNumPostponed : MetaM Nat := do return (← getPostponed).size open Std (PersistentArray) def getResetPostponed : MetaM (PersistentArray PostponedEntry) := do let ps ← getPostponed setPostponed {} return ps /-- Annotate any constant and sort in `e` that satisfies `p` with `pp.universes true` -/ private def exposeRelevantUniverses (e : Expr) (p : Level → Bool) : Expr := e.replace fun | Expr.const _ us _ => if us.any p then some (e.setPPUniverses true) else none | Expr.sort u _ => if p u then some (e.setPPUniverses true) else none | _ => none private def mkLeveErrorMessageCore (header : String) (entry : PostponedEntry) : MetaM MessageData := do match entry.ctx? with | none => return m!"{header}{indentD m!"{entry.lhs} =?= {entry.rhs}"}" | some ctx => withLCtx ctx.lctx ctx.localInstances do let s := entry.lhs.collectMVars entry.rhs.collectMVars /- `p u` is true if it contains a universe metavariable in `s` -/ let p (u : Level) := u.any fun | Level.mvar m _ => s.contains m | _ => false let lhs := exposeRelevantUniverses (← instantiateMVars ctx.lhs) p let rhs := exposeRelevantUniverses (← instantiateMVars ctx.rhs) p try addMessageContext m!"{header}{indentD m!"{entry.lhs} =?= {entry.rhs}"}\nwhile trying to unify{indentD m!"{lhs} : {← inferType lhs}"}\nwith{indentD m!"{rhs} : {← inferType rhs}"}" catch _ => addMessageContext m!"{header}{indentD m!"{entry.lhs} =?= {entry.rhs}"}\nwhile trying to unify{indentD lhs}\nwith{indentD rhs}" def mkLevelStuckErrorMessage (entry : PostponedEntry) : MetaM MessageData := do mkLeveErrorMessageCore "stuck at solving universe constraint" entry def mkLevelErrorMessage (entry : PostponedEntry) : MetaM MessageData := do mkLeveErrorMessageCore "failed to solve universe constraint" entry private def processPostponedStep (exceptionOnFailure : Bool) : MetaM Bool := traceCtx `Meta.isLevelDefEq.postponed.step do let ps ← getResetPostponed for p in ps do unless (← withReader (fun ctx => { ctx with defEqCtx? := p.ctx? }) <| isLevelDefEqAux p.lhs p.rhs) do if exceptionOnFailure then throwError (← mkLevelErrorMessage p) else return false return true partial def processPostponed (mayPostpone : Bool := true) (exceptionOnFailure := false) : MetaM Bool := do if (← getNumPostponed) == 0 then return true else traceCtx `Meta.isLevelDefEq.postponed do let rec loop : MetaM Bool := do let numPostponed ← getNumPostponed if numPostponed == 0 then return true else trace[Meta.isLevelDefEq.postponed] "processing #{numPostponed} postponed is-def-eq level constraints" if !(← processPostponedStep exceptionOnFailure) then return false else let numPostponed' ← getNumPostponed if numPostponed' == 0 then return true else if numPostponed' < numPostponed then loop else trace[Meta.isLevelDefEq.postponed] "no progress solving pending is-def-eq level constraints" return mayPostpone loop /-- `checkpointDefEq x` executes `x` and process all postponed universe level constraints produced by `x`. We keep the modifications only if `processPostponed` return true and `x` returned `true`. Remark: postponed universe level constraints must be solved before returning. Otherwise, we don't know whether `x` really succeeded. -/ @[specialize] def checkpointDefEq (x : MetaM Bool) (mayPostpone : Bool := true) : MetaM Bool := do let s ← saveState let postponed ← getResetPostponed try if (← x) then if (← processPostponed mayPostpone) then let newPostponed ← getPostponed setPostponed (postponed ++ newPostponed) return true else s.restore return false else s.restore return false catch ex => s.restore throw ex def isLevelDefEq (u v : Level) : MetaM Bool := traceCtx `Meta.isLevelDefEq do let b ← checkpointDefEq (mayPostpone := true) <| Meta.isLevelDefEqAux u v trace[Meta.isLevelDefEq] "{u} =?= {v} ... {if b then "success" else "failure"}" return b def isExprDefEq (t s : Expr) : MetaM Bool := traceCtx `Meta.isDefEq <| withReader (fun ctx => { ctx with defEqCtx? := some { lhs := t, rhs := s, lctx := ctx.lctx, localInstances := ctx.localInstances } }) do let b ← checkpointDefEq (mayPostpone := true) <| Meta.isExprDefEqAux t s trace[Meta.isDefEq] "{t} =?= {s} ... {if b then "success" else "failure"}" return b abbrev isDefEq (t s : Expr) : MetaM Bool := isExprDefEq t s def isExprDefEqGuarded (a b : Expr) : MetaM Bool := do try isExprDefEq a b catch _ => return false abbrev isDefEqGuarded (t s : Expr) : MetaM Bool := isExprDefEqGuarded t s def isDefEqNoConstantApprox (t s : Expr) : MetaM Bool := approxDefEq <| isDefEq t s builtin_initialize registerTraceClass `Meta.isLevelDefEq registerTraceClass `Meta.isLevelDefEq.step registerTraceClass `Meta.isLevelDefEq.postponed end Lean.Meta
a14957e565ce2f4970db9ec7ff78d9c09945d2de
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/topology/algebra/infinite_sum.lean
bb266a8a5917c41fa75b986d31b3e4428a08620a
[ "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
58,944
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import algebra.big_operators.intervals import algebra.big_operators.nat_antidiagonal import data.equiv.encodable.lattice import topology.algebra.mul_action import topology.algebra.ordered.monotone_convergence import topology.instances.real /-! # Infinite sum over a topological monoid This sum is known as unconditionally convergent, as it sums to the same value under all possible permutations. For Euclidean spaces (finite dimensional Banach spaces) this is equivalent to absolute convergence. Note: There are summable sequences which are not unconditionally convergent! The other way holds generally, see `has_sum.tendsto_sum_nat`. ## References * Bourbaki: General Topology (1995), Chapter 3 §5 (Infinite sums in commutative groups) -/ noncomputable theory open finset filter function classical open_locale topological_space classical big_operators nnreal variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} section has_sum variables [add_comm_monoid α] [topological_space α] /-- Infinite sum on a topological monoid The `at_top` filter on `finset β` is the limit of all finite sets towards the entire type. So we sum up bigger and bigger sets. This sum operation is invariant under reordering. In particular, the function `ℕ → ℝ` sending `n` to `(-1)^n / (n+1)` does not have a sum for this definition, but a series which is absolutely convergent will have the correct sum. This is based on Mario Carneiro's [infinite sum `df-tsms` in Metamath](http://us.metamath.org/mpeuni/df-tsms.html). For the definition or many statements, `α` does not need to be a topological monoid. We only add this assumption later, for the lemmas where it is relevant. -/ def has_sum (f : β → α) (a : α) : Prop := tendsto (λs:finset β, ∑ b in s, f b) at_top (𝓝 a) /-- `summable f` means that `f` has some (infinite) sum. Use `tsum` to get the value. -/ def summable (f : β → α) : Prop := ∃a, has_sum f a /-- `∑' i, f i` is the sum of `f` it exists, or 0 otherwise -/ @[irreducible] def tsum {β} (f : β → α) := if h : summable f then classical.some h else 0 -- see Note [operator precedence of big operators] notation `∑'` binders `, ` r:(scoped:67 f, tsum f) := r variables {f g : β → α} {a b : α} {s : finset β} lemma summable.has_sum (ha : summable f) : has_sum f (∑'b, f b) := by simp [ha, tsum]; exact some_spec ha lemma has_sum.summable (h : has_sum f a) : summable f := ⟨a, h⟩ /-- Constant zero function has sum `0` -/ lemma has_sum_zero : has_sum (λb, 0 : β → α) 0 := by simp [has_sum, tendsto_const_nhds] lemma has_sum_empty [is_empty β] : has_sum f 0 := by convert has_sum_zero lemma summable_zero : summable (λb, 0 : β → α) := has_sum_zero.summable lemma summable_empty [is_empty β] : summable f := has_sum_empty.summable lemma tsum_eq_zero_of_not_summable (h : ¬ summable f) : ∑'b, f b = 0 := by simp [tsum, h] lemma summable_congr (hfg : ∀b, f b = g b) : summable f ↔ summable g := iff_of_eq (congr_arg summable $ funext hfg) lemma summable.congr (hf : summable f) (hfg : ∀b, f b = g b) : summable g := (summable_congr hfg).mp hf lemma has_sum.has_sum_of_sum_eq {g : γ → α} (h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∑ x in u', g x = ∑ b in v', f b) (hf : has_sum g a) : has_sum f a := le_trans (map_at_top_finset_sum_le_of_sum_eq h_eq) hf lemma has_sum_iff_has_sum {g : γ → α} (h₁ : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∑ x in u', g x = ∑ b in v', f b) (h₂ : ∀v:finset β, ∃u:finset γ, ∀u', u ⊆ u' → ∃v', v ⊆ v' ∧ ∑ b in v', f b = ∑ x in u', g x) : has_sum f a ↔ has_sum g a := ⟨has_sum.has_sum_of_sum_eq h₂, has_sum.has_sum_of_sum_eq h₁⟩ lemma function.injective.has_sum_iff {g : γ → β} (hg : injective g) (hf : ∀ x ∉ set.range g, f x = 0) : has_sum (f ∘ g) a ↔ has_sum f a := by simp only [has_sum, tendsto, hg.map_at_top_finset_sum_eq hf] lemma function.injective.summable_iff {g : γ → β} (hg : injective g) (hf : ∀ x ∉ set.range g, f x = 0) : summable (f ∘ g) ↔ summable f := exists_congr $ λ _, hg.has_sum_iff hf lemma has_sum_subtype_iff_of_support_subset {s : set β} (hf : support f ⊆ s) : has_sum (f ∘ coe : s → α) a ↔ has_sum f a := subtype.coe_injective.has_sum_iff $ by simpa using support_subset_iff'.1 hf lemma has_sum_subtype_iff_indicator {s : set β} : has_sum (f ∘ coe : s → α) a ↔ has_sum (s.indicator f) a := by rw [← set.indicator_range_comp, subtype.range_coe, has_sum_subtype_iff_of_support_subset set.support_indicator_subset] @[simp] lemma has_sum_subtype_support : has_sum (f ∘ coe : support f → α) a ↔ has_sum f a := has_sum_subtype_iff_of_support_subset $ set.subset.refl _ lemma has_sum_fintype [fintype β] (f : β → α) : has_sum f (∑ b, f b) := order_top.tendsto_at_top_nhds _ protected lemma finset.has_sum (s : finset β) (f : β → α) : has_sum (f ∘ coe : (↑s : set β) → α) (∑ b in s, f b) := by { rw ← sum_attach, exact has_sum_fintype _ } protected lemma finset.summable (s : finset β) (f : β → α) : summable (f ∘ coe : (↑s : set β) → α) := (s.has_sum f).summable protected lemma set.finite.summable {s : set β} (hs : s.finite) (f : β → α) : summable (f ∘ coe : s → α) := by convert hs.to_finset.summable f; simp only [hs.coe_to_finset] /-- If a function `f` vanishes outside of a finite set `s`, then it `has_sum` `∑ b in s, f b`. -/ lemma has_sum_sum_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : has_sum f (∑ b in s, f b) := (has_sum_subtype_iff_of_support_subset $ support_subset_iff'.2 hf).1 $ s.has_sum f lemma summable_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : summable f := (has_sum_sum_of_ne_finset_zero hf).summable lemma has_sum_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) : has_sum f (f b) := suffices has_sum f (∑ b' in {b}, f b'), by simpa using this, has_sum_sum_of_ne_finset_zero $ by simpa [hf] lemma has_sum_ite_eq (b : β) [decidable_pred (= b)] (a : α) : has_sum (λb', if b' = b then a else 0) a := begin convert has_sum_single b _, { exact (if_pos rfl).symm }, assume b' hb', exact if_neg hb' end lemma equiv.has_sum_iff (e : γ ≃ β) : has_sum (f ∘ e) a ↔ has_sum f a := e.injective.has_sum_iff $ by simp lemma function.injective.has_sum_range_iff {g : γ → β} (hg : injective g) : has_sum (λ x : set.range g, f x) a ↔ has_sum (f ∘ g) a := (equiv.of_injective g hg).has_sum_iff.symm lemma equiv.summable_iff (e : γ ≃ β) : summable (f ∘ e) ↔ summable f := exists_congr $ λ a, e.has_sum_iff lemma summable.prod_symm {f : β × γ → α} (hf : summable f) : summable (λ p : γ × β, f p.swap) := (equiv.prod_comm γ β).summable_iff.2 hf lemma equiv.has_sum_iff_of_support {g : γ → α} (e : support f ≃ support g) (he : ∀ x : support f, g (e x) = f x) : has_sum f a ↔ has_sum g a := have (g ∘ coe) ∘ e = f ∘ coe, from funext he, by rw [← has_sum_subtype_support, ← this, e.has_sum_iff, has_sum_subtype_support] lemma has_sum_iff_has_sum_of_ne_zero_bij {g : γ → α} (i : support g → β) (hi : ∀ ⦃x y⦄, i x = i y → (x : γ) = y) (hf : support f ⊆ set.range i) (hfg : ∀ x, f (i x) = g x) : has_sum f a ↔ has_sum g a := iff.symm $ equiv.has_sum_iff_of_support (equiv.of_bijective (λ x, ⟨i x, λ hx, x.coe_prop $ hfg x ▸ hx⟩) ⟨λ x y h, subtype.ext $ hi $ subtype.ext_iff.1 h, λ y, (hf y.coe_prop).imp $ λ x hx, subtype.ext hx⟩) hfg lemma equiv.summable_iff_of_support {g : γ → α} (e : support f ≃ support g) (he : ∀ x : support f, g (e x) = f x) : summable f ↔ summable g := exists_congr $ λ _, e.has_sum_iff_of_support he protected lemma has_sum.map [add_comm_monoid γ] [topological_space γ] (hf : has_sum f a) (g : α →+ γ) (hg : continuous g) : has_sum (g ∘ f) (g a) := have g ∘ (λs:finset β, ∑ b in s, f b) = (λs:finset β, ∑ b in s, g (f b)), from funext $ g.map_sum _, show tendsto (λs:finset β, ∑ b in s, g (f b)) at_top (𝓝 (g a)), from this ▸ (hg.tendsto a).comp hf protected lemma summable.map [add_comm_monoid γ] [topological_space γ] (hf : summable f) (g : α →+ γ) (hg : continuous g) : summable (g ∘ f) := (hf.has_sum.map g hg).summable /-- If `f : ℕ → α` has sum `a`, then the partial sums `∑_{i=0}^{n-1} f i` converge to `a`. -/ lemma has_sum.tendsto_sum_nat {f : ℕ → α} (h : has_sum f a) : tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) := h.comp tendsto_finset_range lemma has_sum.unique {a₁ a₂ : α} [t2_space α] : has_sum f a₁ → has_sum f a₂ → a₁ = a₂ := tendsto_nhds_unique lemma summable.has_sum_iff_tendsto_nat [t2_space α] {f : ℕ → α} {a : α} (hf : summable f) : has_sum f a ↔ tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) := begin refine ⟨λ h, h.tendsto_sum_nat, λ h, _⟩, rw tendsto_nhds_unique h hf.has_sum.tendsto_sum_nat, exact hf.has_sum end lemma equiv.summable_iff_of_has_sum_iff {α' : Type*} [add_comm_monoid α'] [topological_space α'] (e : α' ≃ α) {f : β → α} {g : γ → α'} (he : ∀ {a}, has_sum f (e a) ↔ has_sum g a) : summable f ↔ summable g := ⟨λ ⟨a, ha⟩, ⟨e.symm a, he.1 $ by rwa [e.apply_symm_apply]⟩, λ ⟨a, ha⟩, ⟨e a, he.2 ha⟩⟩ variable [has_continuous_add α] lemma has_sum.add (hf : has_sum f a) (hg : has_sum g b) : has_sum (λb, f b + g b) (a + b) := by simp only [has_sum, sum_add_distrib]; exact hf.add hg lemma summable.add (hf : summable f) (hg : summable g) : summable (λb, f b + g b) := (hf.has_sum.add hg.has_sum).summable lemma has_sum_sum {f : γ → β → α} {a : γ → α} {s : finset γ} : (∀i∈s, has_sum (f i) (a i)) → has_sum (λb, ∑ i in s, f i b) (∑ i in s, a i) := finset.induction_on s (by simp only [has_sum_zero, sum_empty, forall_true_iff]) (by simp only [has_sum.add, sum_insert, mem_insert, forall_eq_or_imp, forall_2_true_iff, not_false_iff, forall_true_iff] {contextual := tt}) lemma summable_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) : summable (λb, ∑ i in s, f i b) := (has_sum_sum $ assume i hi, (hf i hi).has_sum).summable lemma has_sum.add_disjoint {s t : set β} (hs : disjoint s t) (ha : has_sum (f ∘ coe : s → α) a) (hb : has_sum (f ∘ coe : t → α) b) : has_sum (f ∘ coe : s ∪ t → α) (a + b) := begin rw has_sum_subtype_iff_indicator at *, rw set.indicator_union_of_disjoint hs, exact ha.add hb end lemma has_sum.add_is_compl {s t : set β} (hs : is_compl s t) (ha : has_sum (f ∘ coe : s → α) a) (hb : has_sum (f ∘ coe : t → α) b) : has_sum f (a + b) := by simpa [← hs.compl_eq] using (has_sum_subtype_iff_indicator.1 ha).add (has_sum_subtype_iff_indicator.1 hb) lemma has_sum.add_compl {s : set β} (ha : has_sum (f ∘ coe : s → α) a) (hb : has_sum (f ∘ coe : sᶜ → α) b) : has_sum f (a + b) := ha.add_is_compl is_compl_compl hb lemma summable.add_compl {s : set β} (hs : summable (f ∘ coe : s → α)) (hsc : summable (f ∘ coe : sᶜ → α)) : summable f := (hs.has_sum.add_compl hsc.has_sum).summable lemma has_sum.compl_add {s : set β} (ha : has_sum (f ∘ coe : sᶜ → α) a) (hb : has_sum (f ∘ coe : s → α) b) : has_sum f (a + b) := ha.add_is_compl is_compl_compl.symm hb lemma has_sum.even_add_odd {f : ℕ → α} (he : has_sum (λ k, f (2 * k)) a) (ho : has_sum (λ k, f (2 * k + 1)) b) : has_sum f (a + b) := begin have := mul_right_injective₀ (@two_ne_zero ℕ _ _), replace he := this.has_sum_range_iff.2 he, replace ho := ((add_left_injective 1).comp this).has_sum_range_iff.2 ho, refine he.add_is_compl _ ho, simpa [(∘)] using nat.is_compl_even_odd end lemma summable.compl_add {s : set β} (hs : summable (f ∘ coe : sᶜ → α)) (hsc : summable (f ∘ coe : s → α)) : summable f := (hs.has_sum.compl_add hsc.has_sum).summable lemma summable.even_add_odd {f : ℕ → α} (he : summable (λ k, f (2 * k))) (ho : summable (λ k, f (2 * k + 1))) : summable f := (he.has_sum.even_add_odd ho.has_sum).summable lemma has_sum.sigma [regular_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α} (ha : has_sum f a) (hf : ∀b, has_sum (λc, f ⟨b, c⟩) (g b)) : has_sum g a := begin refine (at_top_basis.tendsto_iff (closed_nhds_basis a)).mpr _, rintros s ⟨hs, hsc⟩, rcases mem_at_top_sets.mp (ha hs) with ⟨u, hu⟩, use [u.image sigma.fst, trivial], intros bs hbs, simp only [set.mem_preimage, ge_iff_le, finset.le_iff_subset] at hu, have : tendsto (λ t : finset (Σ b, γ b), ∑ p in t.filter (λ p, p.1 ∈ bs), f p) at_top (𝓝 $ ∑ b in bs, g b), { simp only [← sigma_preimage_mk, sum_sigma], refine tendsto_finset_sum _ (λ b hb, _), change tendsto (λ t, (λ t, ∑ s in t, f ⟨b, s⟩) (preimage t (sigma.mk b) _)) at_top (𝓝 (g b)), exact tendsto.comp (hf b) (tendsto_finset_preimage_at_top_at_top _) }, refine hsc.mem_of_tendsto this (eventually_at_top.2 ⟨u, λ t ht, hu _ (λ x hx, _)⟩), exact mem_filter.2 ⟨ht hx, hbs $ mem_image_of_mem _ hx⟩ end /-- If a series `f` on `β × γ` has sum `a` and for each `b` the restriction of `f` to `{b} × γ` has sum `g b`, then the series `g` has sum `a`. -/ lemma has_sum.prod_fiberwise [regular_space α] {f : β × γ → α} {g : β → α} {a : α} (ha : has_sum f a) (hf : ∀b, has_sum (λc, f (b, c)) (g b)) : has_sum g a := has_sum.sigma ((equiv.sigma_equiv_prod β γ).has_sum_iff.2 ha) hf lemma summable.sigma' [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) (hf : ∀b, summable (λc, f ⟨b, c⟩)) : summable (λb, ∑'c, f ⟨b, c⟩) := (ha.has_sum.sigma (assume b, (hf b).has_sum)).summable lemma has_sum.sigma_of_has_sum [regular_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α} (ha : has_sum g a) (hf : ∀b, has_sum (λc, f ⟨b, c⟩) (g b)) (hf' : summable f) : has_sum f a := by simpa [(hf'.has_sum.sigma hf).unique ha] using hf'.has_sum end has_sum section tsum variables [add_comm_monoid α] [topological_space α] [t2_space α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum.tsum_eq (ha : has_sum f a) : ∑'b, f b = a := (summable.has_sum ⟨a, ha⟩).unique ha lemma summable.has_sum_iff (h : summable f) : has_sum f a ↔ ∑'b, f b = a := iff.intro has_sum.tsum_eq (assume eq, eq ▸ h.has_sum) @[simp] lemma tsum_zero : ∑'b:β, (0:α) = 0 := has_sum_zero.tsum_eq @[simp] lemma tsum_empty [is_empty β] : ∑'b, f b = 0 := has_sum_empty.tsum_eq lemma tsum_eq_sum {f : β → α} {s : finset β} (hf : ∀b∉s, f b = 0) : ∑' b, f b = ∑ b in s, f b := (has_sum_sum_of_ne_finset_zero hf).tsum_eq lemma tsum_congr {α β : Type*} [add_comm_monoid α] [topological_space α] {f g : β → α} (hfg : ∀ b, f b = g b) : ∑' b, f b = ∑' b, g b := congr_arg tsum (funext hfg) lemma tsum_fintype [fintype β] (f : β → α) : ∑'b, f b = ∑ b, f b := (has_sum_fintype f).tsum_eq lemma tsum_bool (f : bool → α) : ∑' i : bool, f i = f false + f true := by { rw [tsum_fintype, finset.sum_eq_add]; simp } @[simp] lemma finset.tsum_subtype (s : finset β) (f : β → α) : ∑' x : {x // x ∈ s}, f x = ∑ x in s, f x := (s.has_sum f).tsum_eq @[simp] lemma finset.tsum_subtype' (s : finset β) (f : β → α) : ∑' x : (s : set β), f x = ∑ x in s, f x := s.tsum_subtype f lemma tsum_eq_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) : ∑'b, f b = f b := (has_sum_single b hf).tsum_eq @[simp] lemma tsum_ite_eq (b : β) [decidable_pred (= b)] (a : α) : ∑' b', (if b' = b then a else 0) = a := (has_sum_ite_eq b a).tsum_eq lemma tsum_dite_right (P : Prop) [decidable P] (x : β → ¬ P → α) : ∑' (b : β), (if h : P then (0 : α) else x b h) = if h : P then (0 : α) else ∑' (b : β), x b h := by by_cases hP : P; simp [hP] lemma tsum_dite_left (P : Prop) [decidable P] (x : β → P → α) : ∑' (b : β), (if h : P then x b h else 0) = if h : P then (∑' (b : β), x b h) else 0 := by by_cases hP : P; simp [hP] lemma equiv.tsum_eq_tsum_of_has_sum_iff_has_sum {α' : Type*} [add_comm_monoid α'] [topological_space α'] (e : α' ≃ α) (h0 : e 0 = 0) {f : β → α} {g : γ → α'} (h : ∀ {a}, has_sum f (e a) ↔ has_sum g a) : ∑' b, f b = e (∑' c, g c) := by_cases (assume : summable g, (h.mpr this.has_sum).tsum_eq) (assume hg : ¬ summable g, have hf : ¬ summable f, from mt (e.summable_iff_of_has_sum_iff @h).1 hg, by simp [tsum, hf, hg, h0]) lemma tsum_eq_tsum_of_has_sum_iff_has_sum {f : β → α} {g : γ → α} (h : ∀{a}, has_sum f a ↔ has_sum g a) : ∑'b, f b = ∑'c, g c := (equiv.refl α).tsum_eq_tsum_of_has_sum_iff_has_sum rfl @h lemma equiv.tsum_eq (j : γ ≃ β) (f : β → α) : ∑'c, f (j c) = ∑'b, f b := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ a, j.has_sum_iff lemma equiv.tsum_eq_tsum_of_support {f : β → α} {g : γ → α} (e : support f ≃ support g) (he : ∀ x, g (e x) = f x) : (∑' x, f x) = ∑' y, g y := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, e.has_sum_iff_of_support he lemma tsum_eq_tsum_of_ne_zero_bij {g : γ → α} (i : support g → β) (hi : ∀ ⦃x y⦄, i x = i y → (x : γ) = y) (hf : support f ⊆ set.range i) (hfg : ∀ x, f (i x) = g x) : ∑' x, f x = ∑' y, g y := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, has_sum_iff_has_sum_of_ne_zero_bij i hi hf hfg lemma tsum_subtype (s : set β) (f : β → α) : ∑' x:s, f x = ∑' x, s.indicator f x := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, has_sum_subtype_iff_indicator section has_continuous_add variable [has_continuous_add α] lemma tsum_add (hf : summable f) (hg : summable g) : ∑'b, (f b + g b) = (∑'b, f b) + (∑'b, g b) := (hf.has_sum.add hg.has_sum).tsum_eq lemma tsum_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) : ∑'b, ∑ i in s, f i b = ∑ i in s, ∑'b, f i b := (has_sum_sum $ assume i hi, (hf i hi).has_sum).tsum_eq lemma tsum_sigma' [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (h₁ : ∀b, summable (λc, f ⟨b, c⟩)) (h₂ : summable f) : ∑'p, f p = ∑'b c, f ⟨b, c⟩ := (h₂.has_sum.sigma (assume b, (h₁ b).has_sum)).tsum_eq.symm lemma tsum_prod' [regular_space α] {f : β × γ → α} (h : summable f) (h₁ : ∀b, summable (λc, f (b, c))) : ∑'p, f p = ∑'b c, f (b, c) := (h.has_sum.prod_fiberwise (assume b, (h₁ b).has_sum)).tsum_eq.symm lemma tsum_comm' [regular_space α] {f : β → γ → α} (h : summable (function.uncurry f)) (h₁ : ∀b, summable (f b)) (h₂ : ∀ c, summable (λ b, f b c)) : ∑' c b, f b c = ∑' b c, f b c := begin erw [← tsum_prod' h h₁, ← tsum_prod' h.prod_symm h₂, ← (equiv.prod_comm β γ).tsum_eq], refl, assumption end end has_continuous_add section encodable open encodable variable [encodable γ] /-- You can compute a sum over an encodably type by summing over the natural numbers and taking a supremum. This is useful for outer measures. -/ theorem tsum_supr_decode₂ [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (s : γ → β) : ∑' i : ℕ, m (⨆ b ∈ decode₂ γ i, s b) = ∑' b : γ, m (s b) := begin have H : ∀ n, m (⨆ b ∈ decode₂ γ n, s b) ≠ 0 → (decode₂ γ n).is_some, { intros n h, cases decode₂ γ n with b, { refine (h $ by simp [m0]).elim }, { exact rfl } }, symmetry, refine tsum_eq_tsum_of_ne_zero_bij (λ a, option.get (H a.1 a.2)) _ _ _, { rintros ⟨m, hm⟩ ⟨n, hn⟩ e, have := mem_decode₂.1 (option.get_mem (H n hn)), rwa [← e, mem_decode₂.1 (option.get_mem (H m hm))] at this }, { intros b h, refine ⟨⟨encode b, _⟩, _⟩, { simp only [mem_support, encodek₂] at h ⊢, convert h, simp [set.ext_iff, encodek₂] }, { exact option.get_of_mem _ (encodek₂ _) } }, { rintros ⟨n, h⟩, dsimp only [subtype.coe_mk], transitivity, swap, rw [show decode₂ γ n = _, from option.get_mem (H n h)], congr, simp [ext_iff, -option.some_get] } end /-- `tsum_supr_decode₂` specialized to the complete lattice of sets. -/ theorem tsum_Union_decode₂ (m : set β → α) (m0 : m ∅ = 0) (s : γ → set β) : ∑' i, m (⋃ b ∈ decode₂ γ i, s b) = ∑' b, m (s b) := tsum_supr_decode₂ m m0 s /-! Some properties about measure-like functions. These could also be functions defined on complete sublattices of sets, with the property that they are countably sub-additive. `R` will probably be instantiated with `(≤)` in all applications. -/ /-- If a function is countably sub-additive then it is sub-additive on encodable types -/ theorem rel_supr_tsum [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) ∑' i, m (s i)) (s : γ → β) : R (m (⨆ b : γ, s b)) ∑' b : γ, m (s b) := by { rw [← supr_decode₂, ← tsum_supr_decode₂ _ m0 s], exact m_supr _ } /-- If a function is countably sub-additive then it is sub-additive on finite sets -/ theorem rel_supr_sum [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) (∑' i, m (s i))) (s : δ → β) (t : finset δ) : R (m (⨆ d ∈ t, s d)) (∑ d in t, m (s d)) := by { cases t.nonempty_encodable, rw [supr_subtype'], convert rel_supr_tsum m m0 R m_supr _, rw [← finset.tsum_subtype], assumption } /-- If a function is countably sub-additive then it is binary sub-additive -/ theorem rel_sup_add [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) (∑' i, m (s i))) (s₁ s₂ : β) : R (m (s₁ ⊔ s₂)) (m s₁ + m s₂) := begin convert rel_supr_tsum m m0 R m_supr (λ b, cond b s₁ s₂), { simp only [supr_bool_eq, cond] }, { rw [tsum_fintype, fintype.sum_bool, cond, cond] } end end encodable variables [has_continuous_add α] lemma tsum_add_tsum_compl {s : set β} (hs : summable (f ∘ coe : s → α)) (hsc : summable (f ∘ coe : sᶜ → α)) : (∑' x : s, f x) + (∑' x : sᶜ, f x) = ∑' x, f x := (hs.has_sum.add_compl hsc.has_sum).tsum_eq.symm lemma tsum_union_disjoint {s t : set β} (hd : disjoint s t) (hs : summable (f ∘ coe : s → α)) (ht : summable (f ∘ coe : t → α)) : (∑' x : s ∪ t, f x) = (∑' x : s, f x) + (∑' x : t, f x) := (hs.has_sum.add_disjoint hd ht.has_sum).tsum_eq lemma tsum_even_add_odd {f : ℕ → α} (he : summable (λ k, f (2 * k))) (ho : summable (λ k, f (2 * k + 1))) : (∑' k, f (2 * k)) + (∑' k, f (2 * k + 1)) = ∑' k, f k := (he.has_sum.even_add_odd ho.has_sum).tsum_eq.symm end tsum section pi variables {ι : Type*} {π : α → Type*} [∀ x, add_comm_monoid (π x)] [∀ x, topological_space (π x)] lemma pi.has_sum {f : ι → ∀ x, π x} {g : ∀ x, π x} : has_sum f g ↔ ∀ x, has_sum (λ i, f i x) (g x) := by simp only [has_sum, tendsto_pi, sum_apply] lemma pi.summable {f : ι → ∀ x, π x} : summable f ↔ ∀ x, summable (λ i, f i x) := by simp only [summable, pi.has_sum, skolem] lemma tsum_apply [∀ x, t2_space (π x)] {f : ι → ∀ x, π x}{x : α} (hf : summable f) : (∑' i, f i) x = ∑' i, f i x := (pi.has_sum.mp hf.has_sum x).tsum_eq.symm end pi section topological_group variables [add_comm_group α] [topological_space α] [topological_add_group α] variables {f g : β → α} {a a₁ a₂ : α} -- `by simpa using` speeds up elaboration. Why? lemma has_sum.neg (h : has_sum f a) : has_sum (λb, - f b) (- a) := by simpa only using h.map (-add_monoid_hom.id α) continuous_neg lemma summable.neg (hf : summable f) : summable (λb, - f b) := hf.has_sum.neg.summable lemma summable.of_neg (hf : summable (λb, - f b)) : summable f := by simpa only [neg_neg] using hf.neg lemma summable_neg_iff : summable (λ b, - f b) ↔ summable f := ⟨summable.of_neg, summable.neg⟩ lemma has_sum.sub (hf : has_sum f a₁) (hg : has_sum g a₂) : has_sum (λb, f b - g b) (a₁ - a₂) := by { simp only [sub_eq_add_neg], exact hf.add hg.neg } lemma summable.sub (hf : summable f) (hg : summable g) : summable (λb, f b - g b) := (hf.has_sum.sub hg.has_sum).summable lemma summable.trans_sub (hg : summable g) (hfg : summable (λb, f b - g b)) : summable f := by simpa only [sub_add_cancel] using hfg.add hg lemma summable_iff_of_summable_sub (hfg : summable (λb, f b - g b)) : summable f ↔ summable g := ⟨λ hf, hf.trans_sub $ by simpa only [neg_sub] using hfg.neg, λ hg, hg.trans_sub hfg⟩ lemma has_sum.update (hf : has_sum f a₁) (b : β) [decidable_eq β] (a : α) : has_sum (update f b a) (a - f b + a₁) := begin convert ((has_sum_ite_eq b _).add hf), ext b', by_cases h : b' = b, { rw [h, update_same], simp only [eq_self_iff_true, if_true, sub_add_cancel] }, simp only [h, update_noteq, if_false, ne.def, zero_add, not_false_iff], end lemma summable.update (hf : summable f) (b : β) [decidable_eq β] (a : α) : summable (update f b a) := (hf.has_sum.update b a).summable lemma has_sum.has_sum_compl_iff {s : set β} (hf : has_sum (f ∘ coe : s → α) a₁) : has_sum (f ∘ coe : sᶜ → α) a₂ ↔ has_sum f (a₁ + a₂) := begin refine ⟨λ h, hf.add_compl h, λ h, _⟩, rw [has_sum_subtype_iff_indicator] at hf ⊢, rw [set.indicator_compl], simpa only [add_sub_cancel'] using h.sub hf end lemma has_sum.has_sum_iff_compl {s : set β} (hf : has_sum (f ∘ coe : s → α) a₁) : has_sum f a₂ ↔ has_sum (f ∘ coe : sᶜ → α) (a₂ - a₁) := iff.symm $ hf.has_sum_compl_iff.trans $ by rw [add_sub_cancel'_right] lemma summable.summable_compl_iff {s : set β} (hf : summable (f ∘ coe : s → α)) : summable (f ∘ coe : sᶜ → α) ↔ summable f := ⟨λ ⟨a, ha⟩, (hf.has_sum.has_sum_compl_iff.1 ha).summable, λ ⟨a, ha⟩, (hf.has_sum.has_sum_iff_compl.1 ha).summable⟩ protected lemma finset.has_sum_compl_iff (s : finset β) : has_sum (λ x : {x // x ∉ s}, f x) a ↔ has_sum f (a + ∑ i in s, f i) := (s.has_sum f).has_sum_compl_iff.trans $ by rw [add_comm] protected lemma finset.has_sum_iff_compl (s : finset β) : has_sum f a ↔ has_sum (λ x : {x // x ∉ s}, f x) (a - ∑ i in s, f i) := (s.has_sum f).has_sum_iff_compl protected lemma finset.summable_compl_iff (s : finset β) : summable (λ x : {x // x ∉ s}, f x) ↔ summable f := (s.summable f).summable_compl_iff lemma set.finite.summable_compl_iff {s : set β} (hs : s.finite) : summable (f ∘ coe : sᶜ → α) ↔ summable f := (hs.summable f).summable_compl_iff lemma has_sum_ite_eq_extract [decidable_eq β] (hf : has_sum f a) (b : β) : has_sum (λ n, ite (n = b) 0 (f n)) (a - f b) := begin convert hf.update b 0 using 1, { ext n, rw function.update_apply, }, { rw [sub_add_eq_add_sub, zero_add], }, end section tsum variables [t2_space α] lemma tsum_neg (hf : summable f) : ∑'b, - f b = - ∑'b, f b := hf.has_sum.neg.tsum_eq lemma tsum_sub (hf : summable f) (hg : summable g) : ∑'b, (f b - g b) = ∑'b, f b - ∑'b, g b := (hf.has_sum.sub hg.has_sum).tsum_eq lemma sum_add_tsum_compl {s : finset β} (hf : summable f) : (∑ x in s, f x) + (∑' x : (↑s : set β)ᶜ, f x) = ∑' x, f x := ((s.has_sum f).add_compl (s.summable_compl_iff.2 hf).has_sum).tsum_eq.symm /-- Let `f : β → α` be a sequence with summable series and let `b ∈ β` be an index. Lemma `tsum_ite_eq_extract` writes `Σ f n` as the sum of `f b` plus the series of the remaining terms. -/ lemma tsum_ite_eq_extract [decidable_eq β] (hf : summable f) (b : β) : ∑' n, f n = f b + ∑' n, ite (n = b) 0 (f n) := begin rw (has_sum_ite_eq_extract hf.has_sum b).tsum_eq, exact (add_sub_cancel'_right _ _).symm, end end tsum /-! ### Sums on subtypes If `s` is a finset of `α`, we show that the summability of `f` in the whole space and on the subtype `univ - s` are equivalent, and relate their sums. For a function defined on `ℕ`, we deduce the formula `(∑ i in range k, f i) + (∑' i, f (i + k)) = (∑' i, f i)`, in `sum_add_tsum_nat_add`. -/ section subtype lemma has_sum_nat_add_iff {f : ℕ → α} (k : ℕ) {a : α} : has_sum (λ n, f (n + k)) a ↔ has_sum f (a + ∑ i in range k, f i) := begin refine iff.trans _ ((range k).has_sum_compl_iff), rw [← (not_mem_range_equiv k).symm.has_sum_iff], refl end lemma summable_nat_add_iff {f : ℕ → α} (k : ℕ) : summable (λ n, f (n + k)) ↔ summable f := iff.symm $ (equiv.add_right (∑ i in range k, f i)).summable_iff_of_has_sum_iff $ λ a, (has_sum_nat_add_iff k).symm lemma has_sum_nat_add_iff' {f : ℕ → α} (k : ℕ) {a : α} : has_sum (λ n, f (n + k)) (a - ∑ i in range k, f i) ↔ has_sum f a := by simp [has_sum_nat_add_iff] lemma sum_add_tsum_nat_add [t2_space α] {f : ℕ → α} (k : ℕ) (h : summable f) : (∑ i in range k, f i) + (∑' i, f (i + k)) = ∑' i, f i := by simpa only [add_comm] using ((has_sum_nat_add_iff k).1 ((summable_nat_add_iff k).2 h).has_sum).unique h.has_sum lemma tsum_eq_zero_add [t2_space α] {f : ℕ → α} (hf : summable f) : ∑'b, f b = f 0 + ∑'b, f (b + 1) := by simpa only [sum_range_one] using (sum_add_tsum_nat_add 1 hf).symm /-- For `f : ℕ → α`, then `∑' k, f (k + i)` tends to zero. This does not require a summability assumption on `f`, as otherwise all sums are zero. -/ lemma tendsto_sum_nat_add [t2_space α] (f : ℕ → α) : tendsto (λ i, ∑' k, f (k + i)) at_top (𝓝 0) := begin by_cases hf : summable f, { have h₀ : (λ i, (∑' i, f i) - ∑ j in range i, f j) = λ i, ∑' (k : ℕ), f (k + i), { ext1 i, rw [sub_eq_iff_eq_add, add_comm, sum_add_tsum_nat_add i hf] }, have h₁ : tendsto (λ i : ℕ, ∑' i, f i) at_top (𝓝 (∑' i, f i)) := tendsto_const_nhds, simpa only [h₀, sub_self] using tendsto.sub h₁ hf.has_sum.tendsto_sum_nat }, { convert tendsto_const_nhds, ext1 i, rw ← summable_nat_add_iff i at hf, { exact tsum_eq_zero_of_not_summable hf }, { apply_instance } } end end subtype end topological_group section topological_ring variables [semiring α] [topological_space α] [topological_ring α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum.mul_left (a₂) (h : has_sum f a₁) : has_sum (λb, a₂ * f b) (a₂ * a₁) := by simpa only using h.map (add_monoid_hom.mul_left a₂) (continuous_const.mul continuous_id) lemma has_sum.mul_right (a₂) (hf : has_sum f a₁) : has_sum (λb, f b * a₂) (a₁ * a₂) := by simpa only using hf.map (add_monoid_hom.mul_right a₂) (continuous_id.mul continuous_const) lemma summable.mul_left (a) (hf : summable f) : summable (λb, a * f b) := (hf.has_sum.mul_left _).summable lemma summable.mul_right (a) (hf : summable f) : summable (λb, f b * a) := (hf.has_sum.mul_right _).summable section tsum variables [t2_space α] lemma summable.tsum_mul_left (a) (hf : summable f) : ∑'b, a * f b = a * ∑'b, f b := (hf.has_sum.mul_left _).tsum_eq lemma summable.tsum_mul_right (a) (hf : summable f) : (∑'b, f b * a) = (∑'b, f b) * a := (hf.has_sum.mul_right _).tsum_eq end tsum end topological_ring section has_continuous_smul variables {R : Type*} [monoid R] [topological_space R] [topological_space α] [add_comm_monoid α] [distrib_mul_action R α] [has_continuous_smul R α] {f : β → α} lemma has_sum.smul {a : α} {r : R} (hf : has_sum f a) : has_sum (λ z, r • f z) (r • a) := hf.map (distrib_mul_action.to_add_monoid_hom α r) (continuous_const.smul continuous_id) lemma summable.smul {r : R} (hf : summable f) : summable (λ z, r • f z) := hf.has_sum.smul.summable lemma tsum_smul [t2_space α] {r : R} (hf : summable f) : ∑' z, r • f z = r • ∑' z, f z := hf.has_sum.smul.tsum_eq end has_continuous_smul section division_ring variables [division_ring α] [topological_space α] [topological_ring α] {f g : β → α} {a a₁ a₂ : α} lemma has_sum.div_const (h : has_sum f a) (b : α) : has_sum (λ x, f x / b) (a / b) := by simp only [div_eq_mul_inv, h.mul_right b⁻¹] lemma summable.div_const (h : summable f) (b : α) : summable (λ x, f x / b) := (h.has_sum.div_const b).summable lemma has_sum_mul_left_iff (h : a₂ ≠ 0) : has_sum f a₁ ↔ has_sum (λb, a₂ * f b) (a₂ * a₁) := ⟨has_sum.mul_left _, λ H, by simpa only [inv_mul_cancel_left₀ h] using H.mul_left a₂⁻¹⟩ lemma has_sum_mul_right_iff (h : a₂ ≠ 0) : has_sum f a₁ ↔ has_sum (λb, f b * a₂) (a₁ * a₂) := ⟨has_sum.mul_right _, λ H, by simpa only [mul_inv_cancel_right₀ h] using H.mul_right a₂⁻¹⟩ lemma summable_mul_left_iff (h : a ≠ 0) : summable f ↔ summable (λb, a * f b) := ⟨λ H, H.mul_left _, λ H, by simpa only [inv_mul_cancel_left₀ h] using H.mul_left a⁻¹⟩ lemma summable_mul_right_iff (h : a ≠ 0) : summable f ↔ summable (λb, f b * a) := ⟨λ H, H.mul_right _, λ H, by simpa only [mul_inv_cancel_right₀ h] using H.mul_right a⁻¹⟩ lemma tsum_mul_left [t2_space α] : (∑' x, a * f x) = a * ∑' x, f x := if hf : summable f then hf.tsum_mul_left a else if ha : a = 0 then by simp [ha] else by rw [tsum_eq_zero_of_not_summable hf, tsum_eq_zero_of_not_summable (mt (summable_mul_left_iff ha).2 hf), mul_zero] lemma tsum_mul_right [t2_space α] : (∑' x, f x * a) = (∑' x, f x) * a := if hf : summable f then hf.tsum_mul_right a else if ha : a = 0 then by simp [ha] else by rw [tsum_eq_zero_of_not_summable hf, tsum_eq_zero_of_not_summable (mt (summable_mul_right_iff ha).2 hf), zero_mul] end division_ring section order_topology variables [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum_le (h : ∀b, f b ≤ g b) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ := le_of_tendsto_of_tendsto' hf hg $ assume s, sum_le_sum $ assume b _, h b @[mono] lemma has_sum_mono (hf : has_sum f a₁) (hg : has_sum g a₂) (h : f ≤ g) : a₁ ≤ a₂ := has_sum_le h hf hg lemma has_sum_le_of_sum_le (hf : has_sum f a) (h : ∀ s : finset β, ∑ b in s, f b ≤ a₂) : a ≤ a₂ := le_of_tendsto' hf h lemma le_has_sum_of_le_sum (hf : has_sum f a) (h : ∀ s : finset β, a₂ ≤ ∑ b in s, f b) : a₂ ≤ a := ge_of_tendsto' hf h lemma has_sum_le_inj {g : γ → α} (i : β → γ) (hi : injective i) (hs : ∀c∉set.range i, 0 ≤ g c) (h : ∀b, f b ≤ g (i b)) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ := have has_sum (λc, (partial_inv i c).cases_on' 0 f) a₁, begin refine (has_sum_iff_has_sum_of_ne_zero_bij (i ∘ coe) _ _ _).2 hf, { exact assume c₁ c₂ eq, hi eq }, { intros c hc, rw [mem_support] at hc, cases eq : partial_inv i c with b; rw eq at hc, { contradiction }, { rw [partial_inv_of_injective hi] at eq, exact ⟨⟨b, hc⟩, eq⟩ } }, { assume c, simp [partial_inv_left hi, option.cases_on'] } end, begin refine has_sum_le (assume c, _) this hg, by_cases c ∈ set.range i, { rcases h with ⟨b, rfl⟩, rw [partial_inv_left hi, option.cases_on'], exact h _ }, { have : partial_inv i c = none := dif_neg h, rw [this, option.cases_on'], exact hs _ h } end lemma tsum_le_tsum_of_inj {g : γ → α} (i : β → γ) (hi : injective i) (hs : ∀c∉set.range i, 0 ≤ g c) (h : ∀b, f b ≤ g (i b)) (hf : summable f) (hg : summable g) : tsum f ≤ tsum g := has_sum_le_inj i hi hs h hf.has_sum hg.has_sum lemma sum_le_has_sum (s : finset β) (hs : ∀ b∉s, 0 ≤ f b) (hf : has_sum f a) : ∑ b in s, f b ≤ a := ge_of_tendsto hf (eventually_at_top.2 ⟨s, λ t hst, sum_le_sum_of_subset_of_nonneg hst $ λ b hbt hbs, hs b hbs⟩) lemma is_lub_has_sum (h : ∀ b, 0 ≤ f b) (hf : has_sum f a) : is_lub (set.range (λ s : finset β, ∑ b in s, f b)) a := is_lub_of_tendsto (finset.sum_mono_set_of_nonneg h) hf lemma le_has_sum (hf : has_sum f a) (b : β) (hb : ∀ b' ≠ b, 0 ≤ f b') : f b ≤ a := calc f b = ∑ b in {b}, f b : finset.sum_singleton.symm ... ≤ a : sum_le_has_sum _ (by { convert hb, simp }) hf lemma sum_le_tsum {f : β → α} (s : finset β) (hs : ∀ b∉s, 0 ≤ f b) (hf : summable f) : ∑ b in s, f b ≤ ∑' b, f b := sum_le_has_sum s hs hf.has_sum lemma le_tsum (hf : summable f) (b : β) (hb : ∀ b' ≠ b, 0 ≤ f b') : f b ≤ ∑' b, f b := le_has_sum (summable.has_sum hf) b hb lemma tsum_le_tsum (h : ∀b, f b ≤ g b) (hf : summable f) (hg : summable g) : ∑'b, f b ≤ ∑'b, g b := has_sum_le h hf.has_sum hg.has_sum @[mono] lemma tsum_mono (hf : summable f) (hg : summable g) (h : f ≤ g) : ∑' n, f n ≤ ∑' n, g n := tsum_le_tsum h hf hg lemma tsum_le_of_sum_le (hf : summable f) (h : ∀ s : finset β, ∑ b in s, f b ≤ a₂) : ∑' b, f b ≤ a₂ := has_sum_le_of_sum_le hf.has_sum h lemma tsum_le_of_sum_le' (ha₂ : 0 ≤ a₂) (h : ∀ s : finset β, ∑ b in s, f b ≤ a₂) : ∑' b, f b ≤ a₂ := begin by_cases hf : summable f, { exact tsum_le_of_sum_le hf h }, { rw tsum_eq_zero_of_not_summable hf, exact ha₂ } end lemma has_sum.nonneg (h : ∀ b, 0 ≤ g b) (ha : has_sum g a) : 0 ≤ a := has_sum_le h has_sum_zero ha lemma has_sum.nonpos (h : ∀ b, g b ≤ 0) (ha : has_sum g a) : a ≤ 0 := has_sum_le h ha has_sum_zero lemma tsum_nonneg (h : ∀ b, 0 ≤ g b) : 0 ≤ ∑'b, g b := begin by_cases hg : summable g, { exact hg.has_sum.nonneg h }, { simp [tsum_eq_zero_of_not_summable hg] } end lemma tsum_nonpos (h : ∀ b, f b ≤ 0) : ∑'b, f b ≤ 0 := begin by_cases hf : summable f, { exact hf.has_sum.nonpos h }, { simp [tsum_eq_zero_of_not_summable hf] } end end order_topology section ordered_topological_group variables [ordered_add_comm_group α] [topological_space α] [topological_add_group α] [order_closed_topology α] {f g : β → α} {a₁ a₂ : α} lemma has_sum_lt {i : β} (h : ∀ (b : β), f b ≤ g b) (hi : f i < g i) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ < a₂ := have update f i 0 ≤ update g i 0 := update_le_update_iff.mpr ⟨rfl.le, λ i _, h i⟩, have 0 - f i + a₁ ≤ 0 - g i + a₂ := has_sum_le this (hf.update i 0) (hg.update i 0), by simpa only [zero_sub, add_neg_cancel_left] using add_lt_add_of_lt_of_le hi this @[mono] lemma has_sum_strict_mono (hf : has_sum f a₁) (hg : has_sum g a₂) (h : f < g) : a₁ < a₂ := let ⟨hle, i, hi⟩ := pi.lt_def.mp h in has_sum_lt hle hi hf hg lemma tsum_lt_tsum {i : β} (h : ∀ (b : β), f b ≤ g b) (hi : f i < g i) (hf : summable f) (hg : summable g) : ∑' n, f n < ∑' n, g n := has_sum_lt h hi hf.has_sum hg.has_sum @[mono] lemma tsum_strict_mono (hf : summable f) (hg : summable g) (h : f < g) : ∑' n, f n < ∑' n, g n := let ⟨hle, i, hi⟩ := pi.lt_def.mp h in tsum_lt_tsum hle hi hf hg lemma tsum_pos (hsum : summable g) (hg : ∀ b, 0 ≤ g b) (i : β) (hi : 0 < g i) : 0 < ∑' b, g b := by { rw ← tsum_zero, exact tsum_lt_tsum hg hi summable_zero hsum } end ordered_topological_group section canonically_ordered variables [canonically_ordered_add_monoid α] [topological_space α] [order_closed_topology α] variables {f : β → α} {a : α} lemma le_has_sum' (hf : has_sum f a) (b : β) : f b ≤ a := le_has_sum hf b $ λ _ _, zero_le _ lemma le_tsum' (hf : summable f) (b : β) : f b ≤ ∑' b, f b := le_tsum hf b $ λ _ _, zero_le _ lemma has_sum_zero_iff : has_sum f 0 ↔ ∀ x, f x = 0 := begin refine ⟨_, λ h, _⟩, { contrapose!, exact λ ⟨x, hx⟩ h, irrefl _ (lt_of_lt_of_le (pos_iff_ne_zero.2 hx) (le_has_sum' h x)) }, { convert has_sum_zero, exact funext h } end lemma tsum_eq_zero_iff (hf : summable f) : ∑' i, f i = 0 ↔ ∀ x, f x = 0 := by rw [←has_sum_zero_iff, hf.has_sum_iff] lemma tsum_ne_zero_iff (hf : summable f) : ∑' i, f i ≠ 0 ↔ ∃ x, f x ≠ 0 := by rw [ne.def, tsum_eq_zero_iff hf, not_forall] lemma is_lub_has_sum' (hf : has_sum f a) : is_lub (set.range (λ s : finset β, ∑ b in s, f b)) a := is_lub_of_tendsto (finset.sum_mono_set f) hf end canonically_ordered section uniform_group variables [add_comm_group α] [uniform_space α] lemma summable_iff_cauchy_seq_finset [complete_space α] {f : β → α} : summable f ↔ cauchy_seq (λ (s : finset β), ∑ b in s, f b) := cauchy_map_iff_exists_tendsto.symm variables [uniform_add_group α] {f g : β → α} {a a₁ a₂ : α} lemma cauchy_seq_finset_iff_vanishing : cauchy_seq (λ (s : finset β), ∑ b in s, f b) ↔ ∀ e ∈ 𝓝 (0:α), (∃s:finset β, ∀t, disjoint t s → ∑ b in t, f b ∈ e) := begin simp only [cauchy_seq, cauchy_map_iff, and_iff_right at_top_ne_bot, prod_at_top_at_top_eq, uniformity_eq_comap_nhds_zero α, tendsto_comap_iff, (∘)], rw [tendsto_at_top'], split, { assume h e he, rcases h e he with ⟨⟨s₁, s₂⟩, h⟩, use [s₁ ∪ s₂], assume t ht, specialize h (s₁ ∪ s₂, (s₁ ∪ s₂) ∪ t) ⟨le_sup_left, le_sup_of_le_left le_sup_right⟩, simpa only [finset.sum_union ht.symm, add_sub_cancel'] using h }, { assume h e he, rcases exists_nhds_half_neg he with ⟨d, hd, hde⟩, rcases h d hd with ⟨s, h⟩, use [(s, s)], rintros ⟨t₁, t₂⟩ ⟨ht₁, ht₂⟩, have : ∑ b in t₂, f b - ∑ b in t₁, f b = ∑ b in t₂ \ s, f b - ∑ b in t₁ \ s, f b, { simp only [(finset.sum_sdiff ht₁).symm, (finset.sum_sdiff ht₂).symm, add_sub_add_right_eq_sub] }, simp only [this], exact hde _ (h _ finset.sdiff_disjoint) _ (h _ finset.sdiff_disjoint) } end local attribute [instance] topological_add_group.regular_space /-- The sum over the complement of a finset tends to `0` when the finset grows to cover the whole space. This does not need a summability assumption, as otherwise all sums are zero. -/ lemma tendsto_tsum_compl_at_top_zero [t1_space α] (f : β → α) : tendsto (λ (s : finset β), ∑' b : {x // x ∉ s}, f b) at_top (𝓝 0) := begin by_cases H : summable f, { assume e he, rcases nhds_is_closed he with ⟨o, ho, oe, o_closed⟩, simp only [le_eq_subset, set.mem_preimage, mem_at_top_sets, filter.mem_map, ge_iff_le], obtain ⟨s, hs⟩ : ∃ (s : finset β), ∀ (t : finset β), disjoint t s → ∑ (b : β) in t, f b ∈ o := cauchy_seq_finset_iff_vanishing.1 (tendsto.cauchy_seq H.has_sum) o ho, refine ⟨s, λ a sa, oe _⟩, have A : summable (λ b : {x // x ∉ a}, f b) := a.summable_compl_iff.2 H, apply is_closed.mem_of_tendsto o_closed A.has_sum (eventually_of_forall (λ b, _)), have : disjoint (finset.image (λ (i : {x // x ∉ a}), (i : β)) b) s, { apply disjoint_left.2 (λ i hi his, _), rcases mem_image.1 hi with ⟨i', hi', rfl⟩, exact i'.2 (sa his), }, convert hs _ this using 1, rw sum_image, assume i hi j hj hij, exact subtype.ext hij }, { convert tendsto_const_nhds, ext s, apply tsum_eq_zero_of_not_summable, rwa finset.summable_compl_iff } end variable [complete_space α] lemma summable_iff_vanishing : summable f ↔ ∀ e ∈ 𝓝 (0:α), (∃s:finset β, ∀t, disjoint t s → ∑ b in t, f b ∈ e) := by rw [summable_iff_cauchy_seq_finset, cauchy_seq_finset_iff_vanishing] /- TODO: generalize to monoid with a uniform continuous subtraction operator: `(a + b) - b = a` -/ lemma summable.summable_of_eq_zero_or_self (hf : summable f) (h : ∀b, g b = 0 ∨ g b = f b) : summable g := summable_iff_vanishing.2 $ assume e he, let ⟨s, hs⟩ := summable_iff_vanishing.1 hf e he in ⟨s, assume t ht, have eq : ∑ b in t.filter (λb, g b = f b), f b = ∑ b in t, g b := calc ∑ b in t.filter (λb, g b = f b), f b = ∑ b in t.filter (λb, g b = f b), g b : finset.sum_congr rfl (assume b hb, (finset.mem_filter.1 hb).2.symm) ... = ∑ b in t, g b : begin refine finset.sum_subset (finset.filter_subset _ _) _, assume b hbt hb, simp only [(∉), finset.mem_filter, and_iff_right hbt] at hb, exact (h b).resolve_right hb end, eq ▸ hs _ $ finset.disjoint_of_subset_left (finset.filter_subset _ _) ht⟩ protected lemma summable.indicator (hf : summable f) (s : set β) : summable (s.indicator f) := hf.summable_of_eq_zero_or_self $ set.indicator_eq_zero_or_self _ _ lemma summable.comp_injective {i : γ → β} (hf : summable f) (hi : injective i) : summable (f ∘ i) := begin simpa only [set.indicator_range_comp] using (hi.summable_iff _).2 (hf.indicator (set.range i)), exact λ x hx, set.indicator_of_not_mem hx _ end lemma summable.subtype (hf : summable f) (s : set β) : summable (f ∘ coe : s → α) := hf.comp_injective subtype.coe_injective lemma summable_subtype_and_compl {s : set β} : summable (λ x : s, f x) ∧ summable (λ x : sᶜ, f x) ↔ summable f := ⟨and_imp.2 summable.add_compl, λ h, ⟨h.subtype s, h.subtype sᶜ⟩⟩ lemma summable.sigma_factor {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) (b : β) : summable (λc, f ⟨b, c⟩) := ha.comp_injective sigma_mk_injective lemma summable.sigma [t1_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) : summable (λb, ∑'c, f ⟨b, c⟩) := ha.sigma' (λ b, ha.sigma_factor b) lemma summable.prod_factor {f : β × γ → α} (h : summable f) (b : β) : summable (λ c, f (b, c)) := h.comp_injective $ λ c₁ c₂ h, (prod.ext_iff.1 h).2 lemma tsum_sigma [t1_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) : ∑'p, f p = ∑'b c, f ⟨b, c⟩ := tsum_sigma' (λ b, ha.sigma_factor b) ha lemma tsum_prod [t1_space α] {f : β × γ → α} (h : summable f) : ∑'p, f p = ∑'b c, f ⟨b, c⟩ := tsum_prod' h h.prod_factor lemma tsum_comm [t1_space α] {f : β → γ → α} (h : summable (function.uncurry f)) : ∑' c b, f b c = ∑' b c, f b c := tsum_comm' h h.prod_factor h.prod_symm.prod_factor end uniform_group section topological_group variables {G : Type*} [topological_space G] [add_comm_group G] [topological_add_group G] {f : α → G} lemma summable.vanishing (hf : summable f) ⦃e : set G⦄ (he : e ∈ 𝓝 (0 : G)) : ∃ s : finset α, ∀ t, disjoint t s → ∑ k in t, f k ∈ e := begin letI : uniform_space G := topological_add_group.to_uniform_space G, letI : uniform_add_group G := topological_add_group_is_uniform, rcases hf with ⟨y, hy⟩, exact cauchy_seq_finset_iff_vanishing.1 hy.cauchy_seq e he end /-- Series divergence test: if `f` is a convergent series, then `f x` tends to zero along `cofinite`. -/ lemma summable.tendsto_cofinite_zero (hf : summable f) : tendsto f cofinite (𝓝 0) := begin intros e he, rw [filter.mem_map], rcases hf.vanishing he with ⟨s, hs⟩, refine s.eventually_cofinite_nmem.mono (λ x hx, _), by simpa using hs {x} (disjoint_singleton_left.2 hx) end lemma summable.tendsto_at_top_zero {f : ℕ → G} (hf : summable f) : tendsto f at_top (𝓝 0) := by { rw ←nat.cofinite_eq_at_top, exact hf.tendsto_cofinite_zero } lemma summable.tendsto_top_of_pos {α : Type*} [linear_ordered_field α] [topological_space α] [order_topology α] {f : ℕ → α} (hf : summable f⁻¹) (hf' : ∀ n, 0 < f n) : tendsto f at_top at_top := begin rw [show f = f⁻¹⁻¹, by { ext, simp }], apply filter.tendsto.inv_tendsto_zero, apply tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (summable.tendsto_at_top_zero hf), rw eventually_iff_exists_mem, refine ⟨set.Ioi 0, Ioi_mem_at_top _, λ _ _, _⟩, rw [set.mem_Ioi, inv_eq_one_div, one_div, pi.inv_apply, _root_.inv_pos], exact hf' _, end end topological_group section linear_order /-! For infinite sums taking values in a linearly ordered monoid, the existence of a least upper bound for the finite sums is a criterion for summability. This criterion is useful when applied in a linearly ordered monoid which is also a complete or conditionally complete linear order, such as `ℝ`, `ℝ≥0`, `ℝ≥0∞`, because it is then easy to check the existence of a least upper bound. -/ lemma has_sum_of_is_lub_of_nonneg [linear_ordered_add_comm_monoid β] [topological_space β] [order_topology β] {f : α → β} (b : β) (h : ∀ b, 0 ≤ f b) (hf : is_lub (set.range (λ s, ∑ a in s, f a)) b) : has_sum f b := tendsto_at_top_is_lub (finset.sum_mono_set_of_nonneg h) hf lemma has_sum_of_is_lub [canonically_linear_ordered_add_monoid β] [topological_space β] [order_topology β] {f : α → β} (b : β) (hf : is_lub (set.range (λ s, ∑ a in s, f a)) b) : has_sum f b := tendsto_at_top_is_lub (finset.sum_mono_set f) hf lemma summable_abs_iff [linear_ordered_add_comm_group β] [uniform_space β] [uniform_add_group β] [complete_space β] {f : α → β} : summable (λ x, |f x|) ↔ summable f := have h1 : ∀ x : {x | 0 ≤ f x}, |f x| = f x := λ x, abs_of_nonneg x.2, have h2 : ∀ x : {x | 0 ≤ f x}ᶜ, |f x| = -f x := λ x, abs_of_neg (not_le.1 x.2), calc summable (λ x, |f x|) ↔ summable (λ x : {x | 0 ≤ f x}, |f x|) ∧ summable (λ x : {x | 0 ≤ f x}ᶜ, |f x|) : summable_subtype_and_compl.symm ... ↔ summable (λ x : {x | 0 ≤ f x}, f x) ∧ summable (λ x : {x | 0 ≤ f x}ᶜ, -f x) : by simp only [h1, h2] ... ↔ _ : by simp only [summable_neg_iff, summable_subtype_and_compl] alias summable_abs_iff ↔ summable.of_abs summable.abs end linear_order section cauchy_seq open filter /-- If the extended distance between consecutive points of a sequence is estimated by a summable series of `nnreal`s, then the original sequence is a Cauchy sequence. -/ lemma cauchy_seq_of_edist_le_of_summable [pseudo_emetric_space α] {f : ℕ → α} (d : ℕ → ℝ≥0) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) (hd : summable d) : cauchy_seq f := begin refine emetric.cauchy_seq_iff_nnreal.2 (λ ε εpos, _), -- Actually we need partial sums of `d` to be a Cauchy sequence replace hd : cauchy_seq (λ (n : ℕ), ∑ x in range n, d x) := let ⟨_, H⟩ := hd in H.tendsto_sum_nat.cauchy_seq, -- Now we take the same `N` as in one of the definitions of a Cauchy sequence refine (metric.cauchy_seq_iff'.1 hd ε (nnreal.coe_pos.2 εpos)).imp (λ N hN n hn, _), have hsum := hN n hn, -- We simplify the known inequality rw [dist_nndist, nnreal.nndist_eq, ← sum_range_add_sum_Ico _ hn, add_sub_cancel_left] at hsum, norm_cast at hsum, replace hsum := lt_of_le_of_lt (le_max_left _ _) hsum, rw edist_comm, -- Then use `hf` to simplify the goal to the same form apply lt_of_le_of_lt (edist_le_Ico_sum_of_edist_le hn (λ k _ _, hf k)), assumption_mod_cast end /-- If the distance between consecutive points of a sequence is estimated by a summable series, then the original sequence is a Cauchy sequence. -/ lemma cauchy_seq_of_dist_le_of_summable [pseudo_metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) : cauchy_seq f := begin refine metric.cauchy_seq_iff'.2 (λε εpos, _), replace hd : cauchy_seq (λ (n : ℕ), ∑ x in range n, d x) := let ⟨_, H⟩ := hd in H.tendsto_sum_nat.cauchy_seq, refine (metric.cauchy_seq_iff'.1 hd ε εpos).imp (λ N hN n hn, _), have hsum := hN n hn, rw [real.dist_eq, ← sum_Ico_eq_sub _ hn] at hsum, calc dist (f n) (f N) = dist (f N) (f n) : dist_comm _ _ ... ≤ ∑ x in Ico N n, d x : dist_le_Ico_sum_of_dist_le hn (λ k _ _, hf k) ... ≤ |∑ x in Ico N n, d x| : le_abs_self _ ... < ε : hsum end lemma cauchy_seq_of_summable_dist [pseudo_metric_space α] {f : ℕ → α} (h : summable (λn, dist (f n) (f n.succ))) : cauchy_seq f := cauchy_seq_of_dist_le_of_summable _ (λ _, le_refl _) h lemma dist_le_tsum_of_dist_le_of_tendsto [pseudo_metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : dist (f n) a ≤ ∑' m, d (n + m) := begin refine le_of_tendsto (tendsto_const_nhds.dist ha) (eventually_at_top.2 ⟨n, λ m hnm, _⟩), refine le_trans (dist_le_Ico_sum_of_dist_le hnm (λ k _ _, hf k)) _, rw [sum_Ico_eq_sum_range], refine sum_le_tsum (range _) (λ _ _, le_trans dist_nonneg (hf _)) _, exact hd.comp_injective (add_right_injective n) end lemma dist_le_tsum_of_dist_le_of_tendsto₀ [pseudo_metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ tsum d := by simpa only [zero_add] using dist_le_tsum_of_dist_le_of_tendsto d hf hd ha 0 lemma dist_le_tsum_dist_of_tendsto [pseudo_metric_space α] {f : ℕ → α} (h : summable (λn, dist (f n) (f n.succ))) {a : α} (ha : tendsto f at_top (𝓝 a)) (n) : dist (f n) a ≤ ∑' m, dist (f (n+m)) (f (n+m).succ) := show dist (f n) a ≤ ∑' m, (λx, dist (f x) (f x.succ)) (n + m), from dist_le_tsum_of_dist_le_of_tendsto (λ n, dist (f n) (f n.succ)) (λ _, le_refl _) h ha n lemma dist_le_tsum_dist_of_tendsto₀ [pseudo_metric_space α] {f : ℕ → α} (h : summable (λn, dist (f n) (f n.succ))) {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ ∑' n, dist (f n) (f n.succ) := by simpa only [zero_add] using dist_le_tsum_dist_of_tendsto h ha 0 end cauchy_seq /-! ## Multipliying two infinite sums In this section, we prove various results about `(∑' x : β, f x) * (∑' y : γ, g y)`. Note that we always assume that the family `λ x : β × γ, f x.1 * g x.2` is summable, since there is no way to deduce this from the summmabilities of `f` and `g` in general, but if you are working in a normed space, you may want to use the analogous lemmas in `analysis/normed_space/basic` (e.g `tsum_mul_tsum_of_summable_norm`). We first establish results about arbitrary index types, `β` and `γ`, and then we specialize to `β = γ = ℕ` to prove the Cauchy product formula (see `tsum_mul_tsum_eq_tsum_sum_antidiagonal`). ### Arbitrary index types -/ section tsum_mul_tsum variables [topological_space α] [regular_space α] [semiring α] [topological_ring α] {f : β → α} {g : γ → α} {s t u : α} lemma has_sum.mul_eq (hf : has_sum f s) (hg : has_sum g t) (hfg : has_sum (λ (x : β × γ), f x.1 * g x.2) u) : s * t = u := have key₁ : has_sum (λ b, f b * t) (s * t), from hf.mul_right t, have this : ∀ b : β, has_sum (λ c : γ, f b * g c) (f b * t), from λ b, hg.mul_left (f b), have key₂ : has_sum (λ b, f b * t) u, from has_sum.prod_fiberwise hfg this, key₁.unique key₂ lemma has_sum.mul (hf : has_sum f s) (hg : has_sum g t) (hfg : summable (λ (x : β × γ), f x.1 * g x.2)) : has_sum (λ (x : β × γ), f x.1 * g x.2) (s * t) := let ⟨u, hu⟩ := hfg in (hf.mul_eq hg hu).symm ▸ hu /-- Product of two infinites sums indexed by arbitrary types. See also `tsum_mul_tsum_of_summable_norm` if `f` and `g` are abolutely summable. -/ lemma tsum_mul_tsum (hf : summable f) (hg : summable g) (hfg : summable (λ (x : β × γ), f x.1 * g x.2)) : (∑' x, f x) * (∑' y, g y) = (∑' z : β × γ, f z.1 * g z.2) := hf.has_sum.mul_eq hg.has_sum hfg.has_sum end tsum_mul_tsum section cauchy_product /-! ### `ℕ`-indexed families (Cauchy product) We prove two versions of the Cauchy product formula. The first one is `tsum_mul_tsum_eq_tsum_sum_range`, where the `n`-th term is a sum over `finset.range (n+1)` involving `nat` substraction. In order to avoid `nat` substraction, we also provide `tsum_mul_tsum_eq_tsum_sum_antidiagonal`, where the `n`-th term is a sum over all pairs `(k, l)` such that `k+l=n`, which corresponds to the `finset` `finset.nat.antidiagonal n` -/ variables {f : ℕ → α} {g : ℕ → α} open finset variables [topological_space α] [semiring α] /- The family `(k, l) : ℕ × ℕ ↦ f k * g l` is summable if and only if the family `(n, k, l) : Σ (n : ℕ), nat.antidiagonal n ↦ f k * g l` is summable. -/ lemma summable_mul_prod_iff_summable_mul_sigma_antidiagonal {f g : ℕ → α} : summable (λ x : ℕ × ℕ, f x.1 * g x.2) ↔ summable (λ x : (Σ (n : ℕ), nat.antidiagonal n), f (x.2 : ℕ × ℕ).1 * g (x.2 : ℕ × ℕ).2) := nat.sigma_antidiagonal_equiv_prod.summable_iff.symm variables [regular_space α] [topological_ring α] lemma summable_sum_mul_antidiagonal_of_summable_mul {f g : ℕ → α} (h : summable (λ x : ℕ × ℕ, f x.1 * g x.2)) : summable (λ n, ∑ kl in nat.antidiagonal n, f kl.1 * g kl.2) := begin rw summable_mul_prod_iff_summable_mul_sigma_antidiagonal at h, conv {congr, funext, rw [← finset.sum_finset_coe, ← tsum_fintype]}, exact h.sigma' (λ n, (has_sum_fintype _).summable), end /-- The Cauchy product formula for the product of two infinites sums indexed by `ℕ`, expressed by summing on `finset.nat.antidiagonal`. See also `tsum_mul_tsum_eq_tsum_sum_antidiagonal_of_summable_norm` if `f` and `g` are absolutely summable. -/ lemma tsum_mul_tsum_eq_tsum_sum_antidiagonal (hf : summable f) (hg : summable g) (hfg : summable (λ (x : ℕ × ℕ), f x.1 * g x.2)) : (∑' n, f n) * (∑' n, g n) = (∑' n, ∑ kl in nat.antidiagonal n, f kl.1 * g kl.2) := begin conv_rhs {congr, funext, rw [← finset.sum_finset_coe, ← tsum_fintype]}, rw [tsum_mul_tsum hf hg hfg, ← nat.sigma_antidiagonal_equiv_prod.tsum_eq (_ : ℕ × ℕ → α)], exact tsum_sigma' (λ n, (has_sum_fintype _).summable) (summable_mul_prod_iff_summable_mul_sigma_antidiagonal.mp hfg) end lemma summable_sum_mul_range_of_summable_mul {f g : ℕ → α} (h : summable (λ x : ℕ × ℕ, f x.1 * g x.2)) : summable (λ n, ∑ k in range (n+1), f k * g (n - k)) := begin simp_rw ← nat.sum_antidiagonal_eq_sum_range_succ (λ k l, f k * g l), exact summable_sum_mul_antidiagonal_of_summable_mul h end /-- The Cauchy product formula for the product of two infinites sums indexed by `ℕ`, expressed by summing on `finset.range`. See also `tsum_mul_tsum_eq_tsum_sum_range_of_summable_norm` if `f` and `g` are absolutely summable. -/ lemma tsum_mul_tsum_eq_tsum_sum_range (hf : summable f) (hg : summable g) (hfg : summable (λ (x : ℕ × ℕ), f x.1 * g x.2)) : (∑' n, f n) * (∑' n, g n) = (∑' n, ∑ k in range (n+1), f k * g (n - k)) := begin simp_rw ← nat.sum_antidiagonal_eq_sum_range_succ (λ k l, f k * g l), exact tsum_mul_tsum_eq_tsum_sum_antidiagonal hf hg hfg end end cauchy_product
37548730f000b19fb6b1f5c2eacb1d1916fcaa62
b9def12ac9858ba514e44c0758ebb4e9b73ae5ed
/src/monoidal_categories_reboot/dagger_category.lean
f0f7d379e61ad05cb67b3ec647c32e24fb6c938f
[ "Apache-2.0" ]
permissive
cipher1024/monoidal-categories-reboot
5f826017db2f71920336331739a0f84be2f97bf7
998f2a0553c22369d922195dc20a20fa7dccc6e5
refs/heads/master
1,586,710,273,395
1,543,592,573,000
1,543,592,573,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,272
lean
-- Copyright (c) 2018 Michael Jendrusch. All rights reserved. import category_theory.category import category_theory.functor import category_theory.products import category_theory.natural_isomorphism import category_theory.tactics.obviously -- Give ourselves access to `rewrite_search` import .slice_tactic import .braided_monoidal_category import .rigid_monoidal_category universes u v namespace category_theory.dagger open category_theory open category_theory.monoidal class dagger_structure (C : Type u) [𝒞 : category.{u v} C] := (dagger_hom : Π {X Y : C} (f : X ⟶ Y), Y ⟶ X) (dagger_comp' : ∀ {X Y Z} (f : X ⟶ Y) (g : Y ⟶ Z), dagger_hom (f ≫ g) = (dagger_hom g) ≫ (dagger_hom f) . obviously) (dagger_id' : ∀ X, dagger_hom (𝟙 X) = 𝟙 X . obviously) (dagger_involution' : ∀ {X Y : C} (f : X ⟶ Y), dagger_hom (dagger_hom f) = f . obviously) restate_axiom dagger_structure.dagger_comp' attribute [simp,search] dagger_structure.dagger_comp' restate_axiom dagger_structure.dagger_id' attribute [simp,search] dagger_structure.dagger_id' restate_axiom dagger_structure.dagger_involution' attribute [simp,search] dagger_structure.dagger_involution' postfix ` † `:10000 := dagger_structure.dagger_hom def dagger_structure.dagger {C : Type u} [𝒞 : category.{u v} C] [dagger_structure C] : Cᵒᵖ ⥤ C := { map := λ {X Y} (f), f†, obj := λ X, X } def is_unitary {C : Type u} [category.{u v} C] [dagger_structure C] {X Y : C} (f : X ≅ Y) : Prop := f.inv = f.hom† open category_theory.monoidal.monoidal_category open category_theory.monoidal.braided_monoidal_category class monoidal_dagger_structure (C : Type u) [symmetric_monoidal_category.{u v} C] extends dagger_structure.{u v} C := (dagger_tensor' : ∀ {X Y X' Y' : C} (f : X ⟶ Y) (g : X' ⟶ Y'), (f ⊗ g)† = f† ⊗ g† . obviously) (associator_unitary' : ∀ X Y Z : C, is_unitary (associator X Y Z) . obviously) (left_unitor_unitary' : ∀ X : C, is_unitary (left_unitor X) . obviously) (right_unitor_unitary' : ∀ X : C, is_unitary (right_unitor X) . obviously) (braiding_unitary' : ∀ X Y : C, is_unitary (braiding X Y) . obviously) end category_theory.dagger
9579452ab3bcbcdc4daa89afa2cc61b719045d66
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/field_theory/finite.lean
f1f85649d2c551b3eea0d776ac83240d06100a7e
[ "Apache-2.0" ]
permissive
kckennylau/mathlib
21fb810b701b10d6606d9002a4004f7672262e83
47b3477e20ffb5a06588dd3abb01fe0fe3205646
refs/heads/master
1,634,976,409,281
1,542,042,832,000
1,542,319,733,000
109,560,458
0
0
Apache-2.0
1,542,369,208,000
1,509,867,494,000
Lean
UTF-8
Lean
false
false
2,598
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import group_theory.order_of_element data.nat.totient data.polynomial data.equiv.algebra universes u v variables {α : Type u} {β : Type v} open function finset polynomial nat section variables [integral_domain α] [decidable_eq α] (S : set (units α)) [is_subgroup S] [fintype S] lemma card_nth_roots_subgroup_units {n : ℕ} (hn : 0 < n) (a : S) : (univ.filter (λ b : S, b ^ n = a)).card ≤ (nth_roots n ((a : units α) : α)).card := card_le_card_of_inj_on (λ a, ((a : units α) : α)) (by simp [mem_nth_roots hn, (units.coe_pow _ _).symm, -units.coe_pow, units.ext_iff.symm, subtype.coe_ext]) (by simp [units.ext_iff.symm, subtype.coe_ext.symm]) instance subgroup_units_cyclic : is_cyclic S := by haveI := classical.dec_eq α; exact is_cyclic_of_card_pow_eq_one_le (λ n hn, le_trans (card_nth_roots_subgroup_units S hn 1) (card_nth_roots _ _)) end namespace finite_field variables [field α] [fintype α] instance [decidable_eq α] : fintype (units α) := by haveI := set_fintype {a : α | a ≠ 0}; exact fintype.of_equiv _ (equiv.units_equiv_ne_zero α).symm lemma card_units [decidable_eq α] : fintype.card (units α) = fintype.card α - 1 := begin rw [eq_comm, nat.sub_eq_iff_eq_add (fintype.card_pos_iff.2 ⟨(0 : α)⟩)], haveI := set_fintype {a : α | a ≠ 0}, haveI := set_fintype (@set.univ α), rw [fintype.card_congr (equiv.units_equiv_ne_zero _), ← @set.card_insert _ _ {a : α | a ≠ 0} _ (not_not.2 (eq.refl (0 : α))) (set.fintype_insert _ _), fintype.card_congr (equiv.set.univ α).symm], congr; simp [set.ext_iff, classical.em] end instance : is_cyclic (units α) := by haveI := classical.dec_eq α; haveI := set_fintype (@set.univ (units α)); exact let ⟨g, hg⟩ := is_cyclic.exists_generator (@set.univ (units α)) in ⟨⟨g, λ x, let ⟨n, hn⟩ := hg ⟨x, trivial⟩ in ⟨n, by rw [← is_subgroup.coe_gpow, hn]; refl⟩⟩⟩ lemma prod_univ_units_id_eq_neg_one [decidable_eq α] : univ.prod (λ x, x) = (-1 : units α) := have ((@univ (units α) _).erase (-1)).prod (λ x, x) = 1, from prod_involution (λ x _, x⁻¹) (by simp) (λ a, by simp [units.inv_eq_self_iff] {contextual := tt}) (λ a, by simp [@inv_eq_iff_inv_eq _ _ a, eq_comm] {contextual := tt}) (by simp), by rw [← insert_erase (mem_univ (-1 : units α)), prod_insert (not_mem_erase _ _), this, mul_one] end finite_field
0e73e4d603e33dc284b28f8813ebeeb47ba4af6a
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/discrete_category_auto.lean
935bd5091f316cbf37da41beab1264fbb6390b69
[]
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
5,825
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, Floris van Doorn -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.eq_to_hom import Mathlib.PostPort universes u₁ u₂ v₂ v₁ namespace Mathlib namespace category_theory /-- A type synonym for promoting any type to a category, with the only morphisms being equalities. -/ def discrete (α : Type u₁) := α /-- The "discrete" category on a type, whose morphisms are equalities. Because we do not allow morphisms in `Prop` (only in `Type`), somewhat annoyingly we have to define `X ⟶ Y` as `ulift (plift (X = Y))`. See https://stacks.math.columbia.edu/tag/001A -/ protected instance discrete_category (α : Type u₁) : small_category (discrete α) := category.mk namespace discrete protected instance inhabited {α : Type u₁} [Inhabited α] : Inhabited (discrete α) := id _inst_1 protected instance subsingleton {α : Type u₁} [subsingleton α] : subsingleton (discrete α) := id _inst_1 /-- Extract the equation from a morphism in a discrete category. -/ theorem eq_of_hom {α : Type u₁} {X : discrete α} {Y : discrete α} (i : X ⟶ Y) : X = Y := plift.down (ulift.down i) @[simp] theorem id_def {α : Type u₁} (X : discrete α) : ulift.up (plift.up (Eq.refl X)) = 𝟙 := rfl protected instance category_theory.is_iso {I : Type u₁} {i : discrete I} {j : discrete I} (f : i ⟶ j) : is_iso f := is_iso.mk (eq_to_hom sorry) /-- Any function `I → C` gives a functor `discrete I ⥤ C`. -/ def functor {C : Type u₂} [category C] {I : Type u₁} (F : I → C) : discrete I ⥤ C := functor.mk F fun (X Y : discrete I) (f : X ⟶ Y) => ulift.cases_on f fun (f : plift (X = Y)) => plift.cases_on f fun (f : X = Y) => eq.dcases_on f (fun (H_1 : Y = X) => Eq._oldrec (fun (f : X = X) (H_2 : f == sorry) => 𝟙) sorry f) sorry sorry @[simp] theorem functor_obj {C : Type u₂} [category C] {I : Type u₁} (F : I → C) (i : I) : functor.obj (functor F) i = F i := rfl theorem functor_map {C : Type u₂} [category C] {I : Type u₁} (F : I → C) {i : discrete I} (f : i ⟶ i) : functor.map (functor F) f = 𝟙 := sorry /-- For functors out of a discrete category, a natural transformation is just a collection of maps, as the naturality squares are trivial. -/ def nat_trans {C : Type u₂} [category C] {I : Type u₁} {F : discrete I ⥤ C} {G : discrete I ⥤ C} (f : (i : discrete I) → functor.obj F i ⟶ functor.obj G i) : F ⟶ G := nat_trans.mk f @[simp] theorem nat_trans_app {C : Type u₂} [category C] {I : Type u₁} {F : discrete I ⥤ C} {G : discrete I ⥤ C} (f : (i : discrete I) → functor.obj F i ⟶ functor.obj G i) (i : discrete I) : nat_trans.app (nat_trans f) i = f i := rfl /-- For functors out of a discrete category, a natural isomorphism is just a collection of isomorphisms, as the naturality squares are trivial. -/ def nat_iso {C : Type u₂} [category C] {I : Type u₁} {F : discrete I ⥤ C} {G : discrete I ⥤ C} (f : (i : discrete I) → functor.obj F i ≅ functor.obj G i) : F ≅ G := nat_iso.of_components f sorry @[simp] theorem nat_iso_hom_app {C : Type u₂} [category C] {I : Type u₁} {F : discrete I ⥤ C} {G : discrete I ⥤ C} (f : (i : discrete I) → functor.obj F i ≅ functor.obj G i) (i : I) : nat_trans.app (iso.hom (nat_iso f)) i = iso.hom (f i) := rfl @[simp] theorem nat_iso_inv_app {C : Type u₂} [category C] {I : Type u₁} {F : discrete I ⥤ C} {G : discrete I ⥤ C} (f : (i : discrete I) → functor.obj F i ≅ functor.obj G i) (i : I) : nat_trans.app (iso.inv (nat_iso f)) i = iso.inv (f i) := rfl @[simp] theorem nat_iso_app {C : Type u₂} [category C] {I : Type u₁} {F : discrete I ⥤ C} {G : discrete I ⥤ C} (f : (i : discrete I) → functor.obj F i ≅ functor.obj G i) (i : I) : iso.app (nat_iso f) i = f i := iso.ext (Eq.refl (iso.hom (iso.app (nat_iso f) i))) /-- Every functor `F` from a discrete category is naturally isomorphic (actually, equal) to `discrete.functor (F.obj)`. -/ def nat_iso_functor {C : Type u₂} [category C] {I : Type u₁} {F : discrete I ⥤ C} : F ≅ functor (functor.obj F) := nat_iso fun (i : discrete I) => iso.refl (functor.obj F i) /-- We can promote a type-level `equiv` to an equivalence between the corresponding `discrete` categories. -/ @[simp] theorem equivalence_functor {I : Type u₁} {J : Type u₁} (e : I ≃ J) : equivalence.functor (equivalence e) = functor ⇑e := Eq.refl (equivalence.functor (equivalence e)) /-- We can convert an equivalence of `discrete` categories to a type-level `equiv`. -/ @[simp] theorem equiv_of_equivalence_apply {α : Type u₁} {β : Type u₁} (h : discrete α ≌ discrete β) : ∀ (ᾰ : discrete α), coe_fn (equiv_of_equivalence h) ᾰ = functor.obj (equivalence.functor h) ᾰ := fun (ᾰ : discrete α) => Eq.refl (coe_fn (equiv_of_equivalence h) ᾰ) end discrete namespace discrete /-- A discrete category is equivalent to its opposite category. -/ protected def opposite (α : Type u₁) : discrete αᵒᵖ ≌ discrete α := let F : discrete α ⥤ (discrete αᵒᵖ) := functor fun (x : α) => opposite.op x; equivalence.mk (functor.left_op F) F (nat_iso.of_components (fun (X : discrete αᵒᵖ) => eq.mpr sorry (iso.refl X)) sorry) (nat_iso fun (X : discrete α) => eq.mpr sorry (iso.refl X)) @[simp] theorem functor_map_id {J : Type v₁} {C : Type u₂} [category C] (F : discrete J ⥤ C) {j : discrete J} (f : j ⟶ j) : functor.map F f = 𝟙 := sorry end Mathlib
0d3cd30b1db2a5cecb9e6cf3eb03523d2f1dff3d
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/num/lemmas.lean
e37619a4f384467acbf84b43dd55d6477d964f87
[ "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
53,511
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.num.bitwise import data.int.char_zero import data.nat.gcd import data.nat.psub /-! # Properties of the binary representation of integers -/ local attribute [simp] add_assoc namespace pos_num variables {α : Type*} @[simp, norm_cast] theorem cast_one [has_one α] [has_add α] : ((1 : pos_num) : α) = 1 := rfl @[simp] theorem cast_one' [has_one α] [has_add α] : (pos_num.one : α) = 1 := rfl @[simp, norm_cast] theorem cast_bit0 [has_one α] [has_add α] (n : pos_num) : (n.bit0 : α) = _root_.bit0 n := rfl @[simp, norm_cast] theorem cast_bit1 [has_one α] [has_add α] (n : pos_num) : (n.bit1 : α) = _root_.bit1 n := rfl @[simp, norm_cast] theorem cast_to_nat [add_monoid_with_one α] : ∀ n : pos_num, ((n : ℕ) : α) = n | 1 := nat.cast_one | (bit0 p) := (nat.cast_bit0 _).trans $ congr_arg _root_.bit0 p.cast_to_nat | (bit1 p) := (nat.cast_bit1 _).trans $ congr_arg _root_.bit1 p.cast_to_nat @[simp, norm_cast] theorem to_nat_to_int (n : pos_num) : ((n : ℕ) : ℤ) = n := cast_to_nat _ @[simp, norm_cast] theorem cast_to_int [add_group_with_one α] (n : pos_num) : ((n : ℤ) : α) = n := by rw [← to_nat_to_int, int.cast_coe_nat, cast_to_nat] theorem succ_to_nat : ∀ n, (succ n : ℕ) = n + 1 | 1 := rfl | (bit0 p) := rfl | (bit1 p) := (congr_arg _root_.bit0 (succ_to_nat p)).trans $ show ↑p + 1 + ↑p + 1 = ↑p + ↑p + 1 + 1, by simp [add_left_comm] theorem one_add (n : pos_num) : 1 + n = succ n := by cases n; refl theorem add_one (n : pos_num) : n + 1 = succ n := by cases n; refl @[norm_cast] theorem add_to_nat : ∀ m n, ((m + n : pos_num) : ℕ) = m + n | 1 b := by rw [one_add b, succ_to_nat, add_comm]; refl | a 1 := by rw [add_one a, succ_to_nat]; refl | (bit0 a) (bit0 b) := (congr_arg _root_.bit0 (add_to_nat a b)).trans $ add_add_add_comm _ _ _ _ | (bit0 a) (bit1 b) := (congr_arg _root_.bit1 (add_to_nat a b)).trans $ show ((a + b) + (a + b) + 1 : ℕ) = (a + a) + (b + b + 1), by simp [add_left_comm] | (bit1 a) (bit0 b) := (congr_arg _root_.bit1 (add_to_nat a b)).trans $ show ((a + b) + (a + b) + 1 : ℕ) = (a + a + 1) + (b + b), by simp [add_comm, add_left_comm] | (bit1 a) (bit1 b) := show (succ (a + b) + succ (a + b) : ℕ) = (a + a + 1) + (b + b + 1), by rw [succ_to_nat, add_to_nat]; simp [add_left_comm] theorem add_succ : ∀ (m n : pos_num), m + succ n = succ (m + n) | 1 b := by simp [one_add] | (bit0 a) 1 := congr_arg bit0 (add_one a) | (bit1 a) 1 := congr_arg bit1 (add_one a) | (bit0 a) (bit0 b) := rfl | (bit0 a) (bit1 b) := congr_arg bit0 (add_succ a b) | (bit1 a) (bit0 b) := rfl | (bit1 a) (bit1 b) := congr_arg bit1 (add_succ a b) theorem bit0_of_bit0 : Π n, _root_.bit0 n = bit0 n | 1 := rfl | (bit0 p) := congr_arg bit0 (bit0_of_bit0 p) | (bit1 p) := show bit0 (succ (_root_.bit0 p)) = _, by rw bit0_of_bit0; refl theorem bit1_of_bit1 (n : pos_num) : _root_.bit1 n = bit1 n := show _root_.bit0 n + 1 = bit1 n, by rw [add_one, bit0_of_bit0]; refl @[norm_cast] theorem mul_to_nat (m) : ∀ n, ((m * n : pos_num) : ℕ) = m * n | 1 := (mul_one _).symm | (bit0 p) := show (↑(m * p) + ↑(m * p) : ℕ) = ↑m * (p + p), by rw [mul_to_nat, left_distrib] | (bit1 p) := (add_to_nat (bit0 (m * p)) m).trans $ show (↑(m * p) + ↑(m * p) + ↑m : ℕ) = ↑m * (p + p) + m, by rw [mul_to_nat, left_distrib] theorem to_nat_pos : ∀ n : pos_num, 0 < (n : ℕ) | 1 := zero_lt_one | (bit0 p) := let h := to_nat_pos p in add_pos h h | (bit1 p) := nat.succ_pos _ theorem cmp_to_nat_lemma {m n : pos_num} : (m:ℕ) < n → (bit1 m : ℕ) < bit0 n := show (m:ℕ) < n → (m + m + 1 + 1 : ℕ) ≤ n + n, by intro h; rw [nat.add_right_comm m m 1, add_assoc]; exact add_le_add h h theorem cmp_swap (m) : ∀n, (cmp m n).swap = cmp n m := by induction m with m IH m IH; intro n; cases n with n n; try {unfold cmp}; try {refl}; rw ←IH; cases cmp m n; refl theorem cmp_to_nat : ∀ (m n), (ordering.cases_on (cmp m n) ((m:ℕ) < n) (m = n) ((n:ℕ) < m) : Prop) | 1 1 := rfl | (bit0 a) 1 := let h : (1:ℕ) ≤ a := to_nat_pos a in add_le_add h h | (bit1 a) 1 := nat.succ_lt_succ $ to_nat_pos $ bit0 a | 1 (bit0 b) := let h : (1:ℕ) ≤ b := to_nat_pos b in add_le_add h h | 1 (bit1 b) := nat.succ_lt_succ $ to_nat_pos $ bit0 b | (bit0 a) (bit0 b) := begin have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact add_lt_add this this }, { rw this }, { exact add_lt_add this this } end | (bit0 a) (bit1 b) := begin dsimp [cmp], have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact nat.le_succ_of_le (add_lt_add this this) }, { rw this, apply nat.lt_succ_self }, { exact cmp_to_nat_lemma this } end | (bit1 a) (bit0 b) := begin dsimp [cmp], have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact cmp_to_nat_lemma this }, { rw this, apply nat.lt_succ_self }, { exact nat.le_succ_of_le (add_lt_add this this) }, end | (bit1 a) (bit1 b) := begin have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact nat.succ_lt_succ (add_lt_add this this) }, { rw this }, { exact nat.succ_lt_succ (add_lt_add this this) } end @[norm_cast] theorem lt_to_nat {m n : pos_num} : (m:ℕ) < n ↔ m < n := show (m:ℕ) < n ↔ cmp m n = ordering.lt, from match cmp m n, cmp_to_nat m n with | ordering.lt, h := by simp at h; simp [h] | ordering.eq, h := by simp at h; simp [h, lt_irrefl]; exact dec_trivial | ordering.gt, h := by simp [not_lt_of_gt h]; exact dec_trivial end @[norm_cast] theorem le_to_nat {m n : pos_num} : (m:ℕ) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr lt_to_nat end pos_num namespace num variables {α : Type*} open pos_num theorem add_zero (n : num) : n + 0 = n := by cases n; refl theorem zero_add (n : num) : 0 + n = n := by cases n; refl theorem add_one : ∀ n : num, n + 1 = succ n | 0 := rfl | (pos p) := by cases p; refl theorem add_succ : ∀ (m n : num), m + succ n = succ (m + n) | 0 n := by simp [zero_add] | (pos p) 0 := show pos (p + 1) = succ (pos p + 0), by rw [pos_num.add_one, add_zero]; refl | (pos p) (pos q) := congr_arg pos (pos_num.add_succ _ _) theorem bit0_of_bit0 : ∀ n : num, bit0 n = n.bit0 | 0 := rfl | (pos p) := congr_arg pos p.bit0_of_bit0 theorem bit1_of_bit1 : ∀ n : num, bit1 n = n.bit1 | 0 := rfl | (pos p) := congr_arg pos p.bit1_of_bit1 @[simp] lemma of_nat'_zero : num.of_nat' 0 = 0 := by simp [num.of_nat'] lemma of_nat'_bit (b n) : of_nat' (nat.bit b n) = cond b num.bit1 num.bit0 (of_nat' n) := nat.binary_rec_eq rfl _ _ @[simp] lemma of_nat'_one : num.of_nat' 1 = 1 := by erw [of_nat'_bit tt 0, cond, of_nat'_zero]; refl lemma bit1_succ : ∀ n : num, n.bit1.succ = n.succ.bit0 | 0 := rfl | (pos n) := rfl lemma of_nat'_succ : ∀ {n}, of_nat' (n + 1) = of_nat' n + 1 := nat.binary_rec (by simp; refl) $ λ b n ih, begin cases b, { erw [of_nat'_bit tt n, of_nat'_bit], simp only [← bit1_of_bit1, ← bit0_of_bit0, cond, _root_.bit1] }, { erw [show n.bit tt + 1 = (n + 1).bit ff, by simp [nat.bit, _root_.bit1, _root_.bit0]; cc, of_nat'_bit, of_nat'_bit, ih], simp only [cond, add_one, bit1_succ], }, end @[simp] theorem add_of_nat' (m n) : num.of_nat' (m + n) = num.of_nat' m + num.of_nat' n := by induction n; simp [nat.add_zero, of_nat'_succ, add_zero, nat.add_succ, add_one, add_succ, *] @[simp, norm_cast] theorem cast_zero [has_zero α] [has_one α] [has_add α] : ((0 : num) : α) = 0 := rfl @[simp] theorem cast_zero' [has_zero α] [has_one α] [has_add α] : (num.zero : α) = 0 := rfl @[simp, norm_cast] theorem cast_one [has_zero α] [has_one α] [has_add α] : ((1 : num) : α) = 1 := rfl @[simp] theorem cast_pos [has_zero α] [has_one α] [has_add α] (n : pos_num) : (num.pos n : α) = n := rfl theorem succ'_to_nat : ∀ n, (succ' n : ℕ) = n + 1 | 0 := (_root_.zero_add _).symm | (pos p) := pos_num.succ_to_nat _ theorem succ_to_nat (n) : (succ n : ℕ) = n + 1 := succ'_to_nat n @[simp, norm_cast] theorem cast_to_nat [add_monoid_with_one α] : ∀ n : num, ((n : ℕ) : α) = n | 0 := nat.cast_zero | (pos p) := p.cast_to_nat @[norm_cast] theorem add_to_nat : ∀ m n, ((m + n : num) : ℕ) = m + n | 0 0 := rfl | 0 (pos q) := (_root_.zero_add _).symm | (pos p) 0 := rfl | (pos p) (pos q) := pos_num.add_to_nat _ _ @[norm_cast] theorem mul_to_nat : ∀ m n, ((m * n : num) : ℕ) = m * n | 0 0 := rfl | 0 (pos q) := (zero_mul _).symm | (pos p) 0 := rfl | (pos p) (pos q) := pos_num.mul_to_nat _ _ theorem cmp_to_nat : ∀ (m n), (ordering.cases_on (cmp m n) ((m:ℕ) < n) (m = n) ((n:ℕ) < m) : Prop) | 0 0 := rfl | 0 (pos b) := to_nat_pos _ | (pos a) 0 := to_nat_pos _ | (pos a) (pos b) := by { have := pos_num.cmp_to_nat a b; revert this; dsimp [cmp]; cases pos_num.cmp a b, exacts [id, congr_arg pos, id] } @[norm_cast] theorem lt_to_nat {m n : num} : (m:ℕ) < n ↔ m < n := show (m:ℕ) < n ↔ cmp m n = ordering.lt, from match cmp m n, cmp_to_nat m n with | ordering.lt, h := by simp at h; simp [h] | ordering.eq, h := by simp at h; simp [h, lt_irrefl]; exact dec_trivial | ordering.gt, h := by simp [not_lt_of_gt h]; exact dec_trivial end @[norm_cast] theorem le_to_nat {m n : num} : (m:ℕ) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr lt_to_nat end num namespace pos_num @[simp] theorem of_to_nat' : Π (n : pos_num), num.of_nat' (n : ℕ) = num.pos n | 1 := by erw [@num.of_nat'_bit tt 0, num.of_nat'_zero]; refl | (bit0 p) := by erw [@num.of_nat'_bit ff, of_to_nat']; refl | (bit1 p) := by erw [@num.of_nat'_bit tt, of_to_nat']; refl end pos_num namespace num @[simp, norm_cast] theorem of_to_nat' : Π (n : num), num.of_nat' (n : ℕ) = n | 0 := of_nat'_zero | (pos p) := p.of_to_nat' @[norm_cast] theorem to_nat_inj {m n : num} : (m : ℕ) = n ↔ m = n := ⟨λ h, function.left_inverse.injective of_to_nat' h, congr_arg _⟩ /-- This tactic tries to turn an (in)equality about `num`s to one about `nat`s by rewriting. ```lean example (n : num) (m : num) : n ≤ n + m := begin num.transfer_rw, exact nat.le_add_right _ _ end ``` -/ meta def transfer_rw : tactic unit := `[repeat {rw ← to_nat_inj <|> rw ← lt_to_nat <|> rw ← le_to_nat}, repeat {rw add_to_nat <|> rw mul_to_nat <|> rw cast_one <|> rw cast_zero}] /-- This tactic tries to prove (in)equalities about `num`s by transfering them to the `nat` world and then trying to call `simp`. ```lean example (n : num) (m : num) : n ≤ n + m := by num.transfer ``` -/ meta def transfer : tactic unit := `[intros, transfer_rw, try {simp}] instance : add_monoid num := { add := (+), zero := 0, zero_add := zero_add, add_zero := add_zero, add_assoc := by transfer } instance : add_monoid_with_one num := { nat_cast := num.of_nat', one := 1, nat_cast_zero := of_nat'_zero, nat_cast_succ := λ _, of_nat'_succ, .. num.add_monoid } instance : comm_semiring num := by refine_struct { mul := (*), one := 1, add := (+), zero := 0, npow := @npow_rec num ⟨1⟩ ⟨(*)⟩, .. num.add_monoid, .. num.add_monoid_with_one }; try { intros, refl }; try { transfer }; simp [add_comm, mul_add, add_mul, mul_assoc, mul_comm, mul_left_comm] instance : ordered_cancel_add_comm_monoid num := { add_left_cancel := by {intros a b c, transfer_rw, apply add_left_cancel}, lt := (<), lt_iff_le_not_le := by {intros a b, transfer_rw, apply lt_iff_le_not_le}, le := (≤), le_refl := by transfer, le_trans := by {intros a b c, transfer_rw, apply le_trans}, le_antisymm := by {intros a b, transfer_rw, apply le_antisymm}, add_le_add_left := by {intros a b h c, revert h, transfer_rw, exact λ h, add_le_add_left h c}, le_of_add_le_add_left := by {intros a b c, transfer_rw, apply le_of_add_le_add_left}, ..num.comm_semiring } instance : linear_ordered_semiring num := { le_total := by {intros a b, transfer_rw, apply le_total}, zero_le_one := dec_trivial, mul_lt_mul_of_pos_left := by {intros a b c, transfer_rw, apply mul_lt_mul_of_pos_left}, mul_lt_mul_of_pos_right := by {intros a b c, transfer_rw, apply mul_lt_mul_of_pos_right}, decidable_lt := num.decidable_lt, decidable_le := num.decidable_le, decidable_eq := num.decidable_eq, exists_pair_ne := ⟨0, 1, dec_trivial⟩, ..num.comm_semiring, ..num.ordered_cancel_add_comm_monoid } @[simp, norm_cast] theorem add_of_nat (m n) : ((m + n : ℕ) : num) = m + n := add_of_nat' _ _ @[simp, norm_cast] theorem to_nat_to_int (n : num) : ((n : ℕ) : ℤ) = n := cast_to_nat _ @[simp, norm_cast] theorem cast_to_int {α} [add_group_with_one α] (n : num) : ((n : ℤ) : α) = n := by rw [← to_nat_to_int, int.cast_coe_nat, cast_to_nat] theorem to_of_nat : Π (n : ℕ), ((n : num) : ℕ) = n | 0 := by rw [nat.cast_zero, cast_zero] | (n+1) := by rw [nat.cast_succ, add_one, succ_to_nat, to_of_nat] @[simp, norm_cast] theorem of_nat_cast {α} [add_monoid_with_one α] (n : ℕ) : ((n : num) : α) = n := by rw [← cast_to_nat, to_of_nat] @[simp, norm_cast] theorem of_nat_inj {m n : ℕ} : (m : num) = n ↔ m = n := ⟨λ h, function.left_inverse.injective to_of_nat h, congr_arg _⟩ @[simp, norm_cast] theorem of_to_nat : Π (n : num), ((n : ℕ) : num) = n := of_to_nat' @[norm_cast] theorem dvd_to_nat (m n : num) : (m : ℕ) ∣ n ↔ m ∣ n := ⟨λ ⟨k, e⟩, ⟨k, by rw [← of_to_nat n, e]; simp⟩, λ ⟨k, e⟩, ⟨k, by simp [e, mul_to_nat]⟩⟩ end num namespace pos_num variables {α : Type*} open num @[simp, norm_cast] theorem of_to_nat : Π (n : pos_num), ((n : ℕ) : num) = num.pos n := of_to_nat' @[norm_cast] theorem to_nat_inj {m n : pos_num} : (m : ℕ) = n ↔ m = n := ⟨λ h, num.pos.inj $ by rw [← pos_num.of_to_nat, ← pos_num.of_to_nat, h], congr_arg _⟩ theorem pred'_to_nat : ∀ n, (pred' n : ℕ) = nat.pred n | 1 := rfl | (bit0 n) := have nat.succ ↑(pred' n) = ↑n, by rw [pred'_to_nat n, nat.succ_pred_eq_of_pos (to_nat_pos n)], match pred' n, this : ∀ k : num, nat.succ ↑k = ↑n → ↑(num.cases_on k 1 bit1 : pos_num) = nat.pred (_root_.bit0 n) with | 0, (h : ((1:num):ℕ) = n) := by rw ← to_nat_inj.1 h; refl | num.pos p, (h : nat.succ ↑p = n) := by rw ← h; exact (nat.succ_add p p).symm end | (bit1 n) := rfl @[simp] theorem pred'_succ' (n) : pred' (succ' n) = n := num.to_nat_inj.1 $ by rw [pred'_to_nat, succ'_to_nat, nat.add_one, nat.pred_succ] @[simp] theorem succ'_pred' (n) : succ' (pred' n) = n := to_nat_inj.1 $ by rw [succ'_to_nat, pred'_to_nat, nat.add_one, nat.succ_pred_eq_of_pos (to_nat_pos _)] instance : has_dvd pos_num := ⟨λ m n, pos m ∣ pos n⟩ @[norm_cast] theorem dvd_to_nat {m n : pos_num} : (m:ℕ) ∣ n ↔ m ∣ n := num.dvd_to_nat (pos m) (pos n) theorem size_to_nat : ∀ n, (size n : ℕ) = nat.size n | 1 := nat.size_one.symm | (bit0 n) := by rw [size, succ_to_nat, size_to_nat, cast_bit0, nat.size_bit0 $ ne_of_gt $ to_nat_pos n] | (bit1 n) := by rw [size, succ_to_nat, size_to_nat, cast_bit1, nat.size_bit1] theorem size_eq_nat_size : ∀ n, (size n : ℕ) = nat_size n | 1 := rfl | (bit0 n) := by rw [size, succ_to_nat, nat_size, size_eq_nat_size] | (bit1 n) := by rw [size, succ_to_nat, nat_size, size_eq_nat_size] theorem nat_size_to_nat (n) : nat_size n = nat.size n := by rw [← size_eq_nat_size, size_to_nat] theorem nat_size_pos (n) : 0 < nat_size n := by cases n; apply nat.succ_pos /-- This tactic tries to turn an (in)equality about `pos_num`s to one about `nat`s by rewriting. ```lean example (n : pos_num) (m : pos_num) : n ≤ n + m := begin pos_num.transfer_rw, exact nat.le_add_right _ _ end ``` -/ meta def transfer_rw : tactic unit := `[repeat {rw ← to_nat_inj <|> rw ← lt_to_nat <|> rw ← le_to_nat}, repeat {rw add_to_nat <|> rw mul_to_nat <|> rw cast_one <|> rw cast_zero}] /-- This tactic tries to prove (in)equalities about `pos_num`s by transferring them to the `nat` world and then trying to call `simp`. ```lean example (n : pos_num) (m : pos_num) : n ≤ n + m := by pos_num.transfer ``` -/ meta def transfer : tactic unit := `[intros, transfer_rw, try {simp [add_comm, add_left_comm, mul_comm, mul_left_comm]}] instance : add_comm_semigroup pos_num := by refine {add := (+), ..}; transfer instance : comm_monoid pos_num := by refine_struct {mul := (*), one := (1 : pos_num), npow := @npow_rec pos_num ⟨1⟩ ⟨(*)⟩}; try { intros, refl }; transfer instance : distrib pos_num := by refine {add := (+), mul := (*), ..}; {transfer, simp [mul_add, mul_comm]} instance : linear_order pos_num := { lt := (<), lt_iff_le_not_le := by {intros a b, transfer_rw, apply lt_iff_le_not_le}, le := (≤), le_refl := by transfer, le_trans := by {intros a b c, transfer_rw, apply le_trans}, le_antisymm := by {intros a b, transfer_rw, apply le_antisymm}, le_total := by {intros a b, transfer_rw, apply le_total}, decidable_lt := by apply_instance, decidable_le := by apply_instance, decidable_eq := by apply_instance } @[simp] theorem cast_to_num (n : pos_num) : ↑n = num.pos n := by rw [← cast_to_nat, ← of_to_nat n] @[simp, norm_cast] theorem bit_to_nat (b n) : (bit b n : ℕ) = nat.bit b n := by cases b; refl @[simp, norm_cast] theorem cast_add [add_monoid_with_one α] (m n) : ((m + n : pos_num) : α) = m + n := by rw [← cast_to_nat, add_to_nat, nat.cast_add, cast_to_nat, cast_to_nat] @[simp, norm_cast, priority 500] theorem cast_succ [add_monoid_with_one α] (n : pos_num) : (succ n : α) = n + 1 := by rw [← add_one, cast_add, cast_one] @[simp, norm_cast] theorem cast_inj [add_monoid_with_one α] [char_zero α] {m n : pos_num} : (m:α) = n ↔ m = n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_inj, to_nat_inj] @[simp] theorem one_le_cast [linear_ordered_semiring α] (n : pos_num) : (1 : α) ≤ n := by rw [← cast_to_nat, ← nat.cast_one, nat.cast_le]; apply to_nat_pos @[simp] theorem cast_pos [linear_ordered_semiring α] (n : pos_num) : 0 < (n : α) := lt_of_lt_of_le zero_lt_one (one_le_cast n) @[simp, norm_cast] theorem cast_mul [semiring α] (m n) : ((m * n : pos_num) : α) = m * n := by rw [← cast_to_nat, mul_to_nat, nat.cast_mul, cast_to_nat, cast_to_nat] @[simp] theorem cmp_eq (m n) : cmp m n = ordering.eq ↔ m = n := begin have := cmp_to_nat m n, cases cmp m n; simp at this ⊢; try {exact this}; { simp [show m ≠ n, from λ e, by rw e at this; exact lt_irrefl _ this] } end @[simp, norm_cast] theorem cast_lt [linear_ordered_semiring α] {m n : pos_num} : (m:α) < n ↔ m < n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_lt, lt_to_nat] @[simp, norm_cast] theorem cast_le [linear_ordered_semiring α] {m n : pos_num} : (m:α) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr cast_lt end pos_num namespace num variables {α : Type*} open pos_num theorem bit_to_nat (b n) : (bit b n : ℕ) = nat.bit b n := by cases b; cases n; refl theorem cast_succ' [add_monoid_with_one α] (n) : (succ' n : α) = n + 1 := by rw [← pos_num.cast_to_nat, succ'_to_nat, nat.cast_add_one, cast_to_nat] theorem cast_succ [add_monoid_with_one α] (n) : (succ n : α) = n + 1 := cast_succ' n @[simp, norm_cast] theorem cast_add [semiring α] (m n) : ((m + n : num) : α) = m + n := by rw [← cast_to_nat, add_to_nat, nat.cast_add, cast_to_nat, cast_to_nat] @[simp, norm_cast] theorem cast_bit0 [semiring α] (n : num) : (n.bit0 : α) = _root_.bit0 n := by rw [← bit0_of_bit0, _root_.bit0, cast_add]; refl @[simp, norm_cast] theorem cast_bit1 [semiring α] (n : num) : (n.bit1 : α) = _root_.bit1 n := by rw [← bit1_of_bit1, _root_.bit1, bit0_of_bit0, cast_add, cast_bit0]; refl @[simp, norm_cast] theorem cast_mul [semiring α] : ∀ m n, ((m * n : num) : α) = m * n | 0 0 := (zero_mul _).symm | 0 (pos q) := (zero_mul _).symm | (pos p) 0 := (mul_zero _).symm | (pos p) (pos q) := pos_num.cast_mul _ _ theorem size_to_nat : ∀ n, (size n : ℕ) = nat.size n | 0 := nat.size_zero.symm | (pos p) := p.size_to_nat theorem size_eq_nat_size : ∀ n, (size n : ℕ) = nat_size n | 0 := rfl | (pos p) := p.size_eq_nat_size theorem nat_size_to_nat (n) : nat_size n = nat.size n := by rw [← size_eq_nat_size, size_to_nat] @[simp, priority 999] theorem of_nat'_eq : ∀ n, num.of_nat' n = n := nat.binary_rec (by simp) $ λ b n IH, begin rw of_nat' at IH ⊢, rw [nat.binary_rec_eq, IH], { cases b; simp [nat.bit, bit0_of_bit0, bit1_of_bit1] }, { refl } end theorem zneg_to_znum (n : num) : -n.to_znum = n.to_znum_neg := by cases n; refl theorem zneg_to_znum_neg (n : num) : -n.to_znum_neg = n.to_znum := by cases n; refl theorem to_znum_inj {m n : num} : m.to_znum = n.to_znum ↔ m = n := ⟨λ h, by cases m; cases n; cases h; refl, congr_arg _⟩ @[simp, norm_cast squash] theorem cast_to_znum [has_zero α] [has_one α] [has_add α] [has_neg α] : ∀ n : num, (n.to_znum : α) = n | 0 := rfl | (num.pos p) := rfl @[simp] theorem cast_to_znum_neg [add_group α] [has_one α] : ∀ n : num, (n.to_znum_neg : α) = -n | 0 := neg_zero.symm | (num.pos p) := rfl @[simp] theorem add_to_znum (m n : num) : num.to_znum (m + n) = m.to_znum + n.to_znum := by cases m; cases n; refl end num namespace pos_num open num theorem pred_to_nat {n : pos_num} (h : 1 < n) : (pred n : ℕ) = nat.pred n := begin unfold pred, have := pred'_to_nat n, cases e : pred' n, { have : (1:ℕ) ≤ nat.pred n := nat.pred_le_pred ((@cast_lt ℕ _ _ _).2 h), rw [← pred'_to_nat, e] at this, exact absurd this dec_trivial }, { rw [← pred'_to_nat, e], refl } end theorem sub'_one (a : pos_num) : sub' a 1 = (pred' a).to_znum := by cases a; refl theorem one_sub' (a : pos_num) : sub' 1 a = (pred' a).to_znum_neg := by cases a; refl theorem lt_iff_cmp {m n} : m < n ↔ cmp m n = ordering.lt := iff.rfl theorem le_iff_cmp {m n} : m ≤ n ↔ cmp m n ≠ ordering.gt := not_congr $ lt_iff_cmp.trans $ by rw ← cmp_swap; cases cmp m n; exact dec_trivial end pos_num namespace num variables {α : Type*} open pos_num theorem pred_to_nat : ∀ (n : num), (pred n : ℕ) = nat.pred n | 0 := rfl | (pos p) := by rw [pred, pos_num.pred'_to_nat]; refl theorem ppred_to_nat : ∀ (n : num), coe <$> ppred n = nat.ppred n | 0 := rfl | (pos p) := by rw [ppred, option.map_some, nat.ppred_eq_some.2]; rw [pos_num.pred'_to_nat, nat.succ_pred_eq_of_pos (pos_num.to_nat_pos _)]; refl theorem cmp_swap (m n) : (cmp m n).swap = cmp n m := by cases m; cases n; try {unfold cmp}; try {refl}; apply pos_num.cmp_swap theorem cmp_eq (m n) : cmp m n = ordering.eq ↔ m = n := begin have := cmp_to_nat m n, cases cmp m n; simp at this ⊢; try {exact this}; { simp [show m ≠ n, from λ e, by rw e at this; exact lt_irrefl _ this] } end @[simp, norm_cast] theorem cast_lt [linear_ordered_semiring α] {m n : num} : (m:α) < n ↔ m < n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_lt, lt_to_nat] @[simp, norm_cast] theorem cast_le [linear_ordered_semiring α] {m n : num} : (m:α) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr cast_lt @[simp, norm_cast] theorem cast_inj [linear_ordered_semiring α] {m n : num} : (m:α) = n ↔ m = n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_inj, to_nat_inj] theorem lt_iff_cmp {m n} : m < n ↔ cmp m n = ordering.lt := iff.rfl theorem le_iff_cmp {m n} : m ≤ n ↔ cmp m n ≠ ordering.gt := not_congr $ lt_iff_cmp.trans $ by rw ← cmp_swap; cases cmp m n; exact dec_trivial theorem bitwise_to_nat {f : num → num → num} {g : bool → bool → bool} (p : pos_num → pos_num → num) (gff : g ff ff = ff) (f00 : f 0 0 = 0) (f0n : ∀ n, f 0 (pos n) = cond (g ff tt) (pos n) 0) (fn0 : ∀ n, f (pos n) 0 = cond (g tt ff) (pos n) 0) (fnn : ∀ m n, f (pos m) (pos n) = p m n) (p11 : p 1 1 = cond (g tt tt) 1 0) (p1b : ∀ b n, p 1 (pos_num.bit b n) = bit (g tt b) (cond (g ff tt) (pos n) 0)) (pb1 : ∀ a m, p (pos_num.bit a m) 1 = bit (g a tt) (cond (g tt ff) (pos m) 0)) (pbb : ∀ a b m n, p (pos_num.bit a m) (pos_num.bit b n) = bit (g a b) (p m n)) : ∀ m n : num, (f m n : ℕ) = nat.bitwise g m n := begin intros, cases m with m; cases n with n; try { change zero with 0 }; try { change ((0:num):ℕ) with 0 }, { rw [f00, nat.bitwise_zero]; refl }, { unfold nat.bitwise, rw [f0n, nat.binary_rec_zero], cases g ff tt; refl }, { unfold nat.bitwise, generalize h : (pos m : ℕ) = m', revert h, apply nat.bit_cases_on m' _, intros b m' h, rw [fn0, nat.binary_rec_eq, nat.binary_rec_zero, ←h], cases g tt ff; refl, apply nat.bitwise_bit_aux gff }, { rw fnn, have : ∀b (n : pos_num), (cond b ↑n 0 : ℕ) = ↑(cond b (pos n) 0 : num) := by intros; cases b; refl, induction m with m IH m IH generalizing n; cases n with n n, any_goals { change one with 1 }, any_goals { change pos 1 with 1 }, any_goals { change pos_num.bit0 with pos_num.bit ff }, any_goals { change pos_num.bit1 with pos_num.bit tt }, any_goals { change ((1:num):ℕ) with nat.bit tt 0 }, all_goals { repeat { rw show ∀ b n, (pos (pos_num.bit b n) : ℕ) = nat.bit b ↑n, by intros; cases b; refl }, rw nat.bitwise_bit }, any_goals { assumption }, any_goals { rw [nat.bitwise_zero, p11], cases g tt tt; refl }, any_goals { rw [nat.bitwise_zero_left, this, ← bit_to_nat, p1b] }, any_goals { rw [nat.bitwise_zero_right _ gff, this, ← bit_to_nat, pb1] }, all_goals { rw [← show ∀ n, ↑(p m n) = nat.bitwise g ↑m ↑n, from IH], rw [← bit_to_nat, pbb] } } end @[simp, norm_cast] theorem lor_to_nat : ∀ m n, (lor m n : ℕ) = nat.lor m n := by apply bitwise_to_nat (λx y, pos (pos_num.lor x y)); intros; try {cases a}; try {cases b}; refl @[simp, norm_cast] theorem land_to_nat : ∀ m n, (land m n : ℕ) = nat.land m n := by apply bitwise_to_nat pos_num.land; intros; try {cases a}; try {cases b}; refl @[simp, norm_cast] theorem ldiff_to_nat : ∀ m n, (ldiff m n : ℕ) = nat.ldiff m n := by apply bitwise_to_nat pos_num.ldiff; intros; try {cases a}; try {cases b}; refl @[simp, norm_cast] theorem lxor_to_nat : ∀ m n, (lxor m n : ℕ) = nat.lxor m n := by apply bitwise_to_nat pos_num.lxor; intros; try {cases a}; try {cases b}; refl @[simp, norm_cast] theorem shiftl_to_nat (m n) : (shiftl m n : ℕ) = nat.shiftl m n := begin cases m; dunfold shiftl, {symmetry, apply nat.zero_shiftl}, simp, induction n with n IH, {refl}, simp [pos_num.shiftl, nat.shiftl_succ], rw ←IH end @[simp, norm_cast] theorem shiftr_to_nat (m n) : (shiftr m n : ℕ) = nat.shiftr m n := begin cases m with m; dunfold shiftr, {symmetry, apply nat.zero_shiftr}, induction n with n IH generalizing m, {cases m; refl}, cases m with m m; dunfold pos_num.shiftr, { rw [nat.shiftr_eq_div_pow], symmetry, apply nat.div_eq_of_lt, exact @nat.pow_lt_pow_of_lt_right 2 dec_trivial 0 (n+1) (nat.succ_pos _) }, { transitivity, apply IH, change nat.shiftr m n = nat.shiftr (bit1 m) (n+1), rw [add_comm n 1, nat.shiftr_add], apply congr_arg (λx, nat.shiftr x n), unfold nat.shiftr, change (bit1 ↑m : ℕ) with nat.bit tt m, rw nat.div2_bit }, { transitivity, apply IH, change nat.shiftr m n = nat.shiftr (bit0 m) (n + 1), rw [add_comm n 1, nat.shiftr_add], apply congr_arg (λx, nat.shiftr x n), unfold nat.shiftr, change (bit0 ↑m : ℕ) with nat.bit ff m, rw nat.div2_bit } end @[simp] theorem test_bit_to_nat (m n) : test_bit m n = nat.test_bit m n := begin cases m with m; unfold test_bit nat.test_bit, { change (zero : nat) with 0, rw nat.zero_shiftr, refl }, induction n with n IH generalizing m; cases m; dunfold pos_num.test_bit, {refl}, { exact (nat.bodd_bit _ _).symm }, { exact (nat.bodd_bit _ _).symm }, { change ff = nat.bodd (nat.shiftr 1 (n + 1)), rw [add_comm, nat.shiftr_add], change nat.shiftr 1 1 with 0, rw nat.zero_shiftr; refl }, { change pos_num.test_bit m n = nat.bodd (nat.shiftr (nat.bit tt m) (n + 1)), rw [add_comm, nat.shiftr_add], unfold nat.shiftr, rw nat.div2_bit, apply IH }, { change pos_num.test_bit m n = nat.bodd (nat.shiftr (nat.bit ff m) (n + 1)), rw [add_comm, nat.shiftr_add], unfold nat.shiftr, rw nat.div2_bit, apply IH }, end end num namespace znum variables {α : Type*} open pos_num @[simp, norm_cast] theorem cast_zero [has_zero α] [has_one α] [has_add α] [has_neg α] : ((0 : znum) : α) = 0 := rfl @[simp] theorem cast_zero' [has_zero α] [has_one α] [has_add α] [has_neg α] : (znum.zero : α) = 0 := rfl @[simp, norm_cast] theorem cast_one [has_zero α] [has_one α] [has_add α] [has_neg α] : ((1 : znum) : α) = 1 := rfl @[simp] theorem cast_pos [has_zero α] [has_one α] [has_add α] [has_neg α] (n : pos_num) : (pos n : α) = n := rfl @[simp] theorem cast_neg [has_zero α] [has_one α] [has_add α] [has_neg α] (n : pos_num) : (neg n : α) = -n := rfl @[simp, norm_cast] theorem cast_zneg [add_group α] [has_one α] : ∀ n, ((-n : znum) : α) = -n | 0 := neg_zero.symm | (pos p) := rfl | (neg p) := (neg_neg _).symm theorem neg_zero : (-0 : znum) = 0 := rfl theorem zneg_pos (n : pos_num) : -pos n = neg n := rfl theorem zneg_neg (n : pos_num) : -neg n = pos n := rfl theorem zneg_zneg (n : znum) : - -n = n := by cases n; refl theorem zneg_bit1 (n : znum) : -n.bit1 = (-n).bitm1 := by cases n; refl theorem zneg_bitm1 (n : znum) : -n.bitm1 = (-n).bit1 := by cases n; refl theorem zneg_succ (n : znum) : -n.succ = (-n).pred := by cases n; try {refl}; rw [succ, num.zneg_to_znum_neg]; refl theorem zneg_pred (n : znum) : -n.pred = (-n).succ := by rw [← zneg_zneg (succ (-n)), zneg_succ, zneg_zneg] @[simp] theorem abs_to_nat : ∀ n, (abs n : ℕ) = int.nat_abs n | 0 := rfl | (pos p) := congr_arg int.nat_abs p.to_nat_to_int | (neg p) := show int.nat_abs ((p:ℕ):ℤ) = int.nat_abs (- p), by rw [p.to_nat_to_int, int.nat_abs_neg] @[simp] theorem abs_to_znum : ∀ n : num, abs n.to_znum = n | 0 := rfl | (num.pos p) := rfl @[simp, norm_cast] theorem cast_to_int [add_group_with_one α] : ∀ n : znum, ((n : ℤ) : α) = n | 0 := by rw [cast_zero, cast_zero, int.cast_zero] | (pos p) := by rw [cast_pos, cast_pos, pos_num.cast_to_int] | (neg p) := by rw [cast_neg, cast_neg, int.cast_neg, pos_num.cast_to_int] theorem bit0_of_bit0 : ∀ n : znum, _root_.bit0 n = n.bit0 | 0 := rfl | (pos a) := congr_arg pos a.bit0_of_bit0 | (neg a) := congr_arg neg a.bit0_of_bit0 theorem bit1_of_bit1 : ∀ n : znum, _root_.bit1 n = n.bit1 | 0 := rfl | (pos a) := congr_arg pos a.bit1_of_bit1 | (neg a) := show pos_num.sub' 1 (_root_.bit0 a) = _, by rw [pos_num.one_sub', a.bit0_of_bit0]; refl @[simp, norm_cast] theorem cast_bit0 [add_group_with_one α] : ∀ n : znum, (n.bit0 : α) = bit0 n | 0 := (add_zero _).symm | (pos p) := by rw [znum.bit0, cast_pos, cast_pos]; refl | (neg p) := by rw [znum.bit0, cast_neg, cast_neg, pos_num.cast_bit0, _root_.bit0, _root_.bit0, neg_add_rev] @[simp, norm_cast] theorem cast_bit1 [add_group_with_one α] : ∀ n : znum, (n.bit1 : α) = bit1 n | 0 := by simp [znum.bit1, _root_.bit1, _root_.bit0] | (pos p) := by rw [znum.bit1, cast_pos, cast_pos]; refl | (neg p) := begin rw [znum.bit1, cast_neg, cast_neg], cases e : pred' p with a; have : p = _ := (succ'_pred' p).symm.trans (congr_arg num.succ' e), { change p=1 at this, subst p, simp [_root_.bit1, _root_.bit0] }, { rw [num.succ'] at this, subst p, have : (↑(-↑a:ℤ) : α) = -1 + ↑(-↑a + 1 : ℤ), {simp [add_comm]}, simpa [_root_.bit1, _root_.bit0, -add_comm] }, end @[simp] theorem cast_bitm1 [add_group_with_one α] (n : znum) : (n.bitm1 : α) = bit0 n - 1 := begin conv { to_lhs, rw ← zneg_zneg n }, rw [← zneg_bit1, cast_zneg, cast_bit1], have : ((-1 + n + n : ℤ) : α) = (n + n + -1 : ℤ), {simp [add_comm, add_left_comm]}, simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg, -int.add_neg_one] end theorem add_zero (n : znum) : n + 0 = n := by cases n; refl theorem zero_add (n : znum) : 0 + n = n := by cases n; refl theorem add_one : ∀ n : znum, n + 1 = succ n | 0 := rfl | (pos p) := congr_arg pos p.add_one | (neg p) := by cases p; refl end znum namespace pos_num variables {α : Type*} theorem cast_to_znum : ∀ n : pos_num, (n : znum) = znum.pos n | 1 := rfl | (bit0 p) := (znum.bit0_of_bit0 p).trans $ congr_arg _ (cast_to_znum p) | (bit1 p) := (znum.bit1_of_bit1 p).trans $ congr_arg _ (cast_to_znum p) local attribute [-simp] int.add_neg_one theorem cast_sub' [add_group_with_one α] : ∀ m n : pos_num, (sub' m n : α) = m - n | a 1 := by rw [sub'_one, num.cast_to_znum, ← num.cast_to_nat, pred'_to_nat, ← nat.sub_one]; simp [pos_num.cast_pos] | 1 b := by rw [one_sub', num.cast_to_znum_neg, ← neg_sub, neg_inj, ← num.cast_to_nat, pred'_to_nat, ← nat.sub_one]; simp [pos_num.cast_pos] | (bit0 a) (bit0 b) := begin rw [sub', znum.cast_bit0, cast_sub'], have : ((a + -b + (a + -b) : ℤ) : α) = a + a + (-b + -b), {simp [add_left_comm]}, simpa [_root_.bit0, sub_eq_add_neg] end | (bit0 a) (bit1 b) := begin rw [sub', znum.cast_bitm1, cast_sub'], have : ((-b + (a + (-b + -1)) : ℤ) : α) = (a + -1 + (-b + -b):ℤ), { simp [add_comm, add_left_comm] }, simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg] end | (bit1 a) (bit0 b) := begin rw [sub', znum.cast_bit1, cast_sub'], have : ((-b + (a + (-b + 1)) : ℤ) : α) = (a + 1 + (-b + -b):ℤ), { simp [add_comm, add_left_comm] }, simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg] end | (bit1 a) (bit1 b) := begin rw [sub', znum.cast_bit0, cast_sub'], have : ((-b + (a + -b) : ℤ) : α) = a + (-b + -b), {simp [add_left_comm]}, simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg] end theorem to_nat_eq_succ_pred (n : pos_num) : (n:ℕ) = n.pred' + 1 := by rw [← num.succ'_to_nat, n.succ'_pred'] theorem to_int_eq_succ_pred (n : pos_num) : (n:ℤ) = (n.pred' : ℕ) + 1 := by rw [← n.to_nat_to_int, to_nat_eq_succ_pred]; refl end pos_num namespace num variables {α : Type*} @[simp] theorem cast_sub' [add_group_with_one α] : ∀ m n : num, (sub' m n : α) = m - n | 0 0 := (sub_zero _).symm | (pos a) 0 := (sub_zero _).symm | 0 (pos b) := (zero_sub _).symm | (pos a) (pos b) := pos_num.cast_sub' _ _ theorem to_znum_succ : ∀ n : num, n.succ.to_znum = n.to_znum.succ | 0 := rfl | (pos n) := rfl theorem to_znum_neg_succ : ∀ n : num, n.succ.to_znum_neg = n.to_znum_neg.pred | 0 := rfl | (pos n) := rfl @[simp] theorem pred_succ : ∀ n : znum, n.pred.succ = n | 0 := rfl | (znum.neg p) := show to_znum_neg (pos p).succ'.pred' = _, by rw [pos_num.pred'_succ']; refl | (znum.pos p) := by rw [znum.pred, ← to_znum_succ, num.succ, pos_num.succ'_pred', to_znum] theorem succ_of_int' : ∀ n, znum.of_int' (n + 1) = znum.of_int' n + 1 | (n : ℕ) := by erw [znum.of_int', znum.of_int', num.of_nat'_succ, num.add_one, to_znum_succ, znum.add_one] | -[1+ 0] := by erw [znum.of_int', znum.of_int', of_nat'_succ, of_nat'_zero]; refl | -[1+ n+1] := by erw [znum.of_int', znum.of_int', @num.of_nat'_succ (n+1), num.add_one, to_znum_neg_succ, @of_nat'_succ n, num.add_one, znum.add_one, pred_succ] theorem of_int'_to_znum : ∀ n : ℕ, to_znum n = znum.of_int' n | 0 := rfl | (n+1) := by rw [nat.cast_succ, num.add_one, to_znum_succ, of_int'_to_znum, nat.cast_succ, succ_of_int', znum.add_one] theorem mem_of_znum' : ∀ {m : num} {n : znum}, m ∈ of_znum' n ↔ n = to_znum m | 0 0 := ⟨λ _, rfl, λ _, rfl⟩ | (pos m) 0 := ⟨λ h, by cases h, λ h, by cases h⟩ | m (znum.pos p) := option.some_inj.trans $ by cases m; split; intro h; try {cases h}; refl | m (znum.neg p) := ⟨λ h, by cases h, λ h, by cases m; cases h⟩ theorem of_znum'_to_nat : ∀ (n : znum), coe <$> of_znum' n = int.to_nat' n | 0 := rfl | (znum.pos p) := show _ = int.to_nat' p, by rw [← pos_num.to_nat_to_int p]; refl | (znum.neg p) := congr_arg (λ x, int.to_nat' (-x)) $ show ((p.pred' + 1 : ℕ) : ℤ) = p, by rw ← succ'_to_nat; simp @[simp] theorem of_znum_to_nat : ∀ (n : znum), (of_znum n : ℕ) = int.to_nat n | 0 := rfl | (znum.pos p) := show _ = int.to_nat p, by rw [← pos_num.to_nat_to_int p]; refl | (znum.neg p) := congr_arg (λ x, int.to_nat (-x)) $ show ((p.pred' + 1 : ℕ) : ℤ) = p, by rw ← succ'_to_nat; simp @[simp] theorem cast_of_znum [add_group_with_one α] (n : znum) : (of_znum n : α) = int.to_nat n := by rw [← cast_to_nat, of_znum_to_nat] @[simp, norm_cast] theorem sub_to_nat (m n) : ((m - n : num) : ℕ) = m - n := show (of_znum _ : ℕ) = _, by rw [of_znum_to_nat, cast_sub', ← to_nat_to_int, ← to_nat_to_int, int.to_nat_sub] end num namespace znum variables {α : Type*} @[simp, norm_cast] theorem cast_add [add_group_with_one α] : ∀ m n, ((m + n : znum) : α) = m + n | 0 a := by cases a; exact (_root_.zero_add _).symm | b 0 := by cases b; exact (_root_.add_zero _).symm | (pos a) (pos b) := pos_num.cast_add _ _ | (pos a) (neg b) := by simpa only [sub_eq_add_neg] using pos_num.cast_sub' _ _ | (neg a) (pos b) := have (↑b + -↑a : α) = -↑a + ↑b, by rw [← pos_num.cast_to_int a, ← pos_num.cast_to_int b, ← int.cast_neg, ← int.cast_add (-a)]; simp [add_comm], (pos_num.cast_sub' _ _).trans $ (sub_eq_add_neg _ _).trans this | (neg a) (neg b) := show -(↑(a + b) : α) = -a + -b, by rw [ pos_num.cast_add, neg_eq_iff_neg_eq, neg_add_rev, neg_neg, neg_neg, ← pos_num.cast_to_int a, ← pos_num.cast_to_int b, ← int.cast_add]; simp [add_comm] @[simp] theorem cast_succ [add_group_with_one α] (n) : ((succ n : znum) : α) = n + 1 := by rw [← add_one, cast_add, cast_one] @[simp, norm_cast] theorem mul_to_int : ∀ m n, ((m * n : znum) : ℤ) = m * n | 0 a := by cases a; exact (_root_.zero_mul _).symm | b 0 := by cases b; exact (_root_.mul_zero _).symm | (pos a) (pos b) := pos_num.cast_mul a b | (pos a) (neg b) := show -↑(a * b) = ↑a * -↑b, by rw [pos_num.cast_mul, neg_mul_eq_mul_neg] | (neg a) (pos b) := show -↑(a * b) = -↑a * ↑b, by rw [pos_num.cast_mul, neg_mul_eq_neg_mul] | (neg a) (neg b) := show ↑(a * b) = -↑a * -↑b, by rw [pos_num.cast_mul, neg_mul_neg] theorem cast_mul [ring α] (m n) : ((m * n : znum) : α) = m * n := by rw [← cast_to_int, mul_to_int, int.cast_mul, cast_to_int, cast_to_int] theorem of_int'_neg : ∀ n : ℤ, of_int' (-n) = -of_int' n | -[1+ n] := show of_int' (n + 1 : ℕ) = _, by simp only [of_int', num.zneg_to_znum_neg] | 0 := show num.to_znum _ = -num.to_znum _, by rw [num.of_nat'_zero]; refl | (n+1 : ℕ) := show num.to_znum_neg _ = -num.to_znum _, by rw [num.zneg_to_znum]; refl theorem of_to_int' : ∀ (n : znum), znum.of_int' n = n | 0 := by erw [of_int', num.of_nat'_zero, num.to_znum] | (pos a) := by rw [cast_pos, ← pos_num.cast_to_nat, ← num.of_int'_to_znum, pos_num.of_to_nat]; refl | (neg a) := by rw [cast_neg, of_int'_neg, ← pos_num.cast_to_nat, ← num.of_int'_to_znum, pos_num.of_to_nat]; refl theorem to_int_inj {m n : znum} : (m : ℤ) = n ↔ m = n := ⟨λ h, function.left_inverse.injective of_to_int' h, congr_arg _⟩ theorem cmp_to_int : ∀ (m n), (ordering.cases_on (cmp m n) ((m:ℤ) < n) (m = n) ((n:ℤ) < m) : Prop) | 0 0 := rfl | (pos a) (pos b) := begin have := pos_num.cmp_to_nat a b; revert this; dsimp [cmp]; cases pos_num.cmp a b; dsimp; [simp, exact congr_arg pos, simp [gt]] end | (neg a) (neg b) := begin have := pos_num.cmp_to_nat b a; revert this; dsimp [cmp]; cases pos_num.cmp b a; dsimp; [simp, simp {contextual := tt}, simp [gt]] end | (pos a) 0 := pos_num.cast_pos _ | (pos a) (neg b) := lt_trans (neg_lt_zero.2 $ pos_num.cast_pos _) (pos_num.cast_pos _) | 0 (neg b) := neg_lt_zero.2 $ pos_num.cast_pos _ | (neg a) 0 := neg_lt_zero.2 $ pos_num.cast_pos _ | (neg a) (pos b) := lt_trans (neg_lt_zero.2 $ pos_num.cast_pos _) (pos_num.cast_pos _) | 0 (pos b) := pos_num.cast_pos _ @[norm_cast] theorem lt_to_int {m n : znum} : (m:ℤ) < n ↔ m < n := show (m:ℤ) < n ↔ cmp m n = ordering.lt, from match cmp m n, cmp_to_int m n with | ordering.lt, h := by simp at h; simp [h] | ordering.eq, h := by simp at h; simp [h, lt_irrefl]; exact dec_trivial | ordering.gt, h := by simp [not_lt_of_gt h]; exact dec_trivial end theorem le_to_int {m n : znum} : (m:ℤ) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr lt_to_int @[simp, norm_cast] theorem cast_lt [linear_ordered_ring α] {m n : znum} : (m:α) < n ↔ m < n := by rw [← cast_to_int m, ← cast_to_int n, int.cast_lt, lt_to_int] @[simp, norm_cast] theorem cast_le [linear_ordered_ring α] {m n : znum} : (m:α) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr cast_lt @[simp, norm_cast] theorem cast_inj [linear_ordered_ring α] {m n : znum} : (m:α) = n ↔ m = n := by rw [← cast_to_int m, ← cast_to_int n, int.cast_inj, to_int_inj] /-- This tactic tries to turn an (in)equality about `znum`s to one about `int`s by rewriting. ```lean example (n : znum) (m : znum) : n ≤ n + m * m := begin znum.transfer_rw, exact le_add_of_nonneg_right (mul_self_nonneg _) end ``` -/ meta def transfer_rw : tactic unit := `[repeat {rw ← to_int_inj <|> rw ← lt_to_int <|> rw ← le_to_int}, repeat {rw cast_add <|> rw mul_to_int <|> rw cast_one <|> rw cast_zero}] /-- This tactic tries to prove (in)equalities about `znum`s by transfering them to the `int` world and then trying to call `simp`. ```lean example (n : znum) (m : znum) : n ≤ n + m * m := begin znum.transfer, exact mul_self_nonneg _ end ``` -/ meta def transfer : tactic unit := `[intros, transfer_rw, try {simp [add_comm, add_left_comm, mul_comm, mul_left_comm]}] instance : linear_order znum := { lt := (<), lt_iff_le_not_le := by {intros a b, transfer_rw, apply lt_iff_le_not_le}, le := (≤), le_refl := by transfer, le_trans := by {intros a b c, transfer_rw, apply le_trans}, le_antisymm := by {intros a b, transfer_rw, apply le_antisymm}, le_total := by {intros a b, transfer_rw, apply le_total}, decidable_eq := znum.decidable_eq, decidable_le := znum.decidable_le, decidable_lt := znum.decidable_lt } instance : add_comm_group znum := { add := (+), add_assoc := by transfer, zero := 0, zero_add := zero_add, add_zero := add_zero, add_comm := by transfer, neg := has_neg.neg, add_left_neg := by transfer } instance : add_monoid_with_one znum := { one := 1, nat_cast := λ n, znum.of_int' n, nat_cast_zero := show (num.of_nat' 0).to_znum = 0, by rw num.of_nat'_zero; refl, nat_cast_succ := λ n, show (num.of_nat' (n+1)).to_znum = (num.of_nat' n).to_znum + 1, by rw [num.of_nat'_succ, num.add_one, num.to_znum_succ, znum.add_one], .. znum.add_comm_group } instance : linear_ordered_comm_ring znum := { mul := (*), mul_assoc := by transfer, one := 1, one_mul := by transfer, mul_one := by transfer, left_distrib := by {transfer, simp [mul_add]}, right_distrib := by {transfer, simp [mul_add, mul_comm]}, mul_comm := by transfer, exists_pair_ne := ⟨0, 1, dec_trivial⟩, add_le_add_left := by {intros a b h c, revert h, transfer_rw, exact λ h, add_le_add_left h c}, mul_pos := λ a b, show 0 < a → 0 < b → 0 < a * b, by {transfer_rw, apply mul_pos}, zero_le_one := dec_trivial, ..znum.linear_order, ..znum.add_comm_group, ..znum.add_monoid_with_one } @[simp, norm_cast] theorem cast_sub [ring α] (m n) : ((m - n : znum) : α) = m - n := by simp [sub_eq_neg_add] @[simp, norm_cast] theorem neg_of_int : ∀ n, ((-n : ℤ) : znum) = -n | (n+1:ℕ) := rfl | 0 := by rw [int.cast_neg, int.cast_zero] | -[1+n] := (zneg_zneg _).symm @[simp] theorem of_int'_eq : ∀ n : ℤ, znum.of_int' n = n | (n : ℕ) := rfl | -[1+ n] := begin show num.to_znum_neg (n+1 : ℕ) = -(n+1 : ℕ), rw [← neg_inj, neg_neg, nat.cast_succ, num.add_one, num.zneg_to_znum_neg, num.to_znum_succ, nat.cast_succ, znum.add_one], refl end @[simp] theorem of_nat_to_znum (n : ℕ) : num.to_znum n = n := rfl @[simp, norm_cast] theorem of_to_int (n : znum) : ((n : ℤ) : znum) = n := by rw [← of_int'_eq, of_to_int'] theorem to_of_int (n : ℤ) : ((n : znum) : ℤ) = n := int.induction_on' n 0 (by simp) (by simp) (by simp) @[simp] theorem of_nat_to_znum_neg (n : ℕ) : num.to_znum_neg n = -n := by rw [← of_nat_to_znum, num.zneg_to_znum] @[simp, norm_cast] theorem of_int_cast [add_group_with_one α] (n : ℤ) : ((n : znum) : α) = n := by rw [← cast_to_int, to_of_int] @[simp, norm_cast] theorem of_nat_cast [add_group_with_one α] (n : ℕ) : ((n : znum) : α) = n := by rw [← int.cast_coe_nat, of_int_cast, int.cast_coe_nat] @[simp, norm_cast] theorem dvd_to_int (m n : znum) : (m : ℤ) ∣ n ↔ m ∣ n := ⟨λ ⟨k, e⟩, ⟨k, by rw [← of_to_int n, e]; simp⟩, λ ⟨k, e⟩, ⟨k, by simp [e]⟩⟩ end znum namespace pos_num theorem divmod_to_nat_aux {n d : pos_num} {q r : num} (h₁ : (r:ℕ) + d * _root_.bit0 q = n) (h₂ : (r:ℕ) < 2 * d) : ((divmod_aux d q r).2 + d * (divmod_aux d q r).1 : ℕ) = ↑n ∧ ((divmod_aux d q r).2 : ℕ) < d := begin unfold divmod_aux, have : ∀ {r₂}, num.of_znum' (num.sub' r (num.pos d)) = some r₂ ↔ (r : ℕ) = r₂ + d, { intro r₂, apply num.mem_of_znum'.trans, rw [← znum.to_int_inj, num.cast_to_znum, num.cast_sub', sub_eq_iff_eq_add, ← int.coe_nat_inj'], simp }, cases e : num.of_znum' (num.sub' r (num.pos d)) with r₂; simp [divmod_aux], { refine ⟨h₁, lt_of_not_ge (λ h, _)⟩, cases nat.le.dest h with r₂ e', rw [← num.to_of_nat r₂, add_comm] at e', cases e.symm.trans (this.2 e'.symm) }, { have := this.1 e, split, { rwa [_root_.bit1, add_comm _ 1, mul_add, mul_one, ← add_assoc, ← this] }, { rwa [this, two_mul, add_lt_add_iff_right] at h₂ } } end theorem divmod_to_nat (d n : pos_num) : (n / d : ℕ) = (divmod d n).1 ∧ (n % d : ℕ) = (divmod d n).2 := begin rw nat.div_mod_unique (pos_num.cast_pos _), induction n with n IH n IH, { exact divmod_to_nat_aux (by simp; refl) (nat.mul_le_mul_left 2 (pos_num.cast_pos d : (0 : ℕ) < d)) }, { unfold divmod, cases divmod d n with q r, simp only [divmod] at IH ⊢, apply divmod_to_nat_aux; simp, { rw [_root_.bit1, _root_.bit1, add_right_comm, bit0_eq_two_mul (n : ℕ), ← IH.1, mul_add, ← bit0_eq_two_mul, mul_left_comm, ← bit0_eq_two_mul] }, { rw ← bit0_eq_two_mul, exact nat.bit1_lt_bit0 IH.2 } }, { unfold divmod, cases divmod d n with q r, simp only [divmod] at IH ⊢, apply divmod_to_nat_aux; simp, { rw [bit0_eq_two_mul (n : ℕ), ← IH.1, mul_add, ← bit0_eq_two_mul, mul_left_comm, ← bit0_eq_two_mul] }, { rw ← bit0_eq_two_mul, exact nat.bit0_lt IH.2 } } end @[simp] theorem div'_to_nat (n d) : (div' n d : ℕ) = n / d := (divmod_to_nat _ _).1.symm @[simp] theorem mod'_to_nat (n d) : (mod' n d : ℕ) = n % d := (divmod_to_nat _ _).2.symm end pos_num namespace num @[simp] protected lemma div_zero (n : num) : n / 0 = 0 := show n.div 0 = 0, by { cases n, refl, simp [num.div] } @[simp, norm_cast] theorem div_to_nat : ∀ n d, ((n / d : num) : ℕ) = n / d | 0 0 := by simp | 0 (pos d) := (nat.zero_div _).symm | (pos n) 0 := (nat.div_zero _).symm | (pos n) (pos d) := pos_num.div'_to_nat _ _ @[simp] protected lemma mod_zero (n : num) : n % 0 = n := show n.mod 0 = n, by { cases n, refl, simp [num.mod] } @[simp, norm_cast] theorem mod_to_nat : ∀ n d, ((n % d : num) : ℕ) = n % d | 0 0 := by simp | 0 (pos d) := (nat.zero_mod _).symm | (pos n) 0 := (nat.mod_zero _).symm | (pos n) (pos d) := pos_num.mod'_to_nat _ _ theorem gcd_to_nat_aux : ∀ {n} {a b : num}, a ≤ b → (a * b).nat_size ≤ n → (gcd_aux n a b : ℕ) = nat.gcd a b | 0 0 b ab h := (nat.gcd_zero_left _).symm | 0 (pos a) 0 ab h := (not_lt_of_ge ab).elim rfl | 0 (pos a) (pos b) ab h := (not_lt_of_le h).elim $ pos_num.nat_size_pos _ | (nat.succ n) 0 b ab h := (nat.gcd_zero_left _).symm | (nat.succ n) (pos a) b ab h := begin simp [gcd_aux], rw [nat.gcd_rec, gcd_to_nat_aux, mod_to_nat], {refl}, { rw [← le_to_nat, mod_to_nat], exact le_of_lt (nat.mod_lt _ (pos_num.cast_pos _)) }, rw [nat_size_to_nat, mul_to_nat, nat.size_le] at h ⊢, rw [mod_to_nat, mul_comm], rw [pow_succ', ← nat.mod_add_div b (pos a)] at h, refine lt_of_mul_lt_mul_right (lt_of_le_of_lt _ h) (nat.zero_le 2), rw [mul_two, mul_add], refine add_le_add_left (nat.mul_le_mul_left _ (le_trans (le_of_lt (nat.mod_lt _ (pos_num.cast_pos _))) _)) _, suffices : 1 ≤ _, simpa using nat.mul_le_mul_left (pos a) this, rw [nat.le_div_iff_mul_le a.cast_pos, one_mul], exact le_to_nat.2 ab end @[simp] theorem gcd_to_nat : ∀ a b, (gcd a b : ℕ) = nat.gcd a b := have ∀ a b : num, (a * b).nat_size ≤ a.nat_size + b.nat_size, begin intros, simp [nat_size_to_nat], rw [nat.size_le, pow_add], exact mul_lt_mul'' (nat.lt_size_self _) (nat.lt_size_self _) (nat.zero_le _) (nat.zero_le _) end, begin intros, unfold gcd, split_ifs, { exact gcd_to_nat_aux h (this _ _) }, { rw nat.gcd_comm, exact gcd_to_nat_aux (le_of_not_le h) (this _ _) } end theorem dvd_iff_mod_eq_zero {m n : num} : m ∣ n ↔ n % m = 0 := by rw [← dvd_to_nat, nat.dvd_iff_mod_eq_zero, ← to_nat_inj, mod_to_nat]; refl instance decidable_dvd : decidable_rel ((∣) : num → num → Prop) | a b := decidable_of_iff' _ dvd_iff_mod_eq_zero end num instance pos_num.decidable_dvd : decidable_rel ((∣) : pos_num → pos_num → Prop) | a b := num.decidable_dvd _ _ namespace znum @[simp] protected lemma div_zero (n : znum) : n / 0 = 0 := show n.div 0 = 0, by cases n; refl <|> simp [znum.div] @[simp, norm_cast] theorem div_to_int : ∀ n d, ((n / d : znum) : ℤ) = n / d | 0 0 := by simp [int.div_zero] | 0 (pos d) := (int.zero_div _).symm | 0 (neg d) := (int.zero_div _).symm | (pos n) 0 := (int.div_zero _).symm | (neg n) 0 := (int.div_zero _).symm | (pos n) (pos d) := (num.cast_to_znum _).trans $ by rw ← num.to_nat_to_int; simp | (pos n) (neg d) := (num.cast_to_znum_neg _).trans $ by rw ← num.to_nat_to_int; simp | (neg n) (pos d) := show - _ = (-_/↑d), begin rw [n.to_int_eq_succ_pred, d.to_int_eq_succ_pred, ← pos_num.to_nat_to_int, num.succ'_to_nat, num.div_to_nat], change -[1+ n.pred' / ↑d] = -[1+ n.pred' / (d.pred' + 1)], rw d.to_nat_eq_succ_pred end | (neg n) (neg d) := show ↑(pos_num.pred' n / num.pos d).succ' = (-_ / -↑d), begin rw [n.to_int_eq_succ_pred, d.to_int_eq_succ_pred, ← pos_num.to_nat_to_int, num.succ'_to_nat, num.div_to_nat], change (nat.succ (_/d) : ℤ) = nat.succ (n.pred'/(d.pred' + 1)), rw d.to_nat_eq_succ_pred end @[simp, norm_cast] theorem mod_to_int : ∀ n d, ((n % d : znum) : ℤ) = n % d | 0 d := (int.zero_mod _).symm | (pos n) d := (num.cast_to_znum _).trans $ by rw [← num.to_nat_to_int, cast_pos, num.mod_to_nat, ← pos_num.to_nat_to_int, abs_to_nat]; refl | (neg n) d := (num.cast_sub' _ _).trans $ by rw [← num.to_nat_to_int, cast_neg, ← num.to_nat_to_int, num.succ_to_nat, num.mod_to_nat, abs_to_nat, ← int.sub_nat_nat_eq_coe, n.to_int_eq_succ_pred]; refl @[simp] theorem gcd_to_nat (a b) : (gcd a b : ℕ) = int.gcd a b := (num.gcd_to_nat _ _).trans $ by simpa theorem dvd_iff_mod_eq_zero {m n : znum} : m ∣ n ↔ n % m = 0 := by rw [← dvd_to_int, int.dvd_iff_mod_eq_zero, ← to_int_inj, mod_to_int]; refl instance : decidable_rel ((∣) : znum → znum → Prop) | a b := decidable_of_iff' _ dvd_iff_mod_eq_zero end znum namespace int /-- Cast a `snum` to the corresponding integer. -/ def of_snum : snum → ℤ := snum.rec' (λ a, cond a (-1) 0) (λa p IH, cond a (bit1 IH) (bit0 IH)) instance snum_coe : has_coe snum ℤ := ⟨of_snum⟩ end int instance : has_lt snum := ⟨λa b, (a : ℤ) < b⟩ instance : has_le snum := ⟨λa b, (a : ℤ) ≤ b⟩
eb08f49dd00fd9986675b3c3a41e353ba3ebce6f
c5e5ea6e7fc63b895c31403f68dd2f7255916f14
/src/export_json.lean
ace35d237f07133ffd61627915ec7be49c1647d3
[ "Apache-2.0", "OFL-1.1" ]
permissive
leanprover-community/doc-gen
c974f9d91ef6c1c51bbcf8e4b9cc9aa7cfb72307
097cc0926bb86982318cabde7e7cc7d5a4c3a9e4
refs/heads/master
1,679,268,657,882
1,677,623,140,000
1,677,623,140,000
223,945,837
20
20
Apache-2.0
1,693,407,722,000
1,574,685,636,000
Python
UTF-8
Lean
false
false
18,957
lean
/- Copyright (c) 2019 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis -/ import tactic.core system.io data.string.defs tactic.interactive data.list.sort /-! Used to generate a json file for html docs. The json file is a list of maps, where each map has the structure ```typescript interface DeclInfo { name: string; args: efmt[]; type: efmt; doc_string: string; filename: string; line: int; attributes: string[]; noncomputable_reason: string; sorried: bool; equations: efmt[]; kind: string; structure_fields: [string, efmt][]; constructors: [string, efmt][]; } ``` Where efmt is defined as follows ('c' is a concatenation, 'n' is nesting): ```typescript type efmt = ['c', efmt, efmt] | ['n', efmt] | string; ``` Include this file somewhere in mathlib, e.g. in the `scripts` directory. Make sure mathlib is precompiled, with `all.lean` generated by `mk_all.sh`. Usage: `lean entrypoint.lean` prints the generated JSON to stdout. `entrypoint.lean` imports this file. -/ open tactic io io.fs native set_option pp.generalized_field_notation true meta def string.is_whitespace (s : string) : bool := s.fold tt (λ a b, a && b.is_whitespace) meta def string.has_whitespace (s : string) : bool := s.fold ff (λ a b, a || b.is_whitespace) meta def json.of_string_list (xs : list string) : json := json.array (xs.map json.of_string) meta inductive efmt | compose (a b : efmt) | of_string (s : string) | nest (f : efmt) namespace efmt meta instance : has_append efmt := ⟨compose⟩ meta instance : has_coe string efmt := ⟨of_string⟩ meta instance coe_format : has_coe format efmt := ⟨of_string ∘ format.to_string⟩ meta def to_json : efmt → json | (compose a b) := json.array ["c", a.to_json, b.to_json] | (of_string f) := f | (nest f) := json.array ["n", f.to_json] meta def compose' : efmt → efmt → efmt | (of_string a) (of_string b) := of_string (a ++ b) | (of_string a) (compose (of_string b) c) := of_string (a ++ b) ++ c | (compose a (of_string b)) (of_string c) := a ++ of_string (b ++ c) | a b := compose a b meta def of_eformat : eformat → efmt | (tagged_format.group g) := of_eformat g | (tagged_format.nest i g) := of_eformat g | (tagged_format.tag _ g) := nest (of_eformat g) | (tagged_format.highlight _ g) := of_eformat g | (tagged_format.compose a b) := compose (of_eformat a) (of_eformat b) | (tagged_format.of_format f) := of_string f.to_string meta def sink_lparens_core : list string → efmt → efmt | ps (of_string a) := of_string $ string.join (a :: ps : list string).reverse | ps (compose (compose a b) c) := sink_lparens_core ps (compose a (compose b c)) | ps (compose (of_string "") a) := sink_lparens_core ps a | ps (compose (of_string a) b) := if a = "[" ∨ a = "(" ∨ a = "{" then sink_lparens_core (a :: ps) b else compose (sink_lparens_core ps (of_string a)) (sink_lparens_core [] b) | ps (compose a b) := compose (sink_lparens_core ps a) (sink_lparens_core [] b) | ps (nest a) := nest $ sink_lparens_core ps a meta def sink_rparens_core : efmt → list string → efmt | (of_string a) ps := of_string $ ps.foldl (++) a | (compose a (compose b c)) ps := sink_rparens_core (compose (compose a b) c) ps | (compose a (of_string "")) ps := sink_rparens_core a ps | (compose a (of_string b)) ps := if b = "]" ∨ b = ")" ∨ b = "}" then sink_rparens_core a (b :: ps) else compose (sink_rparens_core a []) (sink_rparens_core (of_string b) ps) | (compose a b) ps := compose (sink_rparens_core a []) (sink_rparens_core b ps) | (nest a) ps := nest $ sink_rparens_core a ps meta def sink_parens (e : efmt) : efmt := sink_lparens_core [] $ sink_rparens_core e [] meta def simplify : efmt → efmt | (compose a b) := compose' (simplify a) (simplify b) | (nest (nest a)) := simplify $ nest a | (nest a) := match simplify a with | of_string a := if a.has_whitespace then nest (of_string a) else of_string a | a := nest a end | (of_string a) := of_string a meta def pp (e : expr) : tactic efmt := (simplify ∘ sink_parens ∘ of_eformat) <$> pp_tagged e end efmt /-- The information collected from each declaration -/ meta structure decl_info := (name : name) (is_meta : bool) (args : list (bool × efmt)) -- tt means implicit (type : efmt) (doc_string : option string) (filename : string) (line : ℕ) (attributes : list string) -- not all attributes, we have a hardcoded list to check (noncomputable_reason : option _root_.name) (sorried : bool) (equations : list efmt) (kind : string) -- def, theorem, constant, axiom, structure, inductive (structure_fields : list (string × efmt)) -- name and type of fields of a constructor (constructors : list (string × efmt)) -- name and type of constructors of an inductive type structure module_doc_info := (filename : string) (line : ℕ) (content : string) section set_option old_structure_cmd true structure ext_tactic_doc_entry extends tactic_doc_entry := (imported : string) (description : string) meta def ext_tactic_doc_entry.to_json (e : ext_tactic_doc_entry) : json := json.object [ ("name", e.name), ("category", e.category.to_string), ("decl_names", json.of_string_list (e.decl_names.map to_string)), ("tags", json.of_string_list e.tags), ("description", e.description), ("import", e.imported)] end meta instance {α} [has_coe α json] : has_coe (option α) json := ⟨λ o, match o with | some x := ↑x | none := json.null end⟩ meta def decl_info.to_json : decl_info → json | ⟨name, is_meta, args, type, doc_string, filename, line, attributes, nc_reason, sorried, equations, kind, structure_fields, constructors⟩ := json.object [ ("name", to_string name), ("is_meta", is_meta), ("args", json.array $ args.map $ λ ⟨b, s⟩, json.object [("arg", s.to_json), ("implicit", b)]), ("type", type.to_json), ("doc_string", doc_string.get_or_else ""), ("filename", filename), ("line", line), ("attributes", json.of_string_list attributes), ("noncomputable_reason", nc_reason.map to_string), ("sorried", sorried), ("equations", equations.map efmt.to_json), ("kind", kind), ("structure_fields", json.array $ structure_fields.map (λ ⟨n, t⟩, json.array [to_string n, t.to_json])), ("constructors", json.array $ constructors.map (λ ⟨n, t⟩, json.array [to_string n, t.to_json]))] section open tactic.interactive -- tt means implicit meta def format_binders (ns : list name) (bi : binder_info) (t : expr) : tactic (bool × efmt) := do t' ← efmt.pp t, let use_instance_style : bool := ns.length = 1 ∧ "_".is_prefix_of ns.head.to_string ∧ bi = binder_info.inst_implicit, let t' := if use_instance_style then t' else format_names ns ++ " : " ++ t', let brackets : string × string := match bi with | binder_info.default := ("(", ")") | binder_info.implicit := ("{", "}") | binder_info.strict_implicit := ("⦃", "⦄") | binder_info.inst_implicit := ("[", "]") | binder_info.aux_decl := ("(", ")") -- TODO: is this correct? end, pure $ prod.mk (bi ≠ binder_info.default : bool) $ (brackets.1 : efmt) ++ t' ++ brackets.2 meta def binder_info.is_inst_implicit : binder_info → bool | binder_info.inst_implicit := tt | _ := ff -- Determines how many pis should be shown as named arguments. meta def count_named_intros : expr → ℕ | e@(expr.pi n bi d b) := if e.is_arrow ∧ n = `ᾰ then 0 else count_named_intros (b.instantiate_var `(Prop)) + 1 | _ := 0 -- tt means implicit meta def get_args_and_type (e : expr) : tactic (list (bool × efmt) × efmt) := prod.fst <$> solve_aux e ( do intron $ count_named_intros e, cxt ← local_context >>= tactic.interactive.compact_decl, cxt' ← cxt.mmap (λ t, do ft ← format_binders t.1 t.2.1 t.2.2, return (ft.1, ft.2)), tgt ← target >>= efmt.pp, return (cxt', tgt)) end /-- The attributes we check for -/ meta def attribute_list := [`simp, `norm_cast, `nolint, `ext, `instance, `class, `priority, `refl, `symm, `trans, `continuity, `measurability, `reducible, `irreducible] meta def attributes_of (n : name) : tactic (list string) := do l ← list.map to_string <$> attribute_list.mfilter (λ attr, succeeds $ has_attribute attr n), mcond (is_protected_decl n) (return $ "protected"::l) (return l) meta def enable_links : tactic unit := do o ← get_options, set_options $ o.set_bool `pp.links tt -- assumes proj_name exists meta def get_proj_type (struct_name proj_name : name) : tactic efmt := do (locs, _) ← mk_const struct_name >>= infer_type >>= mk_local_pis, proj_tp ← mk_const proj_name >>= infer_type, (_, t) ← open_n_pis (proj_tp.instantiate_pis locs) 1, efmt.pp t meta def mk_structure_fields (decl : name) (e : environment) : tactic (list (string × efmt)) := match e.is_structure decl, e.structure_fields_full decl with | tt, some proj_names := proj_names.mmap $ λ n, do tp ← get_proj_type decl n, return (to_string n, tp) | _, _ := return [] end -- this is used as a hack in get_constructor_type to avoid printing `Type ?`. meta def mk_const_with_params (d : declaration) : expr := let lvls := d.univ_params.map level.param in expr.const d.to_name lvls meta def update_binders_with : list expr → list binder → list expr | (expr.local_const unique pretty _ type :: es) (bi :: bis) := (expr.local_const unique pretty bi.info type) :: update_binders_with es bis | _ _ := [] meta def get_constructor_type (type_name constructor_name : name) : tactic efmt := do d ← get_decl type_name, (locs, _) ← infer_type (mk_const_with_params d) >>= mk_local_pis, env ← get_env, let locs := locs.take (env.inductive_num_params type_name), proj_tp ← mk_const constructor_name >>= infer_type, do t ← pis (update_binders_with locs proj_tp.pi_binders.1) (proj_tp.instantiate_pis locs), --.abstract_locals (locs.map expr.local_uniq_name), efmt.pp t meta def mk_constructors (decl : name) (e : environment): tactic (list (string × efmt)) := if (¬ e.is_inductive decl) ∨ (e.is_structure decl) then return [] else do d ← get_decl decl, ns ← get_constructors_for (mk_const_with_params d), ns.mmap $ λ n, do tp ← get_constructor_type decl n, return (to_string n, tp) meta def get_equations (decl : name) : tactic (list efmt) := do decl_is_proof ← mk_const decl >>= is_proof, if decl_is_proof then return [] else do ns ← get_eqn_lemmas_for tt decl, ns.mmap $ λ n, do d ← get_decl n, (_, ty) ← mk_local_pis d.type, efmt.pp ty meta def get_kind (d : declaration) : tactic string := match d with | declaration.defn _ _ _ _ _ _ := return "def" | declaration.ax _ _ _ := return "axiom" | declaration.thm _ _ _ _ := return "theorem" | declaration.cnst _ _ _ _ := do e ← get_env, if e.is_structure d.to_name then return "structure" else if e.is_inductive d.to_name then return "inductive" else return "constant" end /-- extracts `decl_info` from `d`. Should return `none` instead of failing. -/ meta def process_decl (d : declaration) : tactic (option decl_info) := do ff ← d.in_current_file | return none, e ← get_env, let decl_name := d.to_name, if decl_name.is_internal ∨ d.is_auto_generated e then return none else do some filename ← return (e.decl_olean decl_name) | return none, some ⟨line, _⟩ ← return (e.decl_pos decl_name) | return none, doc_string ← (some <$> doc_string decl_name) <|> return none, (args, type) ← get_args_and_type d.type, attributes ← attributes_of decl_name, equations ← get_equations decl_name, let nc_reason := e.decl_noncomputable_reason decl_name, sorried ← decl_name.contains_sorry, kind ← get_kind d, structure_fields ← mk_structure_fields decl_name e, constructors ← mk_constructors decl_name e, return $ some ⟨decl_name, !d.is_trusted, args, type, doc_string, filename, line, attributes, nc_reason, sorried, equations, kind, structure_fields, constructors⟩ meta def write_module_doc_pair : pos × string → json | (⟨line, _⟩, doc) := json.object [("line", line), ("doc", doc)] meta def write_olean_docs : tactic (list (string × json)) := do docs ← olean_doc_strings, return (docs.foldl (λ rest p, match p with | (none, _) := rest | (some filename, l) := (filename, json.array $ l.map write_module_doc_pair) :: rest end) []) /-- The return type is to indicate three types of failure: * tactic failure (bug) * heuristic failure `exceptional.exception` * no name available `none` -/ meta def extract_name : expr → tactic (exceptional (option string)) | e := do e ← whnf e transparency.reducible, -- t ← infer_type e, -- t ← whnf t transparency.reducible, -- expr.sort l ← pure t | pure (pure none), match e.get_app_fn with | expr.const type_name l := match e with | `(@has_coe_to_sort.coe _ _ _ %%a) := do s ← extract_name a, pure $ match s with | exceptional.success (some n) := pure $ some ("↥"++ n) | x := x end | _ := pure $ pure $ some type_name.to_string end | e@(expr.pi name bi var_type body) := do is_p ← is_prop e <|> (tactic.fail format!"Could not analyze {e}"), match is_p, body.has_var with | ff, ff := pure $ pure $ some "function" | ff, tt := pure $ pure $ some "pi" | tt, ff := pure $ pure $ some "implies" | tt, tt := pure $ pure $ some "forall" end | expr.sort level.zero := pure $ pure $ some "Prop" | expr.sort (level.succ l) := pure $ pure $ some "Type" | expr.sort l := pure $ pure $ some "Sort" | expr.local_const _ _ _ _ := pure $ pure $ none | expr.macro _ _ := pure $ pure $ none -- TODO: unfold macros? | expr.lam name bi var_type body := mk_local' name bi var_type >>= extract_name ∘ body.instantiate_var | expr.var i := pure $ exceptional.fail format!"is a var, not a constant" | expr.mvar _ _ _ := pure $ exceptional.fail format!"is a mvar, not a constant" | expr.app _ _ := pure $ exceptional.fail format!"is a app, not a constant" | expr.elet _ _ _ _ := pure $ exceptional.fail format!"is a elet, not a constant" end /-- Extract `[foo, bar]` from `has_pow foo bar`. The result is a map containing the type names as keys, and a map of any unparseable arguments paired with an explanation of why they can't be parsed. -/ meta def find_instance_types (e : expr) : tactic (rb_set string × rb_map expr format) := fold_explicit_args e (mk_rb_set, mk_rb_map) $ λ ⟨m, errs⟩ e, do s ← extract_name e | pure (m, errs), match s with | exceptional.success none := pure (m, errs) | exceptional.success (some n) := pure (m.insert n, errs) | exceptional.exception msg := pure (m, errs.insert e $ msg options.mk) end meta def get_instances : tactic (rb_lmap string string × rb_lmap string string) := attribute.get_instances `instance >>= list.mfoldl (λ ⟨map, rev_map⟩ inst_nm, do ty ← mk_const inst_nm >>= infer_type, (binders, e) ← open_pis_whnf ty transparency.reducible, e ← whnf e transparency.reducible, expr.const class_nm _ ← pure e.get_app_fn | do { tactic.trace $ format!"Problems parsing `{inst_nm}`: `{e}` is not a constant", return (map, rev_map) }, (types, errs) ← find_instance_types e, -- trace any errors if 0 < errs.size then do tactic.trace $ format!"Problems parsing arguments of `{inst_nm}`:" ++ (errs.fold format!"" $ λ e msg f, f ++ (format!"{e}: " ++ msg).indent 2) else skip, -- update the list of instances with everything that didn't fail let new_rev_map := types.fold rev_map (λ arg rev_map, rev_map.insert arg inst_nm.to_string), return $ (map.insert class_nm.to_string inst_nm.to_string, new_rev_map)) (mk_rb_map, mk_rb_map) meta def format_instance_list : tactic (json × json) := do ⟨map, rev_map⟩ ← get_instances, pure ( json.object $ map.to_list.map (λ ⟨n, l⟩, (n, json.of_string_list l)), json.object $ rev_map.to_list.map (λ ⟨n, l⟩, (n, json.of_string_list l))) meta def format_notes : tactic json := do l ← get_library_notes, pure $ json.array $ l.map $ λ ⟨l, r⟩, json.array [l, r] meta def name.imported_by_tactic_basic (decl_name : name) : bool := let env := environment.from_imported_module_name `tactic.basic in env.contains decl_name meta def name.imported_by_tactic_default (decl_name : name) : bool := let env := environment.from_imported_module_name `tactic.default in env.contains decl_name meta def name.imported_always (decl_name : name) : bool := let env := environment.from_imported_module_name `system.random in env.contains decl_name meta def tactic_doc_entry.add_import : tactic_doc_entry × string → ext_tactic_doc_entry | (e, desc) := let imported := match e.decl_names with | decl_name::_ := if decl_name.imported_always then "always imported" else if decl_name.imported_by_tactic_basic then "tactic.basic" else if decl_name.imported_by_tactic_default then "tactic" else "" | [] := "" end in { e with imported := imported, description := desc } meta def format_tactic_docs : tactic json := do l ← list.map tactic_doc_entry.add_import <$> get_tactic_doc_entries, return $ l.map ext_tactic_doc_entry.to_json meta def mk_export_json : tactic json := do e ← get_env, s ← read, let decls := list.reduce_option $ e.get_decls.map_async_chunked $ λ decl, match (enable_links *> process_decl decl) s with | result.success (some di) _ := some di.to_json | _:= none end, mod_docs ← write_olean_docs, notes ← format_notes, tactic_docs ← format_tactic_docs, ⟨instl, rev_instl⟩ ← format_instance_list, pure $ json.object [ ("decls", decls), ("mod_docs", json.object mod_docs), ("notes", notes), ("tactic_docs", tactic_docs), ("instances", instl), ("instances_for", rev_instl) ] open lean.parser /-- Open all locales (to turn on notation, and also install some notation hacks). -/ @[user_command] meta def open_all_locales (_ : interactive.parse (tk "open_all_locales")): lean.parser unit := do m ← of_tactic localized_attr.get_cache, cmds ← of_tactic $ get_localized m.keys, cmds.mmap' $ λ m, when (¬ ∃ tok ∈ m.split_on '`', by exact (tok.length = 1 ∧ tok.front.is_alphanum) ∨ tok ∈ ["ε", "φ", "ψ", "W_", "σ", "ζ", "μ", "π"]) $ lean.parser.emit_code_here m <|> skip, -- HACK: print gadgets with less fluff lean.parser.emit_code_here "notation x ` := `:10 y := opt_param x y", -- HACKIER: print last component of name as string (because we can't do any better...) lean.parser.emit_code_here "notation x ` . `:10 y := auto_param x (name.mk_string y _)" meta def main : io unit := do json ← run_tactic (trace_error "export_json failed:" mk_export_json), put_str json.unparse
4893d4422132759066181b8d2a4e41623399ae8f
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Lean/Meta/ExprDefEq.lean
0e41d1e243f9c4e096fa343bd855ebd12e7a76a0
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
58,496
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.ProjFns import Lean.Structure import Lean.Meta.WHNF import Lean.Meta.InferType import Lean.Meta.FunInfo import Lean.Meta.LevelDefEq import Lean.Meta.Check import Lean.Meta.Offset import Lean.Meta.ForEachExpr import Lean.Meta.UnificationHint namespace Lean.Meta /-- Try to solve `a := (fun x => t) =?= b` by eta-expanding `b`. Remark: eta-reduction is not a good alternative even in a system without universe cumulativity like Lean. Example: ``` (fun x : A => f ?m) =?= f ``` The left-hand side of the constraint above it not eta-reduced because `?m` is a metavariable. -/ private def isDefEqEta (a b : Expr) : MetaM Bool := do if a.isLambda && !b.isLambda then let bType ← inferType b let bType ← whnfD bType match bType with | Expr.forallE n d _ c => let b' := mkLambda n c.binderInfo d (mkApp b (mkBVar 0)) checkpointDefEq <| Meta.isExprDefEqAux a b' | _ => pure false else pure false /-- Support for `Lean.reduceBool` and `Lean.reduceNat` -/ def isDefEqNative (s t : Expr) : MetaM LBool := do let isDefEq (s t) : MetaM LBool := toLBoolM <| Meta.isExprDefEqAux s t let s? ← reduceNative? s let t? ← reduceNative? t match s?, t? with | some s, some t => isDefEq s t | some s, none => isDefEq s t | none, some t => isDefEq s t | none, none => pure LBool.undef /-- Support for reducing Nat basic operations. -/ def isDefEqNat (s t : Expr) : MetaM LBool := do let isDefEq (s t) : MetaM LBool := toLBoolM <| Meta.isExprDefEqAux s t if s.hasFVar || s.hasMVar || t.hasFVar || t.hasMVar then pure LBool.undef else let s? ← reduceNat? s let t? ← reduceNat? t match s?, t? with | some s, some t => isDefEq s t | some s, none => isDefEq s t | none, some t => isDefEq s t | none, none => pure LBool.undef /-- Support for constraints of the form `("..." =?= String.mk cs)` -/ def isDefEqStringLit (s t : Expr) : MetaM LBool := do let isDefEq (s t) : MetaM LBool := toLBoolM <| Meta.isExprDefEqAux s t if s.isStringLit && t.isAppOf `String.mk then isDefEq (toCtorIfLit s) t else if s.isAppOf `String.mk && t.isStringLit then isDefEq s (toCtorIfLit t) else pure LBool.undef /-- Return `true` if `e` is of the form `fun (x_1 ... x_n) => ?m x_1 ... x_n)`, and `?m` is unassigned. Remark: `n` may be 0. -/ def isEtaUnassignedMVar (e : Expr) : MetaM Bool := do match e.etaExpanded? with | some (Expr.mvar mvarId _) => if (← isReadOnlyOrSyntheticOpaqueExprMVar mvarId) then pure false else if (← isExprMVarAssigned mvarId) then pure false else pure true | _ => pure false /- First pass for `isDefEqArgs`. We unify explicit arguments, *and* easy cases Here, we say a case is easy if it is of the form ?m =?= t or t =?= ?m where `?m` is unassigned. These easy cases are not just an optimization. When `?m` is a function, by assigning it to t, we make sure a unification constraint (in the explicit part) ``` ?m t =?= f s ``` is not higher-order. We also handle the eta-expanded cases: ``` fun x₁ ... xₙ => ?m x₁ ... xₙ =?= t t =?= fun x₁ ... xₙ => ?m x₁ ... xₙ ``` This is important because type inference often produces eta-expanded terms, and without this extra case, we could introduce counter intuitive behavior. Pre: `paramInfo.size <= args₁.size = args₂.size` -/ private partial def isDefEqArgsFirstPass (paramInfo : Array ParamInfo) (args₁ args₂ : Array Expr) : MetaM (Option (Array Nat)) := do let rec loop (i : Nat) (postponed : Array Nat) := do if h : i < paramInfo.size then let info := paramInfo.get ⟨i, h⟩ let a₁ := args₁[i] let a₂ := args₂[i] if info.implicit || info.instImplicit then if (← isEtaUnassignedMVar a₁ <||> isEtaUnassignedMVar a₂) then if (← Meta.isExprDefEqAux a₁ a₂) then loop (i+1) postponed else pure none else loop (i+1) (postponed.push i) else if (← Meta.isExprDefEqAux a₁ a₂) then loop (i+1) postponed else pure none else pure (some postponed) loop 0 #[] @[specialize] private def trySynthPending (e : Expr) : MetaM Bool := do let mvarId? ← getStuckMVar? e match mvarId? with | some mvarId => Meta.synthPending mvarId | none => pure false private partial def isDefEqArgs (f : Expr) (args₁ args₂ : Array Expr) : MetaM Bool := if h : args₁.size = args₂.size then do let finfo ← getFunInfoNArgs f args₁.size let (some postponed) ← isDefEqArgsFirstPass finfo.paramInfo args₁ args₂ | pure false let rec processOtherArgs (i : Nat) : MetaM Bool := do if h₁ : i < args₁.size then let a₁ := args₁.get ⟨i, h₁⟩ let a₂ := args₂.get ⟨i, Eq.subst h h₁⟩ if (← Meta.isExprDefEqAux a₁ a₂) then processOtherArgs (i+1) else pure false else pure true if (← processOtherArgs finfo.paramInfo.size) then postponed.allM fun i => do /- Second pass: unify implicit arguments. In the second pass, we make sure we are unfolding at least non reducible definitions (default setting). -/ let a₁ := args₁[i] let a₂ := args₂[i] let info := finfo.paramInfo[i] if info.instImplicit then discard <| trySynthPending a₁ discard <| trySynthPending a₂ withAtLeastTransparency TransparencyMode.default <| Meta.isExprDefEqAux a₁ a₂ else pure false else pure false /-- Check whether the types of the free variables at `fvars` are definitionally equal to the types at `ds₂`. Pre: `fvars.size == ds₂.size` This method also updates the set of local instances, and invokes the continuation `k` with the updated set. We can't use `withNewLocalInstances` because the `isDeq fvarType d₂` may use local instances. -/ @[specialize] partial def isDefEqBindingDomain (fvars : Array Expr) (ds₂ : Array Expr) (k : MetaM Bool) : MetaM Bool := let rec loop (i : Nat) := do if h : i < fvars.size then do let fvar := fvars.get ⟨i, h⟩ let fvarDecl ← getFVarLocalDecl fvar let fvarType := fvarDecl.type let d₂ := ds₂[i] if (← Meta.isExprDefEqAux fvarType d₂) then match (← isClass? fvarType) with | some className => withNewLocalInstance className fvar <| loop (i+1) | none => loop (i+1) else pure false else k loop 0 /- Auxiliary function for `isDefEqBinding` for handling binders `forall/fun`. It accumulates the new free variables in `fvars`, and declare them at `lctx`. We use the domain types of `e₁` to create the new free variables. We store the domain types of `e₂` at `ds₂`. -/ private partial def isDefEqBindingAux (lctx : LocalContext) (fvars : Array Expr) (e₁ e₂ : Expr) (ds₂ : Array Expr) : MetaM Bool := let process (n : Name) (d₁ d₂ b₁ b₂ : Expr) : MetaM Bool := do let d₁ := d₁.instantiateRev fvars let d₂ := d₂.instantiateRev fvars let fvarId ← mkFreshId let lctx := lctx.mkLocalDecl fvarId n d₁ let fvars := fvars.push (mkFVar fvarId) isDefEqBindingAux lctx fvars b₁ b₂ (ds₂.push d₂) match e₁, e₂ with | Expr.forallE n d₁ b₁ _, Expr.forallE _ d₂ b₂ _ => process n d₁ d₂ b₁ b₂ | Expr.lam n d₁ b₁ _, Expr.lam _ d₂ b₂ _ => process n d₁ d₂ b₁ b₂ | _, _ => withReader (fun ctx => { ctx with lctx := lctx }) do isDefEqBindingDomain fvars ds₂ do Meta.isExprDefEqAux (e₁.instantiateRev fvars) (e₂.instantiateRev fvars) @[inline] private def isDefEqBinding (a b : Expr) : MetaM Bool := do let lctx ← getLCtx isDefEqBindingAux lctx #[] a b #[] private def checkTypesAndAssign (mvar : Expr) (v : Expr) : MetaM Bool := traceCtx `Meta.isDefEq.assign.checkTypes do if !mvar.isMVar then trace[Meta.isDefEq.assign.final] "metavariable expected at {mvar} := {v}" return false else -- must check whether types are definitionally equal or not, before assigning and returning true let mvarType ← inferType mvar let vType ← inferType v if (← withTransparency TransparencyMode.default <| Meta.isExprDefEqAux mvarType vType) then trace[Meta.isDefEq.assign.final] "{mvar} := {v}" assignExprMVar mvar.mvarId! v pure true else trace[Meta.isDefEq.assign.typeMismatch] "{mvar} : {mvarType} := {v} : {vType}" pure false /-- Auxiliary method for solving constraints of the form `?m xs := v`. It creates a lambda using `mkLambdaFVars ys v`, where `ys` is a superset of `xs`. `ys` is often equal to `xs`. It is a bigger when there are let-declaration dependencies in `xs`. For example, suppose we have `xs` of the form `#[a, c]` where ``` a : Nat b : Nat := f a c : b = a ``` In this scenario, the type of `?m` is `(x1 : Nat) -> (x2 : f x1 = x1) -> C[x1, x2]`, and type of `v` is `C[a, c]`. Note that, `?m a c` is type correct since `f a = a` is definitionally equal to the type of `c : b = a`, and the type of `?m a c` is equal to the type of `v`. Note that `fun xs => v` is the term `fun (x1 : Nat) (x2 : b = x1) => v` which has type `(x1 : Nat) -> (x2 : b = x1) -> C[x1, x2]` which is not definitionally equal to the type of `?m`, and may not even be type correct. The issue here is that we are not capturing the `let`-declarations. This method collects let-declarations `y` occurring between `xs[0]` and `xs.back` s.t. some `x` in `xs` depends on `y`. `ys` is the `xs` with these extra let-declarations included. In the example above, `ys` is `#[a, b, c]`, and `mkLambdaFVars ys v` produces `fun a => let b := f a; fun (c : b = a) => v` which has a type definitionally equal to the type of `?m`. Recall that the method `checkAssignment` ensures `v` does not contain offending `let`-declarations. This method assumes that for any `xs[i]` and `xs[j]` where `i < j`, we have that `index of xs[i]` < `index of xs[j]`. where the index is the position in the local context. -/ private partial def mkLambdaFVarsWithLetDeps (xs : Array Expr) (v : Expr) : MetaM (Option Expr) := do if not (← hasLetDeclsInBetween) then mkLambdaFVars xs v else let ys ← addLetDeps trace[Meta.debug] "ys: {ys}, v: {v}" mkLambdaFVars ys v where /- Return true if there are let-declarions between `xs[0]` and `xs[xs.size-1]`. We use it a quick-check to avoid the more expensive collection procedure. -/ hasLetDeclsInBetween : MetaM Bool := do let check (lctx : LocalContext) : Bool := do let start := lctx.getFVar! xs[0] |>.index let stop := lctx.getFVar! xs.back |>.index for i in [start+1:stop] do match lctx.getAt? i with | some localDecl => if localDecl.isLet then return true | _ => pure () return false if xs.size <= 1 then pure false else check (← getLCtx) /- Traverse `e` and stores in the state `NameHashSet` any let-declaration with index greater than `(← read)`. The context `Nat` is the position of `xs[0]` in the local context. -/ collectLetDeclsFrom (e : Expr) : ReaderT Nat (StateRefT NameHashSet MetaM) Unit := do let rec visit (e : Expr) : MonadCacheT Expr Unit (ReaderT Nat (StateRefT NameHashSet MetaM)) Unit := checkCache e fun _ => do match e with | Expr.forallE _ d b _ => visit d; visit b | Expr.lam _ d b _ => visit d; visit b | Expr.letE _ t v b _ => visit t; visit v; visit b | Expr.app f a _ => visit f; visit a | Expr.mdata _ b _ => visit b | Expr.proj _ _ b _ => visit b | Expr.fvar fvarId _ => let localDecl ← getLocalDecl fvarId if localDecl.isLet && localDecl.index > (← read) then modify fun s => s.insert localDecl.fvarId | _ => pure () visit (← instantiateMVars e) |>.run /- Auxiliary definition for traversing all declarations between `xs[0]` ... `xs.back` backwards. The `Nat` argument is the current position in the local context being visited, and it is less than or equal to the position of `xs.back` in the local context. The `Nat` context `(← read)` is the position of `xs[0]` in the local context. -/ collectLetDepsAux : Nat → ReaderT Nat (StateRefT NameHashSet MetaM) Unit | 0 => return () | i+1 => do if i+1 == (← read) then return () else match (← getLCtx).getAt? (i+1) with | none => collectLetDepsAux i | some localDecl => if (← get).contains localDecl.fvarId then collectLetDeclsFrom localDecl.type match localDecl.value? with | some val => collectLetDeclsFrom val | _ => pure () collectLetDepsAux i /- Computes the set `ys`. It is a set of `FVarId`s, -/ collectLetDeps : MetaM NameHashSet := do let lctx ← getLCtx let start := lctx.getFVar! xs[0] |>.index let stop := lctx.getFVar! xs.back |>.index let s := xs.foldl (init := {}) fun s x => s.insert x.fvarId! let (_, s) ← collectLetDepsAux stop |>.run start |>.run s return s /- Computes the array `ys` containing let-decls between `xs[0]` and `xs.back` that some `x` in `xs` depends on. -/ addLetDeps : MetaM (Array Expr) := do let lctx ← getLCtx let s ← collectLetDeps /- Convert `s` into the array `ys` -/ let start := lctx.getFVar! xs[0] |>.index let stop := lctx.getFVar! xs.back |>.index let mut ys := #[] for i in [start:stop+1] do match lctx.getAt? i with | none => pure () | some localDecl => if s.contains localDecl.fvarId then ys := ys.push localDecl.toExpr return ys /- Each metavariable is declared in a particular local context. We use the notation `C |- ?m : t` to denote a metavariable `?m` that was declared at the local context `C` with type `t` (see `MetavarDecl`). We also use `?m@C` as a shorthand for `C |- ?m : t` where `t` is the type of `?m`. The following method process the unification constraint ?m@C a₁ ... aₙ =?= t We say the unification constraint is a pattern IFF 1) `a₁ ... aₙ` are pairwise distinct free variables that are ​*not*​ let-variables. 2) `a₁ ... aₙ` are not in `C` 3) `t` only contains free variables in `C` and/or `{a₁, ..., aₙ}` 4) For every metavariable `?m'@C'` occurring in `t`, `C'` is a subprefix of `C` 5) `?m` does not occur in `t` Claim: we don't have to check free variable declarations. That is, if `t` contains a reference to `x : A := v`, we don't need to check `v`. Reason: The reference to `x` is a free variable, and it must be in `C` (by 1 and 3). If `x` is in `C`, then any metavariable occurring in `v` must have been defined in a strict subprefix of `C`. So, condition 4 and 5 are satisfied. If the conditions above have been satisfied, then the solution for the unification constrain is ?m := fun a₁ ... aₙ => t Now, we consider some workarounds/approximations. A1) Suppose `t` contains a reference to `x : A := v` and `x` is not in `C` (failed condition 3) (precise) solution: unfold `x` in `t`. A2) Suppose some `aᵢ` is in `C` (failed condition 2) (approximated) solution (when `config.ctxApprox` is set to true) : ignore condition and also use ?m := fun a₁ ... aₙ => t Here is an example where this approximation fails: Given `C` containing `a : nat`, consider the following two constraints ?m@C a =?= a ?m@C b =?= a If we use the approximation in the first constraint, we get ?m := fun x => x when we apply this solution to the second one we get a failure. IMPORTANT: When applying this approximation we need to make sure the abstracted term `fun a₁ ... aₙ => t` is type correct. The check can only be skipped in the pattern case described above. Consider the following example. Given the local context (α : Type) (a : α) we try to solve ?m α =?= @id α a If we use the approximation above we obtain: ?m := (fun α' => @id α' a) which is a type incorrect term. `a` has type `α` but it is expected to have type `α'`. The problem occurs because the right hand side contains a free variable `a` that depends on the free variable `α` being abstracted. Note that this dependency cannot occur in patterns. We can address this by type checking the term after abstraction. This is not a significant performance bottleneck because this case doesn't happen very often in practice (262 times when compiling stdlib on Jan 2018). The second example is trickier, but it also occurs less frequently (8 times when compiling stdlib on Jan 2018, and all occurrences were at Init/Control when we define monads and auxiliary combinators for them). We considered three options for the addressing the issue on the second example: A3) `a₁ ... aₙ` are not pairwise distinct (failed condition 1). In Lean3, we would try to approximate this case using an approach similar to A2. However, this approximation complicates the code, and is never used in the Lean3 stdlib and mathlib. A4) `t` contains a metavariable `?m'@C'` where `C'` is not a subprefix of `C`. If `?m'` is assigned, we substitute. If not, we create an auxiliary metavariable with a smaller scope. Actually, we let `elimMVarDeps` at `MetavarContext.lean` to perform this step. A5) If some `aᵢ` is not a free variable, then we use first-order unification (if `config.foApprox` is set to true) ?m a_1 ... a_i a_{i+1} ... a_{i+k} =?= f b_1 ... b_k reduces to ?M a_1 ... a_i =?= f a_{i+1} =?= b_1 ... a_{i+k} =?= b_k A6) If (m =?= v) is of the form ?m a_1 ... a_n =?= ?m b_1 ... b_k then we use first-order unification (if `config.foApprox` is set to true) A7) When `foApprox`, we may use another approximation (`constApprox`) for solving constraints of the form ``` ?m s₁ ... sₙ =?= t ``` where `s₁ ... sₙ` are arbitrary terms. We solve them by assigning the constant function to `?m`. ``` ?m := fun _ ... _ => t ``` In general, this approximation may produce bad solutions, and may prevent coercions from being tried. For example, consider the term `pure (x > 0)` with inferred type `?m Prop` and expected type `IO Bool`. In this situation, the elaborator generates the unification constraint ``` ?m Prop =?= IO Bool ``` It is not a higher-order pattern, nor first-order approximation is applicable. However, constant approximation produces the bogus solution `?m := fun _ => IO Bool`, and prevents the system from using the coercion from the decidable proposition `x > 0` to `Bool`. On the other hand, the constant approximation is desirable for elaborating the term ``` let f (x : _) := pure "hello"; f () ``` with expected type `IO String`. In this example, the following unification contraint is generated. ``` ?m () String =?= IO String ``` It is not a higher-order pattern, first-order approximation reduces it to ``` ?m () =?= IO ``` which fails to be solved. However, constant approximation solves it by assigning ``` ?m := fun _ => IO ``` Note that `f`s type is `(x : ?α) -> ?m x String`. The metavariable `?m` may depend on `x`. If `constApprox` is set to true, we use constant approximation. Otherwise, we use a heuristic to decide whether we should apply it or not. The heuristic is based on observing where the constraints above come from. In the first example, the constraint `?m Prop =?= IO Bool` come from polymorphic method where `?m` is expected to be a **function** of type `Type -> Type`. In the second example, the first argument of `?m` is used to model a **potential** dependency on `x`. By using constant approximation here, we are just saying the type of `f` does **not** depend on `x`. We claim this is a reasonable approximation in practice. Moreover, it is expected by any functional programmer used to non-dependently type languages (e.g., Haskell). We distinguish the two cases above by using the field `numScopeArgs` at `MetavarDecl`. This fiels tracks how many metavariable arguments are representing dependencies. -/ def mkAuxMVar (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (numScopeArgs : Nat := 0) : MetaM Expr := do mkFreshExprMVarAt lctx localInsts type MetavarKind.natural Name.anonymous numScopeArgs namespace CheckAssignment builtin_initialize checkAssignmentExceptionId : InternalExceptionId ← registerInternalExceptionId `checkAssignment builtin_initialize outOfScopeExceptionId : InternalExceptionId ← registerInternalExceptionId `outOfScope structure State where cache : ExprStructMap Expr := {} structure Context where mvarId : MVarId mvarDecl : MetavarDecl fvars : Array Expr hasCtxLocals : Bool rhs : Expr abbrev CheckAssignmentM := ReaderT Context $ StateRefT State MetaM def throwCheckAssignmentFailure : CheckAssignmentM α := throw <| Exception.internal checkAssignmentExceptionId def throwOutOfScopeFVar : CheckAssignmentM α := throw <| Exception.internal outOfScopeExceptionId private def findCached? (e : Expr) : CheckAssignmentM (Option Expr) := do return (← get).cache.find? e private def cache (e r : Expr) : CheckAssignmentM Unit := do modify fun s => { s with cache := s.cache.insert e r } instance : MonadCache Expr Expr CheckAssignmentM where findCached? := findCached? cache := cache @[inline] private def visit (f : Expr → CheckAssignmentM Expr) (e : Expr) : CheckAssignmentM Expr := if !e.hasExprMVar && !e.hasFVar then pure e else checkCache e (fun _ => f e) private def addAssignmentInfo (msg : MessageData) : CheckAssignmentM MessageData := do let ctx ← read return m!"{msg} @ {mkMVar ctx.mvarId} {ctx.fvars} := {ctx.rhs}" @[inline] def run (x : CheckAssignmentM Expr) (mvarId : MVarId) (fvars : Array Expr) (hasCtxLocals : Bool) (v : Expr) : MetaM (Option Expr) := do let mvarDecl ← getMVarDecl mvarId let ctx := { mvarId := mvarId, mvarDecl := mvarDecl, fvars := fvars, hasCtxLocals := hasCtxLocals, rhs := v : Context } let x : CheckAssignmentM (Option Expr) := catchInternalIds [outOfScopeExceptionId, checkAssignmentExceptionId] (do let e ← x; return some e) (fun _ => pure none) x.run ctx |>.run' {} mutual partial def checkFVar (fvar : Expr) : CheckAssignmentM Expr := do let ctxMeta ← readThe Meta.Context let ctx ← read if ctx.mvarDecl.lctx.containsFVar fvar then pure fvar else let lctx := ctxMeta.lctx match lctx.findFVar? fvar with | some (LocalDecl.ldecl (value := v) ..) => visit check v | _ => if ctx.fvars.contains fvar then pure fvar else traceM `Meta.isDefEq.assign.outOfScopeFVar do addAssignmentInfo fvar throwOutOfScopeFVar partial def checkMVar (mvar : Expr) : CheckAssignmentM Expr := do let mvarId := mvar.mvarId! let ctx ← read let mctx ← getMCtx if mvarId == ctx.mvarId then traceM `Meta.isDefEq.assign.occursCheck <| addAssignmentInfo "occurs check failed" throwCheckAssignmentFailure else match mctx.getExprAssignment? mvarId with | some v => check v | none => match mctx.findDecl? mvarId with | none => throwUnknownMVar mvarId | some mvarDecl => if ctx.hasCtxLocals then throwCheckAssignmentFailure -- It is not a pattern, then we fail and fall back to FO unification else if mvarDecl.lctx.isSubPrefixOf ctx.mvarDecl.lctx ctx.fvars then /- The local context of `mvar` - free variables being abstracted is a subprefix of the metavariable being assigned. We "substract" variables being abstracted because we use `elimMVarDeps` -/ pure mvar else if mvarDecl.depth != mctx.depth || mvarDecl.kind.isSyntheticOpaque then traceM `Meta.isDefEq.assign.readOnlyMVarWithBiggerLCtx <| addAssignmentInfo (mkMVar mvarId) throwCheckAssignmentFailure else let ctxMeta ← readThe Meta.Context if ctxMeta.config.ctxApprox && ctx.mvarDecl.lctx.isSubPrefixOf mvarDecl.lctx then /- Create an auxiliary metavariable with a smaller context and "checked" type. Note that `mvarType` may be different from `mvarDecl.type`. Example: `mvarType` contains a metavariable that we also need to reduce the context. We remove from `ctx.mvarDecl.lctx` any variable that is not in `mvarDecl.lctx` or in `ctx.fvars`. We don't need to remove the ones in `ctx.fvars` because `elimMVarDeps` will take care of them. First, we collect `toErase` the variables that need to be erased. Notat that if a variable is `ctx.fvars`, but it depends on variable at `toErase`, we must also erase it. -/ let toErase := mvarDecl.lctx.foldl (init := #[]) fun toErase localDecl => if ctx.mvarDecl.lctx.contains localDecl.fvarId then toErase else if ctx.fvars.any fun fvar => fvar.fvarId! == localDecl.fvarId then if mctx.findLocalDeclDependsOn localDecl fun fvarId => toErase.contains fvarId then -- localDecl depends on a variable that will be erased. So, we must add it to `toErase` too toErase.push localDecl.fvarId else toErase else toErase.push localDecl.fvarId let lctx := toErase.foldl (init := mvarDecl.lctx) fun lctx toEraseFVar => lctx.erase toEraseFVar /- Compute new set of local instances. -/ let localInsts := mvarDecl.localInstances.filter fun localInst => toErase.contains localInst.fvar.fvarId! let mvarType ← check mvarDecl.type let newMVar ← mkAuxMVar lctx localInsts mvarType mvarDecl.numScopeArgs modifyThe Meta.State fun s => { s with mctx := s.mctx.assignExpr mvarId newMVar } pure newMVar else traceM `Meta.isDefEq.assign.readOnlyMVarWithBiggerLCtx <| addAssignmentInfo (mkMVar mvarId) throwCheckAssignmentFailure /- Auxiliary function used to "fix" subterms of the form `?m x_1 ... x_n` where `x_i`s are free variables, and one of them is out-of-scope. See `Expr.app` case at `check`. If `ctxApprox` is true, then we solve this case by creating a fresh metavariable ?n with the correct scope, an assigning `?m := fun _ ... _ => ?n` -/ partial def assignToConstFun (mvar : Expr) (numArgs : Nat) (newMVar : Expr) : MetaM Bool := do let mvarType ← inferType mvar forallBoundedTelescope mvarType numArgs fun xs _ => do if xs.size != numArgs then pure false else let some v ← mkLambdaFVarsWithLetDeps xs newMVar | return false match (← checkAssignmentAux mvar.mvarId! #[] false v) with | some v => checkTypesAndAssign mvar v | none => return false -- See checkAssignment partial def checkAssignmentAux (mvarId : MVarId) (fvars : Array Expr) (hasCtxLocals : Bool) (v : Expr) : MetaM (Option Expr) := do run (check v) mvarId fvars hasCtxLocals v partial def checkApp (e : Expr) : CheckAssignmentM Expr := e.withApp fun f args => do let ctxMeta ← readThe Meta.Context if f.isMVar && ctxMeta.config.ctxApprox && args.all Expr.isFVar then let f ← visit checkMVar f catchInternalId outOfScopeExceptionId (do let args ← args.mapM (visit check) return mkAppN f args) (fun ex => do if !f.isMVar then throw ex else if (← isDelayedAssigned f.mvarId!) then throw ex else let eType ← inferType e let mvarType ← check eType /- Create an auxiliary metavariable with a smaller context and "checked" type, assign `?f := fun _ => ?newMVar` Note that `mvarType` may be different from `eType`. -/ let ctx ← read let newMVar ← mkAuxMVar ctx.mvarDecl.lctx ctx.mvarDecl.localInstances mvarType if (← assignToConstFun f args.size newMVar) then pure newMVar else throw ex) else let f ← visit check f let args ← args.mapM (visit check) return mkAppN f args partial def check (e : Expr) : CheckAssignmentM Expr := do match e with | Expr.mdata _ b _ => return e.updateMData! (← visit check b) | Expr.proj _ _ s _ => return e.updateProj! (← visit check s) | Expr.lam _ d b _ => return e.updateLambdaE! (← visit check d) (← visit check b) | Expr.forallE _ d b _ => return e.updateForallE! (← visit check d) (← visit check b) | Expr.letE _ t v b _ => return e.updateLet! (← visit check t) (← visit check v) (← visit check b) | Expr.bvar .. => return e | Expr.sort .. => return e | Expr.const .. => return e | Expr.lit .. => return e | Expr.fvar .. => visit checkFVar e | Expr.mvar .. => visit checkMVar e | Expr.app .. => checkApp e -- TODO: investigate whether the following feature is too expensive or not /- catchInternalIds [checkAssignmentExceptionId, outOfScopeExceptionId] (checkApp e) fun ex => do let e' ← whnfR e if e != e' then check e' else throw ex -/ end end CheckAssignment namespace CheckAssignmentQuick partial def check (hasCtxLocals ctxApprox : Bool) (mctx : MetavarContext) (lctx : LocalContext) (mvarDecl : MetavarDecl) (mvarId : MVarId) (fvars : Array Expr) (e : Expr) : Bool := let rec visit (e : Expr) : Bool := if !e.hasExprMVar && !e.hasFVar then true else match e with | Expr.mdata _ b _ => visit b | Expr.proj _ _ s _ => visit s | Expr.app f a _ => visit f && visit a | Expr.lam _ d b _ => visit d && visit b | Expr.forallE _ d b _ => visit d && visit b | Expr.letE _ t v b _ => visit t && visit v && visit b | Expr.bvar .. => true | Expr.sort .. => true | Expr.const .. => true | Expr.lit .. => true | Expr.fvar fvarId .. => if mvarDecl.lctx.contains fvarId then true else match lctx.find? fvarId with | some (LocalDecl.ldecl (value := v) ..) => false -- need expensive CheckAssignment.check | _ => if fvars.any fun x => x.fvarId! == fvarId then true else false -- We could throw an exception here, but we would have to use ExceptM. So, we let CheckAssignment.check do it | Expr.mvar mvarId' _ => match mctx.getExprAssignment? mvarId' with | some _ => false -- use CheckAssignment.check to instantiate | none => if mvarId' == mvarId then false -- occurs check failed, use CheckAssignment.check to throw exception else match mctx.findDecl? mvarId' with | none => false | some mvarDecl' => if hasCtxLocals then false -- use CheckAssignment.check else if mvarDecl'.lctx.isSubPrefixOf mvarDecl.lctx fvars then true else false -- use CheckAssignment.check visit e end CheckAssignmentQuick /-- Auxiliary function for handling constraints of the form `?m a₁ ... aₙ =?= v`. It will check whether we can perform the assignment ``` ?m := fun fvars => v ``` The result is `none` if the assignment can't be performed. The result is `some newV` where `newV` is a possibly updated `v`. This method may need to unfold let-declarations. -/ def checkAssignment (mvarId : MVarId) (fvars : Array Expr) (v : Expr) : MetaM (Option Expr) := do /- Check whether `mvarId` occurs in the type of `fvars` or not. If it does, return `none` to prevent us from creating the cyclic assignment `?m := fun fvars => v` -/ for fvar in fvars do unless (← occursCheck mvarId (← inferType fvar)) do return none if !v.hasExprMVar && !v.hasFVar then pure (some v) else let mvarDecl ← getMVarDecl mvarId let hasCtxLocals := fvars.any fun fvar => mvarDecl.lctx.containsFVar fvar let ctx ← read let mctx ← getMCtx if CheckAssignmentQuick.check hasCtxLocals ctx.config.ctxApprox mctx ctx.lctx mvarDecl mvarId fvars v then pure (some v) else let v ← instantiateMVars v CheckAssignment.checkAssignmentAux mvarId fvars hasCtxLocals v private def processAssignmentFOApproxAux (mvar : Expr) (args : Array Expr) (v : Expr) : MetaM Bool := match v with | Expr.app f a _ => if args.isEmpty then pure false else Meta.isExprDefEqAux args.back a <&&> Meta.isExprDefEqAux (mkAppRange mvar 0 (args.size - 1) args) f | _ => pure false /- Auxiliary method for applying first-order unification. It is an approximation. Remark: this method is trying to solve the unification constraint: ?m a₁ ... aₙ =?= v It is uses processAssignmentFOApproxAux, if it fails, it tries to unfold `v`. We have added support for unfolding here because we want to be able to solve unification problems such as ?m Unit =?= ITactic where `ITactic` is defined as def ITactic := Tactic Unit -/ private partial def processAssignmentFOApprox (mvar : Expr) (args : Array Expr) (v : Expr) : MetaM Bool := let rec loop (v : Expr) := do let cfg ← getConfig if !cfg.foApprox then pure false else trace[Meta.isDefEq.foApprox] "{mvar} {args} := {v}" let v := v.headBeta if (← checkpointDefEq <| processAssignmentFOApproxAux mvar args v) then pure true else match (← unfoldDefinition? v) with | none => pure false | some v => loop v loop v private partial def simpAssignmentArgAux : Expr → MetaM Expr | Expr.mdata _ e _ => simpAssignmentArgAux e | e@(Expr.fvar fvarId _) => do let decl ← getLocalDecl fvarId match decl.value? with | some value => simpAssignmentArgAux value | _ => pure e | e => pure e /- Auxiliary procedure for processing `?m a₁ ... aₙ =?= v`. We apply it to each `aᵢ`. It instantiates assigned metavariables if `aᵢ` is of the form `f[?n] b₁ ... bₘ`, and then removes metadata, and zeta-expand let-decls. -/ private def simpAssignmentArg (arg : Expr) : MetaM Expr := do let arg ← if arg.getAppFn.hasExprMVar then instantiateMVars arg else pure arg simpAssignmentArgAux arg /- Assign `mvar := fun a_1 ... a_{numArgs} => v`. We use it at `processConstApprox` and `isDefEqMVarSelf` -/ private def assignConst (mvar : Expr) (numArgs : Nat) (v : Expr) : MetaM Bool := do let mvarDecl ← getMVarDecl mvar.mvarId! forallBoundedTelescope mvarDecl.type numArgs fun xs _ => do if xs.size != numArgs then pure false else let some v ← mkLambdaFVarsWithLetDeps xs v | pure false match (← checkAssignment mvar.mvarId! #[] v) with | none => pure false | some v => trace[Meta.isDefEq.constApprox] "{mvar} := {v}" checkTypesAndAssign mvar v private def processConstApprox (mvar : Expr) (numArgs : Nat) (v : Expr) : MetaM Bool := do let cfg ← getConfig let mvarId := mvar.mvarId! let mvarDecl ← getMVarDecl mvarId if mvarDecl.numScopeArgs == numArgs || cfg.constApprox then assignConst mvar numArgs v else pure false /-- Tries to solve `?m a₁ ... aₙ =?= v` by assigning `?m`. It assumes `?m` is unassigned. -/ private partial def processAssignment (mvarApp : Expr) (v : Expr) : MetaM Bool := traceCtx `Meta.isDefEq.assign do trace[Meta.isDefEq.assign] "{mvarApp} := {v}" let mvar := mvarApp.getAppFn let mvarDecl ← getMVarDecl mvar.mvarId! let rec process (i : Nat) (args : Array Expr) (v : Expr) := do let cfg ← getConfig let useFOApprox (args : Array Expr) : MetaM Bool := processAssignmentFOApprox mvar args v <||> processConstApprox mvar args.size v if h : i < args.size then let arg := args.get ⟨i, h⟩ let arg ← simpAssignmentArg arg let args := args.set ⟨i, h⟩ arg match arg with | Expr.fvar fvarId _ => if args[0:i].any fun prevArg => prevArg == arg then useFOApprox args else if mvarDecl.lctx.contains fvarId && !cfg.quasiPatternApprox then useFOApprox args else process (i+1) args v | _ => useFOApprox args else let v ← instantiateMVars v -- enforce A4 if v.getAppFn == mvar then -- using A6 useFOApprox args else let mvarId := mvar.mvarId! match (← checkAssignment mvarId args v) with | none => useFOApprox args | some v => do trace[Meta.isDefEq.assign.beforeMkLambda] "{mvar} {args} := {v}" let some v ← mkLambdaFVarsWithLetDeps args v | return false if args.any (fun arg => mvarDecl.lctx.containsFVar arg) then /- We need to type check `v` because abstraction using `mkLambdaFVars` may have produced a type incorrect term. See discussion at A2 -/ if (← isTypeCorrect v) then checkTypesAndAssign mvar v else trace[Meta.isDefEq.assign.typeError] "{mvar} := {v}" useFOApprox args else checkTypesAndAssign mvar v process 0 mvarApp.getAppArgs v /-- Similar to processAssignment, but if it fails, compute v's whnf and try again. This helps to solve constraints such as `?m =?= { α := ?m, ... }.α` Note this is not perfect solution since we still fail occurs check for constraints such as ```lean ?m =?= List { α := ?m, β := Nat }.β ``` -/ private def processAssignment' (mvarApp : Expr) (v : Expr) : MetaM Bool := do if (← processAssignment mvarApp v) then return true else let vNew ← whnf v if vNew != v then if mvarApp == vNew then return true else processAssignment mvarApp vNew else return false private def isDeltaCandidate? (t : Expr) : MetaM (Option ConstantInfo) := do match t.getAppFn with | Expr.const c _ _ => match (← getConst? c) with | r@(some info) => if info.hasValue then return r else return none | _ => return none | _ => pure none /-- Auxiliary method for isDefEqDelta -/ private def isListLevelDefEq (us vs : List Level) : MetaM LBool := toLBoolM <| isListLevelDefEqAux us vs /-- Auxiliary method for isDefEqDelta -/ private def isDefEqLeft (fn : Name) (t s : Expr) : MetaM LBool := do trace[Meta.isDefEq.delta.unfoldLeft] fn toLBoolM <| Meta.isExprDefEqAux t s /-- Auxiliary method for isDefEqDelta -/ private def isDefEqRight (fn : Name) (t s : Expr) : MetaM LBool := do trace[Meta.isDefEq.delta.unfoldRight] fn toLBoolM <| Meta.isExprDefEqAux t s /-- Auxiliary method for isDefEqDelta -/ private def isDefEqLeftRight (fn : Name) (t s : Expr) : MetaM LBool := do trace[Meta.isDefEq.delta.unfoldLeftRight] fn toLBoolM <| Meta.isExprDefEqAux t s /-- Try to solve `f a₁ ... aₙ =?= f b₁ ... bₙ` by solving `a₁ =?= b₁, ..., aₙ =?= bₙ`. Auxiliary method for isDefEqDelta -/ private def tryHeuristic (t s : Expr) : MetaM Bool := let tFn := t.getAppFn let sFn := s.getAppFn traceCtx `Meta.isDefEq.delta do /- We process arguments before universe levels to reduce a source of brittleness in the TC procedure. In the TC procedure, we can solve problems containing metavariables. If the TC procedure tries to assign one of these metavariables, it interrupts the search using a "stuck" exception. The elaborator catches it, and "interprets" it as "we should try again later". Now suppose we have a TC problem, and there are two "local" candidate instances we can try: "bad" and "good". The "bad" candidate is stuck because of a universe metavariable in the TC problem. If we try "bad" first, the TC procedure is interrupted. Moreover, if we have ignored the exception, "bad" would fail anyway trying to assign two different free variables `α =?= β`. Example: `Preorder.{?u} α =?= Preorder.{?v} β`, where `?u` and `?v` are universe metavariables that were not created by the TC procedure. The key issue here is that we have an `isDefEq t s` invocation that is interrupted by the "stuck" exception, but it would have failed anyway if we had continued processing it. By solving the arguments first, we make the example above fail without throwing the "stuck" exception. TODO: instead of throwing an exception as soon as we get stuck, we should just set a flag. Then the entry-point for `isDefEq` checks the flag before returning `true`. -/ checkpointDefEq do let b ← isDefEqArgs tFn t.getAppArgs s.getAppArgs <&&> isListLevelDefEqAux tFn.constLevels! sFn.constLevels! unless b do trace[Meta.isDefEq.delta] "heuristic failed {t} =?= {s}" pure b /-- Auxiliary method for isDefEqDelta -/ private abbrev unfold (e : Expr) (failK : MetaM α) (successK : Expr → MetaM α) : MetaM α := do match (← unfoldDefinition? e) with | some e => successK e | none => failK /-- Auxiliary method for isDefEqDelta -/ private def unfoldBothDefEq (fn : Name) (t s : Expr) : MetaM LBool := do match t, s with | Expr.const _ ls₁ _, Expr.const _ ls₂ _ => isListLevelDefEq ls₁ ls₂ | Expr.app _ _ _, Expr.app _ _ _ => if (← tryHeuristic t s) then pure LBool.true else unfold t (unfold s (pure LBool.false) (fun s => isDefEqRight fn t s)) (fun t => unfold s (isDefEqLeft fn t s) (fun s => isDefEqLeftRight fn t s)) | _, _ => pure LBool.false private def sameHeadSymbol (t s : Expr) : Bool := match t.getAppFn, s.getAppFn with | Expr.const c₁ _ _, Expr.const c₂ _ _ => true | _, _ => false /-- - If headSymbol (unfold t) == headSymbol s, then unfold t - If headSymbol (unfold s) == headSymbol t, then unfold s - Otherwise unfold t and s if possible. Auxiliary method for isDefEqDelta -/ private def unfoldComparingHeadsDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := unfold t (unfold s (pure LBool.undef) -- `t` and `s` failed to be unfolded (fun s => isDefEqRight sInfo.name t s)) (fun tNew => if sameHeadSymbol tNew s then isDefEqLeft tInfo.name tNew s else unfold s (isDefEqLeft tInfo.name tNew s) (fun sNew => if sameHeadSymbol t sNew then isDefEqRight sInfo.name t sNew else isDefEqLeftRight tInfo.name tNew sNew)) /-- If `t` and `s` do not contain metavariables, then use kernel definitional equality heuristics. Otherwise, use `unfoldComparingHeadsDefEq`. Auxiliary method for isDefEqDelta -/ private def unfoldDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := if !t.hasExprMVar && !s.hasExprMVar then /- If `t` and `s` do not contain metavariables, we simulate strategy used in the kernel. -/ if tInfo.hints.lt sInfo.hints then unfold t (unfoldComparingHeadsDefEq tInfo sInfo t s) fun t => isDefEqLeft tInfo.name t s else if sInfo.hints.lt tInfo.hints then unfold s (unfoldComparingHeadsDefEq tInfo sInfo t s) fun s => isDefEqRight sInfo.name t s else unfoldComparingHeadsDefEq tInfo sInfo t s else unfoldComparingHeadsDefEq tInfo sInfo t s /-- When `TransparencyMode` is set to `default` or `all`. If `t` is reducible and `s` is not ==> `isDefEqLeft (unfold t) s` If `s` is reducible and `t` is not ==> `isDefEqRight t (unfold s)` Otherwise, use `unfoldDefEq` Auxiliary method for isDefEqDelta -/ private def unfoldReducibeDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := do if (← shouldReduceReducibleOnly) then unfoldDefEq tInfo sInfo t s else let tReducible ← isReducible tInfo.name let sReducible ← isReducible sInfo.name if tReducible && !sReducible then unfold t (unfoldDefEq tInfo sInfo t s) fun t => isDefEqLeft tInfo.name t s else if !tReducible && sReducible then unfold s (unfoldDefEq tInfo sInfo t s) fun s => isDefEqRight sInfo.name t s else unfoldDefEq tInfo sInfo t s /-- If `t` is a projection function application and `s` is not ==> `isDefEqRight t (unfold s)` If `s` is a projection function application and `t` is not ==> `isDefEqRight (unfold t) s` Otherwise, use `unfoldReducibeDefEq` Auxiliary method for isDefEqDelta -/ private def unfoldNonProjFnDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := do let tProj? ← isProjectionFn tInfo.name let sProj? ← isProjectionFn sInfo.name if tProj? && !sProj? then unfold s (unfoldDefEq tInfo sInfo t s) fun s => isDefEqRight sInfo.name t s else if !tProj? && sProj? then unfold t (unfoldDefEq tInfo sInfo t s) fun t => isDefEqLeft tInfo.name t s else unfoldReducibeDefEq tInfo sInfo t s /-- isDefEq by lazy delta reduction. This method implements many different heuristics: 1- If only `t` can be unfolded => then unfold `t` and continue 2- If only `s` can be unfolded => then unfold `s` and continue 3- If `t` and `s` can be unfolded and they have the same head symbol, then a) First try to solve unification by unifying arguments. b) If it fails, unfold both and continue. Implemented by `unfoldBothDefEq` 4- If `t` is a projection function application and `s` is not => then unfold `s` and continue. 5- If `s` is a projection function application and `t` is not => then unfold `t` and continue. Remark: 4&5 are implemented by `unfoldNonProjFnDefEq` 6- If `t` is reducible and `s` is not => then unfold `t` and continue. 7- If `s` is reducible and `t` is not => then unfold `s` and continue Remark: 6&7 are implemented by `unfoldReducibeDefEq` 8- If `t` and `s` do not contain metavariables, then use heuristic used in the Kernel. Implemented by `unfoldDefEq` 9- If `headSymbol (unfold t) == headSymbol s`, then unfold t and continue. 10- If `headSymbol (unfold s) == headSymbol t`, then unfold s 11- Otherwise, unfold `t` and `s` and continue. Remark: 9&10&11 are implemented by `unfoldComparingHeadsDefEq` -/ private def isDefEqDelta (t s : Expr) : MetaM LBool := do let tInfo? ← isDeltaCandidate? t.getAppFn let sInfo? ← isDeltaCandidate? s.getAppFn match tInfo?, sInfo? with | none, none => pure LBool.undef | some tInfo, none => unfold t (pure LBool.undef) fun t => isDefEqLeft tInfo.name t s | none, some sInfo => unfold s (pure LBool.undef) fun s => isDefEqRight sInfo.name t s | some tInfo, some sInfo => if tInfo.name == sInfo.name then unfoldBothDefEq tInfo.name t s else unfoldNonProjFnDefEq tInfo sInfo t s private def isAssigned : Expr → MetaM Bool | Expr.mvar mvarId _ => isExprMVarAssigned mvarId | _ => pure false private def isDelayedAssignedHead (tFn : Expr) (t : Expr) : MetaM Bool := do match tFn with | Expr.mvar mvarId _ => if (← isDelayedAssigned mvarId) then let tNew ← instantiateMVars t return tNew != t else pure false | _ => pure false private def isSynthetic : Expr → MetaM Bool | Expr.mvar mvarId _ => do let mvarDecl ← getMVarDecl mvarId match mvarDecl.kind with | MetavarKind.synthetic => pure true | MetavarKind.syntheticOpaque => pure true | MetavarKind.natural => pure false | _ => pure false private def isAssignable : Expr → MetaM Bool | Expr.mvar mvarId _ => do let b ← isReadOnlyOrSyntheticOpaqueExprMVar mvarId; pure (!b) | _ => pure false private def etaEq (t s : Expr) : Bool := match t.etaExpanded? with | some t => t == s | none => false private def isLetFVar (fvarId : FVarId) : MetaM Bool := do let decl ← getLocalDecl fvarId pure decl.isLet private def isDefEqProofIrrel (t s : Expr) : MetaM LBool := do if (← getConfig).proofIrrelevance then let status ← isProofQuick t match status with | LBool.false => pure LBool.undef | LBool.true => let tType ← inferType t let sType ← inferType s toLBoolM <| Meta.isExprDefEqAux tType sType | LBool.undef => let tType ← inferType t if (← isProp tType) then let sType ← inferType s toLBoolM <| Meta.isExprDefEqAux tType sType else pure LBool.undef else pure LBool.undef /- Try to solve constraint of the form `?m args₁ =?= ?m args₂`. - First try to unify `args₁` and `args₂`, and return true if successful - Otherwise, try to assign `?m` to a constant function of the form `fun x_1 ... x_n => ?n` where `?n` is a fresh metavariable. See `processConstApprox`. -/ private def isDefEqMVarSelf (mvar : Expr) (args₁ args₂ : Array Expr) : MetaM Bool := do if args₁.size != args₂.size then pure false else if (← isDefEqArgs mvar args₁ args₂) then pure true else if !(← isAssignable mvar) then pure false else let cfg ← getConfig let mvarId := mvar.mvarId! let mvarDecl ← getMVarDecl mvarId if mvarDecl.numScopeArgs == args₁.size || cfg.constApprox then let type ← inferType (mkAppN mvar args₁) let auxMVar ← mkAuxMVar mvarDecl.lctx mvarDecl.localInstances type assignConst mvar args₁.size auxMVar else pure false /- Remove unnecessary let-decls -/ private def consumeLet : Expr → Expr | e@(Expr.letE _ _ _ b _) => if b.hasLooseBVars then e else consumeLet b | e => e mutual private partial def isDefEqQuick (t s : Expr) : MetaM LBool := let t := consumeLet t let s := consumeLet s match t, s with | Expr.lit l₁ _, Expr.lit l₂ _ => return (l₁ == l₂).toLBool | Expr.sort u _, Expr.sort v _ => toLBoolM <| isLevelDefEqAux u v | Expr.lam .., Expr.lam .. => if t == s then pure LBool.true else toLBoolM <| isDefEqBinding t s | Expr.forallE .., Expr.forallE .. => if t == s then pure LBool.true else toLBoolM <| isDefEqBinding t s | Expr.mdata _ t _, s => isDefEqQuick t s | t, Expr.mdata _ s _ => isDefEqQuick t s | Expr.fvar fvarId₁ _, Expr.fvar fvarId₂ _ => do if (← isLetFVar fvarId₁ <||> isLetFVar fvarId₂) then pure LBool.undef else if fvarId₁ == fvarId₂ then pure LBool.true else isDefEqProofIrrel t s | t, s => isDefEqQuickOther t s private partial def isDefEqQuickOther (t s : Expr) : MetaM LBool := do if t == s then pure LBool.true else if etaEq t s || etaEq s t then pure LBool.true -- t =?= (fun xs => t xs) else let tFn := t.getAppFn let sFn := s.getAppFn if !tFn.isMVar && !sFn.isMVar then pure LBool.undef else if (← isAssigned tFn) then let t ← instantiateMVars t isDefEqQuick t s else if (← isAssigned sFn) then let s ← instantiateMVars s isDefEqQuick t s else if (← isDelayedAssignedHead tFn t) then let t ← instantiateMVars t isDefEqQuick t s else if (← isDelayedAssignedHead sFn s) then let s ← instantiateMVars s isDefEqQuick t s else if (← isSynthetic tFn <&&> trySynthPending tFn) then let t ← instantiateMVars t isDefEqQuick t s else if (← isSynthetic sFn <&&> trySynthPending sFn) then let s ← instantiateMVars s isDefEqQuick t s else if tFn.isMVar && sFn.isMVar && tFn == sFn then Bool.toLBool <$> isDefEqMVarSelf tFn t.getAppArgs s.getAppArgs else let tAssign? ← isAssignable tFn let sAssign? ← isAssignable sFn let assignableMsg (b : Bool) := if b then "[assignable]" else "[nonassignable]" trace[Meta.isDefEq] "{t} {assignableMsg tAssign?} =?= {s} {assignableMsg sAssign?}" if tAssign? && !sAssign? then toLBoolM <| processAssignment' t s else if !tAssign? && sAssign? then toLBoolM <| processAssignment' s t else if !tAssign? && !sAssign? then if tFn.isMVar || sFn.isMVar then let ctx ← read if ctx.config.isDefEqStuckEx then do trace[Meta.isDefEq.stuck] "{t} =?= {s}" Meta.throwIsDefEqStuck else pure LBool.false else pure LBool.undef else isDefEqQuickMVarMVar t s -- Both `t` and `s` are terms of the form `?m ...` private partial def isDefEqQuickMVarMVar (t s : Expr) : MetaM LBool := do let tFn := t.getAppFn let sFn := s.getAppFn let tMVarDecl ← getMVarDecl tFn.mvarId! let sMVarDecl ← getMVarDecl sFn.mvarId! if s.isMVar && !t.isMVar then /- Solve `?m t =?= ?n` by trying first `?n := ?m t`. Reason: this assignment is precise. -/ if (← checkpointDefEq (processAssignment s t)) then pure LBool.true else toLBoolM <| processAssignment t s else if (← checkpointDefEq (processAssignment t s)) then pure LBool.true else toLBoolM <| processAssignment s t end @[inline] def whenUndefDo (x : MetaM LBool) (k : MetaM Bool) : MetaM Bool := do let status ← x match status with | LBool.true => pure true | LBool.false => pure false | LBool.undef => k @[specialize] private def unstuckMVar (e : Expr) (successK : Expr → MetaM Bool) (failK : MetaM Bool): MetaM Bool := do match (← getStuckMVar? e) with | some mvarId => trace[Meta.isDefEq.stuckMVar] "found stuck MVar {mkMVar mvarId} : {← inferType (mkMVar mvarId)}" if (← Meta.synthPending mvarId) then let e ← instantiateMVars e successK e else failK | none => failK private def isDefEqOnFailure (t s : Expr) : MetaM Bool := unstuckMVar t (fun t => Meta.isExprDefEqAux t s) <| unstuckMVar s (fun s => Meta.isExprDefEqAux t s) <| tryUnificationHints t s <||> tryUnificationHints s t private def isDefEqProj : Expr → Expr → MetaM Bool | Expr.proj _ i t _, Expr.proj _ j s _ => pure (i == j) <&&> Meta.isExprDefEqAux t s | Expr.proj structName 0 s _, v => isDefEqSingleton structName s v | v, Expr.proj structName 0 s _ => isDefEqSingleton structName s v | _, _ => pure false where /- If `structName` is a structure with a single field, then reduce `s.1 =?= v` to `s =?= ⟨v⟩` -/ isDefEqSingleton (structName : Name) (s : Expr) (v : Expr) : MetaM Bool := do let ctorVal := getStructureCtor (← getEnv) structName if ctorVal.numFields != 1 then return false -- It is not a structure with a single field. let sType ← whnf (← inferType s) let sTypeFn := sType.getAppFn if !sTypeFn.isConstOf structName then return false let ctorApp := mkApp (mkAppN (mkConst ctorVal.name sTypeFn.constLevels!) sType.getAppArgs) v Meta.isExprDefEqAux s ctorApp /- Given applications `t` and `s` that are in WHNF (modulo the current transparency setting), check whether they are definitionally equal or not. -/ private def isDefEqApp (t s : Expr) : MetaM Bool := do let tFn := t.getAppFn let sFn := s.getAppFn if tFn.isConst && sFn.isConst && tFn.constName! == sFn.constName! then /- See comment at `tryHeuristic` explaining why we processe arguments before universe levels. -/ if (← checkpointDefEq (isDefEqArgs tFn t.getAppArgs s.getAppArgs <&&> isListLevelDefEqAux tFn.constLevels! sFn.constLevels!)) then return true else isDefEqOnFailure t s else if (← checkpointDefEq (Meta.isExprDefEqAux tFn s.getAppFn <&&> isDefEqArgs tFn t.getAppArgs s.getAppArgs)) then return true else isDefEqOnFailure t s partial def isExprDefEqAuxImpl (t : Expr) (s : Expr) : MetaM Bool := do trace[Meta.isDefEq.step] "{t} =?= {s}" checkMaxHeartbeats "isDefEq" withNestedTraces do whenUndefDo (isDefEqQuick t s) do whenUndefDo (isDefEqProofIrrel t s) do let t' ← whnfCore t let s' ← whnfCore s if t != t' || s != s' then isExprDefEqAuxImpl t' s' else do if (← (isDefEqEta t s <||> isDefEqEta s t)) then pure true else if (← isDefEqProj t s) then pure true else whenUndefDo (isDefEqNative t s) do whenUndefDo (isDefEqNat t s) do whenUndefDo (isDefEqOffset t s) do whenUndefDo (isDefEqDelta t s) do if t.isConst && s.isConst then if t.constName! == s.constName! then isListLevelDefEqAux t.constLevels! s.constLevels! else pure false else if t.isApp && s.isApp then isDefEqApp t s else whenUndefDo (isDefEqStringLit t s) do isDefEqOnFailure t s builtin_initialize isExprDefEqAuxRef.set isExprDefEqAuxImpl builtin_initialize registerTraceClass `Meta.isDefEq registerTraceClass `Meta.isDefEq.foApprox registerTraceClass `Meta.isDefEq.constApprox registerTraceClass `Meta.isDefEq.delta registerTraceClass `Meta.isDefEq.step registerTraceClass `Meta.isDefEq.assign end Lean.Meta
b297ef64ce7c3035deef0532a9e6b33aadf6243d
6e41ee3ac9b96e8980a16295cc21f131e731884f
/hott/algebra/category/basic.hlean
7c991a26d4fd76d9aa79d106f194f80b131d2df4
[ "Apache-2.0" ]
permissive
EgbertRijke/lean
3426cfa0e5b3d35d12fc3fd7318b35574cb67dc3
4f2e0c6d7fc9274d953cfa1c37ab2f3e799ab183
refs/heads/master
1,610,834,871,476
1,422,159,801,000
1,422,159,801,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,319
hlean
-- Copyright (c) 2014 Jakob von Raumer. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Jakob von Raumer import ..precategory.basic ..precategory.morphism ..precategory.iso open precategory morphism is_equiv eq truncation nat sigma sigma.ops -- A category is a precategory extended by a witness, -- that the function assigning to each isomorphism a path, -- is an equivalecnce. structure category [class] (ob : Type) extends (precategory ob) := (iso_of_path_equiv : Π {a b : ob}, is_equiv (@iso_of_path ob (precategory.mk hom _ comp ID assoc id_left id_right) a b)) persistent attribute category [multiple-instances] namespace category variables {ob : Type} {C : category ob} {a b : ob} include C -- Make iso_of_path_equiv a class instance -- TODO: Unsafe class instance? persistent attribute iso_of_path_equiv [instance] definition path_of_iso {a b : ob} : a ≅ b → a = b := iso_of_path⁻¹ definition ob_1_type : is_trunc nat.zero .+1 ob := begin apply is_trunc_succ, intros (a, b), fapply trunc_equiv, exact (@path_of_iso _ _ a b), apply inv_closed, apply is_hset_iso, end end category -- Bundled version of categories inductive Category : Type := mk : Π (ob : Type), category ob → Category
681219a7e56d83a191781c5c65273615c46cdbd5
761d983a78bc025071bac14a3facced881cf5e53
/new_affine/monoid_with_monus.lean
41d99b2ac53aa9128f5f50f26eadde0baeed66b0
[]
no_license
rohanrajnair/affine_lib
bcf22ff892cf74ccb36a95bc9b7fff8e0adb2d0d
83076864245ac547b9d615bc6a23804b1b4a8f70
refs/heads/master
1,673,320,928,343
1,603,036,653,000
1,603,036,653,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
442
lean
import algebra.group.basic instance : add_semigroup ℕ := ⟨has_add.add, nat.add_assoc⟩ instance : add_monoid ℕ := ⟨has_add.add, nat.add_assoc, nat.zero, nat.zero_add, nat.add_zero⟩ instance : add_comm_semigroup ℕ := ⟨has_add.add, nat.add_assoc, nat.add_comm⟩ instance : add_comm_monoid ℕ := ⟨has_add.add, nat.add_assoc, nat.zero, nat.zero_add, nat.add_zero, nat.add_comm⟩ #eval (2 : ℕ) - (3 : ℕ) #check nat.sub
3ddb860df660f5727688d2b277c9b693ebb3f557
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/src/Lean/Data/Lsp/Extra.lean
3f41b0ef3ebf782d2e9fb6422531a9a444cebacb
[ "Apache-2.0" ]
permissive
gebner/lean4-old
a4129a041af2d4d12afb3a8d4deedabde727719b
ee51cdfaf63ee313c914d83264f91f414a0e3b6e
refs/heads/master
1,683,628,606,745
1,622,651,300,000
1,622,654,405,000
142,608,821
1
0
null
null
null
null
UTF-8
Lean
false
false
1,744
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga -/ import Lean.Data.Json import Lean.Data.JsonRpc import Lean.Data.Lsp.Basic /-! This file contains Lean-specific extensions to LSP. The following additional packets are supported: - "textDocument/waitForDiagnostics": Yields a response when all the diagnostics for a version of the document greater or equal to the specified one have been emitted. If the request specifies a version above the most recently processed one, the server will delay the response until it does receive the specified version. Exists for synchronization purposes, e.g. during testing or when external tools might want to use our LSP server. -/ namespace Lean.Lsp open Json structure WaitForDiagnosticsParams where uri : DocumentUri version : Nat deriving ToJson, FromJson structure WaitForDiagnostics instance : FromJson WaitForDiagnostics := ⟨fun j => WaitForDiagnostics.mk⟩ instance : ToJson WaitForDiagnostics := ⟨fun o => mkObj []⟩ structure LeanFileProgressProcessingInfo where range : Range deriving FromJson, ToJson structure LeanFileProgressParams where textDocument : VersionedTextDocumentIdentifier processing : Array LeanFileProgressProcessingInfo deriving FromJson, ToJson structure PlainGoalParams extends TextDocumentPositionParams deriving FromJson, ToJson structure PlainGoal where rendered : String goals : Array String deriving FromJson, ToJson structure PlainTermGoalParams extends TextDocumentPositionParams deriving FromJson, ToJson structure PlainTermGoal where goal : String range : Range deriving FromJson, ToJson end Lean.Lsp
5681ee3aa932adf679d90bf8f42276825a08f93d
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/measure/complex.lean
3137af7de2b5404ed6406d7e0d7aef91a9bcb1b0
[ "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,567
lean
/- Copyright (c) 2021 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import measure_theory.measure.vector_measure /-! # Complex measure > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file proves some elementary results about complex measures. In particular, we prove that a complex measure is always in the form `s + it` where `s` and `t` are signed measures. The complex measure is defined to be vector measure over `ℂ`, this definition can be found in `measure_theory.measure.vector_measure` and is known as `measure_theory.complex_measure`. ## Main definitions * `measure_theory.complex_measure.re`: obtains a signed measure `s` from a complex measure `c` such that `s i = (c i).re` for all measurable sets `i`. * `measure_theory.complex_measure.im`: obtains a signed measure `s` from a complex measure `c` such that `s i = (c i).im` for all measurable sets `i`. * `measure_theory.signed_measure.to_complex_measure`: given two signed measures `s` and `t`, `s.to_complex_measure t` provides a complex measure of the form `s + it`. * `measure_theory.complex_measure.equiv_signed_measure`: is the equivalence between the complex measures and the type of the product of the signed measures with itself. # Tags Complex measure -/ noncomputable theory open_locale classical measure_theory ennreal nnreal variables {α β : Type*} {m : measurable_space α} namespace measure_theory open vector_measure namespace complex_measure include m /-- The real part of a complex measure is a signed measure. -/ @[simps apply] def re : complex_measure α →ₗ[ℝ] signed_measure α := map_rangeₗ complex.re_clm complex.continuous_re /-- The imaginary part of a complex measure is a signed measure. -/ @[simps apply] def im : complex_measure α →ₗ[ℝ] signed_measure α := map_rangeₗ complex.im_clm complex.continuous_im /-- Given `s` and `t` signed measures, `s + it` is a complex measure-/ @[simps] def _root_.measure_theory.signed_measure.to_complex_measure (s t : signed_measure α) : complex_measure α := { measure_of' := λ i, ⟨s i, t i⟩, empty' := by rw [s.empty, t.empty]; refl, not_measurable' := λ i hi, by rw [s.not_measurable hi, t.not_measurable hi]; refl, m_Union' := λ f hf hfdisj, (complex.has_sum_iff _ _).2 ⟨s.m_Union hf hfdisj, t.m_Union hf hfdisj⟩ } lemma _root_.measure_theory.signed_measure.to_complex_measure_apply {s t : signed_measure α} {i : set α} : s.to_complex_measure t i = ⟨s i, t i⟩ := rfl lemma to_complex_measure_to_signed_measure (c : complex_measure α) : c.re.to_complex_measure c.im = c := by { ext i hi; refl } lemma _root_.measure_theory.signed_measure.re_to_complex_measure (s t : signed_measure α) : (s.to_complex_measure t).re = s := by { ext i hi, refl } lemma _root_.measure_theory.signed_measure.im_to_complex_measure (s t : signed_measure α) : (s.to_complex_measure t).im = t := by { ext i hi, refl } /-- The complex measures form an equivalence to the type of pairs of signed measures. -/ @[simps] def equiv_signed_measure : complex_measure α ≃ signed_measure α × signed_measure α := { to_fun := λ c, ⟨c.re, c.im⟩, inv_fun := λ ⟨s, t⟩, s.to_complex_measure t, left_inv := λ c, c.to_complex_measure_to_signed_measure, right_inv := λ ⟨s, t⟩, prod.mk.inj_iff.2 ⟨s.re_to_complex_measure t, s.im_to_complex_measure t⟩ } section variables {R : Type*} [semiring R] [module R ℝ] variables [has_continuous_const_smul R ℝ] [has_continuous_const_smul R ℂ] /-- The complex measures form an linear isomorphism to the type of pairs of signed measures. -/ @[simps] def equiv_signed_measureₗ : complex_measure α ≃ₗ[R] signed_measure α × signed_measure α := { map_add' := λ c d, by { ext i hi; refl }, map_smul' := begin intros r c, ext i hi, { change (r • c i).re = r • (c i).re, simp [complex.smul_re] }, { ext i hi, change (r • c i).im = r • (c i).im, simp [complex.smul_im] } end, .. equiv_signed_measure } end lemma absolutely_continuous_ennreal_iff (c : complex_measure α) (μ : vector_measure α ℝ≥0∞) : c ≪ᵥ μ ↔ c.re ≪ᵥ μ ∧ c.im ≪ᵥ μ := begin split; intro h, { split; { intros i hi, simp [h hi] } }, { intros i hi, rw [← complex.re_add_im (c i), (_ : (c i).re = 0), (_ : (c i).im = 0)], exacts [by simp, h.2 hi, h.1 hi] } end end complex_measure end measure_theory
2615a6ba4c4e45246b4e68bb7264b6c734ceb27f
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/combinatorics/simple_graph/connectivity.lean
c9269b94e62db65cd3acd5635f099050236ba4d4
[ "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
15,189
lean
/- Copyright (c) 2021 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import combinatorics.simple_graph.basic /-! # Graph connectivity In a simple graph, * A *walk* is a finite sequence of adjacent vertices, and can be thought of equally well as a sequence of directed edges. * A *trail* is a walk whose edges each appear no more than once. * A *path* is a trail whose vertices appear no more than once. * A *cycle* is a nonempty trail whose first and last vertices are the same and whose vertices except for the first appear no more than once. **Warning:** graph theorists mean something different by "path" than do homotopy theorists. A "walk" in graph theory is a "path" in homotopy theory. Another warning: some graph theorists use "path" and "simple path" for "walk" and "path." Some definitions and theorems have inspiration from multigraph counterparts in [Chou1994]. ## Main definitions * `simple_graph.walk` * `simple_graph.is_trail`, `simple_graph.is_path`, and `simple_graph.is_cycle`. * `simple_graph.path` ## Tags walks, trails, paths, circuits, cycles -/ universes u namespace simple_graph variables {V : Type u} (G : simple_graph V) /-- A walk is a sequence of adjacent vertices. For vertices `u v : V`, the type `walk u v` consists of all walks starting at `u` and ending at `v`. We say that a walk *visits* the vertices it contains. The set of vertices a walk visits is `simple_graph.walk.support`. -/ @[derive decidable_eq] inductive walk : V → V → Type u | nil {u : V} : walk u u | cons {u v w: V} (h : G.adj u v) (p : walk v w) : walk u w attribute [refl] walk.nil instance walk.inhabited (v : V) : inhabited (G.walk v v) := ⟨by refl⟩ namespace walk variables {G} lemma exists_eq_cons_of_ne : Π {u v : V} (hne : u ≠ v) (p : G.walk u v), ∃ (w : V) (h : G.adj u w) (p' : G.walk w v), p = cons h p' | _ _ hne nil := (hne rfl).elim | _ _ _ (cons h p') := ⟨_, h, p', rfl⟩ /-- The length of a walk is the number of edges along it. -/ def length : Π {u v : V}, G.walk u v → ℕ | _ _ nil := 0 | _ _ (cons _ q) := q.length.succ /-- The concatenation of two compatible walks. -/ @[trans] def append : Π {u v w : V}, G.walk u v → G.walk v w → G.walk u w | _ _ _ nil q := q | _ _ _ (cons h p) q := cons h (p.append q) /-- The concatenation of the reverse of the first walk with the second walk. -/ protected def reverse_aux : Π {u v w : V}, G.walk u v → G.walk u w → G.walk v w | _ _ _ nil q := q | _ _ _ (cons h p) q := reverse_aux p (cons (G.symm h) q) /-- The walk in reverse. -/ @[symm] def reverse {u v : V} (w : G.walk u v) : G.walk v u := w.reverse_aux nil /-- Get the `n`th vertex from a walk, where `n` is generally expected to be between `0` and `p.length`, inclusive. If `n` is greater than or equal to `p.length`, the result is the path's endpoint. -/ def get_vert : Π {u v : V} (p : G.walk u v) (n : ℕ), V | u v nil _ := u | u v (cons _ _) 0 := u | u v (cons _ q) (n+1) := q.get_vert n @[simp] lemma cons_append {u v w x : V} (h : G.adj u v) (p : G.walk v w) (q : G.walk w x) : (cons h p).append q = cons h (p.append q) := rfl @[simp] lemma cons_nil_append {u v w : V} (h : G.adj u v) (p : G.walk v w) : (cons h nil).append p = cons h p := rfl @[simp] lemma append_nil : Π {u v : V} (p : G.walk u v), p.append nil = p | _ _ nil := rfl | _ _ (cons h p) := by rw [cons_append, append_nil] @[simp] lemma nil_append {u v : V} (p : G.walk u v) : nil.append p = p := rfl lemma append_assoc : Π {u v w x : V} (p : G.walk u v) (q : G.walk v w) (r : G.walk w x), p.append (q.append r) = (p.append q).append r | _ _ _ _ nil _ _ := rfl | _ _ _ _ (cons h p') q r := by { dunfold append, rw append_assoc, } @[simp] lemma reverse_nil {u : V} : (nil : G.walk u u).reverse = nil := rfl lemma reverse_singleton {u v : V} (h : G.adj u v) : (cons h nil).reverse = cons (G.symm h) nil := rfl @[simp] lemma cons_reverse_aux {u v w x : V} (p : G.walk u v) (q : G.walk w x) (h : G.adj w u) : (cons h p).reverse_aux q = p.reverse_aux (cons (G.symm h) q) := rfl @[simp] protected lemma append_reverse_aux : Π {u v w x : V} (p : G.walk u v) (q : G.walk v w) (r : G.walk u x), (p.append q).reverse_aux r = q.reverse_aux (p.reverse_aux r) | _ _ _ _ nil _ _ := rfl | _ _ _ _ (cons h p') q r := append_reverse_aux p' q (cons (G.symm h) r) @[simp] protected lemma reverse_aux_append : Π {u v w x : V} (p : G.walk u v) (q : G.walk u w) (r : G.walk w x), (p.reverse_aux q).append r = p.reverse_aux (q.append r) | _ _ _ _ nil _ _ := rfl | _ _ _ _ (cons h p') q r := by simp [reverse_aux_append p' (cons (G.symm h) q) r] protected lemma reverse_aux_eq_reverse_append {u v w : V} (p : G.walk u v) (q : G.walk u w) : p.reverse_aux q = p.reverse.append q := by simp [reverse] @[simp] lemma reverse_cons {u v w : V} (h : G.adj u v) (p : G.walk v w) : (cons h p).reverse = p.reverse.append (cons (G.symm h) nil) := by simp [reverse] @[simp] lemma reverse_append {u v w : V} (p : G.walk u v) (q : G.walk v w) : (p.append q).reverse = q.reverse.append p.reverse := by simp [reverse] @[simp] lemma reverse_reverse : Π {u v : V} (p : G.walk u v), p.reverse.reverse = p | _ _ nil := rfl | _ _ (cons h p) := by simp [reverse_reverse] @[simp] lemma length_nil {u : V} : (nil : G.walk u u).length = 0 := rfl @[simp] lemma length_cons {u v w : V} (h : G.adj u v) (p : G.walk v w) : (cons h p).length = p.length + 1 := rfl @[simp] lemma length_append : Π {u v w : V} (p : G.walk u v) (q : G.walk v w), (p.append q).length = p.length + q.length | _ _ _ nil _ := by simp | _ _ _ (cons _ _) _ := by simp [length_append, add_left_comm, add_comm] @[simp] protected lemma length_reverse_aux : Π {u v w : V} (p : G.walk u v) (q : G.walk u w), (p.reverse_aux q).length = p.length + q.length | _ _ _ nil _ := by simp! | _ _ _ (cons _ _) _ := by simp [length_reverse_aux, nat.add_succ, nat.succ_add] @[simp] lemma length_reverse {u v : V} (p : G.walk u v) : p.reverse.length = p.length := by simp [reverse] /-- The `support` of a walk is the list of vertices it visits in order. -/ def support : Π {u v : V}, G.walk u v → list V | u v nil := [u] | u v (cons h p) := u :: p.support /-- The `edges` of a walk is the list of edges it visits in order. -/ def edges : Π {u v : V}, G.walk u v → list (sym2 V) | u v nil := [] | u v (@cons _ _ _ x _ h p) := ⟦(u, x)⟧ :: p.edges @[simp] lemma support_nil {u : V} : (nil : G.walk u u).support = [u] := rfl @[simp] lemma support_cons {u v w : V} (h : G.adj u v) (p : G.walk v w) : (cons h p).support = u :: p.support := rfl lemma support_append {u v w : V} (p : G.walk u v) (p' : G.walk v w) : (p.append p').support = p.support ++ p'.support.tail := by induction p; cases p'; simp [*] @[simp] lemma support_reverse {u v : V} (p : G.walk u v) : p.reverse.support = p.support.reverse := by induction p; simp [support_append, *] lemma support_ne_nil {u v : V} (p : G.walk u v) : p.support ≠ [] := by cases p; simp lemma tail_support_append {u v w : V} (p : G.walk u v) (p' : G.walk v w) : (p.append p').support.tail = p.support.tail ++ p'.support.tail := by rw [support_append, list.tail_append_of_ne_nil _ _ (support_ne_nil _)] lemma support_eq_cons {u v : V} (p : G.walk u v) : p.support = u :: p.support.tail := by cases p; simp @[simp] lemma start_mem_support {u v : V} (p : G.walk u v) : u ∈ p.support := by cases p; simp @[simp] lemma end_mem_support {u v : V} (p : G.walk u v) : v ∈ p.support := by induction p; simp [*] lemma mem_support_iff {u v w : V} (p : G.walk u v) : w ∈ p.support ↔ w = u ∨ w ∈ p.support.tail := by cases p; simp @[simp] lemma mem_tail_support_append_iff {t u v w : V} (p : G.walk u v) (p' : G.walk v w) : t ∈ (p.append p').support.tail ↔ t ∈ p.support.tail ∨ t ∈ p'.support.tail := by rw [tail_support_append, list.mem_append] @[simp] lemma end_mem_tail_support_of_ne {u v : V} (h : u ≠ v) (p : G.walk u v) : v ∈ p.support.tail := by { obtain ⟨_, _, _, rfl⟩ := exists_eq_cons_of_ne h p, simp } @[simp] lemma mem_support_append_iff {t u v w : V} (p : G.walk u v) (p' : G.walk v w) : t ∈ (p.append p').support ↔ t ∈ p.support ∨ t ∈ p'.support := begin simp only [mem_support_iff, mem_tail_support_append_iff], by_cases h : t = v; by_cases h' : t = u; subst_vars; try { have := ne.symm h' }; simp [*], end lemma coe_support {u v : V} (p : G.walk u v) : (p.support : multiset V) = {u} + p.support.tail := by cases p; refl lemma coe_support_append {u v w : V} (p : G.walk u v) (p' : G.walk v w) : ((p.append p').support : multiset V) = {u} + p.support.tail + p'.support.tail := by rw [support_append, ←multiset.coe_add, coe_support] lemma coe_support_append' [decidable_eq V] {u v w : V} (p : G.walk u v) (p' : G.walk v w) : ((p.append p').support : multiset V) = p.support + p'.support - {v} := begin rw [support_append, ←multiset.coe_add], simp only [coe_support], rw add_comm {v}, simp only [← add_assoc, add_tsub_cancel_right], end lemma chain_adj_support_aux : Π {u v w : V} (h : G.adj u v) (p : G.walk v w), list.chain G.adj u p.support | _ _ _ h nil := list.chain.cons h list.chain.nil | _ _ _ h (cons h' p) := list.chain.cons h (chain_adj_support_aux h' p) lemma chain_adj_support : Π {u v : V} (p : G.walk u v), list.chain' G.adj p.support | _ _ nil := list.chain.nil | _ _ (cons h p) := chain_adj_support_aux h p /-- Every edge in a walk's edge list is an edge of the graph. It is written in this form to avoid unsightly coercions. -/ lemma edges_subset_edge_set : Π {u v : V} (p : G.walk u v) {e : sym2 V} (h : e ∈ p.edges), e ∈ G.edge_set | _ _ (cons h' p') e h := by rcases h with ⟨rfl, h⟩; solve_by_elim @[simp] lemma edges_nil {u : V} : (nil : G.walk u u).edges = [] := rfl @[simp] lemma edges_cons {u v w : V} (h : G.adj u v) (p : G.walk v w) : (cons h p).edges = ⟦(u, v)⟧ :: p.edges := rfl @[simp] lemma edges_append {u v w : V} (p : G.walk u v) (p' : G.walk v w) : (p.append p').edges = p.edges ++ p'.edges := by induction p; simp [*] @[simp] lemma edges_reverse {u v : V} (p : G.walk u v) : p.reverse.edges = p.edges.reverse := by induction p; simp [*, sym2.eq_swap] @[simp] lemma length_support {u v : V} (p : G.walk u v) : p.support.length = p.length + 1 := by induction p; simp * @[simp] lemma length_edges {u v : V} (p : G.walk u v) : p.edges.length = p.length := by induction p; simp * lemma mem_support_of_mem_edges : Π {t u v w : V} (p : G.walk v w) (he : ⟦(t, u)⟧ ∈ p.edges), t ∈ p.support | t u v w (cons h p') he := begin simp only [support_cons, edges_cons, list.mem_cons_iff, quotient.eq] at he ⊢, rcases he with ((he|he)|he), { exact or.inl rfl }, { exact or.inr (start_mem_support _) }, { exact or.inr (mem_support_of_mem_edges _ he), } end lemma edges_nodup_of_support_nodup {u v : V} {p : G.walk u v} (h : p.support.nodup) : p.edges.nodup := begin induction p, { simp, }, { simp only [edges_cons, support_cons, list.nodup_cons] at h ⊢, exact ⟨λ h', h.1 (mem_support_of_mem_edges p_p h'), p_ih h.2⟩, } end /-- A *trail* is a walk with no repeating edges. -/ structure is_trail {u v : V} (p : G.walk u v) : Prop := (edges_nodup : p.edges.nodup) /-- A *path* is a walk with no repeating vertices. Use `simple_graph.walk.is_path.mk'` for a simpler constructor. -/ structure is_path {u v : V} (p : G.walk u v) extends to_trail : is_trail p : Prop := (support_nodup : p.support.nodup) /-- A *circuit* at `u : V` is a nonempty trail beginning and ending at `u`. -/ structure is_circuit {u : V} (p : G.walk u u) extends to_trail : is_trail p : Prop := (ne_nil : p ≠ nil) /-- A *cycle* at `u : V` is a circuit at `u` whose only repeating vertex is `u` (which appears exactly twice). -/ structure is_cycle [decidable_eq V] {u : V} (p : G.walk u u) extends to_circuit : is_circuit p : Prop := (support_nodup : p.support.tail.nodup) lemma is_trail_def {u v : V} (p : G.walk u v) : p.is_trail ↔ p.edges.nodup := ⟨is_trail.edges_nodup, λ h, ⟨h⟩⟩ lemma is_path.mk' {u v : V} {p : G.walk u v} (h : p.support.nodup) : is_path p := ⟨⟨edges_nodup_of_support_nodup h⟩, h⟩ lemma is_path_def {u v : V} (p : G.walk u v) : p.is_path ↔ p.support.nodup := ⟨is_path.support_nodup, is_path.mk'⟩ lemma is_cycle_def [decidable_eq V] {u : V} (p : G.walk u u) : p.is_cycle ↔ is_trail p ∧ p ≠ nil ∧ p.support.tail.nodup := iff.intro (λ h, ⟨h.1.1, h.1.2, h.2⟩) (λ h, ⟨⟨h.1, h.2.1⟩, h.2.2⟩) @[simp] lemma is_trail.nil {u : V} : (nil : G.walk u u).is_trail := ⟨by simp [edges]⟩ lemma is_trail.of_cons {u v w : V} {h : G.adj u v} {p : G.walk v w} : (cons h p).is_trail → p.is_trail := by simp [is_trail_def] @[simp] lemma cons_is_trail_iff {u v w : V} (h : G.adj u v) (p : G.walk v w) : (cons h p).is_trail ↔ p.is_trail ∧ ⟦(u, v)⟧ ∉ p.edges := by simp [is_trail_def, and_comm] lemma is_trail.reverse {u v : V} (p : G.walk u v) (h : p.is_trail) : p.reverse.is_trail := by simpa [is_trail_def] using h @[simp] lemma reverse_is_trail_iff {u v : V} (p : G.walk u v) : p.reverse.is_trail ↔ p.is_trail := by split; { intro h, convert h.reverse _, try { rw reverse_reverse } } lemma is_trail.of_append_left {u v w : V} {p : G.walk u v} {q : G.walk v w} (h : (p.append q).is_trail) : p.is_trail := by { rw [is_trail_def, edges_append, list.nodup_append] at h, exact ⟨h.1⟩ } lemma is_trail.of_append_right {u v w : V} {p : G.walk u v} {q : G.walk v w} (h : (p.append q).is_trail) : q.is_trail := by { rw [is_trail_def, edges_append, list.nodup_append] at h, exact ⟨h.2.1⟩ } lemma is_trail.count_edges_le_one [decidable_eq V] {u v : V} {p : G.walk u v} (h : p.is_trail) (e : sym2 V) : p.edges.count e ≤ 1 := list.nodup_iff_count_le_one.mp h.edges_nodup e lemma is_trail.count_edges_eq_one [decidable_eq V] {u v : V} {p : G.walk u v} (h : p.is_trail) {e : sym2 V} (he : e ∈ p.edges) : p.edges.count e = 1 := list.count_eq_one_of_mem h.edges_nodup he @[simp] lemma is_path.nil {u : V} : (nil : G.walk u u).is_path := by { fsplit; simp } lemma is_path.of_cons {u v w : V} {h : G.adj u v} {p : G.walk v w} : (cons h p).is_path → p.is_path := by simp [is_path_def] @[simp] lemma cons_is_path_iff {u v w : V} (h : G.adj u v) (p : G.walk v w) : (cons h p).is_path ↔ p.is_path ∧ u ∉ p.support := by split; simp [is_path_def] { contextual := tt } lemma is_path.reverse {u v : V} {p : G.walk u v} (h : p.is_path) : p.reverse.is_path := by simpa [is_path_def] using h @[simp] lemma is_path_reverse_iff {u v : V} (p : G.walk u v) : p.reverse.is_path ↔ p.is_path := by split; intro h; convert h.reverse; simp lemma is_path.of_append_left {u v w : V} {p : G.walk u v} {q : G.walk v w} : (p.append q).is_path → p.is_path := by { simp only [is_path_def, support_append], exact list.nodup_of_nodup_append_left } lemma is_path.of_append_right {u v w : V} {p : G.walk u v} {q : G.walk v w} (h : (p.append q).is_path) : q.is_path := begin rw ←is_path_reverse_iff at h ⊢, rw reverse_append at h, apply h.of_append_left, end end walk end simple_graph
de0393b2e5d9e5f93c479c32316298db47e0f311
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/string/basic_auto.lean
3062f32e797af4288aacaf96b33a96ed1dd2019f
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
2,604
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Supplementary theorems about the `string` type. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.list.basic import Mathlib.data.char import Mathlib.PostPort namespace Mathlib namespace string def ltb : iterator → iterator → Bool := sorry protected instance has_lt' : HasLess string := { Less := fun (s₁ s₂ : string) => ↥(ltb (mk_iterator s₁) (mk_iterator s₂)) } protected instance decidable_lt : DecidableRel Less := fun (a b : string) => bool.decidable_eq (ltb (mk_iterator a) (mk_iterator b)) tt @[simp] theorem lt_iff_to_list_lt {s₁ : string} {s₂ : string} : s₁ < s₂ ↔ to_list s₁ < to_list s₂ := sorry protected instance has_le : HasLessEq string := { LessEq := fun (s₁ s₂ : string) => ¬s₂ < s₁ } protected instance decidable_le : DecidableRel LessEq := fun (a b : string) => ne.decidable (ltb (mk_iterator b) (mk_iterator a)) tt @[simp] theorem le_iff_to_list_le {s₁ : string} {s₂ : string} : s₁ ≤ s₂ ↔ to_list s₁ ≤ to_list s₂ := iff.trans (not_congr lt_iff_to_list_lt) not_lt theorem to_list_inj {s₁ : string} {s₂ : string} : to_list s₁ = to_list s₂ ↔ s₁ = s₂ := sorry theorem nil_as_string_eq_empty : list.as_string [] = empty := rfl @[simp] theorem to_list_empty : to_list empty = [] := rfl theorem as_string_inv_to_list (s : string) : list.as_string (to_list s) = s := string_imp.cases_on s fun (s : List char) => Eq.refl (list.as_string (to_list (string_imp.mk s))) @[simp] theorem to_list_singleton (c : char) : to_list (singleton c) = [c] := rfl theorem to_list_nonempty {s : string} (h : s ≠ empty) : to_list s = head s :: to_list (popn s 1) := sorry @[simp] theorem head_empty : head empty = Inhabited.default := rfl @[simp] theorem popn_empty {n : ℕ} : popn empty n = empty := sorry protected instance linear_order : linear_order string := linear_order.mk LessEq Less sorry sorry sorry sorry string.decidable_le (fun (a b : string) => string.has_decidable_eq a b) fun (a b : string) => string.decidable_lt a b end string theorem list.to_list_inv_as_string (l : List char) : string.to_list (list.as_string l) = l := sorry @[simp] theorem list.as_string_inj {l : List char} {l' : List char} : list.as_string l = list.as_string l' ↔ l = l' := sorry theorem list.as_string_eq {l : List char} {s : string} : list.as_string l = s ↔ l = string.to_list s := sorry end Mathlib
503fe3fda417cc9f9d60aa4428e0f3529008501b
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/geometry/euclidean/circumcenter.lean
cfc8ffd975221819015d8f332a4842da29fd53b8
[ "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
40,715
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 geometry.euclidean.basic import linear_algebra.affine_space.finite_dimensional import tactic.derive_fintype /-! # Circumcenter and circumradius This file proves some lemmas on points equidistant from a set of points, and defines the circumradius and circumcenter of a simplex. There are also some definitions for use in calculations where it is convenient to work with affine combinations of vertices together with the circumcenter. ## Main definitions * `circumcenter` and `circumradius` are the circumcenter and circumradius of a simplex. ## References * https://en.wikipedia.org/wiki/Circumscribed_circle -/ noncomputable theory open_locale big_operators open_locale classical open_locale real_inner_product_space namespace euclidean_geometry variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V open affine_subspace /-- `p` is equidistant from two points in `s` if and only if its `orthogonal_projection` is. -/ lemma dist_eq_iff_dist_orthogonal_projection_eq {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p1 p2 : P} (p3 : P) (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) : dist p1 p3 = dist p2 p3 ↔ dist p1 (orthogonal_projection s p3) = dist p2 (orthogonal_projection s p3) := begin rw [←mul_self_inj_of_nonneg dist_nonneg dist_nonneg, ←mul_self_inj_of_nonneg dist_nonneg dist_nonneg, dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq p3 hp1, dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq p3 hp2], simp end /-- `p` is equidistant from a set of points in `s` if and only if its `orthogonal_projection` is. -/ lemma dist_set_eq_iff_dist_orthogonal_projection_eq {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {ps : set P} (hps : ps ⊆ s) (p : P) : set.pairwise ps (λ p1 p2, dist p1 p = dist p2 p) ↔ (set.pairwise ps (λ p1 p2, dist p1 (orthogonal_projection s p) = dist p2 (orthogonal_projection s p))) := ⟨λ h p1 hp1 p2 hp2 hne, (dist_eq_iff_dist_orthogonal_projection_eq p (hps hp1) (hps hp2)).1 (h hp1 hp2 hne), λ h p1 hp1 p2 hp2 hne, (dist_eq_iff_dist_orthogonal_projection_eq p (hps hp1) (hps hp2)).2 (h hp1 hp2 hne)⟩ /-- There exists `r` such that `p` has distance `r` from all the points of a set of points in `s` if and only if there exists (possibly different) `r` such that its `orthogonal_projection` has that distance from all the points in that set. -/ lemma exists_dist_eq_iff_exists_dist_orthogonal_projection_eq {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {ps : set P} (hps : ps ⊆ s) (p : P) : (∃ r, ∀ p1 ∈ ps, dist p1 p = r) ↔ ∃ r, ∀ p1 ∈ ps, dist p1 ↑(orthogonal_projection s p) = r := begin have h := dist_set_eq_iff_dist_orthogonal_projection_eq hps p, simp_rw set.pairwise_eq_iff_exists_eq at h, exact h end /-- The induction step for the existence and uniqueness of the circumcenter. Given a nonempty set of points in a nonempty affine subspace whose direction is complete, such that there is a unique (circumcenter, circumradius) pair for those points in that subspace, and a point `p` not in that subspace, there is a unique (circumcenter, circumradius) pair for the set with `p` added, in the span of the subspace with `p` added. -/ lemma exists_unique_dist_eq_of_insert {s : affine_subspace ℝ P} [complete_space s.direction] {ps : set P} (hnps : ps.nonempty) {p : P} (hps : ps ⊆ s) (hp : p ∉ s) (hu : ∃! cs : sphere P, cs.center ∈ s ∧ ps ⊆ (cs : set P)) : ∃! cs₂ : sphere P, cs₂.center ∈ affine_span ℝ (insert p (s : set P)) ∧ (insert p ps) ⊆ (cs₂ : set P) := begin haveI : nonempty s := set.nonempty.to_subtype (hnps.mono hps), rcases hu with ⟨⟨cc, cr⟩, ⟨hcc, hcr⟩, hcccru⟩, simp only at hcc hcr hcccru, let x := dist cc (orthogonal_projection s p), let y := dist p (orthogonal_projection s p), have hy0 : y ≠ 0 := dist_orthogonal_projection_ne_zero_of_not_mem hp, let ycc₂ := (x * x + y * y - cr * cr) / (2 * y), let cc₂ := (ycc₂ / y) • (p -ᵥ orthogonal_projection s p : V) +ᵥ cc, let cr₂ := real.sqrt (cr * cr + ycc₂ * ycc₂), use ⟨cc₂, cr₂⟩, simp only, have hpo : p = (1 : ℝ) • (p -ᵥ orthogonal_projection s p : V) +ᵥ orthogonal_projection s p, { simp }, split, { split, { refine vadd_mem_of_mem_direction _ (mem_affine_span ℝ (set.mem_insert_of_mem _ hcc)), rw direction_affine_span, exact submodule.smul_mem _ _ (vsub_mem_vector_span ℝ (set.mem_insert _ _) (set.mem_insert_of_mem _ (orthogonal_projection_mem _))) }, { intros p1 hp1, rw [sphere.mem_coe, mem_sphere, ←mul_self_inj_of_nonneg dist_nonneg (real.sqrt_nonneg _), real.mul_self_sqrt (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _))], cases hp1, { rw hp1, rw [hpo, dist_sq_smul_orthogonal_vadd_smul_orthogonal_vadd (orthogonal_projection_mem p) hcc _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s p), ←dist_eq_norm_vsub V p, dist_comm _ cc], field_simp [hy0], ring }, { rw [dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq _ (hps hp1), orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ hcc, subtype.coe_mk, dist_of_mem_subset_mk_sphere hp1 hcr, dist_eq_norm_vsub V cc₂ cc, vadd_vsub, norm_smul, ←dist_eq_norm_vsub V, real.norm_eq_abs, abs_div, abs_of_nonneg dist_nonneg, div_mul_cancel _ hy0, abs_mul_abs_self] } } }, { rintros ⟨cc₃, cr₃⟩ ⟨hcc₃, hcr₃⟩, simp only at hcc₃ hcr₃, obtain ⟨t₃, cc₃', hcc₃', hcc₃''⟩ : ∃ (r : ℝ) (p0 : P) (hp0 : p0 ∈ s), cc₃ = r • (p -ᵥ ↑((orthogonal_projection s) p)) +ᵥ p0, { rwa mem_affine_span_insert_iff (orthogonal_projection_mem p) at hcc₃ }, have hcr₃' : ∃ r, ∀ p1 ∈ ps, dist p1 cc₃ = r := ⟨cr₃, λ p1 hp1, dist_of_mem_subset_mk_sphere (set.mem_insert_of_mem _ hp1) hcr₃⟩, rw [exists_dist_eq_iff_exists_dist_orthogonal_projection_eq hps cc₃, hcc₃'', orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ hcc₃'] at hcr₃', cases hcr₃' with cr₃' hcr₃', have hu := hcccru ⟨cc₃', cr₃'⟩, simp only at hu, replace hu := hu ⟨hcc₃', hcr₃'⟩, cases hu with hucc hucr, substs hucc hucr, have hcr₃val : cr₃ = real.sqrt (cr₃' * cr₃' + (t₃ * y) * (t₃ * y)), { cases hnps with p0 hp0, have h' : ↑(⟨cc₃', hcc₃'⟩ : s) = cc₃' := rfl, rw [←dist_of_mem_subset_mk_sphere (set.mem_insert_of_mem _ hp0) hcr₃, hcc₃'', ←mul_self_inj_of_nonneg dist_nonneg (real.sqrt_nonneg _), real.mul_self_sqrt (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _)), dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq _ (hps hp0), orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ hcc₃', h', dist_of_mem_subset_mk_sphere hp0 hcr, dist_eq_norm_vsub V _ cc₃', vadd_vsub, norm_smul, ←dist_eq_norm_vsub V p, real.norm_eq_abs, ←mul_assoc, mul_comm _ (|t₃|), ←mul_assoc, abs_mul_abs_self], ring }, replace hcr₃ := dist_of_mem_subset_mk_sphere (set.mem_insert _ _) hcr₃, rw [hpo, hcc₃'', hcr₃val, ←mul_self_inj_of_nonneg dist_nonneg (real.sqrt_nonneg _), dist_sq_smul_orthogonal_vadd_smul_orthogonal_vadd (orthogonal_projection_mem p) hcc₃' _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s p), dist_comm, ←dist_eq_norm_vsub V p, real.mul_self_sqrt (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _))] at hcr₃, change x * x + _ * (y * y) = _ at hcr₃, rw [(show x * x + (1 - t₃) * (1 - t₃) * (y * y) = x * x + y * y - 2 * y * (t₃ * y) + t₃ * y * (t₃ * y), by ring), add_left_inj] at hcr₃, have ht₃ : t₃ = ycc₂ / y, { field_simp [←hcr₃, hy0], ring }, subst ht₃, change cc₃ = cc₂ at hcc₃'', congr', rw hcr₃val, congr' 2, field_simp [hy0], ring } end /-- Given a finite nonempty affinely independent family of points, there is a unique (circumcenter, circumradius) pair for those points in the affine subspace they span. -/ lemma _root_.affine_independent.exists_unique_dist_eq {ι : Type*} [hne : nonempty ι] [fintype ι] {p : ι → P} (ha : affine_independent ℝ p) : ∃! cs : sphere P, cs.center ∈ affine_span ℝ (set.range p) ∧ set.range p ⊆ (cs : set P) := begin unfreezingI { induction hn : fintype.card ι with m hm generalizing ι }, { exfalso, have h := fintype.card_pos_iff.2 hne, rw hn at h, exact lt_irrefl 0 h }, { cases m, { rw fintype.card_eq_one_iff at hn, cases hn with i hi, haveI : unique ι := ⟨⟨i⟩, hi⟩, use ⟨p i, 0⟩, simp only [set.range_unique, affine_subspace.mem_affine_span_singleton], split, { simp_rw [hi default, set.singleton_subset_iff, sphere.mem_coe, mem_sphere, dist_self], exact ⟨rfl, rfl⟩ }, { rintros ⟨cc, cr⟩, simp only, rintros ⟨rfl, hdist⟩, simp_rw [set.singleton_subset_iff, sphere.mem_coe, mem_sphere, dist_self] at hdist, rw [hi default, hdist], exact ⟨rfl, rfl⟩ } }, { have i := hne.some, let ι2 := {x // x ≠ i}, have hc : fintype.card ι2 = m + 1, { rw fintype.card_of_subtype (finset.univ.filter (λ x, x ≠ i)), { rw finset.filter_not, simp_rw eq_comm, rw [finset.filter_eq, if_pos (finset.mem_univ _), finset.card_sdiff (finset.subset_univ _), finset.card_singleton, finset.card_univ, hn], simp }, { simp } }, haveI : nonempty ι2 := fintype.card_pos_iff.1 (hc.symm ▸ nat.zero_lt_succ _), have ha2 : affine_independent ℝ (λ i2 : ι2, p i2) := ha.subtype _, replace hm := hm ha2 hc, have hr : set.range p = insert (p i) (set.range (λ i2 : ι2, p i2)), { change _ = insert _ (set.range (λ i2 : {x | x ≠ i}, p i2)), rw [←set.image_eq_range, ←set.image_univ, ←set.image_insert_eq], congr' with j, simp [classical.em] }, rw [hr, ←affine_span_insert_affine_span], refine exists_unique_dist_eq_of_insert (set.range_nonempty _) (subset_span_points ℝ _) _ hm, convert ha.not_mem_affine_span_diff i set.univ, change set.range (λ i2 : {x | x ≠ i}, p i2) = _, rw ←set.image_eq_range, congr' with j, simp, refl } } end end euclidean_geometry namespace affine namespace simplex open finset affine_subspace euclidean_geometry variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V /-- The circumsphere of a simplex. -/ def circumsphere {n : ℕ} (s : simplex ℝ P n) : sphere P := s.independent.exists_unique_dist_eq.some /-- The property satisfied by the circumsphere. -/ lemma circumsphere_unique_dist_eq {n : ℕ} (s : simplex ℝ P n) : (s.circumsphere.center ∈ affine_span ℝ (set.range s.points) ∧ set.range s.points ⊆ s.circumsphere) ∧ (∀ cs : sphere P, (cs.center ∈ affine_span ℝ (set.range s.points) ∧ set.range s.points ⊆ cs → cs = s.circumsphere)) := s.independent.exists_unique_dist_eq.some_spec /-- The circumcenter of a simplex. -/ def circumcenter {n : ℕ} (s : simplex ℝ P n) : P := s.circumsphere.center /-- The circumradius of a simplex. -/ def circumradius {n : ℕ} (s : simplex ℝ P n) : ℝ := s.circumsphere.radius /-- The center of the circumsphere is the circumcenter. -/ @[simp] lemma circumsphere_center {n : ℕ} (s : simplex ℝ P n) : s.circumsphere.center = s.circumcenter := rfl /-- The radius of the circumsphere is the circumradius. -/ @[simp] lemma circumsphere_radius {n : ℕ} (s : simplex ℝ P n) : s.circumsphere.radius = s.circumradius := rfl /-- The circumcenter lies in the affine span. -/ lemma circumcenter_mem_affine_span {n : ℕ} (s : simplex ℝ P n) : s.circumcenter ∈ affine_span ℝ (set.range s.points) := s.circumsphere_unique_dist_eq.1.1 /-- All points have distance from the circumcenter equal to the circumradius. -/ @[simp] lemma dist_circumcenter_eq_circumradius {n : ℕ} (s : simplex ℝ P n) (i : fin (n + 1)) : dist (s.points i) s.circumcenter = s.circumradius := dist_of_mem_subset_sphere (set.mem_range_self _) s.circumsphere_unique_dist_eq.1.2 /-- All points lie in the circumsphere. -/ lemma mem_circumsphere {n : ℕ} (s : simplex ℝ P n) (i : fin (n + 1)) : s.points i ∈ s.circumsphere := s.dist_circumcenter_eq_circumradius i /-- All points have distance to the circumcenter equal to the circumradius. -/ @[simp] lemma dist_circumcenter_eq_circumradius' {n : ℕ} (s : simplex ℝ P n) : ∀ i, dist s.circumcenter (s.points i) = s.circumradius := begin intro i, rw dist_comm, exact dist_circumcenter_eq_circumradius _ _ end /-- Given a point in the affine span from which all the points are equidistant, that point is the circumcenter. -/ lemma eq_circumcenter_of_dist_eq {n : ℕ} (s : simplex ℝ P n) {p : P} (hp : p ∈ affine_span ℝ (set.range s.points)) {r : ℝ} (hr : ∀ i, dist (s.points i) p = r) : p = s.circumcenter := begin have h := s.circumsphere_unique_dist_eq.2 ⟨p, r⟩, simp only [hp, hr, forall_const, eq_self_iff_true, subset_sphere, sphere.ext_iff, set.forall_range_iff, mem_sphere, true_and] at h, exact h.1 end /-- Given a point in the affine span from which all the points are equidistant, that distance is the circumradius. -/ lemma eq_circumradius_of_dist_eq {n : ℕ} (s : simplex ℝ P n) {p : P} (hp : p ∈ affine_span ℝ (set.range s.points)) {r : ℝ} (hr : ∀ i, dist (s.points i) p = r) : r = s.circumradius := begin have h := s.circumsphere_unique_dist_eq.2 ⟨p, r⟩, simp only [hp, hr, forall_const, eq_self_iff_true, subset_sphere, sphere.ext_iff, set.forall_range_iff, mem_sphere, true_and] at h, exact h.2 end /-- The circumradius is non-negative. -/ lemma circumradius_nonneg {n : ℕ} (s : simplex ℝ P n) : 0 ≤ s.circumradius := s.dist_circumcenter_eq_circumradius 0 ▸ dist_nonneg /-- The circumradius of a simplex with at least two points is positive. -/ lemma circumradius_pos {n : ℕ} (s : simplex ℝ P (n + 1)) : 0 < s.circumradius := begin refine lt_of_le_of_ne s.circumradius_nonneg _, intro h, have hr := s.dist_circumcenter_eq_circumradius, simp_rw [←h, dist_eq_zero] at hr, have h01 := s.independent.injective.ne (dec_trivial : (0 : fin (n + 2)) ≠ 1), simpa [hr] using h01 end /-- The circumcenter of a 0-simplex equals its unique point. -/ lemma circumcenter_eq_point (s : simplex ℝ P 0) (i : fin 1) : s.circumcenter = s.points i := begin have h := s.circumcenter_mem_affine_span, rw [set.range_unique, mem_affine_span_singleton] at h, rw h, congr end /-- The circumcenter of a 1-simplex equals its centroid. -/ lemma circumcenter_eq_centroid (s : simplex ℝ P 1) : s.circumcenter = finset.univ.centroid ℝ s.points := begin have hr : set.pairwise set.univ (λ i j : fin 2, dist (s.points i) (finset.univ.centroid ℝ s.points) = dist (s.points j) (finset.univ.centroid ℝ s.points)), { intros i hi j hj hij, rw [finset.centroid_pair_fin, dist_eq_norm_vsub V (s.points i), dist_eq_norm_vsub V (s.points j), vsub_vadd_eq_vsub_sub, vsub_vadd_eq_vsub_sub, ←one_smul ℝ (s.points i -ᵥ s.points 0), ←one_smul ℝ (s.points j -ᵥ s.points 0)], fin_cases i; fin_cases j; simp [-one_smul, ←sub_smul]; norm_num }, rw set.pairwise_eq_iff_exists_eq at hr, cases hr with r hr, exact (s.eq_circumcenter_of_dist_eq (centroid_mem_affine_span_of_card_eq_add_one ℝ _ (finset.card_fin 2)) (λ i, hr i (set.mem_univ _))).symm end local attribute [instance] affine_subspace.to_add_torsor /-- The orthogonal projection of a point `p` onto the hyperplane spanned by the simplex's points. -/ def orthogonal_projection_span {n : ℕ} (s : simplex ℝ P n) : P →ᵃ[ℝ] affine_span ℝ (set.range s.points) := orthogonal_projection (affine_span ℝ (set.range s.points)) /-- 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 {n : ℕ} (s : simplex ℝ P n) {p1 : P} (p2 : P) (r : ℝ) (hp : p1 ∈ affine_span ℝ (set.range s.points)) : s.orthogonal_projection_span (r • (p2 -ᵥ s.orthogonal_projection_span p2 : V) +ᵥ p1) = ⟨p1, hp⟩ := orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ _ lemma coe_orthogonal_projection_vadd_smul_vsub_orthogonal_projection {n : ℕ} {r₁ : ℝ} (s : simplex ℝ P n) {p p₁o : P} (hp₁o : p₁o ∈ affine_span ℝ (set.range s.points)) : ↑(s.orthogonal_projection_span (r₁ • (p -ᵥ ↑(s.orthogonal_projection_span p)) +ᵥ p₁o)) = p₁o := congr_arg coe (orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ _ hp₁o) lemma dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq {n : ℕ} (s : simplex ℝ P n) {p1 : P} (p2 : P) (hp1 : p1 ∈ affine_span ℝ (set.range s.points)) : dist p1 p2 * dist p1 p2 = dist p1 (s.orthogonal_projection_span p2) * dist p1 (s.orthogonal_projection_span p2) + dist p2 (s.orthogonal_projection_span p2) * dist p2 (s.orthogonal_projection_span 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 (s.orthogonal_projection_span 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 _ p2), end lemma dist_circumcenter_sq_eq_sq_sub_circumradius {n : ℕ} {r : ℝ} (s : simplex ℝ P n) {p₁ : P} (h₁ : ∀ (i : fin (n + 1)), dist (s.points i) p₁ = r) (h₁' : ↑((s.orthogonal_projection_span) p₁) = s.circumcenter) (h : s.points 0 ∈ affine_span ℝ (set.range s.points)) : dist p₁ s.circumcenter * dist p₁ s.circumcenter = r * r - s.circumradius * s.circumradius := begin rw [dist_comm, ←h₁ 0, s.dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq p₁ h], simp only [h₁', dist_comm p₁, add_sub_cancel', simplex.dist_circumcenter_eq_circumradius], end /-- If there exists a distance that a point has from all vertices of a simplex, the orthogonal projection of that point onto the subspace spanned by that simplex is its circumcenter. -/ lemma orthogonal_projection_eq_circumcenter_of_exists_dist_eq {n : ℕ} (s : simplex ℝ P n) {p : P} (hr : ∃ r, ∀ i, dist (s.points i) p = r) : ↑(s.orthogonal_projection_span p) = s.circumcenter := begin change ∃ r : ℝ, ∀ i, (λ x, dist x p = r) (s.points i) at hr, conv at hr { congr, funext, rw ←set.forall_range_iff }, rw exists_dist_eq_iff_exists_dist_orthogonal_projection_eq (subset_affine_span ℝ _) p at hr, cases hr with r hr, exact s.eq_circumcenter_of_dist_eq (orthogonal_projection_mem p) (λ i, hr _ (set.mem_range_self i)), end /-- If a point has the same distance from all vertices of a simplex, the orthogonal projection of that point onto the subspace spanned by that simplex is its circumcenter. -/ lemma orthogonal_projection_eq_circumcenter_of_dist_eq {n : ℕ} (s : simplex ℝ P n) {p : P} {r : ℝ} (hr : ∀ i, dist (s.points i) p = r) : ↑(s.orthogonal_projection_span p) = s.circumcenter := s.orthogonal_projection_eq_circumcenter_of_exists_dist_eq ⟨r, hr⟩ /-- The orthogonal projection of the circumcenter onto a face is the circumcenter of that face. -/ lemma orthogonal_projection_circumcenter {n : ℕ} (s : simplex ℝ P n) {fs : finset (fin (n + 1))} {m : ℕ} (h : fs.card = m + 1) : ↑((s.face h).orthogonal_projection_span s.circumcenter) = (s.face h).circumcenter := begin have hr : ∃ r, ∀ i, dist ((s.face h).points i) s.circumcenter = r, { use s.circumradius, simp [face_points] }, exact orthogonal_projection_eq_circumcenter_of_exists_dist_eq _ hr end /-- Two simplices with the same points have the same circumcenter. -/ lemma circumcenter_eq_of_range_eq {n : ℕ} {s₁ s₂ : simplex ℝ P n} (h : set.range s₁.points = set.range s₂.points) : s₁.circumcenter = s₂.circumcenter := begin have hs : s₁.circumcenter ∈ affine_span ℝ (set.range s₂.points) := h ▸ s₁.circumcenter_mem_affine_span, have hr : ∀ i, dist (s₂.points i) s₁.circumcenter = s₁.circumradius, { intro i, have hi : s₂.points i ∈ set.range s₂.points := set.mem_range_self _, rw [←h, set.mem_range] at hi, rcases hi with ⟨j, hj⟩, rw [←hj, s₁.dist_circumcenter_eq_circumradius j] }, exact s₂.eq_circumcenter_of_dist_eq hs hr end omit V /-- An index type for the vertices of a simplex plus its circumcenter. This is for use in calculations where it is convenient to work with affine combinations of vertices together with the circumcenter. (An equivalent form sometimes used in the literature is placing the circumcenter at the origin and working with vectors for the vertices.) -/ @[derive fintype] inductive points_with_circumcenter_index (n : ℕ) | point_index : fin (n + 1) → points_with_circumcenter_index | circumcenter_index : points_with_circumcenter_index open points_with_circumcenter_index instance points_with_circumcenter_index_inhabited (n : ℕ) : inhabited (points_with_circumcenter_index n) := ⟨circumcenter_index⟩ /-- `point_index` as an embedding. -/ def point_index_embedding (n : ℕ) : fin (n + 1) ↪ points_with_circumcenter_index n := ⟨λ i, point_index i, λ _ _ h, by injection h⟩ /-- The sum of a function over `points_with_circumcenter_index`. -/ lemma sum_points_with_circumcenter {α : Type*} [add_comm_monoid α] {n : ℕ} (f : points_with_circumcenter_index n → α) : ∑ i, f i = (∑ (i : fin (n + 1)), f (point_index i)) + f circumcenter_index := begin have h : univ = insert circumcenter_index (univ.map (point_index_embedding n)), { ext x, refine ⟨λ h, _, λ _, mem_univ _⟩, cases x with i, { exact mem_insert_of_mem (mem_map_of_mem _ (mem_univ i)) }, { exact mem_insert_self _ _ } }, change _ = ∑ i, f (point_index_embedding n i) + _, rw [add_comm, h, ←sum_map, sum_insert], simp_rw [finset.mem_map, not_exists], intros x hx h, injection h end include V /-- The vertices of a simplex plus its circumcenter. -/ def points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) : points_with_circumcenter_index n → P | (point_index i) := s.points i | circumcenter_index := s.circumcenter /-- `points_with_circumcenter`, applied to a `point_index` value, equals `points` applied to that value. -/ @[simp] lemma points_with_circumcenter_point {n : ℕ} (s : simplex ℝ P n) (i : fin (n + 1)) : s.points_with_circumcenter (point_index i) = s.points i := rfl /-- `points_with_circumcenter`, applied to `circumcenter_index`, equals the circumcenter. -/ @[simp] lemma points_with_circumcenter_eq_circumcenter {n : ℕ} (s : simplex ℝ P n) : s.points_with_circumcenter circumcenter_index = s.circumcenter := rfl omit V /-- The weights for a single vertex of a simplex, in terms of `points_with_circumcenter`. -/ def point_weights_with_circumcenter {n : ℕ} (i : fin (n + 1)) : points_with_circumcenter_index n → ℝ | (point_index j) := if j = i then 1 else 0 | circumcenter_index := 0 /-- `point_weights_with_circumcenter` sums to 1. -/ @[simp] lemma sum_point_weights_with_circumcenter {n : ℕ} (i : fin (n + 1)) : ∑ j, point_weights_with_circumcenter i j = 1 := begin convert sum_ite_eq' univ (point_index i) (function.const _ (1 : ℝ)), { ext j, cases j ; simp [point_weights_with_circumcenter] }, { simp } end include V /-- A single vertex, in terms of `points_with_circumcenter`. -/ lemma point_eq_affine_combination_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) (i : fin (n + 1)) : s.points i = (univ : finset (points_with_circumcenter_index n)).affine_combination s.points_with_circumcenter (point_weights_with_circumcenter i) := begin rw ←points_with_circumcenter_point, symmetry, refine affine_combination_of_eq_one_of_eq_zero _ _ _ (mem_univ _) (by simp [point_weights_with_circumcenter]) _, intros i hi hn, cases i, { have h : i_1 ≠ i := λ h, hn (h ▸ rfl), simp [point_weights_with_circumcenter, h] }, { refl } end omit V /-- The weights for the centroid of some vertices of a simplex, in terms of `points_with_circumcenter`. -/ def centroid_weights_with_circumcenter {n : ℕ} (fs : finset (fin (n + 1))) : points_with_circumcenter_index n → ℝ | (point_index i) := if i ∈ fs then ((card fs : ℝ) ⁻¹) else 0 | circumcenter_index := 0 /-- `centroid_weights_with_circumcenter` sums to 1, if the `finset` is nonempty. -/ @[simp] lemma sum_centroid_weights_with_circumcenter {n : ℕ} {fs : finset (fin (n + 1))} (h : fs.nonempty) : ∑ i, centroid_weights_with_circumcenter fs i = 1 := begin simp_rw [sum_points_with_circumcenter, centroid_weights_with_circumcenter, add_zero, ←fs.sum_centroid_weights_eq_one_of_nonempty ℝ h, set.sum_indicator_subset _ fs.subset_univ], rcongr end include V /-- The centroid of some vertices of a simplex, in terms of `points_with_circumcenter`. -/ lemma centroid_eq_affine_combination_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) (fs : finset (fin (n + 1))) : fs.centroid ℝ s.points = (univ : finset (points_with_circumcenter_index n)).affine_combination s.points_with_circumcenter (centroid_weights_with_circumcenter fs) := begin simp_rw [centroid_def, affine_combination_apply, weighted_vsub_of_point_apply, sum_points_with_circumcenter, centroid_weights_with_circumcenter, points_with_circumcenter_point, zero_smul, add_zero, centroid_weights, set.sum_indicator_subset_of_eq_zero (function.const (fin (n + 1)) ((card fs : ℝ)⁻¹)) (λ i wi, wi • (s.points i -ᵥ classical.choice add_torsor.nonempty)) fs.subset_univ (λ i, zero_smul ℝ _), set.indicator_apply], congr, end omit V /-- The weights for the circumcenter of a simplex, in terms of `points_with_circumcenter`. -/ def circumcenter_weights_with_circumcenter (n : ℕ) : points_with_circumcenter_index n → ℝ | (point_index i) := 0 | circumcenter_index := 1 /-- `circumcenter_weights_with_circumcenter` sums to 1. -/ @[simp] lemma sum_circumcenter_weights_with_circumcenter (n : ℕ) : ∑ i, circumcenter_weights_with_circumcenter n i = 1 := begin convert sum_ite_eq' univ circumcenter_index (function.const _ (1 : ℝ)), { ext ⟨j⟩ ; simp [circumcenter_weights_with_circumcenter] }, { simp } end include V /-- The circumcenter of a simplex, in terms of `points_with_circumcenter`. -/ lemma circumcenter_eq_affine_combination_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) : s.circumcenter = (univ : finset (points_with_circumcenter_index n)).affine_combination s.points_with_circumcenter (circumcenter_weights_with_circumcenter n) := begin rw ←points_with_circumcenter_eq_circumcenter, symmetry, refine affine_combination_of_eq_one_of_eq_zero _ _ _ (mem_univ _) rfl _, rintros ⟨i⟩ hi hn ; tauto end omit V /-- The weights for the reflection of the circumcenter in an edge of a simplex. This definition is only valid with `i₁ ≠ i₂`. -/ def reflection_circumcenter_weights_with_circumcenter {n : ℕ} (i₁ i₂ : fin (n + 1)) : points_with_circumcenter_index n → ℝ | (point_index i) := if i = i₁ ∨ i = i₂ then 1 else 0 | circumcenter_index := -1 /-- `reflection_circumcenter_weights_with_circumcenter` sums to 1. -/ @[simp] lemma sum_reflection_circumcenter_weights_with_circumcenter {n : ℕ} {i₁ i₂ : fin (n + 1)} (h : i₁ ≠ i₂) : ∑ i, reflection_circumcenter_weights_with_circumcenter i₁ i₂ i = 1 := begin simp_rw [sum_points_with_circumcenter, reflection_circumcenter_weights_with_circumcenter, sum_ite, sum_const, filter_or, filter_eq'], rw card_union_eq, { simp }, { simpa only [if_true, mem_univ, disjoint_singleton] using h } end include V /-- The reflection of the circumcenter of a simplex in an edge, in terms of `points_with_circumcenter`. -/ lemma reflection_circumcenter_eq_affine_combination_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) {i₁ i₂ : fin (n + 1)} (h : i₁ ≠ i₂) : reflection (affine_span ℝ (s.points '' {i₁, i₂})) s.circumcenter = (univ : finset (points_with_circumcenter_index n)).affine_combination s.points_with_circumcenter (reflection_circumcenter_weights_with_circumcenter i₁ i₂) := begin have hc : card ({i₁, i₂} : finset (fin (n + 1))) = 2, { simp [h] }, -- Making the next line a separate definition helps the elaborator: set W : affine_subspace ℝ P := affine_span ℝ (s.points '' {i₁, i₂}) with W_def, have h_faces : ↑(orthogonal_projection W s.circumcenter) = ↑((s.face hc).orthogonal_projection_span s.circumcenter), { apply eq_orthogonal_projection_of_eq_subspace, simp }, rw [euclidean_geometry.reflection_apply, h_faces, s.orthogonal_projection_circumcenter hc, circumcenter_eq_centroid, s.face_centroid_eq_centroid hc, centroid_eq_affine_combination_of_points_with_circumcenter, circumcenter_eq_affine_combination_of_points_with_circumcenter, ←@vsub_eq_zero_iff_eq V, affine_combination_vsub, weighted_vsub_vadd_affine_combination, affine_combination_vsub, weighted_vsub_apply, sum_points_with_circumcenter], simp_rw [pi.sub_apply, pi.add_apply, pi.sub_apply, sub_smul, add_smul, sub_smul, centroid_weights_with_circumcenter, circumcenter_weights_with_circumcenter, reflection_circumcenter_weights_with_circumcenter, ite_smul, zero_smul, sub_zero, apply_ite2 (+), add_zero, ←add_smul, hc, zero_sub, neg_smul, sub_self, add_zero], convert sum_const_zero, norm_num end end simplex end affine namespace euclidean_geometry open affine affine_subspace finite_dimensional variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V /-- Given a nonempty affine subspace, whose direction is complete, that contains a set of points, those points are cospherical if and only if they are equidistant from some point in that subspace. -/ lemma cospherical_iff_exists_mem_of_complete {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) [nonempty s] [complete_space s.direction] : cospherical ps ↔ ∃ (center ∈ s) (radius : ℝ), ∀ p ∈ ps, dist p center = radius := begin split, { rintro ⟨c, hcr⟩, rw exists_dist_eq_iff_exists_dist_orthogonal_projection_eq h c at hcr, exact ⟨orthogonal_projection s c, orthogonal_projection_mem _, hcr⟩ }, { exact λ ⟨c, hc, hd⟩, ⟨c, hd⟩ } end /-- Given a nonempty affine subspace, whose direction is finite-dimensional, that contains a set of points, those points are cospherical if and only if they are equidistant from some point in that subspace. -/ lemma cospherical_iff_exists_mem_of_finite_dimensional {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) [nonempty s] [finite_dimensional ℝ s.direction] : cospherical ps ↔ ∃ (center ∈ s) (radius : ℝ), ∀ p ∈ ps, dist p center = radius := cospherical_iff_exists_mem_of_complete h /-- All n-simplices among cospherical points in an n-dimensional subspace have the same circumradius. -/ lemma exists_circumradius_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) [nonempty s] {n : ℕ} [finite_dimensional ℝ s.direction] (hd : finrank ℝ s.direction = n) (hc : cospherical ps) : ∃ r : ℝ, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumradius = r := begin rw cospherical_iff_exists_mem_of_finite_dimensional h at hc, rcases hc with ⟨c, hc, r, hcr⟩, use r, intros sx hsxps, have hsx : affine_span ℝ (set.range sx.points) = s, { refine sx.independent.affine_span_eq_of_le_of_card_eq_finrank_add_one (span_points_subset_coe_of_subset_coe (hsxps.trans h)) _, simp [hd] }, have hc : c ∈ affine_span ℝ (set.range sx.points) := hsx.symm ▸ hc, exact (sx.eq_circumradius_of_dist_eq hc (λ i, hcr (sx.points i) (hsxps (set.mem_range_self i)))).symm end /-- Two n-simplices among cospherical points in an n-dimensional subspace have the same circumradius. -/ lemma circumradius_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) [nonempty s] {n : ℕ} [finite_dimensional ℝ s.direction] (hd : finrank ℝ s.direction = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n} (hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) : sx₁.circumradius = sx₂.circumradius := begin rcases exists_circumradius_eq_of_cospherical_subset h hd hc with ⟨r, hr⟩, rw [hr sx₁ hsx₁, hr sx₂ hsx₂] end /-- All n-simplices among cospherical points in n-space have the same circumradius. -/ lemma exists_circumradius_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V] (hd : finrank ℝ V = n) (hc : cospherical ps) : ∃ r : ℝ, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumradius = r := begin haveI : nonempty (⊤ : affine_subspace ℝ P) := set.univ.nonempty, rw [←finrank_top, ←direction_top ℝ V P] at hd, refine exists_circumradius_eq_of_cospherical_subset _ hd hc, exact set.subset_univ _ end /-- Two n-simplices among cospherical points in n-space have the same circumradius. -/ lemma circumradius_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V] (hd : finrank ℝ V = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n} (hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) : sx₁.circumradius = sx₂.circumradius := begin rcases exists_circumradius_eq_of_cospherical hd hc with ⟨r, hr⟩, rw [hr sx₁ hsx₁, hr sx₂ hsx₂] end /-- All n-simplices among cospherical points in an n-dimensional subspace have the same circumcenter. -/ lemma exists_circumcenter_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) [nonempty s] {n : ℕ} [finite_dimensional ℝ s.direction] (hd : finrank ℝ s.direction = n) (hc : cospherical ps) : ∃ c : P, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumcenter = c := begin rw cospherical_iff_exists_mem_of_finite_dimensional h at hc, rcases hc with ⟨c, hc, r, hcr⟩, use c, intros sx hsxps, have hsx : affine_span ℝ (set.range sx.points) = s, { refine sx.independent.affine_span_eq_of_le_of_card_eq_finrank_add_one (span_points_subset_coe_of_subset_coe (hsxps.trans h)) _, simp [hd] }, have hc : c ∈ affine_span ℝ (set.range sx.points) := hsx.symm ▸ hc, exact (sx.eq_circumcenter_of_dist_eq hc (λ i, hcr (sx.points i) (hsxps (set.mem_range_self i)))).symm end /-- Two n-simplices among cospherical points in an n-dimensional subspace have the same circumcenter. -/ lemma circumcenter_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) [nonempty s] {n : ℕ} [finite_dimensional ℝ s.direction] (hd : finrank ℝ s.direction = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n} (hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) : sx₁.circumcenter = sx₂.circumcenter := begin rcases exists_circumcenter_eq_of_cospherical_subset h hd hc with ⟨r, hr⟩, rw [hr sx₁ hsx₁, hr sx₂ hsx₂] end /-- All n-simplices among cospherical points in n-space have the same circumcenter. -/ lemma exists_circumcenter_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V] (hd : finrank ℝ V = n) (hc : cospherical ps) : ∃ c : P, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumcenter = c := begin haveI : nonempty (⊤ : affine_subspace ℝ P) := set.univ.nonempty, rw [←finrank_top, ←direction_top ℝ V P] at hd, refine exists_circumcenter_eq_of_cospherical_subset _ hd hc, exact set.subset_univ _ end /-- Two n-simplices among cospherical points in n-space have the same circumcenter. -/ lemma circumcenter_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V] (hd : finrank ℝ V = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n} (hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) : sx₁.circumcenter = sx₂.circumcenter := begin rcases exists_circumcenter_eq_of_cospherical hd hc with ⟨r, hr⟩, rw [hr sx₁ hsx₁, hr sx₂ hsx₂] end /-- Suppose all distances from `p₁` and `p₂` to the points of a simplex are equal, and that `p₁` and `p₂` lie in the affine span of `p` with the vertices of that simplex. Then `p₁` and `p₂` are equal or reflections of each other in the affine span of the vertices of the simplex. -/ lemma eq_or_eq_reflection_of_dist_eq {n : ℕ} {s : simplex ℝ P n} {p p₁ p₂ : P} {r : ℝ} (hp₁ : p₁ ∈ affine_span ℝ (insert p (set.range s.points))) (hp₂ : p₂ ∈ affine_span ℝ (insert p (set.range s.points))) (h₁ : ∀ i, dist (s.points i) p₁ = r) (h₂ : ∀ i, dist (s.points i) p₂ = r) : p₁ = p₂ ∨ p₁ = reflection (affine_span ℝ (set.range s.points)) p₂ := begin let span_s := affine_span ℝ (set.range s.points), have h₁' := s.orthogonal_projection_eq_circumcenter_of_dist_eq h₁, have h₂' := s.orthogonal_projection_eq_circumcenter_of_dist_eq h₂, rw [←affine_span_insert_affine_span, mem_affine_span_insert_iff (orthogonal_projection_mem p)] at hp₁ hp₂, obtain ⟨r₁, p₁o, hp₁o, hp₁⟩ := hp₁, obtain ⟨r₂, p₂o, hp₂o, hp₂⟩ := hp₂, obtain rfl : ↑(s.orthogonal_projection_span p₁) = p₁o, { subst hp₁, exact s.coe_orthogonal_projection_vadd_smul_vsub_orthogonal_projection hp₁o }, rw h₁' at hp₁, obtain rfl : ↑(s.orthogonal_projection_span p₂) = p₂o, { subst hp₂, exact s.coe_orthogonal_projection_vadd_smul_vsub_orthogonal_projection hp₂o }, rw h₂' at hp₂, have h : s.points 0 ∈ span_s := mem_affine_span ℝ (set.mem_range_self _), have hd₁ : dist p₁ s.circumcenter * dist p₁ s.circumcenter = r * r - s.circumradius * s.circumradius := s.dist_circumcenter_sq_eq_sq_sub_circumradius h₁ h₁' h, have hd₂ : dist p₂ s.circumcenter * dist p₂ s.circumcenter = r * r - s.circumradius * s.circumradius := s.dist_circumcenter_sq_eq_sq_sub_circumradius h₂ h₂' h, rw [←hd₂, hp₁, hp₂, dist_eq_norm_vsub V _ s.circumcenter, dist_eq_norm_vsub V _ s.circumcenter, vadd_vsub, vadd_vsub, ←real_inner_self_eq_norm_mul_norm, ←real_inner_self_eq_norm_mul_norm, real_inner_smul_left, real_inner_smul_left, real_inner_smul_right, real_inner_smul_right, ←mul_assoc, ←mul_assoc] at hd₁, by_cases hp : p = s.orthogonal_projection_span p, { rw simplex.orthogonal_projection_span at hp, rw [hp₁, hp₂, ←hp], simp only [true_or, eq_self_iff_true, smul_zero, vsub_self] }, { have hz : ⟪p -ᵥ orthogonal_projection span_s p, p -ᵥ orthogonal_projection span_s p⟫ ≠ 0, by simpa only [ne.def, vsub_eq_zero_iff_eq, inner_self_eq_zero] using hp, rw [mul_left_inj' hz, mul_self_eq_mul_self_iff] at hd₁, rw [hp₁, hp₂], cases hd₁, { left, rw hd₁ }, { right, rw [hd₁, reflection_vadd_smul_vsub_orthogonal_projection p r₂ s.circumcenter_mem_affine_span, neg_smul] } } end end euclidean_geometry
9a50b77a461edf9fdfbeb16dc91a13bfd0129a10
968e2f50b755d3048175f176376eff7139e9df70
/examples/prop_logic_theory/unnamed_1876.lean
f954a00e3fbe234811faa793c04c01dd442072b5
[]
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
168
lean
variables s t : Prop -- BEGIN theorem or_of_or (h : s ∨ t) : t ∨ s := begin cases h with h₁ h₂, { exact or.inr h₁,}, { exact or.inl h₂, }, end -- END
b4414d1a59103287928561ba49d7554c156693e1
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/topology/category/Profinite/as_limit.lean
74bb0eca173966c1932e0f566bbe229013b9ee0a
[ "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,300
lean
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Calle Sönne, Adam Topaz -/ import topology.category.Profinite import topology.discrete_quotient /-! # Profinite sets as limits of finite sets. We show that any profinite set is isomorphic to the limit of its discrete (hence finite) quotients. ## Definitions There are a handful of definitions in this file, given `X : Profinite`: 1. `X.fintype_diagram` is the functor `discret_quotient X ⥤ Fintype` whose limit is isomorphic to `X` (the limit taking place in `Profinite` via `Fintype_to_Profinite`, see 2). 2. `X.diagram` is an abbreviation for `X.fintype_diagram ⋙ Fintype_to_Profinite`. 3. `X.as_limit_cone` is the cone over `X.diagram` whose cone point is `X`. 4. `X.iso_as_limit_cone_lift` is the isomorphism `X ≅ (Profinite.limit_cone X.diagram).X` induced by lifting `X.as_limit_cone`. 5. `X.as_limit_cone_iso` is the isomorphism `X.as_limit_cone ≅ (Profinite.limit_cone X.diagram)` induced by `X.iso_as_limit_cone_lift`. 6. `X.as_limit` is a term of type `is_limit X.as_limit_cone`. 7. `X.lim : category_theory.limits.limit_cone X.as_limit_cone` is a bundled combination of 3 and 6. -/ noncomputable theory open category_theory namespace Profinite universe u variables (X : Profinite.{u}) /-- The functor `discrete_quotient X ⥤ Fintype` whose limit is isomorphic to `X`. -/ def fintype_diagram : discrete_quotient X ⥤ Fintype := { obj := λ S, Fintype.of S, map := λ S T f, discrete_quotient.of_le f.le } /-- An abbreviation for `X.fintype_diagram ⋙ Fintype_to_Profinite`. -/ abbreviation diagram : discrete_quotient X ⥤ Profinite := X.fintype_diagram ⋙ Fintype.to_Profinite /-- A cone over `X.diagram` whose cone point is `X`. -/ def as_limit_cone : category_theory.limits.cone X.diagram := { X := X, π := { app := λ S, ⟨S.proj, S.proj_is_locally_constant.continuous⟩ } } instance is_iso_as_limit_cone_lift : is_iso ((limit_cone_is_limit X.diagram).lift X.as_limit_cone) := is_iso_of_bijective _ begin refine ⟨λ a b, _, λ a, _⟩, { intro h, refine discrete_quotient.eq_of_proj_eq (λ S, _), apply_fun (λ f : (limit_cone X.diagram).X, f.val S) at h, exact h }, { obtain ⟨b, hb⟩ := discrete_quotient.exists_of_compat (λ S, a.val S) (λ _ _ h, a.prop (hom_of_le h)), refine ⟨b, _⟩, ext S : 3, apply hb }, end /-- The isomorphism between `X` and the explicit limit of `X.diagram`, induced by lifting `X.as_limit_cone`. -/ def iso_as_limit_cone_lift : X ≅ (limit_cone X.diagram).X := as_iso $ (limit_cone_is_limit _).lift X.as_limit_cone /-- The isomorphism of cones `X.as_limit_cone` and `Profinite.limit_cone X.diagram`. The underlying isomorphism is defeq to `X.iso_as_limit_cone_lift`. -/ def as_limit_cone_iso : X.as_limit_cone ≅ limit_cone _ := limits.cones.ext (iso_as_limit_cone_lift _) (λ _, rfl) /-- `X.as_limit_cone` is indeed a limit cone. -/ def as_limit : category_theory.limits.is_limit X.as_limit_cone := limits.is_limit.of_iso_limit (limit_cone_is_limit _) X.as_limit_cone_iso.symm /-- A bundled version of `X.as_limit_cone` and `X.as_limit`. -/ def lim : limits.limit_cone X.diagram := ⟨X.as_limit_cone, X.as_limit⟩ end Profinite
1ce8f623032721fa28aba8976899ccf171c2c738
43390109ab88557e6090f3245c47479c123ee500
/src/M1F/problem_bank/0205/Q0205.lean
8d0d57a83b095dc5fb5fb39f37f057f0372d6c0c
[ "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
136
lean
import data.real.basic variables x y : ℝ theorem Q5a : ∀x, ∃y, x+y=2 := sorry theorem Q5b : ¬ (∃ y, ∀ x, x+y=2) := sorry
969f497c48b9ecb93e9aaf6557d171e43ef5ba23
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/computability/primrec.lean
65a86d454f31d8f7b80f9047542198b1f05025a9
[ "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
52,122
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import logic.equiv.list import logic.function.iterate /-! # The primitive recursive functions The primitive recursive functions are the least collection of functions `nat → nat` which are closed under projections (using the mkpair pairing function), composition, zero, successor, and primitive recursion (i.e. nat.rec where the motive is C n := nat). We can extend this definition to a large class of basic types by using canonical encodings of types as natural numbers (Gödel numbering), which we implement through the type class `encodable`. (More precisely, we need that the composition of encode with decode yields a primitive recursive function, so we have the `primcodable` type class for this.) ## References * [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019] -/ open denumerable encodable function namespace nat def elim {C : Sort*} : C → (ℕ → C → C) → ℕ → C := @nat.rec (λ _, C) @[simp] theorem elim_zero {C} (a f) : @nat.elim C a f 0 = a := rfl @[simp] theorem elim_succ {C} (a f n) : @nat.elim C a f (succ n) = f n (nat.elim a f n) := rfl def cases {C : Sort*} (a : C) (f : ℕ → C) : ℕ → C := nat.elim a (λ n _, f n) @[simp] theorem cases_zero {C} (a f) : @nat.cases C a f 0 = a := rfl @[simp] theorem cases_succ {C} (a f n) : @nat.cases C a f (succ n) = f n := rfl @[simp, reducible] def unpaired {α} (f : ℕ → ℕ → α) (n : ℕ) : α := f n.unpair.1 n.unpair.2 /-- The primitive recursive functions `ℕ → ℕ`. -/ inductive primrec : (ℕ → ℕ) → Prop | zero : primrec (λ n, 0) | succ : primrec succ | left : primrec (λ n, n.unpair.1) | right : primrec (λ n, n.unpair.2) | pair {f g} : primrec f → primrec g → primrec (λ n, mkpair (f n) (g n)) | comp {f g} : primrec f → primrec g → primrec (λ n, f (g n)) | prec {f g} : primrec f → primrec g → primrec (unpaired (λ z n, n.elim (f z) (λ y IH, g $ mkpair z $ mkpair y IH))) namespace primrec theorem of_eq {f g : ℕ → ℕ} (hf : primrec f) (H : ∀ n, f n = g n) : primrec g := (funext H : f = g) ▸ hf theorem const : ∀ (n : ℕ), primrec (λ _, n) | 0 := zero | (n+1) := succ.comp (const n) protected theorem id : primrec id := (left.pair right).of_eq $ λ n, by simp theorem prec1 {f} (m : ℕ) (hf : primrec f) : primrec (λ n, n.elim m (λ y IH, f $ mkpair y IH)) := ((prec (const m) (hf.comp right)).comp (zero.pair primrec.id)).of_eq $ λ n, by simp; dsimp; rw [unpair_mkpair] theorem cases1 {f} (m : ℕ) (hf : primrec f) : primrec (nat.cases m f) := (prec1 m (hf.comp left)).of_eq $ by simp [cases] theorem cases {f g} (hf : primrec f) (hg : primrec g) : primrec (unpaired (λ z n, n.cases (f z) (λ y, g $ mkpair z y))) := (prec hf (hg.comp (pair left (left.comp right)))).of_eq $ by simp [cases] protected theorem swap : primrec (unpaired (swap mkpair)) := (pair right left).of_eq $ λ n, by simp theorem swap' {f} (hf : primrec (unpaired f)) : primrec (unpaired (swap f)) := (hf.comp primrec.swap).of_eq $ λ n, by simp theorem pred : primrec pred := (cases1 0 primrec.id).of_eq $ λ n, by cases n; simp * theorem add : primrec (unpaired (+)) := (prec primrec.id ((succ.comp right).comp right)).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, -add_comm, add_succ] theorem sub : primrec (unpaired has_sub.sub) := (prec primrec.id ((pred.comp right).comp right)).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, -add_comm, sub_succ] theorem mul : primrec (unpaired (*)) := (prec zero (add.comp (pair left (right.comp right)))).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, mul_succ, add_comm] theorem pow : primrec (unpaired (^)) := (prec (const 1) (mul.comp (pair (right.comp right) left))).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, pow_succ'] end primrec end nat /-- A `primcodable` type is an `encodable` type for which the encode/decode functions are primitive recursive. -/ class primcodable (α : Type*) extends encodable α := (prim [] : nat.primrec (λ n, encodable.encode (decode n))) namespace primcodable open nat.primrec @[priority 10] instance of_denumerable (α) [denumerable α] : primcodable α := ⟨succ.of_eq $ by simp⟩ def of_equiv (α) {β} [primcodable α] (e : β ≃ α) : primcodable β := { prim := (primcodable.prim α).of_eq $ λ n, show encode (decode α n) = (option.cases_on (option.map e.symm (decode α n)) 0 (λ a, nat.succ (encode (e a))) : ℕ), by cases decode α n; dsimp; simp, ..encodable.of_equiv α e } instance empty : primcodable empty := ⟨zero⟩ instance unit : primcodable punit := ⟨(cases1 1 zero).of_eq $ λ n, by cases n; simp⟩ instance option {α : Type*} [h : primcodable α] : primcodable (option α) := ⟨(cases1 1 ((cases1 0 (succ.comp succ)).comp (primcodable.prim α))).of_eq $ λ n, by cases n; simp; cases decode α n; refl⟩ instance bool : primcodable bool := ⟨(cases1 1 (cases1 2 zero)).of_eq $ λ n, begin cases n, {refl}, cases n, {refl}, rw decode_ge_two, {refl}, exact dec_trivial end⟩ end primcodable /-- `primrec f` means `f` is primitive recursive (after encoding its input and output as natural numbers). -/ def primrec {α β} [primcodable α] [primcodable β] (f : α → β) : Prop := nat.primrec (λ n, encode ((decode α n).map f)) namespace primrec variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] open nat.primrec protected theorem encode : primrec (@encode α _) := (primcodable.prim α).of_eq $ λ n, by cases decode α n; refl protected theorem decode : primrec (decode α) := succ.comp (primcodable.prim α) theorem dom_denumerable {α β} [denumerable α] [primcodable β] {f : α → β} : primrec f ↔ nat.primrec (λ n, encode (f (of_nat α n))) := ⟨λ h, (pred.comp h).of_eq $ λ n, by simp; refl, λ h, (succ.comp h).of_eq $ λ n, by simp; refl⟩ theorem nat_iff {f : ℕ → ℕ} : primrec f ↔ nat.primrec f := dom_denumerable theorem encdec : primrec (λ n, encode (decode α n)) := nat_iff.2 (primcodable.prim α) theorem option_some : primrec (@some α) := ((cases1 0 (succ.comp succ)).comp (primcodable.prim α)).of_eq $ λ n, by cases decode α n; simp theorem of_eq {f g : α → σ} (hf : primrec f) (H : ∀ n, f n = g n) : primrec g := (funext H : f = g) ▸ hf theorem const (x : σ) : primrec (λ a : α, x) := ((cases1 0 (const (encode x).succ)).comp (primcodable.prim α)).of_eq $ λ n, by cases decode α n; refl protected theorem id : primrec (@id α) := (primcodable.prim α).of_eq $ by simp theorem comp {f : β → σ} {g : α → β} (hf : primrec f) (hg : primrec g) : primrec (λ a, f (g a)) := ((cases1 0 (hf.comp $ pred.comp hg)).comp (primcodable.prim α)).of_eq $ λ n, begin cases decode α n, {refl}, simp [encodek] end theorem succ : primrec nat.succ := nat_iff.2 nat.primrec.succ theorem pred : primrec nat.pred := nat_iff.2 nat.primrec.pred theorem encode_iff {f : α → σ} : primrec (λ a, encode (f a)) ↔ primrec f := ⟨λ h, nat.primrec.of_eq h $ λ n, by cases decode α n; refl, primrec.encode.comp⟩ theorem of_nat_iff {α β} [denumerable α] [primcodable β] {f : α → β} : primrec f ↔ primrec (λ n, f (of_nat α n)) := dom_denumerable.trans $ nat_iff.symm.trans encode_iff protected theorem of_nat (α) [denumerable α] : primrec (of_nat α) := of_nat_iff.1 primrec.id theorem option_some_iff {f : α → σ} : primrec (λ a, some (f a)) ↔ primrec f := ⟨λ h, encode_iff.1 $ pred.comp $ encode_iff.2 h, option_some.comp⟩ theorem of_equiv {β} {e : β ≃ α} : by haveI := primcodable.of_equiv α e; exact primrec e := by letI : primcodable β := primcodable.of_equiv α e; exact encode_iff.1 primrec.encode theorem of_equiv_symm {β} {e : β ≃ α} : by haveI := primcodable.of_equiv α e; exact primrec e.symm := by letI := primcodable.of_equiv α e; exact encode_iff.1 (show primrec (λ a, encode (e (e.symm a))), by simp [primrec.encode]) theorem of_equiv_iff {β} (e : β ≃ α) {f : σ → β} : by haveI := primcodable.of_equiv α e; exact primrec (λ a, e (f a)) ↔ primrec f := by letI := primcodable.of_equiv α e; exact ⟨λ h, (of_equiv_symm.comp h).of_eq (λ a, by simp), of_equiv.comp⟩ theorem of_equiv_symm_iff {β} (e : β ≃ α) {f : σ → α} : by haveI := primcodable.of_equiv α e; exact primrec (λ a, e.symm (f a)) ↔ primrec f := by letI := primcodable.of_equiv α e; exact ⟨λ h, (of_equiv.comp h).of_eq (λ a, by simp), of_equiv_symm.comp⟩ end primrec namespace primcodable open nat.primrec instance prod {α β} [primcodable α] [primcodable β] : primcodable (α × β) := ⟨((cases zero ((cases zero succ).comp (pair right ((primcodable.prim β).comp left)))).comp (pair right ((primcodable.prim α).comp left))).of_eq $ λ n, begin simp [nat.unpaired], cases decode α n.unpair.1, { simp }, cases decode β n.unpair.2; simp end⟩ end primcodable namespace primrec variables {α : Type*} {σ : Type*} [primcodable α] [primcodable σ] open nat.primrec theorem fst {α β} [primcodable α] [primcodable β] : primrec (@prod.fst α β) := ((cases zero ((cases zero (nat.primrec.succ.comp left)).comp (pair right ((primcodable.prim β).comp left)))).comp (pair right ((primcodable.prim α).comp left))).of_eq $ λ n, begin simp, cases decode α n.unpair.1; simp, cases decode β n.unpair.2; simp end theorem snd {α β} [primcodable α] [primcodable β] : primrec (@prod.snd α β) := ((cases zero ((cases zero (nat.primrec.succ.comp right)).comp (pair right ((primcodable.prim β).comp left)))).comp (pair right ((primcodable.prim α).comp left))).of_eq $ λ n, begin simp, cases decode α n.unpair.1; simp, cases decode β n.unpair.2; simp end theorem pair {α β γ} [primcodable α] [primcodable β] [primcodable γ] {f : α → β} {g : α → γ} (hf : primrec f) (hg : primrec g) : primrec (λ a, (f a, g a)) := ((cases1 0 (nat.primrec.succ.comp $ pair (nat.primrec.pred.comp hf) (nat.primrec.pred.comp hg))).comp (primcodable.prim α)).of_eq $ λ n, by cases decode α n; simp [encodek]; refl theorem unpair : primrec nat.unpair := (pair (nat_iff.2 nat.primrec.left) (nat_iff.2 nat.primrec.right)).of_eq $ λ n, by simp theorem list_nth₁ : ∀ (l : list α), primrec l.nth | [] := dom_denumerable.2 zero | (a::l) := dom_denumerable.2 $ (cases1 (encode a).succ $ dom_denumerable.1 $ list_nth₁ l).of_eq $ λ n, by cases n; simp end primrec /-- `primrec₂ f` means `f` is a binary primitive recursive function. This is technically unnecessary since we can always curry all the arguments together, but there are enough natural two-arg functions that it is convenient to express this directly. -/ def primrec₂ {α β σ} [primcodable α] [primcodable β] [primcodable σ] (f : α → β → σ) := primrec (λ p : α × β, f p.1 p.2) /-- `primrec_pred p` means `p : α → Prop` is a (decidable) primitive recursive predicate, which is to say that `to_bool ∘ p : α → bool` is primitive recursive. -/ def primrec_pred {α} [primcodable α] (p : α → Prop) [decidable_pred p] := primrec (λ a, to_bool (p a)) /-- `primrec_rel p` means `p : α → β → Prop` is a (decidable) primitive recursive relation, which is to say that `to_bool ∘ p : α → β → bool` is primitive recursive. -/ def primrec_rel {α β} [primcodable α] [primcodable β] (s : α → β → Prop) [∀ a b, decidable (s a b)] := primrec₂ (λ a b, to_bool (s a b)) namespace primrec₂ variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] theorem of_eq {f g : α → β → σ} (hg : primrec₂ f) (H : ∀ a b, f a b = g a b) : primrec₂ g := (by funext a b; apply H : f = g) ▸ hg theorem const (x : σ) : primrec₂ (λ (a : α) (b : β), x) := primrec.const _ protected theorem pair : primrec₂ (@prod.mk α β) := primrec.pair primrec.fst primrec.snd theorem left : primrec₂ (λ (a : α) (b : β), a) := primrec.fst theorem right : primrec₂ (λ (a : α) (b : β), b) := primrec.snd theorem mkpair : primrec₂ nat.mkpair := by simp [primrec₂, primrec]; constructor theorem unpaired {f : ℕ → ℕ → α} : primrec (nat.unpaired f) ↔ primrec₂ f := ⟨λ h, by simpa using h.comp mkpair, λ h, h.comp primrec.unpair⟩ theorem unpaired' {f : ℕ → ℕ → ℕ} : nat.primrec (nat.unpaired f) ↔ primrec₂ f := primrec.nat_iff.symm.trans unpaired theorem encode_iff {f : α → β → σ} : primrec₂ (λ a b, encode (f a b)) ↔ primrec₂ f := primrec.encode_iff theorem option_some_iff {f : α → β → σ} : primrec₂ (λ a b, some (f a b)) ↔ primrec₂ f := primrec.option_some_iff theorem of_nat_iff {α β σ} [denumerable α] [denumerable β] [primcodable σ] {f : α → β → σ} : primrec₂ f ↔ primrec₂ (λ m n : ℕ, f (of_nat α m) (of_nat β n)) := (primrec.of_nat_iff.trans $ by simp).trans unpaired theorem uncurry {f : α → β → σ} : primrec (function.uncurry f) ↔ primrec₂ f := by rw [show function.uncurry f = λ (p : α × β), f p.1 p.2, from funext $ λ ⟨a, b⟩, rfl]; refl theorem curry {f : α × β → σ} : primrec₂ (function.curry f) ↔ primrec f := by rw [← uncurry, function.uncurry_curry] end primrec₂ section comp variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] theorem primrec.comp₂ {f : γ → σ} {g : α → β → γ} (hf : primrec f) (hg : primrec₂ g) : primrec₂ (λ a b, f (g a b)) := hf.comp hg theorem primrec₂.comp {f : β → γ → σ} {g : α → β} {h : α → γ} (hf : primrec₂ f) (hg : primrec g) (hh : primrec h) : primrec (λ a, f (g a) (h a)) := hf.comp (hg.pair hh) theorem primrec₂.comp₂ {f : γ → δ → σ} {g : α → β → γ} {h : α → β → δ} (hf : primrec₂ f) (hg : primrec₂ g) (hh : primrec₂ h) : primrec₂ (λ a b, f (g a b) (h a b)) := hf.comp hg hh theorem primrec_pred.comp {p : β → Prop} [decidable_pred p] {f : α → β} : primrec_pred p → primrec f → primrec_pred (λ a, p (f a)) := primrec.comp theorem primrec_rel.comp {R : β → γ → Prop} [∀ a b, decidable (R a b)] {f : α → β} {g : α → γ} : primrec_rel R → primrec f → primrec g → primrec_pred (λ a, R (f a) (g a)) := primrec₂.comp theorem primrec_rel.comp₂ {R : γ → δ → Prop} [∀ a b, decidable (R a b)] {f : α → β → γ} {g : α → β → δ} : primrec_rel R → primrec₂ f → primrec₂ g → primrec_rel (λ a b, R (f a b) (g a b)) := primrec_rel.comp end comp theorem primrec_pred.of_eq {α} [primcodable α] {p q : α → Prop} [decidable_pred p] [decidable_pred q] (hp : primrec_pred p) (H : ∀ a, p a ↔ q a) : primrec_pred q := primrec.of_eq hp (λ a, to_bool_congr (H a)) theorem primrec_rel.of_eq {α β} [primcodable α] [primcodable β] {r s : α → β → Prop} [∀ a b, decidable (r a b)] [∀ a b, decidable (s a b)] (hr : primrec_rel r) (H : ∀ a b, r a b ↔ s a b) : primrec_rel s := primrec₂.of_eq hr (λ a b, to_bool_congr (H a b)) namespace primrec₂ variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] open nat.primrec theorem swap {f : α → β → σ} (h : primrec₂ f) : primrec₂ (swap f) := h.comp₂ primrec₂.right primrec₂.left theorem nat_iff {f : α → β → σ} : primrec₂ f ↔ nat.primrec (nat.unpaired $ λ m n : ℕ, encode $ (decode α m).bind $ λ a, (decode β n).map (f a)) := have ∀ (a : option α) (b : option β), option.map (λ (p : α × β), f p.1 p.2) (option.bind a (λ (a : α), option.map (prod.mk a) b)) = option.bind a (λ a, option.map (f a) b), by intros; cases a; [refl, {cases b; refl}], by simp [primrec₂, primrec, this] theorem nat_iff' {f : α → β → σ} : primrec₂ f ↔ primrec₂ (λ m n : ℕ, option.bind (decode α m) (λ a, option.map (f a) (decode β n))) := nat_iff.trans $ unpaired'.trans encode_iff end primrec₂ namespace primrec variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] theorem to₂ {f : α × β → σ} (hf : primrec f) : primrec₂ (λ a b, f (a, b)) := hf.of_eq $ λ ⟨a, b⟩, rfl theorem nat_elim {f : α → β} {g : α → ℕ × β → β} (hf : primrec f) (hg : primrec₂ g) : primrec₂ (λ a (n : ℕ), n.elim (f a) (λ n IH, g a (n, IH))) := primrec₂.nat_iff.2 $ ((nat.primrec.cases nat.primrec.zero $ (nat.primrec.prec hf $ nat.primrec.comp hg $ nat.primrec.left.pair $ (nat.primrec.left.comp nat.primrec.right).pair $ nat.primrec.pred.comp $ nat.primrec.right.comp nat.primrec.right).comp $ nat.primrec.right.pair $ nat.primrec.right.comp nat.primrec.left).comp $ nat.primrec.id.pair $ (primcodable.prim α).comp nat.primrec.left).of_eq $ λ n, begin simp, cases decode α n.unpair.1 with a, {refl}, simp [encodek], induction n.unpair.2 with m; simp [encodek], simp [ih, encodek] end theorem nat_elim' {f : α → ℕ} {g : α → β} {h : α → ℕ × β → β} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (f a).elim (g a) (λ n IH, h a (n, IH))) := (nat_elim hg hh).comp primrec.id hf theorem nat_elim₁ {f : ℕ → α → α} (a : α) (hf : primrec₂ f) : primrec (nat.elim a f) := nat_elim' primrec.id (const a) $ comp₂ hf primrec₂.right theorem nat_cases' {f : α → β} {g : α → ℕ → β} (hf : primrec f) (hg : primrec₂ g) : primrec₂ (λ a, nat.cases (f a) (g a)) := nat_elim hf $ hg.comp₂ primrec₂.left $ comp₂ fst primrec₂.right theorem nat_cases {f : α → ℕ} {g : α → β} {h : α → ℕ → β} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (f a).cases (g a) (h a)) := (nat_cases' hg hh).comp primrec.id hf theorem nat_cases₁ {f : ℕ → α} (a : α) (hf : primrec f) : primrec (nat.cases a f) := nat_cases primrec.id (const a) (comp₂ hf primrec₂.right) theorem nat_iterate {f : α → ℕ} {g : α → β} {h : α → β → β} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (h a)^[f a] (g a)) := (nat_elim' hf hg (hh.comp₂ primrec₂.left $ snd.comp₂ primrec₂.right)).of_eq $ λ a, by induction f a; simp [*, function.iterate_succ'] theorem option_cases {o : α → option β} {f : α → σ} {g : α → β → σ} (ho : primrec o) (hf : primrec f) (hg : primrec₂ g) : @primrec _ σ _ _ (λ a, option.cases_on (o a) (f a) (g a)) := encode_iff.1 $ (nat_cases (encode_iff.2 ho) (encode_iff.2 hf) $ pred.comp₂ $ primrec₂.encode_iff.2 $ (primrec₂.nat_iff'.1 hg).comp₂ ((@primrec.encode α _).comp fst).to₂ primrec₂.right).of_eq $ λ a, by cases o a with b; simp [encodek]; refl theorem option_bind {f : α → option β} {g : α → β → option σ} (hf : primrec f) (hg : primrec₂ g) : primrec (λ a, (f a).bind (g a)) := (option_cases hf (const none) hg).of_eq $ λ a, by cases f a; refl theorem option_bind₁ {f : α → option σ} (hf : primrec f) : primrec (λ o, option.bind o f) := option_bind primrec.id (hf.comp snd).to₂ theorem option_map {f : α → option β} {g : α → β → σ} (hf : primrec f) (hg : primrec₂ g) : primrec (λ a, (f a).map (g a)) := option_bind hf (option_some.comp₂ hg) theorem option_map₁ {f : α → σ} (hf : primrec f) : primrec (option.map f) := option_map primrec.id (hf.comp snd).to₂ theorem option_iget [inhabited α] : primrec (@option.iget α _) := (option_cases primrec.id (const $ @default α _) primrec₂.right).of_eq $ λ o, by cases o; refl theorem option_is_some : primrec (@option.is_some α) := (option_cases primrec.id (const ff) (const tt).to₂).of_eq $ λ o, by cases o; refl theorem option_get_or_else : primrec₂ (@option.get_or_else α) := primrec.of_eq (option_cases primrec₂.left primrec₂.right primrec₂.right) $ λ ⟨o, a⟩, by cases o; refl theorem bind_decode_iff {f : α → β → option σ} : primrec₂ (λ a n, (decode β n).bind (f a)) ↔ primrec₂ f := ⟨λ h, by simpa [encodek] using h.comp fst ((@primrec.encode β _).comp snd), λ h, option_bind (primrec.decode.comp snd) $ h.comp (fst.comp fst) snd⟩ theorem map_decode_iff {f : α → β → σ} : primrec₂ (λ a n, (decode β n).map (f a)) ↔ primrec₂ f := bind_decode_iff.trans primrec₂.option_some_iff theorem nat_add : primrec₂ ((+) : ℕ → ℕ → ℕ) := primrec₂.unpaired'.1 nat.primrec.add theorem nat_sub : primrec₂ (has_sub.sub : ℕ → ℕ → ℕ) := primrec₂.unpaired'.1 nat.primrec.sub theorem nat_mul : primrec₂ ((*) : ℕ → ℕ → ℕ) := primrec₂.unpaired'.1 nat.primrec.mul theorem cond {c : α → bool} {f : α → σ} {g : α → σ} (hc : primrec c) (hf : primrec f) (hg : primrec g) : primrec (λ a, cond (c a) (f a) (g a)) := (nat_cases (encode_iff.2 hc) hg (hf.comp fst).to₂).of_eq $ λ a, by cases c a; refl theorem ite {c : α → Prop} [decidable_pred c] {f : α → σ} {g : α → σ} (hc : primrec_pred c) (hf : primrec f) (hg : primrec g) : primrec (λ a, if c a then f a else g a) := by simpa using cond hc hf hg theorem nat_le : primrec_rel ((≤) : ℕ → ℕ → Prop) := (nat_cases nat_sub (const tt) (const ff).to₂).of_eq $ λ p, begin dsimp [swap], cases e : p.1 - p.2 with n, { simp [tsub_eq_zero_iff_le.1 e] }, { simp [not_le.2 (nat.lt_of_sub_eq_succ e)] } end theorem nat_min : primrec₂ (@min ℕ _) := ite nat_le fst snd theorem nat_max : primrec₂ (@max ℕ _) := ite (nat_le.comp primrec.fst primrec.snd) snd fst theorem dom_bool (f : bool → α) : primrec f := (cond primrec.id (const (f tt)) (const (f ff))).of_eq $ λ b, by cases b; refl theorem dom_bool₂ (f : bool → bool → α) : primrec₂ f := (cond fst ((dom_bool (f tt)).comp snd) ((dom_bool (f ff)).comp snd)).of_eq $ λ ⟨a, b⟩, by cases a; refl protected theorem bnot : primrec bnot := dom_bool _ protected theorem band : primrec₂ band := dom_bool₂ _ protected theorem bor : primrec₂ bor := dom_bool₂ _ protected theorem not {p : α → Prop} [decidable_pred p] (hp : primrec_pred p) : primrec_pred (λ a, ¬ p a) := (primrec.bnot.comp hp).of_eq $ λ n, by simp protected theorem and {p q : α → Prop} [decidable_pred p] [decidable_pred q] (hp : primrec_pred p) (hq : primrec_pred q) : primrec_pred (λ a, p a ∧ q a) := (primrec.band.comp hp hq).of_eq $ λ n, by simp protected theorem or {p q : α → Prop} [decidable_pred p] [decidable_pred q] (hp : primrec_pred p) (hq : primrec_pred q) : primrec_pred (λ a, p a ∨ q a) := (primrec.bor.comp hp hq).of_eq $ λ n, by simp protected theorem eq [decidable_eq α] : primrec_rel (@eq α) := have primrec_rel (λ a b : ℕ, a = b), from (primrec.and nat_le nat_le.swap).of_eq $ λ a, by simp [le_antisymm_iff], (this.comp₂ (primrec.encode.comp₂ primrec₂.left) (primrec.encode.comp₂ primrec₂.right)).of_eq $ λ a b, encode_injective.eq_iff theorem nat_lt : primrec_rel ((<) : ℕ → ℕ → Prop) := (nat_le.comp snd fst).not.of_eq $ λ p, by simp theorem option_guard {p : α → β → Prop} [∀ a b, decidable (p a b)] (hp : primrec_rel p) {f : α → β} (hf : primrec f) : primrec (λ a, option.guard (p a) (f a)) := ite (hp.comp primrec.id hf) (option_some_iff.2 hf) (const none) theorem option_orelse : primrec₂ ((<|>) : option α → option α → option α) := (option_cases fst snd (fst.comp fst).to₂).of_eq $ λ ⟨o₁, o₂⟩, by cases o₁; cases o₂; refl protected theorem decode₂ : primrec (decode₂ α) := option_bind primrec.decode $ option_guard ((@primrec.eq _ _ nat.decidable_eq).comp (encode_iff.2 snd) (fst.comp fst)) snd theorem list_find_index₁ {p : α → β → Prop} [∀ a b, decidable (p a b)] (hp : primrec_rel p) : ∀ (l : list β), primrec (λ a, l.find_index (p a)) | [] := const 0 | (a::l) := ite (hp.comp primrec.id (const a)) (const 0) (succ.comp (list_find_index₁ l)) theorem list_index_of₁ [decidable_eq α] (l : list α) : primrec (λ a, l.index_of a) := list_find_index₁ primrec.eq l theorem dom_fintype [fintype α] (f : α → σ) : primrec f := let ⟨l, nd, m⟩ := finite.exists_univ_list α in option_some_iff.1 $ begin haveI := decidable_eq_of_encodable α, refine ((list_nth₁ (l.map f)).comp (list_index_of₁ l)).of_eq (λ a, _), rw [list.nth_map, list.nth_le_nth (list.index_of_lt_length.2 (m _)), list.index_of_nth_le]; refl end theorem nat_bodd_div2 : primrec nat.bodd_div2 := (nat_elim' primrec.id (const (ff, 0)) (((cond fst (pair (const ff) (succ.comp snd)) (pair (const tt) snd)).comp snd).comp snd).to₂).of_eq $ λ n, begin simp [-nat.bodd_div2_eq], induction n with n IH, {refl}, simp [-nat.bodd_div2_eq, nat.bodd_div2, *], rcases nat.bodd_div2 n with ⟨_|_, m⟩; simp [nat.bodd_div2] end theorem nat_bodd : primrec nat.bodd := fst.comp nat_bodd_div2 theorem nat_div2 : primrec nat.div2 := snd.comp nat_bodd_div2 theorem nat_bit0 : primrec (@bit0 ℕ _) := nat_add.comp primrec.id primrec.id theorem nat_bit1 : primrec (@bit1 ℕ _ _) := nat_add.comp nat_bit0 (const 1) theorem nat_bit : primrec₂ nat.bit := (cond primrec.fst (nat_bit1.comp primrec.snd) (nat_bit0.comp primrec.snd)).of_eq $ λ n, by cases n.1; refl theorem nat_div_mod : primrec₂ (λ n k : ℕ, (n / k, n % k)) := let f (a : ℕ × ℕ) : ℕ × ℕ := a.1.elim (0, 0) (λ _ IH, if nat.succ IH.2 = a.2 then (nat.succ IH.1, 0) else (IH.1, nat.succ IH.2)) in have hf : primrec f, from nat_elim' fst (const (0, 0)) $ ((ite ((@primrec.eq ℕ _ _).comp (succ.comp $ snd.comp snd) fst) (pair (succ.comp $ fst.comp snd) (const 0)) (pair (fst.comp snd) (succ.comp $ snd.comp snd))) .comp (pair (snd.comp fst) (snd.comp snd))).to₂, suffices ∀ k n, (n / k, n % k) = f (n, k), from hf.of_eq $ λ ⟨m, n⟩, by simp [this], λ k n, begin have : (f (n, k)).2 + k * (f (n, k)).1 = n ∧ (0 < k → (f (n, k)).2 < k) ∧ (k = 0 → (f (n, k)).1 = 0), { induction n with n IH, {exact ⟨rfl, id, λ _, rfl⟩}, rw [λ n:ℕ, show f (n.succ, k) = _root_.ite ((f (n, k)).2.succ = k) (nat.succ (f (n, k)).1, 0) ((f (n, k)).1, (f (n, k)).2.succ), from rfl], by_cases h : (f (n, k)).2.succ = k; simp [h], { have := congr_arg nat.succ IH.1, refine ⟨_, λ k0, nat.no_confusion (h.trans k0)⟩, rwa [← nat.succ_add, h, add_comm, ← nat.mul_succ] at this }, { exact ⟨by rw [nat.succ_add, IH.1], λ k0, lt_of_le_of_ne (IH.2.1 k0) h, IH.2.2⟩ } }, revert this, cases f (n, k) with D M, simp, intros h₁ h₂ h₃, cases nat.eq_zero_or_pos k, { simp [h, h₃ h] at h₁ ⊢, simp [h₁] }, { exact (nat.div_mod_unique h).2 ⟨h₁, h₂ h⟩ } end theorem nat_div : primrec₂ ((/) : ℕ → ℕ → ℕ) := fst.comp₂ nat_div_mod theorem nat_mod : primrec₂ ((%) : ℕ → ℕ → ℕ) := snd.comp₂ nat_div_mod end primrec section variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] variable (H : nat.primrec (λ n, encodable.encode (decode (list β) n))) include H open primrec private def prim : primcodable (list β) := ⟨H⟩ private lemma list_cases' {f : α → list β} {g : α → σ} {h : α → β × list β → σ} (hf : by haveI := prim H; exact primrec f) (hg : primrec g) (hh : by haveI := prim H; exact primrec₂ h) : @primrec _ σ _ _ (λ a, list.cases_on (f a) (g a) (λ b l, h a (b, l))) := by letI := prim H; exact have @primrec _ (option σ) _ _ (λ a, (decode (option (β × list β)) (encode (f a))).map (λ o, option.cases_on o (g a) (h a))), from ((@map_decode_iff _ (option (β × list β)) _ _ _ _ _).2 $ to₂ $ option_cases snd (hg.comp fst) (hh.comp₂ (fst.comp₂ primrec₂.left) primrec₂.right)) .comp primrec.id (encode_iff.2 hf), option_some_iff.1 $ this.of_eq $ λ a, by cases f a with b l; simp [encodek]; refl private lemma list_foldl' {f : α → list β} {g : α → σ} {h : α → σ × β → σ} (hf : by haveI := prim H; exact primrec f) (hg : primrec g) (hh : by haveI := prim H; exact primrec₂ h) : primrec (λ a, (f a).foldl (λ s b, h a (s, b)) (g a)) := by letI := prim H; exact let G (a : α) (IH : σ × list β) : σ × list β := list.cases_on IH.2 IH (λ b l, (h a (IH.1, b), l)) in let F (a : α) (n : ℕ) := (G a)^[n] (g a, f a) in have primrec (λ a, (F a (encode (f a))).1), from fst.comp $ nat_iterate (encode_iff.2 hf) (pair hg hf) $ list_cases' H (snd.comp snd) snd $ to₂ $ pair (hh.comp (fst.comp fst) $ pair ((fst.comp snd).comp fst) (fst.comp snd)) (snd.comp snd), this.of_eq $ λ a, begin have : ∀ n, F a n = ((list.take n (f a)).foldl (λ s b, h a (s, b)) (g a), list.drop n (f a)), { intro, simp [F], generalize : f a = l, generalize : g a = x, induction n with n IH generalizing l x, {refl}, simp, cases l with b l; simp [IH] }, rw [this, list.take_all_of_le (length_le_encode _)] end private lemma list_cons' : by haveI := prim H; exact primrec₂ (@list.cons β) := by letI := prim H; exact encode_iff.1 (succ.comp $ primrec₂.mkpair.comp (encode_iff.2 fst) (encode_iff.2 snd)) private lemma list_reverse' : by haveI := prim H; exact primrec (@list.reverse β) := by letI := prim H; exact (list_foldl' H primrec.id (const []) $ to₂ $ ((list_cons' H).comp snd fst).comp snd).of_eq (suffices ∀ l r, list.foldl (λ (s : list β) (b : β), b :: s) r l = list.reverse_core l r, from λ l, this l [], λ l, by induction l; simp [*, list.reverse_core]) end namespace primcodable variables {α : Type*} {β : Type*} variables [primcodable α] [primcodable β] open primrec instance sum : primcodable (α ⊕ β) := ⟨primrec.nat_iff.1 $ (encode_iff.2 (cond nat_bodd (((@primrec.decode β _).comp nat_div2).option_map $ to₂ $ nat_bit.comp (const tt) (primrec.encode.comp snd)) (((@primrec.decode α _).comp nat_div2).option_map $ to₂ $ nat_bit.comp (const ff) (primrec.encode.comp snd)))).of_eq $ λ n, show _ = encode (decode_sum n), begin simp [decode_sum], cases nat.bodd n; simp [decode_sum], { cases decode α n.div2; refl }, { cases decode β n.div2; refl } end⟩ instance list : primcodable (list α) := ⟨ by letI H := primcodable.prim (list ℕ); exact have primrec₂ (λ (a : α) (o : option (list ℕ)), o.map (list.cons (encode a))), from option_map snd $ (list_cons' H).comp ((@primrec.encode α _).comp (fst.comp fst)) snd, have primrec (λ n, (of_nat (list ℕ) n).reverse.foldl (λ o m, (decode α m).bind (λ a, o.map (list.cons (encode a)))) (some [])), from list_foldl' H ((list_reverse' H).comp (primrec.of_nat (list ℕ))) (const (some [])) (primrec.comp₂ (bind_decode_iff.2 $ primrec₂.swap this) primrec₂.right), nat_iff.1 $ (encode_iff.2 this).of_eq $ λ n, begin rw list.foldl_reverse, apply nat.case_strong_induction_on n, { simp }, intros n IH, simp, cases decode α n.unpair.1 with a, {refl}, simp, suffices : ∀ (o : option (list ℕ)) p (_ : encode o = encode p), encode (option.map (list.cons (encode a)) o) = encode (option.map (list.cons a) p), from this _ _ (IH _ (nat.unpair_right_le n)), intros o p IH, cases o; cases p; injection IH with h, exact congr_arg (λ k, (nat.mkpair (encode a) k).succ.succ) h end⟩ end primcodable namespace primrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem sum_inl : primrec (@sum.inl α β) := encode_iff.1 $ nat_bit0.comp primrec.encode theorem sum_inr : primrec (@sum.inr α β) := encode_iff.1 $ nat_bit1.comp primrec.encode theorem sum_cases {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ → σ} (hf : primrec f) (hg : primrec₂ g) (hh : primrec₂ h) : @primrec _ σ _ _ (λ a, sum.cases_on (f a) (g a) (h a)) := option_some_iff.1 $ (cond (nat_bodd.comp $ encode_iff.2 hf) (option_map (primrec.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hh) (option_map (primrec.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hg)).of_eq $ λ a, by cases f a with b c; simp [nat.div2_bit, nat.bodd_bit, encodek]; refl theorem list_cons : primrec₂ (@list.cons α) := list_cons' (primcodable.prim _) theorem list_cases {f : α → list β} {g : α → σ} {h : α → β × list β → σ} : primrec f → primrec g → primrec₂ h → @primrec _ σ _ _ (λ a, list.cases_on (f a) (g a) (λ b l, h a (b, l))) := list_cases' (primcodable.prim _) theorem list_foldl {f : α → list β} {g : α → σ} {h : α → σ × β → σ} : primrec f → primrec g → primrec₂ h → primrec (λ a, (f a).foldl (λ s b, h a (s, b)) (g a)) := list_foldl' (primcodable.prim _) theorem list_reverse : primrec (@list.reverse α) := list_reverse' (primcodable.prim _) theorem list_foldr {f : α → list β} {g : α → σ} {h : α → β × σ → σ} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (f a).foldr (λ b s, h a (b, s)) (g a)) := (list_foldl (list_reverse.comp hf) hg $ to₂ $ hh.comp fst $ (pair snd fst).comp snd).of_eq $ λ a, by simp [list.foldl_reverse] theorem list_head' : primrec (@list.head' α) := (list_cases primrec.id (const none) (option_some_iff.2 $ (fst.comp snd)).to₂).of_eq $ λ l, by cases l; refl theorem list_head [inhabited α] : primrec (@list.head α _) := (option_iget.comp list_head').of_eq $ λ l, l.head_eq_head'.symm theorem list_tail : primrec (@list.tail α) := (list_cases primrec.id (const []) (snd.comp snd).to₂).of_eq $ λ l, by cases l; refl theorem list_rec {f : α → list β} {g : α → σ} {h : α → β × list β × σ → σ} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : @primrec _ σ _ _ (λ a, list.rec_on (f a) (g a) (λ b l IH, h a (b, l, IH))) := let F (a : α) := (f a).foldr (λ (b : β) (s : list β × σ), (b :: s.1, h a (b, s))) ([], g a) in have primrec F, from list_foldr hf (pair (const []) hg) $ to₂ $ pair ((list_cons.comp fst (fst.comp snd)).comp snd) hh, (snd.comp this).of_eq $ λ a, begin suffices : F a = (f a, list.rec_on (f a) (g a) (λ b l IH, h a (b, l, IH))), {rw this}, simp [F], induction f a with b l IH; simp * end theorem list_nth : primrec₂ (@list.nth α) := let F (l : list α) (n : ℕ) := l.foldl (λ (s : ℕ ⊕ α) (a : α), sum.cases_on s (@nat.cases (ℕ ⊕ α) (sum.inr a) sum.inl) sum.inr) (sum.inl n) in have hF : primrec₂ F, from list_foldl fst (sum_inl.comp snd) ((sum_cases fst (nat_cases snd (sum_inr.comp $ snd.comp fst) (sum_inl.comp snd).to₂).to₂ (sum_inr.comp snd).to₂).comp snd).to₂, have @primrec _ (option α) _ _ (λ p : list α × ℕ, sum.cases_on (F p.1 p.2) (λ _, none) some), from sum_cases hF (const none).to₂ (option_some.comp snd).to₂, this.to₂.of_eq $ λ l n, begin dsimp, symmetry, induction l with a l IH generalizing n, {refl}, cases n with n, { rw [(_ : F (a :: l) 0 = sum.inr a)], {refl}, clear IH, dsimp [F], induction l with b l IH; simp * }, { apply IH } end theorem list_nthd (d : α) : primrec₂ (list.nthd d) := begin suffices : list.nthd d = λ l n, (list.nth l n).get_or_else d, { rw this, exact option_get_or_else.comp₂ list_nth (const _) }, funext, exact list.nthd_eq_get_or_else_nth _ _ _ end theorem list_inth [inhabited α] : primrec₂ (@list.inth α _) := list_nthd _ theorem list_append : primrec₂ ((++) : list α → list α → list α) := (list_foldr fst snd $ to₂ $ comp (@list_cons α _) snd).to₂.of_eq $ λ l₁ l₂, by induction l₁; simp * theorem list_concat : primrec₂ (λ l (a:α), l ++ [a]) := list_append.comp fst (list_cons.comp snd (const [])) theorem list_map {f : α → list β} {g : α → β → σ} (hf : primrec f) (hg : primrec₂ g) : primrec (λ a, (f a).map (g a)) := (list_foldr hf (const []) $ to₂ $ list_cons.comp (hg.comp fst (fst.comp snd)) (snd.comp snd)).of_eq $ λ a, by induction f a; simp * theorem list_range : primrec list.range := (nat_elim' primrec.id (const []) ((list_concat.comp snd fst).comp snd).to₂).of_eq $ λ n, by simp; induction n; simp [*, list.range_succ]; refl theorem list_join : primrec (@list.join α) := (list_foldr primrec.id (const []) $ to₂ $ comp (@list_append α _) snd).of_eq $ λ l, by dsimp; induction l; simp * theorem list_length : primrec (@list.length α) := (list_foldr (@primrec.id (list α) _) (const 0) $ to₂ $ (succ.comp $ snd.comp snd).to₂).of_eq $ λ l, by dsimp; induction l; simp [*, -add_comm] theorem list_find_index {f : α → list β} {p : α → β → Prop} [∀ a b, decidable (p a b)] (hf : primrec f) (hp : primrec_rel p) : primrec (λ a, (f a).find_index (p a)) := (list_foldr hf (const 0) $ to₂ $ ite (hp.comp fst $ fst.comp snd) (const 0) (succ.comp $ snd.comp snd)).of_eq $ λ a, eq.symm $ by dsimp; induction f a with b l; [refl, simp [*, list.find_index]] theorem list_index_of [decidable_eq α] : primrec₂ (@list.index_of α _) := to₂ $ list_find_index snd $ primrec.eq.comp₂ (fst.comp fst).to₂ snd.to₂ theorem nat_strong_rec (f : α → ℕ → σ) {g : α → list σ → option σ} (hg : primrec₂ g) (H : ∀ a n, g a ((list.range n).map (f a)) = some (f a n)) : primrec₂ f := suffices primrec₂ (λ a n, (list.range n).map (f a)), from primrec₂.option_some_iff.1 $ (list_nth.comp (this.comp fst (succ.comp snd)) snd).to₂.of_eq $ λ a n, by simp [list.nth_range (nat.lt_succ_self n)]; refl, primrec₂.option_some_iff.1 $ (nat_elim (const (some [])) (to₂ $ option_bind (snd.comp snd) $ to₂ $ option_map (hg.comp (fst.comp fst) snd) (to₂ $ list_concat.comp (snd.comp fst) snd))).of_eq $ λ a n, begin simp, induction n with n IH, {refl}, simp [IH, H, list.range_succ] end end primrec namespace primcodable variables {α : Type*} {β : Type*} variables [primcodable α] [primcodable β] open primrec def subtype {p : α → Prop} [decidable_pred p] (hp : primrec_pred p) : primcodable (subtype p) := ⟨have primrec (λ n, (decode α n).bind (λ a, option.guard p a)), from option_bind primrec.decode (option_guard (hp.comp snd) snd), nat_iff.1 $ (encode_iff.2 this).of_eq $ λ n, show _ = encode ((decode α n).bind (λ a, _)), begin cases decode α n with a, {refl}, dsimp [option.guard], by_cases h : p a; simp [h]; refl end⟩ instance fin {n} : primcodable (fin n) := @of_equiv _ _ (subtype $ nat_lt.comp primrec.id (const n)) fin.equiv_subtype instance vector {n} : primcodable (vector α n) := subtype ((@primrec.eq _ _ nat.decidable_eq).comp list_length (const _)) instance fin_arrow {n} : primcodable (fin n → α) := of_equiv _ (equiv.vector_equiv_fin _ _).symm instance array {n} : primcodable (array n α) := of_equiv _ (equiv.array_equiv_fin _ _) section ulower local attribute [instance, priority 100] encodable.decidable_range_encode encodable.decidable_eq_of_encodable instance ulower : primcodable (ulower α) := have primrec_pred (λ n, encodable.decode₂ α n ≠ none), from primrec.not (primrec.eq.comp (primrec.option_bind primrec.decode (primrec.ite (primrec.eq.comp (primrec.encode.comp primrec.snd) primrec.fst) (primrec.option_some.comp primrec.snd) (primrec.const _))) (primrec.const _)), primcodable.subtype $ primrec_pred.of_eq this (λ n, decode₂_ne_none_iff) end ulower end primcodable namespace primrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem subtype_val {p : α → Prop} [decidable_pred p] {hp : primrec_pred p} : by haveI := primcodable.subtype hp; exact primrec (@subtype.val α p) := begin letI := primcodable.subtype hp, refine (primcodable.prim (subtype p)).of_eq (λ n, _), rcases decode (subtype p) n with _|⟨a,h⟩; refl end theorem subtype_val_iff {p : β → Prop} [decidable_pred p] {hp : primrec_pred p} {f : α → subtype p} : by haveI := primcodable.subtype hp; exact primrec (λ a, (f a).1) ↔ primrec f := begin letI := primcodable.subtype hp, refine ⟨λ h, _, λ hf, subtype_val.comp hf⟩, refine nat.primrec.of_eq h (λ n, _), cases decode α n with a, {refl}, simp, cases f a; refl end theorem subtype_mk {p : β → Prop} [decidable_pred p] {hp : primrec_pred p} {f : α → β} {h : ∀ a, p (f a)} (hf : primrec f) : by haveI := primcodable.subtype hp; exact primrec (λ a, @subtype.mk β p (f a) (h a)) := subtype_val_iff.1 hf theorem option_get {f : α → option β} {h : ∀ a, (f a).is_some} : primrec f → primrec (λ a, option.get (h a)) := begin intro hf, refine (nat.primrec.pred.comp hf).of_eq (λ n, _), generalize hx : decode α n = x, cases x; simp end theorem ulower_down : primrec (ulower.down : α → ulower α) := by letI : ∀ a, decidable (a ∈ set.range (encode : α → ℕ)) := decidable_range_encode _; exact subtype_mk primrec.encode theorem ulower_up : primrec (ulower.up : ulower α → α) := by letI : ∀ a, decidable (a ∈ set.range (encode : α → ℕ)) := decidable_range_encode _; exact option_get (primrec.decode₂.comp subtype_val) theorem fin_val_iff {n} {f : α → fin n} : primrec (λ a, (f a).1) ↔ primrec f := begin let : primcodable {a//id a<n}, swap, exactI (iff.trans (by refl) subtype_val_iff).trans (of_equiv_iff _) end theorem fin_val {n} : primrec (coe : fin n → ℕ) := fin_val_iff.2 primrec.id theorem fin_succ {n} : primrec (@fin.succ n) := fin_val_iff.1 $ by simp [succ.comp fin_val] theorem vector_to_list {n} : primrec (@vector.to_list α n) := subtype_val theorem vector_to_list_iff {n} {f : α → vector β n} : primrec (λ a, (f a).to_list) ↔ primrec f := subtype_val_iff theorem vector_cons {n} : primrec₂ (@vector.cons α n) := vector_to_list_iff.1 $ by simp; exact list_cons.comp fst (vector_to_list_iff.2 snd) theorem vector_length {n} : primrec (@vector.length α n) := const _ theorem vector_head {n} : primrec (@vector.head α n) := option_some_iff.1 $ (list_head'.comp vector_to_list).of_eq $ λ ⟨a::l, h⟩, rfl theorem vector_tail {n} : primrec (@vector.tail α n) := vector_to_list_iff.1 $ (list_tail.comp vector_to_list).of_eq $ λ ⟨l, h⟩, by cases l; refl theorem vector_nth {n} : primrec₂ (@vector.nth α n) := option_some_iff.1 $ (list_nth.comp (vector_to_list.comp fst) (fin_val.comp snd)).of_eq $ λ a, by simp [vector.nth_eq_nth_le]; rw [← list.nth_le_nth] theorem list_of_fn : ∀ {n} {f : fin n → α → σ}, (∀ i, primrec (f i)) → primrec (λ a, list.of_fn (λ i, f i a)) | 0 f hf := const [] | (n+1) f hf := by simp [list.of_fn_succ]; exact list_cons.comp (hf 0) (list_of_fn (λ i, hf i.succ)) theorem vector_of_fn {n} {f : fin n → α → σ} (hf : ∀ i, primrec (f i)) : primrec (λ a, vector.of_fn (λ i, f i a)) := vector_to_list_iff.1 $ by simp [list_of_fn hf] theorem vector_nth' {n} : primrec (@vector.nth α n) := of_equiv_symm theorem vector_of_fn' {n} : primrec (@vector.of_fn α n) := of_equiv theorem fin_app {n} : primrec₂ (@id (fin n → σ)) := (vector_nth.comp (vector_of_fn'.comp fst) snd).of_eq $ λ ⟨v, i⟩, by simp theorem fin_curry₁ {n} {f : fin n → α → σ} : primrec₂ f ↔ ∀ i, primrec (f i) := ⟨λ h i, h.comp (const i) primrec.id, λ h, (vector_nth.comp ((vector_of_fn h).comp snd) fst).of_eq $ λ a, by simp⟩ theorem fin_curry {n} {f : α → fin n → σ} : primrec f ↔ primrec₂ f := ⟨λ h, fin_app.comp (h.comp fst) snd, λ h, (vector_nth'.comp (vector_of_fn (λ i, show primrec (λ a, f a i), from h.comp primrec.id (const i)))).of_eq $ λ a, by funext i; simp⟩ end primrec namespace nat open vector /-- An alternative inductive definition of `primrec` which does not use the pairing function on ℕ, and so has to work with n-ary functions on ℕ instead of unary functions. We prove that this is equivalent to the regular notion in `to_prim` and `of_prim`. -/ inductive primrec' : ∀ {n}, (vector ℕ n → ℕ) → Prop | zero : @primrec' 0 (λ _, 0) | succ : @primrec' 1 (λ v, succ v.head) | nth {n} (i : fin n) : primrec' (λ v, v.nth i) | comp {m n f} (g : fin n → vector ℕ m → ℕ) : primrec' f → (∀ i, primrec' (g i)) → primrec' (λ a, f (of_fn (λ i, g i a))) | prec {n f g} : @primrec' n f → @primrec' (n+2) g → primrec' (λ v : vector ℕ (n+1), v.head.elim (f v.tail) (λ y IH, g (y ::ᵥ IH ::ᵥ v.tail))) end nat namespace nat.primrec' open vector primrec nat (primrec') nat.primrec' hide ite theorem to_prim {n f} (pf : @primrec' n f) : primrec f := begin induction pf, case nat.primrec'.zero { exact const 0 }, case nat.primrec'.succ { exact primrec.succ.comp vector_head }, case nat.primrec'.nth : n i { exact vector_nth.comp primrec.id (const i) }, case nat.primrec'.comp : m n f g _ _ hf hg { exact hf.comp (vector_of_fn (λ i, hg i)) }, case nat.primrec'.prec : n f g _ _ hf hg { exact nat_elim' vector_head (hf.comp vector_tail) (hg.comp $ vector_cons.comp (fst.comp snd) $ vector_cons.comp (snd.comp snd) $ (@vector_tail _ _ (n+1)).comp fst).to₂ }, end theorem of_eq {n} {f g : vector ℕ n → ℕ} (hf : primrec' f) (H : ∀ i, f i = g i) : primrec' g := (funext H : f = g) ▸ hf theorem const {n} : ∀ m, @primrec' n (λ v, m) | 0 := zero.comp fin.elim0 (λ i, i.elim0) | (m+1) := succ.comp _ (λ i, const m) theorem head {n : ℕ} : @primrec' n.succ head := (nth 0).of_eq $ λ v, by simp [nth_zero] theorem tail {n f} (hf : @primrec' n f) : @primrec' n.succ (λ v, f v.tail) := (hf.comp _ (λ i, @nth _ i.succ)).of_eq $ λ v, by rw [← of_fn_nth v.tail]; congr; funext i; simp def vec {n m} (f : vector ℕ n → vector ℕ m) := ∀ i, primrec' (λ v, (f v).nth i) protected theorem nil {n} : @vec n 0 (λ _, nil) := λ i, i.elim0 protected theorem cons {n m f g} (hf : @primrec' n f) (hg : @vec n m g) : vec (λ v, (f v ::ᵥ g v)) := λ i, fin.cases (by simp *) (λ i, by simp [hg i]) i theorem idv {n} : @vec n n id := nth theorem comp' {n m f g} (hf : @primrec' m f) (hg : @vec n m g) : primrec' (λ v, f (g v)) := (hf.comp _ hg).of_eq $ λ v, by simp theorem comp₁ (f : ℕ → ℕ) (hf : @primrec' 1 (λ v, f v.head)) {n g} (hg : @primrec' n g) : primrec' (λ v, f (g v)) := hf.comp _ (λ i, hg) theorem comp₂ (f : ℕ → ℕ → ℕ) (hf : @primrec' 2 (λ v, f v.head v.tail.head)) {n g h} (hg : @primrec' n g) (hh : @primrec' n h) : primrec' (λ v, f (g v) (h v)) := by simpa using hf.comp' (hg.cons $ hh.cons primrec'.nil) theorem prec' {n f g h} (hf : @primrec' n f) (hg : @primrec' n g) (hh : @primrec' (n+2) h) : @primrec' n (λ v, (f v).elim (g v) (λ (y IH : ℕ), h (y ::ᵥ IH ::ᵥ v))) := by simpa using comp' (prec hg hh) (hf.cons idv) theorem pred : @primrec' 1 (λ v, v.head.pred) := (prec' head (const 0) head).of_eq $ λ v, by simp; cases v.head; refl theorem add : @primrec' 2 (λ v, v.head + v.tail.head) := (prec head (succ.comp₁ _ (tail head))).of_eq $ λ v, by simp; induction v.head; simp [*, nat.succ_add] theorem sub : @primrec' 2 (λ v, v.head - v.tail.head) := begin suffices, simpa using comp₂ (λ a b, b - a) this (tail head) head, refine (prec head (pred.comp₁ _ (tail head))).of_eq (λ v, _), simp, induction v.head; simp [*, nat.sub_succ] end theorem mul : @primrec' 2 (λ v, v.head * v.tail.head) := (prec (const 0) (tail (add.comp₂ _ (tail head) (head)))).of_eq $ λ v, by simp; induction v.head; simp [*, nat.succ_mul]; rw add_comm theorem if_lt {n a b f g} (ha : @primrec' n a) (hb : @primrec' n b) (hf : @primrec' n f) (hg : @primrec' n g) : @primrec' n (λ v, if a v < b v then f v else g v) := (prec' (sub.comp₂ _ hb ha) hg (tail $ tail hf)).of_eq $ λ v, begin cases e : b v - a v, { simp [not_lt.2 (tsub_eq_zero_iff_le.mp e)] }, { simp [nat.lt_of_sub_eq_succ e] } end theorem mkpair : @primrec' 2 (λ v, v.head.mkpair v.tail.head) := if_lt head (tail head) (add.comp₂ _ (tail $ mul.comp₂ _ head head) head) (add.comp₂ _ (add.comp₂ _ (mul.comp₂ _ head head) head) (tail head)) protected theorem encode : ∀ {n}, @primrec' n encode | 0 := (const 0).of_eq (λ v, by rw v.eq_nil; refl) | (n+1) := (succ.comp₁ _ (mkpair.comp₂ _ head (tail encode))) .of_eq $ λ ⟨a::l, e⟩, rfl theorem sqrt : @primrec' 1 (λ v, v.head.sqrt) := begin suffices H : ∀ n : ℕ, n.sqrt = n.elim 0 (λ x y, if x.succ < y.succ*y.succ then y else y.succ), { simp [H], have := @prec' 1 _ _ (λ v, by have x := v.head; have y := v.tail.head; from if x.succ < y.succ*y.succ then y else y.succ) head (const 0) _, { convert this, funext, congr, funext x y, congr; simp }, have x1 := succ.comp₁ _ head, have y1 := succ.comp₁ _ (tail head), exact if_lt x1 (mul.comp₂ _ y1 y1) (tail head) y1 }, intro, symmetry, induction n with n IH, {simp}, dsimp, rw IH, split_ifs, { exact le_antisymm (nat.sqrt_le_sqrt (nat.le_succ _)) (nat.lt_succ_iff.1 $ nat.sqrt_lt.2 h) }, { exact nat.eq_sqrt.2 ⟨not_lt.1 h, nat.sqrt_lt.1 $ nat.lt_succ_iff.2 $ nat.sqrt_succ_le_succ_sqrt _⟩ }, end theorem unpair₁ {n f} (hf : @primrec' n f) : @primrec' n (λ v, (f v).unpair.1) := begin have s := sqrt.comp₁ _ hf, have fss := sub.comp₂ _ hf (mul.comp₂ _ s s), refine (if_lt fss s fss s).of_eq (λ v, _), simp [nat.unpair], split_ifs; refl end theorem unpair₂ {n f} (hf : @primrec' n f) : @primrec' n (λ v, (f v).unpair.2) := begin have s := sqrt.comp₁ _ hf, have fss := sub.comp₂ _ hf (mul.comp₂ _ s s), refine (if_lt fss s s (sub.comp₂ _ fss s)).of_eq (λ v, _), simp [nat.unpair], split_ifs; refl end theorem of_prim : ∀ {n f}, primrec f → @primrec' n f := suffices ∀ f, nat.primrec f → @primrec' 1 (λ v, f v.head), from λ n f hf, (pred.comp₁ _ $ (this _ hf).comp₁ (λ m, encodable.encode $ (decode (vector ℕ n) m).map f) primrec'.encode).of_eq (λ i, by simp [encodek]), λ f hf, begin induction hf, case nat.primrec.zero { exact const 0 }, case nat.primrec.succ { exact succ }, case nat.primrec.left { exact unpair₁ head }, case nat.primrec.right { exact unpair₂ head }, case nat.primrec.pair : f g _ _ hf hg { exact mkpair.comp₂ _ hf hg }, case nat.primrec.comp : f g _ _ hf hg { exact hf.comp₁ _ hg }, case nat.primrec.prec : f g _ _ hf hg { simpa using prec' (unpair₂ head) (hf.comp₁ _ (unpair₁ head)) (hg.comp₁ _ $ mkpair.comp₂ _ (unpair₁ $ tail $ tail head) (mkpair.comp₂ _ head (tail head))) }, end theorem prim_iff {n f} : @primrec' n f ↔ primrec f := ⟨to_prim, of_prim⟩ theorem prim_iff₁ {f : ℕ → ℕ} : @primrec' 1 (λ v, f v.head) ↔ primrec f := prim_iff.trans ⟨ λ h, (h.comp $ vector_of_fn $ λ i, primrec.id).of_eq (λ v, by simp), λ h, h.comp vector_head⟩ theorem prim_iff₂ {f : ℕ → ℕ → ℕ} : @primrec' 2 (λ v, f v.head v.tail.head) ↔ primrec₂ f := prim_iff.trans ⟨ λ h, (h.comp $ vector_cons.comp fst $ vector_cons.comp snd (primrec.const nil)).of_eq (λ v, by simp), λ h, h.comp vector_head (vector_head.comp vector_tail)⟩ theorem vec_iff {m n f} : @vec m n f ↔ primrec f := ⟨λ h, by simpa using vector_of_fn (λ i, to_prim (h i)), λ h i, of_prim $ vector_nth.comp h (primrec.const i)⟩ end nat.primrec' theorem primrec.nat_sqrt : primrec nat.sqrt := nat.primrec'.prim_iff₁.1 nat.primrec'.sqrt
ae4f5ea639448f9affa3686e789e1b665cb28d9d
36938939954e91f23dec66a02728db08a7acfcf9
/lean4/tests/Main.lean
19d8ea886af34c38d845dd1a805415528a4f015f
[]
no_license
pnwamk/reopt-vcg
f8b56dd0279392a5e1c6aee721be8138e6b558d3
c9f9f185fbefc25c36c4b506bbc85fd1a03c3b6d
refs/heads/master
1,631,145,017,772
1,593,549,019,000
1,593,549,143,000
254,191,418
0
0
null
1,586,377,077,000
1,586,377,077,000
null
UTF-8
Lean
false
false
908
lean
import Init.Data.RBMap import Test.AnnotationParsing import Test.Hex import Test.JsonRoundtrip import Test.LoadElf import Test.SExp import Test.SMTExport namespace Test def tests : RBMap String (IO UInt32) (λ x y => x < y) := RBMap.fromList [("AnnotationParsing.lean", AnnotationParsing.test), ("Hex.lean", Hex.test), ("JsonRoundtrip.lean", JsonRoundtrip.test), ("LoadElf.lean", LoadElf.test), ("SExp.lean", SExp.test), ("SMTExport.lean", SMTExport.test) ] (λ x y => x < y) end Test def main(args : List String) : IO UInt32 := do match args with | [testFile] => match Test.tests.find? testFile with | Option.none => throw $ IO.userError $ "Test corresponding to file not found: " ++ testFile ++ " (see tests/Main.lean)" | Option.some test => test | _ => throw $ IO.userError $ "Error: expected a single test file name as an argument, but got " ++ args.toString
c5521ae2e9207c6e4f09f4697d2f3a36a087897c
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/monovary.lean
fab9d802a4108cb26c96b352065f84b587c11d88
[ "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
12,016
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.set.basic /-! # Monovariance of functions Two functions *vary together* if a strict change in the first implies a change in the second. This is in some sense a way to say that two functions `f : ι → α`, `g : ι → β` are "monotone together", without actually having an order on `ι`. This condition comes up in the rearrangement inequality. See `algebra.order.rearrangement`. ## Main declarations * `monovary f g`: `f` monovaries with `g`. If `g i < g j`, then `f i ≤ f j`. * `antivary f g`: `f` antivaries with `g`. If `g i < g j`, then `f j ≤ f i`. * `monovary_on f g s`: `f` monovaries with `g` on `s`. * `monovary_on f g s`: `f` antivaries with `g` on `s`. -/ open function set variables {ι ι' α β γ : Type*} section preorder variables [preorder α] [preorder β] [preorder γ] {f : ι → α} {f' : α → γ} {g : ι → β} {g' : β → γ} {s t : set ι} /-- `f` monovaries with `g` if `g i < g j` implies `f i ≤ f j`. -/ def monovary (f : ι → α) (g : ι → β) : Prop := ∀ ⦃i j⦄, g i < g j → f i ≤ f j /-- `f` antivaries with `g` if `g i < g j` implies `f j ≤ f i`. -/ def antivary (f : ι → α) (g : ι → β) : Prop := ∀ ⦃i j⦄, g i < g j → f j ≤ f i /-- `f` monovaries with `g` on `s` if `g i < g j` implies `f i ≤ f j` for all `i, j ∈ s`. -/ def monovary_on (f : ι → α) (g : ι → β) (s : set ι) : Prop := ∀ ⦃i⦄ (hi : i ∈ s) ⦃j⦄ (hj : j ∈ s), g i < g j → f i ≤ f j /-- `f` antivaries with `g` on `s` if `g i < g j` implies `f j ≤ f i` for all `i, j ∈ s`. -/ def antivary_on (f : ι → α) (g : ι → β) (s : set ι) : Prop := ∀ ⦃i⦄ (hi : i ∈ s) ⦃j⦄ (hj : j ∈ s), g i < g j → f j ≤ f i protected lemma monovary.monovary_on (h : monovary f g) (s : set ι) : monovary_on f g s := λ i _ j _ hij, h hij protected lemma antivary.antivary_on (h : antivary f g) (s : set ι) : antivary_on f g s := λ i _ j _ hij, h hij @[simp] lemma monovary_on.empty : monovary_on f g ∅ := λ i, false.elim @[simp] lemma antivary_on.empty : antivary_on f g ∅ := λ i, false.elim @[simp] lemma monovary_on_univ : monovary_on f g univ ↔ monovary f g := ⟨λ h i j, h trivial trivial, λ h i _ j _ hij, h hij⟩ @[simp] lemma antivary_on_univ : antivary_on f g univ ↔ antivary f g := ⟨λ h i j, h trivial trivial, λ h i _ j _ hij, h hij⟩ protected lemma monovary_on.subset (hst : s ⊆ t) (h : monovary_on f g t) : monovary_on f g s := λ i hi j hj, h (hst hi) (hst hj) protected lemma antivary_on.subset (hst : s ⊆ t) (h : antivary_on f g t) : antivary_on f g s := λ i hi j hj, h (hst hi) (hst hj) lemma monovary_const_left (g : ι → β) (a : α) : monovary (const ι a) g := λ i j _, le_rfl lemma antivary_const_left (g : ι → β) (a : α) : antivary (const ι a) g := λ i j _, le_rfl lemma monovary_const_right (f : ι → α) (b : β) : monovary f (const ι b) := λ i j h, (h.ne rfl).elim lemma antivary_const_right (f : ι → α) (b : β) : antivary f (const ι b) := λ i j h, (h.ne rfl).elim lemma monovary_self (f : ι → α) : monovary f f := λ i j, le_of_lt lemma monovary_on_self (f : ι → α) (s : set ι) : monovary_on f f s := λ i _ j _, le_of_lt protected lemma subsingleton.monovary [subsingleton ι] (f : ι → α) (g : ι → β) : monovary f g := λ i j h, (ne_of_apply_ne _ h.ne $ subsingleton.elim _ _).elim protected lemma subsingleton.antivary [subsingleton ι] (f : ι → α) (g : ι → β) : antivary f g := λ i j h, (ne_of_apply_ne _ h.ne $ subsingleton.elim _ _).elim protected lemma subsingleton.monovary_on [subsingleton ι] (f : ι → α) (g : ι → β) (s : set ι) : monovary_on f g s := λ i _ j _ h, (ne_of_apply_ne _ h.ne $ subsingleton.elim _ _).elim protected lemma subsingleton.antivary_on [subsingleton ι] (f : ι → α) (g : ι → β) (s : set ι) : antivary_on f g s := λ i _ j _ h, (ne_of_apply_ne _ h.ne $ subsingleton.elim _ _).elim lemma monovary_on_const_left (g : ι → β) (a : α) (s : set ι) : monovary_on (const ι a) g s := λ i _ j _ _, le_rfl lemma antivary_on_const_left (g : ι → β) (a : α) (s : set ι) : antivary_on (const ι a) g s := λ i _ j _ _, le_rfl lemma monovary_on_const_right (f : ι → α) (b : β) (s : set ι) : monovary_on f (const ι b) s := λ i _ j _ h, (h.ne rfl).elim lemma antivary_on_const_right (f : ι → α) (b : β) (s : set ι) : antivary_on f (const ι b) s := λ i _ j _ h, (h.ne rfl).elim lemma monovary.comp_right (h : monovary f g) (k : ι' → ι) : monovary (f ∘ k) (g ∘ k) := λ i j hij, h hij lemma antivary.comp_right (h : antivary f g) (k : ι' → ι) : antivary (f ∘ k) (g ∘ k) := λ i j hij, h hij lemma monovary_on.comp_right (h : monovary_on f g s) (k : ι' → ι) : monovary_on (f ∘ k) (g ∘ k) (k ⁻¹' s) := λ i hi j hj, h hi hj lemma antivary_on.comp_right (h : antivary_on f g s) (k : ι' → ι) : antivary_on (f ∘ k) (g ∘ k) (k ⁻¹' s) := λ i hi j hj, h hi hj lemma monovary.comp_monotone_left (h : monovary f g) (hf : monotone f') : monovary (f' ∘ f) g := λ i j hij, hf $ h hij lemma monovary.comp_antitone_left (h : monovary f g) (hf : antitone f') : antivary (f' ∘ f) g := λ i j hij, hf $ h hij lemma antivary.comp_monotone_left (h : antivary f g) (hf : monotone f') : antivary (f' ∘ f) g := λ i j hij, hf $ h hij lemma antivary.comp_antitone_left (h : antivary f g) (hf : antitone f') : monovary (f' ∘ f) g := λ i j hij, hf $ h hij lemma monovary_on.comp_monotone_on_left (h : monovary_on f g s) (hf : monotone f') : monovary_on (f' ∘ f) g s := λ i hi j hj hij, hf $ h hi hj hij lemma monovary_on.comp_antitone_on_left (h : monovary_on f g s) (hf : antitone f') : antivary_on (f' ∘ f) g s := λ i hi j hj hij, hf $ h hi hj hij lemma antivary_on.comp_monotone_on_left (h : antivary_on f g s) (hf : monotone f') : antivary_on (f' ∘ f) g s := λ i hi j hj hij, hf $ h hi hj hij lemma antivary_on.comp_antitone_on_left (h : antivary_on f g s) (hf : antitone f') : monovary_on (f' ∘ f) g s := λ i hi j hj hij, hf $ h hi hj hij section order_dual open order_dual lemma monovary.dual : monovary f g → monovary (to_dual ∘ f) (to_dual ∘ g) := swap lemma antivary.dual : antivary f g → antivary (to_dual ∘ f) (to_dual ∘ g) := swap lemma monovary.dual_left : monovary f g → antivary (to_dual ∘ f) g := id lemma antivary.dual_left : antivary f g → monovary (to_dual ∘ f) g := id lemma monovary.dual_right : monovary f g → antivary f (to_dual ∘ g) := swap lemma antivary.dual_right : antivary f g → monovary f (to_dual ∘ g) := swap lemma monovary_on.dual : monovary_on f g s → monovary_on (to_dual ∘ f) (to_dual ∘ g) s := swap₂ lemma antivary_on.dual : antivary_on f g s → antivary_on (to_dual ∘ f) (to_dual ∘ g) s := swap₂ lemma monovary_on.dual_left : monovary_on f g s → antivary_on (to_dual ∘ f) g s := id lemma antivary_on.dual_left : antivary_on f g s → monovary_on (to_dual ∘ f) g s := id lemma monovary_on.dual_right : monovary_on f g s → antivary_on f (to_dual ∘ g) s := swap₂ lemma antivary_on.dual_right : antivary_on f g s → monovary_on f (to_dual ∘ g) s := swap₂ @[simp] lemma monovary_to_dual_left : monovary (to_dual ∘ f) g ↔ antivary f g := iff.rfl @[simp] lemma monovary_to_dual_right : monovary f (to_dual ∘ g) ↔ antivary f g := forall_swap @[simp] lemma antivary_to_dual_left : antivary (to_dual ∘ f) g ↔ monovary f g := iff.rfl @[simp] lemma antivary_to_dual_right : antivary f (to_dual ∘ g) ↔ monovary f g := forall_swap @[simp] lemma monovary_on_to_dual_left : monovary_on (to_dual ∘ f) g s ↔ antivary_on f g s := iff.rfl @[simp] lemma monovary_on_to_dual_right : monovary_on f (to_dual ∘ g) s ↔ antivary_on f g s := forall₂_swap @[simp] lemma antivary_on_to_dual_left : antivary_on (to_dual ∘ f) g s ↔ monovary_on f g s := iff.rfl @[simp] lemma antivary_on_to_dual_right : antivary_on f (to_dual ∘ g) s ↔ monovary_on f g s := forall₂_swap end order_dual section partial_order variables [partial_order ι] @[simp] lemma monovary_id_iff : monovary f id ↔ monotone f := monotone_iff_forall_lt.symm @[simp] lemma antivary_id_iff : antivary f id ↔ antitone f := antitone_iff_forall_lt.symm @[simp] lemma monovary_on_id_iff : monovary_on f id s ↔ monotone_on f s := monotone_on_iff_forall_lt.symm @[simp] lemma antivary_on_id_iff : antivary_on f id s ↔ antitone_on f s := antitone_on_iff_forall_lt.symm end partial_order variables [linear_order ι] protected lemma monotone.monovary (hf : monotone f) (hg : monotone g) : monovary f g := λ i j hij, hf (hg.reflect_lt hij).le protected lemma monotone.antivary (hf : monotone f) (hg : antitone g) : antivary f g := (hf.monovary hg.dual_right).dual_right protected lemma antitone.monovary (hf : antitone f) (hg : antitone g) : monovary f g := (hf.dual_right.antivary hg).dual_left protected lemma antitone.antivary (hf : antitone f) (hg : monotone g) : antivary f g := (hf.monovary hg.dual_right).dual_right protected lemma monotone_on.monovary_on (hf : monotone_on f s) (hg : monotone_on g s) : monovary_on f g s := λ i hi j hj hij, hf hi hj (hg.reflect_lt hi hj hij).le protected lemma monotone_on.antivary_on (hf : monotone_on f s) (hg : antitone_on g s) : antivary_on f g s := (hf.monovary_on hg.dual_right).dual_right protected lemma antitone_on.monovary_on (hf : antitone_on f s) (hg : antitone_on g s) : monovary_on f g s := (hf.dual_right.antivary_on hg).dual_left protected lemma antitone_on.antivary_on (hf : antitone_on f s) (hg : monotone_on g s) : antivary_on f g s := (hf.monovary_on hg.dual_right).dual_right end preorder section linear_order variables [preorder α] [linear_order β] [preorder γ] {f : ι → α} {f' : α → γ} {g : ι → β} {g' : β → γ} {s : set ι} lemma monovary_on.comp_monotone_on_right (h : monovary_on f g s) (hg : monotone_on g' (g '' s)) : monovary_on f (g' ∘ g) s := λ i hi j hj hij, h hi hj $ hg.reflect_lt (mem_image_of_mem _ hi) (mem_image_of_mem _ hj) hij lemma monovary_on.comp_antitone_on_right (h : monovary_on f g s) (hg : antitone_on g' (g '' s)) : antivary_on f (g' ∘ g) s := λ i hi j hj hij, h hj hi $ hg.reflect_lt (mem_image_of_mem _ hi) (mem_image_of_mem _ hj) hij lemma antivary_on.comp_monotone_on_right (h : antivary_on f g s) (hg : monotone_on g' (g '' s)) : antivary_on f (g' ∘ g) s := λ i hi j hj hij, h hi hj $ hg.reflect_lt (mem_image_of_mem _ hi) (mem_image_of_mem _ hj) hij lemma antivary_on.comp_antitone_on_right (h : antivary_on f g s) (hg : antitone_on g' (g '' s)) : monovary_on f (g' ∘ g) s := λ i hi j hj hij, h hj hi $ hg.reflect_lt (mem_image_of_mem _ hi) (mem_image_of_mem _ hj) hij protected lemma monovary.symm (h : monovary f g) : monovary g f := λ i j hf, le_of_not_lt $ λ hg, hf.not_le $ h hg protected lemma antivary.symm (h : antivary f g) : antivary g f := λ i j hf, le_of_not_lt $ λ hg, hf.not_le $ h hg protected lemma monovary_on.symm (h : monovary_on f g s) : monovary_on g f s := λ i hi j hj hf, le_of_not_lt $ λ hg, hf.not_le $ h hj hi hg protected lemma antivary_on.symm (h : antivary_on f g s) : antivary_on g f s := λ i hi j hj hf, le_of_not_lt $ λ hg, hf.not_le $ h hi hj hg end linear_order section linear_order variables [linear_order α] [linear_order β] {f : ι → α} {g : ι → β} {s : set ι} protected lemma monovary_comm : monovary f g ↔ monovary g f := ⟨monovary.symm, monovary.symm⟩ protected lemma antivary_comm : antivary f g ↔ antivary g f := ⟨antivary.symm, antivary.symm⟩ protected lemma monovary_on_comm : monovary_on f g s ↔ monovary_on g f s := ⟨monovary_on.symm, monovary_on.symm⟩ protected lemma antivary_on_comm : antivary_on f g s ↔ antivary_on g f s := ⟨antivary_on.symm, antivary_on.symm⟩ end linear_order
f749d69f0ebdc4069dfcd45a94d63ed2c411a019
94e33a31faa76775069b071adea97e86e218a8ee
/src/measure_theory/probability_mass_function/monad.lean
b7cb1ed08a5e5a196b85ea0948619974b2ca1360
[ "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
14,425
lean
/- Copyright (c) 2020 Devon Tuma. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Devon Tuma -/ import measure_theory.probability_mass_function.basic /-! # Monad Operations for Probability Mass Functions This file constructs two operations on `pmf` that give it a monad structure. `pure a` is the distribution where a single value `a` has probability `1`. `bind pa pb : pmf β` is the distribution given by sampling `a : α` from `pa : pmf α`, and then sampling from `pb a : pmf β` to get a final result `b : β`. `bind_on_support` generalizes `bind` to allow binding to a partial function, so that the second argument only needs to be defined on the support of the first argument. -/ noncomputable theory variables {α β γ : Type*} open_locale classical big_operators nnreal ennreal namespace pmf section pure /-- The pure `pmf` is the `pmf` where all the mass lies in one point. The value of `pure a` is `1` at `a` and `0` elsewhere. -/ def pure (a : α) : pmf α := ⟨λ a', if a' = a then 1 else 0, has_sum_ite_eq _ _⟩ variables (a a' : α) @[simp] lemma pure_apply : pure a a' = (if a' = a then 1 else 0) := rfl @[simp] lemma support_pure : (pure a).support = {a} := set.ext (λ a', by simp [mem_support_iff]) lemma mem_support_pure_iff: a' ∈ (pure a).support ↔ a' = a := by simp instance [inhabited α] : inhabited (pmf α) := ⟨pure default⟩ section measure variable (s : set α) @[simp] lemma to_outer_measure_pure_apply : (pure a).to_outer_measure s = if a ∈ s then 1 else 0 := begin refine (to_outer_measure_apply' (pure a) s).trans _, split_ifs with ha ha, { refine ennreal.coe_eq_one.2 ((tsum_congr (λ b, _)).trans (tsum_ite_eq a 1)), exact ite_eq_left_iff.2 (λ hb, symm (ite_eq_right_iff.2 (λ h, (hb $ h.symm ▸ ha).elim))) }, { refine ennreal.coe_eq_zero.2 ((tsum_congr (λ b, _)).trans (tsum_zero)), exact ite_eq_right_iff.2 (λ hb, ite_eq_right_iff.2 (λ h, (ha $ h ▸ hb).elim)) } end /-- The measure of a set under `pure a` is `1` for sets containing `a` and `0` otherwise -/ @[simp] lemma to_measure_pure_apply [measurable_space α] (hs : measurable_set s) : (pure a).to_measure s = if a ∈ s then 1 else 0 := (to_measure_apply_eq_to_outer_measure_apply (pure a) s hs).trans (to_outer_measure_pure_apply a s) end measure end pure section bind protected lemma bind.summable (p : pmf α) (f : α → pmf β) (b : β) : summable (λ a : α, p a * f a b) := begin refine nnreal.summable_of_le (assume a, _) p.summable_coe, suffices : p a * f a b ≤ p a * 1, { simpa }, exact mul_le_mul_of_nonneg_left ((f a).coe_le_one _) (p a).2 end /-- The monadic bind operation for `pmf`. -/ def bind (p : pmf α) (f : α → pmf β) : pmf β := ⟨λ b, ∑'a, p a * f a b, begin apply ennreal.has_sum_coe.1, simp only [ennreal.coe_tsum (bind.summable p f _)], rw [ennreal.summable.has_sum_iff, ennreal.tsum_comm], simp [ennreal.tsum_mul_left, (ennreal.coe_tsum (f _).summable_coe).symm, (ennreal.coe_tsum p.summable_coe).symm] end⟩ variables (p : pmf α) (f : α → pmf β) (g : β → pmf γ) @[simp] lemma bind_apply (b : β) : p.bind f b = ∑'a, p a * f a b := rfl @[simp] lemma support_bind : (p.bind f).support = {b | ∃ a ∈ p.support, b ∈ (f a).support} := set.ext (λ b, by simp [mem_support_iff, tsum_eq_zero_iff (bind.summable p f b), not_or_distrib]) lemma mem_support_bind_iff (b : β) : b ∈ (p.bind f).support ↔ ∃ a ∈ p.support, b ∈ (f a).support := by simp lemma coe_bind_apply (b : β) : (p.bind f b : ℝ≥0∞) = ∑'a, p a * f a b := eq.trans (ennreal.coe_tsum $ bind.summable p f b) $ by simp @[simp] lemma pure_bind (a : α) (f : α → pmf β) : (pure a).bind f = f a := have ∀ b a', ite (a' = a) 1 0 * f a' b = ite (a' = a) (f a b) 0, from assume b a', by split_ifs; simp; subst h; simp, by ext b; simp [this] @[simp] lemma bind_pure : p.bind pure = p := have ∀ a a', (p a * ite (a' = a) 1 0) = ite (a = a') (p a') 0, from assume a a', begin split_ifs; try { subst a }; try { subst a' }; simp * at * end, by ext b; simp [this] @[simp] lemma bind_bind : (p.bind f).bind g = p.bind (λ a, (f a).bind g) := begin ext1 b, simp only [ennreal.coe_eq_coe.symm, coe_bind_apply, ennreal.tsum_mul_left.symm, ennreal.tsum_mul_right.symm], rw [ennreal.tsum_comm], simp [mul_assoc, mul_left_comm, mul_comm] end lemma bind_comm (p : pmf α) (q : pmf β) (f : α → β → pmf γ) : p.bind (λ a, q.bind (f a)) = q.bind (λ b, p.bind (λ a, f a b)) := begin ext1 b, simp only [ennreal.coe_eq_coe.symm, coe_bind_apply, ennreal.tsum_mul_left.symm, ennreal.tsum_mul_right.symm], rw [ennreal.tsum_comm], simp [mul_assoc, mul_left_comm, mul_comm] end section measure variable (s : set β) @[simp] lemma to_outer_measure_bind_apply : (p.bind f).to_outer_measure s = ∑' (a : α), (p a : ℝ≥0∞) * (f a).to_outer_measure s := calc (p.bind f).to_outer_measure s = ∑' (b : β), if b ∈ s then (↑(∑' (a : α), p a * f a b) : ℝ≥0∞) else 0 : by simp [to_outer_measure_apply, set.indicator_apply] ... = ∑' (b : β), ↑(∑' (a : α), p a * (if b ∈ s then f a b else 0)) : tsum_congr (λ b, by split_ifs; simp) ... = ∑' (b : β) (a : α), ↑(p a * (if b ∈ s then f a b else 0)) : tsum_congr (λ b, ennreal.coe_tsum $ nnreal.summable_of_le (by split_ifs; simp) (bind.summable p f b)) ... = ∑' (a : α) (b : β), ↑(p a) * ↑(if b ∈ s then f a b else 0) : ennreal.tsum_comm.trans (tsum_congr $ λ a, tsum_congr $ λ b, ennreal.coe_mul) ... = ∑' (a : α), ↑(p a) * ∑' (b : β), ↑(if b ∈ s then f a b else 0) : tsum_congr (λ a, ennreal.tsum_mul_left) ... = ∑' (a : α), ↑(p a) * ∑' (b : β), if b ∈ s then ↑(f a b) else (0 : ℝ≥0∞) : tsum_congr (λ a, congr_arg (λ x, ↑(p a) * x) $ tsum_congr (λ b, by split_ifs; refl)) ... = ∑' (a : α), ↑(p a) * (f a).to_outer_measure s : tsum_congr (λ a, by simp only [to_outer_measure_apply, set.indicator_apply]) /-- The measure of a set under `p.bind f` is the sum over `a : α` of the probability of `a` under `p` times the measure of the set under `f a` -/ @[simp] lemma to_measure_bind_apply [measurable_space β] (hs : measurable_set s) : (p.bind f).to_measure s = ∑' (a : α), (p a : ℝ≥0∞) * (f a).to_measure s := (to_measure_apply_eq_to_outer_measure_apply (p.bind f) s hs).trans ((to_outer_measure_bind_apply p f s).trans (tsum_congr (λ a, congr_arg (λ x, p a * x) (to_measure_apply_eq_to_outer_measure_apply (f a) s hs).symm))) end measure end bind instance : monad pmf := { pure := λ A a, pure a, bind := λ A B pa pb, pa.bind pb } section bind_on_support protected lemma bind_on_support.summable (p : pmf α) (f : Π a ∈ p.support, pmf β) (b : β) : summable (λ a : α, p a * if h : p a = 0 then 0 else f a h b) := begin refine nnreal.summable_of_le (assume a, _) p.summable_coe, split_ifs, { refine (mul_zero (p a)).symm ▸ le_of_eq h.symm }, { suffices : p a * f a h b ≤ p a * 1, { simpa }, exact mul_le_mul_of_nonneg_left ((f a h).coe_le_one _) (p a).2 } end /-- Generalized version of `bind` allowing `f` to only be defined on the support of `p`. `p.bind f` is equivalent to `p.bind_on_support (λ a _, f a)`, see `bind_on_support_eq_bind` -/ def bind_on_support (p : pmf α) (f : Π a ∈ p.support, pmf β) : pmf β := ⟨λ b, ∑' a, p a * if h : p a = 0 then 0 else f a h b, ennreal.has_sum_coe.1 begin simp only [ennreal.coe_tsum (bind_on_support.summable p f _)], rw [ennreal.summable.has_sum_iff, ennreal.tsum_comm], simp only [ennreal.coe_mul, ennreal.coe_one, ennreal.tsum_mul_left], have : ∑' (a : α), (p a : ennreal) = 1 := by simp only [←ennreal.coe_tsum p.summable_coe, ennreal.coe_one, tsum_coe], refine trans (tsum_congr (λ a, _)) this, split_ifs with h, { simp [h] }, { simp [← ennreal.coe_tsum (f a h).summable_coe, (f a h).tsum_coe] } end⟩ variables {p : pmf α} (f : Π a ∈ p.support, pmf β) @[simp] lemma bind_on_support_apply (b : β) : p.bind_on_support f b = ∑' a, p a * if h : p a = 0 then 0 else f a h b := rfl @[simp] lemma support_bind_on_support : (p.bind_on_support f).support = {b | ∃ (a : α) (h : a ∈ p.support), b ∈ (f a h).support} := begin refine set.ext (λ b, _), simp only [tsum_eq_zero_iff (bind_on_support.summable p f b), not_or_distrib, mem_support_iff, bind_on_support_apply, ne.def, not_forall, mul_eq_zero], exact ⟨λ hb, let ⟨a, ⟨ha, ha'⟩⟩ := hb in ⟨a, ha, by simpa [ha] using ha'⟩, λ hb, let ⟨a, ha, ha'⟩ := hb in ⟨a, ⟨ha, by simpa [(mem_support_iff _ a).1 ha] using ha'⟩⟩⟩ end lemma mem_support_bind_on_support_iff (b : β) : b ∈ (p.bind_on_support f).support ↔ ∃ (a : α) (h : a ∈ p.support), b ∈ (f a h).support := by simp /-- `bind_on_support` reduces to `bind` if `f` doesn't depend on the additional hypothesis -/ @[simp] lemma bind_on_support_eq_bind (p : pmf α) (f : α → pmf β) : p.bind_on_support (λ a _, f a) = p.bind f := begin ext b, simp only [bind_on_support_apply (λ a _, f a), p.bind_apply f, dite_eq_ite, nnreal.coe_eq, mul_ite, mul_zero], refine congr_arg _ (funext (λ a, _)), split_ifs with h; simp [h], end lemma coe_bind_on_support_apply (b : β) : (p.bind_on_support f b : ℝ≥0∞) = ∑' a, p a * if h : p a = 0 then 0 else f a h b := by simp only [bind_on_support_apply, ennreal.coe_tsum (bind_on_support.summable p f b), dite_cast, ennreal.coe_mul, ennreal.coe_zero] lemma bind_on_support_eq_zero_iff (b : β) : p.bind_on_support f b = 0 ↔ ∀ a (ha : p a ≠ 0), f a ha b = 0 := begin simp only [bind_on_support_apply, tsum_eq_zero_iff (bind_on_support.summable p f b), mul_eq_zero, or_iff_not_imp_left], exact ⟨λ h a ha, trans (dif_neg ha).symm (h a ha), λ h a ha, trans (dif_neg ha) (h a ha)⟩, end @[simp] lemma pure_bind_on_support (a : α) (f : Π (a' : α) (ha : a' ∈ (pure a).support), pmf β) : (pure a).bind_on_support f = f a ((mem_support_pure_iff a a).mpr rfl) := begin refine pmf.ext (λ b, _), simp only [nnreal.coe_eq, bind_on_support_apply, pure_apply], refine trans (tsum_congr (λ a', _)) (tsum_ite_eq a _), by_cases h : (a' = a); simp [h], end lemma bind_on_support_pure (p : pmf α) : p.bind_on_support (λ a _, pure a) = p := by simp only [pmf.bind_pure, pmf.bind_on_support_eq_bind] @[simp] lemma bind_on_support_bind_on_support (p : pmf α) (f : ∀ a ∈ p.support, pmf β) (g : ∀ (b ∈ (p.bind_on_support f).support), pmf γ) : (p.bind_on_support f).bind_on_support g = p.bind_on_support (λ a ha, (f a ha).bind_on_support (λ b hb, g b ((mem_support_bind_on_support_iff f b).mpr ⟨a, ha, hb⟩))) := begin refine pmf.ext (λ a, _), simp only [ennreal.coe_eq_coe.symm, coe_bind_on_support_apply, ← tsum_dite_right, ennreal.tsum_mul_left.symm, ennreal.tsum_mul_right.symm], simp only [ennreal.tsum_eq_zero, ennreal.coe_eq_coe, ennreal.coe_eq_zero, ennreal.coe_zero, dite_eq_left_iff, mul_eq_zero], refine ennreal.tsum_comm.trans (tsum_congr (λ a', tsum_congr (λ b, _))), split_ifs, any_goals { ring1 }, { have := h_1 a', simp [h] at this, contradiction }, { simp [h_2], }, end lemma bind_on_support_comm (p : pmf α) (q : pmf β) (f : ∀ (a ∈ p.support) (b ∈ q.support), pmf γ) : p.bind_on_support (λ a ha, q.bind_on_support (f a ha)) = q.bind_on_support (λ b hb, p.bind_on_support (λ a ha, f a ha b hb)) := begin apply pmf.ext, rintro c, simp only [ennreal.coe_eq_coe.symm, coe_bind_on_support_apply, ← tsum_dite_right, ennreal.tsum_mul_left.symm, ennreal.tsum_mul_right.symm], refine trans (ennreal.tsum_comm) (tsum_congr (λ b, tsum_congr (λ a, _))), split_ifs with h1 h2 h2; ring, end section measure variable (s : set β) @[simp] lemma to_outer_measure_bind_on_support_apply : (p.bind_on_support f).to_outer_measure s = ∑' (a : α), (p a : ℝ≥0) * if h : p a = 0 then 0 else (f a h).to_outer_measure s := let g : α → β → ℝ≥0 := λ a b, if h : p a = 0 then 0 else f a h b in calc (p.bind_on_support f).to_outer_measure s = ∑' (b : β), if b ∈ s then ↑(∑' (a : α), p a * g a b) else 0 : by simp [to_outer_measure_apply, set.indicator_apply] ... = ∑' (b : β), ↑(∑' (a : α), p a * (if b ∈ s then g a b else 0)) : tsum_congr (λ b, by split_ifs; simp) ... = ∑' (b : β) (a : α), ↑(p a * (if b ∈ s then g a b else 0)) : tsum_congr (λ b, ennreal.coe_tsum $ nnreal.summable_of_le (by split_ifs; simp) (bind_on_support.summable p f b)) ... = ∑' (a : α) (b : β), ↑(p a) * ↑(if b ∈ s then g a b else 0) : ennreal.tsum_comm.trans (tsum_congr $ λ a, tsum_congr $ λ b, ennreal.coe_mul) ... = ∑' (a : α), ↑(p a) * ∑' (b : β), ↑(if b ∈ s then g a b else 0) : tsum_congr (λ a, ennreal.tsum_mul_left) ... = ∑' (a : α), ↑(p a) * ∑' (b : β), if b ∈ s then ↑(g a b) else (0 : ℝ≥0∞) : tsum_congr (λ a, congr_arg (λ x, ↑(p a) * x) $ tsum_congr (λ b, by split_ifs; refl)) ... = ∑' (a : α), ↑(p a) * if h : p a = 0 then 0 else (f a h).to_outer_measure s : tsum_congr (λ a, congr_arg (has_mul.mul ↑(p a)) begin split_ifs with h h, { refine ennreal.tsum_eq_zero.mpr (λ x, _), simp only [g, h, dif_pos], apply if_t_t }, { simp only [to_outer_measure_apply, g, h, set.indicator_apply, not_false_iff, dif_neg] } end) /-- The measure of a set under `p.bind_on_support f` is the sum over `a : α` of the probability of `a` under `p` times the measure of the set under `f a _`. The additional if statement is needed since `f` is only a partial function -/ @[simp] lemma to_measure_bind_on_support_apply [measurable_space β] (hs : measurable_set s) : (p.bind_on_support f).to_measure s = ∑' (a : α), (p a : ℝ≥0∞) * if h : p a = 0 then 0 else (f a h).to_measure s := (to_measure_apply_eq_to_outer_measure_apply (p.bind_on_support f) s hs).trans ((to_outer_measure_bind_on_support_apply f s).trans (tsum_congr $ λ a, congr_arg (has_mul.mul ↑(p a)) (congr_arg (dite (p a = 0) (λ _, 0)) $ funext (λ h, symm $ to_measure_apply_eq_to_outer_measure_apply (f a h) s hs)))) end measure end bind_on_support end pmf
048f21f436b7b20e5ed16d32fc502194a6a54548
94e33a31faa76775069b071adea97e86e218a8ee
/src/topology/locally_constant/basic.lean
061d0cad2b9226e24f66ba69a5378033c8658f9d
[ "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
18,062
lean
/- Copyright (c) 2021 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import topology.subset_properties import topology.connected import topology.algebra.monoid import topology.continuous_function.basic import tactic.tfae import tactic.fin_cases /-! # Locally constant functions This file sets up the theory of locally constant function from a topological space to a type. ## Main definitions and constructions * `is_locally_constant f` : a map `f : X → Y` where `X` is a topological space is locally constant if every set in `Y` has an open preimage. * `locally_constant X Y` : the type of locally constant maps from `X` to `Y` * `locally_constant.map` : push-forward of locally constant maps * `locally_constant.comap` : pull-back of locally constant maps -/ variables {X Y Z α : Type*} [topological_space X] open set filter open_locale topological_space /-- A function between topological spaces is locally constant if the preimage of any set is open. -/ def is_locally_constant (f : X → Y) : Prop := ∀ s : set Y, is_open (f ⁻¹' s) namespace is_locally_constant protected lemma tfae (f : X → Y) : tfae [is_locally_constant f, ∀ x, ∀ᶠ x' in 𝓝 x, f x' = f x, ∀ x, is_open {x' | f x' = f x}, ∀ y, is_open (f ⁻¹' {y}), ∀ x, ∃ (U : set X) (hU : is_open U) (hx : x ∈ U), ∀ x' ∈ U, f x' = f x] := begin tfae_have : 1 → 4, from λ h y, h {y}, tfae_have : 4 → 3, from λ h x, h (f x), tfae_have : 3 → 2, from λ h x, is_open.mem_nhds (h x) rfl, tfae_have : 2 → 5, { intros h x, rcases mem_nhds_iff.1 (h x) with ⟨U, eq, hU, hx⟩, exact ⟨U, hU, hx, eq⟩ }, tfae_have : 5 → 1, { intros h s, refine is_open_iff_forall_mem_open.2 (λ x hx, _), rcases h x with ⟨U, hU, hxU, eq⟩, exact ⟨U, λ x' hx', mem_preimage.2 $ (eq x' hx').symm ▸ hx, hU, hxU⟩ }, tfae_finish end @[nontriviality] lemma of_discrete [discrete_topology X] (f : X → Y) : is_locally_constant f := λ s, is_open_discrete _ lemma is_open_fiber {f : X → Y} (hf : is_locally_constant f) (y : Y) : is_open {x | f x = y} := hf {y} lemma is_closed_fiber {f : X → Y} (hf : is_locally_constant f) (y : Y) : is_closed {x | f x = y} := ⟨hf {y}ᶜ⟩ lemma is_clopen_fiber {f : X → Y} (hf : is_locally_constant f) (y : Y) : is_clopen {x | f x = y} := ⟨is_open_fiber hf _, is_closed_fiber hf _⟩ lemma iff_exists_open (f : X → Y) : is_locally_constant f ↔ ∀ x, ∃ (U : set X) (hU : is_open U) (hx : x ∈ U), ∀ x' ∈ U, f x' = f x := (is_locally_constant.tfae f).out 0 4 lemma iff_eventually_eq (f : X → Y) : is_locally_constant f ↔ ∀ x, ∀ᶠ y in 𝓝 x, f y = f x := (is_locally_constant.tfae f).out 0 1 lemma exists_open {f : X → Y} (hf : is_locally_constant f) (x : X) : ∃ (U : set X) (hU : is_open U) (hx : x ∈ U), ∀ x' ∈ U, f x' = f x := (iff_exists_open f).1 hf x protected lemma eventually_eq {f : X → Y} (hf : is_locally_constant f) (x : X) : ∀ᶠ y in 𝓝 x, f y = f x := (iff_eventually_eq f).1 hf x protected lemma continuous [topological_space Y] {f : X → Y} (hf : is_locally_constant f) : continuous f := ⟨λ U hU, hf _⟩ lemma iff_continuous {_ : topological_space Y} [discrete_topology Y] (f : X → Y) : is_locally_constant f ↔ continuous f := ⟨is_locally_constant.continuous, λ h s, h.is_open_preimage s (is_open_discrete _)⟩ lemma iff_continuous_bot (f : X → Y) : is_locally_constant f ↔ @continuous X Y _ ⊥ f := iff_continuous f lemma of_constant (f : X → Y) (h : ∀ x y, f x = f y) : is_locally_constant f := (iff_eventually_eq f).2 $ λ x, eventually_of_forall $ λ x', h _ _ lemma const (y : Y) : is_locally_constant (function.const X y) := of_constant _ $ λ _ _, rfl lemma comp {f : X → Y} (hf : is_locally_constant f) (g : Y → Z) : is_locally_constant (g ∘ f) := λ s, by { rw set.preimage_comp, exact hf _ } lemma prod_mk {Y'} {f : X → Y} {f' : X → Y'} (hf : is_locally_constant f) (hf' : is_locally_constant f') : is_locally_constant (λ x, (f x, f' x)) := (iff_eventually_eq _).2 $ λ x, (hf.eventually_eq x).mp $ (hf'.eventually_eq x).mono $ λ x' hf' hf, prod.ext hf hf' lemma comp₂ {Y₁ Y₂ Z : Type*} {f : X → Y₁} {g : X → Y₂} (hf : is_locally_constant f) (hg : is_locally_constant g) (h : Y₁ → Y₂ → Z) : is_locally_constant (λ x, h (f x) (g x)) := (hf.prod_mk hg).comp (λ x : Y₁ × Y₂, h x.1 x.2) lemma comp_continuous [topological_space Y] {g : Y → Z} {f : X → Y} (hg : is_locally_constant g) (hf : continuous f) : is_locally_constant (g ∘ f) := λ s, by { rw set.preimage_comp, exact hf.is_open_preimage _ (hg _) } /-- A locally constant function is constant on any preconnected set. -/ lemma apply_eq_of_is_preconnected {f : X → Y} (hf : is_locally_constant f) {s : set X} (hs : is_preconnected s) {x y : X} (hx : x ∈ s) (hy : y ∈ s) : f x = f y := begin let U := f ⁻¹' {f y}, suffices : x ∉ Uᶜ, from not_not.1 this, intro hxV, specialize hs U Uᶜ (hf {f y}) (hf {f y}ᶜ) _ ⟨y, ⟨hy, rfl⟩⟩ ⟨x, ⟨hx, hxV⟩⟩, { simp only [union_compl_self, subset_univ] }, { simpa only [inter_empty, not_nonempty_empty, inter_compl_self] using hs } end lemma iff_is_const [preconnected_space X] {f : X → Y} : is_locally_constant f ↔ ∀ x y, f x = f y := ⟨λ h x y, h.apply_eq_of_is_preconnected is_preconnected_univ trivial trivial, of_constant _⟩ lemma range_finite [compact_space X] {f : X → Y} (hf : is_locally_constant f) : (set.range f).finite := begin letI : topological_space Y := ⊥, haveI : discrete_topology Y := ⟨rfl⟩, rw @iff_continuous X Y ‹_› ‹_› at hf, exact (is_compact_range hf).finite_of_discrete end @[to_additive] lemma one [has_one Y] : is_locally_constant (1 : X → Y) := const 1 @[to_additive] lemma inv [has_inv Y] ⦃f : X → Y⦄ (hf : is_locally_constant f) : is_locally_constant f⁻¹ := hf.comp (λ x, x⁻¹) @[to_additive] lemma mul [has_mul Y] ⦃f g : X → Y⦄ (hf : is_locally_constant f) (hg : is_locally_constant g) : is_locally_constant (f * g) := hf.comp₂ hg (*) @[to_additive] lemma div [has_div Y] ⦃f g : X → Y⦄ (hf : is_locally_constant f) (hg : is_locally_constant g) : is_locally_constant (f / g) := hf.comp₂ hg (/) /-- If a composition of a function `f` followed by an injection `g` is locally constant, then the locally constant property descends to `f`. -/ lemma desc {α β : Type*} (f : X → α) (g : α → β) (h : is_locally_constant (g ∘ f)) (inj : function.injective g) : is_locally_constant f := begin rw (is_locally_constant.tfae f).out 0 3, intros a, have : f ⁻¹' {a} = (g ∘ f) ⁻¹' { g a }, { ext x, simp only [mem_singleton_iff, function.comp_app, mem_preimage], exact ⟨λ h, by rw h, λ h, inj h⟩ }, rw this, apply h, end end is_locally_constant /-- A (bundled) locally constant function from a topological space `X` to a type `Y`. -/ structure locally_constant (X Y : Type*) [topological_space X] := (to_fun : X → Y) (is_locally_constant : is_locally_constant to_fun) namespace locally_constant instance [inhabited Y] : inhabited (locally_constant X Y) := ⟨⟨_, is_locally_constant.const default⟩⟩ instance : has_coe_to_fun (locally_constant X Y) (λ _, X → Y) := ⟨locally_constant.to_fun⟩ initialize_simps_projections locally_constant (to_fun → apply) @[simp] lemma to_fun_eq_coe (f : locally_constant X Y) : f.to_fun = f := rfl @[simp] lemma coe_mk (f : X → Y) (h) : ⇑(⟨f, h⟩ : locally_constant X Y) = f := rfl theorem congr_fun {f g : locally_constant X Y} (h : f = g) (x : X) : f x = g x := congr_arg (λ h : locally_constant X Y, h x) h theorem congr_arg (f : locally_constant X Y) {x y : X} (h : x = y) : f x = f y := congr_arg (λ x : X, f x) h theorem coe_injective : @function.injective (locally_constant X Y) (X → Y) coe_fn | ⟨f, hf⟩ ⟨g, hg⟩ h := have f = g, from h, by subst f @[simp, norm_cast] theorem coe_inj {f g : locally_constant X Y} : (f : X → Y) = g ↔ f = g := coe_injective.eq_iff @[ext] theorem ext ⦃f g : locally_constant X Y⦄ (h : ∀ x, f x = g x) : f = g := coe_injective (funext h) theorem ext_iff {f g : locally_constant X Y} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ section codomain_topological_space variables [topological_space Y] (f : locally_constant X Y) protected lemma continuous : continuous f := f.is_locally_constant.continuous /-- We can turn a locally-constant function into a bundled `continuous_map`. -/ def to_continuous_map : C(X, Y) := ⟨f, f.continuous⟩ /-- As a shorthand, `locally_constant.to_continuous_map` is available as a coercion -/ instance : has_coe (locally_constant X Y) C(X, Y) := ⟨to_continuous_map⟩ @[simp] lemma to_continuous_map_eq_coe : f.to_continuous_map = f := rfl @[simp] lemma coe_continuous_map : ((f : C(X, Y)) : X → Y) = (f : X → Y) := rfl lemma to_continuous_map_injective : function.injective (to_continuous_map : locally_constant X Y → C(X, Y)) := λ _ _ h, ext (continuous_map.congr_fun h) end codomain_topological_space /-- The constant locally constant function on `X` with value `y : Y`. -/ def const (X : Type*) {Y : Type*} [topological_space X] (y : Y) : locally_constant X Y := ⟨function.const X y, is_locally_constant.const _⟩ @[simp] lemma coe_const (y : Y) : (const X y : X → Y) = function.const X y := rfl /-- The locally constant function to `fin 2` associated to a clopen set. -/ def of_clopen {X : Type*} [topological_space X] {U : set X} [∀ x, decidable (x ∈ U)] (hU : is_clopen U) : locally_constant X (fin 2) := { to_fun := λ x, if x ∈ U then 0 else 1, is_locally_constant := begin rw (is_locally_constant.tfae (λ x, if x ∈ U then (0 : fin 2) else 1)).out 0 3, intros e, fin_cases e, { convert hU.1 using 1, ext, simp only [nat.one_ne_zero, mem_singleton_iff, fin.one_eq_zero_iff, mem_preimage, ite_eq_left_iff], tauto }, { rw ← is_closed_compl_iff, convert hU.2, ext, simp } end } @[simp] lemma of_clopen_fiber_zero {X : Type*} [topological_space X] {U : set X} [∀ x, decidable (x ∈ U)] (hU : is_clopen U) : of_clopen hU ⁻¹' ({0} : set (fin 2)) = U := begin ext, simp only [of_clopen, nat.one_ne_zero, mem_singleton_iff, fin.one_eq_zero_iff, coe_mk, mem_preimage, ite_eq_left_iff], tauto, end @[simp] lemma of_clopen_fiber_one {X : Type*} [topological_space X] {U : set X} [∀ x, decidable (x ∈ U)] (hU : is_clopen U) : of_clopen hU ⁻¹' ({1} : set (fin 2)) = Uᶜ := begin ext, simp only [of_clopen, nat.one_ne_zero, mem_singleton_iff, coe_mk, fin.zero_eq_one_iff, mem_preimage, ite_eq_right_iff, mem_compl_eq], tauto, end lemma locally_constant_eq_of_fiber_zero_eq {X : Type*} [topological_space X] (f g : locally_constant X (fin 2)) (h : f ⁻¹' ({0} : set (fin 2)) = g ⁻¹' {0}) : f = g := begin simp only [set.ext_iff, mem_singleton_iff, mem_preimage] at h, ext1 x, exact fin.fin_two_eq_of_eq_zero_iff (h x) end lemma range_finite [compact_space X] (f : locally_constant X Y) : (set.range f).finite := f.is_locally_constant.range_finite lemma apply_eq_of_is_preconnected (f : locally_constant X Y) {s : set X} (hs : is_preconnected s) {x y : X} (hx : x ∈ s) (hy : y ∈ s) : f x = f y := f.is_locally_constant.apply_eq_of_is_preconnected hs hx hy lemma apply_eq_of_preconnected_space [preconnected_space X] (f : locally_constant X Y) (x y : X) : f x = f y := f.is_locally_constant.apply_eq_of_is_preconnected is_preconnected_univ trivial trivial lemma eq_const [preconnected_space X] (f : locally_constant X Y) (x : X) : f = const X (f x) := ext $ λ y, apply_eq_of_preconnected_space f _ _ lemma exists_eq_const [preconnected_space X] [nonempty Y] (f : locally_constant X Y) : ∃ y, f = const X y := begin rcases classical.em (nonempty X) with ⟨⟨x⟩⟩|hX, { exact ⟨f x, f.eq_const x⟩ }, { exact ⟨classical.arbitrary Y, ext $ λ x, (hX ⟨x⟩).elim⟩ } end /-- Push forward of locally constant maps under any map, by post-composition. -/ def map (f : Y → Z) : locally_constant X Y → locally_constant X Z := λ g, ⟨f ∘ g, λ s, by { rw set.preimage_comp, apply g.is_locally_constant }⟩ @[simp] lemma map_apply (f : Y → Z) (g : locally_constant X Y) : ⇑(map f g) = f ∘ g := rfl @[simp] lemma map_id : @map X Y Y _ id = id := by { ext, refl } @[simp] lemma map_comp {Y₁ Y₂ Y₃ : Type*} (g : Y₂ → Y₃) (f : Y₁ → Y₂) : @map X _ _ _ g ∘ map f = map (g ∘ f) := by { ext, refl } /-- Given a locally constant function to `α → β`, construct a family of locally constant functions with values in β indexed by α. -/ def flip {X α β : Type*} [topological_space X] (f : locally_constant X (α → β)) (a : α) : locally_constant X β := f.map (λ f, f a) /-- If α is finite, this constructs a locally constant function to `α → β` given a family of locally constant functions with values in β indexed by α. -/ def unflip {X α β : Type*} [fintype α] [topological_space X] (f : α → locally_constant X β) : locally_constant X (α → β) := { to_fun := λ x a, f a x, is_locally_constant := begin rw (is_locally_constant.tfae (λ x a, f a x)).out 0 3, intros g, have : (λ (x : X) (a : α), f a x) ⁻¹' {g} = ⋂ (a : α), (f a) ⁻¹' {g a}, by tidy, rw this, apply is_open_Inter, intros a, apply (f a).is_locally_constant, end } @[simp] lemma unflip_flip {X α β : Type*} [fintype α] [topological_space X] (f : locally_constant X (α → β)) : unflip f.flip = f := by { ext, refl } @[simp] lemma flip_unflip {X α β : Type*} [fintype α] [topological_space X] (f : α → locally_constant X β) : (unflip f).flip = f := by { ext, refl } section comap open_locale classical variables [topological_space Y] /-- Pull back of locally constant maps under any map, by pre-composition. This definition only makes sense if `f` is continuous, in which case it sends locally constant functions to their precomposition with `f`. See also `locally_constant.coe_comap`. -/ noncomputable def comap (f : X → Y) : locally_constant Y Z → locally_constant X Z := if hf : continuous f then λ g, ⟨g ∘ f, g.is_locally_constant.comp_continuous hf⟩ else begin by_cases H : nonempty X, { introsI g, exact const X (g $ f $ classical.arbitrary X) }, { intro g, refine ⟨λ x, (H ⟨x⟩).elim, _⟩, intro s, rw is_open_iff_nhds, intro x, exact (H ⟨x⟩).elim } end @[simp] lemma coe_comap (f : X → Y) (g : locally_constant Y Z) (hf : continuous f) : ⇑(comap f g) = g ∘ f := by { rw [comap, dif_pos hf], refl } @[simp] lemma comap_id : @comap X X Z _ _ id = id := by { ext, simp only [continuous_id, id.def, function.comp.right_id, coe_comap] } lemma comap_comp [topological_space Z] (f : X → Y) (g : Y → Z) (hf : continuous f) (hg : continuous g) : @comap _ _ α _ _ f ∘ comap g = comap (g ∘ f) := by { ext, simp only [hf, hg, hg.comp hf, coe_comap] } lemma comap_const (f : X → Y) (y : Y) (h : ∀ x, f x = y) : (comap f : locally_constant Y Z → locally_constant X Z) = λ g, ⟨λ x, g y, is_locally_constant.const _⟩ := begin ext, rw coe_comap, { simp only [h, coe_mk, function.comp_app] }, { rw show f = λ x, y, by ext; apply h, exact continuous_const } end end comap section desc /-- If a locally constant function factors through an injection, then it factors through a locally constant function. -/ def desc {X α β : Type*} [topological_space X] {g : α → β} (f : X → α) (h : locally_constant X β) (cond : g ∘ f = h) (inj : function.injective g) : locally_constant X α := { to_fun := f, is_locally_constant := is_locally_constant.desc _ g (by { rw cond, exact h.2 }) inj } @[simp] lemma coe_desc {X α β : Type*} [topological_space X] (f : X → α) (g : α → β) (h : locally_constant X β) (cond : g ∘ f = h) (inj : function.injective g) : ⇑(desc f h cond inj) = f := rfl end desc section indicator variables {R : Type*} [has_one R] {U : set X} (f : locally_constant X R) open_locale classical /-- Given a clopen set `U` and a locally constant function `f`, `locally_constant.mul_indicator` returns the locally constant function that is `f` on `U` and `1` otherwise. -/ @[to_additive /-" Given a clopen set `U` and a locally constant function `f`, `locally_constant.indicator` returns the locally constant function that is `f` on `U` and `0` otherwise. "-/, simps] noncomputable def mul_indicator (hU : is_clopen U) : locally_constant X R := { to_fun := set.mul_indicator U f, is_locally_constant := begin rw is_locally_constant.iff_exists_open, rintros x, obtain ⟨V, hV, hx, h'⟩ := (is_locally_constant.iff_exists_open _).1 f.is_locally_constant x, by_cases x ∈ U, { refine ⟨U ∩ V, is_open.inter hU.1 hV, set.mem_inter h hx, _⟩, rintros y hy, rw set.mem_inter_iff at hy, rw [set.mul_indicator_of_mem hy.1, set.mul_indicator_of_mem h], apply h' y hy.2, }, { rw ←set.mem_compl_iff at h, refine ⟨Uᶜ, (is_clopen.compl hU).1, h, _⟩, rintros y hy, rw set.mem_compl_iff at h, rw set.mem_compl_iff at hy, simp [h, hy], }, end, } variables (a : X) @[to_additive] theorem mul_indicator_apply_eq_if (hU : is_clopen U) : mul_indicator f hU a = if a ∈ U then f a else 1 := set.mul_indicator_apply U f a variables {a} @[to_additive] theorem mul_indicator_of_mem (hU : is_clopen U) (h : a ∈ U) : f.mul_indicator hU a = f a := by{ rw mul_indicator_apply, apply set.mul_indicator_of_mem h, } @[to_additive] theorem mul_indicator_of_not_mem (hU : is_clopen U) (h : a ∉ U) : f.mul_indicator hU a = 1 := by{ rw mul_indicator_apply, apply set.mul_indicator_of_not_mem h, } end indicator end locally_constant
c698b5011700f31bcaed52fb35ede41ea2cce7b1
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/run/pack_unpack3.lean
16a2b4da9b2352b8ba7cc746187501de21446044
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
997
lean
inductive {u} vec (A : Type u) : nat -> Type u | vnil : vec 0 | vcons : Pi (n : nat), A -> vec n -> vec (n+1) inductive {u} tree (A : Type u) : Type u | leaf : A -> tree | node : Pi (n : nat), vec (list (list tree)) n -> tree -- set_option trace.eqn_compiler true constant {u} P {A : Type u} : tree A → Type constant {u} mk1 {A : Type u} (a : A) : P (tree.leaf a) constant {u} mk2 {A : Type u} (n : nat) (xs : vec (list (list (tree A))) n) : P (tree.node n xs) noncomputable definition {u} bla {A : Type u} : ∀ n : tree A, P n | (tree.leaf a) := mk1 a | (tree.node n xs) := mk2 n xs check bla._main.equations._eqn_1 check bla._main.equations._eqn_2 definition {u} foo {A : Type u} : nat → tree A → nat | 0 _ := sorry | (n+1) (tree.leaf a) := 0 | (n+1) (tree.node m xs) := foo n (tree.node m xs) check @foo._main.equations._eqn_1 check @foo._main.equations._eqn_2 check @foo._main.equations._eqn_3
78a0451e1e0ae4357dc09e2d356e4e35b26fd31a
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/probability_theory/integration.lean
08d0ffff2d9ca0dafe911e17e4d43bacea584cf7
[ "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
6,059
lean
/- Copyright (c) 2021 Martin Zinkevich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Martin Zinkevich -/ import measure_theory.integral.lebesgue import probability_theory.independence /-! # Integration in Probability Theory Integration results for independent random variables. Specifically, for two independent random variables X and Y over the extended non-negative reals, `E[X * Y] = E[X] * E[Y]`, and similar results. ## Implementation notes Many lemmas in this file take two arguments of the same typeclass. It is worth remembering that lean will always pick the later typeclass in this situation, and does not care whether the arguments are `[]`, `{}`, or `()`. All of these use the `measurable_space` `M2` to define `μ`: ```lean example {M1 : measurable_space α} [M2 : measurable_space α] {μ : measure α} : sorry := sorry example [M1 : measurable_space α] {M2 : measurable_space α} {μ : measure α} : sorry := sorry ``` -/ noncomputable theory open set measure_theory open_locale ennreal variables {α : Type*} namespace probability_theory /-- This (roughly) proves that if a random variable `f` is independent of an event `T`, then if you restrict the random variable to `T`, then `E[f * indicator T c 0]=E[f] * E[indicator T c 0]`. It is useful for `lintegral_mul_eq_lintegral_mul_lintegral_of_independent_measurable_space`. -/ lemma lintegral_mul_indicator_eq_lintegral_mul_lintegral_indicator {Mf : measurable_space α} [M : measurable_space α] {μ : measure α} (hMf : Mf ≤ M) (c : ℝ≥0∞) {T : set α} (h_meas_T : measurable_set T) (h_ind : indep_sets Mf.measurable_set' {T} μ) {f : α → ℝ≥0∞} (h_meas_f : @measurable α ℝ≥0∞ Mf _ f) : ∫⁻ a, f a * T.indicator (λ _, c) a ∂μ = ∫⁻ a, f a ∂μ * ∫⁻ a, T.indicator (λ _, c) a ∂μ := begin revert f, have h_mul_indicator : ∀ g, measurable g → measurable (λ a, g a * T.indicator (λ x, c) a), from λ g h_mg, h_mg.mul (measurable_const.indicator h_meas_T), apply measurable.ennreal_induction, { intros c' s' h_meas_s', simp_rw [← inter_indicator_mul], rw [lintegral_indicator _ (measurable_set.inter (hMf _ h_meas_s') (h_meas_T)), lintegral_indicator _ (hMf _ h_meas_s'), lintegral_indicator _ h_meas_T], simp only [measurable_const, lintegral_const, univ_inter, lintegral_const_mul, measurable_set.univ, measure.restrict_apply], ring_nf, congr, rw [mul_comm, h_ind s' T h_meas_s' (set.mem_singleton _)], }, { intros f' g h_univ h_meas_f' h_meas_g h_ind_f' h_ind_g, have h_measM_f' : measurable f', from h_meas_f'.mono hMf le_rfl, have h_measM_g : measurable g, from h_meas_g.mono hMf le_rfl, simp_rw [pi.add_apply, right_distrib], rw [lintegral_add (h_mul_indicator _ h_measM_f') (h_mul_indicator _ h_measM_g), lintegral_add h_measM_f' h_measM_g, right_distrib, h_ind_f', h_ind_g] }, { intros f h_meas_f h_mono_f h_ind_f, have h_measM_f : ∀ n, measurable (f n), from λ n, (h_meas_f n).mono hMf le_rfl, simp_rw [ennreal.supr_mul], rw [lintegral_supr h_measM_f h_mono_f, lintegral_supr, ennreal.supr_mul], { simp_rw [← h_ind_f] }, { exact λ n, h_mul_indicator _ (h_measM_f n) }, { exact λ m n h_le a, ennreal.mul_le_mul (h_mono_f h_le a) le_rfl, }, }, end /-- This (roughly) proves that if `f` and `g` are independent random variables, then `E[f * g] = E[f] * E[g]`. However, instead of directly using the independence of the random variables, it uses the independence of measurable spaces for the domains of `f` and `g`. This is similar to the sigma-algebra approach to independence. See `lintegral_mul_eq_lintegral_mul_lintegral_of_independent_fn` for a more common variant of the product of independent variables. -/ lemma lintegral_mul_eq_lintegral_mul_lintegral_of_independent_measurable_space {Mf Mg : measurable_space α} [M : measurable_space α] {μ : measure α} (hMf : Mf ≤ M) (hMg : Mg ≤ M) (h_ind : indep Mf Mg μ) {f g : α → ℝ≥0∞} (h_meas_f : @measurable α ℝ≥0∞ Mf _ f) (h_meas_g : @measurable α ℝ≥0∞ Mg _ g) : ∫⁻ a, f a * g a ∂μ = ∫⁻ a, f a ∂μ * ∫⁻ a, g a ∂μ := begin revert g, have h_measM_f : measurable f, from h_meas_f.mono hMf le_rfl, apply measurable.ennreal_induction, { intros c s h_s, apply lintegral_mul_indicator_eq_lintegral_mul_lintegral_indicator hMf _ (hMg _ h_s) _ h_meas_f, apply indep_sets_of_indep_sets_of_le_right h_ind, rwa singleton_subset_iff, }, { intros f' g h_univ h_measMg_f' h_measMg_g h_ind_f' h_ind_g', have h_measM_f' : measurable f', from h_measMg_f'.mono hMg le_rfl, have h_measM_g : measurable g, from h_measMg_g.mono hMg le_rfl, simp_rw [pi.add_apply, left_distrib], rw [lintegral_add h_measM_f' h_measM_g, lintegral_add (h_measM_f.mul h_measM_f') (h_measM_f.mul h_measM_g), left_distrib, h_ind_f', h_ind_g'] }, { intros f' h_meas_f' h_mono_f' h_ind_f', have h_measM_f' : ∀ n, measurable (f' n), from λ n, (h_meas_f' n).mono hMg le_rfl, simp_rw [ennreal.mul_supr], rw [lintegral_supr, lintegral_supr h_measM_f' h_mono_f', ennreal.mul_supr], { simp_rw [← h_ind_f'], }, { exact λ n, h_measM_f.mul (h_measM_f' n), }, { exact λ n m (h_le : n ≤ m) a, ennreal.mul_le_mul le_rfl (h_mono_f' h_le a), }, } end /-- This proves that if `f` and `g` are independent random variables, then `E[f * g] = E[f] * E[g]`. -/ lemma lintegral_mul_eq_lintegral_mul_lintegral_of_indep_fun [measurable_space α] {μ : measure α} {f g : α → ℝ≥0∞} (h_meas_f : measurable f) (h_meas_g : measurable g) (h_indep_fun : indep_fun f g μ) : ∫⁻ a, (f * g) a ∂μ = ∫⁻ a, f a ∂μ * ∫⁻ a, g a ∂μ := lintegral_mul_eq_lintegral_mul_lintegral_of_independent_measurable_space (measurable_iff_comap_le.1 h_meas_f) (measurable_iff_comap_le.1 h_meas_g) h_indep_fun (measurable.of_comap_le le_rfl) (measurable.of_comap_le le_rfl) end probability_theory
69bd5f731e3568a3d1e405bd05283aa6d97021a0
3dc4623269159d02a444fe898d33e8c7e7e9461b
/.github/workflows/geo/src/binary_products.lean
432ee0e4c08feeef1f1f464fc3963b4eb7638520
[]
no_license
Or7ando/lean
cc003e6c41048eae7c34aa6bada51c9e9add9e66
d41169cf4e416a0d42092fb6bdc14131cee9dd15
refs/heads/master
1,650,600,589,722
1,587,262,906,000
1,587,262,906,000
255,387,160
0
0
null
null
null
null
UTF-8
Lean
false
false
1,850
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.shapes.binary_products universes v u open category_theory category_theory.category category_theory.limits namespace category_theory variables {C : Type u} [𝒞 : category.{v} C] include 𝒞 variables [has_binary_products.{v} C] local attribute [tidy] tactic.case_bash @[simps] def prod_functor : C ⥤ C ⥤ C := { obj := λ X, { obj := λ Y, X ⨯ Y, map := λ Y Z, limits.prod.map (𝟙 X) }, map := λ Y Z f, { app := λ T, limits.prod.map f (𝟙 T) }} @[simp] lemma prod_left_def {X Y : C} : limit.π (pair X Y) walking_pair.left = limits.prod.fst := rfl @[simp] lemma prod_right_def {X Y : C} : limit.π (pair X Y) walking_pair.right = limits.prod.snd := rfl lemma prod.hom_ext {A X Y : C} {a b : A ⟶ X ⨯ Y} (h1 : a ≫ limits.prod.fst = b ≫ limits.prod.fst) (h2 : a ≫ limits.prod.snd = b ≫ limits.prod.snd) : a = b := begin apply limit.hom_ext, rintros (_ | _), simpa, simpa end lemma prod_map_comm {A B X Y : C} (f : A ⟶ B) (g : X ⟶ Y) : limits.prod.map (𝟙 _) f ≫ limits.prod.map g (𝟙 _) = limits.prod.map g (𝟙 _) ≫ limits.prod.map (𝟙 _) f := begin apply prod.hom_ext, simp, erw id_comp, erw comp_id, simp, erw id_comp, erw comp_id end lemma prod_functorial {X Y Z W : C} (f : X ⟶ Y) (g : Y ⟶ Z) : limits.prod.map (f ≫ g) (𝟙 W) = limits.prod.map f (𝟙 W) ≫ limits.prod.map g (𝟙 W) := begin apply prod.hom_ext, simp, simp, dsimp, simp end lemma prod_functorial' {X Y Z W : C} (f : X ⟶ Y) (g : Y ⟶ Z) : limits.prod.map (𝟙 W) (f ≫ g) = limits.prod.map (𝟙 W) f ≫ limits.prod.map (𝟙 W) g := begin apply prod.hom_ext, simp, dsimp, simp, simp end end category_theory
aa03759ecdda87f15ec787756fac4df2d9fde042
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/LeftBinaryInverse.lean
eea4c7f15d13eadb2b6bf22eb5afcc858e59f574
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
9,084
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section LeftBinaryInverse structure LeftBinaryInverse (A : Type) : Type := (linv : (A → (A → A))) (rinv : (A → (A → A))) (leftInverse : (∀ {x y : A} , (rinv (linv x y) x) = y)) open LeftBinaryInverse structure Sig (AS : Type) : Type := (linvS : (AS → (AS → AS))) (rinvS : (AS → (AS → AS))) structure Product (A : Type) : Type := (linvP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (rinvP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (leftInverseP : (∀ {xP yP : (Prod A A)} , (rinvP (linvP xP yP) xP) = yP)) structure Hom {A1 : Type} {A2 : Type} (Le1 : (LeftBinaryInverse A1)) (Le2 : (LeftBinaryInverse A2)) : Type := (hom : (A1 → A2)) (pres_linv : (∀ {x1 x2 : A1} , (hom ((linv Le1) x1 x2)) = ((linv Le2) (hom x1) (hom x2)))) (pres_rinv : (∀ {x1 x2 : A1} , (hom ((rinv Le1) x1 x2)) = ((rinv Le2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (Le1 : (LeftBinaryInverse A1)) (Le2 : (LeftBinaryInverse A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_linv : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((linv Le1) x1 x2) ((linv Le2) y1 y2)))))) (interp_rinv : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((rinv Le1) x1 x2) ((rinv Le2) y1 y2)))))) inductive LeftBinaryInverseTerm : Type | linvL : (LeftBinaryInverseTerm → (LeftBinaryInverseTerm → LeftBinaryInverseTerm)) | rinvL : (LeftBinaryInverseTerm → (LeftBinaryInverseTerm → LeftBinaryInverseTerm)) open LeftBinaryInverseTerm inductive ClLeftBinaryInverseTerm (A : Type) : Type | sing : (A → ClLeftBinaryInverseTerm) | linvCl : (ClLeftBinaryInverseTerm → (ClLeftBinaryInverseTerm → ClLeftBinaryInverseTerm)) | rinvCl : (ClLeftBinaryInverseTerm → (ClLeftBinaryInverseTerm → ClLeftBinaryInverseTerm)) open ClLeftBinaryInverseTerm inductive OpLeftBinaryInverseTerm (n : ℕ) : Type | v : ((fin n) → OpLeftBinaryInverseTerm) | linvOL : (OpLeftBinaryInverseTerm → (OpLeftBinaryInverseTerm → OpLeftBinaryInverseTerm)) | rinvOL : (OpLeftBinaryInverseTerm → (OpLeftBinaryInverseTerm → OpLeftBinaryInverseTerm)) open OpLeftBinaryInverseTerm inductive OpLeftBinaryInverseTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpLeftBinaryInverseTerm2) | sing2 : (A → OpLeftBinaryInverseTerm2) | linvOL2 : (OpLeftBinaryInverseTerm2 → (OpLeftBinaryInverseTerm2 → OpLeftBinaryInverseTerm2)) | rinvOL2 : (OpLeftBinaryInverseTerm2 → (OpLeftBinaryInverseTerm2 → OpLeftBinaryInverseTerm2)) open OpLeftBinaryInverseTerm2 def simplifyCl {A : Type} : ((ClLeftBinaryInverseTerm A) → (ClLeftBinaryInverseTerm A)) | (linvCl x1 x2) := (linvCl (simplifyCl x1) (simplifyCl x2)) | (rinvCl x1 x2) := (rinvCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpLeftBinaryInverseTerm n) → (OpLeftBinaryInverseTerm n)) | (linvOL x1 x2) := (linvOL (simplifyOpB x1) (simplifyOpB x2)) | (rinvOL x1 x2) := (rinvOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpLeftBinaryInverseTerm2 n A) → (OpLeftBinaryInverseTerm2 n A)) | (linvOL2 x1 x2) := (linvOL2 (simplifyOp x1) (simplifyOp x2)) | (rinvOL2 x1 x2) := (rinvOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((LeftBinaryInverse A) → (LeftBinaryInverseTerm → A)) | Le (linvL x1 x2) := ((linv Le) (evalB Le x1) (evalB Le x2)) | Le (rinvL x1 x2) := ((rinv Le) (evalB Le x1) (evalB Le x2)) def evalCl {A : Type} : ((LeftBinaryInverse A) → ((ClLeftBinaryInverseTerm A) → A)) | Le (sing x1) := x1 | Le (linvCl x1 x2) := ((linv Le) (evalCl Le x1) (evalCl Le x2)) | Le (rinvCl x1 x2) := ((rinv Le) (evalCl Le x1) (evalCl Le x2)) def evalOpB {A : Type} {n : ℕ} : ((LeftBinaryInverse A) → ((vector A n) → ((OpLeftBinaryInverseTerm n) → A))) | Le vars (v x1) := (nth vars x1) | Le vars (linvOL x1 x2) := ((linv Le) (evalOpB Le vars x1) (evalOpB Le vars x2)) | Le vars (rinvOL x1 x2) := ((rinv Le) (evalOpB Le vars x1) (evalOpB Le vars x2)) def evalOp {A : Type} {n : ℕ} : ((LeftBinaryInverse A) → ((vector A n) → ((OpLeftBinaryInverseTerm2 n A) → A))) | Le vars (v2 x1) := (nth vars x1) | Le vars (sing2 x1) := x1 | Le vars (linvOL2 x1 x2) := ((linv Le) (evalOp Le vars x1) (evalOp Le vars x2)) | Le vars (rinvOL2 x1 x2) := ((rinv Le) (evalOp Le vars x1) (evalOp Le vars x2)) def inductionB {P : (LeftBinaryInverseTerm → Type)} : ((∀ (x1 x2 : LeftBinaryInverseTerm) , ((P x1) → ((P x2) → (P (linvL x1 x2))))) → ((∀ (x1 x2 : LeftBinaryInverseTerm) , ((P x1) → ((P x2) → (P (rinvL x1 x2))))) → (∀ (x : LeftBinaryInverseTerm) , (P x)))) | plinvl prinvl (linvL x1 x2) := (plinvl _ _ (inductionB plinvl prinvl x1) (inductionB plinvl prinvl x2)) | plinvl prinvl (rinvL x1 x2) := (prinvl _ _ (inductionB plinvl prinvl x1) (inductionB plinvl prinvl x2)) def inductionCl {A : Type} {P : ((ClLeftBinaryInverseTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClLeftBinaryInverseTerm A)) , ((P x1) → ((P x2) → (P (linvCl x1 x2))))) → ((∀ (x1 x2 : (ClLeftBinaryInverseTerm A)) , ((P x1) → ((P x2) → (P (rinvCl x1 x2))))) → (∀ (x : (ClLeftBinaryInverseTerm A)) , (P x))))) | psing plinvcl prinvcl (sing x1) := (psing x1) | psing plinvcl prinvcl (linvCl x1 x2) := (plinvcl _ _ (inductionCl psing plinvcl prinvcl x1) (inductionCl psing plinvcl prinvcl x2)) | psing plinvcl prinvcl (rinvCl x1 x2) := (prinvcl _ _ (inductionCl psing plinvcl prinvcl x1) (inductionCl psing plinvcl prinvcl x2)) def inductionOpB {n : ℕ} {P : ((OpLeftBinaryInverseTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpLeftBinaryInverseTerm n)) , ((P x1) → ((P x2) → (P (linvOL x1 x2))))) → ((∀ (x1 x2 : (OpLeftBinaryInverseTerm n)) , ((P x1) → ((P x2) → (P (rinvOL x1 x2))))) → (∀ (x : (OpLeftBinaryInverseTerm n)) , (P x))))) | pv plinvol prinvol (v x1) := (pv x1) | pv plinvol prinvol (linvOL x1 x2) := (plinvol _ _ (inductionOpB pv plinvol prinvol x1) (inductionOpB pv plinvol prinvol x2)) | pv plinvol prinvol (rinvOL x1 x2) := (prinvol _ _ (inductionOpB pv plinvol prinvol x1) (inductionOpB pv plinvol prinvol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpLeftBinaryInverseTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpLeftBinaryInverseTerm2 n A)) , ((P x1) → ((P x2) → (P (linvOL2 x1 x2))))) → ((∀ (x1 x2 : (OpLeftBinaryInverseTerm2 n A)) , ((P x1) → ((P x2) → (P (rinvOL2 x1 x2))))) → (∀ (x : (OpLeftBinaryInverseTerm2 n A)) , (P x)))))) | pv2 psing2 plinvol2 prinvol2 (v2 x1) := (pv2 x1) | pv2 psing2 plinvol2 prinvol2 (sing2 x1) := (psing2 x1) | pv2 psing2 plinvol2 prinvol2 (linvOL2 x1 x2) := (plinvol2 _ _ (inductionOp pv2 psing2 plinvol2 prinvol2 x1) (inductionOp pv2 psing2 plinvol2 prinvol2 x2)) | pv2 psing2 plinvol2 prinvol2 (rinvOL2 x1 x2) := (prinvol2 _ _ (inductionOp pv2 psing2 plinvol2 prinvol2 x1) (inductionOp pv2 psing2 plinvol2 prinvol2 x2)) def stageB : (LeftBinaryInverseTerm → (Staged LeftBinaryInverseTerm)) | (linvL x1 x2) := (stage2 linvL (codeLift2 linvL) (stageB x1) (stageB x2)) | (rinvL x1 x2) := (stage2 rinvL (codeLift2 rinvL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClLeftBinaryInverseTerm A) → (Staged (ClLeftBinaryInverseTerm A))) | (sing x1) := (Now (sing x1)) | (linvCl x1 x2) := (stage2 linvCl (codeLift2 linvCl) (stageCl x1) (stageCl x2)) | (rinvCl x1 x2) := (stage2 rinvCl (codeLift2 rinvCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpLeftBinaryInverseTerm n) → (Staged (OpLeftBinaryInverseTerm n))) | (v x1) := (const (code (v x1))) | (linvOL x1 x2) := (stage2 linvOL (codeLift2 linvOL) (stageOpB x1) (stageOpB x2)) | (rinvOL x1 x2) := (stage2 rinvOL (codeLift2 rinvOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpLeftBinaryInverseTerm2 n A) → (Staged (OpLeftBinaryInverseTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (linvOL2 x1 x2) := (stage2 linvOL2 (codeLift2 linvOL2) (stageOp x1) (stageOp x2)) | (rinvOL2 x1 x2) := (stage2 rinvOL2 (codeLift2 rinvOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (linvT : ((Repr A) → ((Repr A) → (Repr A)))) (rinvT : ((Repr A) → ((Repr A) → (Repr A)))) end LeftBinaryInverse
40ab6bab3526049e5163a23b30f38d2a441a711b
597e185014db6ce8a949dac0322798f11218338b
/src/kruskal_katona.lean
f48223302651a8e546d4187fe7581bcbfb4e4b37
[]
no_license
b-mehta/lean-experiments
58ce21c7106dfde163c236175fee30b341ba69ee
5f0aed189f724ae6f739ec75dcdddcd2687614e1
refs/heads/master
1,598,987,002,293
1,576,649,380,000
1,576,649,380,000
219,032,370
0
0
null
null
null
null
UTF-8
Lean
false
false
12,206
lean
import data.finset import data.fin import data.rat import data.nat.basic import data.fintype import algebra.big_operators import algebra.group_power import tactic.omega import tactic.linarith open fintype variables {X : Type*} variables [fintype X] [decidable_eq X] variables {r : ℕ} /- Define a type for rsets, give an easy constructor of rsets and a lemma for their cardinality. Also, we can use extensionality on them, and they're a finite type with cardinality a binomial. -/ section rset @[reducible] def rset (r : ℕ) (X) [fintype X] := {x : finset X // x ∈ finset.powerset_len r (elems X)} @[reducible] def rset_mk (A : finset X) (H : finset.card A = r) : rset r X := begin refine ⟨A, _⟩, rw finset.mem_powerset_len, exact ⟨finset.subset_univ _, H⟩ end @[simp] lemma card_of_rset {x : rset r X} : finset.card x.val = r := (finset.mem_powerset_len.1 x.2).2 @[reducible] instance : has_mem X (rset r X) := ⟨λ i A, i ∈ A.1⟩ theorem eq_of_veq : ∀ {s t : rset r X}, s.1 = t.1 → s = t | ⟨s, _⟩ ⟨t, _⟩ rfl := rfl theorem val_inj {s t : rset r X} : s.1 = t.1 ↔ s = t := ⟨eq_of_veq, congr_arg _⟩ theorem ext {s₁ s₂ : rset r X} : s₁ = s₂ ↔ (∀ a, a ∈ s₁ ↔ a ∈ s₂) := val_inj.symm.trans finset.ext @[ext] theorem ext' {s₁ s₂ : rset r X} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ := ext.2 instance rset_fintype (r : ℕ) : fintype (rset r X) := finset.subtype.fintype _ theorem rset_card (r : ℕ) : card (rset r X) = nat.choose (card X) r := begin rw card_of_subtype (finset.powerset_len r (elems X)) (λ _, iff.rfl), apply finset.card_powerset_len end end rset -- An example of an rset, and a set system. #eval elems (rset 3 (fin 5)) def example1 : rset 4 (fin 9) := rset_mk {0,1,4,5} (by trivial) def example2 : finset (rset 3 (fin 5)) := { rset_mk {0,1,2} (by trivial), rset_mk {0,1,3} (by trivial), rset_mk {0,2,3} (by trivial), rset_mk {0,2,4} (by trivial) } #eval example1 #eval example2 section stretch_and_erase def stretch (A : rset r X) (s : X) (h : s ∉ A) : rset (r+1) X := rset_mk (insert s (A.1)) $ by rw [finset.card_insert_of_not_mem h, card_of_rset] lemma mem_stretch (A : rset r X) (s : X) {h : s ∉ A} (i : X) : i ∈ stretch A s h ↔ i ∈ A ∨ i = s := by rw [stretch, finset.mem_insert]; tauto lemma stretch_subset {A : rset r X} {s : X} (h : s ∉ A) : A.1 ⊆ (stretch A s h).1 := finset.subset_insert _ _ lemma mem_stretch_self {A : rset r X} {s : X} (h : s ∉ A) : s ∈ stretch A s h := finset.mem_insert_self _ _ lemma mem_stretch_of_mem {A : rset r X} {s t : X} {p : s ∉ A} : t ∈ A → t ∈ stretch A s p := finset.mem_insert_of_mem def erase (A : rset (r+1) X) (s : X) (h : s ∈ A) : rset r X := rset_mk (finset.erase (A.1) s) $ by rw [finset.card_erase_of_mem h, card_of_rset]; trivial lemma mem_erase (A : rset (r+1) X) (s : X) (h : s ∈ A) (i : X) : i ∈ erase A s h ↔ i ∈ A ∧ i ≠ s := by rw [erase, finset.mem_erase]; tauto lemma mem_of_mem_erase {A : rset (r+1) X} {i s : X} {h : s ∈ A} : i ∈ erase A s h → i ∈ A := finset.mem_of_mem_erase lemma subset_erase {A : rset (r+1) X} {s : X} (h : s ∈ A) : (erase A s h).1 ⊆ A.1 := finset.erase_subset _ _ theorem not_mem_erase_self {A : rset (r+1) X} {s : X} (h : s ∈ A) : s ∉ erase A s h := finset.not_mem_erase _ _ lemma erase_iff_stretch {A : rset r X} {B : rset (r+1) X} {s : X} {H1 : s ∉ A} {H2 : s ∈ B} : stretch A s H1 = B ↔ erase B s H2 = A:= begin split, all_goals {intros p, ext, rw mem_erase <|> rw mem_stretch, split}, all_goals {intro k, rw ← p at *}, { rw mem_stretch at k, finish }, { split, apply mem_stretch_of_mem k, intro i, exact H1 (i ▸ k) }, { cases k, exact mem_of_mem_erase k, exact (k.symm ▸ H2) }, { rw mem_erase, finish } end lemma erase_stretch (A : rset r X) (s : X) (h : s ∉ A) : erase (stretch A s h) s (mem_stretch_self h) = A := erase_iff_stretch.1 rfl lemma stretch_erase (A : rset (r+1) X) (s : X) (h : s ∈ A) : stretch (erase A s h) s (not_mem_erase_self h) = A := erase_iff_stretch.2 rfl lemma erase_iff_stretch' {A : rset r X} {B : rset (r+1) X} : (∃ i ∉ A, stretch A i H = B) ↔ (∃ i ∈ B, erase B i H = A) := begin split, all_goals { rintro ⟨i, Hi, t⟩, use i, refine ⟨_, _⟩, rw ← t, any_goals {apply mem_stretch_self <|> apply not_mem_erase_self}, any_goals {rw erase_iff_stretch <|> rw ← erase_iff_stretch}, exact t } end end stretch_and_erase lemma card_map {α β} [decidable_eq β] {f : α ↪ β} {s : finset α} : (s.map f).card = s.card := begin rw finset.map_eq_image, rw finset.card_image_of_injective, exact f.2 end def all_removals {r : ℕ} (A : rset (r+1) X) : finset (rset r X) := A.1.attach.map ⟨λ i, erase A i.1 i.2, -- prove the function is injective begin rintro ⟨x1, x1p⟩ ⟨x2, x2p⟩ _, congr, dsimp at a, have m : x1 ∉ erase A x1 _ := not_mem_erase_self x1p, rw [a, mem_erase] at m, by_contra, apply m, tauto end ⟩ def mem_all_removals {r : ℕ} {A : rset (r+1) X} {B : rset r X} : B ∈ all_removals A ↔ ∃ i ∈ A, erase A i H = B := by simp [all_removals] lemma card_all_removals {r : ℕ} {A : rset (r+1) X} : (all_removals A).card = r + 1 := by rw [all_removals, card_map, finset.card_attach]; exact card_of_rset def shadow {r : ℕ} (𝒜 : finset (rset (r+1) X)) : finset (rset r X) := 𝒜.bind all_removals reserve prefix `∂`:30 notation ∂𝒜 := shadow 𝒜 #eval ∂example2 -- should be {{0,1}, {0,2}, {0,3}, {0,4}, {1,2}, {1,3}, {2,3}, {2,4}} def mem_shadow {r : ℕ} {𝒜 : finset (rset (r+1) X)} (B : rset r X) : B ∈ ∂𝒜 ↔ ∃ A ∈ 𝒜, ∃ i ∈ A, erase A i H = B := by simp [shadow, all_removals] def cube_graph : rel (rset r X) (rset (r+1) X) := λ A B, A.1 ⊆ B.1 lemma test {A : rset r X} {B : rset (r+1) X} : finset.card (B.1 \ A.1) = 1 ↔ cube_graph A B := begin rw cube_graph, dsimp, rw [← finset.sdiff_eq_empty_iff_subset, ← finset.card_eq_zero], have q: finset.card A.1 + finset.card (B.1 \ A.1) = finset.card B.1 + finset.card (A.1 \ B.1), rw [← finset.card_disjoint_union (finset.disjoint_sdiff), ← finset.card_disjoint_union (finset.disjoint_sdiff), finset.union_sdiff_symm], simp [card_of_rset] at q, rw [q, nat.one_add, nat.succ_inj'] end lemma stretch_iff_related {A : rset r X} {B : rset (r+1) X} : cube_graph A B ↔ ∃ (i ∉ A), stretch A i H = B := begin rw cube_graph, split, intro p, cases finset.card_eq_one.1 (test.2 p) with i _, use i, have k' : ∀ a, a ∈ B ∧ a ∉ A ↔ a = i, intro a, rw [← finset.mem_sdiff, ← finset.mem_singleton, h], have k : i ∈ B ∧ i ∉ A := (k' i).2 rfl, use k.2, ext, rw mem_stretch, refine ⟨λ s, s.elim _ (λ v, v.symm ▸ k.1), λ s, _⟩, apply p, safe, rintros ⟨_, _, k⟩, rw ← k, apply stretch_subset end lemma erase_iff_related (A : rset r X) (B : rset (r+1) X) : cube_graph A B ↔ ∃ (i ∈ B), erase B i H = A := iff.trans stretch_iff_related erase_iff_stretch' lemma all_removals_iff_related {r : ℕ} {A : rset r X} {B : rset (r+1) X} : A ∈ all_removals B ↔ cube_graph A B := by rw [erase_iff_related, mem_all_removals] lemma nat.choose_succ_right_eq {n k : ℕ} : nat.choose n (k + 1) * (k + 1) = nat.choose n k * (n - k) := begin have e : (n+1) * nat.choose n k = nat.choose n k * (k+1) + nat.choose n (k+1) * (k+1), rw [← nat.right_distrib, ← nat.choose_succ_succ, nat.succ_mul_choose_eq], rw [← nat.sub_eq_of_eq_add e, mul_comm, ← nat.mul_sub_left_distrib], simp end theorem div_le_div_iff {α} [linear_ordered_field α] {a b c d : α} (hc : 0 < c) (hd : 0 < d) : a / c ≤ b / d ↔ a * d ≤ b * c := by rw [le_div_iff hd, div_mul_eq_mul_div, div_le_iff hc] lemma multiply_out {A B n r : ℕ} (hr1 : 1 ≤ r) (hr2 : r ≤ n) (h : A * r ≤ B * (n - r + 1)) : (A : ℚ) / (nat.choose n r) ≤ B / nat.choose n (r-1) := begin rw div_le_div_iff; norm_cast, apply le_of_mul_le_mul_right _, exact hr1, cases r, simp, rw nat.succ_eq_add_one at *, rw [← nat.sub_add_comm hr2, nat.add_sub_add_right] at h, rw [nat.add_sub_cancel, mul_assoc B, nat.choose_succ_right_eq, mul_right_comm, ← mul_assoc, mul_right_comm B], exact nat.mul_le_mul_right _ h, apply nat.choose_pos hr2, apply nat.choose_pos (le_trans (nat.pred_le _) hr2) end def from_above {n : ℕ} (𝒜 : finset (rset (r+1) (fin n))) : finset (rset (r+1) (fin n) × rset r (fin n)) := 𝒜.bind $ λ A, (all_removals A).map ⟨λ x, (A, x), λ _ _, by simp⟩ lemma mem_from_above {n : ℕ} {𝒜 : finset (rset (r+1) (fin n))} {A : rset (r+1) (fin n)} {B : rset r (fin n)} : (A,B) ∈ from_above 𝒜 ↔ A ∈ 𝒜 ∧ B ∈ all_removals A := begin rw [from_above, finset.mem_bind], split; intro h, rcases h with ⟨a, Ha, h⟩, rw finset.mem_map at h, rcases h with ⟨b, Hb, h⟩, injection h with Ah Bh, rw [Ah, Bh] at *, exact ⟨Ha, Hb⟩, use A, use h.1, rw finset.mem_map, use B, use h.2, refl end lemma card_from_above {n : ℕ} (𝒜 : finset (rset (r+1) (fin n))) : (from_above 𝒜).card = 𝒜.card * (r+1) := begin rw [from_above, finset.card_bind, ← nat.smul_eq_mul, ← finset.sum_const], congr, ext, rw card_map, exact card_all_removals, intros, rw finset.disjoint_iff_ne, finish end def from_below {n : ℕ} (𝒜 : finset (rset (r+1) (fin n))) : finset (rset (r+1) (fin n) × rset r (fin n)) := begin refine (∂𝒜).bind (λ B, _), refine (finset.univ \ B.1).attach.map ⟨λ x, (stretch B x.1 (finset.mem_sdiff.1 x.2).2, B), _⟩, rintros ⟨x₁, x₁h⟩ ⟨x₂, x₂h⟩ h, rw finset.mem_sdiff at x₂h, injection h, congr, have q := mem_stretch_self x₂h.2, rw [← h_1, mem_stretch] at q, tauto end lemma mem_from_below {n : ℕ} {𝒜 : finset (rset (r+1) (fin n))} {A : rset (r+1) (fin n)} {B : rset r (fin n)} : A ∈ 𝒜 ∧ (∃ (i ∉ B), stretch B i H = A) → (A,B) ∈ from_below 𝒜 := begin intro h, rw [from_below, finset.mem_bind], use B, split, rw mem_shadow, exact ⟨A, h.1, erase_iff_stretch'.1 h.2⟩, rw [finset.mem_map], rcases h.2 with ⟨_, _, _⟩, refine ⟨⟨w, finset.mem_sdiff.2 ⟨complete _, ‹_›⟩⟩, by simp, _⟩, dsimp, rw ‹stretch B w _ = A› end lemma above_sub_below {n : ℕ} {𝒜 : finset (rset (r+1) (fin n))} : from_above 𝒜 ⊆ from_below 𝒜 := begin rintros ⟨x,y⟩ h, apply mem_from_below, rwa [← stretch_iff_related, ← all_removals_iff_related, ← mem_from_above] end lemma card_from_below {n : ℕ} (𝒜 : finset (rset (r+1) (fin n))) : (from_below 𝒜).card ≤ (∂𝒜).card * (n-r) := begin rw [from_below], transitivity, apply finset.card_bind_le, apply ge_of_eq, rw [← nat.smul_eq_mul, ← finset.sum_const], congr, ext, rw [card_map, finset.card_attach, finset.card_sdiff, card_of_rset, finset.card_univ, fintype.card_fin], apply finset.subset_univ end lemma finally {n r : ℕ} (hr2 : r + 1 ≤ n) : n - (r + 1) + 1 = n - r := by omega theorem localLYM {n r : ℕ} (𝒜 : finset (rset (r+1) (fin n))) {hr2 : r + 1 ≤ n} : (𝒜.card : ℚ) / nat.choose n (r+1) ≤ (∂𝒜).card / nat.choose n r := begin apply multiply_out (by simp) hr2, rw ← card_from_above, transitivity, apply finset.card_le_of_subset above_sub_below, transitivity, apply card_from_below, apply nat.mul_le_mul_left, omega, end theorem localLYM {n r : ℕ} (𝒜 : finset (rset (r+1) (fin n))) {hr2 : r + 1 ≤ n} : (𝒜.card : ℚ) / nat.choose n (r+1) ≤ (∂𝒜).card / nat.choose n r := begin apply main_lemma (by simp) hr2, rw [finally hr2], exact ( calc 𝒜.card * (r + 1) = (from_above 𝒜).card : (card_from_above 𝒜).symm ... ≤ (from_below 𝒜).card : begin apply finset.card_le_of_subset _, apply above_sub_below end ... ≤ finset.card (∂𝒜) * (n - r) : (card_from_below 𝒜) ) end
b850d944bc3f1ff6b939da03d5764ddd00f8a0b1
28b6e1a13d35e9b450f65c001660f4ec4713aa10
/Search/Heuristic.lean
15055413f412bad7c0556c485d916126c740d637
[ "Apache-2.0" ]
permissive
dselsam/search
14e3af3261a7a70f8e5885db9722b186f96fe1f5
67003b859d2228d291a3873af6279c1f61430c64
refs/heads/master
1,684,700,794,306
1,614,294,810,000
1,614,294,810,000
339,578,823
1
0
null
null
null
null
UTF-8
Lean
false
false
405
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam Simple best-first-search enumeration -/ namespace Search structure Scores : Type where policy : Array Float value : Float deriving Repr structure Heuristic (m : Type → Type) (α : Type) where score : Array α → m Scores end Search
5758e29cb9b805d96a8e8ed1e42a8d1f7e46ec39
e030b0259b777fedcdf73dd966f3f1556d392178
/tests/lean/interactive/complete.lean
38a5d1305232d88a00b078ac5c51795e6768bedf
[ "Apache-2.0" ]
permissive
fgdorais/lean
17b46a095b70b21fa0790ce74876658dc5faca06
c3b7c54d7cca7aaa25328f0a5660b6b75fe26055
refs/heads/master
1,611,523,590,686
1,484,412,902,000
1,484,412,902,000
38,489,734
0
0
null
1,435,923,380,000
1,435,923,379,000
null
UTF-8
Lean
false
false
250
lean
prelude inductive foo example := foo --^ "command": "complete" @[reducible] --^ "command": "complete", "skip_completions": true example := foo set_option trace.simplify true --^ "command": "complete", "skip_completions": true
fae1dd01baa5bba6f3ed42d5ad1a6b8e74874e7f
47181b4ef986292573c77e09fcb116584d37ea8a
/src/for_mathlib/degree.lean
75c82d9b4a2bea68e5453912164c68ff12c3d96a
[ "MIT" ]
permissive
RaitoBezarius/berkovich-spaces
87662a2bdb0ac0beed26e3338b221e3f12107b78
0a49f75a599bcb20333ec86b301f84411f04f7cf
refs/heads/main
1,690,520,666,912
1,629,328,012,000
1,629,328,012,000
332,238,095
4
0
MIT
1,629,312,085,000
1,611,414,506,000
Lean
UTF-8
Lean
false
false
3,268
lean
import data.polynomial.basic import data.polynomial.degree.definitions lemma polynomial.nat_degree_eq_nat_degree {R} [semiring R] {p q: polynomial R} (hpq: p.degree = q.degree): p.nat_degree = q.nat_degree := begin apply le_antisymm, exact polynomial.nat_degree_le_nat_degree (le_of_eq hpq), exact polynomial.nat_degree_le_nat_degree (le_of_eq hpq.symm), end theorem with_bot.lt_iff_exists_coe {α} [partial_order α]: ∀ {a b: with_bot α}, a < b ↔ (∃ p : α, b = p ∧ a < ↑p) | a (some b) := by simp [with_bot.some_eq_coe, with_bot.coe_eq_coe] | a none := by simp [with_bot.none_eq_bot]; exact (λ x hx, hx ▸ (@not_lt_bot _ _ a)) lemma polynomial.zero_le_nat_degree {R} [semiring R] {p: polynomial R} (hne: p ≠ 0): 0 ≤ p.nat_degree := begin have := (mt polynomial.degree_eq_bot.1) hne, obtain ⟨ n, ⟨ hdeg, hbot ⟩ ⟩ := with_bot.lt_iff_exists_coe.1 (bot_lt_iff_ne_bot.2 this), rw polynomial.nat_degree_eq_of_degree_eq_some hdeg, have := polynomial.zero_le_degree_iff.2 hne, rw hdeg at this, exact_mod_cast this, end lemma polynomial.nat_degree_add_C {R} [semiring R] {a: R} {p: polynomial R}: (p.nat_degree = 0 → p + polynomial.C a ≠ 0) → (p + polynomial.C a).nat_degree = p.nat_degree := begin intro h_cancel, apply (polynomial.degree_eq_iff_nat_degree_eq _).1, rotate 1, { by_cases (p.nat_degree = 0), exact h_cancel h, have h_deg := (nat.eq_zero_or_pos _).resolve_left h, suffices : 0 ≤ (p + polynomial.C a).degree, from polynomial.ne_zero_of_coe_le_degree this, rw polynomial.degree_add_eq_left_of_degree_lt, exact le_of_lt (polynomial.nat_degree_pos_iff_degree_pos.1 h_deg), calc (polynomial.C a).degree ≤ 0 : polynomial.degree_C_le ... < p.degree : polynomial.nat_degree_pos_iff_degree_pos.1 h_deg, }, by_cases (0 < p.nat_degree), { rw polynomial.degree_add_C (polynomial.nat_degree_pos_iff_degree_pos.1 h), exact polynomial.degree_eq_nat_degree (polynomial.ne_zero_of_nat_degree_gt h), }, { replace h := nonpos_iff_eq_zero.1 (not_lt.1 h), rw polynomial.eq_C_of_nat_degree_eq_zero h, by_cases ha_zero : a = 0, { rw ha_zero at *, simp only [add_zero, ring_hom.map_zero, polynomial.nat_degree_C, with_top.coe_zero], simp only [add_zero, ring_hom.map_zero, ne.def] at h_cancel, rw ← polynomial.eq_C_of_nat_degree_eq_zero h, rw_mod_cast [polynomial.degree_eq_nat_degree (h_cancel h), h], }, { replace h_cancel := h_cancel h, by_cases hp_zero: p.coeff 0 = 0, { simp [hp_zero, le_antisymm (polynomial.degree_C_le) (polynomial.zero_le_degree_iff.2 ((not_iff_not_of_iff polynomial.C_eq_zero).2 ha_zero))], }, { rw [polynomial.degree_add_eq_of_leading_coeff_add_ne_zero], rw_mod_cast [← polynomial.eq_C_of_nat_degree_eq_zero h, polynomial.degree_eq_nat_degree, h, polynomial.degree_C ha_zero], exact max_self _, { rw [polynomial.eq_C_of_nat_degree_eq_zero h], simp [hp_zero], }, { rw [polynomial.eq_C_of_nat_degree_eq_zero h, ← polynomial.C_add, ne.def, polynomial.C_eq_zero] at h_cancel, simp [h_cancel], }, } } }, end
c1e134950e872f0692afdc92b89e908a440cb5fe
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/data/num.lean
aee6859ef291d471f2a8ba1765411f8170a7bba3
[ "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
17,905
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ import data.bool tools.helper_tactics open bool eq.ops decidable helper_tactics namespace pos_num theorem succ_not_is_one (a : pos_num) : is_one (succ a) = ff := pos_num.induction_on a rfl (take n iH, rfl) (take n iH, rfl) theorem succ_one : succ one = bit0 one theorem succ_bit1 (a : pos_num) : succ (bit1 a) = bit0 (succ a) theorem succ_bit0 (a : pos_num) : succ (bit0 a) = bit1 a theorem ne_of_bit0_ne_bit0 {a b : pos_num} (H₁ : bit0 a ≠ bit0 b) : a ≠ b := suppose a = b, absurd rfl (this ▸ H₁) theorem ne_of_bit1_ne_bit1 {a b : pos_num} (H₁ : bit1 a ≠ bit1 b) : a ≠ b := suppose a = b, absurd rfl (this ▸ H₁) theorem pred_succ : ∀ (a : pos_num), pred (succ a) = a | one := rfl | (bit0 a) := by rewrite succ_bit0 | (bit1 a) := calc pred (succ (bit1 a)) = cond (is_one (succ a)) one (bit1 (pred (succ a))) : rfl ... = cond ff one (bit1 (pred (succ a))) : succ_not_is_one ... = bit1 (pred (succ a)) : rfl ... = bit1 a : pred_succ a section variables (a b : pos_num) theorem one_add_one : one + one = bit0 one theorem one_add_bit0 : one + (bit0 a) = bit1 a theorem one_add_bit1 : one + (bit1 a) = succ (bit1 a) theorem bit0_add_one : (bit0 a) + one = bit1 a theorem bit1_add_one : (bit1 a) + one = succ (bit1 a) theorem bit0_add_bit0 : (bit0 a) + (bit0 b) = bit0 (a + b) theorem bit0_add_bit1 : (bit0 a) + (bit1 b) = bit1 (a + b) theorem bit1_add_bit0 : (bit1 a) + (bit0 b) = bit1 (a + b) theorem bit1_add_bit1 : (bit1 a) + (bit1 b) = succ (bit1 (a + b)) theorem one_mul : one * a = a end theorem mul_one : ∀ a, a * one = a | one := rfl | (bit1 n) := calc bit1 n * one = bit0 (n * one) + one : rfl ... = bit0 n + one : mul_one n ... = bit1 n : bit0_add_one | (bit0 n) := calc bit0 n * one = bit0 (n * one) : rfl ... = bit0 n : mul_one n theorem decidable_eq [instance] : ∀ (a b : pos_num), decidable (a = b) | one one := inl rfl | one (bit0 b) := inr (by contradiction) | one (bit1 b) := inr (by contradiction) | (bit0 a) one := inr (by contradiction) | (bit0 a) (bit0 b) := match decidable_eq a b with | inl H₁ := inl (by rewrite H₁) | inr H₁ := inr (by intro H; injection H; contradiction) end | (bit0 a) (bit1 b) := inr (by contradiction) | (bit1 a) one := inr (by contradiction) | (bit1 a) (bit0 b) := inr (by contradiction) | (bit1 a) (bit1 b) := match decidable_eq a b with | inl H₁ := inl (by rewrite H₁) | inr H₁ := inr (by intro H; injection H; contradiction) end local notation a < b := (lt a b = tt) local notation a ` ≮ `:50 b:50 := (lt a b = ff) theorem lt_one_right_eq_ff : ∀ a : pos_num, a ≮ one | one := rfl | (bit0 a) := rfl | (bit1 a) := rfl theorem lt_one_succ_eq_tt : ∀ a : pos_num, one < succ a | one := rfl | (bit0 a) := rfl | (bit1 a) := rfl theorem lt_of_lt_bit0_bit0 {a b : pos_num} (H : bit0 a < bit0 b) : a < b := H theorem lt_of_lt_bit0_bit1 {a b : pos_num} (H : bit1 a < bit0 b) : a < b := H theorem lt_of_lt_bit1_bit1 {a b : pos_num} (H : bit1 a < bit1 b) : a < b := H theorem lt_of_lt_bit1_bit0 {a b : pos_num} (H : bit0 a < bit1 b) : a < succ b := H theorem lt_bit0_bit0_eq_lt (a b : pos_num) : lt (bit0 a) (bit0 b) = lt a b := rfl theorem lt_bit1_bit1_eq_lt (a b : pos_num) : lt (bit1 a) (bit1 b) = lt a b := rfl theorem lt_bit1_bit0_eq_lt (a b : pos_num) : lt (bit1 a) (bit0 b) = lt a b := rfl theorem lt_bit0_bit1_eq_lt_succ (a b : pos_num) : lt (bit0 a) (bit1 b) = lt a (succ b) := rfl theorem lt_irrefl : ∀ (a : pos_num), a ≮ a | one := rfl | (bit0 a) := begin rewrite lt_bit0_bit0_eq_lt, apply lt_irrefl end | (bit1 a) := begin rewrite lt_bit1_bit1_eq_lt, apply lt_irrefl end theorem ne_of_lt_eq_tt : ∀ {a b : pos_num}, a < b → a = b → false | one ⌞one⌟ H₁ (eq.refl one) := absurd H₁ ff_ne_tt | (bit0 a) ⌞(bit0 a)⌟ H₁ (eq.refl (bit0 a)) := begin rewrite lt_bit0_bit0_eq_lt at H₁, apply ne_of_lt_eq_tt H₁ (eq.refl a) end | (bit1 a) ⌞(bit1 a)⌟ H₁ (eq.refl (bit1 a)) := begin rewrite lt_bit1_bit1_eq_lt at H₁, apply ne_of_lt_eq_tt H₁ (eq.refl a) end theorem lt_base : ∀ a : pos_num, a < succ a | one := rfl | (bit0 a) := begin rewrite [succ_bit0, lt_bit0_bit1_eq_lt_succ], apply lt_base end | (bit1 a) := begin rewrite [succ_bit1, lt_bit1_bit0_eq_lt], apply lt_base end theorem lt_step : ∀ {a b : pos_num}, a < b → a < succ b | one one H := rfl | one (bit0 b) H := rfl | one (bit1 b) H := rfl | (bit0 a) one H := absurd H ff_ne_tt | (bit0 a) (bit0 b) H := begin rewrite [succ_bit0, lt_bit0_bit1_eq_lt_succ, lt_bit0_bit0_eq_lt at H], apply lt_step H end | (bit0 a) (bit1 b) H := begin rewrite [succ_bit1, lt_bit0_bit0_eq_lt, lt_bit0_bit1_eq_lt_succ at H], exact H end | (bit1 a) one H := absurd H ff_ne_tt | (bit1 a) (bit0 b) H := begin rewrite [succ_bit0, lt_bit1_bit1_eq_lt, lt_bit1_bit0_eq_lt at H], exact H end | (bit1 a) (bit1 b) H := begin rewrite [succ_bit1, lt_bit1_bit0_eq_lt, lt_bit1_bit1_eq_lt at H], apply lt_step H end theorem lt_of_lt_succ_succ : ∀ {a b : pos_num}, succ a < succ b → a < b | one one H := absurd H ff_ne_tt | one (bit0 b) H := rfl | one (bit1 b) H := rfl | (bit0 a) one H := begin rewrite [succ_bit0 at H, succ_one at H, lt_bit1_bit0_eq_lt at H], apply absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff a) H end | (bit0 a) (bit0 b) H := by exact H | (bit0 a) (bit1 b) H := by exact H | (bit1 a) one H := begin rewrite [succ_bit1 at H, succ_one at H, lt_bit0_bit0_eq_lt at H], apply absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff (succ a)) H end | (bit1 a) (bit0 b) H := begin rewrite [succ_bit1 at H, succ_bit0 at H, lt_bit0_bit1_eq_lt_succ at H], rewrite lt_bit1_bit0_eq_lt, apply lt_of_lt_succ_succ H end | (bit1 a) (bit1 b) H := begin rewrite [lt_bit1_bit1_eq_lt, *succ_bit1 at H, lt_bit0_bit0_eq_lt at H], apply lt_of_lt_succ_succ H end theorem lt_succ_succ : ∀ {a b : pos_num}, a < b → succ a < succ b | one one H := absurd H ff_ne_tt | one (bit0 b) H := begin rewrite [succ_bit0, succ_one, lt_bit0_bit1_eq_lt_succ], apply lt_one_succ_eq_tt end | one (bit1 b) H := begin rewrite [succ_one, succ_bit1, lt_bit0_bit0_eq_lt], apply lt_one_succ_eq_tt end | (bit0 a) one H := absurd H ff_ne_tt | (bit0 a) (bit0 b) H := by exact H | (bit0 a) (bit1 b) H := by exact H | (bit1 a) one H := absurd H ff_ne_tt | (bit1 a) (bit0 b) H := begin rewrite [succ_bit1, succ_bit0, lt_bit0_bit1_eq_lt_succ, lt_bit1_bit0_eq_lt at H], apply lt_succ_succ H end | (bit1 a) (bit1 b) H := begin rewrite [lt_bit1_bit1_eq_lt at H, *succ_bit1, lt_bit0_bit0_eq_lt], apply lt_succ_succ H end theorem lt_of_lt_succ : ∀ {a b : pos_num}, succ a < b → a < b | one one H := absurd_of_eq_ff_of_eq_tt !lt_one_right_eq_ff H | one (bit0 b) H := rfl | one (bit1 b) H := rfl | (bit0 a) one H := absurd_of_eq_ff_of_eq_tt !lt_one_right_eq_ff H | (bit0 a) (bit0 b) H := by exact H | (bit0 a) (bit1 b) H := begin rewrite [succ_bit0 at H, lt_bit1_bit1_eq_lt at H, lt_bit0_bit1_eq_lt_succ], apply lt_step H end | (bit1 a) one H := absurd_of_eq_ff_of_eq_tt !lt_one_right_eq_ff H | (bit1 a) (bit0 b) H := begin rewrite [lt_bit1_bit0_eq_lt, succ_bit1 at H, lt_bit0_bit0_eq_lt at H], apply lt_of_lt_succ H end | (bit1 a) (bit1 b) H := begin rewrite [succ_bit1 at H, lt_bit0_bit1_eq_lt_succ at H, lt_bit1_bit1_eq_lt], apply lt_of_lt_succ_succ H end theorem lt_of_lt_succ_of_ne : ∀ {a b : pos_num}, a < succ b → a ≠ b → a < b | one one H₁ H₂ := absurd rfl H₂ | one (bit0 b) H₁ H₂ := rfl | one (bit1 b) H₁ H₂ := rfl | (bit0 a) one H₁ H₂ := begin rewrite [succ_one at H₁, lt_bit0_bit0_eq_lt at H₁], apply absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₁ end | (bit0 a) (bit0 b) H₁ H₂ := begin rewrite [lt_bit0_bit0_eq_lt, succ_bit0 at H₁, lt_bit0_bit1_eq_lt_succ at H₁], apply lt_of_lt_succ_of_ne H₁ (ne_of_bit0_ne_bit0 H₂) end | (bit0 a) (bit1 b) H₁ H₂ := begin rewrite [succ_bit1 at H₁, lt_bit0_bit0_eq_lt at H₁, lt_bit0_bit1_eq_lt_succ], exact H₁ end | (bit1 a) one H₁ H₂ := begin rewrite [succ_one at H₁, lt_bit1_bit0_eq_lt at H₁], apply absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₁ end | (bit1 a) (bit0 b) H₁ H₂ := begin rewrite [succ_bit0 at H₁, lt_bit1_bit1_eq_lt at H₁, lt_bit1_bit0_eq_lt], exact H₁ end | (bit1 a) (bit1 b) H₁ H₂ := begin rewrite [succ_bit1 at H₁, lt_bit1_bit0_eq_lt at H₁, lt_bit1_bit1_eq_lt], apply lt_of_lt_succ_of_ne H₁ (ne_of_bit1_ne_bit1 H₂) end theorem lt_trans : ∀ {a b c : pos_num}, a < b → b < c → a < c | one b (bit0 c) H₁ H₂ := rfl | one b (bit1 c) H₁ H₂ := rfl | a (bit0 b) one H₁ H₂ := absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₂ | a (bit1 b) one H₁ H₂ := absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₂ | (bit0 a) (bit0 b) (bit0 c) H₁ H₂ := begin rewrite lt_bit0_bit0_eq_lt at *, apply lt_trans H₁ H₂ end | (bit0 a) (bit0 b) (bit1 c) H₁ H₂ := begin rewrite [lt_bit0_bit1_eq_lt_succ at *, lt_bit0_bit0_eq_lt at H₁], apply lt_trans H₁ H₂ end | (bit0 a) (bit1 b) (bit0 c) H₁ H₂ := begin rewrite [lt_bit0_bit1_eq_lt_succ at H₁, lt_bit1_bit0_eq_lt at H₂, lt_bit0_bit0_eq_lt], apply @by_cases (a = b), begin intro H, rewrite -H at H₂, exact H₂ end, begin intro H, apply lt_trans (lt_of_lt_succ_of_ne H₁ H) H₂ end end | (bit0 a) (bit1 b) (bit1 c) H₁ H₂ := begin rewrite [lt_bit0_bit1_eq_lt_succ at *, lt_bit1_bit1_eq_lt at H₂], apply lt_trans H₁ (lt_succ_succ H₂) end | (bit1 a) (bit0 b) (bit0 c) H₁ H₂ := begin rewrite [lt_bit0_bit0_eq_lt at H₂, lt_bit1_bit0_eq_lt at *], apply lt_trans H₁ H₂ end | (bit1 a) (bit0 b) (bit1 c) H₁ H₂ := begin rewrite [lt_bit1_bit0_eq_lt at H₁, lt_bit0_bit1_eq_lt_succ at H₂, lt_bit1_bit1_eq_lt], apply @by_cases (b = c), begin intro H, rewrite H at H₁, exact H₁ end, begin intro H, apply lt_trans H₁ (lt_of_lt_succ_of_ne H₂ H) end end | (bit1 a) (bit1 b) (bit0 c) H₁ H₂ := begin rewrite [lt_bit1_bit1_eq_lt at H₁, lt_bit1_bit0_eq_lt at H₂, lt_bit1_bit0_eq_lt], apply lt_trans H₁ H₂ end | (bit1 a) (bit1 b) (bit1 c) H₁ H₂ := begin rewrite lt_bit1_bit1_eq_lt at *, apply lt_trans H₁ H₂ end theorem lt_antisymm : ∀ {a b : pos_num}, a < b → b ≮ a | one one H := rfl | one (bit0 b) H := rfl | one (bit1 b) H := rfl | (bit0 a) one H := absurd H ff_ne_tt | (bit0 a) (bit0 b) H := begin rewrite lt_bit0_bit0_eq_lt at *, apply lt_antisymm H end | (bit0 a) (bit1 b) H := begin rewrite lt_bit1_bit0_eq_lt, rewrite lt_bit0_bit1_eq_lt_succ at H, have H₁ : succ b ≮ a, from lt_antisymm H, apply eq_ff_of_ne_tt, intro H₂, apply @by_cases (succ b = a), show succ b = a → false, begin intro Hp, rewrite -Hp at H, apply absurd_of_eq_ff_of_eq_tt (lt_irrefl (succ b)) H end, show succ b ≠ a → false, begin intro Hn, have H₃ : succ b < succ a, from lt_succ_succ H₂, have H₄ : succ b < a, from lt_of_lt_succ_of_ne H₃ Hn, apply absurd_of_eq_ff_of_eq_tt H₁ H₄ end, end | (bit1 a) one H := absurd H ff_ne_tt | (bit1 a) (bit0 b) H := begin rewrite lt_bit0_bit1_eq_lt_succ, rewrite lt_bit1_bit0_eq_lt at H, have H₁ : lt b a = ff, from lt_antisymm H, apply eq_ff_of_ne_tt, intro H₂, apply @by_cases (b = a), show b = a → false, begin intro Hp, rewrite -Hp at H, apply absurd_of_eq_ff_of_eq_tt (lt_irrefl b) H end, show b ≠ a → false, begin intro Hn, have H₃ : b < a, from lt_of_lt_succ_of_ne H₂ Hn, apply absurd_of_eq_ff_of_eq_tt H₁ H₃ end, end | (bit1 a) (bit1 b) H := begin rewrite lt_bit1_bit1_eq_lt at *, apply lt_antisymm H end local notation a ≤ b := (le a b = tt) theorem le_refl : ∀ a : pos_num, a ≤ a := lt_base theorem le_eq_lt_succ {a b : pos_num} : le a b = lt a (succ b) := rfl theorem not_lt_of_le : ∀ {a b : pos_num}, a ≤ b → b < a → false | one one H₁ H₂ := absurd H₂ ff_ne_tt | one (bit0 b) H₁ H₂ := absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₂ | one (bit1 b) H₁ H₂ := absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₂ | (bit0 a) one H₁ H₂ := begin rewrite [le_eq_lt_succ at H₁, succ_one at H₁, lt_bit0_bit0_eq_lt at H₁], apply absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₁ end | (bit0 a) (bit0 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at H₁, succ_bit0 at H₁, lt_bit0_bit1_eq_lt_succ at H₁], rewrite [lt_bit0_bit0_eq_lt at H₂], apply not_lt_of_le H₁ H₂ end | (bit0 a) (bit1 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at H₁, succ_bit1 at H₁, lt_bit0_bit0_eq_lt at H₁], rewrite [lt_bit1_bit0_eq_lt at H₂], apply not_lt_of_le H₁ H₂ end | (bit1 a) one H₁ H₂ := begin rewrite [le_eq_lt_succ at H₁, succ_one at H₁, lt_bit1_bit0_eq_lt at H₁], apply absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff _) H₁ end | (bit1 a) (bit0 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at H₁, succ_bit0 at H₁, lt_bit1_bit1_eq_lt at H₁], rewrite lt_bit0_bit1_eq_lt_succ at H₂, have H₃ : a < succ b, from lt_step H₁, apply @by_cases (b = a), begin intro Hba, rewrite -Hba at H₁, apply absurd_of_eq_ff_of_eq_tt (lt_irrefl b) H₁ end, begin intro Hnba, have H₄ : b < a, from lt_of_lt_succ_of_ne H₂ Hnba, apply not_lt_of_le H₃ H₄ end end | (bit1 a) (bit1 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at H₁, succ_bit1 at H₁, lt_bit1_bit0_eq_lt at H₁], rewrite [lt_bit1_bit1_eq_lt at H₂], apply not_lt_of_le H₁ H₂ end theorem le_antisymm : ∀ {a b : pos_num}, a ≤ b → b ≤ a → a = b | one one H₁ H₂ := rfl | one (bit0 b) H₁ H₂ := by apply absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff b) H₂ | one (bit1 b) H₁ H₂ := by apply absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff b) H₂ | (bit0 a) one H₁ H₂ := by apply absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff a) H₁ | (bit0 a) (bit0 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at *, succ_bit0 at *, lt_bit0_bit1_eq_lt_succ at *], have H : a = b, from le_antisymm H₁ H₂, rewrite H end | (bit0 a) (bit1 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at *, succ_bit1 at H₁, succ_bit0 at H₂], rewrite [lt_bit0_bit0_eq_lt at H₁, lt_bit1_bit1_eq_lt at H₂], apply false.rec _ (not_lt_of_le H₁ H₂) end | (bit1 a) one H₁ H₂ := by apply absurd_of_eq_ff_of_eq_tt (lt_one_right_eq_ff a) H₁ | (bit1 a) (bit0 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at *, succ_bit0 at H₁, succ_bit1 at H₂], rewrite [lt_bit1_bit1_eq_lt at H₁, lt_bit0_bit0_eq_lt at H₂], apply false.rec _ (not_lt_of_le H₂ H₁) end | (bit1 a) (bit1 b) H₁ H₂ := begin rewrite [le_eq_lt_succ at *, succ_bit1 at *, lt_bit1_bit0_eq_lt at *], have H : a = b, from le_antisymm H₁ H₂, rewrite H end theorem le_trans {a b c : pos_num} : a ≤ b → b ≤ c → a ≤ c := begin intro H₁ H₂, rewrite [le_eq_lt_succ at *], apply @by_cases (a = b), begin intro Hab, rewrite Hab, exact H₂ end, begin intro Hnab, have Haltb : a < b, from lt_of_lt_succ_of_ne H₁ Hnab, apply lt_trans Haltb H₂ end, end end pos_num namespace num open pos_num theorem decidable_eq [instance] : ∀ (a b : num), decidable (a = b) | zero zero := inl rfl | zero (pos b) := inr (by contradiction) | (pos a) zero := inr (by contradiction) | (pos a) (pos b) := if H : a = b then inl (by rewrite H) else inr (suppose pos a = pos b, begin injection this, contradiction end) end num
b0f038323cacbbbaf356e54b0bcac2e062501b60
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebra/punit_instances.lean
146f01df54c792c30e1b1e0b30ddb66e1d796daf
[ "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
4,461
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.module.basic import algebra.gcd_monoid.basic import group_theory.group_action.defs /-! # Instances on punit This file collects facts about algebraic structures on the one-element type, e.g. that it is a commutative ring. -/ universes u namespace punit variables {R S : Type*} (x y : punit.{u+1}) (s : set punit.{u+1}) @[to_additive] instance : comm_group punit := by refine_struct { mul := λ _ _, star, one := star, inv := λ _, star, div := λ _ _, star, npow := λ _ _, star, zpow := λ _ _, star, .. }; intros; exact subsingleton.elim _ _ @[simp, to_additive] lemma one_eq : (1 : punit) = star := rfl @[simp, to_additive] lemma mul_eq : x * y = star := rfl @[simp, to_additive] lemma div_eq : x / y = star := rfl @[simp, to_additive] lemma inv_eq : x⁻¹ = star := rfl instance : comm_ring punit := by refine { .. punit.comm_group, .. punit.add_comm_group, .. }; intros; exact subsingleton.elim _ _ instance : cancel_comm_monoid_with_zero punit := by refine { .. punit.comm_ring, .. }; intros; exact subsingleton.elim _ _ instance : normalized_gcd_monoid punit := by refine { gcd := λ _ _, star, lcm := λ _ _, star, norm_unit := λ x, 1, gcd_dvd_left := λ _ _, ⟨star, subsingleton.elim _ _⟩, gcd_dvd_right := λ _ _, ⟨star, subsingleton.elim _ _⟩, dvd_gcd := λ _ _ _ _ _, ⟨star, subsingleton.elim _ _⟩, gcd_mul_lcm := λ _ _, ⟨1, subsingleton.elim _ _⟩, .. }; intros; exact subsingleton.elim _ _ @[simp] lemma gcd_eq : gcd x y = star := rfl @[simp] lemma lcm_eq : lcm x y = star := rfl @[simp] lemma norm_unit_eq : norm_unit x = 1 := rfl instance : complete_boolean_algebra punit := by refine { le := λ _ _, true, le_antisymm := λ _ _ _ _, subsingleton.elim _ _, lt := λ _ _, false, lt_iff_le_not_le := λ _ _, iff_of_false not_false (λ H, H.2 trivial), top := star, bot := star, sup := λ _ _, star, inf := λ _ _, star, Sup := λ _, star, Inf := λ _, star, compl := λ _, star, sdiff := λ _ _, star, .. }; intros; trivial <|> simp only [eq_iff_true_of_subsingleton] @[simp] lemma top_eq : (⊤ : punit) = star := rfl @[simp] lemma bot_eq : (⊥ : punit) = star := rfl @[simp] lemma sup_eq : x ⊔ y = star := rfl @[simp] lemma inf_eq : x ⊓ y = star := rfl @[simp] lemma Sup_eq : Sup s = star := rfl @[simp] lemma Inf_eq : Inf s = star := rfl @[simp] lemma compl_eq : xᶜ = star := rfl @[simp] lemma sdiff_eq : x \ y = star := rfl @[simp] protected lemma le : x ≤ y := trivial @[simp] lemma not_lt : ¬(x < y) := not_false instance : canonically_ordered_add_monoid punit := by refine { le_iff_exists_add := λ _ _, iff_of_true _ ⟨star, subsingleton.elim _ _⟩, .. punit.comm_ring, .. punit.complete_boolean_algebra, .. }; intros; trivial instance : linear_ordered_cancel_add_comm_monoid punit := { add_left_cancel := λ _ _ _ _, subsingleton.elim _ _, le_of_add_le_add_left := λ _ _ _ _, trivial, le_total := λ _ _, or.inl trivial, decidable_le := λ _ _, decidable.true, decidable_eq := punit.decidable_eq, decidable_lt := λ _ _, decidable.false, .. punit.canonically_ordered_add_monoid } instance : has_scalar R punit := { smul := λ _ _, star } @[simp] lemma smul_eq (r : R) : r • y = star := rfl instance : smul_comm_class R S punit := ⟨λ _ _ _, subsingleton.elim _ _⟩ instance [has_scalar R S] : is_scalar_tower R S punit := ⟨λ _ _ _, subsingleton.elim _ _⟩ instance [has_zero R] : smul_with_zero R punit := by refine { ..punit.has_scalar, .. }; intros; exact subsingleton.elim _ _ instance [monoid R] : mul_action R punit := by refine { ..punit.has_scalar, .. }; intros; exact subsingleton.elim _ _ instance [monoid R] : distrib_mul_action R punit := by refine { ..punit.mul_action, .. }; intros; exact subsingleton.elim _ _ instance [monoid R] : mul_distrib_mul_action R punit := by refine { ..punit.mul_action, .. }; intros; exact subsingleton.elim _ _ /-! TODO: provide `mul_semiring_action R punit` -/ -- importing it here currently causes timeouts elsewhere due to the import order changing instance [monoid_with_zero R] : mul_action_with_zero R punit := { .. punit.mul_action, .. punit.smul_with_zero } instance [semiring R] : module R punit := by refine { .. punit.distrib_mul_action, .. }; intros; exact subsingleton.elim _ _ end punit
9ef404b0e1783043b0fbe0dde4ca7da44dfbef7c
958488bc7f3c2044206e0358e56d7690b6ae696c
/lean/inductive.lean
5eab5d41f1da8f3c93b83b2b35c2ffe6af728b64
[]
no_license
possientis/Prog
a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4
d4b3debc37610a88e0dac3ac5914903604fd1d1f
refs/heads/master
1,692,263,717,723
1,691,757,179,000
1,691,757,179,000
40,361,602
3
0
null
1,679,896,438,000
1,438,953,859,000
Coq
UTF-8
Lean
false
false
8,479
lean
open tactic.interactive inductive WeekDay : Type | Sunday : WeekDay | Monday : WeekDay | Tuesday : WeekDay | Wednesday : WeekDay | Thursday : WeekDay | Friday : WeekDay | Saturday : WeekDay --#check @WeekDay.Sunday open WeekDay --#check @Sunday --#check @WeekDay.rec --#check @WeekDay.rec_on def numberOfDay1 (d : WeekDay) : ℕ := WeekDay.rec_on d 1 2 3 4 5 6 7 def numberOfDay2 (d : WeekDay) : ℕ := WeekDay.rec 1 2 3 4 5 6 7 d def numberOfDay3 (d : WeekDay) : ℕ := WeekDay.cases_on d 1 2 3 4 5 6 7 --#reduce numberOfDay1 Sunday --#reduce numberOfDay1 Monday --#reduce numberOfDay2 Sunday --#reduce numberOfDay2 Monday --#reduce numberOfDay3 Tuesday --#reduce numberOfDay3 Wednesday def next (d : WeekDay) : WeekDay := WeekDay.cases_on d Monday Tuesday Wednesday Thursday Friday Saturday Sunday def previous (d : WeekDay) : WeekDay := WeekDay.cases_on d Saturday Sunday Monday Tuesday Wednesday Thursday Friday --#reduce (next (next Tuesday)) --#reduce (next (previous Tuesday)) lemma L1 : ∀ (d : WeekDay), next (previous d) = d := assume d, WeekDay.cases_on d (show next (previous Sunday) = Sunday , from rfl) (show next (previous Monday) = Monday , from rfl) (show next (previous Tuesday) = Tuesday , from rfl) (show next (previous Wednesday) = Wednesday , from rfl) (show next (previous Thursday) = Thursday , from rfl) (show next (previous Friday) = Friday , from rfl) (show next (previous Saturday) = Saturday , from rfl) --#check L1 lemma L2 : ∀ (d : WeekDay), next (previous d) = d := assume d, begin apply WeekDay.cases_on d; refl end --#check L2 namespace hidden1 universes u v inductive prod (α : Type u) (β : Type v) | mk : α → β → prod --#check @prod --#check @prod.mk inductive sum (α : Type u) (β : Type v) | inl {} : α → sum | inr {} : β → sum end hidden1 namespace hidden2 universes u v def fst {α : Type u} {β : Type v} (p : α × β) : α := prod.rec_on p (λ a b, a) def snd {α : Type u} {β : Type v} (p : α × β) : β := prod.rec_on p (λ a b, b) end hidden2 def prod_example (p: bool × ℕ) : ℕ := prod.rec_on p (λ b n, cond b (2*n) (2*n +1)) --#reduce prod_example (tt,3) --#reduce prod_example (ff,3) def sum_example (s : ℕ ⊕ ℕ) : ℕ := sum.cases_on s (λ n, 2 * n) (λ n, 2 * n +1) --#reduce sum_example (sum.inl 3) --#reduce sum_example (sum.inr 3) --#check @sum.inl --#check @sum.inr namespace hidden3 universes u v inductive prod (α : Type u) (β : Type v) | mk (fst : α) (snd : β) : prod --#check @prod.mk --#check @prod.fst --#check @prod.snd end hidden3 namespace hidden4 structure prod1 (α β: Type) := mk :: (fst : α) (snd : β) --#check @prod1.mk --#check @prod1.fst --#check @prod1.snd end hidden4 structure color := (red : ℕ) (green : ℕ) (blue : ℕ) def yellow := color.mk 255 255 0 --#reduce color.red yellow --#reduce color.green yellow --#reduce color.blue yellow namespace hidden5 universes u v inductive sigma {α : Type u} (β : α → Type v) | dpair : Π a : α, β a → sigma inductive option (α : Type u) | none {} : option | some : α → option inductive inhabited (α : Type u) : Prop | mk : α → inhabited --#check @inhabited end hidden5 namespace hidden6 inductive false : Prop inductive true : Prop | intro : true inductive and (a b:Prop) : Prop | intro : a → b → and inductive or (a b:Prop) : Prop | intro_left : a → or | intro_right : b → or universe u inductive Exists {α : Type u} (p:α → Prop) : Prop | intro : ∀ (a:α), p a → Exists def exists.intro := @Exists.intro inductive subtype {α : Type u} (p : α → Prop) | mk : Π x : α, p x → subtype structure subtype2 {α : Sort u} (p : α → Prop) := (val : α) (property : p val) variables {α : Type u} (p : α → Prop) --#check subtype p --#check subtype2 p --#check { x : α // p x} end hidden6 inductive foo : Type | bar1 : ℕ → ℕ → foo | bar2 : ℕ → ℕ → ℕ → foo --#check @foo def silly1 (x : foo) : ℕ := begin cases x with a b c d e, {exact (a + b)}, {exact (c + d + e)} end --#check @silly1 open foo def silly2 (x : foo) : ℕ := begin cases x, case bar1 : a b {exact b}, case bar2 : c d e {exact e} end --#check @silly2 def silly3 (x : foo) : ℕ := begin cases x, case bar2 : c d e {exact e}, case bar1 : a b {exact b} end --#check @silly3 open nat variable p : ℕ → Prop lemma L3 : p 0 → (∀ n, p (succ n)) → ∀(m k : ℕ), p (m + 3 * k) := assume hz hs m k, begin cases (m + 3 * k), {exact hz}, {apply hs} end --#check L3 lemma L4 : p 0 → (∀ n, p (succ n)) → ∀(m k : ℕ), p (m + 3 * k) := assume hz hs m k, begin generalize : m + 3 * k = n, cases n, {exact hz}, {apply hs} end --#check L4 lemma L5 : ∀ (p : Prop) (m n : ℕ), (m < n → p) → (m ≥ n → p) → p := assume p m n H1 H2, begin cases lt_or_ge m n with H H, {apply H1, assumption}, {apply H2, assumption} end --#check L5 lemma L6 : ∀ (p : Prop) (m n : ℕ), (m < n → p) → (m ≥ n → p) → p := assume p m n H1 H2, begin have H : m < n ∨ m ≥ n, {apply lt_or_ge}, {cases H with H H, {apply H1, assumption}, {apply H2, assumption}} end --#check L6 --#check @nat.sub_self lemma L7 : ∀ (m n : ℕ), m - n = 0 ∨ m ≠ n := assume m n, begin cases decidable.em (m = n) with H H, {rewrite H, left, apply nat.sub_self}, {right, assumption} end --#check L7 def f (m k : ℕ) : ℕ := begin cases m - k, -- hmmmm {exact 3}, -- ≤ 0 it seems {exact 7} -- > 0 it seems end example : f 5 5 = 3 := rfl example : f 5 7 = 3 := rfl example : f 10 2 = 7 := rfl lemma L8 : ∀ (n : ℕ), 0 + n = n := assume n, begin induction n with n IH, {reflexivity}, {simp} end lemma L9 : ∀ (m n : ℕ), succ m + n = succ (m + n) := assume m n, begin induction n with n IH, { by calc succ m + 0 = succ m : rfl ... = succ (m + 0) : rfl }, { by calc succ m + succ n = succ (succ m + n) : by refl ... = succ (succ (m + n)) : by rw IH ... = succ (m + succ n) : by refl } end --#check L9 --#check @zero_add lemma L10 : ∀ (m n : ℕ), m + n = n + m := assume m n, begin induction n with n IH, by calc m + 0 = m : by refl ... = 0 + m : by begin symmetry, apply zero_add end, by calc m + succ n = succ (m + n) : by refl ... = succ (n + m) : by rw IH ... = succ n + m : by begin symmetry, apply L9 end end --#check L10 lemma L11 : ∀ (n : ℕ), 0 + n = n := assume n, by induction n; simp only [*, add_zero, add_succ] --#check L11 lemma L12 : ∀ (m n p : ℕ), (m + n) + p = m + (n + p) := assume m n p, begin induction p with p IH, by calc (m + n) + 0 = m + n : by refl ... = m + (n + 0) : by refl, by calc (m + n) + succ p = succ ((m + n) + p) : by refl ... = succ (m + (n + p)) : by rw IH ... = m + succ (n + p) : by refl ... = m + (n + succ p) : by refl end --#check L12 lemma L13 : ∀ (m n p : ℕ), succ (succ m) = succ (succ n) → n + p = m + p := assume m n p H, begin injection H with H', clear H, injection H' with H, rewrite H end --#check L13 lemma L14 : ∀ (m n p : ℕ), succ (succ m) = succ (succ n) → n + p = m + p := assume m n p H, begin injections with H1 H2, rewrite H2 end --#check L14 lemma L15 : ∀ (m n p : ℕ), succ (succ m) = succ (succ n) → n + p = m + p := assume m n p H, by injections; simp * --#check L15 lemma L16 : ∀ (m n : ℕ), succ m = 0 → n = n + 7 := assume m n H, by injections --#check L16 lemma L17 : ∀ (m n : ℕ), succ m = 0 → n = n + 7 := assume m n H, by contradiction --#check L17 lemma L18 : 7 = 4 → false := assume H, by injections --#check L18
270d0922bd23910fa883730016c3799d76601232
6b10c15e653d49d146378acda9f3692e9b5b1950
/examples/basic_skills/unnamed_473.lean
e6a9ff95603d7beb21a057fcfa6b639570959e5e
[]
no_license
gebner/mathematics_in_lean
3cf7f18767208ea6c3307ec3a67c7ac266d8514d
6d1462bba46d66a9b948fc1aef2714fd265cde0b
refs/heads/master
1,655,301,945,565
1,588,697,505,000
1,588,697,505,000
261,523,603
0
0
null
1,588,695,611,000
1,588,695,610,000
null
UTF-8
Lean
false
false
494
lean
variables (R : Type*) [comm_ring R] #check (add_assoc : ∀ a b c : R, a + b + c = a + (b + c)) #check (add_comm : ∀ a b : R, a + b = b + a) #check (zero_add : ∀ a : R, 0 + a = a) #check (add_left_neg : ∀ a : R, -a + a = 0) #check (mul_assoc : ∀ a b c : R, a * b * c = a * (b * c)) #check (mul_one : ∀ a : R, a * 1 = a) #check (one_mul : ∀ a : R, 1 * a = a) #check (mul_add : ∀ a b c : R, a * (b + c) = a * b + a * c) #check (add_mul : ∀ a b c : R, (a + b) * c = a * c + b * c)
2dde986541e82202fbc10138422eb47b6e914d20
137c667471a40116a7afd7261f030b30180468c2
/src/analysis/analytic/basic.lean
9cbcf6fe88f31c9c3aaddad0a3819801bc067dd3
[ "Apache-2.0" ]
permissive
bragadeesh153/mathlib
46bf814cfb1eecb34b5d1549b9117dc60f657792
b577bb2cd1f96eb47031878256856020b76f73cd
refs/heads/master
1,687,435,188,334
1,626,384,207,000
1,626,384,207,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
49,465
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, Yury Kudryashov -/ import analysis.calculus.formal_multilinear_series import analysis.specific_limits /-! # Analytic functions A function is analytic in one dimension around `0` if it can be written as a converging power series `Σ pₙ zⁿ`. This definition can be extended to any dimension (even in infinite dimension) by requiring that `pₙ` is a continuous `n`-multilinear map. In general, `pₙ` is not unique (in two dimensions, taking `p₂ (x, y) (x', y') = x y'` or `y x'` gives the same map when applied to a vector `(x, y) (x, y)`). A way to guarantee uniqueness is to take a symmetric `pₙ`, but this is not always possible in nonzero characteristic (in characteristic 2, the previous example has no symmetric representative). Therefore, we do not insist on symmetry or uniqueness in the definition, and we only require the existence of a converging series. The general framework is important to say that the exponential map on bounded operators on a Banach space is analytic, as well as the inverse on invertible operators. ## Main definitions Let `p` be a formal multilinear series from `E` to `F`, i.e., `p n` is a multilinear map on `E^n` for `n : ℕ`. * `p.radius`: the largest `r : ℝ≥0∞` such that `∥p n∥ * r^n` grows subexponentially, defined as a liminf. * `p.le_radius_of_bound`, `p.le_radius_of_bound_nnreal`, `p.le_radius_of_is_O`: if `∥p n∥ * r ^ n` is bounded above, then `r ≤ p.radius`; * `p.is_o_of_lt_radius`, `p.norm_mul_pow_le_mul_pow_of_lt_radius`, `p.is_o_one_of_lt_radius`, `p.norm_mul_pow_le_of_lt_radius`, `p.nnnorm_mul_pow_le_of_lt_radius`: if `r < p.radius`, then `∥p n∥ * r ^ n` tends to zero exponentially; * `p.lt_radius_of_is_O`: if `r ≠ 0` and `∥p n∥ * r ^ n = O(a ^ n)` for some `-1 < a < 1`, then `r < p.radius`; * `p.partial_sum n x`: the sum `∑_{i = 0}^{n-1} pᵢ xⁱ`. * `p.sum x`: the sum `∑'_{i = 0}^{∞} pᵢ xⁱ`. Additionally, let `f` be a function from `E` to `F`. * `has_fpower_series_on_ball f p x r`: on the ball of center `x` with radius `r`, `f (x + y) = ∑'_n pₙ yⁿ`. * `has_fpower_series_at f p x`: on some ball of center `x` with positive radius, holds `has_fpower_series_on_ball f p x r`. * `analytic_at 𝕜 f x`: there exists a power series `p` such that holds `has_fpower_series_at f p x`. We develop the basic properties of these notions, notably: * If a function admits a power series, it is continuous (see `has_fpower_series_on_ball.continuous_on` and `has_fpower_series_at.continuous_at` and `analytic_at.continuous_at`). * In a complete space, the sum of a formal power series with positive radius is well defined on the disk of convergence, see `formal_multilinear_series.has_fpower_series_on_ball`. * If a function admits a power series in a ball, then it is analytic at any point `y` of this ball, and the power series there can be expressed in terms of the initial power series `p` as `p.change_origin y`. See `has_fpower_series_on_ball.change_origin`. It follows in particular that the set of points at which a given function is analytic is open, see `is_open_analytic_at`. ## Implementation details We only introduce the radius of convergence of a power series, as `p.radius`. For a power series in finitely many dimensions, there is a finer (directional, coordinate-dependent) notion, describing the polydisk of convergence. This notion is more specific, and not necessary to build the general theory. We do not define it here. -/ noncomputable theory variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {G : Type*} [normed_group G] [normed_space 𝕜 G] open_locale topological_space classical big_operators nnreal filter ennreal open set filter asymptotics /-! ### The radius of a formal multilinear series -/ namespace formal_multilinear_series variables (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} /-- The radius of a formal multilinear series is the largest `r` such that the sum `Σ ∥pₙ∥ ∥y∥ⁿ` converges for all `∥y∥ < r`. This implies that `Σ pₙ yⁿ` converges for all `∥y∥ < r`, but these definitions are *not* equivalent in general. -/ def radius (p : formal_multilinear_series 𝕜 E F) : ℝ≥0∞ := ⨆ (r : ℝ≥0) (C : ℝ) (hr : ∀ n, ∥p n∥ * r ^ n ≤ C), (r : ℝ≥0∞) /-- If `∥pₙ∥ rⁿ` is bounded in `n`, then the radius of `p` is at least `r`. -/ lemma le_radius_of_bound (p : formal_multilinear_series 𝕜 E F) (C : ℝ) {r : ℝ≥0} (h : ∀ (n : ℕ), ∥p n∥ * r^n ≤ C) : (r : ℝ≥0∞) ≤ p.radius := le_supr_of_le r $ le_supr_of_le C $ (le_supr (λ _, (r : ℝ≥0∞)) h) /-- If `∥pₙ∥ rⁿ` is bounded in `n`, then the radius of `p` is at least `r`. -/ lemma le_radius_of_bound_nnreal (p : formal_multilinear_series 𝕜 E F) (C : ℝ≥0) {r : ℝ≥0} (h : ∀ (n : ℕ), nnnorm (p n) * r^n ≤ C) : (r : ℝ≥0∞) ≤ p.radius := p.le_radius_of_bound C $ λ n, by exact_mod_cast (h n) /-- If `∥pₙ∥ rⁿ = O(1)`, as `n → ∞`, then the radius of `p` is at least `r`. -/ lemma le_radius_of_is_O (h : is_O (λ n, ∥p n∥ * r^n) (λ n, (1 : ℝ)) at_top) : ↑r ≤ p.radius := exists.elim (is_O_one_nat_at_top_iff.1 h) $ λ C hC, p.le_radius_of_bound C $ λ n, (le_abs_self _).trans (hC n) lemma radius_eq_top_of_forall_nnreal_is_O (h : ∀ r : ℝ≥0, is_O (λ n, ∥p n∥ * r^n) (λ n, (1 : ℝ)) at_top) : p.radius = ∞ := ennreal.eq_top_of_forall_nnreal_le $ λ r, p.le_radius_of_is_O (h r) lemma radius_eq_top_of_eventually_eq_zero (h : ∀ᶠ n in at_top, p n = 0) : p.radius = ∞ := p.radius_eq_top_of_forall_nnreal_is_O $ λ r, (is_O_zero _ _).congr' (h.mono $ λ n hn, by simp [hn]) eventually_eq.rfl lemma radius_eq_top_of_forall_image_add_eq_zero (n : ℕ) (hn : ∀ m, p (m + n) = 0) : p.radius = ∞ := p.radius_eq_top_of_eventually_eq_zero $ mem_at_top_sets.2 ⟨n, λ k hk, nat.sub_add_cancel hk ▸ hn _⟩ /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` tends to zero exponentially: for some `0 < a < 1`, `∥p n∥ rⁿ = o(aⁿ)`. -/ lemma is_o_of_lt_radius (h : ↑r < p.radius) : ∃ a ∈ Ioo (0 : ℝ) 1, is_o (λ n, ∥p n∥ * r ^ n) (pow a) at_top := begin rw (tfae_exists_lt_is_o_pow (λ n, ∥p n∥ * r ^ n) 1).out 1 4, simp only [radius, lt_supr_iff] at h, rcases h with ⟨t, C, hC, rt⟩, rw [ennreal.coe_lt_coe, ← nnreal.coe_lt_coe] at rt, have : 0 < (t : ℝ), from r.coe_nonneg.trans_lt rt, rw [← div_lt_one this] at rt, refine ⟨_, rt, C, or.inr zero_lt_one, λ n, _⟩, calc abs (∥p n∥ * r ^ n) = (∥p n∥ * t ^ n) * (r / t) ^ n : by field_simp [mul_right_comm, abs_mul, this.ne'] ... ≤ C * (r / t) ^ n : mul_le_mul_of_nonneg_right (hC n) (pow_nonneg (div_nonneg r.2 t.2) _) end /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ = o(1)`. -/ lemma is_o_one_of_lt_radius (h : ↑r < p.radius) : is_o (λ n, ∥p n∥ * r ^ n) (λ _, 1 : ℕ → ℝ) at_top := let ⟨a, ha, hp⟩ := p.is_o_of_lt_radius h in hp.trans $ (is_o_pow_pow_of_lt_left ha.1.le ha.2).congr (λ n, rfl) one_pow /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` tends to zero exponentially: for some `0 < a < 1` and `C > 0`, `∥p n∥ * r ^ n ≤ C * a ^ n`. -/ lemma norm_mul_pow_le_mul_pow_of_lt_radius (h : ↑r < p.radius) : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), ∀ n, ∥p n∥ * r^n ≤ C * a^n := begin rcases ((tfae_exists_lt_is_o_pow (λ n, ∥p n∥ * r ^ n) 1).out 1 5).mp (p.is_o_of_lt_radius h) with ⟨a, ha, C, hC, H⟩, exact ⟨a, ha, C, hC, λ n, (le_abs_self _).trans (H n)⟩ end /-- If `r ≠ 0` and `∥pₙ∥ rⁿ = O(aⁿ)` for some `-1 < a < 1`, then `r < p.radius`. -/ lemma lt_radius_of_is_O (h₀ : r ≠ 0) {a : ℝ} (ha : a ∈ Ioo (-1 : ℝ) 1) (hp : is_O (λ n, ∥p n∥ * r ^ n) (pow a) at_top) : ↑r < p.radius := begin rcases ((tfae_exists_lt_is_o_pow (λ n, ∥p n∥ * r ^ n) 1).out 2 5).mp ⟨a, ha, hp⟩ with ⟨a, ha, C, hC, hp⟩, replace h₀ : 0 < r := pos_iff_ne_zero.2 h₀, lift a to ℝ≥0 using ha.1.le, have : (r : ℝ) < r / a := (lt_div_iff ha.1).2 (by simpa only [mul_one] using mul_lt_mul_of_pos_left ha.2 h₀), norm_cast at this, rw [← ennreal.coe_lt_coe] at this, refine this.trans_le (p.le_radius_of_bound C $ λ n, _), rw [nnreal.coe_div, div_pow, ← mul_div_assoc, div_le_iff (pow_pos ha.1 n)], exact (le_abs_self _).trans (hp n) end /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` is bounded. -/ lemma norm_mul_pow_le_of_lt_radius (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} (h : (r : ℝ≥0∞) < p.radius) : ∃ C > 0, ∀ n, ∥p n∥ * r^n ≤ C := let ⟨a, ha, C, hC, h⟩ := p.norm_mul_pow_le_mul_pow_of_lt_radius h in ⟨C, hC, λ n, (h n).trans $ mul_le_of_le_one_right hC.lt.le (pow_le_one _ ha.1.le ha.2.le)⟩ /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` is bounded. -/ lemma norm_le_div_pow_of_pos_of_lt_radius (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} (h0 : 0 < r) (h : (r : ℝ≥0∞) < p.radius) : ∃ C > 0, ∀ n, ∥p n∥ ≤ C / r ^ n := let ⟨C, hC, hp⟩ := p.norm_mul_pow_le_of_lt_radius h in ⟨C, hC, λ n, iff.mpr (le_div_iff (pow_pos h0 _)) (hp n)⟩ /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` is bounded. -/ lemma nnnorm_mul_pow_le_of_lt_radius (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} (h : (r : ℝ≥0∞) < p.radius) : ∃ C > 0, ∀ n, nnnorm (p n) * r^n ≤ C := let ⟨C, hC, hp⟩ := p.norm_mul_pow_le_of_lt_radius h in ⟨⟨C, hC.lt.le⟩, hC, by exact_mod_cast hp⟩ lemma le_radius_of_tendsto (p : formal_multilinear_series 𝕜 E F) {l : ℝ} (h : tendsto (λ n, ∥p n∥ * r^n) at_top (𝓝 l)) : ↑r ≤ p.radius := p.le_radius_of_is_O (is_O_one_of_tendsto _ h) lemma le_radius_of_summable_norm (p : formal_multilinear_series 𝕜 E F) (hs : summable (λ n, ∥p n∥ * r^n)) : ↑r ≤ p.radius := p.le_radius_of_tendsto hs.tendsto_at_top_zero lemma not_summable_norm_of_radius_lt_nnnorm (p : formal_multilinear_series 𝕜 E F) {x : E} (h : p.radius < nnnorm x) : ¬ summable (λ n, ∥p n∥ * ∥x∥^n) := λ hs, not_le_of_lt h (p.le_radius_of_summable_norm hs) lemma summable_norm_of_lt_radius (p : formal_multilinear_series 𝕜 E F) (h : ↑r < p.radius) : summable (λ n, ∥p n∥ * r^n) := begin obtain ⟨a, ha : a ∈ Ioo (0 : ℝ) 1, C, hC : 0 < C, hp⟩ := p.norm_mul_pow_le_mul_pow_of_lt_radius h, refine (summable_of_norm_bounded (λ n, (C : ℝ) * a ^ n) ((summable_geometric_of_lt_1 ha.1.le ha.2).mul_left _) (λ n, _)), specialize hp n, rwa real.norm_of_nonneg (mul_nonneg (norm_nonneg _) (pow_nonneg r.coe_nonneg n)) end lemma summable_of_nnnorm_lt_radius (p : formal_multilinear_series 𝕜 E F) [complete_space F] {x : E} (h : ↑(nnnorm x) < p.radius) : summable (λ n, p n (λ i, x)) := begin refine summable_of_norm_bounded (λ n, ∥p n∥ * (nnnorm x)^n) (p.summable_norm_of_lt_radius h) _, intros n, calc ∥(p n) (λ (i : fin n), x)∥ ≤ ∥p n∥ * (∏ i : fin n, ∥x∥) : continuous_multilinear_map.le_op_norm _ _ ... = ∥p n∥ * (nnnorm x)^n : by simp end lemma radius_eq_top_of_summable_norm (p : formal_multilinear_series 𝕜 E F) (hs : ∀ r : ℝ≥0, summable (λ n, ∥p n∥ * r^n)) : p.radius = ∞ := ennreal.eq_top_of_forall_nnreal_le (λ r, p.le_radius_of_summable_norm (hs r)) lemma radius_eq_top_iff_summable_norm (p : formal_multilinear_series 𝕜 E F) : p.radius = ∞ ↔ ∀ r : ℝ≥0, summable (λ n, ∥p n∥ * r^n) := begin split, { intros h r, obtain ⟨a, ha : a ∈ Ioo (0 : ℝ) 1, C, hC : 0 < C, hp⟩ := p.norm_mul_pow_le_mul_pow_of_lt_radius (show (r:ℝ≥0∞) < p.radius, from h.symm ▸ ennreal.coe_lt_top), refine (summable_of_norm_bounded (λ n, (C : ℝ) * a ^ n) ((summable_geometric_of_lt_1 ha.1.le ha.2).mul_left _) (λ n, _)), specialize hp n, rwa real.norm_of_nonneg (mul_nonneg (norm_nonneg _) (pow_nonneg r.coe_nonneg n)) }, { exact p.radius_eq_top_of_summable_norm } end /-- If the radius of `p` is positive, then `∥pₙ∥` grows at most geometrically. -/ lemma le_mul_pow_of_radius_pos (p : formal_multilinear_series 𝕜 E F) (h : 0 < p.radius) : ∃ C r (hC : 0 < C) (hr : 0 < r), ∀ n, ∥p n∥ ≤ C * r ^ n := begin rcases ennreal.lt_iff_exists_nnreal_btwn.1 h with ⟨r, r0, rlt⟩, have rpos : 0 < (r : ℝ), by simp [ennreal.coe_pos.1 r0], rcases norm_le_div_pow_of_pos_of_lt_radius p rpos rlt with ⟨C, Cpos, hCp⟩, refine ⟨C, r ⁻¹, Cpos, by simp [rpos], λ n, _⟩, convert hCp n, exact inv_pow' _ _, end /-- The radius of the sum of two formal series is at least the minimum of their two radii. -/ lemma min_radius_le_radius_add (p q : formal_multilinear_series 𝕜 E F) : min p.radius q.radius ≤ (p + q).radius := begin refine ennreal.le_of_forall_nnreal_lt (λ r hr, _), rw lt_min_iff at hr, have := ((p.is_o_one_of_lt_radius hr.1).add (q.is_o_one_of_lt_radius hr.2)).is_O, refine (p + q).le_radius_of_is_O ((is_O_of_le _ $ λ n, _).trans this), rw [← add_mul, normed_field.norm_mul, normed_field.norm_mul, norm_norm], exact mul_le_mul_of_nonneg_right ((norm_add_le _ _).trans (le_abs_self _)) (norm_nonneg _) end @[simp] lemma radius_neg (p : formal_multilinear_series 𝕜 E F) : (-p).radius = p.radius := by simp [radius] /-- Given a formal multilinear series `p` and a vector `x`, then `p.sum x` is the sum `Σ pₙ xⁿ`. A priori, it only behaves well when `∥x∥ < p.radius`. -/ protected def sum (p : formal_multilinear_series 𝕜 E F) (x : E) : F := ∑' n : ℕ , p n (λ i, x) /-- Given a formal multilinear series `p` and a vector `x`, then `p.partial_sum n x` is the sum `Σ pₖ xᵏ` for `k ∈ {0,..., n-1}`. -/ def partial_sum (p : formal_multilinear_series 𝕜 E F) (n : ℕ) (x : E) : F := ∑ k in finset.range n, p k (λ(i : fin k), x) /-- The partial sums of a formal multilinear series are continuous. -/ lemma partial_sum_continuous (p : formal_multilinear_series 𝕜 E F) (n : ℕ) : continuous (p.partial_sum n) := by continuity end formal_multilinear_series /-! ### Expanding a function as a power series -/ section variables {f g : E → F} {p pf pg : formal_multilinear_series 𝕜 E F} {x : E} {r r' : ℝ≥0∞} /-- Given a function `f : E → F` and a formal multilinear series `p`, we say that `f` has `p` as a power series on the ball of radius `r > 0` around `x` if `f (x + y) = ∑' pₙ yⁿ` for all `∥y∥ < r`. -/ structure has_fpower_series_on_ball (f : E → F) (p : formal_multilinear_series 𝕜 E F) (x : E) (r : ℝ≥0∞) : Prop := (r_le : r ≤ p.radius) (r_pos : 0 < r) (has_sum : ∀ {y}, y ∈ emetric.ball (0 : E) r → has_sum (λn:ℕ, p n (λ(i : fin n), y)) (f (x + y))) /-- Given a function `f : E → F` and a formal multilinear series `p`, we say that `f` has `p` as a power series around `x` if `f (x + y) = ∑' pₙ yⁿ` for all `y` in a neighborhood of `0`. -/ def has_fpower_series_at (f : E → F) (p : formal_multilinear_series 𝕜 E F) (x : E) := ∃ r, has_fpower_series_on_ball f p x r variable (𝕜) /-- Given a function `f : E → F`, we say that `f` is analytic at `x` if it admits a convergent power series expansion around `x`. -/ def analytic_at (f : E → F) (x : E) := ∃ (p : formal_multilinear_series 𝕜 E F), has_fpower_series_at f p x variable {𝕜} lemma has_fpower_series_on_ball.has_fpower_series_at (hf : has_fpower_series_on_ball f p x r) : has_fpower_series_at f p x := ⟨r, hf⟩ lemma has_fpower_series_at.analytic_at (hf : has_fpower_series_at f p x) : analytic_at 𝕜 f x := ⟨p, hf⟩ lemma has_fpower_series_on_ball.analytic_at (hf : has_fpower_series_on_ball f p x r) : analytic_at 𝕜 f x := hf.has_fpower_series_at.analytic_at lemma has_fpower_series_on_ball.has_sum_sub (hf : has_fpower_series_on_ball f p x r) {y : E} (hy : y ∈ emetric.ball x r) : has_sum (λ n : ℕ, p n (λ i, y - x)) (f y) := have y - x ∈ emetric.ball (0 : E) r, by simpa [edist_eq_coe_nnnorm_sub] using hy, by simpa only [add_sub_cancel'_right] using hf.has_sum this lemma has_fpower_series_on_ball.radius_pos (hf : has_fpower_series_on_ball f p x r) : 0 < p.radius := lt_of_lt_of_le hf.r_pos hf.r_le lemma has_fpower_series_at.radius_pos (hf : has_fpower_series_at f p x) : 0 < p.radius := let ⟨r, hr⟩ := hf in hr.radius_pos lemma has_fpower_series_on_ball.mono (hf : has_fpower_series_on_ball f p x r) (r'_pos : 0 < r') (hr : r' ≤ r) : has_fpower_series_on_ball f p x r' := ⟨le_trans hr hf.1, r'_pos, λ y hy, hf.has_sum (emetric.ball_subset_ball hr hy)⟩ protected lemma has_fpower_series_at.eventually (hf : has_fpower_series_at f p x) : ∀ᶠ r : ℝ≥0∞ in 𝓝[Ioi 0] 0, has_fpower_series_on_ball f p x r := let ⟨r, hr⟩ := hf in mem_sets_of_superset (Ioo_mem_nhds_within_Ioi (left_mem_Ico.2 hr.r_pos)) $ λ r' hr', hr.mono hr'.1 hr'.2.le lemma has_fpower_series_on_ball.add (hf : has_fpower_series_on_ball f pf x r) (hg : has_fpower_series_on_ball g pg x r) : has_fpower_series_on_ball (f + g) (pf + pg) x r := { r_le := le_trans (le_min_iff.2 ⟨hf.r_le, hg.r_le⟩) (pf.min_radius_le_radius_add pg), r_pos := hf.r_pos, has_sum := λ y hy, (hf.has_sum hy).add (hg.has_sum hy) } lemma has_fpower_series_at.add (hf : has_fpower_series_at f pf x) (hg : has_fpower_series_at g pg x) : has_fpower_series_at (f + g) (pf + pg) x := begin rcases (hf.eventually.and hg.eventually).exists with ⟨r, hr⟩, exact ⟨r, hr.1.add hr.2⟩ end lemma analytic_at.add (hf : analytic_at 𝕜 f x) (hg : analytic_at 𝕜 g x) : analytic_at 𝕜 (f + g) x := let ⟨pf, hpf⟩ := hf, ⟨qf, hqf⟩ := hg in (hpf.add hqf).analytic_at lemma has_fpower_series_on_ball.neg (hf : has_fpower_series_on_ball f pf x r) : has_fpower_series_on_ball (-f) (-pf) x r := { r_le := by { rw pf.radius_neg, exact hf.r_le }, r_pos := hf.r_pos, has_sum := λ y hy, (hf.has_sum hy).neg } lemma has_fpower_series_at.neg (hf : has_fpower_series_at f pf x) : has_fpower_series_at (-f) (-pf) x := let ⟨rf, hrf⟩ := hf in hrf.neg.has_fpower_series_at lemma analytic_at.neg (hf : analytic_at 𝕜 f x) : analytic_at 𝕜 (-f) x := let ⟨pf, hpf⟩ := hf in hpf.neg.analytic_at lemma has_fpower_series_on_ball.sub (hf : has_fpower_series_on_ball f pf x r) (hg : has_fpower_series_on_ball g pg x r) : has_fpower_series_on_ball (f - g) (pf - pg) x r := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma has_fpower_series_at.sub (hf : has_fpower_series_at f pf x) (hg : has_fpower_series_at g pg x) : has_fpower_series_at (f - g) (pf - pg) x := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma analytic_at.sub (hf : analytic_at 𝕜 f x) (hg : analytic_at 𝕜 g x) : analytic_at 𝕜 (f - g) x := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma has_fpower_series_on_ball.coeff_zero (hf : has_fpower_series_on_ball f pf x r) (v : fin 0 → E) : pf 0 v = f x := begin have v_eq : v = (λ i, 0) := subsingleton.elim _ _, have zero_mem : (0 : E) ∈ emetric.ball (0 : E) r, by simp [hf.r_pos], have : ∀ i ≠ 0, pf i (λ j, 0) = 0, { assume i hi, have : 0 < i := pos_iff_ne_zero.2 hi, exact continuous_multilinear_map.map_coord_zero _ (⟨0, this⟩ : fin i) rfl }, have A := (hf.has_sum zero_mem).unique (has_sum_single _ this), simpa [v_eq] using A.symm, end lemma has_fpower_series_at.coeff_zero (hf : has_fpower_series_at f pf x) (v : fin 0 → E) : pf 0 v = f x := let ⟨rf, hrf⟩ := hf in hrf.coeff_zero v /-- If a function admits a power series expansion, then it is exponentially close to the partial sums of this power series on strict subdisks of the disk of convergence. This version provides an upper estimate that decreases both in `∥y∥` and `n`. See also `has_fpower_series_on_ball.uniform_geometric_approx` for a weaker version. -/ lemma has_fpower_series_on_ball.uniform_geometric_approx' {r' : ℝ≥0} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ℝ≥0∞) < r) : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * (a * (∥y∥ / r')) ^ n) := begin obtain ⟨a, ha, C, hC, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), ∀ n, ∥p n∥ * r' ^n ≤ C * a^n := p.norm_mul_pow_le_mul_pow_of_lt_radius (h.trans_le hf.r_le), refine ⟨a, ha, C / (1 - a), div_pos hC (sub_pos.2 ha.2), λ y hy n, _⟩, have yr' : ∥y∥ < r', by { rw ball_0_eq at hy, exact hy }, have hr'0 : 0 < (r' : ℝ), from (norm_nonneg _).trans_lt yr', have : y ∈ emetric.ball (0 : E) r, { refine mem_emetric_ball_0_iff.2 (lt_trans _ h), exact_mod_cast yr' }, rw [norm_sub_rev, ← mul_div_right_comm], have ya : a * (∥y∥ / ↑r') ≤ a, from mul_le_of_le_one_right ha.1.le (div_le_one_of_le yr'.le r'.coe_nonneg), suffices : ∥p.partial_sum n y - f (x + y)∥ ≤ C * (a * (∥y∥ / r')) ^ n / (1 - a * (∥y∥ / r')), { refine this.trans _, apply_rules [div_le_div_of_le_left, sub_pos.2, div_nonneg, mul_nonneg, pow_nonneg, hC.lt.le, ha.1.le, norm_nonneg, nnreal.coe_nonneg, ha.2, (sub_le_sub_iff_left _).2]; apply_instance }, apply norm_sub_le_of_geometric_bound_of_has_sum (ya.trans_lt ha.2) _ (hf.has_sum this), assume n, calc ∥(p n) (λ (i : fin n), y)∥ ≤ ∥p n∥ * (∏ i : fin n, ∥y∥) : continuous_multilinear_map.le_op_norm _ _ ... = (∥p n∥ * r' ^ n) * (∥y∥ / r') ^ n : by field_simp [hr'0.ne', mul_right_comm] ... ≤ (C * a ^ n) * (∥y∥ / r') ^ n : mul_le_mul_of_nonneg_right (hp n) (pow_nonneg (div_nonneg (norm_nonneg _) r'.coe_nonneg) _) ... ≤ C * (a * (∥y∥ / r')) ^ n : by rw [mul_pow, mul_assoc] end /-- If a function admits a power series expansion, then it is exponentially close to the partial sums of this power series on strict subdisks of the disk of convergence. -/ lemma has_fpower_series_on_ball.uniform_geometric_approx {r' : ℝ≥0} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ℝ≥0∞) < r) : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * a ^ n) := begin obtain ⟨a, ha, C, hC, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * (a * (∥y∥ / r')) ^ n), from hf.uniform_geometric_approx' h, refine ⟨a, ha, C, hC, λ y hy n, (hp y hy n).trans _⟩, have yr' : ∥y∥ < r', by rwa ball_0_eq at hy, refine mul_le_mul_of_nonneg_left (pow_le_pow_of_le_left _ _ _) hC.lt.le, exacts [mul_nonneg ha.1.le (div_nonneg (norm_nonneg y) r'.coe_nonneg), mul_le_of_le_one_right ha.1.le (div_le_one_of_le yr'.le r'.coe_nonneg)] end /-- Taylor formula for an analytic function, `is_O` version. -/ lemma has_fpower_series_at.is_O_sub_partial_sum_pow (hf : has_fpower_series_at f p x) (n : ℕ) : is_O (λ y : E, f (x + y) - p.partial_sum n y) (λ y, ∥y∥ ^ n) (𝓝 0) := begin rcases hf with ⟨r, hf⟩, rcases ennreal.lt_iff_exists_nnreal_btwn.1 hf.r_pos with ⟨r', r'0, h⟩, obtain ⟨a, ha, C, hC, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * (a * (∥y∥ / r')) ^ n), from hf.uniform_geometric_approx' h, refine is_O_iff.2 ⟨C * (a / r') ^ n, _⟩, replace r'0 : 0 < (r' : ℝ), by exact_mod_cast r'0, filter_upwards [metric.ball_mem_nhds (0 : E) r'0], intros y hy, simpa [mul_pow, mul_div_assoc, mul_assoc, div_mul_eq_mul_div] using hp y hy n end -- hack to speed up simp when dealing with complicated types local attribute [-instance] unique.subsingleton pi.subsingleton /-- If `f` has formal power series `∑ n, pₙ` on a ball of radius `r`, then for `y, z` in any smaller ball, the norm of the difference `f y - f z - p 1 (λ _, y - z)` is bounded above by `C * (max ∥y - x∥ ∥z - x∥) * ∥y - z∥`. This lemma formulates this property using `is_O` and `filter.principal` on `E × E`. -/ lemma has_fpower_series_on_ball.is_O_image_sub_image_sub_deriv_principal (hf : has_fpower_series_on_ball f p x r) (hr : r' < r) : is_O (λ y : E × E, f y.1 - f y.2 - (p 1 (λ _, y.1 - y.2))) (λ y, ∥y - (x, x)∥ * ∥y.1 - y.2∥) (𝓟 $ emetric.ball (x, x) r') := begin lift r' to ℝ≥0 using ne_top_of_lt hr, rcases (zero_le r').eq_or_lt with rfl|hr'0, { simp }, obtain ⟨a, ha, C, hC : 0 < C, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), ∀ (n : ℕ), ∥p n∥ * ↑r' ^ n ≤ C * a ^ n, from p.norm_mul_pow_le_mul_pow_of_lt_radius (hr.trans_le hf.r_le), simp only [← le_div_iff (pow_pos (nnreal.coe_pos.2 hr'0) _)] at hp, set L : E × E → ℝ := λ y, (C * (a / r') ^ 2) * (∥y - (x, x)∥ * ∥y.1 - y.2∥) * (a / (1 - a) ^ 2 + 2 / (1 - a)), have hL : ∀ y ∈ emetric.ball (x, x) r', ∥f y.1 - f y.2 - (p 1 (λ _, y.1 - y.2))∥ ≤ L y, { intros y hy', have hy : y ∈ (emetric.ball x r).prod (emetric.ball x r), { rw [emetric.ball_prod_same], exact emetric.ball_subset_ball hr.le hy' }, set A : ℕ → F := λ n, p n (λ _, y.1 - x) - p n (λ _, y.2 - x), have hA : has_sum (λ n, A (n + 2)) (f y.1 - f y.2 - (p 1 (λ _, y.1 - y.2))), { convert (has_sum_nat_add_iff' 2).2 ((hf.has_sum_sub hy.1).sub (hf.has_sum_sub hy.2)), rw [finset.sum_range_succ, finset.sum_range_one, hf.coeff_zero, hf.coeff_zero, sub_self, zero_add, ← subsingleton.pi_single_eq (0 : fin 1) (y.1 - x), pi.single, ← subsingleton.pi_single_eq (0 : fin 1) (y.2 - x), pi.single, ← (p 1).map_sub, ← pi.single, subsingleton.pi_single_eq, sub_sub_sub_cancel_right] }, rw [emetric.mem_ball, edist_eq_coe_nnnorm_sub, ennreal.coe_lt_coe] at hy', set B : ℕ → ℝ := λ n, (C * (a / r') ^ 2) * (∥y - (x, x)∥ * ∥y.1 - y.2∥) * ((n + 2) * a ^ n), have hAB : ∀ n, ∥A (n + 2)∥ ≤ B n := λ n, calc ∥A (n + 2)∥ ≤ ∥p (n + 2)∥ * ↑(n + 2) * ∥y - (x, x)∥ ^ (n + 1) * ∥y.1 - y.2∥ : by simpa [fintype.card_fin, pi_norm_const, prod.norm_def, pi.sub_def, prod.fst_sub, prod.snd_sub, sub_sub_sub_cancel_right] using (p $ n + 2).norm_image_sub_le (λ _, y.1 - x) (λ _, y.2 - x) ... = ∥p (n + 2)∥ * ∥y - (x, x)∥ ^ n * (↑(n + 2) * ∥y - (x, x)∥ * ∥y.1 - y.2∥) : by { rw [pow_succ ∥y - (x, x)∥], ac_refl } ... ≤ (C * a ^ (n + 2) / r' ^ (n + 2)) * r' ^ n * (↑(n + 2) * ∥y - (x, x)∥ * ∥y.1 - y.2∥) : by apply_rules [mul_le_mul_of_nonneg_right, mul_le_mul, hp, pow_le_pow_of_le_left, hy'.le, norm_nonneg, pow_nonneg, div_nonneg, mul_nonneg, nat.cast_nonneg, hC.le, r'.coe_nonneg, ha.1.le] ... = B n : by { field_simp [B, pow_succ, hr'0.ne'], simp [mul_assoc, mul_comm, mul_left_comm] }, have hBL : has_sum B (L y), { apply has_sum.mul_left, simp only [add_mul], have : ∥a∥ < 1, by simp only [real.norm_eq_abs, abs_of_pos ha.1, ha.2], convert (has_sum_coe_mul_geometric_of_norm_lt_1 this).add ((has_sum_geometric_of_norm_lt_1 this).mul_left 2) }, exact hA.norm_le_of_bounded hBL hAB }, suffices : is_O L (λ y, ∥y - (x, x)∥ * ∥y.1 - y.2∥) (𝓟 (emetric.ball (x, x) r')), { refine (is_O.of_bound 1 (eventually_principal.2 $ λ y hy, _)).trans this, rw one_mul, exact (hL y hy).trans (le_abs_self _) }, simp_rw [L, mul_right_comm _ (_ * _)], exact (is_O_refl _ _).const_mul_left _, end /-- If `f` has formal power series `∑ n, pₙ` on a ball of radius `r`, then for `y, z` in any smaller ball, the norm of the difference `f y - f z - p 1 (λ _, y - z)` is bounded above by `C * (max ∥y - x∥ ∥z - x∥) * ∥y - z∥`. -/ lemma has_fpower_series_on_ball.image_sub_sub_deriv_le (hf : has_fpower_series_on_ball f p x r) (hr : r' < r) : ∃ C, ∀ (y z ∈ emetric.ball x r'), ∥f y - f z - (p 1 (λ _, y - z))∥ ≤ C * (max ∥y - x∥ ∥z - x∥) * ∥y - z∥ := by simpa only [is_O_principal, mul_assoc, normed_field.norm_mul, norm_norm, prod.forall, emetric.mem_ball, prod.edist_eq, max_lt_iff, and_imp] using hf.is_O_image_sub_image_sub_deriv_principal hr /-- If `f` has formal power series `∑ n, pₙ` at `x`, then `f y - f z - p 1 (λ _, y - z) = O(∥(y, z) - (x, x)∥ * ∥y - z∥)` as `(y, z) → (x, x)`. In particular, `f` is strictly differentiable at `x`. -/ lemma has_fpower_series_at.is_O_image_sub_norm_mul_norm_sub (hf : has_fpower_series_at f p x) : is_O (λ y : E × E, f y.1 - f y.2 - (p 1 (λ _, y.1 - y.2))) (λ y, ∥y - (x, x)∥ * ∥y.1 - y.2∥) (𝓝 (x, x)) := begin rcases hf with ⟨r, hf⟩, rcases ennreal.lt_iff_exists_nnreal_btwn.1 hf.r_pos with ⟨r', r'0, h⟩, refine (hf.is_O_image_sub_image_sub_deriv_principal h).mono _, exact le_principal_iff.2 (emetric.ball_mem_nhds _ r'0) end /-- If a function admits a power series expansion at `x`, then it is the uniform limit of the partial sums of this power series on strict subdisks of the disk of convergence, i.e., `f (x + y)` is the uniform limit of `p.partial_sum n y` there. -/ lemma has_fpower_series_on_ball.tendsto_uniformly_on {r' : ℝ≥0} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ℝ≥0∞) < r) : tendsto_uniformly_on (λ n y, p.partial_sum n y) (λ y, f (x + y)) at_top (metric.ball (0 : E) r') := begin obtain ⟨a, ha, C, hC, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * a ^ n), from hf.uniform_geometric_approx h, refine metric.tendsto_uniformly_on_iff.2 (λ ε εpos, _), have L : tendsto (λ n, (C : ℝ) * a^n) at_top (𝓝 ((C : ℝ) * 0)) := tendsto_const_nhds.mul (tendsto_pow_at_top_nhds_0_of_lt_1 ha.1.le ha.2), rw mul_zero at L, refine (L.eventually (gt_mem_nhds εpos)).mono (λ n hn y hy, _), rw dist_eq_norm, exact (hp y hy n).trans_lt hn end /-- If a function admits a power series expansion at `x`, then it is the locally uniform limit of the partial sums of this power series on the disk of convergence, i.e., `f (x + y)` is the locally uniform limit of `p.partial_sum n y` there. -/ lemma has_fpower_series_on_ball.tendsto_locally_uniformly_on (hf : has_fpower_series_on_ball f p x r) : tendsto_locally_uniformly_on (λ n y, p.partial_sum n y) (λ y, f (x + y)) at_top (emetric.ball (0 : E) r) := begin assume u hu x hx, rcases ennreal.lt_iff_exists_nnreal_btwn.1 hx with ⟨r', xr', hr'⟩, have : emetric.ball (0 : E) r' ∈ 𝓝 x := is_open.mem_nhds emetric.is_open_ball xr', refine ⟨emetric.ball (0 : E) r', mem_nhds_within_of_mem_nhds this, _⟩, simpa [metric.emetric_ball_nnreal] using hf.tendsto_uniformly_on hr' u hu end /-- If a function admits a power series expansion at `x`, then it is the uniform limit of the partial sums of this power series on strict subdisks of the disk of convergence, i.e., `f y` is the uniform limit of `p.partial_sum n (y - x)` there. -/ lemma has_fpower_series_on_ball.tendsto_uniformly_on' {r' : ℝ≥0} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ℝ≥0∞) < r) : tendsto_uniformly_on (λ n y, p.partial_sum n (y - x)) f at_top (metric.ball (x : E) r') := begin convert (hf.tendsto_uniformly_on h).comp (λ y, y - x), { simp [(∘)] }, { ext z, simp [dist_eq_norm] } end /-- If a function admits a power series expansion at `x`, then it is the locally uniform limit of the partial sums of this power series on the disk of convergence, i.e., `f y` is the locally uniform limit of `p.partial_sum n (y - x)` there. -/ lemma has_fpower_series_on_ball.tendsto_locally_uniformly_on' (hf : has_fpower_series_on_ball f p x r) : tendsto_locally_uniformly_on (λ n y, p.partial_sum n (y - x)) f at_top (emetric.ball (x : E) r) := begin have A : continuous_on (λ (y : E), y - x) (emetric.ball (x : E) r) := (continuous_id.sub continuous_const).continuous_on, convert (hf.tendsto_locally_uniformly_on).comp (λ (y : E), y - x) _ A, { ext z, simp }, { assume z, simp [edist_eq_coe_nnnorm, edist_eq_coe_nnnorm_sub] } end /-- If a function admits a power series expansion on a disk, then it is continuous there. -/ lemma has_fpower_series_on_ball.continuous_on (hf : has_fpower_series_on_ball f p x r) : continuous_on f (emetric.ball x r) := hf.tendsto_locally_uniformly_on'.continuous_on $ λ n, ((p.partial_sum_continuous n).comp (continuous_id.sub continuous_const)).continuous_on lemma has_fpower_series_at.continuous_at (hf : has_fpower_series_at f p x) : continuous_at f x := let ⟨r, hr⟩ := hf in hr.continuous_on.continuous_at (emetric.ball_mem_nhds x (hr.r_pos)) lemma analytic_at.continuous_at (hf : analytic_at 𝕜 f x) : continuous_at f x := let ⟨p, hp⟩ := hf in hp.continuous_at /-- In a complete space, the sum of a converging power series `p` admits `p` as a power series. This is not totally obvious as we need to check the convergence of the series. -/ lemma formal_multilinear_series.has_fpower_series_on_ball [complete_space F] (p : formal_multilinear_series 𝕜 E F) (h : 0 < p.radius) : has_fpower_series_on_ball p.sum p 0 p.radius := { r_le := le_refl _, r_pos := h, has_sum := λ y hy, begin rw zero_add, replace hy : (nnnorm y : ℝ≥0∞) < p.radius, by { convert hy, exact (edist_eq_coe_nnnorm _).symm }, exact (p.summable_of_nnnorm_lt_radius hy).has_sum end } lemma has_fpower_series_on_ball.sum [complete_space F] (h : has_fpower_series_on_ball f p x r) {y : E} (hy : y ∈ emetric.ball (0 : E) r) : f (x + y) = p.sum y := begin have A := h.has_sum hy, have B := (p.has_fpower_series_on_ball h.radius_pos).has_sum (lt_of_lt_of_le hy h.r_le), simpa using A.unique B end /-- The sum of a converging power series is continuous in its disk of convergence. -/ lemma formal_multilinear_series.continuous_on [complete_space F] : continuous_on p.sum (emetric.ball 0 p.radius) := begin cases (zero_le p.radius).eq_or_lt with h h, { simp [← h, continuous_on_empty] }, { exact (p.has_fpower_series_on_ball h).continuous_on } end end /-! ### Changing origin in a power series If a function is analytic in a disk `D(x, R)`, then it is analytic in any disk contained in that one. Indeed, one can write $$ f (x + y + z) = \sum_{n} p_n (y + z)^n = \sum_{n, k} \binom{n}{k} p_n y^{n-k} z^k = \sum_{k} \Bigl(\sum_{n} \binom{n}{k} p_n y^{n-k}\Bigr) z^k. $$ The corresponding power series has thus a `k`-th coefficient equal to $\sum_{n} \binom{n}{k} p_n y^{n-k}$. In the general case where `pₙ` is a multilinear map, this has to be interpreted suitably: instead of having a binomial coefficient, one should sum over all possible subsets `s` of `fin n` of cardinal `k`, and attribute `z` to the indices in `s` and `y` to the indices outside of `s`. In this paragraph, we implement this. The new power series is called `p.change_origin y`. Then, we check its convergence and the fact that its sum coincides with the original sum. The outcome of this discussion is that the set of points where a function is analytic is open. -/ namespace formal_multilinear_series variables (p : formal_multilinear_series 𝕜 E F) {x y : E} {r : ℝ≥0} /-- Changing the origin of a formal multilinear series `p`, so that `p.sum (x+y) = (p.change_origin x).sum y` when this makes sense. Here, we don't use the bracket notation `⟨n, s, hs⟩` in place of the argument `i` in the lambda, as this leads to a bad definition with auxiliary `_match` statements, but we will try to use pattern matching in lambdas as much as possible in the proofs below to increase readability. -/ def change_origin (x : E) : formal_multilinear_series 𝕜 E F := λ k, ∑' i : Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}, (p i.1).restr i.2 i.2.2 x /-- Auxiliary lemma controlling the summability of the sequence appearing in the definition of `p.change_origin`, first version. -/ -- Note here and below it is necessary to use `@` and provide implicit arguments using `_`, -- so that it is possible to use pattern matching in the lambda. -- Overall this seems a good trade-off in readability. lemma change_origin_summable_aux1 (h : (nnnorm x + r : ℝ≥0∞) < p.radius) : @summable ℝ _ _ _ ((λ ⟨n, s⟩, ∥p n∥ * ∥x∥ ^ (n - s.card) * r ^ s.card) : (Σ (n : ℕ), finset (fin n)) → ℝ) := begin obtain ⟨a, ha, C, hC, hp : ∀ n, ∥p n∥ * (∥x∥ + ↑r) ^ n ≤ C * a ^ n⟩ := p.norm_mul_pow_le_mul_pow_of_lt_radius h, set B : (Σ n, finset (fin n)) → ℝ := λ ⟨n, s⟩, ∥p n∥ * ∥x∥ ^ (n - s.card) * r ^ s.card, have H : ∀ n s, 0 ≤ B ⟨n, s⟩ := λ n s, by apply_rules [mul_nonneg, pow_nonneg, norm_nonneg, r.2], rw summable_sigma_of_nonneg (λ ⟨n, s⟩, H n s), have : ∀ n, has_sum (λ s, B ⟨n, s⟩) (∥p n∥ * (∥x∥ + r) ^ n), { simpa only [← fin.sum_pow_mul_eq_add_pow, finset.mul_sum, ← mul_assoc, add_comm _ ↑r, mul_right_comm] using λ n, has_sum_fintype (λ s, B ⟨n, s⟩) }, refine ⟨λ n, (this n).summable, _⟩, simp only [(this _).tsum_eq], exact summable_of_nonneg_of_le (λ n, (this n).nonneg (H n)) hp ((summable_geometric_of_lt_1 ha.1.le ha.2).mul_left _) end /-- Auxiliary lemma controlling the summability of the sequence appearing in the definition of `p.change_origin`, second version. -/ lemma change_origin_summable_aux2 (h : (nnnorm x + r : ℝ≥0∞) < p.radius) : @summable ℝ _ _ _ ((λ ⟨k, n, s, hs⟩, ∥(p n).restr s hs x∥ * ↑r ^ k) : (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ) := begin let Bnorm : (Σ (n : ℕ), finset (fin n)) → ℝ := λ ⟨n, s⟩, ∥p n∥ * ∥x∥ ^ (n - s.card) * r ^ s.card, have SBnorm : summable Bnorm := p.change_origin_summable_aux1 h, let Anorm : (Σ (n : ℕ), finset (fin n)) → ℝ := λ ⟨n, s⟩, ∥(p n).restr s rfl x∥ * r ^ s.card, have SAnorm : summable Anorm, { refine summable_of_norm_bounded _ SBnorm (λ i, _), rcases i with ⟨n, s⟩, suffices H : ∥(p n).restr s rfl x∥ * (r : ℝ) ^ s.card ≤ (∥p n∥ * ∥x∥ ^ (n - finset.card s) * r ^ s.card), { have : ∥(r: ℝ)∥ = r, by rw [real.norm_eq_abs, abs_of_nonneg (nnreal.coe_nonneg _)], simpa [Anorm, Bnorm, this] using H }, exact mul_le_mul_of_nonneg_right ((p n).norm_restr s rfl x) (pow_nonneg (nnreal.coe_nonneg _) _) }, let e : (Σ (n : ℕ), finset (fin n)) ≃ (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // finset.card s = k}) := { to_fun := λ ⟨n, s⟩, ⟨s.card, n, s, rfl⟩, inv_fun := λ ⟨k, n, s, hs⟩, ⟨n, s⟩, left_inv := λ ⟨n, s⟩, rfl, right_inv := λ ⟨k, n, s, hs⟩, by { induction hs, refl } }, rw ← e.summable_iff, convert SAnorm, ext ⟨n, s⟩, refl end /-- An auxiliary definition for `change_origin_radius`. -/ def change_origin_summable_aux_j (k : ℕ) : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // finset.card s = k}) := λ ⟨n, s, hs⟩, ⟨k, n, s, hs⟩ lemma change_origin_summable_aux_j_injective (k : ℕ) : function.injective (change_origin_summable_aux_j k) := begin rintros ⟨_, ⟨_, _⟩⟩ ⟨_, ⟨_, _⟩⟩ a, simp only [change_origin_summable_aux_j, true_and, eq_self_iff_true, heq_iff_eq, sigma.mk.inj_iff] at a, rcases a with ⟨rfl, a⟩, simpa using a, end /-- Auxiliary lemma controlling the summability of the sequence appearing in the definition of `p.change_origin`, third version. -/ lemma change_origin_summable_aux3 (k : ℕ) (h : (nnnorm x : ℝ≥0∞) < p.radius) : @summable ℝ _ _ _ (λ ⟨n, s, hs⟩, ∥(p n).restr s hs x∥ : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ) := begin obtain ⟨r, rpos, hr⟩ : ∃ (r : ℝ≥0), 0 < r ∧ ((nnnorm x + r) : ℝ≥0∞) < p.radius := ennreal.lt_iff_exists_add_pos_lt.mp h, have S : @summable ℝ _ _ _ ((λ ⟨n, s, hs⟩, ∥(p n).restr s hs x∥ * (r : ℝ) ^ k) : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ), { convert (p.change_origin_summable_aux2 hr).comp_injective (change_origin_summable_aux_j_injective k), -- again, cleanup that could be done by `tidy`: ext ⟨_, ⟨_, _⟩⟩, refl }, have : (r : ℝ)^k ≠ 0, by simp [pow_ne_zero, nnreal.coe_eq_zero, ne_of_gt rpos], apply (summable_mul_right_iff this).2, convert S, -- again, cleanup that could be done by `tidy`: ext ⟨_, ⟨_, _⟩⟩, refl, end -- FIXME this causes a deterministic timeout with `-T50000` /-- The radius of convergence of `p.change_origin x` is at least `p.radius - ∥x∥`. In other words, `p.change_origin x` is well defined on the largest ball contained in the original ball of convergence.-/ lemma change_origin_radius : p.radius - nnnorm x ≤ (p.change_origin x).radius := begin cases le_or_lt p.radius (nnnorm x) with h h, { have : radius p - ↑(nnnorm x) = 0 := ennreal.sub_eq_zero_of_le h, rw this, exact zero_le _ }, refine ennreal.le_of_forall_nnreal_lt (λ r hr, _), rw [ennreal.lt_sub_iff_add_lt, add_comm] at hr, let A : (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ := λ ⟨k, n, s, hs⟩, ∥(p n).restr s hs x∥ * (r : ℝ) ^ k, have SA : summable A := p.change_origin_summable_aux2 hr, have A_nonneg : ∀ i, 0 ≤ A i, { rintros ⟨k, n, s, hs⟩, change 0 ≤ ∥(p n).restr s hs x∥ * (r : ℝ) ^ k, refine mul_nonneg (norm_nonneg _) (pow_nonneg (nnreal.coe_nonneg _) _) }, have tsum_nonneg : 0 ≤ tsum A := tsum_nonneg A_nonneg, refine le_radius_of_bound _ (tsum A) (λ k, _), calc ∥change_origin p x k∥ * ↑r ^ k ≤ (∑' i : Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}, ∥(p i.1).restr i.2.1 i.2.2 x∥) * r ^ k : begin apply mul_le_mul_of_nonneg_right _ (pow_nonneg (nnreal.coe_nonneg _) _), apply norm_tsum_le_tsum_norm, convert p.change_origin_summable_aux3 k h, ext ⟨_, _, _⟩, refl end ... = tsum (λ i, ∥(p i.1).restr i.2.1 i.2.2 x∥ * ↑r ^ k : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ) : begin rw tsum_mul_right, end ... = tsum (A ∘ change_origin_summable_aux_j k) : begin congr, ext ⟨_, _, _⟩, refl end ... ≤ tsum A : tsum_comp_le_tsum_of_inj SA A_nonneg (change_origin_summable_aux_j_injective k) end -- From this point on, assume that the space is complete, to make sure that series that converge -- in norm also converge in `F`. variable [complete_space F] /-- The `k`-th coefficient of `p.change_origin` is the sum of a summable series. -/ lemma change_origin_has_sum (k : ℕ) (h : (nnnorm x : ℝ≥0∞) < p.radius) : @has_sum (E [×k]→L[𝕜] F) _ _ _ ((λ i, (p i.1).restr i.2.1 i.2.2 x) : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → (E [×k]→L[𝕜] F)) (p.change_origin x k) := begin apply summable.has_sum, apply summable_of_summable_norm, convert p.change_origin_summable_aux3 k h, ext ⟨_, _, _⟩, refl end /-- Summing the series `p.change_origin x` at a point `y` gives back `p (x + y)`-/ theorem change_origin_eval (h : (nnnorm x + nnnorm y : ℝ≥0∞) < p.radius) : has_sum ((λk:ℕ, p.change_origin x k (λ (i : fin k), y))) (p.sum (x + y)) := begin /- The series on the left is a series of series. If we order the terms differently, we get back to `p.sum (x + y)`, in which the `n`-th term is expanded by multilinearity. In the proof below, the term on the left is the sum of a series of terms `A`, the sum on the right is the sum of a series of terms `B`, and we show that they correspond to each other by reordering to conclude the proof. -/ have radius_pos : 0 < p.radius := lt_of_le_of_lt (zero_le _) h, -- `A` is the terms of the series whose sum gives the series for `p.change_origin` let A : (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // s.card = k}) → F := λ ⟨k, n, s, hs⟩, (p n).restr s hs x (λ(i : fin k), y), -- `B` is the terms of the series whose sum gives `p (x + y)`, after expansion by multilinearity. let B : (Σ (n : ℕ), finset (fin n)) → F := λ ⟨n, s⟩, (p n).restr s rfl x (λ (i : fin s.card), y), let Bnorm : (Σ (n : ℕ), finset (fin n)) → ℝ := λ ⟨n, s⟩, ∥p n∥ * ∥x∥ ^ (n - s.card) * ∥y∥ ^ s.card, have SBnorm : summable Bnorm, by convert p.change_origin_summable_aux1 h, have SB : summable B, { refine summable_of_norm_bounded _ SBnorm _, rintros ⟨n, s⟩, calc ∥(p n).restr s rfl x (λ (i : fin s.card), y)∥ ≤ ∥(p n).restr s rfl x∥ * ∥y∥ ^ s.card : begin convert ((p n).restr s rfl x).le_op_norm (λ (i : fin s.card), y), simp [(finset.prod_const (∥y∥))], end ... ≤ (∥p n∥ * ∥x∥ ^ (n - s.card)) * ∥y∥ ^ s.card : mul_le_mul_of_nonneg_right ((p n).norm_restr _ _ _) (pow_nonneg (norm_nonneg _) _) }, -- Check that indeed the sum of `B` is `p (x + y)`. have has_sum_B : has_sum B (p.sum (x + y)), { have K1 : ∀ n, has_sum (λ (s : finset (fin n)), B ⟨n, s⟩) (p n (λ (i : fin n), x + y)), { assume n, have : (p n) (λ (i : fin n), y + x) = ∑ s : finset (fin n), p n (finset.piecewise s (λ (i : fin n), y) (λ (i : fin n), x)) := (p n).map_add_univ (λ i, y) (λ i, x), simp [add_comm y x] at this, rw this, exact has_sum_fintype _ }, have K2 : has_sum (λ (n : ℕ), (p n) (λ (i : fin n), x + y)) (p.sum (x + y)), { have : x + y ∈ emetric.ball (0 : E) p.radius, { apply lt_of_le_of_lt _ h, rw [edist_eq_coe_nnnorm, ← ennreal.coe_add, ennreal.coe_le_coe], exact norm_add_le x y }, simpa using (p.has_fpower_series_on_ball radius_pos).has_sum this }, exact has_sum.sigma_of_has_sum K2 K1 SB }, -- Deduce that the sum of `A` is also `p (x + y)`, as the terms `A` and `B` are the same up to -- reordering have has_sum_A : has_sum A (p.sum (x + y)), { let e : (Σ (n : ℕ), finset (fin n)) ≃ (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // finset.card s = k}) := { to_fun := λ ⟨n, s⟩, ⟨s.card, n, s, rfl⟩, inv_fun := λ ⟨k, n, s, hs⟩, ⟨n, s⟩, left_inv := λ ⟨n, s⟩, rfl, right_inv := λ ⟨k, n, s, hs⟩, by { induction hs, refl } }, have : A ∘ e = B, by { ext ⟨⟩, refl }, rw ← e.has_sum_iff, convert has_sum_B }, -- Summing `A ⟨k, c⟩` with fixed `k` and varying `c` is exactly the `k`-th term in the series -- defining `p.change_origin`, by definition have J : ∀k, has_sum (λ c, A ⟨k, c⟩) (p.change_origin x k (λ(i : fin k), y)), { assume k, have : (nnnorm x : ℝ≥0∞) < radius p := lt_of_le_of_lt (le_self_add) h, convert continuous_multilinear_map.has_sum_eval (p.change_origin_has_sum k this) (λ(i : fin k), y), ext ⟨_, _, _⟩, refl }, exact has_sum_A.sigma J end end formal_multilinear_series section variables [complete_space F] {f : E → F} {p : formal_multilinear_series 𝕜 E F} {x y : E} {r : ℝ≥0∞} /-- If a function admits a power series expansion `p` on a ball `B (x, r)`, then it also admits a power series on any subball of this ball (even with a different center), given by `p.change_origin`. -/ theorem has_fpower_series_on_ball.change_origin (hf : has_fpower_series_on_ball f p x r) (h : (nnnorm y : ℝ≥0∞) < r) : has_fpower_series_on_ball f (p.change_origin y) (x + y) (r - nnnorm y) := { r_le := begin apply le_trans _ p.change_origin_radius, exact ennreal.sub_le_sub hf.r_le (le_refl _) end, r_pos := by simp [h], has_sum := begin assume z hz, have A : (nnnorm y : ℝ≥0∞) + nnnorm z < r, { have : edist z 0 < r - ↑(nnnorm y) := hz, rwa [edist_eq_coe_nnnorm, ennreal.lt_sub_iff_add_lt, add_comm] at this }, convert p.change_origin_eval (lt_of_lt_of_le A hf.r_le), have : y + z ∈ emetric.ball (0 : E) r := calc edist (y + z) 0 ≤ ↑(nnnorm y) + ↑(nnnorm z) : by { rw edist_eq_coe_nnnorm, exact_mod_cast nnnorm_add_le y z } ... < r : A, simpa only [add_assoc] using hf.sum this end } lemma has_fpower_series_on_ball.analytic_at_of_mem (hf : has_fpower_series_on_ball f p x r) (h : y ∈ emetric.ball x r) : analytic_at 𝕜 f y := begin have : (nnnorm (y - x) : ℝ≥0∞) < r, by simpa [edist_eq_coe_nnnorm_sub] using h, have := hf.change_origin this, rw [add_sub_cancel'_right] at this, exact this.analytic_at end variables (𝕜 f) lemma is_open_analytic_at : is_open {x | analytic_at 𝕜 f x} := begin rw is_open_iff_forall_mem_open, rintro x ⟨p, r, hr⟩, refine ⟨emetric.ball x r, λ y hy, hr.analytic_at_of_mem hy, emetric.is_open_ball, _⟩, simp only [edist_self, emetric.mem_ball, hr.r_pos] end variables {𝕜 f} end
38bde402c5cf4a6b320eba50bd153b6f11b95817
1890046a4987fbd27f3f50dbac83f3ce095556d5
/01_Equality/06_properties.lean
3533227125b5910db63a0dfc01f2ec77702e7e95
[]
no_license
kbhuynh/cs-dm
9f335727d1779f7c3d9e8221a52b4c9c106659ba
4041bd73618a49ef6870a1a80764e8947e60e768
refs/heads/master
1,585,353,017,958
1,536,055,215,000
1,536,055,215,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,032
lean
/- HOMEWORK: Read, complete, submit. We've seen that equality is reflexive. That is, everything is equal to itself. It is also symmetric in the sense that if any value, a, is equal to some other value, b, i.e., if a = b, then b is also equal to a, i.e., b = a. What this means is we have an inference rule that both expresses the symmetric property of equality and allows us to compute a proof of b = a from any proof of a = b, no matter what a and b are (no matter what type, T, a and b have, and no matter what values they have of this type). -/ /- (T: Type) (a b: T) (ab: a = b) ------------------------------ (eq.symm) ba: b = a -/ -- Let's see it in action in four lines def a := 1 def b := 2 - 1 lemma ab : a = b := rfl #check ab -- a proof of a = b #check (eq.symm ab) -- a proof of b = a! /- This is a big success. We understand not only the property of being symmetric but that we can use symmetry to derive new proofs from proofs that we already have. In fact, eq.symm is a program that does just this derivation, as we see here! -/ /- Finally we come to the notion that equality is also transitive. That means that for any values, a, b, and c, if a = b, and if b = c, then it must be that consequently a = c as well. {T : Type}, { a b c: T }, ab: a = b, bc: b = c ------------ (eq.trans) ac: a = c That is, if given proofs of a = b and b = c, eq.symm constructs and returns a proof of a = c. Let's see it in action. We've already got variables a and b to work with. We need one more, c. -/ def c := 1 /- We've also already got a proof of a = b. It's easy to generate one of b = c. -/ lemma bc : b = c := rfl /- And now we can apply eq.trans to these two premise-proofs and it will construct and return a proof of the conclusion. The expression that applies eq.trans to these two proofs is (eq.trans ab bc). Now for the fun part! -/ #check eq.trans ab bc /- EXERCISE: First write a textual inference rule, let's call it eq_snart. It says that if T is any type; if a, b, and c are values of this type, T; and you are given proofs of a = b and c = b then you can derive a proof of a = c. -/ /- EXERCISE: Now "prove" that this rule is valid by implementing it as a program that, when given any argument values of the specified types, returns a proof of the specified type (of the conclusion). Hint: Use eq.trans to construct the proof of a = c. It's first argument will be ab, the proof that a = b. It's second argument has to be a proof of b = c for it to work to derive a proof of a = c; but all we've got is a proof of c = b (in the reverse order). How can we pass a second argument of type b = c to eq.trans, so that it can do its job, when we have at hand is a proof of c = b. Now a major hint: we already have a way to construct a proof of b = c from a proof of c = b. Just use it. Ignore the error message in the following incomplete code. Replace the underscore with your answer. Leave parenthesis around your expression so that it gets evaluated as its own term. -/ def eq_snart { T : Type} { a b c: T } (ab: a = b) (cb: c = b) := eq.trans ab (_) /- EXERCISE: Use lean to implement a new rule that that, from a proof of c = b and a proof of b = a, derives (constructs and returns) a proof of a = c. Call the proof eq_snart' (why not, it sounds funny). -/ /- * Conclusion * -/ /- You now begin to see the power of proof assistants. We can now compute with proofs and the type checker makes sure that we can (for all intents and purposes) never use a proof that is not a valid proof of the proposition that it claims to prove. This represents a discontinuous leap over the the state of mathematical practice, where proofs are beautiful little essays rather than values we can compute with. -/ /- EXERCISE: Here we use eq_snart rather than eq.trans directly to prove a = c, given proofs of a = b and c = b. -/ lemma cb : c = b := rfl #check cb theorem aeqc : a = c := eq_snart _ _ /- In general, there are many ways to prove a given theorem. Each distinct proof is nevertheless an inhabitant of the type of the proposition that it proves, and each suffices as evidence to justify a truth judgment for the proposition. In many cases, the particular proof object that is used -/ /- SUMMARY: In this section (1) you first recalled that the equality relation is reflexive, symmetric, and transitive. (2) You saw that in Lean, these are not just abstract ideas; there are also inference rules that you can apply to to arguments of the right types to build proofs of new propositions. (3) You also saw that you can prove your own inference rules by writing programs that implement them! Such programs can use already accepted inference rules (such as eq.refl, eq.symm, eq.trans) in their implementations. Thereafter, the new rules are as good as the old, and can then also be used to construct proofs that might be needed. -/
ee68d5fbc1e426bce87d85ce63a1adeb32d06096
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/measure_theory/set_integral.lean
ceba7c4f974e695137e42e56693995be2979ce78
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
14,967
lean
/- Copyright (c) 2020 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import measure_theory.bochner_integration import measure_theory.indicator_function import measure_theory.lebesgue_measure /-! # Set integral Integrate a function over a subset of a measure space. ## Main definitions `measurable_on`, `integrable_on`, `integral_on` ## Notation `∫ a in s, f a` is `measure_theory.integral (s.indicator f)` -/ noncomputable theory open set filter topological_space measure_theory measure_theory.simple_func open_locale classical topological_space interval universes u v w variables {α : Type u} {β : Type v} {γ : Type w} section measurable_on variables [measurable_space α] [measurable_space β] [has_zero β] {s : set α} {f : α → β} /-- `measurable_on s f` means `f` is measurable over the set `s`. -/ def measurable_on (s : set α) (f : α → β) : Prop := measurable (s.indicator f) @[simp] lemma measurable_on_empty (f : α → β) : measurable_on ∅ f := by { rw [measurable_on, indicator_empty], exact measurable_const } @[simp] lemma measurable.measurable_on_univ (hf : measurable f) : measurable_on univ f := hf.if is_measurable.univ measurable_const @[simp] lemma measurable_on_singleton {α} [topological_space α] [t1_space α] [measurable_space α] [opens_measurable_space α] {a : α} {f : α → β} : measurable_on {a} f := λ s hs, show is_measurable ((indicator {a} f)⁻¹' s), begin rw indicator_preimage, refine is_measurable.union _ (is_measurable_singleton.compl.inter $ measurable_const.preimage hs), by_cases h : a ∈ f⁻¹' s, { rw inter_eq_self_of_subset_left, { exact is_measurable_singleton }, rwa singleton_subset_iff }, rw [singleton_inter_eq_empty.2 h], exact is_measurable.empty end lemma is_measurable.inter_preimage {B : set β} (hs : is_measurable s) (hB : is_measurable B) (hf : measurable_on s f): is_measurable (s ∩ f ⁻¹' B) := begin replace hf : is_measurable ((indicator s f)⁻¹' B) := hf B hB, rw indicator_preimage at hf, replace hf := hf.diff _, rwa union_diff_cancel_right at hf, { assume a, simp {contextual := tt} }, exact hs.compl.inter (measurable_const.preimage hB) end lemma measurable.measurable_on (hs : is_measurable s) (hf : measurable f) : measurable_on s f := hf.if hs measurable_const lemma measurable_on.subset {t : set α} (hs : is_measurable s) (h : s ⊆ t) (hf : measurable_on t f) : measurable_on s f := begin have : measurable_on s (indicator t f) := measurable.measurable_on hs hf, simp only [measurable_on, indicator_indicator] at this, rwa [inter_eq_self_of_subset_left h] at this end lemma measurable_on.union {t : set α} {f : α → β} (hs : is_measurable s) (ht : is_measurable t) (hsm : measurable_on s f) (htm : measurable_on t f) : measurable_on (s ∪ t) f := begin assume B hB, show is_measurable ((indicator (s ∪ t) f)⁻¹' B), rw indicator_preimage, refine is_measurable.union _ ((hs.union ht).compl.inter (measurable_const.preimage hB)), simp only [union_inter_distrib_right], exact (hs.inter_preimage hB hsm).union (ht.inter_preimage hB htm) end end measurable_on section integrable_on variables [measure_space α] [normed_group β] {s t : set α} {f g : α → β} /-- `integrable_on s f` means `f` is integrable over the set `s`. -/ def integrable_on (s : set α) (f : α → β) : Prop := integrable (s.indicator f) lemma integrable_on_congr (h : ∀x, x ∈ s → f x = g x) : integrable_on s f ↔ integrable_on s g := by simp only [integrable_on, indicator_congr h] lemma integrable_on_congr_ae (h : ∀ₘ x, x ∈ s → f x = g x) : integrable_on s f ↔ integrable_on s g := by { apply integrable_congr_ae, exact indicator_congr_ae h } @[simp] lemma integrable_on_empty (f : α → β) : integrable_on ∅ f := by { simp only [integrable_on, indicator_empty], apply integrable_zero } lemma measure_theory.integrable.integrable_on (s : set α) (hf : integrable f) : integrable_on s f := by { refine integrable_of_le (λa, _) hf, apply norm_indicator_le_norm_self } lemma integrable_on.subset (h : s ⊆ t) : integrable_on t f → integrable_on s f := by { apply integrable_of_le_ae, filter_upwards [] norm_indicator_le_of_subset h _ } variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma integrable_on.smul (s : set α) (c : 𝕜) {f : α → β} : integrable_on s f → integrable_on s (λa, c • f a) := by { simp only [integrable_on, indicator_smul], apply integrable.smul } lemma integrable_on.mul_left (s : set α) (r : ℝ) {f : α → ℝ} (hf : integrable_on s f) : integrable_on s (λa, r * f a) := by { simp only [smul_eq_mul.symm], exact hf.smul s r } lemma integrable_on.mul_right (s : set α) (r : ℝ) {f : α → ℝ} (hf : integrable_on s f) : integrable_on s (λa, f a * r) := by { simp only [mul_comm], exact hf.mul_left _ _ } lemma integrable_on.divide (s : set α) (r : ℝ) {f : α → ℝ} (hf : integrable_on s f) : integrable_on s (λa, f a / r) := by { simp only [div_eq_mul_inv], exact hf.mul_right _ _ } lemma integrable_on.add [measurable_space β] [opens_measurable_space β] (hfm : measurable_on s f) (hfi : integrable_on s f) (hgm : measurable_on s g) (hgi : integrable_on s g) : integrable_on s (λa, f a + g a) := by { rw [integrable_on, indicator_add], exact hfi.add hfm hgm hgi } lemma integrable_on.neg (hf : integrable_on s f) : integrable_on s (λa, -f a) := by { rw [integrable_on, indicator_neg], exact hf.neg } lemma integrable_on.sub [measurable_space β] [opens_measurable_space β] (hfm : measurable_on s f) (hfi : integrable_on s f) (hgm : measurable_on s g) (hgi : integrable_on s g) : integrable_on s (λa, f a - g a) := by { rw [integrable_on, indicator_sub], exact hfi.sub hfm hgm hgi } lemma integrable_on.union [measurable_space β] [opens_measurable_space β] (hs : is_measurable s) (ht : is_measurable t) (hsm : measurable_on s f) (hsi : integrable_on s f) (htm : measurable_on t f) (hti : integrable_on t f) : integrable_on (s ∪ t) f := begin rw ← union_diff_self, rw [integrable_on, indicator_union_of_disjoint], { refine integrable.add hsm hsi (htm.subset _ _) (hti.subset _), { exact ht.diff hs }, { exact diff_subset _ _ }, { exact diff_subset _ _ } }, exact disjoint_diff end lemma integrable_on_norm_iff (s : set α) (f : α → β) : integrable_on s (λa, ∥f a∥) ↔ integrable_on s f := begin simp only [integrable_on], convert ← integrable_norm_iff (indicator s f), funext, apply norm_indicator_eq_indicator_norm end end integrable_on section integral_on variables [measure_space α] [normed_group β] [second_countable_topology β] [normed_space ℝ β] [complete_space β] [measurable_space β] [borel_space β] {s t : set α} {f g : α → β} open set notation `∫` binders ` in ` s `, ` r:(scoped f, measure_theory.integral (set.indicator s f)) := r lemma integral_on_undef (h : ¬ (measurable_on s f ∧ integrable_on s f)) : (∫ a in s, f a) = 0 := integral_undef h lemma integral_on_non_measurable (h : ¬ measurable_on s f) : (∫ a in s, f a) = 0 := integral_non_measurable h lemma integral_on_non_integrable (h : ¬ integrable_on s f) : (∫ a in s, f a) = 0 := integral_non_integrable h variables (β) lemma integral_on_zero (s : set α) : (∫ a in s, (0:β)) = 0 := by simp variables {β} lemma integral_on_congr (h : ∀ a ∈ s, f a = g a) : (∫ a in s, f a) = (∫ a in s, g a) := by simp only [indicator_congr h] lemma integral_on_congr_of_ae_eq (hf : measurable_on s f) (hg : measurable_on s g) (h : ∀ₘ a, a ∈ s → f a = g a) : (∫ a in s, f a) = (∫ a in s, g a) := integral_congr_ae hf hg (indicator_congr_ae h) lemma integral_on_congr_of_set (hsm : measurable_on s f) (htm : measurable_on t f) (h : ∀ₘ a, a ∈ s ↔ a ∈ t) : (∫ a in s, f a) = (∫ a in t, f a) := integral_congr_ae hsm htm $ indicator_congr_of_set h variables (s t) lemma integral_on_smul (r : ℝ) (f : α → β) : (∫ a in s, r • (f a)) = r • (∫ a in s, f a) := by rw [← integral_smul, indicator_smul] lemma integral_on_mul_left (r : ℝ) (f : α → ℝ) : (∫ a in s, r * (f a)) = r * (∫ a in s, f a) := integral_on_smul s r f lemma integral_on_mul_right (r : ℝ) (f : α → ℝ) : (∫ a in s, (f a) * r) = (∫ a in s, f a) * r := by { simp only [mul_comm], exact integral_on_mul_left s r f } lemma integral_on_div (r : ℝ) (f : α → ℝ) : (∫ a in s, (f a) / r) = (∫ a in s, f a) / r := by { simp only [div_eq_mul_inv], apply integral_on_mul_right } lemma integral_on_neg (f : α → β) : (∫ a in s, -f a) = - (∫ a in s, f a) := by { simp only [indicator_neg], exact integral_neg _ } variables {s t} lemma integral_on_add {s : set α} (hfm : measurable_on s f) (hfi : integrable_on s f) (hgm : measurable_on s g) (hgi : integrable_on s g) : (∫ a in s, f a + g a) = (∫ a in s, f a) + (∫ a in s, g a) := by { simp only [indicator_add], exact integral_add hfm hfi hgm hgi } lemma integral_on_sub (hfm : measurable_on s f) (hfi : integrable_on s f) (hgm : measurable_on s g) (hgi : integrable_on s g) : (∫ a in s, f a - g a) = (∫ a in s, f a) - (∫ a in s, g a) := by { simp only [indicator_sub], exact integral_sub hfm hfi hgm hgi } lemma integral_on_le_integral_on_ae {f g : α → ℝ} (hfm : measurable_on s f) (hfi : integrable_on s f) (hgm : measurable_on s g) (hgi : integrable_on s g) (h : ∀ₘ a, a ∈ s → f a ≤ g a) : (∫ a in s, f a) ≤ (∫ a in s, g a) := begin apply integral_le_integral_ae hfm hfi hgm hgi, apply indicator_le_indicator_ae, exact h end lemma integral_on_le_integral_on {f g : α → ℝ} (hfm : measurable_on s f) (hfi : integrable_on s f) (hgm : measurable_on s g) (hgi : integrable_on s g) (h : ∀ a, a ∈ s → f a ≤ g a) : (∫ a in s, f a) ≤ (∫ a in s, g a) := integral_on_le_integral_on_ae hfm hfi hgm hgi $ by filter_upwards [] h lemma integral_on_union (hsm : measurable_on s f) (hsi : integrable_on s f) (htm : measurable_on t f) (hti : integrable_on t f) (h : disjoint s t) : (∫ a in (s ∪ t), f a) = (∫ a in s, f a) + (∫ a in t, f a) := by { rw [indicator_union_of_disjoint h, integral_add hsm hsi htm hti] } lemma integral_on_union_ae (hs : is_measurable s) (ht : is_measurable t) (hsm : measurable_on s f) (hsi : integrable_on s f) (htm : measurable_on t f) (hti : integrable_on t f) (h : ∀ₘ a, a ∉ s ∩ t) : (∫ a in (s ∪ t), f a) = (∫ a in s, f a) + (∫ a in t, f a) := begin have := integral_congr_ae _ _ (indicator_union_ae h f), rw [this, integral_add hsm hsi htm hti], { exact hsm.union hs ht htm }, { exact measurable.add hsm htm } end lemma integral_on_nonneg_of_ae {f : α → ℝ} (hf : ∀ₘ a, a ∈ s → 0 ≤ f a) : (0:ℝ) ≤ (∫ a in s, f a) := integral_nonneg_of_ae $ by { filter_upwards [hf] λ a h, indicator_nonneg' h } lemma integral_on_nonneg {f : α → ℝ} (hf : ∀ a, a ∈ s → 0 ≤ f a) : (0:ℝ) ≤ (∫ a in s, f a) := integral_on_nonneg_of_ae $ univ_mem_sets' hf lemma integral_on_nonpos_of_ae {f : α → ℝ} (hf : ∀ₘ a, a ∈ s → f a ≤ 0) : (∫ a in s, f a) ≤ 0 := integral_nonpos_of_nonpos_ae $ by { filter_upwards [hf] λ a h, indicator_nonpos' h } lemma integral_on_nonpos {f : α → ℝ} (hf : ∀ a, a ∈ s → f a ≤ 0) : (∫ a in s, f a) ≤ 0 := integral_on_nonpos_of_ae $ univ_mem_sets' hf lemma tendsto_integral_on_of_monotone {s : ℕ → set α} {f : α → β} (hsm : ∀i, is_measurable (s i)) (h_mono : monotone s) (hfm : measurable_on (Union s) f) (hfi : integrable_on (Union s) f) : tendsto (λi, ∫ a in (s i), f a) at_top (nhds (∫ a in (Union s), f a)) := let bound : α → ℝ := indicator (Union s) (λa, ∥f a∥) in begin apply tendsto_integral_of_dominated_convergence, { assume i, exact hfm.subset (hsm i) (subset_Union _ _) }, { assumption }, { show integrable_on (Union s) (λa, ∥f a∥), rwa integrable_on_norm_iff }, { assume i, apply all_ae_of_all, assume a, rw [norm_indicator_eq_indicator_norm], exact indicator_le_indicator_of_subset (subset_Union _ _) (λa, norm_nonneg _) _ }, { filter_upwards [] λa, le_trans (tendsto_indicator_of_monotone _ h_mono _ _) (pure_le_nhds _) } end lemma tendsto_integral_on_of_antimono (s : ℕ → set α) (f : α → β) (hsm : ∀i, is_measurable (s i)) (h_mono : ∀i j, i ≤ j → s j ⊆ s i) (hfm : measurable_on (s 0) f) (hfi : integrable_on (s 0) f) : tendsto (λi, ∫ a in (s i), f a) at_top (nhds (∫ a in (Inter s), f a)) := let bound : α → ℝ := indicator (s 0) (λa, ∥f a∥) in begin apply tendsto_integral_of_dominated_convergence, { assume i, refine hfm.subset (hsm i) (h_mono _ _ (zero_le _)) }, { exact hfm.subset (is_measurable.Inter hsm) (Inter_subset _ _) }, { show integrable_on (s 0) (λa, ∥f a∥), rwa integrable_on_norm_iff }, { assume i, apply all_ae_of_all, assume a, rw [norm_indicator_eq_indicator_norm], refine indicator_le_indicator_of_subset (h_mono _ _ (zero_le _)) (λa, norm_nonneg _) _ }, { filter_upwards [] λa, le_trans (tendsto_indicator_of_antimono _ h_mono _ _) (pure_le_nhds _) } end -- TODO : prove this for an encodable type -- by proving an encodable version of `filter.has_countable_basis_at_top_finset_nat` lemma integral_on_Union (s : ℕ → set α) (f : α → β) (hm : ∀i, is_measurable (s i)) (hd : ∀ i j, i ≠ j → s i ∩ s j = ∅) (hfm : measurable_on (Union s) f) (hfi : integrable_on (Union s) f) : (∫ a in (Union s), f a) = ∑i, ∫ a in s i, f a := suffices h : tendsto (λn:finset ℕ, n.sum (λ i, ∫ a in s i, f a)) at_top (𝓝 $ (∫ a in (Union s), f a)), by { rwa tsum_eq_has_sum }, begin have : (λn:finset ℕ, n.sum (λ i, ∫ a in s i, f a)) = λn:finset ℕ, ∫ a in (⋃i∈n, s i), f a, { funext, rw [← integral_finset_sum, indicator_finset_bUnion], { assume i hi j hj hij, exact hd i j hij }, { assume i, refine hfm.subset (hm _) (subset_Union _ _) }, { assume i, refine hfi.subset (subset_Union _ _) } }, rw this, refine tendsto_integral_filter_of_dominated_convergence _ _ _ _ _ _ _, { exact indicator (Union s) (λ a, ∥f a∥) }, { exact has_countable_basis_at_top_finset_nat }, { refine univ_mem_sets' (λ n, _), simp only [mem_set_of_eq], refine hfm.subset (is_measurable.Union (λ i, is_measurable.Union_Prop (λh, hm _))) (bUnion_subset_Union _ _), }, { assumption }, { refine univ_mem_sets' (λ n, univ_mem_sets' $ _), simp only [mem_set_of_eq], assume a, rw ← norm_indicator_eq_indicator_norm, refine norm_indicator_le_of_subset (bUnion_subset_Union _ _) _ _ }, { rw [← integrable_on, integrable_on_norm_iff], assumption }, { filter_upwards [] λa, le_trans (tendsto_indicator_bUnion_finset _ _ _) (pure_le_nhds _) } end end integral_on